| import argparse |
| import json |
| import os |
| import shutil |
| from pathlib import Path |
|
|
|
|
| def copy_or_link(src: Path, dst: Path, mode: str) -> None: |
| dst.parent.mkdir(parents=True, exist_ok=True) |
|
|
| if dst.exists(): |
| return |
|
|
| if mode == "hardlink": |
| try: |
| os.link(src, dst) |
| return |
| except OSError: |
| pass |
|
|
| shutil.copy2(src, dst) |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--src", default=".", help="Original hf_dataset directory") |
| parser.add_argument("--dst", default="../hf_dataset_sharded", help="Output sharded dataset directory") |
| parser.add_argument("--group-size", type=int, default=5000, help="Images per subdirectory") |
| parser.add_argument("--mode", choices=["copy", "hardlink"], default="hardlink") |
| args = parser.parse_args() |
|
|
| src = Path(args.src).resolve() |
| dst = Path(args.dst).resolve() |
|
|
| metadata_in = src / "metadata.jsonl" |
| metadata_out = dst / "metadata.jsonl" |
|
|
| if not metadata_in.exists(): |
| raise FileNotFoundError(f"Cannot find {metadata_in}") |
|
|
| if dst.exists(): |
| raise FileExistsError(f"{dst} already exists. Delete it first or choose another --dst.") |
|
|
| dst.mkdir(parents=True) |
|
|
| |
| for item in src.iterdir(): |
| if item.name in {"images", "metadata.jsonl"}: |
| continue |
|
|
| target = dst / item.name |
| if item.is_dir(): |
| shutil.copytree(item, target) |
| else: |
| shutil.copy2(item, target) |
|
|
| count = 0 |
| missing = [] |
|
|
| with metadata_in.open("r", encoding="utf-8") as fin, metadata_out.open("w", encoding="utf-8", newline="\n") as fout: |
| for idx, line in enumerate(fin): |
| if not line.strip(): |
| continue |
|
|
| row = json.loads(line) |
| old_rel = Path(row["file_name"].replace("\\", "/")) |
| old_img = src / old_rel |
|
|
| if not old_img.exists(): |
| missing.append(str(old_rel)) |
| continue |
|
|
| part_name = f"part-{idx // args.group_size:05d}" |
| new_rel = Path("images") / part_name / old_rel.name |
| new_img = dst / new_rel |
|
|
| copy_or_link(old_img, new_img, args.mode) |
|
|
| row["file_name"] = new_rel.as_posix() |
| fout.write(json.dumps(row, ensure_ascii=False) + "\n") |
| count += 1 |
|
|
| print(f"Done. Wrote {count} samples to {dst}") |
| print(f"New metadata: {metadata_out}") |
|
|
| if missing: |
| print(f"Missing images: {len(missing)}") |
| for x in missing[:20]: |
| print(" ", x) |
| raise SystemExit(1) |
|
|
|
|
| if __name__ == "__main__": |
| main()
|
|
|