def post(self, request): sentence = request.data.get("text") dbrow = Record(user=request.user, search_query=sentence) dbrow.save() api = infermedica_api.get_api() response = api.parse(sentence).to_dict()["mentions"] mysymptomlist = [] templist = {} print("reached templist") for data in response: templist["orth"] = data["orth"] templist["id"] = data["id"] mysymptomlist.append(templist.copy()) finalsearchdata = [] print("reached finalserach") for symptom in mysymptomlist: callsearchdata = api.search(symptom['orth']) finalsearchdata.extend(callsearchdata) finaldict = {} print("conversion") for dictdata in finalsearchdata: finaldict[dictdata['label']] = dictdata['id'] symprow = Symptomrecord(user_record=dbrow, present_symptoms=dictdata['label'], present_symptoms_id=dictdata['id']) symprow.save() return Response(finaldict, status=status.HTTP_200_OK)
def post(self, request): try: present_symptoms = request.data.getlist('choices[]') absent_symptoms = request.data.getlist('unchoices[]') except AttributeError: present_symptoms = request.data.get('choices') absent_symptoms = request.data.get('unchoices') query_text = request.data.get('queryText') recordobject = Record.objects.get(user=request.user, search_query=query_text) api = infermedica_api.get_api() re = infermedica_api.Diagnosis(sex=request.data.get("gender"), age=request.data.get("age")) for symptom in present_symptoms: re.add_symptom(symptom, 'present') for symptom in absent_symptoms: re.add_symptom(symptom, 'absent') re = api.diagnosis(re).to_dict() for dictdata in re['conditions']: diseaseobject = Diseaserecord(user_record=recordobject, probable_diseases=dictdata['name'], probable_diseases_id=dictdata['id']) diseaseobject.save() return Response({"test": re}, status=status.HTTP_200_OK)
def index(request): api = infermedica_api.get_api() template = 'causes/index.html' response = HttpResponse("<h1>This is the causes page") debug = request.session['name'] print(request.session['name']) print("we have this many:", len(debug)) request = infermedica_api.Diagnosis(sex='female', age=35) for x in range(1, len(debug)): request.add_symptom(debug[x], 'present') request = api.diagnosis(request) first_cause=request.conditions[0]['name'] second_cause=request.conditions[1]['name'] third_cause=request.conditions[2]['name'] first_prob=request.conditions[0]['probability'] second_prob=request.conditions[1]['probability'] third_prob=request.conditions[2]['probability'] print(first_cause) print(first_prob*100) return render(request, "causes/index.html", context)
def post(self, request): symptoms = Symptoms.objects.filter(user_id=request.user) patient = Patient.objects.filter(user_id=request.user) trackers = Tracker.objects.all() patient_age = patient[0] arr = [] conditions = [] api = infermedica_api.get_api() call = infermedica_api.Diagnosis(sex=patient_age.sex.lower(), age=patient_age.age) for s in symptoms: call.add_symptom(s.s_id, 'present', initial=True) arr.append(s.s_id) call = api.diagnosis(call) conditions.append(call.conditions) for i in conditions: for name in i: name['probability'] *= 100 name['probability'] = round(name['probability'], 2) context = { 'arr': arr, 'symptoms': symptoms, 'conditions': conditions, 'trackers': trackers } return render(request, self.template_name, context)
def __init__(self, api_model, api_version, app_id, app_key, disable_groups=False): # Represent user data self.user_profile = self.UserProfile() self.actual_diagnosis = infermedica_api.Diagnosis(sex="", age=0) self.actual_diagnosis.set_extras(attribute="disable_groups", value=disable_groups) self.triage = None # Infermedica API configuration infermedica_api.configure(app_id=app_id, app_key=app_key, model=api_model, api_version=api_version) try: self.infermedica_api = infermedica_api.get_api() except MissingConfiguration as e: # TODO: esta excepcion no esta funcionando logger.critical(str(e)) raise Exception
def main(): infermedica_api.configure({ 'app_id': args.id, 'app_key': args.key, 'dev_mode': args.mode, }) api = infermedica_api.get_api()
def generateQuestions(kid, choice_id): infermedica_api.configure(app_id='182669ec', app_key='65fbdbdf4f285711553f6bc6d94d9e53') api = infermedica_api.get_api() #UserDetails request = infermedica_api.Diagnosis(sex='male', age=35) for k in range(len(kid)): request.add_symptom(kid[k], choice_id[k]) #print(kid[k], choice_id[k]) request = api.diagnosis(request) try: flag=request.conditions[0]["probability"] except: flag=1 print("Elixir: This sounds critical. You may want to consult a doctor instead.") return while(flag<0.20): print("Elixir: "+request.question.text) prev_out = request.conditions[0]['name'] #print(request.conditions) entities = request.question.items #print(entities) # for i in range(len(entities)): # print(entities[i]["id"]) # print(entities[i]["name"]) print("Elixir: "+entities[0]["name"]+"?") new_input = raw_input("Elixir: Enter your Choice"+"(Yes/No/Maybe/DontAsk): ") new_input = new_input.lower() if(new_input=="yes"): request.add_symptom(entities[0]["id"], "present") elif(new_input=="no"): request.add_symptom(entities[0]["id"], "absent") elif(new_input=="maybe"): request.add_symptom(entities[0]["id"], "unknown") else: break request = api.diagnosis(request) try: flag=request.conditions[0]["probability"] except: flag=1 disease = prev_out print("Elixir: You may have "+disease) external_page = wikipedia.page(disease) print("Elixir: External URL(For more info): "+external_page.url) return disease = request.conditions[0]['name'] print("Elixir: You may have "+disease) external_page = wikipedia.page(disease) print(wikipedia.summary(disease, sentences=1)) print("Elixir: External URL(For more info): "+external_page.url)
def infermedicaCon(self): """ Instantiate Infermedica API """ infermedica_api.configure({ 'app_id': '143fb87b', 'app_key': '7c3c9dd9c4adcdc0d9c314007c28441f', 'dev_mode': True # Use only during development on production remove this parameter }) return infermedica_api.get_api(), infermedica_api
def symptom_diagnosis(gender, age, patientname): api = infermedica_api.get_api() print(gender, age) request = infermedica_api.Diagnosis(sex=gender, age=age) collection = create_db_conn('symptom') symptoms = collection.find({'patientusername': patientname}) for symptom in symptoms: request.add_symptom(symptom['symptomid'], 'present') # call diagnosis again with updated request request = api.diagnosis(request) return request
def get_instance(): parser = ConfigParser() # create a config parser parser.read('configurations.ini') #reading configuration file aId = parser.get('auth', 'app_id') aKey = parser.get('auth', 'app_key') infermedica_api.configure( app_id=aId, app_key=aKey) # configure our api to authenticate requests api = infermedica_api.get_api() return api
def symptom_diagnosis(gender, age, patientname): api = infermedica_api.get_api() print(gender, age) request = infermedica_api.Diagnosis(sex=gender, age=age) collection = create_db_conn('symptom') symptoms = collection.find({'patientusername':patientname}) for symptom in symptoms: request.add_symptom(symptom['symptomid'], 'present') # call diagnosis again with updated request request = api.diagnosis(request) return request
def post(self, request): api = infermedica_api.get_api() response = api.parse(sentence).to_dict()["mentions"] # import pdb; pdb.set_trace() mysymptomlist = {} for data in response: mysymptomlist["orth"] = data["orth"] mysymptomlist["id"] = data["id"] data.append(api.symptom_details(mysymptomlist["id"])) return Response({"test": data}, status=status.HTTP_200_OK)
def testing(): infermedica_api.configure(app_id='eb66ec4d', app_key='0dd627685ea5a3453973ea6aab7f36c1') api = infermedica_api.get_api() symtoms = ["heart", "headache", "craving"] # Create diagnosis object with initial patient information. # Note that time argument is optional here as well as in the add_symptom function request = infermedica_api.Diagnosis(sex='male', age=35) for i in symtoms: symptom_id = api.search(i)[0]["id"] print(symptom_id) request.add_symptom(symptom_id, 'present') # # request.add_symptom('s_21', 'present') # request.add_symptom('s_98', 'present') # request.add_symptom('s_107', 'absent') # request.set_pursued_conditions(['c_33', 'c_49']) # Optional # call diagnosis request = api.diagnosis(request) # # Access question asked by API # print(request.question) # print(request.question.text) # actual text of the question # print(request.question.items) # list of related evidences with possible answers # print(request.question.items[0]['id']) # print(request.question.items[0]['name']) # print(request.question.items[0]['choices']) # list of possible answers # print(request.question.items[0]['choices'][0]['id']) # answer id # print(request.question.items[0]['choices'][0]['label']) # answer label # Access list of conditions with probabilities # print(request.conditions) # print(request.conditions[0]['id']) print(request.conditions[0]['name']) # print(request.conditions[0]['probability']) # Next update the request and get next question: # Just example, the id and answer shall be taken from the real user answer request.add_symptom(request.question.items[0]['id'], request.question.items[0]['choices'][1]['id']) # call diagnosis method again request = api.diagnosis(request) # ... and so on, until you decide to stop the diagnostic interview. return request.conditions[0]['name']
def __init__(self, sex, age): infermedica_api.configure({ 'app_id': INF_APP_ID, 'app_key': INF_APP_KEY, 'dev_mode': True # Use only during development on production remove this parameter }) self.inf_api = infermedica_api.get_api() self.sex = sex self.age = age self.symptoms = {} self.last_question = None self.condition = None
def diagnostics(sex_, age_, symp_list): api = infermedica_api.get_api() request = infermedica_api.Diagnosis(sex=sex_, age=int(age_)) for symptom in symp_list: request.add_symptom( symptom["id"], symptom["choice_id"], initial=True if symptom['choice_id'] == 'present' else False) response = api.diagnosis(request) return { "question": response.question.text, "question_type": response.question.type, "should_stop": response.should_stop, "symptoms": response.symptoms, "item": response.question.items, "conditions": response.conditions, }
def index(request): api = infermedica_api.get_api() # all_symptoms = Symptoms.objects.all() # context = {'all_symptoms' : all_symptoms,} print(request.method) # print(request) if (request.method == "POST"): debug = request.POST.getlist('checks[]') print(len(debug)) request = infermedica_api.Diagnosis(sex='female', age=35) for x in range(1, len(debug)): request.add_symptom(debug[x], 'present') request = api.diagnosis(request) for x in range(1, 3): print(request.conditions[x]) # print(next((item for item in request if item["probability"] >= "0.10"))) # print(request['question']) number_of_symptoms = len(debug) return HttpResponseRedirect('/') else: # request.GET form = PostForm() context = { "form": form, } return render(request, "symptoms/post_form.html", context) #################################################################### # def request_page(request): # if (request.GET.get('mybtn')): # counter = 8 # print counter # return render('symptoms/index.html')
def getQuestion(sex_input, age_input, symptoms_list): infermedica_api.configure(app_id='cf82ff04', app_key='e4ea29fdc3b01d4263da84423dc6cac0') api = infermedica_api.get_api() symptoms = symptoms_list #CATCH TRUE SYMPTOMS request = infermedica_api.Diagnosis(sex=sex_input, age=age_input) #CATCH for i in symptoms: json_symptoms = "{ \"text\": \"" + i + "\", \"include_tokens\": \"false\"}" print(json_symptoms) try: symptom_id = parse2(json_symptoms).json()["mentions"][0]["id"] request.add_symptom(symptom_id, 'present') except IndexError: pass request = api.diagnosis(request) rest_of_test(api, request) return request.question #question du resultat
def post(self, request): symptoms = Symptoms.objects.filter(user_id=request.user) form = SearchForm(request.POST or None) if form.is_valid(): new_search = form.save(commit=False) new_search.user_id = request.user.id query = request.POST['query'] api = infermedica_api.get_api() search = api.search(query) new_search.save() else: print('false') context = { 'form': form, 'query': query, 'search': search, 'symptoms': symptoms } return render(request, self.template_name, context)
def searched(): config_med.setup_examples( ) #connecting to infermedica API to extract diagnosis for symtoms entered by user sym = request.form['search'] #------extracting important keyword from sentence entered by user #example: Suppose use user entered "I have pain and fever" #So extracting words like pain and fever and searching for medical conditions user might be experiencing and then suggesting some more symptom for user to select from and finally getting diagnosis result words1 = word_tokenize(sym) tagged_sent = nltk.pos_tag(words1) pn = [] for word, pos in tagged_sent: print(word, pos) if pos == 'NN' or pos == 'NNS' or pos == 'VBN' or pos == 'VBG': pn.append(word) #print(pn) api = infermedica_api.get_api() symptom = [] for word in pn: #print('Look for evidences containing phrase {}'.format(word)) symptom_json = api.search(word) symptom.append(symptom_json) return render_template("select.html", sym=symptom)
def get_conditions(self, sex, age, symptoms): ''' Return a list of possible conditions by the symptoms :param sex: string can only be "female" or "male" :param age: int :param symptoms: list of strings list of symptoms :rtype: list of strings list of possible conditions ''' infermedica_api.configure(app_id='2f25564c', app_key='bf70a95520b458fe0e69974f34d19a22') api = infermedica_api.get_api() # Create diagnosis object with initial patient information. request = infermedica_api.Diagnosis(sex=sex, age=age) for i in range(len(symptoms)): if symptoms[i] is None: continue try: request.add_symptom(symptoms[i], 'present') except: x = 0 try: request = api.diagnosis(request) except: y = 0 result = [] # get list of possible conditions for i in range(min(len(request.conditions), 3)): try: result.append(request.conditions[i]['name']) except: x = 0 return result
from __future__ import print_function import config config.setup_examples() import infermedica_api if __name__ == '__main__': api = infermedica_api.get_api() # Prepare the diagnosis request object request = infermedica_api.Diagnosis(sex='male', age=30) request.add_symptom('s_1193', 'present') request.add_symptom('s_488', 'present') request.add_symptom('s_418', 'absent') # Alternatively prepare a dict based request object # request = { # 'sex': 'male', # 'age': 30, # 'evidence': [ # {'id': 's_1193', 'choice_id': 'present'}, # {'id': 's_488', 'choice_id': 'present'}, # {'id': 's_418', 'choice_id': 'absent'} # ] # } # call triage method request = api.suggest(request) # and see the results
def diag(sex,age): import sys,os import json setup_examples() import infermedica_api if(True): #sys.stdout = open(os.devnull,'w') api = infermedica_api.get_api() print('What is wrong?') RS=input() response = api.parse(RS) pjson=json.loads(str(response)) idl=[] choice=[] #sys.stdout = sys.__stdout__ for data in pjson['mentions']: idl.append(data['id']) choice.append(data['choice_id']) request = infermedica_api.Diagnosis(sex, age) for i in range(len(idl)): request.add_symptom(idl[i],choice[i]) request = api.diagnosis(request) pjson=json.loads(str(request)) response=pjson names="" furt="" for data in response: if(data == 'conditions'): names=response[data][0]['common_name'] if (data == 'question'): furt=response[data]['text'] print(furt+"\n") query=input() query=query+" "+names.split(',')[0] RS=RS+", "+query response = api.parse(RS) pjson=json.loads(str(response)) idl=[] choice=[] sys.stdout = sys.__stdout__ for data in pjson['mentions']: idl.append(data['id']) choice.append(data['choice_id']) request = infermedica_api.Diagnosis(sex,age) for i in range(len(idl)): request.add_symptom(idl[i],choice[i]) request = api.diagnosis(request) pjson=json.loads(str(request)) response=pjson names="" furt="" for data in response: if(data == 'conditions'): names=response[data][0]['common_name'] if (data == 'question'): furt=response[data]['text'] print(furt+"\n") query=input() query=query+" "+names.split(',')[0] RS=RS+", "+query response = api.parse(RS) pjson=json.loads(str(response)) idl=[] choice=[] sys.stdout = sys.__stdout__ for data in pjson['mentions']: idl.append(data['id']) choice.append(data['choice_id']) request = infermedica_api.Diagnosis(sex,age) for i in range(len(idl)): request.add_symptom(idl[i],choice[i]) request = api.diagnosis(request) pjson=json.loads(str(request)) response=pjson names="" furt="" for data in response: if(data == 'conditions'): names=response[data][0]['common_name'] if (data == 'question'): furt=response[data]['text'] print(furt+"\n") query=input() query=query+" "+names.split(',')[0] RS=RS+", "+query response = api.parse(RS) pjson=json.loads(str(response)) idl=[] choice=[] sys.stdout = sys.__stdout__ for data in pjson['mentions']: idl.append(data['id']) choice.append(data['choice_id']) request = infermedica_api.Diagnosis(sex,age) for i in range(len(idl)): request.add_symptom(idl[i],choice[i]) request = api.diagnosis(request) pjson=json.loads(str(request)) response=pjson names="" furt="" for data in response: if(data == 'conditions'): print(response[data][0]['common_name']) if (data == 'question'): print(response[data]['text'])
class medget: api = infermedica_api.get_api() def get_data(self,sex_m,age_m): ''' Initialize the user to be diagnosed ''' self.user_data = infermedica_api.Diagnosis(sex=sex_m.lower(), age=age_m) def add_symptoms(self, ids): ''' The ids is the list of dicts with keys 'id' and 'status' ''' for i in ids: self.user_data.add_symptom( str(i[str(u'id')]), str(i[str(u'status')]) ) def search_symptoms(self, symptoms_str): ''' Outputs more symptoms related to symptom_str (is a list of symptoms) user enters ''' search_res = [] for i in symptoms_str: res = self.api.search(i) for k in res: res_p = {} res_p['id'] = str(k[str('id')]) res_p['label'] = str(k[str('label')]) search_res.append(res_p) res_p=None return search_res def get_question(self, ): ''' Diagnose the previous question/symptoms input and gives the next question ''' self.user_data = self.api.diagnosis(self.user_data) optn_list = [] ques = {} ques['text'] = self.user_data.question.text ques['option'] = [] for i in self.user_data.question.items: optn = {} optn['id'] = i['id'] optn['name'] = i['name'] optn['choice'] = i['choices'] ques['option'].append(optn) return ques def check_risk(self, risk_prob=0.7): ''' Outputs the risk of disease the user may have according to the probability risk_prob ''' if self.user_data.conditions[0]['probability'] > risk_prob: return 1 else: return 0 def get_result(self, ): ''' Outputs the probable disease the user may have ''' result = {} result['id'] = str(self.user_data.conditions[0][str('id')]) result['name'] = str(self.user_data.conditions[0][str('name')]) result['prob'] = str(self.user_data.conditions[0]['probability']) k = self.api.condition_details(result['id']).__dict__ result['hint'] = str(k[str('extras')][str('hint')]) result['severity'] = str(k[str('severity')]) result['prevalence'] = str(k[str('prevalence')]) result['acuteness'] = str(k[str('acuteness')]) return result
def index(request): api = infermedica_api.get_api() template = 'causes/index.html' response = HttpResponse("<h1>This is the causes page") debug = request.session['name'] print(request.session['name']) print("we have this many:", len(debug)) cause = infermedica_api.Diagnosis(sex='female', age=35) for x in range(0, len(debug)): cause.add_symptom(debug[x], 'present') cause = api.diagnosis(cause) first_cause=cause.conditions[0]['name'] second_cause=cause.conditions[1]['name'] third_cause=cause.conditions[2]['name'] first_prob=cause.conditions[0]['probability'] second_prob=cause.conditions[1]['probability'] third_prob=cause.conditions[2]['probability'] print(first_cause) print(first_prob*100) ############################## common_cold = 'http://otcsa.azurewebsites.net/list-of-illnesses/cold/' influenza = 'http://otcsa.azurewebsites.net/list-of-illnesses/influenza-flu/' acute_sinusitis = 'http://otcsa.azurewebsites.net/list-of-illnesses/sinusitis/' acid_reflux = 'http://otcsa.azurewebsites.net/list-of-illnesses/acid-reflux/' conjunctivitis = 'http://otcsa.azurewebsites.net/list-of-illnesses/conjunctivitis-pinkeye/' # stomach_flu = 'http://otcsa.azurewebsites.net/list-of-illnesses/gastroenteritis-stomach-flu/' headache = 'http://otcsa.azurewebsites.net/list-of-illnesses/headache/' joint_pain = 'http://otcsa.azurewebsites.net/list-of-illnesses/joint-pain/' migraine = 'http://otcsa.azurewebsites.net/list-of-illnesses/migraine/' # muscle_pain = 'http://otcsa.azurewebsites.net/list-of-illnesses/muscle-pain/' rhinitis_allergic = 'http://otcsa.azurewebsites.net/list-of-illnesses/rhinitis-allergic-hayfever/' med = '/treatment' if first_cause == "Common cold": first_cause1 = common_cold elif first_cause == "Influenza": first_cause1 = influenza elif first_cause == "Acute sinusitis": first_cause1 = acute_sinusitis elif first_cause == "Acid reflux disease": first_cause1 = acid_reflux elif first_cause == "Conjunctivitis": first_cause1 = conjunctivitis # elif first_cause == "": # first_cause1 = stomach_flu elif first_cause == "Tension-type headaches": first_cause1 = headache elif first_cause == "Joint or bone trauma": first_cause1 = joint_pain elif first_cause == "Migraine": first_cause1 = migraine # elif first_cause == "Muscle Pain": # first_cause1 = muscle_pain elif first_cause == "Allergic rhinitis": first_cause1 = rhinitis_allergic else: first_cause1 = treatment if second_cause == "Common cold": second_cause1 = common_cold elif second_cause == "Influenza": second_cause1 = influenza elif second_cause == "Acute sinusitis": second_cause1 = acute_sinusitis elif first_cause == "Acid reflux disease": second_cause1 = acid_reflux elif second_cause == "Conjunctivitis": second_cause1 = conjunctivitis elif second_cause == "Tension-type headaches": second_cause1 = headache elif second_cause == "Joint or bone trauma": second_cause1 = joint_pain elif second_cause == "Migraine": second_cause1 = migraine # elif second_cause == "Muscle Pain": # second_cause1 = muscle_pain elif second_cause == "Allergic rhinitis": second_cause1 = rhinitis_allergic else: second_cause1 = treatment if third_cause == "Common cold": third_cause1 = common_cold elif third_cause == "Influenza": third_cause1 = influenza elif third_cause == "Acute sinusitis": third_cause1 = acute_sinusitis elif third_cause == "Acid reflux disease": third_cause1 = acid_reflux elif third_cause == "Conjunctivitis": third_cause1 = conjunctivitis elif third_cause == "Tension-type headaches": third_cause1 = headache elif third_cause == "Joint or bone trauma": third_cause1 = joint_pain elif third_cause == "Migraine": third_cause1 = migraine # elif third_cause == "Muscle Pain": # third_cause1 = muscle_pain elif third_cause == "Allergic rhinitis": third_cause1 = rhinitis_allergic else: third_cause1 = treatment context = { "first_cause": first_cause, "second_cause" : second_cause, "third_cause" : third_cause, "first_prob" : int(first_prob*100), "second_prob" : int(second_prob*100), "third_prob" : int(third_prob*100), "first_cause1": first_cause1, "second_cause1": second_cause1, "third_cause1": third_cause1 } def index(request): print(request.method) if (request.method == "POST"): debug = request.POST.getlist('checks[]') request.session['name'] = debug return HttpResponseRedirect('/treatment/') return render(request, "causes/index.html", context)
def main(): api = infermedica_api.get_api() request_diag = infermedica_api.Diagnosis(sex='male', age=35) lines = read_in_from_server() #print(lines) diagnose(lines, api, request_diag)
def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: dict_of_rec = { "about_treatment":"Lifestyle and home remedies" ,"overveiw": "Overview" ,"causes": "Causes" ,"prevention": "Prevention","about_symptoms": "Symptoms"} last_intent = tracker.latest_message['intent'].get('name').split(".")[-1] parent_intent = tracker.latest_message['intent'].get('name').split(".")[0] disease = tracker.get_slot("disease") print(last_intent) print(parent_intent) intent = tracker.latest_message['intent'].get('name') print(intent) shan_text = [ { "recipient_id": "bot", "type":"text", "text": "Hi again!" } ] shan_btn = [ { "recipient_id": "bot", "type":"button", "buttons": [ { "title": "about products", "payload": "about products" }, { "title": "founders of Medsamaan", "payload": "founders of Medsamaan" }, { "title": "about Medsamaan", "payload": "about Medsamaan" } ] } ] shan_img = [ { "recipient_id": "bot", "type":"image", "images": [ { "text": "about products", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" } ] } ] shan_img_btn =[ { "recipient_id": "bot", "type" : "image_button", "buttons": [ { "title": "about products", "payload": "about products" }, { "title": "founders of Medsamaan", "payload": "founders of Medsamaan" }, { "title": "about Medsamaan", "payload": "about Medsamaan" } ], "images": [ { "text": "about products", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "founders of Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "about Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" } ] } ] shan_img_btn_txt =[ { "recipient_id": "bot", "type" : "image_button_text", "text":"cnocvowecowlcwwobvnw wobwevc nwocwe wowbveviosecewv obfnweof vwovnw vwowf eofefne fefoefqefqefqefoaeflaefne faeoffb ofef", "buttons": [ { "title": "about products", "payload": "about products" }, { "title": "founders of Medsamaan", "payload": "founders of Medsamaan" }, { "title": "about Medsamaan", "payload": "about Medsamaan" } ], "images": [ { "text": "about products", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "founders of Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" }, { "text": "about Medsamaan", "src": "https://www.drugs.com/mayo/media/ADF419FD-A51A-430C-9C92-5703D91A2733.jpg" } ] } ] dict_of_rec = { "about_treatment":"Lifestyle and home remedies" ,"overveiw": "Overview" ,"causes": "Causes" ,"prevention": "Prevention","about_symptoms": "Symptoms"} disease = tracker.get_slot("disease") intent = tracker.latest_message['intent'].get('name') print(intent) if intent == "shantanu_img": dispatcher.utter_custom_json(shan_img) elif intent == "shantanu_text": dispatcher.utter_custom_json(shan_text) elif intent == "shantanu_btn": dispatcher.utter_custom_json(shan_btn) elif intent == "shantanu_img_btn": dispatcher.utter_custom_json(shan_img_btn) elif intent == "shantanu_text_img_button": dispatcher.utter_custom_json(shan_img_btn_txt) elif parent_intent == "smalltalk": wks = ms_sm_wks cell = wks.find(last_intent) ## row & col of search element answer = wks.cell(cell.row, cell.col+3).value ## dispatched answer dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) elif intent =="prevention": wks = disease_symptom_overview print(disease) cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+4).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Overview for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="about_treatment": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+1).value # dispatcher.utter_message("Treatment for " + disease) # dispatcher.utter_message(answer) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="prevention": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+4).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Overview for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="about_symptoms": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+5).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Symptoms for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] print(list_of_rem) for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="overview": wks = disease_symptom_overview cell = wks.find(disease.capitalize()) ## row & col of search element answer = wks.cell(cell.row, cell.col+2).value #list_of_rem = list(dict_of_rec.keys()).remove(intent) list_of_rem = list(dict_of_rec.keys()) list_of_rem.remove(intent) # dispatcher.utter_message("Overview for " + disease) # dispatcher.utter_message(answer) shan_text = [ { "recipient_id": "bot", "type":"text", "text": answer } ] dispatcher.utter_custom_json(shan_text) list_of_buttons = [] for i in list_of_rem: temp_dict ={} temp_dict['title'] = disease +" of "+ dict_of_rec[i] temp_dict['payload'] = i +" of "+ disease list_of_buttons.append(temp_dict) shan_text_btn = [ { "recipient_id": "bot", "type":"text_button", "text":"Related Topics to Look For:", "buttons": list_of_buttons } ] dispatcher.utter_custom_json(shan_text_btn) elif intent=="symptom_checker": user_uttered_msg = tracker.latest_message["text"] infermedica_api.configure(app_id='d91c00d6',app_key='50573fae6348390c63e87e7c5b584547') api = infermedica_api.get_api() headers = { 'App-Id': 'd91c00d6', 'App-Key': '50573fae6348390c63e87e7c5b584547', 'Content-Type': 'application/json', } data = str({"text":user_uttered_msg}) response = requests.post('https://api.infermedica.com/v2/parse', headers=headers, data=data) response.text request = infermedica_api.Diagnosis(sex='male', age=30) syms = response.json()['mentions'] for i in syms: request.add_symptom(i['id'], i['choice_id']) print(request) # call diagnosis request = api.diagnosis(request) request = request.condition for i in request: shan_text = [ { "recipient_id": "bot", "type":"text", "text": i['common_name']+": "+str(i['probability']) } ] dispatcher.utter_custom_json(shan_text) elif "locate" in intent: url='https://maps.googleapis.com/maps/api/place/textsearch/json?'# where you will send your requests api_key='' #enter your api key generated, if not generated then generate at https://cloud.google.com/maps-platform/?apis=places url2 = 'https://maps.googleapis.com/maps/api/place/details/json?' def maps(search,location): x = [] i =0 while((x == [] or x==None) and i<10): x=requests.get(url+'query={}&key={}'.format(search.lower()+"+"+"in"+"+"+location.lower(),api_key)).json()['results'] i+=1 #Extracted 'results' out of the api data . 'results' would come in json #return(x) if len(x)<1: print("No "+search.lower()+" found at {0}".format(location)) # if query invalid then prompt the user to be more general else: RANGE=3 # default 3 results would be displayed . Change accordingly if len(x)<3:RANGE=2 if len(x)<2:RANGE=1 print("nearest ".format(RANGE) + search.lower() + " locations found at {} :\n".format(location)) for i in range(RANGE): y = None j = 0 while((y==[] or y=={} or y==None) and j<10): y = requests.get(url2+'place_id={}&key={}'.format(x[i]['place_id'],api_key)).json()#['formatted_phone_number']#["formatted_phone_number"] j+=1 if 'result' in y: shan_text = [ { "recipient_id": "bot", "type":"name_descript", "items": [{"name":x[i]['name'], "descript":x[i]['formatted_address']+"\n"+y['result']['formatted_phone_number']+"\n"+"https://www.google.com/maps/place/?q=place_id:"+x[i]['place_id']}] } ] else: shan_text = [ { "recipient_id": "bot", "type":"name_descript", "items": [{"name":x[i]['name'], "descript":x[i]['formatted_address']+"\n"+"https://www.google.com/maps/place/?q=place_id:"+x[i]['place_id']}] } ] dispatcher.utter_custom_json(shan_text) loc = tracker.get_slot('current_location') if intent=="locate_clinic": maps("hospital",loc) elif intent=="locate_doctor": maps("doctor",loc) "text": i['common_name']+":"+i['probability'] } ]
from .. import config config.setup_examples() import infermedica_api if __name__ == "__main__": api: infermedica_api.APIv3Connector = infermedica_api.get_api() # Prepare the diagnosis request object request = config.get_example_request_data() # call the explain method request = api.explain(**request, target_id="c_49") # and see the results print("\n\n", request)
from .. import config config.setup_examples() import infermedica_api if __name__ == "__main__": api: infermedica_api.ModelAPIv2Connector = infermedica_api.get_api("v2") print("Symptoms list:") print(api.symptom_list(), end="\n\n") print("Symptom details:") print(api.symptom_details("s_56"), end="\n\n") print("Symptom details (with children):") print(api.symptom_details("s_551"), end="\n\n") print("Non-existent symptom details:") print(api.symptom_details("fail_test"))
class medget: api = infermedica_api.get_api() def get_data(self, sex_m, age_m): self.user_data = infermedica_api.Diagnosis(sex=sex_m, age=age_m) def add_symptoms(self, ids): for i in ids: self.user_data.add_symptom(str(i[str(u'id')]), str(i[str(u'status')])) #absent status add def search_symptoms(self, symptoms_str): search_res = [] #global api #j=0 for i in symptoms_str: res = self.api.search(i) #j = 0 for k in res: res_p = {} res_p['id'] = str(k[str('id')]) res_p['label'] = str(k[str('label')]) search_res.append(res_p) #return self.api.search('headache') return search_res def get_question(self, ): self.user_data = self.api.diagnosis(self.user_data) optn_list = [] ques = {} ques['text'] = self.user_data.question.text ques['option'] = [] for i in self.user_data.question.items: optn = {} optn['id'] = i['id'] optn['name'] = i['name'] optn['choice'] = i['choices'] ques['option'].append(optn) print(ques) return ques #return optn_list #return self.user_data.question.items def check_risk(self, ): if self.user_data.conditions[0]['probability'] > 0.7: return 1 else: return 0 def get_result(self, ): result = {} result['id'] = str(self.user_data.conditions[0][str('id')]) result['name'] = str(self.user_data.conditions[0][str('name')]) result['prob'] = str(self.user_data.conditions[0]['probability']) k = self.api.condition_details(result['id']).__dict__ result['hint'] = str(k[str('extras')][str('hint')]) result['severity'] = str(k[str('severity')]) result['prevalence'] = str(k[str('prevalence')]) result['acuteness'] = str(k[str('acuteness')]) return result
from __future__ import print_function import config config.setup_examples() import infermedica_api if __name__ == '__main__': api = infermedica_api.get_api() print('Risk factors list:') print(api.risk_factors_list(), end="\n\n") # print('\n\nRisk factor details:') # print(api.risk_factor_details(''), end="\n\n") print('Non-existent risk factor details:') print(api.risk_factor_details('fail_test'))
def search(symptom): api = infermedica_api.get_api() data = api.search(symptom["orth"]) return data