sujataprakashdatycs commited on
Commit
1dca8fe
·
verified ·
1 Parent(s): 102d96a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -283
app.py CHANGED
@@ -9,25 +9,57 @@ from chartdiagnosischecker import ChartDiagnosisChecker
9
  from MeatValidatorAgent import MEATValidatorAgent
10
  from dotenv import load_dotenv
11
 
12
- APP_TITLE = "Risk Adjustment (HCC Chart Validation)"
13
- CSV_PATH = "hcc_mapping.csv"
14
- # Define the path to the static PDF file.
15
- STATIC_PDF_PATH = "static/sample_patient_chart.pdf"
16
 
 
 
 
17
 
18
- # ---------- Helper: JSON → Markdown (Unchanged) ----------
19
- def json_to_markdown(meat_results) -> str:
20
- if not meat_results:
21
- return "<div style='color:orange; font-weight:bold;'>⚠️ No results found.</div>"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
- md = "<div style='border:2px solid #1e40af; border-radius:12px; padding:15px; background-color:#f0f9ff;'>"
24
- md += "<h2 style='color:#1e40af;'>🩺 HCC Chart Validation Report</h2>"
25
 
26
- for entry in meat_results:
27
- md += f"<h3 style='color:#1d4ed8;'>📌 {entry['diagnosis']} ({entry['icd10']})</h3>"
28
- md += f"<p><b>Reference:</b> {entry.get('reference', 'N/A')}<br>"
29
- md += f"<b>Answer:</b> {entry.get('answer', 'unknown').upper()}<br>"
30
- md += f"<b>RationAPP_TITLE = "Risk Adjustment (HCC Chart Validation)"
31
  CSV_PATH = "hcc_mapping.csv"
32
  SAMPLE_PDF = "sample_patient_chart.pdf"
33
 
@@ -200,271 +232,3 @@ with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
200
 
201
  if __name__ == "__main__":
202
  interface.queue().launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
