Я пытаюсь преобразовать ответ из библиотеки видения google-cloud client в формат json. Однако я получаю следующую ошибку:
AttributeError: объект google.protobuf.pyext._message.RepeatedCompositeCo не имеет атрибута DESCRIPTOR
Ресурс
from flask_restful import Resource
from flask import request
from flask import json
from util.GoogleVision import GoogleVision
from util.Convert import Convert
import base64
import requests
import os
class Vision(Resource):
def post(self):
googleVision = GoogleVision()
req = request.get_json()
url = req['url']
result = googleVision.detectLabels(url)
return result
GoogleVision.py
import os
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToJson
class GoogleVision():
def detectLabels(self, uri):
client = vision.ImageAnnotatorClient()
image = types.Image()
image.source.image_uri = uri
response = client.label_detection(image=image)
labels = response.label_annotations
res = MessageToJson(labels)
return res
переменная меток имеет тип <class'google.protobuf.pyext._message.RepeatedCompositeContainer'>
Как вы можете видеть, я использую сообщение для функции json в ответе меток. Но я получаю вышеуказанную ошибку.
Есть ли способ конвертировать результат в формат json?
Простой способ сделать это - использовать API Discovery. Вы можете создать объект службы с помощью функции build(). При выполнении запроса вы получите ответ в виде словаря. Затем вы можете преобразовать его в JSON с помощью json.dumps()
.
Пример с API Discovery:
import json
import apiclient.discovery
import base64
class GoogleVision():
def detectLabels(self, uri):
# Instantiates a client
service = apiclient.discovery.build('vision', 'v1')
# Image file
file_name=uri
# Loads the image into memory
with open(file_name, 'rb') as image:
image_content = base64.b64encode(image.read())
# Creates the request
service_request = service.images().annotate(body={
'requests': [{
'image': {
'content': image_content.decode('UTF-8')
},
'features': [{
'type': 'LABEL_DETECTION',
}]
}]
})
# Execute the request
response = service_request.execute()
# Convert to Json
res_json = json.dumps(response)
return res_json
Если вы не хотите использовать API Discovery, вы можете сначала преобразовать ответ в словарь с помощью функции MessageToDict()
а затем в JSON с помощью json.dumps()
.
Пример без API обнаружения с помощью MessageToDict()
:
import json
from google.cloud import vision
from google.cloud.vision import types
from google.protobuf.json_format import MessageToDict
class GoogleVision():
def detectLabels(self, uri):
# Instantiates a client
client = vision.ImageAnnotatorClient()
# Image file
file_name=uri
# Loads the image into memory
with open(file_name, 'rb') as image:
image_content = image.read()
image = types.Image(content=image_content)
# Performs label detection on the image file
response = client.label_detection(image=image)
#Convert the response to dictionary
response = MessageToDict(response)
# Convert to Json
res_json = json.dumps(response)
return res_json