Muhammadidrees commited on
Commit
0456912
·
verified ·
1 Parent(s): 47eec25

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +258 -292
app.py CHANGED
@@ -4,7 +4,7 @@ import torch
4
  import re
5
 
6
  # =======================================================
7
- # Model Loading with Error Handling
8
  # =======================================================
9
  model_name = "augtoma/qCammel-13"
10
  print("Loading tokenizer and model...")
@@ -28,59 +28,33 @@ except Exception as e:
28
  raise
29
 
30
 
31
- # =======================================================
32
- # Constants
33
- # =======================================================
34
- MEDICAL_DISCLAIMER = """
35
- ⚠️ **IMPORTANT MEDICAL DISCLAIMER:**
36
- - This is an AI simulation for educational purposes only
37
- - For medical emergencies, call emergency services immediately (911/999/local emergency number)
38
- - Always consult a licensed healthcare provider for diagnosis and treatment
39
- - Do not use this for serious, worsening, or life-threatening symptoms
40
- - This AI cannot diagnose conditions or prescribe medications
41
- """
42
-
43
- EMERGENCY_KEYWORDS = [
44
- "chest pain", "can't breathe", "breathing difficulty", "suicide",
45
- "heart attack", "stroke", "severe bleeding", "unconscious",
46
- "overdose", "severe pain", "emergency"
47
- ]
48
-
49
-
50
  # =======================================================
51
  # Helper Functions
52
  # =======================================================
53
  def extract_name(text):
54
- """Extract name from user input"""
55
  text = text.lower()
56
- # Remove common phrases
57
- for phrase in ["yes", "i am", "i'm", "my name is", "name is", "it's", "its"]:
58
  text = text.replace(phrase, "")
59
-
60
- # Clean and capitalize
61
  text = re.sub(r'[^\w\s]', '', text).strip()
62
  return text.title() if text and len(text) > 1 else "Patient"
63
 
64
 
65
  def extract_age(text):
66
- """Extract age from user input"""
67
- # Look for numbers in the text
68
  numbers = re.findall(r'\b(\d{1,3})\b', text)
69
  for num in numbers:
70
  age = int(num)
71
- if 1 <= age <= 120: # Reasonable age range
72
  return age
73
  return None
74
 
75
 
76
  def check_emergency(text):
77
- """Check if message contains emergency keywords"""
78
- text_lower = text.lower()
79
- return any(keyword in text_lower for keyword in EMERGENCY_KEYWORDS)
80
 
81
 
82
  def create_initial_session():
83
- """Create a fresh session dictionary"""
84
  return {
85
  "name": None,
86
  "age": None,
@@ -88,156 +62,46 @@ def create_initial_session():
88
  "symptoms": None,
89
  "duration": None,
90
  "medication": None,
91
- "stage": "intro"
 
 
92
  }
93
 
94
 
95
  # =======================================================
