]> git.somenet.org - pub/jan/aic18.git/blob - service-analysis/sentiment_analysis.py
refined README.me, fixed issue #35
[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 JSON string. 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 JSON string as content-type: application/json. JSON objects must contain key 'text'."
19                 
20         def post(self):
21                 if not request.json:
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                                 
39 api.add_resource(Sentiment_Analysis, '/')
40
41 if __name__ == '__main__':
42         app.run(host="0.0.0.0", port=8081, debug=False)