#!/usr/bin/env python3 """ disease_dict.py — Canonical controlled vocabulary for the ophthalmology pretraining dataset. SINGLE SOURCE OF TRUTH, shared by: * caption builders (build_manifest.py / oct_public_common.py / public_common.py / adapter_*.py) * route-A pseudo-labeling (RETFound / VisionFM fine-tune target taxonomy for the private Topcon OCT) Caption field order (disease/lesion-centric, EyeDiff-aligned): {modality}, {region}, {diagnosis[+severity]}, {lesions...} Design rules (from the prompt-design research): - The prompt carries clinically discriminative content only. - Acquisition metadata (device, dataset name, quality score, slice idx, bbox, exact µm thickness, eye) stays in parquet fields, NOT in the prompt. - Lesion tags are added to the DENSE caption tier ONLY, and only the lesions that are definitionally implied by the label (drusen / CNV) or backed by an actual segmentation mask — never inferred from a class name. Confirmed normalization decisions (2026-06): 1. DRUSEN -> diagnosis AMD + lesion 'drusen' CNV -> diagnosis nAMD + lesion 'choroidal_neovascularization' 2. AMD split into two levels: AMD (non-neovascular/dry) vs nAMD (neovascular/wet). Both have ~50k images -> well populated. 3. CSR -> CSC (central serous chorioretinopathy). """ # --------------------------------------------------------------------------- # # 1. Modality: machine code -> prompt surface form # # --------------------------------------------------------------------------- # MODALITY = { "oct_bscan": "OCT B-scan", "fundus_color": "color fundus", "slo_gray": "SLO", } # --------------------------------------------------------------------------- # # 2. Anatomy / region (controlled) # # --------------------------------------------------------------------------- # ANATOMY = { # code -> prompt surface form "macula": "macula", "optic_disc": "optic disc", "peripapillary": "peripapillary", } # --------------------------------------------------------------------------- # # 3. Canonical disease registry # # code -> dict(term, family, severity_scale, rare) # # term=None => 'normal', contributes no diagnosis token # # --------------------------------------------------------------------------- # DISEASE = { "normal": dict(term=None, family="normal", severity_scale=None, rare=False), "DR": dict(term="diabetic retinopathy", family="DR", severity_scale="DR", rare=False), "DME": dict(term="diabetic macular edema", family="DR", severity_scale=None, rare=False), "AMD": dict(term="age-related macular degeneration", family="AMD", severity_scale=None, rare=False), "nAMD": dict(term="neovascular age-related macular degeneration", family="AMD", severity_scale=None, rare=False), "CSC": dict(term="central serous chorioretinopathy", family="CSC", severity_scale=None, rare=False), "MH": dict(term="macular hole", family="MH", severity_scale="MH", rare=False), "ERM": dict(term="epiretinal membrane", family="ERM", severity_scale=None, rare=False), "RVO": dict(term="retinal vein occlusion", family="vascular", severity_scale=None, rare=False), "RAO": dict(term="retinal artery occlusion", family="vascular", severity_scale=None, rare=True), "VID": dict(term="vitreomacular interface disease", family="VMI", severity_scale=None, rare=True), "glaucoma": dict(term="glaucoma", family="glaucoma", severity_scale="glaucoma", rare=False), } # --------------------------------------------------------------------------- # # 4. Severity scales: code -> surface word/phrase modifier # # Composed with the diagnosis term by disease_phrase(). # # --------------------------------------------------------------------------- # # DR uses the ICDR 5-stage scale; the phrase is built specially (NPDR / PDR). DR_SEVERITY = {0: "none", 1: "mild", 2: "moderate", 3: "severe", 4: "proliferative"} GLAUCOMA_SEVERITY = {"mild": "early", "early": "early", "severe": "advanced", "advanced": "advanced"} # Macular hole staging -> severity code; surface built in disease_phrase(). MH_STAGE = {"stage1": "mild", "stage2": "moderate", "stage3": "severe", "stage4": "severe"} # --------------------------------------------------------------------------- # # 5. Lesion vocabulary: code -> prompt surface form # # (dense-caption tier only; gated by real evidence) # # --------------------------------------------------------------------------- # LESION = { # fundus (IDRiD segmentation etc.) "microaneurysms": "microaneurysms", "retinal_hemorrhages": "retinal hemorrhages", "hard_exudates": "hard exudates", "cotton_wool_spots": "cotton-wool spots", "neovascularization": "neovascularization", # AMD spectrum "drusen": "drusen", "choroidal_neovascularization":"choroidal neovascularization", # OCT fluid / structural (RETOUCH / AMD-SD / OIMHS segmentation) "intraretinal_fluid": "intraretinal fluid", "subretinal_fluid": "subretinal fluid", "pigment_epithelial_detachment":"pigment epithelial detachment", "subretinal_hyperreflective_material": "subretinal hyperreflective material", "ellipsoid_zone_disruption": "ellipsoid zone disruption", "cystoid_spaces": "cystoid spaces", "intraretinal_cysts": "intraretinal cysts", "full_thickness_macular_hole": "full-thickness macular hole", } # raw lesion strings from the existing adapters -> canonical lesion code LESION_ALIAS = { "microaneurysms": "microaneurysms", "haemorrhages": "retinal_hemorrhages", "hemorrhages": "retinal_hemorrhages", "hard_exudates": "hard_exudates", "soft_exudates": "cotton_wool_spots", "cotton_wool_spots": "cotton_wool_spots", "drusen": "drusen", "CNV": "choroidal_neovascularization", "IRF": "intraretinal_fluid", "SRF": "subretinal_fluid", "PED": "pigment_epithelial_detachment", "SHRM": "subretinal_hyperreflective_material", "ISOS": "ellipsoid_zone_disruption", } # --------------------------------------------------------------------------- # # 6. Alias table: raw cohort label -> (diagnosis_codes, severity, lesion_codes)# # Encodes the 3 confirmed decisions. Idempotent on canonical codes. # # --------------------------------------------------------------------------- # DIAGNOSIS_ALIAS = { # --- normal --- "NORMAL": (["normal"], "none", []), "Normal": (["normal"], "none", []), "NOR": (["normal"], "none", []), "NO": (["normal"], "none", []), "Control": (["normal"], "none", []), "CONTROL": (["normal"], "none", []), "normal": (["normal"], "none", []), # --- DR / DME --- "DR": (["DR"], "unknown", []), "DME": (["DME"], "unknown", []), # --- AMD spectrum (decision 1 + 2) --- "AMD": (["AMD"], "unknown", []), "DRUSEN": (["AMD"], "unknown", ["drusen"]), "nAMD": (["nAMD"], "unknown", []), "wet_AMD": (["nAMD"], "unknown", []), "CNV": (["nAMD"], "unknown", ["choroidal_neovascularization"]), "AMD/RVO": (["AMD", "RVO"], "unknown", []), # --- CSC (decision 3) --- "CSR": (["CSC"], "unknown", []), "CSC": (["CSC"], "unknown", []), # --- macular hole + staging --- "MH": (["MH"], "unknown", []), "MH_Stage1": (["MH"], "stage1", []), "MH_Stage2": (["MH"], "stage2", []), "MH_Stage3": (["MH"], "stage3", []), "MH_Stage4": (["MH"], "stage4", []), # --- glaucoma --- "Glaucoma": (["glaucoma"], "unknown", []), "POAG": (["glaucoma"], "unknown", []), "glaucoma": (["glaucoma"], "unknown", []), # --- other macular / vascular --- "ERM": (["ERM"], "unknown", []), "RVO": (["RVO"], "unknown", []), "RAO": (["RAO"], "unknown", []), "VID": (["VID"], "unknown", []), # --- fallback --- "Unknown": ([], "unknown", []), "unknown": ([], "unknown", []), } # --------------------------------------------------------------------------- # # 7. Route-A pseudo-label target taxonomy (private Topcon macula OCT) # # Only classes the public-macula classifier can reliably produce AND that # # can be cross-checked against thickness/segmentation. Disc -> not classified.# # --------------------------------------------------------------------------- # PSEUDO_TARGET_CLASSES = ["normal", "DME", "AMD", "nAMD", "CSC", "ERM", "MH"] # Excluded from pseudo-labeling (too few public OCT samples -> unreliable): PSEUDO_EXCLUDED = ["DR", "RVO", "RAO", "VID", "glaucoma"] # --------------------------------------------------------------------------- # # API # # --------------------------------------------------------------------------- # def normalize_diagnosis(raw_label): """raw cohort label (str) -> (diagnosis_codes, severity_code, lesion_codes). Unknown labels fall back to ([], 'unknown', []).""" if raw_label is None: return ([], "unknown", []) key = str(raw_label).strip() return DIAGNOSIS_ALIAS.get(key, ([], "unknown", [])) def normalize_lesion(raw): """raw lesion tag -> canonical lesion code (or None if unknown). Idempotent: an already-canonical code returns itself.""" if raw is None: return None s = str(raw).strip() if s in LESION: return s return LESION_ALIAS.get(s, None) def disease_phrase(code, severity=None): """Compose the clinical prompt phrase for one diagnosis code + severity. Returns '' for normal/unknown (caller decides whether to emit 'normal').""" if code in (None, "normal", "Unknown", "unknown") or code not in DISEASE: return "" term = DISEASE[code]["term"] if term is None: return "" fam = DISEASE[code]["severity_scale"] sev = (severity or "unknown") if fam == "DR" and code == "DR": # ICDR scale -> NPDR / PDR phrasing (EyeDiff-aligned) s = sev if isinstance(sev, int): s = DR_SEVERITY.get(sev, "unknown") if s in ("mild", "moderate", "severe"): return f"{s} non-proliferative diabetic retinopathy" if s == "proliferative": return "proliferative diabetic retinopathy" return "diabetic retinopathy" if fam == "glaucoma": g = GLAUCOMA_SEVERITY.get(str(sev)) return f"{g} glaucoma" if g else "glaucoma" if fam == "MH": s = MH_STAGE.get(str(sev), str(sev)) # stage1->mild; else passthrough (mild/moderate/severe) sizemap = {"mild": "small", "moderate": "medium", "severe": "large"} return f"{sizemap[s]} macular hole" if s in sizemap else "macular hole" return term def lesion_phrases(lesion_codes): """list of lesion codes -> list of surface phrases (dedup, stable order).""" out, seen = [], set() for c in (lesion_codes or []): canon = c if c in LESION else normalize_lesion(c) if canon and canon not in seen: seen.add(canon) out.append(LESION[canon]) return out def compose_disease_segment(diagnosis_codes, severity=None, lesion_codes=None, include_lesions=False, is_normal=None): """Build the disease portion of a caption (after modality+region). Returns a list of comma-segments, e.g.: (['nAMD'], None, ['choroidal_neovascularization'], include_lesions=True) -> ['neovascular age-related macular degeneration', 'choroidal neovascularization'] ([], 'none') (normal) -> ['normal'] is_normal: pass True/False to control the empty-diagnosis fallback explicitly (CONFIRMED normal -> ['normal']; UNKNOWN/unlabeled -> [] so we never assert health we don't have — the B-tier). If None, inferred from severity=='none'. """ codes = [c for c in (diagnosis_codes or []) if c not in ("normal",)] segs = [] for c in codes: p = disease_phrase(c, severity) if p: segs.append(p) if not segs: if is_normal is None: is_normal = ("normal" in (diagnosis_codes or [])) or (severity == "none") segs = ["normal"] if is_normal else [] if include_lesions: segs += lesion_phrases(lesion_codes) return segs def modality_phrase(code): return MODALITY.get(code, code) def anatomy_phrase(code): # Unknown anatomy (e.g. 'secondary_unknown') -> None so the region is omitted # rather than leaking a machine code into the prompt. return ANATOMY.get(code) # --------------------------------------------------------------------------- # # self-test / inspection # # --------------------------------------------------------------------------- # if __name__ == "__main__": print("=== modality ===", MODALITY) print("=== anatomy ===", ANATOMY) print("=== diseases ===", list(DISEASE)) print("=== pseudo-label target ===", PSEUDO_TARGET_CLASSES) print("\n=== sample composed captions ===") samples = [ ("oct_bscan", "macula", "CNV", "unknown", ["CNV"]), ("oct_bscan", "macula", "DRUSEN", "unknown", []), ("oct_bscan", "macula", "DME", "unknown", ["IRF"]), ("fundus_color", None, "DR", 2, ["microaneurysms", "hard_exudates"]), ("fundus_color", None, "Glaucoma", "mild", []), ("oct_bscan", "macula", "MH_Stage3", None, []), ("oct_bscan", "macula", "NORMAL", "none", []), ("oct_bscan", "optic_disc", "Unknown", None, []), ] for mod, reg, raw, sev, les in samples: dx, dsev, dles = normalize_diagnosis(raw) sev_use = sev if sev is not None else dsev segs = [modality_phrase(mod)] if reg: segs.append(anatomy_phrase(reg)) segs += compose_disease_segment(dx, sev_use, (dles + les), include_lesions=True) print(f" raw={raw:11s} -> {', '.join(segs)}")