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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +404 -165
app.py CHANGED
@@ -1,159 +1,223 @@
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
3
  import torch
 
4
 
 
 
 
5
  model_name = "augtoma/qCammel-13"
6
  print("Loading tokenizer and model...")
7
 
8
- tokenizer = AutoTokenizer.from_pretrained(model_name)
9
- if tokenizer.pad_token is None:
10
- tokenizer.pad_token = tokenizer.eos_token
11
-
12
- model = AutoModelForCausalLM.from_pretrained(
13
- model_name,
14
- device_map="auto",
15
- torch_dtype=torch.float16,
16
- trust_remote_code=True,
17
- low_cpu_mem_usage=True
18
- )
19
- model.eval()
20
- print("βœ… Model loaded successfully!")
 
 
 
 
21
 
22
 
23
  # =======================================================
24
- # Global Session Memory
25
  # =======================================================
26
- session = {
27
- "name": None,
28
- "age": None,
29
- "gender": None,
30
- "symptoms": None,
31
- "duration": None,
32
- "stage": "intro"
33
- }
 
 
 
 
 
 
34
 
35
 
36
  # =======================================================
37
- # Helper: Extract Name
38
  # =======================================================
39
  def extract_name(text):
40
- text = text.lower().replace("yes", "").replace("i am", "").replace("i'm", "")
41
- text = text.replace("my name is", "").replace("name", "").replace("is", "").strip()
42
- return text.title() if text else "Patient"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
 
45
  # =======================================================
46
- # Doctor Response Logic
47
  # =======================================================
48
- def doctor_response(user_message):
49
- global session
50
- user_message = user_message.strip().lower()
51
-
52
- # Step 1: Greeting
53
- if session["stage"] == "intro":
54
- session["stage"] = "ask_name"
55
- return "πŸ‘¨β€βš•οΈ Hello! I’m Dr. Aiden. May I know your name, please?"
56
-
57
- # Step 2: Get Name
58
- elif session["stage"] == "ask_name":
59
- session["name"] = extract_name(user_message)
60
- session["stage"] = "ask_age"
61
- return f"Nice to meet you, {session['name']}! How old are you?"
62
-
63
- # Step 3: Get Age
64
- elif session["stage"] == "ask_age":
65
- words = user_message.split()
66
- for w in words:
67
- if w.isdigit():
68
- session["age"] = int(w)
69
- session["stage"] = "ask_gender"
70
- return f"Got it, {session['name']}. Are you male or female?"
71
- return "Please tell me your age in numbers, like 20 or 25."
72
-
73
- # Step 4: Get Gender
74
- elif session["stage"] == "ask_gender":
75
- if "male" in user_message:
76
- session["gender"] = "male"
77
- elif "female" in user_message:
78
- session["gender"] = "female"
79
- else:
80
- return "Could you please specify whether you are male or female?"
81
- session["stage"] = "ask_symptoms"
82
- return f"Thanks, {session['name']}! So you're a {session['age']}-year-old {session['gender']}. What symptoms are you experiencing?"
83
-
84
- # Step 5: Get Symptoms
85
- elif session["stage"] == "ask_symptoms":
86
- session["symptoms"] = user_message
87
- session["stage"] = "ask_duration"
88
- return "Since when have you been feeling this way?"
89
-
90
- # Step 6: Duration
91
- elif session["stage"] == "ask_duration":
92
- session["duration"] = user_message
93
- session["stage"] = "ask_medicine"
94
- return "Got it. Are you taking any medications or treatments currently?"
95
-
96
- # Step 7: Medicine intake
97
- elif session["stage"] == "ask_medicine":
98
- session["medication"] = user_message
99
- session["stage"] = "consult"
100
- return "Thank you. Let’s discuss what could be going on and how you can manage it safely."
101
-
102
- # Step 8: Personalized Consultation
103
- elif session["stage"] == "consult":
104
- name = session["name"]
105
- age = session["age"]
106
- gender = session["gender"]
107
- symptoms = session.get("symptoms", "")
108
- duration = session.get("duration", "")
109
- medication = session.get("medication", "")
110
-
111
- # ------------- Handle diet-related questions -----------------
112
- if any(word in user_message for word in ["diet", "food", "meal", "eat", "nutrition"]):
113
- # Diet suggestions tailored to the condition
114
- if "fever" in symptoms:
115
- diet = (
116
- f"🍎 {name}, since you have a fever, try keeping your meals light and hydrating.\n\n"
117
- "- πŸ₯£ **Breakfast:** Oatmeal or boiled egg with fruit (like banana or apple)\n"
118
- "- 🍲 **Lunch:** Rice with lentil soup or boiled vegetables\n"
119
- "- πŸ› **Dinner:** Light soup or grilled chicken with plain rice\n"
120
- "- πŸ’§ **Hydration:** Drink 8–10 glasses of water, coconut water, or clear soups\n"
121
- "- 🚫 **Avoid:** Fried, oily, or spicy foods\n\n"
122
- "Eat small portions often β€” this helps your body recover faster."
123
- )
124
- elif "stomach" in symptoms or "vomit" in symptoms:
125
- diet = (
126
- f"πŸ₯— {name}, for stomach discomfort, stick to a **bland diet**:\n\n"
127
- "- 🍞 Toast, plain rice, boiled potatoes, or bananas\n"
128
- "- πŸ’§ Sip water, oral rehydration solution, or herbal tea\n"
129
- "- 🚫 Avoid milk, fried, or spicy foods\n"
130
- "- 🍌 Eat small meals to avoid nausea"
131
- )
132
- elif "cold" in symptoms or "flu" in symptoms or "cough" in symptoms:
133
- diet = (
134
- f"🍊 {name}, for flu or cold, focus on **immunity-boosting foods**:\n\n"
135
- "- πŸ‹ Citrus fruits, honey with warm water, and soups\n"
136
- "- 🍲 Chicken soup helps clear congestion\n"
137
- "- β˜• Ginger or green tea for throat relief\n"
138
- "- 🚫 Avoid sugary and chilled drinks"
139
- )
140
- else:
141
- diet = (
142
- f"πŸ₯— {name}, eat a balanced diet: fruits, vegetables, lean protein, and whole grains. "
143
- "Stay hydrated and avoid processed or fried foods."
144
- )
 
 
 
 
 
 
 
 
 
 
145
 
