|
|
import flask |
|
|
from flask_cors import CORS |
|
|
from concurrent.futures import ThreadPoolExecutor |
|
|
import json |
|
|
import datetime |
|
|
import weave |
|
|
from detector_base import get_detector |
|
|
|
|
|
|
|
|
app = flask.Flask(__name__, static_folder='./dist', static_url_path='/') |
|
|
|
|
|
CORS(app, supports_credentials=True) |
|
|
executor = ThreadPoolExecutor(10) |
|
|
|
|
|
def return_data(code, msg, data, cookie="", ToNone=True): |
|
|
if ToNone and len(data) <= 0: |
|
|
data = None |
|
|
jsonStr = { |
|
|
'code': code, |
|
|
'msg': msg, |
|
|
'data': data |
|
|
} |
|
|
response = flask.make_response(flask.jsonify(jsonStr)) |
|
|
if cookie: |
|
|
for key, value in cookie.items(): |
|
|
response.set_cookie(key, value, max_age=3600 * 12) |
|
|
return response |
|
|
|
|
|
@weave.op() |
|
|
def process_request(text, detector): |
|
|
return detector.compute_prob(text) |
|
|
|
|
|
def handle_request(detector_name): |
|
|
|
|
|
if flask.request.method == 'POST': |
|
|
try: |
|
|
data = flask.request.data.decode('utf-8') |
|
|
except Exception as ex: |
|
|
print(datetime.datetime.now().isoformat(), ex, flush=True) |
|
|
return return_data(400, 'Bad request', str(ex)) |
|
|
else: |
|
|
return return_data(0, '', {}) |
|
|
|
|
|
info = {} |
|
|
sentence = json.loads(data) |
|
|
data = {"sentence": sentence} |
|
|
print(datetime.datetime.now().isoformat(), data, flush=True) |
|
|
try: |
|
|
text = data["sentence"] |
|
|
detector = get_detector(detector_name) |
|
|
future = executor.submit(process_request, text, detector) |
|
|
prob, crit, ntoken = future.result() |
|
|
info["crit"] = crit |
|
|
info["prob"] = prob |
|
|
info["ntoken"] = ntoken |
|
|
print(datetime.datetime.now().isoformat(), info, flush=True) |
|
|
return return_data(0, '', info) |
|
|
except Exception as ex: |
|
|
print(datetime.datetime.now().isoformat(), ex, flush=True) |
|
|
return return_data(400, 'Bad request', str(ex)) |
|
|
|
|
|
|
|
|
@app.route("/glimpse", methods=["GET", "POST"]) |
|
|
def glimpse(): |
|
|
return handle_request("glimpse") |
|
|
|
|
|
@app.route("/", methods=["GET"]) |
|
|
def index(): |
|
|
return app.send_static_file('index.html') |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
detectors = ['glimpse'] |
|
|
for detector_name in detectors: |
|
|
get_detector(detector_name) |
|
|
|
|
|
weave.init('Glimpse') |
|
|
app.run(host='0.0.0.0', port=7860) |
|
|
|