#!/usr/bin/env python3 """Create one event-centered visual audit sheet per scenario family.""" from __future__ import annotations import argparse import json from pathlib import Path import cv2 import numpy as np PROJECT_ROOT = Path(__file__).resolve().parents[2] DEFAULT_DATASET_ROOT = PROJECT_ROOT / "closed_dataset" DEFAULT_RUN_ROOT = DEFAULT_DATASET_ROOT / "acceptance_final_v1_runs" DEFAULT_OUTPUT = DEFAULT_DATASET_ROOT / "acceptance_final_v1/contact_sheets" PHYSICAL_COMPLETION_EVENTS = { "pedestrian_crossing_completed", "cut_in_completed", "obstacle_reveal_completed", "hazard_actor_cleared_route", "flow_actor_cleared", } def _json_lines(path: Path) -> list[dict]: return [ json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip() ] def _event_frame(run_dir: Path) -> int: timeline = _json_lines(run_dir / "event_timeline.jsonl") clock = _json_lines(run_dir / "logs/frame_clock.jsonl") start = next(item for item in timeline if item.get("event") == "hazard_started") completion = next( item for item in timeline if item.get("event") in PHYSICAL_COMPLETION_EVENTS ) target_game_time = ( float(start["game_time"]) + float(completion["game_time"]) ) / 2.0 sim_offset = float(clock[0]["sim_time"]) target_sim_time = sim_offset + target_game_time nearest = min(clock, key=lambda item: abs(float(item["sim_time"]) - target_sim_time)) return int(nearest["dataset_frame"]) def _read_video_frame(video: Path, frame_index: int) -> np.ndarray: capture = cv2.VideoCapture(str(video)) if not capture.isOpened(): raise RuntimeError(f"cannot open {video}") capture.set(cv2.CAP_PROP_POS_FRAMES, frame_index) ok, frame = capture.read() capture.release() if not ok: raise RuntimeError(f"cannot read frame {frame_index} from {video}") return frame def _tile(frame: np.ndarray, title: str, subtitle: str) -> np.ndarray: width, height = 384, 216 frame = cv2.resize(frame, (width, height), interpolation=cv2.INTER_AREA) canvas = np.zeros((height + 54, width, 3), dtype=np.uint8) canvas[54:] = frame cv2.putText( canvas, title, (8, 21), cv2.FONT_HERSHEY_SIMPLEX, 0.52, (255, 255, 255), 1, cv2.LINE_AA, ) cv2.putText( canvas, subtitle, (8, 44), cv2.FONT_HERSHEY_SIMPLEX, 0.43, (190, 220, 255), 1, cv2.LINE_AA, ) return canvas def build(dataset_root: Path, run_root: Path, output: Path) -> None: manifest = json.loads((dataset_root / "manifest.json").read_text(encoding="utf-8")) grouped: dict[str, list[dict]] = {} for route in manifest["routes"]: grouped.setdefault(route["family"], []).append(route) output.mkdir(parents=True, exist_ok=True) for family, routes in sorted(grouped.items()): tiles = [] for route in sorted(routes, key=lambda item: item["route_id"]): route_id = route["route_id"] matches = list(run_root.glob(f"*/{route_id}")) if len(matches) != 1: raise RuntimeError(f"expected one run directory for {route_id}") run_dir = matches[0] videos = list((run_dir / "videos").glob("*_pdm_lite_rgb.mp4")) if len(videos) != 1: raise RuntimeError(f"expected one RGB video for {route_id}") frame_index = _event_frame(run_dir) frame = _read_video_frame(videos[0], frame_index) subtitle = ( f"{route['town']} | {route['weather_profile'].replace('_', ' ')}" f" | event frame {frame_index}" ) tiles.append(_tile(frame, route_id, subtitle)) rows = [ np.concatenate(tiles[index : index + 5], axis=1) for index in range(0, len(tiles), 5) ] sheet = np.concatenate(rows, axis=0) path = output / f"{family}.jpg" if not cv2.imwrite(str(path), sheet, [cv2.IMWRITE_JPEG_QUALITY, 92]): raise RuntimeError(f"failed to write {path}") print(path) def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset-root", type=Path, default=DEFAULT_DATASET_ROOT) parser.add_argument("--run-root", type=Path, default=DEFAULT_RUN_ROOT) parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) args = parser.parse_args() build(args.dataset_root.resolve(), args.run_root.resolve(), args.output.resolve()) return 0 if __name__ == "__main__": raise SystemExit(main())