github-actions[bot] commited on
Commit
d835db0
·
1 Parent(s): ae695bd

Automated Deploy: 5adf0d75b051454f4f57f2bdbd9cf6565e76db5f

Browse files
baseball_batting/api.py CHANGED
@@ -41,7 +41,8 @@ class UploadGuard:
41
  if not hmac.compare_digest(supplied, self.settings.api_key.encode()):
42
  return await JSONResponse({"detail": "Invalid or missing API key"}, status_code=401,
43
  headers={"WWW-Authenticate": "Bearer"})(scope, receive, send)
44
- limit = (4 * 1024 * 1024 if scope['path']=='/v1/sam-batting/group-reviews'
 
45
  else self.settings.max_upload_bytes + 1024 * 1024)
46
  size = headers.get(b"content-length")
47
  if size:
@@ -57,7 +58,7 @@ class UploadGuard:
57
  if received > limit:
58
  raise HTTPException(413, "Request exceeds upload limit")
59
  return message
60
- is_upload = scope["method"] == "POST" and scope["path"] in {'/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses','/v1/sam-batting/analyses'}
61
  if is_upload:
62
  if not self.service.ready:
63
  return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
@@ -77,7 +78,7 @@ def create_app(settings=None, service=None):
77
  service.start()
78
  try: yield
79
  finally: service.stop()
