1

I am writing a test for getting label data from Google Cloud Vision API.

Within the test I am using vcrpy to store the results of my label retrieval.

with vcr.use_cassette(
        vcr_cassette_path.as_posix(), record_mode="twice",
        match_on=["uri", "method"], decode_compressed_response=True):
    labels = GCloudVisionLabelsRetriever().get_labels(self.FILE_PATH.as_posix())

Which ends up calling this block, as defined from Google themselves https://cloud.google.com/vision/docs/labels#detect_labels_in_a_local_image:

def detect_labels_from_path(path: str):
    client = vision.ImageAnnotatorClient(
        credentials=settings.GCLOUD_CREDENTIALS)

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

    image = vision.Image(content=content)

    response = client.label_detection(image=image)
    labels = response.label_annotations

    return labels

This is OK for the first time the test runs. The second time the test runs, I get an error saying the reach out to Google is unauthenticated.

I believe that this is because VCR doesn't support gRPC which is what is taking place under the hood.

I wonder if there is some way to mock this, or maybe a package that can deal with gRPC for python tests?

Jacob O
  • 43
  • 2
  • 8

1 Answers1

0

It is necessary to create a new client with the vision.ImageAnnotatorClient every time you are calling the API, instead, you need to create the client and then loop the client.label_detection. Also, I think that passing the Google credentials as

client = vision.ImageAnnotatorClient(credentials=settings.GCLOUD_CREDENTIALS)

is not the correct way, if you have configured the GCLOUD_CREDENTIALS in your path, it is not necessary to specify it, like:

client = vision.ImageAnnotatorClient()

Although, if you want to specify the path of your service account json, you can use the following code for that:

import os
import io
from google.cloud import vision
from google.oauth2 import service_account

#Loads the service account JSON credentials from a file
credentials = service_account.Credentials.from_service_account_file('SERVICE_ACCOUNT_KEY_FILE.json')
client = vision.ImageAnnotatorClient(credentials=credentials)

#I you have configure the GCLOUD_CREDENTIALS to your path, use this instead    
#client = vision.ImageAnnotatorClient()

image_path = "wakeupcat.jpg"

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


image = vision.types.Image(content=content)


# Performs label detection on the image file
response = client.label_detection(image=image)
labels = response.label_annotations

print('Labels:')
for label in labels:
print(label.description)