Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
b3f7d8d
1
Parent(s): 77fa8e1
Automated Deploy: 7f206c4760f869403ac700010babb8a26ed9fd07
Browse files- .dockerignore +4 -0
- Dockerfile +21 -0
- baseball_batting/api.py +1 -1
- baseball_batting/gvhmr_adapter.py +69 -0
- baseball_batting/gvhmr_pose_worker.py +207 -0
- baseball_batting/gvhmr_runtime.py +30 -0
- baseball_batting/gvhmr_worker.py +38 -0
- baseball_batting/motion_adapters.py +72 -0
- baseball_batting/motion_api.py +26 -8
- baseball_batting/motion_contract.py +10 -0
- baseball_batting/motion_export.py +43 -19
- baseball_batting/motion_worker.py +11 -7
- baseball_batting/sam_motion.py +15 -6
- docs/GVHMR_SETUP.md +73 -0
- docs/MOTION_PLAYER_API.md +58 -5
- docs/MOTION_REQUIREMENTS_AUDIT.md +27 -0
- docs/motion-input.schema.json +54 -0
- requirements-gvhmr.txt +38 -0
- tests/test_gvhmr_motion.py +170 -0
- tools/check_gvhmr_runtime.py +19 -0
- tools/prepare_gvhmr_assets.py +71 -0
- tools/register_gvhmr_api_worker.py +26 -0
- tools/start_api.py +6 -0
.dockerignore
CHANGED
|
@@ -6,6 +6,7 @@
|
|
| 6 |
!requirements-api-gpu.txt
|
| 7 |
!requirements-tracking-export.txt
|
| 8 |
!requirements-sam.txt
|
|
|
|
| 9 |
!requirements-coach.txt
|
| 10 |
!pyproject.toml
|
| 11 |
!baseball_batting/
|
|
@@ -27,6 +28,9 @@
|
|
| 27 |
!tools/register_sam_api_worker.py
|
| 28 |
!tools/__init__.py
|
| 29 |
!tools/prepare_sam_assets.py
|
|
|
|
|
|
|
|
|
|
| 30 |
!tools/start_api.py
|
| 31 |
!docs/
|
| 32 |
!docs/api-result.schema.json
|
|
|
|
| 6 |
!requirements-api-gpu.txt
|
| 7 |
!requirements-tracking-export.txt
|
| 8 |
!requirements-sam.txt
|
| 9 |
+
!requirements-gvhmr.txt
|
| 10 |
!requirements-coach.txt
|
| 11 |
!pyproject.toml
|
| 12 |
!baseball_batting/
|
|
|
|
| 28 |
!tools/register_sam_api_worker.py
|
| 29 |
!tools/__init__.py
|
| 30 |
!tools/prepare_sam_assets.py
|
| 31 |
+
!tools/prepare_gvhmr_assets.py
|
| 32 |
+
!tools/register_gvhmr_api_worker.py
|
| 33 |
+
!tools/check_gvhmr_runtime.py
|
| 34 |
!tools/start_api.py
|
| 35 |
!docs/
|
| 36 |
!docs/api-result.schema.json
|
Dockerfile
CHANGED
|
@@ -25,12 +25,29 @@ RUN python -m venv /opt/sam-runtime \
|
|
| 25 |
&& git -C /opt/sam-source fetch --depth=1 origin b5c765a0d89d789985e186d396315e7590887b94 \
|
| 26 |
&& git -C /opt/sam-source checkout --detach b5c765a0d89d789985e186d396315e7590887b94
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
FROM python:3.11-slim-bookworm
|
| 29 |
|
| 30 |
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
|
| 31 |
PIP_NO_CACHE_DIR=1 BASEBALL_MODEL_ROOT=/opt/models BASEBALL_DATA_ROOT=/data \
|
| 32 |
NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility \
|
| 33 |
BASEBALL_SAM_WORKER_RECORD=/data/sam-api-worker.json BASEBALL_SAM_SOURCE=/opt/sam-source \
|
|
|
|
| 34 |
HF_HUB_DOWNLOAD_TIMEOUT=60
|
| 35 |
WORKDIR /app
|
| 36 |
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libgomp1 tini git libgl1 libegl1 libglib2.0-0 \
|
|
@@ -47,6 +64,10 @@ COPY configs ./configs
|
|
| 47 |
COPY tools/setup_api_models.py tools/setup_full_worker.py tools/setup_sam_api_worker.py tools/register_sam_api_worker.py ./tools/
|
| 48 |
COPY tools/__init__.py ./tools/__init__.py
|
| 49 |
COPY tools/prepare_sam_assets.py tools/start_api.py ./tools/
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
COPY --from=sam-runtime /opt/sam-runtime /opt/sam-runtime
|
| 51 |
COPY --chown=1000:1000 --from=sam-runtime /opt/sam-source /opt/sam-source
|
| 52 |
COPY docs/api-result.schema.json ./docs/api-result.schema.json
|
|
|
|
| 25 |
&& git -C /opt/sam-source fetch --depth=1 origin b5c765a0d89d789985e186d396315e7590887b94 \
|
| 26 |
&& git -C /opt/sam-source checkout --detach b5c765a0d89d789985e186d396315e7590887b94
|
| 27 |
|
| 28 |
+
FROM python:3.11-slim-bookworm AS gvhmr-runtime
|
| 29 |
+
ENV UV_PYTHON_INSTALL_DIR=/opt/gvhmr-python UV_LINK_MODE=copy
|
| 30 |
+
RUN apt-get update && apt-get install -y --no-install-recommends git libgl1 libglib2.0-0 \
|
| 31 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 32 |
+
COPY requirements-gvhmr.txt /tmp/requirements-gvhmr.txt
|
| 33 |
+
COPY tools/check_gvhmr_runtime.py /tmp/check_gvhmr_runtime.py
|
| 34 |
+
RUN python -m pip install --no-cache-dir uv==0.9.10 \
|
| 35 |
+
&& python -m uv python install 3.10 \
|
| 36 |
+
&& python -m uv venv --python 3.10 --seed /opt/gvhmr-runtime \
|
| 37 |
+
&& /opt/gvhmr-runtime/bin/python -m pip install --no-cache-dir -r /tmp/requirements-gvhmr.txt \
|
| 38 |
+
&& git init /opt/gvhmr-source \
|
| 39 |
+
&& git -C /opt/gvhmr-source remote add origin https://github.com/zju3dv/GVHMR.git \
|
| 40 |
+
&& git -C /opt/gvhmr-source fetch --depth=1 origin ee960bb6e2ea2d381aa97f08e9b71ef320b624b1 \
|
| 41 |
+
&& git -C /opt/gvhmr-source checkout --detach ee960bb6e2ea2d381aa97f08e9b71ef320b624b1 \
|
| 42 |
+
&& PYTHONPATH=/opt/gvhmr-source /opt/gvhmr-runtime/bin/python /tmp/check_gvhmr_runtime.py
|
| 43 |
+
|
| 44 |
FROM python:3.11-slim-bookworm
|
| 45 |
|
| 46 |
ENV PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 MPLBACKEND=Agg \
|
| 47 |
PIP_NO_CACHE_DIR=1 BASEBALL_MODEL_ROOT=/opt/models BASEBALL_DATA_ROOT=/data \
|
| 48 |
NVIDIA_VISIBLE_DEVICES=all NVIDIA_DRIVER_CAPABILITIES=compute,utility \
|
| 49 |
BASEBALL_SAM_WORKER_RECORD=/data/sam-api-worker.json BASEBALL_SAM_SOURCE=/opt/sam-source \
|
| 50 |
+
BASEBALL_GVHMR_WORKER_RECORD=/data/gvhmr-api-worker.json BASEBALL_GVHMR_SOURCE=/opt/gvhmr-source \
|
| 51 |
HF_HUB_DOWNLOAD_TIMEOUT=60
|
| 52 |
WORKDIR /app
|
| 53 |
RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg libgomp1 tini git libgl1 libegl1 libglib2.0-0 \
|
|
|
|
| 64 |
COPY tools/setup_api_models.py tools/setup_full_worker.py tools/setup_sam_api_worker.py tools/register_sam_api_worker.py ./tools/
|
| 65 |
COPY tools/__init__.py ./tools/__init__.py
|
| 66 |
COPY tools/prepare_sam_assets.py tools/start_api.py ./tools/
|
| 67 |
+
COPY tools/prepare_gvhmr_assets.py tools/register_gvhmr_api_worker.py tools/check_gvhmr_runtime.py ./tools/
|
| 68 |
+
COPY --from=gvhmr-runtime /opt/gvhmr-python /opt/gvhmr-python
|
| 69 |
+
COPY --from=gvhmr-runtime /opt/gvhmr-runtime /opt/gvhmr-runtime
|
| 70 |
+
COPY --chown=1000:1000 --from=gvhmr-runtime /opt/gvhmr-source /opt/gvhmr-source
|
| 71 |
COPY --from=sam-runtime /opt/sam-runtime /opt/sam-runtime
|
| 72 |
COPY --chown=1000:1000 --from=sam-runtime /opt/sam-source /opt/sam-source
|
| 73 |
COPY docs/api-result.schema.json ./docs/api-result.schema.json
|
baseball_batting/api.py
CHANGED
|
@@ -78,7 +78,7 @@ def create_app(settings=None, service=None):
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
-
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
|
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
+
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.11.0", lifespan=lifespan,
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
baseball_batting/gvhmr_adapter.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Numerical parts of the GVHMR adapter, independently testable without CUDA."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from scipy.spatial.transform import Rotation, Slerp
|
| 4 |
+
from .sam_motion import MHR, segments
|
| 5 |
+
from .motion_adapters import smplx_to_calculation
|
| 6 |
+
from .geometry import project
|
| 7 |
+
|
| 8 |
+
MODEL_FPS=30
|
| 9 |
+
COCO={'left_ear':3,'right_ear':4,'left_shoulder':5,'right_shoulder':6,
|
| 10 |
+
'left_elbow':7,'right_elbow':8,'left_wrist':9,'right_wrist':10,
|
| 11 |
+
'left_hip':11,'right_hip':12,'left_knee':13,'right_knee':14,'left_ankle':15,'right_ankle':16}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def uniform_grid(times):
|
| 15 |
+
times=np.asarray(times,float)
|
| 16 |
+
if len(times)<2 or not np.isfinite(times).all() or np.any(np.diff(times)<=0):
|
| 17 |
+
raise ValueError('GVHMR timestamps must increase strictly')
|
| 18 |
+
# The final model tick can duplicate the last observation, but it never
|
| 19 |
+
# changes a source timestamp or extrapolates an exported source frame.
|
| 20 |
+
return times[0]+np.arange(int(np.ceil((times[-1]-times[0])*MODEL_FPS))+1)/MODEL_FPS
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def resample_vectors(values,times,target):
|
| 24 |
+
values=np.asarray(values,float); times=np.asarray(times,float); target=np.asarray(target,float)
|
| 25 |
+
flat=values.reshape(len(values),-1)
|
| 26 |
+
return np.stack([np.interp(target,times,column) for column in flat.T],axis=-1).reshape((len(target),)+values.shape[1:])
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def resample_rotations(values,times,target):
|
| 30 |
+
"""SO(3) interpolation, never linear interpolation of axis-angle rotations."""
|
| 31 |
+
values=np.asarray(values,float); flat=values.reshape(len(values),-1,3)
|
| 32 |
+
target=np.clip(target,times[0],times[-1])
|
| 33 |
+
result=np.stack([Slerp(times,Rotation.from_rotvec(flat[:,j]))(target).as_rotvec()
|
| 34 |
+
for j in range(flat.shape[1])],axis=1)
|
| 35 |
+
return result.reshape((len(target),)+values.shape[1:])
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sequence_windows(valid,times,max_gap,max_frames,context):
|
| 39 |
+
"""Never run temporal inference through missing identity or a source clock gap."""
|
| 40 |
+
for run in segments(np.asarray(valid,bool),np.asarray(times,float),max_gap):
|
| 41 |
+
if len(run)<4:continue
|
| 42 |
+
grid=uniform_grid(np.asarray(times)[run]); core=max_frames-2*context
|
| 43 |
+
if core<1:raise ValueError('GVHMR context exceeds sequence capacity')
|
| 44 |
+
for start in range(0,len(grid),core):
|
| 45 |
+
end=min(len(grid),start+core)
|
| 46 |
+
yield run,grid,max(0,start-context),min(len(grid),end+context),start,end
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def native_prediction(joints,joint_names,translations,intrinsics,image_size,kp2d,boxes,settings):
|
| 50 |
+
"""SMPL-X incam output, with root translation applied exactly once."""
|
| 51 |
+
points=smplx_to_calculation(joints,joint_names)
|
| 52 |
+
cam=np.asarray(translations,float); ks=np.asarray(intrinsics,float)
|
| 53 |
+
if cam.shape!=(len(points),3) or ks.shape!=(len(points),3,3):raise ValueError('GVHMR camera shape differs from joints')
|
| 54 |
+
xy=np.stack([project(p+c,k) for p,c,k in zip(points,cam,ks)])
|
| 55 |
+
usable=np.isfinite(points).all(axis=-1)&np.isfinite(xy).all(axis=-1)&((points[:,:,2]+cam[:,None,2])>1e-8)
|
| 56 |
+
for name,coco in COCO.items():
|
| 57 |
+
index=MHR[name];observed=kp2d[:,coco]
|
| 58 |
+
diagonal=np.linalg.norm(boxes[:,2:]-boxes[:,:2],axis=-1)
|
| 59 |
+
residual=np.linalg.norm(xy[:,index]-observed[:,:2],axis=-1)
|
| 60 |
+
usable[:,index]&=(np.isfinite(observed).all(axis=-1)&(observed[:,2]>=settings['minimum_keypoint_score'])&
|
| 61 |
+
(residual<=settings['maximum_reprojection_box_fraction']*diagonal))
|
| 62 |
+
# Foot surface points have no COCO observation; their visibility depends on
|
| 63 |
+
# the ankle. They remain explicitly derived model landmarks, not observations.
|
| 64 |
+
for side in ('left','right'):
|
| 65 |
+
for part in ('big_toe','small_toe','heel'):
|
| 66 |
+
usable[:,MHR[side+'_'+part]]&=usable[:,MHR[side+'_ankle']]
|
| 67 |
+
valid=usable[:,MHR['left_hip']]&usable[:,MHR['right_hip']]
|
| 68 |
+
return {'points_body':points,'camera_translation':cam,'projection':xy,'intrinsics':ks,
|
| 69 |
+
'projection_valid':valid,'joint_usable':usable,'image_size':np.asarray(image_size)}
|
baseball_batting/gvhmr_pose_worker.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pinned upstream GVHMR inference, isolated from SAM/ONNX dependencies.
|
| 2 |
+
|
| 3 |
+
No upstream demo rendering or 30-FPS video rewrite. Condition on source frames,
|
| 4 |
+
run the temporal model on an explicit 30-Hz grid, and evaluate SMPL-X at every
|
| 5 |
+
original source timestamp. Native parameters stay private for audit/reprocessing.
|
| 6 |
+
"""
|
| 7 |
+
import argparse
|
| 8 |
+
import gc
|
| 9 |
+
import importlib
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
import subprocess
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
import numpy as np
|
| 16 |
+
from .storage import atomic_json,read_json,sha256_file
|
| 17 |
+
from .ingest import iter_frames
|
| 18 |
+
from .gvhmr_adapter import (MODEL_FPS,sequence_windows,resample_vectors,resample_rotations,native_prediction)
|
| 19 |
+
from .motion_adapters import GVHMR_REVISION
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def camera_rotation(previous,image,old_box,box,k):
|
| 23 |
+
"""Background-only two-view rotation; unresolved pairs remain unavailable."""
|
| 24 |
+
import cv2
|
| 25 |
+
if previous is None:return np.eye(3),True
|
| 26 |
+
scale=min(1.,640/image.shape[1]);w=round(image.shape[1]*scale);h=round(image.shape[0]*scale)
|
| 27 |
+
def features(frame,region):
|
| 28 |
+
gray=cv2.cvtColor(cv2.resize(frame,(w,h)),cv2.COLOR_BGR2GRAY)
|
| 29 |
+
mask=np.full((h,w),255,np.uint8)
|
| 30 |
+
if region is not None:
|
| 31 |
+
x1,y1,x2,y2=np.rint(np.asarray(region)*scale).astype(int)
|
| 32 |
+
cv2.rectangle(mask,(max(0,x1-8),max(0,y1-8)),(min(w,x2+8),min(h,y2+8)),0,-1)
|
| 33 |
+
return cv2.SIFT_create(nfeatures=1000).detectAndCompute(gray,mask)
|
| 34 |
+
a,da=features(previous,old_box);b,db=features(image,box)
|
| 35 |
+
if da is None or db is None:return np.eye(3),False
|
| 36 |
+
pairs=cv2.BFMatcher().knnMatch(da,db,k=2)
|
| 37 |
+
matches=[m for pair in pairs if len(pair)==2 for m,n in [pair] if m.distance<.75*n.distance]
|
| 38 |
+
if len(matches)<12:return np.eye(3),False
|
| 39 |
+
p=np.float32([a[m.queryIdx].pt for m in matches]);q=np.float32([b[m.trainIdx].pt for m in matches])
|
| 40 |
+
if np.median(np.linalg.norm(p-q,axis=-1))<.5:return np.eye(3),True
|
| 41 |
+
intrinsic=np.asarray(k).copy();intrinsic[:2]*=scale
|
| 42 |
+
essential,mask=cv2.findEssentialMat(p,q,intrinsic,method=cv2.RANSAC,prob=.999,threshold=1.)
|
| 43 |
+
if essential is None or essential.shape!=(3,3):return np.eye(3),False
|
| 44 |
+
count,rotation,_,_=cv2.recoverPose(essential,p,q,intrinsic,mask=mask)
|
| 45 |
+
return rotation,bool(count>=8 and np.isfinite(rotation).all())
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run(request):
|
| 49 |
+
started=time.monotonic();record=read_json(request['worker_record'])
|
| 50 |
+
repo=Path(record['gvhmr_repo']).resolve()
|
| 51 |
+
revision=subprocess.check_output(['git','-C',str(repo),'rev-parse','HEAD'],text=True).strip()
|
| 52 |
+
if revision!=GVHMR_REVISION:raise ValueError('GVHMR source differs from pinned adapter')
|
| 53 |
+
keys=('gvhmr_checkpoint','hmr2_checkpoint','vitpose_checkpoint','smplx_model')
|
| 54 |
+
hashes={k:sha256_file(record[k]) for k in keys}
|
| 55 |
+
if hashes!=record['artifact_hashes']:raise ValueError('GVHMR assets differ from recorded checksums')
|
| 56 |
+
# Upstream resolves some resources relative to its project root/CWD.
|
| 57 |
+
os.chdir(repo);sys.path.insert(0,str(repo))
|
| 58 |
+
import torch
|
| 59 |
+
if not torch.cuda.is_available():raise RuntimeError('GVHMR requires CUDA')
|
| 60 |
+
torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False
|
| 61 |
+
from hmr4d.network.hmr2.utils.preproc import crop_and_resize,IMAGE_MEAN,IMAGE_STD
|
| 62 |
+
from hmr4d.utils.geo.hmr_cam import get_bbx_xys_from_xyxy,estimate_K
|
| 63 |
+
from hmr4d.utils.geo_transform import compute_cam_angvel
|
| 64 |
+
from hmr4d.utils.preproc.vitpose import VitPoseExtractor
|
| 65 |
+
from hmr4d.utils.preproc.vitfeat_extractor import Extractor
|
| 66 |
+
destination=Path(request['output']);n=request['frame_count'];w,h=request['image_size']
|
| 67 |
+
settings=request['settings'];batch=settings['batch_size'];times=np.asarray(request['times'],float)
|
| 68 |
+
if times.shape!=(n,) or not np.isfinite(times).all() or np.any(np.diff(times)<=0):raise ValueError('Invalid GVHMR source clock')
|
| 69 |
+
ks=np.repeat((np.asarray(request['intrinsics'],float) if request['intrinsics'] is not None else estimate_K(w,h).numpy())[None],n,axis=0)
|
| 70 |
+
boxes=np.array([box if box is not None else [np.nan]*4 for box in request['boxes']],float)
|
| 71 |
+
valid=np.isfinite(boxes).all(axis=-1);safe_boxes=np.where(valid[:,None],boxes,[0,0,w,h])
|
| 72 |
+
bbx=get_bbx_xys_from_xyxy(torch.tensor(safe_boxes,dtype=torch.float32),base_enlarge=1.2).float()
|
| 73 |
+
cache=destination.with_name('gvhmr-crops-private.npy')
|
| 74 |
+
crops=np.lib.format.open_memmap(cache,mode='w+',dtype=np.uint8,shape=(n,256,256,3))
|
| 75 |
+
rotations=np.repeat(np.eye(3)[None],n,axis=0);vo_valid=np.ones(n,bool);previous=None;old_box=None;decoded=0
|
| 76 |
+
def progress(stage,done,total=n):
|
| 77 |
+
atomic_json(request['progress_path'],{'stage':stage,'completed_frames':int(done),'total_frames':int(total),
|
| 78 |
+
'elapsed_s':round(time.monotonic()-started,2)})
|
| 79 |
+
try:
|
| 80 |
+
for i,_,_,image in iter_frames(request['video'],request['rotation']):
|
| 81 |
+
if i>=n:raise ValueError('GVHMR source changed after ingest')
|
| 82 |
+
if valid[i]:
|
| 83 |
+
crop,_=crop_and_resize(image[...,::-1].copy(),bbx[i,:2].numpy(),float(bbx[i,2]),256,enlarge_ratio=1.)
|
| 84 |
+
crops[i]=crop
|
| 85 |
+
else:crops[i]=0
|
| 86 |
+
if not request['static_camera']:
|
| 87 |
+
delta,vo_valid[i]=camera_rotation(previous,image,old_box,request['boxes'][i],ks[i])
|
| 88 |
+
rotations[i]=delta@(rotations[i-1] if i else np.eye(3))
|
| 89 |
+
previous=image;old_box=request['boxes'][i];decoded=i+1
|
| 90 |
+
if i%32==0:progress('gvhmr_source_crops_and_camera',i+1)
|
| 91 |
+
if decoded!=n:raise ValueError('GVHMR decoded frame count differs from source')
|
| 92 |
+
crops.flush();del previous
|
| 93 |
+
valid&=vo_valid
|
| 94 |
+
kp=np.full((n,17,3),np.nan,np.float32);features=np.full((n,1024),np.nan,np.float32)
|
| 95 |
+
ids=np.flatnonzero(valid)
|
| 96 |
+
def normalized(indices):
|
| 97 |
+
array=torch.from_numpy(np.array(crops[indices],copy=True)).float()
|
| 98 |
+
return ((array/255.-IMAGE_MEAN)/IMAGE_STD).permute(0,3,1,2)
|
| 99 |
+
with torch.inference_mode():
|
| 100 |
+
pose=VitPoseExtractor(tqdm_leave=False)
|
| 101 |
+
for start in range(0,len(ids),batch):
|
| 102 |
+
take=ids[start:start+batch]
|
| 103 |
+
kp[take]=pose.extract(normalized(take),bbx[take]).cpu().numpy()
|
| 104 |
+
progress('gvhmr_vitpose',min(start+batch,len(ids)),len(ids))
|
| 105 |
+
del pose;gc.collect();torch.cuda.empty_cache()
|
| 106 |
+
extractor=Extractor(tqdm_leave=False)
|
| 107 |
+
for start in range(0,len(ids),batch):
|
| 108 |
+
take=ids[start:start+batch]
|
| 109 |
+
features[take]=extractor.extract_video_features(normalized(take),bbx[take]).cpu().numpy()
|
| 110 |
+
progress('gvhmr_image_features',min(start+batch,len(ids)),len(ids))
|
| 111 |
+
del extractor;gc.collect();torch.cuda.empty_cache()
|
| 112 |
+
# Register inference configurations only, without upstream training datasets/renderers.
|
| 113 |
+
for module in ('hmr4d.network.gvhmr.relative_transformer','hmr4d.model.gvhmr.utils.endecoder',
|
| 114 |
+
'hmr4d.model.gvhmr.gvhmr_pl_demo'):importlib.import_module(module)
|
| 115 |
+
from hydra import initialize_config_module,compose
|
| 116 |
+
from hydra.utils import instantiate
|
| 117 |
+
with initialize_config_module(version_base='1.3',config_module='hmr4d.configs'):
|
| 118 |
+
cfg=compose(config_name='demo')
|
| 119 |
+
model=instantiate(cfg.model,_recursive_=False)
|
| 120 |
+
state=torch.load(record['gvhmr_checkpoint'],map_location='cpu')['state_dict']
|
| 121 |
+
missing,unexpected=model.load_state_dict(state,strict=False)
|
| 122 |
+
# Derived SMPL-X buffers are not learned checkpoint parameters.
|
| 123 |
+
learned=set(dict(model.named_parameters()))
|
| 124 |
+
if learned.intersection(missing):raise ValueError('GVHMR checkpoint is missing learned parameters')
|
| 125 |
+
del state;model=model.eval().cuda()
|
| 126 |
+
params={key:np.full((n,size),np.nan,np.float32) for key,size in
|
| 127 |
+
[('body_pose',63),('global_orient',3),('transl',3),('betas',10)]}
|
| 128 |
+
sequence_ids=np.full(n,-1,int);resampled=np.zeros(n,bool);windows=[]
|
| 129 |
+
serial=0
|
| 130 |
+
for run,grid,left,right,core_start,core_end in sequence_windows(valid,times,request['max_gap_s'],
|
| 131 |
+
settings['max_sequence_frames'],settings['context_frames']):
|
| 132 |
+
t=times[run];grid_part=grid[left:right]
|
| 133 |
+
# R_w2c is rotation only; never exported as calibrated world motion.
|
| 134 |
+
from scipy.spatial.transform import Rotation
|
| 135 |
+
rotvec=Rotation.from_matrix(rotations[run]).as_rotvec()
|
| 136 |
+
rg=Rotation.from_rotvec(resample_rotations(rotvec,t,grid_part)).as_matrix()
|
| 137 |
+
data={'length':torch.tensor(len(grid_part)),
|
| 138 |
+
'bbx_xys':torch.tensor(resample_vectors(bbx[run].numpy(),t,grid_part),dtype=torch.float32),
|
| 139 |
+
'kp2d':torch.tensor(resample_vectors(kp[run],t,grid_part),dtype=torch.float32),
|
| 140 |
+
'f_imgseq':torch.tensor(resample_vectors(features[run],t,grid_part),dtype=torch.float32),
|
| 141 |
+
'K_fullimg':torch.tensor(resample_vectors(ks[run],t,grid_part),dtype=torch.float32),
|
| 142 |
+
'cam_angvel':compute_cam_angvel(torch.tensor(rg,dtype=torch.float32))}
|
| 143 |
+
prediction=model.predict(data,static_cam=request['static_camera'])['smpl_params_incam']
|
| 144 |
+
# Every source frame is owned by exactly one core, with context
|
| 145 |
+
# on both sides. Chunk boundaries are exported and filter-marked.
|
| 146 |
+
take=run[(t>=grid[core_start]) & ((t<grid[core_end]) if core_end<len(grid) else (t<=grid[-1]))]
|
| 147 |
+
if not len(take):continue
|
| 148 |
+
serial+=1;sequence_ids[take]=serial
|
| 149 |
+
for key in params:
|
| 150 |
+
values=prediction[key].detach().cpu().numpy()
|
| 151 |
+
operation=resample_rotations if key in ('body_pose','global_orient') else resample_vectors
|
| 152 |
+
params[key][take]=operation(values,grid_part,times[take])
|
| 153 |
+
resampled[take]=np.abs((times[take]-t[0])*MODEL_FPS-np.rint((times[take]-t[0])*MODEL_FPS))>1e-6
|
| 154 |
+
windows.append({'source_start_frame':int(take[0]),'source_end_frame':int(take[-1]),
|
| 155 |
+
'sequence_id':serial,'model_sample_count':len(grid_part),'model_rate_hz':MODEL_FPS,
|
| 156 |
+
'model_time_start_s':float(grid_part[0]),'model_time_end_s':float(grid_part[-1])})
|
| 157 |
+
progress('gvhmr_temporal_inference',int((sequence_ids>=0).sum()))
|
| 158 |
+
del model;gc.collect();torch.cuda.empty_cache()
|
| 159 |
+
predicted=np.flatnonzero(sequence_ids>=0)
|
| 160 |
+
if not len(predicted):raise ValueError('no_usable_motion')
|
| 161 |
+
# A single shape for this tracked athlete. Do not stretch independent limbs.
|
| 162 |
+
beta=np.median(params['betas'][predicted],axis=0);params['betas'][predicted]=beta
|
| 163 |
+
from hmr4d.utils.smplx_utils import make_smplx
|
| 164 |
+
from smplx.joint_names import JOINT_NAMES
|
| 165 |
+
body=make_smplx('supermotion').eval().cuda();native=np.full((n,len(JOINT_NAMES),3),np.nan)
|
| 166 |
+
for start in range(0,len(predicted),batch):
|
| 167 |
+
take=predicted[start:start+batch]
|
| 168 |
+
inputs={key:torch.tensor(value[take],device='cuda') for key,value in params.items() if key!='transl'}
|
| 169 |
+
out=body(**inputs).joints.detach().cpu().numpy()
|
| 170 |
+
# Without face contour, the named prefix has the same joint indices.
|
| 171 |
+
native[take,:out.shape[1]]=out
|
| 172 |
+
progress('gvhmr_anatomical_joints',min(start+batch,len(predicted)),len(predicted))
|
| 173 |
+
del body;gc.collect();torch.cuda.empty_cache()
|
| 174 |
+
raw=native_prediction(native,JOINT_NAMES,params['transl'],ks,[w,h],kp,safe_boxes,settings)
|
| 175 |
+
raw.update(sequence_ids=sequence_ids,temporal_resampled=resampled)
|
| 176 |
+
raw['projection_valid']&=valid&(sequence_ids>=0)
|
| 177 |
+
raw['frame_reasons']=np.array(['camera_motion_input_unresolved' if not vo_valid[i] else
|
| 178 |
+
'insufficient_contiguous_temporal_observations' if sequence_ids[i]<0 and valid[i] else '' for i in range(n)])
|
| 179 |
+
tmp=destination.with_suffix('.tmp.npz');np.savez_compressed(tmp,**raw);tmp.replace(destination)
|
| 180 |
+
np.savez_compressed(destination.with_name('gvhmr-parameters-private.npz'),**params,
|
| 181 |
+
camera_rotations=rotations,camera_rotation_valid=vo_valid,source_keypoints_2d=kp)
|
| 182 |
+
atomic_json(destination.with_suffix('.json'),{'model':{'name':'GVHMR SIGGRAPH Asia 2024 / SMPL-X neutral',
|
| 183 |
+
'source_revision':revision,'artifact_hashes':hashes,'precision':'fp32',
|
| 184 |
+
'score_definition':'No calibrated 3D per-joint scores; null',
|
| 185 |
+
'body_shape':'single median predicted beta vector for the selected athlete',
|
| 186 |
+
'model_cadence_hz':MODEL_FPS,'conditioning_time_basis':'capture' if request['physical_clock_known'] else 'video_only',
|
| 187 |
+
'temporal_resampling':'linear conditioning; SO(3) parameter interpolation to source timestamps; no gap filling',
|
| 188 |
+
'camera_rotation':'declared_static' if request['static_camera'] else 'background_SIFT_essential_rotation_estimated',
|
| 189 |
+
'temporal_windows':windows,'checkpoint_unexpected_key_count':len(unexpected),
|
| 190 |
+
'inference_elapsed_s':round(time.monotonic()-started,3)}})
|
| 191 |
+
finally:
|
| 192 |
+
del crops;cache.unlink(missing_ok=True)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def main():
|
| 196 |
+
parser=argparse.ArgumentParser();parser.add_argument('--request',required=True);args=parser.parse_args()
|
| 197 |
+
request=read_json(args.request)
|
| 198 |
+
try:run(request);return 0
|
| 199 |
+
except Exception as error:
|
| 200 |
+
reason=('gvhmr_gpu_memory_exhausted' if type(error).__name__=='OutOfMemoryError' else
|
| 201 |
+
'gvhmr_dependency_unavailable' if isinstance(error,ImportError) else
|
| 202 |
+
'no_usable_motion' if str(error)=='no_usable_motion' else 'gvhmr_inference_failed')
|
| 203 |
+
atomic_json(Path(request['output']).with_suffix('.error.json'),{'reason_code':reason,'error_type':type(error).__name__})
|
| 204 |
+
print(type(error).__name__+': '+str(error),flush=True);return 1
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__=='__main__':raise SystemExit(main())
|
baseball_batting/gvhmr_runtime.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Read-only GVHMR readiness, independent of the existing SAM runtime."""
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from .storage import read_json
|
| 5 |
+
from .motion_adapters import GVHMR_REVISION
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def configured_record():
|
| 9 |
+
path=os.environ.get('BASEBALL_GVHMR_WORKER_RECORD')
|
| 10 |
+
if not path:return None
|
| 11 |
+
try:
|
| 12 |
+
record=read_json(path)
|
| 13 |
+
keys=('worker_python','gvhmr_repo','gvhmr_checkpoint','hmr2_checkpoint','vitpose_checkpoint','smplx_model')
|
| 14 |
+
if record.get('source_revision')!=GVHMR_REVISION:return None
|
| 15 |
+
if all(Path(record[k]).is_dir() if k=='gvhmr_repo' else Path(record[k]).is_file() for k in keys):return record
|
| 16 |
+
except (OSError,ValueError,KeyError,TypeError):pass
|
| 17 |
+
return None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def public_status():
|
| 21 |
+
if configured_record():return {'configured':True,'inference_verified':False,'status':'configured_requires_cuda_inference'}
|
| 22 |
+
path=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'))/'gvhmr-setup-status.json'
|
| 23 |
+
try:
|
| 24 |
+
state=read_json(path)
|
| 25 |
+
reason=state.get('reason_code','gvhmr_not_configured')
|
| 26 |
+
return {'configured':False,'status':state.get('status','unavailable'),'reason_code':reason,
|
| 27 |
+
'setup_guide':'docs/GVHMR_SETUP.md','body_model_provider':'https://smpl-x.is.tue.mpg.de/'}
|
| 28 |
+
except (OSError,ValueError):
|
| 29 |
+
return {'configured':False,'status':'unavailable','reason_code':'gvhmr_not_configured',
|
| 30 |
+
'setup_guide':'docs/GVHMR_SETUP.md','body_model_provider':'https://smpl-x.is.tue.mpg.de/'}
|
baseball_batting/gvhmr_worker.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Queue-side GVHMR launch; GPU dependencies stay in their own interpreter."""
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import subprocess
|
| 5 |
+
import numpy as np
|
| 6 |
+
from . import gvhmr_runtime
|
| 7 |
+
from .sam_measurement_worker import athlete_boxes
|
| 8 |
+
from .storage import atomic_json,read_json
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def reconstruct_gvhmr(job,video,capture,models,options,progress):
|
| 12 |
+
record=gvhmr_runtime.configured_record()
|
| 13 |
+
if record is None:raise RuntimeError('GVHMR worker is not configured')
|
| 14 |
+
first=capture['frames'][0]
|
| 15 |
+
if any(f['width']!=first['width'] or f['height']!=first['height'] for f in capture['frames']):
|
| 16 |
+
raise ValueError('Changing image dimensions require separate recording segments')
|
| 17 |
+
if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
|
| 18 |
+
raise ValueError('Camera principal point is outside upright video')
|
| 19 |
+
boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress,strict_identity=True)
|
| 20 |
+
atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
|
| 21 |
+
c=options.camera
|
| 22 |
+
physical=[f['physical_s'] for f in capture['frames']]
|
| 23 |
+
known=all(t is not None for t in physical)
|
| 24 |
+
times=physical if known else [f['playback_s'] for f in capture['frames']]
|
| 25 |
+
request={'video':str(video.resolve()),'rotation':capture['rotation_degrees'],
|
| 26 |
+
'worker_record':os.environ['BASEBALL_GVHMR_WORKER_RECORD'],'boxes':boxes,
|
| 27 |
+
'times':times,'physical_clock_known':known,'max_gap_s':options.correction.max_gap_s,
|
| 28 |
+
'frame_count':capture['frame_count'],'image_size':[first['width'],first['height']],
|
| 29 |
+
'intrinsics':[[c.fx,0,c.cx],[0,c.fy,c.cy],[0,0,1]] if c else None,
|
| 30 |
+
'static_camera':options.camera_stability=='fixed_verified','settings':options.gvhmr.model_dump(),
|
| 31 |
+
'progress_path':str(job/'progress.json'),'output':str(job/'gvhmr-raw-private.npz')}
|
| 32 |
+
atomic_json(job/'gvhmr-request-private.json',request)
|
| 33 |
+
env=dict(os.environ,MPLBACKEND='Agg',HF_HUB_OFFLINE='1',TRANSFORMERS_OFFLINE='1')
|
| 34 |
+
for secret in ('BASEBALL_API_KEY','GOOGLE_API_KEY','HF_TOKEN','HUGGING_FACE_HUB_TOKEN'):env.pop(secret,None)
|
| 35 |
+
progress('loading_gvhmr',0,capture['frame_count'])
|
| 36 |
+
subprocess.run([record['worker_python'],'-m','baseball_batting.gvhmr_pose_worker','--request',str(job/'gvhmr-request-private.json')],env=env,check=True)
|
| 37 |
+
with np.load(job/'gvhmr-raw-private.npz',allow_pickle=False) as archive:raw=dict(archive)
|
| 38 |
+
return raw,read_json(job/'gvhmr-raw-private.json')['model']
|
baseball_batting/motion_adapters.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model-specific anatomy at the boundary of the shared motion exporter.
|
| 2 |
+
|
| 3 |
+
The legacy calculator has a sparse 70-slot layout. It is an internal calculation
|
| 4 |
+
layout, NOT a claim that SMPL-X is MHR70. Public joints always use canonical names
|
| 5 |
+
and declare their actual source and measurement-definition revision.
|
| 6 |
+
"""
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import numpy as np
|
| 9 |
+
from .sam_motion import MHR, BONES
|
| 10 |
+
from .storage import sha256_file
|
| 11 |
+
|
| 12 |
+
GVHMR_REVISION = 'ee960bb6e2ea2d381aa97f08e9b71ef320b624b1'
|
| 13 |
+
SMPLX_MAP = {'left_ear':59, 'right_ear':58, 'left_shoulder':16, 'right_shoulder':17,
|
| 14 |
+
'left_elbow':18, 'right_elbow':19, 'left_hip':1, 'right_hip':2,
|
| 15 |
+
'left_knee':4, 'right_knee':5, 'left_ankle':7, 'right_ankle':8,
|
| 16 |
+
'left_big_toe':60, 'left_small_toe':61, 'left_heel':62,
|
| 17 |
+
'right_big_toe':63, 'right_small_toe':64, 'right_heel':65,
|
| 18 |
+
'right_wrist':21, 'left_wrist':20}
|
| 19 |
+
SURFACE_LANDMARKS = {name for name in MHR if any(x in name for x in ('ear','toe','heel'))}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def descriptor(model='sam3d'):
|
| 23 |
+
if model not in ('sam3d','gvhmr'): raise ValueError('Unknown reconstruction model')
|
| 24 |
+
sam = model == 'sam3d'
|
| 25 |
+
return {'id':model, 'name':'SAM 3D Body' if sam else 'GVHMR',
|
| 26 |
+
'adapter_version':'sam-mhr70-motion-v1' if sam else 'gvhmr-smplx-motion-v1',
|
| 27 |
+
'definition_version':'batting-corrected-points-v1' if sam else 'batting-corrected-points-smplx-v1',
|
| 28 |
+
'worker_file':'sam_pose_worker.py' if sam else 'gvhmr_pose_worker.py',
|
| 29 |
+
'raw_files':('sam-raw-private.npz','sam-raw-private.json','person-track-private.json') if sam else
|
| 30 |
+
('gvhmr-raw-private.npz','gvhmr-raw-private.json','person-track-private.json'),
|
| 31 |
+
'source_schema':'MHR70' if sam else 'SMPL-X',
|
| 32 |
+
'mapping':MHR if sam else SMPLX_MAP}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def adapter_hash(model):
|
| 36 |
+
item=descriptor(model)
|
| 37 |
+
# Pin both the native extractor and anatomy adapter. SAM's existing hash
|
| 38 |
+
# remains compatible with results written before the model selector existed.
|
| 39 |
+
if model=='sam3d':return sha256_file(Path(__file__).with_name(item['worker_file']))
|
| 40 |
+
from .storage import digest
|
| 41 |
+
return digest({name:sha256_file(Path(__file__).with_name(name)) for name in
|
| 42 |
+
('motion_adapters.py','gvhmr_pose_worker.py','gvhmr_adapter.py','gvhmr_worker.py')})
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def skeleton(model):
|
| 46 |
+
item=descriptor(model); sam=model=='sam3d'; names={v:k for k,v in MHR.items()}
|
| 47 |
+
joints=[]
|
| 48 |
+
for name in MHR:
|
| 49 |
+
surface=not sam and name in SURFACE_LANDMARKS
|
| 50 |
+
definition=('Native '+name.replace('_',' ')+' MHR70 landmark; no mesh-vertex or acromion substitution' if sam else
|
| 51 |
+
'SMPL-X named surface vertex selected by the official vertex-joint selector' if surface else
|
| 52 |
+
'SMPL-X regressed anatomical joint center; model-specific definition, not MHR70')
|
| 53 |
+
joints.append({'name':name,'source_schema':item['source_schema'],'source_index':item['mapping'][name],
|
| 54 |
+
'definition':definition,'derived':surface,
|
| 55 |
+
'derivation':'official_smplx_vertex_joint_selector' if surface else None})
|
| 56 |
+
return {'version':f"{'mhr70' if sam else 'smplx'}-batting-{len(MHR)}-v1",'joint_order':list(MHR),
|
| 57 |
+
'joints':joints,'bones':[[names[a],names[b]] for a,b in BONES],
|
| 58 |
+
'head_center_proxy':'midpoint_of_bilateral_ear_landmarks',
|
| 59 |
+
'hand_motion_proxy':'midpoint_of_bilateral_wrist_landmarks',
|
| 60 |
+
'cross_model_comparability':'different native anatomical definitions; do not pool as identical measurements'}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def smplx_to_calculation(joints, joint_names):
|
| 64 |
+
"""Validate the upstream model mapping before adapting any native prediction."""
|
| 65 |
+
values=np.asarray(joints,float)
|
| 66 |
+
if values.ndim!=3 or values.shape[-1]!=3:raise ValueError('SMPL-X joints must be N x J x 3')
|
| 67 |
+
result=np.full((len(values),70,3),np.nan)
|
| 68 |
+
for name,index in SMPLX_MAP.items():
|
| 69 |
+
if index>=values.shape[1] or index>=len(joint_names) or joint_names[index]!=name:
|
| 70 |
+
raise ValueError('Deployed SMPL-X anatomical mapping differs from the adapter')
|
| 71 |
+
result[:,MHR[name]]=values[:,index]
|
| 72 |
+
return result
|
baseball_batting/motion_api.py
CHANGED
|
@@ -11,6 +11,8 @@ from .motion_contract import MotionInput, MotionManifest, MotionFrame, Projectio
|
|
| 11 |
from .sam_motion import MHR
|
| 12 |
from .api_jobs import QueueFull
|
| 13 |
from .sam_runtime import configured_record, public_status
|
|
|
|
|
|
|
| 14 |
from .storage import atomic_json, read_json, sha256_file
|
| 15 |
from .media import open_verified_media, media_response
|
| 16 |
|
|
@@ -41,9 +43,12 @@ def register(app,service,authenticated):
|
|
| 41 |
if not path.is_relative_to(directory.resolve()):raise HTTPException(500,'Invalid stored artifact path')
|
| 42 |
return path
|
| 43 |
|
| 44 |
-
def require_ready():
|
| 45 |
if not service.ready:raise HTTPException(503,'GPU queue is not ready')
|
| 46 |
-
if configured_record() is None:
|
|
|
|
|
|
|
|
|
|
| 47 |
if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes:
|
| 48 |
raise HTTPException(507,'Insufficient storage')
|
| 49 |
|
|
@@ -79,7 +84,10 @@ def register(app,service,authenticated):
|
|
| 79 |
|
| 80 |
@app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
|
| 81 |
def capabilities():
|
|
|
|
|
|
|
| 82 |
return {'schema_version':'1.0','adapter':ADAPTER_VERSION,'model':'SAM 3D Body MHR70',
|
|
|
|
| 83 |
'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
|
| 84 |
'sam':public_status(),'gpu_queue_ready':service.ready,'mesh_available':False,
|
| 85 |
'joint_count':len(MHR),'per_frame_motion':True,'projections':True,'measurement_series':True,
|
|
@@ -101,12 +109,12 @@ def register(app,service,authenticated):
|
|
| 101 |
options:Annotated[str,Form()]='{}',source_asset_id:Annotated[str|None,Form()]=None):
|
| 102 |
directory=None;lineage=None
|
| 103 |
try:
|
| 104 |
-
require_ready()
|
| 105 |
if (video is None)==(source_asset_id is None):raise HTTPException(422,'Supply exactly one video or source_asset_id')
|
| 106 |
if len(options.encode())>512*1024:raise HTTPException(413,'Options exceed size limit')
|
| 107 |
try:inputs=json.loads(options)
|
| 108 |
except ValueError:raise HTTPException(422,'Options must be a JSON object') from None
|
| 109 |
parsed=validated(inputs)
|
|
|
|
| 110 |
with service.mutation_lock:
|
| 111 |
if source_asset_id:completed(source_asset_id)
|
| 112 |
directory,lineage=reserve(parsed)
|
|
@@ -165,7 +173,7 @@ def register(app,service,authenticated):
|
|
| 165 |
|
| 166 |
@app.post(PREFIX+'/{identifier}/revisions',status_code=202,dependencies=[Depends(authenticated)])
|
| 167 |
def revision(identifier:str,payload:RevisionRequest):
|
| 168 |
-
|
| 169 |
try:
|
| 170 |
with service.mutation_lock:
|
| 171 |
parent,manifest=completed(identifier)
|
|
@@ -173,18 +181,28 @@ def register(app,service,authenticated):
|
|
| 173 |
def merge(before,patch):
|
| 174 |
return {**before,**{k:merge(before[k],v) if isinstance(v,dict) and isinstance(before.get(k),dict) else v for k,v in patch.items()}}
|
| 175 |
parsed=validated(merge(inputs,payload.options))
|
|
|
|
| 176 |
if parsed.athlete_box!=MotionInput.model_validate(inputs).athlete_box:
|
| 177 |
raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
|
| 178 |
directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
|
| 179 |
# Reviewed events/calibration axes/correction changes reuse native inference.
|
| 180 |
-
geometry=('camera','athlete_box','rotation_degrees','source_mirrored')
|
| 181 |
-
|
| 182 |
-
|
|
|
|
| 183 |
and manifest.pipeline.get('tracking_implementation_sha256')==sha256_file(Path(__file__).with_name('sam_measurement_worker.py')))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
integrity=parent/'inference-integrity-private.json'
|
| 185 |
if reusable and integrity.is_file():
|
| 186 |
hashes=read_json(integrity)
|
| 187 |
-
files=(
|
| 188 |
if all((parent/name).is_file() and sha256_file(parent/name)==hashes.get(name) for name in files):
|
| 189 |
for name in files:os.link(parent/name,directory/name)
|
| 190 |
atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
|
|
|
|
| 11 |
from .sam_motion import MHR
|
| 12 |
from .api_jobs import QueueFull
|
| 13 |
from .sam_runtime import configured_record, public_status
|
| 14 |
+
from . import gvhmr_runtime
|
| 15 |
+
from .motion_adapters import descriptor, adapter_hash
|
| 16 |
from .storage import atomic_json, read_json, sha256_file
|
| 17 |
from .media import open_verified_media, media_response
|
| 18 |
|
|
|
|
| 43 |
if not path.is_relative_to(directory.resolve()):raise HTTPException(500,'Invalid stored artifact path')
|
| 44 |
return path
|
| 45 |
|
| 46 |
+
def require_ready(model='sam3d'):
|
| 47 |
if not service.ready:raise HTTPException(503,'GPU queue is not ready')
|
| 48 |
+
if model=='sam3d' and configured_record() is None:
|
| 49 |
+
raise HTTPException(503,{'code':'sam_not_configured','model':'sam3d','sam':public_status()})
|
| 50 |
+
if model=='gvhmr' and gvhmr_runtime.configured_record() is None:
|
| 51 |
+
raise HTTPException(503,{'code':'gvhmr_not_configured','model':'gvhmr','gvhmr':gvhmr_runtime.public_status()})
|
| 52 |
if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes:
|
| 53 |
raise HTTPException(507,'Insufficient storage')
|
| 54 |
|
|
|
|
| 84 |
|
| 85 |
@app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
|
| 86 |
def capabilities():
|
| 87 |
+
models=[{**{k:descriptor(key)[k] for k in ('id','name','adapter_version','definition_version','source_schema')},
|
| 88 |
+
**(public_status() if key=='sam3d' else gvhmr_runtime.public_status())} for key in ('sam3d','gvhmr')]
|
| 89 |
return {'schema_version':'1.0','adapter':ADAPTER_VERSION,'model':'SAM 3D Body MHR70',
|
| 90 |
+
'default_model':'sam3d','models':models,'model_selector':'options.model',
|
| 91 |
'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
|
| 92 |
'sam':public_status(),'gpu_queue_ready':service.ready,'mesh_available':False,
|
| 93 |
'joint_count':len(MHR),'per_frame_motion':True,'projections':True,'measurement_series':True,
|
|
|
|
| 109 |
options:Annotated[str,Form()]='{}',source_asset_id:Annotated[str|None,Form()]=None):
|
| 110 |
directory=None;lineage=None
|
| 111 |
try:
|
|
|
|
| 112 |
if (video is None)==(source_asset_id is None):raise HTTPException(422,'Supply exactly one video or source_asset_id')
|
| 113 |
if len(options.encode())>512*1024:raise HTTPException(413,'Options exceed size limit')
|
| 114 |
try:inputs=json.loads(options)
|
| 115 |
except ValueError:raise HTTPException(422,'Options must be a JSON object') from None
|
| 116 |
parsed=validated(inputs)
|
| 117 |
+
require_ready(parsed.model)
|
| 118 |
with service.mutation_lock:
|
| 119 |
if source_asset_id:completed(source_asset_id)
|
| 120 |
directory,lineage=reserve(parsed)
|
|
|
|
| 173 |
|
| 174 |
@app.post(PREFIX+'/{identifier}/revisions',status_code=202,dependencies=[Depends(authenticated)])
|
| 175 |
def revision(identifier:str,payload:RevisionRequest):
|
| 176 |
+
directory=None;lineage=None
|
| 177 |
try:
|
| 178 |
with service.mutation_lock:
|
| 179 |
parent,manifest=completed(identifier)
|
|
|
|
| 181 |
def merge(before,patch):
|
| 182 |
return {**before,**{k:merge(before[k],v) if isinstance(v,dict) and isinstance(before.get(k),dict) else v for k,v in patch.items()}}
|
| 183 |
parsed=validated(merge(inputs,payload.options))
|
| 184 |
+
require_ready(parsed.model)
|
| 185 |
if parsed.athlete_box!=MotionInput.model_validate(inputs).athlete_box:
|
| 186 |
raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
|
| 187 |
directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
|
| 188 |
# Reviewed events/calibration axes/correction changes reuse native inference.
|
| 189 |
+
geometry=('camera','athlete_box','rotation_degrees','source_mirrored','model','gvhmr')
|
| 190 |
+
parent_options=MotionInput.model_validate(inputs).model_dump()
|
| 191 |
+
reusable=(all(parent_options.get(k)==parsed.model_dump().get(k) for k in geometry)
|
| 192 |
+
and manifest.pipeline['adapter_sha256']==adapter_hash(parsed.model)
|
| 193 |
and manifest.pipeline.get('tracking_implementation_sha256')==sha256_file(Path(__file__).with_name('sam_measurement_worker.py')))
|
| 194 |
+
if parsed.model=='gvhmr':
|
| 195 |
+
# These facts change the temporal conditioning, not merely the export.
|
| 196 |
+
reusable &= (parent_options['timing']==parsed.timing.model_dump() and
|
| 197 |
+
parent_options['camera_stability']==parsed.camera_stability and
|
| 198 |
+
parent_options['correction']['max_gap_s']==parsed.correction.max_gap_s)
|
| 199 |
+
runtime=configured_record() if parsed.model=='sam3d' else gvhmr_runtime.configured_record()
|
| 200 |
+
if runtime and runtime.get('artifact_hashes'):
|
| 201 |
+
reusable &= manifest.pipeline['model'].get('artifact_hashes')==runtime['artifact_hashes']
|
| 202 |
integrity=parent/'inference-integrity-private.json'
|
| 203 |
if reusable and integrity.is_file():
|
| 204 |
hashes=read_json(integrity)
|
| 205 |
+
files=descriptor(parsed.model)['raw_files']
|
| 206 |
if all((parent/name).is_file() and sha256_file(parent/name)==hashes.get(name) for name in files):
|
| 207 |
for name in files:os.link(parent/name,directory/name)
|
| 208 |
atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
|
baseball_batting/motion_contract.py
CHANGED
|
@@ -9,7 +9,17 @@ ADAPTER_VERSION = 'sam-mhr70-motion-v1'
|
|
| 9 |
DEFINITION_VERSION = 'batting-corrected-points-v1'
|
| 10 |
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
class MotionInput(SamBattingInput):
|
|
|
|
|
|
|
| 13 |
coaching: Literal[False] = False
|
| 14 |
annotated_videos: bool = True
|
| 15 |
source_mirrored: bool | None = None
|
|
|
|
| 9 |
DEFINITION_VERSION = 'batting-corrected-points-v1'
|
| 10 |
|
| 11 |
|
| 12 |
+
class GVHMRSettings(Strict):
|
| 13 |
+
batch_size: int = Field(default=4, ge=1, le=16, strict=True)
|
| 14 |
+
max_sequence_frames: int = Field(default=300, ge=90, le=900, strict=True)
|
| 15 |
+
context_frames: int = Field(default=30, ge=10, le=60, strict=True)
|
| 16 |
+
minimum_keypoint_score: float = Field(default=.3, ge=0, le=1)
|
| 17 |
+
maximum_reprojection_box_fraction: float = Field(default=.15, gt=0, le=1)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
class MotionInput(SamBattingInput):
|
| 21 |
+
model: Literal['sam3d', 'gvhmr'] = 'sam3d'
|
| 22 |
+
gvhmr: GVHMRSettings = Field(default_factory=GVHMRSettings)
|
| 23 |
coaching: Literal[False] = False
|
| 24 |
annotated_videos: bool = True
|
| 25 |
source_mirrored: bool | None = None
|
baseball_batting/motion_export.py
CHANGED
|
@@ -6,7 +6,8 @@ import os
|
|
| 6 |
import numpy as np
|
| 7 |
from .motion_contract import (MotionManifest, MotionFrame, ProjectionFrame, MetricSample,
|
| 8 |
ADAPTER_VERSION, DEFINITION_VERSION)
|
| 9 |
-
from .sam_motion import MHR, BONES, MISSING, REPROJECTION, OUTSIDE, SPIKE, BOUNDARY, correct_motion
|
|
|
|
| 10 |
from .sam_measurements import DEFINITIONS, GROUP_KEYS, calculate_measurements, orientation
|
| 11 |
from .sam_videos import export_group_videos, corrected_projection
|
| 12 |
from .storage import atomic_json, sha256_file, digest
|
|
@@ -14,7 +15,8 @@ from .storage import atomic_json, sha256_file, digest
|
|
| 14 |
JOINTS = tuple(MHR)
|
| 15 |
INDEX_NAMES = {v: k for k, v in MHR.items()}
|
| 16 |
REASONS = {MISSING:'missing_model_landmark_or_hip_anchor', REPROJECTION:'projection_consistency_failed',
|
| 17 |
-
OUTSIDE:'outside_source_image', SPIKE:'corroborated_tracking_spike', BOUNDARY:'filter_boundary'
|
|
|
|
| 18 |
EVENT_ONLY = {k for k in DEFINITIONS if k.endswith('_time_ms') or k in
|
| 19 |
{'hip_to_shoulder_ms','shoulder_to_hands_ms'} or k.startswith('stride_')}
|
| 20 |
DEPENDENCIES={
|
|
@@ -48,6 +50,12 @@ def _jsonl(path, records):
|
|
| 48 |
|
| 49 |
def _calculate(corrected, times, options, known):
|
| 50 |
groups, contexts = calculate_measurements(corrected, times, options.sam_options(), clock_known=known)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
if options.scale_status == 'unknown':
|
| 52 |
for swings in groups.values():
|
| 53 |
for swing in swings:
|
|
@@ -85,6 +93,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 85 |
"""Write all artifacts before atomically publishing the completed manifest."""
|
| 86 |
import time
|
| 87 |
job=Path(job); revision=lineage['analysis_revision']; person_id=lineage['analysis_id']+':athlete_1'
|
|
|
|
| 88 |
records=capture['frames']; n=len(records)
|
| 89 |
if n<4:raise ValueError('insufficient_source_frames')
|
| 90 |
playback=np.array([r['playback_s'] for r in records],float)
|
|
@@ -97,11 +106,20 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 97 |
times=capture_times if known else video_times
|
| 98 |
track=track or {'reasons':[None]*n}
|
| 99 |
if len(track['reasons'])!=n:raise ValueError('Tracking records differ from source frame count')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
# Preserve native arrays for debugging; uncertain identity must never become replay evidence.
|
| 101 |
mask=np.array([reason is None for reason in track['reasons']],bool)
|
| 102 |
correction_raw={**raw,'projection_valid':np.asarray(raw['projection_valid'],bool)&mask}
|
| 103 |
progress('temporal_correction',0,n)
|
| 104 |
corrected=correct_motion(correction_raw,times,options.correction)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
indices=list(MHR.values()); count=corrected['valid'][:,indices].sum(axis=1)
|
| 106 |
usable=count>=options.minimum_usable_joints
|
| 107 |
if not usable.any(): raise ValueError('no_usable_motion')
|
|
@@ -115,7 +133,8 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 115 |
segments=[]; segment_ids=[]; serial=0; gap_serial=0; previous=None
|
| 116 |
for i in range(n):
|
| 117 |
kind='segment' if usable[i] else 'gap'
|
| 118 |
-
|
|
|
|
| 119 |
if kind=='segment':serial+=1; identifier=f'segment_{serial}'
|
| 120 |
else:gap_serial+=1; identifier=f'gap_{gap_serial}'
|
| 121 |
segments.append({'segment_id':identifier,'usable':bool(usable[i]),'start_frame':i,'end_frame':i,
|
|
@@ -133,6 +152,12 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 133 |
xy,projection_valid=corrected_projection(corrected,raw['intrinsics'],i)
|
| 134 |
for name,index in MHR.items():
|
| 135 |
reasons=[label for bit,label in REASONS.items() if corrected['reasons'][i,index]&bit]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
if track['reasons'][i]:reasons.append(track['reasons'][i])
|
| 137 |
good=bool(corrected['valid'][i,index] and np.isfinite(positions[i,index]).all())
|
| 138 |
status=('interpolated' if corrected['interpolated'][i,index] else 'estimated') if good else (
|
|
@@ -145,6 +170,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 145 |
'reasons':[] if valid else reasons or ['camera_projection_unavailable']}
|
| 146 |
projection_count+=int(valid)
|
| 147 |
flags=list(frame.get('flags',[]))
|
|
|
|
| 148 |
if not usable[i]:flags.append('pose_unusable')
|
| 149 |
elif count[i]<len(JOINTS):flags.append('partial_pose')
|
| 150 |
if i and times[i]-times[i-1]>options.correction.max_gap_s:flags.append('timestamp_gap')
|
|
@@ -167,7 +193,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 167 |
rows={m.key:m for swings in groups.values() for swing in swings if swing.rep==rep for m in swing.measurements}
|
| 168 |
interpolation=bool(corrected['interpolated'][a:b+1,indices].any())
|
| 169 |
measurement_matrix,_=orientation(corrected['points_relative'],options,base)
|
| 170 |
-
metadata={'analysis_revision':revision,'rep':rep,'definition_version':
|
| 171 |
'baseline_frame':base,'window':{'start_frame':a,'end_frame':b},
|
| 172 |
'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
|
| 173 |
for key,metric in rows.items():
|
|
@@ -198,8 +224,10 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 198 |
'source_detail':window['source'],'status':('reviewed' if detector=='manual' else 'estimated') if index is not None else 'unavailable',
|
| 199 |
'start':stamp(index) if index is not None else None,'end':stamp(end) if end is not None else None,
|
| 200 |
'reasons':[reason] if reason else [],'uses_interpolated_input':interpolation})
|
| 201 |
-
event('swing_window',a,b)
|
| 202 |
-
event('
|
|
|
|
|
|
|
| 203 |
event('stride_start',window['stride_start_frame'],reason=None if window['stride_start_frame'] is not None else 'missing_reviewed_stride_events')
|
| 204 |
event('foot_plant',window['landing_frame'],reason=None if window['landing_frame'] is not None else 'missing_reviewed_stride_events')
|
| 205 |
for name,index in context['peaks'].items():
|
|
@@ -207,7 +235,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 207 |
event(name+'_speed_peak',index,reason=metric.reason_code,detector='pose_speed_peak')
|
| 208 |
event('ball_contact',reason='body_landmarks_do_not_establish_ball_contact',detector='not_detected')
|
| 209 |
atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
|
| 210 |
-
'definition_version':
|
| 211 |
'calculation_inputs':options.model_dump(mode='json')})
|
| 212 |
atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
|
| 213 |
atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
|
|
@@ -236,10 +264,10 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 236 |
'status':'unavailable','reason_code':'camera_projection_unavailable','format':'jsonl','media_type':'application/x-ndjson','expires_at':expiry}
|
| 237 |
artifacts['mesh']={'status':'unavailable','reason_code':'animated_mesh_second_phase','format':'none','media_type':'application/octet-stream','expires_at':expiry}
|
| 238 |
for key in GROUP_KEYS:
|
| 239 |
-
if key in clips:
|
| 240 |
item=asset(job/'group-videos'/(key+'.mp4'),'video/mp4','mp4')
|
| 241 |
item['url']=prefix+'/annotated_'+key;artifacts['annotated_'+key]=item
|
| 242 |
-
else:artifacts['annotated_'+key]={'status':'unavailable','reason_code':'not_requested','format':'mp4','media_type':'video/mp4','expires_at':expiry}
|
| 243 |
# Exact source durations (including the final sample) are exported by the media decoder.
|
| 244 |
from .ingest import iter_frames
|
| 245 |
duration=None
|
|
@@ -255,20 +283,20 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 255 |
'timeline_origin_pts':records[0]['pts'],'timeline_origin_time_base':records[0]['time_base'],
|
| 256 |
'projection_space':'upright_original_image_pixels_x_right_y_down',
|
| 257 |
'camera_model':'pinhole','distortion_correction':'not_applied; source_lens_distortion_unverified',
|
| 258 |
-
'camera_intrinsics_source':options.camera.source if options.camera else '
|
| 259 |
-
pipeline={'model':model,'adapter_version':
|
| 260 |
'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
|
| 261 |
'exporter_sha256':sha256_file(Path(__file__)),'correction':corrected['metadata'],
|
| 262 |
-
'measurement_definition_version':
|
| 263 |
'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
|
| 264 |
coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
|
| 265 |
-
'scale_source':options.scale_source or '
|
| 266 |
'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
|
| 267 |
'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
|
| 268 |
'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'declared_up'} if reference=='declared_field_axes' else (
|
| 269 |
{'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'declared_up'} if reference=='fixed_starting_hip_axis' else
|
| 270 |
{'x':'camera_right','y':'camera_down','z':'camera_away'}),
|
| 271 |
-
'left_right':'
|
| 272 |
'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
|
| 273 |
'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics); add root exactly once',
|
| 274 |
'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
|
|
@@ -279,11 +307,7 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
|
|
| 279 |
'mapping':options.timing.model_dump(mode='json'),'original_video_time_origin_s':float(playback[0]),
|
| 280 |
'original_capture_time_origin_s':float(physical[0]) if known else None,
|
| 281 |
'maximum_derivative_gap_s':options.correction.max_gap_s},
|
| 282 |
-
skeleton=
|
| 283 |
-
'joints':[{'name':name,'source_schema':'MHR70','source_index':index,
|
| 284 |
-
'definition':'Native '+name.replace('_',' ')+' MHR70 landmark; no mesh-vertex or acromion substitution','derived':False} for name,index in MHR.items()],
|
| 285 |
-
'bones':[[INDEX_NAMES[a],INDEX_NAMES[b]] for a,b in BONES],
|
| 286 |
-
'head_center_proxy':'midpoint_of_bilateral_ear_landmarks','hand_motion_proxy':'midpoint_of_bilateral_wrist_landmarks'},
|
| 287 |
sampling={'policy':'every_decoded_source_frame','frame_count':n,'intentionally_skipped_frames':0,
|
| 288 |
'maximum_gap_s':options.correction.max_gap_s,'playback_interpolation':'client_only; never measurement evidence'},
|
| 289 |
quality={'usable_frame_count':int(usable.sum()),'minimum_usable_joints':options.minimum_usable_joints,
|
|
|
|
| 6 |
import numpy as np
|
| 7 |
from .motion_contract import (MotionManifest, MotionFrame, ProjectionFrame, MetricSample,
|
| 8 |
ADAPTER_VERSION, DEFINITION_VERSION)
|
| 9 |
+
from .sam_motion import MHR, BONES, MISSING, REPROJECTION, OUTSIDE, SPIKE, BOUNDARY, OBSERVATION, correct_motion
|
| 10 |
+
from .motion_adapters import descriptor, adapter_hash, skeleton, SURFACE_LANDMARKS
|
| 11 |
from .sam_measurements import DEFINITIONS, GROUP_KEYS, calculate_measurements, orientation
|
| 12 |
from .sam_videos import export_group_videos, corrected_projection
|
| 13 |
from .storage import atomic_json, sha256_file, digest
|
|
|
|
| 15 |
JOINTS = tuple(MHR)
|
| 16 |
INDEX_NAMES = {v: k for k, v in MHR.items()}
|
| 17 |
REASONS = {MISSING:'missing_model_landmark_or_hip_anchor', REPROJECTION:'projection_consistency_failed',
|
| 18 |
+
OUTSIDE:'outside_source_image', SPIKE:'corroborated_tracking_spike', BOUNDARY:'filter_boundary',
|
| 19 |
+
OBSERVATION:'model_observation_unreliable'}
|
| 20 |
EVENT_ONLY = {k for k in DEFINITIONS if k.endswith('_time_ms') or k in
|
| 21 |
{'hip_to_shoulder_ms','shoulder_to_hands_ms'} or k.startswith('stride_')}
|
| 22 |
DEPENDENCIES={
|
|
|
|
| 50 |
|
| 51 |
def _calculate(corrected, times, options, known):
|
| 52 |
groups, contexts = calculate_measurements(corrected, times, options.sam_options(), clock_known=known)
|
| 53 |
+
if options.model=='gvhmr':
|
| 54 |
+
for swings in groups.values():
|
| 55 |
+
for swing in swings:
|
| 56 |
+
for metric in swing.measurements:
|
| 57 |
+
metric.quality_flags=[f.replace('sam_joint_confidence_unknown','gvhmr_joint_confidence_unknown') for f in metric.quality_flags]
|
| 58 |
+
metric.quality_flags.append('smplx_anatomical_definition; cross_model_values_not_interchangeable')
|
| 59 |
if options.scale_status == 'unknown':
|
| 60 |
for swings in groups.values():
|
| 61 |
for swing in swings:
|
|
|
|
| 93 |
"""Write all artifacts before atomically publishing the completed manifest."""
|
| 94 |
import time
|
| 95 |
job=Path(job); revision=lineage['analysis_revision']; person_id=lineage['analysis_id']+':athlete_1'
|
| 96 |
+
adapter=descriptor(options.model); definition_version=adapter['definition_version']
|
| 97 |
records=capture['frames']; n=len(records)
|
| 98 |
if n<4:raise ValueError('insufficient_source_frames')
|
| 99 |
playback=np.array([r['playback_s'] for r in records],float)
|
|
|
|
| 106 |
times=capture_times if known else video_times
|
| 107 |
track=track or {'reasons':[None]*n}
|
| 108 |
if len(track['reasons'])!=n:raise ValueError('Tracking records differ from source frame count')
|
| 109 |
+
model_sequence=np.asarray(raw.get('sequence_ids',np.zeros(n,int)))
|
| 110 |
+
model_frame_reasons=raw.get('frame_reasons',['']*n)
|
| 111 |
+
resampled=np.asarray(raw.get('temporal_resampled',np.zeros(n,bool)),bool)
|
| 112 |
+
if model_sequence.shape!=(n,) or len(model_frame_reasons)!=n or resampled.shape!=(n,):
|
| 113 |
+
raise ValueError('Native temporal provenance differs from source frame count')
|
| 114 |
# Preserve native arrays for debugging; uncertain identity must never become replay evidence.
|
| 115 |
mask=np.array([reason is None for reason in track['reasons']],bool)
|
| 116 |
correction_raw={**raw,'projection_valid':np.asarray(raw['projection_valid'],bool)&mask}
|
| 117 |
progress('temporal_correction',0,n)
|
| 118 |
corrected=correct_motion(correction_raw,times,options.correction)
|
| 119 |
+
if options.model=='gvhmr':
|
| 120 |
+
corrected['interpolated']|=resampled[:,None]&corrected['valid']
|
| 121 |
+
corrected['metadata']['model_temporal_resampling']='SO(3) parameters evaluated at source timestamps; not gap interpolation'
|
| 122 |
+
corrected['metadata']['model_resampled_frame_count']=int(resampled.sum())
|
| 123 |
indices=list(MHR.values()); count=corrected['valid'][:,indices].sum(axis=1)
|
| 124 |
usable=count>=options.minimum_usable_joints
|
| 125 |
if not usable.any(): raise ValueError('no_usable_motion')
|
|
|
|
| 133 |
segments=[]; segment_ids=[]; serial=0; gap_serial=0; previous=None
|
| 134 |
for i in range(n):
|
| 135 |
kind='segment' if usable[i] else 'gap'
|
| 136 |
+
model_boundary=i>0 and model_sequence[i]!=model_sequence[i-1]
|
| 137 |
+
if previous is None or kind!=previous or times[i]-times[i-1]>options.correction.max_gap_s or model_boundary:
|
| 138 |
if kind=='segment':serial+=1; identifier=f'segment_{serial}'
|
| 139 |
else:gap_serial+=1; identifier=f'gap_{gap_serial}'
|
| 140 |
segments.append({'segment_id':identifier,'usable':bool(usable[i]),'start_frame':i,'end_frame':i,
|
|
|
|
| 152 |
xy,projection_valid=corrected_projection(corrected,raw['intrinsics'],i)
|
| 153 |
for name,index in MHR.items():
|
| 154 |
reasons=[label for bit,label in REASONS.items() if corrected['reasons'][i,index]&bit]
|
| 155 |
+
model_reason=model_frame_reasons[i]
|
| 156 |
+
if model_reason:reasons.append(str(model_reason))
|
| 157 |
+
if options.model=='gvhmr':
|
| 158 |
+
reasons.append('model_estimated_depth_unvalidated')
|
| 159 |
+
if name in SURFACE_LANDMARKS:reasons.append('smplx_surface_landmark_derivation')
|
| 160 |
+
if resampled[i]:reasons.append('uniform_grid_pose_resampled_to_source_timestamp')
|
| 161 |
if track['reasons'][i]:reasons.append(track['reasons'][i])
|
| 162 |
good=bool(corrected['valid'][i,index] and np.isfinite(positions[i,index]).all())
|
| 163 |
status=('interpolated' if corrected['interpolated'][i,index] else 'estimated') if good else (
|
|
|
|
| 170 |
'reasons':[] if valid else reasons or ['camera_projection_unavailable']}
|
| 171 |
projection_count+=int(valid)
|
| 172 |
flags=list(frame.get('flags',[]))
|
| 173 |
+
if model_frame_reasons[i]:flags.append(str(model_frame_reasons[i]))
|
| 174 |
if not usable[i]:flags.append('pose_unusable')
|
| 175 |
elif count[i]<len(JOINTS):flags.append('partial_pose')
|
| 176 |
if i and times[i]-times[i-1]>options.correction.max_gap_s:flags.append('timestamp_gap')
|
|
|
|
| 193 |
rows={m.key:m for swings in groups.values() for swing in swings if swing.rep==rep for m in swing.measurements}
|
| 194 |
interpolation=bool(corrected['interpolated'][a:b+1,indices].any())
|
| 195 |
measurement_matrix,_=orientation(corrected['points_relative'],options,base)
|
| 196 |
+
metadata={'analysis_revision':revision,'rep':rep,'definition_version':definition_version,
|
| 197 |
'baseline_frame':base,'window':{'start_frame':a,'end_frame':b},
|
| 198 |
'camera_to_measurement_rotation':_finite(measurement_matrix) if measurement_matrix is not None else None}
|
| 199 |
for key,metric in rows.items():
|
|
|
|
| 224 |
'source_detail':window['source'],'status':('reviewed' if detector=='manual' else 'estimated') if index is not None else 'unavailable',
|
| 225 |
'start':stamp(index) if index is not None else None,'end':stamp(end) if end is not None else None,
|
| 226 |
'reasons':[reason] if reason else [],'uses_interpolated_input':interpolation})
|
| 227 |
+
event('swing_window',a,b)
|
| 228 |
+
event('baseline',base,detector='manual' if manual and options.windows[rep-1].baseline_frame is not None else 'pose_estimated')
|
| 229 |
+
reviewed_forward=manual and options.windows[rep-1].forward_start_frame is not None and options.windows[rep-1].forward_end_frame is not None
|
| 230 |
+
event('forward_swing_window',context['forward_start'],context['forward_end'],detector='manual' if reviewed_forward else 'pose_estimated')
|
| 231 |
event('stride_start',window['stride_start_frame'],reason=None if window['stride_start_frame'] is not None else 'missing_reviewed_stride_events')
|
| 232 |
event('foot_plant',window['landing_frame'],reason=None if window['landing_frame'] is not None else 'missing_reviewed_stride_events')
|
| 233 |
for name,index in context['peaks'].items():
|
|
|
|
| 235 |
event(name+'_speed_peak',index,reason=metric.reason_code,detector='pose_speed_peak')
|
| 236 |
event('ball_contact',reason='body_landmarks_do_not_establish_ball_contact',detector='not_detected')
|
| 237 |
atomic_json(job/'measurements.json',{'schema_version':'1.0','analysis_revision':revision,
|
| 238 |
+
'definition_version':definition_version,'summaries':summaries,'series':series,
|
| 239 |
'calculation_inputs':options.model_dump(mode='json')})
|
| 240 |
atomic_json(job/'events.json',{'schema_version':'1.0','analysis_revision':revision,'events':events})
|
| 241 |
atomic_json(job/'quality.json',{'analysis_revision':revision,'segments':segments,'correction':corrected['metadata'],
|
|
|
|
| 264 |
'status':'unavailable','reason_code':'camera_projection_unavailable','format':'jsonl','media_type':'application/x-ndjson','expires_at':expiry}
|
| 265 |
artifacts['mesh']={'status':'unavailable','reason_code':'animated_mesh_second_phase','format':'none','media_type':'application/octet-stream','expires_at':expiry}
|
| 266 |
for key in GROUP_KEYS:
|
| 267 |
+
if key in clips and clips[key].status=='available':
|
| 268 |
item=asset(job/'group-videos'/(key+'.mp4'),'video/mp4','mp4')
|
| 269 |
item['url']=prefix+'/annotated_'+key;artifacts['annotated_'+key]=item
|
| 270 |
+
else:artifacts['annotated_'+key]={'status':'unavailable','reason_code':clips[key].reason_code if key in clips else 'not_requested','format':'mp4','media_type':'video/mp4','expires_at':expiry}
|
| 271 |
# Exact source durations (including the final sample) are exported by the media decoder.
|
| 272 |
from .ingest import iter_frames
|
| 273 |
duration=None
|
|
|
|
| 283 |
'timeline_origin_pts':records[0]['pts'],'timeline_origin_time_base':records[0]['time_base'],
|
| 284 |
'projection_space':'upright_original_image_pixels_x_right_y_down',
|
| 285 |
'camera_model':'pinhole','distortion_correction':'not_applied; source_lens_distortion_unverified',
|
| 286 |
+
'camera_intrinsics_source':options.camera.source if options.camera else adapter['name']+' estimated focal length and centered principal point'},
|
| 287 |
+
pipeline={'model':model,'selected_model':options.model,'adapter_version':adapter['adapter_version'],'adapter_sha256':adapter_hash(options.model),
|
| 288 |
'tracking_implementation_sha256':sha256_file(Path(__file__).with_name('sam_measurement_worker.py')),
|
| 289 |
'exporter_sha256':sha256_file(Path(__file__)),'correction':corrected['metadata'],
|
| 290 |
+
'measurement_definition_version':definition_version,'measurement_definitions_sha256':digest(DEFINITIONS),
|
| 291 |
'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
|
| 292 |
coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
|
| 293 |
+
'scale_source':options.scale_source or adapter['name']+' native scale; not independently calibrated',
|
| 294 |
'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
|
| 295 |
'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
|
| 296 |
'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'declared_up'} if reference=='declared_field_axes' else (
|
| 297 |
{'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'declared_up'} if reference=='fixed_starting_hip_axis' else
|
| 298 |
{'x':'camera_right','y':'camera_down','z':'camera_away'}),
|
| 299 |
+
'left_right':'athlete_anatomical_native_'+adapter['source_schema'],'ground_status':'unavailable','camera_motion':options.camera_stability,
|
| 300 |
'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
|
| 301 |
'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics); add root exactly once',
|
| 302 |
'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
|
|
|
|
| 307 |
'mapping':options.timing.model_dump(mode='json'),'original_video_time_origin_s':float(playback[0]),
|
| 308 |
'original_capture_time_origin_s':float(physical[0]) if known else None,
|
| 309 |
'maximum_derivative_gap_s':options.correction.max_gap_s},
|
| 310 |
+
skeleton=skeleton(options.model),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
sampling={'policy':'every_decoded_source_frame','frame_count':n,'intentionally_skipped_frames':0,
|
| 312 |
'maximum_gap_s':options.correction.max_gap_s,'playback_interpolation':'client_only; never measurement evidence'},
|
| 313 |
quality={'usable_frame_count':int(usable.sum()),'minimum_usable_joints':options.minimum_usable_joints,
|
baseball_batting/motion_worker.py
CHANGED
|
@@ -6,6 +6,8 @@ import numpy as np
|
|
| 6 |
from .motion_contract import MotionInput
|
| 7 |
from .motion_export import export_motion
|
| 8 |
from .sam_measurement_worker import reconstruct_sam
|
|
|
|
|
|
|
| 9 |
from .ingest import ingest
|
| 10 |
from .storage import atomic_json,read_json,sha256_file
|
| 11 |
|
|
@@ -20,15 +22,16 @@ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120,retention
|
|
| 20 |
capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
|
| 21 |
atomic_json(job/'capture-private.json',capture)
|
| 22 |
if any(w.end_frame>=capture['frame_count'] for w in options.windows):raise ValueError('Reviewed window exceeds video')
|
|
|
|
| 23 |
if (job/'reused-inference.json').is_file():
|
| 24 |
reused=read_json(job/'reused-inference.json')
|
| 25 |
if reused['source_sha256']!=capture['input_sha256']:raise ValueError('Reused inference source differs')
|
| 26 |
-
with np.load(job/
|
| 27 |
-
model=read_json(job/
|
| 28 |
model={**model,'inference_reused_from_job':reused['job_id']}
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
track=read_json(job/'person-track-private.json')
|
| 33 |
return export_motion(job,video,capture,raw,options,model,lineage,retention_s=retention_s,progress=progress,track=track)
|
| 34 |
|
|
@@ -45,8 +48,9 @@ def main():
|
|
| 45 |
'no_usable_motion','invalid_source_timestamps','multiple_people_select_athlete_box','insufficient_source_frames'} else 'motion_processing_failed'
|
| 46 |
failure={'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
|
| 47 |
'reason_code':reason,'error_type':type(error).__name__}
|
| 48 |
-
|
| 49 |
-
|
|
|
|
| 50 |
atomic_json(Path(args.job)/'error.json',failure)
|
| 51 |
print(type(error).__name__+': '+str(error),flush=True);return 1
|
| 52 |
|
|
|
|
| 6 |
from .motion_contract import MotionInput
|
| 7 |
from .motion_export import export_motion
|
| 8 |
from .sam_measurement_worker import reconstruct_sam
|
| 9 |
+
from .gvhmr_worker import reconstruct_gvhmr
|
| 10 |
+
from .motion_adapters import descriptor
|
| 11 |
from .ingest import ingest
|
| 12 |
from .storage import atomic_json,read_json,sha256_file
|
| 13 |
|
|
|
|
| 22 |
capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
|
| 23 |
atomic_json(job/'capture-private.json',capture)
|
| 24 |
if any(w.end_frame>=capture['frame_count'] for w in options.windows):raise ValueError('Reviewed window exceeds video')
|
| 25 |
+
files=descriptor(options.model)['raw_files']
|
| 26 |
if (job/'reused-inference.json').is_file():
|
| 27 |
reused=read_json(job/'reused-inference.json')
|
| 28 |
if reused['source_sha256']!=capture['input_sha256']:raise ValueError('Reused inference source differs')
|
| 29 |
+
with np.load(job/files[0],allow_pickle=False) as data:raw=dict(data)
|
| 30 |
+
model=read_json(job/files[1])['model']
|
| 31 |
model={**model,'inference_reused_from_job':reused['job_id']}
|
| 32 |
+
elif options.model=='sam3d':raw,model=reconstruct_sam(job,video,capture,models,options.sam_options(),progress,strict_identity=True)
|
| 33 |
+
else:raw,model=reconstruct_gvhmr(job,video,capture,models,options,progress)
|
| 34 |
+
atomic_json(job/'inference-integrity-private.json',{name:sha256_file(job/name) for name in files})
|
| 35 |
track=read_json(job/'person-track-private.json')
|
| 36 |
return export_motion(job,video,capture,raw,options,model,lineage,retention_s=retention_s,progress=progress,track=track)
|
| 37 |
|
|
|
|
| 48 |
'no_usable_motion','invalid_source_timestamps','multiple_people_select_athlete_box','insufficient_source_frames'} else 'motion_processing_failed'
|
| 49 |
failure={'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
|
| 50 |
'reason_code':reason,'error_type':type(error).__name__}
|
| 51 |
+
for filename in ('sam-raw-private.error.json','gvhmr-raw-private.error.json'):
|
| 52 |
+
native_error=Path(args.job)/filename
|
| 53 |
+
if native_error.is_file():failure.update(read_json(native_error))
|
| 54 |
atomic_json(Path(args.job)/'error.json',failure)
|
| 55 |
print(type(error).__name__+': '+str(error),flush=True);return 1
|
| 56 |
|
baseball_batting/sam_motion.py
CHANGED
|
@@ -16,7 +16,7 @@ MHR = {'left_ear': 3, 'right_ear': 4, 'left_shoulder': 5, 'right_shoulder': 6,
|
|
| 16 |
BONES = [(3,4),(5,6),(5,7),(7,62),(6,8),(8,41),(5,9),(6,10),(9,10),
|
| 17 |
(9,11),(11,13),(10,12),(12,14),(13,17),(17,15),(17,16),
|
| 18 |
(14,20),(20,18),(20,19)]
|
| 19 |
-
MISSING, REPROJECTION, OUTSIDE, SPIKE, BOUNDARY = 1, 2, 4, 8, 16
|
| 20 |
|
| 21 |
|
| 22 |
def segments(valid, times, max_gap):
|
|
@@ -95,6 +95,14 @@ def correct_motion(raw, times, settings):
|
|
| 95 |
raise ValueError('Correction timestamps must be finite and strictly increasing')
|
| 96 |
valid = np.isfinite(p).all(axis=-1)
|
| 97 |
reasons = np.where(valid, 0, MISSING).astype(np.uint16)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
projection_good = np.asarray(raw.get('projection_valid', np.ones(len(p), bool)), bool)
|
| 99 |
valid &= projection_good[:, None]
|
| 100 |
reasons[~projection_good] |= REPROJECTION
|
|
@@ -121,7 +129,7 @@ def correct_motion(raw, times, settings):
|
|
| 121 |
abnormal[:,a] |= bad; abnormal[:,b] |= bad
|
| 122 |
rejected = np.zeros_like(valid)
|
| 123 |
for j in range(70):
|
| 124 |
-
for ids in
|
| 125 |
if len(ids)<5: continue
|
| 126 |
mid = ids[1:-1]
|
| 127 |
fraction = ((t[mid]-t[ids[:-2]])/(t[ids[2:]]-t[ids[:-2]]))[:,None]
|
|
@@ -142,7 +150,7 @@ def correct_motion(raw, times, settings):
|
|
| 142 |
corrected = np.full_like(rel,np.nan)
|
| 143 |
boundary = np.zeros_like(valid)
|
| 144 |
for j in range(70):
|
| 145 |
-
for ids in
|
| 146 |
q = rel[ids,j]
|
| 147 |
corrected[ids,j] = _adaptive_smooth(q,t[ids],settings.min_cutoff_hz,settings.speed_coefficient)
|
| 148 |
b = settings.boundary_samples
|
|
@@ -150,7 +158,7 @@ def correct_motion(raw, times, settings):
|
|
| 150 |
reasons[boundary] |= BOUNDARY
|
| 151 |
# Retain SAM's predicted translation for projection, never call it ground motion.
|
| 152 |
camera_root = hip + np.asarray(raw['camera_translation'],float)
|
| 153 |
-
for ids in
|
| 154 |
q=camera_root[ids]
|
| 155 |
camera_root[ids]=_adaptive_smooth(q,t[ids],settings.min_cutoff_hz,settings.speed_coefficient)
|
| 156 |
corrected_camera = corrected+camera_root[:,None,:]
|
|
@@ -166,12 +174,13 @@ def correct_motion(raw, times, settings):
|
|
| 166 |
'metadata': {'version': CORRECTION_VERSION, 'method': 'centered_speed_adaptive_quadratic_regression',
|
| 167 |
'settings': settings.model_dump(), 'coordinate_frame': 'hip_relative_camera_oriented',
|
| 168 |
'interpolation': 'disabled; gaps remain gaps', 'joint_confidence': None,
|
| 169 |
-
'frames_with_unusable_points': int(
|
| 170 |
'rejected_point_count': int(rejected.sum()),
|
| 171 |
'smoothed_point_count': int(np.sum(np.isfinite(changes) & (changes>1e-9))),
|
| 172 |
'maximum_adjustment_m': float(np.nanmax(changes)) if np.isfinite(changes).any() else None,
|
| 173 |
'unreliable_sections':unreliable[:200],
|
| 174 |
'unreliable_section_count':len(unreliable),
|
| 175 |
'reason_bits': {'missing':MISSING, 'reprojection':REPROJECTION, 'outside_image':OUTSIDE,
|
| 176 |
-
'corroborated_tracking_spike':SPIKE,'filter_boundary':BOUNDARY
|
|
|
|
| 177 |
'accuracy_validated': False}}
|
|
|
|
| 16 |
BONES = [(3,4),(5,6),(5,7),(7,62),(6,8),(8,41),(5,9),(6,10),(9,10),
|
| 17 |
(9,11),(11,13),(10,12),(12,14),(13,17),(17,15),(17,16),
|
| 18 |
(14,20),(20,18),(20,19)]
|
| 19 |
+
MISSING, REPROJECTION, OUTSIDE, SPIKE, BOUNDARY, OBSERVATION = 1, 2, 4, 8, 16, 32
|
| 20 |
|
| 21 |
|
| 22 |
def segments(valid, times, max_gap):
|
|
|
|
| 95 |
raise ValueError('Correction timestamps must be finite and strictly increasing')
|
| 96 |
valid = np.isfinite(p).all(axis=-1)
|
| 97 |
reasons = np.where(valid, 0, MISSING).astype(np.uint16)
|
| 98 |
+
observed=np.asarray(raw.get('joint_usable',np.ones_like(valid)),bool)
|
| 99 |
+
if observed.shape!=valid.shape:raise ValueError('Joint usability mask differs from motion shape')
|
| 100 |
+
valid &= observed; reasons[~observed] |= OBSERVATION
|
| 101 |
+
sequence=np.asarray(raw.get('sequence_ids',np.zeros(len(p),int)))
|
| 102 |
+
if sequence.shape!=(len(p),):raise ValueError('Sequence IDs differ from timestamps')
|
| 103 |
+
def runs(mask):
|
| 104 |
+
for run in segments(mask,t,settings.max_gap_s):
|
| 105 |
+
yield from np.split(run,np.flatnonzero(np.diff(sequence[run])!=0)+1)
|
| 106 |
projection_good = np.asarray(raw.get('projection_valid', np.ones(len(p), bool)), bool)
|
| 107 |
valid &= projection_good[:, None]
|
| 108 |
reasons[~projection_good] |= REPROJECTION
|
|
|
|
| 129 |
abnormal[:,a] |= bad; abnormal[:,b] |= bad
|
| 130 |
rejected = np.zeros_like(valid)
|
| 131 |
for j in range(70):
|
| 132 |
+
for ids in runs(valid[:,j]):
|
| 133 |
if len(ids)<5: continue
|
| 134 |
mid = ids[1:-1]
|
| 135 |
fraction = ((t[mid]-t[ids[:-2]])/(t[ids[2:]]-t[ids[:-2]]))[:,None]
|
|
|
|
| 150 |
corrected = np.full_like(rel,np.nan)
|
| 151 |
boundary = np.zeros_like(valid)
|
| 152 |
for j in range(70):
|
| 153 |
+
for ids in runs(valid[:,j]):
|
| 154 |
q = rel[ids,j]
|
| 155 |
corrected[ids,j] = _adaptive_smooth(q,t[ids],settings.min_cutoff_hz,settings.speed_coefficient)
|
| 156 |
b = settings.boundary_samples
|
|
|
|
| 158 |
reasons[boundary] |= BOUNDARY
|
| 159 |
# Retain SAM's predicted translation for projection, never call it ground motion.
|
| 160 |
camera_root = hip + np.asarray(raw['camera_translation'],float)
|
| 161 |
+
for ids in runs(hip_ok & np.isfinite(camera_root).all(axis=-1)):
|
| 162 |
q=camera_root[ids]
|
| 163 |
camera_root[ids]=_adaptive_smooth(q,t[ids],settings.min_cutoff_hz,settings.speed_coefficient)
|
| 164 |
corrected_camera = corrected+camera_root[:,None,:]
|
|
|
|
| 174 |
'metadata': {'version': CORRECTION_VERSION, 'method': 'centered_speed_adaptive_quadratic_regression',
|
| 175 |
'settings': settings.model_dump(), 'coordinate_frame': 'hip_relative_camera_oriented',
|
| 176 |
'interpolation': 'disabled; gaps remain gaps', 'joint_confidence': None,
|
| 177 |
+
'frames_with_unusable_points': int(bad.sum()),
|
| 178 |
'rejected_point_count': int(rejected.sum()),
|
| 179 |
'smoothed_point_count': int(np.sum(np.isfinite(changes) & (changes>1e-9))),
|
| 180 |
'maximum_adjustment_m': float(np.nanmax(changes)) if np.isfinite(changes).any() else None,
|
| 181 |
'unreliable_sections':unreliable[:200],
|
| 182 |
'unreliable_section_count':len(unreliable),
|
| 183 |
'reason_bits': {'missing':MISSING, 'reprojection':REPROJECTION, 'outside_image':OUTSIDE,
|
| 184 |
+
'corroborated_tracking_spike':SPIKE,'filter_boundary':BOUNDARY,
|
| 185 |
+
'model_observation_unreliable':OBSERVATION},
|
| 186 |
'accuracy_validated': False}}
|
docs/GVHMR_SETUP.md
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Enable GVHMR on the existing GPU API
|
| 2 |
+
|
| 3 |
+
The normal Docker image contains **separate** SAM and GVHMR Python runtimes.
|
| 4 |
+
The API remains available when either model is unconfigured. SAM stays the default.
|
| 5 |
+
No new public route, Gemini key or GPU purchase is needed to select GVHMR.
|
| 6 |
+
|
| 7 |
+
## Required operator-supplied file
|
| 8 |
+
|
| 9 |
+
Obtain the neutral SMPL-X model from the [official SMPL-X provider](https://smpl-x.is.tue.mpg.de/)
|
| 10 |
+
under the applicable license. The required file is `SMPLX_NEUTRAL.npz`.
|
| 11 |
+
SAM's approved Hugging Face access does not grant SMPL-X access. The setup never
|
| 12 |
+
downloads licensed body models from third-party public mirrors.
|
| 13 |
+
|
| 14 |
+
For a Docker server, mount that file read-only and set:
|
| 15 |
+
|
| 16 |
+
```text
|
| 17 |
+
BASEBALL_SMPLX_MODEL_PATH=/models/smplx/SMPLX_NEUTRAL.npz
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
For the existing Hugging Face Space, store your licensed copy in an appropriately
|
| 21 |
+
private model repository accessible to the Space's existing `HF_TOKEN`. Set:
|
| 22 |
+
|
| 23 |
+
```text
|
| 24 |
+
BASEBALL_SMPLX_REPO=your-owner/your-private-body-model-repository
|
| 25 |
+
BASEBALL_SMPLX_FILENAME=SMPLX_NEUTRAL.npz
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
Set `BASEBALL_SMPLX_REVISION` to pin a specific repository commit if desired.
|
| 29 |
+
Do not put the file in the public Space or GitHub repository. Restart after
|
| 30 |
+
configuring the file location. The startup downloader resolves/pins revisions,
|
| 31 |
+
records checksums and creates `/data/gvhmr-api-worker.json`. Setup failures report
|
| 32 |
+
safe reason codes without printing tokens or provider response bodies.
|
| 33 |
+
|
| 34 |
+
Until the file is supplied, capabilities reports
|
| 35 |
+
`gvhmr_smplx_license_asset_required`, and selecting GVHMR returns 503. SAM keeps
|
| 36 |
+
working. After setup, `configured: true` means files/dependencies are configured;
|
| 37 |
+
successful GPU inference must still be verified with an actual recording.
|
| 38 |
+
|
| 39 |
+
## Runtime and checkpoints
|
| 40 |
+
|
| 41 |
+
Source: [official GVHMR](https://github.com/zju3dv/GVHMR), pinned to
|
| 42 |
+
`ee960bb6e2ea2d381aa97f08e9b71ef320b624b1`.
|
| 43 |
+
|
| 44 |
+
The isolated Python 3.10 runtime uses upstream's Torch 2.3 / CUDA 12.1 stack and
|
| 45 |
+
official PyTorch3D wheel. Docker builds run inference-import/configuration
|
| 46 |
+
preflight without accessing a body model. SAM retains its own existing runtime.
|
| 47 |
+
|
| 48 |
+
Startup obtains only the three non-body checkpoints from the mirror used by
|
| 49 |
+
the upstream project's linked Hugging Face demo: GVHMR release, HMR2 features,
|
| 50 |
+
and ViTPose. `BASEBALL_GVHMR_WEIGHTS_REPO` and
|
| 51 |
+
`BASEBALL_GVHMR_WEIGHTS_REVISION` can select an operator-managed mirror/revision.
|
| 52 |
+
The manifest records source revision and SHA-256 for all four model assets.
|
| 53 |
+
GVHMR's [license](https://github.com/zju3dv/GVHMR/blob/main/LICENSE) restricts use
|
| 54 |
+
to educational, research and non-profit purposes; check the applicable terms
|
| 55 |
+
before commercial deployment. This integration does not change those terms.
|
| 56 |
+
|
| 57 |
+
For an existing installed runtime, use `tools/register_gvhmr_api_worker.py` with
|
| 58 |
+
`--worker-python`, `--gvhmr-repo`, `--gvhmr-checkpoint`, `--hmr2-checkpoint`,
|
| 59 |
+
`--vitpose-checkpoint`, `--smplx-model`, and `--output`. Set
|
| 60 |
+
`BASEBALL_GVHMR_WORKER_RECORD` to that output file. Registration verifies the
|
| 61 |
+
pinned source and asset hashes; it does not download files.
|
| 62 |
+
|
| 63 |
+
## Test both models
|
| 64 |
+
|
| 65 |
+
Use [the same motion API](MOTION_PLAYER_API.md), with `options.model` equal to
|
| 66 |
+
`sam3d` or `gvhmr`. Follow returned status/result URLs. Test the same uploaded
|
| 67 |
+
source through `source_asset_id` or a model-switch revision. Each output carries
|
| 68 |
+
the selected model, anatomy, timestamp mapping and independent immutable files.
|
| 69 |
+
|
| 70 |
+
The adapter tests verify mapping, timestamps, missing observations, SO(3)
|
| 71 |
+
resampling, projections and reproducible measurements using known synthetic
|
| 72 |
+
sequences. They do not establish GVHMR's real-video accuracy. Real GPU comparison
|
| 73 |
+
requires the licensed file; independent reference validation is still separate.
|
docs/MOTION_PLAYER_API.md
CHANGED
|
@@ -1,12 +1,49 @@
|
|
| 1 |
# Motion-player backend API
|
| 2 |
|
| 3 |
-
|
| 4 |
|
| 5 |
Base URL: `https://modventures-baseball-engine.hf.space`. Use the existing server
|
| 6 |
Bearer key for every `/v1/` request. Keep that shared credential in your app's
|
| 7 |
backend. This separate API preserves the current engine/product/SAM contracts.
|
| 8 |
It exports actual corrected motion for an interactive skeleton player, using
|
| 9 |
-
SAM 3D Body
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
## Routes
|
| 12 |
|
|
@@ -32,6 +69,7 @@ Example options, **only when these recording facts are known**:
|
|
| 32 |
|
| 33 |
```json
|
| 34 |
{
|
|
|
|
| 35 |
"handedness": "right",
|
| 36 |
"handedness_source": "Uploader supplied",
|
| 37 |
"camera_stability": "fixed_verified",
|
|
@@ -66,7 +104,7 @@ reidentification is disabled and uncertain frames remain unusable.
|
|
| 66 |
|
| 67 |
## Manifest and artifacts
|
| 68 |
|
| 69 |
-
The manifest declares the ordered 20-joint anatomical skeleton,
|
| 70 |
mapping, bones, fixed coordinates, scale interpretation, source orientation,
|
| 71 |
timing map, model/checkpoint hashes, adapter/correction revisions and settings,
|
| 72 |
measurement-definition version, quality segments and artifact integrity details.
|
|
@@ -95,9 +133,21 @@ on redeployment; configure persistent `BASEBALL_DATA_ROOT` for durable replay.
|
|
| 95 |
Every frame includes source-frame index, original PTS/time base, elapsed
|
| 96 |
`video_time_s`, elapsed `capture_time_s` or null, `segment_id`, every declared
|
| 97 |
joint, separate root translation and frame quality. Every joint has a finite
|
| 98 |
-
position or explicit null, status, null confidence when
|
| 99 |
reason codes. Gaps and filter boundaries remain explicit; there is no intentional
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
Use **video time** to synchronize with the original recording, including variable
|
| 103 |
cadence. Capture time is for physical rates; constant slowdown and explicit maps
|
|
@@ -181,6 +231,9 @@ The response retains the analysis ID, allocates a new job ID/revision and suppli
|
|
| 181 |
new URLs. The parent is unchanged. Native inference is reusable after integrity
|
| 182 |
checks when camera/crop/orientation/adapter inputs match. Changing the athlete
|
| 183 |
requires a new analysis using `source_asset_id`, giving it a new person ID.
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
## Verification limits
|
| 186 |
|
|
|
|
| 1 |
# Motion-player backend API
|
| 2 |
|
| 3 |
+
Contract 1.0 · SAM and GVHMR adapters · 15 October 2026
|
| 4 |
|
| 5 |
Base URL: `https://modventures-baseball-engine.hf.space`. Use the existing server
|
| 6 |
Bearer key for every `/v1/` request. Keep that shared credential in your app's
|
| 7 |
backend. This separate API preserves the current engine/product/SAM contracts.
|
| 8 |
It exports actual corrected motion for an interactive skeleton player, using
|
| 9 |
+
SAM 3D Body or GVHMR through the same routes. A client frontend and animated
|
| 10 |
+
body mesh are outside this version. Existing callers continue to default to SAM.
|
| 11 |
+
|
| 12 |
+
## Choose the model
|
| 13 |
+
|
| 14 |
+
Set `model` inside the existing form-data `options` JSON:
|
| 15 |
+
|
| 16 |
+
```json
|
| 17 |
+
{"model": "sam3d", "annotated_videos": true}
|
| 18 |
+
```
|
| 19 |
+
|
| 20 |
+
or:
|
| 21 |
+
|
| 22 |
+
```json
|
| 23 |
+
{"model": "gvhmr", "annotated_videos": true}
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
Every recording fact, polling route and artifact format stays the same. Read
|
| 27 |
+
`GET /v1/motion-analyses/capabilities`: `models` lists both adapters with their
|
| 28 |
+
individual `configured` status and setup reason. One unavailable model does not
|
| 29 |
+
disable the other. An unconfigured selection returns 503 before reserving a job.
|
| 30 |
+
Unknown model names return 422. There is no silent fallback to another model.
|
| 31 |
+
GVHMR needs a licensed SMPL-X neutral file; see [GVHMR setup](GVHMR_SETUP.md).
|
| 32 |
+
|
| 33 |
+
To compare the **same recording**, first run either model, then submit a new
|
| 34 |
+
analysis with the completed manifest's `source_video.asset_id` in the
|
| 35 |
+
`source_asset_id` form field and the other model in `options`. This reuses the
|
| 36 |
+
original bytes without another upload. Alternatively change `model` through
|
| 37 |
+
`/revisions`; it creates a new immutable revision and runs fresh inference.
|
| 38 |
+
The parent artifacts remain unchanged. This API does not use Gemini.
|
| 39 |
+
|
| 40 |
+
Both adapters declare the same 20 canonical names. Their native anatomical
|
| 41 |
+
definitions differ: SAM uses MHR70 landmarks; GVHMR uses SMPL-X joint centers
|
| 42 |
+
and its explicitly documented ear/foot surface landmarks. The SMPL-X adapter has
|
| 43 |
+
its own `batting-corrected-points-smplx-v1` measurement definition revision,
|
| 44 |
+
retaining the companion document's formulas. Do not pool numbers from different
|
| 45 |
+
models as interchangeable measurements or use a model switch as evidence of
|
| 46 |
+
player improvement. Each manifest records the actual native indices/definitions.
|
| 47 |
|
| 48 |
## Routes
|
| 49 |
|
|
|
|
| 69 |
|
| 70 |
```json
|
| 71 |
{
|
| 72 |
+
"model": "sam3d",
|
| 73 |
"handedness": "right",
|
| 74 |
"handedness_source": "Uploader supplied",
|
| 75 |
"camera_stability": "fixed_verified",
|
|
|
|
| 104 |
|
| 105 |
## Manifest and artifacts
|
| 106 |
|
| 107 |
+
The manifest declares the ordered 20-joint anatomical skeleton, actual native
|
| 108 |
mapping, bones, fixed coordinates, scale interpretation, source orientation,
|
| 109 |
timing map, model/checkpoint hashes, adapter/correction revisions and settings,
|
| 110 |
measurement-definition version, quality segments and artifact integrity details.
|
|
|
|
| 133 |
Every frame includes source-frame index, original PTS/time base, elapsed
|
| 134 |
`video_time_s`, elapsed `capture_time_s` or null, `segment_id`, every declared
|
| 135 |
joint, separate root translation and frame quality. Every joint has a finite
|
| 136 |
+
position or explicit null, status, null confidence when the model supplies none, and
|
| 137 |
reason codes. Gaps and filter boundaries remain explicit; there is no intentional
|
| 138 |
+
source-frame skipping, invented confidence or gap interpolation.
|
| 139 |
+
|
| 140 |
+
GVHMR additionally records its 30-Hz temporal conditioning grid and source-time
|
| 141 |
+
mapping. The grid uses physical capture time when known, otherwise playback
|
| 142 |
+
time. Rotation parameters use SO(3) interpolation back to source timestamps;
|
| 143 |
+
affected joints carry `interpolated` status and explicit provenance, and dependent
|
| 144 |
+
metrics record interpolated input. This does not fill missing athlete tracks or
|
| 145 |
+
source clock gaps. Long sequences use bounded windows with context; window
|
| 146 |
+
boundaries start new segments and are excluded from derivative evidence.
|
| 147 |
+
The `gvhmr` options expose batch size, window/context sizes and input-2D quality
|
| 148 |
+
thresholds. These scores gate model inputs; they are not calibrated 3D confidence.
|
| 149 |
+
Background camera-rotation failures remain unusable frames. Camera rotation and
|
| 150 |
+
the model's native global prediction do not become calibrated ground coordinates.
|
| 151 |
|
| 152 |
Use **video time** to synchronize with the original recording, including variable
|
| 153 |
cadence. Capture time is for physical rates; constant slowdown and explicit maps
|
|
|
|
| 231 |
new URLs. The parent is unchanged. Native inference is reusable after integrity
|
| 232 |
checks when camera/crop/orientation/adapter inputs match. Changing the athlete
|
| 233 |
requires a new analysis using `source_asset_id`, giving it a new person ID.
|
| 234 |
+
Changing the reconstruction model, checkpoint, or GVHMR temporal conditioning
|
| 235 |
+
(clock, camera stability, gap threshold, native settings) prevents inference reuse.
|
| 236 |
+
Correction-only changes can reuse the selected model's verified native output.
|
| 237 |
|
| 238 |
## Verification limits
|
| 239 |
|
docs/MOTION_REQUIREMENTS_AUDIT.md
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Motion-player requirements audit
|
| 2 |
+
|
| 3 |
+
Against `Motion_Player_Backend_Requirements.md` v1.0, 15 October 2026.
|
| 4 |
+
|
| 5 |
+
| Requirement | Implementation and verification |
|
| 6 |
+
| --- | --- |
|
| 7 |
+
| Shared contract and model selector | `MotionInput.model`: `sam3d` (default), `gvhmr`. Separate runtime checks, native adapters and anatomy/definition revisions. No fallback. Model-switch and compatibility tests. |
|
| 8 |
+
| Source upload or backend asset | Authenticated multipart upload or `source_asset_id`; no arbitrary URL/path input. Source bytes retained and checksummed. |
|
| 9 |
+
| Manifest, lineage and versions | Immutable analysis/job/revision/person IDs; model/source/asset hashes, adapter, correction inputs and definition revision. |
|
| 10 |
+
| Original PTS, VFR, retiming | Every source frame retained. Video and capture clocks exported separately. GVHMR explicitly maps a 30-Hz model grid back to original times; rotation interpolation uses SO(3). |
|
| 11 |
+
| Athlete selection and identity | Required box when ambiguous; conservative continuity. Lost/ambiguous identity stays unusable, never automatically reassigned. |
|
| 12 |
+
| Correct and check motion | Shared adaptive temporal filter, bone-proportion/spike checks, no gap filling, explicit filter and model-window boundaries. GVHMR adds 2D observation/reprojection gates and background camera-rotation checks. These are consistency checks, not accuracy validation. |
|
| 13 |
+
| Anatomy and canonical names | Both export all 20 names. Native joint definitions/indices verified. SMPL-X surface-derived landmarks explicitly marked; no claim that its hips/shoulders equal MHR70 landmarks. |
|
| 14 |
+
| Coordinates, scale and root | Fixed camera/declared reference axes; hip-relative positions, root separate, added once for projection. Model scale documented; unknown scale disables absolute measurements. Native global predictions are not promoted to calibrated ground motion. |
|
| 15 |
+
| Motion and quality artifacts | Finite positions or null, status/confidence/reasons for every joint/frame, explicit gaps/segments, stable skeleton/bones. No invented cross-model confidence. |
|
| 16 |
+
| Four measurement groups and graphs | Existing companion formulas from corrected exported points. Separate SMPL-X definition revision documents the anatomical change. Public-artifact reproduction verified for both adapters. |
|
| 17 |
+
| Events and reviewed corrections | Source frames/timestamps, individual manual/estimated provenance and unavailable events. A reviewed surrounding window does not falsely make an automatic baseline/forward boundary manual. New revision retains parent. |
|
| 18 |
+
| Projections and annotation | Same corrected sequence and intrinsics produce JSON projections and all four videos. Source playback timeline preserved; no bottom panel. |
|
| 19 |
+
| Ready/failed semantics | No usable motion fails. Missing selected model returns actionable 503 before job allocation; other model and old APIs remain available. Publish after referenced artifacts are ready. |
|
| 20 |
+
| Auth, retention, cancellation | Existing queue/auth, safe artifact allowlist, checksums/ranges/expiry, cancellation and staging cleanup retained. Durable replay requires persistent storage. |
|
| 21 |
+
| Optional ground/distortion inputs | This release supports declared up/field axes and pinhole intrinsics; it does not implement a calibrated ground trajectory or lens-distortion correction. Dependent results remain unavailable, with explicit metadata/reasons. No unsupported calibration claim. |
|
| 22 |
+
| Optional animated mesh | Deferred second phase, as the document allows. Artifact explicitly unavailable; skeleton remains measurement source. |
|
| 23 |
+
| Reference accuracy acceptance criterion 9 | **Pending independent reference data.** Fixture/round-trip tests establish arithmetic and alignment, not hidden-depth or arbitrary real-video accuracy. |
|
| 24 |
+
| Real GVHMR GPU validation | **Requires the operator's licensed SMPL-X neutral file.** Dependency/configuration and synthetic adapter tests do not count as completed real inference. |
|
| 25 |
+
|
| 26 |
+
Existing `/v1/analyses`, `/product`, and `/v1/sam-batting/analyses` contracts remain
|
| 27 |
+
separate. The selector is added only to `/v1/motion-analyses`.
|
docs/motion-input.schema.json
CHANGED
|
@@ -97,6 +97,48 @@
|
|
| 97 |
"title": "CorrectionSettings",
|
| 98 |
"type": "object"
|
| 99 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
"MeasurementSettings": {
|
| 101 |
"additionalProperties": false,
|
| 102 |
"properties": {
|
|
@@ -597,6 +639,18 @@
|
|
| 597 |
"title": "Coaching",
|
| 598 |
"type": "boolean"
|
| 599 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
"annotated_videos": {
|
| 601 |
"default": true,
|
| 602 |
"title": "Annotated Videos",
|
|
|
|
| 97 |
"title": "CorrectionSettings",
|
| 98 |
"type": "object"
|
| 99 |
},
|
| 100 |
+
"GVHMRSettings": {
|
| 101 |
+
"additionalProperties": false,
|
| 102 |
+
"properties": {
|
| 103 |
+
"batch_size": {
|
| 104 |
+
"default": 4,
|
| 105 |
+
"maximum": 16,
|
| 106 |
+
"minimum": 1,
|
| 107 |
+
"title": "Batch Size",
|
| 108 |
+
"type": "integer"
|
| 109 |
+
},
|
| 110 |
+
"max_sequence_frames": {
|
| 111 |
+
"default": 300,
|
| 112 |
+
"maximum": 900,
|
| 113 |
+
"minimum": 90,
|
| 114 |
+
"title": "Max Sequence Frames",
|
| 115 |
+
"type": "integer"
|
| 116 |
+
},
|
| 117 |
+
"context_frames": {
|
| 118 |
+
"default": 30,
|
| 119 |
+
"maximum": 60,
|
| 120 |
+
"minimum": 10,
|
| 121 |
+
"title": "Context Frames",
|
| 122 |
+
"type": "integer"
|
| 123 |
+
},
|
| 124 |
+
"minimum_keypoint_score": {
|
| 125 |
+
"default": 0.3,
|
| 126 |
+
"maximum": 1,
|
| 127 |
+
"minimum": 0,
|
| 128 |
+
"title": "Minimum Keypoint Score",
|
| 129 |
+
"type": "number"
|
| 130 |
+
},
|
| 131 |
+
"maximum_reprojection_box_fraction": {
|
| 132 |
+
"default": 0.15,
|
| 133 |
+
"exclusiveMinimum": 0,
|
| 134 |
+
"maximum": 1,
|
| 135 |
+
"title": "Maximum Reprojection Box Fraction",
|
| 136 |
+
"type": "number"
|
| 137 |
+
}
|
| 138 |
+
},
|
| 139 |
+
"title": "GVHMRSettings",
|
| 140 |
+
"type": "object"
|
| 141 |
+
},
|
| 142 |
"MeasurementSettings": {
|
| 143 |
"additionalProperties": false,
|
| 144 |
"properties": {
|
|
|
|
| 639 |
"title": "Coaching",
|
| 640 |
"type": "boolean"
|
| 641 |
},
|
| 642 |
+
"model": {
|
| 643 |
+
"default": "sam3d",
|
| 644 |
+
"enum": [
|
| 645 |
+
"sam3d",
|
| 646 |
+
"gvhmr"
|
| 647 |
+
],
|
| 648 |
+
"title": "Model",
|
| 649 |
+
"type": "string"
|
| 650 |
+
},
|
| 651 |
+
"gvhmr": {
|
| 652 |
+
"$ref": "#/$defs/GVHMRSettings"
|
| 653 |
+
},
|
| 654 |
"annotated_videos": {
|
| 655 |
"default": true,
|
| 656 |
"title": "Annotated Videos",
|
requirements-gvhmr.txt
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Isolated Python 3.10 runtime; never install into the SAM/API environments.
|
| 2 |
+
numpy==1.23.5
|
| 3 |
+
scipy==1.13.1
|
| 4 |
+
torch==2.3.0+cu121
|
| 5 |
+
torchvision==0.18.0+cu121
|
| 6 |
+
--extra-index-url https://download.pytorch.org/whl/cu121
|
| 7 |
+
pytorch3d @ https://dl.fbaipublicfiles.com/pytorch3d/packaging/wheels/py310_cu121_pyt230/pytorch3d-0.7.6-cp310-cp310-linux_x86_64.whl
|
| 8 |
+
timm==0.9.12
|
| 9 |
+
lightning==2.3.0
|
| 10 |
+
pytorch-lightning==2.3.0
|
| 11 |
+
torchmetrics==1.4.3
|
| 12 |
+
hydra-core==1.3.2
|
| 13 |
+
hydra-zen==0.13.0
|
| 14 |
+
hydra-colorlog==1.2.0
|
| 15 |
+
rich==13.9.4
|
| 16 |
+
opencv-python-headless==4.11.0.86
|
| 17 |
+
# Upstream's preproc package imports its Tracker even though our adapter uses
|
| 18 |
+
# the shared conservative tracker. Keep its import dependencies available.
|
| 19 |
+
opencv-python==4.11.0.86
|
| 20 |
+
ultralytics==8.2.42
|
| 21 |
+
av==13.0.0
|
| 22 |
+
imageio==2.34.1
|
| 23 |
+
einops==0.8.1
|
| 24 |
+
smplx==0.1.28
|
| 25 |
+
trimesh==4.6.8
|
| 26 |
+
wis3d==1.0.1
|
| 27 |
+
pycolmap==3.10.0
|
| 28 |
+
yacs==0.1.8
|
| 29 |
+
joblib==1.4.2
|
| 30 |
+
tqdm==4.67.1
|
| 31 |
+
tensorboardX==2.6.2.2
|
| 32 |
+
termcolor==2.5.0
|
| 33 |
+
scikit-image==0.24.0
|
| 34 |
+
ffmpeg-python==0.2.0
|
| 35 |
+
pydantic==2.12.3
|
| 36 |
+
PyYAML==6.0.2
|
| 37 |
+
huggingface-hub==0.36.0
|
| 38 |
+
setuptools==75.8.0
|
tests/test_gvhmr_motion.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Known-sequence adapter/clock/export checks. These do not claim model accuracy."""
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pytest
|
| 6 |
+
from fastapi.testclient import TestClient
|
| 7 |
+
from baseball_batting.motion_contract import MotionInput
|
| 8 |
+
from baseball_batting.motion_adapters import SMPLX_MAP,MHR,smplx_to_calculation,skeleton,GVHMR_REVISION
|
| 9 |
+
from baseball_batting.gvhmr_adapter import native_prediction,uniform_grid,resample_rotations,sequence_windows,COCO
|
| 10 |
+
from baseball_batting.motion_export import export_motion,reproduce_measurements
|
| 11 |
+
from baseball_batting.storage import atomic_json,sha256_file
|
| 12 |
+
from baseball_batting.ingest import ingest
|
| 13 |
+
from baseball_batting.geometry import project
|
| 14 |
+
from baseball_batting.api import create_app
|
| 15 |
+
from baseball_batting.api_jobs import JobService
|
| 16 |
+
from test_motion_player import raw_for,inputs
|
| 17 |
+
from test_api import settings,fake_service,wait_until,AUTH
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def native_fixture(capture):
|
| 21 |
+
original=raw_for(capture);n=capture['frame_count']
|
| 22 |
+
names=['unused']*76
|
| 23 |
+
native=np.full((n,76,3),np.nan)
|
| 24 |
+
for name,index in SMPLX_MAP.items():names[index]=name;native[:,index]=original['points_body'][:,MHR[name]]
|
| 25 |
+
observed=np.zeros((n,17,3));observed[:,:,2]=1
|
| 26 |
+
for name,index in COCO.items():observed[:,index,:2]=original['projection'][:,MHR[name]]
|
| 27 |
+
boxes=np.tile([0,0,*original['image_size']],(n,1))
|
| 28 |
+
raw=native_prediction(native,names,original['camera_translation'],original['intrinsics'],
|
| 29 |
+
original['image_size'],observed,boxes,MotionInput().gvhmr.model_dump())
|
| 30 |
+
return raw,native,names,observed,boxes
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_native_mapping_is_checked_and_translation_is_not_added_twice(video):
|
| 34 |
+
capture=ingest(video,inputs().metadata());raw,native,names,observed,boxes=native_fixture(capture)
|
| 35 |
+
np.testing.assert_allclose(raw['points_body'][:,MHR['left_hip']],native[:,1])
|
| 36 |
+
np.testing.assert_allclose(raw['projection'][:,MHR['right_wrist']],
|
| 37 |
+
np.array([project(j[21]+c,k) for j,c,k in zip(native,raw['camera_translation'],raw['intrinsics'])]))
|
| 38 |
+
assert skeleton('gvhmr')['joints'][0]['derived'] is True
|
| 39 |
+
shoulder=next(j for j in skeleton('gvhmr')['joints'] if j['name']=='left_shoulder')
|
| 40 |
+
assert shoulder['source_index']==16 and shoulder['source_schema']=='SMPL-X' and shoulder['derived'] is False
|
| 41 |
+
names[16]='left_acromion'
|
| 42 |
+
with pytest.raises(ValueError,match='anatomical mapping'):smplx_to_calculation(native,names)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_occluded_wrist_and_camera_inconsistency_disable_only_dependent_points(video):
|
| 46 |
+
capture=ingest(video,inputs().metadata());raw,native,names,observed,boxes=native_fixture(capture)
|
| 47 |
+
observed[3,COCO['right_wrist'],2]=.01
|
| 48 |
+
observed[4,COCO['left_wrist'],0]+=1000
|
| 49 |
+
out=native_prediction(native,names,raw['camera_translation'],raw['intrinsics'],raw['image_size'],
|
| 50 |
+
observed,boxes,MotionInput().gvhmr.model_dump())
|
| 51 |
+
assert not out['joint_usable'][3,MHR['right_wrist']]
|
| 52 |
+
assert not out['joint_usable'][4,MHR['left_wrist']]
|
| 53 |
+
assert out['joint_usable'][:,[MHR['left_ankle'],MHR['right_ankle']]].all()
|
| 54 |
+
assert out['projection_valid'].all()
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_uniform_model_clock_rotations_and_chunks_do_not_bridge_gaps():
|
| 58 |
+
t=np.array([0,.016,.033,.051,.066,.083,1.,1.016,1.033,1.05])
|
| 59 |
+
grid=uniform_grid(t[:6]);np.testing.assert_allclose(np.diff(grid),1/30)
|
| 60 |
+
# +170 -> -170 degrees takes the short route through 180, never through zero.
|
| 61 |
+
rotations=np.deg2rad([[0,0,170],[0,0,-170]])
|
| 62 |
+
result=resample_rotations(rotations,np.array([0.,1.]),np.array([.5]))
|
| 63 |
+
assert abs(np.linalg.norm(result[0])-np.pi)<1e-8
|
| 64 |
+
windows=list(sequence_windows(np.ones(len(t),bool),t,.1,90,10))
|
| 65 |
+
assert len(windows)==2
|
| 66 |
+
assert windows[0][0].tolist()==list(range(6)) and windows[1][0].tolist()==list(range(6,10))
|
| 67 |
+
dense=np.arange(800)/60
|
| 68 |
+
chunks=list(sequence_windows(np.ones(len(dense),bool),dense,.1,90,10))
|
| 69 |
+
owners=np.zeros(len(dense),int)
|
| 70 |
+
for run,g,a,b,start,end in chunks:
|
| 71 |
+
source=dense[run]
|
| 72 |
+
take=run[(source>=g[start])&((source<g[end]) if end<len(g) else (source<=g[-1]))]
|
| 73 |
+
owners[take]+=1
|
| 74 |
+
assert b-a<=90
|
| 75 |
+
assert (owners==1).all()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_gvhmr_public_motion_reproduces_measurements_and_annotated_timeline(tmp_path,video):
|
| 79 |
+
opts=inputs(model='gvhmr',timing={'kind':'unretimed','source':'Known fixture clock'})
|
| 80 |
+
capture=ingest(video,opts.metadata());raw,*_=native_fixture(capture)
|
| 81 |
+
raw['sequence_ids']=np.zeros(capture['frame_count'],int)
|
| 82 |
+
raw['temporal_resampled']=np.array([False,True,False,True,False,True,False,False])
|
| 83 |
+
manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'synthetic SMPL-X adapter fixture'},
|
| 84 |
+
{'analysis_id':'fixture','analysis_revision':1})
|
| 85 |
+
assert manifest.pipeline['selected_model']=='gvhmr'
|
| 86 |
+
assert manifest.pipeline['measurement_definition_version']=='batting-corrected-points-smplx-v1'
|
| 87 |
+
assert manifest.coordinates['left_right'].endswith('SMPL-X')
|
| 88 |
+
assert manifest.skeleton['version']=='smplx-batting-20-v1'
|
| 89 |
+
rows=[json.loads(line) for line in (tmp_path/'motion.jsonl').read_text().splitlines()]
|
| 90 |
+
assert len(rows)==capture['frame_count'] and all(len(f['joints'])==20 for f in rows)
|
| 91 |
+
assert rows[1]['joints']['left_shoulder']['status']=='interpolated'
|
| 92 |
+
assert 'smplx_surface_landmark_derivation' in rows[0]['joints']['left_ear']['reasons']
|
| 93 |
+
groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
|
| 94 |
+
values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
|
| 95 |
+
summaries=json.loads((tmp_path/'measurements.json').read_text())['summaries']
|
| 96 |
+
for metric in summaries:assert values[metric['rep'],metric['metric_id']]==metric['value']
|
| 97 |
+
assert all(m['uses_interpolated_input'] for m in summaries)
|
| 98 |
+
assert all(manifest.artifacts['annotated_'+key].status=='available' for key in ('rotation','timing','posture','stance'))
|
| 99 |
+
from baseball_batting.ingest import iter_frames
|
| 100 |
+
assert [float(pts*base) for _,pts,base,_ in iter_frames(tmp_path/'group-videos/rotation.mp4')]==pytest.approx([f['video_time_s'] for f in rows],abs=2e-6)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_model_selector_readiness_is_independent_and_unknown_model_is_rejected(tmp_path,video,monkeypatch):
|
| 104 |
+
import baseball_batting.motion_api as module
|
| 105 |
+
service=fake_service(settings(tmp_path),delay=30)
|
| 106 |
+
monkeypatch.setattr(module,'configured_record',lambda:None)
|
| 107 |
+
monkeypatch.setattr(module.gvhmr_runtime,'configured_record',lambda:{'configured':True})
|
| 108 |
+
files={'video':('clip.mp4',video.read_bytes(),'video/mp4')}
|
| 109 |
+
with TestClient(create_app(service.settings,service)) as client:
|
| 110 |
+
wait_until(lambda:service.ready)
|
| 111 |
+
capability=client.get('/v1/motion-analyses/capabilities',headers=AUTH).json()
|
| 112 |
+
assert capability['default_model']=='sam3d' and {m['id'] for m in capability['models']}=={'sam3d','gvhmr'}
|
| 113 |
+
assert client.post('/v1/motion-analyses',headers=AUTH,files=files,data={'options':'{"model":"other"}'}).status_code==422
|
| 114 |
+
assert client.post('/v1/motion-analyses',headers=AUTH,files=files).status_code==503
|
| 115 |
+
r=client.post('/v1/motion-analyses',headers=AUTH,files=files,data={'options':'{"model":"gvhmr"}'})
|
| 116 |
+
assert r.status_code==202,r.text
|
| 117 |
+
job=service.job_directory(r.json()['job_id'])
|
| 118 |
+
assert json.loads((job/'request.json').read_text())['model']=='gvhmr'
|
| 119 |
+
client.delete(r.json()['status_url'],headers=AUTH)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def test_model_switch_runs_fresh_inference_and_preserves_parent(tmp_path,video,monkeypatch):
|
| 123 |
+
import baseball_batting.motion_worker as worker
|
| 124 |
+
import baseball_batting.motion_api as api
|
| 125 |
+
service=JobService(settings(tmp_path));service.ready=True;calls=[]
|
| 126 |
+
monkeypatch.setattr(api,'configured_record',lambda:{'configured':True})
|
| 127 |
+
monkeypatch.setattr(api.gvhmr_runtime,'configured_record',lambda:{'configured':True})
|
| 128 |
+
def infer(model,job,source,capture):
|
| 129 |
+
calls.append(model);raw=raw_for(capture) if model=='sam3d' else native_fixture(capture)[0]
|
| 130 |
+
stem='sam' if model=='sam3d' else 'gvhmr'
|
| 131 |
+
np.savez_compressed(job/(stem+'-raw-private.npz'),**raw)
|
| 132 |
+
atomic_json(job/(stem+'-raw-private.json'),{'model':{'name':model+' fixture'}})
|
| 133 |
+
atomic_json(job/'person-track-private.json',{'reasons':[None]*capture['frame_count']})
|
| 134 |
+
return raw,{'name':model+' fixture'}
|
| 135 |
+
monkeypatch.setattr(worker,'reconstruct_sam',lambda job,source,capture,*a,**k:infer('sam3d',job,source,capture))
|
| 136 |
+
monkeypatch.setattr(worker,'reconstruct_gvhmr',lambda job,source,capture,*a,**k:infer('gvhmr',job,source,capture))
|
| 137 |
+
lineage=service.store.create_motion(20);parent=service.job_directory(lineage['job_id']);parent.mkdir()
|
| 138 |
+
(parent/'input.mp4').write_bytes(video.read_bytes())
|
| 139 |
+
atomic_json(parent/'lineage.json',lineage)
|
| 140 |
+
atomic_json(parent/'request.json',inputs(annotated_videos=False,timing={'kind':'unretimed','source':'Fixture clock'}).model_dump(mode='json'))
|
| 141 |
+
worker.run(parent,tmp_path/'models');before=(parent/'result.json').read_bytes()
|
| 142 |
+
service.store.update(parent.name,'completed',result_hash=sha256_file(parent/'result.json'))
|
| 143 |
+
client=TestClient(create_app(service.settings,service))
|
| 144 |
+
child=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={'options':{'model':'gvhmr'}})
|
| 145 |
+
assert child.status_code==202,child.text
|
| 146 |
+
directory=service.job_directory(child.json()['job_id'])
|
| 147 |
+
assert not (directory/'reused-inference.json').exists()
|
| 148 |
+
result=worker.run(directory,tmp_path/'models')
|
| 149 |
+
assert calls==['sam3d','gvhmr'] and result.analysis_revision==2
|
| 150 |
+
assert (parent/'result.json').read_bytes()==before
|
| 151 |
+
service.store.update(directory.name,'completed',result_hash=sha256_file(directory/'result.json'))
|
| 152 |
+
reviewed=client.post('/v1/motion-analyses/'+directory.name+'/revisions',headers=AUTH,json={'options':{'correction':{'min_cutoff_hz':8}}})
|
| 153 |
+
assert reviewed.status_code==202,reviewed.text
|
| 154 |
+
reviewed_dir=service.job_directory(reviewed.json()['job_id'])
|
| 155 |
+
assert (reviewed_dir/'reused-inference.json').exists()
|
| 156 |
+
worker.run(reviewed_dir,tmp_path/'models');assert calls==['sam3d','gvhmr']
|
| 157 |
+
different_clock=client.post('/v1/motion-analyses/'+directory.name+'/revisions',headers=AUTH,json={'options':{'timing':{'kind':'unknown'}}})
|
| 158 |
+
assert different_clock.status_code==202
|
| 159 |
+
assert not (service.job_directory(different_clock.json()['job_id'])/'reused-inference.json').exists()
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_missing_licensed_body_model_stops_setup_before_any_download(tmp_path,monkeypatch):
|
| 163 |
+
from tools import prepare_gvhmr_assets
|
| 164 |
+
monkeypatch.setenv('BASEBALL_DATA_ROOT',str(tmp_path))
|
| 165 |
+
monkeypatch.setenv('BASEBALL_GVHMR_SOURCE',str(tmp_path))
|
| 166 |
+
monkeypatch.delenv('BASEBALL_SMPLX_MODEL_PATH',raising=False);monkeypatch.delenv('BASEBALL_SMPLX_REPO',raising=False)
|
| 167 |
+
monkeypatch.setattr(prepare_gvhmr_assets.subprocess,'check_output',lambda *a,**k:GVHMR_REVISION)
|
| 168 |
+
assert prepare_gvhmr_assets.main()==1
|
| 169 |
+
assert json.loads((tmp_path/'gvhmr-setup-status.json').read_text())['reason_code']=='gvhmr_smplx_license_asset_required'
|
| 170 |
+
assert not (tmp_path/'gvhmr-cache').exists()
|
tools/check_gvhmr_runtime.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dependency/configuration preflight; no checkpoint load or body-model access."""
|
| 2 |
+
import importlib
|
| 3 |
+
from hydra import compose,initialize_config_module
|
| 4 |
+
from smplx.joint_names import JOINT_NAMES
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def main():
|
| 8 |
+
for module in ('hmr4d.utils.preproc.vitpose','hmr4d.utils.preproc.vitfeat_extractor',
|
| 9 |
+
'hmr4d.network.gvhmr.relative_transformer','hmr4d.model.gvhmr.utils.endecoder',
|
| 10 |
+
'hmr4d.model.gvhmr.gvhmr_pl_demo','hmr4d.model.gvhmr.pipeline.gvhmr_pipeline'):
|
| 11 |
+
importlib.import_module(module)
|
| 12 |
+
with initialize_config_module(version_base='1.3',config_module='hmr4d.configs'):
|
| 13 |
+
cfg=compose(config_name='demo')
|
| 14 |
+
if cfg.model._target_!='hmr4d.model.gvhmr.gvhmr_pl_demo.DemoPL':raise ValueError('Unexpected GVHMR inference configuration')
|
| 15 |
+
if JOINT_NAMES[16]!='left_shoulder' or JOINT_NAMES[59]!='left_ear':raise ValueError('Unexpected SMPL-X landmark schema')
|
| 16 |
+
print('GVHMR dependencies/configuration ready; licensed body model and GPU inference still required')
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
if __name__=='__main__':main()
|
tools/prepare_gvhmr_assets.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Startup-only GVHMR assets. Licensed SMPL-X must be supplied by the operator.
|
| 2 |
+
|
| 3 |
+
Never fetch licensed body models from public mirrors. An explicit operator-owned
|
| 4 |
+
HF model repository or mounted file is required; HF_TOKEN uses normal hub auth.
|
| 5 |
+
"""
|
| 6 |
+
import os
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
+
from baseball_batting.storage import atomic_json,sha256_file
|
| 11 |
+
from baseball_batting.motion_adapters import GVHMR_REVISION
|
| 12 |
+
|
| 13 |
+
WEIGHTS={'gvhmr_checkpoint':'gvhmr/gvhmr_siga24_release.ckpt',
|
| 14 |
+
'hmr2_checkpoint':'hmr2/epoch=10-step=25000.ckpt',
|
| 15 |
+
'vitpose_checkpoint':'vitpose/vitpose-h-multi-coco.pth'}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def link(source,destination):
|
| 19 |
+
destination.parent.mkdir(parents=True,exist_ok=True)
|
| 20 |
+
source=Path(source).resolve()
|
| 21 |
+
if destination.exists() or destination.is_symlink():
|
| 22 |
+
if destination.resolve()==source:return
|
| 23 |
+
if not destination.is_symlink():raise ValueError('Existing GVHMR asset differs; register an isolated source checkout')
|
| 24 |
+
destination.unlink()
|
| 25 |
+
destination.symlink_to(source)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def main():
|
| 29 |
+
root=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'));root.mkdir(parents=True,exist_ok=True)
|
| 30 |
+
status=root/'gvhmr-setup-status.json'
|
| 31 |
+
def state(reason=None):atomic_json(status,{'status':'configured' if reason is None else 'unavailable','reason_code':reason})
|
| 32 |
+
try:
|
| 33 |
+
source=Path(os.environ.get('BASEBALL_GVHMR_SOURCE','/opt/gvhmr-source'))
|
| 34 |
+
if not source.is_dir():state('gvhmr_runtime_not_installed');return 1
|
| 35 |
+
rev=subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()
|
| 36 |
+
if rev!=GVHMR_REVISION:state('gvhmr_source_revision_mismatch');return 1
|
| 37 |
+
body=os.environ.get('BASEBALL_SMPLX_MODEL_PATH')
|
| 38 |
+
body_repo=os.environ.get('BASEBALL_SMPLX_REPO')
|
| 39 |
+
if not body and not body_repo:
|
| 40 |
+
state('gvhmr_smplx_license_asset_required');return 1
|
| 41 |
+
from huggingface_hub import HfApi,hf_hub_download
|
| 42 |
+
api=HfApi();body_revision=None
|
| 43 |
+
if body_repo:
|
| 44 |
+
body_revision=os.environ.get('BASEBALL_SMPLX_REVISION') or api.model_info(body_repo).sha
|
| 45 |
+
body=hf_hub_download(body_repo,os.environ.get('BASEBALL_SMPLX_FILENAME','SMPLX_NEUTRAL.npz'),
|
| 46 |
+
revision=body_revision,cache_dir=root/'gvhmr-cache')
|
| 47 |
+
body=Path(body)
|
| 48 |
+
if not body.is_file():state('gvhmr_smplx_file_missing');return 1
|
| 49 |
+
# This is the checkpoint mirror referenced by the upstream project's own
|
| 50 |
+
# linked HF demo. Only the three non-body-model assets are downloaded.
|
| 51 |
+
weights_repo=os.environ.get('BASEBALL_GVHMR_WEIGHTS_REPO','camenduru/GVHMR')
|
| 52 |
+
weights_revision=os.environ.get('BASEBALL_GVHMR_WEIGHTS_REVISION') or api.model_info(weights_repo).sha
|
| 53 |
+
assets={key:Path(hf_hub_download(weights_repo,filename,revision=weights_revision,
|
| 54 |
+
cache_dir=root/'gvhmr-cache')) for key,filename in WEIGHTS.items()}
|
| 55 |
+
assets['smplx_model']=body
|
| 56 |
+
for key,filename in WEIGHTS.items():link(assets[key],source/'inputs/checkpoints'/filename)
|
| 57 |
+
link(body,source/'inputs/checkpoints/body_models/smplx/SMPLX_NEUTRAL.npz')
|
| 58 |
+
record={'worker_python':sys.executable,'gvhmr_repo':str(source.resolve()),'source_revision':rev,
|
| 59 |
+
**{key:str(path.resolve()) for key,path in assets.items()},
|
| 60 |
+
'artifact_hashes':{key:sha256_file(path) for key,path in assets.items()},
|
| 61 |
+
'weights_repository':weights_repo,'weights_revision':weights_revision,'body_model_revision':body_revision,
|
| 62 |
+
'status':'installed_requires_inference','license_notice':'Operator supplies licensed SMPL-X; GVHMR research/non-commercial license applies'}
|
| 63 |
+
atomic_json(Path(os.environ.get('BASEBALL_GVHMR_WORKER_RECORD',str(root/'gvhmr-api-worker.json'))),record)
|
| 64 |
+
state();return 0
|
| 65 |
+
except Exception as error:
|
| 66 |
+
code=getattr(getattr(error,'response',None),'status_code',None)
|
| 67 |
+
reason={401:'gvhmr_asset_authentication_failed',403:'gvhmr_asset_access_denied',404:'gvhmr_asset_not_found'}.get(code,'gvhmr_asset_setup_failed')
|
| 68 |
+
state(reason);print('GVHMR setup unavailable: '+reason,flush=True);return 1
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if __name__=='__main__':raise SystemExit(main())
|
tools/register_gvhmr_api_worker.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Register a mounted, licensed GVHMR installation without downloads."""
|
| 2 |
+
import argparse
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import subprocess
|
| 5 |
+
from baseball_batting.motion_adapters import GVHMR_REVISION
|
| 6 |
+
from baseball_batting.storage import atomic_json,sha256_file
|
| 7 |
+
from tools.prepare_gvhmr_assets import WEIGHTS,link
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
parser=argparse.ArgumentParser()
|
| 12 |
+
for name in ('worker-python','gvhmr-repo','gvhmr-checkpoint','hmr2-checkpoint','vitpose-checkpoint','smplx-model','output'):
|
| 13 |
+
parser.add_argument('--'+name,required=True)
|
| 14 |
+
args=parser.parse_args();record={key:str(Path(value).resolve()) for key,value in vars(args).items() if key!='output'}
|
| 15 |
+
if not all(Path(value).exists() for value in record.values()):raise ValueError('Configured GVHMR assets are missing')
|
| 16 |
+
revision=subprocess.check_output(['git','-C',record['gvhmr_repo'],'rev-parse','HEAD'],text=True).strip()
|
| 17 |
+
if revision!=GVHMR_REVISION:raise ValueError('GVHMR source differs from the pinned adapter')
|
| 18 |
+
repo=Path(record['gvhmr_repo'])
|
| 19 |
+
for key,filename in WEIGHTS.items():link(record[key],repo/'inputs/checkpoints'/filename)
|
| 20 |
+
link(record['smplx_model'],repo/'inputs/checkpoints/body_models/smplx/SMPLX_NEUTRAL.npz')
|
| 21 |
+
record.update(source_revision=revision,status='installed_requires_inference',
|
| 22 |
+
artifact_hashes={key:sha256_file(record[key]) for key in (*WEIGHTS,'smplx_model')})
|
| 23 |
+
atomic_json(args.output,record)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if __name__=='__main__':main()
|
tools/start_api.py
CHANGED
|
@@ -14,6 +14,12 @@ def main():
|
|
| 14 |
except subprocess.TimeoutExpired:
|
| 15 |
path=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'))/'sam-setup-status.json'
|
| 16 |
path.write_text(json.dumps({'status':'unavailable','reason_code':'sam_asset_setup_timeout'}))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
os.execv(sys.executable,[sys.executable,'-m','uvicorn','baseball_batting.api:create_app','--factory',
|
| 18 |
'--host','0.0.0.0','--port','8000','--workers','1','--timeout-graceful-shutdown','20','--no-access-log'])
|
| 19 |
|
|
|
|
| 14 |
except subprocess.TimeoutExpired:
|
| 15 |
path=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'))/'sam-setup-status.json'
|
| 16 |
path.write_text(json.dumps({'status':'unavailable','reason_code':'sam_asset_setup_timeout'}))
|
| 17 |
+
gvhmr=Path('/opt/gvhmr-runtime/bin/python')
|
| 18 |
+
if gvhmr.is_file() and os.environ.get('BASEBALL_GVHMR_SKIP_SETUP')!='1':
|
| 19 |
+
try:subprocess.run([str(gvhmr),'-m','tools.prepare_gvhmr_assets'],timeout=600,check=False)
|
| 20 |
+
except subprocess.TimeoutExpired:
|
| 21 |
+
path=Path(os.environ.get('BASEBALL_DATA_ROOT','/data'))/'gvhmr-setup-status.json'
|
| 22 |
+
path.write_text(json.dumps({'status':'unavailable','reason_code':'gvhmr_asset_setup_timeout'}))
|
| 23 |
os.execv(sys.executable,[sys.executable,'-m','uvicorn','baseball_batting.api:create_app','--factory',
|
| 24 |
'--host','0.0.0.0','--port','8000','--workers','1','--timeout-graceful-shutdown','20','--no-access-log'])
|
| 25 |
|