File size: 11,295 Bytes
35e80ff
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e21e264
 
 
 
 
 
35e80ff
 
 
 
 
 
 
 
e21e264
3192171
35e80ff
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3192171
 
 
 
e21e264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1558b6d
 
e21e264
1558b6d
 
 
e21e264
35e80ff
 
326d3cc
 
4800905
 
cc21255
35e80ff
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""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())