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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Materialize VBVR-Reorganized parquet shards back into the on-disk
|
| 3 |
+
sample-directory layout described in the dataset README.
|
| 4 |
+
|
| 5 |
+
Each row of the parquet contains the full bytes of `first_frame.png`,
|
| 6 |
+
`final_frame.png`, and `ground_truth.mp4` plus the `prompt` /
|
| 7 |
+
`prompt_original` text and the raw `metadata_json` string. This script
|
| 8 |
+
streams the parquet (no full-file load) and writes one directory per row
|
| 9 |
+
under:
|
| 10 |
+
|
| 11 |
+
<out>/<split>/<class>/<task>/<sample_id>/
|
| 12 |
+
first_frame.png
|
| 13 |
+
final_frame.png
|
| 14 |
+
ground_truth.mp4
|
| 15 |
+
prompt.txt
|
| 16 |
+
prompt_original.txt (only if present)
|
| 17 |
+
metadata.json (only if non-empty)
|
| 18 |
+
|
| 19 |
+
`split` is taken from the row's `split` column verbatim (e.g.
|
| 20 |
+
`test/In-Domain_50`, `train`, `train_pr_rewritten`). `sample_id`
|
| 21 |
+
already encodes the per-task wrapper layer for train rows
|
| 22 |
+
(`<task>_task/<task>_<id>`) so paths reproduce the source tree exactly.
|
| 23 |
+
|
| 24 |
+
USAGE
|
| 25 |
+
|
| 26 |
+
# 1) extract a single parquet shard:
|
| 27 |
+
python3 extract_parquet_to_dir.py \\
|
| 28 |
+
--parquet parquet/test_in_domain.parquet \\
|
| 29 |
+
--out ./VBVR-extracted
|
| 30 |
+
|
| 31 |
+
# 2) extract every parquet under parquet/ into one tree:
|
| 32 |
+
python3 extract_parquet_to_dir.py \\
|
| 33 |
+
--parquet parquet/ \\
|
| 34 |
+
--out ./VBVR-extracted
|
| 35 |
+
|
| 36 |
+
# 3) extract only one task from a train shard:
|
| 37 |
+
python3 extract_parquet_to_dir.py \\
|
| 38 |
+
--parquet parquet/train__G-13_grid_number_sequence.parquet \\
|
| 39 |
+
--out ./VBVR-extracted \\
|
| 40 |
+
--task G-13_grid_number_sequence_data-generator
|
| 41 |
+
|
| 42 |
+
The script never loads more than one row-group into memory at a time, so
|
| 43 |
+
it's safe on the multi-GB train shards.
|
| 44 |
+
"""
|
| 45 |
+
from __future__ import annotations
|
| 46 |
+
|
| 47 |
+
import argparse
|
| 48 |
+
import sys
|
| 49 |
+
import time
|
| 50 |
+
from pathlib import Path
|
| 51 |
+
|
| 52 |
+
import pyarrow.parquet as pq
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def iter_parquet_files(target: Path):
|
| 56 |
+
if target.is_file():
|
| 57 |
+
yield target
|
| 58 |
+
elif target.is_dir():
|
| 59 |
+
yield from sorted(target.glob("*.parquet"))
|
| 60 |
+
else:
|
| 61 |
+
raise FileNotFoundError(target)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def write_row(out_root: Path, row: dict, *, overwrite: bool) -> bool:
|
| 65 |
+
split = row["split"] or ""
|
| 66 |
+
cls = row["class"] or ""
|
| 67 |
+
task = row["task"] or ""
|
| 68 |
+
sid = row["sample_id"] or ""
|
| 69 |
+
if not (split and cls and task and sid):
|
| 70 |
+
print(f" ! row missing identifying fields, skipped: {row.get('sample_id')!r}",
|
| 71 |
+
file=sys.stderr)
|
| 72 |
+
return False
|
| 73 |
+
dst = out_root / split / cls / task / sid
|
| 74 |
+
if dst.exists() and not overwrite:
|
| 75 |
+
# Reuse existing directory but still (re)write files in case bytes changed.
|
| 76 |
+
pass
|
| 77 |
+
dst.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
|
| 79 |
+
ff = row.get("first_frame")
|
| 80 |
+
if ff and ff.get("bytes"):
|
| 81 |
+
(dst / "first_frame.png").write_bytes(ff["bytes"])
|
| 82 |
+
ef = row.get("final_frame")
|
| 83 |
+
if ef and ef.get("bytes"):
|
| 84 |
+
(dst / "final_frame.png").write_bytes(ef["bytes"])
|
| 85 |
+
gv = row.get("ground_truth_video")
|
| 86 |
+
if gv and gv.get("bytes"):
|
| 87 |
+
(dst / "ground_truth.mp4").write_bytes(gv["bytes"])
|
| 88 |
+
|
| 89 |
+
prompt = row.get("prompt")
|
| 90 |
+
if prompt is not None:
|
| 91 |
+
(dst / "prompt.txt").write_text(prompt, encoding="utf-8")
|
| 92 |
+
op = row.get("prompt_original")
|
| 93 |
+
if op is not None and op != "":
|
| 94 |
+
(dst / "prompt_original.txt").write_text(op, encoding="utf-8")
|
| 95 |
+
mj = row.get("metadata_json")
|
| 96 |
+
if mj:
|
| 97 |
+
(dst / "metadata.json").write_text(mj, encoding="utf-8")
|
| 98 |
+
return True
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def extract_one_parquet(pq_path: Path, out_root: Path, *,
|
| 102 |
+
only_class: str | None,
|
| 103 |
+
only_task: str | None,
|
| 104 |
+
only_sample: str | None,
|
| 105 |
+
overwrite: bool) -> tuple[int, int]:
|
| 106 |
+
"""Stream a single parquet file; return (rows_written, rows_skipped)."""
|
| 107 |
+
pf = pq.ParquetFile(str(pq_path))
|
| 108 |
+
written = 0
|
| 109 |
+
skipped = 0
|
| 110 |
+
t0 = time.time()
|
| 111 |
+
print(f"\n[{pq_path.name}] {pf.metadata.num_rows} rows in "
|
| 112 |
+
f"{pf.num_row_groups} row groups", flush=True)
|
| 113 |
+
for rg_idx in range(pf.num_row_groups):
|
| 114 |
+
table = pf.read_row_group(rg_idx)
|
| 115 |
+
rows = table.to_pylist()
|
| 116 |
+
for row in rows:
|
| 117 |
+
if only_class and row.get("class") != only_class:
|
| 118 |
+
skipped += 1; continue
|
| 119 |
+
if only_task and row.get("task") != only_task:
|
| 120 |
+
skipped += 1; continue
|
| 121 |
+
if only_sample and row.get("sample_id") != only_sample:
|
| 122 |
+
skipped += 1; continue
|
| 123 |
+
if write_row(out_root, row, overwrite=overwrite):
|
| 124 |
+
written += 1
|
| 125 |
+
elapsed = time.time() - t0
|
| 126 |
+
print(f" rg {rg_idx+1}/{pf.num_row_groups} "
|
| 127 |
+
f"+{len(rows)} rows "
|
| 128 |
+
f"(written={written} skipped={skipped} {elapsed:.0f}s)",
|
| 129 |
+
flush=True)
|
| 130 |
+
return written, skipped
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def main(argv: list[str]) -> int:
|
| 134 |
+
ap = argparse.ArgumentParser(description=__doc__,
|
| 135 |
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 136 |
+
ap.add_argument("--parquet", required=True, type=Path,
|
| 137 |
+
help="Path to a .parquet file OR a directory containing .parquet files.")
|
| 138 |
+
ap.add_argument("--out", required=True, type=Path,
|
| 139 |
+
help="Output root directory. Sample dirs are written under "
|
| 140 |
+
"<out>/<split>/<class>/<task>/<sample_id>/.")
|
| 141 |
+
ap.add_argument("--class", dest="only_class", default=None,
|
| 142 |
+
help="Only extract rows whose `class` column equals this "
|
| 143 |
+
"(e.g. 'Pure_Reasoning' or 'Instruction_Following').")
|
| 144 |
+
ap.add_argument("--task", dest="only_task", default=None,
|
| 145 |
+
help="Only extract rows whose `task` column equals this "
|
| 146 |
+
"(e.g. 'G-13_grid_number_sequence_data-generator').")
|
| 147 |
+
ap.add_argument("--sample", dest="only_sample", default=None,
|
| 148 |
+
help="Only extract the row whose `sample_id` equals this exact string.")
|
| 149 |
+
ap.add_argument("--overwrite", action="store_true",
|
| 150 |
+
help="(Default: also true.) Overwrite files in existing dirs. "
|
| 151 |
+
"This flag is kept for clarity.")
|
| 152 |
+
args = ap.parse_args(argv)
|
| 153 |
+
|
| 154 |
+
args.out.mkdir(parents=True, exist_ok=True)
|
| 155 |
+
files = list(iter_parquet_files(args.parquet))
|
| 156 |
+
if not files:
|
| 157 |
+
print(f"no parquet files under {args.parquet}", file=sys.stderr)
|
| 158 |
+
return 1
|
| 159 |
+
print(f"extracting {len(files)} parquet file(s) into {args.out}", flush=True)
|
| 160 |
+
|
| 161 |
+
total_written = 0; total_skipped = 0
|
| 162 |
+
for f in files:
|
| 163 |
+
w, s = extract_one_parquet(f, args.out,
|
| 164 |
+
only_class=args.only_class,
|
| 165 |
+
only_task=args.only_task,
|
| 166 |
+
only_sample=args.only_sample,
|
| 167 |
+
overwrite=args.overwrite)
|
| 168 |
+
total_written += w; total_skipped += s
|
| 169 |
+
|
| 170 |
+
print(f"\ndone: {total_written} rows written, {total_skipped} rows skipped.")
|
| 171 |
+
print(f"output tree at {args.out}")
|
| 172 |
+
return 0
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
if __name__ == "__main__":
|
| 176 |
+
sys.exit(main(sys.argv[1:]))
|