Spaces:
Running on T4
Running on T4
File size: 11,860 Bytes
d835db0 445f7bc 0a35b6f 4b1e064 d835db0 0a35b6f 220c87b 0a35b6f 6b95c6c 0a35b6f ebede04 0a35b6f 11fcb85 0a35b6f b3f7d8d 4bf9ad1 b3f7d8d 4bf9ad1 b3f7d8d d835db0 6b95c6c 6963661 b3f7d8d d835db0 445f7bc 0a35b6f 6b95c6c 220c87b 4b1e064 d835db0 0a35b6f 220c87b 6b95c6c 0a35b6f d835db0 0a35b6f d835db0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 | """Versioned motion-player contract. Existing SAM measurement responses stay unchanged."""
from typing import Any, Literal
from pydantic import Field, model_validator
from .sam_batting_contract import Strict, SamBattingInput
from .sam_motion import MHR
from .api_contract import CameraInput
from .motion_coach_contract import CoachAthlete, CoachContext
SCHEMA_VERSION = '1.0'
ADAPTER_VERSION = 'sam-mhr70-motion-v1'
DEFINITION_VERSION = 'batting-corrected-points-v1'
class MotionCamera(CameraInput):
# OpenCV Brown–Conrady order in the original upright image. No image warp.
distortion: tuple[float, float, float, float, float] | None = None
calibration_status: Literal['unknown', 'estimated', 'calibrated'] = 'unknown'
class PitcherFloorPoints(Strict):
source_frame_index: int = Field(ge=0, strict=True)
near_batter: tuple[float, float]
toward_pitcher: tuple[float, float]
selection_uncertainty_px: float = Field(default=2., gt=0, le=25)
up_sensitivity_deg: float = Field(default=1., gt=0, le=30)
class UpEstimationSettings(Strict):
enabled: bool = True
sample_count: int = Field(default=7, ge=3, le=15, strict=True)
minimum_frames: int = Field(default=3, ge=3, le=15, strict=True)
maximum_gravity_uncertainty_deg: float = Field(default=5., gt=0, le=15)
maximum_frame_deviation_deg: float = Field(default=3., gt=0, le=10)
minimum_consensus_fraction: float = Field(default=.8, ge=.6, le=1)
minimum_temporal_coverage: float = Field(default=.75, ge=.5, le=1)
minimum_background_fraction: float = Field(default=.2, ge=.1, le=.8)
minimum_effective_pixels: int = Field(default=32, ge=16, le=1000, strict=True)
minimum_spatial_cells: int = Field(default=3, ge=2, le=9, strict=True)
maximum_up_residual_deg: float = Field(default=10., gt=0, le=20)
maximum_latitude_residual_deg: float = Field(default=5., gt=0, le=15)
minimum_texture_fraction: float = Field(default=.005, gt=0, le=.1)
@model_validator(mode='after')
def enough_samples(self):
if self.minimum_frames > self.sample_count:
raise ValueError('Up estimation minimum_frames exceeds sample_count')
return self
class RefinementSettings(Strict):
enabled: bool = True
native_batch_frames: int = Field(default=8, ge=1, le=16, strict=True)
window_frames: int = Field(default=48, ge=12, le=120, strict=True)
context_frames: int = Field(default=8, ge=2, le=24, strict=True)
iterations: int = Field(default=25, ge=5, le=100, strict=True)
learning_rate: float = Field(default=.005, gt=0, le=.05)
minimum_observation_score: float = Field(default=.45, ge=.1, le=.95)
minimum_observed_joints: int = Field(default=6, ge=4, le=20, strict=True)
observation_scale_box_fraction: float = Field(default=.025, gt=0, le=.15)
maximum_observation_error_box_fraction: float = Field(default=.08, gt=0, le=.3)
maximum_body_change_fraction: float = Field(default=.12, gt=0, le=.3)
maximum_bone_change_fraction: float = Field(default=.06, gt=0, le=.2)
temporal_weight: float = Field(default=.02, ge=0, le=1)
initializer_weight: float = Field(default=.1, gt=0, le=10)
initializer_scale_body_fraction: float = Field(default=.03, ge=.005, le=.1)
maximum_peak_time_shift_s: float = Field(default=.025, gt=0, le=.1)
maximum_peak_speed_change_fraction: float = Field(default=.2, gt=0, le=.5)
maximum_static_background_motion_fraction: float = Field(default=.003, gt=0, le=.05)
sensitivity_factors: tuple[float, float] = (.5, 2.)
@model_validator(mode='after')
def bounded_windows(self):
if self.window_frames <= 2*self.context_frames:
raise ValueError('Refinement requires a nonempty core between context margins')
if not all(0 < f <= 4 for f in self.sensitivity_factors):
raise ValueError('Sensitivity factors must be positive and at most four')
return self
class MotionTrackingSettings(Strict):
recover_short_losses: bool = True
maximum_recovery_gap_s: float = Field(default=.2, gt=0, le=.5)
minimum_appearance_similarity: float = Field(default=.85, ge=.7, le=.99)
minimum_candidate_margin: float = Field(default=.1, ge=.05, le=.5)
class GVHMRSettings(Strict):
batch_size: int = Field(default=4, ge=1, le=16, strict=True)
max_sequence_frames: int = Field(default=300, ge=90, le=900, strict=True)
context_frames: int = Field(default=60, ge=10, le=60, strict=True)
minimum_keypoint_score: float = Field(default=.3, ge=0, le=1)
maximum_reprojection_box_fraction: float = Field(default=.15, gt=0, le=1)
@model_validator(mode='after')
def context_fits_sequence(self):
if self.max_sequence_frames<=2*self.context_frames:
raise ValueError('GVHMR sequence must contain a nonempty core in addition to both context margins')
return self
class MotionInput(SamBattingInput):
requires_vertical_for_pitcher = False
discipline: Literal['hitting'] = 'hitting'
model: Literal['sam3d', 'gvhmr'] = 'sam3d'
gvhmr: GVHMRSettings = Field(default_factory=GVHMRSettings)
coaching: Literal[False] = False
annotated_videos: bool = True
source_mirrored: bool | None = None
handedness_source: str | None = Field(default=None, min_length=1, max_length=300)
lead_foot_source: str | None = Field(default=None, min_length=1, max_length=300)
scale_status: Literal['model_estimated', 'calibrated', 'unknown'] = 'model_estimated'
minimum_usable_joints: int = Field(default=3, ge=3, le=len(MHR), strict=True)
camera: MotionCamera | None = None
refinement: RefinementSettings = Field(default_factory=RefinementSettings)
tracking: MotionTrackingSettings = Field(default_factory=MotionTrackingSettings)
up_estimation: UpEstimationSettings = Field(default_factory=UpEstimationSettings)
pitcher_floor_points: PitcherFloorPoints | None = None
athlete: CoachAthlete | None = None
context: CoachContext = Field(default_factory=CoachContext)
contact_frame: int | None = Field(default=None, ge=0, strict=True)
swing_id: str | None = Field(default=None, min_length=1, max_length=180, pattern=r'\S')
@model_validator(mode='after')
def coach_inputs(self):
if self.athlete is not None:
for outer, inner in (('handedness', 'batting_hand'), ('lead_foot', 'lead_foot')):
old, new = getattr(self, outer), getattr(self.athlete, inner)
if old is not None and new is not None and old != new:
raise ValueError(f'athlete.{inner} conflicts with {outer}')
if old is None and new is not None:
# Assignment validation would recursively invoke this validator.
object.__setattr__(self, outer, new)
if (self.athlete is not None or self.contact_frame is not None) and not self.single_swing:
raise ValueError('Player coaching inputs require single_swing=true')
if self.contact_frame is not None:
if self.context.practice_type == 'dry_swing':
raise ValueError('A dry swing cannot have bat-ball contact')
if self.windows:
window = self.windows[0]
if not window.start_frame <= self.contact_frame <= window.end_frame:
raise ValueError('Contact frame must lie inside the swing window')
if window.landing_frame is not None and self.contact_frame < window.landing_frame:
raise ValueError('Contact frame must not precede landing_frame')
return self
def validate_frame_count(self, count):
if any(w.end_frame >= count for w in self.windows):
raise ValueError('reviewed_frame_out_of_range')
if self.contact_frame is not None and self.contact_frame >= count:
raise ValueError('contact_frame_out_of_range')
@model_validator(mode='after')
def scale_evidence(self):
if self.scale_status == 'calibrated' and not (self.scale_source and self.scale_source.strip()):
raise ValueError('Calibrated scale requires a calibration source')
return self
def sam_options(self):
data={k:v for k,v in self.model_dump().items() if k in SamBattingInput.model_fields}
if data.get('camera'):
for key in ('distortion','calibration_status'):data['camera'].pop(key,None)
# These axes are measurement inputs, unused by native reconstruction.
# Keep the original direction in MotionInput until camera-up is resolved.
if data['up_vector'] is None:data.update(pitcher_vector=None,pitcher_source=None)
return SamBattingInput.model_validate(data)
class RevisionRequest(Strict):
# A patch is merged with the parent's recording facts, then validated as MotionInput.
options: dict[str, Any] = Field(default_factory=dict)
class Joint(Strict):
position: tuple[float, float, float] | None
status: Literal['estimated', 'interpolated', 'rejected', 'missing']
confidence: float | None = Field(default=None, ge=0, le=1)
reasons: list[str] = Field(default_factory=list)
@model_validator(mode='after')
def usable(self):
if (self.position is None) != (self.status in ('missing', 'rejected')):
raise ValueError('Usable joints require a position; unusable joints must have null positions')
return self
class MotionFrame(Strict):
analysis_revision: int = Field(ge=1)
source_frame_index: int = Field(ge=0)
source_pts: int
source_time_base: str
video_time_s: float = Field(ge=0)
capture_time_s: float | None = Field(default=None, ge=0)
segment_id: str
joints: dict[str, Joint]
root_translation: tuple[float, float, float] | None
frame_quality: dict[str, Any]
class Artifact(Strict):
status: Literal['available', 'unavailable']
url: str | None = None
filename: str | None = None
format: str
media_type: str
size_bytes: int | None = Field(default=None, ge=1)
sha256: str | None = Field(default=None, pattern=r'^[a-f0-9]{64}$')
expires_at: str
reason_code: str | None = None
@model_validator(mode='after')
def availability(self):
if self.status == 'available' and any(getattr(self, k) is None for k in ('url','filename','size_bytes','sha256')):
raise ValueError('Available artifacts require location, length and checksum')
if self.status == 'unavailable' and not self.reason_code:
raise ValueError('Unavailable artifacts require a reason')
return self
class MotionManifest(Strict):
schema_version: Literal['1.0'] = SCHEMA_VERSION
analysis_id: str
job_id: str
analysis_revision: int = Field(ge=1)
parent_job_id: str | None = None
person_id: str
source_video: dict[str, Any]
pipeline: dict[str, Any]
coordinates: dict[str, Any]
timing: dict[str, Any]
skeleton: dict[str, Any]
sampling: dict[str, Any]
quality: dict[str, Any]
artifacts: dict[str, Artifact]
expires_at: str
accuracy_validated: Literal[False] = False
class MetricSample(Strict):
source_frame_index: int = Field(ge=0)
video_time_s: float = Field(ge=0)
capture_time_s: float | None
value: float | None
status: Literal['estimated', 'partial', 'unavailable']
reasons: list[str]
uses_interpolated_input: bool
class ProjectionFrame(Strict):
analysis_revision: int = Field(ge=1)
source_frame_index: int = Field(ge=0)
video_time_s: float = Field(ge=0)
capture_time_s: float | None
segment_id: str
image_width: int = Field(ge=1)
image_height: int = Field(ge=1)
camera_intrinsics: list[list[float]] | None
camera_distortion: tuple[float,float,float,float,float] | None = None
joints: dict[str, dict[str, Any]]
|