80
- app = FastAPI(title="Baseball Swing Engine and Coach", version="1.9.0", lifespan=lifespan,
81
  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.")
82
  app.state.service = service
83
  app.add_middleware(UploadGuard, settings=settings, service=service)
@@ -467,4 +468,6 @@ def create_app(settings=None, service=None):
467
 
468
  from .sam_api import register
469
  register(app,service,authenticated)
 
 
470
  return app
 
41
  if not hmac.compare_digest(supplied, self.settings.api_key.encode()):
42
  return await JSONResponse({"detail": "Invalid or missing API key"}, status_code=401,
43
  headers={"WWW-Authenticate": "Bearer"})(scope, receive, send)
44
+ limit = (512 * 1024 if scope['path'].startswith('/v1/motion-analyses/') and scope['path'].endswith('/revisions')
45
+ else 4 * 1024 * 1024 if scope['path']=='/v1/sam-batting/group-reviews'
46
  else self.settings.max_upload_bytes + 1024 * 1024)
47
  size = headers.get(b"content-length")
48
  if size:
 
58
  if received > limit:
59
  raise HTTPException(413, "Request exceeds upload limit")
60
  return message
61
+ is_upload = scope["method"] == "POST" and scope["path"] in {'/v1/analyses', '/v1/load-timing/analyses', '/v1/swing-coach/analyses','/v1/sam-batting/analyses','/v1/motion-analyses'}
62
  if is_upload:
63
  if not self.service.ready:
64
  return await JSONResponse({"detail": "GPU worker is not ready; check /readyz"}, status_code=503)(scope, receive, send)
 
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
+ app = FastAPI(title="Baseball Swing Engine and Coach", version="1.10.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)
 
468
 
469
  from .sam_api import register
470
  register(app,service,authenticated)
471
+ from .motion_api import register as register_motion
472
+ register_motion(app,service,authenticated)
473
  return app
baseball_batting/api_jobs.py CHANGED
@@ -86,6 +86,7 @@ class JobStore:
86
  db.execute('ALTER TABLE jobs ADD COLUMN swings_sha256 TEXT')
87
  if 'kind' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
88
  db.execute("ALTER TABLE jobs ADD COLUMN kind TEXT NOT NULL DEFAULT 'legacy'")
 
89
 
90
  @contextmanager
91
  def connect(self):
@@ -111,6 +112,27 @@ class JobStore:
111
  value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
112
  return dict(value) if value else None
113
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None, evidence_hash=None, product_hash=None, swings_hash=None):
115
  with self.connect() as db:
116
  db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=?, timing_evidence_sha256=?, product_sha256=?, swings_sha256=? WHERE id=?",
@@ -152,6 +174,7 @@ class JobStore:
152
  def forget(self, identifier):
153
  with self.connect() as db:
154
  db.execute("DELETE FROM jobs WHERE id=?", (identifier,))
 
155
 
156
  def expired(self, cutoff):
157
  with self.connect() as db:
@@ -198,10 +221,13 @@ class JobService:
198
 
199
  def job_command(self, directory):
200
  s = self.settings
201
- module='baseball_batting.sam_measurement_worker' if (self.store.get(directory.name) or {}).get('kind')=='sam_batting' else 'baseball_batting.api_worker'
202
- return [sys.executable, "-m", module, "--models", str(s.model_root),
 
203
  "--job", str(directory), "--max-frames", str(s.max_frames),
204
  "--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)]
 
 
205
 
206
  def start(self):
207
  self.lock = (self.settings.data_root / ".service.lock").open("a")
 
86
  db.execute('ALTER TABLE jobs ADD COLUMN swings_sha256 TEXT')
87
  if 'kind' not in {r[1] for r in db.execute('PRAGMA table_info(jobs)')}:
88
  db.execute("ALTER TABLE jobs ADD COLUMN kind TEXT NOT NULL DEFAULT 'legacy'")
89
+ db.execute('CREATE TABLE IF NOT EXISTS motion_revisions (analysis_id TEXT NOT NULL, revision INTEGER NOT NULL, job_id TEXT UNIQUE NOT NULL, parent_job_id TEXT, PRIMARY KEY (analysis_id, revision))')
90
 
91
  @contextmanager
92
  def connect(self):
 
112
  value = db.execute("SELECT * FROM jobs WHERE id=?", (identifier,)).fetchone()
113
  return dict(value) if value else None
114
 
115
+ def create_motion(self,max_active,parent_job_id=None):
116
+ now=time.time();identifier=uuid.uuid4().hex
117
+ with self.connect() as db:
118
+ db.execute('BEGIN IMMEDIATE')
119
+ if db.execute('SELECT COUNT(*) FROM jobs WHERE status IN (?,?,?,?)',ACTIVE).fetchone()[0]>=max_active:
120
+ raise QueueFull()
121
+ root=identifier;revision=1
122
+ if parent_job_id:
123
+ parent=db.execute('SELECT analysis_id FROM motion_revisions WHERE job_id=?',(parent_job_id,)).fetchone()
124
+ if parent is None:raise ValueError('Motion parent not found')
125
+ root=parent[0]
126
+ revision=db.execute('SELECT MAX(revision) FROM motion_revisions WHERE analysis_id=?',(root,)).fetchone()[0]+1
127
+ db.execute("INSERT INTO jobs (id,status,created,updated,kind) VALUES (?, 'uploading', ?, ?, 'motion_player')",(identifier,now,now))
128
+ db.execute('INSERT INTO motion_revisions VALUES (?,?,?,?)',(root,revision,identifier,parent_job_id))
129
+ return {'job_id':identifier,'analysis_id':root,'analysis_revision':revision,'parent_job_id':parent_job_id}
130
+
131
+ def motion_lineage(self,identifier):
132
+ with self.connect() as db:
133
+ row=db.execute('SELECT analysis_id, revision, parent_job_id FROM motion_revisions WHERE job_id=?',(identifier,)).fetchone()
134
+ return {'job_id':identifier,'analysis_id':row[0],'analysis_revision':row[1],'parent_job_id':row[2]} if row else None
135
+
136
  def update(self, identifier, status, error=None, result_hash=None, coach_hash=None, timing_hash=None, evidence_hash=None, product_hash=None, swings_hash=None):
137
  with self.connect() as db:
138
  db.execute("UPDATE jobs SET status=?, updated=?, error=?, result_sha256=?, coach_payload_sha256=?, load_timing_sha256=?, timing_evidence_sha256=?, product_sha256=?, swings_sha256=? WHERE id=?",
 
174
  def forget(self, identifier):
175
  with self.connect() as db:
176
  db.execute("DELETE FROM jobs WHERE id=?", (identifier,))
177
+ db.execute('DELETE FROM motion_revisions WHERE job_id=?',(identifier,))
178
 
179
  def expired(self, cutoff):
180
  with self.connect() as db:
 
221
 
222
  def job_command(self, directory):
223
  s = self.settings
224
+ kind=(self.store.get(directory.name) or {}).get('kind')
225
+ module={'sam_batting':'baseball_batting.sam_measurement_worker','motion_player':'baseball_batting.motion_worker'}.get(kind,'baseball_batting.api_worker')
226
+ command=[sys.executable, "-m", module, "--models", str(s.model_root),
227
  "--job", str(directory), "--max-frames", str(s.max_frames),
228
  "--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)]
229
+ if kind=='motion_player':command+=['--retention-s',str(s.retention_s)]
230
+ return command
231
 
232
  def start(self):
233
  self.lock = (self.settings.data_root / ".service.lock").open("a")
baseball_batting/media.py CHANGED
@@ -29,9 +29,9 @@ def open_verified_media(path, checksum, expected_size):
29
  raise
30
 
31
 
32
- def media_response(request, handle, size, checksum):
33
  etag = f'"{checksum}"'
34
- headers = {"Content-Type": "video/mp4", "Content-Length": str(size),
35
  "Accept-Ranges": "bytes", "ETag": etag, "Cache-Control": "private, no-store",
36
  "X-Content-Type-Options": "nosniff"}
37
  if request.method == "HEAD":
 
29
  raise
30
 
31
 
32
+ def media_response(request, handle, size, checksum,media_type='video/mp4'):
33
  etag = f'"{checksum}"'
34
+ headers = {"Content-Type": media_type, "Content-Length": str(size),
35
  "Accept-Ranges": "bytes", "ETag": etag, "Cache-Control": "private, no-store",
36
  "X-Content-Type-Options": "nosniff"}
37
  if request.method == "HEAD":
baseball_batting/motion_api.py ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authenticated, immutable motion-player analyses and artifact delivery."""
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ import shutil
6
+ from typing import Annotated
7
+ from fastapi import Depends, File, Form, HTTPException, Request, UploadFile
8
+ from fastapi.responses import JSONResponse
9
+ from pydantic import ValidationError
10
+ from .motion_contract import MotionInput, MotionManifest, MotionFrame, ProjectionFrame, RevisionRequest, ADAPTER_VERSION
11
+ from .api_jobs import QueueFull
12
+ from .sam_runtime import configured_record, public_status
13
+ from .storage import atomic_json, read_json, sha256_file
14
+ from .media import open_verified_media, media_response
15
+
16
+ PREFIX='/v1/motion-analyses'
17
+
18
+
19
+ def register(app,service,authenticated):
20
+ settings=service.settings
21
+ def record(identifier):
22
+ try:directory=service.job_directory(identifier)
23
+ except ValueError:raise HTTPException(404,'Motion analysis not found') from None
24
+ row=service.store.get(identifier)
25
+ if row is None or row['kind']!='motion_player':raise HTTPException(404,'Motion analysis not found')
26
+ return directory,row
27
+
28
+ def completed(identifier):
29
+ directory,row=record(identifier)
30
+ if row['status']!='completed':raise HTTPException(409,'Motion analysis has not completed')
31
+ path=directory/'result.json'
32
+ if not path.is_file() or sha256_file(path)!=row['result_sha256']:
33
+ raise HTTPException(500,'Motion manifest failed its integrity check')
34
+ try:manifest=MotionManifest.model_validate(read_json(path))
35
+ except (ValueError,ValidationError):raise HTTPException(500,'Stored motion manifest is invalid') from None
36
+ return directory,manifest
37
+
38
+ def artifact_path(directory,asset):
39
+ path=(directory/asset.filename).resolve()
40
+ if not path.is_relative_to(directory.resolve()):raise HTTPException(500,'Invalid stored artifact path')
41
+ return path
42
+
43
+ def require_ready():
44
+ if not service.ready:raise HTTPException(503,'GPU queue is not ready')
45
+ if configured_record() is None:raise HTTPException(503,{'code':'sam_not_configured','sam':public_status()})
46
+ if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes:
47
+ raise HTTPException(507,'Insufficient storage')
48
+
49
+ def validated(value):
50
+ try:return MotionInput.model_validate(value)
51
+ except ValidationError as error:
52
+ raise HTTPException(422,[{'loc':list(e['loc']),'msg':e['msg'],'type':e['type']} for e in error.errors(include_input=False,include_url=False)]) from None
53
+
54
+ def response(lineage):
55
+ identifier=lineage['job_id']
56
+ return {**lineage,'status':'queued','status_url':PREFIX+'/'+identifier,
57
+ 'result_url':PREFIX+'/'+identifier+'/result','retention_hours':settings.retention_s/3600}
58
+
59
+ def reserve(options,parent=None):
60
+ try:lineage=service.store.create_motion(settings.max_active_jobs,parent)
61
+ except QueueFull:raise HTTPException(429,'GPU queue is full',headers={'Retry-After':'30'}) from None
62
+ directory=service.job_directory(lineage['job_id']);directory.mkdir()
63
+ atomic_json(directory/'lineage.json',lineage)
64
+ atomic_json(directory/'request.json',options.model_dump(mode='json'))
65
+ return directory,lineage
66
+
67
+ def reuse_source(source_id,directory):
68
+ source_dir,manifest=completed(source_id);asset=manifest.artifacts['source']
69
+ source=artifact_path(source_dir,asset)
70
+ handle,_=open_verified_media(source,asset.sha256,asset.size_bytes);handle.close()
71
+ os.link(source,directory/('input'+source.suffix))
72
+ return source_dir,manifest
73
+
74
+ @app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
75
+ def capabilities():
76
+ return {'schema_version':'1.0','adapter':ADAPTER_VERSION,'model':'SAM 3D Body MHR70',
77
+ 'sam':public_status(),'gpu_queue_ready':service.ready,'mesh_available':False,
78
+ 'joint_count':22,'per_frame_motion':True,'projections':True,'measurement_series':True,
79
+ 'immutable_revisions':True,'source_video_retained':True,'interpolation':'disabled; gaps explicit',
80
+ 'retention_hours':settings.retention_s/3600,'max_frames':settings.max_frames,
81
+ 'max_duration_s':settings.max_duration_s,'input_schema_url':PREFIX+'/input-schema',
82
+ 'output_schema_url':PREFIX+'/output-schema'}
83
+
84
+ @app.get(PREFIX+'/input-schema',dependencies=[Depends(authenticated)])
85
+ def input_schema():return MotionInput.model_json_schema()
86
+
87
+ @app.get(PREFIX+'/output-schema',dependencies=[Depends(authenticated)])
88
+ def output_schema():
89
+ return {'manifest':MotionManifest.model_json_schema(),'motion_frame':MotionFrame.model_json_schema(),
90
+ 'projection_frame':ProjectionFrame.model_json_schema()}
91
+
92
+ @app.post(PREFIX,status_code=202,dependencies=[Depends(authenticated)])
93
+ async def upload(video:Annotated[UploadFile|None,File()]=None,
94
+ options:Annotated[str,Form()]='{}',source_asset_id:Annotated[str|None,Form()]=None):
95
+ directory=None;lineage=None
96
+ try:
97
+ require_ready()
98
+ if (video is None)==(source_asset_id is None):raise HTTPException(422,'Supply exactly one video or source_asset_id')
99
+ if len(options.encode())>512*1024:raise HTTPException(413,'Options exceed size limit')
100
+ try:inputs=json.loads(options)
101
+ except ValueError:raise HTTPException(422,'Options must be a JSON object') from None
102
+ parsed=validated(inputs)
103
+ with service.mutation_lock:
104
+ if source_asset_id:completed(source_asset_id)
105
+ directory,lineage=reserve(parsed)
106
+ if source_asset_id:reuse_source(source_asset_id,directory)
107
+ if video:
108
+ suffix=Path(video.filename or '').suffix.lower()
109
+ if suffix not in {'.mp4','.mov','.mkv','.avi','.webm'}:raise HTTPException(415,'Unsupported video extension')
110
+ size=0
111
+ with (directory/('input'+suffix)).open('wb') as out:
112
+ while block:=await video.read(1024*1024):
113
+ size+=len(block)
114
+ if size>settings.max_upload_bytes:raise HTTPException(413,'Video exceeds upload limit')
115
+ if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes+len(block):raise HTTPException(507,'Insufficient storage')
116
+ out.write(block)
117
+ if not size:raise HTTPException(422,'Video is empty')
118
+ service.store.update(lineage['job_id'],'queued');service.wakeup.set()
119
+ return response(lineage)
120
+ except BaseException:
121
+ if lineage:
122
+ service.store.forget(lineage['job_id']);shutil.rmtree(directory,ignore_errors=True)
123
+ raise
124
+ finally:
125
+ if video:await video.close()
126
+
127
+ @app.get(PREFIX+'/{identifier}',dependencies=[Depends(authenticated)])
128
+ def status(identifier:str):
129
+ with service.mutation_lock:
130
+ directory,row=record(identifier);progress=None;failure=None
131
+ try:progress=read_json(directory/'progress.json')
132
+ except (OSError,ValueError):pass
133
+ if row['status']=='failed':
134
+ try:
135
+ details=read_json(directory/'error.json')
136
+ failure={k:details[k] for k in ('code','reason_code','error_type') if k in details}
137
+ except (OSError,ValueError):pass
138
+ return JSONResponse({**service.store.motion_lineage(identifier),
139
+ 'status':'processing' if row['status']=='running' else row['status'],'progress':progress,
140
+ 'failure':failure,'error':row['error'],
141
+ 'result_url':PREFIX+'/'+identifier+'/result' if row['status']=='completed' else None},
142
+ headers={'Cache-Control':'no-store'})
143
+
144
+ @app.get(PREFIX+'/{identifier}/result',response_model=MotionManifest,dependencies=[Depends(authenticated)])
145
+ def result(identifier:str):
146
+ with service.mutation_lock:_,manifest=completed(identifier)
147
+ return JSONResponse(manifest.model_dump(mode='json'),headers={'Cache-Control':'no-store'})
148
+
149
+ @app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
150
+ @app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
151
+ def artifact(identifier:str,name:str,request:Request):
152
+ with service.mutation_lock:
153
+ directory,manifest=completed(identifier);asset=manifest.artifacts.get(name)
154
+ if asset is None:raise HTTPException(404,'Unknown motion artifact')
155
+ if asset.status!='available':raise HTTPException(409,{'code':asset.reason_code})
156
+ handle,size=open_verified_media(artifact_path(directory,asset),asset.sha256,asset.size_bytes)
157
+ return media_response(request,handle,size,asset.sha256,media_type=asset.media_type)
158
+
159
+ @app.post(PREFIX+'/{identifier}/revisions',status_code=202,dependencies=[Depends(authenticated)])
160
+ def revision(identifier:str,payload:RevisionRequest):
161
+ require_ready();directory=None;lineage=None
162
+ try:
163
+ with service.mutation_lock:
164
+ parent,manifest=completed(identifier)
165
+ inputs=read_json(parent/'request.json')
166
+ def merge(before,patch):
167
+ 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()}}
168
+ parsed=validated(merge(inputs,payload.options))
169
+ if parsed.athlete_box!=MotionInput.model_validate(inputs).athlete_box:
170
+ raise HTTPException(422,'Changing the athlete requires a new analysis using source_asset_id')
171
+ directory,lineage=reserve(parsed,identifier);reuse_source(identifier,directory)
172
+ # Reviewed events/calibration axes/correction changes reuse native inference.
173
+ geometry=('camera','athlete_box','rotation_degrees','source_mirrored')
174
+ reusable=(all(inputs.get(k)==parsed.model_dump().get(k) for k in geometry)
175
+ and manifest.pipeline['adapter_sha256']==sha256_file(Path(__file__).with_name('sam_pose_worker.py')))
176
+ integrity=parent/'inference-integrity-private.json'
177
+ if reusable and integrity.is_file():
178
+ hashes=read_json(integrity)
179
+ files=('sam-raw-private.npz','sam-raw-private.json','person-track-private.json')
180
+ if all((parent/name).is_file() and sha256_file(parent/name)==hashes.get(name) for name in files):
181
+ for name in files:os.link(parent/name,directory/name)
182
+ atomic_json(directory/'reused-inference.json',{'job_id':identifier,'source_sha256':manifest.source_video['sha256']})
183
+ service.store.update(lineage['job_id'],'queued');service.wakeup.set()
184
+ return response(lineage)
185
+ except BaseException:
186
+ if lineage:service.store.forget(lineage['job_id']);shutil.rmtree(directory,ignore_errors=True)
187
+ raise
188
+
189
+ @app.delete(PREFIX+'/{identifier}',status_code=202,dependencies=[Depends(authenticated)])
190
+ def delete(identifier:str):
191
+ record(identifier)
192
+ return {'job_id':identifier,'status':service.delete(identifier)}
baseball_batting/motion_contract.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Versioned motion-player contract. Existing SAM measurement responses stay unchanged."""
2
+ from typing import Any, Literal
3
+ from pydantic import Field, model_validator
4
+ from .sam_batting_contract import Strict, SamBattingInput
5
+
6
+ SCHEMA_VERSION = '1.0'
7
+ ADAPTER_VERSION = 'sam-mhr70-motion-v1'
8
+ DEFINITION_VERSION = 'batting-corrected-points-v1'
9
+
10
+
11
+ class MotionInput(SamBattingInput):
12
+ coaching: Literal[False] = False
13
+ annotated_videos: bool = True
14
+ source_mirrored: bool | None = None
15
+ handedness_source: str | None = Field(default=None, min_length=1, max_length=300)
16
+ lead_foot_source: str | None = Field(default=None, min_length=1, max_length=300)
17
+ scale_status: Literal['model_estimated', 'calibrated', 'unknown'] = 'model_estimated'
18
+ minimum_usable_joints: int = Field(default=3, ge=3, le=22, strict=True)
19
+
20
+ @model_validator(mode='after')
21
+ def scale_evidence(self):
22
+ if self.scale_status == 'calibrated' and not (self.scale_source and self.scale_source.strip()):
23
+ raise ValueError('Calibrated scale requires a calibration source')
24
+ return self
25
+
26
+ def sam_options(self):
27
+ return SamBattingInput.model_validate({k: v for k, v in self.model_dump().items()
28
+ if k in SamBattingInput.model_fields})
29
+
30
+
31
+ class RevisionRequest(Strict):
32
+ # A patch is merged with the parent's recording facts, then validated as MotionInput.
33
+ options: dict[str, Any] = Field(default_factory=dict)
34
+
35
+
36
+ class Joint(Strict):
37
+ position: tuple[float, float, float] | None
38
+ status: Literal['estimated', 'interpolated', 'rejected', 'missing']
39
+ confidence: float | None = Field(default=None, ge=0, le=1)
40
+ reasons: list[str] = Field(default_factory=list)
41
+
42
+ @model_validator(mode='after')
43
+ def usable(self):
44
+ if (self.position is None) != (self.status in ('missing', 'rejected')):
45
+ raise ValueError('Usable joints require a position; unusable joints must have null positions')
46
+ return self
47
+
48
+
49
+ class MotionFrame(Strict):
50
+ analysis_revision: int = Field(ge=1)
51
+ source_frame_index: int = Field(ge=0)
52
+ source_pts: int
53
+ source_time_base: str
54
+ video_time_s: float = Field(ge=0)
55
+ capture_time_s: float | None = Field(default=None, ge=0)
56
+ segment_id: str
57
+ joints: dict[str, Joint]
58
+ root_translation: tuple[float, float, float] | None
59
+ frame_quality: dict[str, Any]
60
+
61
+
62
+ class Artifact(Strict):
63
+ status: Literal['available', 'unavailable']
64
+ url: str | None = None
65
+ filename: str | None = None
66
+ format: str
67
+ media_type: str
68
+ size_bytes: int | None = Field(default=None, ge=1)
69
+ sha256: str | None = Field(default=None, pattern=r'^[a-f0-9]{64}$')
70
+ expires_at: str
71
+ reason_code: str | None = None
72
+
73
+ @model_validator(mode='after')
74
+ def availability(self):
75
+ if self.status == 'available' and any(getattr(self, k) is None for k in ('url','filename','size_bytes','sha256')):
76
+ raise ValueError('Available artifacts require location, length and checksum')
77
+ if self.status == 'unavailable' and not self.reason_code:
78
+ raise ValueError('Unavailable artifacts require a reason')
79
+ return self
80
+
81
+
82
+ class MotionManifest(Strict):
83
+ schema_version: Literal['1.0'] = SCHEMA_VERSION
84
+ analysis_id: str
85
+ job_id: str
86
+ analysis_revision: int = Field(ge=1)
87
+ parent_job_id: str | None = None
88
+ person_id: str
89
+ source_video: dict[str, Any]
90
+ pipeline: dict[str, Any]
91
+ coordinates: dict[str, Any]
92
+ timing: dict[str, Any]
93
+ skeleton: dict[str, Any]
94
+ sampling: dict[str, Any]
95
+ quality: dict[str, Any]
96
+ artifacts: dict[str, Artifact]
97
+ expires_at: str
98
+ accuracy_validated: Literal[False] = False
99
+
100
+
101
+ class MetricSample(Strict):
102
+ source_frame_index: int = Field(ge=0)
103
+ video_time_s: float = Field(ge=0)
104
+ capture_time_s: float | None
105
+ value: float | None
106
+ status: Literal['estimated', 'partial', 'unavailable']
107
+ reasons: list[str]
108
+ uses_interpolated_input: bool
109
+
110
+
111
+ class ProjectionFrame(Strict):
112
+ analysis_revision: int = Field(ge=1)
113
+ source_frame_index: int = Field(ge=0)
114
+ video_time_s: float = Field(ge=0)
115
+ capture_time_s: float | None
116
+ segment_id: str
117
+ image_width: int = Field(ge=1)
118
+ image_height: int = Field(ge=1)
119
+ camera_intrinsics: list[list[float]] | None
120
+ joints: dict[str, dict[str, Any]]
baseball_batting/motion_export.py ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay artifacts from the exact corrected sequence used by the SAM calculator."""
2
+ from datetime import datetime, timezone
3
+ from pathlib import Path
4
+ import json
5
+ 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
13
+
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={
21
+ **{k:['left_hip','right_hip'] for k in DEFINITIONS if k.startswith('hip_')},
22
+ **{k:['left_shoulder','right_shoulder'] for k in DEFINITIONS if k.startswith('shoulder_')},
23
+ 'hip_shoulder_separation_deg':['left_hip','right_hip','left_shoulder','right_shoulder'],
24
+ 'hand_speed_relative_m_s':['left_wrist','right_wrist','left_hip','right_hip'],
25
+ **{k:['left_ear','right_ear','left_hip','right_hip'] for k in DEFINITIONS if k.startswith('head_')},
26
+ **{k:['left_shoulder','right_shoulder','left_hip','right_hip'] for k in ('forward_lean_deg','side_lean_deg')},
27
+ **{k:['left_ankle','right_ankle'] for k in DEFINITIONS if k.startswith(('stance_','stride_'))},
28
+ 'left_foot_heading_deg':['left_big_toe','left_small_toe','left_heel'],
29
+ 'right_foot_heading_deg':['right_big_toe','right_small_toe','right_heel']}
30
+
31
+
32
+ def _finite(value):
33
+ q = np.asarray(value)
34
+ return q.tolist() if np.isfinite(q).all() else None
35
+
36
+
37
+ def _jsonl(path, records):
38
+ temporary = path.with_suffix('.tmp')
39
+ try:
40
+ with temporary.open('w') as out:
41
+ for record in records:
42
+ out.write(json.dumps(record, allow_nan=False, separators=(',', ':'))+'\n')
43
+ out.flush(); os.fsync(out.fileno())
44
+ temporary.replace(path)
45
+ finally:
46
+ temporary.unlink(missing_ok=True)
47
+
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:
54
+ for metric in swing.measurements:
55
+ if metric.unit in ('cm','m/s'):
56
+ metric.value=None; metric.status='unavailable'; metric.reason_code='scale_unknown'
57
+ for context in contexts:
58
+ for key, (_, unit, _) in DEFINITIONS.items():
59
+ if unit in ('cm','m/s'): context['curves'][key][:]=np.nan
60
+ return groups, contexts
61
+
62
+
63
+ def reproduce_measurements(manifest, motion_path):
64
+ """Recompute summaries from the public motion artifact, without private SAM arrays."""
65
+ from .motion_contract import MotionInput
66
+ m = manifest.model_dump(mode='json') if isinstance(manifest,MotionManifest) else manifest
67
+ rows=[MotionFrame.model_validate_json(line) for line in Path(motion_path).read_text().splitlines()]
68
+ n=len(rows); points=np.full((n,70,3),np.nan); boundary=np.zeros((n,70),bool)
69
+ rotation=np.asarray(m['coordinates']['camera_to_export_rotation'])
70
+ scale=m['coordinates']['native_to_export_scale_factor']
71
+ for i,frame in enumerate(rows):
72
+ if frame.source_frame_index!=i or frame.analysis_revision!=m['analysis_revision']:
73
+ raise ValueError('Motion sequence/revision differs from manifest')
74
+ for name,index in MHR.items():
75
+ joint=frame.joints[name]
76
+ if joint.position is not None: points[i,index]=np.asarray(joint.position)@rotation/scale
77
+ boundary[i,index]='filter_boundary' in joint.reasons
78
+ known=m['timing']['physical_time_available']
79
+ times=np.array([f.capture_time_s if known else f.video_time_s for f in rows])
80
+ options=MotionInput.model_validate(m['pipeline']['inputs'])
81
+ return _calculate({'points_relative':points,'boundary':boundary}, times, options, known)[0]
82
+
83
+
84
+ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=86400,progress=lambda *a:None,track=None):
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)
91
+ if not np.isfinite(playback).all() or np.any(np.diff(playback)<=0):
92
+ raise ValueError('invalid_source_timestamps')
93
+ video_times=playback-playback[0]
94
+ physical=np.array([r['physical_s'] if r['physical_s'] is not None else np.nan for r in records],float)
95
+ known=bool(np.isfinite(physical).all() and np.all(np.diff(physical)>0))
96
+ capture_times=physical-physical[0] if known else np.full(n,np.nan)
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')
108
+ groups,contexts=_calculate(corrected,times,options,known)
109
+ baseline=next((c['baseline'] for c in contexts if corrected['valid'][c['baseline'],[9,10]].all()),int(np.flatnonzero(usable)[0]))
110
+ rotation,reference=orientation(corrected['points_relative'],options,baseline)
111
+ if rotation is None: rotation=np.eye(3); reference='camera_oriented_hip_relative'
112
+ scale=options.scale_factor
113
+ positions=corrected['points_relative']@rotation.T*scale
114
+ root=(corrected['points_camera'][:,9]-corrected['points_relative'][:,9])@rotation.T*scale
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
+ if previous is None or kind!=previous or times[i]-times[i-1]>options.correction.max_gap_s:
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,
122
+ 'reason':None if usable[i] else 'pose_unusable'})
123
+ else: segments[-1]['end_frame']=i
124
+ segment_ids.append(segments[-1]['segment_id']);previous=kind
125
+ def stamp(i):
126
+ return {'source_frame_index':i,'video_time_s':float(video_times[i]),
127
+ 'capture_time_s':float(capture_times[i]) if known else None}
128
+ projection_count=0
129
+ motion_rows=[]; projection_rows=[]
130
+ for i in range(n):
131
+ frame=records[i]; joints={}; projected={}; k=raw['intrinsics'][i]
132
+ # Both artifacts and videos use the same corrected camera-space projection.
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 (
139
+ 'missing' if not np.isfinite(raw['points_body'][i,index]).all() else 'rejected')
140
+ joints[name]={'position':positions[i,index].tolist() if good else None,'status':status,
141
+ 'confidence':None,'reasons':reasons}
142
+ valid=good and projection_valid[index]
143
+ inside=bool(valid and 0<=xy[index,0]<frame['width'] and 0<=xy[index,1]<frame['height'])
144
+ projected[name]={'pixel':xy[index].tolist() if valid else None,'valid':bool(valid),'in_frame':inside,
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')
151
+ if corrected['boundary'][i,indices].any():flags.append('filter_boundary')
152
+ if options.source_mirrored is None:flags.append('source_mirroring_unknown')
153
+ common={'analysis_revision':revision,**stamp(i),'segment_id':segment_ids[i]}
154
+ row=MotionFrame(**common,source_pts=frame['pts'],source_time_base=frame['time_base'],joints=joints,
155
+ root_translation=_finite(root[i]),frame_quality={'pose_available':bool(usable[i]),'reasons':flags,
156
+ 'usable_joint_count':int(count[i]),'joint_confidence_available':False})
157
+ motion_rows.append(row.model_dump(mode='json'))
158
+ projection_rows.append(ProjectionFrame(**common,image_width=frame['width'],image_height=frame['height'],
159
+ camera_intrinsics=_finite(k),joints=projected).model_dump(mode='json'))
160
+ _jsonl(job/'motion.jsonl',motion_rows)
161
+ if projection_count:_jsonl(job/'projections.jsonl',projection_rows)
162
+ progress('motion_artifacts',n,n)
163
+ summaries=[]; series=[]; events=[]
164
+ for context in contexts:
165
+ window=context['window']; rep=context['rep']; a,b=window['start_frame'],window['end_frame']; base=context['baseline']
166
+ manual=bool(options.windows); source='manual' if manual else 'pose_estimated'
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':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():
174
+ details=metric.model_dump(mode='json');details.pop('coaching',None)
175
+ summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
176
+ 'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
177
+ 'source_samples':[stamp(i) for i in metric.source_frame_ids]})
178
+ samples=[]
179
+ for i in range(a,b+1):
180
+ value=float(context['curves'][key][i]) if np.isfinite(context['curves'][key][i]) else None
181
+ reason=None
182
+ if value is None:
183
+ if options.scale_status=='unknown' and metric.unit in ('cm','m/s'):reason='scale_unknown'
184
+ elif not known and metric.unit in ('ms','m/s','deg/s'):reason='capture_time_unknown'
185
+ elif key in EVENT_ONLY:reason=metric.reason_code or 'event_summary_only'
186
+ elif key.startswith(('head_excursion_ground','pelvis_ground','center_of_mass')):reason=metric.reason_code
187
+ elif context['reference'] in ('missing_vertical_reference','camera_stability_unverified','degenerate_analysis_axis') and key!='head_excursion_relative_cm':reason=context['reference']
188
+ else:
189
+ missing=[name+'_unusable' for name in DEPENDENCIES.get(key,[]) if not corrected['valid'][i,MHR[name]]]
190
+ reason=missing[0] if missing else 'required_points_or_derivative_neighborhood_unusable'
191
+ samples.append(MetricSample(**stamp(i),value=value,status='estimated' if value is not None else 'unavailable',
192
+ reasons=[reason] if reason else [],uses_interpolated_input=bool(corrected['interpolated'][max(a,i-1):min(b+1,i+2),indices].any())).model_dump(mode='json'))
193
+ group=next(g for g,keys in GROUP_KEYS.items() if key in keys)
194
+ series.append({**metadata,'metric_id':key,'group':group,'unit':metric.unit,'formula':metric.formula,
195
+ 'reference_frame':metric.reference,'statistic':'per_source_frame_value','samples':samples})
196
+ def event(kind,index=None,end=None,reason=None,detector=source):
197
+ events.append({'analysis_revision':revision,'rep':rep,'type':kind,'source':detector,
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);event('baseline',base)
202
+ event('forward_swing_window',context['forward_start'],context['forward_end'])
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():
206
+ metric=rows[name+'_peak_time_ms']
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':DEFINITION_VERSION,'summaries':summaries,'series':series,
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'],
214
+ 'identity':{'person_id':person_id,'method':'conservative_single_athlete_box_continuity',
215
+ 'reidentification':'disabled_after_tracking_loss','tracking_reasons':track['reasons']},
216
+ 'anatomical_assignment':'native_model_mapping_checked; image-level left/right accuracy unvalidated',
217
+ 'depth_accuracy':'unvalidated','body_shape':'native_model estimates; no independent limb stretching or mesh retargeting'})
218
+ clips=export_group_videos(video,capture,corrected,raw['intrinsics'],job,progress) if options.annotated_videos else {}
219
+ source=job/('source'+Path(video).suffix.lower())
220
+ if source!=Path(video):
221
+ if source.exists():
222
+ if sha256_file(source)!=capture['input_sha256']:raise ValueError('Retained source differs from uploaded video')
223
+ else:os.link(video,source)
224
+ expiry=datetime.fromtimestamp(time.time()+retention_s,timezone.utc).isoformat()
225
+ prefix=f'/v1/motion-analyses/{job.name}/artifacts'
226
+ def asset(path,media_type,format):
227
+ return {'status':'available','url':prefix+'/'+path.stem,'filename':str(path.relative_to(job)),
228
+ 'format':format,'media_type':media_type,'size_bytes':path.stat().st_size,'sha256':sha256_file(path),'expires_at':expiry}
229
+ media={'.mp4':'video/mp4','.mov':'video/quicktime','.mkv':'video/x-matroska','.avi':'video/x-msvideo','.webm':'video/webm'}
230
+ artifacts={key:asset(job/filename,mt,fmt) for key,filename,mt,fmt in [
231
+ ('motion','motion.jsonl','application/x-ndjson','jsonl'),('measurements','measurements.json','application/json','json'),
232
+ ('events','events.json','application/json','json'),('quality','quality.json','application/json','json')]}
233
+ artifacts['source']=asset(source,media[source.suffix],'original_video')
234
+ artifacts['projections']=asset(job/'projections.jsonl','application/x-ndjson','jsonl') if projection_count else {
235
+ 'status':'unavailable','reason_code':'camera_projection_unavailable','format':'jsonl','media_type':'application/x-ndjson','expires_at':expiry}
236
+ artifacts['mesh']={'status':'unavailable','reason_code':'animated_mesh_second_phase','format':'none','media_type':'application/octet-stream','expires_at':expiry}
237
+ for key in GROUP_KEYS:
238
+ if key in clips:
239
+ item=asset(job/'group-videos'/(key+'.mp4'),'video/mp4','mp4')
240
+ item['url']=prefix+'/annotated_'+key;artifacts['annotated_'+key]=item
241
+ else:artifacts['annotated_'+key]={'status':'unavailable','reason_code':'not_requested','format':'mp4','media_type':'video/mp4','expires_at':expiry}
242
+ # Exact source durations (including the final sample) are exported by the media decoder.
243
+ from .ingest import iter_frames
244
+ duration=None
245
+ for i,pts,base,_,sample_duration in iter_frames(video,capture['rotation_degrees'],include_duration=True):
246
+ if i!=n-1:continue
247
+ duration=float(pts*base-playback[0]+sample_duration*base) if sample_duration else float(video_times[-1])
248
+ manifest=MotionManifest(analysis_id=lineage['analysis_id'],job_id=job.name,analysis_revision=revision,
249
+ parent_job_id=lineage.get('parent_job_id'),person_id=person_id,expires_at=expiry,
250
+ source_video={'asset_id':job.name,'artifact':'source','sha256':capture['input_sha256'],
251
+ 'display_width':records[0]['width'],'display_height':records[0]['height'],'duration_s':duration,
252
+ 'rotation_degrees_applied':capture['rotation_degrees'],'orientation_transform':capture['orientation_transform'],
253
+ 'source_mirrored':options.source_mirrored,'mirroring_transform_applied':False,
254
+ 'timeline_origin_pts':records[0]['pts'],'timeline_origin_time_base':records[0]['time_base'],
255
+ 'projection_space':'upright_original_image_pixels_x_right_y_down',
256
+ 'camera_model':'pinhole','distortion_correction':'not_applied; source_lens_distortion_unverified',
257
+ 'camera_intrinsics_source':options.camera.source if options.camera else 'SAM model-estimated focal length and centered principal point'},
258
+ pipeline={'model':model,'adapter_version':ADAPTER_VERSION,'adapter_sha256':sha256_file(Path(__file__).with_name('sam_pose_worker.py')),
259
+ 'exporter_sha256':sha256_file(Path(__file__)),'correction':corrected['metadata'],
260
+ 'measurement_definition_version':DEFINITION_VERSION,'measurement_definitions_sha256':digest(DEFINITIONS),
261
+ 'inputs':options.model_dump(mode='json'),'raw_outputs':'retained_private; never merged with corrected motion'},
262
+ coordinates={'unit':'model_units' if options.scale_status=='unknown' else 'm','scale_status':options.scale_status,
263
+ 'scale_source':options.scale_source or 'SAM native converted scale; not independently calibrated',
264
+ 'native_to_export_scale_factor':scale,'origin':'hip_midpoint','frame':reference,
265
+ 'camera_to_export_rotation':rotation.tolist(),'basis_handedness':'right_handed',
266
+ 'axes':{'x':'toward_pitcher','y':'up_cross_toward_pitcher','z':'declared_up'} if reference=='declared_field_axes' else (
267
+ {'x':'starting_hip_axis','y':'up_cross_starting_hip_axis','z':'declared_up'} if reference=='fixed_starting_hip_axis' else
268
+ {'x':'camera_right','y':'camera_down','z':'camera_away'}),
269
+ 'left_right':'athlete_anatomical_native_MHR70','ground_status':'unavailable','camera_motion':options.camera_stability,
270
+ 'root_translation_included':False,'root_translation':'separate model-estimated camera root in export axes; never ground translation',
271
+ 'projection_rule':'project((position + root_translation) @ camera_to_export_rotation, camera_intrinsics); add root exactly once',
272
+ 'handedness':options.handedness,'handedness_source':options.handedness_source or ('caller_supplied' if options.handedness else None),
273
+ 'lead_foot':options.lead_foot or {'right':'left','left':'right'}.get(options.handedness),
274
+ 'lead_foot_source':options.lead_foot_source or ('caller_supplied' if options.lead_foot else 'inferred_from_handedness' if options.handedness else None)},
275
+ timing={'video_time':'source_PTS_minus_first_source_PTS','physical_time_available':known,
276
+ 'capture_time':'declared_physical_time_minus_first_physical_time' if known else None,
277
+ 'mapping':options.timing.model_dump(mode='json'),'original_video_time_origin_s':float(playback[0]),
278
+ 'original_capture_time_origin_s':float(physical[0]) if known else None,
279
+ 'maximum_derivative_gap_s':options.correction.max_gap_s},
280
+ skeleton={'version':'mhr70-batting-22-v1','joint_order':list(JOINTS),
281
+ 'joints':[{'name':name,'source_schema':'MHR70','source_index':index,
282
+ 'definition':'Native '+name.replace('_',' ')+' MHR70 landmark; no mesh-vertex or acromion substitution','derived':False} for name,index in MHR.items()],
283
+ 'bones':[[INDEX_NAMES[a],INDEX_NAMES[b]] for a,b in BONES],
284
+ 'head_center_proxy':'midpoint_of_bilateral_ear_landmarks','hand_motion_proxy':'midpoint_of_bilateral_wrist_landmarks'},
285
+ sampling={'policy':'every_decoded_source_frame','frame_count':n,'intentionally_skipped_frames':0,
286
+ 'maximum_gap_s':options.correction.max_gap_s,'playback_interpolation':'client_only; never measurement evidence'},
287
+ quality={'usable_frame_count':int(usable.sum()),'minimum_usable_joints':options.minimum_usable_joints,
288
+ 'segments':segments,'joint_confidence_available':False,'depth_accuracy_validated':False,
289
+ 'anatomical_label_accuracy_validated':False},artifacts=artifacts)
290
+ atomic_json(job/'manifest.json',manifest.model_dump(mode='json'))
291
+ atomic_json(job/'result.json',manifest.model_dump(mode='json'))
292
+ progress('complete',n,n)
293
+ return manifest
baseball_batting/motion_worker.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Queued motion-player reconstruction/export. No coaching provider calls."""
2
+ import argparse
3
+ from pathlib import Path
4
+ import time
5
+ 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
+
12
+
13
+ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120,retention_s=86400):
14
+ job=Path(job);options=MotionInput.model_validate(read_json(job/'request.json'))
15
+ lineage=read_json(job/'lineage.json');started=time.monotonic()
16
+ def progress(stage,done=0,total=None):
17
+ atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
18
+ 'elapsed_s':round(time.monotonic()-started,2)})
19
+ progress('decoding');video=next(job.glob('input.*'))
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/'sam-raw-private.npz',allow_pickle=False) as data:raw=dict(data)
27
+ model=read_json(job/'sam-raw-private.json')['model']
28
+ model={**model,'inference_reused_from_job':reused['job_id']}
29
+ else:raw,model=reconstruct_sam(job,video,capture,models,options.sam_options(),progress,strict_identity=True)
30
+ atomic_json(job/'inference-integrity-private.json',{name:sha256_file(job/name) for name in
31
+ ('sam-raw-private.npz','sam-raw-private.json','person-track-private.json')})
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
+
35
+
36
+ def main():
37
+ parser=argparse.ArgumentParser()
38
+ parser.add_argument('--job',required=True);parser.add_argument('--models',required=True)
39
+ parser.add_argument('--max-frames',type=int,default=7200);parser.add_argument('--max-pixels',type=int,default=8294400)
40
+ parser.add_argument('--max-duration',type=float,default=120);parser.add_argument('--retention-s',type=float,default=86400)
41
+ args=parser.parse_args()
42
+ try:run(args.job,args.models,args.max_frames,args.max_pixels,args.max_duration,args.retention_s);return 0
43
+ except Exception as error:
44
+ reason=str(error) if isinstance(error,ValueError) and str(error) in {
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
+ sam_error=Path(args.job)/'sam-raw-private.error.json'
49
+ if sam_error.is_file():failure.update(read_json(sam_error))
50
+ atomic_json(Path(args.job)/'error.json',failure)
51
+ print(type(error).__name__+': '+str(error),flush=True);return 1
52
+
53
+
54
+ if __name__=='__main__':raise SystemExit(main())
baseball_batting/sam_measurement_worker.py CHANGED
@@ -10,13 +10,13 @@ from .sam_batting_contract import SamBattingInput,SamBattingResult,MeasurementGr
10
  from .storage import read_json,atomic_json
11
 
12
 
13
- def athlete_boxes(video,capture,models,options,device,progress):
14
  from .api_worker import model_files
15
  from .detection import YOLOXDetector,select_person,relevant_people,iou
16
  from .ingest import iter_frames
17
  paths,_=model_files(models)
18
  detector=YOLOXDetector(paths['person_detector'],device,classes=[0])
19
- previous=None;boxes=[];reasons=[]
20
  width,height=capture['frames'][0]['width'],capture['frames'][0]['height']
21
  roi=options.athlete_box
22
  if roi is not None and (roi[2]>width or roi[3]>height):raise ValueError('Athlete box is outside the upright video')
@@ -24,9 +24,14 @@ def athlete_boxes(video,capture,models,options,device,progress):
24
  detections=detector(image)
25
  selected=select_person(detections,previous or roi)
26
  reason=None
 
 
27
  if selected is None:reason='person_not_tracked'
28
  elif previous is None and roi is None and relevant_people(detections,selected,image.shape[0])>1:
 
29
  selected=None;reason='multiple_people_select_athlete_box'
 
 
30
  if selected:
31
  previous=selected['box'];box=previous
32
  box=[max(0,box[0]),max(0,box[1]),min(width,box[2]),min(height,box[3])]
@@ -97,27 +102,17 @@ def process_predictions(job,video,capture,raw,options,model,*,progress=lambda *a
97
  return public
98
 
99
 
100
- def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120):
101
- from .ingest import ingest
102
  from .sam_runtime import configured_record
103
- job=Path(job);options=SamBattingInput.model_validate(read_json(job/'request.json'))
104
- started=time.monotonic()
105
- def progress(stage,done=0,total=None):
106
- atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
107
- 'stage_progress':done/total if total else None,'elapsed_s':round(time.monotonic()-started,2)})
108
  record=configured_record()
