File size: 6,071 Bytes
1558b6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Version 3.0 timing output, separate from the existing nine-field payload."""
from typing import Annotated, Literal, Union

from pydantic import BaseModel, ConfigDict, Field, model_validator

from .load_timing import LOAD_TIMING_KEYS

CaptureReason = Literal["a_bit_blurry", "a_bit_dark", "low_fps", "low_pose_confidence",
    "multiple_people", "no_person", "partly_out_of_frame", "person_too_small",
    "player_switched", "pose_confidence_fair", "too_blurry", "too_dark", "very_low_fps",
    "view_uncertain", "wrong_view"]


class TimingCapture(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    ok: bool
    reasons: list[CaptureReason]

    @model_validator(mode="after")
    def explain_failure(self):
        if not self.ok and not self.reasons:
            raise ValueError("A failed capture check requires a reason")
        if len(self.reasons) != len(set(self.reasons)):
            raise ValueError("Capture reasons must be unique")
        return self


class TimingMetric(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False,
        json_schema_extra={"allOf": [{
            "if": {"properties": {"status": {"const": "estimated"}}},
            "then": {"properties": {"value": {"type": "number"}}},
            "else": {"properties": {"value": {"type": "null"}}}}]})
    value: float | None
    unit: Literal["ms"]
    status: Literal["estimated", "unclear", "not_applicable"]
    confidence: Literal["est"]
    note: str = Field(min_length=1)

    @model_validator(mode="after")
    def missing_values(self):
        if (self.value is not None) != (self.status == "estimated"):
            raise ValueError("Only estimated metrics may contain a number")
        return self


class LoadToSwingMetric(TimingMetric):
    key: Literal["load_to_swing_ms"]
    value: float | None = Field(gt=0)
    status: Literal["estimated", "unclear"]


class FootDownToSwingMetric(TimingMetric):
    key: Literal["foot_down_to_swing_ms"]


class SwingDurationMetric(TimingMetric):
    key: Literal["swing_duration_ms"]
    value: float | None = Field(gt=0)
    status: Literal["estimated", "unclear"]
    end_event: Literal["contact", "closest_approach"] | None

    @model_validator(mode="after")
    def identify_end(self):
        if self.value is not None and self.end_event is None:
            raise ValueError("A swing duration requires its end event")
        return self


class EarlyLateShiftMetric(TimingMetric):
    key: Literal["early_late_shift_ms"]


TimingValue = Annotated[Union[LoadToSwingMetric, FootDownToSwingMetric,
                              SwingDurationMetric, EarlyLateShiftMetric], Field(discriminator="key")]


def _ordered_timing_schema(schema):
    # Reuse Pydantic's own references so OpenAPI's input/output schema names
    # remain valid. Fixed positions also forbid duplicate keys in JSON Schema.
    metrics = schema["properties"]["metrics"]
    metrics["prefixItems"] = metrics["items"]["oneOf"]
    metrics["items"] = False


class LoadTimingRep(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True,
                             json_schema_extra=_ordered_timing_schema)
    rep: int = Field(ge=1)
    outcome: Literal["hit", "miss", "unknown"]
    stepped: bool | None
    metrics: list[TimingValue] = Field(min_length=4, max_length=4)

    @model_validator(mode="after")
    def coherent_rep(self):
        if tuple(metric.key for metric in self.metrics) != LOAD_TIMING_KEYS:
            raise ValueError("Every swing requires the four timing keys in contract order")
        load, foot, duration, shift = self.metrics
        if self.stepped is False and foot.status != "not_applicable":
            raise ValueError("A no-step swing requires not_applicable foot timing")
        if self.stepped is not False and foot.status == "not_applicable":
            raise ValueError("Unknown step evidence cannot be called not_applicable")
        if foot.value is not None and self.stepped is not True:
            raise ValueError("Foot timing requires a supported step")
        if self.outcome == "hit" and shift.status != "not_applicable":
            raise ValueError("Early/late correction only applies to misses")
        if self.outcome != "hit" and shift.status == "not_applicable":
            raise ValueError("Unknown or missed outcomes require an estimate or unclear shift")
        if shift.value is not None and self.outcome != "miss":
            raise ValueError("An early/late estimate requires a miss")
        if duration.value is not None:
            expected = {"hit": "contact", "miss": "closest_approach"}.get(self.outcome)
            if duration.end_event != expected:
                raise ValueError("Swing duration must match the observed outcome")
        return self


class LoadTimingPayload(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True, title="Load and timing payload")
    schema_version: Literal["3.0"]
    discipline: Literal["hitting"]
    time_basis: Literal["capture"]
    capture: TimingCapture
    reps: list[LoadTimingRep] = Field(max_length=100)

    @model_validator(mode="after")
    def capture_and_reps(self):
        numbers = [rep.rep for rep in self.reps]
        if numbers != sorted(set(numbers)):
            raise ValueError("Swing numbers must be unique and ordered")
        if not self.capture.ok and any(metric.value is not None for rep in self.reps for metric in rep.metrics):
            raise ValueError("A failed capture cannot contain timing numbers")
        return self


def load_timing_schema():
    schema = LoadTimingPayload.model_json_schema(mode="serialization")
    schema["$schema"] = "https://json-schema.org/draft/2020-12/schema"
    schema["description"] = ("GET /v1/analyses/{job_id}/load-timing. Capture milliseconds; "
        "four estimated or null timing values per swing. Body extension is not ball contact. "
        "Negative foot timing means swing before landing; a negative early/late shift asks for an earlier swing.")
    return schema