-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRestAPI.py
More file actions
57 lines (46 loc) · 1.53 KB
/
Copy pathRestAPI.py
File metadata and controls
57 lines (46 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import json
import pickle
import Classifier
from functools import wraps
from flask_restful import Resource, Api
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
api = Api(app)
# The actual decorator function
def require_appkey(view_function):
@wraps(view_function)
# the new, post-decoration function. Note *args and **kwargs here.
def decorated_function(*args, **kwargs):
with open('api.key', 'r') as apikey:
key = apikey.read().replace('\n', '')
print("KEY: ", key)
if request.headers.get('x-api-key') and request.headers.get('x-api-key') == key:
return view_function(*args, **kwargs)
else:
abort(401)
return decorated_function
# Main class
class Emotion(Resource):
@require_appkey
def post(self):
text = request.json['text']
emotions = Classifier.get_emotion(text, count_vect, tf_transformer, calibrated_svc, label_dict)
return emotions
# Load data function
def load_data():
# load configuration file
js = open('config-api.json').read()
config = json.loads(js)
# load model
model = pickle.load(open(config['pre-trained-model'], 'rb'))
# load encoded data
count_vect, transformer, labels = pickle.load(open(config['encoded-data'], 'rb'))
# load label dictionary
label_dict = config['label-dict']
return count_vect, transformer, model, label_dict
# Routes
api.add_resource(Emotion, '/svc/v1/emotion')
# Main
if __name__ == '__main__':
count_vect, tf_transformer, calibrated_svc, label_dict = load_data()
app.run(host='0.0.0.0', port='6232')