File size: 4,849 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/usr/bin/env python3
"""Validate the public nuScenes-NRS release without requiring raw nuScenes data."""

from __future__ import annotations

import argparse
import hashlib
import json
import re
from pathlib import Path

import cv2


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


def validate_split(root: Path, split: str) -> list[str]:
    tokens = split_tokens(root / "splits" / f"{split}.txt")
    if len(tokens) != EXPECTED[split]:
        raise AssertionError(f"{split}: expected {EXPECTED[split]} tokens, found {len(tokens)}")
    files = sorted((root / split / "masks").glob("*.png"))
    names = sorted(path.stem for path in files)
    if names != sorted(tokens):
        raise AssertionError(f"{split}: token list and mask filenames differ")
    for index, path in enumerate(files, start=1):
        image = cv2.imread(str(path), cv2.IMREAD_COLOR)
        if image is None:
            raise AssertionError(f"cannot read {path}")
        if image.shape != (900, 1600, 3) or image.dtype.name != "uint8":
            raise AssertionError(f"bad shape/dtype in {path}: {image.shape}, {image.dtype}")
        # PNG is read as BGR: road must be pure red and all other channels zero.
        if (image[:, :, 0] != 0).any() or (image[:, :, 1] != 0).any():
            raise AssertionError(f"nonzero blue/green channel in {path}")
        if not ((image[:, :, 2] == 0) | (image[:, :, 2] == 255)).all():
            raise AssertionError(f"red channel is not binary in {path}")
        if index % 500 == 0 or index == len(files):
            print(f"checked {split}: {index}/{len(files)}")
    return tokens


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


def validate_scene_disjointness(root: Path, metadata_dir: Path | None) -> None:
    if metadata_dir is None:
        print("scene disjointness: skipped (no official metadata supplied)")
        return
    samples_path = metadata_dir / "sample.json"
    scenes_path = metadata_dir / "scene.json"
    samples = {row["token"]: row for row in json.loads(samples_path.read_text(encoding="utf-8"))}
    scenes = {row["token"]: row for row in json.loads(scenes_path.read_text(encoding="utf-8"))}
    train = {samples[token]["scene_token"] for token in split_tokens(root / "splits/training.txt")}
    val = {samples[token]["scene_token"] for token in split_tokens(root / "splits/validation.txt")}
    if train & val:
        raise AssertionError("training/validation scene overlap")
    unknown = (train | val) - scenes.keys()
    if unknown:
        raise AssertionError(f"unknown scene tokens: {len(unknown)}")
    print(f"scene disjointness: PASS ({len(train)} training, {len(val)} validation scenes)")


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--root", type=Path, default=Path("."))
    parser.add_argument(
        "--metadata-dir",
        type=Path,
        default=None,
        help="Optional official v1.0-trainval metadata directory for scene checks",
    )
    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_scene_disjointness(root, args.metadata_dir.resolve() if args.metadata_dir else None)
    validate_hashes(root)
    print("nuScenes-NRS release validation: PASS")
    return 0


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