14

I am on Windows, using Python 3.8.6rc1, protobuf version 3.13.0 and google-cloud-vision version 2.0.0.

My Code is :

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)

It fails at MessageToDict(response), I have an attribute error: "DESCRIPTOR". It seems like the response is not a valid protobuf object. Can someone help me? Thank you

Martin J
  • 2,019
  • 1
  • 15
  • 28

4 Answers4

27

This does not really answer my question but I find that one way to solve it and access the protobuf object is to use response._pb so the code becomes:

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)
Martin J
  • 2,019
  • 1
  • 15
  • 28
7

Look step 3,

Step 1: Import this lib

from google.protobuf.json_format import MessageToDict

Step 2: Send request

keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(
    request=request
)

Step 3: Convert response to json [Look here, add ".pd"]

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

Step 4: Do whatever you want with that json

print(keyword_ideas_json)

Github for this same issue: here

Rohit Nishad
  • 2,570
  • 2
  • 22
  • 32
5

maybe have a look at this post

json_string = type(response).to_json(response)
# Alternatively
import proto
json_string = proto.Message.to_json(response)
FriedrichSal
  • 185
  • 2
  • 7
2

From the github issue @FriedrichSal posted, you can see that proto does the job and this is still valid in 2022 (library name is proto-plus):

All message types are now defined using proto-plus, which uses different methods for serialization and deserialization.

import proto
objects = client.object_localization(image=image)
json_obs = proto.Message.to_json(objects)
dict_obs = proto.Message.to_dict(objects)

The MessageToJson(objects._pb) still works, but maybe someone prefers not to depend on a "hidden" property.

matrs
  • 59
  • 1
  • 6