Spaces:
Sleeping
Sleeping
Updated app.py to improve matching logic
Browse files
app.py
CHANGED
|
@@ -30,6 +30,10 @@ from pathlib import Path
|
|
| 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")
|
|
@@ -90,6 +94,100 @@ def canon_text(x: str) -> str:
|
|
| 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
|
|
@@ -110,6 +208,73 @@ long = long[long["symptom"] != ""].drop_duplicates()
|
|
| 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
|
|
@@ -139,68 +304,221 @@ for _, row in symptom_prec.iterrows():
|
|
| 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:
|
| 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 |
# Get a report of severity based on symptoms
|
| 174 |
-
def severity_report(user_symptoms:
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 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 |
|
|
@@ -282,31 +600,36 @@ class RetrieveDocsInput(BaseModel):
|
|
| 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 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
return json.dumps(report, indent=2)
|
| 310 |
|
| 311 |
# Create a tool to get disease description, using our schema
|
| 312 |
@tool(args_schema=DiseaseInfoInput)
|
|
@@ -346,12 +669,30 @@ def retrieve_disease_docs(query: str, k: int = 3):
|
|
| 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
|
|
@@ -363,20 +704,26 @@ model = init_chat_model(
|
|
| 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
|
|
|
|
|
|
|
| 370 |
- Provide a disclaimer that the user should consult with a doctor
|
| 371 |
-
- Give precaution advice and recommend professional medical care when appropriate
|
| 372 |
-
- If symptoms suggest a serious emergency risk (e.g. chest pain, difficulty breathing, serious bleeding),
|
| 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
|
| 378 |
-
4)
|
| 379 |
-
5)
|
|
|
|
|
|
|
| 380 |
|
| 381 |
Responses should always be concise.
|
| 382 |
""".strip()
|
|
@@ -463,7 +810,7 @@ def reset_chat():
|
|
| 463 |
with gr.Blocks(title="MediBot – Disease & Symptom Assistant") as demo:
|
| 464 |
gr.Markdown(
|
| 465 |
"""
|
| 466 |
-
# MediBot
|
| 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()
|
|
|
|
| 30 |
# For gradio UI
|
| 31 |
import gradio as gr
|
| 32 |
|
| 33 |
+
# For data quality checks
|
| 34 |
+
from collections import Counter
|
| 35 |
+
import math
|
| 36 |
+
|
| 37 |
# Load environment variables from .env file
|
| 38 |
load_dotenv()
|
| 39 |
os.getenv("OPENAI_API_KEY")
|
|
|
|
| 94 |
# Strip spaces
|
| 95 |
return str(x).strip()
|
| 96 |
|
| 97 |
+
def normalize_user_text(text: str) -> str:
|
| 98 |
+
"""
|
| 99 |
+
Normalize free-text user input for symptom extraction.
|
| 100 |
+
Keeps spaces so phrase matching works.
|
| 101 |
+
"""
|
| 102 |
+
if pd.isna(text):
|
| 103 |
+
return ""
|
| 104 |
+
text = str(text).lower().strip()
|
| 105 |
+
|
| 106 |
+
# Replace underscores with spaces
|
| 107 |
+
text = re.sub(r"\s*_\s*", " ", text)
|
| 108 |
+
|
| 109 |
+
# Remove punctuation except spaces
|
| 110 |
+
text = re.sub(r"[^a-z0-9\s\-]", " ", text)
|
| 111 |
+
|
| 112 |
+
# Collapse repeated whitespace
|
| 113 |
+
text = re.sub(r"\s+", " ", text).strip()
|
| 114 |
+
return text
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def find_symptoms_in_text(user_text: str, known_symptoms: List[str]) -> List[str]:
|
| 118 |
+
"""
|
| 119 |
+
Extract symptoms from free text using exact phrase matching.
|
| 120 |
+
Prefers longer phrases and avoids overlapping partial matches.
|
| 121 |
+
|
| 122 |
+
Example:
|
| 123 |
+
'I have high fever and cough'
|
| 124 |
+
-> ['high fever', 'cough']
|
| 125 |
+
NOT ['fever', 'high fever', 'cough']
|
| 126 |
+
"""
|
| 127 |
+
text = normalize_user_text(user_text)
|
| 128 |
+
if not text:
|
| 129 |
+
return []
|
| 130 |
+
|
| 131 |
+
matched_symptoms = []
|
| 132 |
+
occupied = [False] * len(text)
|
| 133 |
+
|
| 134 |
+
for symptom in known_symptoms:
|
| 135 |
+
if not symptom:
|
| 136 |
+
continue
|
| 137 |
+
|
| 138 |
+
pattern = r"\b" + re.escape(symptom) + r"\b"
|
| 139 |
+
|
| 140 |
+
for m in re.finditer(pattern, text):
|
| 141 |
+
start, end = m.span()
|
| 142 |
+
|
| 143 |
+
# Skip if any part of this span is already used by a longer match
|
| 144 |
+
if any(occupied[start:end]):
|
| 145 |
+
continue
|
| 146 |
+
|
| 147 |
+
matched_symptoms.append(symptom)
|
| 148 |
+
|
| 149 |
+
for i in range(start, end):
|
| 150 |
+
occupied[i] = True
|
| 151 |
+
|
| 152 |
+
return matched_symptoms
|
| 153 |
+
|
| 154 |
+
# Resolve user symptoms from a list of symptom strings, which may include free text and/or symptom names, into a list of canonical symptom names.
|
| 155 |
+
def resolve_user_symptoms(symptoms: List[str]) -> List[str]:
|
| 156 |
+
"""
|
| 157 |
+
Convert a list of user-provided symptom strings into canonical symptom matches.
|
| 158 |
+
|
| 159 |
+
Handles:
|
| 160 |
+
- direct exact matches from list entries
|
| 161 |
+
- free-text extraction from each entry
|
| 162 |
+
- de-duplication while preserving order
|
| 163 |
+
"""
|
| 164 |
+
resolved = []
|
| 165 |
+
seen = set()
|
| 166 |
+
|
| 167 |
+
for item in symptoms:
|
| 168 |
+
if not item:
|
| 169 |
+
continue
|
| 170 |
+
|
| 171 |
+
raw = str(item).strip()
|
| 172 |
+
if not raw:
|
| 173 |
+
continue
|
| 174 |
+
|
| 175 |
+
# First try exact canonical form
|
| 176 |
+
canonical = canon_symptom(raw)
|
| 177 |
+
if canonical in all_symptoms and canonical not in seen:
|
| 178 |
+
resolved.append(canonical)
|
| 179 |
+
seen.add(canonical)
|
| 180 |
+
continue
|
| 181 |
+
|
| 182 |
+
# Otherwise extract symptom phrases from free text
|
| 183 |
+
extracted = find_symptoms_in_text(raw, KNOWN_SYMPTOMS)
|
| 184 |
+
for s in extracted:
|
| 185 |
+
if s not in seen:
|
| 186 |
+
resolved.append(s)
|
| 187 |
+
seen.add(s)
|
| 188 |
+
|
| 189 |
+
return resolved
|
| 190 |
+
|
| 191 |
"""## Format the disease and symptom data"""
|
| 192 |
|
| 193 |
# Create a list of all symptom columns
|
|
|
|
| 208 |
# Create a dictionary of diseases (key) each with a set of symptoms (value)
|
| 209 |
disease_to_symptoms = long.groupby("Disease")["symptom"].apply(set).to_dict()
|
| 210 |
|
| 211 |
+
# Count in how many diseases each symptom appears
|
| 212 |
+
symptom_disease_freq = Counter()
|
| 213 |
+
for disease, symptoms in disease_to_symptoms.items():
|
| 214 |
+
for s in symptoms:
|
| 215 |
+
symptom_disease_freq[s] += 1
|
| 216 |
+
|
| 217 |
+
NUM_DISEASES = len(disease_to_symptoms)
|
| 218 |
+
|
| 219 |
+
# Higher value = more distinctive symptom
|
| 220 |
+
symptom_idf = {
|
| 221 |
+
s: math.log((NUM_DISEASES + 1) / (freq + 1)) + 1
|
| 222 |
+
for s, freq in symptom_disease_freq.items()
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
# A symptom is "uncommon" if it appears in only a small number of diseases
|
| 226 |
+
# Tune this threshold as needed
|
| 227 |
+
UNCOMMON_SYMPTOM_MAX_DISEASE_COUNT = 3
|
| 228 |
+
|
| 229 |
+
uncommon_symptoms = {
|
| 230 |
+
s for s, freq in symptom_disease_freq.items()
|
| 231 |
+
if freq <= UNCOMMON_SYMPTOM_MAX_DISEASE_COUNT
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
# For each disease, which of its symptoms are uncommon/distinguishing?
|
| 235 |
+
disease_to_uncommon_symptoms = {
|
| 236 |
+
disease: (symptoms.intersection(uncommon_symptoms))
|
| 237 |
+
for disease, symptoms in disease_to_symptoms.items()
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
# Based on a separate analysis of the diseases and symptoms, we can identify a set of diseases that are either rare or require heavy context to diagnose properly, and we want to avoid presenting these as likely candidates when the user symptoms are generic or nonspecific, since that could be misleading or cause unnecessary alarm.
|
| 241 |
+
RARE_OR_CONTEXT_HEAVY_DISEASES = {
|
| 242 |
+
"Malaria",
|
| 243 |
+
"Typhoid",
|
| 244 |
+
"Dengue",
|
| 245 |
+
"Hepatitis A",
|
| 246 |
+
"Hepatitis B",
|
| 247 |
+
"Hepatitis C",
|
| 248 |
+
"Hepatitis D",
|
| 249 |
+
"Hepatitis E",
|
| 250 |
+
"AIDS",
|
| 251 |
+
"Tuberculosis",
|
| 252 |
+
"Alcoholic hepatitis",
|
| 253 |
+
"Paralysis (brain hemorrhage)",
|
| 254 |
+
"Heart attack"
|
| 255 |
+
}
|
| 256 |
+
|
| 257 |
+
# Based on a separate analysis of the diseases and symptoms, we can identify a set of diseases that are either rare or require heavy context to diagnose properly, and we want to avoid presenting these as likely candidates when the user symptoms are generic or nonspecific, since that could be misleading or cause unnecessary alarm. For these diseases, we will only allow them as candidates if at least one of the matched symptoms is an uncommon/distinguishing symptom for that disease.
|
| 258 |
+
def rare_disease_allowed(
|
| 259 |
+
disease: str,
|
| 260 |
+
matched_symptoms: set[str],
|
| 261 |
+
) -> tuple[bool, list[str]]:
|
| 262 |
+
"""
|
| 263 |
+
Rare diseases are only allowed if at least one matched symptom
|
| 264 |
+
is an uncommon/distinguishing symptom for that disease.
|
| 265 |
+
Returns:
|
| 266 |
+
(allowed, matched_uncommon_symptoms)
|
| 267 |
+
"""
|
| 268 |
+
if disease not in RARE_OR_CONTEXT_HEAVY_DISEASES:
|
| 269 |
+
return True, []
|
| 270 |
+
|
| 271 |
+
disease_uncommon = disease_to_uncommon_symptoms.get(disease, set())
|
| 272 |
+
matched_uncommon = sorted(matched_symptoms.intersection(disease_uncommon))
|
| 273 |
+
|
| 274 |
+
# Allow only if the user matched at least two uncommon symptoms
|
| 275 |
+
allowed = len(matched_uncommon) > 1
|
| 276 |
+
return allowed, matched_uncommon
|
| 277 |
+
|
| 278 |
# Clean up the symptom values
|
| 279 |
symptom_severity["Symptom"] = symptom_severity["Symptom"].map(canon_symptom)
|
| 280 |
# Set the symptom weights - if the weight is null, set to 0
|
|
|
|
| 304 |
|
| 305 |
# Get the top K candidate diagnoses (diseases) for given symptoms
|
| 306 |
# This function gives highly explainable results for diagnoses
|
| 307 |
+
def disease_candidates(user_symptoms: List[str], top_k: int = 5):
|
| 308 |
+
# Resolve user input into canonical symptoms
|
| 309 |
+
clean_symp = resolve_user_symptoms(user_symptoms)
|
| 310 |
+
if not clean_symp:
|
| 311 |
+
return []
|
| 312 |
+
|
| 313 |
+
clean_symp_set = set(clean_symp)
|
| 314 |
+
|
| 315 |
+
# Denominator based on user-entered evidence
|
| 316 |
+
denominator = sum(
|
| 317 |
+
max(symptom_to_weight.get(s, 1), 1) * symptom_idf.get(s, 1.0)
|
| 318 |
+
for s in clean_symp_set
|
| 319 |
+
) or 1.0
|
| 320 |
+
|
| 321 |
+
candidate_list = []
|
| 322 |
+
|
| 323 |
+
for disease, disease_symptoms in disease_to_symptoms.items():
|
| 324 |
+
matched = clean_symp_set.intersection(disease_symptoms)
|
| 325 |
+
if not matched:
|
| 326 |
+
continue
|
| 327 |
+
|
| 328 |
+
# Rare disease gate:
|
| 329 |
+
# only allow if at least one uncommon/distinguishing symptom
|
| 330 |
+
# from that disease was actually matched by the user
|
| 331 |
+
allowed, matched_uncommon = rare_disease_allowed(disease, matched)
|
| 332 |
+
if not allowed:
|
| 333 |
+
continue
|
| 334 |
+
|
| 335 |
+
numerator = sum(
|
| 336 |
+
max(symptom_to_weight.get(s, 1), 1) * symptom_idf.get(s, 1.0)
|
| 337 |
+
for s in matched
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
user_coverage = numerator / denominator
|
| 341 |
+
|
| 342 |
+
disease_total = sum(
|
| 343 |
+
max(symptom_to_weight.get(s, 1), 1) * symptom_idf.get(s, 1.0)
|
| 344 |
+
for s in disease_symptoms
|
| 345 |
+
) or 1.0
|
| 346 |
+
|
| 347 |
+
disease_coverage = numerator / disease_total
|
| 348 |
+
match_count = len(matched)
|
| 349 |
+
uncommon_match_count = len(matched_uncommon)
|
| 350 |
+
|
| 351 |
+
# Base score
|
| 352 |
+
score = (
|
| 353 |
+
0.60 * user_coverage +
|
| 354 |
+
0.25 * disease_coverage +
|
| 355 |
+
0.10 * min(match_count / 4, 1.0) +
|
| 356 |
+
0.05 * min(uncommon_match_count / 2, 1.0)
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
candidate_list.append({
|
| 360 |
+
"disease": disease,
|
| 361 |
+
"score": round(score, 4),
|
| 362 |
+
"matched_symptoms": sorted(matched),
|
| 363 |
+
"matched_uncommon_symptoms": matched_uncommon,
|
| 364 |
+
"resolved_user_symptoms": clean_symp,
|
| 365 |
+
"is_rare_disease": disease in RARE_OR_CONTEXT_HEAVY_DISEASES,
|
| 366 |
+
})
|
| 367 |
+
|
| 368 |
+
candidate_list.sort(key=lambda x: x["score"], reverse=True)
|
| 369 |
+
return candidate_list[:top_k]
|
| 370 |
+
|
| 371 |
+
# Decide whether the diagnosis candidates are strong enough to present or if we should ask the user for more symptoms / clarification
|
| 372 |
+
def diagnosis_needs_clarification(user_symptoms: List[str], candidates: List[Dict[str, Any]]) -> Dict[str, Any]:
|
| 373 |
+
"""
|
| 374 |
+
Decide whether the evidence is too weak or too generic to present a confident ranking.
|
| 375 |
+
"""
|
| 376 |
+
top_disease = candidates[0]["disease"]
|
| 377 |
+
|
| 378 |
+
if top_disease in RARE_OR_CONTEXT_HEAVY_DISEASES:
|
| 379 |
+
matched = set(candidates[0]["matched_symptoms"])
|
| 380 |
+
matched_specificity = sum(symptom_idf.get(s, 1.0) for s in matched)
|
| 381 |
+
|
| 382 |
+
# Require more signal before surfacing these prominently
|
| 383 |
+
if matched_specificity < 5.5 or len(matched) < 4:
|
| 384 |
+
return {
|
| 385 |
+
"needs_clarification": True,
|
| 386 |
+
"reason": "rare_disease_requires_more_specific_evidence"
|
| 387 |
+
}
|
| 388 |
+
|
| 389 |
+
clean_symp = resolve_user_symptoms(user_symptoms)
|
| 390 |
+
|
| 391 |
+
if len(clean_symp) < 2:
|
| 392 |
+
return {
|
| 393 |
+
"needs_clarification": True,
|
| 394 |
+
"reason": "too_few_symptoms"
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
if not candidates:
|
| 398 |
+
return {
|
| 399 |
+
"needs_clarification": True,
|
| 400 |
+
"reason": "no_candidates"
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
# Average symptom specificity
|
| 404 |
+
avg_specificity = sum(symptom_idf.get(s, 1.0) for s in clean_symp) / max(len(clean_symp), 1)
|
| 405 |
+
|
| 406 |
+
top_score = candidates[0]["score"]
|
| 407 |
+
second_score = candidates[1]["score"] if len(candidates) > 1 else 0.0
|
| 408 |
+
score_gap = top_score - second_score
|
| 409 |
+
|
| 410 |
+
# If all symptoms are generic, ask more
|
| 411 |
+
if avg_specificity < 1.35:
|
| 412 |
+
return {
|
| 413 |
+
"needs_clarification": True,
|
| 414 |
+
"reason": "symptoms_are_common"
|
| 415 |
+
}
|
| 416 |
+
|
| 417 |
+
# If top disease barely beats the next one, ask more
|
| 418 |
+
if score_gap < 0.08:
|
| 419 |
+
return {
|
| 420 |
+
"needs_clarification": True,
|
| 421 |
+
"reason": "top_candidates_too_close"
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
# If top score itself is weak, ask more
|
| 425 |
+
if top_score < 0.45:
|
| 426 |
+
return {
|
| 427 |
+
"needs_clarification": True,
|
| 428 |
+
"reason": "weak_match"
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
return {
|
| 432 |
+
"needs_clarification": False,
|
| 433 |
+
"reason": "enough_signal"
|
| 434 |
+
}
|
| 435 |
+
|
| 436 |
+
# Suggest follow-up questions to ask the user based on their symptoms and the top candidate diseases, to help refine the diagnosis
|
| 437 |
+
def build_followup_questions(user_symptoms: List[str], top_k: int = 5) -> List[str]:
|
| 438 |
+
"""
|
| 439 |
+
Suggest follow-up questions based on symptoms that distinguish among top candidate diseases.
|
| 440 |
+
"""
|
| 441 |
+
clean_symp = set(resolve_user_symptoms(user_symptoms))
|
| 442 |
+
candidates = disease_candidates(list(clean_symp), top_k=top_k)
|
| 443 |
+
|
| 444 |
+
if not candidates:
|
| 445 |
+
return [
|
| 446 |
+
"How long have you had these symptoms?",
|
| 447 |
+
"Have you noticed any other symptoms such as cough, sore throat, nausea, rash, or stomach pain?"
|
| 448 |
+
]
|
| 449 |
+
|
| 450 |
+
candidate_diseases = [c["disease"] for c in candidates]
|
| 451 |
+
candidate_symptom_sets = [disease_to_symptoms[d] for d in candidate_diseases]
|
| 452 |
+
|
| 453 |
+
symptom_counts = Counter()
|
| 454 |
+
for sset in candidate_symptom_sets:
|
| 455 |
+
for s in sset:
|
| 456 |
+
if s not in clean_symp:
|
| 457 |
+
symptom_counts[s] += 1
|
| 458 |
+
|
| 459 |
+
# Good differentiators appear in some but not all candidate diseases
|
| 460 |
+
differentiators = []
|
| 461 |
+
n = len(candidate_symptom_sets)
|
| 462 |
+
for s, count in symptom_counts.items():
|
| 463 |
+
if 1 <= count < n:
|
| 464 |
+
differentiators.append((s, count, symptom_idf.get(s, 1.0)))
|
| 465 |
+
|
| 466 |
+
differentiators.sort(key=lambda x: (-x[2], abs((n / 2) - x[1]), x[0]))
|
| 467 |
+
|
| 468 |
+
chosen = [s for s, _, _ in differentiators[:5]]
|
| 469 |
+
|
| 470 |
+
questions = []
|
| 471 |
+
for s in chosen:
|
| 472 |
+
questions.append(f"Are you also experiencing {s}?")
|
| 473 |
+
|
| 474 |
+
# Add a few high-value context questions
|
| 475 |
+
questions.extend([
|
| 476 |
+
"How long have you had these symptoms?",
|
| 477 |
+
"Do you have cough, sore throat, or runny nose?",
|
| 478 |
+
"Any nausea, vomiting, abdominal pain, or diarrhea?",
|
| 479 |
+
"Have you traveled recently or been exposed to mosquitoes or sick contacts?"
|
| 480 |
+
])
|
| 481 |
+
|
| 482 |
+
# Deduplicate while preserving order
|
| 483 |
+
seen = set()
|
| 484 |
+
final_questions = []
|
| 485 |
+
for q in questions:
|
| 486 |
+
if q not in seen:
|
| 487 |
+
final_questions.append(q)
|
| 488 |
+
seen.add(q)
|
| 489 |
+
|
| 490 |
+
return final_questions[:6]
|
| 491 |
|
| 492 |
# Get a report of severity based on symptoms
|
| 493 |
+
def severity_report(user_symptoms: List[str]):
|
| 494 |
+
clean_symp = resolve_user_symptoms(user_symptoms)
|
| 495 |
+
|
| 496 |
+
weight_per_symp = [(s, symptom_to_weight.get(s, 0)) for s in clean_symp]
|
| 497 |
+
total = sum(w for _, w in weight_per_symp)
|
| 498 |
+
|
| 499 |
+
if total <= 5:
|
| 500 |
+
level = "mild"
|
| 501 |
+
elif total <= 12:
|
| 502 |
+
level = "moderate"
|
| 503 |
+
else:
|
| 504 |
+
level = "high"
|
| 505 |
+
|
| 506 |
+
no_severity = [s for s in clean_symp if s not in symptom_to_weight]
|
| 507 |
+
|
| 508 |
+
return {
|
| 509 |
+
"Resolved symptoms": clean_symp,
|
| 510 |
+
"Total": total,
|
| 511 |
+
"Level": level,
|
| 512 |
+
"Per symptom": weight_per_symp,
|
| 513 |
+
"Symptoms not in severity table": no_severity,
|
| 514 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 515 |
|
| 516 |
# Check data quality
|
| 517 |
all_symptoms = set().union(*disease_to_symptoms.values())
|
| 518 |
+
|
| 519 |
+
# Build a searchable symptom vocabulary
|
| 520 |
+
KNOWN_SYMPTOMS = sorted(all_symptoms, key=lambda s: (-len(s.split()), -len(s), s))
|
| 521 |
+
|
| 522 |
# Get all symptoms w/out a severity weight
|
| 523 |
missing_severity = sorted([s for s in all_symptoms if s not in symptom_to_weight])
|
| 524 |
|
|
|
|
| 600 |
# Top K docs to retrieve (default to 3, but should be between 1 and 10)
|
| 601 |
k: int = Field(3, ge=1, le=10, description="How many disease docs to retrieve")
|
| 602 |
|
| 603 |
+
class ClarificationInput(BaseModel):
|
| 604 |
+
symptoms: List[str] = Field(..., description="List of symptoms or free-text symptom statements")
|
| 605 |
+
top_k: int = Field(5, ge=1, le=10, description="Number of candidate diseases to consider")
|
| 606 |
+
|
| 607 |
# Tools (using RAG, so they are deterministic)
|
| 608 |
|
| 609 |
# Create a diagnosic tool, using our schema
|
| 610 |
@tool(args_schema=DiagnoseInput)
|
| 611 |
+
def diagnose_diseases(symptoms: List[str], top_k: int = 5) -> str:
|
| 612 |
+
"""
|
| 613 |
+
Suggest likely diseases based on symptoms.
|
| 614 |
+
Accepts either:
|
| 615 |
+
- a list of symptom names
|
| 616 |
+
- or free-text symptom statements
|
| 617 |
+
Uses exact phrase matching with longer phrases preferred.
|
| 618 |
+
Returns ranked candidates as JSON.
|
| 619 |
+
"""
|
| 620 |
+
results = disease_candidates(symptoms, top_k=top_k)
|
| 621 |
+
return json.dumps({"candidates": results}, indent=2)
|
| 622 |
|
| 623 |
# Create a symptom severity calculation tool, using our schema
|
| 624 |
@tool(args_schema=SeverityInput)
|
| 625 |
def calc_symptom_severity(symptoms: List[str]) -> str:
|
| 626 |
+
"""
|
| 627 |
+
Calculate a symptom severity score using known symptom phrases.
|
| 628 |
+
Accepts symptom names or free-text symptom statements.
|
| 629 |
+
Returns resolved symptoms, total score, severity level, and per-symptom weights.
|
| 630 |
+
"""
|
| 631 |
+
report = severity_report(symptoms)
|
| 632 |
+
return json.dumps(report, indent=2)
|
|
|
|
| 633 |
|
| 634 |
# Create a tool to get disease description, using our schema
|
| 635 |
@tool(args_schema=DiseaseInfoInput)
|
|
|
|
| 669 |
)
|
| 670 |
return serialized
|
| 671 |
|
| 672 |
+
# Create a tool to assess diagnosis confidence and suggest follow-up questions, using our schema
|
| 673 |
+
@tool(args_schema=ClarificationInput)
|
| 674 |
+
def assess_diagnosis_confidence(symptoms: List[str], top_k: int = 5) -> str:
|
| 675 |
+
"""
|
| 676 |
+
Assess whether current symptoms are specific enough for a meaningful diagnosis ranking
|
| 677 |
+
or whether follow-up questions should be asked first.
|
| 678 |
+
"""
|
| 679 |
+
candidates = disease_candidates(symptoms, top_k=top_k)
|
| 680 |
+
decision = diagnosis_needs_clarification(symptoms, candidates)
|
| 681 |
+
followups = build_followup_questions(symptoms, top_k=top_k) if decision["needs_clarification"] else []
|
| 682 |
+
|
| 683 |
+
return json.dumps({
|
| 684 |
+
"decision": decision,
|
| 685 |
+
"follow_up_questions": followups,
|
| 686 |
+
"candidates_preview": candidates[:3],
|
| 687 |
+
}, indent=2)
|
| 688 |
+
|
| 689 |
tools = [
|
| 690 |
diagnose_diseases,
|
| 691 |
calc_symptom_severity,
|
| 692 |
get_disease_description,
|
| 693 |
get_precaution_advice,
|
| 694 |
retrieve_disease_docs,
|
| 695 |
+
assess_diagnosis_confidence,
|
| 696 |
]
|
| 697 |
|
| 698 |
# LLM + orchestrator agent
|
|
|
|
| 704 |
model_provider="openai",
|
| 705 |
api_key=OPENAI_API_KEY,
|
| 706 |
)
|
| 707 |
+
|
| 708 |
system_prompt = """
|
| 709 |
You are a medical decision support assistant, not to be used as a replacement for professional medical care.
|
| 710 |
+
|
| 711 |
In your responses, always:
|
| 712 |
+
- Use tools to assess symptom severity and diagnostic confidence
|
| 713 |
+
- Do not suggest rare diseases unless the user provides at least two uncommon/distinguishing symptom associated with that disease
|
| 714 |
+
- If symptoms are generic and nonspecific, ask follow-up questions instead of surfacing rare diseases
|
| 715 |
- Provide a disclaimer that the user should consult with a doctor
|
| 716 |
+
- Give precaution advice and recommend professional medical care when appropriate
|
| 717 |
+
- If symptoms suggest a serious emergency risk (e.g. chest pain, difficulty breathing, serious bleeding), recommend urgent care or emergency room services
|
| 718 |
|
| 719 |
Workflow to follow:
|
| 720 |
1) Ask for symptoms if not provided by user
|
| 721 |
2) Call calc_symptom_severity(symptoms)
|
| 722 |
+
3) Call assess_diagnosis_confidence(symptoms, top_k=5)
|
| 723 |
+
4) If the confidence tool says clarification is needed, ask 3-6 concise follow-up questions and do not provide a ranked diagnosis yet
|
| 724 |
+
5) If the confidence tool says enough signal exists, call diagnose_diseases(symptoms, top_k=5)
|
| 725 |
+
6) For the top 1-3 diseases, call retrieve_disease_docs using the disease name or symptoms
|
| 726 |
+
7) Return: top candidates with why, severity level, description + precautions for the top candidate(s), and next steps
|
| 727 |
|
| 728 |
Responses should always be concise.
|
| 729 |
""".strip()
|
|
|
|
| 810 |
with gr.Blocks(title="MediBot – Disease & Symptom Assistant") as demo:
|
| 811 |
gr.Markdown(
|
| 812 |
"""
|
| 813 |
+
# MediBot
|
| 814 |
Enter your symptoms in plain language (comma-separated is fine).
|
| 815 |
**Note:** This is not medical advice—consult a clinician for diagnosis and treatment.
|
| 816 |
""".strip()
|