diff --git a/src/medical_coding/agents/clinical_extractor.py b/src/medical_coding/agents/clinical_extractor.py index 0ad7f7c..6bb9a0c 100644 --- a/src/medical_coding/agents/clinical_extractor.py +++ b/src/medical_coding/agents/clinical_extractor.py @@ -37,7 +37,7 @@ logger = get_logger(__name__) # Standard section header regexes SECTION_PATTERNS: list[tuple[str, str]] = [ ("DISCHARGE_SUMMARY", r"(?:HOSPITAL\s+DISCHARGE\s+SUMMARY|DISCHARGE\s+SUMMARY|CLINICAL\s+SUMMARY)"), - ("DISCHARGE_DIAGNOSES", r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|FINAL\s+CODING\s+SUMMARY|CODING\s+SUMMARY|FINAL\s+CODING|POSTOPERATIVE\s+DIAGNOS[EI]S|DIAGNOS[EI]S\s+ON\s+DISCHARGE|DIAGNOSIS|ACTIVE\s+PROBLEMS|PROBLEM\s+LIST|ACTIVE\s+ISSUES)"), + ("DISCHARGE_DIAGNOSES", r"(?:DISCHARGE\s+DIAGNOS[EI]S|FINAL\s+DIAGNOS[EI]S|FINAL\s+CODING\s+SUMMARY|CODING\s+SUMMARY|FINAL\s+CODING|POSTOPERATIVE\s+DIAGNOS[EI]S|DIAGNOS[EI]S\s+ON\s+DISCHARGE|DIAGNOS[EI]S|ACTIVE\s+PROBLEMS|PROBLEM\s+LIST|ACTIVE\s+ISSUES)"), ("PRINCIPAL_DIAGNOSIS", r"(?:PRINCIPAL\s+DIAGNOS[EI]S|PRIMARY\s+DIAGNOS[EI]S|ADMITTING\s+DIAGNOS[EI]S|ADMISSION\s+DIAGNOS[EI]S)"), ("SECONDARY_DIAGNOSES", r"(?:SECONDARY\s+DIAGNOS[EI]S|ADDITIONAL\s+DIAGNOS[EI]S|CO-?MORBIDITIES|OTHER\s+DIAGNOS[EI]S)"), ("CHIEF_COMPLAINT", r"(?:CHIEF\s+COMPLAINT|REASON\s+FOR\s+ADMISSION|PRESENTING\s+COMPLAINT|ADMITTED\s+FOR)"), @@ -175,6 +175,8 @@ class SectionSegmenter: content_start = m["content_start"] content_end = matches[i + 1]["start_pos"] if i + 1 < len(matches) else len(text) content_str = text[content_start:content_end] + if not content_str.strip() and i + 1 < len(matches): + continue sections.append( ClinicalDocumentSection( section_name=m["section_name"], @@ -191,6 +193,40 @@ class SectionSegmenter: class EvidenceFirstFactExtractor: """Extracts evidence-grounded clinical facts from partitioned document sections.""" + @staticmethod + def _protect_organism_abbreviations(text: str) -> tuple[str, dict[str, str]]: + """Protect genus abbreviations (e.g., E. coli, H. pylori, S. aureus, C. diff) from being split on period.""" + replacements: dict[str, str] = {} + def _repl(m: re.Match) -> str: + token = f"__ORG_ABBR_{len(replacements)}__" + replacements[token] = m.group(0) + return token + # Matches single uppercase letter + dot + space + species word + masked = re.sub(r"\b([A-Za-z])\.\s*([A-Za-z]+(?:\s+[a-z]+)?)\b", _repl, text) + return masked, replacements + + @staticmethod + def _unprotect_organism_abbreviations(text: str, replacements: dict[str, str]) -> str: + res = text + for token, original in replacements.items(): + res = res.replace(token, original) + return res + + @staticmethod + def _split_into_sentences(text: str) -> list[str]: + """Split text into sentences while strictly preserving organism names, numbered lists, and decimal numbers.""" + lines = [line.strip() for line in text.split("\n") if line.strip()] + sentences: list[str] = [] + for line in lines: + masked, rep = EvidenceFirstFactExtractor._protect_organism_abbreviations(line) + # Split only on period/question/exclamation followed by space and capital letter or digit + sub_sents = re.split(r"(? None: self._extracted_procedures: list[str] = [] self._operative_findings: list[dict[str, Any]] = [] @@ -460,7 +496,7 @@ class EvidenceFirstFactExtractor: return [] # Split into sentences or lines - raw_sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", cleaned) if s.strip()] + raw_sentences = self._split_into_sentences(cleaned) for sent in raw_sentences: if len(sent) < 4: @@ -1014,7 +1050,7 @@ class EvidenceFirstFactExtractor: from medical_coding.validation.clinical_gate import HardClinicalCandidateGate - sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", cleaned) if s.strip()] + sentences = self._split_into_sentences(cleaned) for sent in sentences: if ( @@ -1026,49 +1062,51 @@ class EvidenceFirstFactExtractor: ): continue + masked_sent, rep = self._protect_organism_abbreviations(sent) + # Pattern A: Complication cues: "course was complicated by [X]", "complicated by [X]", "developed [X]", "went into [X]", "manifested [X]" comp_match = re.search( r"(?:course\s+(?:was\s+)?complicated\s+by|complicated\s+by|developed|went\s+into|manifested|suffered)\s+([^.]+)", - sent, + masked_sent, re.IGNORECASE, ) # Pattern B: Inpatient management/diagnosis: "treated for [X]", "managed for [X]", "diagnosed with [X]" treat_match = re.search( r"(?:treated\s+(?:for|with\s+(?:iv\s+)?[a-z0-9]+\s+for)|managed\s+for|diagnosed\s+with|inpatient\s+management\s+of)\s+([^.]+)", - sent, + masked_sent, re.IGNORECASE, ) # Pattern C: Specialist evaluations, consultations, and clinical conclusions eval_match = re.search( r"(?:(?:[a-z]+\s+)?(?:evaluation|consultation|consult|assessment|review)\s+(?:concluded|revealed|showed|noted|found|confirmed|diagnosed|suggested)\s+(?:that\s+)?|concluded\s+that\s+|noted\s+to\s+have\s+|found\s+to\s+have\s+|manifested\s+(?:with\s+)?)\s*([^.]+)", - sent, + masked_sent, re.IGNORECASE, ) # Pattern D: Additional or concurrent conditions documented during course additional_match = re.search( r"(?:with\s+additional|and\s+additional|additional|concurrent|superimposed)\s+([^.]+)", - sent, + masked_sent, re.IGNORECASE, ) matched_clauses: list[str] = [] if comp_match: - matched_clauses.append(comp_match.group(1).strip()) + matched_clauses.append(self._unprotect_organism_abbreviations(comp_match.group(1).strip(), rep)) if treat_match: - matched_clauses.append(treat_match.group(1).strip()) + matched_clauses.append(self._unprotect_organism_abbreviations(treat_match.group(1).strip(), rep)) if eval_match: - matched_clauses.append(eval_match.group(1).strip()) + matched_clauses.append(self._unprotect_organism_abbreviations(eval_match.group(1).strip(), rep)) if additional_match: - matched_clauses.append(additional_match.group(1).strip()) + matched_clauses.append(self._unprotect_organism_abbreviations(additional_match.group(1).strip(), rep)) if not matched_clauses: gen_match = re.search( r"(?:patient\s+(?:had|experienced|manifested|presented\s+with|developed)|also\s+(?:had|noted|developed|experienced|found)|showed|revealed|demonstrated|confirmed|diagnosed\s+as)\s+([^.]+)", - sent, + masked_sent, re.IGNORECASE, ) if gen_match: - matched_clauses.append(gen_match.group(1).strip()) + matched_clauses.append(self._unprotect_organism_abbreviations(gen_match.group(1).strip(), rep)) for clause in matched_clauses: # Strip trailing management phrases from clause @@ -1172,7 +1210,7 @@ class EvidenceFirstFactExtractor: from medical_coding.validation.clinical_gate import HardClinicalCandidateGate - sentences = [s.strip() for s in re.split(r"(?<=[.!?\n])\s+", cleaned) if s.strip()] + sentences = self._split_into_sentences(cleaned) for sent in sentences: if ( @@ -1185,24 +1223,39 @@ class EvidenceFirstFactExtractor: continue findings_clauses: list[str] = [] + masked_sent, rep = self._protect_organism_abbreviations(sent) # 1. Imaging findings: CT, CXR, Ultrasound, MRI, Biopsy, EGD img_match = re.search( - r"(?:ct(?:\s+scan)?|cxr|chest\s+x-?ray|ultrasound|usg|mri|egd|biopsy|echocardiogram|studies)\s*(?:of\s+[^\n:]+)?\s*(?::|--|-)?\s*(?:showed|revealed|demonstrated|confirmed|reported|noted)\s+([^.]+)", - sent, + r"(?:ct(?:\s+scan)?|cxr|chest\s+x-?ray|ultrasound|usg|mri|egd|biopsy|echocardiogram|studies)\s*(?:of\s+[^\n:]+)?\s*(?::|--|-)?\s*(?:showed|revealed|demonstrated|confirmed|reported|noted|positive\s+(?:for)?)\s+([^.]+)", + masked_sent, re.IGNORECASE, ) if img_match: - findings_clauses.append(img_match.group(1).strip()) + findings_clauses.append(self._unprotect_organism_abbreviations(img_match.group(1).strip(), rep)) # 2. Microbiology / culture findings: blood culture, urine culture, sputum culture micro_match = re.search( - r"(?:blood\s+cultures?|urine\s+cultures?|sputum\s+cultures?|cultures?|gram\s+stain|clo\s+test)\s*(?::|--|-)?\s*(?:grew|positive\s+for|showed|isolated|revealed)\s+([^.]+)", - sent, + r"(?:blood\s+cultures?|urine\s+cultures?|sputum\s+cultures?|stool\s+cultures?|cultures?|gram\s+stain|clo\s+test|microbiology)\s*(?::|--|-)?\s*(?:grew|positive\s+(?:for)?|showed|isolated|revealed|detected|identified)?\s*([^.]+)", + masked_sent, re.IGNORECASE, ) if micro_match: - findings_clauses.append(micro_match.group(1).strip()) + findings_clauses.append(self._unprotect_organism_abbreviations(micro_match.group(1).strip(), rep)) + + # Direct extraction for prominent clinical microorganisms + for org_pat in [ + r"\b(?:e\.?\s*coli|escherichia\s+coli)\b", + r"\b(?:h\.?\s*pylori|helicobacter\s+pylori)\b", + r"\b(?:c\.?\s*diff(?:icile)?|clostridioides\s+difficile)\b", + r"\b(?:s\.?\s*aureus|staphylococcus\s+aureus|mrsa)\b", + r"\b(?:s\.?\s*pneumoniae|streptococcus\s+pneumoniae)\b", + r"\b(?:p\.?\s*aeruginosa|pseudomonas\s+aeruginosa)\b", + r"\b(?:k\.?\s*pneumoniae|klebsiella\s+pneumoniae)\b", + ]: + org_m = re.search(org_pat, sent, re.IGNORECASE) + if org_m: + findings_clauses.append(org_m.group(0).strip()) for clause in findings_clauses: # Strip trailing notes or measures e.g. "causing hydronephrosis", "measuring 9mm", ">100,000 CFU/mL" @@ -1655,11 +1708,13 @@ class EvidenceFirstFactExtractor: if p2.lower() in generic_suffix_nouns: continue + p2_clean = re.sub(r"^(?:with|due\s+to|secondary\s+to|caused\s+by|from)\s+", "", p2, flags=re.IGNORECASE).strip() + v1, _ = HardClinicalCandidateGate.evaluate_candidate(p1) - v2, _ = HardClinicalCandidateGate.evaluate_candidate(p2) + v2, _ = HardClinicalCandidateGate.evaluate_candidate(p2_clean or p2) if v1 and v2: - return [p1] + EvidenceFirstFactExtractor._split_adjacent_clinical_conditions(p2) + return [p1] + EvidenceFirstFactExtractor._split_adjacent_clinical_conditions(p2_clean or p2) return [text.strip()] @@ -1731,7 +1786,7 @@ class EvidenceFirstFactExtractor: # Temporary mask for genus abbreviations like E. coli, H. pylori, S. pneumoniae, C. difficile masked = cleaned - abbrev_matches = list(re.finditer(r"\b([A-Z])\.\s+([a-z]+)\b", masked)) + abbrev_matches = list(re.finditer(r"\b([A-Za-z])\.\s*([A-Za-z]+(?:\s+[a-z]+)?)\b", masked)) for i, m in enumerate(abbrev_matches): masked = masked.replace(m.group(0), f"__ORGANISM_{i}__") @@ -1742,8 +1797,8 @@ class EvidenceFirstFactExtractor: masked = masked.replace(pm.group(0), f"__PLUS_MARKER_{i}__") # 1. Connectors that unconditionally separate independent clinical entities - # Split on list delimiters: plus signs (+), semicolons (;), ampersands (&), and slashes (/) separating independent entities - list_delims_pattern = r"\s*(?:\+|;|\s+&\s+|\s+/\s+)\s*" + # Split on list delimiters: commas (,), plus signs (+), semicolons (;), ampersands (&), and slashes (/) + list_delims_pattern = r"\s*(?:,|;|\+|\s+&\s+|\s+/\s+)\s*" raw_splits = [p.strip() for p in re.split(list_delims_pattern, masked, flags=re.IGNORECASE) if p.strip()] chunks: list[str] = [] @@ -1788,9 +1843,12 @@ class EvidenceFirstFactExtractor: pre_with = chunk[:generic_with_m.start()].strip() post_with = generic_with_m.group(1).strip() pre_with_clean = re.sub(r"\s+to\s+(?:the\s+)?(?:left|right|bilateral)$", "", pre_with, flags=re.IGNORECASE).strip() + post_with_unmasked = post_with + for i, m in enumerate(abbrev_matches): + post_with_unmasked = post_with_unmasked.replace(f"__ORGANISM_{i}__", m.group(0)) from medical_coding.validation.clinical_gate import HardClinicalCandidateGate v_pre, _ = HardClinicalCandidateGate.evaluate_candidate(pre_with_clean or pre_with) - v_post, _ = HardClinicalCandidateGate.evaluate_candidate(post_with) + v_post, _ = HardClinicalCandidateGate.evaluate_candidate(post_with_unmasked) if v_pre and v_post: refined_chunks.append(pre_with_clean or pre_with) refined_chunks.append(post_with) diff --git a/src/medical_coding/agents/ranker.py b/src/medical_coding/agents/ranker.py index 4170b73..c499d4e 100644 --- a/src/medical_coding/agents/ranker.py +++ b/src/medical_coding/agents/ranker.py @@ -658,6 +658,7 @@ class CandidateRankingAgent(BaseAgent): # If top candidate score is below min_confidence, or if top candidate has unsupported attributes: # Check if there is another candidate in candidate pool that is billable, has no unsupported attributes, # and has core_match_fraction > 0.0 + matching_status = "MATCHED" if top_score < self.min_confidence: fallback_cand = None for cand, s, rat in scored_candidates: @@ -674,6 +675,17 @@ class CandidateRankingAgent(BaseAgent): if fallback_cand: top_cand = fallback_cand + elif candidates and evidence_quote: + # Per requirement: for [no_local_code] diagnoses with evidence, display the nearest relatable code + nearest_cand = scored_candidates[0][0] + for cand, s, rat in scored_candidates: + if cand.is_valid_billable: + nearest_cand = cand + break + top_cand = nearest_cand + top_score = max(0.40, top_score) + top_rationale = f"nearest relatable candidate assigned for documented condition ({top_rationale})" + matching_status = "NEAREST_MATCH" else: abstain_reason = ( "UNSUPPORTED_SPECIFICITY" @@ -723,7 +735,7 @@ class CandidateRankingAgent(BaseAgent): supporting_evidence=[evidence_quote], confidence=max(0.0, min(1.0, round(top_score, 4))), abstention_reason=None, - matching_status="MATCHED", + matching_status=matching_status, candidate_pool=candidates, decision="ACCEPTED", ) diff --git a/src/medical_coding/graph/nodes.py b/src/medical_coding/graph/nodes.py index eb753e7..86ea31e 100644 --- a/src/medical_coding/graph/nodes.py +++ b/src/medical_coding/graph/nodes.py @@ -1001,7 +1001,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: description=item.description, database_code=item.code, database_description=item.description, - matching_status="MATCHED", + matching_status=getattr(item, "matching_status", "MATCHED") or "MATCHED", source_section=getattr(item, "source_section", "") or getattr(item.evidence, "source_section", "") or "DISCHARGE_DIAGNOSES", source_span=getattr(item, "source_span", None) or getattr(item.evidence, "source_span", None), role=item.role, @@ -1036,9 +1036,10 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: elif item.role == DiagnosisRole.SECONDARY: secondary_responses.append(resp) + catalog, retriever = get_or_initialize_retrieval_system() + # SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING (Sections 4 & 11) # If primary diagnosis was clinically confirmed and established, but ICD mapping abstained or failed: - # If primary diagnosis was clinically confirmed and established, but ICD mapping abstained or failed: if primary_response is None: clin_primary = None for c in classified: @@ -1050,7 +1051,56 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: if clin_primary: term = getattr(clin_primary, "normalized_diagnosis", None) or getattr(clin_primary, "raw_term", "") - if not any(a.reason == AbstentionReason.NO_MATCHING_ICD_CANDIDATE and a.raw_term and a.raw_term.lower() == term.lower() for a in abstentions): + c_ev = ( + getattr(clin_primary, "evidence_quote", None) + or getattr(clin_primary, "primary_evidence_quote", None) + or ( + clin_primary.context.evidence.quote + if hasattr(clin_primary, "context") and hasattr(clin_primary.context, "evidence") and clin_primary.context.evidence + else "" + ) + or "" + ) + retrieved = retriever.retrieve(term, top_k=5) if term else [] + nearest_cand = None + for cand in retrieved: + if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code): + nearest_cand = cand + break + if not nearest_cand and retrieved: + nearest_cand = retrieved[0] + + if nearest_cand and c_ev: + is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M")) + is_cpt = bool(getattr(nearest_cand, "coding_system", None) == "CPT" or (nearest_cand.code.isdigit() and len(nearest_cand.code) in (4, 5))) + icd10_val = nearest_cand.code if not is_icdo and not is_cpt else None + icdo_val = nearest_cand.code if is_icdo else None + cpt_val = nearest_cand.code if is_cpt else None + + primary_response = CodedDiagnosisResponse( + raw_term=term, + normalized_diagnosis=term, + description=nearest_cand.description, + database_code=nearest_cand.code, + database_description=nearest_cand.description, + matching_status="NEAREST_MATCH", + source_section=getattr(clin_primary, "source_section", "") or "CLINICAL_DOCUMENTATION", + role=DiagnosisRole.PRIMARY, + acuity=Acuity.ACUTE if "acute" in term.lower() else (Acuity.CHRONIC if "chronic" in term.lower() else Acuity.UNSPECIFIED), + certainty=Certainty.CONFIRMED, + evidence_quote=c_ev or term, + evidence=[{ + "quote": c_ev or term, + "section": getattr(clin_primary, "source_section", "") or "CLINICAL_DOCUMENTATION", + "evidence_type": "CLINICAL_EVIDENCE", + }], + confidence_score=max(0.40, getattr(nearest_cand, "retrieval_score", 0.50)), + is_terminal_billable=True, + icd10cm=icd10_val, + icdo=icdo_val, + cpt=cpt_val, + ) + elif not any(a.reason == AbstentionReason.NO_MATCHING_ICD_CANDIDATE and a.raw_term and a.raw_term.lower() == term.lower() for a in abstentions): abstentions.append( AbstentionRecord( diagnosis_id=getattr(clin_primary, "diagnosis_id", "primary"), @@ -1060,7 +1110,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: stage=PipelineStage.VALIDATION, ) ) - if secondary_responses: + if not primary_response and secondary_responses: # Promote top coded secondary to primary role primary_response = secondary_responses.pop(0) primary_response.role = DiagnosisRole.PRIMARY @@ -1140,18 +1190,70 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: if not is_valid_cand: continue - # Clinical condition has no matching code in authoritative database; put strictly in abstain - if not any(a.raw_term and a.raw_term.lower() == c_term.lower() for a in abstentions): - abstentions.append( - AbstentionRecord( - diagnosis_id=getattr(c, "diagnosis_id", "secondary"), - raw_term=c_term, - reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, - detail=f"Condition '{c_term}' lacked verified local code match; strictly abstained under coding rules.", - stage=PipelineStage.VALIDATION, - ) + # Per requirement: for [no_local_code] type diagnosis, nearest relatable code should get displayed, because they also have evidence + nearest_cand = None + cand_pool_item = state.get("candidate_pool", {}).get(getattr(c, "diagnosis_id", ""), []) + if cand_pool_item: + for cand in cand_pool_item: + if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code): + nearest_cand = cand + break + if not nearest_cand and cand_pool_item: + nearest_cand = cand_pool_item[0] + if not nearest_cand and c_term: + retrieved = retriever.retrieve(c_term, top_k=5) + for cand in retrieved: + if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code): + nearest_cand = cand + break + if not nearest_cand and retrieved: + nearest_cand = retrieved[0] + + if nearest_cand and c_quote: + is_icdo = bool(getattr(nearest_cand, "coding_system", None) == "ICD-O" or nearest_cand.code.startswith("M")) + is_cpt = bool(getattr(nearest_cand, "coding_system", None) == "CPT" or (nearest_cand.code.isdigit() and len(nearest_cand.code) in (4, 5))) + icd10_val = nearest_cand.code if not is_icdo and not is_cpt else None + icdo_val = nearest_cand.code if is_icdo else None + cpt_val = nearest_cand.code if is_cpt else None + + sec_resp = CodedDiagnosisResponse( + raw_term=c_term, + normalized_diagnosis=c_term, + description=nearest_cand.description, + database_code=nearest_cand.code, + database_description=nearest_cand.description, + matching_status="NEAREST_MATCH", + source_section=getattr(c, "source_section", "") or "CLINICAL_DOCUMENTATION", + role=DiagnosisRole.SECONDARY, + acuity=Acuity.ACUTE if "acute" in c_norm else (Acuity.CHRONIC if "chronic" in c_norm else Acuity.UNSPECIFIED), + certainty=Certainty.CONFIRMED, + evidence_quote=c_quote or c_term, + evidence=[{ + "quote": c_quote or c_term, + "section": getattr(c, "source_section", "") or "CLINICAL_DOCUMENTATION", + "evidence_type": "CLINICAL_EVIDENCE", + }], + confidence_score=max(0.40, getattr(nearest_cand, "retrieval_score", 0.50)), + is_terminal_billable=True, + icd10cm=icd10_val, + icdo=icdo_val, + cpt=cpt_val, ) - seen_sec_terms.add(c_norm) + secondary_responses.append(sec_resp) + seen_sec_terms.add(c_norm) + else: + # Clinical condition has no matching code in authoritative database; put strictly in abstain + if not any(a.raw_term and a.raw_term.lower() == c_term.lower() for a in abstentions): + abstentions.append( + AbstentionRecord( + diagnosis_id=getattr(c, "diagnosis_id", "secondary"), + raw_term=c_term, + reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, + detail=f"Condition '{c_term}' lacked verified local code match; strictly abstained under coding rules.", + stage=PipelineStage.VALIDATION, + ) + ) + seen_sec_terms.add(c_norm) # Suppress Z71.1 ("feared health complaint in whom no diagnosis is made") when real clinical conditions exist if primary_response and primary_response.code == "Z71.1" and secondary_responses: @@ -1159,12 +1261,33 @@ 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"] - # Filter secondary_responses so ONLY items with verified local codes are retained; uncoded items are strictly abstained + # Filter secondary_responses so ONLY items with verified local codes or nearest relatable matches are retained; uncoded items without matches are strictly abstained coded_secondaries: list[CodedDiagnosisResponse] = [] for s in secondary_responses: s_code = s.code or getattr(s, "database_code", None) if s_code and s_code != "None" and s.matching_status != "NO_DATABASE_MATCH": coded_secondaries.append(s) + elif s.evidence_quote: + s_name = s.normalized_diagnosis or s.raw_term or s.description or "" + retrieved = retriever.retrieve(s_name, top_k=5) if s_name else [] + if retrieved: + top_r = retrieved[0] + s.icd10cm = top_r.code + s.database_code = top_r.code + s.database_description = top_r.description + s.matching_status = "NEAREST_MATCH" + coded_secondaries.append(s) + else: + if s_name and not any(a.raw_term and a.raw_term.lower() == s_name.lower() for a in abstentions): + abstentions.append( + AbstentionRecord( + diagnosis_id=getattr(s, "diagnosis_id", "secondary-abstained"), + raw_term=s_name, + reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, + detail=f"Condition '{s_name}' lacked verified local code match; strictly abstained under coding rules.", + stage=PipelineStage.VALIDATION, + ) + ) else: s_name = s.normalized_diagnosis or s.raw_term or s.description or "" if s_name and not any(a.raw_term and a.raw_term.lower() == s_name.lower() for a in abstentions): @@ -1179,26 +1302,36 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: ) secondary_responses = coded_secondaries - # Check primary_response for local code match: if missing, abstain and promote coded secondary if available + # Check primary_response for local code match: if missing, attempt nearest relatable match if evidence exists, else abstain and promote coded secondary if available if primary_response: p_code = primary_response.code or getattr(primary_response, "database_code", None) if not p_code or p_code == "None" or primary_response.matching_status == "NO_DATABASE_MATCH": p_name = primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or "" - if p_name and not any(a.raw_term and a.raw_term.lower() == p_name.lower() for a in abstentions): - abstentions.append( - AbstentionRecord( - diagnosis_id=getattr(primary_response, "diagnosis_id", "primary-abstained"), - raw_term=p_name, - reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, - detail=f"Primary condition '{p_name}' lacked verified local code match; strictly abstained under coding rules.", - stage=PipelineStage.VALIDATION, + if primary_response.evidence_quote and p_name: + retrieved = retriever.retrieve(p_name, top_k=5) + if retrieved: + top_r = retrieved[0] + primary_response.icd10cm = top_r.code + primary_response.database_code = top_r.code + primary_response.database_description = top_r.description + primary_response.matching_status = "NEAREST_MATCH" + p_code = top_r.code + if not p_code or p_code == "None" or primary_response.matching_status == "NO_DATABASE_MATCH": + if p_name and not any(a.raw_term and a.raw_term.lower() == p_name.lower() for a in abstentions): + abstentions.append( + AbstentionRecord( + diagnosis_id=getattr(primary_response, "diagnosis_id", "primary-abstained"), + raw_term=p_name, + reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, + detail=f"Primary condition '{p_name}' lacked verified local code match; strictly abstained under coding rules.", + stage=PipelineStage.VALIDATION, + ) ) - ) - if secondary_responses: - primary_response = secondary_responses.pop(0) - primary_response.role = DiagnosisRole.PRIMARY - else: - primary_response = None + if secondary_responses: + primary_response = secondary_responses.pop(0) + primary_response.role = DiagnosisRole.PRIMARY + else: + primary_response = None # Enforce clean role separation: secondary section must NEVER duplicate the primary diagnosis if primary_response: diff --git a/src/medical_coding/reasoning/concept_reasoner.py b/src/medical_coding/reasoning/concept_reasoner.py index 9b1f660..a3bcbc7 100644 --- a/src/medical_coding/reasoning/concept_reasoner.py +++ b/src/medical_coding/reasoning/concept_reasoner.py @@ -57,6 +57,8 @@ DISEASE_FAMILY_PATTERNS: list[tuple[str, list[str], str]] = [ ("myocardial_infarction", ["myocardial infarction", "nstemi", "stemi", "acute coronary syndrome", "subendocardial myocardial infarction", "heart attack"], "heart"), ("cholecystitis", ["cholecystitis", "acute cholecystitis", "chronic cholecystitis"], "gallbladder"), ("cholelithiasis", ["cholelithiasis", "gallstone", "gallstones", "calculus of gallbladder", "biliary calculus"], "gallbladder"), + ("choledocholithiasis", ["choledocholithiasis", "calculus of bile duct", "bile duct calculus", "gallstone in bile duct"], "gallbladder"), + ("nasal_obstruction", ["nasal obstruction", "obstruction of nose", "nasal congestion", "nasal blockage", "deviated nasal septum"], "nose"), ("hyperlipidemia", ["hyperlipidemia", "hypercholesterolemia", "dyslipidemia", "hypertriglyceridemia"], "blood"), ("hypokalemia", ["hypokalemia", "hypopotassemia"], "blood"), ("hyperkalemia", ["hyperkalemia"], "blood"), diff --git a/src/medical_coding/reasoning/match_spec.py b/src/medical_coding/reasoning/match_spec.py index a772bd3..6fc124c 100644 --- a/src/medical_coding/reasoning/match_spec.py +++ b/src/medical_coding/reasoning/match_spec.py @@ -54,6 +54,8 @@ FAMILY_TO_CODE_PREFIXES: dict[str, list[str]] = { "myocardial_infarction": ["I21", "I22"], "cholecystitis": ["K81", "K80"], "cholelithiasis": ["K80"], + "choledocholithiasis": ["K80.50", "K80.30", "K80.32", "K80.5", "K80"], + "nasal_obstruction": ["J34.89", "J34.9", "R09.81", "J34.2", "J34"], "hyperlipidemia": ["E78"], "hypokalemia": ["E87.6", "E87"], "hyperkalemia": ["E87.5", "E87"], diff --git a/src/medical_coding/retrieval/tokenizer.py b/src/medical_coding/retrieval/tokenizer.py index 6303bbd..11ae32a 100644 --- a/src/medical_coding/retrieval/tokenizer.py +++ b/src/medical_coding/retrieval/tokenizer.py @@ -52,6 +52,10 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = { "dns": "deviated nasal septum", "fess": "functional endoscopic sinus surgery sinus endoscopy", "ith": "inferior turbinate hypertrophy", + "coli": "escherichia coli", + "pylori": "helicobacter pylori", + "choledocholithiasis": "calculus bile duct gallstone", + "mrsa": "methicillin resistant staphylococcus aureus", } # Non-informative general words (keeping critical medical distinctions: acute, chronic, type, 1, 2, without, etc.) @@ -282,6 +286,14 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = { "turbinates": ["turbinate", "nasal", "nose"], "nasal": ["nose", "turbinate", "turbinates", "septum"], "septum": ["nasal", "nose"], + "obstruction": ["blockage", "congestion", "disorder", "stricture", "stenosis"], + "choledocholithiasis": ["calculus", "bile", "duct", "gallstone", "gallstones", "cholelithiasis", "stone", "stones"], + "coli": ["escherichia", "infection", "bacteria", "bacteremia"], + "escherichia": ["coli", "infection", "bacteria", "bacteremia"], + "pylori": ["helicobacter", "gastritis", "infection", "bacteria"], + "helicobacter": ["pylori", "gastritis", "infection", "bacteria"], + "staphylococcus": ["staph", "aureus", "infection", "mrsa"], + "streptococcus": ["strep", "pneumoniae", "infection"], "pneumonia": ["pneumonitis", "pna"], "hypertension": ["htn", "high blood pressure"], "diabetes": ["dm", "diabetic"], diff --git a/src/medical_coding/schemas/icd.py b/src/medical_coding/schemas/icd.py index fa11cd3..e861bec 100644 --- a/src/medical_coding/schemas/icd.py +++ b/src/medical_coding/schemas/icd.py @@ -268,9 +268,9 @@ class RankedSelection(BaseModel): description="Outcome of candidate evaluation.", ) ) - matching_status: Literal["MATCHED", "NO_DATABASE_MATCH"] = Field( + matching_status: Literal["MATCHED", "NEAREST_MATCH", "NO_DATABASE_MATCH"] = Field( default="NO_DATABASE_MATCH", - description="Whether a database code was matched or no match was found in the database.", + description="Whether a database code was matched, nearest relatable code matched, or no match was found.", ) source_section: str | None = Field( default=None, diff --git a/src/medical_coding/schemas/response.py b/src/medical_coding/schemas/response.py index 0eda076..8e1c868 100644 --- a/src/medical_coding/schemas/response.py +++ b/src/medical_coding/schemas/response.py @@ -56,9 +56,9 @@ class CodedDiagnosisResponse(BaseModel): default=None, description="Matched CPT procedural code if matched, None if not.", ) - matching_status: Literal["MATCHED", "NO_DATABASE_MATCH"] = Field( + matching_status: Literal["MATCHED", "NEAREST_MATCH", "NO_DATABASE_MATCH"] = Field( default="MATCHED", - description="Whether this diagnosis matched a database code or abstained as NO_DATABASE_MATCH.", + description="Whether this diagnosis matched a database code, nearest relatable match, or abstained as NO_DATABASE_MATCH.", ) database_code: str | None = Field( default=None, diff --git a/src/medical_coding/ui/app.py b/src/medical_coding/ui/app.py index ad70d86..b22ac6e 100644 --- a/src/medical_coding/ui/app.py +++ b/src/medical_coding/ui/app.py @@ -243,12 +243,8 @@ def render_coding_session_results( error_traceback=tb_str, duration_ms=coding_result.processing_time_ms, ) - render_process_oversight_timeline(steps_data, coding_result.processing_time_ms) return - # Render Node-by-Node Process Oversight & Latency Timeline - render_process_oversight_timeline(steps_data, coding_result.processing_time_ms) - # High-Level KPIs st.markdown("### 📊 Coding Decisions & Evidence Audit") render_kpi_metrics(coding_result) diff --git a/src/medical_coding/ui/components.py b/src/medical_coding/ui/components.py index 2305a8f..1d8329b 100644 --- a/src/medical_coding/ui/components.py +++ b/src/medical_coding/ui/components.py @@ -63,7 +63,7 @@ def render_header( def render_kpi_metrics(result: CodingResult) -> None: """Render high-level KPIs for a single document coding run.""" - c1, c2, c3, c4, c5 = st.columns(5) + c1, c2, c3, c4 = st.columns(4) status_str = result.status.value if hasattr(result.status, "value") else str(result.status) status_class = ( @@ -131,19 +131,6 @@ def render_kpi_metrics(result: CodingResult) -> None: unsafe_allow_html=True, ) - with c5: - st.markdown( - clean_html( - f""" -
-
Processing Time
-
{result.processing_time_ms:.1f} ms
-
- """ - ), - unsafe_allow_html=True, - ) - def _clean_audit_from_evidence(ev: str) -> str: """Clean internal audit justifications and boilerplate from display evidence strings.""" @@ -171,6 +158,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None: ) acuity_badge = f'{html.escape(primary.acuity.value if hasattr(primary.acuity, "value") else str(primary.acuity))}' certainty_badge = f'{html.escape(primary.certainty.value if hasattr(primary.certainty, "value") else str(primary.certainty))}' + nearest_badge = 'Nearest Relatable Match' if getattr(primary, "matching_status", "") == "NEAREST_MATCH" else "" conf_pct = int(primary.confidence_score * 100) @@ -217,6 +205,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
{acuity_badge} {certainty_badge} + {nearest_badge} Chief Reason for Encounter {codes_html}
@@ -252,6 +241,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non ) acuity_str = html.escape(diag.acuity.value if hasattr(diag.acuity, "value") else str(diag.acuity)) certainty_str = html.escape(diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty)) + nearest_badge = 'Nearest Relatable Match' if getattr(diag, "matching_status", "") == "NEAREST_MATCH" else "" sec_codes_pills = [] if diag.icd10cm: @@ -286,6 +276,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
{billable_badge} + {nearest_badge} {acuity_str} {certainty_str} {sec_codes_html} @@ -597,68 +588,8 @@ NODE_TITLES: dict[str, str] = { def render_process_oversight_timeline(steps: list[dict[str, Any]], total_duration_ms: float = 0.0) -> None: - """Render a comprehensive process oversight timeline showing status and latency for each node.""" - if not steps: - return - - st.markdown("### ⏱️ Process Oversight & Node Latency Timeline") - st.caption("Real-time node-by-node execution auditing with microsecond time tracking and invariant verification:") - - tot_ms = total_duration_ms or sum(s.get("duration_ms", 0.0) for s in steps) or 1.0 - - timeline_rows = [] - for s in steps: - s_name = s.get("step_name", "unknown") - title = NODE_TITLES.get(s_name, s_name) - status = s.get("status", "SUCCESS") - dur = float(s.get("duration_ms", 0.0)) - share = min(100.0, round((dur / tot_ms) * 100.0, 1)) if tot_ms > 0 else 0.0 - - if status == "SUCCESS": - status_badge = '✓ PASSED' - row_class = "step-row" - status_icon = "🟢" - elif status == "FAILED": - status_badge = '✗ FAILED' - row_class = "step-row step-row-failed" - status_icon = "🔴" - else: - status_badge = '⏳ RUNNING' - row_class = "step-row step-row-running" - status_icon = "🔵" - - msg = s.get("log_message", "") - - timeline_rows.append( - f""" -
-
- #{s.get('step_index', 0):02d} - {status_icon} -
- {title} - {s_name} -
{msg}
-
-
-
- {dur:.1f} ms - ({share}%) -
{status_badge}
-
-
- """ - ) - - content_html = "\n".join(timeline_rows) - st.markdown( - f""" -
- {content_html} -
- """, - unsafe_allow_html=True, - ) + """Render a comprehensive process oversight timeline (suppressed per user specification).""" + return def render_failure_alert( @@ -689,7 +620,7 @@ def render_failure_alert( {err_text}
- Latency before failure: {duration_ms:.1f} ms • Prior completed stages preserved in audit database. + Prior completed stages preserved in audit database.
""", diff --git a/src/medical_coding/validation/deterministic.py b/src/medical_coding/validation/deterministic.py index 0c47f5d..3677956 100644 --- a/src/medical_coding/validation/deterministic.py +++ b/src/medical_coding/validation/deterministic.py @@ -149,6 +149,15 @@ class DeterministicValidator: candidate = better_candidate code = better_candidate.code anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs = _evaluate_candidate_clinical_meaning(candidate) + elif getattr(selection, "matching_status", "") == "NEAREST_MATCH": + # User requirement: for [no_local_code] type diagnosis, nearest relatable code should get displayed, because they also have evidence + checks.append( + ValidationCheck( + rule_name="NearestRelatableMatch", + passed=True, + details=f"Nearest relatable code '{code}' ({candidate.description}) accepted for documented clinical condition.", + ) + ) else: failure_reasons = [] if not anat_ok and anat_err: @@ -267,7 +276,7 @@ class DeterministicValidator: cpt=cpt_val, database_code=code, database_description=candidate.description, - matching_status="MATCHED", + matching_status=getattr(selection, "matching_status", "MATCHED") or "MATCHED", source_section=getattr(condition.context.evidence, "source_section", "") or getattr(selection, "source_section", ""), source_span=getattr(condition.context.evidence, "source_span", None) or getattr(selection, "source_span", None), ) diff --git a/src/medical_coding/validation/reverse_attributes.py b/src/medical_coding/validation/reverse_attributes.py index ef87acb..a95bd09 100644 --- a/src/medical_coding/validation/reverse_attributes.py +++ b/src/medical_coding/validation/reverse_attributes.py @@ -407,12 +407,32 @@ class ReverseAttributeChecker: from medical_coding.retrieval.tokenizer import CLINICAL_ABBREVIATIONS + ORGANISM_EQUIVALENCES: dict[str, list[str]] = { + "escherichia": ["e. coli", "e coli", "escherichia", "coliform"], + "coli": ["e. coli", "e coli", "escherichia coli", "coli"], + "helicobacter": ["h. pylori", "h pylori", "helicobacter"], + "pylori": ["h. pylori", "h pylori", "helicobacter pylori", "pylori"], + "streptococcus": ["strep", "streptococcal", "s. pneumoniae", "s. pyogenes", "streptococcus"], + "staphylococcus": ["staph", "staphylococcal", "s. aureus", "mrsa", "mssa", "staphylococcus"], + "pseudomonas": ["p. aeruginosa", "pseudomonal", "pseudomonas"], + "klebsiella": ["k. pneumoniae", "klebsiella"], + "clostridioides": ["c. diff", "c. difficile", "c difficile", "clostridioides", "clostridium"], + "clostridium": ["c. diff", "c. difficile", "c difficile", "clostridium", "clostridioides"], + "mycobacterium": ["tb", "tuberculosis", "m. tuberculosis", "mycobacterium"], + } + + # Check bracketed synonyms in code description (e.g. [E. coli], [H. pylori]) + bracketed_synonyms = [b.strip() for b in re.findall(r"\[(.*?)\]", desc_lower) if b.strip()] + bracket_supported = any(has_positive_mention(b, combined_evidence) for b in bracketed_synonyms) + for mod in code_modifiers: if mod in unsupported: continue variants = [mod] + CLINICAL_MORPHOLOGY.get(mod, []) if mod in CLINICAL_ABBREVIATIONS: variants.extend(CLINICAL_ABBREVIATIONS[mod].split()) + if mod in ORGANISM_EQUIVALENCES: + variants.extend(ORGANISM_EQUIVALENCES[mod]) if mod.endswith("s") and len(mod) > 4: variants.append(mod[:-1]) if mod.endswith("ic") and len(mod) > 4: @@ -421,6 +441,8 @@ class ReverseAttributeChecker: variants.append(mod[:-2]) supported = any(has_positive_mention(v, combined_evidence) for v in variants) + if not supported and bracket_supported and mod in ("escherichia", "helicobacter", "streptococcus", "staphylococcus", "pseudomonas", "klebsiella", "clostridium", "clostridioides"): + supported = True if not supported: unsupported.append(mod)