blueprints.py 4.64 KB
Newer Older
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
1
2
#!/usr/bin/python
# -*- coding: utf-8 -*-
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
3
4
# Copyright 2014 J. Fernando Sánchez Rada - Grupo de Sistemas Inteligentes
# DIT, UPM
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
5
#
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
6
7
8
# 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
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
9
#
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
10
# http://www.apache.org/licenses/LICENSE-2.0
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
11
#
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
12
# Unless required by applicable law or agreed to in writing, software
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
13
14
15
16
#    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
17
18
19
"""
Blueprints for Senpy
"""
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
20
import json
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
21
import logging
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
22

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
23
24
logger = logging.getLogger(__name__)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
25
from flask import Blueprint, request, jsonify, current_app
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
26

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

29
30
31
32
33
BASIC_PARAMS = {
    "algorithm": {"aliases": ["algorithm", "a", "algo"],
                  "required": False,
                  },
}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
34

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
35

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

    outdict = {}
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
45
    wrong_params = {}
46
    for param, options in params.iteritems():
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
47
48
49
50
        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
51
            if options.get("required", False) and "default" not in options:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
52
                wrong_params[param] = params[param]
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
53
            else:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
54
55
56
                if "default" in options:
                    outdict[param] = options["default"]
        else:
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
57
58
59
60
61
62
63
64
            if "options" in params[param] and outdict[param] not in params[param]["options"]:
                wrong_params[param] = params[param]
    if wrong_params:
        message = {"status": "failed",
                   "message": "Missing or invalid parameters",
                   "parameters": outdict,
                   "errors": {param: error for param, error in wrong_params.iteritems()}
                   }
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
65
66
67
        raise ValueError(json.dumps(message))
    return outdict

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
68

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
69
def basic_analysis(params):
70
71
72
73
74
    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
75
                "analysis": [{"@type": "marl:SentimentAnalysis"}],
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
76
77
78
79
                "entries": []
                }
    if "language" in params:
        response["language"] = params["language"]
80
    for idx, sentence in enumerate(params["input"].split(".")):
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
81
        response["entries"].append({
82
            "@id": "Sentence{}".format(idx),
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
83
84
85
86
            "nif:isString": sentence
        })
    return response

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
87

88
@nif_blueprint.route('/', methods=['POST', 'GET'])
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
89
def home():
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
90
    try:
91
92
        algo = get_params(request).get("algorithm", None)
        specific_params = current_app.senpy.parameters(algo)
93
        params = get_params(request, specific_params)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
94
95
        response = current_app.senpy.analyse(**params)
        return jsonify(response)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
96
97
    except ValueError as ex:
        return ex.message
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
98
99
    except Exception as ex:
        return jsonify(status="400", message=ex.message)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
100

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
101

102
103
104
105
106
@nif_blueprint.route("/default")
def default():
    return current_app.senpy.default_plugin
    #return plugins(action="list", plugin=current_app.senpy.default_algorithm)

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
107

108
109
110
111
@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"):
112
    filt = {}
113
    if plugin:
114
115
116
117
        filt["name"] = plugin
    plugs = current_app.senpy.filter_plugins(**filt)
    if plugin and not plugs:
        return "Plugin not found", 400
118
    if action == "list":
119
        with_params = request.args.get("params", "") == "1"
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
120
        dic = {plug: plugs[plug].jsonable(with_params) for plug in plugs}
121
        return jsonify(dic)
122
123
    if action == "disable":
        current_app.senpy.disable_plugin(plugin)
124
125
        return "Ok"
    elif action == "enable":
126
127
128
129
        current_app.senpy.enable_plugin(plugin)
        return "Ok"
    elif action == "reload":
        current_app.senpy.reload_plugin(plugin)
130
131
        return "Ok"
    else:
132
        return "action '{}' not allowed".format(action), 400
133

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
134

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
135
if __name__ == '__main__':
136
    import config
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
137
    from flask import Flask
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
138

J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
139
    app = Flask(__name__)
140
    app.register_blueprint(nif_blueprint)
J. Fernando Sánchez's avatar
J. Fernando Sánchez committed
141
142
    app.debug = config.DEBUG
    app.run()