File size: 37,436 Bytes
ec7f8fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
#!/usr/bin/env python3
"""
Adapter for 19 OCT public datasets → 41-col manifest (matching private/fundus schema).

19 cohorts:
  17 A-class (enumerated via existing unified_metadata.csv):
    public_oct_kermany, public_oct_octid, public_oct_aroi, public_oct_neh_ut_2021,
    public_oct_areds2, public_oct_glaucoma, public_oct_nyu_poag, public_oct_olives,
    public_oct_chiu_dme_2015, public_oct_srinivasan_2014, public_oct_sparsity_sdoct_2012,
    public_oct_oimhs, public_oct_retouch, public_oct_thoct1800, public_oct_octdl,
    public_oct_amd_sd, public_oct_c8
  + 2 enumerated from source layout:
    public_oct_octa500, public_oct_uestc

Output layout (under {output_root}):
  extracted/{cohort}/{hash[:2]}/{hash}/{bscan.png|bscan_NNN.png}{+meta.json}{+masks}
  manifest/{cohort}_images.parquet
  manifest/{cohort}_sidecar.parquet (where applicable)
  captions/{cohort}_captions.parquet

Notes:
  - Most cohorts use file-level study_id (1 bscan = 1 study). patient_hash is shared
    across bscans of same patient when patient_id is known.
  - OLIVES uses study_id = hash(patient_eye_visit), patient_hash = hash(patient).
  - OCTA500 and UESTC use file-level study_id (volume info preserved in source_basename).
  - Masks (where present) are copied to study_dir as auxiliary files; not in manifest rows.
"""
import argparse
import os
import re
from collections import defaultdict
from pathlib import Path

import pandas as pd

from public_common import (
    default_base_fields, study_hash_for, rel_file_path,
)
from oct_public_common import (
    caption_l1_oct, caption_l3_oct, device_phrase,
    save_mask_preserve, run_cohort,
)


# ============================================================
# Disease label → (diagnosis_group, severity)
# ============================================================

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

DISEASE_MAP = {
    # Normal variants
    "NORMAL": ([], "none"),
    "Normal": ([], "none"),
    "NOR": ([], "none"),
    "NO": ([], "none"),
    "Control": ([], "none"),
    "CONTROL": ([], "none"),
    # Disease classes
    "CNV": (["CNV"], "unknown"),
    "DME": (["DME"], "unknown"),
    "DRUSEN": (["DRUSEN"], "unknown"),
    "DR": (["DR"], "unknown"),
    "AMD": (["AMD"], "unknown"),
    "wet_AMD": (["wet_AMD"], "unknown"),
    "nAMD": (["nAMD"], "unknown"),
    "AMD/RVO": (["AMD", "RVO"], "unknown"),
    "CSR": (["CSR"], "unknown"),
    "MH": (["MH"], "unknown"),
    "MH_Stage1": (["MH"], "mild"),
    "MH_Stage2": (["MH"], "moderate"),
    "MH_Stage3": (["MH"], "severe"),
    "MH_Stage4": (["MH"], "severe"),
    "Glaucoma": (["glaucoma"], "unknown"),
    "POAG": (["glaucoma"], "unknown"),
    "ERM": (["ERM"], "unknown"),
    "RVO": (["RVO"], "unknown"),
    "RAO": (["RAO"], "unknown"),
    "VID": (["VID"], "unknown"),
    # Unknown / fallback
    "Unknown": ([], "unknown"),
}


def map_disease(label):
    return DISEASE_MAP.get(str(label).strip(), (["unknown_disease"], "unknown"))


# ============================================================
# Per-cohort static config (device, anatomy, scan_protocol, ethnicity)
# ============================================================

