zju-eye-pretrain / code /pack_for_hf.py
MaybeRichard's picture
Initial upload: public_fundus (198k images, 42 shards) + manifest + captions + code
e2f75d1 verified
Raw
History Blame Contribute Delete
7.84 kB
#!/usr/bin/env python3
"""
pack_for_hf.py — 把 extracted/ + manifest + masks 转成 HuggingFace parquet shard。
每 row 包含:
- 全部 41 列 manifest 字段
- image: bytes (PNG/JPG raw)
- 各 cohort 对应的 mask column (bytes, 可为 None)
Sharding: 按 cohort 分组,每 cohort 切多 shard, 命名 {cohort}-{i:05d}-of-{N:05d}.parquet,
shard size 目标 ~600 MB。
Usage:
python pack_for_hf.py \\
--manifest /path/to/oct_public_images_v1.parquet \\
--extracted-root /path/to/extracted \\
--output-dir hf_staging/data/public_oct \\
[--cohort public_oct_kermany] # filter
[--shard-size-mb 600]
[--num-workers 4]
"""
import argparse
import io
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
# 每 cohort 的 mask 列名 → 文件名模板 (study_dir 内相对)
# {bscan_index:03d} 会按 row.bscan_index 替换
MASK_RESOLVERS = {
# ----- Public fundus -----
"public_drive_vessel": {
"vessel_mask": "vessel_mask.png",
"fov_mask": "fov_mask.png",
},
"public_idrid": {
"lesion_microaneurysms_mask": "lesion_microaneurysms.png",
"lesion_haemorrhages_mask": "lesion_haemorrhages.png",
"lesion_hard_exudates_mask": "lesion_hard_exudates.png",
"lesion_soft_exudates_mask": "lesion_soft_exudates.png",
"optic_disc_mask": "optic_disc_mask.png",
},
"public_refuge2_disc_cup": {"disc_cup_mask": "disc_cup_mask.png"},
"public_gamma_multimodal": {"disc_cup_mask": "disc_cup_mask.png"},
# ----- Public OCT -----
"public_oct_oimhs": {"layer_mask": "layer_mask.png"},
"public_oct_aroi": {"layer_mask": "layer_mask.png"},
"public_oct_retouch": {"fluid_mask": "fluid_mask.png"},
"public_oct_amd_sd": {"lesion_mask": "lesion_mask.png"},
"public_oct_chiu_dme_2015": {"layer_mask": "layer_mask.png"},
"public_oct_glaucoma": {"layer_mask": "layer_mask.png"},
"public_oct_octa500": {"mask": "mask_{bscan_index:03d}.png"},
# ----- Private Topcon -----
# segmentation.npz (10-layer ALL bscans in one file) — 留给 v2 处理
# 当前 v1 不嵌入 npz, 仅 manifest 有 has_segmentation 字段
}
def resolve_mask_bytes(row, study_dir: Path) -> dict:
"""读取该 row 对应的所有 mask 文件 bytes (缺失为 None)."""
cohort = row.cohort
masks = {}
for col_name, pat in MASK_RESOLVERS.get(cohort, {}).items():
if "{bscan_index" in pat:
idx = row.bscan_index
if idx is None:
masks[col_name] = None
continue
fname = pat.format(bscan_index=int(idx))
else:
fname = pat
p = study_dir / fname
masks[col_name] = p.read_bytes() if p.exists() else None
return masks
def get_study_dir(file_path_str: str, extracted_root: Path) -> Path:
"""从 row.file_path 推 study 目录 (含 bscan/masks 的目录)."""
abs_p = extracted_root / file_path_str
return abs_p.parent
def process_row(row, extracted_root, all_mask_columns):
"""读 image bytes + mask bytes, 返回一个 dict (parquet row)."""
file_path = row["file_path"]
abs_p = extracted_root / file_path
if not abs_p.exists():
return None # 文件缺失,跳过
try:
img_bytes = abs_p.read_bytes()
except Exception:
return None
if len(img_bytes) == 0:
return None # 0 KB 文件,跳过
study_dir = abs_p.parent
mask_data = resolve_mask_bytes(row, study_dir)
# 完整 row dict: 全 manifest 列 + image + 所有 mask 列 (本 cohort 没有的 mask 列填 None)
out = {k: row[k] for k in row.index}
out["image"] = img_bytes
for col in all_mask_columns:
out[col] = mask_data.get(col)
return out
def write_shards(rows_iter, output_dir: Path, cohort: str,
shard_size_bytes: int):
"""
将 rows_iter 中的 dict 写到多个 parquet shard。
Shard 命名: {cohort}-{idx:05d}-of-{total}.parquet (total 先写 NNNNN 占位,最后 rename)。
返回最终 shard 数。
"""
shard_idx = 0
cur_buf = []
cur_bytes = 0
written_shards = []
def flush():
nonlocal shard_idx, cur_buf, cur_bytes
if not cur_buf:
return
tmp_path = output_dir / f"{cohort}-{shard_idx:05d}-tmp.parquet"
tbl = pa.Table.from_pylist(cur_buf)
pq.write_table(tbl, tmp_path, compression="zstd")
written_shards.append(tmp_path)
shard_idx += 1
cur_buf = []
cur_bytes = 0
for r in rows_iter:
if r is None:
continue
# rough size estimate: image bytes + mask bytes + ~500 metadata
sz = len(r["image"]) + 500
for k, v in r.items():
if k.endswith("_mask") and v is not None:
sz += len(v)
if cur_bytes + sz > shard_size_bytes and cur_buf:
flush()
cur_buf.append(r)
cur_bytes += sz
flush()
# Rename with final shard count
n = len(written_shards)
for tmp in written_shards:
idx_part = tmp.name.split("-")[1]
final = output_dir / f"{cohort}-{idx_part}-of-{n:05d}.parquet"
tmp.rename(final)
return n
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--manifest", required=True)
ap.add_argument("--extracted-root", required=True)
ap.add_argument("--output-dir", required=True)
ap.add_argument("--cohort", default=None, help="只处理指定 cohort")
ap.add_argument("--shard-size-mb", type=int, default=600)
ap.add_argument("--num-workers", type=int, default=4)
ap.add_argument("--limit-per-cohort", type=int, default=None,
help="测试用: 每 cohort 只 pack 前 N 行")
args = ap.parse_args()
extracted_root = Path(args.extracted_root)
output_dir = Path(args.output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
shard_size_bytes = args.shard_size_mb * 1024 * 1024
df = pd.read_parquet(args.manifest)
if args.cohort:
df = df[df.cohort == args.cohort]
print(f"Loaded {len(df)} rows from {args.manifest}")
print(f"Cohorts to pack: {df.cohort.unique().tolist()}")
print()
# 所有出现在本 manifest 中的 cohort 的 mask 列名 union
cohorts_in_df = set(df.cohort.unique())
all_mask_columns = sorted({
c for ck, cols in MASK_RESOLVERS.items() if ck in cohorts_in_df
for c in cols
})
print(f"Mask columns union: {all_mask_columns}")
print()
total_shards = 0
total_rows = 0
for cohort, sub in df.groupby("cohort"):
if args.limit_per_cohort:
sub = sub.head(args.limit_per_cohort)
n = len(sub)
print(f"[{cohort}] packing {n} rows ...")
# 并行读 image+mask bytes, 然后串行写 parquet
with ThreadPoolExecutor(max_workers=args.num_workers) as ex:
futs = [ex.submit(process_row, r, extracted_root, all_mask_columns)
for r in sub.to_dict(orient="records")]
results = []
for i, f in enumerate(futs, 1):
results.append(f.result())
if i % 5000 == 0:
n_ok = sum(1 for r in results if r is not None)
print(f" read {i}/{n} ({n_ok} ok)")
n_ok = sum(1 for r in results if r is not None)
n_skip = n - n_ok
n_shards = write_shards(results, output_dir, cohort, shard_size_bytes)
print(f" → {n_ok} rows written, {n_skip} skipped (missing/0KB), {n_shards} shards")
total_shards += n_shards
total_rows += n_ok
print(f"\n[done] {total_rows} rows in {total_shards} shards under {output_dir}")
if __name__ == "__main__":
main()