#!/usr/bin/env python3 """Audit the actual causal frame selection used by the restarted intent run.""" from __future__ import annotations import argparse import bisect import csv import json from pathlib import Path import numpy as np def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--dataset-root", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() root = args.dataset_root windows = [json.loads(line) for line in (root / "metadata/windows.jsonl").read_text().splitlines()] stamps: dict[tuple[str, str], tuple[list[float], list[int]]] = {} ages: dict[str, list[float]] = {role: [] for role in ("top", "front", "wrist")} spans, kept, skipped = [], [], [] for window in windows: candidates = [] for role in ages: key = window["episode_id"], role if key not in stamps: with (root / "episodes" / key[0] / f"{role}_timestamps.csv").open(newline="") as stream: records = list(csv.DictReader(stream)) stamps[key] = ([float(record["time_sec"]) for record in records], [int(record["video_frame_index"]) for record in records]) times, indices = stamps[key] for target in window["top_sample_times_sec"] if role == "wrist" else window[f"{role}_sample_times_sec"]: index = bisect.bisect_right(times, target) - 1 if index < 0 or target - times[index] > 0.1: candidates = [] break candidates.append((role, target, times[index], indices[index])) if not candidates: break if not candidates: skipped.append(window["sample_id"]) continue kept.append(window["sample_id"]) for role, target, selected, _ in candidates: ages[role].append((target - selected) * 1000) for position in range(len(window["top_sample_times_sec"])): selected = [item[2] for item in candidates if item[0] == "top"][position], \ [item[2] for item in candidates if item[0] == "front"][position], \ [item[2] for item in candidates if item[0] == "wrist"][position] spans.append((max(selected) - min(selected)) * 1000) def summary(values: list[float]) -> dict: array = np.asarray(values) return {"count": len(values), "min_ms": float(array.min()), "median_ms": float(np.median(array)), "p95_ms": float(np.percentile(array, 95)), "max_ms": float(array.max())} report = {"causal": True, "windows_kept": len(kept), "windows_skipped": skipped, "frame_age": {role: summary(values) for role, values in ages.items()}, "cross_view_timestamp_span": summary(spans), "future_frame_count": sum(age < 0 for values in ages.values() for age in values)} args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2) + "\n") print(json.dumps(report, indent=2)) if __name__ == "__main__": main()