github-actions[bot] commited on
Commit
314c3d8
·
1 Parent(s): 220c87b

Automated Deploy: 6c70dcd572a3bb7d7e75de475ebde74b578d467a

Browse files
baseball_batting/api.py CHANGED
@@ -58,7 +58,7 @@ class UploadGuard:
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,7 +78,7 @@ def create_app(settings=None, service=None):
78
  service.start()
79
  try: yield
80
  finally: service.stop()
81
- app = FastAPI(title="Baseball Swing Engine and Coach", version="1.14.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)
@@ -470,4 +470,6 @@ def create_app(settings=None, service=None):
470
  register(app,service,authenticated)
471
  from .motion_api import register as register_motion
472
  register_motion(app,service,authenticated)
 
 
473
  return app
 
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','/v1/contact-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.15.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)
 
470
  register(app,service,authenticated)
471
  from .motion_api import register as register_motion
472
  register_motion(app,service,authenticated)
473
+ from .contact_api import register as register_contact
474
+ register_contact(app,service,authenticated)
475
  return app
baseball_batting/api_jobs.py CHANGED
@@ -222,11 +222,12 @@ class JobService:
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):
 
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',
226
+ 'contact':'baseball_batting.contact_worker'}.get(kind,'baseball_batting.api_worker')
227
  command=[sys.executable, "-m", module, "--models", str(s.model_root),
228
  "--job", str(directory), "--max-frames", str(s.max_frames),
229
  "--max-pixels", str(s.max_pixels), "--max-duration", str(s.max_duration_s)]
230
+ if kind in ('motion_player','contact'):command+=['--retention-s',str(s.retention_s)]
231
  return command
232
 
233
  def start(self):
