带谷歌云视觉的Vcrpy

2024-06-16 11:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个测试,用于从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

这在测试第一次运行时是正常的。第二次测试运行时,我收到一个错误消息,说与谷歌的联系未经验证

我相信这是因为VCR不支持gRPC,而gRPC正是在引擎盖下发生的事情

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


Tags: pathimagegrpclabelsresponseaswithgoogle
1条回答
网友
1楼 · 发布于 2024-06-16 11:29:12

每次调用API时,都需要使用vision.ImageAnnotatorClient创建一个新的客户端,而需要创建客户端,然后循环client.label\u检测。另外,我认为通过谷歌认证

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

不是正确的方式,如果已在路径中配置GCLOUD_凭据,则无需指定它,如:

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)

相关问题 更多 >