-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.py
274 lines (233 loc) · 9.07 KB
/
main.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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
import urllib
import json
import os
from flask import Flask
from flask import request
from flask import make_response
import infermedica_api
from secrets import * # contains infermedica app id/key
# from google.appengine.api import urlfetch
# urlfetch.set_default_fetch_deadline(60)
# import gae_fix
# import pyrebase
# firebase = pyrebase.initialize_app({
# "apiKey": FIREBASE_API_KEY,
# "authDomain": FIREBASE_AUTH_DOMAIN,
# "databaseURL": FIREBASE_DB_URL,
# "storageBucket": FIREBASE_STORAGE_BUCKET
# })
# db = firebase.database()
app = Flask(__name__)
app.config['DEBUG'] = True
infermedica_api.configure(app_id=INF_APP_ID, app_key=INF_APP_KEY)
sessionMap = {}
inf_api = infermedica_api.get_api()
conditions = inf_api.conditions_list()
@app.route('/webhook', methods=['POST'])
def webhook():
req = request.get_json(silent=True, force=True)
print("Request:")
print(json.dumps(req, indent=4))
res = processRequest(req)
res = json.dumps(res, indent=4)
print("Response:")
print(res)
response = make_response(res)
response.headers['Content-Type'] = 'application/json'
return response
def processRequest(req):
print("Processing request")
result = req.get("result")
# contexts = result.get("contexts")
action = result.get("action")
if action == "givesymptoms":
return giveSymptoms(req)
elif action == "followup":
return followUp(req)
return result
def finished(sessionId, diagnose_res):
del sessionMap[sessionId]
conditions = diagnose_res.get("conditions")
if conditions is not None:
if len(conditions) > 0:
done = False
out = []
for condition in conditions:
if condition.get("probability") > 0.5:
out.append(condition)
done = True
if len(out) == 3:
break
if len(out) == 0:
out.append(conditions[0])
msg = "Ok, here is your diagnosis... "
for x in range(len(out)):
msg += condition_message(out[x], x != 0)
# msg = "It looks like you have a chance of being diagnosed with: " + ",".join(out)
msg += "Thank you for using home doctor. I hope you feel better."
# save in db
# reports = db.child("reports")
# num_reports = len(reports.shallow().get())
# age = sessionMap[sessionId]['age']
# sex = sessionMap[sessionId]['sex']
# report = {'age': age, 'sex': sex, 'conditions': conditions}
# reports.set(str(num_reports), report)
return {
"speech": msg,
"displayText": msg,
"source": "apiai-homedoctor-webhook"
}
return {
"speech": "I couldn't find anything that you are likely to be affected by. Please see a doctor if you aren't feeling well.",
"displayText": "I couldn't find anything that you are likely to be affected by. Please see a doctor if you aren't feeling well.",
"source": "apiai-homedoctor-webhook"
}
def condition_message(condition, also):
prob = "very low"
if condition.get("probability") >= 0.9:
prob = "extremely high"
elif condition.get("probability") >= 0.7:
prob = "high"
elif condition.get("probability") >= 0.5:
prob = "moderate"
elif condition.get("probability") >= 0.1:
prob = "low"
rarity = "common"
acuteness = "acute"
severity = "mild"
hint = "Please see a doctor."
for cond in conditions:
if cond.get("name") == condition.get("name"):
if cond.get("extras"):
if cond.get("extras").get("hint"):
hint = cond.get("extras").get("hint")
rarity = cond.get("prevalence").replace("_", " ")
acuteness = cond.get("acuteness").replace("_", " ")
severity = cond.get("severity").replace("_", " ")
break
also = "also " if also else ""
if rarity == "moderate":
rarity = "moderate prevalence"
return 'There is {} a {} chance of you having {}. This is a {}, {} condition of {} severity. {}.'.format(
also, prob, condition.get('name'), rarity, acuteness, severity, hint
)
def followUp(req):
sessionId = req.get("sessionId")
result = req.get("result")
contexts = result.get("contexts")
action = result.get("action")
question_result = result.get("parameters").get("boolean_response")
age = 38
sex = "female"
question_symptom_id = "NULL"
symptoms = {}
for context in contexts:
if context.get("name") == "age_sex":
parameters = context.get("parameters")
age = parameters.get("age").get("amount")
sex = parameters.get("sex")
if context.get("name") == "question":
parameters = context.get("parameters")
question_symptom_id = parameters.get("id")
if context.get("name") == "symptoms":
symptoms = context.get("parameters")
del symptoms["boolean_response.original"]
del symptoms["boolean_response"]
if question_result == "Yes":
symptoms[question_symptom_id] = u'present'
elif question_result == "No":
symptoms[question_symptom_id] = u'absent'
else:
symptoms[question_symptom_id] = u'unknown'
print(symptoms)
# call diagnosis
diagnose_res, question = doDiagnosis(sessionId, symptoms, sex, age)
print(diagnose_res)
if sessionMap[sessionId].get("num_asked") > 8:
return finished(sessionId, diagnose_res)
else:
sessionMap[sessionId]['num_asked'] += 1
if question is not None:
question_symptom_id = question.get("items")[0].get("id")
return {
"speech": "Ok. " + question.get("text"),
"displayText": "Ok. " + question.get("text"),
# "data": data,
"contextOut": [{'name': "symptoms", 'lifespan': 20, 'parameters': symptoms},
{'name': "question", 'lifespan': 20, 'parameters': {"id": question_symptom_id}}],
"source": "apiai-homedoctor-webhook"
}
else:
return finished(sessionId, diagnose_res)
def doDiagnosis(sessionId, symptoms, sex, age):
print("Starting diagnosis/question finding task...")
while True:
diagnose_req = infermedica_api.Diagnosis(sex=sex, age=age)
diagnose_req.set_extras("ignore_groups", True)
for symptom in symptoms:
diagnose_req.add_symptom(symptom, symptoms[symptom])
diagnose_res = inf_api.diagnosis(diagnose_req).to_dict()
question = diagnose_res.get("question")
if question is not None:
text = question.get("text")
seen_questions = sessionMap[sessionId].get("seen_questions")
# if text in seen_questions:
# print("ERROR-- REPEATED QUESTION! EXITING!")
# return diagnose_res, None
# else:
# seen_questions.append(text)
print(question)
if question.get("type") == "single":
return diagnose_res, question
else:
print("ERROR-- question type not single?")
items = question.get("items")
for item in items:
question_symptom_id = item.get("id")
symptoms[question_symptom_id] = 'unknown'
continue
else:
return diagnose_res, None
def giveSymptoms(req):
sessionId = req.get("sessionId")
sessionMap[sessionId] = {'seen_questions': [], 'num_asked': 0, 'age': 30, 'sex': "female"}
result = req.get("result")
contexts = result.get("contexts")
action = result.get("action")
age = 38
sex = "female"
for context in contexts:
if context.get("name") == "age_sex":
parameters = context.get("parameters")
age = parameters.get("age").get("amount")
sex = parameters.get("sex")
sessionMap[sessionId]['age'] = age
sessionMap[sessionId]['sex'] = sex
symptomsQuery = result.get("resolvedQuery")
# print("Query=", symptomsQuery)
inf_response = inf_api.parse(symptomsQuery).to_dict()
print(inf_response)
mentions = inf_response.get("mentions")
symptoms = {}
for mention in mentions:
symptoms[mention.get("id")] = mention.get("choice_id")
# call diagnosis
diagnose_res, question = doDiagnosis(sessionId, symptoms, sex, age)
print(diagnose_res)
if question is not None:
question_symptom_id = question.get("items")[0].get("id")
return {
"speech": "Ok. " + question.get("text"),
"displayText": "Ok. " + question.get("text"),
# "data": data,
"contextOut": [{'name': "symptoms", 'lifespan': 20, 'parameters': symptoms},
{'name': "question", 'lifespan': 20, 'parameters': {"id": question_symptom_id}}],
"source": "apiai-homedoctor-webhook"
}
else:
return finished(sessionId, diagnose_res)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()