コード例 #1
0
    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)
コード例 #2
0
    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
コード例 #3
0
    def run(self, dispatcher, tracker, domain):
        api = infermedica_api.API(app_id='bc1dd653',
                                  app_key='76b11cd1b2b2e684e261346544731fb7')

        choices = {}
        buttons = []
        symp = tracker.get_slot('symptom')
        request = infermedica_api.Diagnosis(sex='male', age='25')

        symp = api.parse(symp).to_dict()
        symp_id = symp['mentions'][0]['id']
        request.add_symptom(symp_id, 'present')

        request = api.diagnosis(request)
        items = request.question.items

        #dispatcher.utter_message(items)
        for choice in items:
            choices[choice['id']] = choice['name']

        for key, value in choices.items():
            title = value
            #payload = ('/slot{\"choice\": ' + key + '}')
            #buttons.append({"title": title, "payload": payload})
            request.add_symptom(key, 'present')
            request = api.diagnosis(request)
            text = request.question.text
        #  response = "Let's try this medicine"
        dispatcher.utter_message(text)
        #dispatcher.utter_button_message(response, buttons)
        return [SlotSet('symptom', symp)]
コード例 #4
0
    def run(self, dispatcher, tracker, domain):
        api = infermedica_api.API(app_id='f1acb630',
                                  app_key='41b6c31e0d5158d1dbab51958f216cfc')
        choices = {}
        buttons = []
        symp = tracker.get_slot('symptom')
        request = infermedica_api.Diagnosis(sex='male', age='25')

        symp = api.parse(symp).to_dict()
        symp_id = symp['mentions'][0]['id']
        request.add_symptom(symp_id, 'present')

        request = api.diagnosis(request)
        items = request.question.items

        for choice in items:
            choices[choice['id']] = choice['name']

        response = request.question.text

        for key, value in choices.items():
            title = value
            request.add_symptom(key, 'present')
            request = api.diagnosis(request)
            text = request.question.text
            buttons.append({"title": title, "payload": text})
            response = "Let's try this medicine"

        dispatcher.utter_button_message(response, buttons)
        return [SlotSet('symptom', symp)]
コード例 #5
0
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
コード例 #6
0
    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)
コード例 #7
0
    def run(self, dispatcher, tracker, domain):
        api = infermedica_api.API(app_id=os.environ['APP_ID'],
                                  app_key=os.environ['API_KEY'])
        choices = {}
        buttons = []
        symp = tracker.get_slot('symptom')
        request = infermedica_api.Diagnosis(sex='male', age='25')

        symp = api.parse(symp).to_dict()
        symp_id = symp['mentions'][0]['id']
        request.add_symptom(symp_id, 'present')

        request = api.diagnosis(request)
        items = request.question.items

        for choice in items:
            choices[choice['id']] = choice['name']

        response = request.question.text

        for key, value in choices.items():
            title = value
            payload = ('/slot{\"choice\": ' + key + '}')
            buttons.append({"title": title, "payload": payload})
        #  response = "Let's try this medicine"

        dispatcher.utter_button_message(response, buttons)
        return [SlotSet('symptom', symp)]
コード例 #8
0
ファイル: bot.py プロジェクト: p-mayank/Elixir
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)
コード例 #9
0
def initialize_request(age, sex):
    """
    Creates initial diagnosis request.
    :param age: Patient's age.
    :param sex: Patient's gender.
    :return:
    """
    print("requesting " + str(age) + str(sex))
    request = infermedica_api.Diagnosis(age=age, sex='male')
    return request
コード例 #10
0
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
コード例 #11
0
    def run(self, dispatcher, tracker, domain):
        api = infermedica_api.API(app_id='bc1dd653',
                                  app_key='76b11cd1b2b2e684e261346544731fb7')

        rr = tracker.get_slot('symptom')
        request = infermedica_api.Diagnosis(sex='male', age='25')
        rr = api.parse(rr).to_dict()
        rr_id = rr['mentions'][0]['id']
        request.conditions.to_dict()
        request = api.diagnosis(request)

        dispatcher.utter_message(request)
        return [SlotSet('diagnosis', rr)]
