File size: 15,679 Bytes
e2f75d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/bin/env python3
"""
IDRiD adapter — DR grading + lesion segmentation + OD/fovea localization (single cohort).

Two image tracks (disjoint, distinguished by basename prefix):

  Grading + Localization track (516 = 413 train + 103 test):
      Inputs:
        B. Disease Grading/1. Original Images/{a|b}. {Training|Testing} Set/IDRiD_NNN.jpg
        B. Disease Grading/2. Groundtruths/{a|b}. IDRiD_Disease Grading_{Training|Testing} Labels.csv
        C. Localization/2. Groundtruths/1. Optic Disc Center Location/*.csv
        C. Localization/2. Groundtruths/2. Fovea Center Location/*.csv
      Manifest row: DR grade + DME risk; has_segmentation=False.
      Sidecar parquet: OD + fovea pixel coords + image dims.

  Segmentation track (81 = 54 train + 27 test):
      Inputs:
        A. Segmentation/1. Original Images/{a|b}. {Training|Testing} Set/IDRiD_NN.jpg
        A. Segmentation/2. All Segmentation Groundtruths/.../{MA,HE,EX,SE,OD}.tif
      Mask suffix per class: MA=microaneurysms, HE=haemorrhages, EX=hard exudates,
                              SE=soft exudates, OD=optic disc.
      Manifest row: has_segmentation=True; lesion_tags driven by which masks exist.

Outputs (under {output_root}):
    extracted/public_idrid/{hash[:2]}/{hash}/
        fundus_color.jpg
        lesion_microaneurysms.png    (binary 0/255, present only in seg track)
        lesion_haemorrhages.png
        lesion_hard_exudates.png
        lesion_soft_exudates.png
        optic_disc_mask.png
        meta.json
    manifest/public_idrid_images.parquet
    manifest/public_idrid_sidecar.parquet         (localization coords)
    captions/public_idrid_captions.parquet
"""
import argparse
import json
from pathlib import Path

import numpy as np
import pandas as pd
from PIL import Image

from public_common import (
    IMAGE_SCHEMA_COLUMNS, CAPTION_SCHEMA_COLUMNS,
    study_hash_for, default_base_fields,
    caption_l1_public, caption_l3_public,
    study_dir_for, rel_file_path, write_meta, coerce_image_row,
)

COHORT = "public_idrid"
COHORT_PHRASE = "IDRiD diabetic retinopathy dataset"

DR_SEVERITY = {0: "none", 1: "mild", 2: "moderate", 3: "severe", 4: "proliferative"}
DME_RISK = {0: None, 1: "macular_edema", 2: "clinically_significant_macular_edema"}

LESION_SUFFIX = {
    "MA": ("microaneurysms",    "lesion_microaneurysms.png"),
    "HE": ("haemorrhages",      "lesion_haemorrhages.png"),
    "EX": ("hard_exudates",     "lesion_hard_exudates.png"),
    "SE": ("soft_exudates",     "lesion_soft_exudates.png"),
    "OD": ("optic_disc",        "optic_disc_mask.png"),
}


def _binarize_save(src: Path, dst: Path):
    arr = np.array(Image.open(src).convert("L"))
    Image.fromarray(((arr > 0).astype(np.uint8) * 255), mode="L").save(
        dst, "PNG", optimize=True)


def _save_fundus(src: Path, dst: Path):
    img = Image.open(src).convert("RGB")
    img.save(dst, "JPEG", quality=95)
    return img.size  # (w, h)


# ============================================================
# Grading + Localization track
# ============================================================

def _load_grading_labels(in_root: Path) -> pd.DataFrame:
    parts = []
    for split, fn in [
        ("train", "B. Disease Grading/2. Groundtruths/a. IDRiD_Disease Grading_Training Labels.csv"),
        ("test",  "B. Disease Grading/2. Groundtruths/b. IDRiD_Disease Grading_Testing Labels.csv"),
    ]:
        df = pd.read_csv(in_root / fn)
        df = df[[c for c in df.columns if not c.startswith("Unnamed")]]
        df.columns = [c.strip() for c in df.columns]
        df = df.rename(columns={
            "Image name": "image_name",
            "Retinopathy grade": "dr_grade",
            "Risk of macular edema": "dme_risk",
        })
        df = df.dropna(subset=["image_name"])
        df["split"] = split
        parts.append(df)
    return pd.concat(parts, ignore_index=True)


