gagan3012 commited on
Commit
86a505a
·
verified ·
1 Parent(s): 1ec788c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +281 -0
app.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import plotly.express as px
4
+ from datetime import datetime
5
+ import os
6
+ from openai import OpenAI
7
+ import csv
8
+ from io import StringIO
9
+ import bcrypt
10
+
11
+ # Set up OpenAI API key
12
+ client = OpenAI(api_key=st.secrets["OPENAI_API_KEY"])
13
+
14
+ # Initialize session state
15
+ if 'user' not in st.session_state:
16
+ st.session_state.user = None
17
+ if 'user_type' not in st.session_state:
18
+ st.session_state.user_type = None
19
+
20
+ # File path for CSV database
21
+ CSV_FILE = "migraine_diary.csv"
22
+ USER_FILE = "users.csv"
23
+
24
+ # Function to load data from CSV
25
+ # @st.cache_data
26
+ def load_data():
27
+ if os.path.exists(CSV_FILE):
28
+ return pd.read_csv(CSV_FILE)
29
+ return pd.DataFrame(columns=['user', 'date', 'pain_level', 'duration', 'triggers', 'symptoms', 'medications', 'notes', 'doctor_analysis', 'patient_advice'])
30
+
31
+ # Function to load user data
32
+ # @st.cache_data
33
+ def load_user_data():
34
+ if os.path.exists(USER_FILE):
35
+ return pd.read_csv(USER_FILE)
36
+ return pd.DataFrame(columns=['username', 'password', 'user_type'])
37
+
38
+ # Function to save data to CSV
39
+ def save_data(df):
40
+ df.to_csv(CSV_FILE, index=False)
41
+
42
+ # Function to save user data
43
+ def save_user_data(df):
44
+ df.to_csv(USER_FILE, index=False)
45
+
46
+ # Function to get GPT analysis
47
+ def get_gpt_analysis(entry_text, system_prompt):
48
+ try:
49
+ response = client.chat.completions.create(
50
+ model="gpt-4o-mini",
51
+ messages=[
52
+ {"role": "system", "content": system_prompt},
53
+ {"role": "user", "content": entry_text}
54
+ ]
55
+ )
56
+ return response.choices[0].message.content
57
+ except Exception as e:
58
+ st.error(f"Error in GPT analysis: {str(e)}")
59
+ return "Analysis unavailable at this time."
60
+
61
+ # Password hashing function
62
+ def hash_password(password):
63
+ return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
64
+
65
+ # Password verification function
66
+ def verify_password(stored_password, provided_password):
67
+ return bcrypt.checkpw(provided_password.encode('utf-8'), stored_password.encode('utf-8'))
68
+
69
+ # Login/Register function
70
+ def auth():
71
+ if st.session_state.user is None:
72
+ st.subheader("User Authentication")
73
+ tabs = st.tabs(["Login", "Register"])
74
+
75
+ with tabs[0]:
76
+ st.subheader("Login")
77
+ login_username = st.text_input("Username", key="login_username")
78
+ login_password = st.text_input("Password", type="password", key="login_password")
79
+ login_button = st.button("Login")
80
+
81
+ if login_button:
82
+ user_df = load_user_data()
83
+ user_data = user_df[user_df['username'] == login_username]
84
+ if not user_data.empty and verify_password(user_data.iloc[0]['password'], login_password):
85
+ st.session_state.user = login_username
86
+ st.session_state.user_type = user_data.iloc[0]['user_type']
87
+ st.success("Logged in successfully!")
88
+ st.rerun()
89
+ else:
90
+ st.error("Invalid username or password.")
91
+
92
+ with tabs[1]:
93
+ st.subheader("Register")
94
+ reg_username = st.text_input("Choose a Username", key="reg_username")
95
+ reg_password = st.text_input("Choose a Password", type="password", key="reg_password")
96
+ confirm_password = st.text_input("Confirm Password", type="password", key="confirm_password")
97
+ user_type = st.selectbox("User Type", ["Patient", "Doctor"])
98
+ register_button = st.button("Register")
99
+
100
+ if register_button:
101
+ user_df = load_user_data()
102
+ if reg_username in user_df['username'].values:
103
+ st.error("Username already exists. Please choose a different one.")
104
+ elif reg_password != confirm_password:
105
+ st.error("Passwords do not match.")
106
+ elif len(reg_password) < 1:
107
+ st.error("Password must be at least 8 characters long.")
108
+ else:
109
+ hashed_password = hash_password(reg_password)
110
+ new_user = pd.DataFrame({'username': [reg_username], 'password': [hashed_password], 'user_type': [user_type]})
111
+ user_df = pd.concat([user_df, new_user], ignore_index=True)
112
+ save_user_data(user_df)
113
+ st.session_state.user = reg_username
114
+ st.session_state.user_type = user_type
115
+ st.success("Registered successfully!")
116
+ st.rerun()
117
+ else:
118
+ st.sidebar.write(f"Logged in as {st.session_state.user} ({st.session_state.user_type})")
119
+ if st.sidebar.button("Logout"):
120
+ st.session_state.user = None
121
+ st.session_state.user_type = None
122
+ st.rerun()
123
+
124
+ # Main app
125
+ def main():
126
+ st.set_page_config(page_title="Migraine Diary App", page_icon="🧠", layout="wide")
127
+ st.title("Migraine Diary App")
128
+
129
+ auth()
130
+
131
+ if st.session_state.user:
132
+ if st.session_state.user_type == "Patient":
133
+ patient_interface()
134
+ elif st.session_state.user_type == "Doctor":
135
+ doctor_interface()
136
+
137
+ def patient_interface():
138
+ menu = st.sidebar.selectbox("Menu", ["Add Entry", "View Entries", "Dashboard"])
139
+
140
+ if menu == "Add Entry":
141
+ add_entry()
142
+ elif menu == "View Entries":
143
+ view_entries(is_doctor=False)
144
+ elif menu == "Dashboard":
145
+ display_dashboard(is_doctor=False)
146
+
147
+ def doctor_interface():
148
+ menu = st.sidebar.selectbox("Menu", ["View All Entries", "Patient Dashboard"])
149
+
150
+ if menu == "View All Entries":
151
+ view_entries(is_doctor=True)
152
+ elif menu == "Patient Dashboard":
153
+ display_dashboard(is_doctor=True)
154
+
155
+ def add_entry():
156
+ st.header("Add New Migraine Entry")
157
+ with st.form("migraine_entry"):
158
+ date = st.date_input("Date")
159
+ pain_level = st.slider("Pain Level", 1, 10)
160
+ duration = st.selectbox("Duration", ["Less than 1 hour", "1-4 hours", "4-8 hours", "8-24 hours", "More than 24 hours"])
161
+
162
+ triggers = st.multiselect("Triggers", [
163
+ "Stress", "Lack of Sleep", "Dehydration", "Skipped Meals",
164
+ "Alcohol", "Caffeine", "Chocolate", "Aged Cheeses",
165
+ "Processed Meats", "Artificial Sweeteners", "MSG",
166
+ "Weather Changes", "Barometric Pressure Changes",
167
+ "Bright Lights", "Loud Noises", "Strong Smells",
168
+ "Screen Time", "Reading", "Physical Exertion",
169
+ "Hormonal Changes", "Medication Overuse",
170
+ "Travel", "Altitude Changes", "Other"
171
+ ])
172
+
173
+ symptoms = st.multiselect("Symptoms", [
174
+ "Throbbing Pain", "Pulsating Pain", "One-sided Pain",
175
+ "Nausea", "Vomiting", "Sensitivity to Light",
176
+ "Sensitivity to Sound", "Sensitivity to Smells",
177
+ "Blurred Vision", "Visual Aura", "Blind Spots",
178
+ "Zigzag Lines in Vision", "Tingling or Numbness",
179
+ "Difficulty Speaking", "Weakness", "Dizziness",
180
+ "Vertigo", "Neck Stiffness", "Confusion",
181
+ "Mood Changes", "Food Cravings", "Frequent Urination",
182
+ "Fatigue", "Yawning", "Other"
183
+ ])
184
+
185
+ medications = st.text_input("Medications taken")
186
+ notes = st.text_area("Additional Notes")
187
+
188
+ submitted = st.form_submit_button("Submit Entry")
189
+ if submitted:
190
+ df = load_data()
191
+ entry_text = f"Date: {date}\nPain Level: {pain_level}\nDuration: {duration}\nTriggers: {', '.join(triggers)}\nSymptoms: {', '.join(symptoms)}\nMedications: {medications}\nNotes: {notes}"
192
+
193
+ with st.spinner("Analyzing your entry..."):
194
+ doctor_analysis = get_gpt_analysis(entry_text, "You are a neurologist specializing in migraine management. Provide a technical analysis of the patient's migraine diary entry, including potential correlations, patterns, and suggestions for the treating physician. Keep it short and to the point the doctor is busy.")
195
+ patient_advice = get_gpt_analysis(entry_text, "You are a supportive health coach specializing in migraine management. Provide friendly, easy-to-understand advice for the patient based on their migraine diary entry. Include actionable tips for managing their condition and potential lifestyle adjustments.")
196
+
197
+ new_entry = pd.DataFrame({
198
+ 'user': [st.session_state.user],
199
+ 'date': [date],
200
+ 'pain_level': [pain_level],
201
+ 'duration': [duration],
202
+ 'triggers': [', '.join(triggers)],
203
+ 'symptoms': [', '.join(symptoms)],
204
+ 'medications': [medications],
205
+ 'notes': [notes],
206
+ 'doctor_analysis': [doctor_analysis],
207
+ 'patient_advice': [patient_advice]
208
+ })
209
+ df = pd.concat([df, new_entry], ignore_index=True)
210
+ save_data(df)
211
+ st.success("Entry added successfully!")
212
+ st.subheader("Advice for You:")
213
+ st.write(patient_advice)
214
+
215
+ def view_entries(is_doctor):
216
+ st.header("Migraine Entries")
217
+ df = load_data()
218
+ if is_doctor:
219
+ user_entries = df
220
+ st.subheader("All Patient Entries")
221
+ else:
222
+ user_entries = df[df['user'] == st.session_state.user]
223
+ print(st.session_state.user)
224
+ print(user_entries)
225
+ st.subheader("Your Entries")
226
+
227
+ user_entries = user_entries.sort_values(by='date', ascending=False)
228
+
229
+ if not user_entries.empty:
230
+ for _, entry in user_entries.iterrows():
231
+ with st.expander(f"Entry for {entry['user']} on {entry['date']} - Pain Level: {entry['pain_level']}"):
232
+ st.write(f"Duration: {entry['duration']}")
233
+ st.write(f"Triggers: {entry['triggers']}")
234
+ st.write(f"Symptoms: {entry['symptoms']}")
235
+ st.write(f"Medications: {entry['medications']}")
236
+ st.write(f"Notes: {entry['notes']}")
237
+ if is_doctor:
238
+ st.write("Doctor's Analysis:", entry['doctor_analysis'])
239
+ st.write("Advice for Patient:", entry['patient_advice'])
240
+ else:
241
+ st.info("No entries found.")
242
+
243
+ def display_dashboard(is_doctor):
244
+ st.header("Migraine Dashboard")
245
+ df = load_data()
246
+
247
+ if is_doctor:
248
+ st.subheader("Select Patient")
249
+ selected_user = st.selectbox("Choose a patient", df['user'].unique())
250
+ user_entries = df[df['user'] == selected_user]
251
+ else:
252
+ user_entries = df[df['user'] == st.session_state.user]
253
+
254
+ if not user_entries.empty:
255
+ col1, col2 = st.columns(2)
256
+
257
+ with col1:
258
+ st.subheader("Pain Level Over Time")
259
+ fig = px.line(user_entries, x='date', y='pain_level', title='Pain Level Over Time')
260
+ st.plotly_chart(fig, use_container_width=True)
261
+
262
+ with col2:
263
+ st.subheader("Common Triggers")
264
+ all_triggers = ', '.join(user_entries['triggers'].dropna()).split(', ')
265
+ trigger_counts = pd.Series(all_triggers).value_counts().head(5)
266
+ fig = px.bar(x=trigger_counts.index, y=trigger_counts.values, labels={'x': 'Trigger', 'y': 'Count'})
267
+ st.plotly_chart(fig, use_container_width=True)
268
+
269
+ st.subheader("Migraine Statistics")
270
+ col1, col2, col3 = st.columns(3)
271
+ col1.metric("Total Entries", len(user_entries))
272
+ col2.metric("Average Pain Level", f"{user_entries['pain_level'].mean():.2f}")
273
+ col3.metric("Most Common Trigger", trigger_counts.index[0] if not trigger_counts.empty else "N/A")
274
+
275
+ st.subheader("Recent Entries")
276
+ st.dataframe(user_entries[['date', 'pain_level', 'duration', 'triggers']].sort_values(by='date', ascending=False).head())
277
+ else:
278
+ st.info("No entries found.")
279
+
280
+ if __name__ == "__main__":
281
+ main()