File size: 3,612 Bytes
40bbfa3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validate the archive-based Hugging Face nuScenes-NRS release."""

from __future__ import annotations

import argparse
import hashlib
import re
import zipfile
from pathlib import Path

import cv2
import numpy as np


EXPECTED = {"training": 3182, "validation": 805}
TOKEN_RE = re.compile(r"^[0-9a-f]{32}$")


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 read_tokens(path: Path) -> list[str]:
    tokens = [line.strip() for line in path.read_text(encoding="utf-8").splitlines() if line.strip()]
    if len(tokens) != len(set(tokens)) or any(not TOKEN_RE.fullmatch(t) for t in tokens):
        raise AssertionError(f"invalid or duplicate tokens in {path}")
    return tokens


def validate_split(root: Path, split: str) -> list[str]:
    tokens = read_tokens(root / "splits" / f"{split}.txt")
    if len(tokens) != EXPECTED[split]:
        raise AssertionError(f"{split}: expected {EXPECTED[split]}, found {len(tokens)}")
    archive = root / split / "masks.zip"
    if not archive.is_file():
        raise AssertionError(f"missing {archive}")
    expected_names = {f"masks/{token}.png" for token in tokens}
    with zipfile.ZipFile(archive) as bundle:
        names = {name for name in bundle.namelist() if not name.endswith("/")}
        if names != expected_names:
            missing = len(expected_names - names)
            extra = len(names - expected_names)
            raise AssertionError(f"{split}: archive members differ (missing={missing}, extra={extra})")
        for index, token in enumerate(tokens, start=1):
            payload = bundle.read(f"masks/{token}.png")
            image = cv2.imdecode(np.frombuffer(payload, dtype=np.uint8), cv2.IMREAD_COLOR)
            if image is None or image.shape != (900, 1600, 3) or image.dtype.name != "uint8":
                raise AssertionError(f"bad PNG shape/dtype for {split}/{token}.png")
            if (image[:, :, 0] != 0).any() or (image[:, :, 1] != 0).any():
                raise AssertionError(f"nonzero blue/green channel for {split}/{token}.png")
            if not ((image[:, :, 2] == 0) | (image[:, :, 2] == 255)).all():
                raise AssertionError(f"non-binary red channel for {split}/{token}.png")
            if index % 500 == 0 or index == len(tokens):
                print(f"checked {split}: {index}/{len(tokens)}")
    return tokens


def validate_hashes(root: Path) -> None:
    rows = []
    for line in (root / "SHA256SUMS.txt").read_text(encoding="utf-8").splitlines():
        if line.strip():
            digest, relative = line.split("  ", 1)
            rows.append((digest, relative))
    for expected, relative in rows:
        path = root / relative
        if not path.is_file() or sha256_file(path) != expected:
            raise AssertionError(f"checksum mismatch or missing file: {relative}")
    print(f"checked SHA-256 entries: {len(rows)}")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path("."))
    args = parser.parse_args()
    root = args.root.resolve()
    train = validate_split(root, "training")
    val = validate_split(root, "validation")
    if set(train) & set(val):
        raise AssertionError("training/validation token overlap")
    validate_hashes(root)
    print("nuScenes-NRS archive release validation: PASS")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())