#!/usr/bin/env python3 """Materialize Visual_Agent Parquet tables as path-based JSONL and images.""" from __future__ import annotations import argparse import hashlib import json import os import tempfile from pathlib import Path from typing import Any, Iterable import pyarrow.parquet as pq def sha256_bytes(value: bytes) -> str: return hashlib.sha256(value).hexdigest() def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for block in iter(lambda: handle.read(1024 * 1024), b""): digest.update(block) return digest.hexdigest() def safe_relative_path(value: str) -> Path: path = Path(value) if path.is_absolute() or not path.parts or ".." in path.parts: raise ValueError(f"unsafe relative path: {value!r}") if path.parts[0] != "images": raise ValueError(f"image path must be rooted under images/: {value!r}") return path def write_bytes_atomic(path: Path, value: bytes) -> None: path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile( dir=path.parent, prefix=path.name + ".", suffix=".tmp", delete=False, ) as handle: temporary = Path(handle.name) handle.write(value) handle.flush() os.fsync(handle.fileno()) os.replace(temporary, path) def write_jsonl_atomic(path: Path, rows: Iterable[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_name(path.name + ".tmp") with temporary.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=False) + "\n") os.replace(temporary, path) def materialize_images(input_root: Path, training_root: Path) -> dict[str, int]: image_shards = sorted((input_root / "images").glob("*.parquet")) if not image_shards: raise ValueError(f"no image Parquet shards under {input_root / 'images'}") counts = {"rows": 0, "written": 0, "reused": 0} seen_paths: set[str] = set() for shard in image_shards: parquet = pq.ParquetFile(shard) for batch in parquet.iter_batches(batch_size=32): for row in batch.to_pylist(): relative_text = str(row["path"]) if relative_text in seen_paths: raise ValueError(f"duplicate image path in Parquet: {relative_text}") seen_paths.add(relative_text) relative = safe_relative_path(relative_text) value = bytes(row["bytes"]) expected_size = int(row["size_bytes"]) expected_sha256 = str(row["sha256"]) if len(value) != expected_size: raise ValueError(f"{relative_text}: byte length does not match metadata") if sha256_bytes(value) != expected_sha256: raise ValueError(f"{relative_text}: embedded bytes fail SHA-256 validation") destination = training_root / relative if destination.exists(): if destination.stat().st_size != expected_size: raise ValueError(f"{destination}: existing file has a different size") if sha256_file(destination) != expected_sha256: raise ValueError(f"{destination}: existing file has different content") counts["reused"] += 1 else: write_bytes_atomic(destination, value) counts["written"] += 1 counts["rows"] += 1 return counts def materialize_samples(input_root: Path, training_root: Path) -> dict[str, int]: sample_shards = sorted((input_root / "samples").glob("*.parquet")) if not sample_shards: raise ValueError(f"no sample Parquet shards under {input_root / 'samples'}") indexed_rows: list[tuple[int, str, dict[str, Any]]] = [] seen_row_ids: set[str] = set() for shard in sample_shards: parquet = pq.ParquetFile(shard) for batch in parquet.iter_batches( batch_size=256, columns=["row_index", "row_id", "record_json"], ): for value in batch.to_pylist(): row_index = int(value["row_index"]) row_id = str(value["row_id"]) if row_id in seen_row_ids: raise ValueError(f"duplicate row_id in samples table: {row_id}") seen_row_ids.add(row_id) record = json.loads(str(value["record_json"])) if not isinstance(record, dict): raise ValueError(f"{row_id}: record_json is not an object") for image in record.get("images") or []: relative = safe_relative_path(str(image)) if not (training_root / relative).is_file(): raise ValueError(f"{row_id}: materialized image is missing: {image}") indexed_rows.append((row_index, row_id, record)) indexed_rows.sort(key=lambda item: item[0]) expected_indexes = list(range(len(indexed_rows))) actual_indexes = [item[0] for item in indexed_rows] if actual_indexes != expected_indexes: raise ValueError("samples row_index is not a complete zero-based sequence") combined_path = training_root / "all_training_trajectories_with_images.jsonl" write_jsonl_atomic(combined_path, (item[2] for item in indexed_rows)) p2r_rows = [item[2] for item in indexed_rows if str(item[1]).startswith("p2r_")] p2r_path = training_root / "p2r_v2/p2r_natural_v2_repaired_with_images.jsonl" write_jsonl_atomic(p2r_path, p2r_rows) return { "rows": len(indexed_rows), "p2r_v2_rows": len(p2r_rows), "combined_jsonl_sha256": sha256_file(combined_path), } def materialize(input_root: Path, output_root: Path) -> dict[str, Any]: input_root = input_root.resolve() output_root = output_root.resolve() manifest_path = input_root / "dataset_manifest.json" if not manifest_path.is_file(): raise ValueError(f"missing manifest: {manifest_path}") manifest = json.loads(manifest_path.read_text(encoding="utf-8")) training_root = output_root / "training_trajectories_natural" training_root.mkdir(parents=True, exist_ok=True) image_summary = materialize_images(input_root, training_root) sample_summary = materialize_samples(input_root, training_root) if image_summary["rows"] != int(manifest["unique_images"]): raise ValueError("materialized image count does not match manifest") if sample_summary["rows"] != int(manifest["samples"]): raise ValueError("materialized sample count does not match manifest") if sample_summary["combined_jsonl_sha256"] != str( manifest["combined_jsonl_sha256"] ): raise ValueError("materialized combined JSONL does not match manifest SHA-256") return { "output_root": str(output_root), "samples": sample_summary, "images": image_summary, "combined_jsonl": str( training_root / "all_training_trajectories_with_images.jsonl" ), } def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input-root", type=Path, default=Path(".")) parser.add_argument("--output-root", type=Path, required=True) args = parser.parse_args() print( json.dumps( materialize(args.input_root, args.output_root), ensure_ascii=False, indent=2, sort_keys=True, ) ) if __name__ == "__main__": main()