-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchatbot.py
238 lines (196 loc) · 7.9 KB
/
chatbot.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
import pandas as pd
import re
import json
import unknown
from flask import Flask
from flask_restful import Api, Resource
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
CORS(app)
def load_json(file):
with open(file) as openedFile:
return json.load(openedFile)
#symptoms = pd.DataFrame(columns = ["Symptom", "Probing question", "Diseases"]);
#diseases = pd.DataFrame(columns = ["Disease", "Symptoms", "Time Period", "Treatment"]);
symptoms = load_json("symptoms.json")
diseases = load_json("diseases.json")
responses = load_json("response_data.json")
def processInput(input, response_data):
split_input = re.split(r'\s+|[,;?!.-]\s*', input.lower())
score_list = []
# Check all the responses
for response in response_data:
response_score = 0
required_score = 0
required_words = response["required_words"]
# Check if there are any required words
if required_words:
for word in split_input:
if word in required_words:
required_score += 1
# Amount of required words should match the required score
if required_score == len(required_words):
# print(required_score == len(required_words))
# Check each word the user has typed
for word in split_input:
# If the word is in the response, add to the score
if word in response["user_input"]:
response_score += 1
# Add score to list
score_list.append(response_score)
# Debugging: Find the best phrase
# print(response_score, response["user_input"])
# Find the best response and return it if they're not all 0
best_response = max(score_list)
response_index = score_list.index(best_response)
# If there is no good response, return a random one.
if best_response != 0:
return response_data[response_index]
return "unknown"
ending_statement = "Can I help you in any other way?"
#diagnosis 1
#make a list of diseases with that symptom
possible_diseases = diseases
#make a priority list of symptoms that we need to rule out with priority bring how close it is to 50%
possible_symptoms = {}
confirmed_symptoms = []
def add_symptom(symptom):
global possible_symptoms
global possible_diseases
if symptom["name"] in possible_symptoms:
possible_symptoms[symptom["name"]] = (symptom, possible_symptoms[symptom["name"]][1] + 1)
else:
possible_symptoms[symptom["name"]] = (symptom, 1)
possible_symptoms = {k: v for k, v in sorted(possible_symptoms.items(), reverse=True, key=lambda item: item[1][1])}
def confirm_symptom(symptom):
global possible_symptoms
global possible_diseases
global confirmed_symptoms
possible_symptoms = {}
new_possible_diseases = []
confirmed_symptoms.append(symptom)
for disease in possible_diseases:
if symptom["name"] in disease["symptoms"]:
new_possible_diseases.append(disease)
for new_symptom_name in disease["symptoms"]:
if new_symptom_name in confirmed_symptoms:
continue
for symptom_data in symptoms:
if symptom_data["name"] == new_symptom_name:
add_symptom(symptom_data)
#print(len(possible_diseases), len(new_possible_diseases))
possible_diseases = new_possible_diseases
def remove_symptom(symptom):
global possible_symptoms
global possible_diseases
global confirmed_symptoms
possible_symptoms = {}
new_possible_diseases = []
confirmed_symptoms.append(symptom)
for disease in possible_diseases:
if symptom["name"] not in disease["symptoms"]:
new_possible_diseases.append(disease)
for new_symptom_name in disease["symptoms"]:
if new_symptom_name in confirmed_symptoms:
continue
for symptom_data in symptoms:
if symptom_data["name"] == new_symptom_name:
add_symptom(symptom_data)
possible_diseases = new_possible_diseases
def get_medicine(list):
print(list)
diagnose = False
greet = True
ending = False
doctor = False
probe = None
finish = False
def get_response(inputString):
global diagnose
global greet
global ending
global doctor
global probe
global finish
global possible_symptoms
global possible_diseases
global confirmed_symptoms
if input == "":
return "Please type something so we can chat :("
response = processInput(inputString, responses)
if response == "unknown":
return unknown.unknown_string()
if greet:
if response["intent"] == "Greet":
return response["response"]
elif response["intent"] == "symptom":
greet = False
diagnose = True
confirm_symptom(response)
elif response["intent"] == "book":
greet = False
doctor = True
return "Would you like to book an appointment with neurology?"
else:
return unknown.unknown_string()
if diagnose:
if (probe != None):
if (response["intent"] == "YES"):
confirm_symptom(probe)
else:
remove_symptom(probe)
keys = list(possible_symptoms.keys())
if len(possible_diseases) > 1 and possible_symptoms[keys[0]][1] != possible_symptoms[keys[-1]][1]:
next_symptom = possible_symptoms.popitem()[1][0]
probe = next_symptom
return next_symptom["probing question"]
else:
if len(possible_diseases) < 1:
return "No such disease found"
else:
final_disease = possible_diseases.pop()
text = "It seems you have {name}. {info}".format(name = final_disease["disease"], info = final_disease["info"])
if final_disease["tests"] != []:
text += ". The following tests might be needed to confirm this diagnosis: ".join(final_disease["tests"])
if final_disease["medicines"] != []:
text += ". You can take the following medicines: ".join(final_disease["medicines"])
if final_disease["doctor_specialty"] != "":
text += ". You're recommended to consult a doctor specialising in {} as soon as possible. Would you like to book an appointment with a doctor?".format(final_disease["doctor_specialty"])
doctor = True
else:
text += ". Can I help you with something else?"
finish = True
diagnose = False
probe = None
return text
if doctor:
doctor = False
if (response["intent"] == "YES"):
finish = True
return "Your doctor has been booked. Is there anything else you would like help with?"
else:
ending = True
if ending:
ending = False
finish = True
return ending_statement
if finish:
greet = True
finish = False
if (response["intent"] == "YES"):
possible_diseases = diseases
#make a priority list of symptoms that we need to rule out with priority bring how close it is to 50%
possible_symptoms = {}
confirmed_symptoms = []
return "Great! How can I help?"
# add options here instead of making it an open ended question. book appointment, get diagnosis, buy medicine, buy health insurance
else:
return "Thank you for using our services. Please provide us with valuable feedback at www.feedback.com"
class chatBot(Resource):
def get(self, inputString):
resp = get_response(inputString)
return resp
api.add_resource(chatBot, "/predict/<string:inputString>")
if __name__ == "__main__":
app.run(debug=True)