nuScenes-NRS / scripts /build_release_metadata.py
PeterNano's picture
Release nuScenes-NRS v1.0.0 archive package
40bbfa3 verified
Raw
History Blame Contribute Delete
5.82 kB
#!/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())