Spaces:
Running on T4
Running on T4
Download baseball_batting/api_worker.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/api_worker.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/baseball_batting/api_worker.py
-
curl -L -o api_worker.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/baseball_batting/api_worker.py
11.3 kB
| """GPU worker with optional sparse 3D and optional merged coach/POC review.""" | |
| import argparse | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| import yaml | |
| from .api_contract import AnalysisInput | |
| from .api_output import build_api_result | |
| from .config import CONFIG_ROOT, EngineConfig | |
| from .storage import StageCache, atomic_json, code_hash, digest, read_json, sha256_file | |
| def model_files(directory): | |
| registry = yaml.safe_load((CONFIG_ROOT / "resources.yaml").read_text())["resources"] | |
| paths, hashes = {}, {} | |
| for name in ("body_pose", "person_detector"): | |
| path = Path(directory) / name / "model.onnx" | |
| if not path.is_file() or sha256_file(path) != registry[name]["sha256"]: | |
| raise ValueError(f"Missing or incorrect {name} model; run setup_api_models") | |
| paths[name], hashes[name] = str(path), registry[name]["sha256"] | |
| return paths, hashes | |
| def gpu_preflight(models): | |
| from .body2d import RTMWPose | |
| from .detection import YOLOXDetector | |
| paths, _ = model_files(models) | |
| detector = YOLOXDetector(paths["person_detector"], "cuda", classes=[0]) | |
| detector(np.zeros((640, 640, 3), np.uint8)) | |
| pose = RTMWPose(paths["body_pose"], "cuda") | |
| pose(np.zeros((480, 640, 3), np.uint8), [0, 0, 640, 480]) | |
| tracking_ready = False | |
| if (Path(models)/'tracking_bat/model.json').is_file() and (Path(models)/'tracking_ball/model.json').is_file(): | |
| from .tracking_vision import TrackingModel | |
| for name in ('bat', 'ball'): | |
| TrackingModel(models, name, 'cuda')(np.zeros((640, 640, 3), np.uint8)) | |
| tracking_ready = True | |
| try: | |
| from ai_coach.config import Settings | |
| from ai_coach.video_review import provider_status | |
| visual_status = provider_status(Settings()) | |
| except ImportError: | |
| visual_status = {'status': 'coach_not_installed'} | |
| # Both adapters check that actual operators executed on CUDA. Optional | |
| # coaching availability never changes the measurement worker's readiness. | |
| return {"ready": True, "device": "cuda", "body_3d": False, 'bat_ball_tracking': tracking_ready, | |
| "scope": "required_2d_models; selected_3d_verified_during_job", | |
| "pose_providers": pose.session.get_providers(), "detector_providers": detector.providers, | |
| "visual_model_status": visual_status} | |
| def run_analysis(job, models, *, max_frames=7200, max_pixels=8294400, max_duration_s=120, | |
| device="cuda"): | |
| """device is an internal test seam; the public CLI and HTTP API always use CUDA.""" | |
| from .ingest import ingest | |
| from .observations import run_observations | |
| job = Path(job) | |
| options = AnalysisInput.model_validate(read_json(job / "request.json")) | |
| paths, hashes = model_files(models) | |
| started = time.monotonic() | |
| def progress(stage, completed=0, total=None): | |
| atomic_json(job / "progress.json", {"stage": stage, "completed_frames": completed, | |
| "total_frames": total, "stage_progress": completed / total if total else None, | |
| "elapsed_s": round(time.monotonic() - started, 2)}) | |
| video = next(job.glob("input.*")) | |
| capture_cache = StageCache(job, "ingest", digest({"input": sha256_file(video), | |
| "metadata": options.engine_metadata(), "code": code_hash(), | |
| "limits": [max_frames, max_pixels, max_duration_s]})) | |
| progress("decoding") | |
| if capture_cache.valid("capture"): | |
| capture = read_json(capture_cache.root / "capture.json") | |
| else: | |
| capture = ingest(video, options.engine_metadata(), max_frames=max_frames, | |
| max_pixels=max_pixels, max_duration_s=max_duration_s, | |
| progress=lambda done: progress("decoding", done)) | |
| atomic_json(capture_cache.root / "capture.json", capture) | |
| capture_cache.commit("capture", [capture_cache.root / "capture.json"]) | |
| n = capture["frame_count"] | |
| if any(rep.end_frame >= n for rep in options.reps): | |
| raise ValueError("Rep range exceeds decoded frame count") | |
| config = EngineConfig(device=device, body_pose_path=paths["body_pose"], | |
| person_detector_path=paths["person_detector"], object_detector_path=None, | |
| body3d_enabled=False, temporal3d_enabled=False, anatomy_enabled=False, | |
| learned_events_enabled=False, bat_3d_mode="disabled", export_video=False, | |
| coaching_mode="descriptive_only") | |
| cache = StageCache(job, "observations", digest({"capture": capture_cache.key, | |
| "models": hashes, "config": config.to_dict(), "code": code_hash()})) | |
| progress("pose_2d", 0, n) | |
| observations = run_observations(video, capture, config, cache, | |
| progress=lambda done, total: progress("pose_2d", done, total)) | |
| if any(observations["branch_status"].get(name, {}).get("status") != "ready" | |
| for name in ("body_pose", "person_detector")): | |
| raise RuntimeError("GPU pose or person inference failed") | |
| # A successfully executed model with no athlete is a capture failure for the | |
| # coach, not a worker crash. Preserve the record-again payload. | |
| progress("measurements_2d", n, n) | |
| result = build_api_result(capture, observations, options, hashes) | |
| from .event_body3d import reconstruct_events | |
| from .measurement_quality import apply_measurement_quality | |
| report = reconstruct_events(video, result, options, models, job, device=device, progress=progress) | |
| result = apply_measurement_quality(result, options, report) | |
| evidence = {} | |
| if (Path(models)/'tracking_bat/model.json').is_file() and (Path(models)/'tracking_ball/model.json').is_file(): | |
| from .tracking_vision import track_video | |
| from .bat_ball_timing import visual_contact | |
| observed = track_video(video, result, models, device=device, progress=progress) | |
| atomic_json(job/'bat-ball-observations.json', observed) | |
| secondary = None | |
| if options.stereo_tracking: | |
| secondary_video = next(job.glob('secondary.*'), None) | |
| if secondary_video is None: | |
| raise ValueError('Two-view calibration requires a secondary video') | |
| stereo = options.stereo_tracking | |
| metadata = {'timing': stereo.secondary_timing.model_dump(exclude_none=True), | |
| 'camera_stability': 'fixed_verified', 'intended_use': 'research'} | |
| if stereo.secondary_rotation_degrees is not None: | |
| metadata['rotation_degrees'] = stereo.secondary_rotation_degrees | |
| second_capture = ingest(secondary_video, metadata, max_frames=max_frames, | |
| max_pixels=max_pixels, max_duration_s=max_duration_s) | |
| count = second_capture['frame_count'] | |
| second_result = {'pose_track': {'video': { | |
| 'rotation_degrees_applied': second_capture['rotation_degrees'], 'frame_count': count}, | |
| 'frames': {'t_s': [f['physical_s'] for f in second_capture['frames']], 'box': [None]*count}, | |
| 'reps': [{'start_frame': 0, 'end_frame': count-1}]}} | |
| secondary = track_video(secondary_video, second_result, models, device=device, progress=progress) | |
| atomic_json(job/'secondary-bat-ball-observations.json', secondary) | |
| for rep in result['pose_track']['reps']: | |
| visual = (visual_contact(observed, result['pose_track'], rep, practice_type=options.practice_type) | |
| if options.camera_stability == 'fixed_verified' else | |
| {'outcome': 'unknown', 'reason_code': 'camera_motion_unresolved'}) | |
| if secondary is not None: | |
| from .tracking_geometry import reconstruct_rep | |
| spatial = (reconstruct_rep(observed, secondary, result['pose_track'], rep, options.stereo_tracking) | |
| if options.camera_stability == 'fixed_verified' else | |
| {'outcome': 'unknown', 'reason_code': 'camera_motion_unresolved'}) | |
| if options.practice_type == 'tee' and spatial.get('outcome') == 'miss': | |
| spatial['shift'] = {'value': None, 'reason_code': 'stationary_tee_ball_no_pitch_timing'} | |
| if spatial.get('outcome') == 'miss' and visual.get('outcome') != 'hit': | |
| visual = spatial | |
| elif spatial.get('outcome') == 'miss' and visual.get('outcome') == 'hit': | |
| visual = {'outcome': 'unknown', 'reason_code': 'visual_spatial_outcome_conflict'} | |
| else: | |
| visual['geometry_reason'] = spatial.get('reason_code') | |
| else: | |
| visual['geometry_reason'] = 'depth_unresolved' | |
| evidence[rep['rep']] = visual | |
| else: | |
| evidence = {r['rep']: {'outcome': 'unknown', 'reason_code': 'tracking_models_unavailable', | |
| 'geometry_reason': 'depth_unresolved'} for r in result['pose_track']['reps']} | |
| from .load_timing import build_load_timing_report | |
| from .load_timing_contract import LoadTimingPayload | |
| timing = build_load_timing_report(result, ball_evidence=evidence) | |
| timing_payload = LoadTimingPayload.model_validate(timing["payload"]).model_dump(mode="json") | |
| atomic_json(job / "load-timing.json", timing_payload) | |
| atomic_json(job / "load-timing-diagnostics.json", timing) | |
| from .timing_evidence import build_timing_evidence | |
| rich_timing = build_timing_evidence(timing, result, options) | |
| atomic_json(job/'load-timing-evidence.json', rich_timing) | |
| atomic_json(job / "coach-payload.json", result["coach_payload"]) | |
| atomic_json(job / "result.json", result) | |
| progress("swing_clips", 0, n) | |
| from .swing_clips import export_swing_clips | |
| export_swing_clips(video, capture, result["pose_track"], job, progress=progress, result=result) | |
| if options.coaching_mode != "disabled": | |
| progress("coaching", n, n) | |
| from .product import build_product | |
| build_product(job, video, result, rich_timing, options) | |
| progress("complete", n, n) | |
| return result | |
| def main(): | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--models", required=True) | |
| parser.add_argument("--preflight", action="store_true") | |
| parser.add_argument("--output") | |
| parser.add_argument("--job") | |
| parser.add_argument("--max-frames", type=int, default=7200) | |
| parser.add_argument("--max-pixels", type=int, default=8294400) | |
| parser.add_argument("--max-duration", type=float, default=120) | |
| args = parser.parse_args() | |
| try: | |
| if args.preflight: | |
| atomic_json(args.output, gpu_preflight(args.models)) | |
| else: | |
| run_analysis(args.job, args.models, max_frames=args.max_frames, | |
| max_pixels=args.max_pixels, max_duration_s=args.max_duration) | |
| except Exception as error: | |
| # Logs stay server-side; the public error never includes paths or a traceback. | |
| print(f"{type(error).__name__}: {error}", flush=True) | |
| if args.job: | |
| atomic_json(Path(args.job) / "error.json", {"code": "invalid_video_or_capture" if isinstance(error, ValueError) | |
| else "inference_failed", "message": "Analysis could not finish. Check the recording, capture metadata and server logs."}) | |
| return 1 | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |