File size: 2,715 Bytes
957610d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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)

    # Copy root files and folders except images/ and metadata.jsonl.
    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()