COHORT_CONFIG = {
    "public_oct_kermany": dict(
        phrase="Kermany 2018 OCT classification dataset (UCSD / Cell)",
        vendor="heidelberg", model="spectralis", tech="sd_oct",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="Mixed", hospital_domain="kermany_ucsd_v1"),
    "public_oct_octid": dict(
        phrase="OCTID Indian retinal OCT classification dataset",
        vendor="zeiss", model="cirrus_hd_oct_5000", tech="sd_oct",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="South Asian", hospital_domain="octid_sankara_v1"),
    "public_oct_aroi": dict(
        phrase="AROI nAMD layer segmentation dataset (Croatia)",
        vendor="zeiss", model="cirrus_hd_oct_4000", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="European", hospital_domain="aroi_zagreb_v1"),
    "public_oct_neh_ut_2021": dict(
        phrase="NEH-UT-2021 Iranian retinal OCT dataset",
        vendor="heidelberg", model="spectralis_sd_oct", tech="sd_oct",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="Middle Eastern", hospital_domain="neh_ut_2021_v1"),
    "public_oct_areds2": dict(
        phrase="AREDS2 ancillary SD-OCT AMD dataset (NEI)",
        vendor="bioptigen", model="bioptigen_sd_oct", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="Mixed", hospital_domain="areds2_nei_v1"),
    "public_oct_glaucoma": dict(
        phrase="Glaucoma OCT and fundus dataset (TD-OCT)",
        vendor="zeiss", model="stratus_oct", tech="td_oct",
        anatomy="optic_disc", scan_protocol="single_shot",
        ethnicity="unknown", hospital_domain="glaucoma_oct_v1"),
    "public_oct_nyu_poag": dict(
        phrase="NYU POAG retinal OCT dataset",
        vendor="unknown", model="unknown", tech="unknown",
        anatomy="optic_disc", scan_protocol="volume_3d_macula",
        ethnicity="unknown", hospital_domain="nyu_poag_v1"),
    "public_oct_olives": dict(
        phrase="OLIVES longitudinal DR and DME OCT dataset",
        vendor="heidelberg", model="spectralis_hra_oct", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="unknown", hospital_domain="olives_v1"),
    "public_oct_chiu_dme_2015": dict(
        phrase="Chiu et al. 2015 DME 8-layer segmentation dataset (Duke)",
        vendor="heidelberg", model="spectralis", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="unknown", hospital_domain="chiu_duke_2015_v1"),
    "public_oct_srinivasan_2014": dict(
        phrase="Srinivasan et al. 2014 AMD-DME-Normal OCT dataset (Duke/Harvard/Michigan)",
        vendor="heidelberg", model="spectralis", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="unknown", hospital_domain="srinivasan_2014_v1"),
    "public_oct_sparsity_sdoct_2012": dict(
        phrase="Sparsity SDOCT 2012 AMD vs control dataset",
        vendor="bioptigen", model="bioptigen_sd_oct", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="unknown", hospital_domain="sparsity_sdoct_2012_v1"),
    "public_oct_oimhs": dict(
        phrase="OIMHS macular hole staging and layer segmentation dataset",
        vendor="heidelberg", model="spectralis_sd_oct", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="Asian", hospital_domain="oimhs_china_v1"),
    "public_oct_retouch": dict(
        phrase="RETOUCH 2017 retinal fluid segmentation challenge dataset",
        vendor="varies", model="varies", tech="sd_oct",  # 3 sub-vendors
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="European", hospital_domain="retouch_v1"),
    "public_oct_thoct1800": dict(
        phrase="THOCT1800 Tsinghua AMD-DME-Normal OCT dataset",
        vendor="zeiss", model="cirrus_hd_oct", tech="sd_oct",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="Asian", hospital_domain="thoct1800_tsinghua_v1"),
    "public_oct_octdl": dict(
        phrase="OCTDL Russian 7-class retinal OCT dataset",
        vendor="optovue", model="rtvue_xr_avanti", tech="sd_oct",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="European", hospital_domain="octdl_russia_v1"),
    "public_oct_amd_sd": dict(
        phrase="AMD-SD wet AMD multi-class segmentation dataset (China)",
        vendor="zeiss", model="cirrus_hd_oct_5000", tech="sd_oct",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="Asian", hospital_domain="amd_sd_nanchang_v1"),
    "public_oct_c8": dict(
        phrase="C8 compiled 8-class retinal OCT classification dataset (Kaggle)",
        vendor="unknown", model="unknown", tech="unknown",
        anatomy="macula", scan_protocol="single_shot",
        ethnicity="unknown", hospital_domain="c8_kaggle_v1"),
    "public_oct_octa500": dict(
        phrase="OCTA-500 multi-modal OCT-A and OCT structural retinal dataset",
        vendor="optovue", model="rtvue_xr_avanti", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="Asian", hospital_domain="octa500_njust_v1"),
    "public_oct_uestc": dict(
        phrase="UESTC despeckling 3D OCT dataset (BMizar + Spectralis)",
        vendor="varies", model="varies", tech="sd_oct",
        anatomy="macula", scan_protocol="volume_3d_macula",
        ethnicity="Asian", hospital_domain="uestc_sichuan_v1"),
}


# ============================================================
# Shared row+caps builder for "standard" cohorts
# ============================================================