96
- # Diet Suggestions
97
- # =======================================================
98
- def get_diet_suggestion(name, symptoms):
99
- """Get personalized diet suggestions based on symptoms"""
100
- symptoms_lower = symptoms.lower()
101
-
102
- if "fever" in symptoms_lower:
103
- return f"""🍎 **Diet Plan for {name} (Fever)**
104
-
105
- **Meals:**
106
- - 🥣 **Breakfast:** Oatmeal or boiled egg with banana/apple
107
- - 🍲 **Lunch:** Rice with lentil soup or boiled vegetables
108
- - 🍛 **Dinner:** Light soup or grilled chicken with plain rice
109
-
110
- **Hydration:**
111
- - 💧 Drink 8–10 glasses of water daily
112
- - Coconut water or clear soups
113
- - Herbal teas (chamomile, ginger)
114
-
115
- **Avoid:**
116
- - 🚫 Fried, oily, or spicy foods
117
- - Heavy meals
118
- - Caffeinated drinks
119
-
120
- **Tips:** Eat small portions frequently to help your body recover."""
121
-
122
- elif any(word in symptoms_lower for word in ["stomach", "vomit", "nausea", "diarrhea"]):
123
- return f"""🥗 **Diet Plan for {name} (Stomach Issues)**
124
-
125
- **BRAT Diet:**
126
- - 🍌 Bananas
127
- - 🍚 Rice (plain white rice)
128
- - 🍎 Applesauce
129
- - 🍞 Toast (dry or with minimal butter)
130
-
131
- **Hydration:**
132
- - 💧 Sip water frequently
133
- - Oral rehydration solution (ORS)
134
- - Clear broths
135
-
136
- **Avoid:**
137
- - 🚫 Dairy products
138
- - Fried or spicy foods
139
- - Caffeine and alcohol
140
- - Raw vegetables
141
-
142
- **Tips:** Start with small amounts and gradually increase as you feel better."""
143
-
144
- elif any(word in symptoms_lower for word in ["cold", "flu", "cough", "sore throat"]):
145
- return f"""🍊 **Diet Plan for {name} (Cold/Flu)**
146
-
147
- **Immunity Boosters:**
148
- - 🍋 Citrus fruits (oranges, lemons)
149
- - 🍯 Honey with warm water
150
- - 🧄 Garlic (natural antibiotic)
151
- - 🧅 Onions
152
-
153
- **Meals:**
154
- - 🍲 Chicken soup (helps clear congestion)
155
- - ☕ Ginger or green tea
156
- - 🥣 Warm porridge or oatmeal
157
-
158
- **Hydration:**
159
- - 💧 Plenty of warm fluids
160
- - Herbal teas
161
-
162
- **Avoid:**
163
- - 🚫 Sugary drinks
164
- - Chilled beverages
165
- - Dairy (may increase mucus)
166
-
167
- **Tips:** Stay warm and get plenty of rest."""
168
-
169
- elif any(word in symptoms_lower for word in ["headache", "migraine"]):
170
- return f"""🧘 **Diet Plan for {name} (Headache)**
171
-
172
- **Helpful Foods:**
173
- - 💧 Stay well-hydrated (dehydration causes headaches)
174
- - 🥔 Magnesium-rich: bananas, nuts, spinach
175
- - 🐟 Omega-3: fish, walnuts
176
- - 🧂 Small amounts of salt if low blood pressure
177
-
178
- **Avoid:**
179
- - 🚫 Processed foods
180
- - Artificial sweeteners
181
- - Aged cheeses
182
- - Alcohol
183
- - Excessive caffeine
184
-
185
- **Tips:** Eat regular meals; skipping meals can trigger headaches."""
186
-
187
- else:
188
- return f"""🥗 **General Healthy Diet Plan for {name}**
189
-
190
- **Balanced Meals:**
191
- - 🍎 Fresh fruits and vegetables
192
- - 🍗 Lean proteins (chicken, fish, legumes)
193
- - 🍚 Whole grains (brown rice, oats)
194
- - 🥜 Nuts and seeds
195
-
196
- **Hydration:**
197
- - 💧 8–10 glasses of water daily
198
-
199
- **Avoid:**
200
- - 🚫 Processed and fried foods
201
- - Excessive sugar and salt
202
- - Junk food
203
-
204
- **Tips:** Eat at regular intervals and maintain portion control."""
205
-
206
-
207
- # =======================================================
208
- # AI Response Generation
209
  # =======================================================
210
- def generate_ai_response(session, user_message):
211
- """Generate AI consultation response using the model"""
212
  try:
213
- # Build the prompt
214
- prompt = f"""You are Dr. Aiden — a warm, caring, and professional doctor.
215
- You are consulting a {session['age']}-year-old {session['gender']} named {session['name']}.
 
216
 
217
- Patient details:
218
- - Symptoms: {session['symptoms']}
 
 
 
219
  - Duration: {session['duration']}
220
- - Current medications: {session['medication']}
221
 
222
- Now the patient says: "{user_message}"
 
223
 
224
- Respond as a real doctor would — empathetic, clear, and personalized.
225
- Include:
226
- 1. Acknowledge their condition
227
- 2. Possible causes
228
- 3. Simple home remedies or OTC medicines (if safe)
229
- 4. Diet, rest, and hydration tips
230
- 5. When to visit a real doctor
231
- 6. End with a reassuring tone"""
232
 
233
- # Tokenize and generate
234
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
 
235
 
236
  gen_cfg = GenerationConfig(
237
- temperature=0.7,
238
- top_p=0.9,
239
- max_new_tokens=350,
240
- repetition_penalty=1.1,
 
241
  pad_token_id=tokenizer.pad_token_id,
242
  eos_token_id=tokenizer.eos_token_id
243
  )
@@ -245,148 +109,277 @@ Include:
245
  with torch.no_grad():
246
  output = model.generate(**inputs, generation_config=gen_cfg)
247
 
248
- # Decode the output
249
- output_text = tokenizer.decode(output[0], skip_special_tokens=True)
250
-
251
- # Try to extract just the response part
252
- # The model might repeat the prompt, so we try to find where the actual response starts
253
- if "reassuring tone" in output_text:
254
- parts = output_text.split("reassuring tone")
255
- if len(parts) > 1:
256
- output_text = parts[-1].strip()
257
 
258
- # If the output contains the prompt, try to split it
259
- if user_message in output_text:
260
- parts = output_text.split(user_message)
261
- if len(parts) > 1:
262
- output_text = parts[-1].strip()
263
 
