MaybeRichard commited on
Commit
ec7f8fa
·
verified ·
1 Parent(s): ca2121c

set device_technology=unknown for NYU_POAG/C8 (no assumption); add device-granularity guidance to overview

Browse files
DATASET_OVERVIEW.md CHANGED
@@ -516,6 +516,28 @@ angle_deg = bscan_index * 15.0 # 0°, 15°, ..., 165°
516
 
517
  对 GAMMA / OCTA500 的 volume slice:`bscan_index` 是 slice 序号(0..255 或 0..399),可做 axial position embedding。
518
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
  ### 12.8 三模态 spatial 配准(私有 Topcon)
520
 
521
  每个私有 study 的 fundus / SLO 行 manifest 含:
 
516
 
517
  对 GAMMA / OCTA500 的 volume slice:`bscan_index` 是 slice 序号(0..255 或 0..399),可做 axial position embedding。
518
 
519
+ ### 12.7.1 设备条件化粒度建议(重要)
520
+
521
+ manifest 提供三级设备粒度:`device_technology`(SS/SD/TD-OCT)、`device_vendor`(厂商)、`device_model`(型号)。**生成式训练的条件化不要用到型号级,用 technology + vendor 两级最稳**。
522
+
523
+ **设备差异对生成的真实影响(从大到小)**:
524
+
525
+ | 粒度 | 视觉差异 | 生成条件价值 |
526
+ |---|---|---|
527
+ | `device_technology` (SS/SD/TD-OCT) | **最大**:SS-OCT(1050nm) 脉络膜穿透深、speckle 不同;TD-OCT 分辨率明显低 | 🔴 **必须条件化** |
528
+ | `device_vendor` (Heidelberg/Zeiss/Optovue/Topcon/Bioptigen/BMizar) | 中等:各家去噪管线、对比度、长宽比有可辨识风格 | 🟡 **建议条件化** |
529
+ | `device_model` (Cirrus 4000 vs 5000 vs 6000) | 很小:同厂同代际差异微弱 | 🟢 **不做主条件**,留作 metadata 过滤/检索 |
530
+
531
+ **数据量现实**(条件化需每条件足够样本):按型号粒度好几个条件数据饥饿 —— Zeiss Stratus TD-OCT 仅 49 张、Topcon 3D OCT 2,688 张、Cirrus 拆 4000/5000 各 3-13k,撑不起独立 conditional mode;但归到 technology/vendor 粒度,每桶都充足(Heidelberg Spectralis 系 197k、Optovue 122k、Topcon Triton SS-OCT 私有 374k、Bioptigen 38k、BMizar 33k)。
532
+
533
+ **实操**:
534
+ - 主条件轴 = `device_technology`(3 类,TD-OCT 49 张可并入 SD 极端低质子集或单独标但不指望生成质量)
535
+ - 次条件轴 = `device_vendor`(想做风格控制时用)
536
+ - `device_model` 已写进 caption(如 "Heidelberg Spectralis SD-OCT")+ manifest 列,文本编码器会自然软忽略型号细节,无需显式建 embedding
537
+ - 比设备更重要的条件:`modality` + `anatomy` + `severity`/`diagnosis_group`(疾病),设备是第二梯队
538
+
539
+ **未知设备处理**:NYU_POAG (56,576) + C8 (24,000) 源数据未披露设备 → `device_vendor=unknown, device_model=unknown, device_technology=unknown`(不做技术类型假设),caption 不写设备短语(不编造)。这两个 cohort 不应进入任何 device-conditioned 子集,只用于无条件/疾病条件预训练。
540
+
541
  ### 12.8 三模态 spatial 配准(私有 Topcon)
542
 
543
  每个私有 study 的 fundus / SLO 行 manifest 含:
