forked from knwkx/QAbot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
executable file
·80 lines (63 loc) · 2.25 KB
/
bot.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
import os
import pickle
from flask import Flask, request, jsonify
import logging
from Bani.Bani import Bani
from Bani.core.FAQ import FAQ
logging.basicConfig(level=logging.ERROR)
FAQSTORE_PATH = "/faq_store"
MODEL_PATH = "/model"
def load_faq():
faq_list = []
# this look at the faqStore for .pkl extension, create faq with the file_name
for file_name in os.listdir(FAQSTORE_PATH):
if file_name.endswith(".pkl"):
faq_name = file_name.partition('.')[0]
print(f"FAQ name: {faq_name}")
faq_name = FAQ(name=faq_name)
faq_name.load(FAQSTORE_PATH)
faq_list.append(faq_name)
print(f"FAQ created from {file_name}")
return faq_list
loaded_faq_list = load_faq()
masterBot = Bani(FAQs=loaded_faq_list, modelPath=MODEL_PATH)
print(f"MasterBot created")
app = Flask(__name__)
@app.route("/")
def main():
return jsonify(result="hello world")
@app.route("/answer", methods=["GET"])
def getAnswer():
global masterConfig
global interfaces
params = request.args
if "question" not in params:
return "Question not found.", 400
question = params["question"]
outputs = masterBot.findClosest(question, K=1)
code = -1
answer = None
similarQns = []
if outputs[0].maxScore < 0.5:
# if confidence level not high enough
# get closest question from each FAQ
code = 1
answer = ""
for out in outputs:
similarQns.append(out.question.text)
elif outputs[0].maxScore - outputs[1].maxScore < 0.05:
code = 2
answer = outputs[0].answer.text
similarQns.append(outputs[0].question.text)
for out in outputs[1:]:
if outputs[0].maxScore - out.maxScore < 0.05:
similarQns.append(out.question.text)
else:
break
code = 0 if code==-1 else code
answer = outputs[0].answer.text.strip() if answer==None else answer
similarQns = outputs[0].similarQuestions if len(similarQns)==0 else similarQns
return jsonify(code=code, result=answer, similarQuestions=similarQns)
if __name__ == "__main__":
#app.run(host="0.0.0.0", port=os.getenv("PORT", 1995), threaded=True)
app.run(host="0.0.0.0", port=8057, threaded=True)