def _shared_build_row_caps(meta, cohort, cohort_phrase,
                            has_segmentation_fn=None,
                            l3_extras_fn=None,
                            scan_protocol_override=None):
    """Default row/caps builder. Returns (list_of_rows, list_of_captions).
    Multi-slice studies emit one row per slice; all share study_id + patient_hash."""
    cfg = COHORT_CONFIG[cohort]
    sh = meta["study_hash"]
    ph = meta["patient_hash"]
    eye = meta.get("eye", "unknown")
    disease_label = meta.get("disease_label", "Unknown")
    dx, sev = map_disease(disease_label)

    base = default_base_fields(
        cohort, sh, patient_hash=ph, eye=eye,
        ethnicity=cfg["ethnicity"], hospital_domain=cfg["hospital_domain"])
    base["device_vendor"] = meta.get("device_vendor", cfg["vendor"])
    base["device_model"] = meta.get("device_model", cfg["model"])
    base["diagnosis_group"] = dx
    base["severity"] = sev
    if disease_label and disease_label != "Unknown":
        base["diagnosis_source"] = meta.get("diagnosis_source", "expert_label")

    rows, caps = [], []
    n_slices = meta["n_slices"]
    for slc in meta["slices"]:
        idx = slc["idx"]
        if idx is None:
            image_id = f"{cohort}_{sh}_bscan"
            file_path = rel_file_path(cohort, sh, "bscan.png")
        else:
            image_id = f"{cohort}_{sh}_bscan_{idx:03d}"
            file_path = rel_file_path(cohort, sh, slc["fname"])

        row = dict(base)
        has_seg = has_segmentation_fn(meta, slc) if has_segmentation_fn else bool(
            meta.get("has_segmentation_mask"))
        row.update({
            "image_id": image_id,
            "file_path": file_path,
            "file_format": "png",
            "modality": "oct_bscan",
            "anatomy": cfg["anatomy"],
            "device_technology": cfg["tech"],
            "scan_protocol": scan_protocol_override or cfg["scan_protocol"],
            "bscan_index": idx,
            "image_height_px": slc["h"],
            "image_width_px": slc["w"],
            "has_segmentation": has_seg,
            "n_layers_visible": 0,
            "is_valid": True,
        })
        rows.append(row)

        # 把 row 中的 device 传给 L1 caption (per-row, RETOUCH/UESTC 多设备 cohort 也对)
        caps.extend(caption_l1_oct(image_id, cohort_phrase, eye,
                                   device_vendor=row["device_vendor"],
                                   device_model=row["device_model"]))
        # L3 也把设备短语 prepend (若已知)
        dev = device_phrase(row["device_vendor"], row["device_model"])
        if dev:
            l3_parts = [f"An OCT B-scan from {dev}, {cohort_phrase}"]
        else:
            l3_parts = [f"An OCT B-scan from the {cohort_phrase}"]
        if disease_label and disease_label not in ("Unknown",):
            l3_parts.append(f"label: {disease_label}")
        if idx is not None and n_slices > 1:
            l3_parts.append(f"slice {idx+1} of {n_slices}")
        if l3_extras_fn:
            l3_parts.extend(l3_extras_fn(meta, slc))
        caps.append(caption_l3_oct(image_id, ", ".join(l3_parts) + ".",
                                    "manifest_fields+csv_labels"))

    return rows, caps


# ============================================================
# 17 A-class enumerators (read from unified_metadata.csv)
# ============================================================

def enum_from_csv_simple(ds_df, in_root, csv_dataset_name):
    """File-level studies, patient_hash from patient_id when present.
    study_basename = relative path with separators normalized to ensure uniqueness
    across train/test/disease subdirs."""
    in_root = Path(in_root)
    items = []
    seen_basenames = set()
    for _, r in ds_df.iterrows():
        src = r["image_path"]
        if not os.path.exists(src):
            continue
        # Build unique basename from path relative to in_root
        try:
            rel = str(Path(src).relative_to(in_root))
        except ValueError:
            rel = src
        # Sanitize: replace path separators + spaces + non-ascii safely
        study_basename = re.sub(r"[^A-Za-z0-9._-]", "_", rel)
        if study_basename in seen_basenames:
            # Should not happen given uniqueness of file paths, but defensive
            continue
        seen_basenames.add(study_basename)

        pid = str(r.get("patient_id", "")).strip()
        patient_basename = f"patient_{pid}" if pid and pid not in ("Unknown", "nan", "") else study_basename
        items.append({
            "study_basename": study_basename,
            "patient_basename": patient_basename,
            "study_meta": {
                "disease_label": r.get("disease_label", "Unknown"),
                "eye": str(r.get("eye", "unknown")) if str(r.get("eye", "unknown")) != "Unknown" else "unknown",
                "patient_id": pid if pid and pid != "Unknown" else None,
                "device_csv": r.get("device", "unknown"),
                "label_granularity": r.get("label_granularity", "b-scan"),
                "notes": r.get("notes", ""),
            },
            "slices": [{"src_path": src, "slice_idx": None}],
        })
    return items


