Update app.py
Browse files
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 |
-
|
| 9 |
-
|
| 10 |
-
tokenizer.pad_token
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
# =======================================================
|
| 24 |
-
#
|
| 25 |
# =======================================================
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
# =======================================================
|
| 37 |
-
# Helper
|
| 38 |
# =======================================================
|
| 39 |
def extract_name(text):
|
| 40 |
-
|
| 41 |
-
text = text.
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
# =======================================================
|
| 46 |
-
#
|
| 47 |
# =======================================================
|
| 48 |
-
def
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
-
return diet + "\n\nβοΈ *Note: This is general advice β not a substitute for medical care.*"
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 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-
|
| 200 |
-
<h1
|
| 201 |
-
<p
|
|
|
|
| 202 |
</div>
|
| 203 |
""")
|
| 204 |
-
|
|
|
|
|
|
|
|
|
|
| 205 |
chatbot = gr.Chatbot(
|
| 206 |
label="π¨ββοΈ Chat with Dr. Aiden",
|
| 207 |
-
height=
|
| 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 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
if history is None:
|
| 221 |
history = []
|
| 222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
history.append({"role": "user", "content": message})
|
| 224 |
history.append({"role": "assistant", "content": response})
|
| 225 |
-
|
| 226 |
-
|
|
|
|
| 227 |
def reset():
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|