generate content endpoint

This commit is contained in:
Łukasz Jędyk 2022-06-09 21:50:23 +02:00
parent 83ff7d9144
commit 6fa42c9a0a

View File

@ -3,6 +3,7 @@ import json
from uuid import uuid4
from requests_oauthlib import OAuth1Session
from flask import Blueprint, current_app, request, jsonify
from nltk import sent_tokenize
from ayct_backend.models import *
from ayct_backend.firebase import verify_token
@ -162,3 +163,44 @@ def get_twitter_campaign_details(campaign_id):
"twitter_account_id": twitter_campaign.twitter_account_id,
"posts": posts
}), 200
@campaign.route('/generate', methods=['POST'])
def generate_content():
decoded_token = verify_token(request.headers)
if not decoded_token:
return "Not authorised!", 401
content_type = request.headers.get('Content-Type')
if content_type != 'application/json':
return "Content-type not supported!", 400
request_json = request.json
if 'user_input' not in request_json:
return "Invalid request!", 400
core_url = 'http://s415366.projektstudencki.pl/generate'
payload = {
"data": request_json['user_input'],
"length": 420
}
try:
response = requests.post(core_url, headers={"Content-Type":"application/json"}, data=json.dumps(payload))
except:
return 'Failed to generate content!', 400
generated_content = response.content.decode("utf-8").replace('<|endoftext|>', '').replace(' ', ' ')
content_sentences = sent_tokenize(generated_content)
trimmed_content = ''
for sentence in content_sentences:
if len(trimmed_content) + len(sentence) < 270:
trimmed_content += ' '
trimmed_content += sentence
if len(trimmed_content) < 1:
trimmed_content = generated_content[:270]
return jsonify({
"content": trimmed_content
}), 200