def enum_olives(ds_df, in_root):
    """Special: study_id = hash(patient_eye_visit), patient_hash = hash(patient).
    Multiple bscans of the same (patient, eye, visit) share study_id with slice_idx."""
    visit_path_re = re.compile(r"/W(\d+)/")
    # TREX flat filename: 11-01-001_W100_OD_0.tif → patient=01-001, visit=W100, eye=OD, slc=0
    visit_fname_re = re.compile(r"_W(\d+)_(O[DS])_(\d+)\b")
    groups = defaultdict(list)
    for _, r in ds_df.iterrows():
        src = r["image_path"]
        if not os.path.exists(src):
            continue
        pid = str(r.get("patient_id", "Unknown"))
        eye = str(r.get("eye", "Unknown"))
        stem = Path(src).stem
        slc = None
        # Prefer path-based extraction (Prime_FULL: XX-YYY/Wn/OD/N.png)
        m_path = visit_path_re.search(src)
        if m_path:
            visit = m_path.group(1)
            # slice = stem (numeric)
            if stem.isdigit():
                slc = int(stem)
        else:
            # TREX flat name
            m_fn = visit_fname_re.search(stem)
            if m_fn:
                visit = m_fn.group(1)
                if eye == "Unknown":
                    eye = m_fn.group(2)
                slc = int(m_fn.group(3))
                # Patient ID from TREX flat name: 11-XX-YYY_... → pid = XX-YYY
                if pid in ("Unknown", "nan", ""):
                    pid_m = re.match(r"\d+-(\d{2}-\d{3})_", stem)
                    if pid_m:
                        pid = pid_m.group(1)
            else:
                visit = "unknown"
        groups[(pid, eye, visit)].append((src, slc, r.get("disease_label", "Unknown"), r.get("notes", "")))

    items = []
    for (pid, eye, visit), files in groups.items():
        # Order by slice index
        files.sort(key=lambda x: (x[1] if x[1] is not None else 0))
        slices = [{"src_path": src, "slice_idx": i} for i, (src, _, _, _) in enumerate(files)]
        # disease_label: take majority (should be uniform within group)
        diseases = [f[2] for f in files]
        disease = max(set(diseases), key=diseases.count)
        items.append({
            "study_basename": f"{pid}_{eye}_W{visit}",
            "patient_basename": f"patient_{pid}",
            "study_meta": {
                "disease_label": disease,
                "eye": eye if eye in ("OD", "OS") else "unknown",
                "patient_id": pid,
                "visit": f"W{visit}",
                "label_granularity": "visit",
                "notes": files[0][3],
            },
            "slices": slices,
        })
    return items


def enum_retouch(ds_df, in_root):
    """RETOUCH 3 device sub-cohorts encoded in CSV 'notes' field.
    CSV image_path filenames are flat numerics (1.png, 1000.png, ...) — original
    volume grouping is LOST in the user's flat enumeration. We thus use file-level
    studies, but preserve device subset → device_vendor/model in the row."""
    items = []
    in_root = Path(in_root)
    for _, r in ds_df.iterrows():
        src = r["image_path"]
        if not os.path.exists(src):
            continue
        stem = Path(src).stem
        notes = str(r.get("notes", ""))
        dev_m = re.search(r"TrainingSet-(\w+)", notes)
        dev = dev_m.group(1) if dev_m else "Unknown"
        dev_model = {"Cirrus": "cirrus_hd_oct", "Spectralis": "spectralis",
                     "Topcon": "topcon_3d_oct"}.get(dev, "unknown")
        dev_vendor = {"Cirrus": "zeiss", "Spectralis": "heidelberg",
                      "Topcon": "topcon"}.get(dev, "unknown")
        # Include device in basename to avoid collision across 3 subsets (Spectralis/1.png
        # and Cirrus/1.png both exist as separate volumes)
        study_basename = f"retouch_{dev}_{stem}"
        items.append({
            "study_basename": study_basename,
            "patient_basename": study_basename,  # no patient grouping recoverable from CSV
            "study_meta": {
                "disease_label": r.get("disease_label", "AMD/RVO"),
                "eye": "unknown",
                "patient_id": None,
                "device_vendor": dev_vendor,
                "device_model": dev_model,
                "subset": dev,
                "label_granularity": "b-scan",  # downgraded from volume since we lost grouping
                "has_segmentation_mask": True,
            },
            "slices": [{"src_path": src, "slice_idx": None}],
        })
    return items


