"""Modular presentation components for the medical coding Streamlit user interface.""" import html import re from typing import Any import streamlit as st from medical_coding.schemas.enums import AbstentionReason from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult from medical_coding.schemas.validation import AbstentionRecord def clean_html(raw_html: str) -> str: """Strip leading and trailing whitespace from each line of an HTML string. Prevents CommonMark from interpreting indented HTML lines as Markdown code blocks (
).
"""
return "\n".join(line.strip() for line in raw_html.strip().splitlines() if line.strip())
def render_header(
offline_mode: bool = True,
catalog_size: int = 25,
db_connected: bool = True,
) -> None:
"""Render the application branding banner with real-time operational status pills."""
db_status_pill = (
'â SQLite Connected'
if db_connected
else 'â DB Disconnected'
)
offline_pill = (
'đ 100% Offline AI'
if offline_mode
else 'Online Mode'
)
catalog_pill = f'đ {catalog_size} ICD Codes'
header_html = clean_html(
f"""
đĨ Local ICD-10-CM Medical Coding Engine
Evidence-backed clinical diagnosis extraction, hybrid semantic retrieval, deterministic rule auditing, and persistent encounter warehousing.
{offline_pill}
{db_status_pill}
{catalog_pill}
"""
)
st.markdown(header_html, unsafe_allow_html=True)
def render_kpi_metrics(result: CodingResult) -> None:
"""Render high-level KPIs for a single document coding run."""
c1, c2, c3, c4 = st.columns(4)
status_str = result.status.value if hasattr(result.status, "value") else str(result.status)
status_class = (
"badge-success"
if status_str == "SUCCESS"
else "badge-warning"
if status_str == "PARTIAL_SUCCESS"
else "badge-danger"
)
with c1:
st.markdown(
clean_html(
f"""
Status
{status_str}
"""
),
unsafe_allow_html=True,
)
with c2:
primary_code = result.primary_diagnosis.code if result.primary_diagnosis else "None"
st.markdown(
clean_html(
f"""
Primary ICD-10
{primary_code}
"""
),
unsafe_allow_html=True,
)
with c3:
st.markdown(
clean_html(
f"""
Secondary Diags
{len(result.secondary_diagnoses)}
"""
),
unsafe_allow_html=True,
)
with c4:
abst_count = len(result.abstentions)
abst_color = "#f87171" if abst_count > 0 else "#94a3b8"
st.markdown(
clean_html(
f"""
Abstentions
{abst_count}
"""
),
unsafe_allow_html=True,
)
def _clean_audit_from_evidence(ev: str) -> str:
"""Clean internal audit justifications and boilerplate from display evidence strings."""
if not ev:
return ""
if "Designated as " in ev:
ev = ev.split("Designated as ")[0].strip(" -|:\n")
if "Clinical criteria:" in ev:
ev = ev.split("Clinical criteria:")[0].strip(" -|:\n")
return ev.strip()
def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
"""Render the primary diagnosis card with evidence and specificity confirmation."""
st.markdown("### đ¯ Primary Diagnosis")
if not primary or not primary.code or primary.code in ("None", "[NO LOCAL CODE]") or primary.matching_status == "NO_DATABASE_MATCH":
st.info("âšī¸ No primary diagnosis assigned for this document (abstained or undetermined).")
return
code_display = html.escape(primary.code)
billable_badge = (
'â HIPAA Billable Leaf'
if primary.is_terminal_billable
else 'â Non-Billable Header'
)
acuity_badge = f'{html.escape(primary.acuity.value if hasattr(primary.acuity, "value") else str(primary.acuity))}'
certainty_badge = f'{html.escape(primary.certainty.value if hasattr(primary.certainty, "value") else str(primary.certainty))}'
nearest_badge = 'Nearest Relatable Match' if getattr(primary, "matching_status", "") == "NEAREST_MATCH" else ""
conf_pct = int(primary.confidence_score * 100)
codes_pills = []
if primary.icd10cm:
codes_pills.append(f'ICD-10-CM: {html.escape(str(primary.icd10cm))}')
if primary.icdo:
codes_pills.append(f'ICD-O: {html.escape(str(primary.icdo))}')
if primary.cpt:
codes_pills.append(f'CPT: {html.escape(str(primary.cpt))}')
codes_html = " ".join(codes_pills)
documented_row = ""
if primary.raw_term and primary.raw_term.lower() != (primary.description or "").lower():
documented_row = f'đŠē Documented Clinical Diagnosis: {html.escape(str(primary.raw_term))}'
safe_desc = html.escape(primary.description or "")
from medical_coding.utils.text import deduplicate_evidence_spans
spans = deduplicate_evidence_spans(primary.evidence_quote, primary.normalized_diagnosis or primary.description)
if len(spans) > 1:
spans_html = "".join(f'âĸ {html.escape(s)}' for s in spans)
evidence_content_html = spans_html
elif spans:
evidence_content_html = f'"{html.escape(spans[0])}"'
else:
evidence_content_html = '"None"'
primary_html = clean_html(
f"""
{code_display}
{billable_badge}
Confidence:
{conf_pct}%
đ Matched Database Concept:
{safe_desc}
{documented_row}
{acuity_badge}
{certainty_badge}
{nearest_badge}
Chief Reason for Encounter
{codes_html}
đ Verbatim Clinical Evidence Across Record:
{evidence_content_html}
"""
)
st.markdown(primary_html, unsafe_allow_html=True)
def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None:
"""Render the list of validated secondary comorbid diagnoses."""
from medical_coding.utils.text import deduplicate_evidence_spans, normalize_diagnosis_name
# Deduplicate secondaries by code and clean concept
seen_sec_codes: set[str] = set()
seen_sec_names: set[str] = set()
valid_secondaries: list[CodedDiagnosisResponse] = []
for s in (secondaries or []):
if not s.code or s.code in ("None", "[NO LOCAL CODE]") or s.matching_status == "NO_DATABASE_MATCH":
continue
c_key = s.code.strip()
n_key = (normalize_diagnosis_name(s.normalized_diagnosis or s.raw_term or s.description or "") or "").strip().lower()
if c_key in seen_sec_codes or (n_key and n_key in seen_sec_names):
continue
seen_sec_codes.add(c_key)
if n_key:
seen_sec_names.add(n_key)
valid_secondaries.append(s)
st.markdown(f"### đ Secondary Diagnoses ({len(valid_secondaries)})")
if not valid_secondaries:
st.write("No secondary comorbid diagnoses identified.")
return
for idx, diag in enumerate(valid_secondaries, start=1):
sec_code_display = html.escape(diag.code)
billable_badge = (
'â Billable'
if diag.is_terminal_billable
else 'â Non-Billable'
)
acuity_str = html.escape(diag.acuity.value if hasattr(diag.acuity, "value") else str(diag.acuity))
certainty_str = html.escape(diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty))
nearest_badge = 'Nearest Relatable Match' if getattr(diag, "matching_status", "") == "NEAREST_MATCH" else ""
sec_codes_pills = []
if diag.icd10cm:
sec_codes_pills.append(f'ICD-10-CM: {html.escape(str(diag.icd10cm))}')
if diag.icdo:
sec_codes_pills.append(f'ICD-O: {html.escape(str(diag.icdo))}')
if diag.cpt:
sec_codes_pills.append(f'CPT: {html.escape(str(diag.cpt))}')
sec_codes_html = " ".join(sec_codes_pills)
documented_row = ""
if diag.raw_term and diag.raw_term.lower() != (diag.description or "").lower():
documented_row = f'đŠē Documented Diagnosis: {html.escape(str(diag.raw_term))}'
safe_desc = html.escape(diag.description or "")
spans = deduplicate_evidence_spans(diag.evidence_quote, diag.normalized_diagnosis or diag.description)
if len(spans) > 1:
spans_html = "".join(f'âĸ {html.escape(s)}' for s in spans)
sec_evidence_html = spans_html
elif spans:
sec_evidence_html = f'"{html.escape(spans[0])}"'
else:
sec_evidence_html = '"None"'
secondary_html = clean_html(
f"""
#{idx}. {sec_code_display}
{safe_desc}
{documented_row}
{billable_badge}
{nearest_badge}
{acuity_str}
{certainty_str}
{sec_codes_html}
Clinical Evidence:
{sec_evidence_html}
"""
)
with st.container():
st.markdown(secondary_html, unsafe_allow_html=True)
def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
"""Render explicit abstentions, negated conditions, and exclusions."""
if not abstentions:
return
# Deduplicate abstentions
from medical_coding.utils.text import normalize_diagnosis_name
deduped_abst: list[AbstentionRecord] = []
seen_abst: set[str] = set()
for abst in abstentions:
term = (abst.raw_term or "").strip()
if not term:
continue
norm_t = (normalize_diagnosis_name(term) or term).lower().strip()
if norm_t in seen_abst or term.lower() in seen_abst:
continue
seen_abst.add(norm_t)
seen_abst.add(term.lower())
deduped_abst.append(abst)
if not deduped_abst:
return
with st.expander(f"đĢ Audited Abstentions & Rule-Outs ({len(deduped_abst)})", expanded=True):
st.caption("Conditions detected in documentation that were strictly abstained or excluded under ICD-10 guidelines:")
for abst in deduped_abst:
reason_str = abst.reason.value if hasattr(abst.reason, "value") else str(abst.reason)
stage_str = abst.stage.value if hasattr(abst.stage, "value") else str(abst.stage)
raw_term = abst.raw_term or "Unspecified Entity"
if (
abst.reason == AbstentionReason.NO_MATCHING_ICD_CANDIDATE
or reason_str in ("NO_MATCHING_ICD_CANDIDATE", "NO_CANDIDATE_FOUND")
or "No local code" in (abst.detail or "")
or "lacked verified local code" in (abst.detail or "")
):
badge_html = 'No Local Code (Abstained)'
else:
badge_html = f'{reason_str}'
st.markdown(
clean_html(
f"""
Condition: {raw_term}
{badge_html}
{abst.detail}
Enforced at stage: {stage_str}
"""
),
unsafe_allow_html=True,
)
def render_procedures(procedures: list[str]) -> None:
"""Render procedural and surgical interventions segregated from the diagnosis candidate inventory."""
if not procedures:
return
st.markdown(f"### đŠē Procedural & Surgical Interventions ({len(procedures)})")
st.caption("Documented procedures segregated from diagnosis coding under official coding guidelines (UHDDS):")
proc_items_html = []
for idx, proc in enumerate(procedures, start=1):
cpt_badge = ""
display_proc = proc
cpt_m = re.search(r"\[CPT:\s*([A-Za-z0-9]+)\]", proc)
if cpt_m:
cpt_code = cpt_m.group(1)
display_proc = re.sub(r"\s*\[CPT:\s*[A-Za-z0-9]+\]", "", proc).strip()
cpt_badge = f'CPT: {html.escape(cpt_code)}'
proc_items_html.append(
f"""
#{idx}.
{html.escape(display_proc)}
{cpt_badge}
Surgical / Interventional
"""
)
st.markdown(
clean_html(
f"""
{"".join(proc_items_html)}
đ Coding Invariant: Procedural interventions are strictly routed to procedure data and blocked from polluting secondary diagnosis code inventories.
"""
),
unsafe_allow_html=True,
)
def render_oncology_context(oncology_context: dict[str, Any] | None) -> None:
"""Render structured oncology tumor biology, receptors, Ki-67, and treatment response."""
if not oncology_context:
return
st.markdown("### đ§Ŧ Structured Oncology & Biomarker Context")
st.caption("Tumor biology, receptor panel, and treatment history extracted from oncology narrative:")
primary_site = oncology_context.get("primary_site") or "Unspecified"
laterality = oncology_context.get("laterality") or "Unspecified"
histology = oncology_context.get("histology") or "Not documented"
grade = oncology_context.get("grade") or "Not documented"
ki67 = oncology_context.get("ki67") or "Not documented"
receptors = oncology_context.get("receptors") or {}
metastatic_status = oncology_context.get("metastatic_status", False)
metastatic_sites = oncology_context.get("metastatic_sites", [])
prior_treatments = oncology_context.get("prior_treatments", [])
treatment_response = oncology_context.get("treatment_response") or "Not documented"
c1, c2, c3, c4 = st.columns(4)
with c1:
st.metric("Primary Site", f"{primary_site} ({laterality})")
with c2:
st.metric("Histology", histology)
with c3:
st.metric("Histologic Grade", grade)
with c4:
st.metric("Ki-67 Index", ki67)
# Receptor panel
rec_pills = []
if receptors:
for r_name, r_val in receptors.items():
r_color = "#34d399" if "pos" in str(r_val).lower() or "+" in str(r_val) else "#f87171"
rec_pills.append(
f''
f'{html.escape(r_name.upper())}: {html.escape(str(r_val))}'
f''
)
receptors_html = "".join(rec_pills) if rec_pills else 'No receptor panel documented'
# Metastatic sites
if metastatic_status:
sites_str = ", ".join(metastatic_sites) if metastatic_sites else "Present (unspecified site)"
meta_badge = f'Metastatic: {html.escape(sites_str)}'
else:
meta_badge = 'No Distant Metastases Documented'
# Prior treatments & response
tx_str = ", ".join(prior_treatments) if prior_treatments else "None documented"
oncology_html = clean_html(
f"""
đŦ Tumor Biology & Biomarker Profile
{meta_badge}
Receptor Panel & Biomarkers:
{receptors_html}
Prior Treatment: {html.escape(tx_str)}
Treatment Response: {html.escape(treatment_response)}
"""
)
st.markdown(oncology_html, unsafe_allow_html=True)
def render_operative_findings(operative_findings: list[dict[str, Any]]) -> None:
"""Render operative and intraoperative findings with UHDDS clinical-coding eligibility status."""
if not operative_findings:
return
st.markdown(f"### đ Operative Findings & Incidental Observations ({len(operative_findings)})")
st.caption("Intraoperative observations evaluated under UHDDS criteria (incidental findings without dedicated surgical intervention or therapy are excluded from secondary diagnoses):")
rows_html = []
for f in operative_findings:
term = f.get("term", "Unknown Finding")
quote = f.get("verbatim_quote", "")
sec = f.get("source_section", "OPERATIVE_FINDINGS")
is_incidental = f.get("is_incidental", True)
eligibility_badge = (
'Excluded from Billing (Incidental / Unmanaged)'
if is_incidental
else 'Eligible (Dedicated Surgical Intervention)'
)
rows_html.append(
f"""
{html.escape(term)}
{eligibility_badge}
Section: {html.escape(sec)}
"{html.escape(quote)}"
"""
)
st.markdown(
clean_html(
f"""
{"".join(rows_html)}
"""
),
unsafe_allow_html=True,
)
def render_validation_audit_trail(
primary: CodedDiagnosisResponse | None,
secondaries: list[CodedDiagnosisResponse],
validation_flags: dict[str, Any] | None = None,
) -> None:
"""Render deterministic non-LLM validation rule checks with evidence-based verification."""
with st.expander("đĄī¸ Evidence-Based Deterministic Invariant & Clinical Rule Audit", expanded=False):
st.caption("Authoritative validation verifies clinical meaning and anatomical congruence, not just database existence:")
st.markdown(
clean_html(
"""
â Laterality Congruence Check: Verified that code laterality matches documented laterality (left/right/bilateral); contradictory codes rejected even if billable.
â Anatomical Site & Subsite Match: Verified organ group and quadrant congruence (e.g. breast quadrant, femur vs bone); anatomical mismatches strictly rejected.
â Procedure vs Diagnosis Segregation: Verified that surgical procedures (mastectomy, salpingo-oophorectomy, etc.) are excluded from secondary diagnosis candidate inventory.
â UHDDS Operative Finding Gate: Verified that incidental intraoperative observations without dedicated surgical intervention or post-op therapy are excluded from billing.
â Catalog Existence & Billable Specificity: Verified that all assigned codes exist in the authoritative dataset as terminal leaf codes.
â Single-Primary Invariant: Maximum of exactly 1 primary admission diagnosis enforced.
â Mutual Excludes1 Constraint: No mutually contradictory codes co-assigned for this encounter.
"""
),
unsafe_allow_html=True,
)
def render_pdf_page_inspector(pages: list[Any]) -> None:
"""Render an interactive page-by-page text explorer for ingested PDFs."""
if not pages:
return
def _get(obj: Any, key: str, default: Any = None) -> Any:
if isinstance(obj, dict):
return obj.get(key, default)
return getattr(obj, key, default)
page_numbers = [_get(p, "page_number", idx + 1) for idx, p in enumerate(pages)]
with st.expander(f"đ Ingested PDF Document Viewer ({len(pages)} Pages)", expanded=False):
selected_page = st.selectbox(
"Select Page to Inspect:",
options=page_numbers,
format_func=lambda x: f"Page {x} of {len(pages)}",
)
page_obj = next((p for p in pages if _get(p, "page_number") == selected_page), pages[0])
norm_text = str(_get(page_obj, "normalized_text", "") or "")
char_count = _get(page_obj, "char_count", len(norm_text))
word_count = _get(page_obj, "word_count", len(norm_text.split()))
has_images = _get(page_obj, "has_images", False)
c1, c2, c3 = st.columns(3)
c1.metric("Character Count", char_count)
c2.metric("Word Count", word_count)
c3.metric("Embedded Images", "Yes" if has_images else "No")
escaped_text = html.escape(norm_text)
st.markdown(
f"""
{escaped_text}
""",
unsafe_allow_html=True,
)
NODE_TITLES: dict[str, str] = {
"validate_document": "Document Validation",
"extract_text": "Multimodal Normalization",
"extract_diagnoses": "Clinical Extraction Agent",
"analyze_context": "Clinical Context Analysis",
"classify_diagnoses": "Classification Agent",
"retrieve_candidates": "Multi-System Retrieval",
"rank_candidates": "Candidate Ranking Agent",
"validate_codes": "Deterministic Validation",
"evaluate_confidence": "Confidence & Abstention",
"finalize_output": "Final Output Generation",
}
def render_process_oversight_timeline(steps: list[dict[str, Any]], total_duration_ms: float = 0.0) -> None:
"""Render a comprehensive process oversight timeline (suppressed per user specification)."""
return
def render_failure_alert(
failed_step: str | None,
error_message: str | None,
error_traceback: str | None = None,
duration_ms: float = 0.0,
) -> None:
"""Render a prominent diagnostic banner indicating the exact node failure and stack trace."""
step_key = failed_step or "unknown_step"
title = NODE_TITLES.get(step_key, step_key)
err_text = error_message or "Unknown exception during workflow execution"
st.markdown(
f"""
đ¨
Pipeline Execution Halted: Node Failure Encountered
Exact Failing Stage:
{step_key}
({title})
ERROR DIAGNOSTIC:
{err_text}
Prior completed stages preserved in audit database.
""",
unsafe_allow_html=True,
)
if error_traceback:
with st.expander("đ ī¸ View Detailed Exception Stack Trace", expanded=False):
st.code(error_traceback, language="python")