Cardiosense-AG commited on
Commit
e914999
Β·
verified Β·
1 Parent(s): c937b8c

Update pages/02_Workflow_UI.py

Browse files
Files changed (1) hide show
  1. pages/02_Workflow_UI.py +96 -35
pages/02_Workflow_UI.py CHANGED
@@ -30,6 +30,7 @@ from src.explainability import text_hash, normalize_text, is_stale
30
  from src.guideline_annotator import generate_guideline_rationale
31
  from src.ai_core import generate_soap_draft
32
  from src.model_loader import active_model_status
 
33
 
34
 
35
  # --------------------------- Page Setup ---------------------------------
@@ -132,44 +133,64 @@ def _latest_export(case_id: str, pattern_suffix: str) -> Optional[Path]:
132
  matches = sorted(exp.glob(f"EC-{case_id}_*{pattern_suffix}"), key=lambda p: p.stat().st_mtime)
133
  return matches[-1] if matches else None
134
 
135
- def _note_markdown(case: Dict[str, Any], summary: str, soap: Dict[str, str], guideline_points: List[str], endnotes: List[Dict[str, Any]]) -> str:
 
 
 
136
  p = case.get("patient", {}) or {}
 
 
 
 
 
 
 
 
 
137
  header = (
138
- f"# Consultation Report β€” {case.get('case_id','')}\n\n"
139
- f"**Patient:** {p.get('name','')} ({p.get('age','')}/{p.get('sex','')})\n"
 
 
 
 
 
140
  )
141
- body = (
142
- f"\n## Referral Summary\n{summary.strip()}\n"
143
- f"\n## Subjective\n{(soap.get('subjective') or '').strip()}\n"
144
- f"\n## Objective\n{(soap.get('objective') or '').strip()}\n"
145
- f"\n## Assessment\n{(soap.get('assessment') or '').strip()}\n"
146
- f"\n## Plan\n{(soap.get('plan') or '').strip()}\n"
 
 
 
 
 
 
147
  )
148
- gr = ""
 
149
  if guideline_points:
150
  bullets = "\n".join([f"- {pt}" for pt in guideline_points])
151
- gr = "\n## Guideline Rationale\n" + bullets + "\n"
152
- cites = ""
 
153
  if endnotes:
154
- cites = "\n## Guideline Citations\n" + "\n".join(
155
- [f"- [{e.get('n', i+1)}] {e.get('doc','Guideline')}" + (f" p.{e.get('page','')}" if e.get('page') else "") for i, e in enumerate(endnotes)]
 
156
  )
157
- return header + body + gr + cites + "\n"
158
 
159
- def _seed_once() -> None:
160
- if not st.session_state.get("_seeded", False):
161
- store.seed_cases(reset=True)
162
- st.session_state["_seeded"] = True
 
163
 
164
- def _case_options() -> List[Dict[str, Any]]:
165
- items = store.list_cases()
166
- if not items:
167
- _seed_once()
168
- items = store.list_cases()
169
- return items
170
 
171
- def _get_case(case_id: str) -> Dict[str, Any]:
172
- return store.read_case(case_id) or {}
173
 
174
 
175
  # --------------------------- Global callouts --------------------------------
@@ -502,9 +523,9 @@ with tab_bill:
502
  st.subheader("EHR Consultation Note")
503
  note_path = _latest_export(selected, "Sample Consultation Report.md")
504
  if note_path and note_path.exists():
505
- with st.expander("πŸ“„ View EHR Consultation Note (Markdown)", expanded=True):
506
  md = note_path.read_text(encoding="utf-8")
507
- st.code(md, language="markdown")
508
  st.caption(f"File: {note_path.name}")
509
  else:
510
  st.warning("No consultation note found for this case. Finalize the consult to generate one.")
@@ -527,6 +548,33 @@ with tab_bill:
527
  st.write(f"{icon} **{s.code}** β€” {s.descriptor} β€” ${s.rate:.2f}")
528
  st.caption(s.why)
529
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
530
  chosen_default = b.get("cpt_code") or (elig_codes[0] if elig_codes else None)
531
  if elig_codes:
532
  chosen = st.selectbox("Choose CPT (eligible)", options=elig_codes, index=elig_codes.index(chosen_default) if (chosen_default in elig_codes) else 0, key=f"cpt_{selected}")