コード例 #12
0
ファイル: run.py プロジェクト: MADGagnon/HealthAi
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']
コード例 #13
0
def diagnosis_med():
    selectedSymptom = request.form[
        'symp']  #getting symptom selected by user in above step
    selectedSymptom = selectedSymptom.split(',')
    gender = request.form['gender']
    age = request.form['age']
    api = infermedica_api.API(
        app_id='APP_ID', app_key='APP_KEY'
    )  #insert app_key and app_id you get from infermedica api
    req = infermedica_api.Diagnosis(sex=gender, age=age)
    for sym in selectedSymptom:
        req.add_symptom(sym, 'present')

    req = api.diagnosis(req)
    return render_template("diagnosis_bot.html", req=req)
コード例 #14
0
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,
    }
コード例 #15
0
def get_user(id):
    """ query data from the users table """
    conn = None
    Muser = user.MyUser()
    try:
        params = config()
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        cur.execute("select id,symptom,gender,age,diagnosis,first_name,last_name,profile_pic,question_count FROM users where id = "+str(id))
        print("The number of users: ", cur.rowcount)
        row = cur.fetchone()
        print(row)
        Muser.id = row[0]
        Muser.symptom = row[1]
        Muser.gender = row[2]
        Muser.age = row[3]
        if row[4] != 'empty':
            dstring = str(row[4]).replace("\n", "")
            print(dstring)
            diag_dict = json.loads(dstring)
            request = infermedica_api.Diagnosis(sex=Muser.gender, age=Muser.age)
            Muser.diagnosis = request
            print("-----diag_dict get_user------ " + str(diag_dict))
            diag_dict["case_id"] = 'null'
            diag_dict["evaluation_time"] = 'null'
            ConditionResultList = infermedica_api.models.diagnosis.ConditionResultList().from_json(diag_dict["conditions"])
#            Muser.diagnosis = request.update_from_api(diag_dict)
            Muser.diagnosis.conditions = ConditionResultList
            Muser.diagnosis.question = infermedica_api.models.diagnosis.DiagnosisQuestion().from_json(diag_dict["question"])
            for sym in diag_dict["symptoms"]:
                Muser.diagnosis.add_symptom(sym["id"],sym["choice_id"])
            print("-----Muser.diagnosis get_user------ " + str(Muser.diagnosis))
        Muser.first_name = row[5]
        Muser.last_name = row[6]
        Muser.profile_pic = row[7]
        Muser.question_count = row[8]
        
        cur.close()
    except (Exception, psycopg2.DatabaseError) as error:
        print("sql get_user error : " + str(error))
    finally:
        if conn is not None:
            conn.close()
    return Muser
コード例 #16
0
ファイル: test.py プロジェクト: MADGagnon/HealthAi
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
コード例 #17
0
def infer(request):
    form = infer_form(request.POST)
    if form.is_valid():
        age2 = form.cleaned_data['age']
        sex2 = form.cleaned_data['sex']
        Symp1 = form.cleaned_data['Symptom1']
        Symp2 = form.cleaned_data['Symptom2']
        Symp3 = form.cleaned_data['Symptom3']

    request2 = infermedica_api.Diagnosis(sex=sex2, age=age2)

    request2.add_symptom(Symp1.sid, 'present')
    request2.add_symptom(Symp2.sid, 'present')
    request2.add_symptom(Symp3.sid, 'present')

    # call diagnosis
    request2 = api.diagnosis(request2)
    request2 = request2.conditions

    return render(request, 'patientdetails/infer.html', {'request2': request2})