264
  # Clean up
265
- output_text = output_text.strip()
266
 
267
- # If output is too short or empty, provide a fallback
268
- if len(output_text) < 20:
269
- output_text = f"Hello {session['name']}, I understand you have {session['symptoms']} for {session['duration']}. This could be due to several reasons. I recommend staying hydrated, getting plenty of rest, and monitoring your temperature. If your fever persists beyond 5 days or gets worse, please visit a doctor in person for proper examination."
270
 
271
- # Ensure proper ending punctuation
272
- if not output_text.endswith((".", "!", "?")):
273
- output_text += "."
274
-
275
- # Add disclaimer
276
- output_text += "\n\n⚕️ *Note: This advice is AI-generated and not a substitute for professional medical care.*"
277
 
278
- return output_text
279
 
280
  except Exception as e:
281
- print(f"Error in generate_ai_response: {e}")
282
- return f"I understand you're experiencing {session['symptoms']}, {session['name']}. Since this has been going on for {session['duration']}, I recommend consulting with a healthcare provider for a proper examination and diagnosis.\n\n⚕️ *Note: This advice is AI-generated and not a substitute for professional medical care.*"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
 
284
 
285
  # =======================================================
286
- # Doctor Response Logic
287
  # =======================================================
288
  def doctor_response(user_message, session):
289
- """Generate doctor's response based on conversation stage"""
290
  if not user_message or not user_message.strip():
291
- return "Please type your message.", session
292
 
293
  user_message_clean = user_message.strip()
294
  user_message_lower = user_message_clean.lower()
295
 
296
- # Check for emergency situations
297
  if check_emergency(user_message_clean):
298
- emergency_response = """🚨 **EMERGENCY ALERT** 🚨
299
-
300
- Your message suggests a potentially serious medical emergency.
301
 
302
- **PLEASE TAKE IMMEDIATE ACTION:**
303
- - Call emergency services NOW (911 in US, 999 in UK, or your local emergency number)
304
- - Go to the nearest emergency room
305
- - Do not delay seeking immediate medical attention
306
 
307
- This AI chatbot cannot handle emergencies. Your safety is the priority."""
308
- return emergency_response, session
309
 
310
- # Stage-based conversation flow
311
  try:
312
  if session["stage"] == "intro":
313
  session["stage"] = "ask_name"
314
- return "👨‍⚕️ Hello! I'm Dr. Aiden, your AI medical assistant.\n\n" + MEDICAL_DISCLAIMER + "\n\nMay I know your name, please?", session
 
 
 
 
315
 
316
  elif session["stage"] == "ask_name":
317
  session["name"] = extract_name(user_message_clean)
318
  session["stage"] = "ask_age"
319
- return f"Nice to meet you, {session['name']}! How old are you?", session
320
 
321
  elif session["stage"] == "ask_age":
322
  age = extract_age(user_message_clean)
323
  if age:
324
  session["age"] = age
325
  session["stage"] = "ask_gender"
326
- return f"Got it, {session['name']}. Are you male or female?", session
327
- else:
328
- return "Please tell me your age in numbers (e.g., 25, 30, 45).", session
329
 
330
  elif session["stage"] == "ask_gender":
331
  if "male" in user_message_lower and "female" not in user_message_lower:
332
  session["gender"] = "male"
333
  elif "female" in user_message_lower:
334
- session["gender"] = "female"
335
  else:
336
- return "Could you please specify whether you are male or female?", session
337
 
338
  session["stage"] = "ask_symptoms"
339
- return f"Thanks, {session['name']}! So you're a {session['age']}-year-old {session['gender']}.\n\nWhat symptoms are you experiencing? Please describe them in detail.", session
340
 
341
  elif session["stage"] == "ask_symptoms":
342
  if len(user_message_clean) < 5:
343
- return "Please describe your symptoms in more detail so I can help you better.", session
344
  session["symptoms"] = user_message_clean
345
  session["stage"] = "ask_duration"
346
- return "Since when have you been feeling this way? (e.g., 2 days, 1 week, etc.)", session
347
 
348
  elif session["stage"] == "ask_duration":
349
  session["duration"] = user_message_clean
350
  session["stage"] = "ask_medicine"
351
- return "Are you currently taking any medications or treatments? If not, just say 'no'.", session
352
 
353
  elif session["stage"] == "ask_medicine":
354
- session["medication"] = user_message_clean
355
  session["stage"] = "consult"
356
- # Provide summary and automatically generate initial consultation
357
- summary = f"""Thank you for providing all the information, {session['name']}.
358
-
359
- 📋 **Summary:**
360
- - **Name:** {session['name']}
361
- - **Age:** {session['age']} years old
362
- - **Gender:** {session['gender']}
363
- - **Symptoms:** {session['symptoms']}
364
- - **Duration:** {session['duration']}
365
- - **Current medication:** {session['medication']}
366
-
367
- Let me assess your condition...\n\n"""
368
 