@@ -539,16 +587,29 @@ with tab_bill:
539
  submit_claim = st.button("Submit Claim", type="primary", disabled=not (chosen and att_claim), key=f"submit_claim_{selected}")
540
 
541
  if submit_claim and chosen:
542
- # Persist chosen code
543
- store.update_case(selected, {"billing": {"cpt_code": chosen}})
544
-
545
- # Build and save 837 JSON
 
 
 
 
 
546
  pick = next((s for s in suggestions if s.code == chosen), None)
547
  rate = float(getattr(pick, "rate", 0.0)) if pick else 0.0
548
- claim = billing.build_837_claim(case, code=str(chosen), rate=rate, minutes=minutes, spoke=bool(spoke), attested=True)
 
 
 
 
 
 
 
 
549
  claim_path = config.make_export_path(selected, "Sample 837 Json.json")
550
  Path(claim_path).write_text(json.dumps(claim, ensure_ascii=False, indent=2), encoding="utf-8")
551
-
552
  st.success("Claim submitted. 837 JSON generated (see preview below).")
553
  st.caption(f"Claim: {claim_path.name}")
554
 
 
30
  from src.guideline_annotator import generate_guideline_rationale
31
  from src.ai_core import generate_soap_draft
32
  from src.model_loader import active_model_status
33
+ from datetime import datetime
34
 
35
 
36
  # --------------------------- Page Setup ---------------------------------
 
133
  matches = sorted(exp.glob(f"EC-{case_id}_*{pattern_suffix}"), key=lambda p: p.stat().st_mtime)
134
  return matches[-1] if matches else None
135
 
136
+
137
+ def _note_markdown(case: Dict[str, Any], summary: str, soap: Dict[str, str],
138
+ guideline_points: List[str], endnotes: List[Dict[str, Any]]) -> str:
139
+ """Generate formatted EHR-style consultation report (matches sample format)."""
140
  p = case.get("patient", {}) or {}
141
+ c = case.get("consult", {}) or {}
142
+ consult_id = case.get("case_id", "")
143
+ today = datetime.utcnow().strftime("%B %d, %Y")
144
+
145
+ patient_line = f"**Patient:** {p.get('name','Unknown')} ({p.get('sex','')}, {p.get('age','')})"
146
+ specialty = c.get("specialty") or "Cardiology"
147
+ question = c.get("question") or ""
148
+ referring = c.get("referrer") or "Referring provider not specified"
149
+
150
  header = (
151
+ f"# {specialty} E-Consult Report\n\n"
152
+ f"{patient_line} \n"
153
+ f"**Consult ID:** {consult_id} \n"
154
+ f"**Date:** {today} \n"
155
+ f"**Specialty:** {specialty} \n"
156
+ f"**Referring Provider:** {referring}\n\n"
157
+ "---\n\n"
158
  )
159
+
160
+ referral_section = ""
161
+ if question:
162
+ referral_section += f"### Referral Question\n> {question.strip()}\n\n"
163
+ if summary.strip():
164
+ referral_section += f"### Clinical Summary\n{summary.strip()}\n\n---\n\n"
165
+
166
+ soap_section = (
167
+ f"### Subjective\n{(soap.get('subjective') or '').strip()}\n\n"
168
+ f"### Objective\n{(soap.get('objective') or '').strip()}\n\n"
169
+ f"### Assessment\n{(soap.get('assessment') or '').strip()}\n\n"
170
+ f"### Plan\n{(soap.get('plan') or '').strip()}\n\n---\n\n"
171
  )
172
+
173
+ guideline_section = ""
174
  if guideline_points:
175
  bullets = "\n".join([f"- {pt}" for pt in guideline_points])
176
+ guideline_section = f"### Guideline Alignment\n{bullets}\n\n---\n\n"
177
+
178
+ endnote_section = ""
179
  if endnotes:
180
+ cites = "\n".join(
181
+ [f"- [{e.get('n', i+1)}] {e.get('doc','Guideline')}"
182
+ + (f" p.{e.get('page','')}" if e.get('page') else "") for i, e in enumerate(endnotes)]
183
  )
184
+ endnote_section = f"### References\n{cites}\n\n---\n\n"
185
 
