Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
| 3 |
import torch
|
|
|
|
| 4 |
|
| 5 |
# =======================================================
|
| 6 |
# Load Model
|
|
@@ -20,162 +21,152 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 20 |
low_cpu_mem_usage=True
|
| 21 |
)
|
| 22 |
model.eval()
|
| 23 |
-
print("✅ Model loaded successfully!")
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
# =======================================================
|
| 27 |
-
# Global Memory for Doctor Flow
|
| 28 |
-
# =======================================================
|
| 29 |
-
session = {"name": None, "age": None, "gender": None, "stage": "intro"}
|
| 30 |
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
# =======================================================
|
| 33 |
-
#
|
| 34 |
# =======================================================
|
| 35 |
-
|
| 36 |
-
# Remove filler words like "yes", "i am", "my name is"
|
| 37 |
-
text = text.lower().replace("yes", "").replace("i am", "").replace("i'm", "")
|
| 38 |
-
text = text.replace("name", "").replace("is", "").replace("it's", "")
|
| 39 |
-
text = text.strip()
|
| 40 |
-
# Capitalize nicely
|
| 41 |
-
return text.title() if text else "Patient"
|
| 42 |
-
|
| 43 |
|
| 44 |
# =======================================================
|
| 45 |
# Generate Doctor Response
|
| 46 |
# =======================================================
|
| 47 |
-
def
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
return "👨⚕️ Hello! I’m Dr. Aiden. May I know your name, please?"
|
| 55 |
-
|
| 56 |
-
# Step 2: Get Name
|
| 57 |
-
elif session["stage"] == "ask_name":
|
| 58 |
-
session["name"] = extract_name(user_message)
|
| 59 |
-
session["stage"] = "ask_age"
|
| 60 |
-
return f"Nice to meet you, {session['name']}! How old are you?"
|
| 61 |
-
|
| 62 |
-
# Step 3: Get Age
|
| 63 |
-
elif session["stage"] == "ask_age":
|
| 64 |
-
words = user_message.split()
|
| 65 |
-
for w in words:
|
| 66 |
-
if w.isdigit():
|
| 67 |
-
session["age"] = int(w)
|
| 68 |
-
session["stage"] = "ask_gender"
|
| 69 |
-
return f"Got it, {session['name']}. Are you male or female?"
|
| 70 |
-
return "Please tell me your age in numbers, like 20 or 25."
|
| 71 |
-
|
| 72 |
-
# Step 4: Get Gender
|
| 73 |
-
elif session["stage"] == "ask_gender":
|
| 74 |
-
if "male" in user_message.lower():
|
| 75 |
-
session["gender"] = "male"
|
| 76 |
-
elif "female" in user_message.lower():
|
| 77 |
-
session["gender"] = "female"
|
| 78 |
-
else:
|
| 79 |
-
return "Could you please specify whether you are male or female?"
|
| 80 |
-
|
| 81 |
-
session["stage"] = "consult"
|
| 82 |
-
return f"Thanks, {session['name']}! So you're a {session['age']}-year-old {session['gender']}. What brings you in today?"
|
| 83 |
-
|
| 84 |
-
# Step 5: Medical Consultation Mode
|
| 85 |
-
elif session["stage"] == "consult":
|
| 86 |
-
name = session["name"]
|
| 87 |
-
age = session["age"]
|
| 88 |
-
gender = session["gender"]
|
| 89 |
-
|
| 90 |
-
prompt = f"""
|
| 91 |
-
You are Dr. Aiden — a friendly, empathetic, and experienced doctor.
|
| 92 |
-
You are chatting casually with a {age}-year-old {gender} patient named {name}.
|
| 93 |
-
The patient is describing their health concern.
|
| 94 |
-
|
| 95 |
-
Respond like a real doctor would — empathetic, natural, and informative.
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
- Rest, hydration, and diet advice
|
| 102 |
-
- When to visit a real doctor
|
| 103 |
-
- End with reassurance
|
| 104 |
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
Doctor:"""
|
| 107 |
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
|
| 124 |
-
|
| 125 |
-
if not output_text.endswith((".", "!", "?")):
|
| 126 |
-
output_text += "."
|
| 127 |
-
output_text += "\n\n⚕️ *Note: This advice is AI-generated and not a substitute for professional medical care.*"
|
| 128 |
|
| 129 |
-
|
|
|
|
|
|
|
| 130 |
|
|
|
|
| 131 |
|
| 132 |
# =======================================================
|
| 133 |
-
# Gradio
|
| 134 |
# =======================================================
|
| 135 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 136 |
gr.HTML("""
|
| 137 |
-
<div style="
|
| 138 |
-
|
| 139 |
-
<
|
|
|
|
| 140 |
</div>
|
| 141 |
""")
|
| 142 |
|
| 143 |
chatbot = gr.Chatbot(
|
| 144 |
-
label="👨⚕️ Chat
|
| 145 |
-
height=
|
| 146 |
-
type='messages',
|
| 147 |
avatar_images=(
|
| 148 |
-
"https://cdn-icons-png.flaticon.com/512/706/706830.png",
|
| 149 |
-
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
|
| 150 |
-
)
|
| 151 |
)
|
| 152 |
|
| 153 |
-
user_input = gr.Textbox(
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
history = []
|
| 160 |
-
response = doctor_response(message)
|
| 161 |
-
history.append({"role": "user", "content": message})
|
| 162 |
-
history.append({"role": "assistant", "content": response})
|
| 163 |
-
return "", history
|
| 164 |
|
| 165 |
-
def
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
return
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
# =======================================================
|
| 176 |
-
# Launch
|
| 177 |
# =======================================================
|
| 178 |
if __name__ == "__main__":
|
| 179 |
-
print("
|
| 180 |
-
|
|
|
|
| 181 |
demo.launch(share=True)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
| 3 |
import torch
|
| 4 |
+
import time
|
| 5 |
|
| 6 |
# =======================================================
|
| 7 |
# Load Model
|
|
|
|
| 21 |
low_cpu_mem_usage=True
|
| 22 |
)
|
| 23 |
model.eval()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
print("✅ Model loaded successfully!")
|
| 26 |
+
print(f"📦 Device map: {model.hf_device_map}")
|
| 27 |
+
print(f"💻 Model device: {next(model.parameters()).device}")
|
| 28 |
|
| 29 |
# =======================================================
|
| 30 |
+
# Session memory (for patient info)
|
| 31 |
# =======================================================
|
| 32 |
+
patient_data = {"name": None, "age": None, "gender": None, "collected": False}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# =======================================================
|
| 35 |
# Generate Doctor Response
|
| 36 |
# =======================================================
|
| 37 |
+
def generate_response(user_message):
|
| 38 |
+
name, age, gender, collected = (
|
| 39 |
+
patient_data["name"],
|
| 40 |
+
patient_data["age"],
|
| 41 |
+
patient_data["gender"],
|
| 42 |
+
patient_data["collected"],
|
| 43 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
+
# Stage 1 – ask for name
|
| 46 |
+
if name is None:
|
| 47 |
+
patient_data["name"] = user_message.strip()
|
| 48 |
+
return f"👨⚕️ Hello! I’m Dr. Aiden. May I know your name, please?" if not name else f"Nice to meet you, {name}! How old are you?"
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# Stage 2 – ask for age
|
| 51 |
+
if age is None:
|
| 52 |
+
if user_message.strip().isdigit():
|
| 53 |
+
patient_data["age"] = user_message.strip()
|
| 54 |
+
return f"Got it, {name}. Are you male or female?"
|
| 55 |
+
else:
|
| 56 |
+
return "Please enter your age in numbers (e.g., 25)."
|
| 57 |
+
|
| 58 |
+
# Stage 3 – ask for gender
|
| 59 |
+
if gender is None:
|
| 60 |
+
gender_input = user_message.lower()
|
| 61 |
+
if "male" in gender_input:
|
| 62 |
+
patient_data["gender"] = "male"
|
| 63 |
+
elif "female" in gender_input:
|
| 64 |
+
patient_data["gender"] = "female"
|
| 65 |
+
else:
|
| 66 |
+
return "Please specify 'male' or 'female'."
|
| 67 |
+
return f"Thanks, {name}! So you're a {patient_data['age']}-year-old {patient_data['gender']}. What brings you in today?"
|
| 68 |
+
|
| 69 |
+
# Stage 4 – consult mode (medical questions)
|
| 70 |
+
if collected is False:
|
| 71 |
+
patient_data["collected"] = True
|
| 72 |
+
|
| 73 |
+
# Doctor consultation response
|
| 74 |
+
prompt = f"""
|
| 75 |
+
You are Dr. Aiden — a warm, professional, and empathetic medical doctor having a one-on-one text consultation.
|
| 76 |
+
|
| 77 |
+
The patient’s details:
|
| 78 |
+
- Name: {name}
|
| 79 |
+
- Age: {age}
|
| 80 |
+
- Gender: {gender}
|
| 81 |
+
|
| 82 |
+
You are now starting the medical discussion.
|
| 83 |
+
Respond naturally and fully — as if you are talking to a real patient for the first time about their symptoms.
|
| 84 |
+
|
| 85 |
+
Be sure to include:
|
| 86 |
+
1. A short, caring acknowledgment of the patient's situation
|
| 87 |
+
2. Possible causes (simple explanation)
|
| 88 |
+
3. Basic medicine or home remedy suggestion (only safe over-the-counter advice)
|
| 89 |
+
4. Rest, hydration, and nutrition guidance
|
| 90 |
+
5. When to consult a real doctor
|
| 91 |
+
6. A gentle closing line
|
| 92 |
+
7. End with a disclaimer.
|
| 93 |
+
|
| 94 |
+
Patient says: "{user_message}"
|
| 95 |
Doctor:"""
|
| 96 |
|
| 97 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
|
| 98 |
+
|
| 99 |
+
gen_config = GenerationConfig(
|
| 100 |
+
temperature=0.7,
|
| 101 |
+
top_p=0.92,
|
| 102 |
+
top_k=50,
|
| 103 |
+
do_sample=True,
|
| 104 |
+
max_new_tokens=400,
|
| 105 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 106 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 107 |
+
repetition_penalty=1.1,
|
| 108 |
+
no_repeat_ngram_size=3,
|
| 109 |
+
)
|
| 110 |
|
| 111 |
+
with torch.no_grad():
|
| 112 |
+
output_ids = model.generate(**inputs, generation_config=gen_config)
|
| 113 |
|
| 114 |
+
generated_text = tokenizer.decode(output_ids[0], skip_special_tokens=True).strip()
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
+
# Clean and add disclaimer if missing
|
| 117 |
+
if "⚕️" not in generated_text.lower():
|
| 118 |
+
generated_text += "\n\n⚕️ *This is AI-generated medical guidance, not a substitute for professional medical care.*"
|
| 119 |
|
| 120 |
+
return generated_text.strip()
|
| 121 |
|
| 122 |
# =======================================================
|
| 123 |
+
# Gradio UI
|
| 124 |
# =======================================================
|
| 125 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 126 |
gr.HTML("""
|
| 127 |
+
<div style="background:linear-gradient(135deg,#2b5876,#4e4376);color:white;
|
| 128 |
+
padding:20px;border-radius:10px;text-align:center;">
|
| 129 |
+
<h1>🏥 Your Consultation with Dr. Aiden</h1>
|
| 130 |
+
<p>AI-powered medical chat • Empathetic • Informative • Private</p>
|
| 131 |
</div>
|
| 132 |
""")
|
| 133 |
|
| 134 |
chatbot = gr.Chatbot(
|
| 135 |
+
label="👨⚕️ Doctor–Patient Chat",
|
| 136 |
+
height=500,
|
|
|
|
| 137 |
avatar_images=(
|
| 138 |
+
"https://cdn-icons-png.flaticon.com/512/706/706830.png", # patient
|
| 139 |
+
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png", # doctor
|
| 140 |
+
),
|
| 141 |
)
|
| 142 |
|
| 143 |
+
user_input = gr.Textbox(
|
| 144 |
+
placeholder="Describe your symptoms (e.g., 'I have a fever for 5 days')",
|
| 145 |
+
label="💬 Message Dr. Aiden",
|
| 146 |
+
lines=2,
|
| 147 |
+
)
|
| 148 |
|
| 149 |
+
send = gr.Button("💬 Send", variant="primary")
|
| 150 |
+
clear = gr.Button("🧹 New Consultation")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
+
def chat(user_message, history):
|
| 153 |
+
response = generate_response(user_message)
|
| 154 |
+
history = history + [[user_message, response]]
|
| 155 |
+
return "", history
|
| 156 |
|
| 157 |
+
def clear_memory():
|
| 158 |
+
patient_data.update({"name": None, "age": None, "gender": None, "collected": False})
|
| 159 |
+
return [], "👨⚕️ Hello! I’m Dr. Aiden. May I know your name, please?"
|
| 160 |
|
| 161 |
+
send.click(chat, [user_input, chatbot], [user_input, chatbot])
|
| 162 |
+
user_input.submit(chat, [user_input, chatbot], [user_input, chatbot])
|
| 163 |
+
clear.click(clear_memory, outputs=[chatbot, user_input])
|
| 164 |
|
| 165 |
# =======================================================
|
| 166 |
+
# Launch App
|
| 167 |
# =======================================================
|
| 168 |
if __name__ == "__main__":
|
| 169 |
+
print("=" * 60)
|
| 170 |
+
print("🏥 AI Doctor Chatbot: Dr. Aiden is now online...")
|
| 171 |
+
print("=" * 60)
|
| 172 |
demo.launch(share=True)
|