尝试使用Python将Google Vision响应转换为字典时出现属性错误DESCRIPTOR。

14

我正在使用Windows操作系统,使用的Python版本是3.8.6rc1protobuf版本为3.13.0,同时也使用了google-cloud-vision版本2.0.0

我的代码如下:

from google.protobuf.json_format import MessageToDict
from google.cloud import vision
    
client = vision.ImageAnnotatorClient()
response = client.annotate_image({
            'image': {'source': {'image_uri': 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'}},
        })
MessageToDict(response)

MessageToDict(response)处失败,我遇到了一个属性错误:“DESCRIPTOR”。看起来response不是有效的protobuf对象。有人能帮我吗?谢谢


2
运气好吗?我在处理另一个谷歌 API Protobuf 对象时遇到了同样的问题。 - surgiie
1
我已经发布了一种解决方法作为答案。 - Martin J
4个回答

29

这并不是真正回答我的问题,但我发现解决它并访问protobuf对象的一种方法是使用response._pb,所以代码变成了:

response = client.annotate_image({
            'image': {'source': {'image_uri': 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60'}},
        })
MessageToDict(response._pb)

7

请看第3步骤,

步骤1:导入这个库

from google.protobuf.json_format import MessageToDict

第二步:发送请求

keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
    request=request
)

第三步:将响应转换为 json [看这里,添加“。pd”]

keyword_ideas_json = MessageToDict(keyword_ideas._pb) // add ._pb at the end of object

第四步:自由运用那个json

print(keyword_ideas_json)

此问题的Github链接: 这里


5

可以看一下 这篇帖子

json_string = type(response).to_json(response)
# Alternatively
import proto
json_string = proto.Message.to_json(response)

3

从 FriedrichSal 在 Github 上发布的问题中,可以看到proto 可以完成这项工作,并且在 2022 年仍然有效(库名称为 proto-plus):

现在所有的消息类型都是使用 proto-plus 定义的,它使用不同的方法进行序列化和反序列化。

import proto
objects = client.object_localization(image=image)
json_obs = proto.Message.to_json(objects)
dict_obs = proto.Message.to_dict(objects)
MessageToJson(objects._pb)仍然可用,但是可能有人不想依赖于一个“隐藏”的属性。

这是怎么回事!阿门兄弟。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接