def get_report(request, uid): fhir = FHIR('https://localhost:5001/api/', verify_ssl=False) if request.method == 'GET': try: patient = fhir.get_patient(uid) fbcReqAttributes = ("laboratory", [2, 13, 5, 3, 15, 16, 17, 6]) bpReqAttributes = ("vital-signs", [3, 4, 5]) otherReqAttributes = ("laboratory", [22, 23, 24, 25, 26, 27, 28, 33, 55]) fbcAttributes = getAttributes(uid, fbcReqAttributes[0], fbcReqAttributes[1]) bpAttributes = getAttributes(uid, bpReqAttributes[0], bpReqAttributes[1]) otherAttributes = getAttributes(uid, otherReqAttributes[0], otherReqAttributes[1]) myDict = { 'UID': patient.uuid, 'Name': patient.name.full_name, 'Address': str(patient.addresses[0]), 'Full-Blood Count Attributes': makeDict(fbcAttributes), 'Blood Pressure Values': makeDict(bpAttributes), 'Other blood readings': makeDict(otherAttributes) } response = json.dumps(myDict) return HttpResponse(response, content_type='text/json') except ConnectionError: response = json.dumps([{'Error': 'No patient found'}]) return HttpResponse(response, content_type='text/json')
def getPatient(patientID): fhir = FHIR('https://localhost:5001/api/', verify_ssl=False) try: patient = fhir.get_patient(patientID) except: patient = None return patient
def patient(id): fhir = FHIR() patient = fhir.get_patient(id) observations = fhir.get_patient_observations(id) return render_template('patientinfo.html', observations=observations, patient=patient)
def getaverageage(): fhir = FHIR() patients = fhir.get_all_patients() ages = [] for patient in patients: ages.append(patient.age()) return str(sum(ages) / len(ages))
def observations(id): fhir = FHIR() patient = fhir.get_patient(id) observations = fhir.get_patient_observations(id) spreadSheet = { 'bodyWeight': [], 'BMI': [], 'dBP': [], 'sBP': [], 'pain': [], 'latestObs': { 'uuid': "", 'latestDate': "", 'type': "", 'status': "", 'weight': "", 'sBP': "", 'BMI': "" } } for i in observations: components = i.components for i2 in components: value = i2.value if value == None: continue date = i.effective_datetime dateStr = str(date.day) + "/" + str(date.month) + "/" + str( date.year) display = i2.display if display == "Body Weight": spreadSheet['bodyWeight'].append((dateStr, value)) elif display == "Diastolic Blood Pressure": spreadSheet['dBP'].append((dateStr, value)) elif display == "Systolic Blood Pressure": spreadSheet['sBP'].append((dateStr, value)) elif display == "Body Mass Index": spreadSheet['BMI'].append((dateStr, value)) elif "Pain severity" in display: spreadSheet['pain'].append((dateStr, value)) dictItemsToBeSorted = [ spreadSheet['bodyWeight'], spreadSheet['BMI'], spreadSheet['dBP'], spreadSheet['sBP'], spreadSheet['pain'] ] sortTime(dictItemsToBeSorted) spreadSheet['latestObs']['uuid'] = observations[-1].uuid tmp = observations[-1].effective_datetime spreadSheet['latestObs']['latestDate'] = str(tmp.day) + "/" + str( tmp.month) + "/" + str(tmp.year) spreadSheet['latestObs']['type'] = observations[-1].type spreadSheet['latestObs']['status'] = observations[-1].status spreadSheet['latestObs']['weight'] = spreadSheet['bodyWeight'][-1][-1] spreadSheet['latestObs']['sBP'] = spreadSheet['sBP'][-1][-1] spreadSheet['latestObs']['BMI'] = spreadSheet['BMI'][-1][-1] return render_template("observations.html", obsData=spreadSheet, patient=patient)
def __init__(self, patients_object: Patients): fhir = FHIR() self.patients = patients_object self.patients_uuid_list = self.patients.get_uuid() # List if type(self.patients_uuid_list ) is not list: # type is str when only patient is given self.patients_uuid_list = [self.patients_uuid_list] self.get_patient_observations_by_uuid = lambda x: fhir.get_patient_observations( x)
def __init__(self): self.fhir = FHIR() self.patients = self.fhir.get_all_patients() self.num_examples = len(self.patients) self.num_features = 11 self.patient_record_columns = [ "UUID", "Name", "Gender", "Birthdate", "MaritalStatus", "MultipleBirth", "CoreRace", "CoreEthnicity", "Birthsex", "disabilityAdjLifeYears", "QualAdjLifeYears" ]
def surname(text): fhir = FHIR() patients = fhir.get_all_patients() number_of_patients = 0 for i in patients: number_of_patients = number_of_patients + 1 for index in range(0, number_of_patients): patient = patients[index] if text == patient.name.family: return index return -1
def unique_identifier(text): fhir = FHIR() patients = fhir.get_all_patients() number_of_patients = 0 for i in patients: number_of_patients = number_of_patients + 1 for index in range(0, number_of_patients): patient = patients[index] if text == patient.uuid: return index return -1
def getAttributes(uuid, obType, requiredAttributes): fhir = FHIR('https://localhost:5001/api/', verify_ssl=False) obs = fhir.get_patient_observations(uuid) count = 0 attribList = [] for ob in obs: if ob.type == obType: for i in ob.components: if count in requiredAttributes: attribList.append(str(i)) count += 1 return attribList
def graph_by_states(): fhir = FHIR() patients = fhir.get_all_patients() states = {} for patient in patients: for addressArr in patient.addresses: states.update({addressArr.state: states.get(addressArr.state, 0) + 1}) plt.bar(range(len(states)), list(states.values()), align='center') plt.xticks(range(len(states)), list(states.keys()), rotation='vertical') plt.show()
def __init__(self, page=None, patient_uuid=None): fhir = FHIR() self.uuid_presented = False self.patients = fhir.get_all_patients() if patient_uuid is not None: self.uuid_presented = True self.specific_patient = fhir.get_patient(patient_uuid) if page is not None: try: assert patient_uuid is None self.patients = fhir.get_patient_page(page) except AssertionError: sys.exit( "Error: patients page and patient uuid cannot be initialised at the same time" )
def graph_by_cities(): fhir = FHIR() patients = fhir.get_all_patients() cities = {} for patient in patients: for addressArr in patient.addresses: cities.update({addressArr.city: cities.get(addressArr.city, 0) + 1}) plt.bar(range(len(cities)), list(cities.values()), align='center') plt.xticks(range(len(cities)), list(cities.keys()), rotation='vertical') # fig = plt.figure() # fig.savefig('plot.png') plt.show() # need to think of what can we graph from the observation data # def graph_by_diseases(): # fhir = FHIR() # patients = fhir.get_all_patients() # problems = {} # count = 0 # for patient in patients: # count = count + 1 # if count == 4: # break # print("YOOOO THIS IS THR FKING ID" + patient.uuid) # try: # observations = fhir.get_patient_observations(patient.uuid) # except: # continue # for observation in observations: # print("observation 1") # components = observation.components # for component in components: # print(component.display) # print(component.value) # problems.update({component.display: problems.get(component.display, 0) + 1}) # plt.bar(range(len(problems)), list(problems.values()), align = 'center') # plt.xticks(range(len(problems)),list(problems.keys()), rotation = 'vertical' ) # plt.show(); # def graph_by_diseases(): # def graph_by_certain_age(age):
def graph_languages_spoken(): fhir = FHIR() patients = fhir.get_all_patients() languages = {} for patient in patients: for language in patient.communications.languages: languages.update({language: languages.get(language, 0) + 1}) plt.bar(range(len(languages)), list(languages.values()), align='center') plt.xticks(range(len(languages)), list(languages.keys()), rotation='vertical') fig1 = plt.gcf() plt.draw() number = random.randint(1, 1000) fig1.savefig('plot'+str(number)+'.png', dpi=100) return number
def graph_marital_status(): fhir = FHIR() patients = fhir.get_all_patients() marital_status = {} for patient in patients: if str(patient.marital_status) in marital_status: marital_status[str(patient.marital_status)] += 1 else: marital_status[str(patient.marital_status)] = 1 plt.bar(range(len(marital_status)), list(marital_status.values()), align='center') plt.xticks(range(len(marital_status)), list(marital_status.keys())) fig1 = plt.gcf() plt.draw() number = random.randint(1, 1000) fig1.savefig('plot'+str(number)+'.png', dpi=100) return number
def graph_by_age_groups(): fhir = FHIR() patients = fhir.get_all_patients() ageGroups = {'<10': 0, '10-20': 0, '20-30':0, '30-40':0, '40-50':0, '50-60':0, '60-70': 0, '70-80':0, '80-90':0, '90+':0} for patient in patients: birth = patient.birth_date patientAge = calculate_age(birth) if(patientAge < 10): ageGroups['<10'] += 1 elif( 10 <= patientAge < 20): ageGroups['10-20'] += 1 elif( 20 <=patientAge < 30): ageGroups['20-30'] += 1 elif( 30 <=patientAge < 40): ageGroups['30-40'] += 1 elif( 40 <=patientAge< 50): ageGroups['40-50'] += 1 elif( 50 <=patientAge < 60): ageGroups['50-60'] += 1 elif( 60 <patientAge < 70 ): ageGroups['60-70'] += 1 elif( 70 <patientAge < 80 ): ageGroups['70-80'] += 1 elif( 80 <patientAge < 90 ): ageGroups['80-90'] += 1 elif( 90 <=patientAge ): ageGroups['90+'] += 1 plt.bar(range(len(ageGroups)), list(ageGroups.values()), align='center') plt.xticks(range(len(ageGroups)), list(ageGroups.keys()), rotation='vertical') fig1 = plt.gcf() plt.draw() number = random.randint(1, 1000) fig1.savefig('plot'+str(number)+'.png', dpi=100) return number
def __getSkypePrefixURI(self, patientUUIDs: List[str]): url = "skype:" for index, patientUUID in enumerate(patientUUIDs): if index == 9: break patient = FHIR().get_patient(patientUUID) url += "+1" + str(patient.telecoms[0].number).replace("-", "") url += ";" if (url[-1] == ';'): url = url[:-1] return url
def observationstats(): fhir = FHIR() patients = fhir.get_all_patients() observations = [] for patient in patients: observations.extend(fhir.get_patient_observations(patient.uuid)) total_obsv = len(observations) observation_types = [observation.type for observation in observations] most_frequent_observation_type = max(set(observation_types), key=observation_types.count) observation_components = [] for observation in observations: observation_components.extend(observation.components) total_obsv_components = len(observation_components) observation_component_types = [ observation_component.display for observation_component in observation_components ] most_frequent_observation_component_type = max(set(observation_types), key=observation_types.count) obsvstats_dictionary = { "totalObsv": total_obsv, "mfObservationType": most_frequent_observation_type, "totalObsvComp": total_obsv_components, "mfObsvCompType": most_frequent_observation_component_type } response = jsonify(obsvstats_dictionary) return response
class Main: def __init__(self): self.fhir = FHIR('https://localhost:5001/api/', verify_ssl=False) self.patients = self.fhir.get_all_patients() def print_patients_in_range(self, limit, lower, upper, sender_name, sender_ref, app_url): i = 0 patients_list = [] for patient in self.patients: dict = {} if not i < limit: # print(patients_list) return patients_list id = patient.uuid name = patient.full_name() age = patient.age() if age >= lower and age < upper: telecoms = patient.telecoms phone = telecoms[len(telecoms) - 1].number # print(phone) msg = "Hi " + name + ",\n" + "Are you a carer? If so, we've built an app just for you! You can download our app for carers here: " + app_url + "\nUse this reference code to set up your app: " + sender_ref + "\nTake Care,\n" + sender_name # print(msg) # print(id) # print(name) # print(age) # print() dict["phone"] = phone dict["msg"] = msg patients_list.append(dict) i += 1 # main = Main() # list = main.print_patients_in_range(3, 55, 65, "Paul", "UCL-FHIR-Hack", "appdownload.com") # patient = fhir.get_patient('8f789d0b-3145-4cf2-8504-13159edaa747') # name = patient.full_name() # print(patient) # list = fhir.get_all_patients()
from fhir_parser import FHIR import matplotlib.pyplot as plt import pandas as pd fhir = FHIR(endpoint='https://fhir.compositegrid.com:5001/api/') patients = fhir.get_all_patients() genders = [] ages = [] for patient in patients: if patient.gender == 'male': genders.append(0) else: genders.append(1) ages.append(patient.age()) data = {'sex': genders, 'age': ages} df = pd.DataFrame(data) df.groupby('sex')['age'].plot(title='Age Distribution By Gender', kind='kde') plt.show()
def index(): fhir = FHIR() patients = fhir.get_all_patients() return render_template('patients.html', patients=patients)
def getstatistics(id): fhir = FHIR() patient = fhir.get_patient(id) observations = fhir.get_patient_observations(id) bp_dict = {"date": [], "dbp": [], "sbp": []} hr_dict = {"date": [], "hr": []} rr_dict = {"date": [], "rr": []} bw_dict = {"date": [], "bw": []} bh_dict = {"date": [], "bh": []} bmi_dict = {"date": [], "bmi": []} bmip_dict = {"date": [], "bmip": []} ps_dict = {"date": [], "ps": []} temp_bp_dates = [] bp_observations = [] temp_hr_dates = [] hr_observations = [] temp_rr_dates = [] rr_observations = [] temp_bw_dates = [] bw_observations = [] temp_bh_dates = [] bh_observations = [] temp_bmi_dates = [] bmi_observations = [] temp_bmip_dates = [] bmip_observations = [] temp_ps_dates = [] ps_observations = [] for observation in observations: if observation.components[0].display == "Blood Pressure": bp_observations.append(observation) temp_bp_dates.append(observation.effective_datetime) if observation.components[0].display == "Heart rate": hr_observations.append(observation) temp_hr_dates.append(observation.effective_datetime) if observation.components[0].display == "Respiratory rate": rr_observations.append(observation) temp_rr_dates.append(observation.effective_datetime) if observation.components[0].display == "Body Weight": bw_observations.append(observation) temp_bw_dates.append(observation.effective_datetime) if observation.components[0].display == "Body Height": bh_observations.append(observation) temp_bh_dates.append(observation.effective_datetime) if observation.components[0].display == "Body Mass Index": bmi_observations.append(observation) temp_bmi_dates.append(observation.effective_datetime) if observation.components[ 0].display == "Body mass index (BMI) [Percentile] Per age and gender": bmip_observations.append(observation) temp_bmip_dates.append(observation.effective_datetime) if observation.components[ 0].display == "Pain severity - 0-10 verbal numeric rating [Score] - Reported": ps_observations.append(observation) temp_ps_dates.append(observation.effective_datetime) temp_hr_dates.sort() temp_bp_dates.sort() temp_rr_dates.sort() temp_bw_dates.sort() temp_bh_dates.sort() temp_bmi_dates.sort() temp_bmip_dates.sort() temp_ps_dates.sort() for i in range(0, len(temp_bp_dates)): for observation in bp_observations: if temp_bp_dates[i] == observation.effective_datetime: bp_dict["date"].append( int(time.mktime(temp_bp_dates[i].timetuple())) * 1000) bp_dict["dbp"].append(observation.components[1].value) bp_dict["sbp"].append(observation.components[2].value) break for i in range(0, len(temp_hr_dates)): for observation in hr_observations: if temp_hr_dates[i] == observation.effective_datetime: hr_dict["date"].append( int(time.mktime(temp_hr_dates[i].timetuple())) * 1000) hr_dict["hr"].append(observation.components[0].value) break for i in range(0, len(temp_rr_dates)): for observation in rr_observations: if temp_rr_dates[i] == observation.effective_datetime: rr_dict["date"].append( int(time.mktime(temp_rr_dates[i].timetuple())) * 1000) rr_dict["rr"].append(observation.components[0].value) break for i in range(0, len(temp_bw_dates)): for observation in bw_observations: if temp_bw_dates[i] == observation.effective_datetime: bw_dict["date"].append( int(time.mktime(temp_bw_dates[i].timetuple())) * 1000) bw_dict["bw"].append(observation.components[0].value) break for i in range(0, len(temp_bh_dates)): for observation in bh_observations: if temp_bh_dates[i] == observation.effective_datetime: bh_dict["date"].append( int(time.mktime(temp_bh_dates[i].timetuple())) * 1000) bh_dict["bh"].append(observation.components[0].value) break for i in range(0, len(temp_bmi_dates)): for observation in bmi_observations: if temp_bmi_dates[i] == observation.effective_datetime: bmi_dict["date"].append( int(time.mktime(temp_bmi_dates[i].timetuple())) * 1000) bmi_dict["bmi"].append(observation.components[0].value) break for i in range(0, len(temp_bmip_dates)): for observation in bmip_observations: if temp_bmip_dates[i] == observation.effective_datetime: bmip_dict["date"].append( int(time.mktime(temp_bmip_dates[i].timetuple())) * 1000) bmip_dict["bmip"].append(observation.components[0].value) break for i in range(0, len(temp_ps_dates)): for observation in ps_observations: if temp_ps_dates[i] == observation.effective_datetime: ps_dict["date"].append( int(time.mktime(temp_ps_dates[i].timetuple())) * 1000) ps_dict["ps"].append(observation.components[0].value) break return render_template('statistics.html', patient=patient, bp_dict=bp_dict, hr_dict=hr_dict, rr_dict=rr_dict, bw_dict=bw_dict, bh_dict=bh_dict, bmi_dict=bmi_dict, bmip_dict=bmip_dict, ps_dict=ps_dict)
from fhir_parser import FHIR import pdfkit fhir = FHIR() def showOptions(): print("Please select what you want to do:\n") print("1. Generate documents\n") print("2. Return to last page\n") def getPatient(patient_id): return fhir.get_patient(patient_id) def getObservation(patient_id): return fhir.get_patient_observations(patient_id) def patientDocument(): result = "Patient Name: " + patient.full_name() + "<br>" result += "<br>" result += "Id: " + patient.uuid + "<br>" result += "<br>" result += "Age: " + str(patient.age()) + "<br>" result += "<br>" result += "Gender: " + patient.gender + "<br>" result += "<br>" result += "Addresses: <br>" for x in patient.addresses:
class Model: fhir = FHIR() patients = fhir.get_all_patients() patient_lists = [] def __init__(self): self.patient_lists = self.get_all_patient_lists() def get_all_patient_lists(self): files = glob.glob("saved_lists/*") l = [] for file in files: file = file.replace("saved_lists/", "") file = file.replace(".pickle", "") file = file.replace("_", " ") l.append(file) return l # # def get_patient_details_from_name(self, firstname, surname): # patients_with_name = [] # self.patients = self.fhir.get_all_patients() # for patient in self.patients: # if patient.name.given.lower() == firstname.lower() and patient.name.given.lower() == surname.lower(): # patients_with_name.append(patient) # # return patients_with_name # def update_complete(self, filename, uuid): patient_list = self.fetch_patient_list(filename) i = 0 for i, patient in enumerate(patient_list): if patient[0].uuid == uuid: break if patient_list[i][1]: patient_list[i][1] = False else: patient_list[i][1] = True self.delete_patient_list(filename) self.save_patient_list(patient_list, filename) def save_patient_list(self, list, filename): files = glob.glob("saved_lists/*") for file in files: if os.path.join("saved_lists", filename + "." + "pickle") == file: return False with open("saved_lists/" + filename + ".pickle", 'wb') as handle: pickle.dump(list, handle, protocol=pickle.HIGHEST_PROTOCOL) return True def fetch_patient_list(self, filename): path = os.path.join("saved_lists", filename + "." + "pickle") return self.get_pickle(path) def get_pickle(self, path): try: with open(path, 'rb') as handle: p = pickle.load(handle) return p except FileNotFoundError: return [] def delete_patient_list(self, filename): try: os.remove(os.path.join("saved_lists", filename + "." + "pickle")) except FileNotFoundError: return False return True def get_patient_details_from_query(self, query): patients = [] # todo fix this shitty code for patient in self.patients: patient_dict = self.generate_patient_dict(patient) passed = True for key in query: info = str(query[key][0]) contains_or_exact = query[key][1].lower() p_dict = str(patient_dict[key]) try: if contains_or_exact == "contains": if info not in p_dict: passed = False break if contains_or_exact == "exact": if not p_dict == info: passed = False break if contains_or_exact == "less": if not int(p_dict) < int(info): passed = False break if contains_or_exact == "greater": if not int(p_dict) > int(info): passed = False break except TypeError: passed = False break if passed: patients.append([patient, False]) return patients def generate_patient_dict(self, p): today = datetime.date.today() return { 'uuid': p.uuid, 'first_name': ''.join([i for i in p.name.given if not i.isdigit()]), 'last_name': ''.join([i for i in p.name.family if not i.isdigit()]), 'gender': p.gender, 'birth_year': p.birth_date.year, 'birth_month': p.birth_date.month, 'birth_day': p.birth_date.day, 'age': today.year - p.birth_date.year - ((today.month, today.day) < (p.birth_date.month, p.birth_date.day)), 'house': p.addresses[0].lines[0], 'city': p.addresses[0].city, 'state': p.addresses[0].state, 'postal_code': p.addresses[0].postal_code, 'country': p.addresses[0].country, 'marital_status': p.marital_status.marital_status, 'language': p.communications.languages[0] }
def save_doc(text, dropdown): # Full list of patients fhir = FHIR() patients = fhir.get_all_patients() document = Document() new_line = " " # Find number of patients number_of_patients = 0 for i in patients: number_of_patients = number_of_patients + 1 # Index of Patient if dropdown == "Forename": result = forename(text) elif dropdown == "Surname": result = surname(text) else: result = unique_identifier(text) patient = patients[result] # Address of Patient address = patient.addresses[0] communications = patient.communications # Date Today today = date.today() # Marital Status marital_status_patient = patient.marital_status.marital_status # Age age = today.year - patient.birth_date.year - ( (today.month, today.day) < (patient.birth_date.month, patient.birth_date.day)) # Records of patients patient_data = {"Unique Identifier": patient.uuid.upper(), "Surname": patient.name.family, "Forename": patient.name.given, "Gender": patient.gender.capitalize(), "Birthday": str(patient.birth_date.day) + "." + str(patient.birth_date.month) + "." \ + str(patient.birth_date.year), "Age": str(age), "Marital Status": str(marital_status_patient), "Address": address.full_address, "Languages Spoken": communications.languages} # Records of a patient observations = fhir.get_patient_observations( patient_data["Unique Identifier"].lower()) # Number of observations for 1 Patient count = 0 for i in observations: count = count + 1 # NHS Image LOGO = "1280px-NHS-Logo.svg.png" logo = document.add_picture(LOGO, width=Inches(1.50)) document.add_heading(patient.name.full_name, 1) document.add_heading(new_line, 1) # Adding general information about a patient in a word document for data in patient_data: p = document.add_paragraph() p.add_run(data + ": ").bold = True p.add_run(patient_data[data]) document.add_heading(new_line, 1) # Creating a table table = document.add_table(rows=1, cols=8) hdr_cells = table.rows[0].cells hdr_cells[0].text = 'Observation(s) ' hdr_cells[1].text = 'Number' hdr_cells[2].text = 'Type' hdr_cells[3].text = 'Status ' hdr_cells[5].text = 'Issued Date' hdr_cells[6].text = 'Code' hdr_cells[7].text = 'Result' # Adding data into the table for i in range(0, count): row_cells = table.add_row().cells row_cells[0].text = str(i + 1) row_cells[1].text = observations[i].uuid.upper() row_cells[2].text = observations[i].type.capitalize() row_cells[3].text = observations[i].status.capitalize() row_cells[5].text = str(observations[i].issued_datetime) for component in observations[i].components: row_cells[6].text = component.code row_cells[7].text = component.display + ": " + component.quantity() # Save the document document.save( str(patient.name.given[0]) + "." + str(patient.name.family) + "." + str(age) + '.docx')
def setVariables(searchField, searchCriteria): searchF = searchField searchC = searchCriteria fhir = FHIR() global patients patients = fhir.get_all_patients()
from fhir_parser import FHIR from docxtpl import DocxTemplate from fhir_patient_summary.renderTemplate import * from fhir_patient_summary.createObservationDictionary import * from fhir_patient_summary.convertDocxToPDF import convertDocxToPDF import shutil import tempfile fhir = FHIR() def createPatientSummaryDocumentFromPatientIDList(patientIDList, format: str, destinationDir: str, zipFile=False): if zipFile is True: with tempfile.TemporaryDirectory() as dirpath: createDocuments(patientIDList, format, dirpath) shutil.make_archive(destinationDir + "/patientSummaryDocuments", 'zip', dirpath) return destinationDir + "/patientSummaryDocuments.zip" else: createDocuments(patientIDList, format, destinationDir) return destinationDir def createDocuments(patientIDList, format: str, destinationDir: str): for counter, patientID in enumerate(patientIDList): if counter > 100: # limit number of patients to 100 break createPatientSummaryDocument(patientID, format, destinationDir)
from flask import Flask, render_template, url_for, redirect, request from fhir_parser import FHIR, Patient, Observation from forms import IdentifyForm, HeartRateForm, ChooseForm, BloodPressureForm from access import Connect from datetime import datetime import requests app = Flask(__name__) app.config["SECRET_KEY"] = "password" fhir = FHIR("https://*****:*****@app.route("/", methods=["GET", "POST"]) def home(): patient = None form = IdentifyForm() if form.validate_on_submit(): patient_name = search_patient(form.patientID.data) return redirect(url_for("usr_page", name=patient_name)) else: return render_template("home.html", title="form", form=form) @app.route("/patient/<name>", methods=["POST", "GET"]) def usr_page(name):
import matplotlib.pyplot as plt from fhir_parser import FHIR import math fhir = FHIR() patients = fhir.get_all_patients() def getLanguageData(): languages = {} for patient in patients: for language in patient.communications.languages: languages.update({language: languages.get(language, 0) + 1}) print(languages) return languages def getMaritalStatus(): maritalStatus = {} for patient in patients: maritalStatus.update({ str(patient.marital_status): maritalStatus.get(str(patient.marital_status), 0) + 1 }) return maritalStatus def getAge(): ages = {} for patient in patients: # print(math.floor(patient.age()))
'patient_prefix': patient_info[4], 'patient_surname': patient_info[5], 'doctors_phone_number': doctor_info[0], 'doctors_address1': doctor_info[1], 'doctors_address2': doctor_info[2], 'dr_name': doctor_info[3], 'day': appointment_info[0], 'month': appointment_info[1], 'year': appointment_info[2], 'time': appointment_info[3], 'clinic_type': appointment_info[4], 'signature': signature } save_path = "generated/" + patient_info[6] + patient_info[5] + ".docx" tpl.render(context) tpl.save(save_path) if __name__ == "__main__": doctorJB = Dr.Doctor("Backwell", "Gastroenterology", ["123 Street", "W1 456"], "0123456789", "Guy's Hospital") appointment1 = appt.Appointment("1st", "January", "2020", "12:00", "Gastro Clinic", "8f789d0b-3145-4cf2-8504-13159edaa747") fhir = FHIR('https://localhost:5001/api/', verify_ssl=False) patients = fhir.get_patient_page(5) for patient in patients: generateApptLetterDocX(patient.uuid, doctorJB, appointment1, "templates/doctorAppointment.docx")