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)]
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)]
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)]
def post(self, request): api = infermedica_api.API(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') # r = infermedica_api.Diagnosis(app_id='945555e1', app_key='be2ee424c225c567086a084637a359de') data = api.conditions_list() # r = requests.post(url, data=json.dumps({'text': text}),headers={'Authorization': apiKey, 'Content-Type': 'application/json'}) return Response({"test": data}, status=status.HTTP_200_OK)
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)]
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)
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 })
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)
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'])
import json import requests import apiai import sqlite3 import string import diagnose import urllib, json from flask import Flask, request import infermedica_api INFERMEDICA_KEY = None API_AI_KEY = None api = infermedica_api.API(app_id='21794b8d', app_key=INFERMEDICA_KEY) print(api.info()) app = Flask(name) symptom_mode = False symptom = None gender = None age = None diagnosis = None @app.route('/', methods=['GET']) def verify(): # when the endpoint is registered as a webhook, it must echo back # the 'hub.challenge' value it receives in the query arguments if request.args.get("hub.mode") == "subscribe" and request.args.get("hub.challenge"):
import json import logging from uuid import uuid4 from flask import Blueprint, jsonify, request, Flask, Response, make_response from flask_cors import CORS from rasa_core.channels.channel import UserMessage from rasa_core.channels.channel import InputChannel, OutputChannel, CollectingOutputChannel from rasa_core.events import SlotSet import actions import infermedica_api import string import requests import urllib api = infermedica_api.API(app_id='bc1dd653', app_key='76b11cd1b2b2e684e261346544731fb7') logger = logging.getLogger() symptom_mode = False symptom = None gender = None age = None diagnosis = None class FileMessageStore: DEFAULT_FILENAME = "message_store.json" def __init__(self, filename=DEFAULT_FILENAME): self._store = defaultdict(list) self._filename = filename
import infermedica_api import json app_id = '{get your key from infermedica}' app_key = "{get your key from infermedica}" #https://infermedica.com api = infermedica_api.API(app_id=app_id, app_key=app_key) symptoms_list = [] conditions_list = [] with open('symptoms.json') as symfile: symptoms_list = json.load(symfile) with open('conditions.json') as condfile: conditions_list = json.load(condfile) 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 def add_symptom_to_request_multichoice(request, id, isPresent): present = "present" if isPresent else "absent" request.add_symptom(id, present)
SECRET_KEY = 'a3knBL401Ajsgk3qr4NB' application = Flask(__name__) application.config.from_object(__name__) # # Create a Twilio client with credentials -- may be useful later for # sending messages without any user input # account_sid = "ACa7f75dbd1aa495c95f84c3178c87c96e" auth_token = "8aec53e337711206ef043bc8c10450ea" client = TwilioRestClient(account_sid, auth_token) #configure the api api = infermedica_api.API(app_id='30d763f7', app_key='91a0b173fc675d415ef8f782a4eff3e8') # This function gets the question we want to ask, depending on the state that we're in. The state and the # q_number are counters stored in the session object, and get reset when we're done with a user # interaction. Every time the function is called, it's passed in the current patient information. def get_question(user_input, state, q_number, a, s, symptoms, prev, conditions): # # If the user wants to restart, they can enter Q and quit. # user_input = user_input.lower() if (user_input == 'q' or user_input == 'Q'): session['state'] = 4 session['q_number'] = 0 session['symptoms'] = [] return "Thanks for using Meditext. Text hello to restart Meditext."
import infermedica_api api = infermedica_api.API(app_id = '059ee519', app_key = '82d0384c0192bf00021a4eda9846503b') import requests sex = input("What is your sex? \n") age = input("What is your age? \n") symptoms = input("What symptoms are you feeling? \n") headers = { 'App-Id': '059ee519', 'App-Key': '82d0384c0192bf00021a4eda9846503b', 'Content-Type': 'application/json', } data = '{"text": \"' +symptoms +'\"}' response = requests.post('https://api.infermedica.com/v2/parse', headers=headers, data=data) response = response.json() #print(response) #print(response['mentions'][0]['id']) id = response['mentions'][0]['id'] choiceid = response['mentions'][0]['choice_id'] headers = { 'App-Id': '059ee519', 'App-Key': '82d0384c0192bf00021a4eda9846503b', 'Content-Type': 'application/json', } data = '{\n "sex": \"'+sex+'\",\n "age":'+age+',\n "evidence": [\n {"id": \"' +id + '\", "choice_id": \"'+choiceid + '\"}\n ]\n }'
import os import sys import json import requests import apiai import sqlite3 import string import diagnose import urllib, json from flask import Flask, request import infermedica_api api = infermedica_api.API(app_id='d50419ca', app_key='9748ab94b22d40926c0255219081c568') print(api.info()) app = Flask(__name__) symptom_mode = False symptom = None gender = None age = None diagnosis = None @app.route('/', methods=['GET']) def verify(): # when the endpoint is registered as a webhook, it must echo back # the 'hub.challenge' value it receives in the query arguments
def testdelete(request, patient_id, testresult_id): patient = get_object_or_404(Patient, pk=patient_id) testresult = TestResults.objects.get(pk=testresult_id) testresult.delete() return render(request, 'patientdetails/patientdetail.html', {'patient': patient}) def Prediction(request): testresult = TestResults.objects.all() diagnosis = Diagnosis.objects.all() import infermedica_api api = infermedica_api.API(app_id='1db218b3', app_key='55dc0c8d721d12fd115024d76e6f5dfb') def inferform(request): form = infer_form() symptoms = symptom.objects.all() return render(request, 'patientdetails/inferform.html', { 'form': form, 'symptoms': 'symptom' }) def symplist(request): symptomslist = api.symptoms_list() for symp in symptomslist: sid = (symp['id'])
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
import os import sys import json import requests import urllib, json import infermedica_api api = infermedica_api.API(app_id='aaccd529', app_key='2507fff3b3104d61bca7f4eb7511dc7b') #print(api.info()) def search_symtom(phrase): return api.search(phrase) def search_symtom_limit(phrase, limit): return api.search(phrase, max_results=limit) def search_symtom_gender(phrase, gender): return api.search(phrase, sex=gender) def search_symtom_gender_limit(phrase, gender, limit): return api.search(phrase, sex=gender, max_results=limit) def search_symtom_filter(phrase, search_filters): return api.search(phrase, filters=search_filters)
import apiai import sqlite3 import string import diagnose import search import user import psql import movie_tickets import urllib, json from flask import Flask, request import infermedica_api ClientAccessToken = '58ff267796024863a39bcc78efe8e0ed' googleApiKey = 'AIzaSyDajx797IQYukLSGkT3VwP02Qa2pyWQlEw' api = infermedica_api.API(app_id='21794b8d', app_key='81f5f69f0cc9d2defaa3c722c0e905bf') #print(api.info()) app = Flask(__name__) myUser = user.MyUser() myMovie = movie_tickets.MyMovie() @app.route('/', methods=['GET']) def verify(): # when the endpoint is registered as a webhook, it must echo back # the 'hub.challenge' value it receives in the query arguments if request.args.get("hub.mode") == "subscribe" and request.args.get( "hub.challenge"): if not request.args.get( "hub.verify_token") == os.environ["VERIFY_TOKEN"]:
import logging from random import randint from flask import Flask, render_template from flask_ask import Ask, statement, question, session import infermedica_api import requests import json api = infermedica_api.API(app_id='b31c571d', app_key='240b0fc2f38307e25a7b5ab82199e961') """ print('Parse simple text:') response = api.parse('i have a huge headache and couoghing today') #print(response) ids = [] length = len(response.mentions) for i in range (0, length): if (response.mentions[i].choice_id == "present"): ids.append(response.mentions[i].id) print ids[0] print len(ids) request = infermedica_api.Diagnosis(sex='male', age=35) for i in range (0,len(ids)): request.add_symptom(ids[i],'present') request = api.diagnosis(request) print "hello" question = request.question.text print type(question.encode('utf-8')) print(request.question.items[0]['choices']) print request.question.items[0]['choices'][0]['label']