Google Vision API文本检测Python示例使用项目:“google.com:cloudsdktool”,而不是我自己的项目(Google Vision API text detecti

编程入门 行业动态 更新时间:2024-10-28 13:20:33
Google Vision API文本检测Python示例使用项目:“google.com:cloudsdktool”,而不是我自己的项目(Google Vision API text detection Python example uses project: “google.com:cloudsdktool” and not my own project)

我正在从github repo开始使用Cloud Vision API的python示例。

我已经设置了项目并使用其密钥激活了服务帐户。 我也调用了gcloud auth并输入了我的凭据。

这是我的代码(源自Vision API文本检测的python示例):

import base64 import os import re import sys from googleapiclient import discovery from googleapiclient import errors import nltk from nltk.stem.snowball import EnglishStemmer from oauth2client.client import GoogleCredentials import redis DISCOVERY_URL = 'https://{api}.googleapis.com/$discovery/rest?version={apiVersion}' # noqa BATCH_SIZE = 10 class VisionApi: """Construct and use the Google Vision API service.""" def __init__(self, api_discovery_file='/home/saadq/Dev/Projects/TM-visual-search/credentials-key.json'): self.credentials = GoogleCredentials.get_application_default() print self.credentials.to_json() self.service = discovery.build( 'vision', 'v1', credentials=self.credentials, discoveryServiceUrl=DISCOVERY_URL) print DISCOVERY_URL def detect_text(self, input_filenames, num_retries=3, max_results=6): """Uses the Vision API to detect text in the given file. """ images = {} for filename in input_filenames: with open(filename, 'rb') as image_file: images[filename] = image_file.read() batch_request = [] for filename in images: batch_request.append({ 'image': { 'content': base64.b64encode( images[filename]).decode('UTF-8') }, 'features': [{ 'type': 'TEXT_DETECTION', 'maxResults': max_results, }] }) request = self.service.images().annotate( body={'requests': batch_request}) try: responses = request.execute(num_retries=num_retries) if 'responses' not in responses: return {} text_response = {} for filename, response in zip(images, responses['responses']): if 'error' in response: print("API Error for %s: %s" % ( filename, response['error']['message'] if 'message' in response['error'] else '')) continue if 'textAnnotations' in response: text_response[filename] = response['textAnnotations'] else: text_response[filename] = [] return text_response except errors.HttpError as e: print("Http Error for %s: %s" % (filename, e)) except KeyError as e2: print("Key error: %s" % e2) vision = VisionApi() print vision.detect_text(['test_article.png'])

这是我收到的错误消息:

Http Error for test_article.png: <HttpError 403 when requesting https://vision.googleapis.com/v1/images:annotate?alt=json returned "Google Cloud Vision API has not been used in project google.com:cloudsdktool before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/vision.googleapis.com/overview?project=google.com:cloudsdktool then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">

我希望能够使用我自己的项目作为示例,而不是默认(google.com:cloudsdktool)。

I am working on the python example for Cloud Vision API from github repo.

I have already setup the project and activated the service account with its key. I have also called the gcloud auth and entered my credentials.

Here is my code (as derived from the python example of Vision API text detection):

import base64 import os import re import sys from googleapiclient import discovery from googleapiclient import errors import nltk from nltk.stem.snowball import EnglishStemmer from oauth2client.client import GoogleCredentials import redis DISCOVERY_URL = 'https://{api}.googleapis.com/$discovery/rest?version={apiVersion}' # noqa BATCH_SIZE = 10 class VisionApi: """Construct and use the Google Vision API service.""" def __init__(self, api_discovery_file='/home/saadq/Dev/Projects/TM-visual-search/credentials-key.json'): self.credentials = GoogleCredentials.get_application_default() print self.credentials.to_json() self.service = discovery.build( 'vision', 'v1', credentials=self.credentials, discoveryServiceUrl=DISCOVERY_URL) print DISCOVERY_URL def detect_text(self, input_filenames, num_retries=3, max_results=6): """Uses the Vision API to detect text in the given file. """ images = {} for filename in input_filenames: with open(filename, 'rb') as image_file: images[filename] = image_file.read() batch_request = [] for filename in images: batch_request.append({ 'image': { 'content': base64.b64encode( images[filename]).decode('UTF-8') }, 'features': [{ 'type': 'TEXT_DETECTION', 'maxResults': max_results, }] }) request = self.service.images().annotate( body={'requests': batch_request}) try: responses = request.execute(num_retries=num_retries) if 'responses' not in responses: return {} text_response = {} for filename, response in zip(images, responses['responses']): if 'error' in response: print("API Error for %s: %s" % ( filename, response['error']['message'] if 'message' in response['error'] else '')) continue if 'textAnnotations' in response: text_response[filename] = response['textAnnotations'] else: text_response[filename] = [] return text_response except errors.HttpError as e: print("Http Error for %s: %s" % (filename, e)) except KeyError as e2: print("Key error: %s" % e2) vision = VisionApi() print vision.detect_text(['test_article.png'])

This is the error message I am getting:

Http Error for test_article.png: <HttpError 403 when requesting https://vision.googleapis.com/v1/images:annotate?alt=json returned "Google Cloud Vision API has not been used in project google.com:cloudsdktool before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/vision.googleapis.com/overview?project=google.com:cloudsdktool then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.">

I want to be able to use my own project for the example and not the default (google.com:cloudsdktool).

最满意答案

下载您创建的凭据并更新GOOGLE_APPLICATION_CREDENTIALS环境变量以指向该文件:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials-key.json

参考: https : //github.com/GoogleCloudPlatform/cloud-vision/tree/master/python/text#set-up-to-authenticate-with-your-projects-credentials

Download the credentials you created and update the GOOGLE_APPLICATION_CREDENTIALS environment variable to point to that file:

export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/credentials-key.json

Reference: https://github.com/GoogleCloudPlatform/cloud-vision/tree/master/python/text#set-up-to-authenticate-with-your-projects-credentials

更多推荐

本文发布于:2023-08-04 13:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1415892.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自己的   项目   示例   而不是   文本

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!