File size: 5,986 Bytes
f750715
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python3
"""Unpack VideoGym-Train Parquet shards into the local families/ media tree.

Example usage:
    python unpack.py --dataset-dir . --workers 16
    python unpack.py --dataset-dir . --families geometry graph_theory --workers 8
    python unpack.py --dataset-dir . --tasks sokoban angle_bisector --samples-per-task 100
"""

from __future__ import annotations

import argparse
from concurrent.futures import ProcessPoolExecutor, as_completed
import json
from pathlib import Path

import pyarrow.parquet as pq


def _safe_relative_destination(root: Path, rel_path: str) -> Path:
    rel = Path(rel_path)
    if rel.is_absolute() or ".." in rel.parts or not rel.parts or rel.parts[0] != "families":
        raise ValueError(f"refusing unsafe relative media path: {rel_path!r}")
    return root / rel


def _unpack_shard(
    shard_path: str,
    output_root: str,
    allowed_tasks: set[str] | None,
    samples_per_task: int | None,
    initial_task_offset: int,
) -> tuple[int, int]:
    root = Path(output_root)
    pf = pq.ParquetFile(shard_path)
    written_rows = 0
    written_files = 0
    seen_for_task = initial_task_offset

    for rg_idx in range(pf.num_row_groups):
        table = pf.read_row_group(rg_idx, columns=["task_name", "image", "video"])
        tasks = table["task_name"].to_pylist()
        images = table["image"].to_pylist()
        videos = table["video"].to_pylist()
        for task_name, img, vid in zip(tasks, images, videos):
            if allowed_tasks is not None and task_name not in allowed_tasks:
                continue
            if samples_per_task is not None and seen_for_task >= samples_per_task:
                return written_rows, written_files
            seen_for_task += 1
            for entry in (img, vid):
                dest = _safe_relative_destination(root, entry["path"])
                payload = entry["bytes"]
                if dest.exists() and dest.stat().st_size == len(payload):
                    continue
                dest.parent.mkdir(parents=True, exist_ok=True)
                tmp = dest.with_name(dest.name + ".part")
                tmp.write_bytes(payload)
                tmp.replace(dest)
                written_files += 1
            written_rows += 1
    return written_rows, written_files


def _task_name_from_shard(path: Path) -> str:
    stem = path.stem
    parts = stem.rsplit("-", 3)
    if len(parts) == 4 and parts[2] == "of" and parts[1].isdigit() and parts[3].isdigit():
        return parts[0]
    return stem


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--dataset-dir",
        type=Path,
        default=Path(__file__).resolve().parent,
        help="Root directory of the downloaded VideoGym-Train dataset",
    )
    parser.add_argument(
        "--output-dir",
        type=Path,
        default=None,
        help="Target directory for unpacked families/ (defaults to --dataset-dir)",
    )
    parser.add_argument("--families", nargs="+", help="Unpack only specific task families")
    parser.add_argument("--tasks", nargs="+", help="Unpack only specific task names")
    parser.add_argument(
        "--samples-per-task",
        type=int,
        default=None,
        help="Unpack only the first N samples per task in manifest order",
    )
    parser.add_argument("--workers", type=int, default=8, help="Parallel worker processes")
    args = parser.parse_args()

    dataset_dir = args.dataset_dir.expanduser().resolve()
    output_dir = (args.output_dir or dataset_dir).expanduser().resolve()
    data_dir = dataset_dir / "data"
    if not data_dir.is_dir():
        raise FileNotFoundError(f"missing Parquet data/ directory under {dataset_dir}")
    if args.samples_per_task is not None and args.samples_per_task < 1:
        raise ValueError("--samples-per-task must be a positive integer")

    family_filter = set(args.families) if args.families else None
    task_filter = set(args.tasks) if args.tasks else None

    grouped_shards: dict[str, list[Path]] = {}
    for fam_dir in sorted(p for p in data_dir.iterdir() if p.is_dir()):
        if family_filter is not None and fam_dir.name not in family_filter:
            continue
        for shard in sorted(fam_dir.glob("*.parquet")):
            tname = _task_name_from_shard(shard)
            if task_filter is not None and tname not in task_filter:
                continue
            grouped_shards.setdefault(tname, []).append(shard)

    if not grouped_shards:
        raise ValueError("no matching Parquet shards found for the requested filters")

    jobs: list[tuple[str, str, set[str] | None, int | None, int]] = []
    for tname, shards in sorted(grouped_shards.items()):
        offset = 0
        for shard in shards:
            if args.samples_per_task is not None and offset >= args.samples_per_task:
                break
            nrows = pq.read_metadata(shard).num_rows
            jobs.append(
                (str(shard), str(output_dir), task_filter, args.samples_per_task, offset)
            )
            offset += nrows

    total_rows = 0
    total_files = 0
    workers = max(1, min(args.workers, len(jobs)))
    with ProcessPoolExecutor(max_workers=workers) as pool:
        futures = [pool.submit(_unpack_shard, *job) for job in jobs]
        for idx, fut in enumerate(as_completed(futures), 1):
            rows, files = fut.result()
            total_rows += rows
            total_files += files
            if idx % 25 == 0 or idx == len(jobs):
                print(
                    json.dumps(
                        {
                            "completed_shards": idx,
                            "total_shards": len(jobs),
                            "unpacked_samples": total_rows,
                            "written_files": total_files,
                        }
                    ),
                    flush=True,
                )


if __name__ == "__main__":
    main()