Initial upload: public_fundus (198k images, 42 shards) + manifest + captions + code
e2f75d1 verified | #!/usr/bin/env python3 | |
| """ | |
| GAMMA adapter — multimodal glaucoma grading (fundus + 3D OCT volume + DC mask + fovea). | |
| Inputs: | |
| {input_root}/grading/Glaucoma_grading/{training,testing}/multi-modality_images/NNNN/ | |
| NNNN.jpg fundus image | |
| NNNN/{0..255}_image.jpg 256 OCT B-scan slices (3D macular volume) | |
| NNNN_Sequence.mhd/.raw raw 3D metadata (not used here) | |
| {input_root}/grading/Glaucoma_grading/training/glaucoma_grading_training_GT.xlsx | |
| columns: data, non, early, mid_advanced (one-hot) | |
| {input_root}/fovea_localization_training_GT.xlsx | |
| columns: data, Fovea_X, Fovea_Y | |
| {input_root}/mask_DC/train/NNNN.png disc/cup mask, train only (pixel 0/128/255) | |
| Outputs (under {output_root}): | |
| extracted/public_gamma_multimodal/{hash[:2]}/{hash}/ | |
| fundus_color.jpg | |
| disc_cup_mask.png (train only; 0/128/255) | |
| oct_bscan_volume/000.png...255.png (re-encoded grayscale PNG) | |
| meta.json | |
| manifest/public_gamma_multimodal_images.parquet | |
| manifest/public_gamma_multimodal_sidecar.parquet (fovea coords, train only) | |
| captions/public_gamma_multimodal_captions.parquet | |
| Manifest rows per sample: 1 fundus row + 256 OCT B-scan rows, all sharing the same study_id. | |
| patient_hash = study_id (file-level, no patient ID in dataset). | |
| Glaucoma label mapping (one-hot): | |
| non=1 -> diagnosis_group=[], severity=none | |
| early=1 -> diagnosis_group=["glaucoma"], severity=mild | |
| mid_advanced=1 -> diagnosis_group=["glaucoma"], severity=severe | |
| """ | |
| import argparse | |
| import json | |
| import re | |
| from concurrent.futures import ProcessPoolExecutor, as_completed | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from PIL import Image, ImageFile | |
| ImageFile.LOAD_TRUNCATED_IMAGES = True | |
| from public_common import ( | |
| IMAGE_SCHEMA_COLUMNS, CAPTION_SCHEMA_COLUMNS, | |
| study_hash_for, default_base_fields, | |
| caption_l1_public, caption_l3_public, | |
| study_dir_for, rel_file_path, write_meta, coerce_image_row, | |
| ) | |
| COHORT = "public_gamma_multimodal" | |
| COHORT_PHRASE = "GAMMA multimodal glaucoma grading dataset" | |
| def _glaucoma_label(row): | |
| """Returns (diagnosis_group, severity) from one-hot label row.""" | |
| if row.get("non") == 1: return ([], "none") | |
| if row.get("early") == 1: return (["glaucoma"], "mild") | |
| if row.get("mid_advanced") == 1: return (["glaucoma"], "severe") | |
| return ([], "unknown") | |
| def _save_three_class_mask(src: Path, dst: Path): | |
| arr = np.array(Image.open(src).convert("L")) | |
| out = np.zeros_like(arr) | |
| out[(arr > 64) & (arr < 192)] = 128 | |
| out[arr >= 192] = 255 | |
| Image.fromarray(out, mode="L").save(dst, "PNG", optimize=True) | |
| def process_sample(args): | |
| (sample_id, split, sample_dir_str, label_row, fovea_row, mask_path_str, | |
| out_root_str, force) = args | |
| sample_dir = Path(sample_dir_str) | |
| out_root = Path(out_root_str) | |
| basename = f"{split}_{sample_id}" | |
| sh = study_hash_for(COHORT, basename) | |
| sdir = study_dir_for(out_root, COHORT, sh) | |
| sdir.mkdir(parents=True, exist_ok=True) | |
| oct_dir = sdir / "oct_bscan_volume" | |
| oct_dir.mkdir(exist_ok=True) | |
| meta_p = sdir / "meta.json" | |
| if meta_p.exists() and not force: | |
| try: | |
| meta = json.loads(meta_p.read_text()) | |
| if meta.get("status") == "ok": | |
| return _build_all(meta) | |
| except Exception: | |
| pass | |
| fundus_src = sample_dir / f"{sample_id}.jpg" | |
| fundus_dst = sdir / "fundus_color.jpg" | |
| img = Image.open(fundus_src).convert("RGB") | |
| fw, fh = img.size | |
| img.save(fundus_dst, "JPEG", quality=95) | |
| oct_slice_dir = sample_dir / sample_id | |
| slice_files = sorted(oct_slice_dir.glob("*_image.jpg"), | |
| key=lambda p: int(p.name.split("_")[0])) | |
| n_slices = len(slice_files) | |
| oct_h = oct_w = None | |
| for i, sf in enumerate(slice_files): | |
| with Image.open(sf) as si: | |
| arr = np.array(si.convert("L")) | |
| if oct_h is None: | |
| oct_h, oct_w = arr.shape | |
| Image.fromarray(arr, mode="L").save( | |
| oct_dir / f"{i:03d}.png", "PNG", optimize=True) | |
| has_dc_mask = False | |
| if mask_path_str: | |
| mp = Path(mask_path_str) | |
| if mp.exists(): | |
| _save_three_class_mask(mp, sdir / "disc_cup_mask.png") | |
| has_dc_mask = True | |
| meta = { | |
| "status": "ok", "cohort": COHORT, "study_hash": sh, | |
| "source_basename": basename, "split": split, "sample_id": sample_id, | |
| "fundus_height_px": int(fh), "fundus_width_px": int(fw), | |
| "n_oct_bscan": int(n_slices), | |
| "oct_bscan_height_px": int(oct_h) if oct_h else None, | |
| "oct_bscan_width_px": int(oct_w) if oct_w else None, | |
| "eye": "unknown", | |
| "has_dc_mask": has_dc_mask, | |
| "label_non": int(label_row.get("non", 0)) if label_row else None, | |
| "label_early": int(label_row.get("early", 0)) if label_row else None, | |
| "label_mid_advanced": int(label_row.get("mid_advanced", 0)) if label_row else None, | |
| "fovea_x_px": float(fovea_row["Fovea_X"]) if fovea_row else None, | |
| "fovea_y_px": float(fovea_row["Fovea_Y"]) if fovea_row else None, | |
| } | |
| write_meta(sdir, meta) | |
| return _build_all(meta) | |
| def _build_all(meta: dict): | |
| sh = meta["study_hash"] | |
| if meta.get("label_non") is not None: | |
| dx, sev = _glaucoma_label({"non": meta["label_non"], | |
| "early": meta["label_early"], | |
| "mid_advanced": meta["label_mid_advanced"]}) | |
| dx_source = "expert_grade" | |
| else: | |
| dx, sev = [], "unknown" | |
| dx_source = "none" | |
| base = default_base_fields(COHORT, sh, eye=meta["eye"]) | |
| base["diagnosis_group"] = dx | |
| base["severity"] = sev | |
| base["diagnosis_source"] = dx_source | |
| if dx_source == "expert_grade": | |
| base["label_confidence"] = "consensus" | |
| rows, caps = [], [] | |
| # --- Fundus row --- | |
| fundus_id = f"{COHORT}_{sh}_fundus_color" | |
| fundus_row = dict(base) | |
| fundus_row.update({ | |
| "image_id": fundus_id, | |
| "file_path": rel_file_path(COHORT, sh, "fundus_color.jpg"), | |
| "file_format": "jpg", | |
| "modality": "fundus_color", "anatomy": "macula", | |
| "device_technology": "fundus_camera", "scan_protocol": "single_shot", | |
| "image_height_px": meta["fundus_height_px"], | |
| "image_width_px": meta["fundus_width_px"], | |
| "has_segmentation": bool(meta.get("has_dc_mask")), | |
| "n_layers_visible": 0, | |
| "is_valid": True, | |
| }) | |
| rows.append(fundus_row) | |
| caps.extend(caption_l1_public(fundus_id, COHORT_PHRASE, "fundus_color", meta["eye"])) | |
| parts = [f"A color fundus photograph from the GAMMA dataset ({meta['split']} split)"] | |
| if sev != "unknown": | |
| parts.append(f"glaucoma severity {sev}") | |
| if meta.get("has_dc_mask"): | |
| parts.append("with optic disc and cup segmentation mask") | |
| if meta.get("fovea_x_px") is not None: | |
| parts.append("with fovea center annotation") | |
| caps.append(caption_l3_public(fundus_id, ", ".join(parts) + ".", | |
| "manifest_fields+mask_presence")) | |
| # --- OCT B-scan rows --- | |
| n = int(meta["n_oct_bscan"]) | |
| oct_h = meta.get("oct_bscan_height_px") or 992 | |
| oct_w = meta.get("oct_bscan_width_px") or 512 | |
| for i in range(n): | |
| bid = f"{COHORT}_{sh}_oct_bscan_volume_{i:03d}" | |
| row = dict(base) | |
| row.update({ | |
| "image_id": bid, | |
| "file_path": rel_file_path(COHORT, sh, f"oct_bscan_volume/{i:03d}.png"), | |
| "file_format": "png", | |
| "modality": "oct_bscan", "anatomy": "macula", | |
| "device_technology": "ss_oct", "scan_protocol": "volume_3d_macula", | |
| "bscan_index": i, | |
| "image_height_px": int(oct_h), | |
| "image_width_px": int(oct_w), | |
| "has_segmentation": False, "n_layers_visible": 0, | |
| "is_valid": True, | |
| }) | |
| rows.append(row) | |
| caps.extend(caption_l1_public(bid, COHORT_PHRASE, "oct_bscan", meta["eye"])) | |
| oct_parts = [f"A macular OCT B-scan from the GAMMA dataset ({meta['split']} split)", | |
| f"slice {i+1} of {n} in a 3D macular volume scan"] | |
| if sev != "unknown": | |
| oct_parts.append(f"glaucoma severity {sev}") | |
| caps.append(caption_l3_public(bid, ", ".join(oct_parts) + ".", | |
| "manifest_fields+volume_index")) | |
| return rows, caps, _sidecar_row(meta) if meta.get("fovea_x_px") is not None else None | |
| def _sidecar_row(meta: dict) -> dict: | |
| sh = meta["study_hash"] | |
| return { | |
| "study_id": sh, | |
| "fundus_image_id": f"{COHORT}_{sh}_fundus_color", | |
| "split": meta["split"], | |
| "fovea_x_px": meta.get("fovea_x_px"), | |
| "fovea_y_px": meta.get("fovea_y_px"), | |
| "fundus_width_px": meta["fundus_width_px"], | |
| "fundus_height_px": meta["fundus_height_px"], | |
| } | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--input-root", required=True, | |
| help="Path to .../Generation/GAMMA") | |
| ap.add_argument("--output-root", required=True) | |
| ap.add_argument("--num-workers", type=int, default=4) | |
| ap.add_argument("--force", action="store_true") | |
| ap.add_argument("--limit", type=int, default=None) | |
| args = ap.parse_args() | |
| in_root = Path(args.input_root) | |
| out_root = Path(args.output_root) | |
| train_labels = pd.read_excel( | |
| in_root / "grading/Glaucoma_grading/training/glaucoma_grading_training_GT.xlsx") | |
| train_labels["data"] = train_labels["data"].apply(lambda x: f"{int(x):04d}") | |
| label_idx = train_labels.set_index("data").to_dict(orient="index") | |
| fovea_df = pd.read_excel(in_root / "fovea_localization_training_GT.xlsx") | |
| fovea_df["data"] = fovea_df["data"].apply(lambda x: f"{int(x):04d}") | |
| fovea_idx = fovea_df.set_index("data").to_dict(orient="index") | |
| jobs = [] | |
| name_re = re.compile(r"^\d{4}$") | |
| for split_dir, split_name in [ | |
| (in_root / "grading/Glaucoma_grading/training/multi-modality_images", "train"), | |
| (in_root / "grading/Glaucoma_grading/testing/multi-modality_images", "test"), | |
| ]: | |
| for sample in sorted(p.name for p in split_dir.iterdir() if p.is_dir() and name_re.match(p.name)): | |
| sd = split_dir / sample | |
| lbl = label_idx.get(sample) if split_name == "train" else None | |
| fov = fovea_idx.get(sample) if split_name == "train" else None | |
| mask_p = (in_root / "mask_DC" / "train" / f"{sample}.png") if split_name == "train" else None | |
| jobs.append((sample, split_name, str(sd), lbl, fov, | |
| str(mask_p) if mask_p else None, str(out_root), args.force)) | |
| if args.limit: | |
| jobs = jobs[:args.limit] | |
| print(f"[{COHORT}] {len(jobs)} samples to process") | |
| all_rows, all_caps, all_side = [], [], [] | |
| failures = [] | |
| with ProcessPoolExecutor(max_workers=args.num_workers) as ex: | |
| fut_to_sid = {ex.submit(process_sample, j): j[0] for j in jobs} | |
| for i, fut in enumerate(as_completed(fut_to_sid), 1): | |
| sid = fut_to_sid[fut] | |
| try: | |
| rows, caps, side = fut.result() | |
| except Exception as e: | |
| failures.append((sid, type(e).__name__, str(e)[:120])) | |
| continue | |
| all_rows.extend(rows) | |
| all_caps.extend(caps) | |
| if side: | |
| all_side.append(side) | |
| if i % 20 == 0: | |
| print(f" ... {i}/{len(fut_to_sid)} samples done ({len(failures)} failed)") | |
| if failures: | |
| print(f"[{COHORT}] {len(failures)} samples FAILED:") | |
| for sid, et, msg in failures[:20]: | |
| print(f" {sid}: {et}: {msg}") | |
| mdir = out_root / "manifest"; cdir = out_root / "captions" | |
| mdir.mkdir(parents=True, exist_ok=True); cdir.mkdir(parents=True, exist_ok=True) | |
| imgs_df = pd.DataFrame([coerce_image_row(r) for r in all_rows])[IMAGE_SCHEMA_COLUMNS] | |
| imgs_df.to_parquet(mdir / f"{COHORT}_images.parquet", index=False) | |
| caps_df = pd.DataFrame(all_caps)[CAPTION_SCHEMA_COLUMNS] | |
| caps_df.to_parquet(cdir / f"{COHORT}_captions.parquet", index=False) | |
| if all_side: | |
| pd.DataFrame(all_side).to_parquet(mdir / f"{COHORT}_sidecar.parquet", index=False) | |
| print(f"[{COHORT}] wrote {len(imgs_df)} image rows ({(imgs_df.modality=='fundus_color').sum()} fundus + " | |
| f"{(imgs_df.modality=='oct_bscan').sum()} oct), {len(caps_df)} captions, {len(all_side)} sidecar rows") | |
| print(imgs_df.groupby(["modality", "severity"]).size().to_string()) | |
| if __name__ == "__main__": | |
| main() | |