Fix compound diagnosis splitting, section boundaries, and attribute matching for secondary completeness

This commit is contained in:
Abhinav Gupta
2026-10-12 12:40:30 +05:30
parent 211a1bc480
commit 0b5996ad1b
19 changed files with 1563 additions and 286 deletions
+66
View File
@@ -0,0 +1,66 @@
import asyncio
import pytest
from medical_coding.graph.pipeline import process_clinical_document
@pytest.mark.asyncio
async def test_ent_multidiagnosis_and_procedures():
ent_text = """Discharge Summary - ENT
Age : 32Y 3M 25D Bed No.: SS12B - 4230
Consultant : Dr. GANDHI SACHIN
Date of Admission: 02/07/2026 Discharge Type: FOLLOW UP DISCHARGE
Date of Discharge: 02/07/2026
Date of Procedure : 02/07/2026
DIAGNOSIS : Deviated nasal septum+ inferior turbinate hypertrophy+ sinusitis
DRUG ALLERGY: Not known
COMORBIDITIES: Not known
HISTORY OF PRESENT ILLNESS: Nasal obstruction
CLINICAL EXAMINATION ON ADMISSION:
NOSE: Deviated nasal septum to left with Bilateral inferior turbinate hypertrophy
COURSE IN THE HOSPITAL: Patient came with complaints of nasal obstruction. Examined and found to have deviated nasal septum+ Inferior turbinate hypertrophy+ sinusitis. Admitted and underwent septoplasty+ turbinoplasty+ fess. Patient stable and being discharged
PROCEDURE DETAILS:
Procedure Performed: Septoplasty+ turbinoplasty+ fess
Side : Bilateral
SURGEON : 76
SURGEON : 16884
Anaesthesiologist: 16316
Type of Anaesthesia: GA
INTRAOPERATIVE FINDING: Deviated nasal septum. Polypoidal tissue in anterior ethmoids
INVESTIGATION: CT PNS - DNS TO LEFT SIDE. ADENOID HYPERTROPHY CAUSING MILD AIRWAY NARROWING. MILD MUCOSAL THICKENING NOTED IN B/L MAXILLARY, ETHMOIDAL & SPHENOID SINUSES. OCCLUSION OF LEFT SPHENO-ETHMOIDAL RECESS. MASTOIDITIS.
STATUS AT DISCHARGE: Stable
DISCHARGE MEDICATIONS:
T. AUGMENTIN 625MG 1-0-1 7 DAYS
T. CIPROFLOXACIN 500MG 1-0-1 14 DAYS
PLAN ON DISCHARGE: Patient is stable hence being discharged"""
res = await process_clinical_document(source=ent_text, document_id="test-ent-e2e")
print("\n" + "=" * 50)
print("ENT FORMATTED OUTPUT:")
print(res.format_output())
print("=" * 50)
# 1. Primary diagnosis must be accurately identified as Deviated nasal septum
assert res.primary_diagnosis is not None
pri_term = (res.primary_diagnosis.raw_term or "").lower()
assert "deviated nasal septum" in pri_term
assert res.primary_diagnosis.code == "J34.2"
# 2. Secondary diagnoses must not be empty and must capture inferior turbinate hypertrophy and sinusitis
assert len(res.secondary_diagnoses) >= 2, f"Expected at least 2 secondary diagnoses, got {len(res.secondary_diagnoses)}"
sec_terms = [(s.raw_term or s.normalized_diagnosis or "").lower() for s in res.secondary_diagnoses]
sec_codes = [s.code for s in res.secondary_diagnoses]
assert any("turbinate" in t for t in sec_terms), "Inferior turbinate hypertrophy must be a secondary diagnosis!"
assert any("sinusitis" in t for t in sec_terms), "Sinusitis must be a secondary diagnosis!"
# Turbinate hypertrophy must be correctly coded to J34.3 (not kidney N28.81)
turbinate_diags = [s for s in res.secondary_diagnoses if "turbinate" in (s.raw_term or "").lower()]
assert any(s.code == "J34.3" for s in turbinate_diags), f"Expected J34.3 for turbinate hypertrophy, got: {[s.code for s in turbinate_diags]}"
# Sinusitis must be coded to sinusitis category (J01 / J32)
sinusitis_diags = [s for s in res.secondary_diagnoses if "sinusitis" in (s.raw_term or "").lower()]
assert any(s.code.startswith(("J01", "J32")) for s in sinusitis_diags), f"Expected J01 or J32 for sinusitis, got: {[s.code for s in sinusitis_diags]}"
# 3. Verified CPT procedures
assert len(res.procedures) >= 2, f"Expected verified procedures, got: {res.procedures}"
assert any("30520" in p for p in res.procedures), "Septoplasty [CPT: 30520] must be verified!"
@@ -0,0 +1,55 @@
import asyncio
import pytest
from medical_coding.graph.pipeline import process_clinical_document
@pytest.mark.asyncio
async def test_generalized_adjacent_conditions_separation():
"""Test that multiple adjacent conditions without commas or 'and' are cleanly split into individual diagnoses."""
sample_text = """DIAGNOSIS: Cholelithiasis Pancreatitis
HISTORY OF PRESENT ILLNESS: Patient presented with severe right upper quadrant abdominal pain and elevated lipase.
COURSE IN HOSPITAL: Ultrasound confirmed gallstones. Gastroenterology evaluated and confirmed acute pancreatitis."""
res = await process_clinical_document(source=sample_text, document_id="test-adj-1")
assert res.primary_diagnosis is not None
pri_name = (res.primary_diagnosis.normalized_diagnosis or res.primary_diagnosis.raw_term or "").lower()
assert "cholelithiasis pancreatitis" not in pri_name
all_names = [pri_name] + [
(s.normalized_diagnosis or s.raw_term or s.description or "").lower()
for s in res.secondary_diagnoses
]
assert any("cholelithiasis" in n for n in all_names)
assert any("pancreatitis" in n for n in all_names)
@pytest.mark.asyncio
async def test_generalized_consult_findings_extraction():
"""Test that specialist consult findings in hospital course are extracted as secondary diagnoses."""
sample_text = """DIAGNOSIS: Acute myocardial infarction
HISTORY OF PRESENT ILLNESS: Patient admitted under Cardiology for acute chest pain and troponin elevation.
COURSE IN HOSPITAL: Patient underwent coronary angiography. Endocrinology consultation concluded that patient had uncontrolled diabetes mellitus type 2, and advised insulin glargine."""
res = await process_clinical_document(source=sample_text, document_id="test-consult-1")
assert res.primary_diagnosis is not None
all_names = [
(res.primary_diagnosis.normalized_diagnosis or res.primary_diagnosis.raw_term or "").lower()
] + [
(s.normalized_diagnosis or s.raw_term or s.description or "").lower()
for s in res.secondary_diagnoses
]
assert any("infarction" in n for n in all_names)
assert any("diabetes" in n for n in all_names)
@pytest.mark.asyncio
async def test_generalized_evidence_purity():
"""Verify that clinical criteria and internal audit strings never leak into evidence quotes."""
sample_text = """FINAL DIAGNOSIS: Essential hypertension, Type 2 diabetes mellitus
HISTORY: Patient with long standing history of elevated blood pressure and hyperglycemia."""
res = await process_clinical_document(source=sample_text, document_id="test-purity-1")
for d in [res.primary_diagnosis] + res.secondary_diagnoses:
if d and d.evidence_quote:
eq = d.evidence_quote.lower()
assert "designated as primary diagnosis" not in eq
assert "clinical criteria:" not in eq
assert "explicitly documented" not in eq
@@ -164,3 +164,56 @@ class TestReverseAttributeValidation:
)
assert is_valid
assert len(missing) == 0
class TestNonClinicalNoiseFiltering:
"""Validate strict exclusion of non-clinical daily activities, bodily functions, and generic procedures."""
@pytest.mark.parametrize(
"noise_phrase",
[
"Towel picked up",
"picked up towel",
"I pooped",
"pooped",
"urinated in bed",
"Procedure done",
"Surgery performed",
"brushing teeth",
"went to sleep",
"had breakfast",
],
)
def test_gate_rejects_non_clinical_noise(self, noise_phrase):
is_valid, reason = HardClinicalCandidateGate.evaluate_candidate(noise_phrase, f"1. {noise_phrase}")
assert not is_valid, f"Noise '{noise_phrase}' should have been rejected but was accepted"
@pytest.mark.asyncio
async def test_end_to_end_noise_filtering(self):
from medical_coding.graph.pipeline import process_clinical_document
doc = """
HOSPITAL DISCHARGE SUMMARY
PRINCIPAL DIAGNOSIS:
Acute appendicitis.
SECONDARY DIAGNOSES:
1. Procedure done.
2. Towel picked up.
3. I pooped.
4. Essential hypertension.
HOSPITAL COURSE: Patient presented with RLQ pain and fever. Diagnosed with acute appendicitis. History of hypertension managed with amlodipine. Appendectomy performed without complication.
"""
res = await process_clinical_document(source=doc, document_id="noise-filter-test")
assert res.primary_diagnosis is not None
assert res.primary_diagnosis.code.startswith("K35")
sec_codes = {s.code for s in res.secondary_diagnoses}
assert "I10" in sec_codes
# Noise items must NOT be present anywhere in secondary diagnoses or primary
all_descriptions = [res.primary_diagnosis.description] + [s.description for s in res.secondary_diagnoses]
for desc in all_descriptions:
desc_lower = desc.lower()
assert "towel" not in desc_lower
assert "poop" not in desc_lower
assert "procedure done" not in desc_lower
# Total coded diagnoses should be exactly 2 (appendicitis + hypertension)
assert len(res.secondary_diagnoses) == 1
@@ -0,0 +1,104 @@
import pytest
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
from medical_coding.schemas.enums import DiagnosisRole
from medical_coding.schemas.response import CodingResult
@pytest.mark.asyncio
async def test_secondary_diagnoses_not_dropped_when_in_pmh():
"""Verify that conditions active in discharge diagnoses are not dropped into historical
even if they appear in Past Medical History without medication details.
"""
pipeline = MedicalCodingPipeline()
text = """
HOSPITAL DISCHARGE SUMMARY
DISCHARGE DIAGNOSES:
1. Acute Appendicitis
2. Essential Hypertension
3. Type 2 Diabetes Mellitus
4. Chronic Kidney Disease
PAST MEDICAL HISTORY:
Hypertension, diabetes mellitus, chronic kidney disease.
HOSPITAL COURSE:
Patient underwent laparoscopic appendectomy. Blood pressure and glucose levels were monitored.
Renal function was followed closely.
"""
result = await pipeline.run_document(document_id="test-doc-sec-pmh", text=text)
assert result.primary_diagnosis is not None
assert "appendicitis" in (result.primary_diagnosis.normalized_diagnosis or "").lower()
# Verify secondary diagnoses are not dropped
sec_diagnoses = [s.normalized_diagnosis.lower() for s in result.secondary_diagnoses]
assert any("hypertension" in s for s in sec_diagnoses), f"Hypertension missing from {sec_diagnoses}"
assert any("diabetes" in s for s in sec_diagnoses), f"Diabetes missing from {sec_diagnoses}"
assert any("kidney" in s for s in sec_diagnoses), f"CKD missing from {sec_diagnoses}"
@pytest.mark.asyncio
async def test_cpt_and_icdo_verification():
"""Verify that neoplasm cases get ICD-O morphology codes and procedures get verified CPT codes."""
pipeline = MedicalCodingPipeline()
text = """
HOSPITAL DISCHARGE SUMMARY
PRINCIPAL DIAGNOSIS:
Infiltrating duct carcinoma of right breast
SECONDARY DIAGNOSES:
1. Essential Hypertension
PROCEDURES:
Laparoscopic appendectomy
DJ stenting
HOSPITAL COURSE:
Patient admitted with invasive ductal carcinoma of right breast.
Underwent surgical intervention and monitoring.
"""
result = await pipeline.run_document(document_id="test-doc-cpt-icdo", text=text)
# Primary diagnosis ICD-10-CM and ICD-O
assert result.primary_diagnosis is not None
assert result.primary_diagnosis.icd10cm is not None
assert result.primary_diagnosis.icdo is not None
assert result.primary_diagnosis.icdo.startswith("M85")
# Procedures with verified CPT
assert len(result.procedures) >= 1
assert any("CPT:" in p for p in result.procedures), f"CPT missing from procedures: {result.procedures}"
formatted = result.format_output()
assert "primary diagnosis:" in formatted
assert "ICD-O:" in formatted
assert "secondary diagnosises:" in formatted
@pytest.mark.asyncio
async def test_physical_exam_findings_captured():
"""Verify physical exam findings and signs are captured when clinically relevant."""
pipeline = MedicalCodingPipeline()
text = """
HOSPITAL DISCHARGE SUMMARY
CHIEF COMPLAINT:
Shortness of breath and fever.
CLINICAL EXAMINATION:
Jaundice noted. Auscultation revealed diffuse wheezing and pulmonary rales.
Bilateral ankle edema present.
ASSESSMENT AND PLAN:
Acute bronchitis. Patient also noted to have jaundice and essential hypertension.
Treated with bronchodilators, hydration, and antihypertensive therapy.
"""
result = await pipeline.run_document(document_id="test-doc-exam", text=text)
assert result.primary_diagnosis is not None
sec_terms = [s.normalized_diagnosis.lower() for s in result.secondary_diagnoses]
# Check that hypertension and jaundice or wheezing are evaluated
assert any("hypertension" in s for s in sec_terms) or any("jaundice" in s for s in sec_terms)
+43
View File
@@ -0,0 +1,43 @@
import asyncio
import pytest
from medical_coding.graph.pipeline import process_clinical_document
@pytest.mark.asyncio
async def test_user_screenshot_note():
sample_text = """DIAGNOSIS: Urticaria Gastritis Post frozen embryo transfer (FET)
DRUG ALLERGIES: None
HISTORY OF PRESENT ILLNESS: The patient, a post-frozen embryo transfer (FET) case on hormonal support, was admitted under Medicine for evaluation of acute chest pain, epigastric discomfort, urticarial rash over the chest and neck, and ECG changes while receiving Augmentin and other IVF-related medications.
CLINICAL EXAMINATION ON ADMISSION: On admission, she was hemodynamically stable, afebrile, alert, maintaining oxygen saturation on room air, with no respiratory distress or focal systemic abnormalities.
RELEVANT INVESTIGATIONS: Attached to the file.
COURSE IN THE HOSPITAL AND DISCUSSION: The patient presented with above mentioned complaints. Dermatology evaluation concluded that the rash was urticarial in nature, with additional contact dermatitis over the wrists due to adhesive tape, and advised Levocetirizine 5 mg twice daily along with Flutivate cream twice daily."""
res = await process_clinical_document(source=sample_text, document_id="user-sample-test")
print("\n" + "=" * 50)
print("FORMATTED OUTPUT:")
print(res.format_output())
print("=" * 50)
# Primary diagnosis must not be clubbed
assert res.primary_diagnosis is not None
pri_name = (res.primary_diagnosis.normalized_diagnosis or res.primary_diagnosis.raw_term or "").lower()
assert "urticaria gastritis" not in pri_name, "Urticaria and Gastritis must not be clubbed together!"
# Secondary diagnoses must be present and captured
assert len(res.secondary_diagnoses) >= 1, "Secondary diagnoses must not be empty!"
sec_names = [(s.normalized_diagnosis or s.raw_term or s.description or "").lower() for s in res.secondary_diagnoses]
print("Secondary names:", sec_names)
# Check that contact dermatitis or gastritis or urticaria is among diagnoses
all_names = [pri_name] + sec_names
print("All diagnosed conditions:", all_names)
assert any("gastritis" in n for n in all_names), "Gastritis must be diagnosed!"
assert any("urticaria" in n or "urticarial" in n for n in all_names), "Urticaria must be diagnosed!"
assert any("dermatitis" in n for n in all_names), "Contact dermatitis must be diagnosed!"
# Verify no audit strings leaked into evidence
assert "designated as primary diagnosis" not in (res.primary_diagnosis.evidence_quote or "").lower()
assert "clinical criteria:" not in (res.primary_diagnosis.evidence_quote or "").lower()
if __name__ == "__main__":
asyncio.run(test_user_screenshot_note())