146
- return diet + "\n\nβš•οΈ *Note: This is general advice β€” not a substitute for medical care.*"
147
 
148
- # ----------------- Normal medical consultation ----------------
149
- prompt = f"""
150
- You are Dr. Aiden β€” a warm, caring, and professional doctor.
151
- You are consulting a {age}-year-old {gender} named {name}.
 
 
 
 
 
152
 
153
  Patient details:
154
- - Symptoms: {symptoms}
155
- - Duration: {duration}
156
- - Current medications: {medication}
157
 
158
  Now the patient says: "{user_message}"
159
 
@@ -164,10 +228,11 @@ Include:
164
  3. Simple home remedies or OTC medicines (if safe)
165
  4. Diet, rest, and hydration tips
166
  5. When to visit a real doctor
167
- 6. End with a reassuring tone
168
- """
169
 
 
170
  inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
 
171
  gen_cfg = GenerationConfig(
172
  temperature=0.7,
173
  top_p=0.9,
@@ -180,66 +245,240 @@ Include:
180
  with torch.no_grad():
181
  output = model.generate(**inputs, generation_config=gen_cfg)
182
 
 
183
  output_text = tokenizer.decode(output[0], skip_special_tokens=True)
184
- output_text = output_text.split("Doctor:")[-1].strip()
185
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  if not output_text.endswith((".", "!", "?")):
187
  output_text += "."
188
 
 
189
  output_text += "\n\nβš•οΈ *Note: This advice is AI-generated and not a substitute for professional medical care.*"
 
190
  return output_text
 
 
 
 
191
 
192
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
193
 
194
  # =======================================================
195
  # Gradio Interface
196
  # =======================================================
197
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
198
  gr.HTML("""
199
- <div style="text-align:center; background-color:#4C7DFF; color:white; padding:20px; border-radius:10px;">
200
- <h1>πŸ₯ Doctor Consultation with Dr. Aiden</h1>
201
- <p>AI-powered doctor interview β€” step-by-step and caring conversation</p>
 
202
  </div>
203
  """)
204
-
 
 
 
205
  chatbot = gr.Chatbot(
206
  label="πŸ‘¨β€βš•οΈ Chat with Dr. Aiden",
207
- height=550,
208
  type='messages',
209
  avatar_images=(
210
  "https://cdn-icons-png.flaticon.com/512/706/706830.png",
211
  "https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
212
  )
213
  )
214
-
215
- user_input = gr.Textbox(placeholder="Say 'Hi Doctor' to start your consultation...", label="Your Message", lines=2)
216
- send_btn = gr.Button("πŸ’¬ Send", variant="primary")
217
- clear_btn = gr.Button("🧹 New Consultation")
218
-
219
- def respond(message, history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  if history is None:
221
  history = []
222
- response = doctor_response(message)
 
 
 
 
 
223
  history.append({"role": "user", "content": message})
224
  history.append({"role": "assistant", "content": response})
225
- return "", history
226
-
 
227
  def reset():
228
- global session
229
- session = {
230
- "name": None,
231
- "age": None,
232
- "gender": None,
233
- "symptoms": None,
234
- "duration": None,
235
- "stage": "intro"
236
- }
237
- return []
238
- send_btn.click(respond, [user_input, chatbot], [user_input, chatbot])
239
- user_input.submit(respond, [user_input, chatbot], [user_input, chatbot])
240
- clear_btn.click(reset, None, chatbot, queue=False)
 
 
 
 
 
 
 
 
 
241
 
242
  if __name__ == "__main__":
243
- print("πŸ₯ Launching Dr. Aiden...")
 
244
  demo.queue()
245
- demo.launch(share=True)
 
1
  import gradio as gr
2
  from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
3
  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...")
11
 
12
+ try:
13
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
14
+ if tokenizer.pad_token is None:
15
+ tokenizer.pad_token = tokenizer.eos_token
16
+
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ model_name,
19
+ device_map="auto",
20
+ torch_dtype=torch.float16,
21
+ trust_remote_code=True,
22
+ low_cpu_mem_usage=True
23
+ )
24
+ model.eval()
25
+ print("βœ… Model loaded successfully!")
26
+ except Exception as e:
27
+ print(f"❌ Error loading model: {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,
87
+ "gender": None,
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
 
 
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,
 
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
  # =======================================================
393
  # Gradio Interface
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",
413
  "https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
414
  )
415
  )
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
+
449
+ response, updated_session = doctor_response(message, session)
450
+
451
  history.append({"role": "user", "content": message})
452
  history.append({"role": "assistant", "content": response})
453
+
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)