def _load_loc_csv(p: Path, prefix: str) -> dict:
    df = pd.read_csv(p)
    df = df[[c for c in df.columns if not c.startswith("Unnamed")]]
    df.columns = [c.strip() for c in df.columns]
    df = df.rename(columns={"Image No": "image_name",
                            "X- Coordinate": f"{prefix}_x",
                            "Y - Coordinate": f"{prefix}_y"})
    df = df.dropna(subset=["image_name"])
    return df.set_index("image_name")[[f"{prefix}_x", f"{prefix}_y"]].to_dict(orient="index")


def process_grading(in_root: Path, out_root: Path, force: bool):
    labels = _load_grading_labels(in_root)
    od_train = _load_loc_csv(in_root / "C. Localization/2. Groundtruths/1. Optic Disc Center Location/a. IDRiD_OD_Center_Training Set_Markups.csv", "od")
    od_test  = _load_loc_csv(in_root / "C. Localization/2. Groundtruths/1. Optic Disc Center Location/b. IDRiD_OD_Center_Testing Set_Markups.csv", "od")
    fv_train = _load_loc_csv(in_root / "C. Localization/2. Groundtruths/2. Fovea Center Location/IDRiD_Fovea_Center_Training Set_Markups.csv", "fovea")
    fv_test  = _load_loc_csv(in_root / "C. Localization/2. Groundtruths/2. Fovea Center Location/IDRiD_Fovea_Center_Testing Set_Markups.csv", "fovea")
    od_all = {**od_train, **od_test}
    fv_all = {**fv_train, **fv_test}

    rows, caps, side = [], [], []
    for _, lab in labels.iterrows():
        name = str(lab["image_name"]).strip()
        split = lab["split"]
        src = in_root / f"B. Disease Grading/1. Original Images/{'a. Training Set' if split=='train' else 'b. Testing Set'}/{name}.jpg"
        if not src.exists():
            print(f"  [grading] missing image {src}")
            continue

        basename = f"grading_{split}_{name}"
        sh = study_hash_for(COHORT, basename)
        sdir = study_dir_for(out_root, COHORT, sh)
        sdir.mkdir(parents=True, exist_ok=True)

        meta_p = sdir / "meta.json"
        if meta_p.exists() and not force:
            try:
                meta = json.loads(meta_p.read_text())
                if meta.get("status") == "ok":
                    rows.append(_grading_row(meta))
                    caps.extend(_grading_caps(meta))
                    side.append(_sidecar_row(meta))
                    continue
            except Exception:
                pass

        w, h = _save_fundus(src, sdir / "fundus_color.jpg")
        od = od_all.get(name, {})
        fv = fv_all.get(name, {})
        meta = {
            "status": "ok", "cohort": COHORT, "study_hash": sh,
            "source_basename": basename, "track": "grading",
            "split": split,
            "image_height_px": int(h), "image_width_px": int(w),
            "eye": "unknown",
            "dr_grade": int(lab["dr_grade"]) if pd.notna(lab["dr_grade"]) else None,
            "dme_risk": int(lab["dme_risk"]) if pd.notna(lab["dme_risk"]) else None,
            "od_x_px": float(od.get("od_x")) if od else None,
            "od_y_px": float(od.get("od_y")) if od else None,
            "fovea_x_px": float(fv.get("fovea_x")) if fv else None,
            "fovea_y_px": float(fv.get("fovea_y")) if fv else None,
        }
        write_meta(sdir, meta)
        rows.append(_grading_row(meta))
        caps.extend(_grading_caps(meta))
        side.append(_sidecar_row(meta))

    print(f"[{COHORT}/grading] {len(rows)} rows")
    return rows, caps, side