def enum_oimhs_with_demographics(ds_df, in_root):
    """Items + sidecar. One patient has two eyes (two eye_ids in Images/), each with
    its own copy of files named 1.png, 2.png, etc. → must include eye_id in basename
    to disambiguate same-patient same-filename collisions."""
    items = []
    for _, r in ds_df.iterrows():
        src = r["image_path"]
        if not os.path.exists(src):
            continue
        stem = Path(src).stem
        # path is Images/<eye_id>/<stem>.png → eye_id is parent dir name
        eye_id = Path(src).parent.name
        pid = str(r.get("patient_id", "Unknown"))
        items.append({
            "study_basename": f"oimhs_p{pid}_e{eye_id}_{stem}",
            "patient_basename": f"patient_{pid}",
            "study_meta": {
                "disease_label": r.get("disease_label", "MH"),
                "eye": str(r.get("eye", "unknown")) if str(r.get("eye", "Unknown")) != "Unknown" else "unknown",
                "patient_id": pid,
                "eye_id": eye_id,
                "age": str(r.get("age", "Unknown")),
                "gender": str(r.get("gender", "Unknown")),
                "stage": r.get("disease_label", "").replace("MH_Stage", "") if "Stage" in str(r.get("disease_label", "")) else "Unknown",
                "label_granularity": "eye",
            },
            "slices": [{"src_path": src, "slice_idx": None}],
        })
    return items


def enum_octdl_with_demographics(ds_df, in_root):
    """OCTDL with sex/year(→age)/subcategory/condition sidecar.
    Note: CSV's image_path lacks the .jpg extension and disease subfolder. We have
    to reconstruct the real path: {OCTDL_root}/OCTDL/{disease}/{stem}.jpg."""
    items = []
    # Find OCTDL root by walking disk
    octdl_root = None
    for p in Path(in_root / "23" if not isinstance(in_root, Path) else Path(in_root) / "23").rglob("OCTDL"):
        if p.is_dir() and (p / "AMD").exists():
            octdl_root = p
            break
    if octdl_root is None:
        print("[octdl] ERROR: cannot find OCTDL root with AMD subdir")
        return []
    for _, r in ds_df.iterrows():
        src_csv = r["image_path"]
        disease = r.get("disease_label", "AMD")
        stem = Path(src_csv).name  # CSV path's last segment = file stem (no ext)
        # Try .jpg under disease subdir first
        for ext in (".jpg", ".jpeg", ".png", ".JPG", ".JPEG"):
            candidate = octdl_root / disease / f"{stem}{ext}"
            if candidate.exists():
                src = str(candidate)
                break
        else:
            continue  # file truly missing

        pid = str(r.get("patient_id", "Unknown"))
        items.append({
            "study_basename": f"octdl_{disease}_{stem}",
            "patient_basename": f"patient_{pid}" if pid not in ("Unknown", "nan", "", "0") else f"octdl_{disease}_{stem}",
            "study_meta": {
                "disease_label": disease,
                "eye": str(r.get("eye", "unknown")) if str(r.get("eye", "Unknown")) not in ("Unknown", "0") else "unknown",
                "patient_id": pid,
                "age": str(r.get("age", "Unknown")),
                "gender": str(r.get("gender", "Unknown")),
                "notes": r.get("notes", ""),
                "label_granularity": "b-scan",
            },
            "slices": [{"src_path": src, "slice_idx": None}],
        })
    return items


# ============================================================
# OCTA500 enumerator (filename = volID-sliceID, 300 vol × 400)
# ============================================================

def enum_octa500(in_root, octa500_subdir="OCTA500"):
    base = Path(in_root) / octa500_subdir
    images_dir = base / "images"
    labels_xlsx = base / "Text labels.xlsx"
    labels = {}
    if labels_xlsx.exists():
        df = pd.read_excel(labels_xlsx)
        for _, r in df.iterrows():
            labels[str(int(r["ID"]))] = {
                "disease": str(r["Disease"]).strip(),
                "sex": str(r["Sex"]).strip(),
                "eye": str(r["OS/OD"]).strip(),
                "age": str(r["Age"]).strip(),
            }

    # Group files by volume ID
    groups = defaultdict(list)
    for f in sorted(images_dir.glob("*.png")):
        m = re.match(r"^(\d+)-(\d+)\.png$", f.name)
        if not m:
            continue
        vol, slc = m.group(1), int(m.group(2))
        groups[vol].append((slc, f))

    items = []
    for vol, files in groups.items():
        files.sort()
        lab = labels.get(vol, {})
        slices = [{"src_path": str(f), "slice_idx": i} for i, (_, f) in enumerate(files)]
        items.append({
            "study_basename": f"vol_{vol}",
            "patient_basename": f"vol_{vol}",  # 1 vol = 1 patient (no cross-vol patient ID)
            "study_meta": {
                "disease_label": lab.get("disease", "Unknown"),
                "eye": lab.get("eye", "unknown"),
                "patient_id": vol,
                "age": lab.get("age", "Unknown"),
                "gender": "M" if lab.get("sex") == "M" else ("F" if lab.get("sex") == "F" else "Unknown"),
                "label_granularity": "volume",
                "has_dc_mask": True,  # OCTA500 has B-scan-level 6-class masks
            },
            "slices": slices,
        })
    return items