369
- # Generate initial consultation automatically
370
- initial_consultation = generate_ai_response(session, "Please assess my condition and give me advice")
371
- return summary + initial_consultation, session
 
 
 
372
 
373
  elif session["stage"] == "consult":
374
- # Handle diet-specific queries
375
- if any(word in user_message_lower for word in ["diet", "food", "meal", "eat", "nutrition", "drink"]):
376
- diet_plan = get_diet_suggestion(session["name"], session["symptoms"])
377
- return diet_plan + "\n\n⚕️ *Note: This is general advice. Consult a healthcare provider for personalized dietary recommendations, especially if you have allergies or other conditions.*", session
 
 
 
 
 
378
 
379
- # Generate AI consultation response for any other question
380
- return generate_ai_response(session, user_message_clean), session
381
 
382
- else:
383
- # Reset if stage is unknown
384
- session["stage"] = "intro"
385
- return "Let's start over. Say 'Hi Doctor' to begin your consultation.", session
386
-
387
  except Exception as e:
388
- print(f"Error in doctor_response: {e}")
389
- return "I apologize, but I encountered an error. Please try again or start a new consultation.", session
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
390
 
391
 
392
  # =======================================================
@@ -394,19 +387,17 @@ Let me assess your condition...\n\n"""
394
  # =======================================================
395
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
396
  gr.HTML("""
397
- <div style="text-align:center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color:white; padding:25px; border-radius:15px; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">
398
- <h1 style="margin:0; font-size: 2.5em;">🏥 Dr. Aiden - AI Medical Assistant</h1>
399
- <p style="margin:10px 0 0 0; font-size: 1.1em;">Compassionate AI-powered health consultation</p>
400
- <p style="margin:5px 0 0 0; font-size: 0.9em; opacity: 0.9;">⚠️ For emergencies, call 911 immediately</p>
401
  </div>
402
  """)
403
 
404
- # Session state
405
  session_state = gr.State(create_initial_session)
406
 
407
  chatbot = gr.Chatbot(
408
- label="👨‍⚕️ Chat with Dr. Aiden",
409
- height=500,
410
  type='messages',
411
  avatar_images=(
412
  "https://cdn-icons-png.flaticon.com/512/706/706830.png",
@@ -416,33 +407,26 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
416
 
417
  with gr.Row():
418
  user_input = gr.Textbox(
419
- placeholder="Type your message here (say 'Hi Doctor' to start)...",
420
- label="Your Message",
421
  lines=2,
422
  scale=4
423
  )
424
 
425
  with gr.Row():
426
  send_btn = gr.Button("💬 Send", variant="primary", scale=1)
427
- clear_btn = gr.Button("🔄 New Consultation", variant="secondary", scale=1)
428
 
429
  gr.HTML("""
430
- <div style="margin-top: 20px; padding: 15px; background-color: #fff3cd; border-left: 4px solid #ffc107; border-radius: 5px;">
431
- <strong>⚠️ Important Reminders:</strong>
432
- <ul style="margin: 10px 0; padding-left: 20px;">
433
- <li>This is an AI simulation for educational purposes only</li>
434
- <li>Always consult a real doctor for medical diagnosis and treatment</li>
435
- <li>For emergencies, call 911 or your local emergency services immediately</li>
436
- <li>Do not use this for serious or life-threatening conditions</li>
437
- </ul>
438
  </div>
