"""Open a US Urban Driving Events clip and line its motion data up with the video frames.
Tested 2026-11-26 with Python 3.12.14, numpy 2.5.4 and opencv-python 5.1.0 on the published files.

Every telemetry sample's "t" is seconds from the clip start (see "time_origin" in the JSON), on the same clock as the video,
so a sample's frame is round(t * fps). The per-clip measured video-to-sensor clock offset is in metadata.csv
(video_sensor_offset_s; across the dataset: median 0.05 s, 95th percentile 0.33 s): read it as the timing uncertainty.
Usage: python 02_event_clip_with_telemetry.py ./us-urban-driving-events [clip_uid]
"""
import csv, json, sys
import cv2

root = sys.argv[1] if len(sys.argv) > 1 else "./us-urban-driving-events"
rows = list(csv.DictReader(open(f"{root}/data/train/metadata.csv", newline="")))
print(len(rows), "clips in metadata.csv")
uid = sys.argv[2] if len(sys.argv) > 2 else "rd_3f22a1f07655"
row = next(r for r in rows if r["clip_uid"] == uid)
print(f"{uid}: {row['label_display']} | {row['region']} | {row['time_of_day']}, {row['weather']} | {row['width']}x{row['height']} "
      f"{row['codec']} {row['fps']} fps, {row['duration_s']} s | measured video-sensor offset {row['video_sensor_offset_s']} s")

tel = json.load(open(f"{root}/telemetry/{uid}.json"))
cap = cv2.VideoCapture(f"{root}/data/train/{row['file_name']}")
fps = cap.get(cv2.CAP_PROP_FPS); n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
print(f"video: {n} frames at {fps:.2f} fps")
for kind in ("gyro", "accel", "gps_motion"):
    print(f"{kind}: {len(tel[kind])} samples")

# the sharpest turn in the clip: largest gyro magnitude, and the video frame it falls on
g = max(tel["gyro"], key=lambda s: (s["x"] ** 2 + s["y"] ** 2 + s["z"] ** 2) ** 0.5)
frame = min(n - 1, round(g["t"] * fps))
print(f"largest rotation at t = {g['t']:.3f} s -> frame {frame} ({g['unit']}: x {g['x']}, y {g['y']}, z {g['z']})")
cap.set(cv2.CAP_PROP_POS_FRAMES, frame); ok, img = cap.read()
if ok:
    cv2.imwrite(f"{uid}_frame_{frame}.jpg", img); print("saved", f"{uid}_frame_{frame}.jpg")
for s in tel["gps_motion"]:
    print(f"  t {s['t']:6.3f} s  frame {min(n - 1, round(s['t'] * fps)):4d}  speed {s['speed_mph']} mph  heading {s['heading_deg']} deg")