def octa500_post_artifact(meta, sdir):
    """Copy 6-class B-scan masks for OCTA500."""
    if not meta.get("has_dc_mask"):
        return
    mask_root = Path("/mnt/new/OCT Retinal B-scan数据集汇总/OCTA500/masks")
    for slc in meta["slices"]:
        idx = slc["idx"]
        src_fname = Path(slc["src_path"]).name  # 10001-0001.png
        src_mask = mask_root / src_fname
        if src_mask.exists():
            dst_mask = sdir / f"mask_{idx:03d}.png"
            save_mask_preserve(src_mask, dst_mask, force=False)


def has_segmentation_octa500(meta, slc):
    idx = slc["idx"]
    sdir_parts = Path(meta["slices"][0]["src_path"]).parent  # not used
    # The mask is saved post-hoc with mask_{idx:03d}.png inside study_dir.
    # has_segmentation is True if the corresponding mask file existed at source.
    src_fname = Path(slc["src_path"]).name
    mask_root = Path("/mnt/new/OCT Retinal B-scan数据集汇总/OCTA500/masks")
    return (mask_root / src_fname).exists()


# ============================================================
# UESTC enumerator (3 sub-protocols)
# ============================================================

def enum_uestc(in_root, uestc_subdir="UESTC天池"):
    base = Path(in_root) / uestc_subdir
    items = []
    sub_to_protocol = {
        "Dataset_speckle_OCT_3D_6x6_split": ("BMizar 6x6mm", "uestc_bmizar_6x6"),
        "Dataset_speckle_OCT_3D_20x24_split": ("BMizar 20x24mm", "uestc_bmizar_20x24"),
        "Dataset_speckle_OCT_3D_Spectralis_split": ("Spectralis", "uestc_spectralis"),
    }
    for sub, (subset_name, subset_id) in sub_to_protocol.items():
        sub_dir = base / sub
        if not sub_dir.exists():
            continue
        files = sorted(sub_dir.glob("*.tif"))
        for f in files:
            stem = f.stem  # e.g. 000000
            dev_vendor = "spectralis_bmizar" if "bmizar" in subset_id else "heidelberg"
            dev_model = "bm_400k_bmizar" if "bmizar" in subset_id else "spectralis"
            items.append({
                "study_basename": f"{subset_id}_{stem}",
                "patient_basename": f"{subset_id}_{stem}",  # no patient grouping info
                "study_meta": {
                    "disease_label": "Unknown",
                    "eye": "unknown",
                    "patient_id": None,
                    "subset": subset_name,
                    "subset_id": subset_id,
                    "device_vendor": dev_vendor,
                    "device_model": dev_model,
                    "label_granularity": "b-scan",
                },
                "slices": [{"src_path": str(f), "slice_idx": None}],
            })
    return items


def build_row_caps_uestc(meta, cohort, cohort_phrase):
    """UESTC override: scan_protocol per subset, severity always unknown."""
    cfg = COHORT_CONFIG[cohort]
    sh = meta["study_hash"]; ph = meta["patient_hash"]
    eye = meta.get("eye", "unknown")
    subset = meta.get("subset_id", "")
    subset_label = meta.get("subset", "unknown")

    base = default_base_fields(
        cohort, sh, patient_hash=ph, eye=eye,
        ethnicity="Asian", hospital_domain="uestc_sichuan_v1")
    base["device_vendor"] = meta.get("device_vendor", "varies")
    base["device_model"] = meta.get("device_model", "varies")
    base["severity"] = "unknown"
    base["diagnosis_source"] = "none"

    # scan_protocol distinguishes subsets
    scan_protocol = {
        "uestc_bmizar_6x6": "volume_3d_macula_6x6mm",
        "uestc_bmizar_20x24": "volume_3d_macula_20x24mm",
        "uestc_spectralis": "volume_3d_macula_spectralis",
    }.get(subset, "volume_3d_macula")

    rows, caps = [], []
    for slc in meta["slices"]:
        idx = slc["idx"]
        image_id = f"{cohort}_{sh}_bscan"
        file_path = rel_file_path(cohort, sh, "bscan.png")
        row = dict(base)
        row.update({
            "image_id": image_id, "file_path": file_path,
            "file_format": "png", "modality": "oct_bscan",
            "anatomy": "macula", "device_technology": "sd_oct",
            "scan_protocol": scan_protocol, "bscan_index": idx,
            "image_height_px": slc["h"], "image_width_px": slc["w"],
            "has_segmentation": False, "n_layers_visible": 0,
            "is_valid": True,
        })
        rows.append(row)
        caps.extend(caption_l1_oct(image_id, cohort_phrase, eye,
                                   device_vendor=row["device_vendor"],
                                   device_model=row["device_model"]))
        dev = device_phrase(row["device_vendor"], row["device_model"])
        if dev:
            l3 = f"An OCT B-scan from {dev}, {cohort_phrase}, {subset_label} subset."
        else:
            l3 = f"An OCT B-scan from the {cohort_phrase}, {subset_label} subset."
        caps.append(caption_l3_oct(image_id, l3, "manifest_fields+subset"))
    return rows, caps