コード例 #18
0
def explain(api: infermedica_api.API):
    # Prepare diagnosis request it need to have sufficient amount of evidences
    # The most appropriate way to get a request way for explain method is to
    # use the one which has been created while interacting with diagnosis.
    # For the example purpose a new one is created.
    request = infermedica_api.Diagnosis(sex='female', age=35)

    request.add_symptom('s_10', 'present')
    request.add_symptom('s_608', 'present')
    request.add_symptom('s_1394', 'absent')
    request.add_symptom('s_216', 'present')
    request.add_symptom('s_9', 'present')
    request.add_symptom('s_188', 'present')

    # call the explain method
    request = api.explain(request, target_id='c_62')

    # and see the results

    Log.pretty(request)
コード例 #19
0
def get_diagnosis(age, sex):
    '''
    this function gets the symptoms from the user and adds them to search in infermedica
    '''
    request = infermedica_api.Diagnosis(sex=sex, age=age)
    flag = True
    print ('Please enter the various symptoms you have line by line.')
    print ('Press enter once more when you are done entering all of your symptoms.')
    print ('The more symptoms you enter the more accurate our diagnosis would be.')
    while (flag):
        symptom=raw_input('')
        if(symptom==""):
            flag = False
            break
        dic = api.search(symptom)
        try: 
            SID = dic[0]['id'] 
            request.add_symptom(SID, 'present')
        except: 
            print("")
    request = api.diagnosis(request)
    return request.conditions[0]['name'], request.conditions[0]['probability']
コード例 #20
0
def diagnosis(api: infermedica_api.API):
    request = infermedica_api.Diagnosis(sex='female', age=35)
    request.add_symptom('s_21', 'present', initial=True)
    request.add_symptom('s_98', 'present', initial=True)
    request.add_symptom('s_107', 'absent')

    # call diagnosis
    request = api.diagnosis(request)

    Log.pretty(request)

    # ask patient the questions returned by diagnosis and update request with patient answers
    request.add_symptom('s_99', 'present')
    request.add_symptom('s_8', 'absent')
    request.add_symptom('s_25', 'present')
    # ... and so on until you decided that enough question have been asked
    # or you have sufficient results in request.conditions

    # call diagnosis again with updated request
    request = api.diagnosis(request)

    # repeat the process
    Log.pretty(request)
コード例 #21
0
ファイル: views.py プロジェクト: bhumil2210/Med_Care
def symp_checker(request):
    text = text1 = text2 = text3 = condition = ""
    if request.method == 'POST' and 'btn' in request.POST:
        age = request.POST.get("age")
        gender = request.POST.get("gender")
        symptons = request.POST.get("symptons")
        print(symptons)
        api = infermedica_api.API(app_id='<api_id>', app_key='<api_key>')
        r = api.parse(symptons)
        j = json.loads(str(r))
        d = infermedica_api.Diagnosis(gender, age)
        for i in range(len(j['mentions'])):
            d.add_symptom(j['mentions'][i]['id'],
                          j['mentions'][i]['choice_id'],
                          initial=True)

        d = api.diagnosis(d)
        text = d.question.text
        print(text)
        if request.POST.get("present1"):
            d.add_symptom(d.question.items[0]['id'],
                          d.question.items[0]['choices'][1]['id'])
            d = api.diagnosis(d)
            text1 = d.question.text
        if request.POST.get("present2"):
            d.add_symptom(d.question.items[0]['id'],
                          d.question.items[0]['choices'][1]['id'])
            d = api.diagnosis(d)
            text2 = d.question.text

        condition = d.conditions[0]['name']
    return render(request, "Hospital/sympton.html", {
        'text': text,
        'text1': text1,
        'text2': text2,
        'condition': condition
    })
