fix: resolve HTML tag rendering bug and ensure explicit primary diagnosis precedence over secondary and meta-narratives
This commit is contained in:
@@ -981,10 +981,36 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
# 1. Section / Reason for Admission Context (UHDDS Authority Hierarchy)
|
||||
# Under UHDDS, condition established after study chiefly responsible for occasioning admission
|
||||
# or underlying condition occasioning procedural/medical inpatient therapy
|
||||
# Function to test whether diag_lower is the direct primary diagnosis mention in a clause
|
||||
def _check_primary_match(text: str, target_diag: str) -> bool:
|
||||
for match in re.finditer(rf"\b(?:principal|primary)(?:\s+diagnos[ei]s)?\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE):
|
||||
clause = match.group(1).lower().strip()
|
||||
# Strip subsequent conditions attached by "with", "complicated by", "secondary to", ","
|
||||
for delim in [" with ", " complicated by ", " secondary to ", ","]:
|
||||
if delim in clause:
|
||||
clause = clause[:clause.find(delim)].strip()
|
||||
if re.search(rf"\b{re.escape(target_diag)}\b", clause):
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_secondary_match(text: str, target_diag: str) -> bool:
|
||||
for match in re.finditer(rf"\bsecondary(?:\s+diagnos[ei]s)?\s*[:\-–—]\s*([^\n.;]+)", text, re.IGNORECASE):
|
||||
clause = match.group(1).lower().strip()
|
||||
if re.search(rf"\b{re.escape(target_diag)}\b", clause):
|
||||
return True
|
||||
return False
|
||||
|
||||
is_explicit_primary = bool(
|
||||
re.search(rf"\b(?:principal|primary)\s+diagnos[ei]s\b[^\n\.\;:]*?:\s*[^\n\.\;]*?{re.escape(diag_lower)}", full_context)
|
||||
or (doc_lower and re.search(rf"\b(?:principal|primary)\s+diagnos[ei]s\b[^\n\.\;:]*?:\s*[^\n\.\;]*?{re.escape(diag_lower)}", doc_lower))
|
||||
_check_primary_match(full_context, diag_lower)
|
||||
or (doc_lower and _check_primary_match(doc_lower, diag_lower))
|
||||
or sec_lower in ("principal diagnosis", "primary diagnosis", "principal diagnoses", "primary diagnoses")
|
||||
or getattr(asm, "role", None) in (DiagnosisRole.PRIMARY, "PRIMARY")
|
||||
or getattr(asm, "is_primary", False)
|
||||
)
|
||||
is_explicit_secondary = bool(
|
||||
_check_secondary_match(full_context, diag_lower)
|
||||
or (doc_lower and _check_secondary_match(doc_lower, diag_lower))
|
||||
or sec_lower in ("secondary diagnosis", "secondary diagnoses", "additional diagnoses")
|
||||
)
|
||||
is_admission_driver = False
|
||||
adm_regex = rf"\b(?:admitted\s+(?:for|with|to|in)|reason\s+for\s+admission|admitting\s+diagnosis|principal\s+diagnosis)\b[^\n\.\;]*?(?:due\s+to\s+|for\s+|of\s+|in\s+)?{re.escape(diag_lower)}"
|
||||
@@ -1016,9 +1042,15 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
score += 6.0
|
||||
reasons.append("Identified as principal condition occasioning admission (+6.0)")
|
||||
|
||||
if any(
|
||||
term in full_context
|
||||
if is_explicit_secondary and not is_explicit_primary:
|
||||
score -= 5.0
|
||||
reasons.append("Explicitly documented as SECONDARY DIAGNOSIS by provider (-5.0)")
|
||||
|
||||
in_final_sec = any(
|
||||
term in sec_lower
|
||||
for term in [
|
||||
"principal diagnosis",
|
||||
"primary diagnosis",
|
||||
"discharge diagnosis",
|
||||
"discharge diagnoses",
|
||||
"final diagnosis",
|
||||
@@ -1026,11 +1058,13 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
"final coding summary",
|
||||
"coding summary",
|
||||
]
|
||||
):
|
||||
) or getattr(asm, "section", "") in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS", "DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES")
|
||||
|
||||
if in_final_sec:
|
||||
score += 5.0
|
||||
reasons.append("Explicitly documented under discharge / final diagnoses (+5.0)")
|
||||
elif any(
|
||||
term in full_context
|
||||
term in sec_lower or term in full_context
|
||||
for term in [
|
||||
"chief complaint",
|
||||
"reason for admission",
|
||||
@@ -1063,8 +1097,8 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
)
|
||||
is_leading_primary = bool(
|
||||
is_explicit_primary and not is_complication and (
|
||||
re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", full_context)
|
||||
or (doc_lower and re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", doc_lower))
|
||||
re.search(rf"\b{re.escape(diag_lower)}\s+(?:with|complicated\s+by)\b", ev_lower)
|
||||
or (doc_lower and re.search(rf"\b{re.escape(diag_lower)}\s+(?:with|complicated\s+by)\b", doc_lower))
|
||||
)
|
||||
)
|
||||
if is_complication:
|
||||
|
||||
@@ -279,7 +279,7 @@ class EvidenceFirstFactExtractor:
|
||||
|
||||
# Phase 1: High-yield diagnosis sections (Discharge Diagnoses, Final Diagnoses, Assessment & Plan)
|
||||
for sec in sections:
|
||||
if sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT", "ASSESSMENT_PLAN"):
|
||||
if sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS", "SECONDARY_DIAGNOSES", "ASSESSMENT", "ASSESSMENT_PLAN"):
|
||||
items = self._parse_diagnosis_items(sec.content, sec)
|
||||
for item in items:
|
||||
self._register_candidate(candidates_by_key, item)
|
||||
@@ -451,8 +451,12 @@ class EvidenceFirstFactExtractor:
|
||||
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
|
||||
# Skip absence statements and treatment instructions
|
||||
if HardClinicalCandidateGate.is_absence_statement(sent_clean) or HardClinicalCandidateGate.is_treatment_instruction(sent_clean):
|
||||
# Skip absence statements, treatment instructions, and cross-reference boilerplate
|
||||
if (
|
||||
HardClinicalCandidateGate.is_absence_statement(sent_clean)
|
||||
or HardClinicalCandidateGate.is_treatment_instruction(sent_clean)
|
||||
or re.search(r"\b(?:symptoms?|complaints?)\s+described\s+in\b|\bdescribed\s+in\s+(?:the\s+)?final\s+diagnosis\b|\babove\s+mentioned\s+complaints\b", sent_clean, re.IGNORECASE)
|
||||
):
|
||||
continue
|
||||
|
||||
# Pattern 2: Explicit admission / diagnosis / condition clauses
|
||||
@@ -463,6 +467,12 @@ class EvidenceFirstFactExtractor:
|
||||
)
|
||||
if adm_match:
|
||||
clause = adm_match.group(1).strip()
|
||||
clause = re.sub(
|
||||
r"^(?:(?:several|\d+)\s+(?:days?|weeks?|months?|hours?)\s+of\s+)",
|
||||
"",
|
||||
clause,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
for tail_delim in [" on ", " treated with ", " managed with ", " secondary to ", " requiring ", " with good response", " with symptom"]:
|
||||
if tail_delim in clause.lower():
|
||||
idx = clause.lower().find(tail_delim)
|
||||
@@ -470,7 +480,7 @@ class EvidenceFirstFactExtractor:
|
||||
|
||||
# Causal admission: "initiation of chemotherapy for DLBCL" -> "DLBCL"
|
||||
causal_m = re.search(
|
||||
r"(?:initiation\s+of\s+|cycle\s+\d+\s+of\s+|course\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)?\s*(?:for|of)\s+([^.,;\n]+)",
|
||||
r"(?:(?:initiation|cycle\s+\d+|course)\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)\s+(?:for|of)\s+([^.,;\n]+)",
|
||||
clause,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
@@ -541,6 +551,14 @@ class EvidenceFirstFactExtractor:
|
||||
lines = [line.strip() for line in content.split("\n") if line.strip()]
|
||||
|
||||
for line_idx, line in enumerate(lines):
|
||||
# Check explicit provider-designated PRIMARY role before stripping prefixes
|
||||
is_explicit_primary_line = bool(
|
||||
re.match(
|
||||
r"^\s*(?:primary|principal)\s*(?:diagnosis|diagnoses|condition)?\s*[:\-–—]",
|
||||
line,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
)
|
||||
# Strip list numbering e.g. "1. Acute right emphysematous pyelonephritis - underwent DJ stenting"
|
||||
cleaned_line = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
|
||||
# Strip structural role prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:")
|
||||
@@ -606,7 +624,10 @@ class EvidenceFirstFactExtractor:
|
||||
if is_explicit_historical
|
||||
else (
|
||||
DiagnosisRole.PRIMARY
|
||||
if (sec.section_name in ("DISCHARGE_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0)
|
||||
if (
|
||||
(is_explicit_primary_line and sub_idx == 0)
|
||||
or (sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES", "PRINCIPAL_DIAGNOSIS") and line_idx == 0 and sub_idx == 0)
|
||||
)
|
||||
else DiagnosisRole.SECONDARY
|
||||
)
|
||||
)
|
||||
@@ -625,6 +646,8 @@ class EvidenceFirstFactExtractor:
|
||||
# Explicit PRINCIPAL_DIAGNOSIS gets highest base score (+15.0); DISCHARGE_DIAGNOSES gets +10.0; SECONDARY gets +3.0
|
||||
if is_explicit_historical:
|
||||
base_admitting = -50.0
|
||||
elif is_explicit_primary_line and sub_idx == 0:
|
||||
base_admitting = 15.0
|
||||
elif sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"):
|
||||
base_admitting = 15.0 if (line_idx == 0 and sub_idx == 0) else 5.0
|
||||
elif sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES"):
|
||||
@@ -677,6 +700,10 @@ class EvidenceFirstFactExtractor:
|
||||
if not cleaned:
|
||||
return []
|
||||
|
||||
# Skip cross-reference boilerplate (e.g. "presented with symptoms described in the final diagnosis")
|
||||
if re.search(r"\b(?:symptoms?|complaints?)\s+described\s+in\b|\bdescribed\s+in\s+(?:the\s+)?final\s+diagnosis\b|\babove\s+mentioned\s+complaints\b", cleaned, re.IGNORECASE):
|
||||
return []
|
||||
|
||||
# Split sentences (do not split decimal numbers like 101.4F or 1.5 mg/dL)
|
||||
sentences = [s.strip() for s in re.split(r"\.(?!\d)|[\n;]+", cleaned) if s.strip()]
|
||||
for s in sentences:
|
||||
@@ -684,8 +711,14 @@ class EvidenceFirstFactExtractor:
|
||||
continue
|
||||
|
||||
cond_term = s
|
||||
cond_term = re.sub(
|
||||
r"^(?:(?:several|\d+)\s+(?:days?|weeks?|months?|hours?)\s+of\s+)",
|
||||
"",
|
||||
cond_term,
|
||||
flags=re.IGNORECASE,
|
||||
).strip()
|
||||
causal_m = re.search(
|
||||
r"(?:admitted\s+(?:for|with)|presented\s+with|evaluation\s+of|reason\s+for\s+admission\s*:?)\s*(?:initiation\s+of\s+)?(?:cycle\s+\d+\s+(?:of\s+)?)?(?:course\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)?\s*(?:for|of|with)?\s*([^.,;\n]+)",
|
||||
r"(?:admitted\s+(?:for|with)|presented\s+with|evaluation\s+of|reason\s+for\s+admission\s*:?)\s*(?:(?:initiation|cycle\s+\d+|course)\s+of\s+)?(?:chemotherapy|immunotherapy|radiation|treatment|therapy|infusion|management|stenting|surgery)\s+(?:for|of|with)\s+([^.,;\n]+)",
|
||||
s,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
@@ -1408,7 +1441,7 @@ class EvidenceFirstFactExtractor:
|
||||
cand.treatment_relevance = 1.0
|
||||
cand.encounter_relevance = 1.0
|
||||
cand.scores.encounter_relevance = 1.0
|
||||
is_from_principal_sec = any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence)
|
||||
is_from_principal_sec = any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence) or cand.role == DiagnosisRole.PRIMARY
|
||||
cand.scores.admitting_score += (3.0 if is_from_principal_sec else 1.0)
|
||||
cand.temporality = Temporality.CURRENT
|
||||
cand.assertion_status = AssertionStatus.CONFIRMED
|
||||
|
||||
@@ -1233,7 +1233,7 @@ def _extract_conditions_deterministically(
|
||||
primary_ev = cand.primary_evidence_quote
|
||||
primary_sec = cand.evidence[0].section if cand.evidence else "DOCUMENTATION"
|
||||
is_pmh = any(ev.section in ("PAST_MEDICAL_HISTORY", "PAST_SURGICAL_HISTORY") for ev in cand.evidence)
|
||||
if any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence):
|
||||
if any(ev.section in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS") for ev in cand.evidence) or cand.role == DiagnosisRole.PRIMARY:
|
||||
sec_name = "PRINCIPAL_DIAGNOSIS"
|
||||
elif any(ev.section in ("SECONDARY_DIAGNOSES", "ADDITIONAL_DIAGNOSES") for ev in cand.evidence):
|
||||
sec_name = "SECONDARY_DIAGNOSES"
|
||||
|
||||
@@ -8,6 +8,14 @@ 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 (<pre><code>).
|
||||
"""
|
||||
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,
|
||||
@@ -26,7 +34,7 @@ def render_header(
|
||||
)
|
||||
catalog_pill = f'<span class="pill-badge badge-secondary">📚 {catalog_size} ICD Codes</span>'
|
||||
|
||||
st.markdown(
|
||||
header_html = clean_html(
|
||||
f"""
|
||||
<div class="clinic-header">
|
||||
<div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 12px;">
|
||||
@@ -45,9 +53,9 @@ def render_header(
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
"""
|
||||
)
|
||||
st.markdown(header_html, unsafe_allow_html=True)
|
||||
|
||||
|
||||
def render_kpi_metrics(result: CodingResult) -> None:
|
||||
@@ -65,37 +73,43 @@ def render_kpi_metrics(result: CodingResult) -> None:
|
||||
|
||||
with c1:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Status</div>
|
||||
<div style="margin-top: 8px;">
|
||||
<span class="pill-badge {status_class}">{status_str}</span>
|
||||
clean_html(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Status</div>
|
||||
<div style="margin-top: 8px;">
|
||||
<span class="pill-badge {status_class}">{status_str}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c2:
|
||||
primary_code = result.primary_diagnosis.code if result.primary_diagnosis else "None"
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Primary ICD-10</div>
|
||||
<div class="kpi-value" style="color: #38bdf8;">{primary_code}</div>
|
||||
</div>
|
||||
""",
|
||||
clean_html(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Primary ICD-10</div>
|
||||
<div class="kpi-value" style="color: #38bdf8;">{primary_code}</div>
|
||||
</div>
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c3:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Secondary Diags</div>
|
||||
<div class="kpi-value">{len(result.secondary_diagnoses)}</div>
|
||||
</div>
|
||||
""",
|
||||
clean_html(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Secondary Diags</div>
|
||||
<div class="kpi-value">{len(result.secondary_diagnoses)}</div>
|
||||
</div>
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
@@ -103,23 +117,27 @@ def render_kpi_metrics(result: CodingResult) -> None:
|
||||
abst_count = len(result.abstentions)
|
||||
abst_color = "#f87171" if abst_count > 0 else "#94a3b8"
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Abstentions</div>
|
||||
<div class="kpi-value" style="color: {abst_color};">{abst_count}</div>
|
||||
</div>
|
||||
""",
|
||||
clean_html(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Abstentions</div>
|
||||
<div class="kpi-value" style="color: {abst_color};">{abst_count}</div>
|
||||
</div>
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
with c5:
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Processing Time</div>
|
||||
<div class="kpi-value">{result.processing_time_ms:.1f}<span style="font-size: 13px; font-weight: normal; color: #94a3b8;"> ms</span></div>
|
||||
</div>
|
||||
""",
|
||||
clean_html(
|
||||
f"""
|
||||
<div class="kpi-card">
|
||||
<div class="kpi-label">Processing Time</div>
|
||||
<div class="kpi-value">{result.processing_time_ms:.1f}<span style="font-size: 13px; font-weight: normal; color: #94a3b8;"> ms</span></div>
|
||||
</div>
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
@@ -154,7 +172,11 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
codes_pills.append(f'<span class="pill-badge badge-success">CPT: {primary.cpt}</span>')
|
||||
codes_html = " ".join(codes_pills)
|
||||
|
||||
st.markdown(
|
||||
documented_row = ""
|
||||
if primary.raw_term and primary.raw_term.lower() != (primary.description or "").lower():
|
||||
documented_row = f'<div style="margin: 6px 0; font-size: 14px; color: #e2e8f0;">🩺 <strong style="color: #38bdf8;">Documented Clinical Diagnosis:</strong> {primary.raw_term}</div>'
|
||||
|
||||
primary_html = clean_html(
|
||||
f"""
|
||||
<div class="primary-card">
|
||||
<div class="primary-card-header">
|
||||
@@ -171,7 +193,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
<span style="font-size: 13px; color: #94a3b8; display: block; margin-bottom: 2px;">📖 Matched Database Concept:</span>
|
||||
{primary.description}
|
||||
</div>
|
||||
{f'<div style="margin: 6px 0; font-size: 14px; color: #e2e8f0;">🩺 <strong style="color: #38bdf8;">Documented Clinical Diagnosis:</strong> {primary.raw_term}</div>' if primary.raw_term and primary.raw_term.lower() != (primary.description or "").lower() else ''}
|
||||
{documented_row}
|
||||
<div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
|
||||
{acuity_badge}
|
||||
{certainty_badge}
|
||||
@@ -185,9 +207,9 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
<span class="evidence-quote">"{primary.evidence_quote}"</span>
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
"""
|
||||
)
|
||||
st.markdown(primary_html, unsafe_allow_html=True)
|
||||
|
||||
|
||||
def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None:
|
||||
@@ -219,33 +241,37 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
|
||||
sec_codes_pills.append(f'<span class="pill-badge badge-success">CPT: {diag.cpt}</span>')
|
||||
sec_codes_html = " ".join(sec_codes_pills)
|
||||
|
||||
with st.container():
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="secondary-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; flex-wrap: wrap;">
|
||||
<div>
|
||||
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {sec_code_display}</strong>
|
||||
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{diag.description}</span>
|
||||
{f'<div style="margin-top: 4px; font-size: 13px; color: #cbd5e1;">🩺 <strong style="color: #38bdf8;">Documented Diagnosis:</strong> {diag.raw_term}</div>' if diag.raw_term and diag.raw_term.lower() != (diag.description or "").lower() else ''}
|
||||
</div>
|
||||
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
|
||||
{billable_badge}
|
||||
<span class="pill-badge badge-secondary">{acuity_str}</span>
|
||||
<span class="pill-badge badge-secondary">{certainty_str}</span>
|
||||
{sec_codes_html}
|
||||
</div>
|
||||
documented_row = ""
|
||||
if diag.raw_term and diag.raw_term.lower() != (diag.description or "").lower():
|
||||
documented_row = f'<div style="margin-top: 4px; font-size: 13px; color: #cbd5e1;">🩺 <strong style="color: #38bdf8;">Documented Diagnosis:</strong> {diag.raw_term}</div>'
|
||||
|
||||
secondary_html = clean_html(
|
||||
f"""
|
||||
<div class="secondary-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; flex-wrap: wrap;">
|
||||
<div>
|
||||
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {sec_code_display}</strong>
|
||||
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{diag.description}</span>
|
||||
{documented_row}
|
||||
</div>
|
||||
<div class="evidence-box">
|
||||
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
|
||||
Clinical Evidence:
|
||||
</span>
|
||||
<span class="evidence-quote">"{diag.evidence_quote}"</span>
|
||||
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
|
||||
{billable_badge}
|
||||
<span class="pill-badge badge-secondary">{acuity_str}</span>
|
||||
<span class="pill-badge badge-secondary">{certainty_str}</span>
|
||||
{sec_codes_html}
|
||||
</div>
|
||||
</div>
|
||||
""",
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
<div class="evidence-box">
|
||||
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
|
||||
Clinical Evidence:
|
||||
</span>
|
||||
<span class="evidence-quote">"{diag.evidence_quote}"</span>
|
||||
</div>
|
||||
</div>
|
||||
"""
|
||||
)
|
||||
with st.container():
|
||||
st.markdown(secondary_html, unsafe_allow_html=True)
|
||||
|
||||
|
||||
def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
|
||||
@@ -261,16 +287,18 @@ def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
|
||||
raw_term = abst.raw_term or "Unspecified Entity"
|
||||
|
||||
st.markdown(
|
||||
f"""
|
||||
<div class="abstention-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
|
||||
<strong style="color: #f87171; font-size: 14px;">Condition: {raw_term}</strong>
|
||||
<span class="pill-badge badge-danger">{reason_str}</span>
|
||||
clean_html(
|
||||
f"""
|
||||
<div class="abstention-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
|
||||
<strong style="color: #f87171; font-size: 14px;">Condition: {raw_term}</strong>
|
||||
<span class="pill-badge badge-danger">{reason_str}</span>
|
||||
</div>
|
||||
<div style="font-size: 13px; color: #e2e8f0;">{abst.detail}</div>
|
||||
<div style="font-size: 11px; color: #94a3b8; margin-top: 4px;">Enforced at stage: <code>{stage_str}</code></div>
|
||||
</div>
|
||||
<div style="font-size: 13px; color: #e2e8f0;">{abst.detail}</div>
|
||||
<div style="font-size: 11px; color: #94a3b8; margin-top: 4px;">Enforced at stage: <code>{stage_str}</code></div>
|
||||
</div>
|
||||
""",
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
@@ -284,23 +312,25 @@ def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, second
|
||||
all_codes.extend(secondaries)
|
||||
|
||||
st.markdown(
|
||||
"""
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Catalog Existence Check:</strong> All assigned codes exist in the authoritative local ICD-10-CM dataset.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>HIPAA Terminal Specificity:</strong> Codes are verified billable terminal leaf nodes (non-category headers).
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Single-Primary Invariant:</strong> Maximum of exactly 1 primary admission diagnosis enforced.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Mutual Excludes1 Constraint:</strong> No mutually contradictory codes co-assigned for this encounter.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Anti-Hallucination Bound:</strong> Codes were bounded exclusively to the retrieved candidate pool.
|
||||
</div>
|
||||
""",
|
||||
clean_html(
|
||||
"""
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Catalog Existence Check:</strong> All assigned codes exist in the authoritative local ICD-10-CM dataset.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>HIPAA Terminal Specificity:</strong> Codes are verified billable terminal leaf nodes (non-category headers).
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Single-Primary Invariant:</strong> Maximum of exactly 1 primary admission diagnosis enforced.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Mutual Excludes1 Constraint:</strong> No mutually contradictory codes co-assigned for this encounter.
|
||||
</div>
|
||||
<div class="audit-check-item">
|
||||
<span class="check-pass">✔</span> <strong>Anti-Hallucination Bound:</strong> Codes were bounded exclusively to the retrieved candidate pool.
|
||||
</div>
|
||||
"""
|
||||
),
|
||||
unsafe_allow_html=True,
|
||||
)
|
||||
|
||||
|
||||
@@ -85,6 +85,13 @@ METADATA_PATTERNS = [
|
||||
r"\babove\s+mentioned\s+complaints\b",
|
||||
r"\bfeared\s+health\s+complaint\b",
|
||||
r"\bcomplaint\s+in\s+whom\s+no\s+diagnosis\s+is\s+made\b",
|
||||
# Cross-references, section references, and meta-narrative boilerplate
|
||||
r"\b(?:symptoms?|complaints?|conditions?|diagnos[ei]s)\s+(?:described|mentioned|listed|noted|specified)\s+(?:in|under|above|below)\b",
|
||||
r"\b(?:described|mentioned|listed|noted|specified)\s+(?:in|under)\s+(?:the\s+)?(?:final|discharge|admitting|admission)?\s*diagnos[ei]s\b",
|
||||
r"\b(?:symptoms?|complaints?)\s+as\s+(?:above|below|mentioned)\b",
|
||||
r"\b(?:as\s+described\s+above|as\s+mentioned\s+above|described\s+above|as\s+above)\b",
|
||||
r"\babove\s+mentioned\s+(?:complaints?|symptoms?|conditions?)\b",
|
||||
r"\bseveral\s+days\s+of\s+(?:the\s+)?symptoms\b",
|
||||
# Allergy statements and negative metadata (Section 3)
|
||||
r"^\s*(?:drug\s+)?allerg(?:y|ies)(?:\s*:)?\s*(?:none|nkda|no\s+known\s+(?:drug\s+)?allergies|nil|na|n/a)?\s*$",
|
||||
r"^\s*(?:no\s+known\s+(?:drug\s+)?allergies|nkda)\s*$",
|
||||
@@ -220,8 +227,14 @@ class HardClinicalCandidateGate:
|
||||
if re.search(pat, term_lower):
|
||||
return False, f"Section heading, metadata, allergy, or clinical status artifact: '{clean_term}'"
|
||||
|
||||
# Check 4b: Physical exam, vital signs, systemic examination noise
|
||||
if any(w in term_lower for w in ["patient alert", "responsive temperature", "temperature :", "pulse :", "respiratory rate :", "bp :", "spo2 :", "rs :", "cvs :", "cns :", "pa :", "aebe", "s1, s2 heard well", "soft, non tender", "further management", "above mentioned complaints"]):
|
||||
# Check 4b: Physical exam, vital signs, systemic examination noise, and meta-narrative boilerplate
|
||||
if any(w in term_lower for w in [
|
||||
"patient alert", "responsive temperature", "temperature :", "pulse :",
|
||||
"respiratory rate :", "bp :", "spo2 :", "rs :", "cvs :", "cns :", "pa :",
|
||||
"aebe", "s1, s2 heard well", "soft, non tender", "further management",
|
||||
"above mentioned complaints", "symptoms described", "described in the final diagnosis",
|
||||
"described in final diagnosis", "symptoms described in", "several days of the symptoms",
|
||||
]):
|
||||
return False, f"Physical exam, vital sign, or administrative boilerplate artifact: '{clean_term}'"
|
||||
|
||||
# Check 5: Standalone tumor staging or genetic attributes
|
||||
|
||||
Reference in New Issue
Block a user