dream
82 строки · 3.0 Кб
1import logging
2import os
3import time
4from flask import Flask, request, jsonify
5import sentry_sdk
6from deeppavlov import build_model
7
8logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
9logger = logging.getLogger(__name__)
10sentry_sdk.init(os.getenv("SENTRY_DSN"))
11
12app = Flask(__name__)
13
14config_name = os.getenv("CONFIG")
15
16try:
17el = build_model(config_name, download=True)
18logger.info("model loaded")
19except Exception as e:
20sentry_sdk.capture_exception(e)
21logger.exception(e)
22raise e
23
24
25@app.route("/model", methods=["POST"])
26def respond():
27st_time = time.time()
28inp = request.json
29entity_substr_batch = inp.get("entity_substr", [[""]])
30entity_tags_batch = inp.get(
31"entity_tags", [["" for _ in entity_substr_list] for entity_substr_list in entity_substr_batch]
32)
33context_batch = inp.get("context", [[""]])
34opt_context_batch = []
35for entity_substr_list, hist_utt in zip(entity_substr_batch, context_batch):
36last_utt = hist_utt[-1]
37if last_utt[-1] not in {".", "!", "?"}:
38last_utt = f"{last_utt}."
39if len(hist_utt) > 1:
40prev_utt = hist_utt[-2]
41if prev_utt[-1] not in {".", "!", "?"}:
42prev_utt = f"{prev_utt}."
43opt_context_batch.append([prev_utt, last_utt])
44else:
45opt_context_batch.append([last_utt])
46
47entity_info_batch = [[{}] for _ in entity_substr_batch]
48try:
49entity_substr_batch, entity_ids_batch, conf_batch, entity_pages_batch = el(
50entity_substr_batch, entity_tags_batch, opt_context_batch
51)
52entity_info_batch = []
53for entity_substr_list, entity_ids_list, entity_tags_list, conf_list, entity_pages_list in zip(
54entity_substr_batch,
55entity_ids_batch,
56entity_tags_batch,
57conf_batch,
58entity_pages_batch,
59):
60entity_info_list = []
61for entity_substr, entity_ids, entity_tags, confs, entity_pages in zip(
62entity_substr_list, entity_ids_list, entity_tags_list, conf_list, entity_pages_list
63):
64entity_info = {}
65entity_info["entity_substr"] = entity_substr
66entity_info["entity_ids"] = entity_ids
67entity_info["entity_tags"] = entity_tags
68entity_info["confidences"] = [float(elem[2]) for elem in confs]
69entity_info["tokens_match_conf"] = [float(elem[0]) for elem in confs]
70entity_info["entity_pages"] = entity_pages
71entity_info_list.append(entity_info)
72entity_info_batch.append(entity_info_list)
73except Exception as e:
74sentry_sdk.capture_exception(e)
75logger.exception(e)
76total_time = time.time() - st_time
77logger.info(f"entity linking exec time = {total_time:.3f}s")
78return jsonify(entity_info_batch)
79
80
81if __name__ == "__main__":
82app.run(debug=False, host="0.0.0.0", port=3000)
83