439
  """)
440
 
441
  def respond(message, history, session):
442
- """Handle user message and update chat"""
443
  if history is None:
444
  history = []
445
-
446
  if not message or not message.strip():
447
  return "", history, session
448
 
@@ -454,31 +438,13 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
454
  return "", history, updated_session
455
 
456
  def reset():
457
- """Reset conversation and session"""
458
  return [], create_initial_session()
459
 
460
- # Event handlers
461
- send_btn.click(
462
- respond,
463
- [user_input, chatbot, session_state],
464
- [user_input, chatbot, session_state]
465
- )
466
-
467
- user_input.submit(
468
- respond,
469
- [user_input, chatbot, session_state],
470
- [user_input, chatbot, session_state]
471
- )
472
-
473
- clear_btn.click(
474
- reset,
475
- None,
476
- [chatbot, session_state],
477
- queue=False
478
- )
479
 
480
  if __name__ == "__main__":
481
- print("🏥 Launching Dr. Aiden Medical Assistant...")
482
- print("⚠️ Remember: This is for educational purposes only!")
483
  demo.queue()
484
  demo.launch(share=True)
 
4
  import re
5
 
6
  # =======================================================
7
+ # Model Loading
8
  # =======================================================
9
  model_name = "augtoma/qCammel-13"
10
  print("Loading tokenizer and model...")
 
28
  raise
29
 
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  # =======================================================
32
  # Helper Functions
33
  # =======================================================
34
  def extract_name(text):
 
35
  text = text.lower()
36
+ for phrase in ["yes", "i am", "i'm", "my name is", "name is", "it's", "its", "this is"]:
 
37
  text = text.replace(phrase, "")
 
 
38
  text = re.sub(r'[^\w\s]', '', text).strip()
39
  return text.title() if text and len(text) > 1 else "Patient"
40
 
41
 
42
  def extract_age(text):
 
 
43
  numbers = re.findall(r'\b(\d{1,3})\b', text)
44
  for num in numbers:
45
  age = int(num)
46
+ if 1 <= age <= 120:
47
  return age
48
  return None
49
 
50
 
51
  def check_emergency(text):
52
+ emergency_words = ["chest pain", "can't breathe", "suicide", "heart attack", "stroke",
53
+ "severe bleeding", "unconscious", "overdose"]
54
+ return any(word in text.lower() for word in emergency_words)
55
 
56
 
57
  def create_initial_session():
 
58
  return {
59
  "name": None,
60
  "age": None,
 
62
  "symptoms": None,
63
  "duration": None,
64
  "medication": None,
65
+ "other_info": [],
66
+ "stage": "intro",
67
+ "conversation_context": []
68
  }
69
 
70
 
71
  # =======================================================
72
+ # Generate Natural Doctor Response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
  # =======================================================
74
+ def generate_doctor_response(session, user_message):
75
+ """Generate a natural, conversational doctor response"""
76
  try:
77
+ # Build conversational context
78
+ context = "\n".join(session.get("conversation_context", [])[-3:]) # Last 3 exchanges
79
+
80
+ prompt = f"""You are Dr. Aiden, a kind and experienced family doctor having a natural conversation with your patient.
81
 
82
+ Patient Profile:
83
+ - Name: {session['name']}
84
+ - Age: {session['age']} years old
85
+ - Gender: {session['gender']}
86
+ - Chief Complaint: {session['symptoms']}
87
  - Duration: {session['duration']}
88
+ - Medications: {session['medication']}
89
 
90
+ Recent conversation:
91
+ {context}
92
 
93
+ Patient: {user_message}
 
 
 
 
 
 
 
94
 
