]> git.somenet.org - pub/jan/aic18.git/blob - service-analysis/sentiment_analysis.py
fixed issue of internal server error if single json object not posted as list, refine...
[pub/jan/aic18.git] / service-analysis / sentiment_analysis.py
1 # -*- coding: utf-8 -*-
2 import json
3 import indicoio
4
5 from flask import Flask, request, jsonify, Response
6 from flask_restful import Resource, Api, output_json, abort
7
8 app = Flask(__name__)
9 api = Api(app)
10
11 indicoio.config.api_key = '525f16078717a430f9dac17cdc9dbaa3'
12
13 input_error_409 = 'Input must be a list of JSON objects. JSON objects must contain contain key text.'
14 service_error_503 = 'The sentiment analysis service is currently unavailable.'
15
16 class Sentiment_Analysis(Resource):
17         def get(self):
18                 return "POST a list of JSON objects as content-type: application/json. JSON objects must contain key 'text'.", 405, {'Allow': 'GET'}
19                 
20         def post(self):
21                 if not request.json or not isinstance(request.json, (list,)):
22                         return abort(409, message=input_error_409)
23                 texts = request.json
24                 text_array = []
25                 value = 0
26                 for text in texts:
27                         if 'text' not in text:
28                                 return abort(409, message=input_error_409)
29                         text_array.append(text['text'])
30                 try:
31                         for sentiment_value in indicoio.sentiment(text_array):
32                                 value += sentiment_value
33                 except:
34                         return make_error(503, message=service_error_503)
35                 sentiment = value/len(text_array)
36                 data = {'sentiment': sentiment}
37                 return data, 200, {'Content-Type': 'application/json'}
38                 #r = Response(response=json.dumps(data), status=200, mimetype="application/json")
39                 #r.headers["Content-Type"] = "application/json"
40                 #return r
41                 #return output_json(json.dumps(data), 200, headers={'Content-Type': "application/json"})
42                                 
43 api.add_resource(Sentiment_Analysis, '/')
44
45 if __name__ == '__main__':
46         app.run(host="0.0.0.0", port=8081, debug=False)