python - Google Vision API 文本检测 Python 示例使用项目 : "google.com:cloudsdktool" and not my own project

标签 python google-cloud-platform google-cloud-vision google-cloud-console

我正在研究来自 github repo 的 Cloud Vision API 的 python 示例.

我已经设置了项目并使用其 key 激活了服务帐户。我还调用了 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)。

最佳答案

下载您创建的凭据并更新 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

关于python - Google Vision API 文本检测 Python 示例使用项目 : "google.com:cloudsdktool" and not my own project,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38048320/

相关文章:

python - Pandas:Drop() int64 基于值返回对象

python - 如何更改识别语言

google-cloud-platform - Google Vision OCR,将 90、180、270 个文档中的单词坐标旋转到 0 度

python - 管道代码跨越 Apache Beam/Dataflow 中的多个文件

python - Pandas :为什么你可以对具有不同索引的系列进行算术运算,但不能进行比较?

python - 使用 DictReader 计数

google-cloud-platform - Cloud Function 中 getSignedUrl promise 的权限被拒绝

python - Google PubSub 和自动缩放计算引擎实例 (Python)

已添加 SSL 证书,但显示 "Kubernetes Ingress controller fake certificate"

python - 改进云视觉上的手写 OCR?