import os from flask import Flask, Response, jsonify, request, send_file from flask_cors import CORS, cross_origin from flask_restplus import Api, Namespace, Resource, fields from color_analysis import color_analysis from text2speech import text2speech flask_app = Flask(__name__) cors = CORS(flask_app, resources={r"*": {"origins": "*"}}) app = Api(app = flask_app, version = "1.0.0", title = "Color Analysis", description = "Analizes given image and returns color analysis") analyze_model = app.model('base 64 String', {'text': fields.String(required = True, description="base 64 String", help="")}) text_to_speech_model = app.model('String', {'text': fields.String(required = True, description="String", help="")}) color_analysis_namespace = app.namespace('nextuser', description='Color Analysis APIs') @flask_app.before_request def handle_chunking(): transfer_encoding = request.headers.get("Transfer-Encoding", None) if transfer_encoding == "chunked": request.environ["wsgi.input_terminated"] = True @color_analysis_namespace.route("/color_analysis") class ColorAnalysis(Resource): @app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Internal Server Error' }) @app.expect(analyze_model) def post(self): try: rsp = get_color_analysis(request.json) if rsp is None: return 'Invalid request payload - Cannot detect color', 400 elif type(rsp) is str: return jsonify(rsp) else: return 'Color Analysis Engine - Invalid result - Cannot detect color', 400 except Exception as e: print("Color Analysis Engine threw an exception: " + str(e)) return 'Internal Server Error', 500 @color_analysis_namespace.route("/text-to-speech") class TexrtToSpeech(Resource): @app.doc(responses={ 200: 'OK', 400: 'Invalid Argument', 500: 'Internal Server Error' }) @app.expect(text_to_speech_model) def post(self): try: rsp = getTextToSpeechMp3(request.json) if rsp is None: return 'Invalid request payload - Cannot return speech', 400 else: filepath = os.path.join(os.getcwd(), 'text_to_audio.mp3') rsp.save(filepath) return send_file(filepath, mimetype="application/octet-stream", as_attachment=True, attachment_filename='text_to_audio.mp3') except Exception as e: print("Color Analysis Engine threw an exception: " + str(e)) return 'Internal Server Error', 500 def get_color_analysis(json_data): if json_data is None: return None if 'text' not in json_data: return None text = json_data['text'] if text is None: return None return color_analysis(text) def getTextToSpeechMp3(json_data): if json_data is None: return None if 'text' not in json_data: return None text = json_data['text'] if text is None: return None return text2speech(text)