File size: 1,928 Bytes
5ac28af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Convert the raw MP4 videos into WebDataset .tar shards."""

import argparse
import tarfile
from pathlib import Path


def write_shards(name, files, target_dir, per_shard):
    target_dir.mkdir(parents=True, exist_ok=True)
    for shard_idx in range(0, len(files), per_shard):
        shard_files = files[shard_idx:shard_idx + per_shard]
        shard_number = shard_idx // per_shard
        tar_path = target_dir / f"bouncing-balls-{name}-{shard_number:06d}.tar"
        with tarfile.open(tar_path, "w") as tar:
            for video_path in shard_files:
                key = video_path.stem
                tar.add(video_path, arcname=f"{key}.mp4")
        print(f"Wrote {tar_path} ({len(shard_files)} videos)", flush=True)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--source",
        type=Path,
        default=Path("bouncing-balls"),
        help="Dataset directory containing videos/",
    )
    parser.add_argument(
        "--output",
        type=Path,
        default=None,
        help="Output directory (default: SOURCE/wds)",
    )
    parser.add_argument("--train-per-shard", type=int, default=300)
    parser.add_argument("--val-per-shard", type=int, default=100)
    args = parser.parse_args()

    videos = sorted((args.source / "videos").glob("*.mp4"))
    if not videos:
        raise ValueError(f"No MP4 files found in {args.source / 'videos'}")

    output = args.output or args.source / "wds"
    split = int(0.9 * len(videos))
    train_videos = videos[:split]
    val_videos = videos[split:]

    write_shards("train", train_videos, output / "train", args.train_per_shard)
    write_shards("val", val_videos, output / "val", args.val_per_shard)

    print(
        f"Done: {len(train_videos)} train videos and "
        f"{len(val_videos)} validation videos in {output}",
        flush=True,
    )


if __name__ == "__main__":
    main()