109
  if record is None:raise RuntimeError('SAM worker is not configured')
110
- video=next(job.glob('input.*'))
111
- progress('decoding')
112
- capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
113
- atomic_json(job/'capture-private.json',capture)
114
- if any(w.end_frame>=capture['frame_count'] for w in options.windows):raise ValueError('Reviewed window exceeds video')
115
  first=capture['frames'][0]
116
  if any(f['width']!=first['width'] or f['height']!=first['height'] for f in capture['frames']):
117
  raise ValueError('Changing image dimensions require separate recording segments')
118
  if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
119
  raise ValueError('Camera principal point is outside upright video')
120
- boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress)
121
  atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
122
  c=options.camera
123
  k=[[c.fx,0,c.cx],[0,c.fy,c.cy],[0,0,1]] if c else None
@@ -134,6 +129,21 @@ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120):
134
  with np.load(job/'sam-raw-private.npz',allow_pickle=False) as archive:raw={key:archive[key] for key in archive.files}
135
  if not raw['projection_valid'].any():raise RuntimeError('SAM did not produce any projection-consistent frames')
136
  model=read_json(job/'sam-raw-private.json')['model']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  return process_predictions(job,video,capture,raw,options,model,progress=progress)
138
 
139
 
 
10
  from .storage import read_json,atomic_json