def _grading_row(meta: dict) -> dict:
    sh = meta["study_hash"]
    image_id = f"{COHORT}_{sh}_fundus_color"
    row = default_base_fields(COHORT, sh, eye=meta["eye"])

    dr = meta.get("dr_grade")
    dme_risk = meta.get("dme_risk")
    dx, lesions = [], []
    if dr is not None and dr > 0:
        dx.append("DR")
    if dme_risk and dme_risk > 0:
        dx.append("DME")
        tag = DME_RISK.get(dme_risk)
        if tag:
            lesions.append(tag)
    row["diagnosis_group"] = dx
    row["lesion_tags"] = lesions
    row["severity"] = DR_SEVERITY.get(dr, "unknown")
    row["diagnosis_source"] = "expert_grade" if dr is not None else "none"
    row["label_confidence"] = "consensus" if dr is not None else None

    row.update({
        "image_id": image_id,
        "file_path": rel_file_path(COHORT, sh, "fundus_color.jpg"),
        "file_format": "jpg",
        "modality": "fundus_color", "anatomy": "macula",
        "device_technology": "fundus_camera", "scan_protocol": "single_shot",
        "image_height_px": meta["image_height_px"],
        "image_width_px": meta["image_width_px"],
        "has_segmentation": False, "n_layers_visible": 0,
        "is_valid": True,
    })
    return row


def _grading_caps(meta: dict) -> list:
    sh = meta["study_hash"]
    image_id = f"{COHORT}_{sh}_fundus_color"
    caps = caption_l1_public(image_id, COHORT_PHRASE, "fundus_color", meta["eye"])
    parts = [f"A color fundus photograph from the IDRiD dataset ({meta['split']} split)"]
    if meta.get("dr_grade") is not None:
        parts.append(f"diabetic retinopathy grade {meta['dr_grade']} ({DR_SEVERITY[meta['dr_grade']]})")
    if meta.get("dme_risk") is not None and meta["dme_risk"] > 0:
        parts.append(f"macular edema risk {meta['dme_risk']}")
    l3 = ", ".join(parts) + "."
    caps.append(caption_l3_public(image_id, l3, "manifest_fields+csv_labels"))
    return caps


def _sidecar_row(meta: dict) -> dict:
    sh = meta["study_hash"]
    return {
        "image_id": f"{COHORT}_{sh}_fundus_color",
        "split": meta.get("split"),
        "od_x_px": meta.get("od_x_px"),
        "od_y_px": meta.get("od_y_px"),
        "fovea_x_px": meta.get("fovea_x_px"),
        "fovea_y_px": meta.get("fovea_y_px"),
        "image_width_px": meta.get("image_width_px"),
        "image_height_px": meta.get("image_height_px"),
    }


# ============================================================
# Segmentation track
# ============================================================

def process_segmentation(in_root: Path, out_root: Path, force: bool):
    seg_dir = in_root / "A. Segmentation"
    rows, caps = [], []
    for split, sub_img, sub_gt in [
        ("train", "a. Training Set", "a. Training Set"),
        ("test",  "b. Testing Set",  "b. Testing Set"),
    ]:
        img_dir = seg_dir / "1. Original Images" / sub_img
        gt_dir = seg_dir / "2. All Segmentation Groundtruths" / sub_gt
        for ip in sorted(img_dir.glob("IDRiD_*.jpg")):
            name = ip.stem  # IDRiD_01
            basename = f"seg_{split}_{name}"
            sh = study_hash_for(COHORT, basename)
            sdir = study_dir_for(out_root, COHORT, sh)
            sdir.mkdir(parents=True, exist_ok=True)

            meta_p = sdir / "meta.json"
            if meta_p.exists() and not force:
                try:
                    meta = json.loads(meta_p.read_text())
                    if meta.get("status") == "ok":
                        rows.append(_seg_row(meta))
                        caps.extend(_seg_caps(meta))
                        continue
                except Exception:
                    pass

            w, h = _save_fundus(ip, sdir / "fundus_color.jpg")
            has_mask = {}
            for suffix, (label, fname) in LESION_SUFFIX.items():
                subdir_idx = {"MA": "1. Microaneurysms", "HE": "2. Haemorrhages",
                              "EX": "3. Hard Exudates", "SE": "4. Soft Exudates",
                              "OD": "5. Optic Disc"}[suffix]
                src = gt_dir / subdir_idx / f"{name}_{suffix}.tif"
                if src.exists():
                    _binarize_save(src, sdir / fname)
                    has_mask[label] = True
                else:
                    has_mask[label] = False

            meta = {
                "status": "ok", "cohort": COHORT, "study_hash": sh,
                "source_basename": basename, "track": "segmentation",
                "split": split,
                "image_height_px": int(h), "image_width_px": int(w),
                "eye": "unknown",
                **{f"has_{k}_mask": v for k, v in has_mask.items()},
            }
            write_meta(sdir, meta)
            rows.append(_seg_row(meta))
            caps.extend(_seg_caps(meta))

    print(f"[{COHORT}/seg] {len(rows)} rows")
    return rows, caps


def _seg_row(meta: dict) -> dict:
    sh = meta["study_hash"]
    image_id = f"{COHORT}_{sh}_fundus_color"
    row = default_base_fields(COHORT, sh, eye=meta["eye"])
    lesions = []
    for label in ("microaneurysms", "haemorrhages", "hard_exudates", "soft_exudates"):
        if meta.get(f"has_{label}_mask"):
            lesions.append(label)
    if lesions:
        row["diagnosis_group"] = ["DR"]  # any DR-related lesion implies DR positive
        row["lesion_tags"] = lesions
    row["diagnosis_source"] = "expert_segmentation" if lesions else "none"
    row.update({
        "image_id": image_id,
        "file_path": rel_file_path(COHORT, sh, "fundus_color.jpg"),
        "file_format": "jpg",
        "modality": "fundus_color", "anatomy": "macula",
        "device_technology": "fundus_camera", "scan_protocol": "single_shot",
        "image_height_px": meta["image_height_px"],
        "image_width_px": meta["image_width_px"],
        "has_segmentation": True, "n_layers_visible": 0,
        "is_valid": True,
    })
    return row


def _seg_caps(meta: dict) -> list:
    sh = meta["study_hash"]
    image_id = f"{COHORT}_{sh}_fundus_color"
    caps = caption_l1_public(image_id, COHORT_PHRASE, "fundus_color", meta["eye"])
    present = [k for k in ("microaneurysms", "haemorrhages", "hard_exudates", "soft_exudates", "optic_disc")
               if meta.get(f"has_{k}_mask")]
    parts = [f"A color fundus photograph from the IDRiD dataset ({meta['split']} split, segmentation subset)"]
    if present:
        parts.append("with manually annotated " + ", ".join(p.replace("_", " ") for p in present) + " segmentation masks")
    l3 = ", ".join(parts) + "."
    caps.append(caption_l3_public(image_id, l3, "manifest_fields+mask_presence"))
    return caps


# ============================================================
# Main
# ============================================================

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input-root", required=True,
                    help="Path to .../Generation/IDRiD (contains A./B./C. subdirs)")
    ap.add_argument("--output-root", required=True)
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--skip-grading", action="store_true")
    ap.add_argument("--skip-segmentation", action="store_true")
    args = ap.parse_args()

    in_root = Path(args.input_root)
    out_root = Path(args.output_root)

    rows, caps, side = [], [], []
    if not args.skip_grading:
        r, c, s = process_grading(in_root, out_root, args.force)
        rows += r; caps += c; side += s
    if not args.skip_segmentation:
        r, c = process_segmentation(in_root, out_root, args.force)
        rows += r; caps += c

    if not rows:
        print(f"[{COHORT}] no rows produced")
        return

    mdir = out_root / "manifest"
    cdir = out_root / "captions"
    mdir.mkdir(parents=True, exist_ok=True)
    cdir.mkdir(parents=True, exist_ok=True)

    imgs_df = pd.DataFrame([coerce_image_row(r) for r in rows])[IMAGE_SCHEMA_COLUMNS]
    imgs_df.to_parquet(mdir / f"{COHORT}_images.parquet", index=False)
    caps_df = pd.DataFrame(caps)[CAPTION_SCHEMA_COLUMNS]
    caps_df.to_parquet(cdir / f"{COHORT}_captions.parquet", index=False)
    if side:
        pd.DataFrame(side).to_parquet(mdir / f"{COHORT}_sidecar.parquet", index=False)

    print(f"[{COHORT}] wrote {len(imgs_df)} images, {len(caps_df)} captions, {len(side)} sidecar")
    print(imgs_df.groupby(["has_segmentation", "severity"]).size().to_string())


if __name__ == "__main__":
    main()