netflypsb commited on
Commit
fc1a58d
1 Parent(s): 7f1ed25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -145
app.py CHANGED
@@ -1,154 +1,150 @@
1
  import streamlit as st
2
  import pandas as pd
3
- import datetime as dt
4
- import matplotlib.pyplot as plt
5
- import os
6
 
7
- # Function to load data from the local CSV file
8
  def load_data():
9
- df = pd.read_csv('patient_data.csv')
10
- df['Date of Birth'] = pd.to_datetime(df['Date of Birth'], format='%Y-%m-%d', errors='coerce')
11
- df['Visit Date'] = pd.to_datetime(df['Visit Date'], errors='coerce')
12
- df['Age'] = df['Date of Birth'].apply(lambda dob: (dt.datetime.now() - dob).days // 365)
13
- return df
14
 
15
- # Function to save data to the local CSV file
16
  def save_data(df):
17
- df.to_csv('patient_data.csv', index=False)
18
- st.write("Data saved successfully.")
19
 
20
- # Load data from the CSV file
21
  df = load_data()
22
 
23
- # Sidebar: Select or create patient
24
- action = st.sidebar.selectbox("Action", ["Select Patient", "Create New Patient"])
25
-
26
- if action == "Select Patient":
27
- patient_id = st.sidebar.selectbox("Patient ID", df['Patient ID'].unique())
28
-
29
- # Display patient data
30
- patient_data = df[df['Patient ID'] == patient_id]
31
- if not patient_data.empty:
32
- st.header("General Information")
33
- st.write(f"**Patient ID:** {patient_id}")
34
- st.write(f"**Name:** {patient_data.iloc[0]['Patient Name']}")
35
- st.write(f"**Date of Birth:** {patient_data.iloc[0]['Date of Birth'].strftime('%Y-%m-%d')}")
36
- st.write(f"**Age:** {patient_data.iloc[0]['Age']}")
37
- st.write(f"**Gender:** {patient_data.iloc[0]['Gender']}")
38
- st.write(f"**Medical History:** {patient_data.iloc[0]['Medical History']}")
39
- st.write(f"**Allergies:** {patient_data.iloc[0]['Allergies']}")
40
-
41
- # Graphs of medical data
42
- st.header("Medical Data Over Time")
43
- fig, ax = plt.subplots(2, 2, figsize=(12, 8))
44
- ax[0, 0].plot(patient_data['Visit Date'], patient_data['Systolic BP'])
45
- ax[0, 0].set_title("Systolic Blood Pressure")
46
- ax[0, 1].plot(patient_data['Visit Date'], patient_data['Glucose'])
47
- ax[0, 1].set_title("Glucose")
48
- ax[1, 0].plot(patient_data['Visit Date'], patient_data['Cholesterol'])
49
- ax[1, 0].set_title("Cholesterol")
50
- ax[1, 1].plot(patient_data['Visit Date'], patient_data['Hemoglobin'])
51
- ax[1, 1].set_title("Hemoglobin")
52
- st.pyplot(fig)
53
-
54
- # Current visit input
55
- st.header("Current Visit")
56
- with st.form("current_visit_form"):
57
- new_visit_date = st.date_input("Visit Date", dt.date.today())
58
- complaint = st.text_area("Complaint")
59
- physical_exam = st.text_area("Physical Examination")
60
- systolic_bp = st.number_input("Systolic Blood Pressure", min_value=0)
61
- diastolic_bp = st.number_input("Diastolic Blood Pressure", min_value=0)
62
- temperature = st.number_input("Temperature", min_value=0.0, format="%.1f")
63
- glucose = st.number_input("Glucose", min_value=0)
64
- cholesterol = st.number_input("Cholesterol", min_value=0)
65
- hemoglobin = st.number_input("Hemoglobin", min_value=0)
66
- other_notes = st.text_area("Other Notes")
67
- submitted = st.form_submit_button("Add Entry")
68
- if submitted:
69
- new_entry = {
70
- "Patient ID": patient_id,
71
- "Patient Name": patient_data.iloc[0]['Patient Name'],
72
- "Date of Birth": patient_data.iloc[0]['Date of Birth'],
73
- "Age": patient_data.iloc[0]['Age'],
74
- "Gender": patient_data.iloc[0]['Gender'],
75
- "Medical History": patient_data.iloc[0]['Medical History'],
76
- "Allergies": patient_data.iloc[0]['Allergies'],
77
- "Visit Date": pd.to_datetime(new_visit_date).strftime('%Y-%m-%d'),
78
- "Complaint": complaint,
79
- "Physical Examination": physical_exam,
80
- "Systolic BP": systolic_bp,
81
- "Diastolic BP": diastolic_bp,
82
- "Temperature": temperature,
83
- "Glucose": glucose,
84
- "Cholesterol": cholesterol,
85
- "Hemoglobin": hemoglobin,
86
- "Other Notes": other_notes,
87
- }
88
- df = pd.concat([df, pd.DataFrame([new_entry])], ignore_index=True)
89
- st.write("New entry added to DataFrame.")
90
-
91
- # Save the updated data to CSV
92
- save_data(df)
93
- st.success("New visit entry added successfully!")
94
-
95
- # Reload data
96
- df = load_data()
97
- patient_data = df[df['Patient ID'] == patient_id]
98
-
99
- # Dropdown menu of previous visits
100
- st.header("Previous Visits")
101
- visit_date = st.selectbox("Select Visit Date", patient_data['Visit Date'].dt.strftime('%Y-%m-%d').unique())
102
- visit_data = patient_data[patient_data['Visit Date'] == pd.to_datetime(visit_date)]
103
- if not visit_data.empty:
104
- st.write(f"**Complaint:** {visit_data.iloc[0]['Complaint']}")
105
- st.write(f"**Physical Examination:** {visit_data.iloc[0]['Physical Examination']}")
106
- st.write(f"**Systolic BP:** {visit_data.iloc[0]['Systolic BP']}")
107
- st.write(f"**Diastolic BP:** {visit_data.iloc[0]['Diastolic BP']}")
108
- st.write(f"**Temperature:** {visit_data.iloc[0]['Temperature']}")
109
- st.write(f"**Glucose:** {visit_data.iloc[0]['Glucose']}")
110
- st.write(f"**Cholesterol:** {visit_data.iloc[0]['Cholesterol']}")
111
- st.write(f"**Hemoglobin:** {visit_data.iloc[0]['Hemoglobin']}")
112
- st.write(f"**Other Notes:** {visit_data.iloc[0]['Other Notes']}")
113
- else:
114
- st.write("No visit data available for the selected date.")
115
- else:
116
- st.write("No patient data available.")
117
-
118
- elif action == "Create New Patient":
119
- st.header("Create New Patient Account")
120
- with st.form("new_patient_form"):
121
- new_patient_id = st.text_input("Patient ID")
122
- new_patient_name = st.text_input("Patient Name")
123
- new_dob = st.date_input("Date of Birth")
124
- new_age = (dt.datetime.now() - pd.to_datetime(new_dob)).days // 365
125
- new_gender = st.selectbox("Gender", ["Male", "Female", "Other"])
126
- new_med_history = st.text_area("Medical History")
127
- new_allergies = st.text_area("Allergies")
128
- new_submitted = st.form_submit_button("Add New Patient")
129
- if new_submitted:
130
- new_patient = {
131
- "Patient ID": new_patient_id,
132
- "Patient Name": new_patient_name,
133
- "Date of Birth": pd.to_datetime(new_dob).strftime('%Y-%m-%d'),
134
- "Age": new_age,
135
- "Gender": new_gender,
136
- "Medical History": new_med_history,
137
- "Allergies": new_allergies,
138
- "Visit Date": None,
139
- "Complaint": None,
140
- "Physical Examination": None,
141
- "Systolic BP": None,
142
- "Diastolic BP": None,
143
- "Temperature": None,
144
- "Glucose": None,
145
- "Cholesterol": None,
146
- "Hemoglobin": None,
147
- "Other Notes": None,
148
- }
149
- df = pd.concat([df, pd.DataFrame([new_patient])], ignore_index=True)
150
- st.write("New patient added to DataFrame.")
151
-
152
- # Save the updated data to CSV
153
- save_data(df)
154
- st.success("New patient account created successfully!")
 
1
  import streamlit as st
2
  import pandas as pd
3
+ import json
4
+ from datetime import datetime
 
5
 
6
+ # Function to load patient data from JSON
7
  def load_data():
8
+ with open('data.json', 'r') as f:
9
+ return pd.DataFrame(json.load(f))
 
 
 
10
 
11
+ # Function to save patient data to JSON
12
  def save_data(df):
13
+ with open('data.json', 'w') as f:
14
+ json.dump(df.to_dict(orient='records'), f, indent=4)
15
 
16
+ # Load the existing data
17
  df = load_data()
18
 
19
+ # Sidebar for navigation
20
+ st.sidebar.title("Navigation")
21
+ options = ["View Patient Data", "Add New Patient", "Add New Visit"]
22
+ choice = st.sidebar.selectbox("Choose an option", options)
23
+
24
+ if choice == "View Patient Data":
25
+ # Sidebar for Patient Selection
26
+ st.sidebar.header('Select Patient')
27
+ patient_id = st.sidebar.selectbox('Patient ID', df['patient_id'].unique())
28
+
29
+ # Filter Data for Selected Patient
30
+ patient_data = df[df['patient_id'] == patient_id]
31
+
32
+ # Display Patient Profile
33
+ st.header('Patient Profile')
34
+ st.write(f"Name: {patient_data['name'].values[0]}")
35
+ st.write(f"Age: {patient_data['age'].values[0]}")
36
+ st.write(f"Gender: {patient_data['gender'].values[0]}")
37
+ st.write(f"Medical History: {patient_data['medical_history'].values[0]}")
38
+
39
+ # Visualization of Vital Signs
40
+ st.header('Vital Signs Over Time')
41
+
42
+ # Line Chart for Heart Rate
43
+ fig = px.line(patient_data, x='date', y='heart_rate', title='Heart Rate Over Time')
44
+ st.plotly_chart(fig)
45
+
46
+ # Line Chart for Blood Pressure
47
+ fig = px.line(patient_data, x='date', y='blood_pressure', title='Blood Pressure Over Time')
48
+ st.plotly_chart(fig)
49
+
50
+ # Line Chart for Blood Glucose
51
+ fig = px.line(patient_data, x='date', y='blood_glucose', title='Blood Glucose Over Time')
52
+ st.plotly_chart(fig)
53
+
54
+ # Dropdown for selecting specific visit details
55
+ st.header('Previous Visit Details')
56
+ selected_date = st.selectbox('Select Visit Date', patient_data['date'].unique())
57
+ selected_visit = patient_data[patient_data['date'] == selected_date]
58
+
59
+ st.write(f"**Visit Date:** {selected_date}")
60
+ st.write(f"Heart Rate: {selected_visit['heart_rate'].values[0]}")
61
+ st.write(f"Blood Pressure: {selected_visit['blood_pressure'].values[0]}")
62
+ st.write(f"Blood Glucose: {selected_visit['blood_glucose'].values[0]}")
63
+
64
+ # Alerts and Notifications
65
+ st.header('Alerts')
66
+ if selected_visit['heart_rate'].values[0] > 100:
67
+ st.error('High heart rate detected!')
68
+ if selected_visit['blood_pressure'].values[0] > 140:
69
+ st.error('High blood pressure detected!')
70
+
71
+ # Download Button for Patient Data
72
+ st.download_button(
73
+ label="Download Patient Data as CSV",
74
+ data=patient_data.to_csv().encode('utf-8'),
75
+ file_name=f'patient_{patient_id}_data.csv',
76
+ mime='text/csv',
77
+ )
78
+
79
+ elif choice == "Add New Patient":
80
+ st.header("Add New Patient")
81
+
82
+ # Input fields for new patient data
83
+ new_patient_id = st.number_input("Patient ID", min_value=0, step=1)
84
+ new_name = st.text_input("Name")
85
+ new_age = st.number_input("Age", min_value=0, step=1)
86
+ new_gender = st.selectbox("Gender", ["Male", "Female"])
87
+ new_medical_history = st.text_area("Medical History")
88
+
89
+ if st.button("Add Patient"):
90
+ new_patient_data = {
91
+ 'patient_id': new_patient_id,
92
+ 'name': new_name,
93
+ 'age': new_age,
94
+ 'gender': new_gender,
95
+ 'medical_history': new_medical_history,
96
+ 'date': None,
97
+ 'heart_rate': None,
98
+ 'blood_pressure': None,
99
+ 'blood_glucose': None,
100
+ 'temperature': None,
101
+ 'medical_complaints': None,
102
+ 'symptoms': None,
103
+ 'physical_examination': None,
104
+ 'diagnosis': None,
105
+ 'extra_notes': None,
106
+ 'treatment': None
107
+ }
108
+ df = pd.concat([df, pd.DataFrame([new_patient_data])], ignore_index=True)
109
+ save_data(df)
110
+ st.success("New patient added successfully!")
111
+
112
+ elif choice == "Add New Visit":
113
+ st.header("Add New Visit")
114
+
115
+ # Input fields for adding a new visit
116
+ patient_id = st.number_input("Patient ID", min_value=0, step=1)
117
+ visit_date = st.date_input("Date of Visit", value=datetime.today())
118
+ medical_complaints = st.text_area("Medical Complaints")
119
+ symptoms = st.text_area("Symptoms")
120
+ physical_examination = st.text_area("Physical Examination")
121
+ diagnosis = st.text_area("Diagnosis")
122
+ heart_rate = st.number_input("Heart Rate", min_value=0)
123
+ blood_pressure = st.number_input("Blood Pressure", min_value=0)
124
+ temperature = st.number_input("Temperature", min_value=0)
125
+ glucose = st.number_input("Blood Glucose", min_value=0)
126
+ extra_notes = st.text_area("Extra Notes")
127
+ treatment = st.text_area("Treatment")
128
+
129
+ if st.button("Add Visit"):
130
+ new_visit_data = {
131
+ 'patient_id': patient_id,
132
+ 'name': df[df['patient_id'] == patient_id]['name'].values[0],
133
+ 'age': df[df['patient_id'] == patient_id]['age'].values[0],
134
+ 'gender': df[df['patient_id'] == patient_id]['gender'].values[0],
135
+ 'medical_history': df[df['patient_id'] == patient_id]['medical_history'].values[0],
136
+ 'date': visit_date.strftime('%Y-%m-%d'),
137
+ 'heart_rate': heart_rate,
138
+ 'blood_pressure': blood_pressure,
139
+ 'blood_glucose': glucose,
140
+ 'temperature': temperature,
141
+ 'medical_complaints': medical_complaints,
142
+ 'symptoms': symptoms,
143
+ 'physical_examination': physical_examination,
144
+ 'diagnosis': diagnosis,
145
+ 'extra_notes': extra_notes,
146
+ 'treatment': treatment
147
+ }
148
+ df = pd.concat([df, pd.DataFrame([new_visit_data])], ignore_index=True)
149
+ save_data(df)
150
+ st.success("New visit added successfully!")