Vcrpy与GoogleCloudVision

问题描述

我正在编写一项用于从Google Cloud Vision API获取标签数据的测试。

在测试中,我正在使用vcrpy存储标签检索的结果。

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())

最终根据Google自己的定义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

第一次运行测试就可以了。第二次运行测试时,我收到一条错误消息,提示未验证与Google的联系。

我相信这是因为VCR不支持gRPC,而gRPC是在后台进行的。

我想知道是否有某种方法可以模拟这种情况,或者是否有一个可以处理gRPC进行python测试的软件包?

解决方法

每次调用API时,都需要使用vision.ImageAnnotatorClient创建一个新客户端,相反,您需要先创建客户端,然后循环client.label_detection。另外,我认为将Google凭据作为

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

不是正确的方法,如果您在路径中配置了GCLOUD_CREDENTIALS,则无需指定它,例如:

client = vision.ImageAnnotatorClient()

尽管,如果要指定服务帐户json的路径,则可以使用以下代码:

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)