# ============================================================
# Sidecar builders
# ============================================================

def sidecar_demographics(meta):
    age = meta.get("age", "Unknown")
    gender = meta.get("gender", "Unknown")
    if age in (None, "Unknown", "", "nan") and gender in (None, "Unknown", "", "nan"):
        return None
    return {
        "study_id": meta["study_hash"],
        "patient_hash": meta["patient_hash"],
        "image_id_pattern": f"{meta['cohort']}_{meta['study_hash']}_bscan",
        "age": str(age),
        "gender": str(gender),
        "eye": meta.get("eye", "unknown"),
        "disease_label": meta.get("disease_label", "Unknown"),
    }


# ============================================================
# Mask post-artifact helpers for datasets that have masks
# ============================================================

def aroi_post_artifact(meta, sdir):
    """AROI mask: 6/AROI/AROI - online/24 patient/patientN/mask/<filename>"""
    src = Path(meta["slices"][0]["src_path"])
    stem = src.stem  # e.g. 6-patient1_raw0001
    pid_m = re.match(r"6-(patient\d+)_raw(\d+)", stem)
    if not pid_m:
        return
    pid, raw_idx = pid_m.group(1), pid_m.group(2)
    mask_src = Path("/mnt/new/OCT Retinal B-scan数据集汇总/6/AROI/AROI - online/24 patient") / pid / "mask" / f"raw{raw_idx}.png"
    if mask_src.exists():
        save_mask_preserve(mask_src, sdir / "layer_mask.png")


def oimhs_post_artifact(meta, sdir):
    """OIMHS mask: 16/OIMHS dataset/output_layer/16-patient{eye_id}-{img_stem}_layer.png"""
    src = Path(meta["slices"][0]["src_path"])
    eye_id = src.parent.name  # Images/{eye_id}/file.png
    mask_src = Path(f"/mnt/new/OCT Retinal B-scan数据集汇总/16/OIMHS dataset/output_layer/16-patient{eye_id}-{src.stem}_layer.png")
    if mask_src.exists():
        save_mask_preserve(mask_src, sdir / "layer_mask.png")


def retouch_post_artifact(meta, sdir):
    """RETOUCH mask in parallel masks/ dir."""
    for slc in meta["slices"]:
        src = Path(slc["src_path"])
        mask_src = src.parent.parent / "masks" / src.name
        if mask_src.exists():
            dst_name = "fluid_mask.png" if slc["idx"] is None else f"fluid_mask_{slc['idx']:03d}.png"
            save_mask_preserve(mask_src, sdir / dst_name)


def amd_sd_post_artifact(meta, sdir):
    """AMD-SD mask: AMD-SD/masks/{filename}"""
    src = Path(meta["slices"][0]["src_path"])
    mask_src = src.parent.parent / "masks" / src.name
    if mask_src.exists():
        save_mask_preserve(mask_src, sdir / "lesion_mask.png")


def chiu_post_artifact(meta, sdir):
    """Chiu DME masks (8 layers + fluid) — masks are in parallel dir if extracted by user."""
    src = Path(meta["slices"][0]["src_path"])
    mask_src = src.parent.parent / "masks" / src.name
    if mask_src.exists():
        save_mask_preserve(mask_src, sdir / "layer_mask.png")


# ============================================================
# Main dispatcher
# ============================================================

