File size: 6,806 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
#!/usr/bin/env python3
"""
EyePACS adapter — augmented_resized_V2 (143k DR-graded 600x600 fundus images).

Inputs:
    {input_root}/augmented_resized_V2/{train,val,test}/{0,1,2,3,4}/*.jpg
        Subdir name = DR grade. Filenames like 005b95c28852-600.jpg.

Outputs (under {output_root}):
    extracted/public_eyepacs_combo_dr_aug/{hash[:2]}/{hash}/
        fundus_color.jpg     (copied as-is — already 600x600)
        meta.json
    manifest/public_eyepacs_combo_dr_aug_images.parquet
    captions/public_eyepacs_combo_dr_aug_captions.parquet

143k images → multiprocessed. study_hash basename includes split to avoid hash collisions
if the same id_code appears across splits (it should not, but be defensive).
"""
import argparse
import json
import shutil
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path

import pandas as pd
from PIL import Image, ImageFile

ImageFile.LOAD_TRUNCATED_IMAGES = True

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_eyepacs_combo_dr_aug"
COHORT_PHRASE = "EyePACS combined diabetic retinopathy screening dataset (augmented 600x600 v2)"

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


def process_one(args):
    image_path_str, split, dr_grade, out_root_str, force = args
    image_path = Path(image_path_str)
    out_root = Path(out_root_str)
    basename = f"{split}_{image_path.stem}"  # e.g. train_005b95c28852-600
    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":
                return _row_and_caps(meta)
        except Exception:
            pass

    dst_img = sdir / "fundus_color.jpg"
    try:
        if not dst_img.exists() or force:
            shutil.copyfile(image_path, dst_img)
        # Verify the copy is a readable image (catches truncated / non-JPG bytes)
        with Image.open(dst_img) as im:
            im.verify()
        with Image.open(dst_img) as im:
            w, h = im.size
    except Exception as e:
        # Delete the partial copy so a future run can re-attempt
        try: dst_img.unlink(missing_ok=True)
        except Exception: pass
        return ("FAIL", basename, type(e).__name__, str(e)[:200])

    meta = {
        "status": "ok", "cohort": COHORT, "study_hash": sh,
        "source_basename": basename, "split": split,
        "image_height_px": int(h), "image_width_px": int(w),
        "eye": "unknown",
        "dr_grade": int(dr_grade),
    }
    write_meta(sdir, meta)
    return _row_and_caps(meta)


def _row_and_caps(meta: dict):
    sh = meta["study_hash"]
    image_id = f"{COHORT}_{sh}_fundus_color"
    row = default_base_fields(COHORT, sh, eye=meta["eye"])
    dr = meta["dr_grade"]
    row["diagnosis_group"] = ["DR"] if dr > 0 else []
    row["severity"] = DR_SEVERITY[dr]
    row["diagnosis_source"] = "screening_label"
    row["label_confidence"] = "single_reader"
    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,
    })
    caps = caption_l1_public(image_id, COHORT_PHRASE, "fundus_color", meta["eye"])
    l3 = (f"A color fundus photograph from the EyePACS combined DR screening dataset "
          f"({meta['split']} split, augmented 600x600), "
          f"diabetic retinopathy grade {dr} ({DR_SEVERITY[dr]}).")
    caps.append(caption_l3_public(image_id, l3, "manifest_fields+screening_label"))
    return row, caps


def _enumerate_inputs(in_root: Path):
    base = in_root / "augmented_resized_V2"
    for split in ("train", "val", "test"):
        for grade in range(5):
            d = base / split / str(grade)
            if not d.exists():
                continue
            for ip in d.glob("*.jpg"):
                yield (str(ip), split, grade)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input-root", required=True,
                    help="Path to .../Generation/EyePACS (contains augmented_resized_V2/)")
    ap.add_argument("--output-root", required=True)
    ap.add_argument("--num-workers", type=int, default=8)
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--limit", type=int, default=None)
    args = ap.parse_args()

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

    inputs = list(_enumerate_inputs(in_root))
    print(f"[{COHORT}] enumerated {len(inputs)} images")
    if args.limit:
        inputs = inputs[:args.limit]

    job_args = [(p, s, g, str(out_root), args.force) for (p, s, g) in inputs]

    rows, caps = [], []
    failures = []
    with ProcessPoolExecutor(max_workers=args.num_workers) as ex:
        futs = [ex.submit(process_one, a) for a in job_args]
        for i, fut in enumerate(as_completed(futs), 1):
            try:
                result = fut.result()
            except Exception as e:
                failures.append(("worker", type(e).__name__, str(e)[:200]))
                continue
            if isinstance(result, tuple) and len(result) == 4 and result[0] == "FAIL":
                failures.append(result[1:])
                continue
            row, cap = result
            rows.append(row)
            caps.extend(cap)
            if i % 5000 == 0:
                print(f"  ... {i}/{len(futs)} ({len(failures)} failed so far)")
    if failures:
        print(f"[{COHORT}] {len(failures)} images FAILED to extract:")
        for f in failures[:30]:
            print(f"  {f}")

    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)
    print(f"[{COHORT}] wrote {len(imgs_df)} images, {len(caps_df)} captions")
    print(imgs_df.groupby(["severity"]).size().to_string())


if __name__ == "__main__":
    main()