From 6fa42c9a0afeb11d63b1cb90f7acd100213e996a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C5=81ukasz=20J=C4=99dyk?= Date: Thu, 9 Jun 2022 21:50:23 +0200 Subject: [PATCH] generate content endpoint --- ayct_backend/campaign/__init__.py | 42 +++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/ayct_backend/campaign/__init__.py b/ayct_backend/campaign/__init__.py index 4c0e18b..053826e 100644 --- a/ayct_backend/campaign/__init__.py +++ b/ayct_backend/campaign/__init__.py @@ -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