File size: 2,950 Bytes
8329f20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/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()