186
+ attestation = (
187
+ "### Consulting Clinician Attestation\n"
188
+ "I personally reviewed the provided information, generated this report, "
189
+ "and confirm that I spent the documented time reviewing and documenting this e-consult.\n"
190
+ )
191
 
192
+ return header + referral_section + soap_section + guideline_section + endnote_section + attestation
 
 
 
 
 
193
 
 
 
194
 
195
 
196
  # --------------------------- Global callouts --------------------------------
 
523
  st.subheader("EHR Consultation Note")
524
  note_path = _latest_export(selected, "Sample Consultation Report.md")
525
  if note_path and note_path.exists():
526
+ with st.expander("πŸ“„ View EHR Consultation Note", expanded=True):
527
  md = note_path.read_text(encoding="utf-8")
528
+ st.markdown(md) # render formatted markdown, not raw text
529
  st.caption(f"File: {note_path.name}")
530
  else:
531
  st.warning("No consultation note found for this case. Finalize the consult to generate one.")
 
548
  st.write(f"{icon} **{s.code}** β€” {s.descriptor} β€” ${s.rate:.2f}")
549
  st.caption(s.why)
550
 
551
+ # --- ICD-10 diagnosis suggestions (new) ---
552
+ from src.billing import autosuggest_icd # top of file already imports billing; safe to import here too
553
+
554
+ soap_now = case.get("soap_draft", {}) or {}
555
+ icd_suggestions = autosuggest_icd(
556
+ assessment_text=soap_now.get("assessment", ""),
557
+ plan_text=soap_now.get("plan", "")
558
+ )
559
+ st.markdown("**ICD-10 Diagnosis Suggestions**")
560
+ if icd_suggestions:
561
+ for s in icd_suggestions:
562
+ st.write(f"βœ… **{s.code}** β€” {s.description} (confidence {int(s.confidence*100)}%)")
563
+ st.caption(s.why)
564
+ # Allow user to choose 1–3 codes
565
+ icd_options = [f"{s.code} β€” {s.description}" for s in icd_suggestions]
566
+ picked_icd = st.multiselect(
567
+ "Select diagnosis code(s) to include on the claim",
568
+ options=icd_options,
569
+ default=icd_options[:1],
570
+ key=f"icd_sel_{selected}"
571
+ )
572
+ picked_icd_codes = [o.split(" β€” ")[0] for o in picked_icd]
573
+ else:
574
+ st.info("No ICD-10 suggestions available for this case.")
575
+ picked_icd_codes = []
576
+
577
+
578
  chosen_default = b.get("cpt_code") or (elig_codes[0] if elig_codes else None)
579
  if elig_codes:
580
  chosen = st.selectbox("Choose CPT (eligible)", options=elig_codes, index=elig_codes.index(chosen_default) if (chosen_default in elig_codes) else 0, key=f"cpt_{selected}")
 
587
  submit_claim = st.button("Submit Claim", type="primary", disabled=not (chosen and att_claim), key=f"submit_claim_{selected}")
588
 
589
  if submit_claim and chosen:
590
+ # Persist chosen code + ICD selections
591
+ store.update_case(selected, {
592
+ "billing": {
593
+ "cpt_code": chosen,
594
+ "icd_codes": picked_icd_codes, # NEW: persist ICDs in case JSON
595
+ }
596
+ })
597
+
598
+ # Build and save 837 JSON (includes ICD codes)
599
  pick = next((s for s in suggestions if s.code == chosen), None)
600
  rate = float(getattr(pick, "rate", 0.0)) if pick else 0.0
601
+ claim = billing.build_837_claim(
602
+ case,
603
+ code=str(chosen),
604
+ rate=rate,
605
+ minutes=minutes,
606
+ spoke=bool(spoke),
607
+ attested=True,
608
+ icd_codes=picked_icd_codes, # NEW: include ICD list in claim
609
+ )
610
  claim_path = config.make_export_path(selected, "Sample 837 Json.json")
611
  Path(claim_path).write_text(json.dumps(claim, ensure_ascii=False, indent=2), encoding="utf-8")
612
+
613
  st.success("Claim submitted. 837 JSON generated (see preview below).")
614
  st.caption(f"Claim: {claim_path.name}")
615