zju-eye-pretrain / code /prepare_hf_repo.py
MaybeRichard's picture
Initial upload: public_fundus (198k images, 42 shards) + manifest + captions + code
e2f75d1 verified
Raw
History Blame
12.5 kB
#!/usr/bin/env python3
"""
prepare_hf_repo.py — 生成 HuggingFace 仓库 staging 目录结构。
执行后 staging dir 长这样:
hf_staging/
├── README.md # HF dataset card (含 YAML front-matter 配 multi-config)
├── DATASET_OVERVIEW.md # 详细 overview (从本仓库 copy)
├── LICENSE # 多 cohort 协议汇总
├── code/ # 处理代码 (供 reproducibility)
├── manifest/ # 3 个 *_images_v1.parquet + studies + sidecar
├── captions/ # 3 个 *_captions_v1.parquet
└── data/ # pack_for_hf.py 产物 — 本脚本不动 data/
├── private_topcon/
├── public_fundus/
└── public_oct/
后续用:
cd hf_staging && huggingface-cli upload mayberichard/zju-eye-pretrain . --repo-type=dataset
"""
import argparse
import json
import shutil
from pathlib import Path
HF_README_TEMPLATE = """---
license: other
license_name: ophthalmology-mixed
license_link: https://github.com/mayberichard/zju-eye-pretrain/blob/main/LICENSE
task_categories:
- image-classification
- image-segmentation
- image-to-image
- text-to-image
- unconditional-image-generation
language:
- en
- zh
tags:
- ophthalmology
- retina
- oct
- fundus
- slo
- medical-imaging
- segmentation
- pretraining
size_categories:
- 1M<n<10M
pretty_name: ZJU Eye-Pretrain (Private Shanghai Topcon + 25 public cohorts)
configs:
- config_name: all
data_files:
- split: train
path: data/*/*.parquet
- config_name: private_topcon
data_files:
- split: train
path: data/private_topcon/*.parquet
- config_name: public_fundus
data_files:
- split: train
path: data/public_fundus/*.parquet
- config_name: public_oct
data_files:
- split: train
path: data/public_oct/*.parquet
__PER_COHORT_CONFIGS__
---
# ZJU Eye-Pretrain Dataset
> Unified multi-source ophthalmological imaging dataset for foundation model pretraining and downstream tasks.
**1.1M images** spanning **26 cohorts** with a **strict 41-column unified manifest schema**.
## Composition
| Source | Images | Modalities | Cohorts |
|---|---:|---|---|
| Private Shanghai DRI OCT Triton (SS-OCT) | 419,042 | oct_bscan + fundus_color + slo_gray | 1 |
| Public Fundus | 198,629 | fundus_color (+ GAMMA OCT) | 6 |
| Public OCT | 488,705 | oct_bscan | 19 |
| **Total** | **1,106,376** | | **26** |
See [DATASET_OVERVIEW.md](DATASET_OVERVIEW.md) for full details per cohort (devices, regions, masks, demographics).
## Quick Start
```python
from datasets import load_dataset
# Load everything (1.1M images)
ds = load_dataset("mayberichard/zju-eye-pretrain", streaming=True)
# Load one batch
ds = load_dataset("mayberichard/zju-eye-pretrain", "public_oct")
# Load one cohort
ds = load_dataset("mayberichard/zju-eye-pretrain", "kermany")
# Each row:
# image: PIL.Image
# {layer/lesion/vessel/disc_cup}_mask: PIL.Image or None
# image_id, study_id, patient_hash, modality, anatomy, severity, ...
```
## Schema (41-column manifest, identical across all batches)
```
cohort, study_id, patient_hash, visit_date, eye,
device_vendor, device_model, device_serial_hash, device_software_version,
hospital_domain, ethnicity,
image_quality_score, image_quality_band,
diagnosis_group, lesion_tags, lesion_location, layer_involvement, severity,
diagnosis_source, label_confidence, schema_version,
image_id, file_path, file_format,
modality, anatomy, device_technology, scan_protocol,
scan_x_mm, bscan_index,
image_height_px, image_width_px, axial_resolution_um,
has_segmentation, n_layers_visible,
fovea_x_norm, crt_um, choroid_thickness_um,
oct_footprint_bbox_fundus, oct_footprint_bbox_slo,
is_valid
```
Plus per-image `image` bytes and per-cohort mask columns.
## Captions
Each image has 5 captions (4 L1 variants + 1 L3 derived). Total 5.5M captions in `captions/`.
```python
from datasets import load_dataset
caps = load_dataset("mayberichard/zju-eye-pretrain", "captions_oct")
# join on image_id with the images config
```
## Licensing
This dataset aggregates multiple sources with mixed licenses. See [LICENSE](LICENSE) for per-cohort license terms. Users are responsible for compliance with the original license of each cohort.
**Private Shanghai Topcon data is included for research convenience.** Commercial use is prohibited.
## Citation
If you use this dataset, please cite the original source for each cohort used (see DATASET_OVERVIEW.md).
## Versioning & Updates
This dataset supports incremental updates. New cohorts can be added without touching existing data via additional shards in `data/<batch>/`. Schema migrations preserve old `*_v1.parquet` alongside new versions.
"""
PER_COHORT_CONFIG_TEMPLATE = """- config_name: {cohort_short}
data_files:
- split: train
path: data/{batch}/{cohort}-*.parquet"""
# 19 OCT public + 6 public fundus + 1 private = 26 cohorts
COHORT_TO_BATCH = {
# private
"shanghai_drioct_triton": "private_topcon",
# public fundus
"public_drive_vessel": "public_fundus",
"public_messidor2_dr": "public_fundus",
"public_idrid": "public_fundus",
"public_refuge2_disc_cup": "public_fundus",
"public_eyepacs_combo_dr_aug": "public_fundus",
"public_gamma_multimodal": "public_fundus",
# public OCT
"public_oct_kermany": "public_oct",
"public_oct_octid": "public_oct",
"public_oct_aroi": "public_oct",
"public_oct_neh_ut_2021": "public_oct",
"public_oct_areds2": "public_oct",
"public_oct_glaucoma": "public_oct",
"public_oct_nyu_poag": "public_oct",
"public_oct_olives": "public_oct",
"public_oct_chiu_dme_2015": "public_oct",
"public_oct_srinivasan_2014": "public_oct",
"public_oct_sparsity_sdoct_2012": "public_oct",
"public_oct_oimhs": "public_oct",
"public_oct_retouch": "public_oct",
"public_oct_thoct1800": "public_oct",
"public_oct_octdl": "public_oct",
"public_oct_amd_sd": "public_oct",
"public_oct_c8": "public_oct",
"public_oct_octa500": "public_oct",
"public_oct_uestc": "public_oct",
}
def cohort_short_name(cohort: str) -> str:
"""public_oct_kermany -> kermany"""
if cohort == "shanghai_drioct_triton":
return "private"
return (cohort
.replace("public_oct_", "")
.replace("public_", ""))
def make_readme() -> str:
per_cohort_lines = []
for cohort, batch in sorted(COHORT_TO_BATCH.items()):
short = cohort_short_name(cohort)
per_cohort_lines.append(PER_COHORT_CONFIG_TEMPLATE.format(
cohort_short=short, batch=batch, cohort=cohort))
# Use .replace() not .format() because README body contains literal {} braces
return HF_README_TEMPLATE.replace("__PER_COHORT_CONFIGS__", "\n".join(per_cohort_lines))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--src-code-dir", required=True,
help="本地 ZJU/Dataset 代码目录")
ap.add_argument("--src-private", required=True,
help="私有数据集根 (含 manifest/ + captions/)")
ap.add_argument("--src-public-fundus", required=True,
help="公开 fundus 根 (含 manifest/ + captions/)")
ap.add_argument("--src-public-oct", required=True,
help="公开 OCT 根 (含 manifest/ + captions/)")
ap.add_argument("--output", required=True, help="HF staging 目录")
args = ap.parse_args()
out = Path(args.output)
out.mkdir(parents=True, exist_ok=True)
(out / "data").mkdir(exist_ok=True)
(out / "data" / "private_topcon").mkdir(exist_ok=True)
(out / "data" / "public_fundus").mkdir(exist_ok=True)
(out / "data" / "public_oct").mkdir(exist_ok=True)
# 1. README.md
(out / "README.md").write_text(make_readme(), encoding="utf-8")
print(f" ✓ README.md ({(out/'README.md').stat().st_size//1024} KB)")
# 2. DATASET_OVERVIEW.md (从本地 copy)
src_overview = Path(args.src_code_dir) / "DATASET_OVERVIEW.md"
if src_overview.exists():
shutil.copy(src_overview, out / "DATASET_OVERVIEW.md")
print(f" ✓ DATASET_OVERVIEW.md")
# 3. LICENSE
(out / "LICENSE").write_text(
"# License Summary (per-cohort)\n\n"
"This dataset aggregates ophthalmological data from 26 sources with diverse licenses.\n"
"Users MUST comply with the license of each cohort they use.\n\n"
"| Cohort | License | Source |\n"
"|---|---|---|\n"
"| shanghai_drioct_triton | Research-only (IRB-approved) | Shanghai Zhongshan |\n"
"| public_drive_vessel | CC | DRIVE 2004 |\n"
"| public_messidor2_dr | research-only | ADCIS/Messidor-2 |\n"
"| public_idrid | CC BY 4.0 | IDRiD Challenge |\n"
"| public_refuge2_disc_cup | research-only | REFUGE2 Challenge |\n"
"| public_eyepacs_combo_dr_aug | various Kaggle terms | EyePACS combined |\n"
"| public_gamma_multimodal | research-only | GAMMA Challenge |\n"
"| public_oct_kermany | CC BY 4.0 | Kermany 2018 (Cell) |\n"
"| public_oct_octid | CC BY 4.0 | OCTID 2019 |\n"
"| public_oct_aroi | research-only | AROI 2021 |\n"
"| public_oct_neh_ut_2021 | research-only | NEH UT 2021 |\n"
"| public_oct_areds2 | NEI dbGaP | AREDS2 |\n"
"| public_oct_glaucoma | research-only | Glaucoma OCT 2020 |\n"
"| public_oct_nyu_poag | CC BY 4.0 | NYU POAG 2023 |\n"
"| public_oct_olives | CC BY 4.0 | OLIVES NeurIPS 2022 |\n"
"| public_oct_chiu_dme_2015 | research-only | Duke 2015 |\n"
"| public_oct_srinivasan_2014 | research-only | Duke/Harvard/Michigan 2014 |\n"
"| public_oct_sparsity_sdoct_2012 | research-only | 2012 dataset |\n"
"| public_oct_oimhs | CC BY 4.0 | OIMHS 2023 |\n"
"| public_oct_retouch | research-only | RETOUCH MICCAI 2017 |\n"
"| public_oct_thoct1800 | research-only | Tsinghua THOCT1800 |\n"
"| public_oct_octdl | CC BY 4.0 | OCTDL 2023 |\n"
"| public_oct_amd_sd | research-only | AMD-SD Nanchang |\n"
"| public_oct_c8 | various Kaggle terms | C8 compiled |\n"
"| public_oct_octa500 | research-only | OCTA-500 Li 2024 |\n"
"| public_oct_uestc | research-only (cite Wu 2023) | UESTC Tianchi |\n"
)
print(f" ✓ LICENSE")
# 4. code/
code_dir = out / "code"
code_dir.mkdir(exist_ok=True)
src_code = Path(args.src_code_dir)
code_files = [
"public_common.py", "oct_public_common.py",
"extract_fda.py", "extract_subscan.py", "build_manifest.py",
"adapter_drive.py", "adapter_messidor2.py", "adapter_idrid.py",
"adapter_refuge2.py", "adapter_eyepacs.py", "adapter_gamma.py",
"build_public_manifest.py",
"build_oct_public.py", "build_oct_public_manifest.py",
"pack_for_hf.py", "prepare_hf_repo.py",
"INTEGRATION_GUIDE.md", "run.sh",
]
n_copied = 0
for f in code_files:
src = src_code / f
if src.exists():
shutil.copy(src, code_dir / f)
n_copied += 1
print(f" ✓ code/ ({n_copied} files)")
# 5. manifest/
mf_dir = out / "manifest"
mf_dir.mkdir(exist_ok=True)
for src_root, prefix in [
(Path(args.src_private), "private_topcon"),
(Path(args.src_public_fundus), "public_fundus"),
(Path(args.src_public_oct), "oct_public"),
]:
src_mf = src_root / "manifest"
if not src_mf.exists():
print(f" WARN: {src_mf} 不存在")
continue
for f in src_mf.glob("*.parquet"):
shutil.copy(f, mf_dir / f.name)
print(f" ✓ manifest/ ({len(list(mf_dir.glob('*.parquet')))} parquet)")
# 6. captions/
cap_dir = out / "captions"
cap_dir.mkdir(exist_ok=True)
for src_root in [Path(args.src_private), Path(args.src_public_fundus),
Path(args.src_public_oct)]:
src_cap = src_root / "captions"
if not src_cap.exists():
continue
for f in src_cap.glob("*.parquet"):
shutil.copy(f, cap_dir / f.name)
print(f" ✓ captions/ ({len(list(cap_dir.glob('*.parquet')))} parquet)")
print(f"\n[done] HF staging ready: {out}")
print(f"\n下一步:")
print(f" 1. (单独) 跑 pack_for_hf.py 把 image bytes 转 parquet shard 到 {out}/data/{{batch}}/")
print(f" 2. cd {out} && huggingface-cli upload mayberichard/zju-eye-pretrain . --repo-type=dataset")
if __name__ == "__main__":
main()