Опубликовать ответ Google Cloud Vision и NLP API на AWS Dynamodb
Я работаю над проектом, в котором мне нужно опубликовать ответ от API Google Cloud Vision и обработки естественного языка на таблицу DynamoDB. Я успешно реализовал эти API, но не знаю, как опубликовать этот ответ в DynamodB.
Вот что я попробовал:
import os
import random
import string
from django.shortcuts import render
from django.views.generic import CreateView
from django.http import HttpResponse
from google.cloud.language_v1.gapic import enums
from Base import settings
from . import forms
# AWS Boto Imports
import boto3
# Google Imports
from google.cloud import vision
from google.cloud.vision import types
from google.cloud import language
from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file('svc_cred.json')
def dict_to_item(raw):
if type(raw) is dict:
resp = {}
for k, v in raw.items():
if type(v) is str:
resp[k] = {
'S': v
}
elif type(v) is int:
resp[k] = {
'I': str(v)
}
elif type(v) is dict:
resp[k] = {
'M': dict_to_item(v)
}
elif type(v) is list:
resp[k] = []
for i in v:
resp[k].append(dict_to_item(i))
return resp
elif type(raw) is str:
return {
'S': raw
}
elif type(raw) is int:
return {
'I': str(raw)
}
def generate_pid():
digits = "".join([random.choice(string.digits) for i in range(4)])
pid = digits
return pid
def vision_image_manager(image_file):
# Instantiates a client
client = vision.ImageAnnotatorClient()
file_name = str(image_file)
with open(file_name, 'rb') as img_file:
content = img_file.read()
image = types.Image(content=content)
response = client.label_detection(image=image)
labels = response.label_annotations
lbl_dict = dict(list(enumerate(labels)))
print(type(response))
print(type(labels))
return dict_to_item(lbl_dict)
def nlp_text_manager(text_path):
client = language.LanguageServiceClient(credentials=credentials)
text = text_path
# Instantiates a plain text document.
document = language.types.Document(
content=text,
type=enums.Document.Type.PLAIN_TEXT,)
sentiment = client.analyze_sentiment(document=document).document_sentiment
entities = client.analyze_entities(document=document, encoding_type='UTF32',)
return entities
def post_to_dynamo_db(result):
session = boto3.Session(
aws_access_key_id=settings.AWS_SERVER_PUBLIC_KEY,
aws_secret_access_key=settings.AWS_SERVER_SECRET_KEY
)
client = session.resource('dynamodb')
table = client.Table('basetbl')
table.put_item(
Item={
'id': int(generate_pid()),
'response': dict_to_item(result)
}
)
class BaseView(CreateView):
def get(self, request, *args, **kwargs):
return render(request, 'form.html', {})
def post(self, request, *args, **kwargs):
if request.method == 'POST':
post_data = request.POST.copy()
form = forms.BaseForm(post_data, request.FILES)
print('get post req')
if form.is_valid():
obj = form
obj.imageFile = form.cleaned_data['imageFile']
obj.textFile = form.cleaned_data['textFile']
obj.save()
# Process the image using Google's vision API
image_path = os.path.join(settings.MEDIA_ROOT, 'images/', obj.imageFile.name)
# print(image_path)
image = vision_image_manager(image_path)
text_path = os.path.join(settings.MEDIA_ROOT, 'texts/', obj.textFile.name)
text = nlp_text_manager(text_path)
results = {
'imageResponse': image,
'textResult': text
}
post_to_dynamo_db(results)
return HttpResponse('Get post request along with files', status=200, )
Этот код теперь не возвращает никакой ошибки, но он также разместил пустой объект вместо response
Объект в таблице DynamodB.
Что я сделал не так?
Помоги мне, пожалуйста!
Заранее спасибо!