203
-
204
-
205
- # import os
206
- # import gradio as gr
207
- # import json
208
-
209
- # from HCCDiagnosisListEngine import HCCDiagnosisListEngine
210
- # from chartdiagnosischecker import ChartDiagnosisChecker
211
- # from MeatValidatorAgent import MEATValidatorAgent
212
-
213
- # APP_TITLE = "Risk Adjustment (HCC Chart Validation)"
214
- # CSV_PATH = "hcc_mapping.csv"
215
- # SAMPLE_PDF = "sample_patient_chart.pdf" # Place a sample PDF in the same folder
216
-
217
-
218
- # # ---------- Helper: JSON → Markdown ----------
219
- # def json_to_markdown(meat_results: list[dict]) -> str:
220
- # if not meat_results:
221
- # return "<div style='color:orange; font-weight:bold;'>⚠️ No results found.</div>"
222
-
223
- # md = "<div style='border:2px solid #1e40af; border-radius:12px; padding:15px; background-color:#f0f9ff;'>"
224
- # md += "<h2 style='color:#1e40af;'>🩺 HCC Chart Validation Report</h2>"
225
-
226
- # for entry in meat_results:
227
- # md += f"<h3 style='color:#1d4ed8;'>📌 {entry['diagnosis']} ({entry['icd10']})</h3>"
228
- # md += f"<p><b>Reference:</b> {entry.get('reference', 'N/A')}<br>"
229
- # md += f"<b>Answer:</b> {entry.get('answer', 'unknown').upper()}<br>"
230
- # md += f"<b>Rationale:</b> {entry.get('rationale', '')}<br>"
231
- # md += f"<b>Clinical Status:</b> {entry.get('clinical_status', 'N/A')}</p>"
232
- # md += "<b>MEAT Criteria:</b><ul>"
233
- # meat = entry.get("meat", {})
234
- # md += f"<li>Monitor: {'✅' if meat.get('monitor') else '❌'}</li>"
235
- # md += f"<li>Evaluate: {'✅' if meat.get('evaluate') else '❌'}</li>"
236
- # md += f"<li>Assess: {'✅' if meat.get('assess') else '❌'}</li>"
237
- # md += f"<li>Treat: {'✅' if meat.get('treat') else '❌'}</li>"
238
- # md += "</ul>"
239
- # md += f"<b>MEAT Rationale:</b> {entry.get('meat_rationale', '')}<br><br>"
240
- # md += "</div>"
241
- # return md
242
-
243
-
244
- # # ---------- Pipeline ----------
245
- # def process_pipeline(pdf_file, hcc_code, model_version, csv_path=CSV_PATH):
246
- # try:
247
- # if pdf_file is None:
248
- # return "<div style='color:orange; font-weight:bold;'>⚠️ Please upload a patient chart PDF.</div>"
249
-
250
- # if not hcc_code or str(hcc_code).strip() == "":
251
- # return "<div style='color:orange; font-weight:bold;'>⚠️ Please enter a valid HCC Code before running validation.</div>"
252
-
253
- # pdf_path = pdf_file.name
254
- # patient_name = os.path.splitext(os.path.basename(pdf_path))[0]
255
- # print(f"\n[PROCESSING] {patient_name}")
256
-
257
- # # Step 1: HCC Diagnoses
258
- # diag_engine = HCCDiagnosisListEngine(hcc_code, model_version, csv_path)
259
- # diagnoses = diag_engine.run()
260
-
261
- # # Step 2: Chart Checking
262
- # checker = ChartDiagnosisChecker(pdf_path)
263
- # checked = checker.run(diagnoses)
264
-
265
- # # ✅ Only proceed if at least one "yes"
266
- # has_positive = any(entry.get("answer", "").lower() == "yes" for entry in checked)
267
- # if not has_positive:
268
- # return f"<b>❌ Not found diagnosis in the chart related to HCC code {hcc_code}.</b>"
269
-
270
- # # Step 3: MEAT Validation
271
- # meat_validator = MEATValidatorAgent()
272
- # meat_results = meat_validator.run(checked)
273
-
274
- # return json_to_markdown(meat_results)
275
-
276
- # except Exception as e:
277
- # print(f"[ERROR] {e}")
278
- # return f"<div style='color:red; font-weight:bold;'>⚠️ Error during processing: {e}</div>"
279
-
280
-
281
- # # ---------- Gradio Theme ----------
282
- # simple_theme = gr.themes.Soft(
283
- # primary_hue=gr.themes.colors.blue,
284
- # secondary_hue=gr.themes.colors.slate,
285
- # neutral_hue=gr.themes.colors.slate,
286
- # ).set(
287
- # button_primary_background_fill="#1e40af",
288
- # button_primary_background_fill_hover="#1d4ed8",
289
- # button_primary_text_color="white",
290
- # background_fill_primary="white",
291
- # background_fill_secondary="#f8fafc",
292
- # )
293
-
294
-
295
- # # ---------- Gradio UI ----------
296
- # with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
297
- # gr.HTML(f"""
298
- # <h1 style='text-align:center;color:#1e40af;'> 🏩 {APP_TITLE}</h1>
299
- # <p style='text-align:center;color:#64748b;'>
300
- # Upload a chart, set HCC + model version, and validate MEAT criteria.
301
- # </p>
302
- # """)
303
-
304
- # with gr.Row():
305
- # with gr.Column(scale=1):
306
- # pdf_upload = gr.File(label="Upload Patient Chart (PDF)", file_types=[".pdf"])
307
- # hcc_code = gr.Textbox(label="HCC Code (e.g., 12)", placeholder="Enter HCC code")
308
- # model_version = gr.Dropdown(choices=["V24", "V28"], label="Model Version", value="V24")
309
- # run_btn = gr.Button("🚀 Run Validation", variant="primary")
310
- # sample_btn = gr.Button("📄 Use Sample PDF", variant="secondary")
311
-
312
- # with gr.Column(scale=2):
313
- # output_md = gr.Markdown(
314
- # label="Validation Report",
315
- # 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>",
316
- # )
317
-
318
- # # ---------- Button Events ----------
319
- # sample_btn.click(
320
- # fn=lambda: gr.File.update(value=SAMPLE_PDF),
321
- # inputs=[],
322
- # outputs=[pdf_upload],
323
- # )
324
-
325
- # run_btn.click(
326
- # fn=process_pipeline,
327
- # inputs=[pdf_upload, hcc_code, model_version],
328
- # outputs=[output_md],
329
- # )
330
-
331
-
332
- # if __name__ == "__main__":
333
- # interface.queue().launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
334
-
335
-
336
-
337
-
338
-
339
-
340
-
341
-
342
-
343
-
344
-
345
-
346
-
347
-
348
-
349
-
350
-
351
-
352
- #### old
353
- # import os
354
- # import gradio as gr
355
- # import json
356
-
357
- # from HCCDiagnosisListEngine import HCCDiagnosisListEngine
358
- # from chartdiagnosischecker import ChartDiagnosisChecker
359
- # from MeatValidatorAgent import MEATValidatorAgent
360
-
361
- # APP_TITLE = "Risk Adjustment (HCC Chart Validation)"
362
- # CSV_PATH = "hcc_mapping.csv"
363
-
364
- # # ---------- Helper: JSON → Markdown ----------
365
- # def json_to_markdown(meat_results: list[dict]) -> str:
366
- # if not meat_results:
367
- # return "⚠️ **No results found.**"
368
-
369
- # md = "## 🏥 HCC Chart Validation Report\n\n"
370
-
371
- # for entry in meat_results:
372
- # md += f"### 📌 {entry['diagnosis']} ({entry['icd10']})\n"
373
- # md += f"- **Reference:** {entry.get('reference', 'N/A')}\n"
374
- # md += f"- **Answer:** {entry.get('answer', 'unknown').upper()}\n"
375
- # md += f"- **Rationale:** {entry.get('rationale', '')}\n"
376
- # md += f"- **Clinical Status:** {entry.get('clinical_status', 'N/A')}\n"
377
- # md += f"- **MEAT Criteria:**\n"
378
- # meat = entry.get("meat", {})
379
- # if meat:
380
- # md += " - Monitor: ✅\n" if meat.get("monitor") else " - Monitor: ❌\n"
381
- # md += " - Evaluate: ✅\n" if meat.get("evaluate") else " - Evaluate: ❌\n"
382
- # md += " - Assess: ✅\n" if meat.get("assess") else " - Assess: ❌\n"
383
- # md += " - Treat: ✅\n" if meat.get("treat") else " - Treat: ❌\n"
384
- # md += f"- **MEAT Rationale:** {entry.get('meat_rationale', '')}\n\n"
385
- # return md.strip()
386
-
387
-
388
-
389
- # # ---------- Pipeline ----------
390
- # def process_pipeline(pdf_file, hcc_code, model_version, csv_path=CSV_PATH):
391
- # try:
392
- # if pdf_file is None:
393
- # return "⚠️ Please upload a patient chart PDF."
394
-
395
- # if not hcc_code or str(hcc_code).strip() == "":
396
- # return "⚠️ Please enter a valid HCC Code before running validation."
397
-
398
- # pdf_path = pdf_file.name
399
- # patient_name = os.path.splitext(os.path.basename(pdf_path))[0]
400
- # print(f"\n[PROCESSING] {patient_name}")
401
-
402
-
403
-
404
- # # Step 1: HCC Diagnoses
405
- # diag_engine = HCCDiagnosisListEngine(hcc_code, model_version, csv_path)
406
- # diagnoses = diag_engine.run()
407
-
408
- # # Step 2: Chart Checking
409
- # checker = ChartDiagnosisChecker(pdf_path)
410
- # checked = checker.run(diagnoses)
411
-
412
- # # ✅ New condition: only proceed if at least one "yes"
413
- # has_positive = any(entry.get("answer", "").lower() == "yes" for entry in checked)
414
- # if not has_positive:
415
- # return f"**❌ Not found diagnosis in the chart related to HCC code {hcc_code}.**"
416
-
417
- # # Step 3: MEAT Validation
418
- # meat_validator = MEATValidatorAgent()
419
- # meat_results = meat_validator.run(checked)
420
-
421
- # return json_to_markdown(meat_results)
422
-
423
- # except Exception as e:
424
- # print(f"[ERROR] {e}")
425
- # return f"⚠️ Error during processing: {e}"
426
-
427
-
428
-
429
-
430
- # # ---------- Gradio Theme ----------
431
- # simple_theme = gr.themes.Soft(
432
- # primary_hue=gr.themes.colors.blue,
433
- # secondary_hue=gr.themes.colors.slate,
434
- # neutral_hue=gr.themes.colors.slate,
435
- # ).set(
436
- # button_primary_background_fill="#1e40af",
437
- # button_primary_background_fill_hover="#1d4ed8",
438
- # button_primary_text_color="white",
439
- # background_fill_primary="white",
440
- # background_fill_secondary="#f8fafc",
441
- # )
442
-
443
-
444
- # # ---------- Gradio UI ----------
445
- # with gr.Blocks(theme=simple_theme, title=APP_TITLE) as interface:
446
- # gr.HTML(f"<h1 style='text-align:center;color:#1e40af;'>🏥 {APP_TITLE}</h1>")
447
- # gr.HTML("<p style='text-align:center;color:#64748b;'>Upload a chart, set HCC + model version, and validate MEAT criteria.</p>")
448
-
449
- # with gr.Row():
450
- # with gr.Column(scale=1):
451
- # pdf_upload = gr.File(label="Upload Patient Chart (PDF)", file_types=[".pdf"])
452
- # hcc_code = gr.Textbox(label="HCC Code (e.g., 12)", placeholder="Enter HCC code")
453
- # model_version = gr.Dropdown(choices=["V24", "V28"], label="Model Version", value="V24")
454
- # run_btn = gr.Button("🚀 Run Validation", variant="primary")
455
-
456
- # with gr.Column(scale=2):
457
- # output_md = gr.Markdown(
458
- # label="Validation Report",
459
- # value="📄 Upload a PDF and click **Run Validation** to start.",
460
- # )
461
-
462
- # run_btn.click(
463
- # fn=process_pipeline,
464
- # inputs=[pdf_upload, hcc_code, model_version],
465
- # outputs=[output_md],
466
- # )
467
-
468
-
469
- # if __name__ == "__main__":
470
- # interface.queue().launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))
 
