Update app.py
Browse files
app.py
CHANGED
|
@@ -1,450 +1,285 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
|
| 3 |
-
import
|
| 4 |
-
import
|
| 5 |
-
|
| 6 |
-
#
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
)
|
| 24 |
-
model.
|
| 25 |
-
|
| 26 |
-
except Exception as e:
|
| 27 |
-
print(f"❌ Error loading model: {e}")
|
| 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,
|
| 61 |
-
"gender": 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 |
-
|
| 91 |
-
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 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 |
-
)
|
| 108 |
-
|
| 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 |
-
|
| 135 |
-
return generate_fallback_response(session, user_message)
|
| 136 |
-
|
| 137 |
|
| 138 |
-
def
|
| 139 |
-
"""Generate a
|
| 140 |
-
|
| 141 |
-
symptoms = session['symptoms'].lower()
|
| 142 |
-
duration = session['duration']
|
| 143 |
|
| 144 |
-
|
| 145 |
-
return f"""I can see you've had this fever for {duration}, {name}. That's quite uncomfortable, I'm sure.
|
| 146 |
|
| 147 |
-
|
|
|
|
| 148 |
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
|
|
|
| 152 |
|
| 153 |
-
|
|
|
|
| 154 |
|
| 155 |
-
|
|
|
|
| 156 |
|
| 157 |
-
|
| 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 |
-
|
|
|
|
| 163 |
|
| 164 |
-
|
|
|
|
| 165 |
|
| 166 |
-
|
|
|
|
| 167 |
|
| 168 |
-
|
|
|
|
| 169 |
|
| 170 |
-
|
|
|
|
| 171 |
|
| 172 |
-
|
|
|
|
| 173 |
|
| 174 |
-
|
| 175 |
|
| 176 |
-
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
#
|
| 194 |
-
|
| 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 |
-
|
| 202 |
-
|
| 203 |
|
| 204 |
-
|
| 205 |
-
|
| 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 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 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 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 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 |
-
|
| 265 |
-
|
| 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 |
-
|
| 272 |
-
|
|
|
|
| 273 |
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 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 |
-
# =======================================================
|
| 386 |
-
# Gradio Interface
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 397 |
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
type='messages',
|
| 402 |
-
avatar_images=(
|
| 403 |
-
"https://cdn-icons-png.flaticon.com/512/706/706830.png",
|
| 404 |
-
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
|
| 405 |
-
)
|
| 406 |
)
|
| 407 |
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 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 |
|
| 433 |
-
|
|
|
|
| 434 |
|
| 435 |
-
|
| 436 |
-
|
|
|
|
| 437 |
|
| 438 |
-
return "",
|
|
|
|
|
|
|
|
|
|
| 439 |
|
| 440 |
-
|
| 441 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
|
|
|
| 446 |
|
|
|
|
| 447 |
if __name__ == "__main__":
|
| 448 |
-
print("🩺 Dr. Aiden's Clinic is now open...")
|
| 449 |
-
demo.queue()
|
| 450 |
demo.launch(share=True)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import google.generativeai as genai
|
| 3 |
+
import os
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
# Set your Gemini API Key securely
|
| 7 |
+
os.environ["GOOGLE_API_KEY"] = "AIzaSyDwMK08RcUvg9JomaJSuX9XT3BGNasQk5M"
|
| 8 |
+
|
| 9 |
+
# Configure Gemini client
|
| 10 |
+
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
| 11 |
+
|
| 12 |
+
# Using Gemini 2.5 Flash
|
| 13 |
+
MODEL_ID = "gemini-2.0-flash-exp"
|
| 14 |
+
|
| 15 |
+
# System prompt for the AI Doctor
|
| 16 |
+
DOCTOR_SYSTEM_PROMPT = """You are Dr. AI Assistant, a professional and empathetic medical doctor conducting a thorough patient consultation.
|
| 17 |
+
|
| 18 |
+
YOUR CONSULTATION PROCESS:
|
| 19 |
+
1. **Initial Greeting & Personal Details Collection**:
|
| 20 |
+
- Greet the patient warmly
|
| 21 |
+
- Ask for: Name, Age, Gender, Contact details
|
| 22 |
+
- Ask about occupation and lifestyle
|
| 23 |
+
|
| 24 |
+
2. **Medical History**:
|
| 25 |
+
- Ask about chief complaints (main symptoms)
|
| 26 |
+
- Duration and severity of symptoms
|
| 27 |
+
- Past medical history
|
| 28 |
+
- Current medications
|
| 29 |
+
- Allergies
|
| 30 |
+
- Family medical history
|
| 31 |
+
- Previous surgeries or hospitalizations
|
| 32 |
+
|
| 33 |
+
3. **Detailed Symptom Analysis**:
|
| 34 |
+
- Ask specific questions about each symptom
|
| 35 |
+
- Pain level (1-10 scale)
|
| 36 |
+
- Aggravating and relieving factors
|
| 37 |
+
- Associated symptoms
|
| 38 |
+
|
| 39 |
+
4. **Lifestyle Assessment**:
|
| 40 |
+
- Diet and eating habits
|
| 41 |
+
- Exercise routine
|
| 42 |
+
- Sleep patterns
|
| 43 |
+
- Stress levels
|
| 44 |
+
- Smoking/alcohol consumption
|
| 45 |
+
- Water intake
|
| 46 |
+
|
| 47 |
+
5. **Physical Examination Questions** (virtual):
|
| 48 |
+
- Ask about vital signs if known (BP, temperature, pulse)
|
| 49 |
+
- Visible symptoms
|
| 50 |
+
- Any recent changes in body
|
| 51 |
+
|
| 52 |
+
6. **Provide Comprehensive Recommendations**:
|
| 53 |
+
- Preliminary assessment
|
| 54 |
+
- Dietary recommendations
|
| 55 |
+
- Lifestyle modifications
|
| 56 |
+
- Exercise suggestions
|
| 57 |
+
- Medication suggestions (with disclaimer)
|
| 58 |
+
- When to seek immediate medical attention
|
| 59 |
+
- Follow-up advice
|
| 60 |
+
|
| 61 |
+
7. **Generate Summary** (when patient requests):
|
| 62 |
+
- Patient details
|
| 63 |
+
- Chief complaints
|
| 64 |
+
- Medical history
|
| 65 |
+
- Assessment
|
| 66 |
+
- Recommendations (diet, lifestyle, medications)
|
| 67 |
+
- Disclaimer about consulting a physical doctor
|
| 68 |
+
|
| 69 |
+
IMPORTANT GUIDELINES:
|
| 70 |
+
- Be professional, empathetic, and reassuring
|
| 71 |
+
- **CRITICAL: Ask ONLY ONE question at a time - NEVER ask multiple questions in a single response**
|
| 72 |
+
- Wait for the patient's answer before asking the next question
|
| 73 |
+
- Use medical terminology but explain in simple terms
|
| 74 |
+
- Always include disclaimer that this is preliminary advice
|
| 75 |
+
- Recommend seeing a physical doctor for serious conditions
|
| 76 |
+
- Show concern and empathy
|
| 77 |
+
- Be thorough but not overwhelming
|
| 78 |
+
- Keep the conversation natural and flowing like a real doctor-patient interaction
|
| 79 |
+
|
| 80 |
+
DISCLAIMER TO INCLUDE:
|
| 81 |
+
"⚠️ Please note: This is an AI-powered preliminary consultation. For accurate diagnosis and treatment, please consult a licensed medical professional in person. In case of emergency, call emergency services immediately."
|
| 82 |
+
|
| 83 |
+
Start by greeting the patient and asking for their name."""
|
| 84 |
+
|
| 85 |
+
def initialize_chat():
|
| 86 |
+
"""Initialize the Gemini chat with doctor system prompt"""
|
| 87 |
+
model = genai.GenerativeModel(
|
| 88 |
+
model_name=MODEL_ID,
|
| 89 |
+
system_instruction=DOCTOR_SYSTEM_PROMPT
|
| 90 |
)
|
| 91 |
+
chat = model.start_chat(history=[])
|
| 92 |
+
return chat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
+
# Global chat instance
|
| 95 |
+
chat_session = initialize_chat()
|
| 96 |
|
| 97 |
+
def chat_with_doctor(message, history):
|
| 98 |
+
"""Handle patient messages and get doctor's response"""
|
| 99 |
+
global chat_session
|
| 100 |
+
|
| 101 |
+
try:
|
| 102 |
+
# Send patient message to doctor
|
| 103 |
+
response = chat_session.send_message(message)
|
| 104 |
+
doctor_response = response.text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
return doctor_response
|
| 107 |
+
|
| 108 |
except Exception as e:
|
| 109 |
+
return f"I apologize, but I encountered an error: {str(e)}. Please try again or restart the consultation."
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
def generate_consultation_summary(history):
|
| 112 |
+
"""Generate a comprehensive summary of the consultation"""
|
| 113 |
+
global chat_session
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
summary_request = """Please generate a comprehensive consultation summary in the following format:
|
|
|
|
| 116 |
|
| 117 |
+
📋 **MEDICAL CONSULTATION SUMMARY**
|
| 118 |
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 119 |
|
| 120 |
+
**Patient Information:**
|
| 121 |
+
- Name: [name]
|
| 122 |
+
- Age: [age]
|
| 123 |
+
- Gender: [gender]
|
| 124 |
+
- Date of Consultation: [current date]
|
| 125 |
|
| 126 |
+
**Chief Complaints:**
|
| 127 |
+
[List main symptoms and concerns]
|
| 128 |
|
| 129 |
+
**Medical History:**
|
| 130 |
+
[Relevant medical history]
|
| 131 |
|
| 132 |
+
**Assessment:**
|
| 133 |
+
[Your preliminary assessment]
|
| 134 |
|
| 135 |
+
**Recommendations:**
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
1. **Dietary Recommendations:**
|
| 138 |
+
[Specific diet advice]
|
| 139 |
|
| 140 |
+
2. **Lifestyle Modifications:**
|
| 141 |
+
[Lifestyle changes needed]
|
| 142 |
|
| 143 |
+
3. **Exercise & Physical Activity:**
|
| 144 |
+
[Exercise recommendations]
|
| 145 |
|
| 146 |
+
4. **Medication Suggestions:**
|
| 147 |
+
[If any - with disclaimer]
|
| 148 |
|
| 149 |
+
5. **Follow-up Care:**
|
| 150 |
+
[When to seek medical attention]
|
| 151 |
|
| 152 |
+
**Important Notes:**
|
| 153 |
+
⚠️ This is a preliminary AI consultation. Please consult a licensed medical doctor for accurate diagnosis and treatment.
|
| 154 |
|
| 155 |
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
| 156 |
|
| 157 |
+
Generated by Dr. AI Assistant"""
|
| 158 |
|
| 159 |
+
try:
|
| 160 |
+
response = chat_session.send_message(summary_request)
|
| 161 |
+
return response.text
|
| 162 |
+
except Exception as e:
|
| 163 |
+
return f"Error generating summary: {str(e)}"
|
| 164 |
+
|
| 165 |
+
def restart_consultation():
|
| 166 |
+
"""Restart the consultation with a fresh session"""
|
| 167 |
+
global chat_session
|
| 168 |
+
chat_session = initialize_chat()
|
| 169 |
+
return [], "Consultation restarted. Please tell me your name to begin."
|
| 170 |
+
|
| 171 |
+
# Create Gradio Interface
|
| 172 |
+
with gr.Blocks(title="AI Doctor Consultation", theme=gr.themes.Soft()) as demo:
|
| 173 |
+
gr.Markdown("""
|
| 174 |
+
# 🩺 AI Doctor Consultation System
|
| 175 |
+
### Professional Medical Consultation with Dr. AI Assistant
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
+
Welcome! I'm Dr. AI Assistant, here to conduct a thorough medical consultation.
|
| 178 |
+
I'll ask about your symptoms, medical history, lifestyle, and provide comprehensive recommendations.
|
| 179 |
|
| 180 |
+
**⚠️ Important:** This is a preliminary consultation. Always consult a licensed physician for proper diagnosis and treatment.
|
| 181 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
with gr.Row():
|
| 184 |
+
with gr.Column(scale=4):
|
| 185 |
+
chatbot = gr.Chatbot(
|
| 186 |
+
height=500,
|
| 187 |
+
show_label=False,
|
| 188 |
+
avatar_images=(None, "https://api.dicebear.com/7.x/bottts/svg?seed=doctor"),
|
| 189 |
+
bubble_full_width=False
|
| 190 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
+
with gr.Row():
|
| 193 |
+
msg = gr.Textbox(
|
| 194 |
+
placeholder="Type your message here...",
|
| 195 |
+
show_label=False,
|
| 196 |
+
scale=4
|
| 197 |
+
)
|
| 198 |
+
send_btn = gr.Button("Send 📤", scale=1, variant="primary")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
+
with gr.Row():
|
| 201 |
+
summary_btn = gr.Button("📋 Generate Consultation Summary", variant="secondary")
|
| 202 |
+
clear_btn = gr.Button("🔄 Restart Consultation", variant="stop")
|
|
|
|
|
|
|
|
|
|
| 203 |
|
| 204 |
+
with gr.Column(scale=1):
|
| 205 |
+
gr.Markdown("""
|
| 206 |
+
### 📌 Consultation Guide
|
| 207 |
|
| 208 |
+
**What I'll ask about:**
|
| 209 |
+
- Personal details
|
| 210 |
+
- Chief complaints
|
| 211 |
+
- Medical history
|
| 212 |
+
- Current medications
|
| 213 |
+
- Lifestyle habits
|
| 214 |
+
- Diet & exercise
|
| 215 |
|
| 216 |
+
**I'll provide:**
|
| 217 |
+
- Preliminary assessment
|
| 218 |
+
- Dietary advice
|
| 219 |
+
- Lifestyle changes
|
| 220 |
+
- Exercise plan
|
| 221 |
+
- Medication suggestions
|
| 222 |
+
- Follow-up guidance
|
| 223 |
|
| 224 |
+
**Commands:**
|
| 225 |
+
- Type normally to chat
|
| 226 |
+
- Click "Generate Summary" for full report
|
| 227 |
+
- Click "Restart" for new consultation
|
| 228 |
+
|
| 229 |
+
⚕️ *Be honest and detailed for best advice*
|
| 230 |
+
""")
|
| 231 |
+
|
| 232 |
+
summary_output = gr.Textbox(
|
| 233 |
+
label="📋 Consultation Summary",
|
| 234 |
+
placeholder="Click 'Generate Summary' after consultation",
|
| 235 |
+
lines=15,
|
| 236 |
+
max_lines=20
|
| 237 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 238 |
|
| 239 |
+
# Auto-start conversation
|
| 240 |
+
def start_conversation():
|
| 241 |
+
initial_message = "Hello! I'm Dr. AI Assistant. I'm here to help you today. Let's start with some basic information.\n\n👤 May I have your name, please?"
|
| 242 |
+
return [[None, initial_message]]
|
| 243 |
|
| 244 |
+
demo.load(
|
| 245 |
+
start_conversation,
|
| 246 |
+
outputs=[chatbot]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
)
|
| 248 |
|
| 249 |
+
# Handle send message
|
| 250 |
+
def respond(message, chat_history):
|
| 251 |
+
if not message.strip():
|
| 252 |
+
return "", chat_history
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
|
| 254 |
+
# Add user message
|
| 255 |
+
chat_history.append((message, None))
|
| 256 |
|
| 257 |
+
# Get doctor response
|
| 258 |
+
bot_response = chat_with_doctor(message, chat_history)
|
| 259 |
+
chat_history[-1] = (message, bot_response)
|
| 260 |
|
| 261 |
+
return "", chat_history
|
| 262 |
+
|
| 263 |
+
msg.submit(respond, [msg, chatbot], [msg, chatbot])
|
| 264 |
+
send_btn.click(respond, [msg, chatbot], [msg, chatbot])
|
| 265 |
|
| 266 |
+
# Generate summary
|
| 267 |
+
summary_btn.click(
|
| 268 |
+
lambda history: generate_consultation_summary(history),
|
| 269 |
+
inputs=[chatbot],
|
| 270 |
+
outputs=[summary_output]
|
| 271 |
+
)
|
| 272 |
+
|
| 273 |
+
# Restart consultation
|
| 274 |
+
def restart_and_update():
|
| 275 |
+
new_history, greeting = restart_consultation()
|
| 276 |
+
return [[None, greeting]], ""
|
| 277 |
|
| 278 |
+
clear_btn.click(
|
| 279 |
+
restart_and_update,
|
| 280 |
+
outputs=[chatbot, summary_output]
|
| 281 |
+
)
|
| 282 |
|
| 283 |
+
# Launch the app
|
| 284 |
if __name__ == "__main__":
|
|
|
|
|
|
|
| 285 |
demo.launch(share=True)
|