set device_technology=unknown for NYU_POAG/C8 (no assumption); add device-granularity guidance to overview
ec7f8fa verified | #!/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() | |