Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
| 3 |
import torch
|
| 4 |
-
import time
|
| 5 |
|
| 6 |
# =======================================================
|
| 7 |
# Load Model
|
|
@@ -21,152 +20,180 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
| 21 |
low_cpu_mem_usage=True
|
| 22 |
)
|
| 23 |
model.eval()
|
| 24 |
-
|
| 25 |
print("β
Model loaded successfully!")
|
| 26 |
-
|
| 27 |
-
print(f"π» Model device: {next(model.parameters()).device}")
|
| 28 |
|
| 29 |
# =======================================================
|
| 30 |
-
# Session
|
| 31 |
# =======================================================
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
# =======================================================
|
| 35 |
-
#
|
| 36 |
# =======================================================
|
| 37 |
-
def
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 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 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
else:
|
| 66 |
-
return "
|
| 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 |
Doctor:"""
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
eos_token_id=tokenizer.eos_token_id,
|
| 107 |
-
repetition_penalty=1.1,
|
| 108 |
-
no_repeat_ngram_size=3,
|
| 109 |
-
)
|
| 110 |
|
| 111 |
-
|
| 112 |
-
|
| 113 |
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
-
|
| 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
|
| 124 |
# =======================================================
|
| 125 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 126 |
gr.HTML("""
|
| 127 |
-
<div style="background
|
| 128 |
-
|
| 129 |
-
<
|
| 130 |
-
<p>AI-powered medical chat β’ Empathetic β’ Informative β’ Private</p>
|
| 131 |
</div>
|
| 132 |
""")
|
| 133 |
|
| 134 |
chatbot = gr.Chatbot(
|
| 135 |
-
label="π¨ββοΈ
|
| 136 |
-
height=
|
|
|
|
| 137 |
avatar_images=(
|
| 138 |
-
"https://cdn-icons-png.flaticon.com/512/706/706830.png",
|
| 139 |
-
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
|
| 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 |
-
|
| 150 |
-
|
|
|
|
| 151 |
|
| 152 |
-
def
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
| 155 |
return "", history
|
| 156 |
|
| 157 |
-
def
|
| 158 |
-
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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("
|
| 170 |
-
|
| 171 |
-
print("=" * 60)
|
| 172 |
demo.launch(share=True)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
|
| 3 |
import torch
|
|
|
|
| 4 |
|
| 5 |
# =======================================================
|
| 6 |
# Load Model
|
|
|
|
| 20 |
low_cpu_mem_usage=True
|
| 21 |
)
|
| 22 |
model.eval()
|
|
|
|
| 23 |
print("β
Model loaded successfully!")
|
| 24 |
+
|
|
|
|
| 25 |
|
| 26 |
# =======================================================
|
| 27 |
+
# Global Session Memory
|
| 28 |
# =======================================================
|
| 29 |
+
session = {
|
| 30 |
+
"name": None,
|
| 31 |
+
"age": None,
|
| 32 |
+
"gender": None,
|
| 33 |
+
"symptoms": None,
|
| 34 |
+
"duration": None,
|
| 35 |
+
"stage": "intro"
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
|
| 39 |
# =======================================================
|
| 40 |
+
# Helper: Extract Name
|
| 41 |
# =======================================================
|
| 42 |
+
def extract_name(text):
|
| 43 |
+
text = text.lower().replace("yes", "").replace("i am", "").replace("i'm", "")
|
| 44 |
+
text = text.replace("my name is", "").replace("name", "").replace("is", "").strip()
|
| 45 |
+
return text.title() if text else "Patient"
|
|
|
|
|
|
|
|
|
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
# =======================================================
|
| 49 |
+
# Doctor Response Logic
|
| 50 |
+
# =======================================================
|
| 51 |
+
def doctor_response(user_message):
|
| 52 |
+
global session
|
| 53 |
+
user_message = user_message.strip()
|
| 54 |
+
|
| 55 |
+
# Intro
|
| 56 |
+
if session["stage"] == "intro":
|
| 57 |
+
session["stage"] = "ask_name"
|
| 58 |
+
return "π¨ββοΈ Hello! Iβm Dr. Aiden. May I know your name, please?"
|
| 59 |
+
|
| 60 |
+
# Ask Name
|
| 61 |
+
elif session["stage"] == "ask_name":
|
| 62 |
+
session["name"] = extract_name(user_message)
|
| 63 |
+
session["stage"] = "ask_age"
|
| 64 |
+
return f"Nice to meet you, {session['name']}! How old are you?"
|
| 65 |
+
|
| 66 |
+
# Ask Age
|
| 67 |
+
elif session["stage"] == "ask_age":
|
| 68 |
+
words = user_message.split()
|
| 69 |
+
for w in words:
|
| 70 |
+
if w.isdigit():
|
| 71 |
+
session["age"] = int(w)
|
| 72 |
+
session["stage"] = "ask_gender"
|
| 73 |
+
return f"Got it, {session['name']}. Are you male or female?"
|
| 74 |
+
return "Please tell me your age in numbers, like 20 or 25."
|
| 75 |
+
|
| 76 |
+
# Ask Gender
|
| 77 |
+
elif session["stage"] == "ask_gender":
|
| 78 |
+
if "male" in user_message.lower():
|
| 79 |
+
session["gender"] = "male"
|
| 80 |
+
elif "female" in user_message.lower():
|
| 81 |
+
session["gender"] = "female"
|
| 82 |
else:
|
| 83 |
+
return "Could you please specify whether you are male or female?"
|
| 84 |
+
session["stage"] = "ask_symptoms"
|
| 85 |
+
return f"Thanks, {session['name']}! So you're a {session['age']}-year-old {session['gender']}. What symptoms are you experiencing?"
|
| 86 |
+
|
| 87 |
+
# Ask Symptoms
|
| 88 |
+
elif session["stage"] == "ask_symptoms":
|
| 89 |
+
session["symptoms"] = user_message
|
| 90 |
+
session["stage"] = "ask_duration"
|
| 91 |
+
return "Since when have you been feeling this way?"
|
| 92 |
+
|
| 93 |
+
# Ask Duration
|
| 94 |
+
elif session["stage"] == "ask_duration":
|
| 95 |
+
session["duration"] = user_message
|
| 96 |
+
session["stage"] = "consult"
|
| 97 |
+
return "Got it. Are you taking any medications or treatments currently?"
|
| 98 |
+
|
| 99 |
+
# Consultation
|
| 100 |
+
elif session["stage"] == "consult":
|
| 101 |
+
name = session["name"]
|
| 102 |
+
age = session["age"]
|
| 103 |
+
gender = session["gender"]
|
| 104 |
+
symptoms = session["symptoms"]
|
| 105 |
+
duration = session["duration"]
|
| 106 |
+
|
| 107 |
+
prompt = f"""
|
| 108 |
+
You are Dr. Aiden β a warm, friendly, and professional doctor having an interview-style consultation.
|
| 109 |
+
The patient is a {age}-year-old {gender} named {name}.
|
| 110 |
+
They have been feeling {symptoms} for {duration}.
|
| 111 |
+
They said: "{user_message}"
|
| 112 |
+
|
| 113 |
+
Respond like a real doctor β show empathy, analyze the symptoms, suggest likely causes, give simple medication and home care advice.
|
| 114 |
+
|
| 115 |
+
Include:
|
| 116 |
+
1. Acknowledge their discomfort.
|
| 117 |
+
2. Explain possible causes in simple terms.
|
| 118 |
+
3. Recommend over-the-counter medicines (if safe).
|
| 119 |
+
4. Suggest food, hydration, and rest tips.
|
| 120 |
+
5. Warn when to visit a real doctor.
|
| 121 |
+
6. End with gentle reassurance.
|
| 122 |
+
|
| 123 |
Doctor:"""
|
| 124 |
|
| 125 |
+
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
|
| 126 |
+
gen_cfg = GenerationConfig(
|
| 127 |
+
temperature=0.7,
|
| 128 |
+
top_p=0.9,
|
| 129 |
+
max_new_tokens=350,
|
| 130 |
+
repetition_penalty=1.1,
|
| 131 |
+
pad_token_id=tokenizer.pad_token_id,
|
| 132 |
+
eos_token_id=tokenizer.eos_token_id
|
| 133 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
with torch.no_grad():
|
| 136 |
+
output = model.generate(**inputs, generation_config=gen_cfg)
|
| 137 |
|
| 138 |
+
output_text = tokenizer.decode(output[0], skip_special_tokens=True)
|
| 139 |
+
output_text = output_text.split("Doctor:")[-1].strip()
|
| 140 |
+
if not output_text.endswith((".", "!", "?")):
|
| 141 |
+
output_text += "."
|
| 142 |
+
output_text += "\n\nβοΈ *Note: This advice is AI-generated and not a substitute for professional medical care.*"
|
| 143 |
|
| 144 |
+
return output_text
|
|
|
|
|
|
|
| 145 |
|
|
|
|
| 146 |
|
| 147 |
# =======================================================
|
| 148 |
+
# Gradio Interface
|
| 149 |
# =======================================================
|
| 150 |
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 151 |
gr.HTML("""
|
| 152 |
+
<div style="text-align:center; background-color:#4C7DFF; color:white; padding:20px; border-radius:10px;">
|
| 153 |
+
<h1>π₯ Doctor Consultation with Dr. Aiden</h1>
|
| 154 |
+
<p>AI-powered doctor interview β step-by-step and caring conversation</p>
|
|
|
|
| 155 |
</div>
|
| 156 |
""")
|
| 157 |
|
| 158 |
chatbot = gr.Chatbot(
|
| 159 |
+
label="π¨ββοΈ Chat with Dr. Aiden",
|
| 160 |
+
height=550,
|
| 161 |
+
type='messages',
|
| 162 |
avatar_images=(
|
| 163 |
+
"https://cdn-icons-png.flaticon.com/512/706/706830.png",
|
| 164 |
+
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png"
|
| 165 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
)
|
| 167 |
|
| 168 |
+
user_input = gr.Textbox(placeholder="Say 'Hi Doctor' to start your consultation...", label="Your Message", lines=2)
|
| 169 |
+
send_btn = gr.Button("π¬ Send", variant="primary")
|
| 170 |
+
clear_btn = gr.Button("π§Ή New Consultation")
|
| 171 |
|
| 172 |
+
def respond(message, history):
|
| 173 |
+
if history is None:
|
| 174 |
+
history = []
|
| 175 |
+
response = doctor_response(message)
|
| 176 |
+
history.append({"role": "user", "content": message})
|
| 177 |
+
history.append({"role": "assistant", "content": response})
|
| 178 |
return "", history
|
| 179 |
|
| 180 |
+
def reset():
|
| 181 |
+
global session
|
| 182 |
+
session = {
|
| 183 |
+
"name": None,
|
| 184 |
+
"age": None,
|
| 185 |
+
"gender": None,
|
| 186 |
+
"symptoms": None,
|
| 187 |
+
"duration": None,
|
| 188 |
+
"stage": "intro"
|
| 189 |
+
}
|
| 190 |
+
return []
|
| 191 |
+
|
| 192 |
+
send_btn.click(respond, [user_input, chatbot], [user_input, chatbot])
|
| 193 |
+
user_input.submit(respond, [user_input, chatbot], [user_input, chatbot])
|
| 194 |
+
clear_btn.click(reset, None, chatbot, queue=False)
|
| 195 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
if __name__ == "__main__":
|
| 197 |
+
print("π₯ Launching Dr. Aiden...")
|
| 198 |
+
demo.queue()
|
|
|
|
| 199 |
demo.launch(share=True)
|