From c269bb9ca2d88c78b9a3cd8cecce4d97ad52363c Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Thu, 15 Oct 2026 09:54:57 +0530 Subject: [PATCH] fix(pipeline): drop duplicate diagnoses and remove repetitive evidence in final output --- src/medical_coding/graph/nodes.py | 101 ++++++++-- src/medical_coding/schemas/response.py | 175 +++++++++++++++--- src/medical_coding/ui/app.py | 63 ++++--- src/medical_coding/ui/components.py | 63 +++++-- src/medical_coding/utils/text.py | 149 +++++++++++++++ .../test_demo_fix_strengthened_classifier.py | 157 ++++++++++++++++ 6 files changed, 625 insertions(+), 83 deletions(-) diff --git a/src/medical_coding/graph/nodes.py b/src/medical_coding/graph/nodes.py index 58cb571..ce72154 100644 --- a/src/medical_coding/graph/nodes.py +++ b/src/medical_coding/graph/nodes.py @@ -1475,19 +1475,96 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]: abstentions = rechecked_abstentions - # Enforce clean role separation: secondary section must NEVER duplicate the primary diagnosis + # Deduplicate and clean repetitive evidences on primary response + from medical_coding.utils.text import ( + clean_and_deduplicate_evidence_list, + clean_and_deduplicate_evidence_quote, + normalize_diagnosis_name, + ) + if primary_response: - pri_code = primary_response.code - pri_norm = (primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or "").lower().strip() - filtered_sec = [] - for s in secondary_responses: - if pri_code and s.code and s.code == pri_code: - continue - s_norm = (s.normalized_diagnosis or s.raw_term or s.description or "").lower().strip() - if s_norm and pri_norm and s_norm == pri_norm: - continue - filtered_sec.append(s) - secondary_responses = filtered_sec + p_diag_name = primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description + primary_response.evidence_quote = clean_and_deduplicate_evidence_quote(primary_response.evidence_quote, p_diag_name) + primary_response.evidence = clean_and_deduplicate_evidence_list(getattr(primary_response, "evidence", []) or primary_response.evidence_quote, p_diag_name) + + # Enforce clean role separation and drop duplicates among secondaries and against primary + pri_code = (primary_response.code or getattr(primary_response, "database_code", "") or "").strip() if primary_response else "" + pri_norm = (primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or "").lower().strip() if primary_response else "" + pri_clean_norm = (normalize_diagnosis_name(pri_norm) or pri_norm).lower().strip() if pri_norm else "" + + deduped_secondaries: list[CodedDiagnosisResponse] = [] + seen_sec_codes: set[str] = set() + seen_sec_names: set[str] = set() + + for s in secondary_responses: + s_code = (s.code or getattr(s, "database_code", "") or "").strip() + s_name = (s.normalized_diagnosis or s.raw_term or s.description or "").strip() + s_norm = s_name.lower().strip() + s_clean_norm = (normalize_diagnosis_name(s_norm) or s_norm).lower().strip() + + # Drop secondary if it duplicates the primary diagnosis + if pri_code and s_code and s_code == pri_code: + continue + if pri_clean_norm and s_clean_norm and pri_clean_norm == s_clean_norm: + continue + + # Check if already in deduplicated secondaries + existing_match: CodedDiagnosisResponse | None = None + if s_code and s_code not in ("None", "[NO LOCAL CODE]") and s_code in seen_sec_codes: + existing_match = next((x for x in deduped_secondaries if (x.code or "").strip() == s_code), None) + elif s_clean_norm and s_clean_norm in seen_sec_names: + existing_match = next( + (x for x in deduped_secondaries if (normalize_diagnosis_name(x.normalized_diagnosis or x.raw_term or x.description or "") or "").lower().strip() == s_clean_norm), + None, + ) + + if existing_match: + # Merge evidence quotes and lists cleanly without repetition + combined_ev = f"{existing_match.evidence_quote or ''} | {s.evidence_quote or ''}".strip(" |") + merged_diag_name = existing_match.normalized_diagnosis or existing_match.description + existing_match.evidence_quote = clean_and_deduplicate_evidence_quote(combined_ev, merged_diag_name) + merged_ev_list = (getattr(existing_match, "evidence", []) or []) + (getattr(s, "evidence", []) or []) + existing_match.evidence = clean_and_deduplicate_evidence_list(merged_ev_list, merged_diag_name) + existing_match.confidence_score = max(existing_match.confidence_score, s.confidence_score) + else: + if s_code and s_code not in ("None", "[NO LOCAL CODE]"): + seen_sec_codes.add(s_code) + if s_clean_norm: + seen_sec_names.add(s_clean_norm) + # Clean and deduplicate evidence on this secondary + s.evidence_quote = clean_and_deduplicate_evidence_quote(s.evidence_quote, s_name) + s.evidence = clean_and_deduplicate_evidence_list(getattr(s, "evidence", []) or s.evidence_quote, s_name) + deduped_secondaries.append(s) + + secondary_responses = deduped_secondaries + + # Drop conditions from abstentions that are ALREADY coded in primary or secondaries + coded_names: set[str] = set() + if primary_response: + p_n = primary_response.normalized_diagnosis or primary_response.raw_term or primary_response.description or "" + coded_names.add(p_n.lower().strip()) + coded_names.add((normalize_diagnosis_name(p_n) or p_n).lower().strip()) + for s in secondary_responses: + s_n = s.normalized_diagnosis or s.raw_term or s.description or "" + coded_names.add(s_n.lower().strip()) + coded_names.add((normalize_diagnosis_name(s_n) or s_n).lower().strip()) + + deduped_abstentions: list[AbstentionRecord] = [] + seen_abst_terms: set[str] = set() + for abst in abstentions: + a_term = (abst.raw_term or "").strip() + if not a_term: + continue + a_norm = a_term.lower().strip() + a_clean = (normalize_diagnosis_name(a_term) or a_term).lower().strip() + if a_norm in coded_names or a_clean in coded_names: + continue + if a_clean in seen_abst_terms or a_norm in seen_abst_terms: + continue + seen_abst_terms.add(a_clean) + seen_abst_terms.add(a_norm) + deduped_abstentions.append(abst) + abstentions = deduped_abstentions # Determine execution status if primary_response or secondary_responses: diff --git a/src/medical_coding/schemas/response.py b/src/medical_coding/schemas/response.py index 8e1c868..b69d3d7 100644 --- a/src/medical_coding/schemas/response.py +++ b/src/medical_coding/schemas/response.py @@ -1,5 +1,6 @@ """Final deterministic JSON output models and API request/response schemas.""" +import re from typing import Any, Literal from pydantic import BaseModel, Field, model_validator @@ -171,12 +172,123 @@ class CodingResult(BaseModel): @model_validator(mode="after") def verify_primary_constraint(self) -> "CodingResult": - """Enforce strict invariant: primary diagnosis must have PRIMARY role if present.""" + """Enforce strict invariant: primary diagnosis must have PRIMARY role if present, + and drop duplicates and repetitive evidences across diagnoses, abstentions, and procedures. + """ if self.primary_diagnosis and self.primary_diagnosis.role != DiagnosisRole.PRIMARY: raise ValueError("Primary diagnosis must have role PRIMARY") for sec in self.secondary_diagnoses: if sec.role == DiagnosisRole.PRIMARY: raise ValueError("Secondary diagnoses cannot have role PRIMARY") + + from medical_coding.utils.text import ( + clean_and_deduplicate_evidence_list, + clean_and_deduplicate_evidence_quote, + normalize_diagnosis_name, + ) + + # 1. Clean and deduplicate primary evidence + pri_code = "" + pri_clean_norm = "" + if self.primary_diagnosis: + p = self.primary_diagnosis + p_name = p.normalized_diagnosis or p.raw_term or p.description or "" + p.evidence_quote = clean_and_deduplicate_evidence_quote(p.evidence_quote, p_name) + p.evidence = clean_and_deduplicate_evidence_list(getattr(p, "evidence", []) or p.evidence_quote, p_name) + pri_code = (p.code or getattr(p, "database_code", "") or "").strip() + pri_norm = (p_name or "").lower().strip() + pri_clean_norm = (normalize_diagnosis_name(pri_norm) or pri_norm).lower().strip() + + # 2. Deduplicate secondary diagnoses against primary and among themselves + deduped_secondaries: list[CodedDiagnosisResponse] = [] + seen_sec_codes: set[str] = set() + seen_sec_names: set[str] = set() + + for s in (self.secondary_diagnoses or []): + s_code = (s.code or getattr(s, "database_code", "") or "").strip() + s_name = (s.normalized_diagnosis or s.raw_term or s.description or "").strip() + s_norm = s_name.lower().strip() + s_clean_norm = (normalize_diagnosis_name(s_norm) or s_norm).lower().strip() + + # Skip secondary if it duplicates the primary diagnosis + if pri_code and s_code and s_code == pri_code: + continue + if pri_clean_norm and s_clean_norm and pri_clean_norm == s_clean_norm: + continue + + # Check if already seen among secondaries + existing_match: CodedDiagnosisResponse | None = None + if s_code and s_code not in ("None", "[NO LOCAL CODE]") and s_code in seen_sec_codes: + existing_match = next((x for x in deduped_secondaries if (x.code or "").strip() == s_code), None) + elif s_clean_norm and s_clean_norm in seen_sec_names: + existing_match = next( + (x for x in deduped_secondaries if (normalize_diagnosis_name(x.normalized_diagnosis or x.raw_term or x.description or "") or "").lower().strip() == s_clean_norm), + None, + ) + + if existing_match: + # Merge evidence cleanly without repetition + combined_ev = f"{existing_match.evidence_quote or ''} | {s.evidence_quote or ''}".strip(" |") + merged_diag_name = existing_match.normalized_diagnosis or existing_match.description + existing_match.evidence_quote = clean_and_deduplicate_evidence_quote(combined_ev, merged_diag_name) + merged_ev_list = (getattr(existing_match, "evidence", []) or []) + (getattr(s, "evidence", []) or []) + existing_match.evidence = clean_and_deduplicate_evidence_list(merged_ev_list, merged_diag_name) + existing_match.confidence_score = max(existing_match.confidence_score, s.confidence_score) + else: + if s_code and s_code not in ("None", "[NO LOCAL CODE]"): + seen_sec_codes.add(s_code) + if s_clean_norm: + seen_sec_names.add(s_clean_norm) + # Clean evidence on this secondary + s.evidence_quote = clean_and_deduplicate_evidence_quote(s.evidence_quote, s_name) + s.evidence = clean_and_deduplicate_evidence_list(getattr(s, "evidence", []) or s.evidence_quote, s_name) + deduped_secondaries.append(s) + + self.secondary_diagnoses = deduped_secondaries + + # 3. Drop conditions from abstentions that are ALREADY coded in primary or secondaries + coded_names: set[str] = set() + if self.primary_diagnosis: + p_n = self.primary_diagnosis.normalized_diagnosis or self.primary_diagnosis.raw_term or self.primary_diagnosis.description or "" + coded_names.add(p_n.lower().strip()) + coded_names.add((normalize_diagnosis_name(p_n) or p_n).lower().strip()) + for s in self.secondary_diagnoses: + s_n = s.normalized_diagnosis or s.raw_term or s.description or "" + coded_names.add(s_n.lower().strip()) + coded_names.add((normalize_diagnosis_name(s_n) or s_n).lower().strip()) + + deduped_abstentions = [] + seen_abst_terms: set[str] = set() + for abst in (self.abstentions or []): + a_term = (abst.raw_term or "").strip() + if not a_term: + continue + a_norm = a_term.lower().strip() + a_clean = (normalize_diagnosis_name(a_term) or a_term).lower().strip() + if a_norm in coded_names or a_clean in coded_names: + continue + if a_clean in seen_abst_terms or a_norm in seen_abst_terms: + continue + seen_abst_terms.add(a_clean) + seen_abst_terms.add(a_norm) + deduped_abstentions.append(abst) + self.abstentions = deduped_abstentions + + # 4. Deduplicate procedures + deduped_procs: list[str] = [] + seen_procs: set[str] = set() + for proc in (self.procedures or []): + p_str = proc.strip() + if not p_str: + continue + clean_p = re.sub(r"\[.*?\]", "", p_str).lower().strip() + clean_p = re.sub(r"\s+", " ", clean_p) + if clean_p in seen_procs: + continue + seen_procs.add(clean_p) + deduped_procs.append(p_str) + self.procedures = deduped_procs + return self def format_output(self) -> str: @@ -185,33 +297,24 @@ class CodingResult(BaseModel): secondary diagnosises: diagnosis: , code: , evidence: """ - def _clean_ev(text: str | None) -> str: - if not text: - return "None" - clean = str(text).strip() - if "Designated as " in clean: - clean = clean.split("Designated as ")[0].strip(" -|:\n") - return clean if clean else "None" + from medical_coding.utils.text import clean_and_deduplicate_evidence_quote def _get_cand_ev(cand: Any) -> str: - quotes: list[str] = [] - ev_list = getattr(cand, "evidence", []) or [] - if isinstance(ev_list, list): - for item in ev_list: - q = "" - if isinstance(item, dict): - q = _clean_ev(item.get("quote")) - elif hasattr(item, "text"): - q = _clean_ev(item.text) - elif hasattr(item, "sentence"): - q = _clean_ev(item.sentence) - elif isinstance(item, str): - q = _clean_ev(item) - if q and q != "None" and q not in quotes: - quotes.append(q) - if quotes: - return " | ".join(quotes) - return _clean_ev(getattr(cand, "evidence_quote", None)) + raw_ev = getattr(cand, "evidence_quote", None) + if not raw_ev: + ev_list = getattr(cand, "evidence", []) or [] + if isinstance(ev_list, list): + quotes = [] + for item in ev_list: + if isinstance(item, dict): + quotes.append(str(item.get("quote", ""))) + elif hasattr(item, "quote"): + quotes.append(str(getattr(item, "quote", ""))) + elif isinstance(item, str): + quotes.append(item) + raw_ev = " | ".join(q for q in quotes if q) + diag_name = getattr(cand, "normalized_diagnosis", None) or getattr(cand, "raw_term", None) or getattr(cand, "description", None) + return clean_and_deduplicate_evidence_quote(raw_ev, diag_name) def _get_formatted_code(cand: Any) -> str: base_code = getattr(cand, "icd10cm", None) or cand.code or "" @@ -238,10 +341,22 @@ class CodingResult(BaseModel): else: lines.append("primary diagnosis: None, code: None, evidence: None") - coded_secondaries = [ - s for s in (self.secondary_diagnoses or []) - if s.code and s.code != "None" and s.matching_status != "NO_DATABASE_MATCH" - ] + # Deduplicate coded secondaries for printing + seen_codes: set[str] = set() + seen_names: set[str] = set() + coded_secondaries = [] + for s in (self.secondary_diagnoses or []): + if not s.code or s.code == "None" or s.matching_status == "NO_DATABASE_MATCH": + continue + code_key = s.code.strip() + name_key = (s.normalized_diagnosis or s.raw_term or s.description or "").lower().strip() + if code_key in seen_codes or (name_key and name_key in seen_names): + continue + seen_codes.add(code_key) + if name_key: + seen_names.add(name_key) + coded_secondaries.append(s) + if coded_secondaries: lines.append("secondary diagnosises:") for s in coded_secondaries: diff --git a/src/medical_coding/ui/app.py b/src/medical_coding/ui/app.py index b22ac6e..233b64a 100644 --- a/src/medical_coding/ui/app.py +++ b/src/medical_coding/ui/app.py @@ -153,37 +153,31 @@ def format_coding_result(result: Any) -> str: secondary diagnosises: diagnosis: , code: , evidence: """ - def _clean_ev(text: str | None) -> str: - if not text: - return "None" - clean = str(text).strip() - if "Designated as " in clean: - clean = clean.split("Designated as ")[0].strip(" -|:\n") - return clean if clean else "None" + if hasattr(result, "format_output") and callable(getattr(result, "format_output")): + return result.format_output() + + from medical_coding.utils.text import clean_and_deduplicate_evidence_quote def _get_cand_ev(cand: Any) -> str: - quotes: list[str] = [] - ev_list = getattr(cand, "evidence", []) or [] - if isinstance(ev_list, list): - for item in ev_list: - q = "" - if isinstance(item, dict): - q = _clean_ev(item.get("quote")) - elif hasattr(item, "text"): - q = _clean_ev(item.text) - elif hasattr(item, "sentence"): - q = _clean_ev(item.sentence) - elif isinstance(item, str): - q = _clean_ev(item) - if q and q != "None" and q not in quotes: - quotes.append(q) - if quotes: - return " | ".join(quotes) - return _clean_ev(getattr(cand, "evidence_quote", None)) + raw_ev = getattr(cand, "evidence_quote", None) + if not raw_ev: + ev_list = getattr(cand, "evidence", []) or [] + if isinstance(ev_list, list): + quotes = [] + for item in ev_list: + if isinstance(item, dict): + quotes.append(str(item.get("quote", ""))) + elif hasattr(item, "quote"): + quotes.append(str(getattr(item, "quote", ""))) + elif isinstance(item, str): + quotes.append(item) + raw_ev = " | ".join(q for q in quotes if q) + diag_name = getattr(cand, "normalized_diagnosis", None) or getattr(cand, "raw_term", None) or getattr(cand, "description", None) + return clean_and_deduplicate_evidence_quote(raw_ev, diag_name) lines = [] p = getattr(result, "primary_diagnosis", None) - if p: + if p and getattr(p, "code", None) and getattr(p, "code") != "None": p_name = getattr(p, "normalized_diagnosis", None) or getattr(p, "raw_term", None) or getattr(p, "description", None) or "None" p_code = getattr(p, "code", None) or getattr(p, "icd10cm", None) or "None" p_ev = _get_cand_ev(p) @@ -191,7 +185,22 @@ def format_coding_result(result: Any) -> str: else: lines.append("primary diagnosis: None, code: None, evidence: None") - secondaries = getattr(result, "secondary_diagnoses", []) or [] + raw_secondaries = getattr(result, "secondary_diagnoses", []) or [] + seen_codes: set[str] = set() + seen_names: set[str] = set() + secondaries = [] + for s in raw_secondaries: + s_code = (getattr(s, "code", None) or getattr(s, "icd10cm", None) or "").strip() + if not s_code or s_code == "None": + continue + s_name = (getattr(s, "normalized_diagnosis", None) or getattr(s, "raw_term", None) or getattr(s, "description", None) or "").lower().strip() + if s_code in seen_codes or (s_name and s_name in seen_names): + continue + seen_codes.add(s_code) + if s_name: + seen_names.add(s_name) + secondaries.append(s) + if secondaries: lines.append("secondary diagnosises:") for s in secondaries: diff --git a/src/medical_coding/ui/components.py b/src/medical_coding/ui/components.py index 1d8329b..3cf42df 100644 --- a/src/medical_coding/ui/components.py +++ b/src/medical_coding/ui/components.py @@ -176,13 +176,15 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None: documented_row = f'
🩺 Documented Clinical Diagnosis: {html.escape(str(primary.raw_term))}
' safe_desc = html.escape(primary.description or "") - raw_quote = _clean_audit_from_evidence(primary.evidence_quote or "") - if " | " in raw_quote: - spans = [_clean_audit_from_evidence(s) for s in raw_quote.split(" | ") if _clean_audit_from_evidence(s)] + from medical_coding.utils.text import deduplicate_evidence_spans + spans = deduplicate_evidence_spans(primary.evidence_quote, primary.normalized_diagnosis or primary.description) + if len(spans) > 1: spans_html = "".join(f'
• {html.escape(s)}
' for s in spans) evidence_content_html = spans_html + elif spans: + evidence_content_html = f'"{html.escape(spans[0])}"' else: - evidence_content_html = f'"{html.escape(raw_quote)}"' + evidence_content_html = '"None"' primary_html = clean_html( f""" @@ -223,10 +225,24 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None: def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> None: """Render the list of validated secondary comorbid diagnoses.""" - valid_secondaries = [ - s for s in (secondaries or []) - if s.code and s.code not in ("None", "[NO LOCAL CODE]") and s.matching_status != "NO_DATABASE_MATCH" - ] + from medical_coding.utils.text import deduplicate_evidence_spans, normalize_diagnosis_name + + # Deduplicate secondaries by code and clean concept + seen_sec_codes: set[str] = set() + seen_sec_names: set[str] = set() + valid_secondaries: list[CodedDiagnosisResponse] = [] + for s in (secondaries or []): + if not s.code or s.code in ("None", "[NO LOCAL CODE]") or s.matching_status == "NO_DATABASE_MATCH": + continue + c_key = s.code.strip() + n_key = (normalize_diagnosis_name(s.normalized_diagnosis or s.raw_term or s.description or "") or "").strip().lower() + if c_key in seen_sec_codes or (n_key and n_key in seen_sec_names): + continue + seen_sec_codes.add(c_key) + if n_key: + seen_sec_names.add(n_key) + valid_secondaries.append(s) + st.markdown(f"### 📋 Secondary Diagnoses ({len(valid_secondaries)})") if not valid_secondaries: st.write("No secondary comorbid diagnoses identified.") @@ -257,13 +273,14 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non documented_row = f'
🩺 Documented Diagnosis: {html.escape(str(diag.raw_term))}
' safe_desc = html.escape(diag.description or "") - raw_sec_quote = _clean_audit_from_evidence(diag.evidence_quote or "") - if " | " in raw_sec_quote: - spans = [_clean_audit_from_evidence(s) for s in raw_sec_quote.split(" | ") if _clean_audit_from_evidence(s)] + spans = deduplicate_evidence_spans(diag.evidence_quote, diag.normalized_diagnosis or diag.description) + if len(spans) > 1: spans_html = "".join(f'
• {html.escape(s)}
' for s in spans) sec_evidence_html = spans_html + elif spans: + sec_evidence_html = f'"{html.escape(spans[0])}"' else: - sec_evidence_html = f'"{html.escape(raw_sec_quote)}"' + sec_evidence_html = '"None"' secondary_html = clean_html( f""" @@ -300,9 +317,27 @@ def render_abstentions(abstentions: list[AbstentionRecord]) -> None: if not abstentions: return - with st.expander(f"🚫 Audited Abstentions & Rule-Outs ({len(abstentions)})", expanded=True): + # Deduplicate abstentions + from medical_coding.utils.text import normalize_diagnosis_name + deduped_abst: list[AbstentionRecord] = [] + seen_abst: set[str] = set() + for abst in abstentions: + term = (abst.raw_term or "").strip() + if not term: + continue + norm_t = (normalize_diagnosis_name(term) or term).lower().strip() + if norm_t in seen_abst or term.lower() in seen_abst: + continue + seen_abst.add(norm_t) + seen_abst.add(term.lower()) + deduped_abst.append(abst) + + if not deduped_abst: + return + + with st.expander(f"🚫 Audited Abstentions & Rule-Outs ({len(deduped_abst)})", expanded=True): st.caption("Conditions detected in documentation that were strictly abstained or excluded under ICD-10 guidelines:") - for abst in abstentions: + for abst in deduped_abst: reason_str = abst.reason.value if hasattr(abst.reason, "value") else str(abst.reason) stage_str = abst.stage.value if hasattr(abst.stage, "value") else str(abst.stage) raw_term = abst.raw_term or "Unspecified Entity" diff --git a/src/medical_coding/utils/text.py b/src/medical_coding/utils/text.py index e46eb14..60bb9d7 100644 --- a/src/medical_coding/utils/text.py +++ b/src/medical_coding/utils/text.py @@ -1,6 +1,7 @@ """Text processing, span extraction, and ICD string normalization utilities.""" import re +from typing import Any def normalize_whitespace(text: str) -> str: @@ -245,3 +246,151 @@ def extract_search_query_variations(raw_term: str, evidence: str = "") -> list[s return variations + +def deduplicate_evidence_spans( + evidence_items: list[Any] | str | None, + diagnosis_name: str | None = None, +) -> list[str]: + """Clean and deduplicate evidence strings, removing identical repeats, + subsumed substrings, bare diagnosis label headers, and audit boilerplate. + + Preserves unique clinical evidence statements in chronological order. + """ + if not evidence_items: + return [] + + # 1. Flatten all items into raw candidate text chunks + raw_chunks: list[str] = [] + if isinstance(evidence_items, str): + for part in re.split(r"\s*\|\s*|\n+", evidence_items): + if part.strip(): + raw_chunks.append(part.strip()) + elif isinstance(evidence_items, list): + for item in evidence_items: + q = "" + if isinstance(item, dict): + q = str(item.get("quote") or item.get("text") or item.get("sentence") or "") + elif hasattr(item, "quote"): + q = str(getattr(item, "quote") or "") + elif hasattr(item, "text"): + q = str(getattr(item, "text") or "") + elif hasattr(item, "sentence"): + q = str(getattr(item, "sentence") or "") + elif isinstance(item, str): + q = item + if q.strip(): + for part in re.split(r"\s*\|\s*|\n+", q): + if part.strip(): + raw_chunks.append(part.strip()) + else: + q_str = str(evidence_items).strip() + if q_str: + raw_chunks.append(q_str) + + # 2. Clean each chunk of audit boilerplate and wrappers + cleaned_chunks: list[str] = [] + for chunk in raw_chunks: + c = chunk.strip() + if not c or c.lower() in ("none", "null", "undefined", "[no local code]"): + continue + # Strip internal audit annotations + if "Designated as " in c: + c = c.split("Designated as ")[0].strip(" -|:\n") + if "Clinical criteria:" in c: + c = c.split("Clinical criteria:")[0].strip(" -|:\n") + if "Confidence:" in c: + c = c.split("Confidence:")[0].strip(" -|:\n") + # Strip quotes and bullet markers + c = c.strip(" \"'“”`•–-*#\t\r\n") + c = c.rstrip(":") + if c and c.lower() not in ("none", "null"): + cleaned_chunks.append(c) + + if not cleaned_chunks: + return [] + + # 3. Normalized comparison helper + def _norm(s: str) -> str: + s_low = s.lower().strip() + return re.sub(r"[^\w\s]", "", s_low).strip() + + diag_norm = _norm(diagnosis_name) if diagnosis_name else "" + + # 4. Remove bare diagnosis label if more detailed narrative sentences exist + has_descriptive_evidence = any( + len(_norm(c).split()) >= 4 and _norm(c) != diag_norm for c in cleaned_chunks + ) + + filtered_chunks: list[str] = [] + for c in cleaned_chunks: + c_norm = _norm(c) + if not c_norm: + continue + if diag_norm and c_norm == diag_norm and has_descriptive_evidence: + # Skip bare header match when descriptive narrative evidence is present + continue + filtered_chunks.append(c) + + if not filtered_chunks: + filtered_chunks = cleaned_chunks + + # 5. Deduplicate exact and subsumed chunks (keeping longer/more informative spans) + unique_spans: list[str] = [] + for cand in filtered_chunks: + cand_norm = _norm(cand) + if not cand_norm: + continue + + is_subsumed = False + replace_index = -1 + + for i, existing in enumerate(unique_spans): + ex_norm = _norm(existing) + # Exact duplicate + if cand_norm == ex_norm: + is_subsumed = True + break + # cand is substring of existing + if cand_norm in ex_norm and len(cand_norm) < len(ex_norm): + is_subsumed = True + break + # existing is substring of cand -> cand is more descriptive + if ex_norm in cand_norm and len(ex_norm) < len(cand_norm): + replace_index = i + break + + if replace_index >= 0: + unique_spans[replace_index] = cand + elif not is_subsumed: + unique_spans.append(cand) + + return unique_spans + + +def clean_and_deduplicate_evidence_quote( + evidence_text: Any, + diagnosis_name: str | None = None, +) -> str: + """Return a single cleaned, non-repetitive evidence string joined by ' | '.""" + if not evidence_text: + return "None" + spans = deduplicate_evidence_spans(evidence_text, diagnosis_name=diagnosis_name) + return " | ".join(spans) if spans else "None" + + +def clean_and_deduplicate_evidence_list( + evidence_list: list[Any] | str | None, + diagnosis_name: str | None = None, +) -> list[dict[str, Any]]: + """Return a list of deduplicated evidence dictionaries.""" + spans = deduplicate_evidence_spans(evidence_list, diagnosis_name=diagnosis_name) + return [ + { + "quote": s, + "section": "CLINICAL_DOCUMENTATION", + "evidence_type": "CLINICAL_EVIDENCE", + } + for s in spans + ] + + diff --git a/tests/test_demo_fix_strengthened_classifier.py b/tests/test_demo_fix_strengthened_classifier.py index 87b84e2..4423ca3 100644 --- a/tests/test_demo_fix_strengthened_classifier.py +++ b/tests/test_demo_fix_strengthened_classifier.py @@ -15,10 +15,13 @@ from medical_coding.models.factory import FastLocalEmbeddings from medical_coding.dataset.validator import LocalICDCatalog from medical_coding.schemas.clinical import ContextAssessment from medical_coding.schemas.enums import ( + Acuity, Certainty, ConditionStatus, DiagnosisRole, + ExecutionStatus, NegationStatus, + PipelineStage, Temporality, AbstentionReason, ) @@ -298,3 +301,157 @@ def test_finalize_output_node_rechecks_abstentions_with_positive_evidence( assert any(c.database_code == "I10" for c in coded_all) # Abstention list must be cleared of the recovered condition assert not any(a.raw_term == "K/C/O Primary hypertension on medication" for a in res.abstentions) + + +# ============================================================================== +# 4. DUPLICATE AND REPETITIVE EVIDENCE CLEANING TESTS +# ============================================================================== + + +def test_deduplicate_evidence_spans_and_clean_repetition() -> None: + """Verify that repetitive evidence strings, substrings, and bare headers are cleanly removed.""" + from medical_coding.utils.text import ( + clean_and_deduplicate_evidence_quote, + deduplicate_evidence_spans, + ) + + # 1. Bare diagnosis header with narrative evidence -> header dropped + raw_ev = "Acute cholecystitis | Patient was admitted with acute RUQ pain and fever, confirmed acute cholecystitis on ultrasound. | Underwent successful laparoscopic cholecystectomy." + spans = deduplicate_evidence_spans(raw_ev, diagnosis_name="Acute cholecystitis") + assert len(spans) == 2 + assert "Acute cholecystitis" not in spans + assert "Patient was admitted with acute RUQ pain and fever, confirmed acute cholecystitis on ultrasound." in spans + assert "Underwent successful laparoscopic cholecystectomy." in spans + + # 2. Identical repeats + raw_ev2 = "Blood pressure maintained on lisinopril for hypertension. | Blood pressure maintained on lisinopril for hypertension." + spans2 = deduplicate_evidence_spans(raw_ev2) + assert len(spans2) == 1 + assert spans2[0] == "Blood pressure maintained on lisinopril for hypertension." + + # 3. Subsumed substring + raw_ev3 = ["Patient presented with chest pain", "Patient presented with chest pain and shortness of breath"] + spans3 = deduplicate_evidence_spans(raw_ev3) + assert len(spans3) == 1 + assert spans3[0] == "Patient presented with chest pain and shortness of breath" + + # 4. Clean quote output + clean_q = clean_and_deduplicate_evidence_quote(raw_ev, diagnosis_name="Acute cholecystitis") + assert clean_q == "Patient was admitted with acute RUQ pain and fever, confirmed acute cholecystitis on ultrasound. | Underwent successful laparoscopic cholecystectomy." + + +def test_coding_result_deduplicates_secondaries_and_cleans_evidences() -> None: + """Verify that CodingResult drops duplicate secondary diagnoses, drops secondaries matching primary, and cleans repetitive evidence.""" + from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult + + primary = CodedDiagnosisResponse( + code="K81.0", + description="Acute cholecystitis", + role=DiagnosisRole.PRIMARY, + acuity=Acuity.ACUTE, + certainty=Certainty.CONFIRMED, + evidence_quote="Acute cholecystitis | Patient admitted for Acute cholecystitis with fever.", + confidence_score=0.95, + ) + + # Duplicate of primary (same code) + dup_pri_sec = CodedDiagnosisResponse( + code="K81.0", + description="Acute cholecystitis", + role=DiagnosisRole.SECONDARY, + acuity=Acuity.ACUTE, + certainty=Certainty.CONFIRMED, + evidence_quote="Patient admitted for Acute cholecystitis with fever.", + confidence_score=0.90, + ) + + # Two identical secondary entries with same code K80.80 + sec1 = CodedDiagnosisResponse( + code="K80.80", + description="Other cholelithiasis without obstruction", + role=DiagnosisRole.SECONDARY, + acuity=Acuity.CHRONIC, + certainty=Certainty.CONFIRMED, + evidence_quote="Gallstones noted on ultrasound.", + confidence_score=0.75, + ) + sec2 = CodedDiagnosisResponse( + code="K80.80", + description="Other cholelithiasis without obstruction", + role=DiagnosisRole.SECONDARY, + acuity=Acuity.CHRONIC, + certainty=Certainty.CONFIRMED, + evidence_quote="Gallstones noted on ultrasound. | Cholelithiasis visualized.", + confidence_score=0.85, + ) + + # Valid different secondary + sec_htn = CodedDiagnosisResponse( + code="I10", + description="Essential (primary) hypertension", + role=DiagnosisRole.SECONDARY, + acuity=Acuity.CHRONIC, + certainty=Certainty.CONFIRMED, + evidence_quote="Hypertension on lisinopril. | Hypertension on lisinopril.", + confidence_score=0.90, + ) + + abstention_for_coded_cond = AbstentionRecord( + diagnosis_id="chole-abstained", + raw_term="Acute cholecystitis", # Already coded in primary! + reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, + detail="Old abstention record", + stage=PipelineStage.VALIDATION, + ) + + abstention_valid = AbstentionRecord( + diagnosis_id="rare-abstained", + raw_term="Uncoded rare condition", + reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE, + detail="No matching code", + stage=PipelineStage.VALIDATION, + ) + + result = CodingResult( + document_id="doc-dedup-test", + status=ExecutionStatus.SUCCESS, + primary_diagnosis=primary, + secondary_diagnoses=[dup_pri_sec, sec1, sec2, sec_htn], + abstentions=[abstention_for_coded_cond, abstention_valid], + procedures=["Laparoscopic cholecystectomy [CPT: 47600]", "Laparoscopic cholecystectomy"], + processing_time_ms=10.0, + ) + + # 1. Primary evidence should be deduplicated (bare header removed) + assert result.primary_diagnosis is not None + assert result.primary_diagnosis.evidence_quote == "Patient admitted for Acute cholecystitis with fever." + + # 2. Secondary list must NOT contain duplicate of primary + assert not any(s.code == "K81.0" for s in result.secondary_diagnoses) + + # 3. K80.80 must appear exactly ONCE (deduplicated) + k80_matches = [s for s in result.secondary_diagnoses if s.code == "K80.80"] + assert len(k80_matches) == 1 + # Evidence merged cleanly + assert "Gallstones noted on ultrasound." in k80_matches[0].evidence_quote + assert "Cholelithiasis visualized." in k80_matches[0].evidence_quote + # Confidence score is max (0.85) + assert k80_matches[0].confidence_score == 0.85 + + # 4. Hypertension repetitive evidence should be cleaned + htn_match = next(s for s in result.secondary_diagnoses if s.code == "I10") + assert htn_match.evidence_quote == "Hypertension on lisinopril." + + # 5. Abstention list must drop 'Acute cholecystitis' because it is coded + assert len(result.abstentions) == 1 + assert result.abstentions[0].raw_term == "Uncoded rare condition" + + # 6. Procedures must be deduplicated + assert len(result.procedures) == 1 + + # 7. Formatted output must have no duplicates + formatted = result.format_output() + assert formatted.count("code: K80.80") == 1 + assert formatted.count("code: I10") == 1 + assert "Hypertension on lisinopril. | Hypertension on lisinopril." not in formatted +