微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Vcrpy与GoogleCloudVision

如何解决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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。