"""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]]