File size: 14,477 Bytes
79017c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#!/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)}")