File size: 4,396 Bytes
ce39f54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Check that a local copy of VLM-UQBench is complete and self-consistent.

Checks that every image and mask path in the manifests and outputs is relative,
stays inside the dataset folder and exists; that the files under images/,
perturbed/ and masks/ match metadata/file_map.jsonl one to one; that the
recorded SHA-256 values agree; and that every output row points to a manifest
row. With --hash it also re-hashes every stored file (reads about 6 GB).

Usage:
    python scripts/verify_release.py [--root .] [--hash]
"""
from __future__ import annotations

import argparse
import hashlib
import json
import sys
from pathlib import Path, PurePosixPath

import pyarrow.parquet as pq

FILE_DIRS = ("images", "perturbed", "masks")


def read_jsonl(path: Path) -> list[dict]:
    with open(path, encoding="utf-8") as f:
        return [json.loads(line) for line in f if line.strip()]


def sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--root", type=Path, default=Path(__file__).resolve().parents[1])
    ap.add_argument("--hash", action="store_true", help="re-hash every stored file")
    args = ap.parse_args()
    root = args.root.resolve()
    errors: list[str] = []

    def check_path(p: str, where: str) -> None:
        pp = PurePosixPath(p)
        if pp.is_absolute() or ".." in pp.parts or "\\" in p:
            errors.append(f"{where}: bad path {p!r}")
            return
        full = (root / pp).resolve()
        if root not in full.parents or not full.is_file():
            errors.append(f"{where}: missing or outside root {p!r}")

    # file map <-> files on disk
    fmap = read_jsonl(root / "metadata" / "file_map.jsonl")
    sha_of = {}
    for r in fmap:
        if r["path"] is not None:
            if sha_of.setdefault(r["path"], r["sha256"]) != r["sha256"]:
                errors.append(f"file_map: {r['path']} has two hashes")
    stored = {r["path"] for r in fmap if r["stored"]}
    on_disk = {str(p.relative_to(root)) for d in FILE_DIRS for p in (root / d).rglob("*")
               if p.is_file() and p.name not in ("LICENSE.md",)}
    for p in sorted(on_disk - stored)[:20]:
        errors.append(f"unlisted file {p}")
    for p in sorted(stored - on_disk)[:20]:
        errors.append(f"listed file missing {p}")
    if args.hash:
        for p in sorted(stored):
            if (root / p).is_file() and sha256(root / p) != sha_of[p]:
                errors.append(f"hash mismatch {p}")

    # manifests
    n_paths, uids = 0, set()
    manifests = sorted((root / "manifests").rglob("*.jsonl"))
    for mf in manifests:
        rel = mf.relative_to(root)
        seen = set()
        for i, r in enumerate(read_jsonl(mf)):
            where = f"{rel}:{i + 1}"
            if r["uid"] in seen:
                errors.append(f"{where}: duplicate uid {r['uid']}")
            seen.add(r["uid"])
            for p in ([r["image"]] if r.get("image") else []) + r.get("masks", []):
                n_paths += 1
                check_path(p, where)
            if r.get("image") and r.get("image_sha256") and sha_of.get(r["image"]) != r["image_sha256"]:
                errors.append(f"{where}: image_sha256 differs from file_map")
        uids |= seen

    # outputs
    n_out = 0
    for pf in sorted((root / "outputs").rglob("*.parquet")):
        rel = pf.relative_to(root)
        t = pq.read_table(pf, columns=["uid", "image"]).to_pydict()
        for i, (uid, img) in enumerate(zip(t["uid"], t["image"])):
            n_out += 1
            if uid not in uids:
                errors.append(f"{rel}:{i}: uid not in manifests {uid}")
            if img:
                n_paths += 1
                check_path(img, f"{rel}:{i}")

    print(f"manifests: {len(manifests)} files, {len(uids)} rows; output rows: {n_out}; "
          f"paths checked: {n_paths}; stored files: {len(stored)}"
          + ("; hashes verified" if args.hash else ""))
    for e in errors[:50]:
        print("ERROR", e)
    print("OK" if not errors else f"FAILED ({len(errors)} problems)")
    return 1 if errors else 0


if __name__ == "__main__":
    sys.exit(main())