コード例 #22
0
 def get_diagnosis(self):
     print("Starting diagnosis/question finding task...")
     while True:
         diagnose_req = infermedica_api.Diagnosis(sex=self.sex,
                                                  age=self.age)
         diagnose_req.set_extras("ignore_groups", True)
         for symptom in self.symptoms:
             diagnose_req.add_symptom(symptom, self.symptoms[symptom][1])
         diagnose_res = self.inf_api.diagnosis(diagnose_req).to_dict()
         #{'text': u'Is your headache severe?', 'extras': {}, 'type': u'single',
         #'items': [{u'choices': [{u'id': u'present', u'label': u'Yes'}, {u'id': u'absent', u'label': u'No'}, {u'id': u'unknown', u'label': u"Don't know"}], u'id': u's_1193', u'name': u'Headache, severe'}]}
         question = diagnose_res.get("question")
         #[{u'common_name': u'Tension-type headaches', u'id': u'c_55', u'probability': 0.0499, u'name': u'Tension-type headaches'}]
         self.condition = diagnose_res.get("conditions")
         if question is not None:
             text = question.get("text")
             # if text in seen_questions:
             #    print("ERROR-- REPEATED QUESTION! EXITING!")
             #    return diagnose_res, None
             # else:
             #    seen_questions.append(text)
             if question.get("type") == "single":
                 self.last_question = {}
                 self.last_question['text'] = question['text']
                 item = question["items"][0]
                 self.last_question['id'] = item['id']
                 self.last_question['name'] = item['name']
             else:
                 #TODO
                 print("ERROR-- question type not single?")
                 self.last_question = None
                 #items = question.get("items")
                 #for item in items:
                 #    question_symptom_id = item.get("id")
                 #    symptoms[question_symptom_id] = 'unknown'
                 #continue
         return diagnose_res
コード例 #23
0
ファイル: Api.py プロジェクト: AndreyBorisKhesin/Wizards
    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
コード例 #24
0
def symptom_question(age):
	global request
	request = infermedica_api.Diagnosis(sex=chosen_gender, age=age)
	request = api.diagnosis(request)
	return question("Please tell me about your symptoms?").reprompt("Could you please tell me your symptoms?")
コード例 #25
0
def init_diagnose(symptom_id, age, gender, sender_id):
    request = infermedica_api.Diagnosis(sex=gender, age=age)
    request.add_symptom(symptom_id, 'present')
    request = api.diagnosis(request)
    return request
コード例 #26
0
import infermedica_api
import random

api = infermedica_api.API(app_id='de9f4fd9', app_key='675302b9ab8bd6ba22f8868968f74033')

request = infermedica_api.Diagnosis(sex='female', age=70)
request.add_symptom('s_285', 'absent') # weight loss
request.add_symptom('s_13', 'absent') # abdominal pain
request.add_symptom('s_156', 'absent') # nausea
request.add_symptom('s_98', 'present') # fever
request.add_symptom('s_21', 'present') # headache
request.add_symptom('s_119', 'absent') # weakness
request.add_symptom('s_88', 'absent') # shortness of breath
request.add_symptom('s_241', 'absent') # skin lesions

request = api.diagnosis(request)

# print(request)

doneDiagnosing = False

while(request.question and doneDiagnosing == False):
	print("---")
	print(request.question.text + " (" + request.question.type + ")")

	donePresent = False

	for i, item in enumerate(request.question.items):
		if (request.question.type == "group_single" or request.question.type == "single"):
			if donePresent == False:
				choiceIndex = 0
コード例 #27
0
    def get_data(self, sex_m, age_m):

        self.user_data = infermedica_api.Diagnosis(sex=sex_m, age=age_m)
コード例 #28
0
 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)
