簡體   English   中英

嘗試使用 python 將 Google 視覺響應轉換為字典時出現屬性錯誤 DESCRIPTOR

[英]Attribute error DESCRIPTOR while trying to convert google vision response to dictionary with python

我在 Windows 上,使用Python 3.8.6rc1protobuf version 3.13.0google-cloud-vision version 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)失敗,我有一個attribute error: "DESCRIPTOR" 似乎response不是有效的 protobuf object。 有人能幫我嗎? 謝謝

這並沒有真正回答我的問題,但我發現解決它並訪問 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)

也許看看這個帖子

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

看第3步,

第 1 步:導入此庫

from google.ads.googleads.errors import GoogleAdsException

第 2 步:發送請求

keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
    request=request
)

第 3 步:將響應轉換為 json [看這里]

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

第 4 步:對那個json做任何你想做的事

print(keyword_ideas_json)

Github 上同樣的問題: 這里

從發布的 github 問題@FriedrichSal 中, 您可以看到如今(2022 年) proto完成了這項工作(庫 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)仍然有效,但我不希望依賴“隱藏”屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM