File size: 12,503 Bytes
3c366de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unified preprocessing for 7 fundus-image classification datasets.

Per dataset it produces:
    <dataset_root>/
        train/<label>/<img>
        val/<label>/<img>
        test/<label>/<img>
        labels.csv   (columns: split,filepath,label,class_name,orig_id)
and DELETES everything classification-irrelevant (segmentation masks, disc/fovea
localization, image-quality columns, extra preprocessing versions, other modalities,
upload templates, helper code, original nested folders ...).

Split policy (decided with the user):
  * Datasets WITH a complete official labeled split -> keep it:
        AIROGS (train/val/test),  APTOS (train/val/test),  DeepDRiD (train/val/test)
  * Datasets WITHOUT one -> stratified 7:1:2 (seed=42):
        MMAC (official has no test -> pool train+val and re-split),
        ADAM, IDRiD, PAPILA(grouped by patient)
Class encodings:
  MMAC   0..4 myopic-maculopathy grade
  ADAM   0=Non-AMD 1=AMD
  AIROGS 0=NRG    1=RG          (release-crop version only)
  PAPILA 0=healthy 1=glaucoma   (diagnosis==2 "suspect" dropped; split by patient)
  IDRiD  0..4 DR grade
  APTOS  0..4 DR grade
  DeepDRiD 0..4 DR grade        (regular fundus only; per-eye label)