9
  from MeatValidatorAgent import MEATValidatorAgent
10
  from dotenv import load_dotenv
11
 
12
+ # app.py
 
 
 
13
 
14
+ import os
15
+ import gradio as gr
16
+ import json
17
 
18
+ # from HCCDiagnosisListEngine import HCCDiagnosisListEngine
19
+ # from chartdiagnosischecker import ChartDiagnosisChecker
20
+ # from MeatValidatorAgent import MEATValidatorAgent
21
+ from dotenv import load_dotenv
22
+ load_dotenv()
23
+
24
+ # ==============================================================================
25
+ # MOCK CLASSES FOR DEMONSTRATION (as original files were not provided)
26
+ # NOTE: Replace these with your actual class imports.
27
+ # ==============================================================================
28
+ class HCCDiagnosisListEngine:
29
+ def __init__(self, hcc_code, model_version, csv_path):
30
+ self.hcc_code = hcc_code
31
+ def run(self):
32
+ print(f"Engine running for HCC: {self.hcc_code}")
33
+ return [
34
+ {'diagnosis': 'Type 2 diabetes mellitus with diabetic nephropathy', 'icd10': 'E11.22'},
35
+ {'diagnosis': 'Chronic kidney disease, stage 3', 'icd10': 'N18.3'}
36
+ ]
37
+
38
+ class ChartDiagnosisChecker:
39
+ def __init__(self, pdf_path):
40
+ self.pdf_path = pdf_path
41
+ def run(self, diagnoses):
42
+ print(f"Checker running for PDF: {self.pdf_path}")
43
+ checked_diagnoses = diagnoses
44
+ for i, diag in enumerate(checked_diagnoses):
45
+ diag['answer'] = 'yes' if i == 0 else 'no'
46
+ diag['reference'] = f"Page {i+1}, line {i*3}"
47
+ diag['rationale'] = f"The patient record on page {i+1} explicitly mentions this condition."
48
+ return checked_diagnoses
49
+
50
+ class MEATValidatorAgent:
51
+ def run(self, checked_diagnoses):
52
+ print("MEAT Validator running...")
53
+ positive_diagnoses = [d for d in checked_diagnoses if d.get("answer", "").lower() == "yes"]
54
+ for diag in positive_diagnoses:
55
+ diag['clinical_status'] = 'Chronic, Stable'
56
+ diag['meat'] = {'monitor': True, 'evaluate': True, 'assess': False, 'treat': True}
57
+ diag['meat_rationale'] = "Patient's condition is being monitored with regular blood tests (Monitor), evaluated for progression (Evaluate), and treated with Metformin (Treat)."
58
+ return positive_diagnoses
59
+ # ==============================================================================
60
 
 
 
61
 
62
+ APP_TITLE = "Risk Adjustment (HCC Chart Validation)"
 
 
 
 
63
  CSV_PATH = "hcc_mapping.csv"
64
  SAMPLE_PDF = "sample_patient_chart.pdf"
65
 
 
232
 
233
  if __name__ == "__main__":
234
  interface.queue().launch(server_name="0.0.0.0", server_port=int(os.environ.get("PORT", 7860)))