code/build_oct_public.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Adapter for 19 OCT public datasets → 41-col manifest (matching private/fundus schema).
4
+
5
+ 19 cohorts:
6
+ 17 A-class (enumerated via existing unified_metadata.csv):
7
+ public_oct_kermany, public_oct_octid, public_oct_aroi, public_oct_neh_ut_2021,
8
+ public_oct_areds2, public_oct_glaucoma, public_oct_nyu_poag, public_oct_olives,
9
+ public_oct_chiu_dme_2015, public_oct_srinivasan_2014, public_oct_sparsity_sdoct_2012,
10
+ public_oct_oimhs, public_oct_retouch, public_oct_thoct1800, public_oct_octdl,
11
+ public_oct_amd_sd, public_oct_c8
12
+ + 2 enumerated from source layout:
13
+ public_oct_octa500, public_oct_uestc
14
+
15
+ Output layout (under {output_root}):
16
+ extracted/{cohort}/{hash[:2]}/{hash}/{bscan.png|bscan_NNN.png}{+meta.json}{+masks}
17
+ manifest/{cohort}_images.parquet
18
+ manifest/{cohort}_sidecar.parquet (where applicable)
19
+ captions/{cohort}_captions.parquet
20
+
21
+ Notes:
22
+ - Most cohorts use file-level study_id (1 bscan = 1 study). patient_hash is shared
23
+ across bscans of same patient when patient_id is known.
24
+ - OLIVES uses study_id = hash(patient_eye_visit), patient_hash = hash(patient).
25
+ - OCTA500 and UESTC use file-level study_id (volume info preserved in source_basename).
26
+ - Masks (where present) are copied to study_dir as auxiliary files; not in manifest rows.
27
+ """
28
+ import argparse
29
+ import os
30
+ import re
31
+ from collections import defaultdict
32
+ from pathlib import Path
33
+
34
+ import pandas as pd
35
+
36
+ from public_common import (
37
+ default_base_fields, study_hash_for, rel_file_path,
38
+ )
39
+ from oct_public_common import (
40
+ caption_l1_oct, caption_l3_oct, device_phrase,
41
+ save_mask_preserve, run_cohort,
42
+ )
43
+
44
+
45
+ # ============================================================
46
+ # Disease label → (diagnosis_group, severity)
47
+ # ============================================================
48
+
49
+ DR_SEVERITY = {0: "none", 1: "mild", 2: "moderate", 3: "severe", 4: "proliferative"}
50
+
51
+ DISEASE_MAP = {
52
+ # Normal variants
53
+ "NORMAL": ([], "none"),
54
+ "Normal": ([], "none"),
55
+ "NOR": ([], "none"),
56
+ "NO": ([], "none"),
57
+ "Control": ([], "none"),
58
+ "CONTROL": ([], "none"),
59
+ # Disease classes
60
+ "CNV": (["CNV"], "unknown"),
61
+ "DME": (["DME"], "unknown"),
62
+ "DRUSEN": (["DRUSEN"], "unknown"),
63
+ "DR": (["DR"], "unknown"),
64
+ "AMD": (["AMD"], "unknown"),
65
+ "wet_AMD": (["wet_AMD"], "unknown"),
66
+ "nAMD": (["nAMD"], "unknown"),
67
+ "AMD/RVO": (["AMD", "RVO"], "unknown"),
68
+ "CSR": (["CSR"], "unknown"),
69
+ "MH": (["MH"], "unknown"),
70
+ "MH_Stage1": (["MH"], "mild"),
71
+ "MH_Stage2": (["MH"], "moderate"),
72
+ "MH_Stage3": (["MH"], "severe"),
73
+ "MH_Stage4": (["MH"], "severe"),
74
+ "Glaucoma": (["glaucoma"], "unknown"),
75
+ "POAG": (["glaucoma"], "unknown"),
76
+ "ERM": (["ERM"], "unknown"),
77
+ "RVO": (["RVO"], "unknown"),
78
+ "RAO": (["RAO"], "unknown"),
79
+ "VID": (["VID"], "unknown"),
80
+ # Unknown / fallback
81
+ "Unknown": ([], "unknown"),
82
+ }
83
+
84
+
85
+ def map_disease(label):
86
+ return DISEASE_MAP.get(str(label).strip(), (["unknown_disease"], "unknown"))
87
+
88
+
89
+ # ============================================================
90
+ # Per-cohort static config (device, anatomy, scan_protocol, ethnicity)
91
+ # ============================================================
92
+
93
+ COHORT_CONFIG = {
94
+ "public_oct_kermany": dict(
95
+ phrase="Kermany 2018 OCT classification dataset (UCSD / Cell)",
96
+ vendor="heidelberg", model="spectralis", tech="sd_oct",
97
+ anatomy="macula", scan_protocol="single_shot",
98
+ ethnicity="Mixed", hospital_domain="kermany_ucsd_v1"),
99
+ "public_oct_octid": dict(
100
+ phrase="OCTID Indian retinal OCT classification dataset",
101
+ vendor="zeiss", model="cirrus_hd_oct_5000", tech="sd_oct",
102
+ anatomy="macula", scan_protocol="single_shot",
103
+ ethnicity="South Asian", hospital_domain="octid_sankara_v1"),
104
+ "public_oct_aroi": dict(
105
+ phrase="AROI nAMD layer segmentation dataset (Croatia)",
106
+ vendor="zeiss", model="cirrus_hd_oct_4000", tech="sd_oct",
107
+ anatomy="macula", scan_protocol="volume_3d_macula",
108
+ ethnicity="European", hospital_domain="aroi_zagreb_v1"),
109
+ "public_oct_neh_ut_2021": dict(
110
+ phrase="NEH-UT-2021 Iranian retinal OCT dataset",
111
+ vendor="heidelberg", model="spectralis_sd_oct", tech="sd_oct",
112
+ anatomy="macula", scan_protocol="single_shot",
113
+ ethnicity="Middle Eastern", hospital_domain="neh_ut_2021_v1"),
114
+ "public_oct_areds2": dict(
115
+ phrase="AREDS2 ancillary SD-OCT AMD dataset (NEI)",
116
+ vendor="bioptigen", model="bioptigen_sd_oct", tech="sd_oct",
117
+ anatomy="macula", scan_protocol="volume_3d_macula",
118
+ ethnicity="Mixed", hospital_domain="areds2_nei_v1"),
119
+ "public_oct_glaucoma": dict(
120
+ phrase="Glaucoma OCT and fundus dataset (TD-OCT)",
121
+ vendor="zeiss", model="stratus_oct", tech="td_oct",
122
+ anatomy="optic_disc", scan_protocol="single_shot",
123
+ ethnicity="unknown", hospital_domain="glaucoma_oct_v1"),
124
+ "public_oct_nyu_poag": dict(
125
+ phrase="NYU POAG retinal OCT dataset",
126
+ vendor="unknown", model="unknown", tech="unknown",
127
+ anatomy="optic_disc", scan_protocol="volume_3d_macula",
128
+ ethnicity="unknown", hospital_domain="nyu_poag_v1"),
129
+ "public_oct_olives": dict(
130
+ phrase="OLIVES longitudinal DR and DME OCT dataset",
131
+ vendor="heidelberg", model="spectralis_hra_oct", tech="sd_oct",
132
+ anatomy="macula", scan_protocol="volume_3d_macula",
133
+ ethnicity="unknown", hospital_domain="olives_v1"),
134
+ "public_oct_chiu_dme_2015": dict(
135
+ phrase="Chiu et al. 2015 DME 8-layer segmentation dataset (Duke)",
136
+ vendor="heidelberg", model="spectralis", tech="sd_oct",
137
+ anatomy="macula", scan_protocol="volume_3d_macula",
138
+ ethnicity="unknown", hospital_domain="chiu_duke_2015_v1"),
139
+ "public_oct_srinivasan_2014": dict(
140
+ phrase="Srinivasan et al. 2014 AMD-DME-Normal OCT dataset (Duke/Harvard/Michigan)",
141
+ vendor="heidelberg", model="spectralis", tech="sd_oct",
142
+ anatomy="macula", scan_protocol="volume_3d_macula",
143
+ ethnicity="unknown", hospital_domain="srinivasan_2014_v1"),
144
+ "public_oct_sparsity_sdoct_2012": dict(
145
+ phrase="Sparsity SDOCT 2012 AMD vs control dataset",
146
+ vendor="bioptigen", model="bioptigen_sd_oct", tech="sd_oct",
147
+ anatomy="macula", scan_protocol="volume_3d_macula",
148
+ ethnicity="unknown", hospital_domain="sparsity_sdoct_2012_v1"),
149
+ "public_oct_oimhs": dict(
150
+ phrase="OIMHS macular hole staging and layer segmentation dataset",
151
+ vendor="heidelberg", model="spectralis_sd_oct", tech="sd_oct",
152
+ anatomy="macula", scan_protocol="volume_3d_macula",
153
+ ethnicity="Asian", hospital_domain="oimhs_china_v1"),
154
+ "public_oct_retouch": dict(
155
+ phrase="RETOUCH 2017 retinal fluid segmentation challenge dataset",
156
+ vendor="varies", model="varies", tech="sd_oct", # 3 sub-vendors
157
+ anatomy="macula", scan_protocol="volume_3d_macula",
158
+ ethnicity="European", hospital_domain="retouch_v1"),
159
+ "public_oct_thoct1800": dict(
160
+ phrase="THOCT1800 Tsinghua AMD-DME-Normal OCT dataset",
161
+ vendor="zeiss", model="cirrus_hd_oct", tech="sd_oct",
162
+ anatomy="macula", scan_protocol="single_shot",
163
+ ethnicity="Asian", hospital_domain="thoct1800_tsinghua_v1"),
164
+ "public_oct_octdl": dict(
165
+ phrase="OCTDL Russian 7-class retinal OCT dataset",
166
+ vendor="optovue", model="rtvue_xr_avanti", tech="sd_oct",
167
+ anatomy="macula", scan_protocol="single_shot",
168
+ ethnicity="European", hospital_domain="octdl_russia_v1"),
169
+ "public_oct_amd_sd": dict(
170
+ phrase="AMD-SD wet AMD multi-class segmentation dataset (China)",
171
+ vendor="zeiss", model="cirrus_hd_oct_5000", tech="sd_oct",
172
+ anatomy="macula", scan_protocol="single_shot",
173
+ ethnicity="Asian", hospital_domain="amd_sd_nanchang_v1"),
174
+ "public_oct_c8": dict(
175
+ phrase="C8 compiled 8-class retinal OCT classification dataset (Kaggle)",
176
+ vendor="unknown", model="unknown", tech="unknown",
177
+ anatomy="macula", scan_protocol="single_shot",
178
+ ethnicity="unknown", hospital_domain="c8_kaggle_v1"),
179
+ "public_oct_octa500": dict(
180
+ phrase="OCTA-500 multi-modal OCT-A and OCT structural retinal dataset",
181
+ vendor="optovue", model="rtvue_xr_avanti", tech="sd_oct",
182
+ anatomy="macula", scan_protocol="volume_3d_macula",
183
+ ethnicity="Asian", hospital_domain="octa500_njust_v1"),
184
+ "public_oct_uestc": dict(
185
+ phrase="UESTC despeckling 3D OCT dataset (BMizar + Spectralis)",
186
+ vendor="varies", model="varies", tech="sd_oct",
187
+ anatomy="macula", scan_protocol="volume_3d_macula",
188
+ ethnicity="Asian", hospital_domain="uestc_sichuan_v1"),
189
+ }
190
+
191
+
192
+ # ============================================================
193
+ # Shared row+caps builder for "standard" cohorts
194
+ # ============================================================
195
+
196
+ def _shared_build_row_caps(meta, cohort, cohort_phrase,
197
+ has_segmentation_fn=None,
198
+ l3_extras_fn=None,
199
+ scan_protocol_override=None):
200
+ """Default row/caps builder. Returns (list_of_rows, list_of_captions).
201
+ Multi-slice studies emit one row per slice; all share study_id + patient_hash."""
202
+ cfg = COHORT_CONFIG[cohort]
203
+ sh = meta["study_hash"]
204
+ ph = meta["patient_hash"]
205
+ eye = meta.get("eye", "unknown")
206
+ disease_label = meta.get("disease_label", "Unknown")
207
+ dx, sev = map_disease(disease_label)
208
+
209
+ base = default_base_fields(
210
+ cohort, sh, patient_hash=ph, eye=eye,
211
+ ethnicity=cfg["ethnicity"], hospital_domain=cfg["hospital_domain"])
212
+ base["device_vendor"] = meta.get("device_vendor", cfg["vendor"])
213
+ base["device_model"] = meta.get("device_model", cfg["model"])
214
+ base["diagnosis_group"] = dx
215
+ base["severity"] = sev
216
+ if disease_label and disease_label != "Unknown":
217
+ base["diagnosis_source"] = meta.get("diagnosis_source", "expert_label")
218
+
219
+ rows, caps = [], []
220
+ n_slices = meta["n_slices"]
221
+ for slc in meta["slices"]:
222
+ idx = slc["idx"]
223
+ if idx is None:
224
+ image_id = f"{cohort}_{sh}_bscan"
225
+ file_path = rel_file_path(cohort, sh, "bscan.png")
226
+ else:
227
+ image_id = f"{cohort}_{sh}_bscan_{idx:03d}"
228
+ file_path = rel_file_path(cohort, sh, slc["fname"])
229
+
230
+ row = dict(base)
231
+ has_seg = has_segmentation_fn(meta, slc) if has_segmentation_fn else bool(
232
+ meta.get("has_segmentation_mask"))
233
+ row.update({
234
+ "image_id": image_id,
235
+ "file_path": file_path,
236
+ "file_format": "png",
237
+ "modality": "oct_bscan",
238
+ "anatomy": cfg["anatomy"],
239
+ "device_technology": cfg["tech"],
240
+ "scan_protocol": scan_protocol_override or cfg["scan_protocol"],
241
+ "bscan_index": idx,
242
+ "image_height_px": slc["h"],
243
+ "image_width_px": slc["w"],
244
+ "has_segmentation": has_seg,
245
+ "n_layers_visible": 0,
246
+ "is_valid": True,
247
+ })
248
+ rows.append(row)
249
+
250
+ # 把 row 中的 device 传给 L1 caption (per-row, RETOUCH/UESTC 多设备 cohort 也对)
251
+ caps.extend(caption_l1_oct(image_id, cohort_phrase, eye,
252
+ device_vendor=row["device_vendor"],
253
+ device_model=row["device_model"]))
254
+ # L3 也把设备短语 prepend (若已知)
255
+ dev = device_phrase(row["device_vendor"], row["device_model"])
256
+ if dev:
257
+ l3_parts = [f"An OCT B-scan from {dev}, {cohort_phrase}"]
258
+ else:
259
+ l3_parts = [f"An OCT B-scan from the {cohort_phrase}"]
260
+ if disease_label and disease_label not in ("Unknown",):
261
+ l3_parts.append(f"label: {disease_label}")
262
+ if idx is not None and n_slices > 1:
263
+ l3_parts.append(f"slice {idx+1} of {n_slices}")
264
+ if l3_extras_fn:
265
+ l3_parts.extend(l3_extras_fn(meta, slc))
266
+ caps.append(caption_l3_oct(image_id, ", ".join(l3_parts) + ".",
267
+ "manifest_fields+csv_labels"))
268
+
269
+ return rows, caps
270
+
271
+
272
+ # ============================================================
273
+ # 17 A-class enumerators (read from unified_metadata.csv)
274
+ # ============================================================
275
+
276
+ def enum_from_csv_simple(ds_df, in_root, csv_dataset_name):
277
+ """File-level studies, patient_hash from patient_id when present.
278
+ study_basename = relative path with separators normalized to ensure uniqueness
279
+ across train/test/disease subdirs."""
280
+ in_root = Path(in_root)
281
+ items = []
282
+ seen_basenames = set()
283
+ for _, r in ds_df.iterrows():
284
+ src = r["image_path"]
285
+ if not os.path.exists(src):
286
+ continue
287
+ # Build unique basename from path relative to in_root
288
+ try:
289
+ rel = str(Path(src).relative_to(in_root))
290
+ except ValueError:
291
+ rel = src
292
+ # Sanitize: replace path separators + spaces + non-ascii safely
293
+ study_basename = re.sub(r"[^A-Za-z0-9._-]", "_", rel)
294
+ if study_basename in seen_basenames:
295
+ # Should not happen given uniqueness of file paths, but defensive
296
+ continue
297
+ seen_basenames.add(study_basename)
298
+
299
+ pid = str(r.get("patient_id", "")).strip()
300
+ patient_basename = f"patient_{pid}" if pid and pid not in ("Unknown", "nan", "") else study_basename
301
+ items.append({
302
+ "study_basename": study_basename,
303
+ "patient_basename": patient_basename,
304
+ "study_meta": {
305
+ "disease_label": r.get("disease_label", "Unknown"),
306
+ "eye": str(r.get("eye", "unknown")) if str(r.get("eye", "unknown")) != "Unknown" else "unknown",
307
+ "patient_id": pid if pid and pid != "Unknown" else None,
308
+ "device_csv": r.get("device", "unknown"),
309
+ "label_granularity": r.get("label_granularity", "b-scan"),
310
+ "notes": r.get("notes", ""),
311
+ },
312
+ "slices": [{"src_path": src, "slice_idx": None}],
313
+ })
314
+ return items
315
+
316
+
317
+ def enum_olives(ds_df, in_root):
318
+ """Special: study_id = hash(patient_eye_visit), patient_hash = hash(patient).
319
+ Multiple bscans of the same (patient, eye, visit) share study_id with slice_idx."""
320
+ visit_path_re = re.compile(r"/W(\d+)/")
321
+ # TREX flat filename: 11-01-001_W100_OD_0.tif → patient=01-001, visit=W100, eye=OD, slc=0
322
+ visit_fname_re = re.compile(r"_W(\d+)_(O[DS])_(\d+)\b")
323
+ groups = defaultdict(list)
324
+ for _, r in ds_df.iterrows():
325
+ src = r["image_path"]
326
+ if not os.path.exists(src):
327
+ continue
328
+ pid = str(r.get("patient_id", "Unknown"))
329
+ eye = str(r.get("eye", "Unknown"))
330
+ stem = Path(src).stem
331
+ slc = None
332
+ # Prefer path-based extraction (Prime_FULL: XX-YYY/Wn/OD/N.png)
333
+ m_path = visit_path_re.search(src)
334
+ if m_path:
335
+ visit = m_path.group(1)
336
+ # slice = stem (numeric)
337
+ if stem.isdigit():
338
+ slc = int(stem)
339
+ else:
340
+ # TREX flat name
341
+ m_fn = visit_fname_re.search(stem)
342
+ if m_fn:
343
+ visit = m_fn.group(1)
344
+ if eye == "Unknown":
345
+ eye = m_fn.group(2)
346
+ slc = int(m_fn.group(3))
347
+ # Patient ID from TREX flat name: 11-XX-YYY_... → pid = XX-YYY
348
+ if pid in ("Unknown", "nan", ""):
349
+ pid_m = re.match(r"\d+-(\d{2}-\d{3})_", stem)
350
+ if pid_m:
351
+ pid = pid_m.group(1)
352
+ else:
353
+ visit = "unknown"
354
+ groups[(pid, eye, visit)].append((src, slc, r.get("disease_label", "Unknown"), r.get("notes", "")))
355
+
356
+ items = []
357
+ for (pid, eye, visit), files in groups.items():
358
+ # Order by slice index
359
+ files.sort(key=lambda x: (x[1] if x[1] is not None else 0))
360
+ slices = [{"src_path": src, "slice_idx": i} for i, (src, _, _, _) in enumerate(files)]
361
+ # disease_label: take majority (should be uniform within group)
362
+ diseases = [f[2] for f in files]
363
+ disease = max(set(diseases), key=diseases.count)
364
+ items.append({
365
+ "study_basename": f"{pid}_{eye}_W{visit}",
366
+ "patient_basename": f"patient_{pid}",
367
+ "study_meta": {
368
+ "disease_label": disease,
369
+ "eye": eye if eye in ("OD", "OS") else "unknown",
370
+ "patient_id": pid,
371
+ "visit": f"W{visit}",
372
+ "label_granularity": "visit",
373
+ "notes": files[0][3],
374
+ },
375
+ "slices": slices,
376
+ })
377
+ return items
378
+
379
+
380
+ def enum_retouch(ds_df, in_root):
381
+ """RETOUCH 3 device sub-cohorts encoded in CSV 'notes' field.
382
+ CSV image_path filenames are flat numerics (1.png, 1000.png, ...) — original
383
+ volume grouping is LOST in the user's flat enumeration. We thus use file-level
384
+ studies, but preserve device subset → device_vendor/model in the row."""
385
+ items = []
386
+ in_root = Path(in_root)
387
+ for _, r in ds_df.iterrows():
388
+ src = r["image_path"]
389
+ if not os.path.exists(src):
390
+ continue
391
+ stem = Path(src).stem
392
+ notes = str(r.get("notes", ""))
393
+ dev_m = re.search(r"TrainingSet-(\w+)", notes)
394
+ dev = dev_m.group(1) if dev_m else "Unknown"
395
+ dev_model = {"Cirrus": "cirrus_hd_oct", "Spectralis": "spectralis",
396
+ "Topcon": "topcon_3d_oct"}.get(dev, "unknown")
397
+ dev_vendor = {"Cirrus": "zeiss", "Spectralis": "heidelberg",
398
+ "Topcon": "topcon"}.get(dev, "unknown")
399
+ # Include device in basename to avoid collision across 3 subsets (Spectralis/1.png
400
+ # and Cirrus/1.png both exist as separate volumes)
401
+ study_basename = f"retouch_{dev}_{stem}"
402
+ items.append({
403
+ "study_basename": study_basename,
404
+ "patient_basename": study_basename, # no patient grouping recoverable from CSV
405
+ "study_meta": {
406
+ "disease_label": r.get("disease_label", "AMD/RVO"),
407
+ "eye": "unknown",
408
+ "patient_id": None,
409
+ "device_vendor": dev_vendor,
410
+ "device_model": dev_model,
411
+ "subset": dev,
412
+ "label_granularity": "b-scan", # downgraded from volume since we lost grouping
413
+ "has_segmentation_mask": True,
414
+ },
415
+ "slices": [{"src_path": src, "slice_idx": None}],
416
+ })
417
+ return items
418
+
419
+
420
+ def enum_oimhs_with_demographics(ds_df, in_root):
421
+ """Items + sidecar. One patient has two eyes (two eye_ids in Images/), each with
422
+ its own copy of files named 1.png, 2.png, etc. → must include eye_id in basename
423
+ to disambiguate same-patient same-filename collisions."""
424
+ items = []
425
+ for _, r in ds_df.iterrows():
426
+ src = r["image_path"]
427
+ if not os.path.exists(src):
428
+ continue
429
+ stem = Path(src).stem
430
+ # path is Images/<eye_id>/<stem>.png → eye_id is parent dir name
431
+ eye_id = Path(src).parent.name
432
+ pid = str(r.get("patient_id", "Unknown"))
433
+ items.append({
434
+ "study_basename": f"oimhs_p{pid}_e{eye_id}_{stem}",
435
+ "patient_basename": f"patient_{pid}",
436
+ "study_meta": {
437
+ "disease_label": r.get("disease_label", "MH"),
438
+ "eye": str(r.get("eye", "unknown")) if str(r.get("eye", "Unknown")) != "Unknown" else "unknown",
439
+ "patient_id": pid,
440
+ "eye_id": eye_id,
441
+ "age": str(r.get("age", "Unknown")),
442
+ "gender": str(r.get("gender", "Unknown")),
443
+ "stage": r.get("disease_label", "").replace("MH_Stage", "") if "Stage" in str(r.get("disease_label", "")) else "Unknown",
444
+ "label_granularity": "eye",
445
+ },
446
+ "slices": [{"src_path": src, "slice_idx": None}],
447
+ })
448
+ return items
449
+
450
+
451
+ def enum_octdl_with_demographics(ds_df, in_root):
452
+ """OCTDL with sex/year(→age)/subcategory/condition sidecar.
453
+ Note: CSV's image_path lacks the .jpg extension and disease subfolder. We have
454
+ to reconstruct the real path: {OCTDL_root}/OCTDL/{disease}/{stem}.jpg."""
455
+ items = []
456
+ # Find OCTDL root by walking disk
457
+ octdl_root = None
458
+ for p in Path(in_root / "23" if not isinstance(in_root, Path) else Path(in_root) / "23").rglob("OCTDL"):
459
+ if p.is_dir() and (p / "AMD").exists():
460
+ octdl_root = p
461
+ break
462
+ if octdl_root is None:
463
+ print("[octdl] ERROR: cannot find OCTDL root with AMD subdir")
464
+ return []
465
+ for _, r in ds_df.iterrows():
466
+ src_csv = r["image_path"]
467
+ disease = r.get("disease_label", "AMD")
468
+ stem = Path(src_csv).name # CSV path's last segment = file stem (no ext)
469
+ # Try .jpg under disease subdir first
470
+ for ext in (".jpg", ".jpeg", ".png", ".JPG", ".JPEG"):
471
+ candidate = octdl_root / disease / f"{stem}{ext}"
472
+ if candidate.exists():
473
+ src = str(candidate)
474
+ break
475
+ else:
476
+ continue # file truly missing
477
+
478
+ pid = str(r.get("patient_id", "Unknown"))
479
+ items.append({
480
+ "study_basename": f"octdl_{disease}_{stem}",
481
+ "patient_basename": f"patient_{pid}" if pid not in ("Unknown", "nan", "", "0") else f"octdl_{disease}_{stem}",
482
+ "study_meta": {
483
+ "disease_label": disease,
484
+ "eye": str(r.get("eye", "unknown")) if str(r.get("eye", "Unknown")) not in ("Unknown", "0") else "unknown",
485
+ "patient_id": pid,
486
+ "age": str(r.get("age", "Unknown")),
487
+ "gender": str(r.get("gender", "Unknown")),
488
+ "notes": r.get("notes", ""),
489
+ "label_granularity": "b-scan",
490
+ },
491
+ "slices": [{"src_path": src, "slice_idx": None}],
492
+ })
493
+ return items
494
+
495
+
496
+ # ============================================================
497
+ # OCTA500 enumerator (filename = volID-sliceID, 300 vol × 400)
498
+ # ============================================================
499
+
500
+ def enum_octa500(in_root, octa500_subdir="OCTA500"):
501
+ base = Path(in_root) / octa500_subdir
502
+ images_dir = base / "images"
503
+ labels_xlsx = base / "Text labels.xlsx"
504
+ labels = {}
505
+ if labels_xlsx.exists():
506
+ df = pd.read_excel(labels_xlsx)
507
+ for _, r in df.iterrows():
508
+ labels[str(int(r["ID"]))] = {
509
+ "disease": str(r["Disease"]).strip(),
510
+ "sex": str(r["Sex"]).strip(),
511
+ "eye": str(r["OS/OD"]).strip(),
512
+ "age": str(r["Age"]).strip(),
513
+ }
514
+
515
+ # Group files by volume ID
516
+ groups = defaultdict(list)
517
+ for f in sorted(images_dir.glob("*.png")):
518
+ m = re.match(r"^(\d+)-(\d+)\.png$", f.name)
519
+ if not m:
520
+ continue
521
+ vol, slc = m.group(1), int(m.group(2))
522
+ groups[vol].append((slc, f))
523
+
524
+ items = []
525
+ for vol, files in groups.items():
526
+ files.sort()
527
+ lab = labels.get(vol, {})
528
+ slices = [{"src_path": str(f), "slice_idx": i} for i, (_, f) in enumerate(files)]
529
+ items.append({
530
+ "study_basename": f"vol_{vol}",
531
+ "patient_basename": f"vol_{vol}", # 1 vol = 1 patient (no cross-vol patient ID)
532
+ "study_meta": {
533
+ "disease_label": lab.get("disease", "Unknown"),
534
+ "eye": lab.get("eye", "unknown"),
535
+ "patient_id": vol,
536
+ "age": lab.get("age", "Unknown"),
537
+ "gender": "M" if lab.get("sex") == "M" else ("F" if lab.get("sex") == "F" else "Unknown"),
538
+ "label_granularity": "volume",
539
+ "has_dc_mask": True, # OCTA500 has B-scan-level 6-class masks
540
+ },
541
+ "slices": slices,
542
+ })
543
+ return items
544
+
545
+
546
+ def octa500_post_artifact(meta, sdir):
547
+ """Copy 6-class B-scan masks for OCTA500."""
548
+ if not meta.get("has_dc_mask"):
549
+ return
550
+ mask_root = Path("/mnt/new/OCT Retinal B-scan数据集汇总/OCTA500/masks")
551
+ for slc in meta["slices"]:
552
+ idx = slc["idx"]
553
+ src_fname = Path(slc["src_path"]).name # 10001-0001.png
554
+ src_mask = mask_root / src_fname
555
+ if src_mask.exists():
556
+ dst_mask = sdir / f"mask_{idx:03d}.png"
557
+ save_mask_preserve(src_mask, dst_mask, force=False)
558
+
559
+
560
+ def has_segmentation_octa500(meta, slc):
561
+ idx = slc["idx"]
562
+ sdir_parts = Path(meta["slices"][0]["src_path"]).parent # not used
563
+ # The mask is saved post-hoc with mask_{idx:03d}.png inside study_dir.
564
+ # has_segmentation is True if the corresponding mask file existed at source.
565
+ src_fname = Path(slc["src_path"]).name
566
+ mask_root = Path("/mnt/new/OCT Retinal B-scan数据集汇总/OCTA500/masks")
567
+ return (mask_root / src_fname).exists()
568
+
569
+
570
+ # ============================================================
571
+ # UESTC enumerator (3 sub-protocols)
572
+ # ============================================================
573
+
574
+ def enum_uestc(in_root, uestc_subdir="UESTC天池"):
575
+ base = Path(in_root) / uestc_subdir
576
+ items = []
577
+ sub_to_protocol = {
578
+ "Dataset_speckle_OCT_3D_6x6_split": ("BMizar 6x6mm", "uestc_bmizar_6x6"),
579
+ "Dataset_speckle_OCT_3D_20x24_split": ("BMizar 20x24mm", "uestc_bmizar_20x24"),
580
+ "Dataset_speckle_OCT_3D_Spectralis_split": ("Spectralis", "uestc_spectralis"),
581
+ }
582
+ for sub, (subset_name, subset_id) in sub_to_protocol.items():
583
+ sub_dir = base / sub
584
+ if not sub_dir.exists():
585
+ continue
586
+ files = sorted(sub_dir.glob("*.tif"))
587
+ for f in files:
588
+ stem = f.stem # e.g. 000000
589
+ dev_vendor = "spectralis_bmizar" if "bmizar" in subset_id else "heidelberg"
590
+ dev_model = "bm_400k_bmizar" if "bmizar" in subset_id else "spectralis"
591
+ items.append({
592
+ "study_basename": f"{subset_id}_{stem}",
593
+ "patient_basename": f"{subset_id}_{stem}", # no patient grouping info
594
+ "study_meta": {
595
+ "disease_label": "Unknown",
596
+ "eye": "unknown",
597
+ "patient_id": None,
598
+ "subset": subset_name,
599
+ "subset_id": subset_id,
600
+ "device_vendor": dev_vendor,
601
+ "device_model": dev_model,
602
+ "label_granularity": "b-scan",
603
+ },
604
+ "slices": [{"src_path": str(f), "slice_idx": None}],
605
+ })
606
+ return items
607
+
608
+
609
+ def build_row_caps_uestc(meta, cohort, cohort_phrase):
610
+ """UESTC override: scan_protocol per subset, severity always unknown."""
611
+ cfg = COHORT_CONFIG[cohort]
612
+ sh = meta["study_hash"]; ph = meta["patient_hash"]
613
+ eye = meta.get("eye", "unknown")
614
+ subset = meta.get("subset_id", "")
615
+ subset_label = meta.get("subset", "unknown")
616
+
617
+ base = default_base_fields(
618
+ cohort, sh, patient_hash=ph, eye=eye,
619
+ ethnicity="Asian", hospital_domain="uestc_sichuan_v1")
620
+ base["device_vendor"] = meta.get("device_vendor", "varies")
621
+ base["device_model"] = meta.get("device_model", "varies")
622
+ base["severity"] = "unknown"
623
+ base["diagnosis_source"] = "none"
624
+
625
+ # scan_protocol distinguishes subsets
626
+ scan_protocol = {
627
+ "uestc_bmizar_6x6": "volume_3d_macula_6x6mm",
628
+ "uestc_bmizar_20x24": "volume_3d_macula_20x24mm",
629
+ "uestc_spectralis": "volume_3d_macula_spectralis",
630
+ }.get(subset, "volume_3d_macula")
631
+
632
+ rows, caps = [], []
633
+ for slc in meta["slices"]:
634
+ idx = slc["idx"]
635
+ image_id = f"{cohort}_{sh}_bscan"
636
+ file_path = rel_file_path(cohort, sh, "bscan.png")
637
+ row = dict(base)
638
+ row.update({
639
+ "image_id": image_id, "file_path": file_path,
640
+ "file_format": "png", "modality": "oct_bscan",
641
+ "anatomy": "macula", "device_technology": "sd_oct",
642
+ "scan_protocol": scan_protocol, "bscan_index": idx,
643
+ "image_height_px": slc["h"], "image_width_px": slc["w"],
644
+ "has_segmentation": False, "n_layers_visible": 0,
645
+ "is_valid": True,
646
+ })
647
+ rows.append(row)
648
+ caps.extend(caption_l1_oct(image_id, cohort_phrase, eye,
649
+ device_vendor=row["device_vendor"],
650
+ device_model=row["device_model"]))
651
+ dev = device_phrase(row["device_vendor"], row["device_model"])
652
+ if dev:
653
+ l3 = f"An OCT B-scan from {dev}, {cohort_phrase}, {subset_label} subset."
654
+ else:
655
+ l3 = f"An OCT B-scan from the {cohort_phrase}, {subset_label} subset."
656
+ caps.append(caption_l3_oct(image_id, l3, "manifest_fields+subset"))
657
+ return rows, caps
658
+
659
+
660
+ # ============================================================
661
+ # Sidecar builders
662
+ # ============================================================
663
+
664
+ def sidecar_demographics(meta):
665
+ age = meta.get("age", "Unknown")
666
+ gender = meta.get("gender", "Unknown")
667
+ if age in (None, "Unknown", "", "nan") and gender in (None, "Unknown", "", "nan"):
668
+ return None
669
+ return {
670
+ "study_id": meta["study_hash"],
671
+ "patient_hash": meta["patient_hash"],
672
+ "image_id_pattern": f"{meta['cohort']}_{meta['study_hash']}_bscan",
673
+ "age": str(age),
674
+ "gender": str(gender),
675
+ "eye": meta.get("eye", "unknown"),
676
+ "disease_label": meta.get("disease_label", "Unknown"),
677
+ }
678
+
679
+
680
+ # ============================================================
681
+ # Mask post-artifact helpers for datasets that have masks
682
+ # ============================================================
683
+
684
+ def aroi_post_artifact(meta, sdir):
685
+ """AROI mask: 6/AROI/AROI - online/24 patient/patientN/mask/<filename>"""
686
+ src = Path(meta["slices"][0]["src_path"])
687
+ stem = src.stem # e.g. 6-patient1_raw0001
688
+ pid_m = re.match(r"6-(patient\d+)_raw(\d+)", stem)
689
+ if not pid_m:
690
+ return
691
+ pid, raw_idx = pid_m.group(1), pid_m.group(2)
692
+ mask_src = Path("/mnt/new/OCT Retinal B-scan数据集汇总/6/AROI/AROI - online/24 patient") / pid / "mask" / f"raw{raw_idx}.png"
693
+ if mask_src.exists():
694
+ save_mask_preserve(mask_src, sdir / "layer_mask.png")
695
+
696
+
697
+ def oimhs_post_artifact(meta, sdir):
698
+ """OIMHS mask: 16/OIMHS dataset/output_layer/16-patient{eye_id}-{img_stem}_layer.png"""
699
+ src = Path(meta["slices"][0]["src_path"])
700
+ eye_id = src.parent.name # Images/{eye_id}/file.png
701
+ mask_src = Path(f"/mnt/new/OCT Retinal B-scan数据集汇总/16/OIMHS dataset/output_layer/16-patient{eye_id}-{src.stem}_layer.png")
702
+ if mask_src.exists():
703
+ save_mask_preserve(mask_src, sdir / "layer_mask.png")
704
+
705
+
706
+ def retouch_post_artifact(meta, sdir):
707
+ """RETOUCH mask in parallel masks/ dir."""
708
+ for slc in meta["slices"]:
709
+ src = Path(slc["src_path"])
710
+ mask_src = src.parent.parent / "masks" / src.name
711
+ if mask_src.exists():
712
+ dst_name = "fluid_mask.png" if slc["idx"] is None else f"fluid_mask_{slc['idx']:03d}.png"
713
+ save_mask_preserve(mask_src, sdir / dst_name)
714
+
715
+
716
+ def amd_sd_post_artifact(meta, sdir):
717
+ """AMD-SD mask: AMD-SD/masks/{filename}"""
718
+ src = Path(meta["slices"][0]["src_path"])
719
+ mask_src = src.parent.parent / "masks" / src.name
720
+ if mask_src.exists():
721
+ save_mask_preserve(mask_src, sdir / "lesion_mask.png")
722
+
723
+
724
+ def chiu_post_artifact(meta, sdir):
725
+ """Chiu DME masks (8 layers + fluid) — masks are in parallel dir if extracted by user."""
726
+ src = Path(meta["slices"][0]["src_path"])
727
+ mask_src = src.parent.parent / "masks" / src.name
728
+ if mask_src.exists():
729
+ save_mask_preserve(mask_src, sdir / "layer_mask.png")
730
+
731
+
732
+ # ============================================================
733
+ # Main dispatcher
734
+ # ============================================================
735
+
736
+ CSV_NAME_TO_COHORT = {
737
+ "Kermany": ("public_oct_kermany", None, None, None),
738
+ "OCTID": ("public_oct_octid", None, None, None),
739
+ "AROI": ("public_oct_aroi", None, None, aroi_post_artifact),
740
+ "NEH_UT_2021": ("public_oct_neh_ut_2021", None, None, None),
741
+ "AREDS2": ("public_oct_areds2", None, None, None),
742
+ "Glaucoma_OCT": ("public_oct_glaucoma", None, None, None),
743
+ "NYU_POAG": ("public_oct_nyu_poag", None, None, None),
744
+ "OLIVES": ("public_oct_olives", enum_olives, None, None),
745
+ "Chiu_DME_2015": ("public_oct_chiu_dme_2015", None, None, chiu_post_artifact),
746
+ "Srinivasan_2014": ("public_oct_srinivasan_2014", None, None, None),
747
+ "Sparsity_SDOCT_2012": ("public_oct_sparsity_sdoct_2012", None, None, None),
748
+ "OIMHS": ("public_oct_oimhs", enum_oimhs_with_demographics, sidecar_demographics, oimhs_post_artifact),
749
+ "RETOUCH": ("public_oct_retouch", enum_retouch, None, retouch_post_artifact),
750
+ "THOCT1800": ("public_oct_thoct1800", None, None, None),
751
+ "OCTDL": ("public_oct_octdl", enum_octdl_with_demographics, sidecar_demographics, None),
752
+ "AMD-SD": ("public_oct_amd_sd", None, None, amd_sd_post_artifact),
753
+ "C8": ("public_oct_c8", None, None, None),
754
+ }
755
+
756
+
757
+ def main():
758
+ ap = argparse.ArgumentParser()
759
+ ap.add_argument("--input-root", required=True,
760
+ help="Path to '/mnt/new/OCT Retinal B-scan数据集汇总'")
761
+ ap.add_argument("--output-root", required=True,
762
+ help="Output root (will create extracted/, manifest/, captions/)")
763
+ ap.add_argument("--csv", default=None,
764
+ help="Path to unified_metadata.csv (default: <input-root>/数据分类整理汇总/unified_metadata.csv)")
765
+ ap.add_argument("--cohorts", default="all",
766
+ help="comma-separated cohort names (full or short like 'kermany,octa500'), or 'all'")
767
+ ap.add_argument("--num-workers", type=int, default=8)
768
+ ap.add_argument("--force", action="store_true")
769
+ ap.add_argument("--limit-per-cohort", type=int, default=None,
770
+ help="for testing: process only first N studies per cohort")
771
+ args = ap.parse_args()
772
+
773
+ in_root = Path(args.input_root)
774
+ out_root = Path(args.output_root)
775
+ csv_path = Path(args.csv) if args.csv else (in_root / "数据分类整理汇总" / "unified_metadata.csv")
776
+
777
+ all_cohort_names = list(set(v[0] for v in CSV_NAME_TO_COHORT.values())) + [
778
+ "public_oct_octa500", "public_oct_uestc"]
779
+ if args.cohorts == "all":
780
+ cohorts_to_run = set(all_cohort_names)
781
+ else:
782
+ requested = [c.strip() for c in args.cohorts.split(",")]
783
+ cohorts_to_run = set()
784
+ for r in requested:
785
+ for full in all_cohort_names:
786
+ if full == r or full.endswith(f"_{r}") or r in full:
787
+ cohorts_to_run.add(full)
788
+
789
+ print(f"Will process {len(cohorts_to_run)} cohorts:")
790
+ for c in sorted(cohorts_to_run):
791
+ print(f" {c}")
792
+ print()
793
+
794
+ # CSV-driven A-class cohorts
795
+ if any(v[0] in cohorts_to_run for v in CSV_NAME_TO_COHORT.values()):
796
+ print(f"Loading CSV: {csv_path}")
797
+ csv_df = pd.read_csv(csv_path, low_memory=False)
798
+ print(f" {len(csv_df)} rows")
799
+
800
+ for csv_name, (cohort, enum_fn, sidecar_fn, post_fn) in CSV_NAME_TO_COHORT.items():
801
+ if cohort not in cohorts_to_run:
802
+ continue
803
+ ds_df = csv_df[csv_df["dataset_name"] == csv_name]
804
+ if len(ds_df) == 0:
805
+ print(f"[{cohort}] no CSV rows for dataset {csv_name}, skipping")
806
+ continue
807
+ if enum_fn is None:
808
+ items = enum_from_csv_simple(ds_df, in_root, csv_name)
809
+ else:
810
+ items = enum_fn(ds_df, in_root)
811
+ if args.limit_per_cohort:
812
+ items = items[:args.limit_per_cohort]
813
+ run_cohort(cohort, items, _shared_build_row_caps, out_root,
814
+ num_workers=args.num_workers, force=args.force,
815
+ sidecar_fn=sidecar_fn, cohort_phrase=COHORT_CONFIG[cohort]["phrase"],
816
+ post_artifact_fn=post_fn)
817
+
818
+ # OCTA500
819
+ if "public_oct_octa500" in cohorts_to_run:
820
+ items = enum_octa500(in_root)
821
+ if args.limit_per_cohort:
822
+ items = items[:args.limit_per_cohort]
823
+
824
+ def build_octa500(meta, cohort, cohort_phrase):
825
+ return _shared_build_row_caps(
826
+ meta, cohort, cohort_phrase,
827
+ has_segmentation_fn=has_segmentation_octa500,
828
+ l3_extras_fn=lambda m, s: ["with B-scan-level 6-class segmentation mask"]
829
+ if has_segmentation_octa500(m, s) else [],
830
+ )
831
+
832
+ run_cohort("public_oct_octa500", items, build_octa500, out_root,
833
+ num_workers=args.num_workers, force=args.force,
834
+ sidecar_fn=sidecar_demographics,
835
+ cohort_phrase=COHORT_CONFIG["public_oct_octa500"]["phrase"],
836
+ post_artifact_fn=octa500_post_artifact)
837
+
838
+ # UESTC
839
+ if "public_oct_uestc" in cohorts_to_run:
840
+ items = enum_uestc(in_root)
841
+ if args.limit_per_cohort:
842
+ items = items[:args.limit_per_cohort]
843
+ run_cohort("public_oct_uestc", items, build_row_caps_uestc, out_root,
844
+ num_workers=args.num_workers, force=args.force,
845
+ sidecar_fn=None,
846
+ cohort_phrase=COHORT_CONFIG["public_oct_uestc"]["phrase"],
847
+ post_artifact_fn=None)
848
+
849
+ print("\n[main] all done.")
850
+
851
+
852
+ if __name__ == "__main__":
853
+ main()
manifest/oct_public_images_v1.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7690b7a0944afc277b819ee072efca0888fd52e02bd9cf14f111c831ba8f9015
3
- size 20370119
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e929d4891459c9eaa79b11d8ba62dda33a42bdcb334de7364a1583f7b98720ee
3
+ size 20370146