コード例 #29
0
ファイル: app.py プロジェクト: c135792468/WhatsWrong
def diagnosis():
    mydb = mysql.connector.connect(host="localhost",
                                   user="******",
                                   passwd="krisali1",
                                   database="infermedica")

    #mysql cursor object
    mycursor = mydb.cursor()

    #setting the api credentials, in the infermedica object
    api = infermedica_api.API(app_id='ab68b198',
                              app_key='0a0702c5648044b31adc9d388d37841d')

    #android sends json array objects and react sends a regular json
    #thats why there is an if statement checking the objects

    ##use json dumps for android
    #can use the search key for react
    #have to check type because react and android send different objects
    jsonResp = request.get_json()
    if type(jsonResp) is list:
        #in order to read the object, have to convert the json array that was sent to a json obj, then get the data
        #for each key, other wise we will  run into python errors

        #dumps converts the json to a string
        #we can take the first object because we know the android app will only send one object
        jsonString = json.dumps(jsonResp[0])
        #loads converts the string to a pyython json
        jsonObj = json.loads(jsonString)
        #get thhe data from the json
        stringSearch = jsonObj['search']
        stringSex = jsonObj['gender']
        numAge = jsonObj['age']
    else:
        #the json is much simpler from react
        #we can use the search keys directly
        stringSearch = jsonResp['search']
        stringSex = jsonResp['gender']
        numAge = jsonResp['age']

    #setting the sex of the user
    ##there are errors when you send the item in the dictionary so do an if statement for a hardcoded sex value
    if stringSex == 'Male':
        infer_request = infermedica_api.Diagnosis(sex='male', age=numAge)
    elif stringSex == 'Female':
        infer_request = infermedica_api.Diagnosis(sex='female', age=numAge)
    else:
        #there really shouldnt ever be an error with gender because the front end sends hard coded values
        #also the front end checks for null entries as well
        return 'error with gender'

    #iterate through the json, and add each symptom id to the request, also set the symptom as present as apposed to absent
    for jsonSymp in jsonResp:
        infer_request.add_symptom(jsonSymp['SID'], 'present')

    #using the infermedica library, use the diagnosis function to receive the diagnosis
    infer_request = api.diagnosis(infer_request)

    jsonArrData = []
    #have to convert the json received in the api request to a python string
    stringConditions = json.dumps(infer_request.conditions)
    #then convert it to a python json
    jsonConditions = json.loads(stringConditions)

    #each diagnosis we receive  from infermedica is referred to as a medical condition
    #our database has all of the medical conditions available in infermedica
    #when we receive the diagnosis( a json of conditions and their condition ids) we search our
    #database for those id's, and the condition's medical information, then send that information back to the
    #front end

    #if there is no available diagnosis
    if len(jsonConditions) == 0:
        jsonArrData.append({'CID': 'no_results'})
        return jsonify(jsonArrData)

    for jsonTmp in jsonConditions:
        #create the sql select statement using the cid we receive from infermedica as the filter in the where statement
        #category is medical field, severity is medical severity, hint is advice that infermedica suggests,
        #physician is the specialist for the condition
        stringSQL = "SELECT category, severity, hint, physician FROM infermedica.condition_data WHERE CID = '" + jsonTmp[
            'id'] + "'"
        #using try except to catch sql errors
        try:
            mycursor.execute(stringSQL)
            myresult = mycursor.fetchall()

            if len(myresult) == 0:
                #there should never be a case where we have 0 results, because all of the condition ids are in our database
                # but better to be safe

                #do nothing, skip to next item in the list
                #python throws an error if you dont execute a command, so just set a dummy variable
                t = 't'
            else:
                #add the data to our json. convert probability to a string to avoid type errors for the front end and android
                jsonArrData.append({
                    'CID': r['id'],
                    'common_name': r['common_name'],
                    'condition_name': r['name'],
                    'probability': str(r['probability']),
                    'category': myresult[0][0],
                    'severity': myresult[0][1],
                    'hint': myresult[0][2],
                    'physician': myresult[0][3]
                })
        except:
            #move on to the next item
            t = 't'

    #again, there really shouldnt be a case like this, unless something went wrong in ppython or sql, so keep the error checking and let
    # the front end know theres an error
    #otherwise send the json of conditions
    if len(jsonArrData) == 0:
        jsonArrData.append({'CID': 'error_python_error'})
        return jsonify(jsonArrData)
    else:
        return jsonify(jsonArrData)
コード例 #30
0
ファイル: complete.py プロジェクト: skcethackathons/TheDocBoT
import infermedica_api

api = infermedica_api.API(app_id='bfdd6ddf',
                          app_key='ccd593a6b534da1593df17aa3945bfea')

# 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)

request.add_symptom('s_21', 'present')
request.add_symptom('s_98', 'present')
request.add_symptom('s_107', 'absent')

# 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'])