fix: resolve HTML tag rendering bug and ensure explicit primary diagnosis precedence over secondary and meta-narratives

This commit is contained in:
Abhinav Gupta
2026-10-08 15:03:02 +05:30
parent ced32805b3
commit 7b40481e36
6 changed files with 271 additions and 106 deletions
+42 -8
View File
@@ -981,10 +981,36 @@ class PrimarySecondaryClassifier(BaseAgent):
# 1. Section / Reason for Admission Context (UHDDS Authority Hierarchy) # 1. Section / Reason for Admission Context (UHDDS Authority Hierarchy)
# Under UHDDS, condition established after study chiefly responsible for occasioning admission # Under UHDDS, condition established after study chiefly responsible for occasioning admission
# or underlying condition occasioning procedural/medical inpatient therapy # 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( is_explicit_primary = bool(
re.search(rf"\b(?:principal|primary)\s+diagnos[ei]s\b[^\n\.\;:]*?:\s*[^\n\.\;]*?{re.escape(diag_lower)}", full_context) _check_primary_match(full_context, diag_lower)
or (doc_lower and re.search(rf"\b(?:principal|primary)\s+diagnos[ei]s\b[^\n\.\;:]*?:\s*[^\n\.\;]*?{re.escape(diag_lower)}", doc_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 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 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)}" 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 score += 6.0
reasons.append("Identified as principal condition occasioning admission (+6.0)") reasons.append("Identified as principal condition occasioning admission (+6.0)")
if any( if is_explicit_secondary and not is_explicit_primary:
term in full_context 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 [ for term in [
"principal diagnosis",
"primary diagnosis",
"discharge diagnosis", "discharge diagnosis",
"discharge diagnoses", "discharge diagnoses",
"final diagnosis", "final diagnosis",
@@ -1026,11 +1058,13 @@ class PrimarySecondaryClassifier(BaseAgent):
"final coding summary", "final coding summary",
"coding summary", "coding summary",
] ]
): ) or getattr(asm, "section", "") in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS", "DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES")
if in_final_sec:
score += 5.0 score += 5.0
reasons.append("Explicitly documented under discharge / final diagnoses (+5.0)") reasons.append("Explicitly documented under discharge / final diagnoses (+5.0)")
elif any( elif any(
term in full_context term in sec_lower or term in full_context
for term in [ for term in [
"chief complaint", "chief complaint",
"reason for admission", "reason for admission",
@@ -1063,8 +1097,8 @@ class PrimarySecondaryClassifier(BaseAgent):
) )
is_leading_primary = bool( is_leading_primary = bool(
is_explicit_primary and not is_complication and ( is_explicit_primary and not is_complication and (
re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", full_context) re.search(rf"\b{re.escape(diag_lower)}\s+(?:with|complicated\s+by)\b", ev_lower)
or (doc_lower and re.search(rf"{re.escape(diag_lower)}[^\n.;]*?\b(?:with|complicated\s+by)\b", doc_lower)) or (doc_lower and re.search(rf"\b{re.escape(diag_lower)}\s+(?:with|complicated\s+by)\b", doc_lower))
) )
) )
if is_complication: if is_complication:
@@ -279,7 +279,7 @@ class EvidenceFirstFactExtractor:
# Phase 1: High-yield diagnosis sections (Discharge Diagnoses, Final Diagnoses, Assessment & Plan) # Phase 1: High-yield diagnosis sections (Discharge Diagnoses, Final Diagnoses, Assessment & Plan)
for sec in sections: 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) items = self._parse_diagnosis_items(sec.content, sec)
for item in items: for item in items:
self._register_candidate(candidates_by_key, item) self._register_candidate(candidates_by_key, item)
@@ -451,8 +451,12 @@ class EvidenceFirstFactExtractor:
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
# Skip absence statements and treatment instructions # Skip absence statements, treatment instructions, and cross-reference boilerplate
if HardClinicalCandidateGate.is_absence_statement(sent_clean) or HardClinicalCandidateGate.is_treatment_instruction(sent_clean): 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 continue
# Pattern 2: Explicit admission / diagnosis / condition clauses # Pattern 2: Explicit admission / diagnosis / condition clauses
@@ -463,6 +467,12 @@ class EvidenceFirstFactExtractor:
) )
if adm_match: if adm_match:
clause = adm_match.group(1).strip() 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"]: for tail_delim in [" on ", " treated with ", " managed with ", " secondary to ", " requiring ", " with good response", " with symptom"]:
if tail_delim in clause.lower(): if tail_delim in clause.lower():
idx = clause.lower().find(tail_delim) idx = clause.lower().find(tail_delim)
@@ -470,7 +480,7 @@ class EvidenceFirstFactExtractor:
# Causal admission: "initiation of chemotherapy for DLBCL" -> "DLBCL" # Causal admission: "initiation of chemotherapy for DLBCL" -> "DLBCL"
causal_m = re.search( 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, clause,
re.IGNORECASE, re.IGNORECASE,
) )
@@ -541,6 +551,14 @@ class EvidenceFirstFactExtractor:
lines = [line.strip() for line in content.split("\n") if line.strip()] lines = [line.strip() for line in content.split("\n") if line.strip()]
for line_idx, line in enumerate(lines): 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" # Strip list numbering e.g. "1. Acute right emphysematous pyelonephritis - underwent DJ stenting"
cleaned_line = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip() cleaned_line = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
# Strip structural role prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:") # Strip structural role prefixes (e.g., "Primary:", "Principal Diagnosis -", "Secondary:")
@@ -606,7 +624,10 @@ class EvidenceFirstFactExtractor:
if is_explicit_historical if is_explicit_historical
else ( else (
DiagnosisRole.PRIMARY 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 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 # Explicit PRINCIPAL_DIAGNOSIS gets highest base score (+15.0); DISCHARGE_DIAGNOSES gets +10.0; SECONDARY gets +3.0
if is_explicit_historical: if is_explicit_historical:
base_admitting = -50.0 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"): elif sec.section_name in ("PRINCIPAL_DIAGNOSIS", "PRIMARY_DIAGNOSIS"):
base_admitting = 15.0 if (line_idx == 0 and sub_idx == 0) else 5.0 base_admitting = 15.0 if (line_idx == 0 and sub_idx == 0) else 5.0
elif sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES"): elif sec.section_name in ("DISCHARGE_DIAGNOSES", "FINAL_DIAGNOSES"):
@@ -677,6 +700,10 @@ class EvidenceFirstFactExtractor:
if not cleaned: if not cleaned:
return [] 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) # 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()] sentences = [s.strip() for s in re.split(r"\.(?!\d)|[\n;]+", cleaned) if s.strip()]
for s in sentences: for s in sentences:
@@ -684,8 +711,14 @@ class EvidenceFirstFactExtractor:
continue continue
cond_term = s 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( 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, s,
re.IGNORECASE, re.IGNORECASE,
) )
@@ -1408,7 +1441,7 @@ class EvidenceFirstFactExtractor:
cand.treatment_relevance = 1.0 cand.treatment_relevance = 1.0
cand.encounter_relevance = 1.0 cand.encounter_relevance = 1.0
cand.scores.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.scores.admitting_score += (3.0 if is_from_principal_sec else 1.0)
cand.temporality = Temporality.CURRENT cand.temporality = Temporality.CURRENT
cand.assertion_status = AssertionStatus.CONFIRMED cand.assertion_status = AssertionStatus.CONFIRMED
+1 -1
View File
@@ -1233,7 +1233,7 @@ def _extract_conditions_deterministically(
primary_ev = cand.primary_evidence_quote primary_ev = cand.primary_evidence_quote
primary_sec = cand.evidence[0].section if cand.evidence else "DOCUMENTATION" 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) 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" sec_name = "PRINCIPAL_DIAGNOSIS"
elif any(ev.section in ("SECONDARY_DIAGNOSES", "ADDITIONAL_DIAGNOSES") for ev in cand.evidence): elif any(ev.section in ("SECONDARY_DIAGNOSES", "ADDITIONAL_DIAGNOSES") for ev in cand.evidence):
sec_name = "SECONDARY_DIAGNOSES" sec_name = "SECONDARY_DIAGNOSES"
+49 -19
View File
@@ -8,6 +8,14 @@ from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult
from medical_coding.schemas.validation import AbstentionRecord 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( def render_header(
offline_mode: bool = True, offline_mode: bool = True,
catalog_size: int = 25, 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>' catalog_pill = f'<span class="pill-badge badge-secondary">📚 {catalog_size} ICD Codes</span>'
st.markdown( header_html = clean_html(
f""" f"""
<div class="clinic-header"> <div class="clinic-header">
<div style="display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 12px;"> <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> </div>
</div> </div>
""", """
unsafe_allow_html=True,
) )
st.markdown(header_html, unsafe_allow_html=True)
def render_kpi_metrics(result: CodingResult) -> None: def render_kpi_metrics(result: CodingResult) -> None:
@@ -65,6 +73,7 @@ def render_kpi_metrics(result: CodingResult) -> None:
with c1: with c1:
st.markdown( st.markdown(
clean_html(
f""" f"""
<div class="kpi-card"> <div class="kpi-card">
<div class="kpi-label">Status</div> <div class="kpi-label">Status</div>
@@ -72,30 +81,35 @@ def render_kpi_metrics(result: CodingResult) -> None:
<span class="pill-badge {status_class}">{status_str}</span> <span class="pill-badge {status_class}">{status_str}</span>
</div> </div>
</div> </div>
""", """
),
unsafe_allow_html=True, unsafe_allow_html=True,
) )
with c2: with c2:
primary_code = result.primary_diagnosis.code if result.primary_diagnosis else "None" primary_code = result.primary_diagnosis.code if result.primary_diagnosis else "None"
st.markdown( st.markdown(
clean_html(
f""" f"""
<div class="kpi-card"> <div class="kpi-card">
<div class="kpi-label">Primary ICD-10</div> <div class="kpi-label">Primary ICD-10</div>
<div class="kpi-value" style="color: #38bdf8;">{primary_code}</div> <div class="kpi-value" style="color: #38bdf8;">{primary_code}</div>
</div> </div>
""", """
),
unsafe_allow_html=True, unsafe_allow_html=True,
) )
with c3: with c3:
st.markdown( st.markdown(
clean_html(
f""" f"""
<div class="kpi-card"> <div class="kpi-card">
<div class="kpi-label">Secondary Diags</div> <div class="kpi-label">Secondary Diags</div>
<div class="kpi-value">{len(result.secondary_diagnoses)}</div> <div class="kpi-value">{len(result.secondary_diagnoses)}</div>
</div> </div>
""", """
),
unsafe_allow_html=True, unsafe_allow_html=True,
) )
@@ -103,23 +117,27 @@ def render_kpi_metrics(result: CodingResult) -> None:
abst_count = len(result.abstentions) abst_count = len(result.abstentions)
abst_color = "#f87171" if abst_count > 0 else "#94a3b8" abst_color = "#f87171" if abst_count > 0 else "#94a3b8"
st.markdown( st.markdown(
clean_html(
f""" f"""
<div class="kpi-card"> <div class="kpi-card">
<div class="kpi-label">Abstentions</div> <div class="kpi-label">Abstentions</div>
<div class="kpi-value" style="color: {abst_color};">{abst_count}</div> <div class="kpi-value" style="color: {abst_color};">{abst_count}</div>
</div> </div>
""", """
),
unsafe_allow_html=True, unsafe_allow_html=True,
) )
with c5: with c5:
st.markdown( st.markdown(
clean_html(
f""" f"""
<div class="kpi-card"> <div class="kpi-card">
<div class="kpi-label">Processing Time</div> <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 class="kpi-value">{result.processing_time_ms:.1f}<span style="font-size: 13px; font-weight: normal; color: #94a3b8;"> ms</span></div>
</div> </div>
""", """
),
unsafe_allow_html=True, 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_pills.append(f'<span class="pill-badge badge-success">CPT: {primary.cpt}</span>')
codes_html = " ".join(codes_pills) 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""" f"""
<div class="primary-card"> <div class="primary-card">
<div class="primary-card-header"> <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> <span style="font-size: 13px; color: #94a3b8; display: block; margin-bottom: 2px;">📖 Matched Database Concept:</span>
{primary.description} {primary.description}
</div> </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;"> <div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
{acuity_badge} {acuity_badge}
{certainty_badge} {certainty_badge}
@@ -185,9 +207,9 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
<span class="evidence-quote">"{primary.evidence_quote}"</span> <span class="evidence-quote">"{primary.evidence_quote}"</span>
</div> </div>
</div> </div>
""", """
unsafe_allow_html=True,
) )
st.markdown(primary_html, unsafe_allow_html=True)
def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None: def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None:
@@ -219,15 +241,18 @@ 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_pills.append(f'<span class="pill-badge badge-success">CPT: {diag.cpt}</span>')
sec_codes_html = " ".join(sec_codes_pills) sec_codes_html = " ".join(sec_codes_pills)
with st.container(): documented_row = ""
st.markdown( 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""" f"""
<div class="secondary-card"> <div class="secondary-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; flex-wrap: wrap;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; flex-wrap: wrap;">
<div> <div>
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {sec_code_display}</strong> <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> <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 ''} {documented_row}
</div> </div>
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;"> <div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
{billable_badge} {billable_badge}
@@ -243,9 +268,10 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
<span class="evidence-quote">"{diag.evidence_quote}"</span> <span class="evidence-quote">"{diag.evidence_quote}"</span>
</div> </div>
</div> </div>
""", """
unsafe_allow_html=True,
) )
with st.container():
st.markdown(secondary_html, unsafe_allow_html=True)
def render_abstentions(abstentions: list[AbstentionRecord]) -> None: def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
@@ -261,6 +287,7 @@ def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
raw_term = abst.raw_term or "Unspecified Entity" raw_term = abst.raw_term or "Unspecified Entity"
st.markdown( st.markdown(
clean_html(
f""" f"""
<div class="abstention-card"> <div class="abstention-card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;"> <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px;">
@@ -270,7 +297,8 @@ def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
<div style="font-size: 13px; color: #e2e8f0;">{abst.detail}</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 style="font-size: 11px; color: #94a3b8; margin-top: 4px;">Enforced at stage: <code>{stage_str}</code></div>
</div> </div>
""", """
),
unsafe_allow_html=True, unsafe_allow_html=True,
) )
@@ -284,6 +312,7 @@ def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, second
all_codes.extend(secondaries) all_codes.extend(secondaries)
st.markdown( st.markdown(
clean_html(
""" """
<div class="audit-check-item"> <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. <span class="check-pass">✔</span> <strong>Catalog Existence Check:</strong> All assigned codes exist in the authoritative local ICD-10-CM dataset.
@@ -300,7 +329,8 @@ def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, second
<div class="audit-check-item"> <div class="audit-check-item">
<span class="check-pass">✔</span> <strong>Anti-Hallucination Bound:</strong> Codes were bounded exclusively to the retrieved candidate pool. <span class="check-pass">✔</span> <strong>Anti-Hallucination Bound:</strong> Codes were bounded exclusively to the retrieved candidate pool.
</div> </div>
""", """
),
unsafe_allow_html=True, unsafe_allow_html=True,
) )
+15 -2
View File
@@ -85,6 +85,13 @@ METADATA_PATTERNS = [
r"\babove\s+mentioned\s+complaints\b", r"\babove\s+mentioned\s+complaints\b",
r"\bfeared\s+health\s+complaint\b", r"\bfeared\s+health\s+complaint\b",
r"\bcomplaint\s+in\s+whom\s+no\s+diagnosis\s+is\s+made\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) # 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*(?: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*$", r"^\s*(?:no\s+known\s+(?:drug\s+)?allergies|nkda)\s*$",
@@ -220,8 +227,14 @@ class HardClinicalCandidateGate:
if re.search(pat, term_lower): if re.search(pat, term_lower):
return False, f"Section heading, metadata, allergy, or clinical status artifact: '{clean_term}'" return False, f"Section heading, metadata, allergy, or clinical status artifact: '{clean_term}'"
# Check 4b: Physical exam, vital signs, systemic examination noise # 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"]): 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}'" return False, f"Physical exam, vital sign, or administrative boilerplate artifact: '{clean_term}'"
# Check 5: Standalone tumor staging or genetic attributes # Check 5: Standalone tumor staging or genetic attributes
+55
View File
@@ -153,3 +153,58 @@ async def test_regression_oncology_and_pmh_comorbidities() -> None:
assert "Z71.1" not in sec_codes assert "Z71.1" not in sec_codes
assert len(res.secondary_diagnoses) == 2 assert len(res.secondary_diagnoses) == 2
@pytest.mark.asyncio
async def test_regression_primary_label_with_meta_reference_narrative() -> None:
"""Explicit PRIMARY label must win primary diagnosis; meta-references ('symptoms described in...') must be rejected."""
doc = """
HOSPITAL DISCHARGE SUMMARY
CHIEF COMPLAINT:
The patient presented with several days of the symptoms described in the final diagnosis.
FINAL DIAGNOSES:
PRIMARY: Acute right pyelonephritis with right renal calculus.
SECONDARY: Right renal calculus
"""
res = await process_clinical_document(source=doc, document_id="doc-reg-primary-meta")
assert res is not None
assert res.primary_diagnosis is not None
# Primary must be Acute pyelonephritis (N10), NOT meta-reference noise
assert res.primary_diagnosis.code == "N10"
assert "pyelonephritis" in res.primary_diagnosis.description.lower()
assert "symptoms described" not in res.primary_diagnosis.raw_term.lower()
# Meta-reference noise must never appear in secondary diagnoses
for sec in res.secondary_diagnoses:
assert "symptoms described" not in sec.raw_term.lower()
assert "symptoms described" not in (sec.description or "").lower()
# Right renal calculus must be secondary
sec_codes = {s.code for s in res.secondary_diagnoses}
assert "N20.0" in sec_codes
def test_clean_html_removes_indentation_and_prevents_code_blocks() -> None:
"""Verify that clean_html removes all leading whitespace from multi-line HTML."""
from medical_coding.ui.components import clean_html
sample_html = """
<div class="primary-card">
<div class="primary-desc">
<span>Database Concept:</span>
Acute pyelonephritis
</div>
<div style="display: flex; gap: 8px;">
<span class="pill-badge">ACUTE</span>
</div>
</div>
"""
cleaned = clean_html(sample_html)
for line in cleaned.splitlines():
# No line should start with 4 or more spaces (Markdown code block trigger)
assert not line.startswith(" "), f"Line starts with 4+ spaces: {line!r}"
assert not line.startswith("\t"), f"Line starts with tab: {line!r}"
assert cleaned.startswith('<div class="primary-card">')