95
+ Dr. Aiden: """
96
+
97
+ inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=1800).to(model.device)
98
 
99
  gen_cfg = GenerationConfig(
100
+ temperature=0.8,
101
+ top_p=0.92,
102
+ max_new_tokens=300,
103
+ repetition_penalty=1.15,
104
+ do_sample=True,
105
  pad_token_id=tokenizer.pad_token_id,
106
  eos_token_id=tokenizer.eos_token_id
107
  )
 
109
  with torch.no_grad():
110
  output = model.generate(**inputs, generation_config=gen_cfg)
111
 
112
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
 
 
 
 
 
 
 
 
113
 
114
+ # Extract just the doctor's response
115
+ if "Dr. Aiden:" in response:
116
+ response = response.split("Dr. Aiden:")[-1].strip()
117
+ elif "Patient:" in response:
118
+ response = response.split("Patient:")[0].strip()
119
 
120
  # Clean up
121
+ response = response.strip()
122
 
123
+ # If response is too short or looks like it failed, give a fallback
124
+ if len(response) < 30 or response.startswith("You are Dr"):
125
+ response = generate_fallback_response(session, user_message)
126
 
127
+ # Add to conversation context
128
+ session["conversation_context"].append(f"Patient: {user_message}")
129
+ session["conversation_context"].append(f"Doctor: {response}")
 
 
 
130
 
131
+ return response
132
 
133
  except Exception as e:
134
+ print(f"Generation error: {e}")
135
+ return generate_fallback_response(session, user_message)
136
+
137
+
138
+ def generate_fallback_response(session, user_message):
139
+ """Generate a fallback response based on symptoms"""
140
+ name = session['name']
141
+ symptoms = session['symptoms'].lower()
142
+ duration = session['duration']
143
+
144
+ if "fever" in symptoms:
145
+ return f"""I can see you've had this fever for {duration}, {name}. That's quite uncomfortable, I'm sure.
146
+
147
+ A fever lasting 5 days could be viral or bacterial. Let me give you some advice:
148
+
149
+ First, make sure you're drinking plenty of fluids - water, coconut water, or clear soups. Your body needs hydration when fighting infection.
150
+
151
+ For the fever itself, you can take paracetamol (like Panadol) 500mg every 6 hours if the temperature goes above 100°F.
152
+
153
+ Get lots of rest - your body heals when you sleep. Eat light meals like khichdi, soup, or boiled vegetables.
154
+
155
+ Now here's what concerns me: if your fever goes above 103°F, you develop severe headache, difficulty breathing, or if it continues beyond 7 days, please visit a clinic immediately. These could be signs of something more serious like dengue or typhoid, which need proper testing.
156
+
157
+ How are you feeling otherwise? Any body aches, chills, or other symptoms I should know about?"""
158
+
159
+ elif any(word in symptoms for word in ["cold", "cough", "flu"]):
160
+ return f"""Okay {name}, so you've been dealing with this for {duration}. Cold and flu can really drain your energy.
161
+
162
+ Here's what I want you to do:
163
+
164
+ Stay warm and rest as much as possible. Your immune system works best when you're sleeping.
165
+
166
+ Drink warm liquids - ginger tea with honey is excellent. It soothes the throat and honey has antibacterial properties.
167
+
168
+ For congestion, try steam inhalation 2-3 times a day. Just hot water in a bowl, put a towel over your head, and breathe in the steam for 5-10 minutes.
169
+
170
+ You can take an antihistamine like Cetirizine at night if the symptoms are disturbing your sleep.
171
+
172
+ Eat vitamin C rich foods - oranges, lemons, guavas. They boost immunity.
173
+
174
+ Most colds resolve in 7-10 days. But if you develop high fever, chest pain, or difficulty breathing, that's when you need to see me in person or visit a doctor immediately.
175
+
176
+ Are you able to eat properly? Any chest discomfort?"""
177
+
178
+ else:
179
+ return f"""I understand you're concerned about {session['symptoms']}, {name}. You've been dealing with this for {duration}, which I know must be worrying.
180
+
181
+ Let me help you with this. Based on what you've told me, here are some general recommendations:
182
+
183
+ 1. Keep track of your symptoms - note if they're getting better or worse
184
+ 2. Stay well hydrated - aim for 8-10 glasses of water daily
185
+ 3. Get adequate rest and avoid stress
186
+ 4. Eat balanced, nutritious meals
187
+
188
+ However, {name}, I want to be honest with you - some conditions really need a physical examination and possibly some tests. If your symptoms are severe, getting worse, or not improving in a few days, please visit a healthcare facility.
189
+
190
+ Is there anything specific that's worrying you the most? Or any other symptoms you haven't mentioned yet?"""
191
 
192
 
193
  # =======================================================
194
+ # Main Response Logic
195
  # =======================================================
196
  def doctor_response(user_message, session):
197
+ """Handle conversation flow naturally"""
198
  if not user_message or not user_message.strip():
199
+ return "I'm here, go ahead.", session
200
 
201
  user_message_clean = user_message.strip()
202
  user_message_lower = user_message_clean.lower()
203
 
204
+ # Emergency check
205
  if check_emergency(user_message_clean):
206
+ return """⚠️ I'm concerned about what you just told me. This sounds like it could be a medical emergency.
 
 
207
 
208
+ Please call emergency services RIGHT NOW:
209
+ - Pakistan: 1122 or 115
210
+ - Or go to the nearest emergency room immediately
 
211
 
212
+ Don't wait. Your safety is what matters most. This chat cannot handle emergencies.""", session
 
213
 
214
+ # Conversation flow
215
  try:
216
  if session["stage"] == "intro":
217
  session["stage"] = "ask_name"
218
+ return """Hello! Come in, come in. I'm Dr. Aiden.
219
+
220
+ Please, have a seat. Before we begin, I just want you to know this is an AI consultation for guidance only. For serious conditions, you should see a doctor in person.
221
+
222
+ Now, what's your name?""", session
223
 
224
  elif session["stage"] == "ask_name":
225
  session["name"] = extract_name(user_message_clean)
226
  session["stage"] = "ask_age"
227
+ return f"Nice to meet you, {session['name']}. And how old are you?", session
228
 
229
  elif session["stage"] == "ask_age":
230
  age = extract_age(user_message_clean)
231
  if age:
232
  session["age"] = age
233
  session["stage"] = "ask_gender"
234
+ return f"Alright, {session['age']} years old. Are you male or female?", session
235
+ return "Sorry, I didn't catch your age. Could you tell me in numbers? Like 25 or 30?", session
 
236
 
237
  elif session["stage"] == "ask_gender":
238
  if "male" in user_message_lower and "female" not in user_message_lower:
239
  session["gender"] = "male"
240
  elif "female" in user_message_lower:
241
+ session["gender"] = "female"
242
  else:
243
+ return "Male or female?", session
244
 
245
  session["stage"] = "ask_symptoms"
