feat(matching): implement nearest relatable match fallback, organism parsing, and UI badge
This commit is contained in:
@@ -37,7 +37,7 @@ logger = get_logger(__name__)
|
|||||||
# Standard section header regexes
|
# Standard section header regexes
|
||||||
SECTION_PATTERNS: list[tuple[str, str]] = [
|
SECTION_PATTERNS: list[tuple[str, str]] = [
|
||||||
("DISCHARGE_SUMMARY", r"(?:HOSPITAL\s+DISCHARGE\s+SUMMARY|DISCHARGE\s+SUMMARY|CLINICAL\s+SUMMARY)"),
|
("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)"),
|
("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)"),
|
("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)"),
|
("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_start = m["content_start"]
|
||||||
content_end = matches[i + 1]["start_pos"] if i + 1 < len(matches) else len(text)
|
content_end = matches[i + 1]["start_pos"] if i + 1 < len(matches) else len(text)
|
||||||
content_str = text[content_start:content_end]
|
content_str = text[content_start:content_end]
|
||||||
|
if not content_str.strip() and i + 1 < len(matches):
|
||||||
|
continue
|
||||||
sections.append(
|
sections.append(
|
||||||
ClinicalDocumentSection(
|
ClinicalDocumentSection(
|
||||||
section_name=m["section_name"],
|
section_name=m["section_name"],
|
||||||
@@ -191,6 +193,40 @@ class SectionSegmenter:
|
|||||||
class EvidenceFirstFactExtractor:
|
class EvidenceFirstFactExtractor:
|
||||||
"""Extracts evidence-grounded clinical facts from partitioned document sections."""
|
"""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"(?<!\b[A-Za-z])(?<!\b\d)[.!?]+\s+(?=[A-Z0-9])", masked)
|
||||||
|
for s in sub_sents:
|
||||||
|
s_unmasked = EvidenceFirstFactExtractor._unprotect_organism_abbreviations(s.strip(), rep)
|
||||||
|
if s_unmasked:
|
||||||
|
sentences.append(s_unmasked)
|
||||||
|
return sentences
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
self._extracted_procedures: list[str] = []
|
self._extracted_procedures: list[str] = []
|
||||||
self._operative_findings: list[dict[str, Any]] = []
|
self._operative_findings: list[dict[str, Any]] = []
|
||||||
@@ -460,7 +496,7 @@ class EvidenceFirstFactExtractor:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
# Split into sentences or lines
|
# 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:
|
for sent in raw_sentences:
|
||||||
if len(sent) < 4:
|
if len(sent) < 4:
|
||||||
@@ -1014,7 +1050,7 @@ class EvidenceFirstFactExtractor:
|
|||||||
|
|
||||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
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:
|
for sent in sentences:
|
||||||
if (
|
if (
|
||||||
@@ -1026,49 +1062,51 @@ class EvidenceFirstFactExtractor:
|
|||||||
):
|
):
|
||||||
continue
|
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]"
|
# Pattern A: Complication cues: "course was complicated by [X]", "complicated by [X]", "developed [X]", "went into [X]", "manifested [X]"
|
||||||
comp_match = re.search(
|
comp_match = re.search(
|
||||||
r"(?:course\s+(?:was\s+)?complicated\s+by|complicated\s+by|developed|went\s+into|manifested|suffered)\s+([^.]+)",
|
r"(?:course\s+(?:was\s+)?complicated\s+by|complicated\s+by|developed|went\s+into|manifested|suffered)\s+([^.]+)",
|
||||||
sent,
|
masked_sent,
|
||||||
re.IGNORECASE,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
# Pattern B: Inpatient management/diagnosis: "treated for [X]", "managed for [X]", "diagnosed with [X]"
|
# Pattern B: Inpatient management/diagnosis: "treated for [X]", "managed for [X]", "diagnosed with [X]"
|
||||||
treat_match = re.search(
|
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+([^.]+)",
|
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,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
# Pattern C: Specialist evaluations, consultations, and clinical conclusions
|
# Pattern C: Specialist evaluations, consultations, and clinical conclusions
|
||||||
eval_match = re.search(
|
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*([^.]+)",
|
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,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
# Pattern D: Additional or concurrent conditions documented during course
|
# Pattern D: Additional or concurrent conditions documented during course
|
||||||
additional_match = re.search(
|
additional_match = re.search(
|
||||||
r"(?:with\s+additional|and\s+additional|additional|concurrent|superimposed)\s+([^.]+)",
|
r"(?:with\s+additional|and\s+additional|additional|concurrent|superimposed)\s+([^.]+)",
|
||||||
sent,
|
masked_sent,
|
||||||
re.IGNORECASE,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
|
|
||||||
matched_clauses: list[str] = []
|
matched_clauses: list[str] = []
|
||||||
if comp_match:
|
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:
|
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:
|
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:
|
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:
|
if not matched_clauses:
|
||||||
gen_match = re.search(
|
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+([^.]+)",
|
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,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
if gen_match:
|
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:
|
for clause in matched_clauses:
|
||||||
# Strip trailing management phrases from clause
|
# Strip trailing management phrases from clause
|
||||||
@@ -1172,7 +1210,7 @@ class EvidenceFirstFactExtractor:
|
|||||||
|
|
||||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
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:
|
for sent in sentences:
|
||||||
if (
|
if (
|
||||||
@@ -1185,24 +1223,39 @@ class EvidenceFirstFactExtractor:
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
findings_clauses: list[str] = []
|
findings_clauses: list[str] = []
|
||||||
|
masked_sent, rep = self._protect_organism_abbreviations(sent)
|
||||||
|
|
||||||
# 1. Imaging findings: CT, CXR, Ultrasound, MRI, Biopsy, EGD
|
# 1. Imaging findings: CT, CXR, Ultrasound, MRI, Biopsy, EGD
|
||||||
img_match = re.search(
|
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+([^.]+)",
|
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+([^.]+)",
|
||||||
sent,
|
masked_sent,
|
||||||
re.IGNORECASE,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
if img_match:
|
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
|
# 2. Microbiology / culture findings: blood culture, urine culture, sputum culture
|
||||||
micro_match = re.search(
|
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+([^.]+)",
|
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*([^.]+)",
|
||||||
sent,
|
masked_sent,
|
||||||
re.IGNORECASE,
|
re.IGNORECASE,
|
||||||
)
|
)
|
||||||
if micro_match:
|
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:
|
for clause in findings_clauses:
|
||||||
# Strip trailing notes or measures e.g. "causing hydronephrosis", "measuring 9mm", ">100,000 CFU/mL"
|
# 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:
|
if p2.lower() in generic_suffix_nouns:
|
||||||
continue
|
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)
|
v1, _ = HardClinicalCandidateGate.evaluate_candidate(p1)
|
||||||
v2, _ = HardClinicalCandidateGate.evaluate_candidate(p2)
|
v2, _ = HardClinicalCandidateGate.evaluate_candidate(p2_clean or p2)
|
||||||
|
|
||||||
if v1 and v2:
|
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()]
|
return [text.strip()]
|
||||||
|
|
||||||
@@ -1731,7 +1786,7 @@ class EvidenceFirstFactExtractor:
|
|||||||
|
|
||||||
# Temporary mask for genus abbreviations like E. coli, H. pylori, S. pneumoniae, C. difficile
|
# Temporary mask for genus abbreviations like E. coli, H. pylori, S. pneumoniae, C. difficile
|
||||||
masked = cleaned
|
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):
|
for i, m in enumerate(abbrev_matches):
|
||||||
masked = masked.replace(m.group(0), f"__ORGANISM_{i}__")
|
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}__")
|
masked = masked.replace(pm.group(0), f"__PLUS_MARKER_{i}__")
|
||||||
|
|
||||||
# 1. Connectors that unconditionally separate independent clinical entities
|
# 1. Connectors that unconditionally separate independent clinical entities
|
||||||
# Split on list delimiters: plus signs (+), semicolons (;), ampersands (&), and slashes (/) separating independent entities
|
# Split on list delimiters: commas (,), plus signs (+), semicolons (;), ampersands (&), and slashes (/)
|
||||||
list_delims_pattern = r"\s*(?:\+|;|\s+&\s+|\s+/\s+)\s*"
|
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()]
|
raw_splits = [p.strip() for p in re.split(list_delims_pattern, masked, flags=re.IGNORECASE) if p.strip()]
|
||||||
|
|
||||||
chunks: list[str] = []
|
chunks: list[str] = []
|
||||||
@@ -1788,9 +1843,12 @@ class EvidenceFirstFactExtractor:
|
|||||||
pre_with = chunk[:generic_with_m.start()].strip()
|
pre_with = chunk[:generic_with_m.start()].strip()
|
||||||
post_with = generic_with_m.group(1).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()
|
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
|
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||||
v_pre, _ = HardClinicalCandidateGate.evaluate_candidate(pre_with_clean or pre_with)
|
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:
|
if v_pre and v_post:
|
||||||
refined_chunks.append(pre_with_clean or pre_with)
|
refined_chunks.append(pre_with_clean or pre_with)
|
||||||
refined_chunks.append(post_with)
|
refined_chunks.append(post_with)
|
||||||
|
|||||||
@@ -658,6 +658,7 @@ class CandidateRankingAgent(BaseAgent):
|
|||||||
# If top candidate score is below min_confidence, or if top candidate has unsupported attributes:
|
# 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,
|
# Check if there is another candidate in candidate pool that is billable, has no unsupported attributes,
|
||||||
# and has core_match_fraction > 0.0
|
# and has core_match_fraction > 0.0
|
||||||
|
matching_status = "MATCHED"
|
||||||
if top_score < self.min_confidence:
|
if top_score < self.min_confidence:
|
||||||
fallback_cand = None
|
fallback_cand = None
|
||||||
for cand, s, rat in scored_candidates:
|
for cand, s, rat in scored_candidates:
|
||||||
@@ -674,6 +675,17 @@ class CandidateRankingAgent(BaseAgent):
|
|||||||
|
|
||||||
if fallback_cand:
|
if fallback_cand:
|
||||||
top_cand = 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:
|
else:
|
||||||
abstain_reason = (
|
abstain_reason = (
|
||||||
"UNSUPPORTED_SPECIFICITY"
|
"UNSUPPORTED_SPECIFICITY"
|
||||||
@@ -723,7 +735,7 @@ class CandidateRankingAgent(BaseAgent):
|
|||||||
supporting_evidence=[evidence_quote],
|
supporting_evidence=[evidence_quote],
|
||||||
confidence=max(0.0, min(1.0, round(top_score, 4))),
|
confidence=max(0.0, min(1.0, round(top_score, 4))),
|
||||||
abstention_reason=None,
|
abstention_reason=None,
|
||||||
matching_status="MATCHED",
|
matching_status=matching_status,
|
||||||
candidate_pool=candidates,
|
candidate_pool=candidates,
|
||||||
decision="ACCEPTED",
|
decision="ACCEPTED",
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1001,7 +1001,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
|||||||
description=item.description,
|
description=item.description,
|
||||||
database_code=item.code,
|
database_code=item.code,
|
||||||
database_description=item.description,
|
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_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),
|
source_span=getattr(item, "source_span", None) or getattr(item.evidence, "source_span", None),
|
||||||
role=item.role,
|
role=item.role,
|
||||||
@@ -1036,9 +1036,10 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
|||||||
elif item.role == DiagnosisRole.SECONDARY:
|
elif item.role == DiagnosisRole.SECONDARY:
|
||||||
secondary_responses.append(resp)
|
secondary_responses.append(resp)
|
||||||
|
|
||||||
|
catalog, retriever = get_or_initialize_retrieval_system()
|
||||||
|
|
||||||
# SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING (Sections 4 & 11)
|
# 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 diagnosis was clinically confirmed and established, but ICD mapping abstained or failed:
|
|
||||||
if primary_response is None:
|
if primary_response is None:
|
||||||
clin_primary = None
|
clin_primary = None
|
||||||
for c in classified:
|
for c in classified:
|
||||||
@@ -1050,7 +1051,56 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
|||||||
|
|
||||||
if clin_primary:
|
if clin_primary:
|
||||||
term = getattr(clin_primary, "normalized_diagnosis", None) or getattr(clin_primary, "raw_term", "")
|
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(
|
abstentions.append(
|
||||||
AbstentionRecord(
|
AbstentionRecord(
|
||||||
diagnosis_id=getattr(clin_primary, "diagnosis_id", "primary"),
|
diagnosis_id=getattr(clin_primary, "diagnosis_id", "primary"),
|
||||||
@@ -1060,7 +1110,7 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
|||||||
stage=PipelineStage.VALIDATION,
|
stage=PipelineStage.VALIDATION,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
if secondary_responses:
|
if not primary_response and secondary_responses:
|
||||||
# Promote top coded secondary to primary role
|
# Promote top coded secondary to primary role
|
||||||
primary_response = secondary_responses.pop(0)
|
primary_response = secondary_responses.pop(0)
|
||||||
primary_response.role = DiagnosisRole.PRIMARY
|
primary_response.role = DiagnosisRole.PRIMARY
|
||||||
@@ -1140,18 +1190,70 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
|||||||
if not is_valid_cand:
|
if not is_valid_cand:
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Clinical condition has no matching code in authoritative database; put strictly in abstain
|
# Per requirement: for [no_local_code] type diagnosis, nearest relatable code should get displayed, because they also have evidence
|
||||||
if not any(a.raw_term and a.raw_term.lower() == c_term.lower() for a in abstentions):
|
nearest_cand = None
|
||||||
abstentions.append(
|
cand_pool_item = state.get("candidate_pool", {}).get(getattr(c, "diagnosis_id", ""), [])
|
||||||
AbstentionRecord(
|
if cand_pool_item:
|
||||||
diagnosis_id=getattr(c, "diagnosis_id", "secondary"),
|
for cand in cand_pool_item:
|
||||||
raw_term=c_term,
|
if catalog.is_valid_code(cand.code) and catalog.is_billable_code(cand.code):
|
||||||
reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE,
|
nearest_cand = cand
|
||||||
detail=f"Condition '{c_term}' lacked verified local code match; strictly abstained under coding rules.",
|
break
|
||||||
stage=PipelineStage.VALIDATION,
|
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
|
# 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:
|
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
|
primary_response.role = DiagnosisRole.PRIMARY
|
||||||
secondary_responses = [s for s in secondary_responses if s.code != "Z71.1"]
|
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] = []
|
coded_secondaries: list[CodedDiagnosisResponse] = []
|
||||||
for s in secondary_responses:
|
for s in secondary_responses:
|
||||||
s_code = s.code or getattr(s, "database_code", None)
|
s_code = s.code or getattr(s, "database_code", None)
|
||||||
if s_code and s_code != "None" and s.matching_status != "NO_DATABASE_MATCH":
|
if s_code and s_code != "None" and s.matching_status != "NO_DATABASE_MATCH":
|
||||||
coded_secondaries.append(s)
|
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:
|
else:
|
||||||
s_name = s.normalized_diagnosis or s.raw_term or s.description or ""
|
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):
|
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
|
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:
|
if primary_response:
|
||||||
p_code = primary_response.code or getattr(primary_response, "database_code", None)
|
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":
|
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 ""
|
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):
|
if primary_response.evidence_quote and p_name:
|
||||||
abstentions.append(
|
retrieved = retriever.retrieve(p_name, top_k=5)
|
||||||
AbstentionRecord(
|
if retrieved:
|
||||||
diagnosis_id=getattr(primary_response, "diagnosis_id", "primary-abstained"),
|
top_r = retrieved[0]
|
||||||
raw_term=p_name,
|
primary_response.icd10cm = top_r.code
|
||||||
reason=AbstentionReason.NO_MATCHING_ICD_CANDIDATE,
|
primary_response.database_code = top_r.code
|
||||||
detail=f"Primary condition '{p_name}' lacked verified local code match; strictly abstained under coding rules.",
|
primary_response.database_description = top_r.description
|
||||||
stage=PipelineStage.VALIDATION,
|
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:
|
||||||
if secondary_responses:
|
primary_response = secondary_responses.pop(0)
|
||||||
primary_response = secondary_responses.pop(0)
|
primary_response.role = DiagnosisRole.PRIMARY
|
||||||
primary_response.role = DiagnosisRole.PRIMARY
|
else:
|
||||||
else:
|
primary_response = None
|
||||||
primary_response = None
|
|
||||||
|
|
||||||
# Enforce clean role separation: secondary section must NEVER duplicate the primary diagnosis
|
# Enforce clean role separation: secondary section must NEVER duplicate the primary diagnosis
|
||||||
if primary_response:
|
if primary_response:
|
||||||
|
|||||||
@@ -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"),
|
("myocardial_infarction", ["myocardial infarction", "nstemi", "stemi", "acute coronary syndrome", "subendocardial myocardial infarction", "heart attack"], "heart"),
|
||||||
("cholecystitis", ["cholecystitis", "acute cholecystitis", "chronic cholecystitis"], "gallbladder"),
|
("cholecystitis", ["cholecystitis", "acute cholecystitis", "chronic cholecystitis"], "gallbladder"),
|
||||||
("cholelithiasis", ["cholelithiasis", "gallstone", "gallstones", "calculus of gallbladder", "biliary calculus"], "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"),
|
("hyperlipidemia", ["hyperlipidemia", "hypercholesterolemia", "dyslipidemia", "hypertriglyceridemia"], "blood"),
|
||||||
("hypokalemia", ["hypokalemia", "hypopotassemia"], "blood"),
|
("hypokalemia", ["hypokalemia", "hypopotassemia"], "blood"),
|
||||||
("hyperkalemia", ["hyperkalemia"], "blood"),
|
("hyperkalemia", ["hyperkalemia"], "blood"),
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ FAMILY_TO_CODE_PREFIXES: dict[str, list[str]] = {
|
|||||||
"myocardial_infarction": ["I21", "I22"],
|
"myocardial_infarction": ["I21", "I22"],
|
||||||
"cholecystitis": ["K81", "K80"],
|
"cholecystitis": ["K81", "K80"],
|
||||||
"cholelithiasis": ["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"],
|
"hyperlipidemia": ["E78"],
|
||||||
"hypokalemia": ["E87.6", "E87"],
|
"hypokalemia": ["E87.6", "E87"],
|
||||||
"hyperkalemia": ["E87.5", "E87"],
|
"hyperkalemia": ["E87.5", "E87"],
|
||||||
|
|||||||
@@ -52,6 +52,10 @@ CLINICAL_ABBREVIATIONS: dict[str, str] = {
|
|||||||
"dns": "deviated nasal septum",
|
"dns": "deviated nasal septum",
|
||||||
"fess": "functional endoscopic sinus surgery sinus endoscopy",
|
"fess": "functional endoscopic sinus surgery sinus endoscopy",
|
||||||
"ith": "inferior turbinate hypertrophy",
|
"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.)
|
# 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"],
|
"turbinates": ["turbinate", "nasal", "nose"],
|
||||||
"nasal": ["nose", "turbinate", "turbinates", "septum"],
|
"nasal": ["nose", "turbinate", "turbinates", "septum"],
|
||||||
"septum": ["nasal", "nose"],
|
"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"],
|
"pneumonia": ["pneumonitis", "pna"],
|
||||||
"hypertension": ["htn", "high blood pressure"],
|
"hypertension": ["htn", "high blood pressure"],
|
||||||
"diabetes": ["dm", "diabetic"],
|
"diabetes": ["dm", "diabetic"],
|
||||||
|
|||||||
@@ -268,9 +268,9 @@ class RankedSelection(BaseModel):
|
|||||||
description="Outcome of candidate evaluation.",
|
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",
|
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(
|
source_section: str | None = Field(
|
||||||
default=None,
|
default=None,
|
||||||
|
|||||||
@@ -56,9 +56,9 @@ class CodedDiagnosisResponse(BaseModel):
|
|||||||
default=None,
|
default=None,
|
||||||
description="Matched CPT procedural code if matched, None if not.",
|
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",
|
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(
|
database_code: str | None = Field(
|
||||||
default=None,
|
default=None,
|
||||||
|
|||||||
@@ -243,12 +243,8 @@ def render_coding_session_results(
|
|||||||
error_traceback=tb_str,
|
error_traceback=tb_str,
|
||||||
duration_ms=coding_result.processing_time_ms,
|
duration_ms=coding_result.processing_time_ms,
|
||||||
)
|
)
|
||||||
render_process_oversight_timeline(steps_data, coding_result.processing_time_ms)
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# Render Node-by-Node Process Oversight & Latency Timeline
|
|
||||||
render_process_oversight_timeline(steps_data, coding_result.processing_time_ms)
|
|
||||||
|
|
||||||
# High-Level KPIs
|
# High-Level KPIs
|
||||||
st.markdown("### 📊 Coding Decisions & Evidence Audit")
|
st.markdown("### 📊 Coding Decisions & Evidence Audit")
|
||||||
render_kpi_metrics(coding_result)
|
render_kpi_metrics(coding_result)
|
||||||
|
|||||||
@@ -63,7 +63,7 @@ def render_header(
|
|||||||
|
|
||||||
def render_kpi_metrics(result: CodingResult) -> None:
|
def render_kpi_metrics(result: CodingResult) -> None:
|
||||||
"""Render high-level KPIs for a single document coding run."""
|
"""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_str = result.status.value if hasattr(result.status, "value") else str(result.status)
|
||||||
status_class = (
|
status_class = (
|
||||||
@@ -131,19 +131,6 @@ def render_kpi_metrics(result: CodingResult) -> None:
|
|||||||
unsafe_allow_html=True,
|
unsafe_allow_html=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
with c5:
|
|
||||||
st.markdown(
|
|
||||||
clean_html(
|
|
||||||
f"""
|
|
||||||
<div class="kpi-card">
|
|
||||||
<div class="kpi-label">Processing Time</div>
|
|
||||||
<div class="kpi-value">{result.processing_time_ms:.1f}<span style="font-size: 13px; font-weight: normal; color: #94a3b8;"> ms</span></div>
|
|
||||||
</div>
|
|
||||||
"""
|
|
||||||
),
|
|
||||||
unsafe_allow_html=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _clean_audit_from_evidence(ev: str) -> str:
|
def _clean_audit_from_evidence(ev: str) -> str:
|
||||||
"""Clean internal audit justifications and boilerplate from display evidence strings."""
|
"""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'<span class="pill-badge badge-info">{html.escape(primary.acuity.value if hasattr(primary.acuity, "value") else str(primary.acuity))}</span>'
|
acuity_badge = f'<span class="pill-badge badge-info">{html.escape(primary.acuity.value if hasattr(primary.acuity, "value") else str(primary.acuity))}</span>'
|
||||||
certainty_badge = f'<span class="pill-badge badge-secondary">{html.escape(primary.certainty.value if hasattr(primary.certainty, "value") else str(primary.certainty))}</span>'
|
certainty_badge = f'<span class="pill-badge badge-secondary">{html.escape(primary.certainty.value if hasattr(primary.certainty, "value") else str(primary.certainty))}</span>'
|
||||||
|
nearest_badge = '<span class="pill-badge badge-warning">Nearest Relatable Match</span>' if getattr(primary, "matching_status", "") == "NEAREST_MATCH" else ""
|
||||||
|
|
||||||
conf_pct = int(primary.confidence_score * 100)
|
conf_pct = int(primary.confidence_score * 100)
|
||||||
|
|
||||||
@@ -217,6 +205,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
|||||||
<div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
|
<div style="display: flex; gap: 8px; margin: 10px 0; flex-wrap: wrap;">
|
||||||
{acuity_badge}
|
{acuity_badge}
|
||||||
{certainty_badge}
|
{certainty_badge}
|
||||||
|
{nearest_badge}
|
||||||
<span class="pill-badge badge-info">Chief Reason for Encounter</span>
|
<span class="pill-badge badge-info">Chief Reason for Encounter</span>
|
||||||
{codes_html}
|
{codes_html}
|
||||||
</div>
|
</div>
|
||||||
@@ -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))
|
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))
|
certainty_str = html.escape(diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty))
|
||||||
|
nearest_badge = '<span class="pill-badge badge-warning">Nearest Relatable Match</span>' if getattr(diag, "matching_status", "") == "NEAREST_MATCH" else ""
|
||||||
|
|
||||||
sec_codes_pills = []
|
sec_codes_pills = []
|
||||||
if diag.icd10cm:
|
if diag.icd10cm:
|
||||||
@@ -286,6 +276,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
|
|||||||
</div>
|
</div>
|
||||||
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
|
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
|
||||||
{billable_badge}
|
{billable_badge}
|
||||||
|
{nearest_badge}
|
||||||
<span class="pill-badge badge-secondary">{acuity_str}</span>
|
<span class="pill-badge badge-secondary">{acuity_str}</span>
|
||||||
<span class="pill-badge badge-secondary">{certainty_str}</span>
|
<span class="pill-badge badge-secondary">{certainty_str}</span>
|
||||||
{sec_codes_html}
|
{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:
|
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."""
|
"""Render a comprehensive process oversight timeline (suppressed per user specification)."""
|
||||||
if not steps:
|
return
|
||||||
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 = '<span class="pill-badge badge-success">✓ PASSED</span>'
|
|
||||||
row_class = "step-row"
|
|
||||||
status_icon = "🟢"
|
|
||||||
elif status == "FAILED":
|
|
||||||
status_badge = '<span class="pill-badge badge-danger">✗ FAILED</span>'
|
|
||||||
row_class = "step-row step-row-failed"
|
|
||||||
status_icon = "🔴"
|
|
||||||
else:
|
|
||||||
status_badge = '<span class="pill-badge badge-info">⏳ RUNNING</span>'
|
|
||||||
row_class = "step-row step-row-running"
|
|
||||||
status_icon = "🔵"
|
|
||||||
|
|
||||||
msg = s.get("log_message", "")
|
|
||||||
|
|
||||||
timeline_rows.append(
|
|
||||||
f"""
|
|
||||||
<div class="{row_class}">
|
|
||||||
<div style="display: flex; align-items: center; gap: 12px;">
|
|
||||||
<span class="step-num">#{s.get('step_index', 0):02d}</span>
|
|
||||||
<span style="font-size: 14px;">{status_icon}</span>
|
|
||||||
<div>
|
|
||||||
<span class="step-title">{title}</span>
|
|
||||||
<span style="font-size: 11px; color: #94a3b8; margin-left: 8px;"><code>{s_name}</code></span>
|
|
||||||
<div style="font-size: 12px; color: #cbd5e1; margin-top: 2px;">{msg}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div style="text-align: right; min-width: 140px;">
|
|
||||||
<span class="step-latency">{dur:.1f} ms</span>
|
|
||||||
<span style="font-size: 11px; color: #64748b; margin-left: 6px;">({share}%)</span>
|
|
||||||
<div style="margin-top: 4px;">{status_badge}</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
"""
|
|
||||||
)
|
|
||||||
|
|
||||||
content_html = "\n".join(timeline_rows)
|
|
||||||
st.markdown(
|
|
||||||
f"""
|
|
||||||
<div class="timeline-card">
|
|
||||||
{content_html}
|
|
||||||
</div>
|
|
||||||
""",
|
|
||||||
unsafe_allow_html=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def render_failure_alert(
|
def render_failure_alert(
|
||||||
@@ -689,7 +620,7 @@ def render_failure_alert(
|
|||||||
<code style="color: #fee2e2; font-size: 13px;">{err_text}</code>
|
<code style="color: #fee2e2; font-size: 13px;">{err_text}</code>
|
||||||
</div>
|
</div>
|
||||||
<div style="font-size: 11px; color: #94a3b8;">
|
<div style="font-size: 11px; color: #94a3b8;">
|
||||||
Latency before failure: <strong>{duration_ms:.1f} ms</strong> • Prior completed stages preserved in audit database.
|
Prior completed stages preserved in audit database.
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
""",
|
""",
|
||||||
|
|||||||
@@ -149,6 +149,15 @@ class DeterministicValidator:
|
|||||||
candidate = better_candidate
|
candidate = better_candidate
|
||||||
code = better_candidate.code
|
code = better_candidate.code
|
||||||
anat_ok, anat_err, lat_ok, lat_err, attr_ok, attr_errs = _evaluate_candidate_clinical_meaning(candidate)
|
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:
|
else:
|
||||||
failure_reasons = []
|
failure_reasons = []
|
||||||
if not anat_ok and anat_err:
|
if not anat_ok and anat_err:
|
||||||
@@ -267,7 +276,7 @@ class DeterministicValidator:
|
|||||||
cpt=cpt_val,
|
cpt=cpt_val,
|
||||||
database_code=code,
|
database_code=code,
|
||||||
database_description=candidate.description,
|
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_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),
|
source_span=getattr(condition.context.evidence, "source_span", None) or getattr(selection, "source_span", None),
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -407,12 +407,32 @@ class ReverseAttributeChecker:
|
|||||||
|
|
||||||
from medical_coding.retrieval.tokenizer import CLINICAL_ABBREVIATIONS
|
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:
|
for mod in code_modifiers:
|
||||||
if mod in unsupported:
|
if mod in unsupported:
|
||||||
continue
|
continue
|
||||||
variants = [mod] + CLINICAL_MORPHOLOGY.get(mod, [])
|
variants = [mod] + CLINICAL_MORPHOLOGY.get(mod, [])
|
||||||
if mod in CLINICAL_ABBREVIATIONS:
|
if mod in CLINICAL_ABBREVIATIONS:
|
||||||
variants.extend(CLINICAL_ABBREVIATIONS[mod].split())
|
variants.extend(CLINICAL_ABBREVIATIONS[mod].split())
|
||||||
|
if mod in ORGANISM_EQUIVALENCES:
|
||||||
|
variants.extend(ORGANISM_EQUIVALENCES[mod])
|
||||||
if mod.endswith("s") and len(mod) > 4:
|
if mod.endswith("s") and len(mod) > 4:
|
||||||
variants.append(mod[:-1])
|
variants.append(mod[:-1])
|
||||||
if mod.endswith("ic") and len(mod) > 4:
|
if mod.endswith("ic") and len(mod) > 4:
|
||||||
@@ -421,6 +441,8 @@ class ReverseAttributeChecker:
|
|||||||
variants.append(mod[:-2])
|
variants.append(mod[:-2])
|
||||||
|
|
||||||
supported = any(has_positive_mention(v, combined_evidence) for v in variants)
|
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:
|
if not supported:
|
||||||
unsupported.append(mod)
|
unsupported.append(mod)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user