sujataprakashdatycs commited on
Commit
7d37a7e
·
verified ·
1 Parent(s): 5397e93

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -289
app.py CHANGED
@@ -292,7 +292,7 @@ with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
292
  """)
293
 
294
  with gr.Row():
295
- pdf_upload = gr.File(label="Upload Patient Chart (PDF)", file_types=[".pdf"], scale=2)
296
  hcc_code = gr.Textbox(label="HCC Code (e.g., 12)", placeholder="Enter HCC code", scale=1)
297
  model_version = gr.Dropdown(choices=["V24", "V28"], label="Model Version", value="V24", scale=1)
298
  run_btn = gr.Button("🚀 Run Validation", variant="primary", scale=1)
@@ -333,291 +333,3 @@ if __name__ == "__main__":
333
  )
334
 
335
 
336
-
337
-
338
-
339
- # import os
340
- # import gradio as gr
341
- # import json
342
- # import time
343
- # import base64
344
- # from dotenv import load_dotenv
345
- # from ClinicalStatusAgent import ClinicalStatusAgent
346
- # from TestFindingAgent import TestFindingAgent
347
- # from ComorbidityCheckerAgent import ComorbidityCheckerAgent
348
- # from HCCDiagnosisListEngine import HCCDiagnosisListEngine
349
- # from chartdiagnosischecker import ChartDiagnosisChecker
350
- # from MeatValidatorAgent import MEATValidatorAgent
351
- # from typing import Optional
352
-
353
- # load_dotenv()
354
- # APP_TITLE = "Risk Adjustment (HCC Chart Validation)"
355
- # CSV_PATH = "hcc_mapping.csv"
356
- # SAMPLE_PDF = "sample_patient_chart.pdf" # Place a sample PDF in the same folder
357
-
358
-
359
- # # ---------- JSON to Markdown ----------
360
- # def json_to_markdown(data) -> str:
361
- # try:
362
- # if isinstance(data, dict) and "final_analysis" in data:
363
- # patient_id = data.get("patient_id", "Unknown Patient")
364
- # hcc_code = data.get("hcc_code", "N/A")
365
- # model_version = data.get("model_version", "N/A")
366
- # analyses = data.get("final_analysis", [])
367
- # elif isinstance(data, list):
368
- # patient_id = "N/A"
369
- # hcc_code = "N/A"
370
- # model_version = "N/A"
371
- # analyses = data
372
- # else:
373
- # return "<div style='color:red; font-weight:bold;'>⚠️ Invalid data format for report.</div>"
374
-
375
- # md = f"""
376
- # <div style="border:2px solid #4CAF50; padding:15px; border-radius:10px; background:#f9fdf9;">
377
- # <h2 style="color:#2e7d32;">📋 HCC Chart Validation Report </h2>
378
- # <p><b>🧾 Patient ID:</b> {patient_id}</p>
379
- # <p><b>🏷️ HCC Code:</b> {hcc_code}</p>
380
- # <p><b>⚙️ Model Version:</b> {model_version}</p>
381
- # </div>
382
- # <br/>
383
- # """
384
- # for idx, diag in enumerate(analyses, 1):
385
- # md += f"""
386
- # <div style="border:1px solid #ccc; padding:12px; border-radius:8px; margin-bottom:12px;">
387
- # <h3 style="color:#1565c0;">{idx}. {diag.get("diagnosis", "Unknown Diagnosis")}</h3>
388
- # <p><b>ICD-10:</b> {diag.get("icd10", "N/A")}</p>
389
- # <p><b>Reference:</b> <a href="{diag.get("reference","")}" target="_blank">{diag.get("reference","")}</a></p>
390
- # """
391
- # explicit_ans = diag.get("answer_explicit", "N/A")
392
- # explicit_rat = diag.get("rationale_explicit", "")
393
- # implicit_ans = diag.get("answer_implicit", "N/A")
394
- # implicit_rat = diag.get("rationale_implicit", "")
395
-
396
- # if explicit_ans.lower() == "yes":
397
- # md += f"<p><b>Explicit:</b> {explicit_ans} — {explicit_rat}</p>"
398
- # else:
399
- # md += f"<p><b>Implicit:</b> {implicit_ans} — {implicit_rat}</p>"
400
-
401
- # md += f"""
402
- # <p><b>Clinical Status:</b> {diag.get("clinical_status","N/A")}</p>
403
- # <p><b>Status Rationale:</b> {diag.get("status_rationale","")}</p>
404
- # """
405
- # if "tests" in diag:
406
- # md += "<details><summary><b>🧪 Tests & Procedures</b></summary><ul>"
407
- # tests = diag["tests"]
408
- # if "vitals" in tests:
409
- # md += "<li><b>Vitals:</b><ul>"
410
- # for k, v in tests["vitals"].items():
411
- # md += f"<li>{k}: {v}</li>"
412
- # md += "</ul></li>"
413
- # if "procedures" in tests:
414
- # md += "<li><b>Procedures:</b><ul>"
415
- # for k, v in tests["procedures"].items():
416
- # md += f"<li>{k}: {v}</li>"
417
- # md += "</ul></li>"
418
- # if "lab_test" in tests:
419
- # md += "<li><b>Lab Tests:</b><ul>"
420
- # for k, v in tests["lab_test"].items():
421
- # md += f"<li>{k}: {v}</li>"
422
- # md += "</ul></li>"
423
- # md += "</ul></details>"
424
-
425
- # if "meat" in diag:
426
- # md += "<details><summary><b>🍖 MEAT Validation</b></summary><ul>"
427
- # for k, v in diag["meat"].items():
428
- # emoji = "✅" if v else "❌"
429
- # md += f"<li>{k.capitalize()}: {emoji}</li>"
430
- # md += "</ul>"
431
- # md += f"<p><b>MEAT Rationale:</b> {diag.get('meat_rationale','')}</p>"
432
- # md += "</details>"
433
-
434
- # if "comorbidities" in diag and diag["comorbidities"]:
435
- # md += "<details><summary><b>🩺 Comorbidities</b></summary><ul>"
436
- # for c in diag["comorbidities"]:
437
- # emoji = "✅" if c.get("is_present") else "❌"
438
- # md += f"<li>{emoji} <b>{c.get('condition')}</b><br/><i>{c.get('rationale')}</i></li>"
439
- # md += "</ul></details>"
440
-
441
- # md += "</div>"
442
-
443
- # return md
444
-
445
- # except Exception as e:
446
- # return f"<div style='color:red; font-weight:bold;'>⚠️ Error rendering report: {e}</div>"
447
-
448
-
449
- # # ---------- Processing Pipeline ----------
450
- # def process_pipeline(
451
- # pdf_file,
452
- # hcc_code,
453
- # model_version,
454
- # csv_path=CSV_PATH,
455
- # output_folder="outputs",
456
- # progress=gr.Progress()
457
- # ):
458
- # try:
459
- # start = time.time()
460
- # if pdf_file is None:
461
- # yield "<div style='color:orange; font-weight:bold;'>⚠️ Please upload a patient chart PDF.</div>"
462
- # return
463
- # hcc_code_str = str(hcc_code or "").strip()
464
- # if not hcc_code_str:
465
- # yield "<div style='color:orange; font-weight:bold;'>⚠️ Please enter a valid HCC Code before running validation.</div>"
466
- # return
467
- # os.makedirs(output_folder, exist_ok=True)
468
- # pdf_path = pdf_file.name
469
- # patient_name = os.path.splitext(os.path.basename(pdf_path))[0]
470
- # print(f"\n[PROCESSING] {patient_name}")
471
-
472
- # diagnoses = HCCDiagnosisListEngine(hcc_code_str, model_version, csv_path).run()
473
- # if not diagnoses:
474
- # yield f"<b>❌ No diagnoses found for HCC {hcc_code_str}.</b>"
475
- # return
476
- # all_checked_results = ChartDiagnosisChecker(pdf_path).run(diagnoses)
477
- # confirmed_diagnoses = [
478
- # d for d in all_checked_results
479
- # if d.get("answer_explicit", "").lower() == "yes"
480
- # or d.get("answer_implicit", "").lower() == "yes"
481
- # ]
482
- # if not confirmed_diagnoses:
483
- # msg = f"<b>❌ No confirmed diagnoses for HCC {hcc_code_str} in {patient_name}. Report saved.</b>"
484
- # yield msg
485
- # return
486
- # diagnoses_with_tests = TestFindingAgent(hcc_code=hcc_code_str, model_version=model_version).run(confirmed_diagnoses)
487
- # diagnoses_with_status = ClinicalStatusAgent().run(diagnoses_with_tests)
488
- # active_diagnoses = [d for d in diagnoses_with_status if d.get("clinical_status") == "ACTIVE"]
489
- # validated_meat_diagnoses = []
490
- # if active_diagnoses:
491
- # validated_meat_diagnoses = MEATValidatorAgent().run(active_diagnoses)
492
- # diagnoses_passed_meat = [d for d in validated_meat_diagnoses if any(d.get("meat", {}).values())]
493
- # comorbidity_results = []
494
- # if diagnoses_passed_meat:
495
- # comorbidity_results = ComorbidityCheckerAgent(pdf_path, hcc_code_str, model_version).run(diagnoses_passed_meat)
496
-
497
- # status_map = {d["diagnosis"]: d for d in diagnoses_with_status}
498
- # meat_map = {d["diagnosis"]: d for d in validated_meat_diagnoses}
499
- # comorbidity_map = {d["diagnosis"]: d for d in comorbidity_results}
500
-
501
- # final_analysis = []
502
- # for entry in all_checked_results:
503
- # diag_name = entry["diagnosis"]
504
- # updated_entry = entry.copy()
505
- # if diag_name in status_map:
506
- # updated_entry.update(status_map[diag_name])
507
- # if diag_name in meat_map:
508
- # updated_entry.update(meat_map[diag_name])
509
- # if diag_name in comorbidity_map:
510
- # updated_entry.update(comorbidity_map[diag_name])
511
- # final_analysis.append(updated_entry)
512
-
513
- # filtered_final_analysis = [
514
- # e for e in final_analysis
515
- # if e.get("answer_explicit", "").lower() == "yes"
516
- # or e.get("answer_implicit", "").lower() == "yes"
517
- # ]
518
- # output_data = {
519
- # "patient_id": patient_name,
520
- # "hcc_code": hcc_code_str,
521
- # "model_version": model_version,
522
- # "final_analysis": filtered_final_analysis
523
- # }
524
- # elapsed = time.time() - start
525
- # final_report = json_to_markdown(output_data) + f"<br/><div style='color:green;'>✅ Completed in {elapsed:.1f} sec</div>"
526
- # yield final_report
527
-
528
- # except Exception as e:
529
- # print(f"[ERROR] {e}")
530
- # yield f"<div style='color:red; font-weight:bold;'>⚠️ Error: {e}</div>"
531
-
532
-
533
- # # ---------- Gradio Theme ----------
534
- # simple_theme = gr.themes.Soft(
535
- # primary_hue=gr.themes.colors.blue,
536
- # secondary_hue=gr.themes.colors.slate,
537
- # neutral_hue=gr.themes.colors.slate,
538
- # ).set(
539
- # button_primary_background_fill="#1e40af",
540
- # button_primary_background_fill_hover="#1d4ed8",
541
- # button_primary_text_color="white",
542
- # background_fill_primary="white",
543
- # background_fill_secondary="#f8fafc",
544
- # )
545
-
546
-
547
- # # ---------- Helper for Sample PDF ----------
548
- # def load_sample_pdf():
549
- # if not os.path.exists(SAMPLE_PDF):
550
- # raise FileNotFoundError(f"Sample PDF not found at {SAMPLE_PDF}")
551
- # class PDFWrapper:
552
- # def __init__(self, path):
553
- # self.name = path
554
- # return PDFWrapper(SAMPLE_PDF)
555
-
556
-
557
- # # ---------- Helper for PDF Preview (Base64) ----------
558
- # def pdf_to_iframe(file):
559
- # if file is None:
560
- # return "<p style='color:orange;'>No PDF uploaded.</p>"
561
- # try:
562
- # with open(file.name, "rb") as f:
563
- # pdf_bytes = f.read()
564
- # encoded = base64.b64encode(pdf_bytes).decode("utf-8")
565
- # return f"""
566
- # <iframe
567
- # src="data:application/pdf;base64,{encoded}"
568
- # width="100%" height="600px"
569
- # style="border:1px solid #ccc;"
570
- # ></iframe>
571
- # """
572
- # except Exception as e:
573
- # return f"<p style='color:red;'>Failed to display PDF: {e}</p>"
574
-
575
-
576
- # # ---------- Gradio UI ----------
577
- # with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
578
- # gr.HTML(f"""
579
- # <h1 style='text-align:center;color:#1e40af;'> 🏩 {APP_TITLE}</h1>
580
- # <p style='text-align:center;color:#64748b;'>
581
- # Upload a chart, set HCC + model version, and validate MEAT criteria.
582
- # </p>
583
- # """)
584
-
585
- # with gr.Row():
586
- # pdf_upload = gr.File(label="Upload Patient Chart (PDF)", file_types=[".pdf"], scale=2)
587
- # hcc_code = gr.Textbox(label="HCC Code (e.g., 12)", placeholder="Enter HCC code", scale=1)
588
- # model_version = gr.Dropdown(choices=["V24", "V28"], label="Model Version", value="V24", scale=1)
589
- # run_btn = gr.Button("🚀 Run Validation", variant="primary", scale=1)
590
-
591
- # with gr.Row():
592
- # with gr.Column(scale=1):
593
- # pdf_preview = gr.HTML(label="📑 PDF Preview", value="<p>Upload a PDF to preview</p>")
594
- # with gr.Column(scale=2):
595
- # output_md = gr.Markdown(
596
- # label="Validation Report",
597
- # 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>",
598
- # )
599
-
600
- # # Connect PDF upload to preview
601
- # pdf_upload.change(fn=pdf_to_iframe, inputs=pdf_upload, outputs=pdf_preview)
602
-
603
- # # Connect run button
604
- # run_btn.click(
605
- # fn=process_pipeline,
606
- # inputs=[pdf_upload, hcc_code, model_version],
607
- # outputs=[output_md],
608
- # )
609
-
610
- # gr.Examples(
611
- # examples=[[SAMPLE_PDF]],
612
- # inputs=[pdf_upload],
613
- # outputs=[output_md],
614
- # fn=lambda x: process_pipeline(load_sample_pdf(), hcc_code="12", model_version="V24"),
615
- # cache_examples=False
616
- # )
617
-
618
-
619
- # if __name__ == "__main__":
620
- # interface.queue().launch(
621
- # server_name="0.0.0.0",
622
- # server_port=int(os.environ.get("PORT", 7860))
623
- # )
 
292
  """)
293
 
294
  with gr.Row():
295
+ pdf_upload = gr.File(label="Upload Patient Chart (PDF)", file_types=[".pdf"], scale=1)
296
  hcc_code = gr.Textbox(label="HCC Code (e.g., 12)", placeholder="Enter HCC code", scale=1)
297
  model_version = gr.Dropdown(choices=["V24", "V28"], label="Model Version", value="V24", scale=1)
298
  run_btn = gr.Button("🚀 Run Validation", variant="primary", scale=1)
 
333
  )
334
 
335