CSV_NAME_TO_COHORT = {
    "Kermany": ("public_oct_kermany", None, None, None),
    "OCTID": ("public_oct_octid", None, None, None),
    "AROI": ("public_oct_aroi", None, None, aroi_post_artifact),
    "NEH_UT_2021": ("public_oct_neh_ut_2021", None, None, None),
    "AREDS2": ("public_oct_areds2", None, None, None),
    "Glaucoma_OCT": ("public_oct_glaucoma", None, None, None),
    "NYU_POAG": ("public_oct_nyu_poag", None, None, None),
    "OLIVES": ("public_oct_olives", enum_olives, None, None),
    "Chiu_DME_2015": ("public_oct_chiu_dme_2015", None, None, chiu_post_artifact),
    "Srinivasan_2014": ("public_oct_srinivasan_2014", None, None, None),
    "Sparsity_SDOCT_2012": ("public_oct_sparsity_sdoct_2012", None, None, None),
    "OIMHS": ("public_oct_oimhs", enum_oimhs_with_demographics, sidecar_demographics, oimhs_post_artifact),
    "RETOUCH": ("public_oct_retouch", enum_retouch, None, retouch_post_artifact),
    "THOCT1800": ("public_oct_thoct1800", None, None, None),
    "OCTDL": ("public_oct_octdl", enum_octdl_with_demographics, sidecar_demographics, None),
    "AMD-SD": ("public_oct_amd_sd", None, None, amd_sd_post_artifact),
    "C8": ("public_oct_c8", None, None, None),
}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input-root", required=True,
                    help="Path to '/mnt/new/OCT Retinal B-scan数据集汇总'")
    ap.add_argument("--output-root", required=True,
                    help="Output root (will create extracted/, manifest/, captions/)")
    ap.add_argument("--csv", default=None,
                    help="Path to unified_metadata.csv (default: <input-root>/数据分类整理汇总/unified_metadata.csv)")
    ap.add_argument("--cohorts", default="all",
                    help="comma-separated cohort names (full or short like 'kermany,octa500'), or 'all'")
    ap.add_argument("--num-workers", type=int, default=8)
    ap.add_argument("--force", action="store_true")
    ap.add_argument("--limit-per-cohort", type=int, default=None,
                    help="for testing: process only first N studies per cohort")
    args = ap.parse_args()

    in_root = Path(args.input_root)
    out_root = Path(args.output_root)
    csv_path = Path(args.csv) if args.csv else (in_root / "数据分类整理汇总" / "unified_metadata.csv")

    all_cohort_names = list(set(v[0] for v in CSV_NAME_TO_COHORT.values())) + [
        "public_oct_octa500", "public_oct_uestc"]
    if args.cohorts == "all":
        cohorts_to_run = set(all_cohort_names)
    else:
        requested = [c.strip() for c in args.cohorts.split(",")]
        cohorts_to_run = set()
        for r in requested:
            for full in all_cohort_names:
                if full == r or full.endswith(f"_{r}") or r in full:
                    cohorts_to_run.add(full)

    print(f"Will process {len(cohorts_to_run)} cohorts:")
    for c in sorted(cohorts_to_run):
        print(f"  {c}")
    print()

    # CSV-driven A-class cohorts
    if any(v[0] in cohorts_to_run for v in CSV_NAME_TO_COHORT.values()):
        print(f"Loading CSV: {csv_path}")
        csv_df = pd.read_csv(csv_path, low_memory=False)
        print(f"  {len(csv_df)} rows")

        for csv_name, (cohort, enum_fn, sidecar_fn, post_fn) in CSV_NAME_TO_COHORT.items():
            if cohort not in cohorts_to_run:
                continue
            ds_df = csv_df[csv_df["dataset_name"] == csv_name]
            if len(ds_df) == 0:
                print(f"[{cohort}] no CSV rows for dataset {csv_name}, skipping")
                continue
            if enum_fn is None:
                items = enum_from_csv_simple(ds_df, in_root, csv_name)
            else:
                items = enum_fn(ds_df, in_root)
            if args.limit_per_cohort:
                items = items[:args.limit_per_cohort]
            run_cohort(cohort, items, _shared_build_row_caps, out_root,
                       num_workers=args.num_workers, force=args.force,
                       sidecar_fn=sidecar_fn, cohort_phrase=COHORT_CONFIG[cohort]["phrase"],
                       post_artifact_fn=post_fn)

    # OCTA500
    if "public_oct_octa500" in cohorts_to_run:
        items = enum_octa500(in_root)
        if args.limit_per_cohort:
            items = items[:args.limit_per_cohort]

        def build_octa500(meta, cohort, cohort_phrase):
            return _shared_build_row_caps(
                meta, cohort, cohort_phrase,
                has_segmentation_fn=has_segmentation_octa500,
                l3_extras_fn=lambda m, s: ["with B-scan-level 6-class segmentation mask"]
                                          if has_segmentation_octa500(m, s) else [],
            )

        run_cohort("public_oct_octa500", items, build_octa500, out_root,
                   num_workers=args.num_workers, force=args.force,
                   sidecar_fn=sidecar_demographics,
                   cohort_phrase=COHORT_CONFIG["public_oct_octa500"]["phrase"],
                   post_artifact_fn=octa500_post_artifact)

    # UESTC
    if "public_oct_uestc" in cohorts_to_run:
        items = enum_uestc(in_root)
        if args.limit_per_cohort:
            items = items[:args.limit_per_cohort]
        run_cohort("public_oct_uestc", items, build_row_caps_uestc, out_root,
                   num_workers=args.num_workers, force=args.force,
                   sidecar_fn=None,
                   cohort_phrase=COHORT_CONFIG["public_oct_uestc"]["phrase"],
                   post_artifact_fn=None)

    print("\n[main] all done.")


if __name__ == "__main__":
    main()