"""Timing-only previews and neighboring event frames, using the original PTS.""" import argparse from copy import deepcopy from pathlib import Path from baseball_batting.ingest import iter_frames from baseball_batting.storage import atomic_json, read_json, sha256_file from tools.preview_swing_ranges import export_previews def export_timing_review(video, result, report, destination, max_clips=10): import cv2 import numpy as np destination = Path(destination) destination.mkdir(parents=True, exist_ok=True) filtered = deepcopy(result) track = filtered["pose_track"] diagnostics = {row["rep"]: row for row in report["diagnostics"]} for rep in track["reps"]: row = diagnostics[rep["rep"]] rep["events"] = deepcopy(row["events"]) # 3D is neither needed nor rendered by this timing test. filtered.pop("experimental_body3d", None) manifest = export_previews(video, filtered, destination, max_clips=max_clips) selections, needed = [], set() for rep in track["reps"][:max_clips]: for name, event in rep["events"].items(): center = event["frame"] frames = list(range(max(rep["start_frame"], center-2), min(rep["end_frame"], center+2)+1)) selections.append((rep, name, center, frames)) needed.update(frames) snapshots = {} if needed: info = track["video"] decoded = iter_frames(video, info["rotation_degrees_applied"], max_pixels=8294400) try: for index, pts, base, image in decoded: if index > max(needed): break if index not in needed: continue expected = track["frames"]["playback_t_s"][index] if (pts is None or expected is None or (image.shape[1], image.shape[0]) != (info["width"], info["height"]) or abs(float(pts*base)-expected) > float(base)+1e-6): raise ValueError("Event frames do not match the original video timestamps and size.") scale = min(1., 256/image.shape[1], 320/image.shape[0]) snapshots[index] = cv2.resize(image, (max(1, round(image.shape[1]*scale)), max(1, round(image.shape[0]*scale)))) finally: decoded.close() if needed-set(snapshots): raise ValueError("Source video is missing expected event frames.") records = [] for rep, name, center, frames in selections: tiles = [] for index in frames: image = snapshots[index] canvas = np.full((380, 280, 3), 20, np.uint8) x, y = (280-image.shape[1])//2, 42 canvas[y:y+image.shape[0], x:x+image.shape[1]] = image color = (0, 230, 255) if index == center else (255, 255, 255) cv2.putText(canvas, f"frame {index}" + (" (event)" if index == center else ""), (8, 24), cv2.FONT_HERSHEY_SIMPLEX, .5, color, 1, cv2.LINE_AA) real = track["frames"]["t_s"][index] stamp = f"capture {real:.4f}s" if real is not None else "capture time unknown" cv2.putText(canvas, stamp, (8, 366), cv2.FONT_HERSHEY_SIMPLEX, .43, color, 1, cv2.LINE_AA) tiles.append(canvas) image = np.concatenate(tiles, axis=1) filename = f"swing-{rep['rep']:03d}-{name}-frames.png" if not cv2.imwrite(str(destination/filename), image): raise OSError("Could not write event frame review.") records.append({"rep": rep["rep"], "event": name, "frame": center, "neighbor_frames": frames, "file": filename, "sha256": sha256_file(destination/filename)}) manifest["event_snapshots"] = records manifest["purpose"] = "Load/timing event inspection; body_extension_proxy is not ball contact." atomic_json(destination/"previews.json", manifest) return manifest def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--video", required=True) parser.add_argument("--result", required=True) parser.add_argument("--report", required=True) parser.add_argument("--output", required=True) parser.add_argument("--max-clips", type=int, default=10) args = parser.parse_args() manifest = export_timing_review(args.video, read_json(args.result), read_json(args.report), args.output, args.max_clips) print(f"Saved {len(manifest['previews'])} preview records and {len(manifest['event_snapshots'])} event frame sequences.") if __name__ == "__main__": main()