blueprints.py 4.6 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#!/usr/bin/python
# -*- coding: utf-8 -*-
#    Copyright 2014 J. Fernando Sánchez Rada - Grupo de Sistemas Inteligentes
#                                                       DIT, UPM
#
#    Licensed under the Apache License, Version 2.0 (the "License");
#    you may not use this file except in compliance with the License.
#    You may obtain a copy of the License at
#
#        http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS,
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#    See the License for the specific language governing permissions and
#    limitations under the License.
'''
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
18
Simple Sentiment Analysis server
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
19
20
21
22
'''
from flask import Blueprint, render_template, request, jsonify, current_app
import json

23
nif_blueprint = Blueprint("NIF Sentiment Analysis Server", __name__)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
24

25
26
27
28
29
BASIC_PARAMS = {
    "algorithm": {"aliases": ["algorithm", "a", "algo"],
                  "required": False,
                  },
}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
30

31
def get_params(req, params=BASIC_PARAMS):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
32
33
34
    indict = None
    if req.method == 'POST':
        indict = req.form
J. Fernando Sánchez's avatar
Oups    
J. Fernando Sánchez committed
35
    elif req.method == 'GET':
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
36
37
38
39
40
        indict = req.args
    else:
        raise ValueError("Invalid data")

    outdict = {}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
41
    wrongParams = {}
42
    for param, options in params.iteritems():
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
43
44
45
46
        for alias in options["aliases"]:
            if alias in indict:
                outdict[param] = indict[alias]
        if param not in outdict:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
47
            if options.get("required", False):
48
                wrongParams[param] = params[param]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
49
            else:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
50
51
52
                if "default" in options:
                    outdict[param] = options["default"]
        else:
53
54
55
            if "options" in params[param] and \
                outdict[param] not in params[param]["options"]:
                wrongParams[param] = params[param]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
56
57
58
59
    if wrongParams:
        message = {"status": "failed", "message": "Missing or invalid parameters"}
        message["parameters"] = outdict
        message["errors"] = {param:error for param, error in wrongParams.iteritems()}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
60
61
62
63
        raise ValueError(json.dumps(message))
    return outdict

def basic_analysis(params):
64
65
66
67
68
    response = {"@context": ["http://demos.gsi.dit.upm.es/eurosentiment/static/context.jsonld",
                             {
                                 "@base": "{}#".format(request.url.encode('utf-8'))
                             }
                             ],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
69
70
71
72
73
74
75
                "analysis": [{
                    "@type": "marl:SentimentAnalysis"
                }],
                "entries": []
                }
    if "language" in params:
        response["language"] = params["language"]
76
    for idx, sentence in enumerate(params["input"].split(".")):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
77
        response["entries"].append({
78
            "@id": "Sentence{}".format(idx),
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
79
80
81
82
            "nif:isString": sentence
        })
    return response

83
@nif_blueprint.route('/', methods=['POST', 'GET'])
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
84
85
def home(entries=None):
    try:
86
87
        algo = get_params(request).get("algorithm", None)
        specific_params = current_app.senpy.parameters(algo)
88
        params = get_params(request, specific_params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
89
90
    except ValueError as ex:
        return ex.message
91
    response = current_app.senpy.analyse(**params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
92
93
    return jsonify(response)

94
95
96
97
98
@nif_blueprint.route("/default")
def default():
    return current_app.senpy.default_plugin
    #return plugins(action="list", plugin=current_app.senpy.default_algorithm)

99
100
101
102
@nif_blueprint.route('/plugins/', methods=['POST', 'GET'])
@nif_blueprint.route('/plugins/<plugin>', methods=['POST', 'GET'])
@nif_blueprint.route('/plugins/<plugin>/<action>', methods=['POST', 'GET'])
def plugins(plugin=None, action="list"):
103
    filt = {}
104
    if plugin:
105
106
107
108
        filt["name"] = plugin
    plugs = current_app.senpy.filter_plugins(**filt)
    if plugin and not plugs:
        return "Plugin not found", 400
109
    if action == "list":
110
111
        with_params = request.args.get("params", "") == "1"
        dic = {plug:plugs[plug].jsonable(with_params) for plug in plugs}
112
        return jsonify(dic)
113
114
    if action == "disable":
        current_app.senpy.disable_plugin(plugin)
115
116
        return "Ok"
    elif action == "enable":
117
118
119
120
        current_app.senpy.enable_plugin(plugin)
        return "Ok"
    elif action == "reload":
        current_app.senpy.reload_plugin(plugin)
121
122
        return "Ok"
    else:
123
        return "action '{}' not allowed".format(action), 400
124

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
125
if __name__ == '__main__':
126
    import config
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
127
128
    from flask import Flask
    app = Flask(__name__)
129
    app.register_blueprint(nif_blueprint)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
130
131
    app.debug = config.DEBUG
    app.run()