-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
85 lines (73 loc) · 2.85 KB
/
app.py
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2019 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
https://developer.cisco.com/docs/licenses
All use of the material herein must be in accordance with the terms of
the License. All rights not expressly granted by the License are
reserved. Unless required by applicable law or agreed to separately 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.
"""
import logging
import string
import pickle
from flask import Response
from flask import Flask
from flask import request
from flask import jsonify
from config import DefaultConfig as CONFIG
FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(filename="zzzlogs.log", level=logging.INFO, format=FORMAT)
app = Flask(__name__)
def predict_thread(phrase, model) -> dict:
preprocessed = preprocess(phrase)
result = model.predict_proba([preprocessed])
logging.info("Phrase: %s", phrase)
counter = 0
for x in model.classes_:
logging.info('Class: "%s" Probability: %s', x, str(result[0][counter]))
counter += 1
results = list(zip(model.classes_, result[0]))
results.sort(key=lambda x: x[1], reverse=True)
logging.info(results)
return {"scores": results}
def preprocess(text):
text = [word.lower().strip().rstrip("s") for word in text.split()]
text = ["".join(c for c in s if c not in string.punctuation) for s in text]
return [" ".join(x for x in text if x)][0]
with open("model.pickle", "rb") as g:
f_pipeline = pickle.load(g)
@app.route("/api/v1/nlp", methods=["POST", "GET"])
def server_route():
results = {}
if request.method == "GET":
status_code = Response(status=200)
return status_code
if request.method == "POST":
logging.info(request.json)
logging.info(request.method)
logging.info(request)
data = request.json
try:
if data.get("secret", "") == CONFIG.NLP_SECRET:
results = predict_thread(data["text"], f_pipeline)
logging.info("Made it past results")
return jsonify(results)
logging.warning("Unauthorized access attempt from: %s", request.remote_addr)
status_code = Response(status=403)
return status_code
except Exception:
logging.warning(
"Access error from %s. Received body was %s", request.remote_addr, data
)
status_code = Response(status=400)
return status_code
status_code = Response(status=501)
return status_code
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5005)