Spaces:
Sleeping
Sleeping
Updates to app.py
Browse files
app.py
CHANGED
|
@@ -1,581 +1,523 @@
|
|
| 1 |
-
# -------------------------------------------------------------------
|
| 2 |
-
# 1. Import libraries
|
| 3 |
-
# -------------------------------------------------------------------
|
| 4 |
-
# For environment variable management
|
| 5 |
-
from dotenv import load_dotenv
|
| 6 |
-
|
| 7 |
-
# For data manipulation
|
| 8 |
-
import os
|
| 9 |
-
import re
|
| 10 |
-
import json
|
| 11 |
-
from typing import List, Dict, Any, Optional
|
| 12 |
-
import pandas as pd
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
from langchain.
|
| 18 |
-
from
|
| 19 |
-
from
|
| 20 |
-
from
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
OPENAI_API_KEY
|
| 41 |
-
|
| 42 |
-
#
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
# -------------------------------------------------------------------
|
| 59 |
-
# 2. Load data
|
| 60 |
-
# -------------------------------------------------------------------
|
| 61 |
-
# Load the disease and related symptom data
|
| 62 |
-
dataset = pd.read_csv(DATASET_PATH)
|
| 63 |
-
# Load the symptom severity data
|
| 64 |
-
symptom_severity = pd.read_csv(SYMPTOM_SEVERITY_PATH)
|
| 65 |
-
# Load the symptom description data
|
| 66 |
-
symptom_desc = pd.read_csv(SYMPTOM_DESC_PATH)
|
| 67 |
-
# Load the symptom precaution data
|
| 68 |
-
symptom_prec = pd.read_csv(SYMPTOM_PREC_PATH)
|
| 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 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
#
|
| 160 |
-
|
| 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 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
#
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
return
|
| 223 |
-
"
|
| 224 |
-
"
|
| 225 |
-
"
|
| 226 |
-
"
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
#
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
#
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
)
|
| 269 |
-
|
| 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 |
-
#
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
#
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
#
|
| 318 |
-
|
| 319 |
-
#
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
"""
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
#
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
""
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
#
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
]
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
#
|
| 459 |
-
def
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
#
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
#
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
"""
|
| 525 |
-
# MediBot (RAG + Tools)
|
| 526 |
-
Enter your symptoms in plain language (comma-separated is fine).
|
| 527 |
-
**Note:** This is not medical advice—consult a clinician for diagnosis and treatment.
|
| 528 |
-
""".strip()
|
| 529 |
-
)
|
| 530 |
-
|
| 531 |
-
chatbot = gr.Chatbot(height=420) #type="messages", height=420)
|
| 532 |
-
lc_state = gr.State([])
|
| 533 |
-
|
| 534 |
-
# User input row
|
| 535 |
-
with gr.Row():
|
| 536 |
-
user_box = gr.Textbox(
|
| 537 |
-
label="Your message",
|
| 538 |
-
placeholder="e.g., fever, headache, chills, fatigue",
|
| 539 |
-
scale=8,
|
| 540 |
-
)
|
| 541 |
-
send_btn = gr.Button("Send", scale=2)
|
| 542 |
-
|
| 543 |
-
with gr.Row():
|
| 544 |
-
examples = gr.Examples(
|
| 545 |
-
examples=[
|
| 546 |
-
["I have fever, headache, chills, and fatigue. What could it be?"],
|
| 547 |
-
["I also have nausea and joint pain."],
|
| 548 |
-
["Sore throat, runny nose, mild cough for 2 days."],
|
| 549 |
-
["Chest pain and shortness of breath."],
|
| 550 |
-
],
|
| 551 |
-
inputs=user_box,
|
| 552 |
-
label="Examples",
|
| 553 |
-
)
|
| 554 |
-
|
| 555 |
-
clear_btn = gr.Button("Clear chat")
|
| 556 |
-
|
| 557 |
-
# Wire events
|
| 558 |
-
|
| 559 |
-
# When the send button is clicked, run the submit_chat function with the current user input, chat history, and LangChain state, and update the chatbot and clear the user input box
|
| 560 |
-
send_btn.click(
|
| 561 |
-
fn=submit_chat,
|
| 562 |
-
inputs=[user_box, chatbot, lc_state],
|
| 563 |
-
outputs=[chatbot, user_box, lc_state],
|
| 564 |
-
)
|
| 565 |
-
|
| 566 |
-
# Allow pressing Enter in the textbox to submit the chat as well
|
| 567 |
-
user_box.submit(
|
| 568 |
-
fn=submit_chat,
|
| 569 |
-
inputs=[user_box, chatbot, lc_state],
|
| 570 |
-
outputs=[chatbot, user_box, lc_state],
|
| 571 |
-
)
|
| 572 |
-
|
| 573 |
-
# Clear button resets both the Gradio chat history and the LangChain state
|
| 574 |
-
clear_btn.click(
|
| 575 |
-
fn=lambda: ([], [], []),
|
| 576 |
-
inputs=[],
|
| 577 |
-
outputs=[chatbot, user_box, lc_state],
|
| 578 |
-
)
|
| 579 |
-
|
| 580 |
-
# Launch the UI
|
| 581 |
-
demo.launch(share=True)
|
|
|
|
| 1 |
+
# -------------------------------------------------------------------
|
| 2 |
+
# 1. Import libraries
|
| 3 |
+
# -------------------------------------------------------------------
|
| 4 |
+
# For environment variable management
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
|
| 7 |
+
# For data manipulation
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import json
|
| 11 |
+
from typing import List, Dict, Any, Optional, Tuple
|
| 12 |
+
import pandas as pd
|
| 13 |
+
from pydantic import BaseModel, Field
|
| 14 |
+
|
| 15 |
+
# For LangChain agent and tools
|
| 16 |
+
from langchain.tools import tool
|
| 17 |
+
from langchain.chat_models import init_chat_model
|
| 18 |
+
from langchain_core.documents import Document
|
| 19 |
+
from langchain.agents import create_agent
|
| 20 |
+
from langchain_core.messages import BaseMessage, HumanMessage, AIMessage, ToolMessage, SystemMessage, FunctionMessage
|
| 21 |
+
|
| 22 |
+
# Use OpenAI for embeddings and LLM
|
| 23 |
+
from langchain_openai import OpenAIEmbeddings
|
| 24 |
+
# Use FAISS for vector store
|
| 25 |
+
from langchain_community.vectorstores import FAISS
|
| 26 |
+
|
| 27 |
+
# For filepaths
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
# For gradio UI
|
| 31 |
+
import gradio as gr
|
| 32 |
+
|
| 33 |
+
# Load environment variables from .env file
|
| 34 |
+
load_dotenv()
|
| 35 |
+
os.getenv("OPENAI_API_KEY")
|
| 36 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
| 37 |
+
|
| 38 |
+
# Expect OPENAI_API_KEY to be set in HF Space secrets
|
| 39 |
+
if not OPENAI_API_KEY:
|
| 40 |
+
raise RuntimeError("OPENAI_API_KEY environment variable is not set.")
|
| 41 |
+
|
| 42 |
+
# Constants and config
|
| 43 |
+
## Dataset folder
|
| 44 |
+
BASE_DIR = Path(__file__).resolve().parent
|
| 45 |
+
DATA_DIR = BASE_DIR / "data"
|
| 46 |
+
FAISS_PATH = BASE_DIR / "faiss_store"
|
| 47 |
+
|
| 48 |
+
## Dataset file paths
|
| 49 |
+
DATASET_PATH = DATA_DIR / "dataset.csv"
|
| 50 |
+
SYMPTOM_SEVERITY_PATH = DATA_DIR / "Symptom-severity.csv"
|
| 51 |
+
SYMPTOM_DESC_PATH = DATA_DIR / "symptom_Description.csv"
|
| 52 |
+
SYMPTOM_PREC_PATH = DATA_DIR / "symptom_precaution.csv"
|
| 53 |
+
|
| 54 |
+
for path in [DATASET_PATH, SYMPTOM_SEVERITY_PATH, SYMPTOM_DESC_PATH, SYMPTOM_PREC_PATH]:
|
| 55 |
+
if not path.exists():
|
| 56 |
+
raise FileNotFoundError(f"Missing required data file: {path}")
|
| 57 |
+
|
| 58 |
+
# -------------------------------------------------------------------
|
| 59 |
+
# 2. Load data
|
| 60 |
+
# -------------------------------------------------------------------
|
| 61 |
+
# Load the disease and related symptom data
|
| 62 |
+
dataset = pd.read_csv(DATASET_PATH)
|
| 63 |
+
# Load the symptom severity data
|
| 64 |
+
symptom_severity = pd.read_csv(SYMPTOM_SEVERITY_PATH)
|
| 65 |
+
# Load the symptom description data
|
| 66 |
+
symptom_desc = pd.read_csv(SYMPTOM_DESC_PATH)
|
| 67 |
+
# Load the symptom precaution data
|
| 68 |
+
symptom_prec = pd.read_csv(SYMPTOM_PREC_PATH)
|
| 69 |
+
|
| 70 |
+
"""# Data cleanup and standardization"""
|
| 71 |
+
|
| 72 |
+
# Canonicalize the symptom data (clean it so it has consistent and compatible formatting)
|
| 73 |
+
def canon_symptom(x: str) -> str:
|
| 74 |
+
# Convert nulls to blanks ("")
|
| 75 |
+
if pd.isna(x):
|
| 76 |
+
return ""
|
| 77 |
+
# Remove spaces and convert to lowercase
|
| 78 |
+
x = str(x).strip().lower()
|
| 79 |
+
# The symptoms may include underscores and some also have spaces (i.e. "_ "), so replace these with a single space
|
| 80 |
+
x = re.sub(r"\s*_\s*", " ", x)
|
| 81 |
+
# Replace multiple spaces with a single space
|
| 82 |
+
x = re.sub(r" +", " ", x)
|
| 83 |
+
return x
|
| 84 |
+
|
| 85 |
+
# Generic text canonicalization (for disease names, descriptions, and precautions)
|
| 86 |
+
def canon_text(x: str) -> str:
|
| 87 |
+
# Convert nulls to blanks ("")
|
| 88 |
+
if pd.isna(x):
|
| 89 |
+
return ""
|
| 90 |
+
# Strip spaces
|
| 91 |
+
return str(x).strip()
|
| 92 |
+
|
| 93 |
+
"""## Format the disease and symptom data"""
|
| 94 |
+
|
| 95 |
+
# Create a list of all symptom columns
|
| 96 |
+
symp_cols = [c for c in dataset.columns if c.lower().startswith("symptom_")]
|
| 97 |
+
|
| 98 |
+
# Convert the dataset to a long format with "Disease" and "symptom" columns
|
| 99 |
+
long = (
|
| 100 |
+
dataset.melt(id_vars=["Disease"], value_vars=symp_cols, value_name="symptom").drop(columns=["variable"])
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# Clean up the disease column
|
| 104 |
+
long["Disease"] = long["Disease"].map(canon_text)
|
| 105 |
+
# Clean up the symptoms
|
| 106 |
+
long["symptom"] = long["symptom"].map(canon_symptom)
|
| 107 |
+
# Drop duplicate symptoms
|
| 108 |
+
long = long[long["symptom"] != ""].drop_duplicates()
|
| 109 |
+
|
| 110 |
+
# Create a dictionary of diseases (key) each with a set of symptoms (value)
|
| 111 |
+
disease_to_symptoms = long.groupby("Disease")["symptom"].apply(set).to_dict()
|
| 112 |
+
|
| 113 |
+
# Clean up the symptom values
|
| 114 |
+
symptom_severity["Symptom"] = symptom_severity["Symptom"].map(canon_symptom)
|
| 115 |
+
# Set the symptom weights - if the weight is null, set to 0
|
| 116 |
+
symptom_severity["weight"] = pd.to_numeric(symptom_severity["weight"], errors="coerce").fillna(0).astype(int)
|
| 117 |
+
# Convert to a dictionary of symptom (key) and weight (value) for lookups
|
| 118 |
+
symptom_to_weight = dict(zip(symptom_severity["Symptom"], symptom_severity["weight"]))
|
| 119 |
+
|
| 120 |
+
"""## Join symptom description and precautions data"""
|
| 121 |
+
|
| 122 |
+
# Clean the disease names and descriptions
|
| 123 |
+
symptom_desc["Disease"] = symptom_desc["Disease"].map(canon_text)
|
| 124 |
+
symptom_prec["Disease"] = symptom_prec["Disease"].map(canon_text)
|
| 125 |
+
symptom_desc["Description"] = symptom_desc["Description"].map(canon_text)
|
| 126 |
+
|
| 127 |
+
# Create a dictionary of disease names (key) and symptom descriptions (value)
|
| 128 |
+
disease_to_desc = dict(zip(symptom_desc["Disease"], symptom_desc["Description"]))
|
| 129 |
+
# Get a list of the precaution columns (excludes the "Disease" column)
|
| 130 |
+
prec_cols = [c for c in symptom_prec.columns if c.lower().startswith("precaution_")]
|
| 131 |
+
|
| 132 |
+
# Create a dictionary and map the precautions to the diseases
|
| 133 |
+
disease_to_prec = {}
|
| 134 |
+
for _, row in symptom_prec.iterrows():
|
| 135 |
+
dis = row["Disease"]
|
| 136 |
+
# Get a list of the precautions (not blank) for the current disease
|
| 137 |
+
prec_list = [canon_text(row[c]) for c in prec_cols if canon_text(row[c])]
|
| 138 |
+
disease_to_prec[dis] = prec_list
|
| 139 |
+
|
| 140 |
+
# Get the top K candidate diagnoses (diseases) for given symptoms
|
| 141 |
+
# This function gives highly explainable results for diagnoses
|
| 142 |
+
def disease_candidates(user_symptoms: list[str], top_k: int = 5):
|
| 143 |
+
# Clean the symptom list
|
| 144 |
+
clean_symp = {canon_symptom(s) for s in user_symptoms}
|
| 145 |
+
# Only keep the non-blank symptoms
|
| 146 |
+
clean_symp = {s for s in clean_symp if s}
|
| 147 |
+
# If the symptom list is empty, return an empty list
|
| 148 |
+
if not clean_symp:
|
| 149 |
+
return []
|
| 150 |
+
|
| 151 |
+
# The denominator should be the sum of symptom weights (if the symptom is not in the dictionary, then just use 1 for the weight)
|
| 152 |
+
denominator = sum(symptom_to_weight.get(s, 0) for s in clean_symp) or 1
|
| 153 |
+
|
| 154 |
+
candidate_list = []
|
| 155 |
+
|
| 156 |
+
for disease, symp in disease_to_symptoms.items():
|
| 157 |
+
# Find the intersection of user symptoms w/symptoms for the current disease
|
| 158 |
+
inter = clean_symp.intersection(symp)
|
| 159 |
+
# If we didn't find matching symptoms, this is not a good candidate
|
| 160 |
+
if not inter:
|
| 161 |
+
continue
|
| 162 |
+
# The numerator should be the sum of symptom weights for matching symptoms
|
| 163 |
+
numerator = sum(symptom_to_weight.get(s, 0) for s in inter)
|
| 164 |
+
candidate_score = numerator / denominator
|
| 165 |
+
# Add the candidate disease, score, and sorted maching symptom list
|
| 166 |
+
candidate_list.append((disease, candidate_score, sorted(inter)))
|
| 167 |
+
|
| 168 |
+
# Sort the list in descending order (highest scored first)
|
| 169 |
+
candidate_list.sort(key=lambda x: x[1], reverse=True)
|
| 170 |
+
# Return the top K candidates by score
|
| 171 |
+
return candidate_list[:top_k]
|
| 172 |
+
|
| 173 |
+
# Get a report of severity based on symptoms
|
| 174 |
+
def severity_report(user_symptoms: list[str]):
|
| 175 |
+
# Clean the symptoms and only keep non-blank symptoms
|
| 176 |
+
clean_symp = [canon_symptom(s) for s in user_symptoms]
|
| 177 |
+
clean_symp = [s for s in clean_symp if s]
|
| 178 |
+
|
| 179 |
+
# Get weights per symptom
|
| 180 |
+
weight_per_symp = [(s, symptom_to_weight.get(s, 0)) for s in clean_symp]
|
| 181 |
+
# Get the total weight for all symptoms
|
| 182 |
+
total = sum(w for _, w in weight_per_symp)
|
| 183 |
+
|
| 184 |
+
# Give severity levels based on total symptom weight
|
| 185 |
+
if total <= 5:
|
| 186 |
+
level = "mild"
|
| 187 |
+
elif total <= 12:
|
| 188 |
+
level = "moderate"
|
| 189 |
+
else:
|
| 190 |
+
level = "high"
|
| 191 |
+
|
| 192 |
+
# Track the symptoms that were not found in the severity table (i.e. have no weight)
|
| 193 |
+
no_severity = [s for s in clean_symp if s not in symptom_to_weight]
|
| 194 |
+
|
| 195 |
+
return {
|
| 196 |
+
"Total": total,
|
| 197 |
+
"Level": level,
|
| 198 |
+
"Per symptom": weight_per_symp,
|
| 199 |
+
"Symptoms not in severity table": no_severity
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
# Check data quality
|
| 203 |
+
all_symptoms = set().union(*disease_to_symptoms.values())
|
| 204 |
+
# Get all symptoms w/out a severity weight
|
| 205 |
+
missing_severity = sorted([s for s in all_symptoms if s not in symptom_to_weight])
|
| 206 |
+
|
| 207 |
+
all_diseases = set(disease_to_symptoms.keys())
|
| 208 |
+
# Get diseases missing a description
|
| 209 |
+
missing_desc = sorted([d for d in all_diseases if d not in disease_to_desc])
|
| 210 |
+
# Get diseases missing precautions
|
| 211 |
+
missing_prec = sorted([d for d in all_diseases if d not in disease_to_prec])
|
| 212 |
+
|
| 213 |
+
# Create disease documents
|
| 214 |
+
def disease_doc(disease: str) -> str:
|
| 215 |
+
# Get the symptoms for this disease (from the dataset)
|
| 216 |
+
symptoms = sorted(disease_to_symptoms.get(disease, set()))
|
| 217 |
+
# Get the description for this disease (from the dataset)
|
| 218 |
+
description = disease_to_desc.get(disease, "")
|
| 219 |
+
# Get the precaustions for this disease (from the dataset)
|
| 220 |
+
precautions = disease_to_prec.get(disease, [])
|
| 221 |
+
|
| 222 |
+
return "\n".join([
|
| 223 |
+
f"Disease: {disease}",
|
| 224 |
+
f"Description: {description}",
|
| 225 |
+
"Symptoms: " + ", ".join(symptoms),
|
| 226 |
+
"Precautions: " + ", ".join(precautions) if precautions else "Precautions: (none listed)"
|
| 227 |
+
])
|
| 228 |
+
|
| 229 |
+
docs: List[Document] = []
|
| 230 |
+
for d in sorted(disease_to_symptoms.keys()):
|
| 231 |
+
docs.append(
|
| 232 |
+
Document(
|
| 233 |
+
page_content = disease_doc(d),
|
| 234 |
+
metadata={"disease": d}
|
| 235 |
+
)
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
# Created embeddings of the disease docs and store in a vector store
|
| 239 |
+
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
|
| 240 |
+
# If we don't have embeddings in cache, create them
|
| 241 |
+
def load_or_create_faiss(docs, faiss_path=FAISS_PATH):
|
| 242 |
+
""" Load FAISS index if it exists, otherwise create it from docs and save it. """
|
| 243 |
+
index_file = os.path.join(faiss_path, "index.faiss")
|
| 244 |
+
store_file = os.path.join(faiss_path, "index.pkl")
|
| 245 |
+
# If FAISS cache exists, load it
|
| 246 |
+
if os.path.exists(index_file) and os.path.exists(store_file):
|
| 247 |
+
print("Loading FAISS index from cache...")
|
| 248 |
+
return FAISS.load_local(faiss_path, embeddings, allow_dangerous_deserialization=True)
|
| 249 |
+
# Otherwise create a new FAISS index
|
| 250 |
+
print("⚙️ Building new FAISS index...")
|
| 251 |
+
vectorstore = FAISS.from_documents(docs, embeddings)
|
| 252 |
+
# Ensure directory exists
|
| 253 |
+
os.makedirs(faiss_path, exist_ok=True)
|
| 254 |
+
# Save to disk
|
| 255 |
+
vectorstore.save_local(faiss_path)
|
| 256 |
+
print("💾 Saved FAISS index to disk.")
|
| 257 |
+
return vectorstore
|
| 258 |
+
|
| 259 |
+
# Create or load the FAISS vector store for the disease documents
|
| 260 |
+
vector_store = load_or_create_faiss(docs, faiss_path=FAISS_PATH)
|
| 261 |
+
|
| 262 |
+
# Define schemas to use for the tools
|
| 263 |
+
|
| 264 |
+
# Define the input schema for each tool using Pydantic BaseModel
|
| 265 |
+
class DiagnoseInput(BaseModel):
|
| 266 |
+
# List of symptoms
|
| 267 |
+
symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
|
| 268 |
+
# Top K candidates to return (default to 5, but should be between 1 and 10)
|
| 269 |
+
top_k: int = Field(5, ge=1, le=10, description="Number of candidate diseases to return")
|
| 270 |
+
|
| 271 |
+
class SeverityInput(BaseModel):
|
| 272 |
+
# List of symptoms
|
| 273 |
+
symptoms: List[str] = Field(..., description="List of symptoms the user is experiencing")
|
| 274 |
+
|
| 275 |
+
class DiseaseInfoInput(BaseModel):
|
| 276 |
+
# Disease name
|
| 277 |
+
disease: str = Field(..., description="Disease name (must match name in dataset)")
|
| 278 |
+
|
| 279 |
+
class RetrieveDocsInput(BaseModel):
|
| 280 |
+
# Search query
|
| 281 |
+
query: str = Field(..., description="A search query (i.e. symptoms list or disease name)")
|
| 282 |
+
# Top K docs to retrieve (default to 3, but should be between 1 and 10)
|
| 283 |
+
k: int = Field(3, ge=1, le=10, description="How many disease docs to retrieve")
|
| 284 |
+
|
| 285 |
+
# Tools (using RAG, so they are deterministic)
|
| 286 |
+
|
| 287 |
+
# Create a diagnosic tool, using our schema
|
| 288 |
+
@tool(args_schema=DiagnoseInput)
|
| 289 |
+
def diagnose_diseases(symptoms: List[str], top_k: int=5) -> str:
|
| 290 |
+
"""
|
| 291 |
+
Suggest likely diseases based on matching symptoms (using severity weights) from the dataset.
|
| 292 |
+
Returns a JSON string of ranked candidates.
|
| 293 |
+
"""
|
| 294 |
+
# Get the top K disease diagnoses
|
| 295 |
+
results = disease_candidates(symptoms, top_k=top_k)
|
| 296 |
+
# Return a JSON formatted string from the list
|
| 297 |
+
return json.dumps({"candidates": results}, indent=2)
|
| 298 |
+
|
| 299 |
+
# Create a symptom severity calculation tool, using our schema
|
| 300 |
+
@tool(args_schema=SeverityInput)
|
| 301 |
+
def calc_symptom_severity(symptoms: List[str]) -> str:
|
| 302 |
+
"""
|
| 303 |
+
Calculate a symptom severity score using weights from the Symptom-severity.csv dataset.
|
| 304 |
+
Returns a JSON string with the total score, severity level, and weights per symptom.
|
| 305 |
+
"""
|
| 306 |
+
# Get the symptoms severity summary
|
| 307 |
+
report = severity_report(symptoms)
|
| 308 |
+
# Return a JSON formatted string
|
| 309 |
+
return json.dumps(report, indent=2)
|
| 310 |
+
|
| 311 |
+
# Create a tool to get disease description, using our schema
|
| 312 |
+
@tool(args_schema=DiseaseInfoInput)
|
| 313 |
+
def get_disease_description(disease: str) -> str:
|
| 314 |
+
"""
|
| 315 |
+
Get the description for a disease (from the symptom_Description.csv dataset)
|
| 316 |
+
"""
|
| 317 |
+
# Clean the disease name
|
| 318 |
+
disease = canon_text(disease)
|
| 319 |
+
# Lookup the disease description and return
|
| 320 |
+
return disease_to_desc.get(disease, "")
|
| 321 |
+
|
| 322 |
+
# Create a tool to get disease precaution advice, using our schema
|
| 323 |
+
@tool(args_schema=DiseaseInfoInput)
|
| 324 |
+
def get_precaution_advice(disease: str) -> str:
|
| 325 |
+
"""
|
| 326 |
+
Get precaution steps for a disease (from the symptom_precaution.csv dataset)
|
| 327 |
+
"""
|
| 328 |
+
# Clean the disease name
|
| 329 |
+
disease = canon_text(disease)
|
| 330 |
+
# Lookup the disease precautions and return
|
| 331 |
+
return json.dumps(disease_to_prec.get(disease, []), indent=2)
|
| 332 |
+
|
| 333 |
+
# Create a tool to retrieve disease documents from the vector store, using our schema
|
| 334 |
+
@tool(args_schema=RetrieveDocsInput)
|
| 335 |
+
def retrieve_disease_docs(query: str, k: int = 3):
|
| 336 |
+
"""
|
| 337 |
+
Retrieve disease documents from the vector store for "ground truth" and explanations.
|
| 338 |
+
Returns (serialized_text, retrieved_documents).)
|
| 339 |
+
"""
|
| 340 |
+
# Get K similar docs from the vector store, based on the query
|
| 341 |
+
retrieved = vector_store.similarity_search(query, k=k)
|
| 342 |
+
# Get a serialized string of the top K matching disease docs
|
| 343 |
+
serialized = "\n\n".join(
|
| 344 |
+
f"Source: {doc.metadata}\nContent\n{doc.page_content}"
|
| 345 |
+
for doc in retrieved
|
| 346 |
+
)
|
| 347 |
+
return serialized
|
| 348 |
+
|
| 349 |
+
tools = [
|
| 350 |
+
diagnose_diseases,
|
| 351 |
+
calc_symptom_severity,
|
| 352 |
+
get_disease_description,
|
| 353 |
+
get_precaution_advice,
|
| 354 |
+
retrieve_disease_docs,
|
| 355 |
+
]
|
| 356 |
+
|
| 357 |
+
# LLM + orchestrator agent
|
| 358 |
+
|
| 359 |
+
# Use a deterministic model since we are using tools for diagnosis and severity calculation and use the mini model for faster responses
|
| 360 |
+
model = init_chat_model(
|
| 361 |
+
"gpt-4.1-mini",
|
| 362 |
+
temperature=0,
|
| 363 |
+
model_provider="openai",
|
| 364 |
+
api_key=OPENAI_API_KEY,
|
| 365 |
+
)
|
| 366 |
+
system_prompt = """
|
| 367 |
+
You are a medical decision support assistant, not to be used as a replacement for professional medical care.
|
| 368 |
+
In your responses, always:
|
| 369 |
+
- Use tools to identify diagnosis candidates and symptom severity
|
| 370 |
+
- Provide a disclaimer that the user should consult with a doctor
|
| 371 |
+
- Give precaution advice and recommend professional medical care when appropriate (i.e. moderate to severe symptoms)
|
| 372 |
+
- If symptoms suggest a serious emergency risk (e.g. chest pain, difficulty breathing, serious bleeding), then recommend urgent care or emergency room services
|
| 373 |
+
|
| 374 |
+
Workflow to follow:
|
| 375 |
+
1) Ask for symptoms if not provided by user
|
| 376 |
+
2) Call calc_symptom_severity(symptoms)
|
| 377 |
+
3) Call diagnose_diseases(symptoms, top_k=5)
|
| 378 |
+
4) For the top 1-3 diseases, call retreive_disease_docs using the disease name or symptoms.
|
| 379 |
+
5) Return: top candidates also with why (matched symptoms), severity level, description + precautions for the top candidate(s), and provide follow-up questions to refine.
|
| 380 |
+
|
| 381 |
+
Responses should always be concise.
|
| 382 |
+
""".strip()
|
| 383 |
+
|
| 384 |
+
agent = create_agent(model, tools, system_prompt=system_prompt)
|
| 385 |
+
|
| 386 |
+
# Multi-turn chat
|
| 387 |
+
def chat_once(messages: List[BaseMessage]) -> List[BaseMessage]:
|
| 388 |
+
"""
|
| 389 |
+
messages: List of BaseMessage objects for the conversation history.
|
| 390 |
+
Returns updated list of BaseMessage objects with the agent's final response added.
|
| 391 |
+
"""
|
| 392 |
+
final_state = None
|
| 393 |
+
for step in agent.stream({"messages": messages}, stream_mode="values"):
|
| 394 |
+
final_state = step
|
| 395 |
+
|
| 396 |
+
# Return the actual BaseMessage objects from the final state
|
| 397 |
+
return final_state["messages"]
|
| 398 |
+
|
| 399 |
+
# For the Gradio UI, we want to run the agent and get the updated LangChain message history, so we can extract the assistant's final response and also maintain the full conversation state (including tool calls) in the UI.
|
| 400 |
+
def run_agent_once(lc_history: List[BaseMessage]) -> List[BaseMessage]:
|
| 401 |
+
"""
|
| 402 |
+
Runs the agent on the current conversation and returns the updated LangChain message history.
|
| 403 |
+
"""
|
| 404 |
+
final_state = None
|
| 405 |
+
for step in agent.stream({"messages": lc_history}, stream_mode="values"):
|
| 406 |
+
final_state = step
|
| 407 |
+
return final_state["messages"]
|
| 408 |
+
|
| 409 |
+
# Helper function to extract the last assistant response content from the LangChain message history
|
| 410 |
+
def get_last_ai_content(lc_history: List[BaseMessage]) -> str:
|
| 411 |
+
"""
|
| 412 |
+
Extract the last assistant response content from the LangChain message history.
|
| 413 |
+
"""
|
| 414 |
+
for m in reversed(lc_history):
|
| 415 |
+
if isinstance(m, AIMessage):
|
| 416 |
+
return (m.content or "").strip()
|
| 417 |
+
return ""
|
| 418 |
+
|
| 419 |
+
# Gradio UI handlers
|
| 420 |
+
def submit_chat(user_text: str, chat_history: List[dict], lc_state: Optional[List[BaseMessage]]):
|
| 421 |
+
"""
|
| 422 |
+
Gradio handler:
|
| 423 |
+
- user_text: current textbox input
|
| 424 |
+
- chat_history: list of {"role": "...", "content": "..."} used by gr.Chatbot(type="messages")
|
| 425 |
+
- lc_state: LangChain BaseMessage history stored in gr.State
|
| 426 |
+
|
| 427 |
+
Returns:
|
| 428 |
+
- updated chat_history (for UI)
|
| 429 |
+
- cleared textbox
|
| 430 |
+
- updated lc_state
|
| 431 |
+
"""
|
| 432 |
+
user_text = (user_text or "").strip()
|
| 433 |
+
if not user_text:
|
| 434 |
+
return chat_history, "", lc_state
|
| 435 |
+
|
| 436 |
+
if lc_state is None:
|
| 437 |
+
lc_state = []
|
| 438 |
+
|
| 439 |
+
# 1) Add user message to LangChain state
|
| 440 |
+
lc_state.append(HumanMessage(content=user_text))
|
| 441 |
+
|
| 442 |
+
# 2) Run agent, get updated LangChain history (includes tool calls, etc.)
|
| 443 |
+
lc_state = run_agent_once(lc_state)
|
| 444 |
+
|
| 445 |
+
# 3) Extract the assistant’s final natural-language response
|
| 446 |
+
assistant_text = get_last_ai_content(lc_state)
|
| 447 |
+
if not assistant_text:
|
| 448 |
+
assistant_text = "I couldn't generate a response. Please try rephrasing your symptoms."
|
| 449 |
+
|
| 450 |
+
# 4) Update the Gradio chat history (messages format)
|
| 451 |
+
chat_history = chat_history + [
|
| 452 |
+
{"role": "user", "content": user_text},
|
| 453 |
+
{"role": "assistant", "content": assistant_text},
|
| 454 |
+
]
|
| 455 |
+
|
| 456 |
+
return chat_history, "", lc_state
|
| 457 |
+
|
| 458 |
+
# Handler to reset the chat - clears the Gradio chat history and the LangChain state
|
| 459 |
+
def reset_chat():
|
| 460 |
+
return [], [] # chat_history, lc_state
|
| 461 |
+
|
| 462 |
+
# Build the Gradio UI
|
| 463 |
+
with gr.Blocks(title="MediBot – Disease & Symptom Assistant") as demo:
|
| 464 |
+
gr.Markdown(
|
| 465 |
+
"""
|
| 466 |
+
# MediBot (RAG + Tools)
|
| 467 |
+
Enter your symptoms in plain language (comma-separated is fine).
|
| 468 |
+
**Note:** This is not medical advice—consult a clinician for diagnosis and treatment.
|
| 469 |
+
""".strip()
|
| 470 |
+
)
|
| 471 |
+
|
| 472 |
+
chatbot = gr.Chatbot(height=420)
|
| 473 |
+
lc_state = gr.State([])
|
| 474 |
+
|
| 475 |
+
# User input row
|
| 476 |
+
with gr.Row():
|
| 477 |
+
user_box = gr.Textbox(
|
| 478 |
+
label="Your message",
|
| 479 |
+
placeholder="e.g., fever, headache, chills, fatigue",
|
| 480 |
+
scale=8,
|
| 481 |
+
)
|
| 482 |
+
send_btn = gr.Button("Send", scale=2)
|
| 483 |
+
|
| 484 |
+
with gr.Row():
|
| 485 |
+
examples = gr.Examples(
|
| 486 |
+
examples=[
|
| 487 |
+
["I have fever, headache, chills, and fatigue. What could it be?"],
|
| 488 |
+
["I also have nausea and joint pain."],
|
| 489 |
+
["Sore throat, runny nose, mild cough for 2 days."],
|
| 490 |
+
["Chest pain and shortness of breath."],
|
| 491 |
+
],
|
| 492 |
+
inputs=user_box,
|
| 493 |
+
label="Examples",
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
clear_btn = gr.Button("Clear chat")
|
| 497 |
+
|
| 498 |
+
# Wire events
|
| 499 |
+
|
| 500 |
+
# When the send button is clicked, run the submit_chat function with the current user input, chat history, and LangChain state, and update the chatbot and clear the user input box
|
| 501 |
+
send_btn.click(
|
| 502 |
+
fn=submit_chat,
|
| 503 |
+
inputs=[user_box, chatbot, lc_state],
|
| 504 |
+
outputs=[chatbot, user_box, lc_state],
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
# Allow pressing Enter in the textbox to submit the chat as well
|
| 508 |
+
user_box.submit(
|
| 509 |
+
fn=submit_chat,
|
| 510 |
+
inputs=[user_box, chatbot, lc_state],
|
| 511 |
+
outputs=[chatbot, user_box, lc_state],
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
# Clear button resets both the Gradio chat history and the LangChain state
|
| 515 |
+
clear_btn.click(
|
| 516 |
+
fn=lambda: ([], "", []),
|
| 517 |
+
inputs=[],
|
| 518 |
+
outputs=[chatbot, user_box, lc_state],
|
| 519 |
+
)
|
| 520 |
+
|
| 521 |
+
# Launch the UI
|
| 522 |
+
if __name__ == "__main__":
|
| 523 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|