baseball_batting/contact_api.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authenticated video-only contact estimates sharing the existing GPU queue."""
2
+ from pathlib import Path
3
+ import shutil
4
+ from typing import Annotated
5
+ from fastapi import Depends,File,Form,HTTPException,Request,UploadFile
6
+ from fastapi.responses import JSONResponse
7
+ from pydantic import ValidationError
8
+ from .contact_contract import ContactInput,ContactResult
9
+ from .api_jobs import QueueFull
10
+ from .storage import atomic_json,read_json,sha256_file
11
+ from .media import open_verified_media,media_response
12
+
13
+ PREFIX='/v1/contact-analyses'
14
+
15
+
16
+ def register(app,service,authenticated):
17
+ settings=service.settings
18
+ def record(identifier):
19
+ try:directory=service.job_directory(identifier)
20
+ except ValueError:raise HTTPException(404,'Contact analysis not found') from None
21
+ row=service.store.get(identifier)
22
+ if row is None or row['kind']!='contact':raise HTTPException(404,'Contact analysis not found')
23
+ return directory,row
24
+
25
+ def completed(identifier):
26
+ directory,row=record(identifier)
27
+ if row['status']!='completed':raise HTTPException(409,'Contact analysis has not completed')
28
+ path=directory/'result.json'
29
+ if not path.is_file() or sha256_file(path)!=row['result_sha256']:
30
+ raise HTTPException(500,'Stored contact result failed its integrity check')
31
+ try:result=ContactResult.model_validate(read_json(path))
32
+ except (ValueError,ValidationError):raise HTTPException(500,'Stored contact result is invalid') from None
33
+ return directory,result
34
+
35
+ @app.get(PREFIX+'/capabilities',dependencies=[Depends(authenticated)])
36
+ def capabilities():
37
+ return {'schema_version':'1.0','ready':service.ready and service.tracking_ready,'device':'cuda',
38
+ 'required_fields':['video'],'minimum_fps_required':None,'variable_frame_rate':True,
39
+ 'capture_clock_required':False,'sam_required':False,'manual_events_required':False,
40
+ 'audio':'optional_embedded_audio_corroboration_only','accuracy_validated':False,
41
+ 'max_frames':settings.max_frames,'max_duration_s':settings.max_duration_s,
42
+ 'retention_hours':settings.retention_s/3600}
43
+
44
+ @app.get(PREFIX+'/input-schema',dependencies=[Depends(authenticated)])
45
+ def input_schema():return ContactInput.model_json_schema()
46
+
47
+ @app.get(PREFIX+'/output-schema',dependencies=[Depends(authenticated)])
48
+ def output_schema():return ContactResult.model_json_schema()
49
+
50
+ @app.post(PREFIX,status_code=202,dependencies=[Depends(authenticated)])
51
+ async def upload(video:Annotated[UploadFile,File(description='One swing video; any frame rate')],
52
+ options:Annotated[str,Form(description='Optional JSON; omit for video-only analysis')]='{}'):
53
+ identifier=None;directory=None
54
+ try:
55
+ if not service.ready or not service.tracking_ready:
56
+ raise HTTPException(503,{'code':'tracking_models_unavailable','message':'Bat and ball models must pass GPU preflight.'})
57
+ if len(options.encode())>512*1024:raise HTTPException(413,'Options exceed size limit')
58
+ try:parsed=ContactInput.model_validate_json(options)
59
+ except ValidationError as error:
60
+ raise HTTPException(422,[{k:e[k] for k in ('loc','type','msg')} for e in error.errors(include_input=False,include_url=False)]) from None
61
+ suffix=Path(video.filename or '').suffix.lower()
62
+ if suffix not in {'.mp4','.mov','.mkv','.avi','.webm'}:raise HTTPException(415,'Unsupported video extension')
63
+ if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes:raise HTTPException(507,'Insufficient storage')
64
+ try:identifier=service.store.create(settings.max_active_jobs,kind='contact')
65
+ except QueueFull:raise HTTPException(429,'GPU queue is full',headers={'Retry-After':'30'}) from None
66
+ directory=service.job_directory(identifier);directory.mkdir();size=0
67
+ with (directory/('input'+suffix)).open('wb') as out:
68
+ while block:=await video.read(1024*1024):
69
+ size+=len(block)
70
+ if size>settings.max_upload_bytes:raise HTTPException(413,'Video exceeds upload limit')
71
+ if shutil.disk_usage(settings.data_root).free<settings.minimum_free_bytes+len(block):raise HTTPException(507,'Insufficient storage')
72
+ out.write(block)
73
+ if not size:raise HTTPException(422,'Video is empty')
74
+ atomic_json(directory/'request.json',parsed.model_dump(mode='json'))
75
+ service.store.update(identifier,'queued');service.wakeup.set()
76
+ return {'job_id':identifier,'status':'queued','status_url':PREFIX+'/'+identifier,
77
+ 'result_url':PREFIX+'/'+identifier+'/result','retention_hours':settings.retention_s/3600}
78
+ except BaseException:
79
+ if identifier:service.store.forget(identifier);shutil.rmtree(directory,ignore_errors=True)
80
+ raise
81
+ finally:await video.close()
82
+
83
+ @app.get(PREFIX+'/{identifier}',dependencies=[Depends(authenticated)])
84
+ def status(identifier:str):
85
+ with service.mutation_lock:
86
+ directory,row=record(identifier);progress=None;failure=None
87
+ try:progress=read_json(directory/'progress.json')
88
+ except (OSError,ValueError):pass
89
+ if row['status']=='failed':
90
+ try:failure=read_json(directory/'error.json')
91
+ except (OSError,ValueError):pass
92
+ return JSONResponse({'job_id':identifier,'status':'processing' if row['status']=='running' else row['status'],
93
+ 'progress':progress,'error':row['error'],'failure':failure,
94
+ 'result_url':PREFIX+'/'+identifier+'/result' if row['status']=='completed' else None},headers={'Cache-Control':'no-store'})
95
+
96
+ @app.get(PREFIX+'/{identifier}/result',response_model=ContactResult,dependencies=[Depends(authenticated)])
97
+ def result(identifier:str):
98
+ with service.mutation_lock:_,payload=completed(identifier)
99
+ return JSONResponse(payload.model_dump(mode='json'),headers={'Cache-Control':'no-store'})
100
+
101
+ @app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
102
+ @app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
103
+ def artifact(identifier:str,name:str,request:Request):
104
+ with service.mutation_lock:
105
+ directory,payload=completed(identifier);asset=payload.artifacts.get(name)
106
+ if asset is None:raise HTTPException(404,'Unknown contact artifact')
107
+ if asset.status!='available':raise HTTPException(409,{'code':asset.reason_code})
108
+ path=(directory/asset.filename).resolve()
109
+ if not path.is_relative_to(directory.resolve()):raise HTTPException(500,'Invalid stored artifact path')
110
+ handle,size=open_verified_media(path,asset.sha256,asset.size_bytes)
111
+ return media_response(request,handle,size,asset.sha256,media_type=asset.media_type)
112
+
113
+ @app.delete(PREFIX+'/{identifier}',status_code=202,dependencies=[Depends(authenticated)])
114
+ def delete(identifier:str):
115
+ record(identifier)
116
+ return {'job_id':identifier,'status':service.delete(identifier)}
baseball_batting/contact_audio.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optional embedded audio transients: corroboration only, never impact proof."""
2
+ import numpy as np
3
+
4
+
5
+ def inspect(video, origin_s, duration_s, contact, enabled=True):
6
+ if not enabled:
7
+ return {'status':'not_requested','used_for_contact_timestamp':False}
8
+ import av
9
+ from scipy.signal import find_peaks
10
+ try:
11
+ with av.open(str(video),options={'protocol_whitelist':'file,pipe'}) as container:
12
+ if not container.streams.audio:
13
+ return {'status':'no_audio','used_for_contact_timestamp':False}
14
+ resampler=av.AudioResampler(format='fltp',layout='mono',rate=16000)
15
+ energy=[];times=[]
16
+ for frame in container.decode(container.streams.audio[0]):
17
+ for sample in resampler.resample(frame):
18
+ if sample.pts is None or sample.time_base is None:
19
+ continue
20
+ start=float(sample.pts*sample.time_base)-origin_s
21
+ if start>duration_s+.5:
22
+ break
23
+ data=sample.to_ndarray().reshape(-1)
24
+ for a in range(0,len(data)-80+1,80):
25
+ time=start+a/16000
26
+ if 0<=time<=duration_s:
27
+ energy.append(float(np.mean(data[a:a+80]**2)));times.append(time)
28
+ if frame.pts is not None and float(frame.pts*frame.time_base)-origin_s>duration_s+.5:
29
+ break
30
+ if len(energy)<10:
31
+ return {'status':'insufficient_audio','used_for_contact_timestamp':False}
32
+ q=np.log(np.asarray(energy)+1e-10)
33
+ novelty=np.maximum(0,q-np.r_[q[0],q[:-1]])
34
+ floor=float(np.median(novelty)+6*np.median(np.abs(novelty-np.median(novelty))))
35
+ peaks,_=find_peaks(novelty,height=max(.5,floor),distance=10)
36
+ peaks=sorted(peaks,key=lambda i:novelty[i],reverse=True)[:32]
37
+ candidates=sorted(float(times[i]) for i in peaks)
38
+ near=[]
39
+ if contact.video_time_interval_s:
40
+ a,b=contact.video_time_interval_s
41
+ near=[t for t in candidates if a-.03<=t<=b+.25]
42
+ return {'status':'analyzed','transient_video_times_s':candidates,'near_visual_contact_times_s':near,
43
+ 'used_for_contact_timestamp':False,'impact_sound_verified':False,
44
+ 'note':'Transient sounds may be unrelated or delayed; audio never creates or verifies contact.'}
45
+ except (av.FFmpegError,ValueError,OverflowError):
46
+ return {'status':'audio_unreadable','used_for_contact_timestamp':False}
baseball_batting/contact_contract.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone single-video contact estimates; no pose or capture-FPS requirement."""
2
+ from typing import Any, Literal
3
+ from pydantic import Field, model_validator
4
+ from .sam_batting_contract import Strict
5
+ from .api_contract import TimingInput
6
+ from .motion_contract import Artifact
7
+
8
+
9
+ class ContactInput(Strict):
10
+ # All fields are optional. Unknown capture time never blocks video time.
11
+ timing: TimingInput = Field(default_factory=TimingInput)
12
+ rotation_degrees: Literal[0, 90, 180, 270] | None = None
13
+ annotated_video: bool = True
14
+ use_audio: bool = True
15
+
16
+ def metadata(self):
17
+ result = {'timing': self.timing.model_dump(exclude_none=True), 'intended_use': 'research'}
18
+ if self.rotation_degrees is not None:
19
+ result['rotation_degrees'] = self.rotation_degrees
20
+ return result
21
+
22
+
23
+ class ContactEstimate(Strict):
24
+ status: Literal['estimated', 'unavailable']
25
+ source_frame_index: int | None = Field(default=None, ge=0)
26
+ frame_interval: tuple[int, int] | None = None
27
+ video_time_s: float | None = Field(default=None, ge=0)
28
+ video_time_interval_s: tuple[float, float] | None = None
29
+ capture_time_s: float | None = Field(default=None, ge=0)
30
+ capture_time_interval_s: tuple[float, float] | None = None
31
+ local_frame_spacing_ms: float | None = Field(default=None, gt=0)
32
+ method: str | None = None
33
+ reasons: list[str] = Field(default_factory=list)
34
+ confidence: None = None
35
+ verified: Literal[False] = False
36
+ accuracy_validated: Literal[False] = False
37
+ evidence: dict[str, Any] = Field(default_factory=dict)
38
+
39
+ @model_validator(mode='after')
40
+ def consistent(self):
41
+ fields = ('source_frame_index', 'frame_interval', 'video_time_s',
42
+ 'video_time_interval_s', 'local_frame_spacing_ms', 'method')
43
+ if self.status == 'estimated':
44
+ if any(getattr(self, key) is None for key in fields):
45
+ raise ValueError('An estimated contact requires source samples, a time interval and method')
46
+ for bounds, value in [(self.frame_interval, self.source_frame_index),
47
+ (self.video_time_interval_s, self.video_time_s),
48
+ (self.capture_time_interval_s, self.capture_time_s)]:
49
+ if bounds is not None and (bounds[1] < bounds[0] or value is None or not bounds[0] <= value <= bounds[1]):
50
+ raise ValueError('Contact estimate must lie in its interval')
51
+ if (self.capture_time_s is None) != (self.capture_time_interval_s is None):
52
+ raise ValueError('Capture time and interval must be available together')
53
+ elif any(getattr(self, key) is not None for key in (*fields, 'capture_time_s', 'capture_time_interval_s')) or not self.reasons:
54
+ raise ValueError('Unavailable contact has null locations and a reason')
55
+ return self
56
+
57
+
58
+ class ContactResult(Strict):
59
+ schema_version: Literal['1.0'] = '1.0'
60
+ job_id: str
61
+ status: Literal['completed'] = 'completed'
62
+ contact: ContactEstimate
63
+ source_video: dict[str, Any]
64
+ timing: dict[str, Any]
65
+ pipeline: dict[str, Any]
66
+ audio: dict[str, Any]
67
+ artifacts: dict[str, Artifact]
68
+ expires_at: str
69
+ accuracy_validated: Literal[False] = False
baseball_batting/contact_detection.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Observed bat sweep and ball deflection, at source timestamps of any cadence.
2
+
3
+ No pose, supplied swing onset, known capture clock, fixed FPS, or gap filling.
4
+ The result is a visual transition interval, never a verified impact or miss.
5
+ """
6
+ import numpy as np
7
+ from .bat_ball_timing import _line_track, shaft_distance
8
+ from .contact_contract import ContactEstimate
9
+
10
+ VERSION = 'single-video-contact-v1'
11
+
12
+
13
+ def _unknown(reason, counts):
14
+ return ContactEstimate(status='unavailable', reasons=[reason], evidence=counts)
15
+
16
+
17
+ def _branch(rows,times,index,side,length,stationary=False):
18
+ # At high FPS three frames may cover less than a ball radius. Extend observed
19
+ # support rather than declaring such footage unsupported or filling gaps.
20
+ for width in (3,5,7):
21
+ ids=list(range(index-width,index)) if side=='before' else list(range(index+1,index+width+1))
22
+ if ids[0]<0 or ids[-1]>=len(rows):continue
23
+ segment=rows[index].get('segment_id',0)
24
+ if any(r.get('segment_id',0)!=segment or r.get('camera_motion_status')=='unresolved' for r in rows[min(ids[0],index):max(ids[-1],index)+1]):continue
25
+ dt=np.diff(times[min(ids[0],index):max(ids[-1],index)+1])
26
+ if dt.max()>3*np.median(dt):continue
27
+ fit=_line_track([rows[k] for k in ids],times[ids],times[index],length,stationary=stationary)
28
+ if fit is not None:return fit,ids
29
+ return None,None
30
+
31
+
32
+ def estimate(observations, capture):
33
+ rows = observations['frames']
34
+ times = np.asarray([f['playback_s'] for f in capture['frames']], float)
35
+ if len(times) != len(rows) or len(times) < 7:
36
+ return _unknown('insufficient_contact_context', {})
37
+ times -= times[0]
38
+ if not np.isfinite(times).all() or np.any(np.diff(times) <= 0):
39
+ raise ValueError('invalid_source_timestamps')
40
+ counts = {'frames_with_observed_bat_endpoints': sum(any(b.get('points') is not None for b in r['bat']) for r in rows),
41
+ 'frames_with_observed_ball': sum(bool(r['ball']) for r in rows),
42
+ 'supported_ball_transitions': 0, 'camera_motion_policy': 'background_affine_stabilized_segments',
43
+ 'timing_interval_kind': 'observed_transition_frames; not a calibrated accuracy interval'}
44
+ candidates = []
45
+ for i in range(3, len(rows)-3):
46
+ context = rows[i-3:i+4]
47
+ if len({r.get('segment_id', 0) for r in context}) != 1:
48
+ continue
49
+ if any(r.get('camera_motion_status') == 'unresolved' for r in context):
50
+ continue
51
+ # Use local cadence: a true timestamp hole is not explained by a high/low FPS label.
52
+ dt = np.diff(times[i-3:i+4])
53
+ if dt.max() > 3*np.median(dt):
54
+ continue
55
+ bats = [[b for b in rows[k]['bat'] if b.get('points') is not None] for k in (i-1, i, i+1)]
56
+ if any(len(b) != 1 for b in bats):
57
+ continue
58
+ previous, ends, following = (np.asarray(b[0]['points'], float) for b in bats)
59
+ length = float(np.linalg.norm(ends[1]-ends[0]))
60
+ if not np.isfinite(length) or length < 12:
61
+ continue
62
+ after,after_ids = _branch(rows,times,i,'after',length)
63
+ if after is None:
64
+ continue
65
+ # Infer stationary tee versus moving incoming ball from observed motion, not a required form field.
66
+ for stationary in (False, True):
67
+ before,before_ids = _branch(rows,times,i,'before',length,stationary)
68
+ if before is None:
69
+ continue
70
+ ein, incoming, rin, incoming_xy = before
71
+ eout, outgoing, rout, outgoing_xy = after
72
+ if stationary and np.ptp(incoming_xy, axis=0).dot(np.ptp(incoming_xy, axis=0)) > max(2, rin)**2:
73
+ continue
74
+ v, u = incoming[0], outgoing[0]
75
+ change = np.linalg.norm(u-v)*(times[after_ids[-1]]-times[before_ids[0]])
76
+ cosine = np.dot(v, u)/max(np.linalg.norm(v)*np.linalg.norm(u), 1e-9)
77
+ if (not stationary and cosine > .8) or change < 4*max(rin, rout, ein, eout, 1):
78
+ continue
79
+ counts['supported_ball_transitions'] += 1
80
+ delta = u-v
81
+ offset = outgoing[1]-incoming[1]
82
+ relative = -np.dot(offset, delta)/max(np.dot(delta, delta), 1e-9)
83
+ t = float(times[i]+relative)
84
+ if not times[i-1] <= t <= times[i+1]:
85
+ continue
86
+ p, q = incoming[1]+v*relative, outgoing[1]+u*relative
87
+ if np.linalg.norm(p-q) > max(rin, rout)+ein+eout:
88
+ continue
89
+ # A motionless bat beside a ball bounce is insufficient evidence.
90
+ motion = following.mean(axis=0)-previous.mean(axis=0)
91
+ if np.linalg.norm(motion) <= max(2., .02*length) or np.dot(u-v, motion) <= 0:
92
+ continue
93
+ if float(shaft_distance((p+q)/2, ends)) > max(rin, rout)+ein+eout+max(2., .025*length):
94
+ continue
95
+ candidates.append({'index': i, 'time': t, 'interval': [i-1, i+1],
96
+ 'support': before_ids+[i]+after_ids, 'residual': float(ein+eout),
97
+ 'method': 'observed_stationary_ball_departure_and_bat' if stationary else 'observed_bat_and_ball_deflection',
98
+ 'incoming_ball_pixels': incoming_xy.tolist(), 'outgoing_ball_pixels': outgoing_xy.tolist()})
99
+ if not candidates:
100
+ reason = ('bat_endpoints_unobserved_or_ambiguous' if not counts['frames_with_observed_bat_endpoints'] else
101
+ 'ball_unobserved' if not counts['frames_with_observed_ball'] else
102
+ 'contact_evidence_insufficient')
103
+ return _unknown(reason, counts)
104
+ groups = []
105
+ for c in sorted(candidates, key=lambda x: x['interval'][0]):
106
+ if groups and c['interval'][0] <= max(x['interval'][1] for x in groups[-1]):
107
+ groups[-1].append(c)
108
+ else:
109
+ groups.append([c])
110
+ if len(groups) != 1:
111
+ return _unknown('multiple_contact_candidates', {**counts, 'candidate_group_count': len(groups)})
112
+ group = groups[0]
113
+ best = min(group, key=lambda c: c['residual'])
114
+ a, b = min(c['interval'][0] for c in group), max(c['interval'][1] for c in group)
115
+ idx = min(range(a, b+1), key=lambda k: abs(times[k]-best['time']))
116
+ physical = np.asarray([f['physical_s'] if f['physical_s'] is not None else np.nan for f in capture['frames']], float)
117
+ known = np.isfinite(physical).all() and (np.diff(physical) > 0).all()
118
+ physical -= physical[0]
119
+ capture_value = float(np.interp(best['time'], times, physical)) if known else None
120
+ return ContactEstimate(status='estimated', source_frame_index=idx, frame_interval=(a, b),
121
+ video_time_s=best['time'], video_time_interval_s=(float(times[a]), float(times[b])),
122
+ capture_time_s=capture_value,
123
+ capture_time_interval_s=(float(physical[a]), float(physical[b])) if known else None,
124
+ local_frame_spacing_ms=float(np.diff(times[a:b+1]).max()*1000), method=best['method'],
125
+ reasons=['single_view_visual_estimate', 'accuracy_unvalidated']+([] if known else ['capture_time_unknown']),
126
+ evidence={**counts, 'source_frame_indices': sorted({k for c in group for k in c['support']}),
127
+ 'candidate_count': len(group), 'fit_residual_px': best['residual'],
128
+ 'fit_coordinate_space': 'stabilized_image_pixels',
129
+ 'subframe_time_is_fitted_not_directly_observed': True})
baseball_batting/contact_videos.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Source-timed bat/ball overlays and a contact-evidence clip."""
2
+ from pathlib import Path
3
+ import cv2
4
+ import numpy as np
5
+ from .ingest import iter_frames
6
+ from .swing_clips import _Writer, _source_time, _ticks, TIME_BASE, ClipError
7
+
8
+
9
+ def draw(image, row, contact, index):
10
+ image=image.copy()
11
+ thickness=max(1,round(image.shape[1]/640))
12
+ for bat in row['bat']:
13
+ if bat.get('points') is not None:
14
+ a,b=np.rint(bat['points']).astype(int)
15
+ cv2.line(image,tuple(a),tuple(b),(90,225,130),thickness+1,cv2.LINE_AA)
16
+ for ball in row['ball']:
17
+ cv2.circle(image,tuple(np.rint(ball['point']).astype(int)),max(3,round(ball['radius_px'])),(20,220,255),thickness,cv2.LINE_AA)
18
+ active=contact.frame_interval is not None and contact.frame_interval[0]<=index<=contact.frame_interval[1]
19
+ text='CONTACT ESTIMATE' if active else 'Bat/ball observations' if contact.status=='estimated' else 'Contact not located'
20
+ cv2.putText(image,text,(12,32*thickness),cv2.FONT_HERSHEY_SIMPLEX,.7*thickness,
21
+ (30,220,255) if active else (230,230,230),thickness,cv2.LINE_AA)
22
+ return image
23
+
24
+
25
+ def export(video,capture,rows,contact,job,progress=lambda *a:None):
26
+ job=Path(job);frames=capture['frames'];n=len(frames)
27
+ source=[_source_time(f) for f in frames]
28
+ if any(b<=a for a,b in zip(source,source[1:])):
29
+ raise ClipError('source_timestamps_invalid')
30
+ origin=source[0];timeline=[_ticks(t-origin) for t in source]
31
+ a=b=None
32
+ if contact.video_time_interval_s:
33
+ lo,hi=contact.video_time_interval_s
34
+ times=[float(t-origin) for t in source]
35
+ a=max(0,int(np.searchsorted(times,max(0,lo-.35)))-1)
36
+ b=min(n-1,int(np.searchsorted(times,hi+.35)))
37
+ writers={};metadata={}
38
+ temporary={k:job/('.'+k+'.tmp.mp4') for k in ('annotated','evidence')}
39
+ try:
40
+ for i,pts,base,image,duration in iter_frames(video,capture['rotation_degrees'],include_duration=True):
41
+ if i>=n or pts*base!=source[i]:raise ClipError('source_video_mismatch')
42
+ ticks=timeline[i+1]-timeline[i] if i+1<n else (_ticks(duration*base) if duration and duration>0 else 0)
43
+ if ticks<=0:raise ClipError('last_frame_duration_unavailable')
44
+ image=draw(image,rows[i],contact,i)
45
+ keys=['annotated']+(['evidence'] if a is not None and a<=i<=b else [])
46
+ for key in keys:
47
+ if key not in writers:writers[key]=_Writer(temporary[key],image.shape)
48
+ writers[key].write(image,timeline[i]-(timeline[a] if key=='evidence' else 0),ticks)
49
+ if i%32==0 or i==n-1:progress('annotated_video',i+1,n)
50
+ for key,writer in writers.items():
51
+ writer.finish()
52
+ expected=n if key=='annotated' else b-a+1
53
+ if writer.count!=expected:raise ClipError('clip_frame_count_mismatch')
54
+ temporary[key].replace(job/(key+'.mp4'))
55
+ metadata[key]={'frame_count':writer.count,'duration_s':writer.end*float(TIME_BASE),
56
+ 'source_start_frame':a if key=='evidence' else 0,
57
+ 'source_end_frame':b if key=='evidence' else n-1,
58
+ 'source_video_start_s':float(source[a]-origin) if key=='evidence' else 0.,'has_audio':False}
59
+ return metadata
60
+ finally:
61
+ for key,writer in writers.items():
62
+ if temporary[key].exists():writer.abort();temporary[key].unlink(missing_ok=True)
baseball_batting/contact_vision.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Video-only object observations with automatic crop search and camera checks."""
2
+ import numpy as np
3
+ import cv2
4
+ from .tracking_vision import TrackingModel, frame_detections, deduplicate
5
+ from .detection import YOLOXDetector
6
+ from .ingest import iter_frames
7
+
8
+
9
+ def background_transform(previous, current, boxes):
10
+ scale = min(1., 640/max(current.shape))
11
+ size = (round(current.shape[1]*scale), round(current.shape[0]*scale))
12
+ a, b = cv2.resize(previous, size), cv2.resize(current, size)
13
+ mask = np.full(a.shape, 255, np.uint8)
14
+ for box in boxes:
15
+ if box is None:
16
+ continue
17
+ x1,y1,x2,y2 = np.rint(np.asarray(box)*scale).astype(int)
18
+ cv2.rectangle(mask, (max(0,x1-8),max(0,y1-8)), (min(size[0],x2+8),min(size[1],y2+8)), 0, -1)
19
+ points = cv2.goodFeaturesToTrack(a, 250, .02, 8, mask=mask)
20
+ if points is None or len(points) < 12:
21
+ return None
22
+ moved, status, _ = cv2.calcOpticalFlowPyrLK(a,b,points,None)
23
+ if moved is None:
24
+ return None
25
+ back, reverse, _ = cv2.calcOpticalFlowPyrLK(b,a,moved,None)
26
+ if back is None:
27
+ return None
28
+ good = (status[:,0]>0)&(reverse[:,0]>0)&(np.linalg.norm(back[:,0]-points[:,0],axis=-1)<1.5)
29
+ if good.sum() < 12:
30
+ return None
31
+ transform, inliers = cv2.estimateAffinePartial2D(points[good,0],moved[good,0],method=cv2.RANSAC,ransacReprojThreshold=2.)
32
+ if transform is None or inliers is None or inliers.sum() < 12 or inliers.mean() < .6:
33
+ return None
34
+ # Features must cover more than a tiny foreground patch.
35
+ selected = points[good,0][inliers[:,0]>0]
36
+ if np.prod(np.ptp(selected,axis=0))/np.prod(size) < .08:
37
+ return None
38
+ transform[:,2] /= scale
39
+ matrix = np.vstack([transform,[0,0,1]])
40
+ if not np.isfinite(matrix).all() or not .8 < np.linalg.det(matrix[:2,:2]) < 1.2:
41
+ return None
42
+ return matrix
43
+
44
+
45
+ def stabilized(row, matrix):
46
+ def point(p):
47
+ q = matrix @ np.r_[p, 1.]
48
+ return q[:2].tolist()
49
+ scale = float(np.sqrt(abs(np.linalg.det(matrix[:2,:2]))))
50
+ return {**row, 'bat':[{**b,'points':[point(p) for p in b['points']] if b.get('points') is not None else None} for b in row['bat']],
51
+ 'ball':[{**b,'point':point(b['point']),'radius_px':b['radius_px']*scale} for b in row['ball']]}
52
+
53
+
54
+ def collect(video, capture, models, progress=lambda *a:None, device='cuda'):
55
+ from .api_worker import model_files
56
+ paths,_ = model_files(models)
57
+ person = YOLOXDetector(paths['person_detector'], device, classes=[0])
58
+ bat, ball = TrackingModel(models,'bat',device), TrackingModel(models,'ball',device)
59
+ original, observations = [], []
60
+ previous = None; old_boxes = []; segment = 0; transform = np.eye(3)
61
+ for i,pts,base,image in iter_frames(video,capture['rotation_degrees']):
62
+ record = capture['frames'][i]
63
+ if pts != record['pts'] or str(base) != record['time_base']:
64
+ raise ValueError('Source timestamps changed during tracking')
65
+ people = person(image)
66
+ boxes = [p['box'] for p in sorted(people,key=lambda p:np.prod(np.asarray(p['box'][2:])-p['box'][:2]),reverse=True)[:2]]
67
+ row = frame_detections(image,bat,ball,boxes[0] if boxes else None)
68
+ # Additional person-scale crop improves small/blurred bat visibility without supplied ROI.
69
+ if boxes:
70
+ x1,y1,x2,y2 = boxes[0]; pad=.3*max(x2-x1,y2-y1)
71
+ a=np.maximum(0,np.array([x1-pad,y1-pad])).astype(int)
72
+ b=np.minimum(image.shape[1::-1],np.array([x2+pad,y2+pad])).astype(int)
73
+ if min(b-a)>16:
74
+ roi=image[a[1]:b[1],a[0]:b[0]]
75
+ row['bat']=deduplicate(row['bat']+bat(roi,a))
76
+ gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
77
+ matrix=background_transform(previous,gray,old_boxes+boxes) if previous is not None else np.eye(3)
78
+ if matrix is None:
79
+ segment+=1;transform=np.eye(3)
80
+ else:
81
+ transform=transform@np.linalg.inv(matrix)
82
+ row.update(source_frame_index=i,segment_id=segment,
83
+ video_time_s=float(record['playback_s']-capture['frames'][0]['playback_s']),
84
+ camera_motion_status='unresolved' if matrix is None else 'background_affine_estimated')
85
+ original.append(row)
86
+ observations.append(stabilized(row,transform))
87
+ previous=gray;old_boxes=boxes
88
+ progress('bat_ball_tracking',i+1,capture['frame_count'])
89
+ if len(original)!=capture['frame_count']:
90
+ raise ValueError('Tracking decode differs from source')
91
+ return {'frames':observations}, original, {'bat':bat.record,'ball':ball.record}
baseball_batting/contact_worker.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Isolated GPU contact job. Video is the only required client input."""
2
+ import argparse
3
+ from datetime import datetime,timezone
4
+ from pathlib import Path
5
+ import json
6
+ import os
7
+ import time
8
+ import numpy as np
9
+ from .contact_contract import ContactInput,ContactResult
10
+ from .contact_detection import estimate,VERSION
11
+ from .ingest import ingest
12
+ from .storage import atomic_json,read_json,sha256_file
13
+
14
+
15
+ def run(job,models,*,max_frames=7200,max_pixels=8294400,max_duration=120,retention_s=86400,device='cuda'):
16
+ from .contact_vision import collect
17
+ from .contact_audio import inspect
18
+ from .contact_videos import export
19
+ job=Path(job);options=ContactInput.model_validate(read_json(job/'request.json'));started=time.monotonic()
20
+ def progress(stage,done=0,total=None):
21
+ atomic_json(job/'progress.json',{'stage':stage,'completed_frames':done,'total_frames':total,
22
+ 'elapsed_s':round(time.monotonic()-started,2)})
23
+ video=next(job.glob('input.*'));progress('decoding')
24
+ capture=ingest(video,options.metadata(),max_frames=max_frames,max_pixels=max_pixels,max_duration_s=max_duration)
25
+ playback=np.asarray([f['playback_s'] for f in capture['frames']],float)
26
+ if not np.isfinite(playback).all() or len(playback)<2 or np.any(np.diff(playback)<=0):
27
+ raise ValueError('invalid_source_timestamps')
28
+ atomic_json(job/'capture-private.json',capture)
29
+ observed,original,model=collect(video,capture,models,progress,device)
30
+ progress('contact_estimation',len(original),len(original));contact=estimate(observed,capture)
31
+ # Public observations are original upright pixels, never the stabilized fit coordinate system.
32
+ with (job/'observations.jsonl').open('w') as out:
33
+ for frame,row in zip(capture['frames'],original):
34
+ out.write(json.dumps({**row,'source_pts':frame['pts'],'source_time_base':frame['time_base'],
35
+ 'confidence_meaning':'object detector scores; not contact correctness'},allow_nan=False)+'\n')
36
+ duration=float(playback[-1]-playback[0])
37
+ audio=inspect(video,float(playback[0]),duration,contact,options.use_audio)
38
+ clips=export(video,capture,original,contact,job,progress) if options.annotated_video else {}
39
+ source=job/('source'+video.suffix)
40
+ if source.exists():
41
+ if sha256_file(source)!=capture['input_sha256']:raise ValueError('Source differs from retained input')
42
+ else:os.link(video,source)
43
+ expiry=datetime.fromtimestamp(time.time()+retention_s,timezone.utc).isoformat()
44
+ prefix='/v1/contact-analyses/'+job.name+'/artifacts/'
45
+ def asset(name,path,fmt,media):
46
+ return {'status':'available','url':prefix+name,'filename':path.name,'format':fmt,
47
+ 'media_type':media,'size_bytes':path.stat().st_size,'sha256':sha256_file(path),'expires_at':expiry}
48
+ artifacts={'observations':asset('observations',job/'observations.jsonl','jsonl','application/x-ndjson'),
49
+ 'source':asset('source',source,'original_video',{'.mov':'video/quicktime','.webm':'video/webm',
50
+ '.mkv':'video/x-matroska','.avi':'video/x-msvideo'}.get(video.suffix,'video/mp4'))}
51
+ for key in ('annotated','evidence'):
52
+ artifacts[key]=asset(key,job/(key+'.mp4'),'mp4','video/mp4') if key in clips else {
53
+ 'status':'unavailable','format':'mp4','media_type':'video/mp4','expires_at':expiry,
54
+ 'reason_code':'not_requested' if not options.annotated_video else 'contact_not_located'}
55
+ result=ContactResult(job_id=job.name,contact=contact,audio=audio,expires_at=expiry,
56
+ source_video={'sha256':capture['input_sha256'],'frame_count':len(original),
57
+ 'display_width':capture['frames'][0]['width'],'display_height':capture['frames'][0]['height'],
58
+ 'rotation_degrees_applied':capture['rotation_degrees'],'last_frame_video_time_s':duration,
59
+ 'timeline_origin_pts':capture['frames'][0]['pts'],'timeline_origin_time_base':capture['frames'][0]['time_base']},
60
+ timing={'video_time':'source_PTS_minus_first_source_PTS','capture_time_available':capture['physical_clock_known'],
61
+ 'mapping':options.timing.model_dump(mode='json'),'minimum_fps_required':None,'frames_skipped':0,
62
+ 'minimum_frame_spacing_ms':float(np.diff(playback).min()*1000),
63
+ 'maximum_frame_spacing_ms':float(np.diff(playback).max()*1000),
64
+ 'notice':'Fitted subframe time is an estimate. Frame spacing and transition interval limit timing resolution.'},
65
+ pipeline={'version':VERSION,'device':device,'models':model,'options':options.model_dump(mode='json'),
66
+ 'implementation_sha256':{name:sha256_file(Path(__file__).with_name(name)) for name in
67
+ ('contact_detection.py','contact_vision.py','contact_audio.py','contact_videos.py','bat_ball_timing.py')},
68
+ 'requires_pose':False,'requires_3d':False,'requires_manual_events':False,
69
+ 'object_gap_filling':False,'contact_verification':'visual_estimate_only; independent_accuracy_validation_pending',
70
+ 'clips':clips},artifacts=artifacts)
71
+ atomic_json(job/'result.json',result.model_dump(mode='json'));progress('complete',len(original),len(original))
72
+ return result
73
+
74
+
75
+ def main():
76
+ parser=argparse.ArgumentParser()
77
+ for key in ('job','models'):parser.add_argument('--'+key,required=True)
78
+ parser.add_argument('--max-frames',type=int,default=7200)
79
+ parser.add_argument('--max-pixels',type=int,default=8294400)
80
+ parser.add_argument('--max-duration',type=float,default=120)
81
+ parser.add_argument('--retention-s',type=float,default=86400)
82
+ args=parser.parse_args()
83
+ try:
84
+ run(args.job,args.models,max_frames=args.max_frames,max_pixels=args.max_pixels,max_duration=args.max_duration,retention_s=args.retention_s)
85
+ return 0
86
+ except Exception as error:
87
+ atomic_json(Path(args.job)/'error.json',{'code':'invalid_video_or_capture' if isinstance(error,ValueError) else 'inference_failed',
88
+ 'reason_code':'invalid_source_timestamps' if str(error)=='invalid_source_timestamps' else 'contact_processing_failed',
89
+ 'error_type':type(error).__name__})
90
+ print(type(error).__name__+': '+str(error),flush=True)
91
+ return 1
92
+
93
+
94
+ if __name__=='__main__':raise SystemExit(main())
docs/CONTACT_API.md ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Single-video bat–ball contact API
2
+
3
+ The separate contact API accepts **one video as its only required input**. It
4
+ estimates a visible bat/ball interaction and exports the supporting observations
5
+ and annotated video. SAM, GVHMR, body pose, player height, camera calibration,
6
+ manual event frames, a Gemini key, and a fixed recording FPS are not required.
7
+
8
+ This is a visual estimate, **not validated contact verification**. Do not turn
9
+ `contact.status: estimated` into a verified impact or apply validated laboratory
10
+ contact benchmarks automatically. No observed contact does not establish a miss
11
+ or a dry swing. The existing motion, coaching, and load-timing APIs are unchanged;
12
+ this endpoint does not modify their results or send a coaching payload.
13
+
14
+ ## Requests and endpoints
15
+
16
+ Base URL: `https://modventures-baseball-engine.hf.space`
17
+
18
+ All `/v1/` routes need the existing server Bearer key. Keep that key on your app
19
+ backend. Upload the recording through your backend/proxy and enforce job ownership.
20
+
21
+ | Method and path | Purpose |
22
+ | --- | --- |
23
+ | `POST /v1/contact-analyses` | Multipart upload; returns 202 with job/status/result URLs. |
24
+ | `GET /v1/contact-analyses/{job_id}` | Poll queued/processing/completed/failed/cancelled status. |
25
+ | `GET /v1/contact-analyses/{job_id}/result` | Completed contact result; 409 before completion. |
26
+ | `GET` / `HEAD /v1/contact-analyses/{job_id}/artifacts/{name}` | Authenticated, checksummed artifact; video byte ranges supported. |
27
+ | `DELETE /v1/contact-analyses/{job_id}` | Cancel/delete retained job data. |
28
+ | `GET /v1/contact-analyses/capabilities` | GPU/model readiness, limits and retention. |
29
+ | `GET /v1/contact-analyses/input-schema` | Current optional-options JSON schema. |
30
+ | `GET /v1/contact-analyses/output-schema` | Current result JSON schema. |
31
+
32
+ In Postman, choose **Body → form-data** and add `video` as a **File**. Select the
33
+ video and send. Do not manually set multipart Content-Type; Postman supplies its
34
+ boundary. No `options` field is necessary. Swagger at `/docs` also supports upload.
35
+
36
+ Optional `options` is a **Text** field containing JSON:
37
+
38
+ ```json
39
+ {
40
+ "annotated_video": true,
41
+ "use_audio": true,
42
+ "timing": {"kind": "unknown"}
43
+ }
44
+ ```
45
+
46
+ Those are the defaults. `rotation_degrees` optionally overrides source orientation
47
+ with 0, 90, 180 or 270 clockwise. Unknown fields, including `fps`, are rejected.
48
+ Do not supply capture speed just to obtain non-null physical timing.
49
+
50
+ If original speed is documented, the existing timing structure is supported:
51
+
52
+ ```json
53
+ {"timing": {"kind": "unretimed", "source": "Original recording; no speed changes"}}
54
+ ```
55
+
56
+ Documented constant slowdown and explicit per-frame physical-time maps are also
57
+ supported. Video-only uploads remain usable with unknown physical time.
58
+
59
+ The queue shares the existing GPU service and cancellation/retention machinery.
60
+ The bat and ball models must pass CUDA preflight. Defaults are 512 MiB upload,
61
+ 120 seconds, 7,200 decoded frames and 24-hour retention; consult capabilities and
62
+ server settings. A high-frame-rate clip can reach the frame cap sooner; there is
63
+ no minimum-FPS rule and no resampling or intentionally skipped source frames.
64
+
65
+ ## Response and timing
66
+
67
+ The upload response contains `job_id`, `status_url`, `result_url`, and
68
+ `retention_hours`. Follow those URLs rather than constructing another API's path.
69
+
70
+ On completion, inspect `contact.status`:
71
+
72
+ - `estimated`: a single supported visual interaction interval was found.
73
+ - `unavailable`: insufficient/ambiguous evidence; all contact locations are null.
74
+
75
+ For an estimate, `contact` includes:
76
+
77
+ | Field | Meaning |
78
+ | --- | --- |
79
+ | `source_frame_index` | Nearest decoded source frame to the fitted estimate. Zero-based. |
80
+ | `frame_interval` | Inclusive source-frame interval supporting the transition. |
81
+ | `video_time_s` | Fitted estimate on the source playback timeline, elapsed from first video PTS. |
82
+ | `video_time_interval_s` | Source-frame bounds of the observed transition. Not a calibrated accuracy interval. |
83
+ | `capture_time_s`, `capture_time_interval_s` | Corresponding physical times only when a documented mapping was supplied; otherwise null. |
84
+ | `local_frame_spacing_ms` | Largest source sample spacing inside that transition. Not an accuracy guarantee. |
85
+ | `method` | Observed moving-ball deflection or stationary-ball departure with a bat sweep. |
86
+ | `confidence` | Null: no calibrated contact-confidence method exists. |
87
+ | `verified`, `accuracy_validated` | False. A fitted time is not independent verification. |
88
+ | `reasons` | Estimate limitations, or reasons contact could not be located. |
89
+ | `evidence` | Supporting source indices, observation counts, fit residual and coordinate-system description. |
90
+
91
+ At 25 FPS, frames are about 40 ms apart; at 30 FPS, about 33 ms. Such footage is
92
+ accepted. Contact can fall between frames or be blurred/hidden. Subframe fitting
93
+ does not create subframe observations or prove millisecond accuracy. A changed
94
+ playback FPS cannot reveal whether the original recording was retimed.
95
+
96
+ There is no user-supplied tee/live setting: the detector tests a moving incoming
97
+ ball and an observed stationary ball followed by departure. A ball simply
98
+ disappearing, a bat/ball projected overlap, or an arm-extension pose is insufficient.
99
+
100
+ ## Artifacts and evidence playback
101
+
102
+ Follow `result.artifacts[name].url` only when its status is `available`:
103
+
104
+ | Name | Content |
105
+ | --- | --- |
106
+ | `source` | Original uploaded video, unchanged bytes and original audio. |
107
+ | `observations` | JSONL of actual bat/ball detections in upright original-image pixels, source indices/PTS and camera continuity status. No filled object tracks. |
108
+ | `annotated` | Full silent H.264 video with bat lines, ball circles and an estimated-contact interval highlight. Available even if contact is unknown when requested. |
109
+ | `evidence` | Short annotated clip surrounding a located contact interval; unavailable when no contact is located. |
110
+
111
+ Every available artifact has length, SHA-256, format, media type and expiry.
112
+ Both videos preserve source presentation timing and every included frame; the
113
+ longest dimension is at most 1,280 pixels. Their pixels may be resized; observation
114
+ JSONL remains in original upright source pixels. Use `pipeline.clips` for clip
115
+ source start/end frames and `source_video_start_s`. Add that offset to evidence
116
+ clip playback time to locate the corresponding source video position.
117
+
118
+ The result also includes source orientation, frame count and hash; timestamp
119
+ spacing; actual model/checkpoint hashes and implementation hashes; and optional
120
+ embedded-audio diagnostics. Audio transients can corroborate a visual estimate.
121
+ They never establish contact, change its timestamp, or convert an unknown result
122
+ into a hit. Sounds may be unrelated, delayed, or offset by editing.
123
+
124
+ ## Detection and validation limits
125
+
126
+ Production inference uses the existing pinned BaseballCV bat-shaft keypoint and
127
+ baseball detector ONNX weights on CUDA. Automatic person boxes guide crop search;
128
+ no body-joint reconstruction is run. Background affine tracking stabilizes short
129
+ continuous observation segments. Unresolved camera motion or cuts split support;
130
+ fits cannot cross them. This does not establish a 3D world or independently solve
131
+ parallax and occlusion.
132
+
133
+ The geometry requires independently observed ball paths before and after the
134
+ interaction, compatible bat movement, and one unambiguous transition. High-FPS
135
+ support can use a longer observed path when adjacent ball displacement is tiny.
136
+ Frame gaps, missing observations and multiple candidates remain explicit.
137
+
138
+ Common unavailable reasons:
139
+
140
+ - `insufficient_contact_context`
141
+ - `bat_endpoints_unobserved_or_ambiguous`
142
+ - `ball_unobserved`
143
+ - `contact_evidence_insufficient`
144
+ - `multiple_contact_candidates`
145
+
146
+ A job completes successfully with unavailable contact when detection is uncertain.
147
+ Invalid media/timestamps or a worker/model failure instead fail the job. Model
148
+ availability is checked before upload allocation. Limits and readiness are not
149
+ claims that the pretrained models detect every phone recording reliably.
150
+
151
+ Tests cover clock mappings, varied/variable cadence, actual decoded artifact
152
+ timing, camera stabilization, ambiguity, missing evidence, optional audio,
153
+ queue completion, authentication, byte ranges, integrity and cancellation.
154
+ Constructed observations verify calculation behavior, not detector accuracy.
155
+ Record actual real-video test results separately; do not present synthetic success
156
+ as validation on real players.
docs/PITCHER_FLOOR_DIRECTION.md CHANGED
@@ -126,7 +126,9 @@ excerpt; actual vectors and diagnostics depend on the recording and selection:
126
  }
127
  ```
128
 
129
- The full `pitcher_estimation` also repeats its vector/source and includes:
 
 
130
 
131
  - `selection` and `source_frame`: original selection, actual source-frame index,
132
  dimensions, PTS/time base and video timestamp.
@@ -150,6 +152,8 @@ For `provided`, display **User-supplied pitcher direction**. The vector/source
150
  remain exact, `method` is `caller_supplied`, and `reliable` is null. For `unknown`,
151
  both effective vector and source are null, `applied/reliable` are false, and
152
  `reason_code` explains why. Do not turn the 2D arrow into a substitute vector.
 
 
153
 
154
  Original validated facts remain in `pipeline.inputs`; the derived vector/source
155
  are added only to `pipeline.calculation_inputs`. The same reference is included
 
126
  }
127
  ```
128
 
129
+ The full `pitcher_estimation` also repeats its vector/source. Additional
130
+ diagnostics are present when their validation stage was reached; they are
131
+ optional for unknown results:
132
 
133
  - `selection` and `source_frame`: original selection, actual source-frame index,
134
  dimensions, PTS/time base and video timestamp.
 
152
  remain exact, `method` is `caller_supplied`, and `reliable` is null. For `unknown`,
153
  both effective vector and source are null, `applied/reliable` are false, and
154
  `reason_code` explains why. Do not turn the 2D arrow into a substitute vector.
155
+ Older cached manifests may omit these new keys. Treat an absent reference as
156
+ unknown and offer a new analysis/revision; do not rewrite an immutable result.
157
 
158
  Original validated facts remain in `pipeline.inputs`; the derived vector/source
159
  are added only to `pipeline.calculation_inputs`. The same reference is included
docs/contact-input.schema.json ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "$defs": {
3
+ "TimingInput": {
4
+ "additionalProperties": false,
5
+ "properties": {
6
+ "kind": {
7
+ "default": "unknown",
8
+ "enum": [
9
+ "unknown",
10
+ "unretimed",
11
+ "constant_slowdown",
12
+ "explicit"
13
+ ],
14
+ "title": "Kind",
15
+ "type": "string"
16
+ },
17
+ "source": {
18
+ "anyOf": [
19
+ {
20
+ "maxLength": 512,
21
+ "minLength": 1,
22
+ "type": "string"
23
+ },
24
+ {
25
+ "type": "null"
26
+ }
27
+ ],
28
+ "default": null,
29
+ "title": "Source"
30
+ },
31
+ "factor": {
32
+ "anyOf": [
33
+ {
34
+ "exclusiveMinimum": 0,
35
+ "type": "number"
36
+ },
37
+ {
38
+ "type": "null"
39
+ }
40
+ ],
41
+ "default": null,
42
+ "title": "Factor"
43
+ },
44
+ "all_captured_frames_retained": {
45
+ "anyOf": [
46
+ {
47
+ "type": "boolean"
48
+ },
49
+ {
50
+ "type": "null"
51
+ }
52
+ ],
53
+ "default": null,
54
+ "title": "All Captured Frames Retained"
55
+ },
56
+ "physical_times_s": {
57
+ "anyOf": [
58
+ {
59
+ "items": {
60
+ "type": "number"
61
+ },
62
+ "maxItems": 20000,
63
+ "minItems": 1,
64
+ "type": "array"
65
+ },
66
+ {
67
+ "type": "null"
68
+ }
69
+ ],
70
+ "default": null,
71
+ "title": "Physical Times S"
72
+ }
73
+ },
74
+ "title": "TimingInput",
75
+ "type": "object"
76
+ }
77
+ },
78
+ "additionalProperties": false,
79
+ "properties": {
80
+ "timing": {
81
+ "$ref": "#/$defs/TimingInput"
82
+ },
83
+ "rotation_degrees": {
84
+ "anyOf": [
85
+ {
86
+ "enum": [
87
+ 0,
88
+ 90,
89
+ 180,
90
+ 270
91
+ ],
92
+ "type": "integer"
93
+ },
94
+ {
95
+ "type": "null"
96
+ }
97
+ ],
98
+ "default": null,
99
+ "title": "Rotation Degrees"
100
+ },
101
+ "annotated_video": {
102
+ "default": true,
103
+ "title": "Annotated Video",
104
+ "type": "boolean"
105
+ },
106
+ "use_audio": {
107
+ "default": true,
108
+ "title": "Use Audio",
109
+ "type": "boolean"
110
+ }
111
+ },
112
+ "title": "ContactInput",
113
+ "type": "object"
114
+ }
docs/contact-result.schema.json ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "ContactEstimate": {
99
+ "additionalProperties": false,
100
+ "properties": {
101
+ "status": {
102
+ "enum": [
103
+ "estimated",
104
+ "unavailable"
105
+ ],
106
+ "title": "Status",
107
+ "type": "string"
108
+ },
109
+ "source_frame_index": {
110
+ "anyOf": [
111
+ {
112
+ "minimum": 0,
113
+ "type": "integer"
114
+ },
115
+ {
116
+ "type": "null"
117
+ }
118
+ ],
119
+ "default": null,
120
+ "title": "Source Frame Index"
121
+ },
122
+ "frame_interval": {
123
+ "anyOf": [
124
+ {
125
+ "maxItems": 2,
126
+ "minItems": 2,
127
+ "prefixItems": [
128
+ {
129
+ "type": "integer"
130
+ },
131
+ {
132
+ "type": "integer"
133
+ }
134
+ ],
135
+ "type": "array"
136
+ },
137
+ {
138
+ "type": "null"
139
+ }
140
+ ],
141
+ "default": null,
142
+ "title": "Frame Interval"
143
+ },
144
+ "video_time_s": {
145
+ "anyOf": [
146
+ {
147
+ "minimum": 0,
148
+ "type": "number"
149
+ },
150
+ {
151
+ "type": "null"
152
+ }
153
+ ],
154
+ "default": null,
155
+ "title": "Video Time S"
156
+ },
157
+ "video_time_interval_s": {
158
+ "anyOf": [
159
+ {
160
+ "maxItems": 2,
161
+ "minItems": 2,
162
+ "prefixItems": [
163
+ {
164
+ "type": "number"
165
+ },
166
+ {
167
+ "type": "number"
168
+ }
169
+ ],
170
+ "type": "array"
171
+ },
172
+ {
173
+ "type": "null"
174
+ }
175
+ ],
176
+ "default": null,
177
+ "title": "Video Time Interval S"
178
+ },
179
+ "capture_time_s": {
180
+ "anyOf": [
181
+ {
182
+ "minimum": 0,
183
+ "type": "number"
184
+ },
185
+ {
186
+ "type": "null"
187
+ }
188
+ ],
189
+ "default": null,
190
+ "title": "Capture Time S"
191
+ },
192
+ "capture_time_interval_s": {
193
+ "anyOf": [
194
+ {
195
+ "maxItems": 2,
196
+ "minItems": 2,
197
+ "prefixItems": [
198
+ {
199
+ "type": "number"
200
+ },
201
+ {
202
+ "type": "number"
203
+ }
204
+ ],
205
+ "type": "array"
206
+ },
207
+ {
208
+ "type": "null"
209
+ }
210
+ ],
211
+ "default": null,
212
+ "title": "Capture Time Interval S"
213
+ },
214
+ "local_frame_spacing_ms": {
215
+ "anyOf": [
216
+ {
217
+ "exclusiveMinimum": 0,
218
+ "type": "number"
219
+ },
220
+ {
221
+ "type": "null"
222
+ }
223
+ ],
224
+ "default": null,
225
+ "title": "Local Frame Spacing Ms"
226
+ },
227
+ "method": {
228
+ "anyOf": [
229
+ {
230
+ "type": "string"
231
+ },
232
+ {
233
+ "type": "null"
234
+ }
235
+ ],
236
+ "default": null,
237
+ "title": "Method"
238
+ },
239
+ "reasons": {
240
+ "items": {
241
+ "type": "string"
242
+ },
243
+ "title": "Reasons",
244
+ "type": "array"
245
+ },
246
+ "confidence": {
247
+ "default": null,
248
+ "title": "Confidence",
249
+ "type": "null"
250
+ },
251
+ "verified": {
252
+ "const": false,
253
+ "default": false,
254
+ "title": "Verified",
255
+ "type": "boolean"
256
+ },
257
+ "accuracy_validated": {
258
+ "const": false,
259
+ "default": false,
260
+ "title": "Accuracy Validated",
261
+ "type": "boolean"
262
+ },
263
+ "evidence": {
264
+ "additionalProperties": true,
265
+ "title": "Evidence",
266
+ "type": "object"
267
+ }
268
+ },
269
+ "required": [
270
+ "status"
271
+ ],
272
+ "title": "ContactEstimate",
273
+ "type": "object"
274
+ }
275
+ },
276
+ "additionalProperties": false,
277
+ "properties": {
278
+ "schema_version": {
279
+ "const": "1.0",
280
+ "default": "1.0",
281
+ "title": "Schema Version",
282
+ "type": "string"
283
+ },
284
+ "job_id": {
285
+ "title": "Job Id",
286
+ "type": "string"
287
+ },
288
+ "status": {
289
+ "const": "completed",
290
+ "default": "completed",
291
+ "title": "Status",
292
+ "type": "string"
293
+ },
294
+ "contact": {
295
+ "$ref": "#/$defs/ContactEstimate"
296
+ },
297
+ "source_video": {
298
+ "additionalProperties": true,
299
+ "title": "Source Video",
300
+ "type": "object"
301
+ },
302
+ "timing": {
303
+ "additionalProperties": true,
304
+ "title": "Timing",
305
+ "type": "object"
306
+ },
307
+ "pipeline": {
308
+ "additionalProperties": true,
309
+ "title": "Pipeline",
310
+ "type": "object"
311
+ },
312
+ "audio": {
313
+ "additionalProperties": true,
314
+ "title": "Audio",
315
+ "type": "object"
316
+ },
317
+ "artifacts": {
318
+ "additionalProperties": {
319
+ "$ref": "#/$defs/Artifact"
320
+ },
321
+ "title": "Artifacts",
322
+ "type": "object"
323
+ },
324
+ "expires_at": {
325
+ "title": "Expires At",
326
+ "type": "string"
327
+ },
328
+ "accuracy_validated": {
329
+ "const": false,
330
+ "default": false,
331
+ "title": "Accuracy Validated",
332
+ "type": "boolean"
333
+ }
334
+ },
335
+ "required": [
336
+ "job_id",
337
+ "contact",
338
+ "source_video",
339
+ "timing",
340
+ "pipeline",
341
+ "audio",
342
+ "artifacts",
343
+ "expires_at"
344
+ ],
345
+ "title": "ContactResult",
346
+ "type": "object"
347
+ }
tests/test_contact_api.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sys
3
+ from pathlib import Path
4
+ import numpy as np
5
+ import pytest
6
+ from fastapi.testclient import TestClient
7
+ from baseball_batting.api import create_app
8
+ from baseball_batting.api_jobs import JobService
9
+ from baseball_batting.contact_worker import run
10
+ from baseball_batting.contact_contract import ContactInput,ContactResult
11
+ from baseball_batting.ingest import ingest,iter_frames
12
+ from baseball_batting.storage import atomic_json,sha256_file
13
+ from test_api import settings,fake_service,wait_until,AUTH
14
+ from test_contact_detection import observed
15
+
16
+ PREFIX='/v1/contact-analyses'
17
+
18
+
19
+ def inject_observations(monkeypatch, *, positive=True):
20
+ def collect(video,capture,models,progress,device):
21
+ times=[f['playback_s'] for f in capture['frames']]
22
+ obs,_=observed(times,index=4)
23
+ original=[]
24
+ for i,row in enumerate(obs['frames']):
25
+ if not positive:row['ball']=[]
26
+ original.append({**row,'source_frame_index':i,'video_time_s':times[i]-times[0]})
27
+ return obs,original,{'bat':{'test_fixture':True},'ball':{'test_fixture':True}}
28
+ monkeypatch.setattr('baseball_batting.contact_vision.collect',collect)
29
+
30
+
31
+ def stored(service,video,monkeypatch, *, positive=True):
32
+ inject_observations(monkeypatch,positive=positive)
33
+ identifier=service.store.create(20,kind='contact');job=service.job_directory(identifier);job.mkdir()
34
+ (job/'input.mp4').write_bytes(video.read_bytes());atomic_json(job/'request.json',{})
35
+ result=run(job,service.settings.model_root,device='cpu')
36
+ service.store.update(identifier,'completed',result_hash=sha256_file(job/'result.json'))
37
+ return job,result
38
+
39
+
40
+ def test_upload_only_video_accepts_defaults_and_dispatches_isolated_worker(video,tmp_path):
41
+ service=fake_service(settings(tmp_path),delay=30)
42
+ with TestClient(create_app(service.settings,service)) as client:
43
+ wait_until(lambda:service.ready);service.tracking_ready=True
44
+ files={'video':('swing.mp4',video.read_bytes(),'video/mp4')}
45
+ assert client.post(PREFIX,files=files).status_code==401
46
+ assert client.post(PREFIX,files=files,headers=AUTH,data={'options':'{"fps":30}'}).status_code==422
47
+ response=client.post(PREFIX,files=files,headers=AUTH)
48
+ assert response.status_code==202,response.text
49
+ data=response.json();job=service.job_directory(data['job_id'])
50
+ assert service.store.get(job.name)['kind']=='contact'
51
+ assert json.loads((job/'request.json').read_text())==ContactInput().model_dump(mode='json')
52
+ command=service.job_command(job)
53
+ assert 'baseball_batting.contact_worker' in command and '--retention-s' in command
54
+ assert client.get(data['result_url'],headers=AUTH).status_code==409
55
+ assert client.get(data['status_url'],headers=AUTH).status_code==200
56
+ assert client.get('/v1/motion-analyses/'+job.name,headers=AUTH).status_code==404
57
+ assert client.delete(data['status_url'],headers=AUTH).status_code==202
58
+ wait_until(lambda:client.get(data['status_url'],headers=AUTH).json()['status']=='cancelled')
59
+ service.tracking_ready=False
60
+ assert client.post(PREFIX,files=files,headers=AUTH).status_code==503
61
+ assert client.get(PREFIX+'/output-schema',headers=AUTH).status_code==200
62
+ assert client.get(PREFIX+'/capabilities',headers=AUTH).json()['minimum_fps_required'] is None
63
+
64
+
65
+ @pytest.mark.parametrize('positive',[False,True])
66
+ def test_real_decode_worker_result_and_source_timed_artifacts(video,tmp_path,monkeypatch,positive):
67
+ service=fake_service(settings(tmp_path));job,result=stored(service,video,monkeypatch,positive=positive)
68
+ result=ContactResult.model_validate_json((job/'result.json').read_text())
69
+ assert result.contact.status==('estimated' if positive else 'unavailable')
70
+ assert result.contact.capture_time_s is None and result.contact.verified is False
71
+ assert result.audio['status']=='no_audio'
72
+ capture=ingest(video,{})
73
+ actual=list(iter_frames(job/'annotated.mp4'))
74
+ expected=[f['playback_s']-capture['frames'][0]['playback_s'] for f in capture['frames']]
75
+ np.testing.assert_allclose([float(pts*base) for _,pts,base,_ in actual],expected,atol=2e-6)
76
+ assert result.source_video['frame_count']==len(actual)==8
77
+ assert (job/'source.mp4').read_bytes()==video.read_bytes()
78
+ assert result.artifacts['evidence'].status==('available' if positive else 'unavailable')
79
+ if positive:
80
+ meta=result.pipeline['clips']['evidence'];clip=list(iter_frames(job/'evidence.mp4'))
81
+ a,b=meta['source_start_frame'],meta['source_end_frame']
82
+ np.testing.assert_allclose([float(pts*base)+meta['source_video_start_s'] for _,pts,base,_ in clip],expected[a:b+1],atol=2e-6)
83
+ with TestClient(create_app(service.settings,service)) as client:
84
+ wait_until(lambda:service.ready)
85
+ root=PREFIX+'/'+job.name
86
+ assert client.get(root+'/result',headers=AUTH).json()['job_id']==job.name
87
+ for name in ['source','observations','annotated']:
88
+ url=root+'/artifacts/'+name
89
+ assert client.get(url).status_code==401
90
+ assert client.head(url,headers=AUTH).status_code==200
91
+ assert client.get(url,headers=AUTH).content==(job/result.artifacts[name].filename).read_bytes()
92
+ assert client.get(root+'/artifacts/source',headers={**AUTH,'Range':'bytes=0-9'}).status_code==206
93
+ assert client.get(root+'/artifacts/capture-private',headers=AUTH).status_code==404
94
+ (job/'observations.jsonl').write_text('tampered')
95
+ assert client.get(root+'/artifacts/observations',headers=AUTH).status_code==500
96
+
97
+
98
+ def test_end_to_end_queue_completes_with_contact_worker_output(video,tmp_path,monkeypatch):
99
+ # Real subprocess/queue/persistence; its object observations are explicitly constructed.
100
+ script=("import sys; from pathlib import Path; from unittest.mock import patch; "
101
+ "sys.path.insert(0,'tests'); from test_contact_api import inject_observations; "
102
+ "from baseball_batting.contact_worker import run; "
103
+ "from pytest import MonkeyPatch; inject_observations(MonkeyPatch()); "
104
+ "run(sys.argv[1],sys.argv[2],device='cpu')")
105
+ s=settings(tmp_path)
106
+ service=JobService(s,command_factory=lambda d:[sys.executable,'-c',script,str(d),str(s.model_root)],
107
+ preflight_command=[sys.executable,'-c','raise SystemExit(0)'])
108
+ with TestClient(create_app(s,service)) as client:
109
+ wait_until(lambda:service.ready);service.tracking_ready=True
110
+ response=client.post(PREFIX,headers=AUTH,files={'video':('swing.mp4',video.read_bytes(),'video/mp4')})
111
+ data=response.json();wait_until(lambda:service.store.get(data['job_id'])['status']=='completed',timeout=20)
112
+ result=client.get(data['result_url'],headers=AUTH)
113
+ assert result.status_code==200 and result.json()['contact']['status']=='estimated'
114
+ assert not (service.job_directory(data['job_id'])/'input.mp4').exists()
115
+ assert client.get(result.json()['artifacts']['source']['url'],headers=AUTH).status_code==200
116
+
117
+
118
+ def test_optional_audio_never_creates_contact_or_changes_video_time(tmp_path):
119
+ import av
120
+ from fractions import Fraction
121
+ from baseball_batting.contact_audio import inspect
122
+ from baseball_batting.contact_contract import ContactEstimate
123
+ path=tmp_path/'transients.wav'
124
+ with av.open(str(path),'w') as out:
125
+ stream=out.add_stream('pcm_s16le',rate=16000);stream.layout='mono'
126
+ data=np.zeros((1,16000),np.int16);data[0,3200:3240]=20000
127
+ frame=av.AudioFrame.from_ndarray(data,format='s16',layout='mono')
128
+ frame.sample_rate=16000;frame.pts=0;frame.time_base=Fraction(1,16000)
129
+ for packet in stream.encode(frame):out.mux(packet)
130
+ for packet in stream.encode():out.mux(packet)
131
+ unknown=ContactEstimate(status='unavailable',reasons=['no_ball'])
132
+ audio=inspect(path,0,1,unknown)
133
+ assert audio['status']=='analyzed' and audio['transient_video_times_s']
134
+ assert audio['used_for_contact_timestamp'] is False and unknown.status=='unavailable'
135
+ assert inspect(path,0,1,unknown,False)['status']=='not_requested'
tests/test_contact_detection.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Timing/geometry behavior, not a claim of neural-network accuracy."""
2
+ from copy import deepcopy
3
+ import numpy as np
4
+ import pytest
5
+ from baseball_batting.contact_detection import estimate
6
+ from baseball_batting.contact_contract import ContactInput,ContactEstimate
7
+ from baseball_batting.contact_vision import background_transform,stabilized
8
+
9
+
10
+ def observed(times, *, tee=False, index=None, physical=False):
11
+ times=np.asarray(times,float);index=len(times)//2 if index is None else index
12
+ rows=[]
13
+ for t in times-times[index]:
14
+ xy=[100+(0 if tee else 300*t),80] if t<=0 else [100-400*t,80-300*t]
15
+ rows.append({'bat':[{'points':[[100-800*t,20],[100-800*t,130]]}],
16
+ 'ball':[{'point':xy,'radius_px':2.}],'segment_id':0})
17
+ capture={'frames':[{'playback_s':float(t),'physical_s':float(t) if physical else None} for t in times]}
18
+ return {'frames':rows},capture
19
+
20
+
21
+ @pytest.mark.parametrize('fps',[12,15,23.976,25,29.97,30,60,120,240])
22
+ @pytest.mark.parametrize('tee',[False,True])
23
+ def test_video_only_has_no_fps_or_pose_or_capture_clock_gate(fps,tee):
24
+ obs,cap=observed(np.arange(81)/fps,tee=tee)
25
+ result=estimate(obs,cap)
26
+ assert result.status=='estimated'
27
+ assert result.video_time_interval_s[0]<=40/fps<=result.video_time_interval_s[1]
28
+ assert result.video_time_s==pytest.approx(40/fps)
29
+ assert result.capture_time_s is None and result.verified is False
30
+ assert result.local_frame_spacing_ms==pytest.approx(1000/fps)
31
+
32
+
33
+ def test_variable_cadence_nonzero_pts_origin_and_physical_slowdown():
34
+ times=5+np.r_[0,np.cumsum(np.tile([.018,.024,.031,.020],20))]
35
+ obs,cap=observed(times)
36
+ for row,time in zip(cap['frames'],times):row['physical_s']=10+(time-5)/4
37
+ result=estimate(obs,cap)
38
+ assert result.status=='estimated'
39
+ assert result.video_time_s==pytest.approx(times[40]-times[0])
40
+ assert result.capture_time_s==pytest.approx((times[40]-times[0])/4)
41
+ assert result.capture_time_interval_s[1]-result.capture_time_interval_s[0]==pytest.approx((result.video_time_interval_s[1]-result.video_time_interval_s[0])/4)
42
+
43
+
44
+ @pytest.mark.parametrize('failure',['no_bat','no_ball','no_deflection','stationary_bat','ball_gap','camera_cut','camera_unresolved','ambiguous_ball','ambiguous_bat'])
45
+ def test_uncertain_observations_never_create_contact_or_a_miss(failure):
46
+ obs,cap=observed(np.arange(81)/60)
47
+ for i,row in enumerate(obs['frames']):
48
+ if failure=='no_bat':row['bat']=[]
49
+ if failure=='no_ball':row['ball']=[]
50
+ if failure=='stationary_bat':row['bat']=[{'points':[[100,20],[100,130]]}]
51
+ if failure=='no_deflection':row['ball'][0]['point']=[100+(i-40)*5,80]
52
+ if failure=='ball_gap' and 36<=i<=44:row['ball']=[]
53
+ if failure=='camera_cut':row['segment_id']=int(i>=40)
54
+ if failure=='camera_unresolved':row['camera_motion_status']='unresolved'
55
+ if failure=='ambiguous_ball':row['ball'].append({'point':np.asarray(row['ball'][0]['point'])+.7,'radius_px':2.})
56
+ if failure=='ambiguous_bat':row['bat']*=2
57
+ result=estimate(obs,cap)
58
+ assert result.status=='unavailable' and result.video_time_s is None and result.reasons
59
+
60
+
61
+ def test_multiple_hits_are_not_silently_selected_for_single_swing_endpoint():
62
+ first,_=observed(np.arange(81)/60)
63
+ second=deepcopy(first)
64
+ cap={'frames':[{'playback_s':i/60,'physical_s':None} for i in range(162)]}
65
+ out=estimate({'frames':first['frames']+second['frames']},cap)
66
+ assert out.status=='unavailable' and out.reasons==['multiple_contact_candidates']
67
+
68
+
69
+ def test_actual_timestamp_hole_cannot_be_bridged_by_ball_fits():
70
+ obs,cap=observed(np.arange(81)/60)
71
+ for row in cap['frames'][40:]:row['playback_s']+=1
72
+ assert estimate(obs,cap).status=='unavailable'
73
+ cap['frames'][40]['playback_s']=cap['frames'][39]['playback_s']
74
+ with pytest.raises(ValueError,match='invalid_source_timestamps'):estimate(obs,cap)
75
+
76
+
77
+ def test_only_supported_optional_inputs_and_coherent_result_are_accepted():
78
+ assert ContactInput().timing.kind=='unknown'
79
+ for patch in [{'fps':30},{'model':'sam3d'},{'timing':{'kind':'unretimed'}},{'worker_python':'x'}]:
80
+ with pytest.raises(ValueError):ContactInput.model_validate(patch)
81
+ with pytest.raises(ValueError):ContactEstimate(status='estimated')
82
+ with pytest.raises(ValueError):ContactEstimate(status='unavailable',video_time_s=1,reasons=['x'])
83
+
84
+
85
+ def test_camera_translation_is_estimated_from_distributed_background():
86
+ import cv2
87
+ rng=np.random.default_rng(51)
88
+ image=rng.integers(0,256,(240,320),np.uint8)
89
+ moved=cv2.warpAffine(image,np.float32([[1,0,4],[0,1,3]]),(320,240))
90
+ matrix=background_transform(image,moved,[])
91
+ assert matrix is not None
92
+ np.testing.assert_allclose(matrix[:2,2],[4,3],atol=.2)
93
+ row={'bat':[{'points':[[50,50],[70,70]]}],'ball':[{'point':[20,20],'radius_px':2}]}
94
+ actual=stabilized(row,np.linalg.inv(matrix))
95
+ np.testing.assert_allclose(actual['ball'][0]['point'],[16,17],atol=.2)
96
+ assert row['ball'][0]['point']==[20,20]
97
+ assert background_transform(np.zeros_like(image),np.zeros_like(image),[]) is None