"""Versioned coach measurements for one recorded swing; old stored payloads remain readable.""" from typing import Literal from pydantic import Field, model_validator from .sam_batting_contract import Strict from .coach_geometry import EXTENDED_METRICS COACH_SCHEMA_VERSION = '1.1' class CoachAthlete(Strict): athlete_id: str = Field(min_length=1, max_length=180, pattern=r'\S') batting_hand: Literal['left', 'right'] | None = None lead_foot: Literal['left', 'right'] | None = None age_years: int | None = Field(default=None, ge=0, strict=True) height_cm: float | None = Field(default=None, gt=0, strict=True) class CoachContext(Strict): sport: Literal['baseball'] = 'baseball' practice_type: Literal['tee', 'front_toss', 'side_toss', 'pitching_machine', 'live_pitching', 'game', 'dry_swing', 'unknown'] = 'unknown' Reason = Literal['contact_not_verified', 'contact_not_applicable', 'event_not_detected', 'event_timing_uncertain', 'required_event_unavailable', 'required_event_limited', 'lead_foot_unknown', 'required_landmarks_unusable', 'ground_plane_unknown', 'scale_is_model_estimated', 'scale_unknown', 'excessive_interpolation', 'occlusion_unresolved', 'temporal_inconsistency', 'capture_time_unknown', 'follow_through_not_recorded', 'model_accuracy_unvalidated'] class CoachEvent(Strict): video_time_s: float | None = Field(ge=0) capture_time_s: float | None = Field(ge=0) status: Literal['available', 'limited', 'unavailable'] source: Literal['manual_review', 'pose_estimated', 'bat_ball_detector', 'derived_from_contact'] | None reasons: list[Reason] source_frame_index: int | None = Field(default=None, ge=0, strict=True) @model_validator(mode='after') def consistent(self): if self.status == 'unavailable': if any(v is not None for v in (self.video_time_s, self.capture_time_s, self.source, self.source_frame_index)): raise ValueError('Unavailable events must have null times and source') elif self.video_time_s is None or self.source is None: raise ValueError('Usable events need video time and source') if (self.status == 'available') != (not self.reasons): raise ValueError('Only available events have an empty reasons list') return self class CoachEvents(Strict): stride_start: CoachEvent front_foot_down: CoachEvent contact: CoachEvent follow_through: CoachEvent | None = None class ValueInterval(Strict): lower: float upper: float source: Literal['adjacent_event_frames'] = 'adjacent_event_frames' @model_validator(mode='after') def ordered(self): if self.lower > self.upper: raise ValueError('Measurement interval must be ordered') return self class CoachMeasurement(Strict): value: float | None status: Literal['available', 'limited', 'unavailable'] confidence: float | None = Field(ge=0, le=1) uses_interpolated_input: bool reasons: list[Reason] benchmark: None = None value_interval: ValueInterval | None = None @model_validator(mode='after') def consistent(self): if (self.status == 'unavailable') != (self.value is None): raise ValueError('Only unavailable measurements have a null value') if self.status == 'unavailable' and self.confidence is not None: raise ValueError('Unavailable measurements have null confidence') if (self.status == 'available') != (not self.reasons): raise ValueError('Only available measurements have an empty reasons list') if self.value_interval is not None and (self.value is None or not self.value_interval.lower <= self.value <= self.value_interval.upper): raise ValueError('The event sensitivity interval must include the measurement value') return self class SeparationAtFootDown(CoachMeasurement): metric_id: Literal['hip_shoulder_separation_at_foot_down'] = 'hip_shoulder_separation_at_foot_down' group: Literal['stride'] = 'stride' unit: Literal['deg'] = 'deg' reference: Literal['signed_horizontal_shoulder_minus_hip_heading'] = 'signed_horizontal_shoulder_minus_hip_heading' event_id: Literal['front_foot_down'] = 'front_foot_down' value: float | None = Field(ge=-180, lt=180) class RelativeStride(CoachMeasurement): metric_id: Literal['stride_relative_length'] = 'stride_relative_length' group: Literal['stride'] = 'stride' unit: Literal['cm'] = 'cm' reference: Literal['lead_ankle_displacement_relative_to_rear_ankle'] = 'lead_ankle_displacement_relative_to_rear_ankle' start_event_id: Literal['stride_start'] = 'stride_start' end_event_id: Literal['front_foot_down'] = 'front_foot_down' value: float | None = Field(ge=0) class SeparationAtContact(CoachMeasurement): metric_id: Literal['hip_shoulder_separation_at_contact'] = 'hip_shoulder_separation_at_contact' group: Literal['contact_follow_through'] = 'contact_follow_through' unit: Literal['deg'] = 'deg' reference: Literal['signed_horizontal_shoulder_minus_hip_heading'] = 'signed_horizontal_shoulder_minus_hip_heading' event_id: Literal['contact'] = 'contact' value: float | None = Field(ge=-180, lt=180) class ExtendedMeasurement(CoachMeasurement): metric_id: Literal['torso_inclination_at_stride_start', 'hip_shoulder_separation_at_stride_start', 'pelvis_rotation_to_contact', 'lead_knee_extension_to_contact', 'torso_inclination_at_contact', 'shoulder_rotation_after_contact'] group: Literal['balance_load', 'power_move', 'contact_follow_through'] unit: Literal['deg'] = 'deg' reference: Literal['torso_angle_from_vertical', 'signed_horizontal_shoulder_minus_hip_heading', 'absolute_net_horizontal_rotation', 'change_in_3d_lead_knee_angle'] event_id: Literal['stride_start', 'contact'] | None = None start_event_id: Literal['front_foot_down', 'contact'] | None = None end_event_id: Literal['contact', 'follow_through'] | None = None def model_dump(self, **kwargs): data = super().model_dump(**kwargs) return {k: v for k, v in data.items() if k not in ('event_id', 'start_event_id', 'end_event_id') or v is not None} class MotionCoachPayload(Strict): schema_version: Literal['1.0', '1.1'] = COACH_SCHEMA_VERSION measurement_definitions_version: Literal['1.0', '1.1'] = COACH_SCHEMA_VERSION analysis_id: str = Field(min_length=1) analysis_revision: int = Field(ge=1) swing_id: str = Field(min_length=1) status: Literal['completed'] = 'completed' athlete: CoachAthlete context: CoachContext events: CoachEvents measurements: list[SeparationAtFootDown | RelativeStride | SeparationAtContact | ExtendedMeasurement] = Field(min_length=3, max_length=9) @model_validator(mode='after') def metric_set(self): expected = {'hip_shoulder_separation_at_foot_down', 'stride_relative_length', 'hip_shoulder_separation_at_contact'} if self.schema_version == '1.1': expected.update(EXTENDED_METRICS) if self.measurement_definitions_version != self.schema_version: raise ValueError('Schema and measurement definitions versions must match') if {m.metric_id for m in self.measurements} != expected or len(self.measurements) != len(expected): raise ValueError('Each registered metric must appear exactly once') return self def model_dump(self, **kwargs): data = super().model_dump(**kwargs) for row in data['measurements']: for key in ('event_id', 'start_event_id', 'end_event_id'): if row.get(key, 'absent') is None: row.pop(key) return data