feat(pipeline): complete multi-diagnosis classification, UHDDS role assignment, and robust ICD code retrieval
This commit is contained in:
@@ -1130,12 +1130,70 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
# Sort descending by score
|
||||
scored_candidates.sort(key=lambda x: x[1], reverse=True)
|
||||
|
||||
# Check for ambiguous tie between two high-acuity admission drivers (Scenario 4)
|
||||
has_ambiguous_tie = False
|
||||
if len(scored_candidates) >= 2:
|
||||
s0 = scored_candidates[0][1]
|
||||
s1 = scored_candidates[1][1]
|
||||
asm0 = scored_candidates[0][0]
|
||||
asm1 = scored_candidates[1][0]
|
||||
if (
|
||||
s0 >= 4.0
|
||||
and s1 >= 4.0
|
||||
and abs(s0 - s1) < 0.01
|
||||
and asm0.status == ConditionStatus.ACUTE
|
||||
and asm1.status == ConditionStatus.ACUTE
|
||||
):
|
||||
has_ambiguous_tie = True
|
||||
|
||||
if has_ambiguous_tie:
|
||||
# Emit both as PRIMARY so deterministic validator can enforce UHDDS ambiguity demotion
|
||||
top_asm, top_score, top_reasons = scored_candidates[0]
|
||||
sec_asm, sec_score, sec_reasons = scored_candidates[1]
|
||||
classifications.append(
|
||||
ConditionClassification(
|
||||
diagnosis_id=top_asm.condition_id or str(uuid4()),
|
||||
diagnosis=top_asm.diagnosis,
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason=f"Ambiguous co-primary diagnosis: '{top_asm.diagnosis}' competed with other primary candidates (score={top_score:.1f})",
|
||||
primary_justification=f"Condition occasioning admission: {top_asm.evidence}",
|
||||
admitting_condition_score=top_score,
|
||||
evidence_quote=top_asm.evidence,
|
||||
)
|
||||
)
|
||||
classifications.append(
|
||||
ConditionClassification(
|
||||
diagnosis_id=sec_asm.condition_id or str(uuid4()),
|
||||
diagnosis=sec_asm.diagnosis,
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason=f"Ambiguous co-primary diagnosis: '{sec_asm.diagnosis}' competed with other primary candidates (score={sec_score:.1f})",
|
||||
primary_justification=f"Condition occasioning admission: {sec_asm.evidence}",
|
||||
admitting_condition_score=sec_score,
|
||||
evidence_quote=sec_asm.evidence,
|
||||
)
|
||||
)
|
||||
for asm, score, r_list in scored_candidates[2:]:
|
||||
classifications.append(
|
||||
ConditionClassification(
|
||||
diagnosis_id=asm.condition_id or str(uuid4()),
|
||||
diagnosis=asm.diagnosis,
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason=f"Co-existing condition managed during admission (score={score:.1f}): {'; '.join(r_list)}",
|
||||
admitting_condition_score=score,
|
||||
evidence_quote=asm.evidence,
|
||||
)
|
||||
)
|
||||
return classifications
|
||||
|
||||
# Select the top candidate that meets Section 8 primary criteria
|
||||
chosen_primary_idx = None
|
||||
for i, (asm, s, _r_list) in enumerate(scored_candidates):
|
||||
if (
|
||||
s > 1.5
|
||||
and asm.certainty == Certainty.CONFIRMED
|
||||
and asm.certainty in (Certainty.CONFIRMED, Certainty.SUSPECTED, Certainty.POSSIBLE, "CONFIRMED", "SUSPECTED", "POSSIBLE")
|
||||
and asm.temporality in (Temporality.CURRENT, "CURRENT")
|
||||
and bool(asm.evidence and asm.evidence.strip())
|
||||
):
|
||||
@@ -1144,6 +1202,18 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
chosen_primary_idx = i
|
||||
break
|
||||
|
||||
# Fallback if no candidate exceeded s > 1.5: pick highest-scoring valid active candidate
|
||||
if chosen_primary_idx is None:
|
||||
for i, (asm, _s, _r_list) in enumerate(scored_candidates):
|
||||
if (
|
||||
asm.temporality in (Temporality.CURRENT, "CURRENT")
|
||||
and bool(asm.evidence and asm.evidence.strip())
|
||||
):
|
||||
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(asm.diagnosis, asm.evidence or "")
|
||||
if is_valid:
|
||||
chosen_primary_idx = i
|
||||
break
|
||||
|
||||
if chosen_primary_idx is not None:
|
||||
top_asm, top_score, top_reasons = scored_candidates[chosen_primary_idx]
|
||||
remaining_candidates = [
|
||||
@@ -1153,54 +1223,15 @@ class PrimarySecondaryClassifier(BaseAgent):
|
||||
top_asm, top_score, top_reasons = scored_candidates[0]
|
||||
remaining_candidates = scored_candidates[1:]
|
||||
|
||||
# Check for genuine ambiguity (two equally qualifying primary diagnoses without documentary distinction)
|
||||
has_ambiguous_tie = False
|
||||
if len(scored_candidates) > 1 and chosen_primary_idx == 0:
|
||||
second_asm, second_score, _ = scored_candidates[1]
|
||||
# Genuine tie only if both scores are high, exactly equal, and both document competing reasons for admission
|
||||
if top_score >= 4.0 and second_score >= 4.0 and abs(top_score - second_score) < 0.01:
|
||||
top_ctx = f"{top_asm.evidence} {top_asm.reason}".lower()
|
||||
sec_ctx = f"{second_asm.evidence} {second_asm.reason}".lower()
|
||||
admission_cues = [
|
||||
"chief complaint",
|
||||
"reason for admission",
|
||||
"admitted for",
|
||||
"admitted with",
|
||||
"presenting complaint",
|
||||
"occasioning admission",
|
||||
"emergent",
|
||||
]
|
||||
top_has_adm = any(cue in top_ctx for cue in admission_cues)
|
||||
sec_has_adm = any(cue in sec_ctx for cue in admission_cues)
|
||||
if top_has_adm and sec_has_adm:
|
||||
has_ambiguous_tie = True
|
||||
|
||||
if has_ambiguous_tie:
|
||||
# DO NOT arbitrarily choose one! All active candidates become SECONDARY with ambiguity note
|
||||
for asm, score, _r_list in scored_candidates:
|
||||
classifications.append(
|
||||
ConditionClassification(
|
||||
diagnosis_id=asm.condition_id or str(uuid4()),
|
||||
diagnosis=asm.diagnosis,
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason=(
|
||||
f"Ambiguous co-primary candidate (score={score:.1f}); "
|
||||
"not designated as unique Primary to prevent arbitrary selection without physician query."
|
||||
),
|
||||
admitting_condition_score=score,
|
||||
evidence_quote=asm.evidence,
|
||||
)
|
||||
)
|
||||
elif chosen_primary_idx is not None and top_score > 1.5:
|
||||
# Unique Primary selected
|
||||
if chosen_primary_idx is not None:
|
||||
# Primary selected (either unique or prioritized under UHDDS Section II.C)
|
||||
classifications.append(
|
||||
ConditionClassification(
|
||||
diagnosis_id=top_asm.condition_id or str(uuid4()),
|
||||
diagnosis=top_asm.diagnosis,
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason=f"Selected as unique Primary Diagnosis (score={top_score:.1f}): {'; '.join(top_reasons)}",
|
||||
classification_reason=f"Selected as Primary Diagnosis (score={top_score:.1f}): {'; '.join(top_reasons)}",
|
||||
primary_justification=f"Condition chiefly responsible for occasioning admission: {top_asm.evidence}",
|
||||
admitting_condition_score=top_score,
|
||||
evidence_quote=top_asm.evidence,
|
||||
|
||||
@@ -342,7 +342,7 @@ class EvidenceFirstFactExtractor:
|
||||
|
||||
# 1. Extract receptor status and molecular markers (e.g., Triple negative, BRCA, PD-L1, GCB type, double expressor)
|
||||
mol_m = re.search(
|
||||
r",?\s*\b(triple\s+negative|brca(?:\s*1|\s*2)?\s*(?:pathogenic|mutation|positive|negative)?(?:\s*mutation)?|pd[\s\-]?l1\s*(?:positive|negative)?(?:\s*\(.*?\))?|gcb\s+type|non-gcb\s+type|double\s+expressor|bcl[0-9]+(?:\+|-)?|cd[0-9]+(?:\+|-)?|her2(?:\s*(?:positive|negative|0|\d+))?|egfr(?:\+|-)?)\b",
|
||||
r",?\s*\b(triple\s+negative|brca(?:\s*1|\s*2)?\s*(?:pathogenic|mutation|positive|negative)?(?:\s*mutation)?|pd[\s\-]?l1\s*(?:positive|negative)?(?:\s*\(.*?\))?|(?:non-)?gcb(?:\s+(?:sub)?type)?|double\s+expressor|bcl[0-9]+(?:\+|-)?|cd[0-9]+(?:\+|-)?|her2(?:\s*(?:positive|negative|0|\d+))?|egfr(?:\+|-)?)\b",
|
||||
cleaned,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
|
||||
@@ -543,7 +543,12 @@ class CandidateRankingAgent(BaseAgent):
|
||||
is_acute_doc = bool(re.search(r"\b(?:acute|exacerbation|decompensated|decompensation)\b", full_context))
|
||||
is_chronic_doc = bool(re.search(r"\b(?:chronic|longstanding)\b", full_context) or (re.search(r"\bcompensated\b", full_context) and not re.search(r"\bdecompensated\b", full_context)))
|
||||
|
||||
is_acute_cand = "acute" in desc_lower and "chronic" not in desc_lower
|
||||
is_acute_cand = (
|
||||
("acute" in desc_lower and "chronic" not in desc_lower)
|
||||
or cand.code.startswith(("I21", "J20", "K35", "K85", "N10", "N17"))
|
||||
or (cand.code.startswith("K80") and "acute" in desc_lower)
|
||||
or (cand.code.startswith("K81") and "acute" in desc_lower)
|
||||
)
|
||||
is_chronic_cand = "chronic" in desc_lower and "acute" not in desc_lower
|
||||
is_acute_on_chronic_cand = "acute on chronic" in desc_lower or (
|
||||
"acute" in desc_lower and "chronic" in desc_lower
|
||||
|
||||
@@ -662,23 +662,45 @@ def retrieve_candidates_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
existing_codes.add(rec.code)
|
||||
|
||||
# LEVEL 5: Broad Local Database Fallback (if hits < 5)
|
||||
if len(hits) < 5 and concept.body_site:
|
||||
fallback_recs = [
|
||||
r for r in catalog.get_all_records()
|
||||
if concept.body_site in r.description.lower()
|
||||
if len(hits) < 5:
|
||||
content_words = [
|
||||
w for w in re.findall(r"\b[a-z0-9]{4,}\b", query.lower())
|
||||
if w not in ("with", "without", "acute", "chronic", "status", "post", "from", "type")
|
||||
]
|
||||
for r in fallback_recs[:10]:
|
||||
if r.code not in existing_codes:
|
||||
cand = ICDCandidate(
|
||||
code=r.code,
|
||||
description=r.description,
|
||||
is_valid_billable=r.is_valid_billable,
|
||||
coding_system=getattr(r, "coding_system", "ICD-10-CM"),
|
||||
retrieval_score=0.45,
|
||||
retrieval_method="hybrid",
|
||||
)
|
||||
hits.append(cand)
|
||||
existing_codes.add(r.code)
|
||||
if content_words:
|
||||
fallback_recs = [
|
||||
r for r in catalog.get_all_records()
|
||||
if any(cw in r.description.lower() for cw in content_words)
|
||||
]
|
||||
for r in fallback_recs[:15]:
|
||||
if r.code not in existing_codes:
|
||||
cand = ICDCandidate(
|
||||
code=r.code,
|
||||
description=r.description,
|
||||
is_valid_billable=r.is_valid_billable,
|
||||
coding_system=getattr(r, "coding_system", "ICD-10-CM"),
|
||||
retrieval_score=0.45,
|
||||
retrieval_method="fallback_token_scan",
|
||||
)
|
||||
hits.append(cand)
|
||||
existing_codes.add(r.code)
|
||||
elif concept.body_site:
|
||||
fallback_recs = [
|
||||
r for r in catalog.get_all_records()
|
||||
if concept.body_site in r.description.lower()
|
||||
]
|
||||
for r in fallback_recs[:10]:
|
||||
if r.code not in existing_codes:
|
||||
cand = ICDCandidate(
|
||||
code=r.code,
|
||||
description=r.description,
|
||||
is_valid_billable=r.is_valid_billable,
|
||||
coding_system=getattr(r, "coding_system", "ICD-10-CM"),
|
||||
retrieval_score=0.45,
|
||||
retrieval_method="hybrid",
|
||||
)
|
||||
hits.append(cand)
|
||||
existing_codes.add(r.code)
|
||||
|
||||
# 4. Post-Retrieval Compatibility Reasoning (Section 10)
|
||||
scored_hits: list[tuple[float, ICDCandidate]] = []
|
||||
@@ -1048,6 +1070,93 @@ def finalize_output_node(state: PipelineGraphState) -> dict[str, Any]:
|
||||
)
|
||||
)
|
||||
|
||||
# SEPARATION OF CLINICAL DIAGNOSIS AND ICD CODE MAPPING FOR SECONDARIES
|
||||
# Ensure every active secondary diagnosis clinically confirmed is retained in secondary_responses
|
||||
seen_sec_terms = set()
|
||||
if primary_response:
|
||||
if primary_response.normalized_diagnosis:
|
||||
seen_sec_terms.add(primary_response.normalized_diagnosis.lower())
|
||||
if primary_response.raw_term:
|
||||
seen_sec_terms.add(primary_response.raw_term.lower())
|
||||
if primary_response.description:
|
||||
seen_sec_terms.add(primary_response.description.lower())
|
||||
seen_sec_terms.update(
|
||||
s.normalized_diagnosis.lower() for s in secondary_responses if s.normalized_diagnosis
|
||||
)
|
||||
seen_sec_terms.update(s.raw_term.lower() for s in secondary_responses if s.raw_term)
|
||||
seen_sec_terms.update(s.description.lower() for s in secondary_responses if s.description)
|
||||
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
|
||||
for c in classified:
|
||||
if c.role == DiagnosisRole.SECONDARY and c.is_billable_candidate:
|
||||
c_term = (
|
||||
getattr(c, "normalized_diagnosis", None)
|
||||
or getattr(c, "raw_term", None)
|
||||
or getattr(c, "diagnosis", "")
|
||||
)
|
||||
if not c_term:
|
||||
continue
|
||||
c_norm = c_term.lower()
|
||||
c_words = {w for w in re.findall(r"[a-z0-9]+", c_norm) if len(w) > 3}
|
||||
is_already_covered = False
|
||||
for s_term in seen_sec_terms:
|
||||
if (s_term in c_norm or c_norm in s_term) and len(s_term) > 4:
|
||||
is_already_covered = True
|
||||
break
|
||||
s_words = {w for w in re.findall(r"[a-z0-9]+", s_term) if len(w) > 3}
|
||||
shared = c_words & s_words
|
||||
if len(shared) >= 2 or any(k in shared for k in ("diabetes", "hypertension", "cholecystitis", "infarction", "failure", "calculus", "hypokalemia", "hyperlipidemia", "anemia", "pancreatitis", "gastritis")):
|
||||
is_already_covered = True
|
||||
break
|
||||
if is_already_covered:
|
||||
continue
|
||||
|
||||
c_quote = (
|
||||
getattr(c, "evidence_quote", None)
|
||||
or (
|
||||
c.context.evidence.quote
|
||||
if hasattr(c, "context") and hasattr(c.context, "evidence") and c.context.evidence
|
||||
else ""
|
||||
)
|
||||
or ""
|
||||
)
|
||||
|
||||
is_valid_cand, _ = HardClinicalCandidateGate.evaluate_candidate(c_term, c_quote)
|
||||
if not is_valid_cand:
|
||||
continue
|
||||
sec_resp = CodedDiagnosisResponse(
|
||||
raw_term=getattr(c, "raw_term", c_term),
|
||||
normalized_diagnosis=c_term,
|
||||
description=c_term,
|
||||
database_code=None,
|
||||
database_description=None,
|
||||
matching_status="NO_DATABASE_MATCH",
|
||||
source_section=getattr(c, "source_section", "") or "DISCHARGE_DIAGNOSES",
|
||||
source_span=getattr(c, "source_span", None),
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
acuity=Acuity.ACUTE
|
||||
if "acute" in c_term.lower()
|
||||
else Acuity.CHRONIC
|
||||
if "chronic" in c_term.lower()
|
||||
else Acuity.UNSPECIFIED,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote=c_quote,
|
||||
evidence=[{
|
||||
"quote": c_quote,
|
||||
"section": getattr(c, "source_section", "") or "DISCHARGE_DIAGNOSES",
|
||||
"evidence_type": "SECONDARY_DIAGNOSIS",
|
||||
}],
|
||||
confidence_score=0.70,
|
||||
is_terminal_billable=False,
|
||||
icd10cm=None,
|
||||
icdo=None,
|
||||
cpt=None,
|
||||
)
|
||||
secondary_responses.append(sec_resp)
|
||||
seen_sec_terms.add(c_term.lower())
|
||||
seen_sec_terms.add(getattr(c, "raw_term", c_term).lower())
|
||||
|
||||
# Determine execution status
|
||||
if primary_response or secondary_responses:
|
||||
status = ExecutionStatus.SUCCESS if not abstentions else ExecutionStatus.PARTIAL_SUCCESS
|
||||
@@ -1255,14 +1364,22 @@ def _assess_context_deterministically(
|
||||
|
||||
# Rule 2: Past medical history without inpatient monitoring/treatment
|
||||
norm_section = section_lower.replace("_", " ")
|
||||
is_hpi = "present illness" in norm_section or "hpi" in norm_section
|
||||
is_pmh = (
|
||||
"past medical" in norm_section
|
||||
or "pmh" in norm_section
|
||||
or "past surgical" in norm_section
|
||||
or "psh" in norm_section
|
||||
or "history" in norm_section
|
||||
or term.lower().startswith("history of ")
|
||||
or "history of" in quote_lower
|
||||
not is_hpi
|
||||
and (
|
||||
"past medical" in norm_section
|
||||
or "pmh" in norm_section
|
||||
or "past surgical" in norm_section
|
||||
or "psh" in norm_section
|
||||
or (
|
||||
"history" in norm_section
|
||||
and "present" not in norm_section
|
||||
and "illness" not in norm_section
|
||||
)
|
||||
or term.lower().startswith("history of ")
|
||||
or "history of" in quote_lower
|
||||
)
|
||||
)
|
||||
has_active_care = any(
|
||||
w in quote_lower
|
||||
|
||||
@@ -54,6 +54,26 @@ DISEASE_FAMILY_PATTERNS: list[tuple[str, list[str], str]] = [
|
||||
("asthma", ["asthma", "bronchial asthma", "status asthmaticus"], "lung"),
|
||||
("liver_sarcoma", ["embryonal sarcoma of liver", "sarcoma of liver", "liver sarcoma", "angiosarcoma of liver", "embryonal sarcoma"], "liver"),
|
||||
("liver_metastasis", ["liver metastasis", "liver metastases", "metastasis to liver", "secondary malignant neoplasm of liver"], "liver"),
|
||||
("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"),
|
||||
("hyperlipidemia", ["hyperlipidemia", "hypercholesterolemia", "dyslipidemia", "hypertriglyceridemia"], "blood"),
|
||||
("hypokalemia", ["hypokalemia", "hypopotassemia"], "blood"),
|
||||
("hyperkalemia", ["hyperkalemia"], "blood"),
|
||||
("hyponatremia", ["hyponatremia"], "blood"),
|
||||
("anemia", ["anemia", "iron deficiency anemia", "acute blood loss anemia"], "blood"),
|
||||
("appendicitis", ["appendicitis", "acute appendicitis"], "appendix"),
|
||||
("pancreatitis", ["pancreatitis", "acute pancreatitis", "chronic pancreatitis"], "pancreas"),
|
||||
("atrial_fibrillation", ["atrial fibrillation", "a-fib", "afib", "atrial flutter"], "heart"),
|
||||
("coronary_artery_disease", ["coronary artery disease", "cad", "atherosclerotic heart disease", "ashd", "ischemic heart disease"], "heart"),
|
||||
("cerebrovascular_accident", ["cerebrovascular accident", "cva", "cerebral infarction", "ischemic stroke", "stroke"], "brain"),
|
||||
("deep_vein_thrombosis", ["deep vein thrombosis", "dvt", "deep venous thrombosis"], "vein"),
|
||||
("pulmonary_embolism", ["pulmonary embolism", "pe"], "lung"),
|
||||
("gerd", ["gastroesophageal reflux", "gerd", "acid reflux", "esophagitis"], "esophagus"),
|
||||
("cellulitis", ["cellulitis"], "skin"),
|
||||
("osteoarthritis", ["osteoarthritis", "degenerative joint disease", "oa"], "joint"),
|
||||
("hypothyroidism", ["hypothyroidism", "underactive thyroid"], "thyroid"),
|
||||
("acute_kidney_injury", ["acute kidney injury", "aki", "acute renal failure"], "kidney"),
|
||||
]
|
||||
|
||||
|
||||
|
||||
@@ -51,6 +51,26 @@ FAMILY_TO_CODE_PREFIXES: dict[str, list[str]] = {
|
||||
"asthma": ["J45"],
|
||||
"liver_sarcoma": ["C22.4", "C22"],
|
||||
"liver_metastasis": ["C78.7", "C78", "C7B.02"],
|
||||
"myocardial_infarction": ["I21", "I22"],
|
||||
"cholecystitis": ["K81", "K80"],
|
||||
"cholelithiasis": ["K80"],
|
||||
"hyperlipidemia": ["E78"],
|
||||
"hypokalemia": ["E87.6", "E87"],
|
||||
"hyperkalemia": ["E87.5", "E87"],
|
||||
"hyponatremia": ["E87.1", "E87"],
|
||||
"anemia": ["D50", "D64"],
|
||||
"appendicitis": ["K35", "K36", "K37"],
|
||||
"pancreatitis": ["K85"],
|
||||
"atrial_fibrillation": ["I48"],
|
||||
"coronary_artery_disease": ["I25"],
|
||||
"cerebrovascular_accident": ["I63", "I67"],
|
||||
"deep_vein_thrombosis": ["I82"],
|
||||
"pulmonary_embolism": ["I26"],
|
||||
"gerd": ["K21"],
|
||||
"cellulitis": ["L03"],
|
||||
"osteoarthritis": ["M15", "M16", "M17", "M19"],
|
||||
"hypothyroidism": ["E03"],
|
||||
"acute_kidney_injury": ["N17"],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -247,9 +247,10 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = {
|
||||
"ureter": ["ureteric", "ureteral"],
|
||||
"ureteric": ["ureter", "ureteral"],
|
||||
"ureteral": ["ureter", "ureteric"],
|
||||
"calculus": ["stone", "calculi"],
|
||||
"calculi": ["calculus", "stone"],
|
||||
"stone": ["calculus", "calculi"],
|
||||
"calculus": ["stone", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones", "lithiasis", "nephrolithiasis"],
|
||||
"calculi": ["calculus", "stone", "stones", "cholelithiasis", "gallstone", "gallstones"],
|
||||
"stone": ["calculus", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones"],
|
||||
"stones": ["calculus", "calculi", "stone", "cholelithiasis", "gallstone", "gallstones"],
|
||||
"renal": ["kidney", "renal"],
|
||||
"kidney": ["renal", "kidney"],
|
||||
"gastric": ["stomach", "gastric"],
|
||||
@@ -334,6 +335,34 @@ CLINICAL_MORPHOLOGY: dict[str, list[str]] = {
|
||||
"displaced": ["displacement"],
|
||||
"fracture": ["fractures"],
|
||||
"fractures": ["fracture"],
|
||||
"cholecystitis": ["gallbladder"],
|
||||
"cholelithiasis": ["calculus", "gallbladder", "gallstone", "gallstones", "calculi"],
|
||||
"gallstones": ["cholelithiasis", "calculus", "gallbladder", "gallstone", "stone"],
|
||||
"gallstone": ["cholelithiasis", "calculus", "gallbladder", "gallstones", "stone"],
|
||||
"gallbladder": ["cholecystitis", "cholelithiasis", "biliary"],
|
||||
"myocardial": ["infarction", "nstemi", "stemi", "heart"],
|
||||
"infarction": ["myocardial", "nstemi", "stemi"],
|
||||
"nstemi": ["subendocardial", "myocardial", "infarction"],
|
||||
"stemi": ["myocardial", "infarction"],
|
||||
"subendocardial": ["nstemi", "infarction", "myocardial"],
|
||||
"hyperlipidemia": ["hypercholesterolemia", "dyslipidemia", "lipids"],
|
||||
"dyslipidemia": ["hyperlipidemia", "hypercholesterolemia", "lipids"],
|
||||
"hypercholesterolemia": ["hyperlipidemia", "dyslipidemia", "cholesterol"],
|
||||
"hypokalemia": ["potassium", "electrolyte"],
|
||||
"hyperkalemia": ["potassium", "electrolyte"],
|
||||
"hyponatremia": ["sodium", "electrolyte"],
|
||||
"potassium": ["hypokalemia", "hyperkalemia"],
|
||||
"sodium": ["hyponatremia"],
|
||||
"anemia": ["iron", "deficiency", "blood"],
|
||||
"appendicitis": ["appendix"],
|
||||
"diverticulitis": ["diverticular", "colon"],
|
||||
"pancreatitis": ["pancreas", "pancreatic"],
|
||||
"pancreas": ["pancreatitis", "pancreatic"],
|
||||
"pancreatic": ["pancreas", "pancreatitis"],
|
||||
"fibrillation": ["atrial", "afib"],
|
||||
"atherosclerosis": ["coronary", "artery", "disease", "cad"],
|
||||
"hypothyroidism": ["thyroid"],
|
||||
"thyroid": ["hypothyroidism"],
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -131,11 +131,15 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
st.info("ℹ️ No primary diagnosis assigned for this document (abstained or undetermined).")
|
||||
return
|
||||
|
||||
billable_badge = (
|
||||
'<span class="pill-badge badge-success">✓ HIPAA Billable Leaf</span>'
|
||||
if primary.is_terminal_billable
|
||||
else '<span class="pill-badge badge-danger">⚠ Non-Billable Header</span>'
|
||||
)
|
||||
code_display = primary.code or "[NO LOCAL CODE]"
|
||||
if primary.matching_status == "NO_DATABASE_MATCH" or not primary.code:
|
||||
billable_badge = '<span class="pill-badge badge-warning">No Database Match</span>'
|
||||
else:
|
||||
billable_badge = (
|
||||
'<span class="pill-badge badge-success">✓ HIPAA Billable Leaf</span>'
|
||||
if primary.is_terminal_billable
|
||||
else '<span class="pill-badge badge-danger">⚠ Non-Billable Header</span>'
|
||||
)
|
||||
acuity_badge = f'<span class="pill-badge badge-info">{primary.acuity.value if hasattr(primary.acuity, "value") else primary.acuity}</span>'
|
||||
certainty_badge = f'<span class="pill-badge badge-secondary">{primary.certainty.value if hasattr(primary.certainty, "value") else primary.certainty}</span>'
|
||||
|
||||
@@ -155,7 +159,7 @@ def render_primary_diagnosis(primary: CodedDiagnosisResponse | None) -> None:
|
||||
<div class="primary-card">
|
||||
<div class="primary-card-header">
|
||||
<div>
|
||||
<span class="primary-code">{primary.code}</span>
|
||||
<span class="primary-code">{code_display}</span>
|
||||
<span style="margin-left: 12px;">{billable_badge}</span>
|
||||
</div>
|
||||
<div>
|
||||
@@ -190,11 +194,15 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
|
||||
return
|
||||
|
||||
for idx, diag in enumerate(secondaries, start=1):
|
||||
billable_badge = (
|
||||
'<span class="pill-badge badge-success">✓ Billable</span>'
|
||||
if diag.is_terminal_billable
|
||||
else '<span class="pill-badge badge-danger">⚠ Non-Billable</span>'
|
||||
)
|
||||
sec_code_display = diag.code or "[NO LOCAL CODE]"
|
||||
if diag.matching_status == "NO_DATABASE_MATCH" or not diag.code:
|
||||
billable_badge = '<span class="pill-badge badge-warning">No Database Match</span>'
|
||||
else:
|
||||
billable_badge = (
|
||||
'<span class="pill-badge badge-success">✓ Billable</span>'
|
||||
if diag.is_terminal_billable
|
||||
else '<span class="pill-badge badge-danger">⚠ Non-Billable</span>'
|
||||
)
|
||||
acuity_str = diag.acuity.value if hasattr(diag.acuity, "value") else str(diag.acuity)
|
||||
certainty_str = diag.certainty.value if hasattr(diag.certainty, "value") else str(diag.certainty)
|
||||
|
||||
@@ -213,7 +221,7 @@ def render_secondary_diagnoses(secondaries: list[CodedDiagnosisResponse]) -> Non
|
||||
<div class="secondary-card">
|
||||
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; flex-wrap: wrap;">
|
||||
<div>
|
||||
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {diag.code}</strong>
|
||||
<strong style="font-size: 18px; color: #38bdf8;">#{idx}. {sec_code_display}</strong>
|
||||
<span style="font-size: 15px; font-weight: 600; color: #f8fafc; margin-left: 10px;">{diag.description}</span>
|
||||
</div>
|
||||
<div style="display: flex; gap: 6px; align-items: center; flex-wrap: wrap;">
|
||||
|
||||
@@ -85,8 +85,7 @@ METADATA_PATTERNS = [
|
||||
# 5. Tumor attributes / Staging markers (attributes of a neoplasm, not standalone diagnoses)
|
||||
STANDALONE_ATTRIBUTE_PATTERNS = [
|
||||
r"^\s*stage\s+(?:i|ii|iii|iv|[1-4])[a-z]?\s*$",
|
||||
r"^\s*gcb\s+type\s*$",
|
||||
r"^\s*non-gcb\s+type\s*$",
|
||||
r"^\s*(?:non-)?gcb(?:\s+(?:sub)?type)?\s*$",
|
||||
r"^\s*double\s+expressor(?:\s*(?:bcl2/bcl6|myc/bcl2|\(.*\)))?\s*$",
|
||||
r"^\s*ki[\s\-]?67\s*(?:index)?\s*(?:>|=|<)?\s*\d+\s*%?\s*$",
|
||||
r"^\s*grade\s+(?:i|ii|iii|iv|[1-4])(?:\s+histology)?\s*$",
|
||||
|
||||
Reference in New Issue
Block a user