File size: 5,820 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
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#!/usr/bin/env python3
"""Build split lists and a compact manifest for a nuScenes-NRS release.

This maintainer utility reads only the derived mask directories and (optionally)
the official sample/scene metadata. It never copies or publishes raw nuScenes
files. The generated files are deterministic when the mask directories and
metadata are unchanged.
"""

from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path


EXPECTED = {"training": 3182, "validation": 805}


def load_json(path: Path):
    with path.open("r", encoding="utf-8") as handle:
        return json.load(handle)


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 main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--release-root", type=Path, required=True)
    parser.add_argument(
        "--metadata-dir",
        type=Path,
        default=None,
        help="Optional v1.0-trainval directory containing sample.json and scene.json",
    )
    args = parser.parse_args()
    root = args.release_root.resolve()
    split_dir = root / "splits"
    split_dir.mkdir(parents=True, exist_ok=True)

    samples = {}
    scenes = {}
    if args.metadata_dir:
        samples = {row["token"]: row for row in load_json(args.metadata_dir / "sample.json")}
        scenes = {row["token"]: row for row in load_json(args.metadata_dir / "scene.json")}

    manifest = {
        "dataset": "nuScenes-NRS",
        "release_version": "1.0.0",
        "source": {
            "dataset": "nuScenes v1.0-trainval plus the matching lidarseg release",
            "raw_data_redistributed": False,
            "camera": "CAM_FRONT",
            "lidar": "LIDAR_TOP",
        },
        "mask": {
            "format": "PNG",
            "dtype": "uint8",
            "channels": 3,
            "resolution": [1600, 900],
            "encoding_rgb": {"road": [255, 0, 0], "background": [0, 0, 0]},
            "filename": "<sample-token>.png",
        },
        "generation": {
            "lidarseg_class": 24,
            "lidarseg_class_name": "drivable_surface",
            "projection": "LiDAR_TOP -> ego -> global -> camera ego -> CAM_FRONT",
            "delaunay_max_edge_px": 40.0,
            "closing_kernel": [15, 15],
            "closing_iterations": 2,
            "douglas_peucker_factor": 0.01,
            "minimum_contour_area_px": 1000,
            "erosion_kernel": [5, 5],
            "erosion_iterations": 1,
        },
        "splits": {},
    }

    all_tokens = {}
    for split, expected in EXPECTED.items():
        mask_dir = root / split / "masks"
        files = sorted(mask_dir.glob("*.png"))
        tokens = [path.stem for path in files]
        if len(files) != expected:
            raise SystemExit(f"{split}: expected {expected} masks, found {len(files)}")
        if len(set(tokens)) != len(tokens):
            raise SystemExit(f"{split}: duplicate mask tokens")
        if any(len(token) != 32 for token in tokens):
            bad = next(token for token in tokens if len(token) != 32)
            raise SystemExit(f"{split}: non-token filename stem {bad!r}")
        split_file = split_dir / f"{split}.txt"
        split_file.write_text("".join(f"{token}\n" for token in tokens), encoding="utf-8")
        scene_tokens = set()
        scene_names = set()
        if samples:
            missing = [token for token in tokens if token not in samples]
            if missing:
                raise SystemExit(f"{split}: {len(missing)} tokens absent from sample.json")
            scene_tokens = {samples[token]["scene_token"] for token in tokens}
            scene_names = {scenes[token]["name"] for token in scene_tokens if token in scenes}
        manifest["splits"][split] = {
            "mask_count": len(files),
            "scene_count": len(scene_tokens) if samples else None,
            "scene_tokens_sha256": hashlib.sha256(
                "\n".join(sorted(scene_tokens)).encode("utf-8")
            ).hexdigest()
            if samples
            else None,
            "scene_names": sorted(scene_names) if samples else None,
            "token_list": f"splits/{split}.txt",
            "mask_directory": f"{split}/masks",
            "token_list_sha256": sha256_file(split_file),
        }
        for token in tokens:
            all_tokens.setdefault(token, []).append(split)

    overlap = sorted(token for token, splits in all_tokens.items() if len(splits) > 1)
    if overlap:
        raise SystemExit(f"training/validation overlap: {len(overlap)} tokens")
    if samples:
        train_scenes = {
            samples[token]["scene_token"]
            for token, splits in all_tokens.items()
            if splits == ["training"]
        }
        val_scenes = {
            samples[token]["scene_token"]
            for token, splits in all_tokens.items()
            if splits == ["validation"]
        }
        if train_scenes & val_scenes:
            raise SystemExit("training/validation scene overlap detected")
        manifest["split_policy"] = {
            "scene_disjoint": True,
            "training_scene_count": len(train_scenes),
            "validation_scene_count": len(val_scenes),
        }
    else:
        manifest["split_policy"] = {"scene_disjoint": None}

    manifest_path = root / "dataset_manifest.json"
    manifest_path.write_text(
        json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps({"release_root": str(root), "manifest": str(manifest_path), "masks": len(all_tokens)}, indent=2))
    return 0


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