lukiod commited on
Commit
6ed2a87
·
verified ·
1 Parent(s): e1fb3b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -93
app.py CHANGED
@@ -7,7 +7,6 @@ import gc
7
  from typing import List, Dict, Optional
8
  import os
9
 
10
- # ================== Model Configuration ==================
11
  class ModelHandler:
12
  def __init__(self):
13
  self.model_name = "google/flan-t5-large"
@@ -32,12 +31,10 @@ class ModelHandler:
32
 
33
  def generate_response(self, prompt: str, max_length: int = 512) -> str:
34
  try:
35
- # Clear memory
36
  gc.collect()
37
  if torch.cuda.is_available():
38
  torch.cuda.empty_cache()
39
 
40
- # Prepare input
41
  inputs = self.tokenizer(
42
  prompt,
43
  return_tensors="pt",
@@ -45,7 +42,6 @@ class ModelHandler:
45
  max_length=512
46
  ).to(self.device)
47
 
48
- # Generate response
49
  with torch.no_grad():
50
  outputs = self.model.generate(
51
  inputs.input_ids,
@@ -58,7 +54,6 @@ class ModelHandler:
58
 
59
  response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
60
 
61
- # Clear memory
62
  del outputs, inputs
63
  gc.collect()
64
  if torch.cuda.is_available():
@@ -73,7 +68,6 @@ class ModelHandler:
73
  if torch.cuda.is_available():
74
  torch.cuda.empty_cache()
75
 
76
- # ================== Data Management ==================
77
  class HealthData:
78
  def __init__(self):
79
  self.metrics = []
@@ -116,65 +110,43 @@ class HealthData:
116
 
117
  return "\n".join(context_parts) if context_parts else "No health data available."
118
 
119
- # ================== Health Assistant ==================
120
  class HealthAssistant:
121
  def __init__(self):
122
  self.model = ModelHandler()
123
  self.data = HealthData()
124
  self.request_count = 0
125
 
126
- def _create_prompt(self, message: str, context: str = "", history: List = None) -> str:
127
- prompt_parts = [
128
- "You are a helpful healthcare assistant. Provide accurate and helpful information.",
129
- f"User Health Information:\n{context}" if context else "",
130
- "Previous conversation:",
131
- ]
132
 
 
 
 
 
 
 
133
  if history:
134
- for h in history[-3:]: # Last 3 messages for context
135
- prompt_parts.append(f"User: {h['content']}" if h['role'] == 'user'
136
- else f"Assistant: {h['content']}")
 
 
 
 
 
137
 
138
- prompt_parts.append(f"Current question: {message}")
139
- return "\n\n".join(filter(None, prompt_parts))
140
 
141
  def get_response(self, message: str, history: List = None) -> str:
142
- # Increment request counter
143
  self.request_count += 1
144
-
145
- # Get health context
146
- context = self.data.get_health_context()
147
-
148
- # Create prompt
149
- prompt = self._create_prompt(message, context, history)
150
-
151
- # Get response
152
  response = self.model.generate_response(prompt)
153
 
154
- # Periodic memory cleanup
155
  if self.request_count % 5 == 0:
156
  self.model.clear_memory()
157
 
158
  return response
159
 
160
- def analyze_symptoms(self, symptoms: str) -> str:
161
- if not symptoms:
162
- return "Please describe your symptoms."
163
-
164
- prompt = (
165
- "Analyze these symptoms as a medical professional:\n"
166
- f"{symptoms}\n\n"
167
- "Provide analysis with:\n"
168
- "1. Risk Level\n"
169
- "2. Key Symptoms\n"
170
- "3. Possible Causes\n"
171
- "4. Recommended Actions\n"
172
- "5. When to Seek Medical Care"
173
- )
174
-
175
- return self.model.generate_response(prompt)
176
-
177
- # ================== Gradio Interface ==================
178
  class HealthAssistantUI:
179
  def __init__(self):
180
  self.assistant = HealthAssistant()
@@ -184,8 +156,7 @@ class HealthAssistantUI:
184
  return "", history
185
 
186
  bot_message = self.assistant.get_response(message, history)
187
- history.append({"role": "user", "content": message})
188
- history.append({"role": "assistant", "content": bot_message})
189
  return "", history
190
 
191
  def save_metrics(self, weight: float, steps: int, sleep: float) -> tuple:
@@ -220,58 +191,36 @@ class HealthAssistantUI:
220
  with gr.Tabs():
221
  # Chat Interface
222
  with gr.Tab("💬 Health Chat"):
223
- with gr.Row():
224
- with gr.Column(scale=3):
225
- chatbot = gr.Chatbot(
226
- show_label=False,
227
- height=450,
228
- container=True,
229
- )
230
- with gr.Column(scale=1):
231
- gr.Markdown("### Your Health Info")
232
- context_display = gr.Markdown(
233
- value=self.assistant.data.get_health_context()
234
- )
235
-
236
  with gr.Row():
237
  msg = gr.Textbox(
238
  placeholder="Type your health question... (Press Enter)",
239
  lines=2,
240
- max_lines=2,
241
  show_label=False,
242
- container=False,
243
  scale=9
244
  )
245
  send_btn = gr.Button("Send", scale=1)
246
-
247
  clear_btn = gr.Button("Clear Chat")
248
-
249
- # Symptom Checker
250
- with gr.Tab("🔍 Symptom Checker"):
251
- symptoms_input = gr.Textbox(
252
- label="Describe your symptoms",
253
- placeholder="Enter your symptoms in detail...",
254
- lines=4
255
- )
256
- analyze_btn = gr.Button("Analyze Symptoms", variant="primary")
257
- symptoms_output = gr.Markdown()
258
-
259
- # Health Metrics
260
  with gr.Tab("📊 Health Metrics"):
261
  with gr.Row():
262
  with gr.Column():
263
  weight_input = gr.Number(label="Weight (kg)")
264
  steps_input = gr.Number(label="Steps")
265
  sleep_input = gr.Number(label="Hours Slept")
266
- metrics_btn = gr.Button("Save Metrics", variant="primary")
267
  metrics_status = gr.Markdown()
268
 
269
  with gr.Column():
270
  metrics_display = gr.Dataframe(
271
  headers=["Date", "Weight", "Steps", "Sleep"]
272
  )
273
-
274
- # Medication Manager
275
  with gr.Tab("💊 Medication Manager"):
276
  with gr.Row():
277
  with gr.Column():
@@ -279,7 +228,7 @@ class HealthAssistantUI:
279
  med_dosage = gr.Textbox(label="Dosage")
280
  med_time = gr.Textbox(label="Time")
281
  med_notes = gr.Textbox(label="Notes (optional)")
282
- med_btn = gr.Button("Add Medication", variant="primary")
283
  med_status = gr.Markdown()
284
 
285
  with gr.Column():
@@ -290,13 +239,7 @@ class HealthAssistantUI:
290
  # Event handlers
291
  msg.submit(self.user_chat, [msg, chatbot], [msg, chatbot])
292
  send_btn.click(self.user_chat, [msg, chatbot], [msg, chatbot])
293
- clear_btn.click(lambda: None, None, chatbot)
294
-
295
- analyze_btn.click(
296
- self.assistant.analyze_symptoms,
297
- inputs=[symptoms_input],
298
- outputs=[symptoms_output]
299
- )
300
 
301
  metrics_btn.click(
302
  self.save_metrics,
@@ -310,12 +253,6 @@ class HealthAssistantUI:
310
  outputs=[med_status, meds_display]
311
  )
312
 
313
- gr.Markdown(
314
- """### ⚠️ Medical Disclaimer
315
- This AI assistant provides general health information only.
316
- Always consult healthcare professionals for medical advice."""
317
- )
318
-
319
  return demo
320
 
321
  def main():
 
7
  from typing import List, Dict, Optional
8
  import os
9
 
 
10
  class ModelHandler:
11
  def __init__(self):
12
  self.model_name = "google/flan-t5-large"
 
31
 
32
  def generate_response(self, prompt: str, max_length: int = 512) -> str:
33
  try:
 
34
  gc.collect()
35
  if torch.cuda.is_available():
36
  torch.cuda.empty_cache()
37
 
 
38
  inputs = self.tokenizer(
39
  prompt,
40
  return_tensors="pt",
 
42
  max_length=512
43
  ).to(self.device)
44
 
 
45
  with torch.no_grad():
46
  outputs = self.model.generate(
47
  inputs.input_ids,
 
54
 
55
  response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
56
 
 
57
  del outputs, inputs
58
  gc.collect()
59
  if torch.cuda.is_available():
 
68
  if torch.cuda.is_available():
69
  torch.cuda.empty_cache()
70
 
 
71
  class HealthData:
72
  def __init__(self):
73
  self.metrics = []
 
110
 
111
  return "\n".join(context_parts) if context_parts else "No health data available."
112
 
 
113
  class HealthAssistant:
114
  def __init__(self):
115
  self.model = ModelHandler()
116
  self.data = HealthData()
117
  self.request_count = 0
118
 
119
+ def _create_prompt(self, message: str, history: List = None) -> str:
120
+ prompt_parts = ["You are a helpful healthcare assistant."]
 
 
 
 
121
 
122
+ # Add health context
123
+ health_context = self.data.get_health_context()
124
+ if health_context != "No health data available.":
125
+ prompt_parts.append(f"Current health information:\n{health_context}")
126
+
127
+ # Add conversation history
128
  if history:
129
+ prompt_parts.append("Previous conversation:")
130
+ for user_msg, bot_msg in history[-3:]:
131
+ prompt_parts.append(f"User: {user_msg}")
132
+ prompt_parts.append(f"Assistant: {bot_msg}")
133
+
134
+ # Add current question
135
+ prompt_parts.append(f"User: {message}")
136
+ prompt_parts.append("Assistant:")
137
 
138
+ return "\n\n".join(prompt_parts)
 
139
 
140
  def get_response(self, message: str, history: List = None) -> str:
 
141
  self.request_count += 1
142
+ prompt = self._create_prompt(message, history)
 
 
 
 
 
 
 
143
  response = self.model.generate_response(prompt)
144
 
 
145
  if self.request_count % 5 == 0:
146
  self.model.clear_memory()
147
 
148
  return response
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  class HealthAssistantUI:
151
  def __init__(self):
152
  self.assistant = HealthAssistant()
 
156
  return "", history
157
 
158
  bot_message = self.assistant.get_response(message, history)
159
+ history.append([message, bot_message])
 
160
  return "", history
161
 
162
  def save_metrics(self, weight: float, steps: int, sleep: float) -> tuple:
 
191
  with gr.Tabs():
192
  # Chat Interface
193
  with gr.Tab("💬 Health Chat"):
194
+ chatbot = gr.Chatbot(
195
+ height=450,
196
+ show_label=False,
197
+ )
 
 
 
 
 
 
 
 
 
198
  with gr.Row():
199
  msg = gr.Textbox(
200
  placeholder="Type your health question... (Press Enter)",
201
  lines=2,
 
202
  show_label=False,
 
203
  scale=9
204
  )
205
  send_btn = gr.Button("Send", scale=1)
 
206
  clear_btn = gr.Button("Clear Chat")
207
+
208
+ # Health Metrics Tab
 
 
 
 
 
 
 
 
 
 
209
  with gr.Tab("📊 Health Metrics"):
210
  with gr.Row():
211
  with gr.Column():
212
  weight_input = gr.Number(label="Weight (kg)")
213
  steps_input = gr.Number(label="Steps")
214
  sleep_input = gr.Number(label="Hours Slept")
215
+ metrics_btn = gr.Button("Save Metrics")
216
  metrics_status = gr.Markdown()
217
 
218
  with gr.Column():
219
  metrics_display = gr.Dataframe(
220
  headers=["Date", "Weight", "Steps", "Sleep"]
221
  )
222
+
223
+ # Medication Manager Tab
224
  with gr.Tab("💊 Medication Manager"):
225
  with gr.Row():
226
  with gr.Column():
 
228
  med_dosage = gr.Textbox(label="Dosage")
229
  med_time = gr.Textbox(label="Time")
230
  med_notes = gr.Textbox(label="Notes (optional)")
231
+ med_btn = gr.Button("Add Medication")
232
  med_status = gr.Markdown()
233
 
234
  with gr.Column():
 
239
  # Event handlers
240
  msg.submit(self.user_chat, [msg, chatbot], [msg, chatbot])
241
  send_btn.click(self.user_chat, [msg, chatbot], [msg, chatbot])
242
+ clear_btn.click(lambda: [], None, chatbot)
 
 
 
 
 
 
243
 
244
  metrics_btn.click(
245
  self.save_metrics,
 
253
  outputs=[med_status, meds_display]
254
  )
255
 
 
 
 
 
 
 
256
  return demo
257
 
258
  def main():