Spaces:
Running on T4
Running on T4
Download tools/preview_swing_ranges.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 8.01 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/preview_swing_ranges.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tools/preview_swing_ranges.py
-
curl -L -o preview_swing_ranges.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tools/preview_swing_ranges.py
8.01 kB
| """Make inspection clips from API swing ranges; never changes measurements.""" | |
| import argparse | |
| from fractions import Fraction | |
| import math | |
| from pathlib import Path | |
| import os | |
| from baseball_batting.ingest import iter_frames | |
| from baseball_batting.preview_overlay import draw_points | |
| from baseball_batting.storage import atomic_json, read_json, sha256_file | |
| def export_previews(video, result, destination, max_clips=10, overlay=True): | |
| import av | |
| import cv2 | |
| if not 0 <= max_clips <= 100: | |
| raise ValueError("max_clips must be between 0 and 100") | |
| destination = Path(destination) | |
| destination.mkdir(parents=True, exist_ok=True) | |
| track = result["pose_track"] | |
| frames, info = track["frames"], track["video"] | |
| model_rows = {r["frame"]: r for r in result.get("experimental_body3d", {}).get("frames", [])} | |
| image_stature = result.get("measurement_method", {}).get("body_height_px") | |
| comparisons = [] | |
| selected, records = [], [] | |
| prior_end = -1 | |
| for rep in track["reps"][:max_clips]: | |
| start, end = rep["start_frame"], rep["end_frame"] | |
| if not 0 <= start <= end < info["frame_count"] or start <= prior_end: | |
| raise ValueError("Swing ranges must be ordered, disjoint and inside the video") | |
| prior_end = end | |
| record = {"rep": rep["rep"], "start_frame": start, "end_frame": end, | |
| "frame_count": end-start+1, "status": "unavailable"} | |
| records.append(record) | |
| times = frames["playback_t_s"][start:end+1] | |
| if (len(times) != end-start+1 or any(t is None or not math.isfinite(t) for t in times) | |
| or any(b <= a for a, b in zip(times, times[1:]))): | |
| record["reason"] = "Source playback timestamps are missing or nonmonotonic; no retimed preview fabricated." | |
| continue | |
| selected.append((rep, record, times)) | |
| if selected: | |
| decoded = iter_frames(video, info["rotation_degrees_applied"], max_pixels=8294400) | |
| try: | |
| current = None | |
| for rep, record, times in selected: | |
| start, end = rep["start_frame"], rep["end_frame"] | |
| target = destination / f"swing-{rep['rep']:03d}.mp4" | |
| temporary = target.with_suffix(".tmp.mp4") | |
| try: | |
| with av.open(str(temporary), "w", options={"movflags": "+faststart"}) as out: | |
| stream = None | |
| for wanted in range(start, end+1): | |
| while current is None or current[0] < wanted: | |
| current = next(decoded) | |
| index, pts, base, image = current | |
| if index != wanted or image.shape[:2] != (info["height"], info["width"]): | |
| raise ValueError("Source frames do not match the analysis") | |
| # Read the actual PTS too; a preview of another source | |
| # must not be labeled with this result's frame ranges. | |
| if pts is None or abs(float(pts*base)-times[index-start]) > float(base)+1e-6: | |
| raise ValueError("Source playback timestamps differ from the analysis") | |
| if overlay: | |
| feet = frames["kp_extra"][index] if "kp_extra" in frames else None | |
| projection = model_rows.get(index, {}).get("projection") | |
| image = draw_points(image, frames["kp"][index], rep["rep"], index, rep["events"], | |
| feet, projection, image_stature) | |
| names = [name for name in ("contact", "foot_plant") | |
| if rep["events"].get(name, {}).get("frame") == index] | |
| if projection is not None and names: | |
| file = f"swing-{rep['rep']:03d}-frame-{index:06d}-comparison.png" | |
| png = cv2.resize(image, (int(info["width"]*min(1., 1280/info["width"])), | |
| int(info["height"]*min(1., 1280/info["width"])))) | |
| if not cv2.imwrite(str(destination/file), png): | |
| raise OSError("Could not save model comparison") | |
| comparisons.append({"rep": rep["rep"], "frame": index, "events": names, "file": file, | |
| "sha256": sha256_file(destination/file)}) | |
| scale = min(1., 960/info["width"]) | |
| width = max(2, 2*int(info["width"]*scale/2)) | |
| height = max(2, 2*int(info["height"]*scale/2)) | |
| if (width, height) != (info["width"], info["height"]): | |
| image = cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA) | |
| if stream is None: | |
| rate = Fraction(info.get("playback_fps") or 30).limit_denominator(100000) | |
| stream = out.add_stream("libx264", rate=rate) | |
| stream.width, stream.height, stream.pix_fmt = width, height, "yuv420p" | |
| stream.time_base = stream.codec_context.time_base = base | |
| stream.options = {"crf": "23", "preset": "fast", "bf": "0"} | |
| frame = av.VideoFrame.from_ndarray(image, format="bgr24") | |
| frame.time_base = base | |
| frame.pts = round((times[index-start]-times[0])/float(base)) | |
| for packet in stream.encode(frame): out.mux(packet) | |
| for packet in stream.encode(): out.mux(packet) | |
| exported = [(pts, base) for _, pts, base, _ in iter_frames(temporary)] | |
| if len(exported) != len(times): | |
| raise ValueError("Preview changed the frame count") | |
| for source_time, (pts, base) in zip(times, exported): | |
| if pts is None or abs(float(pts*base)-(source_time-times[0])) > float(base)+1e-6: | |
| raise ValueError("Preview changed playback presentation positions") | |
| os.replace(temporary, target) | |
| record.update(status="complete", file=target.name, sha256=sha256_file(target), | |
| timing="source_playback_positions_relative_to_clip_start", | |
| width=width, height=height, audio="not_included", overlay=overlay) | |
| except Exception as error: | |
| temporary.unlink(missing_ok=True) | |
| record["reason"] = f"{type(error).__name__}: {str(error)[:300]}" | |
| finally: | |
| decoded.close() | |
| manifest = {"swing_candidates_total": len(track["reps"]), "preview_limit": max_clips, | |
| "purpose": "Visual inspection only; candidate ranges and events are unvalidated estimates.", | |
| "previews": records, "model_comparisons": comparisons} | |
| 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("--output", required=True) | |
| parser.add_argument("--max-clips", type=int, default=10) | |
| args = parser.parse_args() | |
| manifest = export_previews(args.video, read_json(args.result), args.output, args.max_clips) | |
| for record in manifest["previews"]: | |
| print(f"Swing {record['rep']}: {record['status']} | {record.get('file', record.get('reason'))}") | |
| if not manifest["swing_candidates_total"]: | |
| print("No detected swing ranges to preview.") | |
| if __name__ == "__main__": | |
| main() | |