Outcast
Outcast

Reputation: 5117

How to use Google Vision API in python program?

I am trying to run the most basic text detection and OCR (Optical Character Recognition) program of Google Vision API in python. My source code is taken from the Google Cloud tutorial for this API and it is the following:

import  io
from google.cloud import vision
from google.cloud.vision import types

def detect_text(file):
    """Detects text in the file."""
    client = vision.ImageAnnotatorClient()

    with io.open(file, 'rb') as image_file:
        content = image_file.read()

    image = types.Image(content=content)

    response = client.text_detection(image=image)
    texts = response.text_annotations
    print('Texts:')

    for text in texts:
        print('\n"{}"'.format(text.description))

        vertices = (['({},{})'.format(vertex.x, vertex.y)
                    for vertex in text.bounding_poly.vertices])

        print('bounds: {}'.format(','.join(vertices)))

file_name = "prescription.jpg"
detect_text(file_name)

However I get the following error:

google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or
explicitly create credential and re-run the application. For more
information, please see
https://developers.google.com/accounts/docs/application-default-credentials.

This is weird because:

1) I created a new service account

2) I added export GOOGLE_APPLICATION_CREDENTIALS="/Users/User/PycharmProjects/GCP-OCR/Trial-e046e4bc6ce1.json" to my .bash_profile (I put the json file at the Pycharm file of this project) Perhaps the only weird thing is that the private key at the json file is around 20 lines while I would expect to be around 1 line.

How can I fix this bug and make the program running?

By the way the problem is solved if I simply add

import os
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/Users/User/PycharmProjects/GCP-OCR/Trial-e046e4bc6ce1.json"

to my source code.

Upvotes: 1

Views: 2866

Answers (1)

Guillem Xercavins
Guillem Xercavins

Reputation: 7058

The credentials are fine if this works when you set up the variable in your Python code. I tested it myself and it works using your initial approach, too. Don't forget to update your .bash_profile with:

source ~/.bash_profile

as explained in How to reload .bash_profile from the command line?

Verify that the environment variable is properly set with:

echo $GOOGLE_APPLICATION_CREDENTIALS

which should output the correct path to your credentials

Upvotes: 2

Related Questions