11
 
12
 
13
+ def athlete_boxes(video,capture,models,options,device,progress,*,strict_identity=False):
14
  from .api_worker import model_files
15
  from .detection import YOLOXDetector,select_person,relevant_people,iou
16
  from .ingest import iter_frames
17
  paths,_=model_files(models)
18
  detector=YOLOXDetector(paths['person_detector'],device,classes=[0])
19
+ previous=None;boxes=[];reasons=[];identity_lost=False
20
  width,height=capture['frames'][0]['width'],capture['frames'][0]['height']
21
  roi=options.athlete_box
22
  if roi is not None and (roi[2]>width or roi[3]>height):raise ValueError('Athlete box is outside the upright video')
 
24
  detections=detector(image)
25
  selected=select_person(detections,previous or roi)
26
  reason=None
27
+ if strict_identity and identity_lost:
28
+ selected=None;reason='identity_uncertain_after_tracking_loss'
29
  if selected is None:reason='person_not_tracked'
30
  elif previous is None and roi is None and relevant_people(detections,selected,image.shape[0])>1:
31
+ if strict_identity:raise ValueError('multiple_people_select_athlete_box')
32
  selected=None;reason='multiple_people_select_athlete_box'
33
+ if strict_identity and previous is not None and selected is None:
34
+ identity_lost=True;reason='identity_uncertain_after_tracking_loss'
35
  if selected:
36
  previous=selected['box'];box=previous
37
  box=[max(0,box[0]),max(0,box[1]),min(width,box[2]),min(height,box[3])]
 
102
  return public
103
 
104
 
105
+ def reconstruct_sam(job,video,capture,models,options,progress,*,strict_identity=False):
106
+ """Shared native reconstruction; exporters must not run a second pose model."""
107
  from .sam_runtime import configured_record
 
 
 
 
 
108
  record=configured_record()
109
  if record is None:raise RuntimeError('SAM worker is not configured')
 
 
 
 
 
110
  first=capture['frames'][0]
111
  if any(f['width']!=first['width'] or f['height']!=first['height'] for f in capture['frames']):
112
  raise ValueError('Changing image dimensions require separate recording segments')
113
  if options.camera and (options.camera.cx>=first['width'] or options.camera.cy>=first['height']):
114
  raise ValueError('Camera principal point is outside upright video')
115
+ boxes,reasons=athlete_boxes(video,capture,models,options,'cuda',progress,strict_identity=strict_identity)
116
  atomic_json(job/'person-track-private.json',{'boxes':boxes,'reasons':reasons})
117
  c=options.camera
118
  k=[[c.fx,0,c.cx],[0,c.fy,c.cy],[0,0,1]] if c else None
 
129
  with np.load(job/'sam-raw-private.npz',allow_pickle=False) as archive:raw={key:archive[key] for key in archive.files}
130
  if not raw['projection_valid'].any():raise RuntimeError('SAM did not produce any projection-consistent frames')
131
  model=read_json(job/'sam-raw-private.json')['model']
132
+ return raw,model
133
+
134
+
135
+ def run(job,models,max_frames=7200,max_pixels=8294400,max_duration=120):
136
+ from .ingest import ingest
137
+ job=Path(job);options=SamBattingInput.model_validate(read_json(job/'request.json'))
138
+ started=time.monotonic()
139
+ def progress(stage,done=0,total=None):
140
+ atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
141
+ 'stage_progress':done/total if total else None,'elapsed_s':round(time.monotonic()-started,2)})
142
+ video=next(job.glob('input.*'));progress('decoding')
143
+ capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
144
+ atomic_json(job/'capture-private.json',capture)
145
+ if any(w.end_frame>=capture['frame_count'] for w in options.windows):raise ValueError('Reviewed window exceeds video')
146
+ raw,model=reconstruct_sam(job,video,capture,models,options,progress)
147
  return process_predictions(job,video,capture,raw,options,model,progress=progress)
148
 
149
 
baseball_batting/sam_videos.py CHANGED
@@ -13,6 +13,13 @@ FOCUS={'rotation':{5,6,9,10},'timing':{5,6,7,8,9,10,41,62},
13
  'posture':{3,4,5,6,9,10},'stance':{9,10,11,12,13,14,15,16,17,18,19,20}}
14
 
15
 
 
 
 
 
 
 
 
16
  def draw_group(image,xy,valid,group):
17
  image=image.copy();w=image.shape[1]
18
  radius=max(2,round(w/220))
@@ -44,9 +51,7 @@ def export_group_videos(video,capture,corrected,intrinsics,job,progress=None):
44
  if i>=n or pts is None or not base or pts*base!=source[i]:raise ClipError('source_video_mismatch')
45
  ticks=(timeline[i+1]-timeline[i]) if i+1<n else (_ticks(duration*base) if duration and duration>0 else 0)
46
  if ticks<=0:raise ClipError('last_frame_duration_unavailable')
47
- k=intrinsics[i]
48
- xy=project(corrected['points_camera'][i],k) if np.isfinite(k).all() else np.full((70,2),np.nan)
49
- valid=corrected['valid'][i]&np.isfinite(xy).all(axis=-1)
50
  for key in keys:
51
  annotated=draw_group(image,xy,valid,key)
52
  if key not in writers:writers[key]=_Writer(temporary[key],annotated.shape)
 
13
  'posture':{3,4,5,6,9,10},'stance':{9,10,11,12,13,14,15,16,17,18,19,20}}
14
 
15
 
16
+ def corrected_projection(corrected,intrinsics,index):
17
+ points=corrected['points_camera'][index];k=intrinsics[index]
18
+ xy=project(points,k) if np.isfinite(k).all() else np.full((70,2),np.nan)
19
+ valid=corrected['valid'][index]&np.isfinite(xy).all(axis=-1)&(points[:,2]>1e-8)
20
+ return xy,valid
21
+
22
+
23
  def draw_group(image,xy,valid,group):
24
  image=image.copy();w=image.shape[1]
25
  radius=max(2,round(w/220))
 
51
  if i>=n or pts is None or not base or pts*base!=source[i]:raise ClipError('source_video_mismatch')
52
  ticks=(timeline[i+1]-timeline[i]) if i+1<n else (_ticks(duration*base) if duration and duration>0 else 0)
53
  if ticks<=0:raise ClipError('last_frame_duration_unavailable')
54
+ xy,valid=corrected_projection(corrected,intrinsics,i)
 
 
55
  for key in keys:
56
  annotated=draw_group(image,xy,valid,key)
57
  if key not in writers:writers[key]=_Writer(temporary[key],annotated.shape)
