Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,4 @@
|
|
| 1 |
-
##
|
| 2 |
-
|
| 3 |
|
| 4 |
import os
|
| 5 |
import gradio as gr
|
|
@@ -22,7 +21,8 @@ SAMPLE_PDF = "sample_patient_chart.pdf" # Place a sample PDF in the same folder
|
|
| 22 |
|
| 23 |
|
| 24 |
# ---------- JSON to Markdown ----------
|
| 25 |
-
|
|
|
|
| 26 |
try:
|
| 27 |
if isinstance(data, dict):
|
| 28 |
file_name = data.get("file_name", "Unknown Patient")
|
|
@@ -41,9 +41,15 @@ def json_to_markdown(data) -> str:
|
|
| 41 |
else:
|
| 42 |
return "<div style='color:red; font-weight:bold;'>β οΈ Invalid data format for report.</div>"
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
md = f"""
|
| 45 |
-
<div style="border:2px solid
|
| 46 |
-
<h2 style="color:
|
| 47 |
<p><b>π§Ύ File Name:</b> {file_name}</p>
|
| 48 |
<p><b>π·οΈ HCC Code:</b> {hcc_code}</p>
|
| 49 |
<p><b>βοΈ Model Version:</b> {model_version}</p>
|
|
@@ -52,7 +58,7 @@ def json_to_markdown(data) -> str:
|
|
| 52 |
# Add demographics
|
| 53 |
if any([patient_name, dob, age, gender, address, phone, patient_identifier]):
|
| 54 |
md += "<hr style='border:0;border-top:1px solid #c8e6c9;margin:10px 0;'/>"
|
| 55 |
-
md += "<h3 style='color:
|
| 56 |
if patient_name: md += f"<p><b>Name:</b> {patient_name}</p>"
|
| 57 |
if patient_identifier: md += f"<p><b>Patient Identifier:</b> {patient_identifier}</p>"
|
| 58 |
if dob: md += f"<p><b>Date of Birth:</b> {dob}</p>"
|
|
@@ -195,9 +201,19 @@ def process_pipeline(pdf_file, hcc_code, model_version, csv_path=CSV_PATH, outpu
|
|
| 195 |
yield demographics_md + log(f"π Step {step}/{total_steps}: Checking diagnoses in patient chart...", step)
|
| 196 |
all_checked_results = ChartDiagnosisChecker(pdf_path).run(diagnoses)
|
| 197 |
confirmed_diagnoses = [d for d in all_checked_results if d.get("answer_explicit", "").lower() == "yes" or d.get("answer_implicit", "").lower() == "yes"]
|
|
|
|
|
|
|
| 198 |
if not confirmed_diagnoses:
|
| 199 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
return
|
|
|
|
| 201 |
|
| 202 |
# Step 4: Tests
|
| 203 |
step += 1
|
|
@@ -337,18 +353,16 @@ with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
|
|
| 337 |
outputs=[output_md],
|
| 338 |
)
|
| 339 |
|
| 340 |
-
# --- MODIFICATION: Adjusted column scaling to make the Examples section smaller ---
|
| 341 |
with gr.Row():
|
| 342 |
-
with gr.Column(scale=1):
|
| 343 |
gr.Examples(
|
| 344 |
examples=[[SAMPLE_PDF, "12", "V24"]],
|
| 345 |
inputs=[pdf_upload, hcc_code, model_version],
|
| 346 |
label="Click to load an example",
|
| 347 |
cache_examples=False
|
| 348 |
)
|
| 349 |
-
with gr.Column(scale=2):
|
| 350 |
pass
|
| 351 |
-
# --- END OF MODIFICATION ---
|
| 352 |
|
| 353 |
|
| 354 |
if __name__ == "__main__":
|
|
@@ -357,6 +371,365 @@ if __name__ == "__main__":
|
|
| 357 |
server_port=int(os.environ.get("PORT", 7860))
|
| 358 |
)
|
| 359 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
# import os
|
| 361 |
# import gradio as gr
|
| 362 |
# import json
|
|
|
|
| 1 |
+
## Adding red box for failure
|
|
|
|
| 2 |
|
| 3 |
import os
|
| 4 |
import gradio as gr
|
|
|
|
| 21 |
|
| 22 |
|
| 23 |
# ---------- JSON to Markdown ----------
|
| 24 |
+
# --- MODIFICATION: Added 'status' parameter to control color scheme ---
|
| 25 |
+
def json_to_markdown(data, status='success') -> str:
|
| 26 |
try:
|
| 27 |
if isinstance(data, dict):
|
| 28 |
file_name = data.get("file_name", "Unknown Patient")
|
|
|
|
| 41 |
else:
|
| 42 |
return "<div style='color:red; font-weight:bold;'>β οΈ Invalid data format for report.</div>"
|
| 43 |
|
| 44 |
+
# Dynamically set colors based on status
|
| 45 |
+
if status == 'error':
|
| 46 |
+
border_color, bg_color, header_color = "#f44336", "#ffeb ee", "#d32f2f" # Red theme
|
| 47 |
+
else:
|
| 48 |
+
border_color, bg_color, header_color = "#4CAF50", "#f9fdf9", "#2e7d32" # Green theme
|
| 49 |
+
|
| 50 |
md = f"""
|
| 51 |
+
<div style="border:2px solid {border_color}; padding:15px; border-radius:10px; background:{bg_color};">
|
| 52 |
+
<h2 style="color:{header_color};">π HCC Chart Validation Report </h2>
|
| 53 |
<p><b>π§Ύ File Name:</b> {file_name}</p>
|
| 54 |
<p><b>π·οΈ HCC Code:</b> {hcc_code}</p>
|
| 55 |
<p><b>βοΈ Model Version:</b> {model_version}</p>
|
|
|
|
| 58 |
# Add demographics
|
| 59 |
if any([patient_name, dob, age, gender, address, phone, patient_identifier]):
|
| 60 |
md += "<hr style='border:0;border-top:1px solid #c8e6c9;margin:10px 0;'/>"
|
| 61 |
+
md += f"<h3 style='color:{header_color};'>π€ Patient Demographics</h3>" # Use dynamic color
|
| 62 |
if patient_name: md += f"<p><b>Name:</b> {patient_name}</p>"
|
| 63 |
if patient_identifier: md += f"<p><b>Patient Identifier:</b> {patient_identifier}</p>"
|
| 64 |
if dob: md += f"<p><b>Date of Birth:</b> {dob}</p>"
|
|
|
|
| 201 |
yield demographics_md + log(f"π Step {step}/{total_steps}: Checking diagnoses in patient chart...", step)
|
| 202 |
all_checked_results = ChartDiagnosisChecker(pdf_path).run(diagnoses)
|
| 203 |
confirmed_diagnoses = [d for d in all_checked_results if d.get("answer_explicit", "").lower() == "yes" or d.get("answer_implicit", "").lower() == "yes"]
|
| 204 |
+
|
| 205 |
+
# --- MODIFICATION: Custom failure UI for this specific condition ---
|
| 206 |
if not confirmed_diagnoses:
|
| 207 |
+
error_report_md = json_to_markdown(initial_report_data, status='error')
|
| 208 |
+
error_message = f"No confirmed diagnoses found for HCC {hcc_code_str} in the patient chart."
|
| 209 |
+
error_box_html = f"""
|
| 210 |
+
<div style='border:1px solid #d32f2f; color: #c62828; background-color: #ffcdd2; padding:12px; border-radius:8px; margin-top:15px;'>
|
| 211 |
+
<b>β Validation Failed:</b> {error_message}
|
| 212 |
+
</div>
|
| 213 |
+
"""
|
| 214 |
+
yield error_report_md + error_box_html
|
| 215 |
return
|
| 216 |
+
# --- END OF MODIFICATION ---
|
| 217 |
|
| 218 |
# Step 4: Tests
|
| 219 |
step += 1
|
|
|
|
| 353 |
outputs=[output_md],
|
| 354 |
)
|
| 355 |
|
|
|
|
| 356 |
with gr.Row():
|
| 357 |
+
with gr.Column(scale=1):
|
| 358 |
gr.Examples(
|
| 359 |
examples=[[SAMPLE_PDF, "12", "V24"]],
|
| 360 |
inputs=[pdf_upload, hcc_code, model_version],
|
| 361 |
label="Click to load an example",
|
| 362 |
cache_examples=False
|
| 363 |
)
|
| 364 |
+
with gr.Column(scale=2):
|
| 365 |
pass
|
|
|
|
| 366 |
|
| 367 |
|
| 368 |
if __name__ == "__main__":
|
|
|
|
| 371 |
server_port=int(os.environ.get("PORT", 7860))
|
| 372 |
)
|
| 373 |
|
| 374 |
+
# ## small samples
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
# import os
|
| 378 |
+
# import gradio as gr
|
| 379 |
+
# import json
|
| 380 |
+
# import time
|
| 381 |
+
# import base64
|
| 382 |
+
# from dotenv import load_dotenv
|
| 383 |
+
# from ClinicalStatusAgent import ClinicalStatusAgent
|
| 384 |
+
# from TestFindingAgent import TestFindingAgent
|
| 385 |
+
# from ComorbidityCheckerAgent import ComorbidityCheckerAgent
|
| 386 |
+
# from HCCDiagnosisListEngine import HCCDiagnosisListEngine
|
| 387 |
+
# from chartdiagnosischecker import ChartDiagnosisChecker
|
| 388 |
+
# from MeatValidatorAgent import MEATValidatorAgent
|
| 389 |
+
# from PatientInfoExtractionEngine import PatientInfoExtractionEngine
|
| 390 |
+
|
| 391 |
+
# load_dotenv()
|
| 392 |
+
# APP_TITLE = "Risk Adjustment (HCC Chart Validation)"
|
| 393 |
+
# CSV_PATH = "hcc_mapping.csv"
|
| 394 |
+
# SAMPLE_PDF = "sample_patient_chart.pdf" # Place a sample PDF in the same folder
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
# # ---------- JSON to Markdown ----------
|
| 398 |
+
# def json_to_markdown(data) -> str:
|
| 399 |
+
# try:
|
| 400 |
+
# if isinstance(data, dict):
|
| 401 |
+
# file_name = data.get("file_name", "Unknown Patient")
|
| 402 |
+
# hcc_code = data.get("hcc_code", "N/A")
|
| 403 |
+
# model_version = data.get("model_version", "N/A")
|
| 404 |
+
# analyses = data.get("final_analysis", [])
|
| 405 |
+
|
| 406 |
+
# # Demographics
|
| 407 |
+
# patient_name = data.get("patient_name", "")
|
| 408 |
+
# dob = data.get("dob", "")
|
| 409 |
+
# age = data.get("age", "")
|
| 410 |
+
# gender = data.get("gender", "")
|
| 411 |
+
# address = data.get("address", "")
|
| 412 |
+
# phone = data.get("phone", "")
|
| 413 |
+
# patient_identifier = data.get("patient_identifier", "")
|
| 414 |
+
# else:
|
| 415 |
+
# return "<div style='color:red; font-weight:bold;'>β οΈ Invalid data format for report.</div>"
|
| 416 |
+
|
| 417 |
+
# md = f"""
|
| 418 |
+
# <div style="border:2px solid #4CAF50; padding:15px; border-radius:10px; background:#f9fdf9;">
|
| 419 |
+
# <h2 style="color:#2e7d32;">π HCC Chart Validation Report </h2>
|
| 420 |
+
# <p><b>π§Ύ File Name:</b> {file_name}</p>
|
| 421 |
+
# <p><b>π·οΈ HCC Code:</b> {hcc_code}</p>
|
| 422 |
+
# <p><b>βοΈ Model Version:</b> {model_version}</p>
|
| 423 |
+
# """
|
| 424 |
+
|
| 425 |
+
# # Add demographics
|
| 426 |
+
# if any([patient_name, dob, age, gender, address, phone, patient_identifier]):
|
| 427 |
+
# md += "<hr style='border:0;border-top:1px solid #c8e6c9;margin:10px 0;'/>"
|
| 428 |
+
# md += "<h3 style='color:#1b5e20;'>π€ Patient Demographics</h3>"
|
| 429 |
+
# if patient_name: md += f"<p><b>Name:</b> {patient_name}</p>"
|
| 430 |
+
# if patient_identifier: md += f"<p><b>Patient Identifier:</b> {patient_identifier}</p>"
|
| 431 |
+
# if dob: md += f"<p><b>Date of Birth:</b> {dob}</p>"
|
| 432 |
+
# if age: md += f"<p><b>Age:</b> {age}</p>"
|
| 433 |
+
# if gender: md += f"<p><b>Gender:</b> {gender}</p>"
|
| 434 |
+
# if address: md += f"<p><b>Address:</b> {address}</p>"
|
| 435 |
+
# if phone: md += f"<p><b>Phone:</b> {phone}</p>"
|
| 436 |
+
|
| 437 |
+
# md += "</div><br/>"
|
| 438 |
+
|
| 439 |
+
# # Render analyses if they exist
|
| 440 |
+
# if analyses:
|
| 441 |
+
# for idx, diag in enumerate(analyses, 1):
|
| 442 |
+
# md += f"""
|
| 443 |
+
# <div style="border:1px solid #ccc; padding:12px; border-radius:8px; margin-bottom:12px;">
|
| 444 |
+
# <h3 style="color:#1565c0;">Diagnosis {idx}. {diag.get("diagnosis", "Unknown Diagnosis")}</h3>
|
| 445 |
+
# <p><b>ICD-10:</b> {diag.get("icd10", "N/A")}</p>
|
| 446 |
+
# <p><b>Reference:</b> <a href="{diag.get("reference","")}" target="_blank">{diag.get("reference","")}</a></p>
|
| 447 |
+
# """
|
| 448 |
+
# explicit_ans = diag.get("answer_explicit", "N/A")
|
| 449 |
+
# explicit_rat = diag.get("rationale_explicit", "")
|
| 450 |
+
# implicit_ans = diag.get("answer_implicit", "N/A")
|
| 451 |
+
# implicit_rat = diag.get("rationale_implicit", "")
|
| 452 |
+
|
| 453 |
+
# if explicit_ans.lower() == "yes":
|
| 454 |
+
# md += f"<p><b>Explicit:</b> {explicit_ans} β {explicit_rat}</p>"
|
| 455 |
+
# else:
|
| 456 |
+
# md += f"<p><b>Implicit:</b> {implicit_ans} β {implicit_rat}</p>"
|
| 457 |
+
|
| 458 |
+
# md += f"""
|
| 459 |
+
# <p><b>Clinical Status:</b> {diag.get("clinical_status","N/A")}</p>
|
| 460 |
+
# <p><b>Status Rationale:</b> {diag.get("status_rationale","")}</p>
|
| 461 |
+
# """
|
| 462 |
+
# if "tests" in diag:
|
| 463 |
+
# md += "<details><summary><b>π§ͺ Tests & Procedures</b></summary><ul>"
|
| 464 |
+
# tests = diag["tests"]
|
| 465 |
+
# if "vitals" in tests:
|
| 466 |
+
# md += "<li><b>Vitals:</b><ul>"
|
| 467 |
+
# for k, v in tests["vitals"].items(): md += f"<li>{k}: {v}</li>"
|
| 468 |
+
# md += "</ul></li>"
|
| 469 |
+
# if "procedures" in tests:
|
| 470 |
+
# md += "<li><b>Procedures:</b><ul>"
|
| 471 |
+
# for k, v in tests["procedures"].items(): md += f"<li>{k}: {v}</li>"
|
| 472 |
+
# md += "</ul></li>"
|
| 473 |
+
# if "lab_test" in tests:
|
| 474 |
+
# md += "<li><b>Lab Tests:</b><ul>"
|
| 475 |
+
# for k, v in tests["lab_test"].items(): md += f"<li>{k}: {v}</li>"
|
| 476 |
+
# md += "</ul></li>"
|
| 477 |
+
# md += "</ul></details>"
|
| 478 |
+
|
| 479 |
+
# if "meat" in diag:
|
| 480 |
+
# md += "<details><summary><b>π MEAT Validation</b></summary><ul>"
|
| 481 |
+
# for k, v in diag["meat"].items():
|
| 482 |
+
# emoji = "β
" if v else "β"
|
| 483 |
+
# md += f"<li>{k.capitalize()}: {emoji}</li>"
|
| 484 |
+
# md += "</ul>"
|
| 485 |
+
# md += f"<p><b>MEAT Rationale:</b> {diag.get('meat_rationale','')}</p>"
|
| 486 |
+
# md += "</details>"
|
| 487 |
+
|
| 488 |
+
# if "comorbidities" in diag and diag["comorbidities"]:
|
| 489 |
+
# present_comorbidities = [c for c in diag["comorbidities"] if c.get("is_present")]
|
| 490 |
+
# if present_comorbidities:
|
| 491 |
+
# md += "<details open><summary><b>π©Ί Comorbidities</b></summary><ul>"
|
| 492 |
+
# for c in present_comorbidities:
|
| 493 |
+
# md += f"<li>β
<b>{c.get('condition')}</b><br/><i>{c.get('rationale')}</i></li>"
|
| 494 |
+
# md += "</ul></details>"
|
| 495 |
+
|
| 496 |
+
# md += "</div>"
|
| 497 |
+
# return md
|
| 498 |
+
# except Exception as e:
|
| 499 |
+
# return f"<div style='color:red; font-weight:bold;'>β οΈ Error rendering report: {e}</div>"
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
# # ---------- Processing Pipeline with Gradio Progress ----------
|
| 503 |
+
# def process_pipeline(pdf_file, hcc_code, model_version, csv_path=CSV_PATH, output_folder="outputs"):
|
| 504 |
+
# try:
|
| 505 |
+
# start = time.time()
|
| 506 |
+
# step = 0
|
| 507 |
+
# total_steps = 8 # Total number of steps in the pipeline
|
| 508 |
+
|
| 509 |
+
# def log(msg, current_step=0):
|
| 510 |
+
# elapsed = time.time() - start
|
| 511 |
+
# bar_html = '<div style="display: flex; width: 100%; gap: 2px; height: 12px; margin: 8px 0 5px 0;">'
|
| 512 |
+
# for i in range(1, total_steps + 1):
|
| 513 |
+
# if i < current_step: color = "#1e40af"
|
| 514 |
+
# elif i == current_step: color = "#3b82f6"
|
| 515 |
+
# else: color = "#e5e7eb"
|
| 516 |
+
# bar_html += f'<div style="flex-grow: 1; background-color: {color}; border-radius: 3px;"></div>'
|
| 517 |
+
# bar_html += '</div>'
|
| 518 |
+
# return f"<div style='padding-top:10px;'>{msg}{bar_html}<small>β³ Elapsed: {elapsed:.1f} sec</small></div>"
|
| 519 |
+
|
| 520 |
+
# if pdf_file is None:
|
| 521 |
+
# yield log("β οΈ Please upload a patient chart PDF.", 0)
|
| 522 |
+
# return
|
| 523 |
+
# hcc_code_str = str(hcc_code or "").strip()
|
| 524 |
+
# if not hcc_code_str:
|
| 525 |
+
# yield log("β οΈ Please enter a valid HCC Code before running validation.", 0)
|
| 526 |
+
# return
|
| 527 |
+
|
| 528 |
+
# os.makedirs(output_folder, exist_ok=True)
|
| 529 |
+
# pdf_path = pdf_file.name
|
| 530 |
+
# file_name = os.path.splitext(os.path.basename(pdf_path))[0]
|
| 531 |
+
# print(f"[PROCESSING] {file_name}")
|
| 532 |
+
|
| 533 |
+
# # Step 1: Extract Demographics
|
| 534 |
+
# step += 1
|
| 535 |
+
# initial_progress_msg = log(f"π§ Step {step}/{total_steps}: Extracting patient demographics...", step)
|
| 536 |
+
# yield initial_progress_msg
|
| 537 |
+
# demographics_engine = PatientInfoExtractionEngine(pdf_path)
|
| 538 |
+
# demographics_info = demographics_engine.run()
|
| 539 |
+
# print(f"[DEMOGRAPHICS] Extracted: {demographics_info}")
|
| 540 |
+
|
| 541 |
+
# initial_report_data = {
|
| 542 |
+
# "file_name": file_name,
|
| 543 |
+
# "hcc_code": hcc_code_str,
|
| 544 |
+
# "model_version": model_version,
|
| 545 |
+
# "final_analysis": [],
|
| 546 |
+
# "patient_name": demographics_info.get("name", ""),
|
| 547 |
+
# "dob": demographics_info.get("dob", ""),
|
| 548 |
+
# "age": demographics_info.get("age", ""),
|
| 549 |
+
# "gender": demographics_info.get("gender", ""),
|
| 550 |
+
# "address": demographics_info.get("address", ""),
|
| 551 |
+
# "phone": demographics_info.get("phone", ""),
|
| 552 |
+
# "patient_identifier": demographics_info.get("patient_identifier", "")
|
| 553 |
+
# }
|
| 554 |
+
# demographics_md = json_to_markdown(initial_report_data)
|
| 555 |
+
# yield demographics_md
|
| 556 |
+
# time.sleep(0.5)
|
| 557 |
+
|
| 558 |
+
# # Step 2: Diagnoses
|
| 559 |
+
# step += 1
|
| 560 |
+
# yield demographics_md + log(f"π Step {step}/{total_steps}: Extracting possible HCC Diagnoses...", step)
|
| 561 |
+
# diagnoses = HCCDiagnosisListEngine(hcc_code_str, model_version, csv_path).run()
|
| 562 |
+
# if not diagnoses:
|
| 563 |
+
# yield demographics_md + log(f"β No diagnoses found for HCC {hcc_code_str}.", step)
|
| 564 |
+
# return
|
| 565 |
+
|
| 566 |
+
# # Step 3: Chart checking
|
| 567 |
+
# step += 1
|
| 568 |
+
# yield demographics_md + log(f"π Step {step}/{total_steps}: Checking diagnoses in patient chart...", step)
|
| 569 |
+
# all_checked_results = ChartDiagnosisChecker(pdf_path).run(diagnoses)
|
| 570 |
+
# confirmed_diagnoses = [d for d in all_checked_results if d.get("answer_explicit", "").lower() == "yes" or d.get("answer_implicit", "").lower() == "yes"]
|
| 571 |
+
# if not confirmed_diagnoses:
|
| 572 |
+
# yield demographics_md + log(f"β No confirmed diagnoses for HCC {hcc_code_str} in {file_name}.", step)
|
| 573 |
+
# return
|
| 574 |
+
|
| 575 |
+
# # Step 4: Tests
|
| 576 |
+
# step += 1
|
| 577 |
+
# yield demographics_md + log(f"π§ͺ Step {step}/{total_steps}: Finding relevant tests...", step)
|
| 578 |
+
# diagnoses_with_tests = TestFindingAgent(hcc_code=hcc_code_str, model_version=model_version).run(confirmed_diagnoses)
|
| 579 |
+
|
| 580 |
+
# # Step 5: Clinical Status
|
| 581 |
+
# step += 1
|
| 582 |
+
# yield demographics_md + log(f"βοΈ Step {step}/{total_steps}: Determining clinical status...", step)
|
| 583 |
+
# diagnoses_with_status = ClinicalStatusAgent().run(diagnoses_with_tests)
|
| 584 |
+
# active_diagnoses = [d for d in diagnoses_with_status if d.get("clinical_status") == "ACTIVE"]
|
| 585 |
+
|
| 586 |
+
# # Step 6: MEAT
|
| 587 |
+
# step += 1
|
| 588 |
+
# if active_diagnoses:
|
| 589 |
+
# yield demographics_md + log(f"π Step {step}/{total_steps}: Validating MEAT...", step)
|
| 590 |
+
# validated_meat_diagnoses = MEATValidatorAgent().run(active_diagnoses)
|
| 591 |
+
# else:
|
| 592 |
+
# validated_meat_diagnoses = []
|
| 593 |
+
# yield demographics_md + log("βΉοΈ No ACTIVE diagnoses found. Skipping MEAT/Comorbidity.", step)
|
| 594 |
+
|
| 595 |
+
# # Step 7: Comorbidities
|
| 596 |
+
# step += 1
|
| 597 |
+
# diagnoses_passed_meat = [d for d in validated_meat_diagnoses if any(d.get("meat", {}).values())]
|
| 598 |
+
# if diagnoses_passed_meat:
|
| 599 |
+
# yield demographics_md + log(f"π€ Step {step}/{total_steps}: Checking comorbidities...", step)
|
| 600 |
+
# comorbidity_results = ComorbidityCheckerAgent(pdf_path, hcc_code_str, model_version).run(diagnoses_passed_meat)
|
| 601 |
+
# else:
|
| 602 |
+
# comorbidity_results = []
|
| 603 |
+
|
| 604 |
+
# # Step 8: Final Report
|
| 605 |
+
# step += 1
|
| 606 |
+
# yield demographics_md + log(f"β
Step {step}/{total_steps}: Generating final report...", step)
|
| 607 |
+
|
| 608 |
+
# # Merge results for final output
|
| 609 |
+
# status_map = {d["diagnosis"]: d for d in diagnoses_with_status}
|
| 610 |
+
# meat_map = {d["diagnosis"]: d for d in validated_meat_diagnoses}
|
| 611 |
+
# comorbidity_map = {d["diagnosis"]: d for d in comorbidity_results}
|
| 612 |
+
# final_analysis = []
|
| 613 |
+
# for entry in all_checked_results:
|
| 614 |
+
# diag_name = entry["diagnosis"]
|
| 615 |
+
# updated_entry = entry.copy()
|
| 616 |
+
# if diag_name in status_map: updated_entry.update(status_map[diag_name])
|
| 617 |
+
# if diag_name in meat_map: updated_entry.update(meat_map[diag_name])
|
| 618 |
+
# if diag_name in comorbidity_map: updated_entry.update(comorbidity_map[diag_name])
|
| 619 |
+
# final_analysis.append(updated_entry)
|
| 620 |
+
|
| 621 |
+
# filtered_final_analysis = [e for e in final_analysis if e.get("answer_explicit", "").lower() == "yes" or e.get("answer_implicit", "").lower() == "yes"]
|
| 622 |
+
|
| 623 |
+
# output_data = {
|
| 624 |
+
# "file_name": file_name,
|
| 625 |
+
# "hcc_code": hcc_code_str,
|
| 626 |
+
# "model_version": model_version,
|
| 627 |
+
# "final_analysis": filtered_final_analysis,
|
| 628 |
+
# "patient_name": demographics_info.get("name", ""),
|
| 629 |
+
# "dob": demographics_info.get("dob", ""),
|
| 630 |
+
# "age": demographics_info.get("age", ""),
|
| 631 |
+
# "gender": demographics_info.get("gender", ""),
|
| 632 |
+
# "address": demographics_info.get("address", ""),
|
| 633 |
+
# "phone": demographics_info.get("phone", ""),
|
| 634 |
+
# "patient_identifier": demographics_info.get("patient_identifier", "")
|
| 635 |
+
# }
|
| 636 |
+
|
| 637 |
+
# elapsed = time.time() - start
|
| 638 |
+
# yield json_to_markdown(output_data) + f"<br/><div style='color:green;'>β
Completed in {elapsed:.1f} sec</div>"
|
| 639 |
+
|
| 640 |
+
# except Exception as e:
|
| 641 |
+
# print(f"[ERROR] {e}")
|
| 642 |
+
# yield f"<div style='color:red; font-weight:bold;'>β οΈ Error: {e}</div>"
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
# # ---------- Gradio Theme and Helpers ----------
|
| 646 |
+
# simple_theme = gr.themes.Soft(
|
| 647 |
+
# primary_hue=gr.themes.colors.blue,
|
| 648 |
+
# secondary_hue=gr.themes.colors.slate,
|
| 649 |
+
# neutral_hue=gr.themes.colors.slate,
|
| 650 |
+
# ).set(
|
| 651 |
+
# button_primary_background_fill="#1e40af",
|
| 652 |
+
# button_primary_background_fill_hover="#1d4ed8",
|
| 653 |
+
# button_primary_text_color="white",
|
| 654 |
+
# background_fill_primary="white",
|
| 655 |
+
# background_fill_secondary="#f8fafc",
|
| 656 |
+
# )
|
| 657 |
+
|
| 658 |
+
# def load_sample_pdf():
|
| 659 |
+
# if not os.path.exists(SAMPLE_PDF):
|
| 660 |
+
# raise FileNotFoundError(f"Sample PDF not found at {SAMPLE_PDF}")
|
| 661 |
+
# class PDFWrapper:
|
| 662 |
+
# def __init__(self, path):
|
| 663 |
+
# self.name = path
|
| 664 |
+
# return PDFWrapper(SAMPLE_PDF)
|
| 665 |
+
|
| 666 |
+
# def pdf_to_iframe(file):
|
| 667 |
+
# if file is None: return "<p style='color:orange;'>No PDF uploaded.</p>"
|
| 668 |
+
# try:
|
| 669 |
+
# with open(file.name, "rb") as f: pdf_bytes = f.read()
|
| 670 |
+
# encoded = base64.b64encode(pdf_bytes).decode("utf-8")
|
| 671 |
+
# return f'<iframe src="data:application/pdf;base64,{encoded}" width="100%" height="600px" style="border:1px solid #ccc;"></iframe>'
|
| 672 |
+
# except Exception as e:
|
| 673 |
+
# return f"<p style='color:red;'>Failed to display PDF: {e}</p>"
|
| 674 |
+
|
| 675 |
+
# def clear_outputs():
|
| 676 |
+
# initial_md = "<div style='border:2px solid #1e40af; border-radius:12px; padding:15px; background-color:#f0f9ff;'>π Upload a PDF and click <b>Run Validation</b> to start.</div>"
|
| 677 |
+
# initial_preview = "<p>Upload a PDF to preview</p>"
|
| 678 |
+
# return initial_md, initial_preview
|
| 679 |
+
|
| 680 |
+
# # ---------- Gradio UI ----------
|
| 681 |
+
# with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
|
| 682 |
+
# gr.HTML(f"""
|
| 683 |
+
# <h1 style='text-align:center;color:#1e40af;'> π© {APP_TITLE}</h1>
|
| 684 |
+
# <p style='text-align:center;color:#64748b;'>
|
| 685 |
+
# Upload a chart, set HCC + model version, and validate MEAT criteria.
|
| 686 |
+
# </p>
|
| 687 |
+
# """)
|
| 688 |
+
|
| 689 |
+
# with gr.Row():
|
| 690 |
+
# pdf_upload = gr.File(label="Upload Patient Chart (PDF)", file_types=[".pdf"], scale=1)
|
| 691 |
+
# hcc_code = gr.Textbox(label="HCC Code (e.g., 12)", placeholder="Enter HCC code", scale=1)
|
| 692 |
+
# model_version = gr.Dropdown(choices=["V24", "V28"], label="Model Version", value="V24", scale=1)
|
| 693 |
+
# run_btn = gr.Button("π Run Validation", variant="primary", scale=1)
|
| 694 |
+
|
| 695 |
+
# with gr.Row():
|
| 696 |
+
# with gr.Column(scale=2):
|
| 697 |
+
# pdf_preview = gr.HTML(label="π PDF Preview", value="<p>Upload a PDF to preview</p>")
|
| 698 |
+
# with gr.Column(scale=2):
|
| 699 |
+
# output_md = gr.Markdown(
|
| 700 |
+
# label="Validation Report",
|
| 701 |
+
# value="<div style='border:2px solid #1e40af; border-radius:12px; padding:15px; background-color:#f0f9ff;'>π Upload a PDF and click <b>Run Validation</b> to start.</div>",
|
| 702 |
+
# )
|
| 703 |
+
|
| 704 |
+
# pdf_upload.change(fn=pdf_to_iframe, inputs=pdf_upload, outputs=pdf_preview)
|
| 705 |
+
# pdf_upload.clear(fn=clear_outputs, inputs=[], outputs=[output_md, pdf_preview])
|
| 706 |
+
|
| 707 |
+
# run_btn.click(
|
| 708 |
+
# fn=process_pipeline,
|
| 709 |
+
# inputs=[pdf_upload, hcc_code, model_version],
|
| 710 |
+
# outputs=[output_md],
|
| 711 |
+
# )
|
| 712 |
+
|
| 713 |
+
# # --- MODIFICATION: Adjusted column scaling to make the Examples section smaller ---
|
| 714 |
+
# with gr.Row():
|
| 715 |
+
# with gr.Column(scale=1): # This column will be smaller
|
| 716 |
+
# gr.Examples(
|
| 717 |
+
# examples=[[SAMPLE_PDF, "12", "V24"]],
|
| 718 |
+
# inputs=[pdf_upload, hcc_code, model_version],
|
| 719 |
+
# label="Click to load an example",
|
| 720 |
+
# cache_examples=False
|
| 721 |
+
# )
|
| 722 |
+
# with gr.Column(scale=2): # This empty column will take up the remaining space
|
| 723 |
+
# pass
|
| 724 |
+
# # --- END OF MODIFICATION ---
|
| 725 |
+
|
| 726 |
+
|
| 727 |
+
# if __name__ == "__main__":
|
| 728 |
+
# interface.queue().launch(
|
| 729 |
+
# server_name="0.0.0.0",
|
| 730 |
+
# server_port=int(os.environ.get("PORT", 7860))
|
| 731 |
+
# )
|
| 732 |
+
|
| 733 |
# import os
|
| 734 |
# import gradio as gr
|
| 735 |
# import json
|