#!/usr/bin/env python3 """Rewrite repository-relative V-Zero image paths to local absolute paths.""" from __future__ import annotations import argparse import os from pathlib import Path from typing import Any import pyarrow as pa import pyarrow.parquet as pq CORE_IMAGE_COLUMNS = ( "images", "teacher_images", "teacher_neg_images", "teacher_random_images", ) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--input", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--root", type=Path, required=True, help="Downloaded dataset repository root") return parser.parse_args() def local_path(value: str | None, *, root: Path) -> str | None: if value is None: return None path = Path(value) if path.is_absolute(): raise ValueError(f"Expected a repository-relative image path, got: {value}") resolved = (root / path).resolve() try: resolved.relative_to(root) except ValueError as error: raise ValueError(f"Image path escapes the dataset root: {value}") from error if not resolved.is_file(): raise FileNotFoundError(resolved) return str(resolved) def rewrite_image_list(value: Any, *, root: Path, column: str) -> list[dict[str, Any]]: rewritten: list[dict[str, Any]] = [] for item in value or []: if not isinstance(item, dict) or not isinstance(item.get("image"), str): raise TypeError(f"{column} must contain structs with a string 'image' field") updated = dict(item) updated["image"] = local_path(item["image"], root=root) rewritten.append(updated) return rewritten def main() -> None: args = parse_args() source = args.input.resolve() destination = args.output.resolve() root = args.root.resolve() if source == destination: raise ValueError("--output must not overwrite --input") if not source.is_file(): raise FileNotFoundError(source) if not root.is_dir(): raise NotADirectoryError(root) table = pq.read_table(source) rows = table.to_pylist() for row in rows: for column in CORE_IMAGE_COLUMNS: row[column] = rewrite_image_list(row.get(column), root=root, column=column) destination.parent.mkdir(parents=True, exist_ok=True) temporary = destination.with_name(f".{destination.name}.tmp") pq.write_table(pa.Table.from_pylist(rows, schema=table.schema), temporary, compression="zstd") readback = pq.read_table(temporary) if readback.num_rows != table.num_rows or readback.schema != table.schema: temporary.unlink(missing_ok=True) raise RuntimeError("Materialized parquet readback validation failed") os.replace(temporary, destination) print(f"Wrote {len(rows):,} rows to {destination}") if __name__ == "__main__": main()