docs/MOTION_PLAYER_API.md ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Motion-player backend API
2
+
3
+ Version 1.0 · 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. A client frontend and animated body mesh are outside this version.
10
+
11
+ ## Routes
12
+
13
+ | Method and path | Purpose |
14
+ | --- | --- |
15
+ | `POST /v1/motion-analyses` | Multipart video or existing source asset; returns 202. |
16
+ | `GET /v1/motion-analyses/{job_id}` | Status, progress, immutable revision and failure reason. |
17
+ | `GET /v1/motion-analyses/{job_id}/result` | Completed manifest and artifact URLs. |
18
+ | `GET` / `HEAD /v1/motion-analyses/{job_id}/artifacts/{name}` | Authenticated, checksummed artifact; byte ranges supported. |
19
+ | `POST /v1/motion-analyses/{job_id}/revisions` | Recording-fact/correction/event patch into a new immutable revision. |
20
+ | `DELETE /v1/motion-analyses/{job_id}` | Cancel/delete this execution and its retained files. |
21
+ | `GET /v1/motion-analyses/capabilities` | Model/configuration, limits and retention. |
22
+ | `GET /v1/motion-analyses/input-schema` | Recording options schema. |
23
+ | `GET /v1/motion-analyses/output-schema` | Manifest, motion-frame and projection-frame schemas. |
24
+
25
+ ## Upload and polling
26
+
27
+ In form-data, `video` is a File and `options` is Text containing JSON. Alternatively
28
+ omit `video` and send `source_asset_id` from a completed motion manifest. Exactly
29
+ one source is required; remote URLs and server paths are not accepted.
30
+
31
+ 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",
38
+ "timing": {"kind": "unretimed", "source": "Original speed verified by uploader"},
39
+ "single_swing": false,
40
+ "annotated_videos": true
41
+ }
42
+ ```
43
+
44
+ Other options reuse the SAM input: upright-image camera intrinsics; documented
45
+ `up_vector` and `pitcher_vector`; uniform `scale_factor` and its source;
46
+ `lead_foot`, `athlete_box`, correction settings and reviewed `windows` in decoded
47
+ source-frame indices. `scale_status` defaults to `model_estimated`; `calibrated`
48
+ requires a calibration source; `unknown` exports model units and disables absolute
49
+ distances/linear speeds. Height alone is not camera calibration. `source_mirrored`
50
+ records the source information; the adapter does not silently flip/relabel it.
51
+ This version uses a pinhole model; distortion correction and calibrated ground
52
+ translation are not supplied. Missing calibration does not prevent motion export.
53
+ Coaching/LLM calls are disabled on this path.
54
+
55
+ The 202 response includes `analysis_id`, `job_id`, `analysis_revision`,
56
+ `parent_job_id`, `status_url`, `result_url` and `retention_hours`. The first
57
+ analysis ID equals its job ID. Poll the supplied status URL until `completed` or
58
+ `failed`; active work reports `processing`. Queued/uploading/cancelled states are
59
+ explicit. Completed results can contain unavailable individual measurements.
60
+ No usable motion, fewer than four decoded frames, invalid timestamps, ambiguous
61
+ athlete selection or inference failure produces a failed job with a reason.
62
+
63
+ Multiple plausible athletes require `athlete_box`. Tracking uses conservative
64
+ box continuity, not biometric identity recognition. After tracking loss, automatic
65
+ reidentification is disabled and uncertain frames remain unusable.
66
+
67
+ ## Manifest and artifacts
68
+
69
+ The manifest declares the ordered 22-joint anatomical skeleton, native MHR70
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.
73
+
74
+ | Artifact name | Content |
75
+ | --- | --- |
76
+ | `motion` | `motion.jsonl`: one corrected joint record per decoded source frame. |
77
+ | `source` | Original uploaded video bytes, with orientation/display dimensions. |
78
+ | `measurements` | `measurements.json`: four groups' summaries and graph series. |
79
+ | `events` | `events.json`: windows, baseline, stride/foot plant and speed peaks. |
80
+ | `quality` | `quality.json`: segments, corrections and identity/accuracy limitations. |
81
+ | `projections` | `projections.jsonl`: projections of the same corrected joints, when valid. |
82
+ | `annotated_rotation`, `annotated_timing`, `annotated_posture`, `annotated_stance` | Optional MP4s with group skeleton overlays; no bottom panel. |
83
+ | `mesh` | Unavailable with reason `animated_mesh_second_phase`. |
84
+
85
+ Each artifact includes status, format, media type, authenticated relative URL,
86
+ size, SHA-256 and `expires_at`, or an unavailable reason. All referenced files
87
+ are ready before completion. Only allowlisted artifacts are downloadable; raw
88
+ inference/debugging arrays remain private. Follow returned URLs with the Bearer
89
+ header. Source videos and artifacts expire after the configured retention
90
+ (24 hours by default), cancellation or deletion. Ephemeral hosting can lose jobs
91
+ on redeployment; configure persistent `BASEBALL_DATA_ROOT` for durable replay.
92
+
93
+ ## Replay and alignment
94
+
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 SAM supplies none, and
99
+ reason codes. Gaps and filter boundaries remain explicit; there is no intentional
100
+ sampling, invented confidence or gap interpolation.
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
104
+ are recorded. Never assume index divided by nominal FPS is the timeline. Never
105
+ interpolate replay across segment/gap boundaries. Client playback interpolation
106
+ must not become measurement evidence.
107
+
108
+ Positions are hip-relative, in a fixed right-handed orientation. With supplied
109
+ field vectors, X is toward the pitcher, Z is declared up and Y = Z × X. With
110
+ only up, the starting hip axis supplies the fixed horizontal reference. Otherwise
111
+ the real camera axes (right/down/away) are exported without claiming gravity or
112
+ field direction. Native model scale remains estimated unless calibrated.
113
+
114
+ `root_translation_included` is false. The separate root is a model-estimated
115
+ camera root in the same export axes/units, **not ground motion**. For projection:
116
+
117
+ ```text
118
+ camera_point = (joint.position + frame.root_translation) @ camera_to_export_rotation
119
+ pixel = pinhole_project(camera_point, projection_frame.camera_intrinsics)
120
+ ```
121
+
122
+ Add root exactly once. Uniform scale cancels in perspective division. Projections
123
+ include source IDs/times, per-frame camera intrinsics, upright image dimensions,
124
+ validity and in-frame flags. Apply declared source orientation once. Raw detected
125
+ 2D points are not substituted for corrected projections. Overlay videos use those
126
+ same projections and original playback timing, at most 1280 pixels on the longest
127
+ side, without audio.
128
+
129
+ ## Measurements and events
130
+
131
+ The existing `sam_measurements.py` calculator implements the supplied companion
132
+ document's definitions. Summaries contain metric ID, definition version, value,
133
+ unit, reference, statistic, baseline, window, exact source samples/times, reasons
134
+ and interpolation provenance. Series contain shared definitions/units/references
135
+ and timestamped samples. Event-only values remain summaries; their curve samples
136
+ use `event_summary_only` rather than repeating a summary as continuous motion.
137
+
138
+ Head movement uses the ear midpoint; hand speed uses the wrist midpoint relative
139
+ to hips. Neither is bat speed, eye tracking or foot pressure. Sampled peak order
140
+ does not prove onset order/energy transfer. Body points alone do not establish
141
+ ball contact. Missing ground translation or a segment-mass model leaves ground
142
+ displacement/COM unavailable. Unknown scale disables cm and m/s values; unknown
143
+ physical timing disables rates/durations. Joint gaps and correction boundaries
144
+ block derivative evidence.
145
+
146
+ The backend exposes a reproduction helper using only public artifacts:
147
+
148
+ ```python
149
+ from baseball_batting.motion_export import reproduce_measurements
150
+ groups = reproduce_measurements(manifest_dict, "motion.jsonl")
151
+ ```
152
+
153
+ Events identify type, status, source, start/end source samples, revision and
154
+ reasons. Sources distinguish manual review, pose-estimated windows and sampled
155
+ speed peaks. Automatic windows remain candidates. An unavailable foot-plant
156
+ event does not prove that no step occurred.
157
+
158
+ ## Immutable reviewed revisions
159
+
160
+ Send a JSON patch to the parent's `/revisions` endpoint. Unchanged options are
161
+ inherited. Example:
162
+
163
+ ```json
164
+ {
165
+ "options": {
166
+ "windows": [{
167
+ "start_frame": 20,
168
+ "end_frame": 150,
169
+ "baseline_frame": 25,
170
+ "forward_start_frame": 75,
171
+ "forward_end_frame": 115,
172
+ "stride_start_frame": 45,
173
+ "landing_frame": 70,
174
+ "source": "Coach reviewed source recording"
175
+ }]
176
+ }
177
+ }
178
+ ```
179
+
180
+ The response retains the analysis ID, allocates a new job ID/revision and supplies
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
+
187
+ Tests cover joint completeness/mapping, axes/scale, variable cadence/retiming,
188
+ source/overlay synchronization, public-point reprojection, measurement reproduction,
189
+ explicit gaps/identity uncertainty, missing wrists, unknown camera/clock/scale,
190
+ immutable concurrent revisions, source retention, cancellation, authentication,
191
+ artifact checksums and byte ranges. These check implementation behavior. Hidden
192
+ depth, anatomical assignment in arbitrary real clips and real-world measurement
193
+ accuracy still need independent reference data. Smooth replay and image alignment
194
+ alone do not prove accurate 3D motion.
docs/motion-frame.schema.json ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$defs": {
3
+ "Joint": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "position": {
7
+ "anyOf": [
8
+ {
9
+ "maxItems": 3,
10
+ "minItems": 3,
11
+ "prefixItems": [
12
+ {
13
+ "type": "number"
14
+ },
15
+ {
16
+ "type": "number"
17
+ },
18
+ {
19
+ "type": "number"
20
+ }
21
+ ],
22
+ "type": "array"
23
+ },
24
+ {
25
+ "type": "null"
26
+ }
27
+ ],
28
+ "title": "Position"
29
+ },
30
+ "status": {
31
+ "enum": [
32
+ "estimated",
33
+ "interpolated",
34
+ "rejected",
35
+ "missing"
36
+ ],
37
+ "title": "Status",
38
+ "type": "string"
39
+ },
40
+ "confidence": {
41
+ "anyOf": [
42
+ {
43
+ "maximum": 1,
44
+ "minimum": 0,
45
+ "type": "number"
46
+ },
47
+ {
48
+ "type": "null"
49
+ }
50
+ ],
51
+ "default": null,
52
+ "title": "Confidence"
53
+ },
54
+ "reasons": {
55
+ "items": {
56
+ "type": "string"
57
+ },
58
+ "title": "Reasons",
59
+ "type": "array"
60
+ }
61
+ },
62
+ "required": [
63
+ "position",
64
+ "status"
65
+ ],
66
+ "title": "Joint",
67
+ "type": "object"
68
+ }
69
+ },
70
+ "additionalProperties": false,
71
+ "properties": {
72
+ "analysis_revision": {
73
+ "minimum": 1,
74
+ "title": "Analysis Revision",
75
+ "type": "integer"
76
+ },
77
+ "source_frame_index": {
78
+ "minimum": 0,
79
+ "title": "Source Frame Index",
80
+ "type": "integer"
81
+ },
82
+ "source_pts": {
83
+ "title": "Source Pts",
84
+ "type": "integer"
85
+ },
86
+ "source_time_base": {
87
+ "title": "Source Time Base",
88
+ "type": "string"
89
+ },
90
+ "video_time_s": {
91
+ "minimum": 0,
92
+ "title": "Video Time S",
93
+ "type": "number"
94
+ },
95
+ "capture_time_s": {
96
+ "anyOf": [
97
+ {
98
+ "minimum": 0,
99
+ "type": "number"
100
+ },
101
+ {
102
+ "type": "null"
103
+ }
104
+ ],
105
+ "default": null,
106
+ "title": "Capture Time S"
107
+ },
108
+ "segment_id": {
109
+ "title": "Segment Id",
110
+ "type": "string"
111
+ },
112
+ "joints": {
113
+ "additionalProperties": {
114
+ "$ref": "#/$defs/Joint"
115
+ },
116
+ "title": "Joints",
117
+ "type": "object"
118
+ },
119
+ "root_translation": {
120
+ "anyOf": [
121
+ {
122
+ "maxItems": 3,
123
+ "minItems": 3,
124
+ "prefixItems": [
125
+ {
126
+ "type": "number"
127
+ },
128
+ {
129
+ "type": "number"
130
+ },
131
+ {
132
+ "type": "number"
133
+ }
134
+ ],
135
+ "type": "array"
136
+ },
137
+ {
138
+ "type": "null"
139
+ }
140
+ ],
141
+ "title": "Root Translation"
142
+ },
143
+ "frame_quality": {
144
+ "additionalProperties": true,
145
+ "title": "Frame Quality",
146
+ "type": "object"
147
+ }
148
+ },
149
+ "required": [
150
+ "analysis_revision",
151
+ "source_frame_index",
152
+ "source_pts",
153
+ "source_time_base",
154
+ "video_time_s",
155
+ "segment_id",
156
+ "joints",
157
+ "root_translation",
158
+ "frame_quality"
159
+ ],
160
+ "title": "MotionFrame",
161
+ "type": "object"
162
+ }
docs/motion-input.schema.json ADDED
@@ -0,0 +1,665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$defs": {
3
+ "CameraInput": {
4
+ "additionalProperties": false,
5
+ "description": "Intrinsics refer to the upright decoded image, after rotation.",
6
+ "properties": {
7
+ "fx": {
8
+ "exclusiveMinimum": 0,
9
+ "title": "Fx",
10
+ "type": "number"
11
+ },
12
+ "fy": {
13
+ "exclusiveMinimum": 0,
14
+ "title": "Fy",
15
+ "type": "number"
16
+ },
17
+ "cx": {
18
+ "minimum": 0,
19
+ "title": "Cx",
20
+ "type": "number"
21
+ },
22
+ "cy": {
23
+ "minimum": 0,
24
+ "title": "Cy",
25
+ "type": "number"
26
+ },
27
+ "source": {
28
+ "maxLength": 512,
29
+ "minLength": 1,
30
+ "title": "Source",
31
+ "type": "string"
32
+ }
33
+ },
34
+ "required": [
35
+ "fx",
36
+ "fy",
37
+ "cx",
38
+ "cy",
39
+ "source"
40
+ ],
41
+ "title": "CameraInput",
42
+ "type": "object"
43
+ },
44
+ "CorrectionSettings": {
45
+ "additionalProperties": false,
46
+ "properties": {
47
+ "min_cutoff_hz": {
48
+ "default": 6,
49
+ "exclusiveMinimum": 0,
50
+ "maximum": 30,
51
+ "title": "Min Cutoff Hz",
52
+ "type": "number"
53
+ },
54
+ "speed_coefficient": {
55
+ "default": 4,
56
+ "maximum": 30,
57
+ "minimum": 0,
58
+ "title": "Speed Coefficient",
59
+ "type": "number"
60
+ },
61
+ "max_gap_s": {
62
+ "default": 0.1,
63
+ "exclusiveMinimum": 0,
64
+ "maximum": 0.5,
65
+ "title": "Max Gap S",
66
+ "type": "number"
67
+ },
68
+ "bone_relative_tolerance": {
69
+ "default": 0.35,
70
+ "exclusiveMinimum": 0.05,
71
+ "maximum": 1,
72
+ "title": "Bone Relative Tolerance",
73
+ "type": "number"
74
+ },
75
+ "spike_mad_multiplier": {
76
+ "default": 6,
77
+ "maximum": 20,
78
+ "minimum": 3,
79
+ "title": "Spike Mad Multiplier",
80
+ "type": "number"
81
+ },
82
+ "boundary_samples": {
83
+ "default": 2,
84
+ "maximum": 5,
85
+ "minimum": 1,
86
+ "title": "Boundary Samples",
87
+ "type": "integer"
88
+ },
89
+ "spike_minimum_m": {
90
+ "default": 0.005,
91
+ "exclusiveMinimum": 0,
92
+ "maximum": 0.2,
93
+ "title": "Spike Minimum M",
94
+ "type": "number"
95
+ }
96
+ },
97
+ "title": "CorrectionSettings",
98
+ "type": "object"
99
+ },
100
+ "MeasurementSettings": {
101
+ "additionalProperties": false,
102
+ "properties": {
103
+ "minimum_axis_length_m": {
104
+ "default": 0.015,
105
+ "exclusiveMinimum": 0,
106
+ "maximum": 0.2,
107
+ "title": "Minimum Axis Length M",
108
+ "type": "number"
109
+ },
110
+ "minimum_horizontal_fraction": {
111
+ "default": 0.15,
112
+ "exclusiveMaximum": 1,
113
+ "exclusiveMinimum": 0,
114
+ "title": "Minimum Horizontal Fraction",
115
+ "type": "number"
116
+ },
117
+ "minimum_foot_vector_m": {
118
+ "default": 0.01,
119
+ "exclusiveMinimum": 0,
120
+ "maximum": 0.2,
121
+ "title": "Minimum Foot Vector M",
122
+ "type": "number"
123
+ },
124
+ "minimum_upright_torso_m": {
125
+ "default": 0.05,
126
+ "exclusiveMinimum": 0,
127
+ "maximum": 0.3,
128
+ "title": "Minimum Upright Torso M",
129
+ "type": "number"
130
+ },
131
+ "maximum_heading_step_deg": {
132
+ "default": 150,
133
+ "exclusiveMaximum": 180,
134
+ "exclusiveMinimum": 0,
135
+ "title": "Maximum Heading Step Deg",
136
+ "type": "number"
137
+ },
138
+ "peak_competition_ratio": {
139
+ "default": 0.9,
140
+ "exclusiveMinimum": 0,
141
+ "maximum": 1,
142
+ "title": "Peak Competition Ratio",
143
+ "type": "number"
144
+ },
145
+ "peak_separation_s": {
146
+ "default": 0.08,
147
+ "exclusiveMinimum": 0,
148
+ "maximum": 1,
149
+ "title": "Peak Separation S",
150
+ "type": "number"
151
+ },
152
+ "direction_min_rotation_deg": {
153
+ "default": 5,
154
+ "exclusiveMinimum": 0,
155
+ "maximum": 90,
156
+ "title": "Direction Min Rotation Deg",
157
+ "type": "number"
158
+ },
159
+ "motion_prominence_m_s": {
160
+ "default": 0.15,
161
+ "exclusiveMinimum": 0,
162
+ "maximum": 10,
163
+ "title": "Motion Prominence M S",
164
+ "type": "number"
165
+ },
166
+ "motion_separation_s": {
167
+ "default": 0.7,
168
+ "exclusiveMinimum": 0,
169
+ "maximum": 5,
170
+ "title": "Motion Separation S",
171
+ "type": "number"
172
+ },
173
+ "window_before_peak_s": {
174
+ "default": 0.2,
175
+ "exclusiveMinimum": 0,
176
+ "maximum": 2,
177
+ "title": "Window Before Peak S",
178
+ "type": "number"
179
+ },
180
+ "window_after_peak_s": {
181
+ "default": 0.25,
182
+ "exclusiveMinimum": 0,
183
+ "maximum": 2,
184
+ "title": "Window After Peak S",
185
+ "type": "number"
186
+ }
187
+ },
188
+ "title": "MeasurementSettings",
189
+ "type": "object"
190
+ },
191
+ "SwingWindow": {
192
+ "additionalProperties": false,
193
+ "properties": {
194
+ "start_frame": {
195
+ "minimum": 0,
196
+ "title": "Start Frame",
197
+ "type": "integer"
198
+ },
199
+ "end_frame": {
200
+ "minimum": 0,
201
+ "title": "End Frame",
202
+ "type": "integer"
203
+ },
204
+ "baseline_frame": {
205
+ "anyOf": [
206
+ {
207
+ "minimum": 0,
208
+ "type": "integer"
209
+ },
210
+ {
211
+ "type": "null"
212
+ }
213
+ ],
214
+ "default": null,
215
+ "title": "Baseline Frame"
216
+ },
217
+ "forward_start_frame": {
218
+ "anyOf": [
219
+ {
220
+ "minimum": 0,
221
+ "type": "integer"
222
+ },
223
+ {
224
+ "type": "null"
225
+ }
226
+ ],
227
+ "default": null,
228
+ "title": "Forward Start Frame"
229
+ },
230
+ "forward_end_frame": {
231
+ "anyOf": [
232
+ {
233
+ "minimum": 0,
234
+ "type": "integer"
235
+ },
236
+ {
237
+ "type": "null"
238
+ }
239
+ ],
240
+ "default": null,
241
+ "title": "Forward End Frame"
242
+ },
243
+ "stride_start_frame": {
244
+ "anyOf": [
245
+ {
246
+ "minimum": 0,
247
+ "type": "integer"
248
+ },
249
+ {
250
+ "type": "null"
251
+ }
252
+ ],
253
+ "default": null,
254
+ "title": "Stride Start Frame"
255
+ },
256
+ "landing_frame": {
257
+ "anyOf": [
258
+ {
259
+ "minimum": 0,
260
+ "type": "integer"
261
+ },
262
+ {
263
+ "type": "null"
264
+ }
265
+ ],
266
+ "default": null,
267
+ "title": "Landing Frame"
268
+ },
269
+ "forward_rotation_sign": {
270
+ "anyOf": [
271
+ {
272
+ "enum": [
273
+ -1,
274
+ 1
275
+ ],
276
+ "type": "integer"
277
+ },
278
+ {
279
+ "type": "null"
280
+ }
281
+ ],
282
+ "default": null,
283
+ "title": "Forward Rotation Sign"
284
+ },
285
+ "source": {
286
+ "default": "caller_reviewed_video",
287
+ "maxLength": 180,
288
+ "minLength": 1,
289
+ "title": "Source",
290
+ "type": "string"
291
+ }
292
+ },
293
+ "required": [
294
+ "start_frame",
295
+ "end_frame"
296
+ ],
297
+ "title": "SwingWindow",
298
+ "type": "object"
299
+ },
300
+ "TimingInput": {
301
+ "additionalProperties": false,
302
+ "properties": {
303
+ "kind": {
304
+ "default": "unknown",
305
+ "enum": [
306
+ "unknown",
307
+ "unretimed",
308
+ "constant_slowdown",
309
+ "explicit"
310
+ ],
311
+ "title": "Kind",
312
+ "type": "string"
313
+ },
314
+ "source": {
315
+ "anyOf": [
316
+ {
317
+ "maxLength": 512,
318
+ "minLength": 1,
319
+ "type": "string"
320
+ },
321
+ {
322
+ "type": "null"
323
+ }
324
+ ],
325
+ "default": null,
326
+ "title": "Source"
327
+ },
328
+ "factor": {
329
+ "anyOf": [
330
+ {
331
+ "exclusiveMinimum": 0,
332
+ "type": "number"
333
+ },
334
+ {
335
+ "type": "null"
336
+ }
337
+ ],
338
+ "default": null,
339
+ "title": "Factor"
340
+ },
341
+ "all_captured_frames_retained": {
342
+ "anyOf": [
343
+ {
344
+ "type": "boolean"
345
+ },
346
+ {
347
+ "type": "null"
348
+ }
349
+ ],
350
+ "default": null,
351
+ "title": "All Captured Frames Retained"
352
+ },
353
+ "physical_times_s": {
354
+ "anyOf": [
355
+ {
356
+ "items": {
357
+ "type": "number"
358
+ },
359
+ "maxItems": 20000,
360
+ "minItems": 1,
361
+ "type": "array"
362
+ },
363
+ {
364
+ "type": "null"
365
+ }
366
+ ],
367
+ "default": null,
368
+ "title": "Physical Times S"
369
+ }
370
+ },
371
+ "title": "TimingInput",
372
+ "type": "object"
373
+ }
374
+ },
375
+ "additionalProperties": false,
376
+ "properties": {
377
+ "timing": {
378
+ "$ref": "#/$defs/TimingInput"
379
+ },
380
+ "rotation_degrees": {
381
+ "anyOf": [
382
+ {
383
+ "enum": [
384
+ 0,
385
+ 90,
386
+ 180,
387
+ 270
388
+ ],
389
+ "type": "integer"
390
+ },
391
+ {
392
+ "type": "null"
393
+ }
394
+ ],
395
+ "default": null,
396
+ "title": "Rotation Degrees"
397
+ },
398
+ "camera_stability": {
399
+ "default": "unknown",
400
+ "enum": [
401
+ "unknown",
402
+ "fixed_verified",
403
+ "moving"
404
+ ],
405
+ "title": "Camera Stability",
406
+ "type": "string"
407
+ },
408
+ "handedness": {
409
+ "anyOf": [
410
+ {
411
+ "enum": [
412
+ "left",
413
+ "right"
414
+ ],
415
+ "type": "string"
416
+ },
417
+ {
418
+ "type": "null"
419
+ }
420
+ ],
421
+ "default": null,
422
+ "title": "Handedness"
423
+ },
424
+ "lead_foot": {
425
+ "anyOf": [
426
+ {
427
+ "enum": [
428
+ "left",
429
+ "right"
430
+ ],
431
+ "type": "string"
432
+ },
433
+ {
434
+ "type": "null"
435
+ }
436
+ ],
437
+ "default": null,
438
+ "title": "Lead Foot"
439
+ },
440
+ "camera": {
441
+ "anyOf": [
442
+ {
443
+ "$ref": "#/$defs/CameraInput"
444
+ },
445
+ {
446
+ "type": "null"
447
+ }
448
+ ],
449
+ "default": null
450
+ },
451
+ "up_vector": {
452
+ "anyOf": [
453
+ {
454
+ "maxItems": 3,
455
+ "minItems": 3,
456
+ "prefixItems": [
457
+ {
458
+ "type": "number"
459
+ },
460
+ {
461
+ "type": "number"
462
+ },
463
+ {
464
+ "type": "number"
465
+ }
466
+ ],
467
+ "type": "array"
468
+ },
469
+ {
470
+ "type": "null"
471
+ }
472
+ ],
473
+ "default": null,
474
+ "title": "Up Vector"
475
+ },
476
+ "up_source": {
477
+ "anyOf": [
478
+ {
479
+ "maxLength": 300,
480
+ "type": "string"
481
+ },
482
+ {
483
+ "type": "null"
484
+ }
485
+ ],
486
+ "default": null,
487
+ "title": "Up Source"
488
+ },
489
+ "pitcher_vector": {
490
+ "anyOf": [
491
+ {
492
+ "maxItems": 3,
493
+ "minItems": 3,
494
+ "prefixItems": [
495
+ {
496
+ "type": "number"
497
+ },
498
+ {
499
+ "type": "number"
500
+ },
501
+ {
502
+ "type": "number"
503
+ }
504
+ ],
505
+ "type": "array"
506
+ },
507
+ {
508
+ "type": "null"
509
+ }
510
+ ],
511
+ "default": null,
512
+ "title": "Pitcher Vector"
513
+ },
514
+ "pitcher_source": {
515
+ "anyOf": [
516
+ {
517
+ "maxLength": 300,
518
+ "type": "string"
519
+ },
520
+ {
521
+ "type": "null"
522
+ }
523
+ ],
524
+ "default": null,
525
+ "title": "Pitcher Source"
526
+ },
527
+ "scale_factor": {
528
+ "default": 1,
529
+ "exclusiveMinimum": 0,
530
+ "maximum": 10,
531
+ "title": "Scale Factor",
532
+ "type": "number"
533
+ },
534
+ "scale_source": {
535
+ "anyOf": [
536
+ {
537
+ "maxLength": 300,
538
+ "type": "string"
539
+ },
540
+ {
541
+ "type": "null"
542
+ }
543
+ ],
544
+ "default": null,
545
+ "title": "Scale Source"
546
+ },
547
+ "athlete_box": {
548
+ "anyOf": [
549
+ {
550
+ "maxItems": 4,
551
+ "minItems": 4,
552
+ "prefixItems": [
553
+ {
554
+ "type": "number"
555
+ },
556
+ {
557
+ "type": "number"
558
+ },
559
+ {
560
+ "type": "number"
561
+ },
562
+ {
563
+ "type": "number"
564
+ }
565
+ ],
566
+ "type": "array"
567
+ },
568
+ {
569
+ "type": "null"
570
+ }
571
+ ],
572
+ "default": null,
573
+ "title": "Athlete Box"
574
+ },
575
+ "single_swing": {
576
+ "default": false,
577
+ "title": "Single Swing",
578
+ "type": "boolean"
579
+ },
580
+ "windows": {
581
+ "items": {
582
+ "$ref": "#/$defs/SwingWindow"
583
+ },
584
+ "maxItems": 20,
585
+ "title": "Windows",
586
+ "type": "array"
587
+ },
588
+ "correction": {
589
+ "$ref": "#/$defs/CorrectionSettings"
590
+ },
591
+ "measurement": {
592
+ "$ref": "#/$defs/MeasurementSettings"
593
+ },
594
+ "coaching": {
595
+ "const": false,
596
+ "default": false,
597
+ "title": "Coaching",
598
+ "type": "boolean"
599
+ },
600
+ "annotated_videos": {
601
+ "default": true,
602
+ "title": "Annotated Videos",
603
+ "type": "boolean"
604
+ },
605
+ "source_mirrored": {
606
+ "anyOf": [
607
+ {
608
+ "type": "boolean"
609
+ },
610
+ {
611
+ "type": "null"
612
+ }
613
+ ],
614
+ "default": null,
615
+ "title": "Source Mirrored"
616
+ },
617
+ "handedness_source": {
618
+ "anyOf": [
619
+ {
620
+ "maxLength": 300,
621
+ "minLength": 1,
622
+ "type": "string"
623
+ },
624
+ {
625
+ "type": "null"
626
+ }
627
+ ],
628
+ "default": null,
629
+ "title": "Handedness Source"
630
+ },
631
+ "lead_foot_source": {
632
+ "anyOf": [
633
+ {
634
+ "maxLength": 300,
635
+ "minLength": 1,
636
+ "type": "string"
637
+ },
638
+ {
639
+ "type": "null"
640
+ }
641
+ ],
642
+ "default": null,
643
+ "title": "Lead Foot Source"
644
+ },
645
+ "scale_status": {
646
+ "default": "model_estimated",
647
+ "enum": [
648
+ "model_estimated",
649
+ "calibrated",
650
+ "unknown"
651
+ ],
652
+ "title": "Scale Status",
653
+ "type": "string"
654
+ },
655
+ "minimum_usable_joints": {
656
+ "default": 3,
657
+ "maximum": 22,
658
+ "minimum": 3,
659
+ "title": "Minimum Usable Joints",
660
+ "type": "integer"
661
+ }
662
+ },
663
+ "title": "MotionInput",
664
+ "type": "object"
665
+ }
docs/motion-manifest.schema.json ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$defs": {
3
+ "Artifact": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "status": {
7
+ "enum": [
8
+ "available",
9
+ "unavailable"
10
+ ],
11
+ "title": "Status",
12
+ "type": "string"
13
+ },
14
+ "url": {
15
+ "anyOf": [
16
+ {
17
+ "type": "string"
18
+ },
19
+ {
20
+ "type": "null"
21
+ }
22
+ ],
23
+ "default": null,
24
+ "title": "Url"
25
+ },
26
+ "filename": {
27
+ "anyOf": [
28
+ {
29
+ "type": "string"
30
+ },
31
+ {
32
+ "type": "null"
33
+ }
34
+ ],
35
+ "default": null,
36
+ "title": "Filename"
37
+ },
38
+ "format": {
39
+ "title": "Format",
40
+ "type": "string"
41
+ },
42
+ "media_type": {
43
+ "title": "Media Type",
44
+ "type": "string"
45
+ },
46
+ "size_bytes": {
47
+ "anyOf": [
48
+ {
49
+ "minimum": 1,
50
+ "type": "integer"
51
+ },
52
+ {
53
+ "type": "null"
54
+ }
55
+ ],
56
+ "default": null,
57
+ "title": "Size Bytes"
58
+ },
59
+ "sha256": {
60
+ "anyOf": [
61
+ {
62
+ "pattern": "^[a-f0-9]{64}$",
63
+ "type": "string"
64
+ },
65
+ {
66
+ "type": "null"
67
+ }
68
+ ],
69
+ "default": null,
70
+ "title": "Sha256"
71
+ },
72
+ "expires_at": {
73
+ "title": "Expires At",
74
+ "type": "string"
75
+ },
76
+ "reason_code": {
77
+ "anyOf": [
78
+ {
79
+ "type": "string"
80
+ },
81
+ {
82
+ "type": "null"
83
+ }
84
+ ],
85
+ "default": null,
86
+ "title": "Reason Code"
87
+ }
88
+ },
89
+ "required": [
90
+ "status",
91
+ "format",
92
+ "media_type",
93
+ "expires_at"
94
+ ],
95
+ "title": "Artifact",
96
+ "type": "object"
97
+ }
98
+ },
99
+ "additionalProperties": false,
100
+ "properties": {
101
+ "schema_version": {
102
+ "const": "1.0",
103
+ "default": "1.0",
104
+ "title": "Schema Version",
105
+ "type": "string"
106
+ },
107
+ "analysis_id": {
108
+ "title": "Analysis Id",
109
+ "type": "string"
110
+ },
111
+ "job_id": {
112
+ "title": "Job Id",
113
+ "type": "string"
114
+ },
115
+ "analysis_revision": {
116
+ "minimum": 1,
117
+ "title": "Analysis Revision",
118
+ "type": "integer"
119
+ },
120
+ "parent_job_id": {
121
+ "anyOf": [
122
+ {
123
+ "type": "string"
124
+ },
125
+ {
126
+ "type": "null"
127
+ }
128
+ ],
129
+ "default": null,
130
+ "title": "Parent Job Id"
131
+ },
132
+ "person_id": {
133
+ "title": "Person Id",
134
+ "type": "string"
135
+ },
136
+ "source_video": {
137
+ "additionalProperties": true,
138
+ "title": "Source Video",
139
+ "type": "object"
140
+ },
141
+ "pipeline": {
142
+ "additionalProperties": true,
143
+ "title": "Pipeline",
144
+ "type": "object"
145
+ },
146
+ "coordinates": {
147
+ "additionalProperties": true,
148
+ "title": "Coordinates",
149
+ "type": "object"
150
+ },
151
+ "timing": {
152
+ "additionalProperties": true,
153
+ "title": "Timing",
154
+ "type": "object"
155
+ },
156
+ "skeleton": {
157
+ "additionalProperties": true,
158
+ "title": "Skeleton",
159
+ "type": "object"
160
+ },
161
+ "sampling": {
162
+ "additionalProperties": true,
163
+ "title": "Sampling",
164
+ "type": "object"
165
+ },
166
+ "quality": {
167
+ "additionalProperties": true,
168
+ "title": "Quality",
169
+ "type": "object"
170
+ },
171
+ "artifacts": {
172
+ "additionalProperties": {
173
+ "$ref": "#/$defs/Artifact"
174
+ },
175
+ "title": "Artifacts",
176
+ "type": "object"
177
+ },
178
+ "expires_at": {
179
+ "title": "Expires At",
180
+ "type": "string"
181
+ },
182
+ "accuracy_validated": {
183
+ "const": false,
184
+ "default": false,
185
+ "title": "Accuracy Validated",
186
+ "type": "boolean"
187
+ }
188
+ },
189
+ "required": [
190
+ "analysis_id",
191
+ "job_id",
192
+ "analysis_revision",
193
+ "person_id",
194
+ "source_video",
195
+ "pipeline",
196
+ "coordinates",
197
+ "timing",
198
+ "skeleton",
199
+ "sampling",
200
+ "quality",
201
+ "artifacts",
202
+ "expires_at"
203
+ ],
204
+ "title": "MotionManifest",
205
+ "type": "object"
206
+ }
docs/motion-projection-frame.schema.json ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "additionalProperties": false,
3
+ "properties": {
4
+ "analysis_revision": {
5
+ "minimum": 1,
6
+ "title": "Analysis Revision",
7
+ "type": "integer"
8
+ },
9
+ "source_frame_index": {
10
+ "minimum": 0,
11
+ "title": "Source Frame Index",
12
+ "type": "integer"
13
+ },
14
+ "video_time_s": {
15
+ "minimum": 0,
16
+ "title": "Video Time S",
17
+ "type": "number"
18
+ },
19
+ "capture_time_s": {
20
+ "anyOf": [
21
+ {
22
+ "type": "number"
23
+ },
24
+ {
25
+ "type": "null"
26
+ }
27
+ ],
28
+ "title": "Capture Time S"
29
+ },
30
+ "segment_id": {
31
+ "title": "Segment Id",
32
+ "type": "string"
33
+ },
34
+ "image_width": {
35
+ "minimum": 1,
36
+ "title": "Image Width",
37
+ "type": "integer"
38
+ },
39
+ "image_height": {
40
+ "minimum": 1,
41
+ "title": "Image Height",
42
+ "type": "integer"
43
+ },
44
+ "camera_intrinsics": {
45
+ "anyOf": [
46
+ {
47
+ "items": {
48
+ "items": {
49
+ "type": "number"
50
+ },
51
+ "type": "array"
52
+ },
53
+ "type": "array"
54
+ },
55
+ {
56
+ "type": "null"
57
+ }
58
+ ],
59
+ "title": "Camera Intrinsics"
60
+ },
61
+ "joints": {
62
+ "additionalProperties": {
63
+ "additionalProperties": true,
64
+ "type": "object"
65
+ },
66
+ "title": "Joints",
67
+ "type": "object"
68
+ }
69
+ },
70
+ "required": [
71
+ "analysis_revision",
72
+ "source_frame_index",
73
+ "video_time_s",
74
+ "capture_time_s",
75
+ "segment_id",
76
+ "image_width",
77
+ "image_height",
78
+ "camera_intrinsics",
79
+ "joints"
80
+ ],
81
+ "title": "ProjectionFrame",
82
+ "type": "object"
83
+ }
tests/test_motion_player.py ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Replay/recalculation agreement, clocks, conditional validity and immutable artifacts."""
2
+ import json
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pytest
6
+ from baseball_batting.motion_contract import MotionInput,MotionManifest,MotionFrame
7
+ from baseball_batting.motion_export import export_motion,reproduce_measurements,JOINTS
8
+ from baseball_batting.ingest import ingest,iter_frames
9
+ from baseball_batting.geometry import project
10
+ from baseball_batting.sam_motion import MHR
11
+ from baseball_batting.storage import sha256_file,atomic_json
12
+ from test_sam_batting import pose,raw_pose
13
+
14
+
15
+ def inputs(**kwargs):
16
+ return MotionInput(camera_stability='fixed_verified',up_vector=[0,-1,0],up_source='Known fixture vertical',
17
+ handedness='right',single_swing=True,**kwargs)
18
+
19
+
20
+ def raw_for(capture):
21
+ f=capture['frames'][0];raw=raw_pose(pose(capture['frame_count']),f['width'],f['height'])
22
+ # A known camera making all requested fixture joints visible, not a SAM accuracy claim.
23
+ raw['intrinsics'][:,0,0]=raw['intrinsics'][:,1,1]=60
24
+ raw['projection']=np.stack([project(p+c,k) for p,c,k in zip(raw['points_body'],raw['camera_translation'],raw['intrinsics'])])
25
+ return raw
26
+
27
+
28
+ def build(tmp_path,video,opts=None,mutate=None):
29
+ opts=opts or inputs(timing={'kind':'unretimed','source':'Known synthetic clock'})
30
+ capture=ingest(video,opts.metadata());raw=raw_for(capture)
31
+ if mutate:mutate(raw)
32
+ manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'synthetic fixture, not SAM'},
33
+ {'analysis_id':'fixture-analysis','analysis_revision':1},retention_s=100)
34
+ return manifest,capture,raw
35
+
36
+
37
+ def test_artifacts_reconstruct_all_joints_and_reproduce_measurements(tmp_path,video):
38
+ manifest,capture,_=build(tmp_path,video)
39
+ MotionManifest.model_validate_json((tmp_path/'result.json').read_text())
40
+ frames=[MotionFrame.model_validate_json(line) for line in (tmp_path/'motion.jsonl').read_text().splitlines()]
41
+ assert len(frames)==capture['frame_count']
42
+ assert all(set(f.joints)==set(JOINTS) for f in frames)
43
+ assert all(f.joints['left_wrist'].confidence is None for f in frames)
44
+ assert manifest.coordinates['root_translation_included'] is False
45
+ assert manifest.source_video['sha256']==sha256_file(video)
46
+ assert manifest.source_video['duration_s']>frames[-1].video_time_s
47
+ for asset in manifest.artifacts.values():
48
+ if asset.status=='available':assert sha256_file(tmp_path/asset.filename)==asset.sha256
49
+ assert (tmp_path/'source.mp4').read_bytes()==video.read_bytes()
50
+ series=json.loads((tmp_path/'measurements.json').read_text())
51
+ recomputed=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
52
+ values={(s.rep,m.key):m.value for swings in recomputed.values() for s in swings for m in s.measurements}
53
+ for metric in series['summaries']:
54
+ value=values[metric['rep'],metric['metric_id']]
55
+ assert value==pytest.approx(metric['value']) if value is not None else metric['value'] is None
56
+ assert {g for g in ('rotation','timing','posture','stance')}=={s['group'] for s in series['series']}
57
+ # Variable-cadence source timestamps survive both exported motion and all four videos.
58
+ expected=[r['playback_s']-capture['frames'][0]['playback_s'] for r in capture['frames']]
59
+ np.testing.assert_allclose([f.video_time_s for f in frames],expected)
60
+ for group in ('rotation','timing','posture','stance'):
61
+ actual=list(iter_frames(tmp_path/'group-videos'/(group+'.mp4')))
62
+ np.testing.assert_allclose([float(pts*base) for _,pts,base,_ in actual],expected,atol=2e-6)
63
+ assert actual[0][3].shape[:2]==(capture['frames'][0]['height'],capture['frames'][0]['width'])
64
+
65
+
66
+ def test_public_projection_uses_same_motion_and_root_exactly_once(tmp_path,video):
67
+ opts=inputs(scale_factor=2,scale_source='Fixture known scale',timing={'kind':'unretimed','source':'Fixture clock'})
68
+ manifest,_,_=build(tmp_path,video,opts)
69
+ motion=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
70
+ projections=[json.loads(l) for l in (tmp_path/'projections.jsonl').read_text().splitlines()]
71
+ rotation=np.array(manifest.coordinates['camera_to_export_rotation'])
72
+ assert np.linalg.det(rotation)==pytest.approx(1)
73
+ for frame,projection in zip(motion,projections):
74
+ assert frame['source_frame_index']==projection['source_frame_index']
75
+ for name,joint in frame['joints'].items():
76
+ if joint['position'] is None:continue
77
+ camera=(np.array(joint['position'])+frame['root_translation'])@rotation
78
+ xy=project(camera,projection['camera_intrinsics'])
79
+ np.testing.assert_allclose(xy,projection['joints'][name]['pixel'],atol=1e-9)
80
+ # Corrected joints stay in a fixed, right-handed frame, with anatomical mapping.
81
+ assert manifest.skeleton['joint_order'].index('left_wrist')!=MHR['left_wrist']
82
+ assert next(j for j in manifest.skeleton['joints'] if j['name']=='left_wrist')['source_index']==62
83
+ recomputed=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
84
+ stance=next(m for s in recomputed['stance'] for m in s.measurements if m.key=='stance_span_cm')
85
+ assert stance.value==120
86
+
87
+
88
+ @pytest.mark.parametrize('kind',['unknown_clock','unknown_scale','unknown_camera','missing_wrist','spike'])
89
+ def test_specific_quality_and_missing_dependencies_do_not_remove_other_groups(tmp_path,video,kind):
90
+ if kind=='spike':
91
+ # Robust spike statistics need a longer clean baseline than the eight-frame cadence fixture.
92
+ import av
93
+ video=tmp_path/'spike.mp4'
94
+ with av.open(str(video),'w') as out:
95
+ stream=out.add_stream('libx264',rate=30);stream.width=160;stream.height=120;stream.pix_fmt='yuv420p'
96
+ for i in range(31):
97
+ for packet in stream.encode(av.VideoFrame.from_ndarray(np.full((120,160,3),i,np.uint8),format='bgr24')):out.mux(packet)
98
+ for packet in stream.encode():out.mux(packet)
99
+ kwargs={'annotated_videos':False,'timing':{'kind':'unretimed','source':'Fixture clock'}}
100
+ if kind=='unknown_clock':kwargs['timing']={'kind':'unknown'}
101
+ if kind=='unknown_scale':kwargs['scale_status']='unknown'
102
+ opts=inputs(**kwargs)
103
+ if kind=='unknown_camera':opts.camera_stability='moving'
104
+ def mutate(raw):
105
+ if kind=='missing_wrist':raw['points_body'][4,MHR['right_wrist']]=np.nan
106
+ if kind=='spike':raw['points_body'][4,MHR['left_wrist'],0]+=1
107
+ manifest,_,_=build(tmp_path,video,opts,mutate)
108
+ rows=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
109
+ values=json.loads((tmp_path/'measurements.json').read_text())
110
+ if kind=='unknown_clock':
111
+ assert all(f['capture_time_s'] is None for f in rows)
112
+ assert all(m['value'] is None for m in values['summaries'] if m['unit'] in ('m/s','deg/s','ms'))
113
+ if kind=='unknown_scale':
114
+ assert manifest.coordinates['unit']=='model_units'
115
+ assert all(m['value'] is None and m['reason_code']=='scale_unknown' for m in values['summaries'] if m['unit'] in ('cm','m/s'))
116
+ if kind=='unknown_camera':
117
+ assert manifest.coordinates['frame']=='camera_oriented_hip_relative'
118
+ assert manifest.coordinates['axes']['y']=='camera_down'
119
+ assert all(m['value'] is None for m in values['summaries'] if m['unit']=='deg')
120
+ if kind in ('missing_wrist','spike'):
121
+ name='right_wrist' if kind=='missing_wrist' else 'left_wrist'
122
+ joint=rows[4]['joints'][name]
123
+ assert joint['position'] is None
124
+ assert joint['status']==('missing' if kind=='missing_wrist' else 'rejected')
125
+ assert next(m['value'] for m in values['summaries'] if m['metric_id']=='stance_span_cm')==60
126
+ assert not any(f['joints'][name]['status']=='interpolated' for f in rows for name in JOINTS)
127
+ assert manifest.artifacts['mesh'].status=='unavailable'
128
+ assert all(a.status=='unavailable' for key,a in manifest.artifacts.items() if key.startswith('annotated_'))
129
+ for path in tmp_path.glob('*.json*'):
130
+ for line in path.read_text().splitlines() if path.suffix=='.jsonl' else [path.read_text()]:
131
+ json.loads(line,parse_constant=lambda v:(_ for _ in ()).throw(ValueError(v)))
132
+
133
+
134
+ def test_retiming_events_and_immutable_export_are_aligned(tmp_path,video):
135
+ opts=inputs(timing={'kind':'constant_slowdown','source':'Fixture capture','factor':4,'all_captured_frames_retained':True},
136
+ annotated_videos=False,windows=[{'start_frame':0,'end_frame':7,'baseline_frame':0,
137
+ 'stride_start_frame':1,'landing_frame':5,'forward_start_frame':1,'forward_end_frame':6,'forward_rotation_sign':1}])
138
+ manifest,capture,_=build(tmp_path,video,opts)
139
+ frames=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
140
+ np.testing.assert_allclose([f['capture_time_s'] for f in frames],[f['video_time_s']/4 for f in frames])
141
+ events=json.loads((tmp_path/'events.json').read_text())['events']
142
+ plant=next(e for e in events if e['type']=='foot_plant')
143
+ assert plant['source']=='manual' and plant['status']=='reviewed'
144
+ assert plant['start']['source_frame_index']==5
145
+ assert plant['start']['capture_time_s']==pytest.approx(capture['frames'][5]['physical_s'])
146
+ assert next(e for e in events if e['type']=='ball_contact')['status']=='unavailable'
147
+ # A resumed export is safe if the source link was already written before restart.
148
+ original=manifest.artifacts['source'].sha256
149
+ export_motion(tmp_path,video,capture,raw_for(capture),opts,{'name':'fixture'},
150
+ {'analysis_id':'fixture-analysis','analysis_revision':1})
151
+ assert sha256_file(tmp_path/'source.mp4')==original
152
+
153
+
154
+ def test_no_usable_pose_is_failure_instead_of_empty_success(tmp_path,video):
155
+ def missing(raw):raw['points_body'][:]=np.nan
156
+ with pytest.raises(ValueError,match='no_usable_motion'):build(tmp_path,video,mutate=missing)
157
+ assert not (tmp_path/'result.json').exists()
158
+
159
+
160
+ def test_clock_gaps_and_identity_uncertainty_remain_explicit(tmp_path,video):
161
+ opts=inputs(annotated_videos=False,timing={'kind':'explicit','source':'Known fixture times',
162
+ 'physical_times_s':[0,.01,.02,.03,1.,1.01,1.02,1.03]})
163
+ capture=ingest(video,opts.metadata());raw=raw_for(capture)
164
+ track={'reasons':[None]*6+['identity_uncertain_after_tracking_loss']*2}
165
+ manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'fixture'},
166
+ {'analysis_id':'fixture','analysis_revision':1},track=track)
167
+ rows=[json.loads(l) for l in (tmp_path/'motion.jsonl').read_text().splitlines()]
168
+ assert rows[3]['segment_id']!=rows[4]['segment_id']
169
+ assert 'timestamp_gap' in rows[4]['frame_quality']['reasons']
170
+ assert not rows[6]['frame_quality']['pose_available']
171
+ assert all(j['position'] is None for j in rows[6]['joints'].values())
172
+ assert all('identity_uncertain_after_tracking_loss' in j['reasons'] for j in rows[6]['joints'].values())
173
+ assert np.isfinite(raw['points_body']).all() # Debug predictions have not been overwritten.
174
+ series=json.loads((tmp_path/'measurements.json').read_text())['series']
175
+ assert all(s['value'] is None for metric in series if metric['unit'] in ('deg/s','m/s') for s in metric['samples'])
176
+
177
+
178
+ def test_worker_reuses_native_inference_for_reviewed_event_revision(tmp_path,video,monkeypatch):
179
+ from baseball_batting import motion_worker
180
+ from baseball_batting.api import create_app
181
+ from baseball_batting.api_jobs import JobService
182
+ from fastapi.testclient import TestClient
183
+ from test_api import settings,AUTH
184
+ service=JobService(settings(tmp_path));calls=[]
185
+ def infer(job,source,capture,models,options,progress,**kwargs):
186
+ calls.append(kwargs);raw=raw_for(capture)
187
+ np.savez_compressed(job/'sam-raw-private.npz',**raw)
188
+ model={'name':'fixture only'}
189
+ atomic_json(job/'sam-raw-private.json',{'model':model})
190
+ atomic_json(job/'person-track-private.json',{'reasons':[None]*capture['frame_count']})
191
+ return raw,model
192
+ monkeypatch.setattr(motion_worker,'reconstruct_sam',infer)
193
+ monkeypatch.setattr('baseball_batting.motion_api.configured_record',lambda:{'configured':True})
194
+ lineage=service.store.create_motion(20);parent=service.job_directory(lineage['job_id']);parent.mkdir()
195
+ (parent/'input.mp4').write_bytes(video.read_bytes())
196
+ opts=inputs(annotated_videos=False,timing={'kind':'unretimed','source':'Fixture clock'})
197
+ atomic_json(parent/'request.json',opts.model_dump(mode='json'));atomic_json(parent/'lineage.json',lineage)
198
+ motion_worker.run(parent,tmp_path/'models')
199
+ service.store.update(parent.name,'completed',result_hash=sha256_file(parent/'result.json'))
200
+ before=(parent/'result.json').read_bytes();service.ready=True
201
+ client=TestClient(create_app(service.settings,service))
202
+ r=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,
203
+ json={'options':{'correction':{'min_cutoff_hz':8},'windows':[{'start_frame':0,'end_frame':7,'stride_start_frame':1,'landing_frame':5}]}})
204
+ assert r.status_code==202
205
+ child=service.job_directory(r.json()['job_id']);assert (child/'reused-inference.json').is_file()
206
+ result=motion_worker.run(child,tmp_path/'models')
207
+ assert len(calls)==1 and calls[0]['strict_identity'] is True
208
+ assert result.analysis_revision==2 and result.analysis_id==lineage['analysis_id']
209
+ assert result.pipeline['model']['inference_reused_from_job']==parent.name
210
+ assert (parent/'result.json').read_bytes()==before
211
+ # Queue finalization removes only the upload link, retaining the authenticated source artifact.
212
+ import sys
213
+ service.command_factory=lambda directory:[sys.executable,'-c','pass']
214
+ service.store.claim();service.execute(child.name)
215
+ assert service.store.get(child.name)['status']=='completed'
216
+ assert not (child/'input.mp4').exists() and (child/'source.mp4').exists()
217
+ reject=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,
218
+ json={'options':{'athlete_box':[0,0,100,100]}})
219
+ assert reject.status_code==422
tests/test_motion_player_api.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from concurrent.futures import ThreadPoolExecutor
3
+ import pytest
4
+ from fastapi.testclient import TestClient
5
+ from baseball_batting.api import create_app
6
+ from baseball_batting.api_jobs import JobStore,JobService
7
+ from baseball_batting.storage import atomic_json,sha256_file
8
+ from baseball_batting.motion_contract import MotionInput
9
+ from test_api import fake_service,settings,wait_until,AUTH
10
+ from test_motion_player import build,inputs
11
+
12
+
13
+ def stored(service,video):
14
+ lineage=service.store.create_motion(20);job=service.job_directory(lineage['job_id']);job.mkdir()
15
+ manifest,_,_=build(job,video,inputs(annotated_videos=False,timing={'kind':'unretimed','source':'Fixture clock'}))
16
+ # Match the actual immutable queue lineage used by the API.
17
+ manifest.analysis_id=lineage['analysis_id'];manifest.job_id=lineage['job_id']
18
+ atomic_json(job/'result.json',manifest.model_dump(mode='json'))
19
+ atomic_json(job/'request.json',MotionInput.model_validate(manifest.pipeline['inputs']).model_dump(mode='json'))
20
+ atomic_json(job/'lineage.json',lineage)
21
+ service.store.update(job.name,'completed',result_hash=sha256_file(job/'result.json'))
22
+ return job,manifest
23
+
24
+
25
+ def test_motion_upload_auth_readiness_validation_queue_and_cancel(tmp_path,video,monkeypatch):
26
+ import baseball_batting.motion_api as module
27
+ service=fake_service(settings(tmp_path),delay=30)
28
+ monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
29
+ with TestClient(create_app(service.settings,service)) as client:
30
+ wait_until(lambda:service.ready)
31
+ files={'video':('swing.mp4',video.read_bytes(),'video/mp4')}
32
+ assert client.post('/v1/motion-analyses',files=files).status_code==401
33
+ assert client.post('/v1/motion-analyses',files=files,headers=AUTH,data={'options':'{"worker_python":"bad"}'}).status_code==422
34
+ r=client.post('/v1/motion-analyses',files=files,headers=AUTH)
35
+ assert r.status_code==202
36
+ data=r.json();job=service.job_directory(data['job_id'])
37
+ assert service.store.get(job.name)['kind']=='motion_player'
38
+ assert json.loads((job/'request.json').read_text())['coaching'] is False
39
+ assert client.get(data['result_url'],headers=AUTH).status_code==409
40
+ assert client.get(data['status_url'],headers=AUTH).json()['analysis_revision']==1
41
+ assert client.delete(data['status_url'],headers=AUTH).status_code==202
42
+ wait_until(lambda:service.store.get(job.name)['status']=='cancelled')
43
+ assert not job.exists()
44
+ assert client.get('/v1/motion-analyses/output-schema',headers=AUTH).status_code==200
45
+ assert client.get('/v1/motion-analyses/input-schema').status_code==401
46
+ assert client.get('/v1/motion-analyses/capabilities',headers=AUTH).json()['joint_count']==22
47
+ monkeypatch.setattr(module,'configured_record',lambda:None)
48
+ assert client.post('/v1/motion-analyses',files=files,headers=AUTH).status_code==503
49
+
50
+
51
+ def test_verified_artifacts_source_ranges_and_integrity(tmp_path,video):
52
+ service=fake_service(settings(tmp_path));job,manifest=stored(service,video)
53
+ root='/v1/motion-analyses/'+job.name
54
+ with TestClient(create_app(service.settings,service)) as client:
55
+ wait_until(lambda:service.ready)
56
+ assert client.get(root+'/result').status_code==401
57
+ assert client.get(root+'/result',headers=AUTH).json()['job_id']==job.name
58
+ for key in ('motion','measurements','events','quality','projections','source'):
59
+ url=root+'/artifacts/'+key
60
+ assert client.get(url).status_code==401
61
+ asset=manifest.artifacts[key]
62
+ # Fixture artifacts have URLs for this actual job directory.
63
+ assert client.head(url,headers=AUTH).headers['content-type']==asset.media_type
64
+ assert client.get(url,headers=AUTH).content==(job/asset.filename).read_bytes()
65
+ part=client.get(root+'/artifacts/source',headers={**AUTH,'Range':'bytes=0-9'})
66
+ assert part.status_code==206 and part.content==video.read_bytes()[:10]
67
+ assert client.get(root+'/artifacts/sam-raw-private.npz',headers=AUTH).status_code==404
68
+ assert client.get(root+'/artifacts/mesh',headers=AUTH).status_code==409
69
+ (job/'motion.jsonl').write_text('tampered')
70
+ assert client.get(root+'/artifacts/motion',headers=AUTH).status_code==500
71
+ assert client.get('/v1/sam-batting/analyses/'+job.name+'/result',headers=AUTH).status_code==404
72
+
73
+
74
+ def test_revisions_preserve_parent_and_reuse_source_with_new_immutable_revision(tmp_path,video,monkeypatch):
75
+ import baseball_batting.motion_api as module
76
+ monkeypatch.setattr(module,'configured_record',lambda:{'configured':True})
77
+ service=fake_service(settings(tmp_path),delay=30);parent,manifest=stored(service,video)
78
+ original=(parent/'result.json').read_bytes()
79
+ with TestClient(create_app(service.settings,service)) as client:
80
+ wait_until(lambda:service.ready)
81
+ r=client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={
82
+ 'options':{'windows':[{'start_frame':0,'end_frame':7,'stride_start_frame':1,'landing_frame':5}]}})
83
+ assert r.status_code==202,r.text
84
+ data=r.json();child=service.job_directory(data['job_id'])
85
+ assert data['analysis_id']==manifest.analysis_id and data['analysis_revision']==2
86
+ assert (child/'input.mp4').read_bytes()==video.read_bytes()
87
+ options=json.loads((child/'request.json').read_text())
88
+ assert options['timing']['kind']=='unretimed' and options['windows'][0]['landing_frame']==5
89
+ assert (parent/'result.json').read_bytes()==original
90
+ client.delete(data['status_url'],headers=AUTH)
91
+ wait_until(lambda:service.store.get(child.name)['status']=='cancelled')
92
+ assert (parent/'source.mp4').exists()
93
+ assert client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,json={'options':{'model_path':'bad'}}).status_code==422
94
+ assert client.post('/v1/motion-analyses/'+parent.name+'/revisions',headers=AUTH,content=b'x'*(512*1024+1)).status_code==413
95
+ asset=client.post('/v1/motion-analyses',headers=AUTH,data={'source_asset_id':parent.name,'options':'{}'})
96
+ assert asset.status_code==202
97
+ assert asset.json()['analysis_id']!=manifest.analysis_id and asset.json()['analysis_revision']==1
98
+ client.delete(asset.json()['status_url'],headers=AUTH)
99
+
100
+
101
+ def test_revision_numbers_are_unique_under_concurrent_requests_and_worker_is_isolated(tmp_path):
102
+ store=JobStore(tmp_path);first=store.create_motion(30)
103
+ with ThreadPoolExecutor(max_workers=4) as pool:
104
+ children=list(pool.map(lambda _:store.create_motion(30,first['job_id']),range(8)))
105
+ assert sorted(c['analysis_revision'] for c in children)==list(range(2,10))
106
+ assert all(c['analysis_id']==first['analysis_id'] for c in children)
107
+ service=JobService(settings(tmp_path))
108
+ command=service.job_command(service.job_directory(first['job_id']))
109
+ assert 'baseball_batting.motion_worker' in command and '--retention-s' in command