sonjil commited on
Commit
354ff98
·
verified ·
1 Parent(s): 58996dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +302 -0
app.py CHANGED
@@ -0,0 +1,302 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import groq
3
+ from dotenv import load_dotenv
4
+ import os
5
+
6
+ load_dotenv()
7
+
8
+ # Initialize the Groq client
9
+ client = groq.Groq()
10
+
11
+ GROQ_API_KEY = os.getenv("GROQ_API_KEY")
12
+
13
+ # Available models
14
+ MODELS = [
15
+ "mixtral-8x7b-32768",
16
+ "gemma2-9b-it",
17
+ "llama-3.2-1b-preview",
18
+
19
+ ]
20
+
21
+ # Default system prompt
22
+ DEFAULT_SYSTEM_PROMPT = """You are an expert physiotherapist dedicated to helping users improve their well-being.
23
+ Using the user's provided data,
24
+ Send a brief, 2-line message to [patient name], personalized message that checks in on their condition or asks
25
+ how they’ve been feeling lately, even though they haven’t taken a plan yet.
26
+ The message should be warm, empathetic, and tailored to their persona,
27
+ city or country, and specific needs. Focus on being kind, supportive, and motivating,
28
+ while offering a helpful tip or insight that shows your genuine care for their health.
29
+ Build trust by emphasizing that you’re here to help them at their pace, without any pressure, so they feel confident and reassured in reaching out whenever they’re ready."""
30
+
31
+ # Sidebar for system prompt
32
+ st.sidebar.title("System Prompt")
33
+ system_prompt = st.sidebar.text_area("Edit the system prompt here:", value=DEFAULT_SYSTEM_PROMPT, height=300)
34
+
35
+ # Add a button to apply the system prompt
36
+ if st.sidebar.button("Apply System Prompt"):
37
+ st.session_state.system_prompt = system_prompt
38
+ # Clear the chat history when a new prompt is applied
39
+ st.session_state.messages = [{"role": "system", "content": system_prompt}]
40
+ st.sidebar.success("System prompt applied successfully! Chat history cleared.")
41
+
42
+ # Initialize system_prompt in session state if it doesn't exist
43
+ if "system_prompt" not in st.session_state:
44
+ st.session_state.system_prompt = DEFAULT_SYSTEM_PROMPT
45
+
46
+ # Initialize chat history if it doesn't exist
47
+ if "messages" not in st.session_state:
48
+ st.session_state.messages = [{"role": "system", "content": st.session_state.system_prompt}]
49
+
50
+ # Streamlit app
51
+ st.title("Health Genie App")
52
+
53
+ # Model selection
54
+ selected_model = st.selectbox("Select a model", MODELS)
55
+
56
+ # Add a Clear Conversation button
57
+ if st.button("Clear Conversation"):
58
+ st.session_state.messages = [{"role": "system", "content": st.session_state.system_prompt}]
59
+ st.success("Conversation cleared!")
60
+
61
+ # Predefined patient profiles
62
+ patient_profiles = {
63
+ "Patient 1": {
64
+ "name": "John Doe",
65
+ "age": 35, "gender": "Male", "height": 175, "weight": 80, "city": "New York", "country": "USA",
66
+ "occupation": "Software Engineer", "chief_complaints": "Lower back pain", "pain_level": 6,
67
+ "pain_duration": "2 weeks", "comorbidities": "None", "lifestyle": "Sedentary",
68
+ "pain_history": "Started after long hours of sitting", "aggravating_factor": "Prolonged sitting",
69
+ "relieving_factor": "Walking", "patient_goal": "Return to normal work routine",
70
+ "joints": "Lumbar spine", "observations": "Reduced lumbar lordosis",
71
+ "clinical_assessment": "Muscle spasm in lower back", "medical_reports": "X-ray shows no abnormalities",
72
+ "provisional_diagnosis": "Mechanical low back pain", "treatment_plan": "Physical therapy and ergonomic adjustments",
73
+ "precautions": "Avoid prolonged sitting", "remarks_physio": "Focus on core strengthening",
74
+ "attitude": "Motivated", "patient_persona": "Tech-savvy, busy professional"
75
+ },
76
+ "Patient 2": {
77
+ "name": "Jane Smith",
78
+ "age": 55, "gender": "Female", "height": 165, "weight": 70, "city": "London", "country": "UK",
79
+ "occupation": "Teacher", "chief_complaints": "Knee pain", "pain_level": 7,
80
+ "pain_duration": "3 months", "comorbidities": "Hypertension", "lifestyle": "Moderately active",
81
+ "pain_history": "Gradual onset, worsening over time", "aggravating_factor": "Climbing stairs",
82
+ "relieving_factor": "Rest and ice", "patient_goal": "Walk without pain",
83
+ "joints": "Right knee", "observations": "Slight swelling",
84
+ "clinical_assessment": "Crepitus on movement", "medical_reports": "MRI shows mild osteoarthritis",
85
+ "provisional_diagnosis": "Osteoarthritis of the knee", "treatment_plan": "Physical therapy and weight management",
86
+ "precautions": "Low-impact exercises only", "remarks_physio": "Gait training and knee stabilization exercises",
87
+ "attitude": "Concerned", "patient_persona": "Dedicated educator, worried about mobility"
88
+ },
89
+ "Patient 3": {
90
+ "name": "Emily Brown",
91
+ "age": 28, "gender": "Female", "height": 160, "weight": 55, "city": "Sydney", "country": "Australia",
92
+ "occupation": "Graphic Designer", "chief_complaints": "Neck and shoulder pain", "pain_level": 5,
93
+ "pain_duration": "1 month", "comorbidities": "Migraine", "lifestyle": "Active",
94
+ "pain_history": "Started after increased workload", "aggravating_factor": "Long hours at computer",
95
+ "relieving_factor": "Stretching", "patient_goal": "Work without discomfort",
96
+ "joints": "Cervical spine, shoulder", "observations": "Forward head posture",
97
+ "clinical_assessment": "Tight upper trapezius", "medical_reports": "No imaging done",
98
+ "provisional_diagnosis": "Work-related musculoskeletal disorder", "treatment_plan": "Ergonomic assessment, posture correction",
99
+ "precautions": "Regular breaks from computer work", "remarks_physio": "Focus on scapular stabilization",
100
+ "attitude": "Proactive", "patient_persona": "Creative professional, health-conscious"
101
+ },
102
+ "Patient 4": {
103
+ "name": "Michael Johnson",
104
+ "age": 45, "gender": "Male", "height": 180, "weight": 90, "city": "Toronto", "country": "Canada",
105
+ "occupation": "Construction Worker", "chief_complaints": "Shoulder pain", "pain_level": 8,
106
+ "pain_duration": "6 weeks", "comorbidities": "Type 2 Diabetes", "lifestyle": "Physically demanding job",
107
+ "pain_history": "Injury while lifting heavy object", "aggravating_factor": "Overhead activities",
108
+ "relieving_factor": "Rest and NSAIDs", "patient_goal": "Return to work full capacity",
109
+ "joints": "Right shoulder", "observations": "Limited range of motion",
110
+ "clinical_assessment": "Positive impingement tests", "medical_reports": "Ultrasound shows rotator cuff tendinopathy",
111
+ "provisional_diagnosis": "Rotator cuff tendinopathy", "treatment_plan": "Physical therapy, gradual return to work",
112
+ "precautions": "Avoid heavy lifting temporarily", "remarks_physio": "Rotator cuff strengthening program",
113
+ "attitude": "Frustrated", "patient_persona": "Hardworking, eager to return to full duties"
114
+ },
115
+ "Patient 5": {
116
+ "name": "Anna Schmidt",
117
+ "age": 62, "gender": "Female", "height": 170, "weight": 75, "city": "Berlin", "country": "Germany",
118
+ "occupation": "Retired", "chief_complaints": "Hip pain", "pain_level": 6,
119
+ "pain_duration": "4 months", "comorbidities": "Osteoporosis", "lifestyle": "Moderately active",
120
+ "pain_history": "Gradual onset, worse in mornings", "aggravating_factor": "Prolonged walking",
121
+ "relieving_factor": "Warm compress", "patient_goal": "Maintain independence in daily activities",
122
+ "joints": "Left hip", "observations": "Antalgic gait",
123
+ "clinical_assessment": "Reduced internal rotation", "medical_reports": "X-ray shows mild joint space narrowing",
124
+ "provisional_diagnosis": "Early hip osteoarthritis", "treatment_plan": "Physical therapy, aquatic exercises",
125
+ "precautions": "Fall prevention strategies", "remarks_physio": "Focus on hip mobility and strength",
126
+ "attitude": "Determined", "patient_persona": "Active retiree, enjoys gardening"
127
+ }
128
+ }
129
+
130
+ # Function to create a row of 3 inputs
131
+ def create_input_row(col1_input, col2_input, col3_input):
132
+ col1, col2, col3 = st.columns(3)
133
+ with col1:
134
+ val1 = col1_input()
135
+ with col2:
136
+ val2 = col2_input()
137
+ with col3:
138
+ val3 = col3_input()
139
+ return val1, val2, val3
140
+
141
+ # Create buttons for patient profiles
142
+ st.subheader("Quick Patient Profiles")
143
+ cols = st.columns(5)
144
+ for i, (profile_name, profile_data) in enumerate(patient_profiles.items()):
145
+ if cols[i].button(profile_name):
146
+ st.session_state.update(profile_data)
147
+ user_name = st.session_state.get("name", "") # Update the name field
148
+
149
+ # Create a form for user inputs
150
+ with st.form(key='patient_info_form'):
151
+ # User input rows
152
+ name, age, gender = create_input_row(
153
+ lambda: st.text_input("Patient Name", value=st.session_state.get("name", "")),
154
+ lambda: st.number_input("Age", min_value=0, max_value=120, value=st.session_state.get("age", 30)),
155
+ lambda: st.selectbox("Gender", ["Male", "Female", "Other"], index=["Male", "Female", "Other"].index(st.session_state.get("gender", "Male")))
156
+ )
157
+
158
+ height, weight, city = create_input_row(
159
+ lambda: st.number_input("Height (cm)", min_value=0, max_value=300, value=st.session_state.get("height", 170)),
160
+ lambda: st.number_input("Weight (kg)", min_value=0, max_value=500, value=st.session_state.get("weight", 70)),
161
+ lambda: st.text_input("City/Town", value=st.session_state.get("city", ""))
162
+ )
163
+
164
+ country, occupation, chief_complaints = create_input_row(
165
+ lambda: st.text_input("Country", value=st.session_state.get("country", "")),
166
+ lambda: st.text_input("Occupation", value=st.session_state.get("occupation", "")),
167
+ lambda: st.text_area("Chief Complaints", value=st.session_state.get("chief_complaints", ""))
168
+ )
169
+
170
+ pain_level, pain_duration, comorbidities = create_input_row(
171
+ lambda: st.number_input("Pain Level", 0, 10, value=st.session_state.get("pain_level", 5)),
172
+ lambda: st.text_input("Pain Duration", value=st.session_state.get("pain_duration", "")),
173
+ lambda: st.text_area("Co-morbidities", value=st.session_state.get("comorbidities", ""))
174
+ )
175
+
176
+ lifestyle, pain_history, aggravating_factor = create_input_row(
177
+ lambda: st.text_area("Lifestyle", value=st.session_state.get("lifestyle", "")),
178
+ lambda: st.text_area("History of this Pain", value=st.session_state.get("pain_history", "")),
179
+ lambda: st.text_area("Aggravating Factor", value=st.session_state.get("aggravating_factor", ""))
180
+ )
181
+
182
+ relieving_factor, patient_goal, joints = create_input_row(
183
+ lambda: st.text_area("Relieving Factor", value=st.session_state.get("relieving_factor", "")),
184
+ lambda: st.text_area("Patient Eventual Goal", value=st.session_state.get("patient_goal", "")),
185
+ lambda: st.text_area("Joints", value=st.session_state.get("joints", ""))
186
+ )
187
+
188
+ observations, clinical_assessment, medical_reports = create_input_row(
189
+ lambda: st.text_area("Observations", value=st.session_state.get("observations", "")),
190
+ lambda: st.text_area("Clinical Assessment", value=st.session_state.get("clinical_assessment", "")),
191
+ lambda: st.text_area("Medical Reports Summary", value=st.session_state.get("medical_reports", ""))
192
+ )
193
+
194
+ provisional_diagnosis, treatment_plan, precautions = create_input_row(
195
+ lambda: st.text_area("Provisional Diagnosis", value=st.session_state.get("provisional_diagnosis", "")),
196
+ lambda: st.text_area("Treatment Plan Advised", value=st.session_state.get("treatment_plan", "")),
197
+ lambda: st.text_area("Precautions/Advice", value=st.session_state.get("precautions", ""))
198
+ )
199
+
200
+ remarks_physio, attitude, patient_persona = create_input_row(
201
+ lambda: st.text_area("Remarks for Physio", value=st.session_state.get("remarks_physio", "")),
202
+ lambda: st.text_input("Attitude", value=st.session_state.get("attitude", "")),
203
+ lambda: st.text_area("Patient Persona", value=st.session_state.get("patient_persona", ""))
204
+ )
205
+
206
+ # Add the Apply button at the end of the form
207
+ apply_button = st.form_submit_button(label='Apply')
208
+
209
+ # Handle form submission
210
+ if apply_button:
211
+ # Update session state with new values
212
+ st.session_state.update({
213
+ "name": name,
214
+ "age": age,
215
+ "gender": gender,
216
+ "height": height,
217
+ "weight": weight,
218
+ "city": city,
219
+ "country": country,
220
+ "occupation": occupation,
221
+ "chief_complaints": chief_complaints,
222
+ "pain_level": pain_level,
223
+ "pain_duration": pain_duration,
224
+ "comorbidities": comorbidities,
225
+ "lifestyle": lifestyle,
226
+ "pain_history": pain_history,
227
+ "aggravating_factor": aggravating_factor,
228
+ "relieving_factor": relieving_factor,
229
+ "patient_goal": patient_goal,
230
+ "joints": joints,
231
+ "observations": observations,
232
+ "clinical_assessment": clinical_assessment,
233
+ "medical_reports": medical_reports,
234
+ "provisional_diagnosis": provisional_diagnosis,
235
+ "treatment_plan": treatment_plan,
236
+ "precautions": precautions,
237
+ "remarks_physio": remarks_physio,
238
+ "attitude": attitude,
239
+ "patient_persona": patient_persona
240
+ })
241
+ st.success("Patient information updated successfully!")
242
+
243
+ # Display chat messages (excluding system message)
244
+ for message in st.session_state.messages[1:]:
245
+ with st.chat_message(message["role"]):
246
+ st.markdown(message["content"])
247
+
248
+ # User input
249
+ if prompt := st.chat_input("What would you like recommendations for?"):
250
+ # Prepare the user information
251
+ user_info = f"""
252
+ Name: {name}
253
+ Age: {age}, Gender: {gender}, Height: {height} cm, Weight: {weight} kg
254
+ Location: {city}, {country}
255
+ Occupation: {occupation}
256
+ Chief Complaints: {chief_complaints}
257
+ Pain Level: {pain_level}, Pain Duration: {pain_duration}
258
+ Co-morbidities: {comorbidities}
259
+ Lifestyle: {lifestyle}
260
+ Pain History: {pain_history}
261
+ Aggravating Factor: {aggravating_factor}
262
+ Relieving Factor: {relieving_factor}
263
+ Patient Goal: {patient_goal}
264
+ Joints: {joints}
265
+ Observations: {observations}
266
+ Clinical Assessment: {clinical_assessment}
267
+ Medical Reports: {medical_reports}
268
+ Provisional Diagnosis: {provisional_diagnosis}
269
+ Treatment Plan: {treatment_plan}
270
+ Precautions: {precautions}
271
+ Remarks for Physio: {remarks_physio}
272
+ Attitude: {attitude}
273
+ Patient Persona: {patient_persona}
274
+ """
275
+
276
+ # Update the system prompt with user information
277
+ updated_system_prompt = f"{st.session_state.system_prompt}\n\nCurrent Patient Information:\n{user_info}"
278
+
279
+ # Update the first message in the conversation (system prompt)
280
+ st.session_state.messages[0] = {"role": "system", "content": updated_system_prompt}
281
+
282
+ # Append the user's question
283
+ st.session_state.messages.append({"role": "user", "content": prompt})
284
+ with st.chat_message("user"):
285
+ st.markdown(prompt)
286
+
287
+ # Generate response
288
+ with st.chat_message("assistant"):
289
+ message_placeholder = st.empty()
290
+ full_response = ""
291
+ for response in client.chat.completions.create(
292
+ messages=st.session_state.messages,
293
+ model=selected_model,
294
+ stream=True,
295
+ ):
296
+ full_response += (response.choices[0].delta.content or "")
297
+ message_placeholder.markdown(full_response + "▌")
298
+ message_placeholder.markdown(full_response)
299
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
300
+
301
+ # Display a warning about API key
302
+ st.sidebar.warning("Make sure to set your Groq API key as an environment variable named GROQ_API_KEY")