fix(pipeline): implement comprehensive improvements across five key areas on noise-fix

- Area 1: Complete clinical inventory generation with compound concept decomposition (secondary to/due to), laterality preservation, and deduplication
- Area 2: First-class assertion, negation, entity typing, and CMS Guideline I.B.4 integral symptom suppression
- Area 3: Semantic code validation beyond database existence via reverse attribute matching and specificity downgrading
- Area 4: Strict UHDDS primary vs secondary role separation with complete deduplication and HTML escape rendering in Streamlit components
- Area 5: Exact clinical provenance preservation and 6-metric diagnostic scorecard with comprehensive regression tests
This commit is contained in:
Abhinav Gupta
2026-10-09 10:42:54 +05:30
parent 5d99f9b1a1
commit c161b09095
11 changed files with 742 additions and 180 deletions
@@ -245,7 +245,8 @@ class EvidenceFirstFactExtractor:
item.normalized_diagnosis = raw_t
canon = self._canonicalize_term(item.raw_term)
key = canon.lower().strip()
lat = item.clinical_attributes.get("laterality", "") if item.clinical_attributes else ""
key = f"{canon.lower().strip()}_{lat}".strip("_")
if not key or len(key) < 2:
return
@@ -254,6 +255,10 @@ class EvidenceFirstFactExtractor:
else:
existing = candidates_by_key[key]
existing.evidence.extend(item.evidence)
if item.role == DiagnosisRole.PRIMARY:
existing.role = DiagnosisRole.PRIMARY
if item.primary_justification:
existing.primary_justification = item.primary_justification
if item.temporality == Temporality.CURRENT:
existing.temporality = Temporality.CURRENT
if existing.role == DiagnosisRole.HISTORICAL:
@@ -473,7 +478,7 @@ class EvidenceFirstFactExtractor:
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 ", " requiring ", " with good response", " with symptom"]:
if tail_delim in clause.lower():
idx = clause.lower().find(tail_delim)
clause = clause[:idx].strip()
@@ -489,7 +494,7 @@ class EvidenceFirstFactExtractor:
if len(sub_cand) >= 3:
clause = sub_cand
sub_clauses = re.split(r"\s+and\s+|\s*,\s*", clause)
sub_clauses = self._split_compound_clinical_phrase(clause)
for sc in sub_clauses:
sc = sc.strip()
sc = re.sub(r"^(?:a|an|the)\s+", "", sc, flags=re.IGNORECASE).strip()
@@ -915,13 +920,13 @@ class EvidenceFirstFactExtractor:
for clause in matched_clauses:
# Strip trailing management phrases from clause
for tail in [" requiring ", " managed with ", " treated with ", " on ", " with good response", " secondary to ", " with symptom", " and was ", " and received "]:
for tail in [" requiring ", " managed with ", " treated with ", " on ", " with good response", " with symptom", " and was ", " and received "]:
if tail in clause.lower():
idx = clause.lower().find(tail)
clause = clause[:idx].strip()
# Split compound items e.g. "septic shock and diabetic ketoacidosis"
sub_items = re.split(r"\s+and\s+|\s*,\s*", clause)
# Split compound items e.g. "septic shock and diabetic ketoacidosis", "acute kidney injury secondary to dehydration"
sub_items = self._split_compound_clinical_phrase(clause)
for item_str in sub_items:
item_str = item_str.strip()
item_str = re.sub(r"^(?:a|an|the)\s+", "", item_str, flags=re.IGNORECASE).strip()
@@ -1577,10 +1582,50 @@ class EvidenceFirstFactExtractor:
top.primary_justification = f"Documented chief condition occasioning admission and inpatient treatment: {top.primary_evidence_quote}"
primary_diag = top
# Remaining become SECONDARY
# Remaining become SECONDARY, unless integral symptom or duplicate of primary
top_norm = top.normalized_diagnosis.lower()
top_words = set(re.findall(r"[a-z0-9]+", top_norm)) - {
"acute", "chronic", "right", "left", "bilateral", "unspecified", "severe", "mild", "stage", "with", "without"
}
for idx, sec_cand in enumerate(active_candidates):
if idx == chosen_idx:
continue
sec_norm = sec_cand.normalized_diagnosis.lower()
sec_words = set(re.findall(r"[a-z0-9]+", sec_norm)) - {
"acute", "chronic", "right", "left", "bilateral", "unspecified", "severe", "mild", "stage", "with", "without"
}
# Check 1: Duplicate / generalized mention of the primary diagnosis
if sec_words and top_words and (sec_words <= top_words or (len(sec_words & top_words) >= 2 and len(sec_words - top_words) == 0)):
sec_cand.role = DiagnosisRole.PRIMARY
sec_cand.is_authorized = False
sec_cand.classification_reason = f"Corroborating mention of primary diagnosis '{top.normalized_diagnosis}'"
top.evidence.extend(sec_cand.evidence)
continue
# Check 2: Integral symptom / sign of primary diagnosis (CMS Guideline I.B.4)
is_integral = any(
sym in sec_norm
for sym in [
"pain", "colic", "fever", "cough", "dyspnea", "shortness of breath",
"nausea", "vomiting", "dyspepsia", "indigestion", "heartburn",
"discomfort", "wheezing", "fatigue", "malaise", "respiratory distress",
"peripheral edema", "edema", "chest pain", "flank pain", "hematuria"
]
) and not (
any(sec_norm.endswith(sfx) or f"{sfx} " in sec_norm for sfx in ("itis", "oma", "osis"))
or any(dx in sec_norm for dx in ["syndrome", "failure", "infarction", "disease", "disorder", "calculus", "lithiasis", "ulcer", "pneumonia"])
)
if is_integral:
from medical_coding.schemas.enums import ClinicalEntityType
sec_cand.role = DiagnosisRole.SYMPTOM
sec_cand.entity_type = ClinicalEntityType.SYMPTOM
sec_cand.is_authorized = False
sec_cand.classification_reason = f"Symptom integral to the primary diagnosis '{top.normalized_diagnosis}'; excluded from independent billing under CMS Guideline I.B.4"
continue
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(
sec_cand.normalized_diagnosis, sec_cand.primary_evidence_quote
)
+18
View File
@@ -1155,6 +1155,24 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
primary_response.role = DiagnosisRole.PRIMARY
secondary_responses = [s for s in secondary_responses if s.code != "Z71.1"]
# Enforce clean role separation: secondary section must NEVER carry mentions of the primary diagnosis
if primary_response:
pri_code = primary_response.code
pri_words = set(re.findall(r"[a-z0-9]+", f"{(primary_response.description or '').lower()} {(primary_response.raw_term or '').lower()} {(primary_response.normalized_diagnosis or '').lower()}")) - {
"acute", "chronic", "with", "without", "and", "the", "for", "type", "stage", "unspecified", "right", "left", "bilateral"
}
filtered_sec = []
for s in secondary_responses:
if pri_code and s.code and s.code == pri_code:
continue
s_words = set(re.findall(r"[a-z0-9]+", f"{(s.description or '').lower()} {(s.raw_term or '').lower()} {(s.normalized_diagnosis or '').lower()}")) - {
"acute", "chronic", "with", "without", "and", "the", "for", "type", "stage", "unspecified", "right", "left", "bilateral"
}
if s_words and pri_words and (s_words <= pri_words or (len(s_words & pri_words) >= 2 and len(s_words - pri_words) <= 1)):
continue
filtered_sec.append(s)
secondary_responses = filtered_sec
# Determine execution status
if primary_response or secondary_responses:
status = ExecutionStatus.SUCCESS if not abstentions else ExecutionStatus.PARTIAL_SUCCESS
+5
View File
@@ -423,3 +423,8 @@ async def process_clinical_document_batch(
)
return batch_status
def process_clinical_document_sync(*args: Any, **kwargs: Any) -> CodingResult:
"""Synchronous execution wrapper for process_clinical_document."""
return asyncio.run(process_clinical_document(*args, **kwargs))
+43 -20
View File
@@ -212,7 +212,7 @@ def render_coding_session_results(
data=json_data,
file_name=f"{document_id}_coding_report.json",
mime="application/json",
use_container_width=True,
width="stretch",
key=f"dl_json_{thread_id}",
)
with d_col2:
@@ -249,7 +249,7 @@ def render_coding_session_results(
data=csv_df.to_csv(index=False),
file_name=f"{document_id}_summary.csv",
mime="text/csv",
use_container_width=True,
width="stretch",
key=f"dl_csv_{thread_id}",
)
@@ -336,11 +336,13 @@ with tab1:
st.rerun()
with p_col3:
if active_thread_id:
if st.button("✨ Reset Session", use_container_width=True, key="reset_active_thread_btn"):
if st.button("✨ Reset Session", width="stretch", key="reset_active_thread_btn"):
if "thread_id" in st.query_params:
del st.query_params["thread_id"]
if "active_thread_id" in st.session_state:
del st.session_state["active_thread_id"]
if "doc_id_override" in st.session_state:
del st.session_state["doc_id_override"]
st.rerun()
input_mode = st.radio(
@@ -353,12 +355,25 @@ with tab1:
horizontal=True,
)
default_doc_id = (
active_thread_record.get("document_id")
if active_thread_record
else f"ENC-{uuid4().hex[:8].upper()}"
)
document_id = st.text_input("Encounter Identifier (Document ID):", value=default_doc_id)
# Dynamic document ID determination to ensure unique provenance per case
if active_thread_record:
suggested_doc_id = active_thread_record.get("document_id", f"ENC-{uuid4().hex[:8].upper()}")
elif input_mode == "⚡ Interactive Demonstration Scenarios":
suggested_doc_id = st.session_state.get("active_demo_id", "ENC-HF-2026-001")
elif input_mode == "📁 Multimodal Document Ingestion (PDF / Image / TXT)":
suggested_doc_id = st.session_state.get("active_uploaded_doc_id", f"ENC-{uuid4().hex[:8].upper()}")
else:
suggested_doc_id = st.session_state.get("manual_doc_id", f"ENC-{uuid4().hex[:8].upper()}")
# Track active modality to reset input when switching
if st.session_state.get("last_input_mode") != input_mode:
st.session_state["last_input_mode"] = input_mode
st.session_state["doc_id_override"] = suggested_doc_id
doc_id_val = st.session_state.get("doc_id_override", suggested_doc_id)
document_id = st.text_input("Encounter Identifier (Document ID):", value=doc_id_val, key="encounter_doc_id_input")
st.session_state["doc_id_override"] = document_id
clinical_text = active_thread_record.get("raw_text", "") if active_thread_record else ""
active_file_bytes: bytes | None = None
active_filename = active_thread_record.get("input_source", "clinical_document.txt") if active_thread_record else "clinical_document.txt"
@@ -376,6 +391,11 @@ with tab1:
if uploaded_file is not None:
active_file_bytes = uploaded_file.getvalue()
active_filename = uploaded_file.name
derived_upload_id = f"ENC-{Path(uploaded_file.name).stem.upper().replace(' ', '_')}"
if st.session_state.get("active_uploaded_doc_id") != derived_upload_id:
st.session_state["active_uploaded_doc_id"] = derived_upload_id
st.session_state["doc_id_override"] = derived_upload_id
document_id = derived_upload_id
with st.spinner("🔍 Auto-detecting format and parsing clinical document..."):
ingest_result = ingestion_agent.ingest(
@@ -538,33 +558,36 @@ with tab1:
col_a, col_b, col_c = st.columns(3)
with col_a:
if st.button("📄 Ingest as Vector PDF", use_container_width=True):
if st.button("📄 Ingest as Vector PDF", width="stretch"):
pdf_bytes_gen = generate_sample_pdf(case_info["title"], case_info["text"])
st.session_state["active_demo_bytes"] = pdf_bytes_gen
st.session_state["active_demo_filename"] = f"{case_info['encounter_id']}.pdf"
st.session_state["active_demo_format"] = "pdf"
st.session_state["active_demo_text"] = case_info["text"]
st.session_state["active_demo_id"] = case_info["encounter_id"]
st.session_state["doc_id_override"] = case_info["encounter_id"]
st.success("Generated synthetic clinical PDF!")
with col_b:
if st.button("🖼️ Ingest as Screenshot (OCR)", use_container_width=True):
if st.button("🖼️ Ingest as Screenshot (OCR)", width="stretch"):
img_bytes_gen = generate_sample_image(case_info["title"], case_info["text"])
st.session_state["active_demo_bytes"] = img_bytes_gen
st.session_state["active_demo_filename"] = f"{case_info['encounter_id']}_screenshot.png"
st.session_state["active_demo_format"] = "image"
st.session_state["active_demo_text"] = case_info["text"]
st.session_state["active_demo_id"] = case_info["encounter_id"]
st.session_state["doc_id_override"] = case_info["encounter_id"]
st.success("Rendered clinical screenshot image for OCR parsing!")
with col_c:
if st.button("📝 Ingest as Plain Text (.txt)", use_container_width=True):
if st.button("📝 Ingest as Plain Text (.txt)", width="stretch"):
txt_bytes_gen = generate_sample_txt(case_info["title"], case_info["text"])
st.session_state["active_demo_bytes"] = txt_bytes_gen
st.session_state["active_demo_filename"] = f"{case_info['encounter_id']}.txt"
st.session_state["active_demo_format"] = "txt"
st.session_state["active_demo_text"] = case_info["text"]
st.session_state["active_demo_id"] = case_info["encounter_id"]
st.session_state["doc_id_override"] = case_info["encounter_id"]
st.success("Loaded as plain text document!")
if "active_demo_id" in st.session_state:
@@ -650,7 +673,7 @@ with tab1:
col_run, col_clear = st.columns([3, 1])
with col_run:
run_button = st.button("⚡ Run ICD-10 Medical Coding Pipeline", type="primary", use_container_width=True)
run_button = st.button("⚡ Run ICD-10 Medical Coding Pipeline", type="primary", width="stretch")
if run_button:
if not clinical_text and not active_file_bytes:
@@ -976,7 +999,7 @@ with tab3:
"Latency (ms)": f"{d['processing_time_ms']:.1f}",
"Date": d["created_at"][:19] if d["created_at"] else "N/A",
})
st.dataframe(pd.DataFrame(summary_rows), use_container_width=True)
st.dataframe(pd.DataFrame(summary_rows), width="stretch")
# Detailed Encounter Inspector Drawer
st.markdown("---")
@@ -1068,7 +1091,7 @@ with tab3:
data=full_df.to_csv(index=False),
file_name="encounters_vault_export.csv",
mime="text/csv",
use_container_width=True,
width="stretch",
)
with e_col2:
st.download_button(
@@ -1076,7 +1099,7 @@ with tab3:
data=json.dumps(stored_docs, indent=2),
file_name="encounters_vault_export.json",
mime="application/json",
use_container_width=True,
width="stretch",
)
with vault_tab2:
@@ -1148,7 +1171,7 @@ with tab3:
"Latency (ms)": f"{t['duration_ms']:.1f}",
"Start Time": t["start_time"][:19] if t["start_time"] else "N/A",
})
st.dataframe(pd.DataFrame(th_summary_rows), use_container_width=True)
st.dataframe(pd.DataFrame(th_summary_rows), width="stretch")
st.markdown("---")
st.markdown("##### 🔎 Inspect Execution Thread Timeline & Audit")
@@ -1168,13 +1191,13 @@ with tab3:
f"**Thread:** `{sel_thread['thread_id']}` | **Status:** `{sel_thread['status']}` | **Duration:** `{sel_thread['duration_ms']:.1f}ms`"
)
with c_act2:
if st.button("🚀 Load into Workspace (Tab 1)", key=f"load_ws_{selected_th_id}", use_container_width=True):
if st.button("🚀 Load into Workspace (Tab 1)", key=f"load_ws_{selected_th_id}", width="stretch"):
st.query_params["thread_id"] = selected_th_id
st.session_state["active_thread_id"] = selected_th_id
st.success(f"Thread {selected_th_id} loaded! Switch to Tab 1.")
st.rerun()
with c_act3:
if st.button("🗑️ Delete Thread", key=f"del_th_{selected_th_id}", use_container_width=True):
if st.button("🗑️ Delete Thread", key=f"del_th_{selected_th_id}", width="stretch"):
repo.delete_pipeline_thread(selected_th_id)
st.success(f"Thread {selected_th_id} deleted!")
st.rerun()
@@ -1323,4 +1346,4 @@ with tab5:
}
for r in all_records
])
st.dataframe(catalog_df, use_container_width=True)
st.dataframe(catalog_df, width="stretch")
+25 -18
View File
@@ -1,5 +1,6 @@
"""Modular presentation components for the medical coding Streamlit user interface."""
import html
from typing import Any
import streamlit as st
@@ -149,7 +150,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
st.info("ℹ️ No primary diagnosis assigned for this document (abstained or undetermined).")
return
code_display = primary.code or "[NO LOCAL CODE]"
code_display = html.escape(primary.code or "[NO LOCAL CODE]")
if primary.matching_status == "NO_DATABASE_MATCH" or not primary.code:
billable_badge = '<span class="pill-badge badge-warning">No Database Match</span>'
else:
@@ -158,23 +159,26 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
if primary.is_terminal_billable
else '<span class="pill-badge badge-danger">⚠ Non-Billable Header</span>'
)
acuity_badge = f'<span class="pill-badge badge-info">{primary.acuity.value if hasattr(primary.acuity, "value") else primary.acuity}</span>'
certainty_badge = f'<span class="pill-badge badge-secondary">{primary.certainty.value if hasattr(primary.certainty, "value") else primary.certainty}</span>'
acuity_badge = f'<span class="pill-badge badge-info">{html.escape(primary.acuity.value if hasattr(primary.acuity, "value") else str(primary.acuity))}</span>'
certainty_badge = f'<span class="pill-badge badge-secondary">{html.escape(primary.certainty.value if hasattr(primary.certainty, "value") else str(primary.certainty))}</span>'
conf_pct = int(primary.confidence_score * 100)
codes_pills = []
if primary.icd10cm:
codes_pills.append(f'<span class="pill-badge badge-info">ICD-10-CM: {primary.icd10cm}</span>')
codes_pills.append(f'<span class="pill-badge badge-info">ICD-10-CM: {html.escape(str(primary.icd10cm))}</span>')
if primary.icdo:
codes_pills.append(f'<span class="pill-badge badge-warning">ICD-O: {primary.icdo}</span>')
codes_pills.append(f'<span class="pill-badge badge-warning">ICD-O: {html.escape(str(primary.icdo))}</span>')
if primary.cpt:
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: {html.escape(str(primary.cpt))}</span>')
codes_html = " ".join(codes_pills)
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>'
documented_row = f'<div style="margin: 6px 0; font-size: 14px; color: #e2e8f0;">🩺 <strong style="color: #38bdf8;">Documented Clinical Diagnosis:</strong> {html.escape(str(primary.raw_term))}</div>'
safe_desc = html.escape(primary.description or "")
safe_evidence = html.escape(primary.evidence_quote or "")
primary_html = clean_html(
f"""
@@ -191,7 +195,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
</div>
<div class="primary-desc">
<span style="font-size: 13px; color: #94a3b8; display: block; margin-bottom: 2px;">📖 Matched Database Concept:</span>
{primary.description}
{safe_desc}
</div>
{documented_row}
<div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
@@ -204,7 +208,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
📄 Verbatim Clinical Evidence Quote:
</span><br/>
<span class="evidence-quote">"{primary.evidence_quote}"</span>
<span class="evidence-quote">"{safe_evidence}"</span>
</div>
</div>
"""
@@ -220,7 +224,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
return
for idx, diag in enumerate(secondaries, start=1):
sec_code_display = diag.code or "[NO LOCAL CODE]"
sec_code_display = html.escape(diag.code or "[NO LOCAL CODE]")
if diag.matching_status == "NO_DATABASE_MATCH" or not diag.code:
billable_badge = '<span class="pill-badge badge-warning">No Database Match</span>'
else:
@@ -229,21 +233,24 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
if diag.is_terminal_billable
else '<span class="pill-badge badge-danger">⚠ Non-Billable</span>'
)
acuity_str = diag.acuity.value if hasattr(diag.acuity, "value") else str(diag.acuity)
certainty_str = diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty)
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))
sec_codes_pills = []
if diag.icd10cm:
sec_codes_pills.append(f'<span class="pill-badge badge-info">ICD-10-CM: {diag.icd10cm}</span>')
sec_codes_pills.append(f'<span class="pill-badge badge-info">ICD-10-CM: {html.escape(str(diag.icd10cm))}</span>')
if diag.icdo:
sec_codes_pills.append(f'<span class="pill-badge badge-warning">ICD-O: {diag.icdo}</span>')
sec_codes_pills.append(f'<span class="pill-badge badge-warning">ICD-O: {html.escape(str(diag.icdo))}</span>')
if diag.cpt:
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: {html.escape(str(diag.cpt))}</span>')
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'<div style="margin-top: 4px; font-size: 13px; color: #cbd5e1;">🩺 <strong style="color: #38bdf8;">Documented Diagnosis:</strong> {diag.raw_term}</div>'
documented_row = f'<div style="margin-top: 4px; font-size: 13px; color: #cbd5e1;">🩺 <strong style="color: #38bdf8;">Documented Diagnosis:</strong> {html.escape(str(diag.raw_term))}</div>'
safe_desc = html.escape(diag.description or "")
safe_evidence = html.escape(diag.evidence_quote or "")
secondary_html = clean_html(
f"""
@@ -251,7 +258,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
<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>
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{safe_desc}</span>
{documented_row}
</div>
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
@@ -265,7 +272,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
<span style="font-weight: 600; color: #6ee7b7; font-size: 11px; text-transform: uppercase;">
Clinical Evidence:
</span>
<span class="evidence-quote">"{diag.evidence_quote}"</span>
<span class="evidence-quote">"{safe_evidence}"</span>
</div>
</div>
"""
+11 -3
View File
@@ -338,10 +338,18 @@ class HardClinicalCandidateGate:
if not words.intersection(PATHOLOGY_KEYWORDS):
return ClinicalEntityType.INVESTIGATION
# 10. Symptoms & Signs
if any(sym in term_lower for sym in ["pain", "cough", "nausea", "vomiting", "dyspnea", "shortness of breath", "fatigue", "malaise", "colic", "dizziness"]):
# 10. Organisms and Microbiological Findings
if any(org in term_lower for org in ["e. coli", "escherichia coli", "klebsiella", "pseudomonas", "staphylococcus", "streptococcus", "candida", "h. pylori", "helicobacter"]):
return ClinicalEntityType.CLINICAL_FINDING
# 10b. Laboratory Results & Abnormal Findings
if any(lab in term_lower for lab in ["leukocytosis", "thrombocytopenia", "elevated troponin", "elevated creatinine", "hypokalemia", "hyperkalemia", "hyponatremia", "acidosis", "alkalosis"]):
return ClinicalEntityType.LAB_RESULT
# 10c. Symptoms & Signs
if any(sym in term_lower for sym in ["pain", "cough", "nausea", "vomiting", "dyspnea", "shortness of breath", "fatigue", "malaise", "colic", "dizziness", "dyspepsia", "indigestion", "heartburn", "headache", "discomfort", "orthopnea", "hematuria"]):
return ClinicalEntityType.SYMPTOM
if any(sign in term_lower for sign in ["tachycardia", "tachypnea", "fever", "hypotension", "wheezing", "rales", "edema", "swelling"]):
if any(sign in term_lower for sign in ["tachycardia", "tachypnea", "fever", "hypotension", "wheezing", "rales", "edema", "swelling", "cyanosis", "jaundice", "pallor"]):
return ClinicalEntityType.SIGN
# 11. Neoplasms
@@ -104,6 +104,69 @@ class DeterministicValidator:
stage=PipelineStage.VALIDATION,
)
# 3. Semantic Code Attribute Validation (CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY)
ev_text = (
getattr(condition.context.evidence, "quote", "")
if hasattr(condition, "context") and hasattr(condition.context, "evidence") and condition.context.evidence
else ""
)
if selection.supporting_evidence:
ev_text = f"{ev_text} {' '.join(selection.supporting_evidence)}"
is_attr_valid, unsupp_attrs = ReverseAttributeChecker.validate_code_attributes(
code_description=candidate.description,
evidence_text=ev_text,
diagnosis_term=condition.raw_term,
)
if not is_attr_valid:
better_candidate = None
if selection.candidate_pool:
for alt_cand in selection.candidate_pool:
if not self.catalog.is_valid_code(alt_cand.code) or not self.catalog.is_billable_code(alt_cand.code):
continue
alt_valid, _ = ReverseAttributeChecker.validate_code_attributes(
code_description=alt_cand.description,
evidence_text=ev_text,
diagnosis_term=condition.raw_term,
)
if alt_valid:
better_candidate = alt_cand
break
if better_candidate:
candidate = better_candidate
code = better_candidate.code
checks.append(
ValidationCheck(
rule_name="SemanticAttributeMatch",
passed=True,
details=f"Realigned code to supported candidate '{code}' ({candidate.description}) without unsupported {', '.join(unsupp_attrs)}.",
)
)
else:
checks.append(
ValidationCheck(
rule_name="SemanticAttributeMatch",
passed=False,
details=f"Code '{code}' specifies unsupported attributes: {', '.join(unsupp_attrs)}.",
)
)
return None, AbstentionRecord(
diagnosis_id=condition.diagnosis_id,
raw_term=condition.raw_term,
reason=AbstentionReason.UNSUPPORTED_SPECIFICITY,
detail=f"Code '{code}' requires unsupported clinical attributes ({', '.join(unsupp_attrs)}) not evidenced in documentation.",
stage=PipelineStage.VALIDATION,
)
else:
checks.append(
ValidationCheck(
rule_name="SemanticAttributeMatch",
passed=True,
details=f"All clinical qualifiers in '{code}' ({candidate.description}) are supported by documentation.",
)
)
cand_sys = getattr(candidate, "coding_system", None) or "ICD-10-CM"
icd10cm_val = selection.selected_icd10cm or (code if cand_sys == "ICD-10-CM" else None)
icdo_val = selection.selected_icdo or (code if cand_sys == "ICD-O" else None)
@@ -125,21 +125,21 @@ def has_positive_mention(synonym: str, text: str) -> bool:
pattern = rf"\b{syn_esc}\b"
for match in re.finditer(pattern, text, re.IGNORECASE):
start = match.start()
lookback_start = max(0, start - 45)
lookback_start = max(0, start - 60)
preceding = text[lookback_start:start]
# Inspect after last punctuation if present
last_punct = max(preceding.rfind("."), preceding.rfind(";"), preceding.rfind(","))
if last_punct != -1:
preceding = preceding[last_punct + 1 :]
# Check if preceding snippet contains negation words
# Sentence boundaries stop negation scope, but commas in lists do not
sent_boundary = max(preceding.rfind("."), preceding.rfind(";"), preceding.rfind("\n"))
clause = preceding[sent_boundary + 1 :] if sent_boundary != -1 else preceding
# Check if preceding snippet or clause contains negation words
if re.search(
r"\b(?:no|not|without|denies|denied|negative\s+for|no\s+evidence\s+of|no\s+active|ruled\s+out|free\s+of)\b",
preceding,
clause,
re.IGNORECASE,
):
continue
if preceding.rstrip().endswith("non-") or preceding.rstrip().endswith("non"):
if clause.rstrip().endswith("non-") or clause.rstrip().endswith("non"):
continue
return True