Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
9ec8d34
1
Parent(s): 393a41f
Automated Deploy: 83dd0e037548607e097653f87bce7ef9d342efc6
Browse files- backend/app/modules/sessions/schemas.py +1 -1
- backend/app/modules/sessions/service.py +1 -1
- backend/docs/FRONTEND_INTEGRATION.md +2 -2
- backend/docs/openapi.json +11 -4
- backend/tests/integration/test_sessions.py +19 -0
- baseball_batting/automatic_pitcher_direction.py +3 -1
- baseball_batting/body_pitcher_direction.py +248 -0
- baseball_batting/motion_api.py +4 -2
- baseball_batting/motion_export.py +10 -5
- baseball_batting/sam_measurements.py +2 -1
- docs/APP_API_INTEGRATION.md +8 -5
- docs/MOTION_PLAYER_API.md +11 -6
- docs/PITCHER_FLOOR_DIRECTION.md +44 -42
- tests/test_automatic_pitcher_direction.py +8 -15
- tests/test_body_pitcher_direction.py +215 -0
- tests/test_motion_player_api.py +5 -1
backend/app/modules/sessions/schemas.py
CHANGED
|
@@ -35,7 +35,7 @@ class MarksIn(RequestModel):
|
|
| 35 |
contact_source: Literal["detected", "suggested", "manual"]
|
| 36 |
stride_start_frame: int = Field(ge=0)
|
| 37 |
stride_end_frame: int = Field(ge=0)
|
| 38 |
-
pitcher_direction: PitcherDirection
|
| 39 |
|
| 40 |
|
| 41 |
class SessionIn(RequestModel):
|
|
|
|
| 35 |
contact_source: Literal["detected", "suggested", "manual"]
|
| 36 |
stride_start_frame: int = Field(ge=0)
|
| 37 |
stride_end_frame: int = Field(ge=0)
|
| 38 |
+
pitcher_direction: PitcherDirection | None = None
|
| 39 |
|
| 40 |
|
| 41 |
class SessionIn(RequestModel):
|
backend/app/modules/sessions/service.py
CHANGED
|
@@ -44,7 +44,7 @@ def validate_marks(body: SessionIn) -> None:
|
|
| 44 |
if marks.stride_end_frame >= marks.contact_frame:
|
| 45 |
errors.setdefault("marks.contact_frame", "Must be after stride_end_frame.")
|
| 46 |
direction = marks.pitcher_direction
|
| 47 |
-
if math.dist(direction.from_, direction.to) < MIN_DIRECTION_LENGTH:
|
| 48 |
errors["marks.pitcher_direction"] = "The arrow must be at least 8% of the frame long."
|
| 49 |
if body.is_self and body.athlete is not None:
|
| 50 |
errors["athlete"] = "Must be null for your own rep."
|
|
|
|
| 44 |
if marks.stride_end_frame >= marks.contact_frame:
|
| 45 |
errors.setdefault("marks.contact_frame", "Must be after stride_end_frame.")
|
| 46 |
direction = marks.pitcher_direction
|
| 47 |
+
if direction is not None and math.dist(direction.from_, direction.to) < MIN_DIRECTION_LENGTH:
|
| 48 |
errors["marks.pitcher_direction"] = "The arrow must be at least 8% of the frame long."
|
| 49 |
if body.is_self and body.athlete is not None:
|
| 50 |
errors["athlete"] = "Must be null for your own rep."
|
backend/docs/FRONTEND_INTEGRATION.md
CHANGED
|
@@ -151,7 +151,7 @@ The app calls the ML API itself. Our backend never calls the ML API: the app for
|
|
| 151 |
- **Uploaded files must match their type.** A JPEG sent as a video is rejected at step 3 with 422 `UPLOAD_INVALID`. If step 3 says `UPLOAD_MISSING`, the PUT never finished: retry the upload.
|
| 152 |
- **Marks:**
|
| 153 |
- `stride_start_frame < stride_end_frame < contact_frame`, all within `0 .. round(duration_sec*fps)-1`.
|
| 154 |
-
- `pitcher_direction` points
|
| 155 |
- Pitching labels map like this: leg lift is `stride_start_frame`, foot strike is `stride_end_frame`.
|
| 156 |
- **Athlete:**
|
| 157 |
- For `is_self: true`, send `athlete: null`; the server snapshots the profile.
|
|
@@ -255,7 +255,7 @@ Use it for drill names and the review drill picker. `mode=p` returns pitching dr
|
|
| 255 |
| Roster `joinedAt` | Not provided | Join time is not stored; show `email` when `name` is empty |
|
| 256 |
| D5 deletes after a lifecycle period | D5 deletes the media immediately | Privacy |
|
| 257 |
| `level` "High school" and similar labels | `high_school` and similar enum values | Map in the adapter |
|
| 258 |
-
| `pitcherDir` | `marks.pitcher_direction {from, to}` | |
|
| 259 |
| `contactSec`, `strideStartSec`, etc. | Not stored | Compute them as `frame / fps` |
|
| 260 |
|
| 261 |
## 13. Checklist per milestone
|
|
|
|
| 151 |
- **Uploaded files must match their type.** A JPEG sent as a video is rejected at step 3 with 422 `UPLOAD_INVALID`. If step 3 says `UPLOAD_MISSING`, the PUT never finished: retry the upload.
|
| 152 |
- **Marks:**
|
| 153 |
- `stride_start_frame < stride_end_frame < contact_frame`, all within `0 .. round(duration_sec*fps)-1`.
|
| 154 |
+
- `pitcher_direction` is optional: omit it or send `null` when no manual direction is available. The session returns it as `null`. When supplied, its points must be fractions of the frame, from 0 to 1, and at least 0.08 apart. This stored annotation does not trigger engine analysis; the motion engine attempts automatic direction estimation independently.
|
| 155 |
- Pitching labels map like this: leg lift is `stride_start_frame`, foot strike is `stride_end_frame`.
|
| 156 |
- **Athlete:**
|
| 157 |
- For `is_self: true`, send `athlete: null`; the server snapshots the profile.
|
|
|
|
| 255 |
| Roster `joinedAt` | Not provided | Join time is not stored; show `email` when `name` is empty |
|
| 256 |
| D5 deletes after a lifecycle period | D5 deletes the media immediately | Privacy |
|
| 257 |
| `level` "High school" and similar labels | `high_school` and similar enum values | Map in the adapter |
|
| 258 |
+
| `pitcherDir` | `marks.pitcher_direction {from, to}` | Optional; omit or send `null` for automatic engine direction estimation. |
|
| 259 |
| `contactSec`, `strideStartSec`, etc. | Not stored | Compute them as `frame / fps` |
|
| 260 |
|
| 261 |
## 13. Checklist per milestone
|
backend/docs/openapi.json
CHANGED
|
@@ -3487,7 +3487,15 @@
|
|
| 3487 |
"title": "Stride End Frame"
|
| 3488 |
},
|
| 3489 |
"pitcher_direction": {
|
| 3490 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3491 |
}
|
| 3492 |
},
|
| 3493 |
"additionalProperties": false,
|
|
@@ -3497,8 +3505,7 @@
|
|
| 3497 |
"contact_offset",
|
| 3498 |
"contact_source",
|
| 3499 |
"stride_start_frame",
|
| 3500 |
-
"stride_end_frame"
|
| 3501 |
-
"pitcher_direction"
|
| 3502 |
],
|
| 3503 |
"title": "MarksIn"
|
| 3504 |
},
|
|
@@ -6347,4 +6354,4 @@
|
|
| 6347 |
}
|
| 6348 |
}
|
| 6349 |
}
|
| 6350 |
-
}
|
|
|
|
| 3487 |
"title": "Stride End Frame"
|
| 3488 |
},
|
| 3489 |
"pitcher_direction": {
|
| 3490 |
+
"anyOf": [
|
| 3491 |
+
{
|
| 3492 |
+
"$ref": "#/components/schemas/PitcherDirection"
|
| 3493 |
+
},
|
| 3494 |
+
{
|
| 3495 |
+
"type": "null"
|
| 3496 |
+
}
|
| 3497 |
+
],
|
| 3498 |
+
"default": null
|
| 3499 |
}
|
| 3500 |
},
|
| 3501 |
"additionalProperties": false,
|
|
|
|
| 3505 |
"contact_offset",
|
| 3506 |
"contact_source",
|
| 3507 |
"stride_start_frame",
|
| 3508 |
+
"stride_end_frame"
|
|
|
|
| 3509 |
],
|
| 3510 |
"title": "MarksIn"
|
| 3511 |
},
|
|
|
|
| 6354 |
}
|
| 6355 |
}
|
| 6356 |
}
|
| 6357 |
+
}
|
backend/tests/integration/test_sessions.py
CHANGED
|
@@ -4,6 +4,7 @@ import uuid
|
|
| 4 |
from datetime import UTC, datetime, timedelta
|
| 5 |
|
| 6 |
import httpx
|
|
|
|
| 7 |
from sqlalchemy import select
|
| 8 |
|
| 9 |
from app.core.config import get_settings
|
|
@@ -28,6 +29,24 @@ from tests.factories import (
|
|
| 28 |
|
| 29 |
# ---------- D2 ----------
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
async def test_create_session_after_real_presigned_put(client):
|
| 32 |
player = await make_account()
|
| 33 |
video_id = await upload(client, player["headers"], "video")
|
|
|
|
| 4 |
from datetime import UTC, datetime, timedelta
|
| 5 |
|
| 6 |
import httpx
|
| 7 |
+
import pytest
|
| 8 |
from sqlalchemy import select
|
| 9 |
|
| 10 |
from app.core.config import get_settings
|
|
|
|
| 29 |
|
| 30 |
# ---------- D2 ----------
|
| 31 |
|
| 32 |
+
|
| 33 |
+
@pytest.mark.parametrize("explicit_null", [False, True])
|
| 34 |
+
async def test_create_and_read_session_without_manual_pitcher_direction(client, explicit_null):
|
| 35 |
+
player = await make_account()
|
| 36 |
+
video_id = await upload(client, player["headers"], "video")
|
| 37 |
+
body = session_body(video_id, None)
|
| 38 |
+
if explicit_null:
|
| 39 |
+
body["marks"]["pitcher_direction"] = None
|
| 40 |
+
else:
|
| 41 |
+
body["marks"].pop("pitcher_direction")
|
| 42 |
+
response = await client.post("/v1/sessions", json=body, headers=player["headers"])
|
| 43 |
+
assert response.status_code == 201, response.text
|
| 44 |
+
session = response.json()["session"]
|
| 45 |
+
assert session["marks"]["pitcher_direction"] is None
|
| 46 |
+
response = await client.get(f"/v1/sessions/{session['id']}", headers=player["headers"])
|
| 47 |
+
assert response.status_code == 200, response.text
|
| 48 |
+
assert response.json()["session"]["marks"]["pitcher_direction"] is None
|
| 49 |
+
|
| 50 |
async def test_create_session_after_real_presigned_put(client):
|
| 51 |
player = await make_account()
|
| 52 |
video_id = await upload(client, player["headers"], "video")
|
baseball_batting/automatic_pitcher_direction.py
CHANGED
|
@@ -1,4 +1,6 @@
|
|
| 1 |
-
"""
|
|
|
|
|
|
|
| 2 |
|
| 3 |
No stance or stride defines the field axis. Camera height cancels when the
|
| 4 |
outline is intersected with a level floor. Shape/temporal checks are engineering
|
|
|
|
| 1 |
+
"""Legacy experimental field direction from a visible home-plate outline.
|
| 2 |
+
|
| 3 |
+
Not called by motion uploads; body_pitcher_direction is the automatic path.
|
| 4 |
|
| 5 |
No stance or stride defines the field axis. Camera height cancels when the
|
| 6 |
outline is intersected with a level floor. Shape/temporal checks are engineering
|
baseball_batting/body_pitcher_direction.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Estimate a batting-direction proxy from a setup followed by a swing.
|
| 2 |
+
|
| 3 |
+
Both adapters supply camera-oriented MHR landmarks. The setup hip line gives
|
| 4 |
+
an approximate axis; loaded hands and subsequent hand/torso motion resolve its
|
| 5 |
+
sign. Neither stride nor ball flight defines the axis. This is a deterministic
|
| 6 |
+
pose heuristic, not a trained target detector or a measured field direction.
|
| 7 |
+
"""
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
from scipy.signal import find_peaks
|
| 12 |
+
|
| 13 |
+
from .camera_up_provider import CAMERA_FRAME
|
| 14 |
+
from .sam_motion import derivative, segments
|
| 15 |
+
from .storage import sha256_file
|
| 16 |
+
|
| 17 |
+
METHOD = 'automatic_body_swing_direction_v1'
|
| 18 |
+
SOURCE = 'Automatic body swing estimate; setup hip axis signed by loaded hands and forward hand/torso motion; target alignment unverified'
|
| 19 |
+
LIMITS = {
|
| 20 |
+
'minimum_run_frames': 16, 'minimum_setup_frames': 5,
|
| 21 |
+
'minimum_extension_frames': 3, 'maximum_candidates': 40,
|
| 22 |
+
'maximum_setup_spread_deg': 12., 'maximum_setup_hip_shoulder_deg': 35.,
|
| 23 |
+
'maximum_between_swing_spread_deg': 20.,
|
| 24 |
+
'minimum_shoulder_rotation_deg': 25., 'minimum_hip_rotation_deg': 10.,
|
| 25 |
+
'minimum_loaded_offset_hip_widths': .35,
|
| 26 |
+
'minimum_extension_offset_hip_widths': .2,
|
| 27 |
+
'minimum_hand_progress_hip_widths': 1.,
|
| 28 |
+
'maximum_wrist_separation_shoulder_widths': .75,
|
| 29 |
+
'minimum_forward_velocity_fraction': .25,
|
| 30 |
+
'maximum_axis_step_deg': 60., 'maximum_hand_step_shoulder_widths': 1.,
|
| 31 |
+
}
|
| 32 |
+
JOINTS = [5, 6, 9, 10, 41, 62]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def reference(reason='no_clear_setup_and_swing'):
|
| 36 |
+
return {'status': 'unknown', 'pitcher_vector': None, 'pitcher_source': None,
|
| 37 |
+
'coordinate_frame': CAMERA_FRAME, 'method': METHOD, 'automatic': True,
|
| 38 |
+
'applied': False, 'reliable': False, 'confidence': None,
|
| 39 |
+
'accuracy_validated': False, 'reason_code': reason, 'limits': dict(LIMITS),
|
| 40 |
+
'implementation_sha256': sha256_file(Path(__file__)),
|
| 41 |
+
'reference_kind': 'estimated_batting_direction',
|
| 42 |
+
'target_alignment_verified': False,
|
| 43 |
+
'assumptions': ['setup_hip_line_approximately_aligned_with_hitting_direction',
|
| 44 |
+
'hands_load_on_rear_side_before_forward_swing',
|
| 45 |
+
'camera_orientation_constant_during_evidence_window'],
|
| 46 |
+
'reliability_kind': 'pose_and_temporal_consistency_checks; not validated accuracy',
|
| 47 |
+
'candidates': [], 'accepted_candidate_count': 0}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _unit(q):
|
| 51 |
+
length = np.linalg.norm(q, axis=-1, keepdims=True)
|
| 52 |
+
return np.divide(q, length, out=np.full_like(q, np.nan), where=length > 1e-8)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _angle(a, b):
|
| 56 |
+
return np.degrees(np.arccos(np.clip(np.sum(a*b, axis=-1), -1., 1.)))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _turn(a, b, up):
|
| 60 |
+
return np.degrees(np.arctan2(np.cross(a, b) @ up, np.sum(a*b, axis=-1)))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _candidate(p, t, run, peak, next_peak, velocity, speed, up, hip_axis, shoulder_axis, width, hip_width):
|
| 64 |
+
"""Require a continuous setup → forward motion → extension, with no gaps."""
|
| 65 |
+
row = {'peak_frame': int(peak), 'accepted': False, 'reason_code': 'no_stable_loaded_setup'}
|
| 66 |
+
hip = (p[:, 9]+p[:, 10])/2
|
| 67 |
+
hands = (p[:, 41]+p[:, 62])/2-hip
|
| 68 |
+
shoulders = (p[:, 5]+p[:, 6])/2-hip
|
| 69 |
+
height = shoulders @ up
|
| 70 |
+
# A setup is near the rear shoulder, with hands together and relatively
|
| 71 |
+
# still. Arms extended in follow-through must not become a new setup.
|
| 72 |
+
side = np.sign(np.sum(hands*hip_axis, axis=1))
|
| 73 |
+
rear_shoulder = shoulders + side[:, None]*(p[:, 6]-p[:, 5])/2
|
| 74 |
+
setup_ok = ((speed <= .3*speed[peak]) & (height > .5*width)
|
| 75 |
+
& (hands @ up > .35*height) & (hands @ up < 1.65*height)
|
| 76 |
+
& (np.linalg.norm(hands-rear_shoulder, axis=1) < 1.2*width)
|
| 77 |
+
& (_angle(hip_axis, shoulder_axis) < LIMITS['maximum_setup_hip_shoulder_deg']))
|
| 78 |
+
setup_ok &= np.abs(np.sum(hands*hip_axis, axis=1)) > LIMITS['minimum_loaded_offset_hip_widths']*hip_width
|
| 79 |
+
setup_mask = np.zeros(len(p), bool)
|
| 80 |
+
setup_mask[run[run < peak]] = setup_ok[run[run < peak]]
|
| 81 |
+
# The run already encodes valid timestamps and model sequence boundaries.
|
| 82 |
+
chunks = segments(setup_mask, t, np.inf)
|
| 83 |
+
chunks = [ids for ids in chunks if len(ids) >= LIMITS['minimum_setup_frames']]
|
| 84 |
+
if not chunks:
|
| 85 |
+
return row
|
| 86 |
+
setup = chunks[-1]
|
| 87 |
+
axis = _unit(np.median(hip_axis[setup], axis=0))
|
| 88 |
+
shoulder = _unit(np.median(shoulder_axis[setup], axis=0))
|
| 89 |
+
if not np.isfinite([axis, shoulder]).all():
|
| 90 |
+
row['reason_code'] = 'setup_axis_unstable'
|
| 91 |
+
return row
|
| 92 |
+
spread = float(max(np.max(_angle(hip_axis[setup], axis)),
|
| 93 |
+
np.max(_angle(shoulder_axis[setup], shoulder))))
|
| 94 |
+
row.update(setup_start_frame=int(setup[0]), setup_end_frame=int(setup[-1]),
|
| 95 |
+
setup_spread_deg=spread)
|
| 96 |
+
if spread > LIMITS['maximum_setup_spread_deg']:
|
| 97 |
+
row['reason_code'] = 'setup_axis_unstable'
|
| 98 |
+
return row
|
| 99 |
+
start_hands = np.median(hands[setup], axis=0)
|
| 100 |
+
hip_span = float(np.median(hip_width[setup]))
|
| 101 |
+
loaded = float(start_hands @ axis)
|
| 102 |
+
if abs(loaded) < LIMITS['minimum_loaded_offset_hip_widths']*hip_span:
|
| 103 |
+
row['reason_code'] = 'loaded_hand_side_ambiguous'
|
| 104 |
+
return row
|
| 105 |
+
loaded_sign = np.sign(loaded)
|
| 106 |
+
direction = -loaded_sign*axis
|
| 107 |
+
if np.any((hands[setup] @ direction) > -LIMITS['minimum_loaded_offset_hip_widths']*hip_span):
|
| 108 |
+
row['reason_code'] = 'loaded_hand_side_inconsistent'
|
| 109 |
+
return row
|
| 110 |
+
alignment = float(velocity[peak] @ direction / speed[peak])
|
| 111 |
+
row['forward_velocity_fraction'] = alignment
|
| 112 |
+
if alignment < LIMITS['minimum_forward_velocity_fraction']:
|
| 113 |
+
row['reason_code'] = 'hand_motion_opposes_loaded_side'
|
| 114 |
+
return row
|
| 115 |
+
# Avoid reaching into a later repetition to validate a failed motion peak.
|
| 116 |
+
# The window scales with this movement's timing, including slow-motion video.
|
| 117 |
+
deadline = t[peak]+max(2*(t[peak]-t[setup[-1]]), 3*np.median(np.diff(t[run])))
|
| 118 |
+
after = run[(run > peak) & (run < next_peak) & (t[run] <= deadline)]
|
| 119 |
+
extended = np.zeros(len(p), bool)
|
| 120 |
+
extended[after] = (hands[after] @ direction) > LIMITS['minimum_extension_offset_hip_widths']*hip_span
|
| 121 |
+
extensions = [ids for ids in segments(extended, t, np.inf)
|
| 122 |
+
if len(ids) >= LIMITS['minimum_extension_frames']]
|
| 123 |
+
if not extensions:
|
| 124 |
+
row['reason_code'] = 'forward_hand_extension_unavailable'
|
| 125 |
+
return row
|
| 126 |
+
end = extensions[0][:LIMITS['minimum_extension_frames']]
|
| 127 |
+
evidence = np.arange(setup[-1], end[-1]+1)
|
| 128 |
+
step = max(float(np.max(_angle(hip_axis[evidence[:-1]], hip_axis[evidence[1:]]))),
|
| 129 |
+
float(np.max(_angle(shoulder_axis[evidence[:-1]], shoulder_axis[evidence[1:]]))))
|
| 130 |
+
hand_step = float(np.max(np.linalg.norm(np.diff(hands[evidence], axis=0), axis=1)
|
| 131 |
+
/ width[evidence[:-1]]))
|
| 132 |
+
row.update(maximum_axis_step_deg=step, maximum_hand_step_shoulder_widths=hand_step)
|
| 133 |
+
if step > LIMITS['maximum_axis_step_deg'] or hand_step > LIMITS['maximum_hand_step_shoulder_widths']:
|
| 134 |
+
row['reason_code'] = 'body_track_discontinuous'
|
| 135 |
+
return row
|
| 136 |
+
shoulder_turn = float(np.median(_turn(shoulder, shoulder_axis[end], up))*loaded_sign)
|
| 137 |
+
hip_turn = float(np.median(_turn(axis, hip_axis[end], up))*loaded_sign)
|
| 138 |
+
wrist_progress = [(np.median(p[end, j]-hip[end], axis=0)
|
| 139 |
+
-np.median(p[setup, j]-hip[setup], axis=0)) @ direction / hip_span
|
| 140 |
+
for j in (41, 62)]
|
| 141 |
+
row.update(extension_start_frame=int(end[0]), extension_end_frame=int(end[-1]),
|
| 142 |
+
shoulder_forward_turn_deg=shoulder_turn, hip_forward_turn_deg=hip_turn,
|
| 143 |
+
wrist_progress_hip_widths=[float(v) for v in wrist_progress])
|
| 144 |
+
if min(wrist_progress) < LIMITS['minimum_hand_progress_hip_widths']:
|
| 145 |
+
row['reason_code'] = 'insufficient_forward_hand_progress'
|
| 146 |
+
elif not LIMITS['minimum_shoulder_rotation_deg'] <= shoulder_turn < 150:
|
| 147 |
+
row['reason_code'] = 'shoulder_turn_does_not_support_swing'
|
| 148 |
+
elif not LIMITS['minimum_hip_rotation_deg'] <= hip_turn < 130:
|
| 149 |
+
row['reason_code'] = 'hip_turn_does_not_support_swing'
|
| 150 |
+
else:
|
| 151 |
+
row.update(accepted=True, reason_code=None, pitcher_vector=direction.tolist())
|
| 152 |
+
return row
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def estimate(corrected, times, options, up_reference, *, sequence_ids=None, progress=lambda *a: None):
|
| 156 |
+
"""Shared SAM/GVHMR path. No image detector, handedness or camera intrinsics."""
|
| 157 |
+
out = reference()
|
| 158 |
+
if options.camera_stability == 'moving':
|
| 159 |
+
out['reason_code'] = 'camera_moving'
|
| 160 |
+
return out
|
| 161 |
+
if options.up_vector is None:
|
| 162 |
+
out['reason_code'] = 'automatic_up_unavailable'
|
| 163 |
+
return out
|
| 164 |
+
if up_reference.get('status') == 'estimated' and not up_reference.get('reliable'):
|
| 165 |
+
out['reason_code'] = 'automatic_up_unreliable'
|
| 166 |
+
return out
|
| 167 |
+
p = np.asarray(corrected['points_relative'], float)
|
| 168 |
+
t = np.asarray(times, float)
|
| 169 |
+
if p.ndim != 3 or p.shape[1:] != (70, 3) or t.shape != (len(p),):
|
| 170 |
+
raise ValueError('Body direction requires N x 70 x 3 points and matching timestamps')
|
| 171 |
+
if not np.isfinite(t).all() or np.any(np.diff(t) <= 0):
|
| 172 |
+
raise ValueError('Body direction timestamps must increase strictly')
|
| 173 |
+
up = _unit(np.asarray(options.up_vector, float))
|
| 174 |
+
if not np.isfinite(up).all():
|
| 175 |
+
out['reason_code'] = 'vertical_reference_invalid'
|
| 176 |
+
return out
|
| 177 |
+
mask = np.isfinite(p[:, JOINTS]).all(axis=(1, 2))
|
| 178 |
+
for key, exclude in (('valid', False), ('boundary', True), ('interpolated', True)):
|
| 179 |
+
if key in corrected:
|
| 180 |
+
values = np.asarray(corrected[key], bool)
|
| 181 |
+
if values.shape != p.shape[:2]:
|
| 182 |
+
raise ValueError('Body direction masks differ from motion shape')
|
| 183 |
+
mask &= ~values[:, JOINTS].any(axis=1) if exclude else values[:, JOINTS].all(axis=1)
|
| 184 |
+
sequence = np.asarray(sequence_ids if sequence_ids is not None else np.zeros(len(p), int))
|
| 185 |
+
if sequence.shape != t.shape:
|
| 186 |
+
raise ValueError('Body direction sequence IDs differ from timestamps')
|
| 187 |
+
h, s = p[:, 10]-p[:, 9], p[:, 6]-p[:, 5]
|
| 188 |
+
width = np.linalg.norm(s, axis=1)
|
| 189 |
+
h = h-(h @ up)[:, None]*up
|
| 190 |
+
s = s-(s @ up)[:, None]*up
|
| 191 |
+
hip_width = np.linalg.norm(h, axis=1)
|
| 192 |
+
hip_axis, shoulder_axis = _unit(h), _unit(s)
|
| 193 |
+
mask &= ((width > 1e-6) & (hip_width > .3*width)
|
| 194 |
+
& (np.linalg.norm(s, axis=1) > .6*width)
|
| 195 |
+
& (np.linalg.norm(p[:, 41]-p[:, 62], axis=1)
|
| 196 |
+
< LIMITS['maximum_wrist_separation_shoulder_widths']*width))
|
| 197 |
+
runs = []
|
| 198 |
+
for ids in segments(mask, t, options.correction.max_gap_s):
|
| 199 |
+
runs.extend(part for part in np.split(ids, np.flatnonzero(np.diff(sequence[ids]) != 0)+1)
|
| 200 |
+
if len(part) >= LIMITS['minimum_run_frames'])
|
| 201 |
+
out['usable_run_count'] = len(runs)
|
| 202 |
+
out['camera_stability'] = options.camera_stability
|
| 203 |
+
if not runs:
|
| 204 |
+
out['reason_code'] = 'insufficient_continuous_body_frames'
|
| 205 |
+
return out
|
| 206 |
+
hands = (p[:, 41]+p[:, 62]-p[:, 9]-p[:, 10])/2
|
| 207 |
+
accepted = []
|
| 208 |
+
progress('pitcher_direction_estimation', 0, len(runs))
|
| 209 |
+
for index, run in enumerate(runs):
|
| 210 |
+
speed = np.full(len(p), np.nan)
|
| 211 |
+
velocity = np.full_like(hands, np.nan)
|
| 212 |
+
velocity[run] = derivative(hands[run], t[run], max_gap=options.correction.max_gap_s)
|
| 213 |
+
speed[run] = np.linalg.norm(velocity[run], axis=1)
|
| 214 |
+
finite = speed[run][np.isfinite(speed[run])]
|
| 215 |
+
# Relative prominence is invariant to native body scale and uniform
|
| 216 |
+
# playback-speed changes. Displacement/rotation checks reject tiny noise.
|
| 217 |
+
prominence = max(float(np.percentile(finite, 90))*.3,
|
| 218 |
+
float(np.percentile(finite, 20))*3, 1e-8)
|
| 219 |
+
peaks, _ = find_peaks(np.nan_to_num(speed[run]), prominence=prominence)
|
| 220 |
+
for peak, next_peak in zip(run[peaks], [*run[peaks[1:]], run[-1]+1]):
|
| 221 |
+
if len(out['candidates']) >= LIMITS['maximum_candidates']:
|
| 222 |
+
out['reason_code'] = 'too_many_motion_candidates'
|
| 223 |
+
return out
|
| 224 |
+
row = _candidate(p, t, run, peak, next_peak, velocity, speed, up, hip_axis, shoulder_axis, width, hip_width)
|
| 225 |
+
out['candidates'].append(row)
|
| 226 |
+
# Multiple speed peaks during one swing are one piece of evidence.
|
| 227 |
+
if row['accepted'] and not any(a['setup_start_frame'] <= row['setup_end_frame'] <= a['extension_end_frame']
|
| 228 |
+
for a in accepted):
|
| 229 |
+
accepted.append(row)
|
| 230 |
+
progress('pitcher_direction_estimation', index+1, len(runs))
|
| 231 |
+
out['accepted_candidate_count'] = len(accepted)
|
| 232 |
+
if not accepted:
|
| 233 |
+
if not out['candidates']:
|
| 234 |
+
out['reason_code'] = 'no_swing_motion'
|
| 235 |
+
else:
|
| 236 |
+
reasons = {row['reason_code'] for row in out['candidates']}
|
| 237 |
+
if len(reasons) == 1:
|
| 238 |
+
out['reason_code'] = reasons.pop()
|
| 239 |
+
return out
|
| 240 |
+
vectors = np.array([row['pitcher_vector'] for row in accepted])
|
| 241 |
+
spread = float(np.max(_angle(vectors[:, None], vectors[None, :])))
|
| 242 |
+
out['between_swing_spread_deg'] = spread
|
| 243 |
+
if spread > LIMITS['maximum_between_swing_spread_deg']:
|
| 244 |
+
out['reason_code'] = 'inconsistent_body_swing_directions'
|
| 245 |
+
return out
|
| 246 |
+
out.update(status='estimated', pitcher_vector=_unit(np.median(vectors, axis=0)).tolist(),
|
| 247 |
+
pitcher_source=SOURCE, applied=True, reliable=True, reason_code=None)
|
| 248 |
+
return out
|
baseball_batting/motion_api.py
CHANGED
|
@@ -102,9 +102,11 @@ def register(app,service,authenticated):
|
|
| 102 |
'refinement_accuracy_validated':False,'camera_distortion_model':'Brown-Conrady k1 k2 p1 p2 k3',
|
| 103 |
'automatic_camera_up':camera_up_status(settings.model_root),
|
| 104 |
'automatic_pitcher_direction':{'supported':True,'automatic_when_missing':True,
|
| 105 |
-
'method':'
|
| 106 |
'requires_user_direction_input':False,
|
| 107 |
-
'
|
|
|
|
|
|
|
| 108 |
'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
|
| 109 |
'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
|
| 110 |
'camera_frame':'upright_camera_x_right_y_down_z_away'},
|
|
|
|
| 102 |
'refinement_accuracy_validated':False,'camera_distortion_model':'Brown-Conrady k1 k2 p1 p2 k3',
|
| 103 |
'automatic_camera_up':camera_up_status(settings.model_root),
|
| 104 |
'automatic_pitcher_direction':{'supported':True,'automatic_when_missing':True,
|
| 105 |
+
'method':'automatic_body_swing_direction_v1','accuracy_validated':False,
|
| 106 |
'requires_user_direction_input':False,
|
| 107 |
+
'requires_home_plate':False,'requires_handedness':False,
|
| 108 |
+
'reference_kind':'estimated_batting_direction','target_alignment_verified':False,
|
| 109 |
+
'unknown_when':'no continuous clear setup and forward swing, conflicting directions, moving camera, or missing up estimate'},
|
| 110 |
'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
|
| 111 |
'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
|
| 112 |
'camera_frame':'upright_camera_x_right_y_down_z_away'},
|
baseball_batting/motion_export.py
CHANGED
|
@@ -152,8 +152,9 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 152 |
from .pitcher_direction import resolve as resolve_pitcher_direction
|
| 153 |
pitcher_reference=resolve_pitcher_direction(calculation_options,capture,up_reference)
|
| 154 |
if options.pitcher_vector is None and options.pitcher_floor_points is None:
|
| 155 |
-
from .
|
| 156 |
-
pitcher_reference=estimate_pitcher_direction(
|
|
|
|
| 157 |
if options.pitcher_vector is None and pitcher_reference['status']=='estimated' and pitcher_reference['reliable'] is True:
|
| 158 |
calculation_options=calculation_options.model_copy(update={
|
| 159 |
'pitcher_vector':tuple(pitcher_reference['pitcher_vector']),
|
|
@@ -247,6 +248,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 247 |
'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
|
| 248 |
metadata['up_reference_status']=up_reference['status']
|
| 249 |
metadata['pitcher_reference_status']=pitcher_reference['status']
|
|
|
|
| 250 |
for key,metric in rows.items():
|
| 251 |
details=metric.model_dump(mode='json');details.pop('coaching',None)
|
| 252 |
if (up_reference['status']=='estimated' and details['value'] is not None and key not in
|
|
@@ -255,8 +257,10 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 255 |
if (pitcher_reference['status']=='estimated' and details['value'] is not None and key in
|
| 256 |
('hip_heading_deg','shoulder_heading_deg','left_foot_heading_deg','right_foot_heading_deg',
|
| 257 |
'stride_relative_forward_cm','stride_relative_lateral_cm')):
|
| 258 |
-
details['quality_flags'].append('
|
| 259 |
else 'pitcher_reference_estimated_from_floor_points')
|
|
|
|
|
|
|
| 260 |
summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
|
| 261 |
'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
|
| 262 |
'source_samples':[stamp(i) for i in metric.source_frame_ids]})
|
|
@@ -413,9 +417,10 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 413 |
'scale_source':options.scale_source or adapter['name']+' native scale; not independently calibrated',
|
| 414 |
'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
|
| 415 |
'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
|
| 416 |
-
'axes':{'x':'
|
|
|
|
| 417 |
{'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'estimated_up' if up_reference['status']=='estimated' else 'declared_up'} if reference=='fixed_starting_hip_axis' else
|
| 418 |
-
{'x':'camera_right','y':'camera_down','z':'camera_away'}),
|
| 419 |
'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
|
| 420 |
'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
|
| 421 |
'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
|
|
|
|
| 152 |
from .pitcher_direction import resolve as resolve_pitcher_direction
|
| 153 |
pitcher_reference=resolve_pitcher_direction(calculation_options,capture,up_reference)
|
| 154 |
if options.pitcher_vector is None and options.pitcher_floor_points is None:
|
| 155 |
+
from .body_pitcher_direction import estimate as estimate_pitcher_direction
|
| 156 |
+
pitcher_reference=estimate_pitcher_direction(corrected,times,calculation_options,up_reference,
|
| 157 |
+
sequence_ids=model_sequence,progress=progress)
|
| 158 |
if options.pitcher_vector is None and pitcher_reference['status']=='estimated' and pitcher_reference['reliable'] is True:
|
| 159 |
calculation_options=calculation_options.model_copy(update={
|
| 160 |
'pitcher_vector':tuple(pitcher_reference['pitcher_vector']),
|
|
|
|
| 248 |
'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
|
| 249 |
metadata['up_reference_status']=up_reference['status']
|
| 250 |
metadata['pitcher_reference_status']=pitcher_reference['status']
|
| 251 |
+
metadata['pitcher_reference_kind']=pitcher_reference.get('reference_kind')
|
| 252 |
for key,metric in rows.items():
|
| 253 |
details=metric.model_dump(mode='json');details.pop('coaching',None)
|
| 254 |
if (up_reference['status']=='estimated' and details['value'] is not None and key not in
|
|
|
|
| 257 |
if (pitcher_reference['status']=='estimated' and details['value'] is not None and key in
|
| 258 |
('hip_heading_deg','shoulder_heading_deg','left_foot_heading_deg','right_foot_heading_deg',
|
| 259 |
'stride_relative_forward_cm','stride_relative_lateral_cm')):
|
| 260 |
+
details['quality_flags'].append('pitcher_reference_estimated_from_body_motion' if pitcher_reference.get('automatic')
|
| 261 |
else 'pitcher_reference_estimated_from_floor_points')
|
| 262 |
+
if pitcher_reference.get('reference_kind')=='estimated_batting_direction':
|
| 263 |
+
details['quality_flags'].append('target_alignment_unverified')
|
| 264 |
summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
|
| 265 |
'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
|
| 266 |
'source_samples':[stamp(i) for i in metric.source_frame_ids]})
|
|
|
|
| 417 |
'scale_source':options.scale_source or adapter['name']+' native scale; not independently calibrated',
|
| 418 |
'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
|
| 419 |
'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
|
| 420 |
+
'axes':{'x':'estimated_hitting_direction','y':'up_cross_estimated_hitting_direction','z':'estimated_up' if up_reference['status']=='estimated' else 'declared_up'} if reference=='estimated_batting_axes' else (
|
| 421 |
+
{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'estimated_up' if up_reference['status']=='estimated' else 'declared_up'} if reference=='declared_field_axes' else (
|
| 422 |
{'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'estimated_up' if up_reference['status']=='estimated' else 'declared_up'} if reference=='fixed_starting_hip_axis' else
|
| 423 |
+
{'x':'camera_right','y':'camera_down','z':'camera_away'})),
|
| 424 |
'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable',
|
| 425 |
'camera_motion':calculation_options.camera_stability,'camera_motion_declared':options.camera_stability,
|
| 426 |
'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
|
baseball_batting/sam_measurements.py
CHANGED
|
@@ -65,7 +65,8 @@ def orientation(points, options, baseline):
|
|
| 65 |
u = normalize(options.up_vector)
|
| 66 |
if options.pitcher_vector is not None:
|
| 67 |
e = np.asarray(options.pitcher_vector,float)
|
| 68 |
-
|
|
|
|
| 69 |
else:
|
| 70 |
e = points[baseline,10]-points[baseline,9]
|
| 71 |
reference = 'fixed_starting_hip_axis'
|
|
|
|
| 65 |
u = normalize(options.up_vector)
|
| 66 |
if options.pitcher_vector is not None:
|
| 67 |
e = np.asarray(options.pitcher_vector,float)
|
| 68 |
+
from .body_pitcher_direction import SOURCE as body_direction_source
|
| 69 |
+
reference = 'estimated_batting_axes' if options.pitcher_source == body_direction_source else 'declared_field_axes'
|
| 70 |
else:
|
| 71 |
e = points[baseline,10]-points[baseline,9]
|
| 72 |
reference = 'fixed_starting_hip_axis'
|
docs/APP_API_INTEGRATION.md
CHANGED
|
@@ -187,11 +187,14 @@ Example **only when the uploader confirms these recording facts**:
|
|
| 187 |
Other supported calibration inputs: `camera`, `up_vector`/`up_source`,
|
| 188 |
`pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`.
|
| 189 |
Normal uploads should omit `pitcher_vector`, `pitcher_source`, and
|
| 190 |
-
`pitcher_floor_points`. When all are absent, both models automatically
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
GeoCalib provider supplies missing
|
| 194 |
-
|
|
|
|
|
|
|
|
|
|
| 195 |
interrupting the job or requesting user input. This does not bypass the existing
|
| 196 |
camera-stability requirements for measurements. See
|
| 197 |
[automatic direction behavior and limitations](PITCHER_FLOOR_DIRECTION.md#automatic-direction-default).
|
|
|
|
| 187 |
Other supported calibration inputs: `camera`, `up_vector`/`up_source`,
|
| 188 |
`pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`.
|
| 189 |
Normal uploads should omit `pitcher_vector`, `pitcher_source`, and
|
| 190 |
+
`pitcher_floor_points`. When all are absent, both models automatically estimate
|
| 191 |
+
hitting direction from the batter's setup and subsequent hand/torso movement.
|
| 192 |
+
A home plate, field markings, handedness, camera calibration, and user clicks
|
| 193 |
+
are not required. The existing GeoCalib provider supplies missing up estimates;
|
| 194 |
+
it must be installed on the server. This gives an approximate hitting direction,
|
| 195 |
+
not the verified location of an unseen pitcher. The output reference is
|
| 196 |
+
`estimated_batting_axes`, with `target_alignment_verified: false` in
|
| 197 |
+
`coordinates.pitcher_estimation`. Missing or ambiguous evidence returns an unknown direction without
|
| 198 |
interrupting the job or requesting user input. This does not bypass the existing
|
| 199 |
camera-stability requirements for measurements. See
|
| 200 |
[automatic direction behavior and limitations](PITCHER_FLOOR_DIRECTION.md#automatic-direction-default).
|
docs/MOTION_PLAYER_API.md
CHANGED
|
@@ -112,12 +112,17 @@ pitcher direction may be supplied before vertical is resolved. See
|
|
| 112 |
[automatic camera-up estimation](CAMERA_UP_ESTIMATION.md) for coordinates,
|
| 113 |
acceptance checks, FE labels and the `up_estimation.enabled` opt-out.
|
| 114 |
|
| 115 |
-
When no pitcher vector or floor points are supplied,
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
For an optional manual override, send `pitcher_floor_points` with `source_frame_index`,
|
| 123 |
`near_batter` and `toward_pitcher` in upright source pixels. This uses supplied
|
|
|
|
| 112 |
[automatic camera-up estimation](CAMERA_UP_ESTIMATION.md) for coordinates,
|
| 113 |
acceptance checks, FE labels and the `up_estimation.enabled` opt-out.
|
| 114 |
|
| 115 |
+
When no pitcher vector or floor points are supplied, both models automatically
|
| 116 |
+
estimate hitting direction from a stable batting setup followed by hand and
|
| 117 |
+
torso movement (`automatic_body_swing_direction_v1`). No plate, field markings,
|
| 118 |
+
handedness, camera intrinsics, or user direction input is required. The existing
|
| 119 |
+
automatic up estimate is used. Missing or conflicting evidence leaves direction
|
| 120 |
+
unknown without stopping the job. This is an approximate batting direction based
|
| 121 |
+
on the setup hip line, not a measurement of an unseen pitcher's location. The
|
| 122 |
+
output names this reference `estimated_batting_axes`, records the supporting
|
| 123 |
+
frames in `coordinates.pitcher_estimation`, and flags affected measurements with
|
| 124 |
+
`pitcher_reference_estimated_from_body_motion` and `target_alignment_unverified`.
|
| 125 |
+
Accuracy on real labelled videos has not been validated.
|
| 126 |
|
| 127 |
For an optional manual override, send `pitcher_floor_points` with `source_frame_index`,
|
| 128 |
`near_batter` and `toward_pitcher` in upright source pixels. This uses supplied
|
docs/PITCHER_FLOOR_DIRECTION.md
CHANGED
|
@@ -4,51 +4,53 @@ Motion API 1.14.0 · SAM 3D Body and GVHMR · 19 October 2026
|
|
| 4 |
|
| 5 |
## Automatic direction (default)
|
| 6 |
|
| 7 |
-
Updated
|
| 8 |
-
`pitcher_source`, and `pitcher_floor_points`. Both SAM and GVHMR
|
| 9 |
-
|
| 10 |
-
measurements.
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
The
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
|
| 27 |
On acceptance, `coordinates.pitcher_estimation` contains `automatic: true`,
|
| 28 |
-
`status: estimated`, the method,
|
| 29 |
-
|
|
|
|
| 30 |
`pipeline.calculation_inputs` receive the vector and generated source; submitted
|
| 31 |
-
`pipeline.inputs`
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
manual fields from the UI does not imply every recording yields a direction.
|
| 52 |
|
| 53 |
## Optional manual override
|
| 54 |
|
|
|
|
| 4 |
|
| 5 |
## Automatic direction (default)
|
| 6 |
|
| 7 |
+
Updated 30 October 2026. Normal motion uploads omit `pitcher_vector`,
|
| 8 |
+
`pitcher_source`, and `pitcher_floor_points`. Both SAM and GVHMR now run
|
| 9 |
+
`automatic_body_swing_direction_v1` on their corrected 3D body tracks before
|
| 10 |
+
calculating/exporting measurements. The old home-plate detector is no longer
|
| 11 |
+
called. There are no new request fields, downloads, or user prompts.
|
| 12 |
+
|
| 13 |
+
The estimator uses shoulders, hips, and both wrists. It finds a stable loaded
|
| 14 |
+
setup before a hand-speed peak, projects the setup hip line onto the horizontal
|
| 15 |
+
plane, and resolves its direction using the loaded hand side. Both wrists must
|
| 16 |
+
then move across toward the other side while the hips and shoulders turn in the
|
| 17 |
+
same swing direction. Several consecutive setup and extension frames must agree.
|
| 18 |
+
Separate accepted swings must agree within 20 degrees. Missing/rejected points,
|
| 19 |
+
filter boundaries, model sequence breaks, and timestamp gaps cannot connect a
|
| 20 |
+
setup to a later swing. Cropped feet are allowed: stride never defines the axis.
|
| 21 |
+
Handedness and camera intrinsics are not inputs to this estimator. Relative
|
| 22 |
+
movement checks do not require a physical scale or original recording speed.
|
| 23 |
+
|
| 24 |
+
An accepted vertical reference is still needed. GeoCalib supplies it when omitted;
|
| 25 |
+
an explicit up vector also works. Camera movement declared or detected by
|
| 26 |
+
refinement blocks this reference. Acceptance does not declare the camera fixed or
|
| 27 |
+
bypass existing camera-stability, timing, scale, or reviewed-event requirements.
|
| 28 |
|
| 29 |
On acceptance, `coordinates.pitcher_estimation` contains `automatic: true`,
|
| 30 |
+
`status: estimated`, the method, setup/peak/extension frame indices, turn angles,
|
| 31 |
+
hand progress, agreement checks and assumptions. `reference_kind` is
|
| 32 |
+
`estimated_batting_direction`; `target_alignment_verified` is false. Effective
|
| 33 |
`pipeline.calculation_inputs` receive the vector and generated source; submitted
|
| 34 |
+
`pipeline.inputs` stay unchanged. Replay and measurements use that same vector.
|
| 35 |
+
When the axis is used, the coordinate frame is `estimated_batting_axes`, with
|
| 36 |
+
positive X named `estimated_hitting_direction`. Relevant measurements carry
|
| 37 |
+
`pitcher_reference_estimated_from_body_motion` and `target_alignment_unverified`.
|
| 38 |
+
Explicit vectors and manual floor selections retain precedence.
|
| 39 |
+
|
| 40 |
+
**Limits:** this is a deterministic body-motion heuristic, not a trained baseball
|
| 41 |
+
direction model. It assumes the setup hip line approximately follows the intended
|
| 42 |
+
hitting direction. Open/closed setups, unusual drills, inaccurate model depth,
|
| 43 |
+
and movement that resembles a swing can bias or fool it. Body motion alone cannot
|
| 44 |
+
verify the actual direction to an unseen pitcher. A clipped swing without a clear
|
| 45 |
+
setup or extension, conflicting repetitions, or missing vertical leaves the
|
| 46 |
+
direction null; normal motion export continues. Do not interpret this axis as
|
| 47 |
+
independent evidence that the athlete's setup is aligned correctly with a target.
|
| 48 |
+
|
| 49 |
+
`accuracy_validated` stays false and `confidence` stays null. `reliable` means
|
| 50 |
+
the engineering acceptance checks passed, not a calibrated accuracy probability.
|
| 51 |
+
Synthetic tests cover both batting sides, camera rotations, missing evidence,
|
| 52 |
+
motion conflicts, and replay consistency. Independently labelled real videos
|
| 53 |
+
are still required to measure accuracy and false positives.
|
|
|
|
| 54 |
|
| 55 |
## Optional manual override
|
| 56 |
|
tests/test_automatic_pitcher_direction.py
CHANGED
|
@@ -2,7 +2,6 @@
|
|
| 2 |
|
| 3 |
Synthetic accuracy verifies geometry, not home-plate recognition in real footage.
|
| 4 |
"""
|
| 5 |
-
import json
|
| 6 |
import av
|
| 7 |
import cv2
|
| 8 |
import numpy as np
|
|
@@ -12,7 +11,7 @@ from baseball_batting.automatic_pitcher_direction import outlines, fit_outline,
|
|
| 12 |
from baseball_batting.motion_contract import MotionInput, MotionCamera
|
| 13 |
from baseball_batting.geometry import project
|
| 14 |
from baseball_batting.ingest import ingest
|
| 15 |
-
from baseball_batting.motion_export import export_motion
|
| 16 |
from baseball_batting.camera_up import consensus
|
| 17 |
from baseball_batting.pitcher_direction import Unreliable
|
| 18 |
from test_motion_player import raw_for
|
|
@@ -135,7 +134,10 @@ def test_multiple_visible_plates_are_ambiguous(tmp_path, monkeypatch):
|
|
| 135 |
|
| 136 |
|
| 137 |
@pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
|
| 138 |
-
def
|
|
|
|
|
|
|
|
|
|
| 139 |
path = video_file(tmp_path)
|
| 140 |
options = MotionInput(model=model, annotated_videos=False, single_swing=True,
|
| 141 |
camera_stability='fixed_verified')
|
|
@@ -143,20 +145,11 @@ def test_export_applies_automatic_reference_and_replays_identical_measurements(t
|
|
| 143 |
manifest = export_motion(tmp_path, path, capture, raw_for(capture), options, {'name':'synthetic'},
|
| 144 |
{'analysis_id':'auto-plate', 'analysis_revision':1}, up_reference=automatic_up())
|
| 145 |
ref = manifest.coordinates['pitcher_estimation']
|
| 146 |
-
assert ref['status'] == '
|
|
|
|
| 147 |
assert manifest.pipeline['inputs']['pitcher_vector'] is None
|
| 148 |
assert manifest.pipeline['inputs']['camera'] is None
|
| 149 |
-
assert manifest.pipeline['calculation_inputs']['pitcher_vector']
|
| 150 |
-
report = json.loads((tmp_path/'measurements.json').read_text())
|
| 151 |
-
assert report['pitcher_reference'] == ref
|
| 152 |
-
flags = [f for m in report['summaries'] for f in m['quality_flags']]
|
| 153 |
-
assert 'pitcher_reference_estimated_from_home_plate' in flags
|
| 154 |
-
assert 'pitcher_reference_estimated_from_floor_points' not in flags
|
| 155 |
-
reproduced = reproduce_measurements(manifest, tmp_path/'motion.jsonl')
|
| 156 |
-
expected = {(s.rep,m.key):m.value for group in reproduced.values() for s in group for m in s.measurements}
|
| 157 |
-
for row in report['summaries']:
|
| 158 |
-
value = expected[row['rep'],row['metric_id']]
|
| 159 |
-
assert row['value'] == pytest.approx(value) if value is not None else row['value'] is None
|
| 160 |
|
| 161 |
|
| 162 |
def test_only_consistent_accepted_camera_estimates_are_available_for_scene_geometry():
|
|
|
|
| 2 |
|
| 3 |
Synthetic accuracy verifies geometry, not home-plate recognition in real footage.
|
| 4 |
"""
|
|
|
|
| 5 |
import av
|
| 6 |
import cv2
|
| 7 |
import numpy as np
|
|
|
|
| 11 |
from baseball_batting.motion_contract import MotionInput, MotionCamera
|
| 12 |
from baseball_batting.geometry import project
|
| 13 |
from baseball_batting.ingest import ingest
|
| 14 |
+
from baseball_batting.motion_export import export_motion
|
| 15 |
from baseball_batting.camera_up import consensus
|
| 16 |
from baseball_batting.pitcher_direction import Unreliable
|
| 17 |
from test_motion_player import raw_for
|
|
|
|
| 134 |
|
| 135 |
|
| 136 |
@pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
|
| 137 |
+
def test_export_no_longer_uses_plate_detection_as_automatic_direction(tmp_path, model, monkeypatch):
|
| 138 |
+
def unexpected(*args, **kwargs):
|
| 139 |
+
raise AssertionError('Legacy home-plate detector must not run for motion uploads')
|
| 140 |
+
monkeypatch.setattr('baseball_batting.automatic_pitcher_direction.estimate', unexpected)
|
| 141 |
path = video_file(tmp_path)
|
| 142 |
options = MotionInput(model=model, annotated_videos=False, single_swing=True,
|
| 143 |
camera_stability='fixed_verified')
|
|
|
|
| 145 |
manifest = export_motion(tmp_path, path, capture, raw_for(capture), options, {'name':'synthetic'},
|
| 146 |
{'analysis_id':'auto-plate', 'analysis_revision':1}, up_reference=automatic_up())
|
| 147 |
ref = manifest.coordinates['pitcher_estimation']
|
| 148 |
+
assert ref['status'] == 'unknown', ref # This fixture has no body swing.
|
| 149 |
+
assert ref['method'] == 'automatic_body_swing_direction_v1'
|
| 150 |
assert manifest.pipeline['inputs']['pitcher_vector'] is None
|
| 151 |
assert manifest.pipeline['inputs']['camera'] is None
|
| 152 |
+
assert manifest.pipeline['calculation_inputs']['pitcher_vector'] is None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
|
| 155 |
def test_only_consistent_accepted_camera_estimates_are_available_for_scene_geometry():
|
tests/test_body_pitcher_direction.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Known synthetic motion and pipeline regression, not real-video accuracy labels."""
|
| 2 |
+
import json
|
| 3 |
+
|
| 4 |
+
import av
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pytest
|
| 7 |
+
from scipy.spatial.transform import Rotation
|
| 8 |
+
from test_sam_batting import pose, raw_pose
|
| 9 |
+
|
| 10 |
+
from baseball_batting.body_pitcher_direction import METHOD, estimate
|
| 11 |
+
from baseball_batting.ingest import ingest
|
| 12 |
+
from baseball_batting.motion_contract import MotionInput
|
| 13 |
+
from baseball_batting.motion_export import export_motion, reproduce_measurements
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def swing(side=1, fps=30):
|
| 17 |
+
"""A stationary-foot swing with a known target along -side * X.
|
| 18 |
+
|
| 19 |
+
Independently prescribed smooth hand travel and rotating torso. No production
|
| 20 |
+
constants or event-window code defines the truth. Left/right are anatomical.
|
| 21 |
+
"""
|
| 22 |
+
t = np.arange(0, 3, 1/fps)
|
| 23 |
+
p = pose(len(t))
|
| 24 |
+
q = (1+np.tanh((t-1.5)/.15))/2
|
| 25 |
+
for joints, theta in (([9, 10], .7*q), ([5, 6], 1.4*q)):
|
| 26 |
+
r = Rotation.from_rotvec(np.column_stack([q*0, -side*theta, q*0])).as_matrix()
|
| 27 |
+
p[:, joints] = np.einsum('nij,nkj->nki', r, p[:, joints])
|
| 28 |
+
hand = np.column_stack([side*(.35-.9*q), -.5+.1*q, .15+.4*np.sin(np.pi*q)])
|
| 29 |
+
p[:, 41] = hand+[0, -.03, 0]
|
| 30 |
+
p[:, 62] = hand+[0, .03, 0]
|
| 31 |
+
p[:, 7] = (p[:, 5]+p[:, 62])/2
|
| 32 |
+
p[:, 8] = (p[:, 6]+p[:, 41])/2
|
| 33 |
+
return p, t, np.array([-float(side), 0, 0])
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def run(p, t, up=(0, -1, 0), **kwargs):
|
| 37 |
+
options = kwargs.pop('options', MotionInput(up_vector=up, up_source='Fixture vertical'))
|
| 38 |
+
corrected = {'points_relative': p, 'boundary': np.zeros(p.shape[:2], bool),
|
| 39 |
+
'valid': np.isfinite(p).all(axis=-1)}
|
| 40 |
+
corrected.update(kwargs.pop('masks', {}))
|
| 41 |
+
return estimate(corrected, t, options, {}, **kwargs)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@pytest.mark.parametrize('side', [-1, 1])
|
| 45 |
+
@pytest.mark.parametrize('angles', [(0, 0, 0), (10, 60, -12), (-20, 150, 30), (80, -90, 25)])
|
| 46 |
+
@pytest.mark.parametrize('fps', [30, 60])
|
| 47 |
+
def test_no_plate_camera_calibration_or_handedness_needed(side, angles, fps):
|
| 48 |
+
p, t, truth = swing(side, fps)
|
| 49 |
+
r = Rotation.from_euler('xyz', angles, degrees=True).as_matrix()
|
| 50 |
+
out = run(p @ r.T, t, up=r @ [0., -1., 0.])
|
| 51 |
+
assert out['status'] == 'estimated', out
|
| 52 |
+
assert np.degrees(np.arccos(np.clip(out['pitcher_vector'] @ (r @ truth), -1, 1))) < 2
|
| 53 |
+
assert abs(np.dot(out['pitcher_vector'], r @ [0., -1., 0.])) < 1e-12
|
| 54 |
+
assert out['reference_kind'] == 'estimated_batting_direction'
|
| 55 |
+
assert out['accuracy_validated'] is False and out['confidence'] is None
|
| 56 |
+
assert not out['target_alignment_verified']
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_translation_scale_slow_motion_and_small_pose_noise():
|
| 60 |
+
p, t, truth = swing()
|
| 61 |
+
rng = np.random.default_rng(2026)
|
| 62 |
+
p += rng.normal(0, .0015, p.shape)
|
| 63 |
+
p = p*1.7+np.column_stack([t*.4, t*.1, -t*.2])[:, None, :]
|
| 64 |
+
out = run(p, t*2)
|
| 65 |
+
assert out['status'] == 'estimated', out
|
| 66 |
+
assert np.degrees(np.arccos(np.clip(out['pitcher_vector'] @ truth, -1, 1))) < 3
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_stride_and_foot_angle_do_not_define_direction():
|
| 70 |
+
p, t, _ = swing()
|
| 71 |
+
expected = run(p, t)['pitcher_vector']
|
| 72 |
+
p[:, 13:21] = np.nan # Upper-body evidence works even if feet are cropped.
|
| 73 |
+
assert run(p, t)['pitcher_vector'] == expected
|
| 74 |
+
p[:, 13] = np.column_stack([t*0, t*0+.9, t]) # Deliberately sideways stride.
|
| 75 |
+
assert run(p, t)['pitcher_vector'] == expected
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@pytest.mark.parametrize('damage', ['no_setup', 'no_extension', 'gap', 'boundary', 'mask',
|
| 79 |
+
'sequence_break', 'clock_gap', 'separate_hands', 'no_hip_turn'])
|
| 80 |
+
def test_incomplete_or_conflicting_body_evidence_stays_unknown(damage):
|
| 81 |
+
p, t, _ = swing()
|
| 82 |
+
kwargs = {}
|
| 83 |
+
if damage == 'no_setup':
|
| 84 |
+
p, t = p[46:], t[46:]
|
| 85 |
+
elif damage == 'no_extension':
|
| 86 |
+
p, t = p[:44], t[:44]
|
| 87 |
+
elif damage == 'gap':
|
| 88 |
+
p[44:47, 41] = np.nan
|
| 89 |
+
elif damage in ('boundary', 'mask'):
|
| 90 |
+
mask = np.zeros(p.shape[:2], bool)
|
| 91 |
+
mask[44:47, 41] = True
|
| 92 |
+
kwargs['masks'] = {('boundary' if damage == 'boundary' else 'valid'): mask if damage == 'boundary' else ~mask}
|
| 93 |
+
elif damage == 'sequence_break':
|
| 94 |
+
kwargs['sequence_ids'] = np.arange(len(t)) >= 45
|
| 95 |
+
elif damage == 'clock_gap':
|
| 96 |
+
t[45:] += 1
|
| 97 |
+
elif damage == 'separate_hands':
|
| 98 |
+
p[:, 41, 2] += 1
|
| 99 |
+
elif damage == 'no_hip_turn':
|
| 100 |
+
p[:, [9, 10]] = p[0, [9, 10]]
|
| 101 |
+
result = run(p, t, **kwargs)
|
| 102 |
+
assert result['status'] == 'unknown', result
|
| 103 |
+
assert result['pitcher_vector'] is None and not result['applied']
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
@pytest.mark.parametrize('kind', ['still', 'noise', 'hand_wave'])
|
| 107 |
+
def test_non_swing_motion_does_not_produce_a_direction(kind):
|
| 108 |
+
p, t, _ = swing()
|
| 109 |
+
if kind != 'hand_wave':
|
| 110 |
+
p[:] = p[0]
|
| 111 |
+
if kind == 'noise':
|
| 112 |
+
p += np.random.default_rng(6).normal(0, .001, p.shape)
|
| 113 |
+
if kind == 'hand_wave':
|
| 114 |
+
p[:, [5, 6, 9, 10]] = p[0, [5, 6, 9, 10]]
|
| 115 |
+
assert run(p, t)['status'] == 'unknown'
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@pytest.mark.parametrize('other_side', [1, -1])
|
| 119 |
+
def test_repeated_swings_require_direction_agreement(other_side):
|
| 120 |
+
p, t, _ = swing()
|
| 121 |
+
other, _, _ = swing(other_side)
|
| 122 |
+
sequence = np.r_[np.zeros(len(t)), np.ones(len(t))]
|
| 123 |
+
result = run(np.concatenate([p, other]), np.r_[t, t+3], sequence_ids=sequence)
|
| 124 |
+
assert result['accepted_candidate_count'] == 2, result
|
| 125 |
+
assert result['status'] == ('estimated' if other_side == 1 else 'unknown')
|
| 126 |
+
if other_side == -1:
|
| 127 |
+
assert result['reason_code'] == 'inconsistent_body_swing_directions'
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def test_returning_to_setup_is_not_counted_as_another_forward_swing():
|
| 131 |
+
p, _t, _ = swing()
|
| 132 |
+
repeated = np.concatenate([p, p[::-1], p])
|
| 133 |
+
result = run(repeated, np.arange(len(repeated))/30)
|
| 134 |
+
assert result['status'] == 'estimated', result
|
| 135 |
+
accepted = [row for row in result['candidates'] if row['accepted']]
|
| 136 |
+
assert len(accepted) == 2
|
| 137 |
+
assert all(not len(p) <= row['peak_frame'] < 2*len(p) for row in accepted)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_instant_pose_jump_is_not_a_swing():
|
| 141 |
+
p, t, _ = swing()
|
| 142 |
+
p[:45] = p[0]
|
| 143 |
+
p[45:] = p[-1]
|
| 144 |
+
assert run(p, t)['status'] == 'unknown'
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def test_missing_vertical_and_camera_movement_are_explicit():
|
| 148 |
+
p, t, _ = swing()
|
| 149 |
+
assert run(p, t, options=MotionInput())['reason_code'] == 'automatic_up_unavailable'
|
| 150 |
+
opts = MotionInput(up_vector=[0, -1, 0], up_source='Test', camera_stability='moving')
|
| 151 |
+
assert run(p, t, options=opts)['reason_code'] == 'camera_moving'
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@pytest.fixture
|
| 155 |
+
def swing_video(tmp_path):
|
| 156 |
+
p, _, _ = swing()
|
| 157 |
+
path = tmp_path/'swing.mp4'
|
| 158 |
+
# Blank scene: a visible plate cannot be contributing any evidence.
|
| 159 |
+
with av.open(str(path), 'w') as output:
|
| 160 |
+
stream = output.add_stream('libx264', rate=30)
|
| 161 |
+
stream.width, stream.height, stream.pix_fmt = 640, 480, 'yuv420p'
|
| 162 |
+
for _ in p:
|
| 163 |
+
for packet in stream.encode(av.VideoFrame.from_ndarray(np.zeros((480, 640, 3), np.uint8), format='bgr24')):
|
| 164 |
+
output.mux(packet)
|
| 165 |
+
for packet in stream.encode():
|
| 166 |
+
output.mux(packet)
|
| 167 |
+
return path, p
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
@pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
|
| 171 |
+
def test_both_exports_apply_body_direction_and_reproduce_measurements(tmp_path, swing_video, model, capsys):
|
| 172 |
+
video, p = swing_video
|
| 173 |
+
options = MotionInput(model=model, annotated_videos=False, camera_stability='fixed_verified',
|
| 174 |
+
single_swing=True, timing={'kind':'unretimed', 'source':'Fixture clock'})
|
| 175 |
+
capture = ingest(video, options.metadata())
|
| 176 |
+
automatic_up = {'status': 'estimated', 'reliable': True, 'up_vector': [0, -1, 0], 'up_source': 'Fixture provider',
|
| 177 |
+
'coordinate_frame': 'upright_camera_x_right_y_down_z_away'}
|
| 178 |
+
manifest = export_motion(tmp_path, video, capture, raw_pose(p), options, {'name':'synthetic'},
|
| 179 |
+
{'analysis_id':'body-direction', 'analysis_revision':1}, up_reference=automatic_up)
|
| 180 |
+
ref = manifest.coordinates['pitcher_estimation']
|
| 181 |
+
assert ref['status'] == 'estimated' and ref['method'] == METHOD, ref
|
| 182 |
+
assert manifest.coordinates['frame'] == 'estimated_batting_axes'
|
| 183 |
+
assert manifest.coordinates['axes']['x'] == 'estimated_hitting_direction'
|
| 184 |
+
assert manifest.pipeline['inputs']['pitcher_vector'] is None
|
| 185 |
+
assert manifest.pipeline['inputs']['handedness'] is None
|
| 186 |
+
assert manifest.pipeline['calculation_inputs']['pitcher_vector'] == ref['pitcher_vector']
|
| 187 |
+
report = json.loads((tmp_path/'measurements.json').read_text())
|
| 188 |
+
assert report['pitcher_reference'] == ref
|
| 189 |
+
flags = [flag for metric in report['summaries'] for flag in metric['quality_flags']]
|
| 190 |
+
assert 'pitcher_reference_estimated_from_body_motion' in flags
|
| 191 |
+
assert 'target_alignment_unverified' in flags
|
| 192 |
+
assert 'pitcher_reference_estimated_from_home_plate' not in flags
|
| 193 |
+
reproduced = reproduce_measurements(manifest, tmp_path/'motion.jsonl')
|
| 194 |
+
expected = {(s.rep, m.key): m.value for group in reproduced.values() for s in group for m in s.measurements}
|
| 195 |
+
for row in report['summaries']:
|
| 196 |
+
value = expected[row['rep'], row['metric_id']]
|
| 197 |
+
assert row['value'] == pytest.approx(value) if value is not None else row['value'] is None
|
| 198 |
+
from baseball_batting.job_terminal import JobTerminal
|
| 199 |
+
JobTerminal('body-direction', tmp_path).finish('completed')
|
| 200 |
+
output = capsys.readouterr().out
|
| 201 |
+
assert 'pitcher=estimated vector=' in output
|
| 202 |
+
assert 'method=automatic_body_swing_direction_v1' in output
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_explicit_direction_still_wins(tmp_path, swing_video, monkeypatch):
|
| 206 |
+
video, p = swing_video
|
| 207 |
+
def unexpected(*args, **kwargs):
|
| 208 |
+
raise AssertionError('Automatic estimator called despite explicit direction')
|
| 209 |
+
monkeypatch.setattr('baseball_batting.body_pitcher_direction.estimate', unexpected)
|
| 210 |
+
opts = MotionInput(annotated_videos=False, up_vector=[0, -1, 0], up_source='Test',
|
| 211 |
+
pitcher_vector=[0, 0, 1], pitcher_source='Reviewed direction')
|
| 212 |
+
manifest = export_motion(tmp_path, video, ingest(video, opts.metadata()), raw_pose(p), opts,
|
| 213 |
+
{'name':'fixture'}, {'analysis_id':'manual', 'analysis_revision':1})
|
| 214 |
+
assert manifest.coordinates['pitcher_vector'] == [0, 0, 1]
|
| 215 |
+
assert manifest.coordinates['pitcher_estimation']['status'] == 'provided'
|
tests/test_motion_player_api.py
CHANGED
|
@@ -45,7 +45,11 @@ def test_motion_upload_auth_readiness_validation_queue_and_cancel(tmp_path,video
|
|
| 45 |
assert not job.exists()
|
| 46 |
assert client.get('/v1/motion-analyses/output-schema',headers=AUTH).status_code==200
|
| 47 |
assert client.get('/v1/motion-analyses/input-schema').status_code==401
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
monkeypatch.setattr(module,'configured_record',lambda:None)
|
| 50 |
assert client.post('/v1/motion-analyses',files=files,headers=AUTH).status_code==503
|
| 51 |
|
|
|
|
| 45 |
assert not job.exists()
|
| 46 |
assert client.get('/v1/motion-analyses/output-schema',headers=AUTH).status_code==200
|
| 47 |
assert client.get('/v1/motion-analyses/input-schema').status_code==401
|
| 48 |
+
capabilities=client.get('/v1/motion-analyses/capabilities',headers=AUTH).json()
|
| 49 |
+
assert capabilities['joint_count']==20
|
| 50 |
+
direction=capabilities['automatic_pitcher_direction']
|
| 51 |
+
assert direction['method']=='automatic_body_swing_direction_v1'
|
| 52 |
+
assert not direction['requires_home_plate'] and not direction['requires_user_direction_input']
|
| 53 |
monkeypatch.setattr(module,'configured_record',lambda:None)
|
| 54 |
assert client.post('/v1/motion-analyses',files=files,headers=AUTH).status_code==503
|
| 55 |
|