fix(validation): implement prioritized surgical oncology repair plan and semantic code validation

- Fix UI crash NameError: name 'Path' is not defined in medical_coding.ui.app
- Item 1: Enforce semantic code validation first; reject laterality and anatomical site mismatches even if active and billable
- Item 2: Segregate surgical procedures from diagnosis inventory (mastectomy, salpingo-oophorectomy in procedures, blocked from secondary diagnoses)
- Item 3: Capture structured oncology context preserving histology, grade, ER/PR/HER2 receptors, Ki-67, and treatment response
- Item 4: Extract operative findings separately with UHDDS eligibility gate (incidental findings excluded from secondary diagnosis coding)
- Item 5: Ground audit claims in evidence-based semantic checks (LateralityMatch, AnatomicalSiteMatch, SemanticAttributeMatch)
- Item 6: Accelerate candidate retrieval latency via query-level caching in HybridICDRetriever
- Add UI presentation cards for procedures, structured oncology, operative findings, and enhanced audit trails
- Add comprehensive test suite in tests/test_surgical_oncology_repair.py
This commit is contained in:
Abhinav Gupta
2026-10-09 11:39:20 +05:30
parent c161b09095
commit 7885abf57d
12 changed files with 1006 additions and 48 deletions
+301 -3
View File
@@ -23,6 +23,7 @@ from medical_coding.schemas.enums import (
Temporality,
)
from medical_coding.schemas.evidence import (
CancerConcept,
ClinicalDiagnosisCandidate,
ClinicalDiagnosisState,
MultiDimensionalScore,
@@ -45,6 +46,8 @@ SECTION_PATTERNS: list[tuple[str, str]] = [
("HOSPITAL_COURSE", r"(?:HOSPITAL\s+COURSE|SUMMARY\s+OF\s+HOSPITAL\s+STAY|BRIEF\s+SUMMARY\s+OF\s+HOSPITAL\s+COURSE|COURSE\s+IN\s+(?:THE\s+)?HOSPITAL(?:\s+AND\s+DISCUSSION)?|CLINICAL\s+COURSE)"),
("COMPLICATIONS", r"(?:HOSPITAL\s+COMPLICATIONS|IN-?HOSPITAL\s+COMPLICATIONS|COMPLICATIONS|ADVERSE\s+EVENTS)"),
("PROCEDURES", r"(?:PROCEDURES\s+PERFORMED|OPERATIVE\s+PROCEDURES|SURGICAL\s+PROCEDURES|MAJOR\s+PROCEDURES|PROCEDURES)"),
("OPERATIVE_FINDINGS", r"(?:INTRAOPERATIVE\s+FINDINGS|OPERATIVE\s+FINDINGS|SURGICAL\s+FINDINGS|INTRA-?OPERATIVE\s+FINDINGS|OPERATIVE\s+NOTE\s+FINDINGS|FINDINGS)"),
("ONCOLOGY_BIOMARKERS", r"(?:BIOMARKERS\s*(?:&|AND)?\s*RECEPTOR\s+STATUS|PATHOLOGY(?:\s+REPORT)?|HISTOPATHOLOGY|RECEPTOR\s+STATUS|IMMUNOHISTOCHEMISTRY|TUMOR\s+CHARACTERISTICS)"),
("PAST_MEDICAL_HISTORY", r"(?:PAST\s+MEDICAL\s+HISTORY|PMH|MEDICAL\s+HISTORY|BACKGROUND\s+HISTORY|PAST\s+HISTORY|PERSONAL\s+HISTORY)"),
("PAST_SURGICAL_HISTORY", r"(?:PAST\s+SURGICAL\s+HISTORY|PSH|SURGICAL\s+HISTORY)"),
("INVESTIGATIONS", r"(?:RELEVANT\s+INVESTIGATIONS|INVESTIGATIONS|LABORATORY\s+DATA|PERTINENT\s+LABS|DIAGNOSTIC\s+STUDIES|IMAGING|RADIOLOGY|ECHOCARDIOGRAM|CT\s+SCAN|ULTRASOUND|MRI)"),
@@ -182,17 +185,25 @@ class SectionSegmenter:
class EvidenceFirstFactExtractor:
"""Extracts evidence-grounded clinical facts from partitioned document sections."""
def __init__(self) -> None:
self._extracted_procedures: list[str] = []
self._operative_findings: list[dict[str, Any]] = []
def extract_clinical_state(
self,
text: str,
document_id: str,
document_id: str = "doc-default",
doc_id: str | None = None,
) -> ClinicalDiagnosisState:
"""Extract all clinical diagnosis candidates, score them, and determine roles."""
effective_doc_id = doc_id or document_id
self._extracted_procedures = []
self._operative_findings = []
sections = SectionSegmenter.segment(text)
candidates = self._extract_candidates_from_sections(sections, text)
# Classify candidates using strict evidence hierarchy
state = self._classify_and_structure_state(candidates, sections, document_id)
state = self._classify_and_structure_state(candidates, sections, effective_doc_id)
return state
def _register_candidate(
@@ -220,6 +231,8 @@ class EvidenceFirstFactExtractor:
item.raw_term, item.primary_evidence_quote
)
if not is_valid:
if "procedure" in reject_reason.lower() or "surgical" in reject_reason.lower():
self._extracted_procedures.append(item.raw_term)
logger.debug("Candidate gate rejected '%s': %s", item.raw_term, reject_reason)
return
@@ -319,11 +332,24 @@ class EvidenceFirstFactExtractor:
# Phase 6: Procedures & Indications (Operative procedures, interventional indications)
for sec in sections:
if sec.section_name == "PROCEDURES":
if sec.section_name in ("PROCEDURES", "PAST_SURGICAL_HISTORY"):
proc_lines = [l.strip() for l in sec.content.split("\n") if l.strip()]
for l in proc_lines:
l_clean = re.sub(r"^\d+[\.\)\-]\s*", "", l).strip()
if len(l_clean) >= 3:
self._extracted_procedures.append(l_clean)
items = self._parse_procedure_indications(sec.content, sec)
for item in items:
self._register_candidate(candidates_by_key, item)
# Phase 6b: Operative Findings (Intraoperative observations, cysts, adhesions)
for sec in sections:
if sec.section_name == "OPERATIVE_FINDINGS":
op_findings, items = self._parse_operative_findings(sec.content, sec)
self._operative_findings.extend(op_findings)
for item in items:
self._register_candidate(candidates_by_key, item)
# Phase 7: General Narrative Sections (General, discharge summary narrative, HPI)
for sec in sections:
if sec.section_name in ("GENERAL", "DISCHARGE_SUMMARY", "HISTORY_OF_PRESENT_ILLNESS"):
@@ -610,6 +636,8 @@ class EvidenceFirstFactExtractor:
if polarity != NegationStatus.NEGATED:
is_valid_cand, gate_reason = HardClinicalCandidateGate.evaluate_candidate(sub_term, cleaned_line)
if not is_valid_cand:
if "procedure" in gate_reason.lower() or "surgical" in gate_reason.lower():
self._extracted_procedures.append(sub_term)
logger.info("Clinical gate rejected candidate in %s: '%s' (%s)", sec.section_name, sub_term, gate_reason)
continue
@@ -1172,6 +1200,239 @@ class EvidenceFirstFactExtractor:
return candidates
def _parse_operative_findings(
self,
content: str,
sec: ClinicalDocumentSection,
) -> tuple[list[dict[str, Any]], list[ClinicalDiagnosisCandidate]]:
"""Extract intraoperative findings with distinct clinical-coding eligibility gate."""
findings: list[dict[str, Any]] = []
candidates: list[ClinicalDiagnosisCandidate] = []
cleaned = content.strip()
if not cleaned:
return findings, candidates
lines = [line.strip() for line in cleaned.split("\n") if line.strip()]
for line in lines:
line_clean = re.sub(r"^\d+[\.\)\-]\s*", "", line).strip()
if len(line_clean) < 3 or HardClinicalCandidateGate.is_absence_statement(line_clean):
continue
# Identify finding entities (e.g. "ovarian cyst", "pelvic adhesions", "liver normal")
is_normal = any(w in line_clean.lower() for w in ["normal", "unremarkable", "intact", "no pathology", "no abnormalities", "clear"])
is_incidental = any(w in line_clean.lower() for w in ["incidental", "benign", "small", "simple", "minor", "asymptomatic"])
term = line_clean
for delim in [",", "-", "–", ":"]:
if delim in term:
term = term.split(delim)[0].strip()
term = re.sub(r"^(?:a|an|the)\s+", "", term, flags=re.IGNORECASE).strip()
finding_record = {
"term": term,
"quote": line,
"section": sec.section_name,
"is_normal": is_normal,
"is_incidental": is_incidental,
"requires_coding": not is_normal and not is_incidental,
}
findings.append(finding_record)
if is_normal:
continue
# Distinct clinical-coding eligibility gate:
# Under UHDDS criteria, incidental intraoperative findings without dedicated surgical intervention
# or postoperative therapy are excluded from billable coding.
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(term, line)
if not is_valid:
continue
polarity, certainty = self._assess_polarity_and_certainty(line)
ev = StructuredEvidence(
text=line,
section=sec.section_name,
sentence=line,
polarity=polarity,
certainty=certainty,
temporality=Temporality.CURRENT,
evidence_type=EvidenceType.PROCEDURE,
clinical_relevance=0.3 if is_incidental else 0.8,
)
scores = MultiDimensionalScore(
evidence_score=1.0,
diagnostic_certainty=1.0 if certainty == Certainty.CONFIRMED else 0.8,
encounter_relevance=0.3 if is_incidental else 0.8,
role_confidence=0.5,
admitting_score=1.0 if not is_incidental else -5.0,
)
cand = ClinicalDiagnosisCandidate(
raw_term=term,
normalized_diagnosis=term,
role=DiagnosisRole.SECONDARY if not is_incidental else DiagnosisRole.EXCLUDED,
certainty=certainty,
temporality=Temporality.CURRENT,
assertion_status=AssertionStatus.CONFIRMED,
evidence=[ev],
scores=scores,
is_authorized=not is_incidental and polarity != NegationStatus.NEGATED,
classification_reason=f"Operative finding in {sec.section_name}" if not is_incidental else f"Incidental operative finding in {sec.section_name}; excluded under UHDDS criteria",
)
candidates.append(cand)
return findings, candidates
@staticmethod
def _extract_structured_oncology_context(text: str) -> CancerConcept | None:
"""Capture structured oncology context: histology, grade, receptor status, Ki-67, metastatic sites, prior treatment, and response."""
text_lower = text.lower()
# Check if document describes neoplasm / malignancy
has_neoplasm = any(
w in text_lower
for w in [
"carcinoma", "cancer", "neoplasm", "malignancy", "tumor", "tumour",
"adenocarcinoma", "lymphoma", "sarcoma", "melanoma", "dcis"
]
)
if not has_neoplasm:
return None
# 1. Primary Site
primary_site = "breast" if "breast" in text_lower else "unknown"
if primary_site == "unknown":
for site in ["ovary", "ovarian", "colon", "lung", "prostate", "cervix", "uterus", "kidney"]:
if site in text_lower:
primary_site = site
break
# 2. Laterality of primary tumor
laterality = None
site_pat = primary_site if primary_site != "unknown" else r"(?:breast|ovary|lung|kidney)"
if re.search(rf"\bright\s+(?:\w+\s+)?{site_pat}\b|\b{site_pat}\b[^\n,.]*?\bright\b", text_lower):
laterality = "right"
elif re.search(rf"\bleft\s+(?:\w+\s+)?{site_pat}\b|\b{site_pat}\b[^\n,.]*?\bleft\b", text_lower):
laterality = "left"
elif re.search(rf"\bbilateral\s+(?:\w+\s+)?{site_pat}\b|\b{site_pat}\b[^\n,.]*?\bbilateral\b", text_lower):
laterality = "bilateral"
elif "right" in text_lower and "left" not in text_lower:
laterality = "right"
elif "left" in text_lower and "right" not in text_lower:
laterality = "left"
elif "bilateral" in text_lower:
laterality = "bilateral"
# 3. Histology
histology = None
for hist_pat in [
r"\binvasive\s+ductal\s+carcinoma\b",
r"\binfiltrating\s+ductal\s+carcinoma\b",
r"\binvasive\s+lobular\s+carcinoma\b",
r"\bductal\s+carcinoma\s+in\s+situ\b",
r"\bdcis\b",
r"\bhigh[- ]grade\s+serous\s+carcinoma\b",
r"\bserous\s+carcinoma\b",
r"\badenocarcinoma\b",
r"\bsquamous\s+cell\s+carcinoma\b",
]:
m = re.search(hist_pat, text_lower)
if m:
histology = m.group(0).title()
break
# 4. Grade
grade = None
grade_m = re.search(r"\b(?:grade\s*([1-3]|i{1,3})|poorly\s+differentiated|moderately\s+differentiated|well\s+differentiated)\b", text_lower)
if grade_m:
grade = grade_m.group(0).capitalize()
# 5. Receptor Status (ER, PR, HER2)
receptor_status: dict[str, str] = {}
er_m = re.search(r"\ber\s*(?:[:=]|\s+is|\s+was)?\s*([><=]?\s*\d+%\s*(?:positive|\+)|positive|\+|negative|\-|equivocal|[><=]?\s*\d+%)", text, re.IGNORECASE)
if er_m:
v = er_m.group(1).lower().strip()
receptor_status["ER"] = "positive" if "+" in v or "pos" in v else "negative" if "-" in v or "neg" in v else v
receptor_status["er"] = receptor_status["ER"]
pr_m = re.search(r"\bpr\s*(?:[:=]|\s+is|\s+was)?\s*([><=]?\s*\d+%\s*(?:positive|\+)|positive|\+|negative|\-|equivocal|[><=]?\s*\d+%)", text, re.IGNORECASE)
if pr_m:
v = pr_m.group(1).lower().strip()
receptor_status["PR"] = "positive" if "+" in v or "pos" in v else "negative" if "-" in v or "neg" in v else v
receptor_status["pr"] = receptor_status["PR"]
her2_m = re.search(r"\bher2(?:\s*/\s*neu)?\s*(?:[:=]|\s+is|\s+was)?\s*(positive|\+|negative|\-|equivocal|[0-3]\+?)\b", text, re.IGNORECASE)
if her2_m:
v = her2_m.group(1).lower().strip()
receptor_status["HER2"] = v
receptor_status["her2"] = v
# 6. Ki-67 Proliferation Index
ki67 = None
ki67_m = re.search(
r"\bki-?67(?:\s+(?:proliferation\s+index|labeling\s+index|index))?\s*(?:[:=]|\s+is|\s+was)?\s*([><=]?\s*\d+%(?:\s*(?:high|low))?|high|low)",
text,
re.IGNORECASE,
)
if ki67_m:
ki67 = ki67_m.group(1).strip()
# 7. Metastatic Status & Sites
met_sites: list[str] = []
if re.search(r"\bno\s+(?:evidence\s+of\s+)?(?:distant\s+)?metastases\b|\bnon[- ]metastatic\b|\bm0\b", text_lower):
met_status = "NON_METASTATIC"
elif re.search(r"\bmetastat(?:ic|es)\b|\bm1\b", text_lower):
met_status = "METASTATIC"
for site in ["bone", "liver", "lung", "brain", "pleura", "peritoneum", "adrenal", "lymph node"]:
if site in text_lower:
met_sites.append(site)
else:
met_status = "UNKNOWN"
# 8. Prior Treatments
prior_tx: list[str] = []
for tx_pat in [
r"\bneoadjuvant\s+chemotherapy\b",
r"\badjuvant\s+chemotherapy\b",
r"\bradiotherapy\b|\bradiation\b",
r"\btamoxifen\b",
r"\bletrozole\b",
r"\banastrozole\b",
r"\btrastuzumab\b|\bherceptin\b",
]:
if re.search(tx_pat, text_lower):
prior_tx.append(re.search(tx_pat, text_lower).group(0))
# 9. Response to Treatment
resp = None
for resp_pat in [
r"\bpathologic(?:al)?\s+complete\s+response\b|\bpcr\b",
r"\bcomplete\s+(?:pathologic(?:al)?\s+|clinical\s+)?response\b",
r"\bpartial\s+(?:pathologic(?:al)?\s+|clinical\s+)?response\b",
r"\bstable\s+disease\b",
r"\bprogressive\s+disease\b",
r"\bresidual\s+(?:invasive\s+)?(?:disease|carcinoma)\b",
r"\bno\s+residual\s+invasive\s+disease\b",
]:
m = re.search(resp_pat, text_lower)
if m:
resp = m.group(0).title()
break
return CancerConcept(
primary_site=primary_site,
laterality=laterality,
malignancy_type="carcinoma",
histology=histology,
grade=grade,
metastatic_status=met_status,
metastatic_sites=met_sites,
receptor_status=receptor_status,
ki67=ki67,
treatment_response=resp,
prior_treatments=prior_tx,
evidence=text[:200],
)
def _split_compound_clinical_phrase(self, phrase: str) -> list[str]:
"""Split compound clinical phrases into independent clinical concepts.
@@ -1626,6 +1887,22 @@ class EvidenceFirstFactExtractor:
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
# Check 3: Intraoperative finding without dedicated surgical or therapeutic intervention
if any(ev.section == "OPERATIVE_FINDINGS" for ev in sec_cand.evidence) or sec_cand.role == DiagnosisRole.EXCLUDED:
full_content_lower = " ".join(s.content for s in sections).lower()
has_intervention = any(
w in full_content_lower
for w in ["cystectomy", "extensive adhesiolysis", "surgical excision of cyst", "pathology confirmed malignancy"]
)
if not has_intervention:
sec_cand.role = DiagnosisRole.EXCLUDED
sec_cand.is_authorized = False
sec_cand.classification_reason = (
f"[OPERATIVE_FINDINGS] Incidental finding '{sec_cand.normalized_diagnosis}' without documented "
"dedicated inpatient intervention or therapy; excluded from billable coding under UHDDS criteria."
)
continue
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(
sec_cand.normalized_diagnosis, sec_cand.primary_evidence_quote
)
@@ -1634,6 +1911,24 @@ class EvidenceFirstFactExtractor:
sec_cand.classification_reason = f"Active co-existing condition managed during admission: {sec_cand.primary_evidence_quote}"
secondary_diags.append(sec_cand)
# Extract structured oncology context across entire document narrative
full_doc_text = " ".join(s.content for s in sections)
oncology_context = self._extract_structured_oncology_context(full_doc_text)
if oncology_context and primary_diag:
primary_diag.clinical_attributes["oncology_context"] = oncology_context.model_dump()
if oncology_context.histology:
primary_diag.clinical_attributes["histology"] = oncology_context.histology
if oncology_context.grade:
primary_diag.clinical_attributes["grade"] = oncology_context.grade
if oncology_context.receptor_status:
primary_diag.clinical_attributes["receptor_status"] = oncology_context.receptor_status
if oncology_context.ki67:
primary_diag.clinical_attributes["ki67"] = oncology_context.ki67
if oncology_context.treatment_response:
primary_diag.clinical_attributes["treatment_response"] = oncology_context.treatment_response
if oncology_context.prior_treatments:
primary_diag.clinical_attributes["prior_treatments"] = oncology_context.prior_treatments
return ClinicalDiagnosisState(
document_id=document_id,
primary_diagnosis=primary_diag,
@@ -1643,5 +1938,8 @@ class EvidenceFirstFactExtractor:
uncertain_conditions=uncertain_conditions,
all_candidates=candidates,
has_unique_primary=primary_diag is not None,
procedures=list(dict.fromkeys(self._extracted_procedures)),
operative_findings=self._operative_findings,
oncology_context=oncology_context,
audit_notes=[f"Classified {len(candidates)} total entities: 1 Primary, {len(secondary_diags)} Secondary, {len(historical_conditions)} Historical, {len(ruled_out_conditions)} Ruled out."],
)
+8
View File
@@ -418,6 +418,8 @@ def extract_diagnoses_node(state: PipelineGraphState) -> dict[str, Any]:
"extracted_diagnoses": legacy_extracted,
"clinical_diagnosis_state": clinical_diag_state,
"diagnosis_candidates": clinical_diag_state.all_candidates if clinical_diag_state else [],
"extracted_procedures": getattr(clinical_diag_state, "procedures", []) if clinical_diag_state else [],
"operative_findings": getattr(clinical_diag_state, "operative_findings", []) if clinical_diag_state else [],
"current_stage": PipelineStage.EXTRACTION,
}
except Exception as e:
@@ -1209,6 +1211,9 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
primary_diagnosis=primary_response,
secondary_diagnoses=secondary_responses,
abstentions=abstentions,
procedures=state.get("extracted_procedures", []) or (getattr(diag_state, "procedures", []) if diag_state else []),
operative_findings=state.get("operative_findings", []) or (getattr(diag_state, "operative_findings", []) if diag_state else []),
oncology_context=diag_state.oncology_context.model_dump() if diag_state and getattr(diag_state, "oncology_context", None) else None,
excluded_candidates=excluded_candidates,
validation={
"evidence_grounded": True,
@@ -1225,6 +1230,9 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
"audit_trail": audit_trail,
"validated_code_count": len(validated),
"abstention_count": len(abstentions),
"extracted_procedures": state.get("extracted_procedures", []) or (getattr(diag_state, "procedures", []) if diag_state else []),
"operative_findings": state.get("operative_findings", []) or (getattr(diag_state, "operative_findings", []) if diag_state else []),
"oncology_context": diag_state.oncology_context.model_dump() if diag_state and getattr(diag_state, "oncology_context", None) else None,
},
)
+12
View File
@@ -50,6 +50,7 @@ class HybridICDRetriever(BaseICDRetriever):
self.min_score_threshold = min_score_threshold
self.default_top_k = default_top_k
self._query_cache: dict[tuple[str, int, float, str | None], list[ICDCandidate]] = {}
def retrieve(
self,
@@ -77,6 +78,11 @@ class HybridICDRetriever(BaseICDRetriever):
if not clean_query:
return []
# Check in-memory query cache for instant sub-millisecond retrieval
cache_key = (clean_query.lower(), k, threshold, system)
if hasattr(self, "_query_cache") and cache_key in self._query_cache:
return [c.model_copy() for c in self._query_cache[cache_key]]
# Retrieve candidates from both local engines with an expanded initial window
search_window = max(k * 10, 350)
lexical_hits = self.lexical_retriever.retrieve(clean_query, top_k=search_window)
@@ -187,6 +193,12 @@ class HybridICDRetriever(BaseICDRetriever):
threshold,
clean_query,
)
if hasattr(self, "_query_cache"):
if len(self._query_cache) >= 1000:
self._query_cache.clear()
self._query_cache[cache_key] = [c.model_copy() for c in top_candidates]
return top_candidates
def retrieve_multi_system(
+20
View File
@@ -259,6 +259,18 @@ class ClinicalDiagnosisState(BaseModel):
uncertain_conditions: list[ClinicalDiagnosisCandidate] = Field(default_factory=list)
all_candidates: list[ClinicalDiagnosisCandidate] = Field(default_factory=list)
has_unique_primary: bool = False
procedures: list[str] = Field(
default_factory=list,
description="Extracted surgical and clinical procedures segregated from diagnoses.",
)
operative_findings: list[dict[str, Any]] = Field(
default_factory=list,
description="Extracted operative/intraoperative findings evaluated under distinct clinical eligibility gate.",
)
oncology_context: Any | None = Field(
default=None,
description="Structured oncology context including histology, grade, receptors, Ki-67, and response.",
)
audit_notes: list[str] = Field(default_factory=list)
@@ -313,10 +325,18 @@ class CancerConcept(BaseModel):
metastatic_sites: list[str] = Field(default_factory=list, description="Verified metastatic anatomical sites.")
receptor_status: dict[str, str] = Field(default_factory=dict, description="e.g. {'ER': 'negative', 'PR': 'negative', 'HER2': '0', 'PD-L1': 'positive'}.")
molecular_attributes: list[str] = Field(default_factory=list, description="e.g. ['BRCA pathogenic', 'BRCA1 positive'].")
ki67: str | None = Field(default=None, description="Ki-67 proliferation index (e.g. '> 80%', 'low', 'high').")
treatment_response: str | None = Field(default=None, description="Pathologic or clinical response to neoadjuvant/adjuvant therapy.")
prior_treatments: list[str] = Field(default_factory=list, description="Prior treatments (e.g. neoadjuvant chemotherapy, endocrine therapy).")
treatment_history: list[str] = Field(default_factory=list, description="Past chemotherapy/radiotherapy/surgery.")
current_treatment: list[str] = Field(default_factory=list, description="Current inpatient chemotherapy or management.")
evidence: str = Field(default="", description="Verbatim documentary evidence.")
@property
def receptors(self) -> dict[str, str]:
"""Convenience property alias for receptor_status."""
return self.receptor_status
class OrthopedicConcept(BaseModel):
"""Structured orthopedic fracture and ligament concept separating anatomical attributes from disease entity."""
+12
View File
@@ -128,6 +128,18 @@ class CodingResult(BaseModel):
default_factory=list,
description="Audit records for all conditions where coding was abstained.",
)
procedures: list[str] = Field(
default_factory=list,
description="Extracted procedural and surgical events segregated from diagnoses.",
)
operative_findings: list[dict[str, Any]] = Field(
default_factory=list,
description="Operative and intraoperative findings evaluated under distinct clinical gate.",
)
oncology_context: dict[str, Any] | None = Field(
default=None,
description="Structured oncology biomarkers and tumor biology attributes.",
)
processing_time_ms: float = Field(
ge=0.0,
description="Total end-to-end execution latency in milliseconds.",
+2
View File
@@ -61,6 +61,8 @@ class PipelineGraphState(TypedDict, total=False):
# Clinical Extraction & Context Analysis (Evidence-First Architecture)
clinical_diagnosis_state: ClinicalDiagnosisState | None
diagnosis_candidates: list[ClinicalDiagnosisCandidate]
extracted_procedures: list[str]
operative_findings: list[dict[str, Any]]
icd_mapping_states: list[ICDMappingState]
# Legacy attributes preserved for backwards compatibility
+17 -1
View File
@@ -3,6 +3,7 @@
import asyncio
import json
from datetime import datetime
from pathlib import Path
from typing import Any
from uuid import uuid4
@@ -25,8 +26,11 @@ from medical_coding.ui.components import (
render_failure_alert,
render_header,
render_kpi_metrics,
render_oncology_context,
render_operative_findings,
render_pdf_page_inspector,
render_primary_diagnosis,
render_procedures,
render_process_oversight_timeline,
render_secondary_diagnoses,
render_validation_audit_trail,
@@ -189,14 +193,26 @@ def render_coding_session_results(
# Primary Diagnosis
render_primary_diagnosis(coding_result.primary_diagnosis)
# Structured Oncology & Biomarker Context (if present)
if coding_result.oncology_context:
render_oncology_context(coding_result.oncology_context)
# Procedural & Surgical Interventions (segregated from secondary diagnoses)
if coding_result.procedures:
render_procedures(coding_result.procedures)
# Secondary Diagnoses
render_secondary_diagnoses(coding_result.secondary_diagnoses)
# Operative Findings & Incidental Observations (evaluated under UHDDS gate)
if coding_result.operative_findings:
render_operative_findings(coding_result.operative_findings)
# Explicit Abstentions & Rule-Outs
render_abstentions(coding_result.abstentions)
# Deterministic Rule Audit Trail
render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses)
render_validation_audit_trail(coding_result.primary_diagnosis, coding_result.secondary_diagnoses, coding_result.validation)
# Structured JSON Response Payload
with st.expander("🔍 View Structured JSON Response Payload", expanded=False):
+182 -12
View File
@@ -310,22 +310,195 @@ def render_abstentions(abstentions: list[AbstentionRecord]) -> None:
)
def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, secondaries: list[CodedDiagnosisResponse]) -> None:
"""Render deterministic non-LLM validation rule checks."""
with st.expander("🛡️ Deterministic Non-LLM Invariants & Rule Audit", expanded=False):
all_codes = []
if primary:
all_codes.append(primary)
all_codes.extend(secondaries)
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):
proc_items_html.append(
f"""
<div class="procedure-item" style="background: rgba(147, 51, 234, 0.08); border: 1px solid rgba(168, 85, 247, 0.3); border-radius: 8px; padding: 10px 14px; margin-bottom: 8px; display: flex; justify-content: space-between; align-items: center;">
<div>
<span style="font-weight: 700; color: #c084fc; margin-right: 8px;">#{idx}.</span>
<strong style="color: #f3e8ff; font-size: 14px;">{html.escape(proc)}</strong>
</div>
<span class="pill-badge badge-info" style="border-color: rgba(168, 85, 247, 0.5); color: #d8b4fe;">Surgical / Interventional</span>
</div>
"""
)
st.markdown(
clean_html(
f"""
<div class="procedure-card" style="background: #141728; border: 1.5px solid rgba(168, 85, 247, 0.4); border-radius: 12px; padding: 16px; margin: 14px 0;">
{"".join(proc_items_html)}
<div style="font-size: 11px; color: #a855f7; margin-top: 6px;">
🔒 <strong>Coding Invariant:</strong> Procedural interventions are strictly routed to procedure data and blocked from polluting secondary diagnosis code inventories.
</div>
</div>
"""
),
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'<span style="background: rgba(15, 23, 42, 0.8); border: 1px solid #334155; border-radius: 6px; padding: 4px 10px; margin-right: 8px; font-size: 13px;">'
f'<strong style="color: #94a3b8;">{html.escape(r_name.upper())}:</strong> <span style="color: {r_color}; font-weight: 600;">{html.escape(str(r_val))}</span>'
f'</span>'
)
receptors_html = "".join(rec_pills) if rec_pills else '<span style="color: #94a3b8; font-size: 13px;">No receptor panel documented</span>'
# Metastatic sites
if metastatic_status:
sites_str = ", ".join(metastatic_sites) if metastatic_sites else "Present (unspecified site)"
meta_badge = f'<span class="pill-badge badge-danger">Metastatic: {html.escape(sites_str)}</span>'
else:
meta_badge = '<span class="pill-badge badge-success">No Distant Metastases Documented</span>'
# Prior treatments & response
tx_str = ", ".join(prior_treatments) if prior_treatments else "None documented"
oncology_html = clean_html(
f"""
<div style="background: #0d221c; border: 1.5px solid rgba(16, 185, 129, 0.4); border-radius: 12px; padding: 16px; margin: 12px 0;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px; border-bottom: 1px solid rgba(16, 185, 129, 0.2); padding-bottom: 8px;">
<strong style="color: #34d399; font-size: 15px;">🔬 Tumor Biology & Biomarker Profile</strong>
<div>{meta_badge}</div>
</div>
<div style="margin-bottom: 12px;">
<span style="font-size: 12px; color: #94a3b8; display: block; margin-bottom: 4px; text-transform: uppercase; font-weight: 600;">Receptor Panel & Biomarkers:</span>
<div style="display: flex; flex-wrap: wrap; gap: 6px;">{receptors_html}</div>
</div>
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 12px; margin-top: 8px; font-size: 13px; color: #e2e8f0;">
<div>
<span style="color: #94a3b8;">Prior Treatment:</span> <strong style="color: #f1f5f9;">{html.escape(tx_str)}</strong>
</div>
<div>
<span style="color: #94a3b8;">Treatment Response:</span> <strong style="color: #6ee7b7;">{html.escape(treatment_response)}</strong>
</div>
</div>
</div>
"""
)
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 = (
'<span class="pill-badge badge-danger">Excluded from Billing (Incidental / Unmanaged)</span>'
if is_incidental
else '<span class="pill-badge badge-success">Eligible (Dedicated Surgical Intervention)</span>'
)
rows_html.append(
f"""
<div style="background: #111e33; border: 1px solid #233857; border-radius: 8px; padding: 12px 14px; margin-bottom: 8px;">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px;">
<strong style="color: #60a5fa; font-size: 14px;">{html.escape(term)}</strong>
{eligibility_badge}
</div>
<div style="font-size: 12px; color: #94a3b8;">
Section: <code>{html.escape(sec)}</code>
</div>
<div style="font-size: 13px; color: #cbd5e1; margin-top: 4px; font-style: italic;">
"{html.escape(quote)}"
</div>
</div>
"""
)
st.markdown(
clean_html(
f"""
<div style="background: #091322; border: 1px solid #1e3a5f; border-radius: 12px; padding: 16px; margin: 12px 0;">
{"".join(rows_html)}
</div>
"""
),
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(
"""
<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>Laterality Congruence Check:</strong> Verified that code laterality matches documented laterality (left/right/bilateral); contradictory codes rejected even if billable.
</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).
<span class="check-pass">✔</span> <strong>Anatomical Site & Subsite Match:</strong> Verified organ group and quadrant congruence (e.g. breast quadrant, femur vs bone); anatomical mismatches strictly rejected.
</div>
<div class="audit-check-item">
<span class="check-pass">✔</span> <strong>Procedure vs Diagnosis Segregation:</strong> Verified that surgical procedures (mastectomy, salpingo-oophorectomy, etc.) are excluded from secondary diagnosis candidate inventory.
</div>
<div class="audit-check-item">
<span class="check-pass">✔</span> <strong>UHDDS Operative Finding Gate:</strong> Verified that incidental intraoperative observations without dedicated surgical intervention or post-op therapy are excluded from billing.
</div>
<div class="audit-check-item">
<span class="check-pass">✔</span> <strong>Catalog Existence & Billable Specificity:</strong> Verified that all assigned codes exist in the authoritative dataset as terminal leaf codes.
</div>
<div class="audit-check-item">
<span class="check-pass">✔</span> <strong>Single-Primary Invariant:</strong> Maximum of exactly 1 primary admission diagnosis enforced.
@@ -333,9 +506,6 @@ def render_validation_audit_trail(primary: CodedDiagnosisResponse | None, second
<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,
@@ -147,6 +147,10 @@ PROCEDURE_TERMS = {
"cholecystectomy", "appendectomy", "hysterectomy", "lumpectomy", "angioplasty",
"bypass", "dialysis", "hemodialysis", "paracentesis", "thoracentesis", "fet",
"frozen embryo transfer", "infusion", "chemotherapy", "radiotherapy", "radiation",
"salpingo-oophorectomy", "salpingooophorectomy", "oophorectomy", "salpingectomy",
"lymphadenectomy", "axillary dissection", "lymph node dissection",
"sentinel node biopsy", "sentinel lymph node biopsy", "cystectomy",
"adhesiolysis", "lysis of adhesions", "ablation", "cauterization",
}
PROCEDURE_SUFFIXES = (
+71 -27
View File
@@ -104,7 +104,7 @@ class DeterministicValidator:
stage=PipelineStage.VALIDATION,
)
# 3. Semantic Code Attribute Validation (CODE_SPECIFICITY <= EVIDENCE_SPECIFICITY)
# 3. Clinical Meaning & Anatomical Consistency Checks
ev_text = (
getattr(condition.context.evidence, "quote", "")
if hasattr(condition, "context") and hasattr(condition.context, "evidence") and condition.context.evidence
@@ -113,59 +113,103 @@ class DeterministicValidator:
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:
def _evaluate_candidate_clinical_meaning(cand: ICDCandidate) -> tuple[bool, str | None, bool, str | None, bool, list[str]]:
anat_ok, anat_err = ReverseAttributeChecker.validate_anatomical_site(
code_description=cand.description,
evidence_text=ev_text,
diagnosis_term=condition.raw_term,
)
lat_ok, lat_err = ReverseAttributeChecker.validate_laterality(
code_description=cand.description,
evidence_text=ev_text,
diagnosis_term=condition.raw_term,
)
attr_ok, attr_errs = ReverseAttributeChecker.validate_code_attributes(
code_description=cand.description,
evidence_text=ev_text,
diagnosis_term=condition.raw_term,
)
return anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs
anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs = _evaluate_candidate_clinical_meaning(candidate)
is_clinically_valid = anat_ok and lat_ok and attr_ok
if not is_clinically_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:
a_ok, _, l_ok, _, at_ok, _ = _evaluate_candidate_clinical_meaning(alt_cand)
if a_ok and l_ok and at_ok:
better_candidate = alt_cand
break
if better_candidate:
candidate = better_candidate
code = better_candidate.code
anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs = _evaluate_candidate_clinical_meaning(candidate)
else:
failure_reasons = []
if not anat_ok and anat_err:
failure_reasons.append(anat_err)
if not lat_ok and lat_err:
failure_reasons.append(lat_err)
if not attr_ok and attr_errs:
failure_reasons.extend(attr_errs)
fail_summary = "; ".join(failure_reasons) or "clinical meaning mismatch"
checks.append(
ValidationCheck(
rule_name="SemanticAttributeMatch",
passed=True,
details=f"Realigned code to supported candidate '{code}' ({candidate.description}) without unsupported {', '.join(unsupp_attrs)}.",
rule_name="AnatomicalSiteMatch",
passed=anat_ok,
details=f"Anatomical site confirmed in documentation: '{ev_text[:80]}'" if anat_ok else f"Failed: {anat_err}",
)
)
checks.append(
ValidationCheck(
rule_name="LateralityMatch",
passed=lat_ok,
details="Laterality supported by documentation." if lat_ok else f"Failed: {lat_err}",
)
)
else:
checks.append(
ValidationCheck(
rule_name="SemanticAttributeMatch",
passed=False,
details=f"Code '{code}' specifies unsupported attributes: {', '.join(unsupp_attrs)}.",
passed=attr_ok,
details="All clinical qualifiers supported." if attr_ok else f"Failed: unsupported {', '.join(attr_errs)}",
)
)
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.",
detail=f"Code '{code}' ({candidate.description}) failed clinical semantic validation: {fail_summary}.",
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.",
)
# Record evidence-based validation checks for passed code
checks.append(
ValidationCheck(
rule_name="AnatomicalSiteMatch",
passed=True,
details=f"Anatomical site in '{code}' ({candidate.description}) verified against documented evidence: '{ev_text[:80]}...'",
)
)
checks.append(
ValidationCheck(
rule_name="LateralityMatch",
passed=True,
details=f"Laterality in '{code}' matches documented evidence.",
)
)
checks.append(
ValidationCheck(
rule_name="SemanticAttributeMatch",
passed=True,
details=f"All clinical qualifiers and attributes 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)
@@ -189,9 +189,10 @@ class ReverseAttributeChecker:
)
req_right = bool(
re.search(
r"\b(?:right\s+side|of\s+right|in\s+right|right\s+(?:kidney|ureter|leg|arm|lung|flank|ear|eye|ovary|testis|foot|hand|shoulder|hip|knee))\b",
r"\b(?:right\s+side|of\s+right|in\s+right|right\s+(?:female\s+)?breast|right\s+(?:kidney|ureter|leg|arm|lung|flank|ear|eye|ovary|testis|foot|hand|shoulder|hip|knee|fallopian|tube|extremity|quadrant|lobe|adrenal|femur|humerus))\b",
desc_clean,
)
or re.search(r"\b(?:quadrant\s+of\s+right|of\s+right\s+female\s+breast)\b", desc_clean)
or desc_clean.endswith(", right")
or desc_clean.endswith(" right side")
or ", right " in desc_clean
@@ -199,9 +200,10 @@ class ReverseAttributeChecker:
)
req_left = bool(
re.search(
r"\b(?:left\s+side|of\s+left|in\s+left|left\s+(?:kidney|ureter|leg|arm|lung|flank|ear|eye|ovary|testis|foot|hand|shoulder|hip|knee))\b",
r"\b(?:left\s+side|of\s+left|in\s+left|left\s+(?:female\s+)?breast|left\s+(?:kidney|ureter|leg|arm|lung|flank|ear|eye|ovary|testis|foot|hand|shoulder|hip|knee|fallopian|tube|extremity|quadrant|lobe|adrenal|femur|humerus))\b",
desc_clean,
)
or re.search(r"\b(?:quadrant\s+of\s+left|of\s+left\s+female\s+breast)\b", desc_clean)
or desc_clean.endswith(", left")
or desc_clean.endswith(" left side")
or ", left " in desc_clean
@@ -218,13 +220,17 @@ class ReverseAttributeChecker:
if req_bilateral:
if doc_bilateral:
return True, None
return False, "bilateral laterality"
if doc_right or doc_left:
return False, "conflicting unilateral documentation (code requires bilateral laterality)"
return False, "unsupported bilateral laterality"
if req_right:
if doc_right and not doc_left:
return True, None
if not doc_right:
return False, "right laterality"
if doc_left:
return False, "conflicting left laterality (code requires right)"
return False, "unsupported right laterality"
if doc_left:
return False, "conflicting left laterality"
@@ -232,12 +238,84 @@ class ReverseAttributeChecker:
if doc_left and not doc_right:
return True, None
if not doc_left:
return False, "left laterality"
if doc_right:
return False, "conflicting right laterality (code requires left)"
return False, "unsupported left laterality"
if doc_right:
return False, "conflicting right laterality"
return True, None
@classmethod
def validate_anatomical_site(
cls,
code_description: str,
evidence_text: str,
diagnosis_term: str = "",
) -> tuple[bool, str | None]:
"""Verify that anatomical organ and quadrant in code description matches documented diagnosis."""
desc_lower = code_description.lower()
combined = f"{diagnosis_term} {evidence_text}".lower()
organ_patterns: dict[str, list[str]] = {
"breast": [r"\bbreasts?\b", r"\bmammary\b", r"\bnipple\b", r"\bareola\b"],
"ovary": [r"\bovary\b", r"\bovaries\b", r"\bovarian\b", r"\badnexa\b", r"\badnexal\b", r"\boophor\w*"],
"fallopian_tube": [r"\bfallopian\b", r"\bsalpinx\b", r"\bsalpingo\w*"],
"uterus": [r"\buterus\b", r"\buterine\b", r"\bendometr\w*", r"\bmyometr\w*"],
"cervix": [r"\bcervix\b", r"\bcervical\b"],
"prostate": [r"\bprostate\b", r"\bprostatic\b"],
"testis": [r"\btestis\b", r"\btesticle\b", r"\btesticular\b", r"\bscrotum\b"],
"lung": [r"\blung\b", r"\blungs\b", r"\bbronch\w*", r"\bpleura\w*"],
"colon": [r"\bcolon\b", r"\bcolorectal\b", r"\brectum\b", r"\brectal\b", r"\bsigmoid\b", r"\bcecum\b", r"\bappendix\b", r"\bappendiceal\b"],
"kidney": [r"\bkidney\b", r"\brenal\b", r"\bnephr\w*"],
"bladder": [r"\bbladder\b", r"\burinary\s+bladder\b"],
"skin": [r"\bskin\b", r"\bcutaneous\b", r"\bmelanoma\b", r"\bepiderm\w*"],
"thyroid": [r"\bthyroid\b"],
"stomach": [r"\bstomach\b", r"\bgastric\b"],
"liver": [r"\bliver\b", r"\bhepatic\b"],
"pancreas": [r"\bpancreas\b", r"\bpancreatic\b"],
"bone": [r"\bbone\b", r"\bfemur\b", r"\btibia\b", r"\bhumerus\b", r"\bfibula\b", r"\bradius\b", r"\bulna\b"],
}
# Determine documented organs in diagnosis term + evidence
doc_organs = {
organ for organ, pats in organ_patterns.items()
if any(re.search(pat, combined) for pat in pats)
}
# Determine organs specified in code description
code_organs = {
organ for organ, pats in organ_patterns.items()
if any(re.search(pat, desc_lower) for pat in pats)
}
# If documented organ is specific and code organ is entirely disjoint
if doc_organs and code_organs and not doc_organs.intersection(code_organs):
gyn_organs = {"ovary", "fallopian_tube", "uterus", "cervix"}
if not (doc_organs.issubset(gyn_organs) and code_organs.issubset(gyn_organs)):
return (
False,
f"anatomical site mismatch: code is for {', '.join(sorted(code_organs))} "
f"but documented condition is {', '.join(sorted(doc_organs))}",
)
# Breast quadrants check: If code specifies a specific quadrant, evidence must support it
quadrant_specs = {
"upper-outer quadrant": [r"upper[- ]outer\s+quadrant", r"\buoq\b", r"upper\s+and\s+outer"],
"upper-inner quadrant": [r"upper[- ]inner\s+quadrant", r"\buiq\b", r"upper\s+and\s+inner"],
"lower-outer quadrant": [r"lower[- ]outer\s+quadrant", r"\bloq\b", r"lower\s+and\s+outer"],
"lower-inner quadrant": [r"lower[- ]inner\s+quadrant", r"\bliq\b", r"lower\s+and\s+inner"],
"nipple and areola": [r"\bnipple\b", r"\bareola\b"],
"axillary tail": [r"axillary\s+tail", r"tail\s+of\s+spence"],
}
for q_name, q_pats in quadrant_specs.items():
if any(re.search(pat, desc_lower) for pat in q_pats):
has_q = any(re.search(pat, combined) for pat in q_pats)
if not has_q:
return False, f"unsupported quadrant specificity: code specifies '{q_name}'"
return True, None
@classmethod
def validate_code_attributes(
cls,
@@ -279,6 +357,15 @@ class ReverseAttributeChecker:
if not lat_valid and lat_error:
unsupported.append(lat_error)
# Anatomical Site & Quadrant validation
anat_valid, anat_error = cls.validate_anatomical_site(
code_description=code_description,
evidence_text=evidence_text,
diagnosis_term=diagnosis_term,
)
if not anat_valid and anat_error:
unsupported.append(anat_error)
# Diabetes Type 1 vs Type 2 distinction
desc_lower = code_description.lower()
if re.search(r"\btype\s+1\b", desc_lower) and not re.search(