246
+ return f"Got it. So {session['name']}, tell me - what brings you here today? What's been bothering you?", session
247
 
248
  elif session["stage"] == "ask_symptoms":
249
  if len(user_message_clean) < 5:
250
+ return "Can you describe it a bit more? I want to understand what you're going through.", session
251
  session["symptoms"] = user_message_clean
252
  session["stage"] = "ask_duration"
253
+ return "I see. And when did this start? How long have you been feeling this way?", session
254
 
255
  elif session["stage"] == "ask_duration":
256
  session["duration"] = user_message_clean
257
  session["stage"] = "ask_medicine"
258
+ return "Okay. Are you taking any medicines for this right now? Any tablets or syrups?", session
259
 
260
  elif session["stage"] == "ask_medicine":
261
+ session["medication"] = user_message_clean if "no" not in user_message_lower else "No current medications"
262
  session["stage"] = "consult"
 
 
 
 
 
 
 
 
 
 
 
 
263
 
264
+ # Natural transition to consultation
265
+ return f"""Alright {session['name']}, let me understand this properly.
266
+
267
+ So you're {session['age']} years old, and you've been having {session['symptoms']} for about {session['duration']}. {"You're not taking anything for it right now" if "no" in user_message_lower else f"And you're currently taking {session['medication']}"}.
268
+
269
+ Let me share my thoughts with you...\n\n""" + generate_doctor_response(session, "What do you think about my condition and what should I do?"), session
270
 
271
  elif session["stage"] == "consult":
272
+ # Natural ongoing consultation
273
+
274
+ # Diet questions
275
+ if any(word in user_message_lower for word in ["diet", "food", "eat", "meal"]):
276
+ return get_diet_advice(session), session
277
+
278
+ # Medicine questions
279
+ if any(word in user_message_lower for word in ["medicine", "tablet", "drug", "medication", "panadol"]):
280
+ return get_medicine_advice(session), session
281
 
282
+ # General questions
283
+ return generate_doctor_response(session, user_message_clean), session
284
 
 
 
 
 
 
285
  except Exception as e:
286
+ print(f"Error: {e}")
287
+ return "Sorry, could you repeat that? I want to make sure I understand you correctly.", session
288
+
289
+
290
+ def get_diet_advice(session):
291
+ """Natural diet advice"""
292
+ name = session['name']
293
+ symptoms = session['symptoms'].lower()
294
+
295
+ if "fever" in symptoms:
296
+ return f"""Good question about diet, {name}. When you have a fever, your body needs energy but your digestion is weak.
297
+
298
+ Here's what I recommend:
299
+
300
+ **For breakfast**: Keep it light - maybe some oatmeal porridge or a boiled egg with a banana. Easy to digest.
301
+
302
+ **Lunch and dinner**: Khichdi is excellent - rice and dal together. Or you can have plain rice with some boiled vegetables or light chicken soup.
303
+
304
+ **Throughout the day**: This is very important - drink lots of fluids. Water, coconut water, lemon water. Your body loses water when you have fever.
305
+
306
+ **Avoid these**: No fried foods, no spicy food, no heavy curries. Your stomach can't handle them right now.
307
+
308
+ Little meals, multiple times a day. Don't force yourself to eat if you're not hungry, but definitely keep drinking fluids.
309
+
310
+ Does that make sense? Any other questions about food?"""
311
+
312
+ elif "cold" in symptoms or "cough" in symptoms:
313
+ return f"""Ah yes, diet is important for recovery, {name}.
314
+
315
+ When you have cold and cough:
316
+
317
+ **Hot is good**: Warm soups, especially chicken soup - it's not just comfort food, it actually helps with congestion. Ginger tea with honey is excellent.
318
+
319
+ **Fruits**: Oranges, kinnow, any citrus fruits. They have vitamin C which helps your immune system fight the infection.
320
+
321
+ **Regular meals**: Dal rice, roti sabzi - normal food is fine. Just make sure it's warm, not cold from the fridge.
322
+
323
+ **Avoid**: Cold drinks, ice cream, banana (can increase mucus), dairy products if you have lot of phlegm.
324
+
325
+ **Drink**: Warm water throughout the day. You can add a bit of honey and lemon to it.
326
+
327
+ And one home remedy - at night before sleeping, have a glass of warm milk with half teaspoon of turmeric. It helps with throat irritation.
328
+
329
+ Anything else you'd like to know?"""
330
+
331
+ else:
332
+ return f"""For what you're experiencing, {name}, I'd say maintain a balanced diet.
333
+
334
+ Eat fresh vegetables, fruits, whole grains. Include protein - dal, chicken, fish, eggs. Your body needs good nutrition to heal.
335
+
336
+ Stay hydrated - very important. At least 8-10 glasses of water daily.
337
+
338
+ Avoid processed foods, too much sugar, fried items.
339
+
340
+ Eat at regular times, don't skip meals.
341
+
342
+ Is there something specific about your diet you're concerned about?"""
343
+
344
+
345
+ def get_medicine_advice(session):
346
+ """Natural medicine advice"""
347
+ name = session['name']
348
+ symptoms = session['symptoms'].lower()
349
+
350
+ response = f"""Alright {name}, regarding medications:\n\n"""
351
+
352
+ if "fever" in symptoms:
353
+ response += """For your fever, you can take **Paracetamol 500mg** (Panadol is the common brand here).
354
+
355
+ Take one tablet every 6 hours, but only when your temperature is above 100°F. Don't take it more than 4 times in 24 hours.
356
+
357
+ Take it after eating something, even if just a few biscuits. Don't take it on empty stomach.
358
+
359
+ If the fever is not coming down with Paracetamol, or if it's going very high (above 103°F), that's a red flag. You need to see a doctor in person then."""
360
+
361
+ elif "cold" in symptoms or "cough" in symptoms:
362
+ response += """For cold and cough:
363
+
364
+ **For runny nose/sneezing**: Cetirizine 10mg, one tablet at night before sleeping. It'll help you rest better.
365
+
366
+ **For cough**: If it's dry cough - any cough syrup with dextromethorphan. If you have phlegm - syrup with guaifenesin (expectorant). Take as per bottle instructions.
367
+
368
+ **For blocked nose**: You can use saline nasal drops.
369
+
370
+ These are all over-the-counter, you can get them from any pharmacy.
371
+
372
+ But listen carefully - if you develop fever, chest pain, or difficulty breathing, stop these and consult a doctor immediately."""
373
+
374
+ else:
375
+ response += """I can give you general guidance, but I'd be more comfortable if you saw a doctor in person for proper examination and prescription.
376
+
377
+ Some conditions need specific tests or examinations before recommending medicines.
378
+
379
+ For now, stay comfortable, rest well, and monitor your symptoms. If anything worsens, please visit a clinic."""
380
+
381
+ response += "\n\nAny other questions for me?"
382
+ return response
383
 
