File size: 8,812 Bytes
3192171
326d3cc
6c0b843
326d3cc
 
 
 
 
 
 
 
 
 
6c0b843
 
 
 
 
 
 
326d3cc
 
6c0b843
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3192171
 
 
 
 
 
 
 
 
 
e21e264
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
3192171
35e80ff
3192171
 
 
 
 
326d3cc
 
 
e21e264
 
 
 
 
326d3cc
 
 
3192171
e21e264
 
 
 
 
 
3192171
 
 
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3192171
 
326d3cc
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
"""Public recording inputs. Model paths and worker executables stay server-side."""
from typing import Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator


class TimingInput(BaseModel):
    model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
    kind: Literal["unknown", "unretimed", "constant_slowdown", "explicit"] = "unknown"
    source: str | None = Field(default=None, min_length=1, max_length=512)
    factor: float | None = Field(default=None, gt=0)
    all_captured_frames_retained: bool | None = None
    physical_times_s: list[float] | None = Field(default=None, min_length=1, max_length=20000)

    @field_validator("factor", "physical_times_s", mode="before")
    @classmethod
    def numeric_not_boolean(cls, value):
        if isinstance(value, bool) or (isinstance(value, list) and any(isinstance(v, bool) for v in value)):
            raise ValueError("Capture timing must use numeric values, not booleans")
        return value

    @model_validator(mode="after")
    def check_evidence(self):
        if self.factor is not None and self.kind != "constant_slowdown":
            raise ValueError("Slowdown factor contradicts the selected timing kind")
        if self.physical_times_s is not None and self.kind != "explicit":
            raise ValueError("A capture-time map requires explicit timing")
        if self.kind != "unknown" and not (self.source and self.source.strip()):
            raise ValueError("Known capture timing requires a source description")
        if self.kind == "constant_slowdown":
            if self.factor is None or self.all_captured_frames_retained is not True:
                raise ValueError("Slow motion requires its factor and all captured frames retained")
        if self.kind == "explicit":
            if not self.physical_times_s or any(b <= a for a, b in
                    zip(self.physical_times_s, self.physical_times_s[1:])):
                raise ValueError("Explicit capture times must increase strictly")
        return self


class RepRange(BaseModel):
    model_config = ConfigDict(extra="forbid")
    start_frame: int = Field(ge=0, strict=True)
    end_frame: int = Field(ge=0, strict=True)

    @model_validator(mode="after")
    def ordered(self):
        if self.end_frame < self.start_frame:
            raise ValueError("end_frame precedes start_frame")
        return self


class CameraInput(BaseModel):
    """Intrinsics refer to the upright decoded image, after rotation."""
    model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
    fx: float = Field(gt=0)
    fy: float = Field(gt=0)
    cx: float = Field(ge=0)
    cy: float = Field(ge=0)
    source: str = Field(min_length=1, max_length=512)


class TrackingCamera(BaseModel):
    """Calibration in upright image pixels, world translation in metres."""
    model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
    intrinsics: list[list[float]]
    rotation: list[list[float]]
    translation_m: tuple[float, float, float]
    distortion: list[float] = Field(default_factory=lambda: [0., 0., 0., 0., 0.])

    @model_validator(mode="after")
    def valid_geometry(self):
        from .geometry import intrinsics, rotation
        intrinsics(self.intrinsics)
        rotation(self.rotation)
        if len(self.distortion) not in (4, 5, 8):
            raise ValueError('Lens distortion must have 4, 5 or 8 coefficients')
        return self


class StereoTrackingInput(BaseModel):
    model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
    cameras: list[TrackingCamera] = Field(min_length=2, max_length=2)
    source: str = Field(min_length=1, max_length=512)
    synchronization_source: str = Field(min_length=1, max_length=512)
    secondary_offset_s: float
    synchronization_bound_ms: float = Field(ge=0, le=10)
    position_bound_m: float = Field(gt=0, le=.2)
    position_bound_source: str = Field(min_length=1, max_length=512)
    bat_length_m: float = Field(gt=.2, lt=1.5)
    barrel_radius_m: float = Field(gt=.005, lt=.1)
    barrel_start_fraction: float = Field(default=.5, ge=0, lt=1)
    ball_radius_m: float = Field(default=.0366, gt=.005, lt=.1)
    secondary_timing: TimingInput
    secondary_rotation_degrees: Literal[0, 90, 180, 270] | None = None
    max_shift_ms: float = Field(default=250, gt=0, le=1000)

    @model_validator(mode="after")
    def documented(self):
        if any(not s.strip() for s in (self.source, self.synchronization_source, self.position_bound_source)):
            raise ValueError('Calibration, synchronization and position bounds need documented sources')
        if self.secondary_timing.kind == 'unknown':
            raise ValueError('Secondary capture time must be documented')
        import numpy as np
        centres = [-np.asarray(c.rotation).T@np.asarray(c.translation_m) for c in self.cameras]
        if np.linalg.norm(centres[1]-centres[0]) < .01:
            raise ValueError('Two distinct calibrated camera positions are required')
        return self


