Update app.py
Browse files
app.py
CHANGED
|
@@ -28,50 +28,55 @@ print(f"Model device: {next(model.parameters()).device}")
|
|
| 28 |
|
| 29 |
|
| 30 |
# =======================================================
|
| 31 |
-
# Generate
|
| 32 |
# =======================================================
|
| 33 |
def generate_doctor_response(history):
|
| 34 |
user_message = history[-1]["content"]
|
| 35 |
|
| 36 |
if not user_message.strip():
|
| 37 |
-
history.append({"role": "assistant", "content": "
|
| 38 |
yield history
|
| 39 |
return
|
| 40 |
|
| 41 |
-
#
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
|
| 52 |
-
-
|
| 53 |
-
-
|
| 54 |
-
-
|
| 55 |
-
-
|
| 56 |
-
-
|
| 57 |
-
- End with a simple disclaimer
|
| 58 |
|
| 59 |
-
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
# Tokenize input
|
| 64 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
|
| 65 |
|
| 66 |
gen_config = GenerationConfig(
|
| 67 |
-
temperature=0.
|
| 68 |
-
top_p=0.
|
| 69 |
-
top_k=
|
| 70 |
do_sample=True,
|
| 71 |
-
max_new_tokens=
|
| 72 |
pad_token_id=tokenizer.pad_token_id,
|
| 73 |
eos_token_id=tokenizer.eos_token_id,
|
| 74 |
-
repetition_penalty=1.
|
| 75 |
no_repeat_ngram_size=3
|
| 76 |
)
|
| 77 |
|
|
@@ -84,76 +89,59 @@ Your response:"""
|
|
| 84 |
response = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
| 85 |
|
| 86 |
# Clean response
|
| 87 |
-
response =
|
| 88 |
|
| 89 |
# Stream response token by token
|
| 90 |
history.append({"role": "assistant", "content": ""})
|
| 91 |
-
for i in range(0, len(response),
|
| 92 |
-
chunk = response[:i +
|
| 93 |
history[-1]["content"] = chunk + "β"
|
| 94 |
yield history.copy()
|
| 95 |
-
time.sleep(0.
|
| 96 |
|
| 97 |
history[-1]["content"] = response
|
| 98 |
yield history
|
| 99 |
|
| 100 |
|
| 101 |
-
def
|
| 102 |
-
"""Clean
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
response_lower = response.lower()
|
| 107 |
-
for prefix in
|
| 108 |
if response_lower.startswith(prefix):
|
| 109 |
response = response[len(prefix):].strip()
|
| 110 |
-
response = response.lstrip(',').strip()
|
| 111 |
break
|
| 112 |
|
| 113 |
-
#
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
should_skip = False
|
| 122 |
-
for pattern in skip_patterns:
|
| 123 |
-
if line_lower.startswith(pattern):
|
| 124 |
-
should_skip = True
|
| 125 |
-
break
|
| 126 |
-
if not should_skip and line.strip():
|
| 127 |
-
cleaned_lines.append(line)
|
| 128 |
-
|
| 129 |
-
response = '\n'.join(cleaned_lines)
|
| 130 |
-
|
| 131 |
-
# Stop at repetitive text or gibberish
|
| 132 |
-
if 'accordingly' in response.lower() or 'respectively' in response.lower():
|
| 133 |
-
sentences = response.split('.')
|
| 134 |
-
good_sentences = []
|
| 135 |
-
for sent in sentences:
|
| 136 |
-
if 'accordingly' not in sent.lower() and 'respectively' not in sent.lower():
|
| 137 |
-
good_sentences.append(sent)
|
| 138 |
-
else:
|
| 139 |
-
break
|
| 140 |
-
response = '. '.join(good_sentences)
|
| 141 |
|
| 142 |
-
# Limit to reasonable
|
| 143 |
-
sentences = [s.strip() for s in response.split('.') if s.strip()]
|
| 144 |
-
if len(sentences) >
|
| 145 |
-
response = '
|
| 146 |
else:
|
| 147 |
-
response = '
|
| 148 |
|
| 149 |
-
#
|
| 150 |
-
if
|
| 151 |
-
|
| 152 |
-
|
|
|
|
| 153 |
|
| 154 |
-
#
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
return response.strip()
|
| 159 |
|
|
@@ -174,11 +162,19 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
|
|
| 174 |
|
| 175 |
gr.HTML("""
|
| 176 |
<div class="medical-header">
|
| 177 |
-
<h1>π₯ AI Doctor
|
| 178 |
-
<p>
|
| 179 |
</div>
|
| 180 |
""")
|
| 181 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
chatbot = gr.Chatbot(
|
| 183 |
label="π¬ Doctor-Patient Consultation",
|
| 184 |
type='messages',
|
|
@@ -186,69 +182,57 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
|
|
| 186 |
"https://cdn-icons-png.flaticon.com/512/706/706830.png", # Patient
|
| 187 |
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png" # Doctor
|
| 188 |
),
|
| 189 |
-
height=
|
| 190 |
show_copy_button=True
|
| 191 |
)
|
| 192 |
|
| 193 |
with gr.Row():
|
| 194 |
user_input = gr.Textbox(
|
| 195 |
-
placeholder="Describe your symptoms
|
| 196 |
-
label="π§
|
| 197 |
-
lines=
|
| 198 |
scale=4
|
| 199 |
)
|
| 200 |
|
| 201 |
with gr.Row():
|
| 202 |
-
send_btn = gr.Button("π¬
|
| 203 |
-
clear_btn = gr.Button("
|
| 204 |
|
| 205 |
-
gr.Markdown("### π‘ Example
|
| 206 |
gr.Examples(
|
| 207 |
examples=[
|
| 208 |
-
"I
|
| 209 |
-
"I
|
| 210 |
-
"I
|
| 211 |
-
"I
|
| 212 |
-
"I
|
| 213 |
-
"I
|
| 214 |
],
|
| 215 |
inputs=user_input,
|
| 216 |
)
|
| 217 |
|
| 218 |
gr.Markdown("""
|
| 219 |
---
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
β
**Medication Recommendations** - Appropriate medicines with dosage guidance
|
| 224 |
-
β
**Nutrition & Diet Plans** - Foods and nutrients to help recovery
|
| 225 |
-
β
**Lifestyle Modifications** - Exercise, sleep, stress management tips
|
| 226 |
-
β
**Follow-up Advice** - When to see a doctor and warning signs
|
| 227 |
-
|
| 228 |
-
β οΈ **Important Medical Disclaimer:**
|
| 229 |
-
This AI provides general medical information for educational purposes only. It is NOT a substitute for professional medical advice, diagnosis, or treatment. Always seek the advice of your physician or qualified healthcare provider with any questions about a medical condition. Never disregard professional medical advice or delay seeking it because of something you have read here.
|
| 230 |
-
|
| 231 |
-
π¨ **Emergency:** If you are experiencing a medical emergency, call emergency services immediately.
|
| 232 |
""")
|
| 233 |
|
| 234 |
# =======================================================
|
| 235 |
-
# Respond Function
|
| 236 |
# =======================================================
|
| 237 |
def respond(message, history):
|
| 238 |
user_message = message.strip()
|
| 239 |
if not user_message:
|
| 240 |
return "", history
|
| 241 |
|
| 242 |
-
#
|
| 243 |
history.append({"role": "user", "content": user_message})
|
| 244 |
|
| 245 |
-
#
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
if len(history) == 0 or history[-1]["role"] != "assistant":
|
| 250 |
-
history.append({"role": "assistant", "content": updated_history[-1]["content"]})
|
| 251 |
-
else:
|
| 252 |
history[-1]["content"] = updated_history[-1]["content"]
|
| 253 |
yield "", history
|
| 254 |
|
|
@@ -265,7 +249,8 @@ with gr.Blocks(theme=gr.themes.Soft(), css="""
|
|
| 265 |
# =======================================================
|
| 266 |
if __name__ == "__main__":
|
| 267 |
print("="*60)
|
| 268 |
-
print("π₯ AI
|
|
|
|
| 269 |
print("="*60)
|
| 270 |
demo.queue(max_size=20)
|
| 271 |
demo.launch(
|
|
|
|
| 28 |
|
| 29 |
|
| 30 |
# =======================================================
|
| 31 |
+
# Generate Doctor Response - Interactive Medical Consultation
|
| 32 |
# =======================================================
|
| 33 |
def generate_doctor_response(history):
|
| 34 |
user_message = history[-1]["content"]
|
| 35 |
|
| 36 |
if not user_message.strip():
|
| 37 |
+
history.append({"role": "assistant", "content": "How can I help you today?"})
|
| 38 |
yield history
|
| 39 |
return
|
| 40 |
|
| 41 |
+
# Build conversation context from history
|
| 42 |
+
conversation_context = ""
|
| 43 |
+
if len(history) > 1:
|
| 44 |
+
# Include previous exchanges for context
|
| 45 |
+
for msg in history[:-1]:
|
| 46 |
+
if msg["role"] == "user":
|
| 47 |
+
conversation_context += f"PATIENT: {msg['content']}\n"
|
| 48 |
+
else:
|
| 49 |
+
conversation_context += f"DOCTOR: {msg['content']}\n"
|
| 50 |
+
|
| 51 |
+
# Medical conversation prompt - like real doctor-patient interaction
|
| 52 |
+
prompt = f"""You are an experienced medical doctor conducting a patient consultation. Have a natural, interactive conversation where you:
|
| 53 |
|
| 54 |
+
- Ask relevant follow-up questions to understand symptoms better
|
| 55 |
+
- Gather medical history (medications, lifestyle, family history)
|
| 56 |
+
- Provide medical assessment and recommendations
|
| 57 |
+
- Suggest medications with dosages when appropriate
|
| 58 |
+
- Give diet and lifestyle advice
|
| 59 |
+
- Explain what tests or next steps are needed
|
|
|
|
| 60 |
|
| 61 |
+
Respond naturally as a caring doctor would. Keep responses concise (2-4 sentences). Ask ONE specific follow-up question when you need more information.
|
| 62 |
|
| 63 |
+
Previous conversation:
|
| 64 |
+
{conversation_context}
|
| 65 |
+
PATIENT: {user_message}
|
| 66 |
+
DOCTOR:"""
|
| 67 |
|
| 68 |
# Tokenize input
|
| 69 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048).to(model.device)
|
| 70 |
|
| 71 |
gen_config = GenerationConfig(
|
| 72 |
+
temperature=0.75,
|
| 73 |
+
top_p=0.92,
|
| 74 |
+
top_k=45,
|
| 75 |
do_sample=True,
|
| 76 |
+
max_new_tokens=250,
|
| 77 |
pad_token_id=tokenizer.pad_token_id,
|
| 78 |
eos_token_id=tokenizer.eos_token_id,
|
| 79 |
+
repetition_penalty=1.2,
|
| 80 |
no_repeat_ngram_size=3
|
| 81 |
)
|
| 82 |
|
|
|
|
| 89 |
response = tokenizer.decode(generated_ids, skip_special_tokens=True).strip()
|
| 90 |
|
| 91 |
# Clean response
|
| 92 |
+
response = clean_doctor_response(response)
|
| 93 |
|
| 94 |
# Stream response token by token
|
| 95 |
history.append({"role": "assistant", "content": ""})
|
| 96 |
+
for i in range(0, len(response), 4):
|
| 97 |
+
chunk = response[:i + 4]
|
| 98 |
history[-1]["content"] = chunk + "β"
|
| 99 |
yield history.copy()
|
| 100 |
+
time.sleep(0.012)
|
| 101 |
|
| 102 |
history[-1]["content"] = response
|
| 103 |
yield history
|
| 104 |
|
| 105 |
|
| 106 |
+
def clean_doctor_response(response: str) -> str:
|
| 107 |
+
"""Clean the doctor's response to be natural and conversational."""
|
| 108 |
+
|
| 109 |
+
# Remove role labels if present
|
| 110 |
+
prefixes_to_remove = ["doctor:", "assistant:", "response:", "patient:"]
|
| 111 |
response_lower = response.lower()
|
| 112 |
+
for prefix in prefixes_to_remove:
|
| 113 |
if response_lower.startswith(prefix):
|
| 114 |
response = response[len(prefix):].strip()
|
|
|
|
| 115 |
break
|
| 116 |
|
| 117 |
+
# Stop at repetitive patterns or gibberish
|
| 118 |
+
stop_phrases = ["accordingly", "respectively", "speaking correctly", "faithfully yours"]
|
| 119 |
+
for phrase in stop_phrases:
|
| 120 |
+
if phrase in response.lower():
|
| 121 |
+
# Find first occurrence and cut there
|
| 122 |
+
idx = response.lower().find(phrase)
|
| 123 |
+
response = response[:idx].strip()
|
| 124 |
+
break
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
# Limit to reasonable number of sentences (4-6 max)
|
| 127 |
+
sentences = [s.strip() + '.' for s in response.split('.') if s.strip()]
|
| 128 |
+
if len(sentences) > 6:
|
| 129 |
+
response = ' '.join(sentences[:6])
|
| 130 |
else:
|
| 131 |
+
response = ' '.join(sentences)
|
| 132 |
|
| 133 |
+
# Remove incomplete sentences at the end
|
| 134 |
+
if response and response[-1] not in '.!?':
|
| 135 |
+
last_period = response.rfind('.')
|
| 136 |
+
if last_period > 0:
|
| 137 |
+
response = response[:last_period + 1]
|
| 138 |
|
| 139 |
+
# Clean up extra spaces
|
| 140 |
+
response = ' '.join(response.split())
|
| 141 |
+
|
| 142 |
+
# Fallback for very short or empty responses
|
| 143 |
+
if len(response.strip()) < 20:
|
| 144 |
+
response = "Could you tell me more about your symptoms? When did they start?"
|
| 145 |
|
| 146 |
return response.strip()
|
| 147 |
|
|
|
|
| 162 |
|
| 163 |
gr.HTML("""
|
| 164 |
<div class="medical-header">
|
| 165 |
+
<h1>π₯ AI Doctor Consultation</h1>
|
| 166 |
+
<p>Interactive Medical Conversation β’ Just Like Visiting Your Doctor</p>
|
| 167 |
</div>
|
| 168 |
""")
|
| 169 |
|
| 170 |
+
gr.Markdown("""
|
| 171 |
+
### π¬ How This Works:
|
| 172 |
+
- Describe your symptoms or health concerns
|
| 173 |
+
- The AI doctor will ask questions to understand your condition
|
| 174 |
+
- You'll get medical advice, medication suggestions, and lifestyle recommendations
|
| 175 |
+
- Have a natural back-and-forth conversation just like a real doctor visit
|
| 176 |
+
""")
|
| 177 |
+
|
| 178 |
chatbot = gr.Chatbot(
|
| 179 |
label="π¬ Doctor-Patient Consultation",
|
| 180 |
type='messages',
|
|
|
|
| 182 |
"https://cdn-icons-png.flaticon.com/512/706/706830.png", # Patient
|
| 183 |
"https://cdn-icons-png.flaticon.com/512/3774/3774299.png" # Doctor
|
| 184 |
),
|
| 185 |
+
height=500,
|
| 186 |
show_copy_button=True
|
| 187 |
)
|
| 188 |
|
| 189 |
with gr.Row():
|
| 190 |
user_input = gr.Textbox(
|
| 191 |
+
placeholder="Describe your symptoms or answer the doctor's questions...",
|
| 192 |
+
label="π§ Patient (You)",
|
| 193 |
+
lines=2,
|
| 194 |
scale=4
|
| 195 |
)
|
| 196 |
|
| 197 |
with gr.Row():
|
| 198 |
+
send_btn = gr.Button("π¬ Send", variant="primary", scale=1)
|
| 199 |
+
clear_btn = gr.Button("π New Consultation", scale=1)
|
| 200 |
|
| 201 |
+
gr.Markdown("### π‘ Example Conversations")
|
| 202 |
gr.Examples(
|
| 203 |
examples=[
|
| 204 |
+
"Hi Doctor, I've been having fever and body aches for 2 days",
|
| 205 |
+
"I have numbness in my toes and difficulty walking",
|
| 206 |
+
"I've been feeling very tired all the time lately",
|
| 207 |
+
"I have chest pain and shortness of breath",
|
| 208 |
+
"I get headaches almost every day",
|
| 209 |
+
"I have stomach pain after eating"
|
| 210 |
],
|
| 211 |
inputs=user_input,
|
| 212 |
)
|
| 213 |
|
| 214 |
gr.Markdown("""
|
| 215 |
---
|
| 216 |
+
β οΈ **Medical Disclaimer:** This AI provides general medical information for educational purposes.
|
| 217 |
+
It is NOT a substitute for professional medical advice. Always consult a qualified healthcare
|
| 218 |
+
provider for diagnosis and treatment. In case of emergency, call emergency services immediately.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
""")
|
| 220 |
|
| 221 |
# =======================================================
|
| 222 |
+
# Respond Function with Context Memory
|
| 223 |
# =======================================================
|
| 224 |
def respond(message, history):
|
| 225 |
user_message = message.strip()
|
| 226 |
if not user_message:
|
| 227 |
return "", history
|
| 228 |
|
| 229 |
+
# Add user message to history
|
| 230 |
history.append({"role": "user", "content": user_message})
|
| 231 |
|
| 232 |
+
# Generate response with full conversation context
|
| 233 |
+
for updated_history in generate_doctor_response(history):
|
| 234 |
+
# Update the last assistant message
|
| 235 |
+
if history[-1]["role"] == "assistant":
|
|
|
|
|
|
|
|
|
|
| 236 |
history[-1]["content"] = updated_history[-1]["content"]
|
| 237 |
yield "", history
|
| 238 |
|
|
|
|
| 249 |
# =======================================================
|
| 250 |
if __name__ == "__main__":
|
| 251 |
print("="*60)
|
| 252 |
+
print("π₯ AI Doctor Consultation System Starting...")
|
| 253 |
+
print(" Interactive medical conversation with context memory")
|
| 254 |
print("="*60)
|
| 255 |
demo.queue(max_size=20)
|
| 256 |
demo.launch(
|