384
 
385
  # =======================================================
 
387
  # =======================================================
388
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
389
  gr.HTML("""
390
+ <div style="text-align:center; background: linear-gradient(135deg, #2193b0 0%, #6dd5ed 100%); color:white; padding:30px; border-radius:15px;">
391
+ <h1 style="margin:0; font-size: 2.5em;">🩺 Dr. Aiden's Clinic</h1>
392
+ <p style="margin:10px 0 0 0; font-size: 1.2em;">Your friendly AI doctor - here to listen and help</p>
 
393
  </div>
394
  """)
395
 
 
396
  session_state = gr.State(create_initial_session)
397
 
398
  chatbot = gr.Chatbot(
399
+ label="💬 Consultation Room",
400
+ height=550,
401
  type='messages',
402
  avatar_images=(
403
  "https://cdn-icons-png.flaticon.com/512/706/706830.png",
 
407
 
408
  with gr.Row():
409
  user_input = gr.Textbox(
410
+ placeholder="Type your message here...",
411
+ label="",
412
  lines=2,
413
  scale=4
414
  )
415
 
416
  with gr.Row():
417
  send_btn = gr.Button("💬 Send", variant="primary", scale=1)
418
+ clear_btn = gr.Button("🔄 New Patient", variant="secondary", scale=1)
419
 
420
  gr.HTML("""
421
+ <div style="margin-top: 15px; padding: 12px; background-color: #fff3cd; border-radius: 8px; font-size: 0.9em;">
422
+ <strong>⚠️ Important:</strong> This is an AI simulation. Always consult a real doctor for medical conditions.
423
+ For emergencies call 1122 (Pakistan) or 911.
 
 
 
 
 
424
  </div>
425
  """)
426
 
427
  def respond(message, history, session):
 
428
  if history is None:
429
  history = []
 
430
  if not message or not message.strip():
431
  return "", history, session
432
 
 
438
  return "", history, updated_session
439
 
440
  def reset():
 
441
  return [], create_initial_session()
442
 
443
+ send_btn.click(respond, [user_input, chatbot, session_state], [user_input, chatbot, session_state])
444
+ user_input.submit(respond, [user_input, chatbot, session_state], [user_input, chatbot, session_state])
445
+ clear_btn.click(reset, None, [chatbot, session_state], queue=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
446
 
447
  if __name__ == "__main__":
448
+ print("🩺 Dr. Aiden's Clinic is now open...")
 
449
  demo.queue()
450
  demo.launch(share=True)