Run dry-run first (prints the plan, moves nothing), then with --execute.
"""
import os, sys, csv, random, shutil
from collections import defaultdict
import pandas as pd

ROOT = "/mnt/tidal-alsh-share2/dataset/qinshengqian/research/c3/GPT-Image/Dataset"
SEED = 42
RATIOS = (0.7, 0.1, 0.2)
EXECUTE = "--execute" in sys.argv
KEEP = {"train", "val", "test", "labels.csv"}


# ----------------------------------------------------------------------------- helpers
def walk_index(root, exts=(".jpg", ".jpeg", ".png", ".tif", ".tiff", ".bmp")):
    """Map basename-without-extension -> absolute path for every image under root."""
    idx = {}
    for dp, _, files in os.walk(root):
        for f in files:
            if f.lower().endswith(exts):
                idx[os.path.splitext(f)[0]] = os.path.join(dp, f)
    return idx


def stratified_split(pairs, ratios=RATIOS, seed=SEED):
    """pairs: list[(key,label)] -> dict key->split, stratified per label."""
    by = defaultdict(list)
    for k, l in pairs:
        by[l].append(k)
    out, rnd = {}, random.Random(seed)
    for l in sorted(by, key=str):
        ks = sorted(by[l])
        rnd.shuffle(ks)
        n = len(ks)
        ntr = int(round(n * ratios[0]))
        nva = int(round(n * ratios[1]))
        # guarantee non-empty test when a class is large enough
        if n >= 3 and ntr + nva >= n:
            nva = max(0, n - ntr - 1)
        for i, k in enumerate(ks):
            out[k] = "train" if i < ntr else ("val" if i < ntr + nva else "test")
    return out


def place(out_dir, records, do_clean_root=True):
    """records: list of dict(src, split, label, class_name, orig_id).
    Moves files into out_dir/<split>/<label>/, writes labels.csv, then whitelist-cleans."""
    # collision check
    seen, dup = set(), 0
    for r in records:
        key = (r["split"], str(r["label"]), os.path.basename(r["src"]))
        if key in seen:
            dup += 1
        seen.add(key)
    counts = defaultdict(int)
    for r in records:
        counts[(r["split"], r["label"])] += 1
    # report
    name = os.path.basename(out_dir.rstrip("/"))
    total = len(records)
    print(f"  [{name}] total={total}  duplicates={dup}")
    for sp in ("train", "val", "test"):
        per = {l: c for (s, l), c in sorted(counts.items()) if s == sp}
        if per:
            print(f"     {sp:5s} n={sum(per.values()):5d}  by_class={per}")
    if dup:
        print(f"  !! {dup} basename collisions in same split/label — aborting this dataset")
        return
    if not EXECUTE:
        return
    rows = []
    for r in records:
        dd = os.path.join(out_dir, r["split"], str(r["label"]))
        os.makedirs(dd, exist_ok=True)
        base = os.path.basename(r["src"])
        dst = os.path.join(dd, base)
        shutil.move(r["src"], dst)
        rows.append([r["split"], os.path.join(r["split"], str(r["label"]), base),
                     r["label"], r["class_name"], r["orig_id"]])
    with open(os.path.join(out_dir, "labels.csv"), "w", newline="") as f:
        w = csv.writer(f)
        w.writerow(["split", "filepath", "label", "class_name", "orig_id"])
        w.writerows(sorted(rows))
    if do_clean_root:
        for item in os.listdir(out_dir):
            if item in KEEP:
                continue
            p = os.path.join(out_dir, item)
            shutil.rmtree(p) if os.path.isdir(p) else os.remove(p)
    print(f"     -> moved & cleaned: {out_dir}")


# ----------------------------------------------------------------------------- datasets
def do_mmac():
    out = os.path.join(ROOT, "Myopia", "Classification_of_Myopic_Maculopathy")
    base = os.path.join(out, "1. Classification of Myopic Maculopathy")
    gt = os.path.join(base, "2. Groundtruths")
    label_map = {}
    for fn in ["1. MMAC2023_Myopic_Maculopathy_Classification_Training_Labels.csv",
               "2. MMAC2023_Myopic_Maculopathy_Classification_Validation_Labels.csv"]:
        df = pd.read_csv(os.path.join(gt, fn))
        for _, r in df.iterrows():
            label_map[str(r["image"])] = int(r["myopic_maculopathy_grade"])
    idx = walk_index(os.path.join(base, "1. Images"))
    recs, pairs = [], []
    for img, g in label_map.items():
        key = os.path.splitext(img)[0]
        if key not in idx:
            continue
        pairs.append((key, g))
    sp = stratified_split(pairs)
    for key, g in pairs:
        recs.append(dict(src=idx[key], split=sp[key], label=g,
                         class_name=f"grade_{g}", orig_id=key))
    return out, recs


def do_adam():
    out = os.path.join(ROOT, "AMD", "adamdataset")
    base = os.path.join(out, "ADAM", "Training400")
    pairs, srcs = [], {}
    for sub, lab, cname in [("Non-AMD", 0, "Non-AMD"), ("AMD", 1, "AMD")]:
        for dp, _, files in os.walk(os.path.join(base, sub)):
            for f in files:
                if f.lower().endswith((".jpg", ".jpeg", ".png")):
                    k = os.path.splitext(f)[0]
                    pairs.append((k, lab))
                    srcs[k] = (os.path.join(dp, f), lab, cname)
    sp = stratified_split(pairs)
    recs = [dict(src=srcs[k][0], split=sp[k], label=srcs[k][1],
                 class_name=srcs[k][2], orig_id=k) for k, _ in pairs]
    return out, recs


def do_airogs():
    out = os.path.join(ROOT, "Glaucoma", "eyepacs-airogs-light")
    base = os.path.join(out, "release-crop", "release-crop")
    split_map = {"train": "train", "validation": "val", "test": "test"}
    cls = {"NRG": (0, "NRG"), "RG": (1, "RG")}
    recs = []
    for osp, nsp in split_map.items():
        for c, (lab, cname) in cls.items():
            d = os.path.join(base, osp, c)
            if not os.path.isdir(d):
                continue
            for f in os.listdir(d):
                if f.lower().endswith((".jpg", ".jpeg", ".png")):
                    recs.append(dict(src=os.path.join(d, f), split=nsp, label=lab,
                                     class_name=cname, orig_id=os.path.splitext(f)[0]))
    return out, recs


def do_papila():
    out = os.path.join(ROOT, "Glaucoma", "papila-retinal-fundus-images")
    base = os.path.join(out, "PapilaDB-PAPILA-17f8fa7746adb20275b5b6a0d99dc9dfe3007e9f")
    idx = walk_index(os.path.join(base, "FundusImages"))
    # build per-image label, grouped by patient
    eye_lab = {}          # image_key -> (label, patient)
    for eye, suffix in [("od", "OD"), ("os", "OS")]:
        df = pd.read_excel(os.path.join(base, "ClinicalData", f"patient_data_{eye}.xlsx"),
                           header=None)
        for _, r in df.iterrows():
            pid = str(r[0]).strip()
            if not pid.startswith("#"):
                continue
            num = int(pid[1:])
            diag = r[3]
            try:
                diag = int(float(diag))
            except (ValueError, TypeError):
                continue
            if diag == 2:          # suspect -> drop
                continue
            lab = 0 if diag == 0 else 1
            key = f"RET{num:03d}{suffix}"
            if key in idx:
                eye_lab[key] = (lab, f"RET{num:03d}")
    # patient-level label = glaucoma if any kept eye glaucoma
    pat_lab = defaultdict(int)
    for k, (lab, pat) in eye_lab.items():
        pat_lab[pat] = max(pat_lab[pat], lab)
    sp = stratified_split(list(pat_lab.items()))
    recs = []
    for k, (lab, pat) in eye_lab.items():
        recs.append(dict(src=idx[k], split=sp[pat], label=lab,
                         class_name=("healthy" if lab == 0 else "glaucoma"), orig_id=k))
    return out, recs


def do_idrid():
    out = os.path.join(ROOT, "DR", "idrid-dataset")
    df = pd.read_csv(os.path.join(out, "idrid_labels.csv"))
    idx = walk_index(os.path.join(out, "Imagenes"))
    pairs, srcs = [], {}
    for _, r in df.iterrows():
        k = str(r["id_code"]).strip()
        if k not in idx:
            continue
        lab = int(r["diagnosis"])
        pairs.append((k, lab))
        srcs[k] = lab
    sp = stratified_split(pairs)
    recs = [dict(src=idx[k], split=sp[k], label=srcs[k],
                 class_name=f"grade_{srcs[k]}", orig_id=k) for k, _ in pairs]
    return out, recs


def do_aptos():
    out = os.path.join(ROOT, "DR", "aptos2019")
    recs = []
    for csvname, sp, imgdir in [("train_1.csv", "train", "train_images"),
                                ("valid.csv", "val", "val_images"),
                                ("test.csv", "test", "test_images")]:
        df = pd.read_csv(os.path.join(out, csvname))
        idx = walk_index(os.path.join(out, imgdir))
        for _, r in df.iterrows():
            k = str(r["id_code"]).strip()
            if k not in idx:
                continue
            lab = int(r["diagnosis"])
            recs.append(dict(src=idx[k], split=sp, label=lab,
                             class_name=f"grade_{lab}", orig_id=k))
    return out, recs


def do_deepdrid():
    out = os.path.join(ROOT, "DR", "deepdrid")
    base = os.path.join(out, "DeepDRiD-master", "regular_fundus_images")

    def eye_level(row, image_id):
        col = "left_eye_DR_Level" if "_l" in image_id else "right_eye_DR_Level"
        v = row.get(col)
        if pd.isna(v):
            v = row.get("patient_DR_Level")
        return None if pd.isna(v) else int(v)

    recs = []
    # train + val from per-image csv
    for sub, sp in [("regular-fundus-training", "train"), ("regular-fundus-validation", "val")]:
        d = os.path.join(base, sub)
        df = pd.read_csv(os.path.join(d, f"{sub}.csv"))
        idx = walk_index(os.path.join(d, "Images"))
        for _, r in df.iterrows():
            iid = str(r["image_id"]).strip()
            if iid not in idx:
                continue
            lab = eye_level(r, iid)
            if lab is None or lab < 0 or lab > 4:
                continue
            recs.append(dict(src=idx[iid], split=sp, label=lab,
                             class_name=f"grade_{lab}", orig_id=iid))
    # test from Online-Challenge labels.xlsx
    ev = os.path.join(base, "Online-Challenge1&2-Evaluation")
    dfx = pd.read_excel(os.path.join(ev, "Challenge1_labels.xlsx"))
    idx = walk_index(os.path.join(ev, "Images"))
    col = "DR_Levels" if "DR_Levels" in dfx.columns else dfx.columns[-1]
    for _, r in dfx.iterrows():
        iid = str(r["image_id"]).strip()
        if iid not in idx or pd.isna(r[col]):
            continue
        lab = int(r[col])
        if 0 <= lab <= 4:
            recs.append(dict(src=idx[iid], split="test", label=lab,
                             class_name=f"grade_{lab}", orig_id=iid))
    return out, recs


DATASETS = [("MMAC/Myopia", do_mmac), ("ADAM/AMD", do_adam),
            ("AIROGS/Glaucoma", do_airogs), ("PAPILA/Glaucoma", do_papila),
            ("IDRiD/DR", do_idrid), ("APTOS/DR", do_aptos), ("DeepDRiD/DR", do_deepdrid)]


def main():
    only = [a for a in sys.argv[1:] if not a.startswith("--")]
    print(f"=== prepare_datasets ({'EXECUTE' if EXECUTE else 'DRY-RUN'}) seed={SEED} ===")
    for name, fn in DATASETS:
        if only and name.split("/")[0].lower() not in [o.lower() for o in only]:
            continue
        print(f"\n### {name}")
        out, recs = fn()
        place(out, recs)
    print("\n=== done ===")


if __name__ == "__main__":
    main()