class AnalysisInput(BaseModel):
    model_config = ConfigDict(extra="forbid", allow_inf_nan=False)
    discipline: Literal["hitting"] = "hitting"
    view: Literal["face_on", "unknown"] = "unknown"
    handedness: Literal["left", "right"] | None = None
    level: Literal["hs_jv", "hs_varsity", "college"] | None = None
    pitcher_direction: Literal["image_left", "image_right"] | None = None
    body_height_px: float | None = Field(default=None, gt=0)
    body_height_source: str | None = Field(default=None, min_length=1, max_length=512)
    rotation_degrees: Literal[0, 90, 180, 270] | None = None
    camera_stability: Literal["unknown", "fixed_verified", "moving"] = "unknown"
    measurement_backend: Literal["2d", "rtmw3d", "sam3d"] = "2d"
    coaching_mode: Literal["disabled", "measurements_only", "poc_video"] = "disabled"
    height_m: float | None = Field(default=None, ge=.5, le=2.5)
    camera: CameraInput | None = None
    root_depth_m: float | None = Field(default=None, gt=.5, le=100)
    root_depth_source: str | None = Field(default=None, min_length=1, max_length=512)
    camera_up: tuple[float, float, float] = (0., -1., 0.)
    timing: TimingInput = Field(default_factory=TimingInput)
    single_swing: bool = False
    reps: list[RepRange] = Field(default_factory=list, max_length=100)
    practice_type: Literal['tee', 'soft_toss', 'front_toss', 'live', 'machine', 'unknown'] = 'unknown'
    pitch_speed_mps: float | None = Field(default=None, gt=0, le=100)
    pitch_location: str | None = Field(default=None, min_length=1, max_length=256)
    pitch_context_source: str | None = Field(default=None, min_length=1, max_length=512)
    stereo_tracking: StereoTrackingInput | None = None

    @model_validator(mode="after")
    def ranges(self):
        import math
        if (self.pitch_speed_mps is not None or self.pitch_location is not None) and not (self.pitch_context_source and self.pitch_context_source.strip()):
            raise ValueError('Pitch speed/location need a source; they are supplied context, not video measurements')
        if self.stereo_tracking and self.timing.kind == 'unknown':
            raise ValueError('Two-view analysis requires documented primary capture time')
        if self.stereo_tracking and self.camera_stability != 'fixed_verified':
            raise ValueError('Two-view calibration requires verified fixed cameras')
        if self.root_depth_m is not None and not (self.root_depth_source and self.root_depth_source.strip()):
            raise ValueError("A supplied pelvis depth needs a source description")
        if sum(x*x for x in self.camera_up) < .5 or not all(math.isfinite(x) for x in self.camera_up):
            raise ValueError("camera_up must be a finite nonzero direction in camera coordinates")
        if self.body_height_px is not None and not (self.body_height_source and self.body_height_source.strip()):
            raise ValueError("A supplied image height needs a source description")
        if self.single_swing and self.reps:
            raise ValueError("Use single_swing or explicit rep ranges, not both")
        if any(b.start_frame <= a.end_frame for a, b in zip(self.reps, self.reps[1:])):
            raise ValueError("Rep ranges must be ordered and must not overlap")
        return self

    def engine_metadata(self):
        value = {"timing": self.timing.model_dump(exclude_none=True),
                 "camera_stability": self.camera_stability, "intended_use": "research"}
        if self.rotation_degrees is not None:
            value["rotation_degrees"] = self.rotation_degrees
        if self.handedness:
            value["handedness"] = self.handedness
        if self.height_m is not None:
            value["height_m"] = self.height_m
        return value