Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
ae2c68f
1
Parent(s): fe40b87
Automated Deploy: 83f1f6fa59ef9d22788ee608e3ba12967f91dd5c
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- AI-coach-agent/docs/SWING_REPORT_API.md +1 -1
- AI-coach-agent/src/ai_coach/knowledge/benchmarks.yaml +308 -2
- AI-coach-agent/src/ai_coach/knowledge/swing_metrics.yaml +284 -31
- AI-coach-agent/src/ai_coach/swing_report/schemas.py +29 -11
- AI-coach-agent/src/ai_coach/swing_report/service.py +64 -4
- AI-coach-agent/src/ai_coach/swing_report/text.py +52 -4
- AI-coach-agent/src/ai_coach/swing_report/validation.py +65 -10
- AI-coach-agent/tests/test_swing_report_evidence_scope.py +42 -0
- AI-coach-agent/tests/test_swing_report_report.py +10 -10
- AI-coach-agent/tools/build_benchmarks.py +8 -3
- backend/CONTRIBUTING.md +9 -4
- backend/app/common/consent.py +17 -0
- backend/app/common/labels.py +30 -0
- backend/app/common/media.py +17 -0
- backend/app/common/names.py +17 -0
- backend/app/common/uploads.py +43 -0
- backend/app/core/pagination.py +14 -0
- backend/app/core/rate_limit.py +5 -0
- backend/app/integrations/storage.py +3 -0
- backend/app/modules/academy_org/repository.py +0 -8
- backend/app/modules/academy_org/service.py +20 -28
- backend/app/modules/academy_staff/controller.py +3 -11
- backend/app/modules/academy_staff/repository.py +28 -16
- backend/app/modules/academy_staff/service.py +29 -22
- backend/app/modules/api_audit/service.py +3 -4
- backend/app/modules/assignments/controller.py +3 -13
- backend/app/modules/assignments/repository.py +2 -6
- backend/app/modules/assignments/service.py +7 -17
- backend/app/modules/catalog/service.py +1 -2
- backend/app/modules/coach/service.py +2 -5
- backend/app/modules/goals/service.py +5 -9
- backend/app/modules/idempotency/service.py +8 -3
- backend/app/modules/notifications/service.py +3 -4
- backend/app/modules/reporting/service.py +6 -12
- backend/app/modules/reviews/repository.py +0 -3
- backend/app/modules/reviews/service.py +16 -28
- backend/app/modules/sessions/repository.py +0 -9
- backend/app/modules/sessions/service.py +8 -11
- backend/app/modules/swing_reports/repository.py +0 -9
- backend/app/modules/swing_reports/service.py +15 -4
- backend/app/modules/threads/controller.py +2 -9
- backend/app/modules/threads/repository.py +2 -9
- backend/app/modules/threads/service.py +15 -33
- backend/docs/openapi.json +0 -0
- backend/tests/integration/test_swing_reports.py +38 -1
- baseball_batting/api.py +1 -1
- baseball_batting/coach_geometry.py +57 -0
- baseball_batting/motion_api.py +4 -3
- baseball_batting/motion_coach.py +100 -10
- baseball_batting/motion_coach_contract.py +58 -8
AI-coach-agent/docs/SWING_REPORT_API.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# Swing report API: expected output
|
| 2 |
|
| 3 |
-
**Status:**
|
| 4 |
|
| 5 |
**Input:** one swing analysis payload, following the ML engineer's contract v1.0.
|
| 6 |
|
|
|
|
| 1 |
# Swing report API: expected output
|
| 2 |
|
| 3 |
+
**Status:** historical proposal for version `1.0`. This document's sample scores and limited-value aggregation are superseded by the [implemented 1.1 contract and scoring behavior](../../docs/motion-coach-v1.1.md). The receiver accepts both input versions; the report retains version `1.0` with additive interval fields.
|
| 4 |
|
| 5 |
**Input:** one swing analysis payload, following the ML engineer's contract v1.0.
|
| 6 |
|
AI-coach-agent/src/ai_coach/knowledge/benchmarks.yaml
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
-
# GENERATED by tools/build_benchmarks.py from data_ref/calibration/contract_v1
|
| 2 |
# Do not edit by hand: change the generator or the source data and regenerate.
|
| 3 |
-
version: 2026-10-
|
| 4 |
kind: reference_interval
|
| 5 |
source_reference: OpenBiomechanics Project hitting dataset (Driveline), percentiles P25-P75 and P10-P90
|
| 6 |
sign_convention: 'raw contract values: wrap180(shoulder_heading - hip_heading), not mirrored by batting hand'
|
|
@@ -167,3 +167,309 @@ metrics:
|
|
| 167 |
lower: 15.6
|
| 168 |
upper: 47.7
|
| 169 |
median: 30.2
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# GENERATED by tools/build_benchmarks.py from data_ref/calibration/contract_v1 and contract_v1_1.
|
| 2 |
# Do not edit by hand: change the generator or the source data and regenerate.
|
| 3 |
+
version: 2026-10-31.1
|
| 4 |
kind: reference_interval
|
| 5 |
source_reference: OpenBiomechanics Project hitting dataset (Driveline), percentiles P25-P75 and P10-P90
|
| 6 |
sign_convention: 'raw contract values: wrap180(shoulder_heading - hip_heading), not mirrored by batting hand'
|
|
|
|
| 167 |
lower: 15.6
|
| 168 |
upper: 47.7
|
| 169 |
median: 30.2
|
| 170 |
+
torso_inclination_at_stride_start:
|
| 171 |
+
unit: deg
|
| 172 |
+
cells:
|
| 173 |
+
right/high_school:
|
| 174 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_stride_start.right.high_school
|
| 175 |
+
population: High school right-handed hitters (12 athletes)
|
| 176 |
+
n_athletes: 12
|
| 177 |
+
n_swings: 54
|
| 178 |
+
on_target:
|
| 179 |
+
lower: 16.477
|
| 180 |
+
upper: 22.165
|
| 181 |
+
satisfactory:
|
| 182 |
+
lower: 13.647
|
| 183 |
+
upper: 26.95
|
| 184 |
+
median: 18.132
|
| 185 |
+
right/college:
|
| 186 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_stride_start.right.college
|
| 187 |
+
population: College right-handed hitters (50 athletes)
|
| 188 |
+
n_athletes: 50
|
| 189 |
+
n_swings: 312
|
| 190 |
+
on_target:
|
| 191 |
+
lower: 12.451
|
| 192 |
+
upper: 21.514
|
| 193 |
+
satisfactory:
|
| 194 |
+
lower: 10.482
|
| 195 |
+
upper: 23.561
|
| 196 |
+
median: 17.587
|
| 197 |
+
right/pro:
|
| 198 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_stride_start.right.pro
|
| 199 |
+
population: Professional right-handed hitters (8 athletes)
|
| 200 |
+
n_athletes: 8
|
| 201 |
+
n_swings: 46
|
| 202 |
+
on_target:
|
| 203 |
+
lower: 12.79
|
| 204 |
+
upper: 19.706
|
| 205 |
+
satisfactory:
|
| 206 |
+
lower: 10.569
|
| 207 |
+
upper: 20.202
|
| 208 |
+
median: 16.559
|
| 209 |
+
left/college:
|
| 210 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_stride_start.left.college
|
| 211 |
+
population: College left-handed hitters (23 athletes)
|
| 212 |
+
n_athletes: 23
|
| 213 |
+
n_swings: 148
|
| 214 |
+
on_target:
|
| 215 |
+
lower: 10.876
|
| 216 |
+
upper: 20.913
|
| 217 |
+
satisfactory:
|
| 218 |
+
lower: 7.027
|
| 219 |
+
upper: 21.64
|
| 220 |
+
median: 15.483
|
| 221 |
+
hip_shoulder_separation_at_stride_start:
|
| 222 |
+
unit: deg
|
| 223 |
+
cells:
|
| 224 |
+
right/high_school:
|
| 225 |
+
benchmark_id: obp-contract-v1.hip_shoulder_separation_at_stride_start.right.high_school
|
| 226 |
+
population: High school right-handed hitters (12 athletes)
|
| 227 |
+
n_athletes: 12
|
| 228 |
+
n_swings: 54
|
| 229 |
+
on_target:
|
| 230 |
+
lower: -15.439
|
| 231 |
+
upper: -5.326
|
| 232 |
+
satisfactory:
|
| 233 |
+
lower: -19.805
|
| 234 |
+
upper: -2.582
|
| 235 |
+
median: -8.689
|
| 236 |
+
right/college:
|
| 237 |
+
benchmark_id: obp-contract-v1.hip_shoulder_separation_at_stride_start.right.college
|
| 238 |
+
population: College right-handed hitters (50 athletes)
|
| 239 |
+
n_athletes: 50
|
| 240 |
+
n_swings: 312
|
| 241 |
+
on_target:
|
| 242 |
+
lower: -13.629
|
| 243 |
+
upper: -6.051
|
| 244 |
+
satisfactory:
|
| 245 |
+
lower: -15.908
|
| 246 |
+
upper: 0.649
|
| 247 |
+
median: -8.338
|
| 248 |
+
right/pro:
|
| 249 |
+
benchmark_id: obp-contract-v1.hip_shoulder_separation_at_stride_start.right.pro
|
| 250 |
+
population: Professional right-handed hitters (8 athletes)
|
| 251 |
+
n_athletes: 8
|
| 252 |
+
n_swings: 46
|
| 253 |
+
on_target:
|
| 254 |
+
lower: -7.626
|
| 255 |
+
upper: -3.168
|
| 256 |
+
satisfactory:
|
| 257 |
+
lower: -10.813
|
| 258 |
+
upper: 0.28
|
| 259 |
+
median: -5.479
|
| 260 |
+
left/college:
|
| 261 |
+
benchmark_id: obp-contract-v1.hip_shoulder_separation_at_stride_start.left.college
|
| 262 |
+
population: College left-handed hitters (23 athletes)
|
| 263 |
+
n_athletes: 23
|
| 264 |
+
n_swings: 148
|
| 265 |
+
on_target:
|
| 266 |
+
lower: -1.404
|
| 267 |
+
upper: 7.816
|
| 268 |
+
satisfactory:
|
| 269 |
+
lower: -4.207
|
| 270 |
+
upper: 9.349
|
| 271 |
+
median: 3.77
|
| 272 |
+
pelvis_rotation_to_contact:
|
| 273 |
+
unit: deg
|
| 274 |
+
cells:
|
| 275 |
+
right/high_school:
|
| 276 |
+
benchmark_id: obp-contract-v1.pelvis_rotation_to_contact.right.high_school
|
| 277 |
+
population: High school right-handed hitters (12 athletes)
|
| 278 |
+
n_athletes: 12
|
| 279 |
+
n_swings: 75
|
| 280 |
+
on_target:
|
| 281 |
+
lower: 95.252
|
| 282 |
+
upper: 109.403
|
| 283 |
+
satisfactory:
|
| 284 |
+
lower: 71.621
|
| 285 |
+
upper: 113.136
|
| 286 |
+
median: 101.385
|
| 287 |
+
right/college:
|
| 288 |
+
benchmark_id: obp-contract-v1.pelvis_rotation_to_contact.right.college
|
| 289 |
+
population: College right-handed hitters (50 athletes)
|
| 290 |
+
n_athletes: 50
|
| 291 |
+
n_swings: 339
|
| 292 |
+
on_target:
|
| 293 |
+
lower: 92.239
|
| 294 |
+
upper: 112.851
|
| 295 |
+
satisfactory:
|
| 296 |
+
lower: 87.519
|
| 297 |
+
upper: 119.838
|
| 298 |
+
median: 99.919
|
| 299 |
+
right/pro:
|
| 300 |
+
benchmark_id: obp-contract-v1.pelvis_rotation_to_contact.right.pro
|
| 301 |
+
population: Professional right-handed hitters (8 athletes)
|
| 302 |
+
n_athletes: 8
|
| 303 |
+
n_swings: 54
|
| 304 |
+
on_target:
|
| 305 |
+
lower: 101.744
|
| 306 |
+
upper: 110.155
|
| 307 |
+
satisfactory:
|
| 308 |
+
lower: 91.703
|
| 309 |
+
upper: 111.75
|
| 310 |
+
median: 107.33
|
| 311 |
+
left/college:
|
| 312 |
+
benchmark_id: obp-contract-v1.pelvis_rotation_to_contact.left.college
|
| 313 |
+
population: College left-handed hitters (23 athletes)
|
| 314 |
+
n_athletes: 23
|
| 315 |
+
n_swings: 158
|
| 316 |
+
on_target:
|
| 317 |
+
lower: 91.944
|
| 318 |
+
upper: 109.794
|
| 319 |
+
satisfactory:
|
| 320 |
+
lower: 71.154
|
| 321 |
+
upper: 116.492
|
| 322 |
+
median: 102.235
|
| 323 |
+
lead_knee_extension_to_contact:
|
| 324 |
+
unit: deg
|
| 325 |
+
cells:
|
| 326 |
+
right/high_school:
|
| 327 |
+
benchmark_id: obp-contract-v1.lead_knee_extension_to_contact.right.high_school
|
| 328 |
+
population: High school right-handed hitters (12 athletes)
|
| 329 |
+
n_athletes: 12
|
| 330 |
+
n_swings: 75
|
| 331 |
+
on_target:
|
| 332 |
+
lower: 20.026
|
| 333 |
+
upper: 33.401
|
| 334 |
+
satisfactory:
|
| 335 |
+
lower: 13.012
|
| 336 |
+
upper: 46.79
|
| 337 |
+
median: 26.679
|
| 338 |
+
right/college:
|
| 339 |
+
benchmark_id: obp-contract-v1.lead_knee_extension_to_contact.right.college
|
| 340 |
+
population: College right-handed hitters (50 athletes)
|
| 341 |
+
n_athletes: 50
|
| 342 |
+
n_swings: 339
|
| 343 |
+
on_target:
|
| 344 |
+
lower: 24.36
|
| 345 |
+
upper: 37.117
|
| 346 |
+
satisfactory:
|
| 347 |
+
lower: 11.016
|
| 348 |
+
upper: 41.516
|
| 349 |
+
median: 30.214
|
| 350 |
+
right/pro:
|
| 351 |
+
benchmark_id: obp-contract-v1.lead_knee_extension_to_contact.right.pro
|
| 352 |
+
population: Professional right-handed hitters (8 athletes)
|
| 353 |
+
n_athletes: 8
|
| 354 |
+
n_swings: 54
|
| 355 |
+
on_target:
|
| 356 |
+
lower: 26.439
|
| 357 |
+
upper: 39.377
|
| 358 |
+
satisfactory:
|
| 359 |
+
lower: 25.249
|
| 360 |
+
upper: 44.219
|
| 361 |
+
median: 31.089
|
| 362 |
+
left/college:
|
| 363 |
+
benchmark_id: obp-contract-v1.lead_knee_extension_to_contact.left.college
|
| 364 |
+
population: College left-handed hitters (23 athletes)
|
| 365 |
+
n_athletes: 23
|
| 366 |
+
n_swings: 158
|
| 367 |
+
on_target:
|
| 368 |
+
lower: 22.863
|
| 369 |
+
upper: 35.16
|
| 370 |
+
satisfactory:
|
| 371 |
+
lower: 18.307
|
| 372 |
+
upper: 44.186
|
| 373 |
+
median: 27.741
|
| 374 |
+
torso_inclination_at_contact:
|
| 375 |
+
unit: deg
|
| 376 |
+
cells:
|
| 377 |
+
right/high_school:
|
| 378 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_contact.right.high_school
|
| 379 |
+
population: High school right-handed hitters (12 athletes)
|
| 380 |
+
n_athletes: 12
|
| 381 |
+
n_swings: 75
|
| 382 |
+
on_target:
|
| 383 |
+
lower: 23.757
|
| 384 |
+
upper: 28.781
|
| 385 |
+
satisfactory:
|
| 386 |
+
lower: 23.44
|
| 387 |
+
upper: 31.166
|
| 388 |
+
median: 25.992
|
| 389 |
+
right/college:
|
| 390 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_contact.right.college
|
| 391 |
+
population: College right-handed hitters (50 athletes)
|
| 392 |
+
n_athletes: 50
|
| 393 |
+
n_swings: 339
|
| 394 |
+
on_target:
|
| 395 |
+
lower: 23.095
|
| 396 |
+
upper: 29.757
|
| 397 |
+
satisfactory:
|
| 398 |
+
lower: 19.666
|
| 399 |
+
upper: 34.174
|
| 400 |
+
median: 25.627
|
| 401 |
+
right/pro:
|
| 402 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_contact.right.pro
|
| 403 |
+
population: Professional right-handed hitters (8 athletes)
|
| 404 |
+
n_athletes: 8
|
| 405 |
+
n_swings: 54
|
| 406 |
+
on_target:
|
| 407 |
+
lower: 25.461
|
| 408 |
+
upper: 29.828
|
| 409 |
+
satisfactory:
|
| 410 |
+
lower: 23.969
|
| 411 |
+
upper: 32.311
|
| 412 |
+
median: 27.233
|
| 413 |
+
left/college:
|
| 414 |
+
benchmark_id: obp-contract-v1.torso_inclination_at_contact.left.college
|
| 415 |
+
population: College left-handed hitters (23 athletes)
|
| 416 |
+
n_athletes: 23
|
| 417 |
+
n_swings: 158
|
| 418 |
+
on_target:
|
| 419 |
+
lower: 26.972
|
| 420 |
+
upper: 30.407
|
| 421 |
+
satisfactory:
|
| 422 |
+
lower: 23.096
|
| 423 |
+
upper: 32.363
|
| 424 |
+
median: 28.916
|
| 425 |
+
shoulder_rotation_after_contact:
|
| 426 |
+
unit: deg
|
| 427 |
+
cells:
|
| 428 |
+
right/high_school:
|
| 429 |
+
benchmark_id: obp-contract-v1.shoulder_rotation_after_contact.right.high_school
|
| 430 |
+
population: High school right-handed hitters (12 athletes)
|
| 431 |
+
n_athletes: 12
|
| 432 |
+
n_swings: 75
|
| 433 |
+
on_target:
|
| 434 |
+
lower: 33.222
|
| 435 |
+
upper: 49.491
|
| 436 |
+
satisfactory:
|
| 437 |
+
lower: 30.717
|
| 438 |
+
upper: 50.917
|
| 439 |
+
median: 46.241
|
| 440 |
+
right/college:
|
| 441 |
+
benchmark_id: obp-contract-v1.shoulder_rotation_after_contact.right.college
|
| 442 |
+
population: College right-handed hitters (50 athletes)
|
| 443 |
+
n_athletes: 50
|
| 444 |
+
n_swings: 339
|
| 445 |
+
on_target:
|
| 446 |
+
lower: 32.14
|
| 447 |
+
upper: 42.911
|
| 448 |
+
satisfactory:
|
| 449 |
+
lower: 24.678
|
| 450 |
+
upper: 50.737
|
| 451 |
+
median: 39.678
|
| 452 |
+
right/pro:
|
| 453 |
+
benchmark_id: obp-contract-v1.shoulder_rotation_after_contact.right.pro
|
| 454 |
+
population: Professional right-handed hitters (8 athletes)
|
| 455 |
+
n_athletes: 8
|
| 456 |
+
n_swings: 54
|
| 457 |
+
on_target:
|
| 458 |
+
lower: 41.326
|
| 459 |
+
upper: 51.044
|
| 460 |
+
satisfactory:
|
| 461 |
+
lower: 39.631
|
| 462 |
+
upper: 57.817
|
| 463 |
+
median: 48.357
|
| 464 |
+
left/college:
|
| 465 |
+
benchmark_id: obp-contract-v1.shoulder_rotation_after_contact.left.college
|
| 466 |
+
population: College left-handed hitters (23 athletes)
|
| 467 |
+
n_athletes: 23
|
| 468 |
+
n_swings: 158
|
| 469 |
+
on_target:
|
| 470 |
+
lower: 34.359
|
| 471 |
+
upper: 44.89
|
| 472 |
+
satisfactory:
|
| 473 |
+
lower: 28.626
|
| 474 |
+
upper: 53.315
|
| 475 |
+
median: 40.799
|
AI-coach-agent/src/ai_coach/knowledge/swing_metrics.yaml
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# Swing report metric registry (
|
| 2 |
#
|
| 3 |
# Sign convention. The contract reports separation as wrap180(shoulder_heading - hip_heading) with ONE convention for
|
| 4 |
# both batting sides, so the same body position has opposite signs for right- and left-handed hitters. Benchmarks are kept
|
|
@@ -11,8 +11,8 @@
|
|
| 11 |
# Drill ids come from drills.yaml (hitting). `drill_review`: spec = the choice shown in docs/SWING_REPORT_API.md;
|
| 12 |
# needs_coach_review = a sensible pick from the starter library that a coach must confirm.
|
| 13 |
# Text rules: plain words, no numbers, no good/bad judgements (guardrails.BANNED).
|
| 14 |
-
version: "1.
|
| 15 |
-
measurement_definitions_version: "1.
|
| 16 |
|
| 17 |
groups:
|
| 18 |
- group: balance_load
|
|
@@ -43,15 +43,15 @@ metrics:
|
|
| 43 |
what_it_means: When your front foot lands, how differently your hips and shoulders are pointing.
|
| 44 |
in_range_text: Your hips and shoulders were turned about the way most hitters are when your front foot landed.
|
| 45 |
directions:
|
| 46 |
-
above: #
|
| 47 |
-
meaning:
|
| 48 |
-
result_text:
|
| 49 |
-
satisfactory: Your shoulders were
|
| 50 |
-
off_target: Your shoulders were
|
| 51 |
-
headline: Your
|
| 52 |
-
coach_message: Your
|
| 53 |
-
coach_tip:
|
| 54 |
-
practice_feel: Keep your
|
| 55 |
drill_id: hit_13
|
| 56 |
drill_review: spec
|
| 57 |
below: # shoulders wound far behind the hips at landing
|
|
@@ -60,14 +60,14 @@ metrics:
|
|
| 60 |
satisfactory: Your shoulders were turned back a little more than most hitters when your front foot landed.
|
| 61 |
off_target: Your shoulders were turned far back behind your hips when your front foot landed.
|
| 62 |
headline: Your shoulders are wound far back when your front foot lands.
|
| 63 |
-
coach_message: Your shoulders are turned
|
| 64 |
-
coach_tip:
|
| 65 |
-
practice_feel:
|
| 66 |
drill_id: hit_09
|
| 67 |
drill_review: needs_coach_review
|
| 68 |
maintain:
|
| 69 |
-
coach_message: Your
|
| 70 |
-
practice_feel:
|
| 71 |
drill_id: hit_14
|
| 72 |
drill_review: needs_coach_review
|
| 73 |
|
|
@@ -88,9 +88,9 @@ metrics:
|
|
| 88 |
satisfactory: Your step was a little longer than most hitters take.
|
| 89 |
off_target: Your step was much longer than most hitters take.
|
| 90 |
headline: Your front foot steps out farther than most hitters.
|
| 91 |
-
coach_message: Your
|
| 92 |
-
coach_tip:
|
| 93 |
-
practice_feel:
|
| 94 |
drill_id: hit_01
|
| 95 |
drill_review: needs_coach_review
|
| 96 |
below:
|
|
@@ -99,9 +99,9 @@ metrics:
|
|
| 99 |
satisfactory: Your step was a little shorter than most hitters take.
|
| 100 |
off_target: Your step was much shorter than most hitters take.
|
| 101 |
headline: Your front foot barely moves forward before you swing.
|
| 102 |
-
coach_message: Your
|
| 103 |
-
coach_tip:
|
| 104 |
-
practice_feel:
|
| 105 |
drill_id: hit_04
|
| 106 |
drill_review: needs_coach_review
|
| 107 |
maintain:
|
|
@@ -126,9 +126,9 @@ metrics:
|
|
| 126 |
satisfactory: Your shoulders were turned a little ahead of your hips when the bat met the ball.
|
| 127 |
off_target: Your shoulders had turned well ahead of your hips when the bat met the ball.
|
| 128 |
headline: Your shoulders turn ahead of your hips by the time the bat meets the ball.
|
| 129 |
-
coach_message: Your shoulders
|
| 130 |
-
coach_tip:
|
| 131 |
-
practice_feel:
|
| 132 |
drill_id: hit_14
|
| 133 |
drill_review: needs_coach_review
|
| 134 |
below: # hips turned well ahead of the shoulders at contact
|
|
@@ -137,17 +137,260 @@ metrics:
|
|
| 137 |
satisfactory: Your hips were turned a little ahead of your shoulders when the bat met the ball.
|
| 138 |
off_target: Your hips had turned well ahead of your shoulders when the bat met the ball.
|
| 139 |
headline: Your hips spin well ahead of your shoulders by the time the bat meets the ball.
|
| 140 |
-
coach_message: Your hips
|
| 141 |
-
coach_tip:
|
| 142 |
-
practice_feel:
|
| 143 |
drill_id: hit_12
|
| 144 |
drill_review: needs_coach_review
|
| 145 |
maintain: # every rated result is on target and this is the area to keep sharp
|
| 146 |
-
coach_message: Your
|
| 147 |
-
practice_feel:
|
| 148 |
drill_id: hit_08
|
| 149 |
drill_review: needs_coach_review
|
| 150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
# The practice suggestion when nothing in the swing could be rated, so the player always has a drill.
|
| 152 |
general_focus:
|
| 153 |
display_name: General practice
|
|
@@ -201,6 +444,16 @@ reasons:
|
|
| 201 |
limitation: The movement did not line up from frame to frame, so treat this as approximate.
|
| 202 |
report: The movement did not line up from frame to frame, so some results are approximate.
|
| 203 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
# data_quality notes the coach adds itself (not from the payload).
|
| 205 |
notes:
|
| 206 |
level_assumed:
|
|
|
|
| 1 |
+
# Swing report metric registry (contracts 1.0 and 1.1). Reference comparisons are not technique diagnoses.
|
| 2 |
#
|
| 3 |
# Sign convention. The contract reports separation as wrap180(shoulder_heading - hip_heading) with ONE convention for
|
| 4 |
# both batting sides, so the same body position has opposite signs for right- and left-handed hitters. Benchmarks are kept
|
|
|
|
| 11 |
# Drill ids come from drills.yaml (hitting). `drill_review`: spec = the choice shown in docs/SWING_REPORT_API.md;
|
| 12 |
# needs_coach_review = a sensible pick from the starter library that a coach must confirm.
|
| 13 |
# Text rules: plain words, no numbers, no good/bad judgements (guardrails.BANNED).
|
| 14 |
+
version: "1.1" # coaching_rules_version
|
| 15 |
+
measurement_definitions_version: "1.1"
|
| 16 |
|
| 17 |
groups:
|
| 18 |
- group: balance_load
|
|
|
|
| 43 |
what_it_means: When your front foot lands, how differently your hips and shoulders are pointing.
|
| 44 |
in_range_text: Your hips and shoulders were turned about the way most hitters are when your front foot landed.
|
| 45 |
directions:
|
| 46 |
+
above: # relative orientation at landing; does not establish when opening began
|
| 47 |
+
meaning: shoulders_more_open_at_landing
|
| 48 |
+
result_text:
|
| 49 |
+
satisfactory: Your shoulders were more open relative to your hips than the reference when your front foot landed.
|
| 50 |
+
off_target: Your shoulders were more open relative to your hips than the reference when your front foot landed.
|
| 51 |
+
headline: Your hip and shoulder angle at foot down differs from the reference.
|
| 52 |
+
coach_message: Your hip and shoulder angle at foot down differs from the reference. Review this moment before changing your swing.
|
| 53 |
+
coach_tip: Review your hip and shoulder angle when your front foot lands.
|
| 54 |
+
practice_feel: Keep your turn smooth and comfortable.
|
| 55 |
drill_id: hit_13
|
| 56 |
drill_review: spec
|
| 57 |
below: # shoulders wound far behind the hips at landing
|
|
|
|
| 60 |
satisfactory: Your shoulders were turned back a little more than most hitters when your front foot landed.
|
| 61 |
off_target: Your shoulders were turned far back behind your hips when your front foot landed.
|
| 62 |
headline: Your shoulders are wound far back when your front foot lands.
|
| 63 |
+
coach_message: Your shoulders are turned farther behind your hips than the reference at foot down. Review this moment before changing your swing.
|
| 64 |
+
coach_tip: Review your hip and shoulder angle when your front foot lands.
|
| 65 |
+
practice_feel: Keep your turn smooth and comfortable.
|
| 66 |
drill_id: hit_09
|
| 67 |
drill_review: needs_coach_review
|
| 68 |
maintain:
|
| 69 |
+
coach_message: Your hip and shoulder angle at foot down was within the reference range. Keep your movement smooth and repeatable.
|
| 70 |
+
practice_feel: Keep your turn smooth and comfortable.
|
| 71 |
drill_id: hit_14
|
| 72 |
drill_review: needs_coach_review
|
| 73 |
|
|
|
|
| 88 |
satisfactory: Your step was a little longer than most hitters take.
|
| 89 |
off_target: Your step was much longer than most hitters take.
|
| 90 |
headline: Your front foot steps out farther than most hitters.
|
| 91 |
+
coach_message: Your foot movement was longer than the reference range. Check the drill and marked moments before changing your step.
|
| 92 |
+
coach_tip: Review where your stride starts and where your foot lands.
|
| 93 |
+
practice_feel: Use a comfortable, repeatable step.
|
| 94 |
drill_id: hit_01
|
| 95 |
drill_review: needs_coach_review
|
| 96 |
below:
|
|
|
|
| 99 |
satisfactory: Your step was a little shorter than most hitters take.
|
| 100 |
off_target: Your step was much shorter than most hitters take.
|
| 101 |
headline: Your front foot barely moves forward before you swing.
|
| 102 |
+
coach_message: Your foot movement was shorter than the reference range. Check the drill and marked moments before changing your step.
|
| 103 |
+
coach_tip: Review where your stride starts and where your foot lands.
|
| 104 |
+
practice_feel: Use a comfortable, repeatable step.
|
| 105 |
drill_id: hit_04
|
| 106 |
drill_review: needs_coach_review
|
| 107 |
maintain:
|
|
|
|
| 126 |
satisfactory: Your shoulders were turned a little ahead of your hips when the bat met the ball.
|
| 127 |
off_target: Your shoulders had turned well ahead of your hips when the bat met the ball.
|
| 128 |
headline: Your shoulders turn ahead of your hips by the time the bat meets the ball.
|
| 129 |
+
coach_message: Your shoulders were ahead of your hips at the marked hit. Review this moment before changing your swing.
|
| 130 |
+
coach_tip: Review the marked hit and your hip and shoulder angle.
|
| 131 |
+
practice_feel: Keep your turn smooth and comfortable.
|
| 132 |
drill_id: hit_14
|
| 133 |
drill_review: needs_coach_review
|
| 134 |
below: # hips turned well ahead of the shoulders at contact
|
|
|
|
| 137 |
satisfactory: Your hips were turned a little ahead of your shoulders when the bat met the ball.
|
| 138 |
off_target: Your hips had turned well ahead of your shoulders when the bat met the ball.
|
| 139 |
headline: Your hips spin well ahead of your shoulders by the time the bat meets the ball.
|
| 140 |
+
coach_message: Your hips were ahead of your shoulders at the marked hit. Review this moment before changing your swing.
|
| 141 |
+
coach_tip: Review the marked hit and your hip and shoulder angle.
|
| 142 |
+
practice_feel: Keep your turn smooth and comfortable.
|
| 143 |
drill_id: hit_12
|
| 144 |
drill_review: needs_coach_review
|
| 145 |
maintain: # every rated result is on target and this is the area to keep sharp
|
| 146 |
+
coach_message: Your hip and shoulder angle at the marked hit was within the reference range. Keep your movement smooth and repeatable.
|
| 147 |
+
practice_feel: Keep your turn smooth and comfortable.
|
| 148 |
drill_id: hit_08
|
| 149 |
drill_review: needs_coach_review
|
| 150 |
|
| 151 |
+
- metric_id: torso_inclination_at_stride_start
|
| 152 |
+
display_name: Torso Inclination at Stride Start
|
| 153 |
+
group: balance_load
|
| 154 |
+
unit: deg
|
| 155 |
+
reference: torso_angle_from_vertical
|
| 156 |
+
event_id: stride_start
|
| 157 |
+
mirror_for_left: false
|
| 158 |
+
what_it_means: How far your torso leans from upright when your stride begins.
|
| 159 |
+
in_range_text: Your torso lean when your stride began was within the reference range.
|
| 160 |
+
directions:
|
| 161 |
+
above:
|
| 162 |
+
meaning: torso_inclination_at_stride_start_above
|
| 163 |
+
result_text:
|
| 164 |
+
satisfactory: Your torso lean when your stride began was above the reference range.
|
| 165 |
+
off_target: Your torso lean when your stride began was above the reference range.
|
| 166 |
+
headline: Your torso lean when your stride began was above the reference range.
|
| 167 |
+
coach_message: Your torso lean when your stride began was above the reference range. Use a comfortable swing and
|
| 168 |
+
keep the movement repeatable.
|
| 169 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 170 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 171 |
+
drill_id: hit_04
|
| 172 |
+
drill_review: reference_comparison_only
|
| 173 |
+
below:
|
| 174 |
+
meaning: torso_inclination_at_stride_start_below
|
| 175 |
+
result_text:
|
| 176 |
+
satisfactory: Your torso lean when your stride began was below the reference range.
|
| 177 |
+
off_target: Your torso lean when your stride began was below the reference range.
|
| 178 |
+
headline: Your torso lean when your stride began was below the reference range.
|
| 179 |
+
coach_message: Your torso lean when your stride began was below the reference range. Use a comfortable swing and
|
| 180 |
+
keep the movement repeatable.
|
| 181 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 182 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 183 |
+
drill_id: hit_04
|
| 184 |
+
drill_review: reference_comparison_only
|
| 185 |
+
maintain:
|
| 186 |
+
coach_message: Your torso lean when your stride began was within the reference range. Keep your movement smooth and
|
| 187 |
+
repeatable.
|
| 188 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 189 |
+
drill_id: hit_04
|
| 190 |
+
drill_review: reference_comparison_only
|
| 191 |
+
- metric_id: hip_shoulder_separation_at_stride_start
|
| 192 |
+
display_name: Hip Shoulder Separation at Stride Start
|
| 193 |
+
group: balance_load
|
| 194 |
+
unit: deg
|
| 195 |
+
reference: signed_horizontal_shoulder_minus_hip_heading
|
| 196 |
+
event_id: stride_start
|
| 197 |
+
mirror_for_left: false
|
| 198 |
+
what_it_means: The angle between your hips and shoulders when your stride begins.
|
| 199 |
+
in_range_text: Your hip and shoulder angle when your stride began was within the reference range.
|
| 200 |
+
directions:
|
| 201 |
+
above:
|
| 202 |
+
meaning: hip_shoulder_separation_at_stride_start_above
|
| 203 |
+
result_text:
|
| 204 |
+
satisfactory: Your hip and shoulder angle when your stride began was above the reference range.
|
| 205 |
+
off_target: Your hip and shoulder angle when your stride began was above the reference range.
|
| 206 |
+
headline: Your hip and shoulder angle when your stride began was above the reference range.
|
| 207 |
+
coach_message: Your hip and shoulder angle when your stride began was above the reference range. Use a comfortable
|
| 208 |
+
swing and keep the movement repeatable.
|
| 209 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 210 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 211 |
+
drill_id: hit_04
|
| 212 |
+
drill_review: reference_comparison_only
|
| 213 |
+
below:
|
| 214 |
+
meaning: hip_shoulder_separation_at_stride_start_below
|
| 215 |
+
result_text:
|
| 216 |
+
satisfactory: Your hip and shoulder angle when your stride began was below the reference range.
|
| 217 |
+
off_target: Your hip and shoulder angle when your stride began was below the reference range.
|
| 218 |
+
headline: Your hip and shoulder angle when your stride began was below the reference range.
|
| 219 |
+
coach_message: Your hip and shoulder angle when your stride began was below the reference range. Use a comfortable
|
| 220 |
+
swing and keep the movement repeatable.
|
| 221 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 222 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 223 |
+
drill_id: hit_04
|
| 224 |
+
drill_review: reference_comparison_only
|
| 225 |
+
maintain:
|
| 226 |
+
coach_message: Your hip and shoulder angle when your stride began was within the reference range. Keep your movement
|
| 227 |
+
smooth and repeatable.
|
| 228 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 229 |
+
drill_id: hit_04
|
| 230 |
+
drill_review: reference_comparison_only
|
| 231 |
+
- metric_id: pelvis_rotation_to_contact
|
| 232 |
+
display_name: Hip Turn to Contact
|
| 233 |
+
group: power_move
|
| 234 |
+
unit: deg
|
| 235 |
+
reference: absolute_net_horizontal_rotation
|
| 236 |
+
start_event_id: front_foot_down
|
| 237 |
+
end_event_id: contact
|
| 238 |
+
mirror_for_left: false
|
| 239 |
+
what_it_means: How far your hips turn between front foot touch and contact.
|
| 240 |
+
in_range_text: Your hip turn from foot touch to contact was within the reference range.
|
| 241 |
+
directions:
|
| 242 |
+
above:
|
| 243 |
+
meaning: pelvis_rotation_to_contact_above
|
| 244 |
+
result_text:
|
| 245 |
+
satisfactory: Your hip turn from foot touch to contact was above the reference range.
|
| 246 |
+
off_target: Your hip turn from foot touch to contact was above the reference range.
|
| 247 |
+
headline: Your hip turn from foot touch to contact was above the reference range.
|
| 248 |
+
coach_message: Your hip turn from foot touch to contact was above the reference range. Use a comfortable swing
|
| 249 |
+
and keep the movement repeatable.
|
| 250 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 251 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 252 |
+
drill_id: hit_14
|
| 253 |
+
drill_review: reference_comparison_only
|
| 254 |
+
below:
|
| 255 |
+
meaning: pelvis_rotation_to_contact_below
|
| 256 |
+
result_text:
|
| 257 |
+
satisfactory: Your hip turn from foot touch to contact was below the reference range.
|
| 258 |
+
off_target: Your hip turn from foot touch to contact was below the reference range.
|
| 259 |
+
headline: Your hip turn from foot touch to contact was below the reference range.
|
| 260 |
+
coach_message: Your hip turn from foot touch to contact was below the reference range. Use a comfortable swing
|
| 261 |
+
and keep the movement repeatable.
|
| 262 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 263 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 264 |
+
drill_id: hit_14
|
| 265 |
+
drill_review: reference_comparison_only
|
| 266 |
+
maintain:
|
| 267 |
+
coach_message: Your hip turn from foot touch to contact was within the reference range. Keep your movement smooth
|
| 268 |
+
and repeatable.
|
| 269 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 270 |
+
drill_id: hit_14
|
| 271 |
+
drill_review: reference_comparison_only
|
| 272 |
+
- metric_id: lead_knee_extension_to_contact
|
| 273 |
+
display_name: Front Knee Extension to Contact
|
| 274 |
+
group: power_move
|
| 275 |
+
unit: deg
|
| 276 |
+
reference: change_in_3d_lead_knee_angle
|
| 277 |
+
start_event_id: front_foot_down
|
| 278 |
+
end_event_id: contact
|
| 279 |
+
mirror_for_left: false
|
| 280 |
+
what_it_means: How much your front knee straightens between foot touch and contact.
|
| 281 |
+
in_range_text: Your front knee straightening from foot touch to contact was within the reference range.
|
| 282 |
+
directions:
|
| 283 |
+
above:
|
| 284 |
+
meaning: lead_knee_extension_to_contact_above
|
| 285 |
+
result_text:
|
| 286 |
+
satisfactory: Your front knee straightening from foot touch to contact was above the reference range.
|
| 287 |
+
off_target: Your front knee straightening from foot touch to contact was above the reference range.
|
| 288 |
+
headline: Your front knee straightening from foot touch to contact was above the reference range.
|
| 289 |
+
coach_message: Your front knee straightening from foot touch to contact was above the reference range. Use a comfortable
|
| 290 |
+
swing and keep the movement repeatable.
|
| 291 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 292 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 293 |
+
drill_id: hit_14
|
| 294 |
+
drill_review: reference_comparison_only
|
| 295 |
+
below:
|
| 296 |
+
meaning: lead_knee_extension_to_contact_below
|
| 297 |
+
result_text:
|
| 298 |
+
satisfactory: Your front knee straightening from foot touch to contact was below the reference range.
|
| 299 |
+
off_target: Your front knee straightening from foot touch to contact was below the reference range.
|
| 300 |
+
headline: Your front knee straightening from foot touch to contact was below the reference range.
|
| 301 |
+
coach_message: Your front knee straightening from foot touch to contact was below the reference range. Use a comfortable
|
| 302 |
+
swing and keep the movement repeatable.
|
| 303 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 304 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 305 |
+
drill_id: hit_14
|
| 306 |
+
drill_review: reference_comparison_only
|
| 307 |
+
maintain:
|
| 308 |
+
coach_message: Your front knee straightening from foot touch to contact was within the reference range. Keep your
|
| 309 |
+
movement smooth and repeatable.
|
| 310 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 311 |
+
drill_id: hit_14
|
| 312 |
+
drill_review: reference_comparison_only
|
| 313 |
+
- metric_id: torso_inclination_at_contact
|
| 314 |
+
display_name: Torso Inclination at Contact
|
| 315 |
+
group: contact_follow_through
|
| 316 |
+
unit: deg
|
| 317 |
+
reference: torso_angle_from_vertical
|
| 318 |
+
event_id: contact
|
| 319 |
+
mirror_for_left: false
|
| 320 |
+
what_it_means: How far your torso leans from upright at contact.
|
| 321 |
+
in_range_text: Your torso lean at contact was within the reference range.
|
| 322 |
+
directions:
|
| 323 |
+
above:
|
| 324 |
+
meaning: torso_inclination_at_contact_above
|
| 325 |
+
result_text:
|
| 326 |
+
satisfactory: Your torso lean at contact was above the reference range.
|
| 327 |
+
off_target: Your torso lean at contact was above the reference range.
|
| 328 |
+
headline: Your torso lean at contact was above the reference range.
|
| 329 |
+
coach_message: Your torso lean at contact was above the reference range. Use a comfortable swing and keep the movement
|
| 330 |
+
repeatable.
|
| 331 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 332 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 333 |
+
drill_id: hit_08
|
| 334 |
+
drill_review: reference_comparison_only
|
| 335 |
+
below:
|
| 336 |
+
meaning: torso_inclination_at_contact_below
|
| 337 |
+
result_text:
|
| 338 |
+
satisfactory: Your torso lean at contact was below the reference range.
|
| 339 |
+
off_target: Your torso lean at contact was below the reference range.
|
| 340 |
+
headline: Your torso lean at contact was below the reference range.
|
| 341 |
+
coach_message: Your torso lean at contact was below the reference range. Use a comfortable swing and keep the movement
|
| 342 |
+
repeatable.
|
| 343 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 344 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 345 |
+
drill_id: hit_08
|
| 346 |
+
drill_review: reference_comparison_only
|
| 347 |
+
maintain:
|
| 348 |
+
coach_message: Your torso lean at contact was within the reference range. Keep your movement smooth and repeatable.
|
| 349 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 350 |
+
drill_id: hit_08
|
| 351 |
+
drill_review: reference_comparison_only
|
| 352 |
+
- metric_id: shoulder_rotation_after_contact
|
| 353 |
+
display_name: Early Follow-Through Shoulder Turn
|
| 354 |
+
group: contact_follow_through
|
| 355 |
+
unit: deg
|
| 356 |
+
reference: absolute_net_horizontal_rotation
|
| 357 |
+
start_event_id: contact
|
| 358 |
+
end_event_id: follow_through
|
| 359 |
+
mirror_for_left: false
|
| 360 |
+
what_it_means: How far your shoulders turn during the first tenth of a second after contact.
|
| 361 |
+
in_range_text: Your shoulder turn just after contact was within the reference range.
|
| 362 |
+
directions:
|
| 363 |
+
above:
|
| 364 |
+
meaning: shoulder_rotation_after_contact_above
|
| 365 |
+
result_text:
|
| 366 |
+
satisfactory: Your shoulder turn just after contact was above the reference range.
|
| 367 |
+
off_target: Your shoulder turn just after contact was above the reference range.
|
| 368 |
+
headline: Your shoulder turn just after contact was above the reference range.
|
| 369 |
+
coach_message: Your shoulder turn just after contact was above the reference range. Use a comfortable swing and
|
| 370 |
+
keep the movement repeatable.
|
| 371 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 372 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 373 |
+
drill_id: hit_08
|
| 374 |
+
drill_review: reference_comparison_only
|
| 375 |
+
below:
|
| 376 |
+
meaning: shoulder_rotation_after_contact_below
|
| 377 |
+
result_text:
|
| 378 |
+
satisfactory: Your shoulder turn just after contact was below the reference range.
|
| 379 |
+
off_target: Your shoulder turn just after contact was below the reference range.
|
| 380 |
+
headline: Your shoulder turn just after contact was below the reference range.
|
| 381 |
+
coach_message: Your shoulder turn just after contact was below the reference range. Use a comfortable swing and
|
| 382 |
+
keep the movement repeatable.
|
| 383 |
+
coach_tip: Practice a comfortable, repeatable swing.
|
| 384 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 385 |
+
drill_id: hit_08
|
| 386 |
+
drill_review: reference_comparison_only
|
| 387 |
+
maintain:
|
| 388 |
+
coach_message: Your shoulder turn just after contact was within the reference range. Keep your movement smooth and
|
| 389 |
+
repeatable.
|
| 390 |
+
practice_feel: Keep your movement smooth and comfortable.
|
| 391 |
+
drill_id: hit_08
|
| 392 |
+
drill_review: reference_comparison_only
|
| 393 |
+
|
| 394 |
# The practice suggestion when nothing in the swing could be rated, so the player always has a drill.
|
| 395 |
general_focus:
|
| 396 |
display_name: General practice
|
|
|
|
| 444 |
limitation: The movement did not line up from frame to frame, so treat this as approximate.
|
| 445 |
report: The movement did not line up from frame to frame, so some results are approximate.
|
| 446 |
|
| 447 |
+
capture_time_unknown:
|
| 448 |
+
limitation: We do not know the true speed of this clip.
|
| 449 |
+
report: We do not know the true clip speed, so we cannot time the finish.
|
| 450 |
+
follow_through_not_recorded:
|
| 451 |
+
limitation: The clip ends too soon after the hit.
|
| 452 |
+
report: The clip ends too soon for us to check the turn after the hit.
|
| 453 |
+
model_accuracy_unvalidated:
|
| 454 |
+
limitation: Body points are estimates. We have not checked them against true body positions.
|
| 455 |
+
report: Scores come from estimated body points. Treat them as rough guides.
|
| 456 |
+
|
| 457 |
# data_quality notes the coach adds itself (not from the payload).
|
| 458 |
notes:
|
| 459 |
level_assumed:
|
AI-coach-agent/src/ai_coach/swing_report/schemas.py
CHANGED
|
@@ -11,8 +11,8 @@ from typing import Annotated, Literal
|
|
| 11 |
|
| 12 |
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
|
| 13 |
|
| 14 |
-
SCHEMA_VERSION = "1.
|
| 15 |
-
MEASUREMENT_DEFINITIONS_VERSION = "1.
|
| 16 |
REPORT_SCHEMA_VERSION = "1.0"
|
| 17 |
|
| 18 |
Side = Literal["left", "right"]
|
|
@@ -20,21 +20,28 @@ PracticeType = Literal["tee", "front_toss", "side_toss", "pitching_machine", "li
|
|
| 20 |
MeasurementGroup = Literal["balance_load", "stride", "power_move", "contact_follow_through"]
|
| 21 |
ResultStatus = Literal["available", "limited", "unavailable"]
|
| 22 |
MeasurementUnit = Literal["deg", "cm"]
|
| 23 |
-
EventId = Literal["stride_start", "front_foot_down", "contact"]
|
| 24 |
-
EventSource = Literal["manual_review", "pose_estimated", "bat_ball_detector"]
|
| 25 |
-
MetricId = Literal["hip_shoulder_separation_at_foot_down", "stride_relative_length", "hip_shoulder_separation_at_contact"
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
ReasonCode = Literal[
|
| 28 |
"contact_not_verified", "contact_not_applicable", "event_not_detected", "event_timing_uncertain",
|
| 29 |
"required_event_unavailable", "required_event_limited", "lead_foot_unknown", "required_landmarks_unusable",
|
| 30 |
"ground_plane_unknown", "scale_is_model_estimated", "scale_unknown", "excessive_interpolation",
|
| 31 |
-
"occlusion_unresolved", "temporal_inconsistency",
|
|
|
|
| 32 |
] # fmt: skip
|
| 33 |
|
| 34 |
GROUP_ORDER: tuple[str, ...] = ("balance_load", "stride", "power_move", "contact_follow_through")
|
| 35 |
EVENT_IDS: tuple[str, ...] = ("stride_start", "front_foot_down", "contact")
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
| 38 |
|
| 39 |
NonEmptyStr = Annotated[str, StringConstraints(min_length=1, pattern=r"\S")]
|
| 40 |
|
|
@@ -62,12 +69,20 @@ class SwingEvent(_Input):
|
|
| 62 |
capture_time_s: float | None
|
| 63 |
source: EventSource | None
|
| 64 |
reasons: list[ReasonCode] = Field(default_factory=list) # optional only for available events
|
|
|
|
| 65 |
|
| 66 |
|
| 67 |
class Events(_Input):
|
| 68 |
stride_start: SwingEvent
|
| 69 |
front_foot_down: SwingEvent
|
| 70 |
contact: SwingEvent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
|
| 73 |
class ApprovedBenchmark(_Input):
|
|
@@ -94,17 +109,18 @@ class Measurement(_Input):
|
|
| 94 |
uses_interpolated_input: bool
|
| 95 |
reasons: list[ReasonCode]
|
| 96 |
benchmark: ApprovedBenchmark | None
|
|
|
|
| 97 |
|
| 98 |
|
| 99 |
class SwingAnalysisPayload(_Input):
|
| 100 |
-
schema_version: Literal["1.0"]
|
| 101 |
analysis_id: NonEmptyStr
|
| 102 |
analysis_revision: int = Field(ge=1)
|
| 103 |
swing_id: NonEmptyStr
|
| 104 |
status: Literal["completed"]
|
| 105 |
athlete: Athlete
|
| 106 |
context: SwingContext
|
| 107 |
-
measurement_definitions_version: Literal["1.0"]
|
| 108 |
events: Events
|
| 109 |
measurements: list[Measurement] = Field(min_length=1)
|
| 110 |
|
|
@@ -199,6 +215,8 @@ class MeasurementReport(_Output):
|
|
| 199 |
result_text: str | None
|
| 200 |
coach_tip: str | None
|
| 201 |
limitations: list[Limitation]
|
|
|
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
class DataQualityNote(_Output):
|
|
|
|
| 11 |
|
| 12 |
from pydantic import BaseModel, ConfigDict, Field, StringConstraints
|
| 13 |
|
| 14 |
+
SCHEMA_VERSION = "1.1"
|
| 15 |
+
MEASUREMENT_DEFINITIONS_VERSION = "1.1"
|
| 16 |
REPORT_SCHEMA_VERSION = "1.0"
|
| 17 |
|
| 18 |
Side = Literal["left", "right"]
|
|
|
|
| 20 |
MeasurementGroup = Literal["balance_load", "stride", "power_move", "contact_follow_through"]
|
| 21 |
ResultStatus = Literal["available", "limited", "unavailable"]
|
| 22 |
MeasurementUnit = Literal["deg", "cm"]
|
| 23 |
+
EventId = Literal["stride_start", "front_foot_down", "contact", "follow_through"]
|
| 24 |
+
EventSource = Literal["manual_review", "pose_estimated", "bat_ball_detector", "derived_from_contact"]
|
| 25 |
+
MetricId = Literal["hip_shoulder_separation_at_foot_down", "stride_relative_length", "hip_shoulder_separation_at_contact",
|
| 26 |
+
"torso_inclination_at_stride_start", "hip_shoulder_separation_at_stride_start",
|
| 27 |
+
"pelvis_rotation_to_contact", "lead_knee_extension_to_contact", "torso_inclination_at_contact",
|
| 28 |
+
"shoulder_rotation_after_contact"]
|
| 29 |
+
MeasurementReference = Literal["signed_horizontal_shoulder_minus_hip_heading", "lead_ankle_displacement_relative_to_rear_ankle",
|
| 30 |
+
"torso_angle_from_vertical", "absolute_net_horizontal_rotation", "change_in_3d_lead_knee_angle"]
|
| 31 |
ReasonCode = Literal[
|
| 32 |
"contact_not_verified", "contact_not_applicable", "event_not_detected", "event_timing_uncertain",
|
| 33 |
"required_event_unavailable", "required_event_limited", "lead_foot_unknown", "required_landmarks_unusable",
|
| 34 |
"ground_plane_unknown", "scale_is_model_estimated", "scale_unknown", "excessive_interpolation",
|
| 35 |
+
"occlusion_unresolved", "temporal_inconsistency", "capture_time_unknown", "follow_through_not_recorded",
|
| 36 |
+
"model_accuracy_unvalidated",
|
| 37 |
] # fmt: skip
|
| 38 |
|
| 39 |
GROUP_ORDER: tuple[str, ...] = ("balance_load", "stride", "power_move", "contact_follow_through")
|
| 40 |
EVENT_IDS: tuple[str, ...] = ("stride_start", "front_foot_down", "contact")
|
| 41 |
+
LEGACY_METRIC_IDS = ("hip_shoulder_separation_at_foot_down", "stride_relative_length", "hip_shoulder_separation_at_contact")
|
| 42 |
+
METRIC_IDS: tuple[str, ...] = (*LEGACY_METRIC_IDS, "torso_inclination_at_stride_start",
|
| 43 |
+
"hip_shoulder_separation_at_stride_start", "pelvis_rotation_to_contact", "lead_knee_extension_to_contact",
|
| 44 |
+
"torso_inclination_at_contact", "shoulder_rotation_after_contact")
|
| 45 |
|
| 46 |
NonEmptyStr = Annotated[str, StringConstraints(min_length=1, pattern=r"\S")]
|
| 47 |
|
|
|
|
| 69 |
capture_time_s: float | None
|
| 70 |
source: EventSource | None
|
| 71 |
reasons: list[ReasonCode] = Field(default_factory=list) # optional only for available events
|
| 72 |
+
source_frame_index: int | None = Field(default=None, ge=0)
|
| 73 |
|
| 74 |
|
| 75 |
class Events(_Input):
|
| 76 |
stride_start: SwingEvent
|
| 77 |
front_foot_down: SwingEvent
|
| 78 |
contact: SwingEvent
|
| 79 |
+
follow_through: SwingEvent | None = None
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ValueInterval(_Input):
|
| 83 |
+
lower: float
|
| 84 |
+
upper: float
|
| 85 |
+
source: Literal["adjacent_event_frames"]
|
| 86 |
|
| 87 |
|
| 88 |
class ApprovedBenchmark(_Input):
|
|
|
|
| 109 |
uses_interpolated_input: bool
|
| 110 |
reasons: list[ReasonCode]
|
| 111 |
benchmark: ApprovedBenchmark | None
|
| 112 |
+
value_interval: ValueInterval | None = None
|
| 113 |
|
| 114 |
|
| 115 |
class SwingAnalysisPayload(_Input):
|
| 116 |
+
schema_version: Literal["1.0", "1.1"]
|
| 117 |
analysis_id: NonEmptyStr
|
| 118 |
analysis_revision: int = Field(ge=1)
|
| 119 |
swing_id: NonEmptyStr
|
| 120 |
status: Literal["completed"]
|
| 121 |
athlete: Athlete
|
| 122 |
context: SwingContext
|
| 123 |
+
measurement_definitions_version: Literal["1.0", "1.1"]
|
| 124 |
events: Events
|
| 125 |
measurements: list[Measurement] = Field(min_length=1)
|
| 126 |
|
|
|
|
| 215 |
result_text: str | None
|
| 216 |
coach_tip: str | None
|
| 217 |
limitations: list[Limitation]
|
| 218 |
+
value_interval: Interval | None = None
|
| 219 |
+
score_interval: Interval | None = None
|
| 220 |
|
| 221 |
|
| 222 |
class DataQualityNote(_Output):
|
AI-coach-agent/src/ai_coach/swing_report/service.py
CHANGED
|
@@ -13,7 +13,7 @@ from typing import Any, Literal
|
|
| 13 |
|
| 14 |
from ..config import Settings, get_settings
|
| 15 |
from . import repository as repo
|
| 16 |
-
from .schemas import REPORT_SCHEMA_VERSION,
|
| 17 |
from .scoring import NOT_RATED, ON_TARGET, RATING_LABELS, mean_score, rating_for, round_half_up, score, side_of
|
| 18 |
from .text import PROMPT_VERSION, Generator, model_facts, write_texts
|
| 19 |
from .validation import validate_payload
|
|
@@ -71,6 +71,9 @@ def _rate_measurement(metric: dict, m, hand: str | None, athlete: AthleteContext
|
|
| 71 |
"score": None, "rating": NOT_RATED, "rating_label": "", "rating_is_tentative": False, "not_rated_reason": None,
|
| 72 |
"benchmark": None, "what_it_means": metric["what_it_means"], "result_text": None, "coach_tip": None,
|
| 73 |
"limitations": [{"code": r, "text": repo.reason_text(r)["limitation"]} for r in dict.fromkeys(m.reasons)],
|
|
|
|
|
|
|
|
|
|
| 74 |
}
|
| 75 |
side = None
|
| 76 |
if m.status == "unavailable" or m.value is None:
|
|
@@ -83,6 +86,12 @@ def _rate_measurement(metric: dict, m, hand: str | None, athlete: AthleteContext
|
|
| 83 |
out["score"] = score(m.value, b.on_lower, b.on_upper, b.sat_lower, b.sat_upper)
|
| 84 |
out["rating"] = rating_for(out["score"])
|
| 85 |
out["rating_is_tentative"] = m.status == "limited"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
raw_side = side_of(m.value, b.on_lower, b.on_upper)
|
| 87 |
# Coaching direction is normalised: mirrored metrics flip for left-handed hitters (see swing_metrics.yaml).
|
| 88 |
if raw_side and metric["mirror_for_left"] and hand == "left":
|
|
@@ -115,12 +124,16 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 115 |
athlete = athlete or AthleteContext()
|
| 116 |
settings = settings or get_settings()
|
| 117 |
hand, hand_inferred = resolve_batting_hand(parsed, athlete)
|
|
|
|
|
|
|
| 118 |
notes: list[str] = []
|
| 119 |
|
| 120 |
measurements: list[dict] = []
|
| 121 |
sides: dict[str, str | None] = {}
|
| 122 |
for metric in repo.metrics():
|
| 123 |
m = parsed.measurement(metric["metric_id"])
|
|
|
|
|
|
|
| 124 |
out, sides[metric["metric_id"]] = _rate_measurement(metric, m, hand, athlete, notes)
|
| 125 |
measurements.append(out)
|
| 126 |
by_id = {m["metric_id"]: m for m in measurements}
|
|
@@ -148,7 +161,23 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 148 |
})
|
| 149 |
overall = mean_score(g["score"] for g in groups)
|
| 150 |
overall_tentative = any(g["score_is_tentative"] for g in groups if g["score"] is not None)
|
| 151 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 152 |
|
| 153 |
# Rules text for every field, then the subset the model may reword.
|
| 154 |
rules: dict[str, str | None] = {}
|
|
@@ -156,6 +185,16 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 156 |
tips_wanted: set[str] = set()
|
| 157 |
for m in measurements:
|
| 158 |
result_text, tip = _rules_result(repo.metric_info(m["metric_id"]), m["rating"], sides[m["metric_id"]])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
m["result_text"], m["coach_tip"] = result_text, tip
|
| 160 |
findings[m["metric_id"]] = result_text
|
| 161 |
if result_text is not None:
|
|
@@ -177,6 +216,8 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 177 |
headline = repo.text("headline_all_on_target")
|
| 178 |
else:
|
| 179 |
headline = repo.text("headline_nothing_rated")
|
|
|
|
|
|
|
| 180 |
if overall_tentative and focus["kind"] != "general":
|
| 181 |
headline = f"{headline} {repo.text('headline_tentative')}"
|
| 182 |
rules["coach_message"] = focus["coach_message"]
|
|
@@ -189,9 +230,24 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 189 |
"data_quality": _data_quality(parsed, measurements, notes, hand, hand_inferred),
|
| 190 |
}
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
if any(k.startswith("result:") for k in rules): # something rated: let the model word it
|
| 193 |
rules["headline"] = headline
|
| 194 |
facts = model_facts(report, findings, subjects, tips_wanted, groups_wanted)
|
|
|
|
|
|
|
| 195 |
result = write_texts(facts, rules, settings, generator=generator, request_id=request_id)
|
| 196 |
texts = result.texts
|
| 197 |
report["overview"]["headline"] = texts["headline"]
|
|
@@ -210,7 +266,7 @@ def build_report(payload: dict, athlete: AthleteContext | None = None, *, settin
|
|
| 210 |
report["meta"] = {
|
| 211 |
"generated_at": (now or datetime.now(UTC)).astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 212 |
"request_id": request_id, **text_meta, "prompt_version": PROMPT_VERSION,
|
| 213 |
-
"input_schema_version":
|
| 214 |
"benchmark_registry_version": repo.benchmark_version(), "coaching_rules_version": repo.coaching_rules_version(),
|
| 215 |
}
|
| 216 |
return SwingReport.model_validate(report).model_dump(mode="json")
|
|
@@ -263,7 +319,11 @@ def _rules_group_summary(g: dict, by_id: dict[str, dict]) -> str:
|
|
| 263 |
if reason == "no_rated_measurements":
|
| 264 |
return repo.text("group_not_rated")
|
| 265 |
if g["rating"] == ON_TARGET:
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
rated = [m for m in members if m["score"] is not None]
|
| 268 |
worst = min(rated, key=lambda m: m["score"])
|
| 269 |
return worst["result_text"] or repo.text("group_on_target")
|
|
|
|
| 13 |
|
| 14 |
from ..config import Settings, get_settings
|
| 15 |
from . import repository as repo
|
| 16 |
+
from .schemas import REPORT_SCHEMA_VERSION, SwingAnalysisPayload, SwingReport
|
| 17 |
from .scoring import NOT_RATED, ON_TARGET, RATING_LABELS, mean_score, rating_for, round_half_up, score, side_of
|
| 18 |
from .text import PROMPT_VERSION, Generator, model_facts, write_texts
|
| 19 |
from .validation import validate_payload
|
|
|
|
| 71 |
"score": None, "rating": NOT_RATED, "rating_label": "", "rating_is_tentative": False, "not_rated_reason": None,
|
| 72 |
"benchmark": None, "what_it_means": metric["what_it_means"], "result_text": None, "coach_tip": None,
|
| 73 |
"limitations": [{"code": r, "text": repo.reason_text(r)["limitation"]} for r in dict.fromkeys(m.reasons)],
|
| 74 |
+
"value_interval": None if m.value_interval is None else {
|
| 75 |
+
"lower": m.value_interval.lower, "upper": m.value_interval.upper},
|
| 76 |
+
"score_interval": None,
|
| 77 |
}
|
| 78 |
side = None
|
| 79 |
if m.status == "unavailable" or m.value is None:
|
|
|
|
| 86 |
out["score"] = score(m.value, b.on_lower, b.on_upper, b.sat_lower, b.sat_upper)
|
| 87 |
out["rating"] = rating_for(out["score"])
|
| 88 |
out["rating_is_tentative"] = m.status == "limited"
|
| 89 |
+
if m.value_interval is not None:
|
| 90 |
+
low, high = m.value_interval.lower, m.value_interval.upper
|
| 91 |
+
candidates = [low, high, m.value]
|
| 92 |
+
candidates += [v for v in (b.on_lower, b.on_upper, b.sat_lower, b.sat_upper) if low <= v <= high]
|
| 93 |
+
scores = [score(v, b.on_lower, b.on_upper, b.sat_lower, b.sat_upper) for v in candidates]
|
| 94 |
+
out["score_interval"] = {"lower": min(scores), "upper": max(scores)}
|
| 95 |
raw_side = side_of(m.value, b.on_lower, b.on_upper)
|
| 96 |
# Coaching direction is normalised: mirrored metrics flip for left-handed hitters (see swing_metrics.yaml).
|
| 97 |
if raw_side and metric["mirror_for_left"] and hand == "left":
|
|
|
|
| 124 |
athlete = athlete or AthleteContext()
|
| 125 |
settings = settings or get_settings()
|
| 126 |
hand, hand_inferred = resolve_batting_hand(parsed, athlete)
|
| 127 |
+
hand_conflict = bool(parsed.athlete.batting_hand and athlete.batting_hand and
|
| 128 |
+
parsed.athlete.batting_hand != athlete.batting_hand)
|
| 129 |
notes: list[str] = []
|
| 130 |
|
| 131 |
measurements: list[dict] = []
|
| 132 |
sides: dict[str, str | None] = {}
|
| 133 |
for metric in repo.metrics():
|
| 134 |
m = parsed.measurement(metric["metric_id"])
|
| 135 |
+
if m is None:
|
| 136 |
+
continue # old payloads do not acquire invented new measurements
|
| 137 |
out, sides[metric["metric_id"]] = _rate_measurement(metric, m, hand, athlete, notes)
|
| 138 |
measurements.append(out)
|
| 139 |
by_id = {m["metric_id"]: m for m in measurements}
|
|
|
|
| 161 |
})
|
| 162 |
overall = mean_score(g["score"] for g in groups)
|
| 163 |
overall_tentative = any(g["score_is_tentative"] for g in groups if g["score"] is not None)
|
| 164 |
+
context_unverified = parsed.context.practice_type in ("unknown", "dry_swing")
|
| 165 |
+
sensitive = {m["metric_id"] for m in measurements if m["score_interval"] is not None and (
|
| 166 |
+
m["score_interval"]["upper"] - m["score_interval"]["lower"] >= 20 or
|
| 167 |
+
rating_for(m["score_interval"]["lower"]) != rating_for(m["score_interval"]["upper"]))}
|
| 168 |
+
eligible = [] if context_unverified or hand_conflict else [m for m in measurements if m["metric_id"] not in sensitive]
|
| 169 |
+
focus = _choose_focus(eligible, sides)
|
| 170 |
+
if focus["kind"] == "maintain" and any(m["metric_id"] in sensitive and m["rating"] != ON_TARGET for m in measurements):
|
| 171 |
+
focus = _choose_focus([], sides)
|
| 172 |
+
if hand_conflict:
|
| 173 |
+
focus["coach_message"] = "The swing and profile list different batting sides. Check the side before using these scores to change your swing."
|
| 174 |
+
elif context_unverified:
|
| 175 |
+
focus["coach_message"] = "These results describe your measured movement. The drill context does not support a technique correction."
|
| 176 |
+
focus["practice_feel"] = "Keep your practice comfortable and repeatable."
|
| 177 |
+
elif sensitive and focus["kind"] == "general":
|
| 178 |
+
focus["coach_message"] = "The results change with the marked swing moments. Treat them as approximate before changing your swing."
|
| 179 |
+
if focus["is_tentative"]:
|
| 180 |
+
focus["coach_message"] = "This result is an estimate. " + focus["coach_message"]
|
| 181 |
|
| 182 |
# Rules text for every field, then the subset the model may reword.
|
| 183 |
rules: dict[str, str | None] = {}
|
|
|
|
| 185 |
tips_wanted: set[str] = set()
|
| 186 |
for m in measurements:
|
| 187 |
result_text, tip = _rules_result(repo.metric_info(m["metric_id"]), m["rating"], sides[m["metric_id"]])
|
| 188 |
+
if context_unverified or hand_conflict or m["metric_id"] in sensitive:
|
| 189 |
+
tip = None
|
| 190 |
+
if m["score"] is not None:
|
| 191 |
+
subject = m["display_name"].lower()
|
| 192 |
+
b = m["benchmark"]["on_target"]
|
| 193 |
+
position = "within" if b["lower"] <= m["value"] <= b["upper"] else (
|
| 194 |
+
"above" if m["value"] > b["upper"] else "below")
|
| 195 |
+
result_text = f"Your estimated {subject} was {position} the reference range."
|
| 196 |
+
elif result_text is not None and m["rating_is_tentative"]:
|
| 197 |
+
result_text = "This result is approximate. " + result_text
|
| 198 |
m["result_text"], m["coach_tip"] = result_text, tip
|
| 199 |
findings[m["metric_id"]] = result_text
|
| 200 |
if result_text is not None:
|
|
|
|
| 216 |
headline = repo.text("headline_all_on_target")
|
| 217 |
else:
|
| 218 |
headline = repo.text("headline_nothing_rated")
|
| 219 |
+
if any(m["score"] is not None for m in measurements):
|
| 220 |
+
headline = "Your results are reference comparisons. There is not enough evidence to choose a technique correction."
|
| 221 |
if overall_tentative and focus["kind"] != "general":
|
| 222 |
headline = f"{headline} {repo.text('headline_tentative')}"
|
| 223 |
rules["coach_message"] = focus["coach_message"]
|
|
|
|
| 230 |
"data_quality": _data_quality(parsed, measurements, notes, hand, hand_inferred),
|
| 231 |
}
|
| 232 |
|
| 233 |
+
if context_unverified:
|
| 234 |
+
report["data_quality"].append({"code": "practice_context_unverified", "severity": "warning",
|
| 235 |
+
"text": "The drill context does not match a verified reference task. Scores are comparisons, not technique diagnoses."})
|
| 236 |
+
if hand_conflict:
|
| 237 |
+
report["data_quality"].append({"code": "batting_hand_conflict", "severity": "warning",
|
| 238 |
+
"text": "The analysis and athlete profile list different batting sides. Scores use the analysis side; verify it before interpreting them."})
|
| 239 |
+
if sensitive:
|
| 240 |
+
report["data_quality"].append({"code": "event_sensitive_scores", "severity": "warning",
|
| 241 |
+
"text": "Some ratings change when an event moves by one frame. Score ranges show that sensitivity, not total measurement error."})
|
| 242 |
+
if len([g for g in groups if g["score"] is not None]) < len(groups):
|
| 243 |
+
report["data_quality"].append({"code": "partial_group_coverage", "severity": "warning",
|
| 244 |
+
"text": "The overall score uses only groups with scored measurements. It is not a complete assessment of every swing phase."})
|
| 245 |
+
|
| 246 |
if any(k.startswith("result:") for k in rules): # something rated: let the model word it
|
| 247 |
rules["headline"] = headline
|
| 248 |
facts = model_facts(report, findings, subjects, tips_wanted, groups_wanted)
|
| 249 |
+
facts["practice_type"] = parsed.context.practice_type
|
| 250 |
+
facts["technique_correction_supported"] = not context_unverified and not hand_conflict and focus["kind"] != "general"
|
| 251 |
result = write_texts(facts, rules, settings, generator=generator, request_id=request_id)
|
| 252 |
texts = result.texts
|
| 253 |
report["overview"]["headline"] = texts["headline"]
|
|
|
|
| 266 |
report["meta"] = {
|
| 267 |
"generated_at": (now or datetime.now(UTC)).astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
| 268 |
"request_id": request_id, **text_meta, "prompt_version": PROMPT_VERSION,
|
| 269 |
+
"input_schema_version": parsed.schema_version, "measurement_definitions_version": parsed.measurement_definitions_version,
|
| 270 |
"benchmark_registry_version": repo.benchmark_version(), "coaching_rules_version": repo.coaching_rules_version(),
|
| 271 |
}
|
| 272 |
return SwingReport.model_validate(report).model_dump(mode="json")
|
|
|
|
| 319 |
if reason == "no_rated_measurements":
|
| 320 |
return repo.text("group_not_rated")
|
| 321 |
if g["rating"] == ON_TARGET:
|
| 322 |
+
rated = [m for m in members if m["score"] is not None]
|
| 323 |
+
if len(rated) == 1:
|
| 324 |
+
return rated[0]["result_text"]
|
| 325 |
+
qualifier = "estimated " if g["score_is_tentative"] else ""
|
| 326 |
+
return f"These {qualifier}results were in the usual range for the measured moves."
|
| 327 |
rated = [m for m in members if m["score"] is not None]
|
| 328 |
worst = min(rated, key=lambda m: m["score"])
|
| 329 |
return worst["result_text"] or repo.text("group_on_target")
|
AI-coach-agent/src/ai_coach/swing_report/text.py
CHANGED
|
@@ -40,6 +40,13 @@ Rules for every string you write:
|
|
| 40 |
measurements, contact, injuries, pain, health advice, scores or promises of improvement.
|
| 41 |
- Do not use judgement words such as good, bad, great, perfect, poor, wrong or mistake.
|
| 42 |
- Keep each finding's meaning exactly. For on_target results say the movement is in the typical range.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
Fields:
|
| 45 |
- headline: at most twenty-five words. If the focus kind is "fix", name the focus group as the area to work on and say
|
|
@@ -125,7 +132,7 @@ def gemini_generator(settings: Settings) -> Generator:
|
|
| 125 |
response = client.models.generate_content(
|
| 126 |
model=settings.model, contents=prompt,
|
| 127 |
config=types.GenerateContentConfig(
|
| 128 |
-
temperature=settings.temperature, max_output_tokens=max(settings.max_output_tokens,
|
| 129 |
response_mime_type="application/json", response_json_schema=schema, thinking_config=thinking),
|
| 130 |
)
|
| 131 |
u = response.usage_metadata
|
|
@@ -204,7 +211,40 @@ def _parse(raw: str, rules: dict[str, str | None], facts: dict) -> dict[str, str
|
|
| 204 |
return out
|
| 205 |
|
| 206 |
|
| 207 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
texts: dict[str, str | None] = {}
|
| 209 |
used, rejected = 0, {}
|
| 210 |
for key, rule_text in rules.items():
|
|
@@ -213,6 +253,10 @@ def _merge(candidate: dict[str, str], rules: dict[str, str | None]) -> tuple[dic
|
|
| 213 |
texts[key] = None # nothing is wanted here (e.g. no tip for an on-target measurement)
|
| 214 |
continue
|
| 215 |
problems = check_text(text, _kind(key)) if text is not None else ["missing"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 216 |
if problems:
|
| 217 |
texts[key] = rule_text
|
| 218 |
rejected[key] = problems
|
|
@@ -234,6 +278,9 @@ def write_texts(facts: dict, rules: dict[str, str | None], settings: Settings, *
|
|
| 234 |
|
| 235 |
`rules` holds the fixed-rule text for each field the model may write; `facts` is what the model sees.
|
| 236 |
"""
|
|
|
|
|
|
|
|
|
|
| 237 |
if generator is None and not settings.llm_enabled:
|
| 238 |
return TextResult(dict(rules), "rules", fallback_reason="llm_not_configured")
|
| 239 |
generate = generator or gemini_generator(settings)
|
|
@@ -244,7 +291,7 @@ def write_texts(facts: dict, rules: dict[str, str | None], settings: Settings, *
|
|
| 244 |
request_id = request_id or uuid.uuid4().hex[:12]
|
| 245 |
|
| 246 |
def finish(raw: str, cache_hit: bool) -> TextResult:
|
| 247 |
-
texts, used, rejected = _merge(_parse(raw, rules, facts), rules)
|
| 248 |
if rejected:
|
| 249 |
log.info("swing report text: %d field(s) replaced by rules: %s", len(rejected), rejected)
|
| 250 |
source = "llm" if not rejected else ("rules" if used == 0 else "mixed")
|
|
@@ -302,7 +349,8 @@ def model_facts(report: dict[str, Any], findings: dict[str, str | None], subject
|
|
| 302 |
for m in report["measurements"] if m["rating"] != "not_rated"
|
| 303 |
]
|
| 304 |
groups = [
|
| 305 |
-
{"group": g["group"], "name":
|
|
|
|
| 306 |
for g in report["groups"] if g["group"] in groups_wanted
|
| 307 |
]
|
| 308 |
focus = report.get("focus_area")
|
|
|
|
| 40 |
measurements, contact, injuries, pain, health advice, scores or promises of improvement.
|
| 41 |
- Do not use judgement words such as good, bad, great, perfect, poor, wrong or mistake.
|
| 42 |
- Keep each finding's meaning exactly. For on_target results say the movement is in the typical range.
|
| 43 |
+
- A group name is a navigation label, not evidence that every part of that group was measured. Discuss only the
|
| 44 |
+
listed metric_ids. Only shoulder_rotation_after_contact measures any follow-through, and only its early shoulder turn.
|
| 45 |
+
- Preserve uncertainty: every approximate finding and group summary must say estimated, approximate or uncertain.
|
| 46 |
+
- When technique_correction_supported is false, describe the reference comparison without telling the player to
|
| 47 |
+
shorten, lengthen or change their mechanics. Do not diagnose a drill-specific movement as a fault.
|
| 48 |
+
- No claims about power, energy, force, bat speed, ball flight or the quality of the whole swing.
|
| 49 |
+
- A single hip-shoulder angle does not establish when the shoulders began opening. Do not call it early or late.
|
| 50 |
|
| 51 |
Fields:
|
| 52 |
- headline: at most twenty-five words. If the focus kind is "fix", name the focus group as the area to work on and say
|
|
|
|
| 132 |
response = client.models.generate_content(
|
| 133 |
model=settings.model, contents=prompt,
|
| 134 |
config=types.GenerateContentConfig(
|
| 135 |
+
temperature=settings.temperature, max_output_tokens=max(settings.max_output_tokens, 3000),
|
| 136 |
response_mime_type="application/json", response_json_schema=schema, thinking_config=thinking),
|
| 137 |
)
|
| 138 |
u = response.usage_metadata
|
|
|
|
| 211 |
return out
|
| 212 |
|
| 213 |
|
| 214 |
+
def semantic_problems(text: str, key: str, facts: dict) -> list[str]:
|
| 215 |
+
"""Reject known scope/rating/uncertainty violations before wording reaches a player."""
|
| 216 |
+
rows = {m["metric_id"]: m for m in facts.get("measurements", [])}
|
| 217 |
+
group = next((g for g in facts.get("groups", []) if key == "group:" + g["group"]), None)
|
| 218 |
+
ids = group["metric_ids"] if group else ([key.split(":", 1)[1]] if key.startswith(("result:", "tip:")) else list(rows))
|
| 219 |
+
selected = [rows[k] for k in ids if k in rows]
|
| 220 |
+
problems = []
|
| 221 |
+
t = text.lower()
|
| 222 |
+
if re.search(r"follow[ -]?through|finish(?:ing)? (?:position|movement)", t):
|
| 223 |
+
if "shoulder_rotation_after_contact" not in ids:
|
| 224 |
+
problems.append("unmeasured_follow_through")
|
| 225 |
+
elif not re.search(r"early shoulder turn|shoulder turn just after", t) or re.search(r"whole|entire|complete", t):
|
| 226 |
+
problems.append("follow_through_scope_exceeded")
|
| 227 |
+
if re.search(r"\b(?:power|energy|force|exit velocity|bat speed|ball flight|bat path)\b", t):
|
| 228 |
+
problems.append("unsupported_physical_claim")
|
| 229 |
+
if re.search(r"shoulder.*(?:early|late|before.*(?:foot|land))", t):
|
| 230 |
+
problems.append("unsupported_shoulder_timing")
|
| 231 |
+
approximate = any(m.get("approximate") for m in selected)
|
| 232 |
+
if approximate and not key.startswith("tip:") and not re.search(r"\b(?:approximate|estimate[ds]?|uncertain|appears?)\b", t):
|
| 233 |
+
problems.append("uncertainty_removed")
|
| 234 |
+
rating = group["rating"] if group else (selected[0]["rating"] if len(selected) == 1 else None)
|
| 235 |
+
if rating not in (None, "on_target") and re.search(r"typical range|on target|everything.*(?:range|normal)", t):
|
| 236 |
+
problems.append("rating_changed")
|
| 237 |
+
if len(selected) == 1:
|
| 238 |
+
finding = (selected[0].get("finding") or "").lower()
|
| 239 |
+
if ("above the reference" in finding and "below" in t) or ("below the reference" in finding and "above" in t):
|
| 240 |
+
problems.append("direction_changed")
|
| 241 |
+
if facts.get("technique_correction_supported") is False and re.search(
|
| 242 |
+
r"\b(?:shorten|shorter|lengthen|longer|reduce|increase|fix|correct|too long|too short|turn earlier|turn later)\b", t):
|
| 243 |
+
problems.append("unsupported_technique_correction")
|
| 244 |
+
return problems
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _merge(candidate: dict[str, str], rules: dict[str, str | None], facts: dict | None = None) -> tuple[dict[str, str | None], int, dict]:
|
| 248 |
texts: dict[str, str | None] = {}
|
| 249 |
used, rejected = 0, {}
|
| 250 |
for key, rule_text in rules.items():
|
|
|
|
| 253 |
texts[key] = None # nothing is wanted here (e.g. no tip for an on-target measurement)
|
| 254 |
continue
|
| 255 |
problems = check_text(text, _kind(key)) if text is not None else ["missing"]
|
| 256 |
+
if text is not None and facts is not None:
|
| 257 |
+
problems += semantic_problems(text, key, facts)
|
| 258 |
+
if rule_text is None and (text or "").strip():
|
| 259 |
+
problems.append("unrequested_advice")
|
| 260 |
if problems:
|
| 261 |
texts[key] = rule_text
|
| 262 |
rejected[key] = problems
|
|
|
|
| 278 |
|
| 279 |
`rules` holds the fixed-rule text for each field the model may write; `facts` is what the model sees.
|
| 280 |
"""
|
| 281 |
+
if facts.get("technique_correction_supported") is False:
|
| 282 |
+
# An unknown drill or an unstable score does not support free-form technique advice.
|
| 283 |
+
return TextResult(dict(rules), "rules", fallback_reason="insufficient_coaching_context")
|
| 284 |
if generator is None and not settings.llm_enabled:
|
| 285 |
return TextResult(dict(rules), "rules", fallback_reason="llm_not_configured")
|
| 286 |
generate = generator or gemini_generator(settings)
|
|
|
|
| 291 |
request_id = request_id or uuid.uuid4().hex[:12]
|
| 292 |
|
| 293 |
def finish(raw: str, cache_hit: bool) -> TextResult:
|
| 294 |
+
texts, used, rejected = _merge(_parse(raw, rules, facts), rules, facts)
|
| 295 |
if rejected:
|
| 296 |
log.info("swing report text: %d field(s) replaced by rules: %s", len(rejected), rejected)
|
| 297 |
source = "llm" if not rejected else ("rules" if used == 0 else "mixed")
|
|
|
|
| 349 |
for m in report["measurements"] if m["rating"] != "not_rated"
|
| 350 |
]
|
| 351 |
groups = [
|
| 352 |
+
{"group": g["group"], "name": "Measured movements", "rating": g["rating"], "metric_ids": g["metric_ids"],
|
| 353 |
+
"approximate": g["score_is_tentative"]}
|
| 354 |
for g in report["groups"] if g["group"] in groups_wanted
|
| 355 |
]
|
| 356 |
focus = report.get("focus_area")
|
AI-coach-agent/src/ai_coach/swing_report/validation.py
CHANGED
|
@@ -14,8 +14,8 @@ from typing import Any
|
|
| 14 |
from pydantic import ValidationError
|
| 15 |
|
| 16 |
from .schemas import (
|
| 17 |
-
MEASUREMENT_DEFINITIONS_VERSION,
|
| 18 |
METRIC_IDS,
|
|
|
|
| 19 |
SCHEMA_VERSION,
|
| 20 |
Measurement,
|
| 21 |
SwingAnalysisPayload,
|
|
@@ -35,8 +35,21 @@ METRIC_SPECS: dict[str, dict[str, Any]] = {
|
|
| 35 |
"hip_shoulder_separation_at_contact": {
|
| 36 |
"group": "contact_follow_through", "unit": "deg", "reference": "signed_horizontal_shoulder_minus_hip_heading",
|
| 37 |
"event_id": "contact"},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
} # fmt: skip
|
| 39 |
-
SEPARATION_METRICS = ("hip_shoulder_separation_at_foot_down", "hip_shoulder_separation_at_contact"
|
|
|
|
| 40 |
SCOPE_FIELDS = ("event_id", "start_event_id", "end_event_id")
|
| 41 |
USABLE = ("available", "limited")
|
| 42 |
|
|
@@ -61,7 +74,7 @@ def _message(err: dict) -> str:
|
|
| 61 |
if kind == "missing":
|
| 62 |
return "This field is required."
|
| 63 |
if kind == "extra_forbidden":
|
| 64 |
-
return "This field is not part of
|
| 65 |
if kind == "finite_number":
|
| 66 |
return "Must be a finite number."
|
| 67 |
msg = str(err.get("msg", "Invalid value."))
|
|
@@ -73,11 +86,10 @@ def validate_payload(raw: Any) -> tuple[SwingAnalysisPayload | None, Problems]:
|
|
| 73 |
return None, {"payload": "Must be a JSON object."}
|
| 74 |
problems: Problems = {}
|
| 75 |
# Rule 1 first, with a clear message: another version may have a different shape altogether.
|
| 76 |
-
if raw.get("schema_version")
|
| 77 |
-
problems["schema_version"] =
|
| 78 |
-
|
| 79 |
-
problems["measurement_definitions_version"] =
|
| 80 |
-
f'Only measurement definitions version "{MEASUREMENT_DEFINITIONS_VERSION}" is supported.')
|
| 81 |
if problems:
|
| 82 |
return None, problems
|
| 83 |
try:
|
|
@@ -97,6 +109,10 @@ def check_rules(p: SwingAnalysisPayload, problems: Problems) -> None:
|
|
| 97 |
|
| 98 |
events: dict[str, SwingEvent] = {"stride_start": p.events.stride_start, "front_foot_down": p.events.front_foot_down,
|
| 99 |
"contact": p.events.contact}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
# Rule 3: exactly one entry per registered metric.
|
| 102 |
seen: dict[str, int] = {}
|
|
@@ -104,9 +120,12 @@ def check_rules(p: SwingAnalysisPayload, problems: Problems) -> None:
|
|
| 104 |
if m.metric_id in seen:
|
| 105 |
add(f"measurements[{i}].metric_id", "Duplicate metric id: each metric must appear once.")
|
| 106 |
seen.setdefault(m.metric_id, i)
|
| 107 |
-
|
|
|
|
| 108 |
if missing:
|
| 109 |
add("measurements", "Missing measurements: " + ", ".join(missing) + ".")
|
|
|
|
|
|
|
| 110 |
|
| 111 |
# Rules 5, 6 and 8 on events.
|
| 112 |
for name, ev in events.items():
|
|
@@ -134,6 +153,12 @@ def check_rules(p: SwingAnalysisPayload, problems: Problems) -> None:
|
|
| 134 |
add(f"{base}.source", "Pose estimation cannot establish contact.")
|
| 135 |
if ev.source == "bat_ball_detector" and name != "contact":
|
| 136 |
add(f"{base}.source", "The bat-ball detector is valid only for the contact event.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
start, landing, contact = events["stride_start"], events["front_foot_down"], events["contact"]
|
| 139 |
if (start.status in USABLE and landing.status in USABLE and start.video_time_s is not None
|
|
@@ -142,6 +167,23 @@ def check_rules(p: SwingAnalysisPayload, problems: Problems) -> None:
|
|
| 142 |
if (landing.status == "available" and contact.status == "available" and landing.video_time_s is not None
|
| 143 |
and contact.video_time_s is not None and landing.video_time_s > contact.video_time_s):
|
| 144 |
add("events.front_foot_down.video_time_s", "Must be before contact when both are available.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
for i, m in enumerate(p.measurements):
|
| 147 |
_check_measurement(i, m, events, p, add)
|
|
@@ -178,6 +220,9 @@ def _check_measurement(i: int, m: Measurement, events: dict[str, SwingEvent], p:
|
|
| 178 |
|
| 179 |
# Rule 7: event quality propagates.
|
| 180 |
for event_id in required_events(m.metric_id):
|
|
|
|
|
|
|
|
|
|
| 181 |
status = events[event_id].status
|
| 182 |
if status == "unavailable" and m.status != "unavailable":
|
| 183 |
add(f"{base}.status", f"Must be unavailable because {event_id} is unavailable.")
|
|
@@ -190,7 +235,7 @@ def _check_measurement(i: int, m: Measurement, events: dict[str, SwingEvent], p:
|
|
| 190 |
add(f"{base}.status", "Must be unavailable when the scale is unknown.")
|
| 191 |
if "scale_is_model_estimated" in m.reasons and m.status == "unavailable" and m.reasons == ["scale_is_model_estimated"]:
|
| 192 |
add(f"{base}.status", "A model-estimated scale needs status limited, not unavailable.")
|
| 193 |
-
if m.metric_id
|
| 194 |
if p.athlete.lead_foot is None:
|
| 195 |
if m.status != "unavailable":
|
| 196 |
add(f"{base}.status", "Must be unavailable when the lead foot is unknown.")
|
|
@@ -205,6 +250,16 @@ def _check_measurement(i: int, m: Measurement, events: dict[str, SwingEvent], p:
|
|
| 205 |
add(f"{base}.value", "Separation must be from -180 up to but not including 180 degrees.")
|
| 206 |
if m.metric_id == "stride_relative_length" and m.value < 0:
|
| 207 |
add(f"{base}.value", "Stride length must not be negative.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
|
| 209 |
# Rule 11: an optional benchmark must be coherent (the coach uses its own ranges either way).
|
| 210 |
b = m.benchmark
|
|
|
|
| 14 |
from pydantic import ValidationError
|
| 15 |
|
| 16 |
from .schemas import (
|
|
|
|
| 17 |
METRIC_IDS,
|
| 18 |
+
LEGACY_METRIC_IDS,
|
| 19 |
SCHEMA_VERSION,
|
| 20 |
Measurement,
|
| 21 |
SwingAnalysisPayload,
|
|
|
|
| 35 |
"hip_shoulder_separation_at_contact": {
|
| 36 |
"group": "contact_follow_through", "unit": "deg", "reference": "signed_horizontal_shoulder_minus_hip_heading",
|
| 37 |
"event_id": "contact"},
|
| 38 |
+
"torso_inclination_at_stride_start": {"group": "balance_load", "unit": "deg",
|
| 39 |
+
"reference": "torso_angle_from_vertical", "event_id": "stride_start"},
|
| 40 |
+
"hip_shoulder_separation_at_stride_start": {"group": "balance_load", "unit": "deg",
|
| 41 |
+
"reference": "signed_horizontal_shoulder_minus_hip_heading", "event_id": "stride_start"},
|
| 42 |
+
"pelvis_rotation_to_contact": {"group": "power_move", "unit": "deg",
|
| 43 |
+
"reference": "absolute_net_horizontal_rotation", "start_event_id": "front_foot_down", "end_event_id": "contact"},
|
| 44 |
+
"lead_knee_extension_to_contact": {"group": "power_move", "unit": "deg",
|
| 45 |
+
"reference": "change_in_3d_lead_knee_angle", "start_event_id": "front_foot_down", "end_event_id": "contact"},
|
| 46 |
+
"torso_inclination_at_contact": {"group": "contact_follow_through", "unit": "deg",
|
| 47 |
+
"reference": "torso_angle_from_vertical", "event_id": "contact"},
|
| 48 |
+
"shoulder_rotation_after_contact": {"group": "contact_follow_through", "unit": "deg",
|
| 49 |
+
"reference": "absolute_net_horizontal_rotation", "start_event_id": "contact", "end_event_id": "follow_through"},
|
| 50 |
} # fmt: skip
|
| 51 |
+
SEPARATION_METRICS = ("hip_shoulder_separation_at_foot_down", "hip_shoulder_separation_at_contact",
|
| 52 |
+
"hip_shoulder_separation_at_stride_start")
|
| 53 |
SCOPE_FIELDS = ("event_id", "start_event_id", "end_event_id")
|
| 54 |
USABLE = ("available", "limited")
|
| 55 |
|
|
|
|
| 74 |
if kind == "missing":
|
| 75 |
return "This field is required."
|
| 76 |
if kind == "extra_forbidden":
|
| 77 |
+
return "This field is not part of the swing analysis contract."
|
| 78 |
if kind == "finite_number":
|
| 79 |
return "Must be a finite number."
|
| 80 |
msg = str(err.get("msg", "Invalid value."))
|
|
|
|
| 86 |
return None, {"payload": "Must be a JSON object."}
|
| 87 |
problems: Problems = {}
|
| 88 |
# Rule 1 first, with a clear message: another version may have a different shape altogether.
|
| 89 |
+
if raw.get("schema_version") not in ("1.0", SCHEMA_VERSION):
|
| 90 |
+
problems["schema_version"] = 'Supported contract versions are "1.0" and "1.1".'
|
| 91 |
+
elif raw.get("measurement_definitions_version") != raw.get("schema_version"):
|
| 92 |
+
problems["measurement_definitions_version"] = 'Measurement definitions must match contract "1.0" or "1.1".'
|
|
|
|
| 93 |
if problems:
|
| 94 |
return None, problems
|
| 95 |
try:
|
|
|
|
| 109 |
|
| 110 |
events: dict[str, SwingEvent] = {"stride_start": p.events.stride_start, "front_foot_down": p.events.front_foot_down,
|
| 111 |
"contact": p.events.contact}
|
| 112 |
+
if p.events.follow_through is not None:
|
| 113 |
+
events["follow_through"] = p.events.follow_through
|
| 114 |
+
elif p.schema_version == "1.1":
|
| 115 |
+
add("events.follow_through", "Contract 1.1 requires a follow-through event, including an unavailable event.")
|
| 116 |
|
| 117 |
# Rule 3: exactly one entry per registered metric.
|
| 118 |
seen: dict[str, int] = {}
|
|
|
|
| 120 |
if m.metric_id in seen:
|
| 121 |
add(f"measurements[{i}].metric_id", "Duplicate metric id: each metric must appear once.")
|
| 122 |
seen.setdefault(m.metric_id, i)
|
| 123 |
+
expected = LEGACY_METRIC_IDS if p.schema_version == "1.0" else METRIC_IDS
|
| 124 |
+
missing = [k for k in expected if k not in seen]
|
| 125 |
if missing:
|
| 126 |
add("measurements", "Missing measurements: " + ", ".join(missing) + ".")
|
| 127 |
+
if set(seen) - set(expected):
|
| 128 |
+
add("measurements", "Measurements must match the declared contract version.")
|
| 129 |
|
| 130 |
# Rules 5, 6 and 8 on events.
|
| 131 |
for name, ev in events.items():
|
|
|
|
| 153 |
add(f"{base}.source", "Pose estimation cannot establish contact.")
|
| 154 |
if ev.source == "bat_ball_detector" and name != "contact":
|
| 155 |
add(f"{base}.source", "The bat-ball detector is valid only for the contact event.")
|
| 156 |
+
if ev.source == "derived_from_contact" and name != "follow_through":
|
| 157 |
+
add(f"{base}.source", "Only follow-through may be derived from contact.")
|
| 158 |
+
if ev.status == "unavailable" and ev.source_frame_index is not None:
|
| 159 |
+
add(f"{base}.source_frame_index", "An unavailable event cannot have a source frame.")
|
| 160 |
+
if p.schema_version == "1.1" and ev.status in USABLE and ev.source_frame_index is None:
|
| 161 |
+
add(f"{base}.source_frame_index", "Contract 1.1 requires the decoded source frame index.")
|
| 162 |
|
| 163 |
start, landing, contact = events["stride_start"], events["front_foot_down"], events["contact"]
|
| 164 |
if (start.status in USABLE and landing.status in USABLE and start.video_time_s is not None
|
|
|
|
| 167 |
if (landing.status == "available" and contact.status == "available" and landing.video_time_s is not None
|
| 168 |
and contact.video_time_s is not None and landing.video_time_s > contact.video_time_s):
|
| 169 |
add("events.front_foot_down.video_time_s", "Must be before contact when both are available.")
|
| 170 |
+
finish = events.get("follow_through")
|
| 171 |
+
if finish and finish.status in USABLE and (contact.status not in USABLE or
|
| 172 |
+
finish.video_time_s is None or contact.video_time_s is None or finish.video_time_s <= contact.video_time_s):
|
| 173 |
+
add("events.follow_through.video_time_s", "Follow-through must follow usable contact.")
|
| 174 |
+
if p.schema_version == "1.1":
|
| 175 |
+
for earlier, later in (("stride_start", "front_foot_down"), ("front_foot_down", "contact"),
|
| 176 |
+
("contact", "follow_through")):
|
| 177 |
+
a, b = events.get(earlier), events.get(later)
|
| 178 |
+
if a is None or b is None or a.status not in USABLE or b.status not in USABLE:
|
| 179 |
+
continue
|
| 180 |
+
for field in ("source_frame_index", "video_time_s", "capture_time_s"):
|
| 181 |
+
av, bv = getattr(a, field), getattr(b, field)
|
| 182 |
+
if av is not None and bv is not None and (av > bv or (av == bv and earlier != "front_foot_down")):
|
| 183 |
+
add(f"events.{earlier}.{field}", f"Must be before {later}." if earlier != "front_foot_down"
|
| 184 |
+
else "Must not be after contact.")
|
| 185 |
+
if finish and finish.status in USABLE and (finish.capture_time_s is None or contact.capture_time_s is None):
|
| 186 |
+
add("events.follow_through.capture_time_s", "Timed follow-through requires a known capture clock.")
|
| 187 |
|
| 188 |
for i, m in enumerate(p.measurements):
|
| 189 |
_check_measurement(i, m, events, p, add)
|
|
|
|
| 220 |
|
| 221 |
# Rule 7: event quality propagates.
|
| 222 |
for event_id in required_events(m.metric_id):
|
| 223 |
+
if event_id not in events:
|
| 224 |
+
add(f"{base}.status", f"Missing required event: {event_id}.")
|
| 225 |
+
continue
|
| 226 |
status = events[event_id].status
|
| 227 |
if status == "unavailable" and m.status != "unavailable":
|
| 228 |
add(f"{base}.status", f"Must be unavailable because {event_id} is unavailable.")
|
|
|
|
| 235 |
add(f"{base}.status", "Must be unavailable when the scale is unknown.")
|
| 236 |
if "scale_is_model_estimated" in m.reasons and m.status == "unavailable" and m.reasons == ["scale_is_model_estimated"]:
|
| 237 |
add(f"{base}.status", "A model-estimated scale needs status limited, not unavailable.")
|
| 238 |
+
if m.metric_id in ("stride_relative_length", "lead_knee_extension_to_contact"):
|
| 239 |
if p.athlete.lead_foot is None:
|
| 240 |
if m.status != "unavailable":
|
| 241 |
add(f"{base}.status", "Must be unavailable when the lead foot is unknown.")
|
|
|
|
| 250 |
add(f"{base}.value", "Separation must be from -180 up to but not including 180 degrees.")
|
| 251 |
if m.metric_id == "stride_relative_length" and m.value < 0:
|
| 252 |
add(f"{base}.value", "Stride length must not be negative.")
|
| 253 |
+
if m.reference in ("torso_angle_from_vertical", "absolute_net_horizontal_rotation") and m.value < 0:
|
| 254 |
+
add(f"{base}.value", "An angle magnitude cannot be negative.")
|
| 255 |
+
if m.reference == "torso_angle_from_vertical" and m.value >= 90:
|
| 256 |
+
add(f"{base}.value", "Torso inclination requires an upright torso.")
|
| 257 |
+
if m.reference == "change_in_3d_lead_knee_angle" and not -180 <= m.value <= 180:
|
| 258 |
+
add(f"{base}.value", "Knee extension must be between minus and plus 180 degrees.")
|
| 259 |
+
if m.value_interval is not None:
|
| 260 |
+
interval = m.value_interval
|
| 261 |
+
if m.value is None or not interval.lower <= m.value <= interval.upper:
|
| 262 |
+
add(f"{base}.value_interval", "The interval must be ordered and contain the measurement value.")
|
| 263 |
|
| 264 |
# Rule 11: an optional benchmark must be coherent (the coach uses its own ranges either way).
|
| 265 |
b = m.benchmark
|
AI-coach-agent/tests/test_swing_report_evidence_scope.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A fluent sentence must not override measured scope, uncertainty or drill context."""
|
| 2 |
+
from ai_coach.config import Settings
|
| 3 |
+
from ai_coach.swing_report.text import semantic_problems, write_texts
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def facts(metric='hip_shoulder_separation_at_contact', *, supported=True):
|
| 7 |
+
return {'technique_correction_supported': supported,
|
| 8 |
+
'groups': [{'group': 'contact_follow_through', 'metric_ids': [metric], 'rating': 'on_target'}],
|
| 9 |
+
'measurements': [{'metric_id': metric, 'approximate': True, 'rating': 'on_target',
|
| 10 |
+
'finding': 'Within the reference range.'}]}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_contact_angle_cannot_establish_follow_through_or_power():
|
| 14 |
+
f = facts()
|
| 15 |
+
assert 'unmeasured_follow_through' in semantic_problems(
|
| 16 |
+
'Your estimated follow-through is in the typical range.', 'group:contact_follow_through', f)
|
| 17 |
+
assert 'unsupported_physical_claim' in semantic_problems(
|
| 18 |
+
'Your estimated turn creates more power.', 'group:contact_follow_through', f)
|
| 19 |
+
assert 'uncertainty_removed' in semantic_problems(
|
| 20 |
+
'Your shoulder and hip gap is in the typical range.', 'group:contact_follow_through', f)
|
| 21 |
+
assert 'unsupported_shoulder_timing' in semantic_problems(
|
| 22 |
+
'Your estimated shoulder turn started too early.', 'group:contact_follow_through', f)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_early_shoulder_turn_does_not_validate_entire_finish():
|
| 26 |
+
f = facts('shoulder_rotation_after_contact')
|
| 27 |
+
assert 'follow_through_scope_exceeded' in semantic_problems(
|
| 28 |
+
'Your estimated whole follow-through is in the typical range.', 'group:contact_follow_through', f)
|
| 29 |
+
assert not semantic_problems('Your estimated early shoulder turn is in the typical range.',
|
| 30 |
+
'group:contact_follow_through', f)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_unknown_context_never_calls_model_for_free_form_technique_advice():
|
| 34 |
+
def forbidden(*_):
|
| 35 |
+
raise AssertionError('No model advice is justified for an unknown drill.')
|
| 36 |
+
f = facts(supported=False)
|
| 37 |
+
rules = {'headline': 'These are estimated reference comparisons.', 'coach_message': 'Review the clip with your coach.'}
|
| 38 |
+
result = write_texts(f, rules, Settings(_env_file=None, google_api_key=None), generator=forbidden)
|
| 39 |
+
assert result.texts == rules and result.source == 'rules'
|
| 40 |
+
assert result.fallback_reason == 'insufficient_coaching_context'
|
| 41 |
+
assert 'unsupported_technique_correction' in semantic_problems(
|
| 42 |
+
'Try a shorter step.', 'coach_message', f)
|
AI-coach-agent/tests/test_swing_report_report.py
CHANGED
|
@@ -63,7 +63,7 @@ def test_spec_example():
|
|
| 63 |
sep = by_metric(r)["hip_shoulder_separation_at_foot_down"]
|
| 64 |
assert (sep["score"], sep["rating"], sep["rating_label"], sep["display_value"]) == (55, "off_target", "Off Target", "3°")
|
| 65 |
assert sep["benchmark"] == {
|
| 66 |
-
"benchmark_id": "obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college", "version": "2026-10-
|
| 67 |
"population": "College right-handed hitters (50 athletes)", "on_target": {"lower": -25.3, "upper": -8.5},
|
| 68 |
"satisfactory": {"lower": -32.5, "upper": -0.4}, "unit": "deg",
|
| 69 |
"source_reference": "OpenBiomechanics Project hitting dataset (Driveline), percentiles P25-P75 and P10-P90"}
|
|
@@ -89,12 +89,12 @@ def test_spec_example():
|
|
| 89 |
"how": "Set the tee on the outer half. Keep your front shoulder pointed at the pitcher until "
|
| 90 |
"your hips have turned, then swing.", "cue": "Shoulder in.", "reps": "3x8"}
|
| 91 |
assert focus["evidence_metric_ids"] == ["hip_shoulder_separation_at_foot_down"]
|
| 92 |
-
assert {n["code"] for n in r["data_quality"]} == {"contact_not_verified", "scale_is_model_estimated"}
|
| 93 |
meta = r["meta"]
|
| 94 |
assert meta["text_source"] == "rules" and meta["model"] is None and meta["fallback_reason"] == "llm_not_configured"
|
| 95 |
assert meta["request_id"] == "req_1" and meta["prompt_version"].startswith("swing-report-v1-")
|
| 96 |
assert (meta["input_schema_version"], meta["measurement_definitions_version"], meta["benchmark_registry_version"],
|
| 97 |
-
meta["coaching_rules_version"]) == ("1.0", "1.0", "2026-10-
|
| 98 |
assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", meta["generated_at"])
|
| 99 |
|
| 100 |
|
|
@@ -253,7 +253,7 @@ def test_level_mapping(level, cell, notes):
|
|
| 253 |
r = build(athlete=AthleteContext(level=level))
|
| 254 |
assert by_metric(r)["hip_shoulder_separation_at_foot_down"]["benchmark"]["benchmark_id"].endswith(cell)
|
| 255 |
codes = {n["code"] for n in r["data_quality"]} - {"contact_not_verified", "scale_is_model_estimated"}
|
| 256 |
-
assert codes == notes
|
| 257 |
|
| 258 |
|
| 259 |
def test_population_fallback_for_left_high_school():
|
|
@@ -319,13 +319,13 @@ def llm_settings(tmp_path, **kw) -> Settings:
|
|
| 319 |
|
| 320 |
|
| 321 |
GOOD = {
|
| 322 |
-
"headline": "Your stride
|
| 323 |
-
"group_summaries": [{"group": "stride", "summary": "Your step
|
| 324 |
-
"coach_message": "Your
|
| 325 |
"measurements": [
|
| 326 |
-
{"metric_id": "hip_shoulder_separation_at_foot_down", "result_text": "Your
|
| 327 |
"coach_tip": "Let your hips turn first."},
|
| 328 |
-
{"metric_id": "stride_relative_length", "result_text": "Your step length is typical.", "coach_tip": ""},
|
| 329 |
],
|
| 330 |
}
|
| 331 |
|
|
@@ -424,4 +424,4 @@ def test_benchmarks_yaml_matches_generator():
|
|
| 424 |
def test_registry_drills_exist_and_catalog_lists():
|
| 425 |
assert {d["drill_id"] for d in repo.drills("hitting")} >= {"hit_01", "hit_13"}
|
| 426 |
assert all(d["drill_id"].startswith("pit_") for d in repo.drills("pitching"))
|
| 427 |
-
assert repo.benchmark_version() == "2026-10-
|
|
|
|
| 63 |
sep = by_metric(r)["hip_shoulder_separation_at_foot_down"]
|
| 64 |
assert (sep["score"], sep["rating"], sep["rating_label"], sep["display_value"]) == (55, "off_target", "Off Target", "3°")
|
| 65 |
assert sep["benchmark"] == {
|
| 66 |
+
"benchmark_id": "obp-contract-v1.hip_shoulder_separation_at_foot_down.right.college", "version": "2026-10-31.1",
|
| 67 |
"population": "College right-handed hitters (50 athletes)", "on_target": {"lower": -25.3, "upper": -8.5},
|
| 68 |
"satisfactory": {"lower": -32.5, "upper": -0.4}, "unit": "deg",
|
| 69 |
"source_reference": "OpenBiomechanics Project hitting dataset (Driveline), percentiles P25-P75 and P10-P90"}
|
|
|
|
| 89 |
"how": "Set the tee on the outer half. Keep your front shoulder pointed at the pitcher until "
|
| 90 |
"your hips have turned, then swing.", "cue": "Shoulder in.", "reps": "3x8"}
|
| 91 |
assert focus["evidence_metric_ids"] == ["hip_shoulder_separation_at_foot_down"]
|
| 92 |
+
assert {n["code"] for n in r["data_quality"]} == {"contact_not_verified", "scale_is_model_estimated", "partial_group_coverage"}
|
| 93 |
meta = r["meta"]
|
| 94 |
assert meta["text_source"] == "rules" and meta["model"] is None and meta["fallback_reason"] == "llm_not_configured"
|
| 95 |
assert meta["request_id"] == "req_1" and meta["prompt_version"].startswith("swing-report-v1-")
|
| 96 |
assert (meta["input_schema_version"], meta["measurement_definitions_version"], meta["benchmark_registry_version"],
|
| 97 |
+
meta["coaching_rules_version"]) == ("1.0", "1.0", "2026-10-31.1", "1.1")
|
| 98 |
assert re.fullmatch(r"\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ", meta["generated_at"])
|
| 99 |
|
| 100 |
|
|
|
|
| 253 |
r = build(athlete=AthleteContext(level=level))
|
| 254 |
assert by_metric(r)["hip_shoulder_separation_at_foot_down"]["benchmark"]["benchmark_id"].endswith(cell)
|
| 255 |
codes = {n["code"] for n in r["data_quality"]} - {"contact_not_verified", "scale_is_model_estimated"}
|
| 256 |
+
assert codes == notes | {"partial_group_coverage"}
|
| 257 |
|
| 258 |
|
| 259 |
def test_population_fallback_for_left_high_school():
|
|
|
|
| 319 |
|
| 320 |
|
| 321 |
GOOD = {
|
| 322 |
+
"headline": "Your stride results are approximate. Your hip and shoulder angle differs from the reference.",
|
| 323 |
+
"group_summaries": [{"group": "stride", "summary": "Your step is an estimate, and your hip and shoulder angle differs from the reference."}],
|
| 324 |
+
"coach_message": "Your results are estimates. Let your hips lead as you turn.",
|
| 325 |
"measurements": [
|
| 326 |
+
{"metric_id": "hip_shoulder_separation_at_foot_down", "result_text": "Your hip and shoulder angle differs from the reference.",
|
| 327 |
"coach_tip": "Let your hips turn first."},
|
| 328 |
+
{"metric_id": "stride_relative_length", "result_text": "Your estimated step length is in the typical range.", "coach_tip": ""},
|
| 329 |
],
|
| 330 |
}
|
| 331 |
|
|
|
|
| 424 |
def test_registry_drills_exist_and_catalog_lists():
|
| 425 |
assert {d["drill_id"] for d in repo.drills("hitting")} >= {"hit_01", "hit_13"}
|
| 426 |
assert all(d["drill_id"].startswith("pit_") for d in repo.drills("pitching"))
|
| 427 |
+
assert repo.benchmark_version() == "2026-10-31.1"
|
AI-coach-agent/tools/build_benchmarks.py
CHANGED
|
@@ -22,7 +22,7 @@ ROOT = Path(__file__).resolve().parents[1]
|
|
| 22 |
DEFAULT_JSON = ROOT.parent / "data_ref" / "calibration" / "contract_v1" / "contract_v1_benchmarks.json"
|
| 23 |
OUT = ROOT / "src" / "ai_coach" / "knowledge" / "benchmarks.yaml"
|
| 24 |
|
| 25 |
-
VERSION = "2026-10-
|
| 26 |
MIN_ATHLETES = 5
|
| 27 |
HANDS = ("right", "left")
|
| 28 |
OBP_LEVELS = ("high_school", "college", "pro")
|
|
@@ -33,10 +33,15 @@ LEVEL_MAP = {"high_school": "high_school", "college": "college", "adult": "colle
|
|
| 33 |
"unknown": "high_school"}
|
| 34 |
FALLBACK_LEVEL = "college"
|
| 35 |
UNITS = {"hip_shoulder_separation_at_foot_down": "deg", "hip_shoulder_separation_at_contact": "deg",
|
| 36 |
-
"stride_relative_length": "cm"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
def build(data: dict) -> dict:
|
|
|
|
| 40 |
metrics: dict = {}
|
| 41 |
for metric_id, unit in UNITS.items():
|
| 42 |
cells = data["metrics"][metric_id]
|
|
@@ -71,7 +76,7 @@ def build(data: dict) -> dict:
|
|
| 71 |
|
| 72 |
|
| 73 |
HEADER = (
|
| 74 |
-
"# GENERATED by tools/build_benchmarks.py from data_ref/calibration/contract_v1
|
| 75 |
"# Do not edit by hand: change the generator or the source data and regenerate.\n"
|
| 76 |
)
|
| 77 |
|
|
|
|
| 22 |
DEFAULT_JSON = ROOT.parent / "data_ref" / "calibration" / "contract_v1" / "contract_v1_benchmarks.json"
|
| 23 |
OUT = ROOT / "src" / "ai_coach" / "knowledge" / "benchmarks.yaml"
|
| 24 |
|
| 25 |
+
VERSION = "2026-10-31.1"
|
| 26 |
MIN_ATHLETES = 5
|
| 27 |
HANDS = ("right", "left")
|
| 28 |
OBP_LEVELS = ("high_school", "college", "pro")
|
|
|
|
| 33 |
"unknown": "high_school"}
|
| 34 |
FALLBACK_LEVEL = "college"
|
| 35 |
UNITS = {"hip_shoulder_separation_at_foot_down": "deg", "hip_shoulder_separation_at_contact": "deg",
|
| 36 |
+
"stride_relative_length": "cm", "torso_inclination_at_stride_start": "deg",
|
| 37 |
+
"hip_shoulder_separation_at_stride_start": "deg", "pelvis_rotation_to_contact": "deg",
|
| 38 |
+
"lead_knee_extension_to_contact": "deg", "torso_inclination_at_contact": "deg",
|
| 39 |
+
"shoulder_rotation_after_contact": "deg"}
|
| 40 |
+
EXTENDED_JSON = ROOT.parent / "data_ref" / "calibration" / "contract_v1_1" / "contract_v1_1_benchmarks.json"
|
| 41 |
|
| 42 |
|
| 43 |
def build(data: dict) -> dict:
|
| 44 |
+
data = {**data, "metrics": {**data["metrics"], **json.loads(EXTENDED_JSON.read_text())["metrics"]}}
|
| 45 |
metrics: dict = {}
|
| 46 |
for metric_id, unit in UNITS.items():
|
| 47 |
cells = data["metrics"][metric_id]
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
HEADER = (
|
| 79 |
+
"# GENERATED by tools/build_benchmarks.py from data_ref/calibration/contract_v1 and contract_v1_1.\n"
|
| 80 |
"# Do not edit by hand: change the generator or the source data and regenerate.\n"
|
| 81 |
)
|
| 82 |
|
backend/CONTRIBUTING.md
CHANGED
|
@@ -22,15 +22,20 @@ These rules apply to every change in `backend/`. The design is in `DESIGN.md`. T
|
|
| 22 |
|---|---|
|
| 23 |
| CRUD | `app.common.base_repository.BaseRepository` (`get`, `get_or_404`, `first_by`, `list_by`, `exists_by`, `create`, `update`, `delete`) |
|
| 24 |
| Errors | `app.core.errors`: `ValidationFailed` (400), `Unauthenticated` (401), `PlanLimitReached` (402), `Forbidden` (403), `NotFound` (404), `Conflict` (409, pass `code=`), `TooLarge` (413), `Unprocessable` (422), `RateLimited` (429), `ServiceUnavailable` (503). Pass `code=` for spec codes such as `EMAIL_TAKEN` and `fields=` for field errors. |
|
| 25 |
-
| Lists | `app.core.pagination` (`Paging` dependency, `encode_cursor`) and `common.schemas.Page[T]`, which returns `{items, next_cursor}` |
|
| 26 |
| Plan and usage | `app.modules.billing.entitlement.EntitlementService(db)` (`get`, `ensure_can_analyze`) |
|
| 27 |
-
| Retried writes | `app.modules.idempotency.service.run_idempotent` (`Idempotency-Key` header) |
|
| 28 |
| Session list items | `app.modules.sessions.summary` (`summary_query`, `load_summaries`, `SessionSummary`) |
|
| 29 |
| Team shape | `app.modules.teams.schemas.TeamOut` |
|
| 30 |
| Review shape | `app.modules.reviews.schemas.ReviewOut` |
|
| 31 |
-
| Storage | `app.integrations.storage.StorageClient` (`presign_put`, `presign_get`, `head`, `delete_many`) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
| Tokens and passwords | `app.core.security` |
|
| 33 |
-
| Rate limits | `app.core.rate_limit` (`RateLimiter`; tests reset all limiters automatically) |
|
| 34 |
|
| 35 |
**Do not edit these shared files.** If one needs a change, describe it in your report instead:
|
| 36 |
- `app/core/*`
|
|
|
|
| 22 |
|---|---|
|
| 23 |
| CRUD | `app.common.base_repository.BaseRepository` (`get`, `get_or_404`, `first_by`, `list_by`, `exists_by`, `create`, `update`, `delete`) |
|
| 24 |
| Errors | `app.core.errors`: `ValidationFailed` (400), `Unauthenticated` (401), `PlanLimitReached` (402), `Forbidden` (403), `NotFound` (404), `Conflict` (409, pass `code=`), `TooLarge` (413), `Unprocessable` (422), `RateLimited` (429), `ServiceUnavailable` (503). Pass `code=` for spec codes such as `EMAIL_TAKEN` and `fields=` for field errors. |
|
| 25 |
+
| Lists | `app.core.pagination` (`Paging` dependency, `paginate(rows_fetched_with_limit_plus_1, limit, key)` -> `(page, next_cursor)`, `encode_cursor`) and `common.schemas.Page[T]`, which returns `{items, next_cursor}` |
|
| 26 |
| Plan and usage | `app.modules.billing.entitlement.EntitlementService(db)` (`get`, `ensure_can_analyze`) |
|
| 27 |
+
| Retried writes | `app.modules.idempotency.service.run_idempotent` (`Idempotency-Key` header; pass `scope=<path id>` when the route has a target id) |
|
| 28 |
| Session list items | `app.modules.sessions.summary` (`summary_query`, `load_summaries`, `SessionSummary`) |
|
| 29 |
| Team shape | `app.modules.teams.schemas.TeamOut` |
|
| 30 |
| Review shape | `app.modules.reviews.schemas.ReviewOut` |
|
| 31 |
+
| Storage | `app.integrations.storage.StorageClient` (`presign_put`, `presign_get`, `head`, `put_bytes`, `delete_many`) |
|
| 32 |
+
| Media URLs | `app.common.media` (`media_ref`, `upload_ref`) build every `MediaRef` |
|
| 33 |
+
| Claiming an upload | `app.common.uploads.claim_upload` (lock, owner, kind, already used, bytes present, set `attached_at`; each module passes its own `UploadErrors`) |
|
| 34 |
+
| Analysis consent | `app.common.consent.analysis_consent_blocked(db, account_id, require_accepted)` |
|
| 35 |
+
| Labels and tones | `app.common.labels` (`DISCIPLINES`, `FOCUS_LABEL`, `tone`, `tone_counts`, `drill_catalog`) |
|
| 36 |
+
| Account names | `app.common.names.account_names(session, ids)` |
|
| 37 |
| Tokens and passwords | `app.core.security` |
|
| 38 |
+
| Rate limits | `app.core.rate_limit` (`RateLimiter` and one named getter per limiter, e.g. `get_academy_apply_limiter`; tests reset all limiters automatically) |
|
| 39 |
|
| 40 |
**Do not edit these shared files.** If one needs a change, describe it in your report instead:
|
| 41 |
- `app/core/*`
|
backend/app/common/consent.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Whether the player's analysis consent allows running an analysis."""
|
| 2 |
+
|
| 3 |
+
from uuid import UUID
|
| 4 |
+
|
| 5 |
+
from sqlalchemy import select
|
| 6 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
+
|
| 8 |
+
from app.modules.settings.models import ConsentEvent
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
async def analysis_consent_blocked(db: AsyncSession, account_id: UUID, require_accepted: bool) -> bool:
|
| 12 |
+
"""True when the latest analysis consent is a withdrawal, or (when required) there is no acceptance."""
|
| 13 |
+
action = await db.scalar(
|
| 14 |
+
select(ConsentEvent.action)
|
| 15 |
+
.where(ConsentEvent.account_id == account_id, ConsentEvent.category == "analysis")
|
| 16 |
+
.order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1))
|
| 17 |
+
return action == "withdrawn" or (require_accepted and action is None)
|
backend/app/common/labels.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small lookups shared by several modules: mode and focus labels, score tones, the drill catalog."""
|
| 2 |
+
|
| 3 |
+
from collections.abc import Iterable
|
| 4 |
+
from functools import cache
|
| 5 |
+
|
| 6 |
+
DISCIPLINES = {"h": "hitting", "p": "pitching"} # session mode -> ai_coach drill discipline
|
| 7 |
+
FOCUS_LABEL = {"h": "Hitting", "p": "Pitching", "both": "Both"} # coach focus -> display label
|
| 8 |
+
TONE_GREEN_MIN = 80 # overall score at or above: "g"; at or above TONE_YELLOW_MIN: "y"; below: "r"
|
| 9 |
+
TONE_YELLOW_MIN = 60
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@cache
|
| 13 |
+
def drill_catalog() -> dict[str, dict]:
|
| 14 |
+
"""ai_coach catalog drills by id."""
|
| 15 |
+
from ai_coach.knowledge import all_drills
|
| 16 |
+
|
| 17 |
+
return {d["id"]: d for d in all_drills()}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def tone(score: int | None) -> str:
|
| 21 |
+
if score is None:
|
| 22 |
+
return "y"
|
| 23 |
+
return "g" if score >= TONE_GREEN_MIN else "y" if score >= TONE_YELLOW_MIN else "r"
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def tone_counts(scores: Iterable[int]) -> dict[str, int]:
|
| 27 |
+
counts = dict.fromkeys("gyr", 0)
|
| 28 |
+
for score in scores:
|
| 29 |
+
counts[tone(score)] += 1
|
| 30 |
+
return counts
|
backend/app/common/media.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Short-lived read URLs for stored media. Every module that returns a MediaRef builds it here."""
|
| 2 |
+
|
| 3 |
+
from datetime import UTC, datetime, timedelta
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from app.common.schemas import MediaRef
|
| 7 |
+
from app.integrations.storage import StorageClient
|
| 8 |
+
from app.modules.uploads.models import Upload
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def media_ref(storage: StorageClient, upload_id: UUID, object_key: str, seconds: float | None = None) -> MediaRef:
|
| 12 |
+
return MediaRef(upload_id=upload_id, url=storage.presign_get(object_key),
|
| 13 |
+
expires_at=datetime.now(UTC) + timedelta(seconds=storage.download_ttl), seconds=seconds)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def upload_ref(storage: StorageClient, upload: Upload | None, seconds: float | None = None) -> MediaRef | None:
|
| 17 |
+
return media_ref(storage, upload.id, upload.object_key, seconds) if upload is not None else None
|
backend/app/common/names.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Display names for a set of accounts in one query."""
|
| 2 |
+
|
| 3 |
+
from collections.abc import Iterable
|
| 4 |
+
from uuid import UUID
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import select
|
| 7 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 8 |
+
|
| 9 |
+
from app.modules.accounts.models import Account
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
async def account_names(session: AsyncSession, ids: Iterable[UUID | None]) -> dict[UUID, str | None]:
|
| 13 |
+
wanted = {i for i in ids if i}
|
| 14 |
+
if not wanted:
|
| 15 |
+
return {}
|
| 16 |
+
rows = await session.execute(select(Account.id, Account.name).where(Account.id.in_(wanted)))
|
| 17 |
+
return {i: n for i, n in rows}
|
backend/app/common/uploads.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Claiming an upload for a record: ownership, kind, not already used, bytes present, then mark it attached."""
|
| 2 |
+
|
| 3 |
+
from collections.abc import Awaitable, Callable
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from datetime import UTC, datetime
|
| 6 |
+
from uuid import UUID
|
| 7 |
+
|
| 8 |
+
from sqlalchemy import select
|
| 9 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
+
|
| 11 |
+
from app.integrations.storage import StorageClient
|
| 12 |
+
from app.modules.uploads.models import Upload
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass(frozen=True)
|
| 16 |
+
class UploadErrors:
|
| 17 |
+
"""The exceptions each module raises for a failed claim (they differ in code and wording)."""
|
| 18 |
+
|
| 19 |
+
invalid: Exception # missing or not the caller's
|
| 20 |
+
used: Exception
|
| 21 |
+
not_ready: Exception
|
| 22 |
+
wrong_kind: Exception | None = None # defaults to invalid
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
async def claim_upload(
|
| 26 |
+
db: AsyncSession, storage: StorageClient, upload_id: UUID, *, owner_id: UUID, kind: str, errors: UploadErrors,
|
| 27 |
+
in_use: Callable[[], Awaitable[bool]] | None = None,
|
| 28 |
+
reusable: Callable[[], Awaitable[bool]] | None = None,
|
| 29 |
+
) -> None:
|
| 30 |
+
"""Lock the upload row so concurrent claims serialize. in_use also counts rows that reference it without
|
| 31 |
+
attached_at set; reusable says a claim on an already attached upload is the same record re-sending it."""
|
| 32 |
+
upload = await db.scalar(select(Upload).where(Upload.id == upload_id).with_for_update())
|
| 33 |
+
if upload is None or upload.owner_id != owner_id:
|
| 34 |
+
raise errors.invalid
|
| 35 |
+
if upload.kind != kind:
|
| 36 |
+
raise errors.wrong_kind or errors.invalid
|
| 37 |
+
attached = upload.attached_at is not None
|
| 38 |
+
if attached and not (reusable and await reusable()) or (not attached and in_use and await in_use()):
|
| 39 |
+
raise errors.used
|
| 40 |
+
if await storage.head(upload.object_key) is None:
|
| 41 |
+
raise errors.not_ready
|
| 42 |
+
if not attached:
|
| 43 |
+
upload.attached_at = datetime.now(UTC)
|
backend/app/core/pagination.py
CHANGED
|
@@ -2,8 +2,10 @@
|
|
| 2 |
|
| 3 |
import base64
|
| 4 |
import json
|
|
|
|
| 5 |
from dataclasses import dataclass
|
| 6 |
from datetime import datetime
|
|
|
|
| 7 |
from uuid import UUID
|
| 8 |
|
| 9 |
from fastapi import Query
|
|
@@ -31,6 +33,18 @@ def decode_cursor(value: str) -> Cursor:
|
|
| 31 |
raise ValidationFailed(fields={"cursor": "Invalid cursor."}) from exc
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
@dataclass(frozen=True)
|
| 35 |
class PageParams:
|
| 36 |
limit: int
|
|
|
|
| 2 |
|
| 3 |
import base64
|
| 4 |
import json
|
| 5 |
+
from collections.abc import Callable, Sequence
|
| 6 |
from dataclasses import dataclass
|
| 7 |
from datetime import datetime
|
| 8 |
+
from typing import TypeVar
|
| 9 |
from uuid import UUID
|
| 10 |
|
| 11 |
from fastapi import Query
|
|
|
|
| 33 |
raise ValidationFailed(fields={"cursor": "Invalid cursor."}) from exc
|
| 34 |
|
| 35 |
|
| 36 |
+
T = TypeVar("T")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def paginate(rows: Sequence[T], limit: int, key: Callable[[T], tuple[datetime, UUID]] | None = None
|
| 40 |
+
) -> tuple[list[T], str | None]:
|
| 41 |
+
"""Split rows fetched with limit + 1 into the page and its next cursor. key gives (created_at, id)."""
|
| 42 |
+
page = list(rows[:limit])
|
| 43 |
+
if len(rows) <= limit:
|
| 44 |
+
return page, None
|
| 45 |
+
return page, encode_cursor(*(key(page[-1]) if key else (page[-1].created_at, page[-1].id))) # type: ignore[attr-defined]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
@dataclass(frozen=True)
|
| 49 |
class PageParams:
|
| 50 |
limit: int
|
backend/app/core/rate_limit.py
CHANGED
|
@@ -67,3 +67,8 @@ def get_rate_limiter() -> RateLimiter:
|
|
| 67 |
@lru_cache
|
| 68 |
def get_team_lookup_limiter() -> RateLimiter:
|
| 69 |
return RateLimiter(30)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
@lru_cache
|
| 68 |
def get_team_lookup_limiter() -> RateLimiter:
|
| 69 |
return RateLimiter(30)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@lru_cache
|
| 73 |
+
def get_academy_apply_limiter() -> RateLimiter:
|
| 74 |
+
return RateLimiter(10)
|
backend/app/integrations/storage.py
CHANGED
|
@@ -49,6 +49,9 @@ class StorageClient:
|
|
| 49 |
raise
|
| 50 |
return ObjectInfo(size_bytes=int(meta["ContentLength"]), content_type=meta.get("ContentType", ""))
|
| 51 |
|
|
|
|
|
|
|
|
|
|
| 52 |
async def read_prefix(self, key: str, length: int) -> bytes:
|
| 53 |
response = await asyncio.to_thread(
|
| 54 |
self._s3.get_object, Bucket=self.bucket, Key=key, Range=f"bytes=0-{length - 1}")
|
|
|
|
| 49 |
raise
|
| 50 |
return ObjectInfo(size_bytes=int(meta["ContentLength"]), content_type=meta.get("ContentType", ""))
|
| 51 |
|
| 52 |
+
async def put_bytes(self, key: str, data: bytes, content_type: str) -> None:
|
| 53 |
+
await asyncio.to_thread(self._s3.put_object, Bucket=self.bucket, Key=key, Body=data, ContentType=content_type)
|
| 54 |
+
|
| 55 |
async def read_prefix(self, key: str, length: int) -> bytes:
|
| 56 |
response = await asyncio.to_thread(
|
| 57 |
self._s3.get_object, Bucket=self.bucket, Key=key, Range=f"bytes=0-{length - 1}")
|
backend/app/modules/academy_org/repository.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
"""Groups, private coach notes, roster additions and the academy library. Database only."""
|
| 2 |
|
| 3 |
from collections.abc import Sequence
|
| 4 |
-
from datetime import datetime
|
| 5 |
from uuid import UUID
|
| 6 |
|
| 7 |
from sqlalchemy import Select, and_, or_, select
|
|
@@ -168,10 +167,3 @@ class OrgRepository(BaseRepository[PlayerGroup]):
|
|
| 168 |
.outerjoin(Account, Account.id == LibraryDrill.author_id)
|
| 169 |
.outerjoin(Upload, Upload.id == LibraryDrill.upload_id))
|
| 170 |
|
| 171 |
-
async def upload(self, upload_id: UUID, owner_id: UUID) -> Upload | None:
|
| 172 |
-
return await self.session.scalar(select(Upload).where(Upload.id == upload_id, Upload.owner_id == owner_id)
|
| 173 |
-
.with_for_update())
|
| 174 |
-
|
| 175 |
-
async def attach(self, upload: Upload, when: datetime) -> None:
|
| 176 |
-
upload.attached_at = when
|
| 177 |
-
await self.session.flush()
|
|
|
|
| 1 |
"""Groups, private coach notes, roster additions and the academy library. Database only."""
|
| 2 |
|
| 3 |
from collections.abc import Sequence
|
|
|
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from sqlalchemy import Select, and_, or_, select
|
|
|
|
| 167 |
.outerjoin(Account, Account.id == LibraryDrill.author_id)
|
| 168 |
.outerjoin(Upload, Upload.id == LibraryDrill.upload_id))
|
| 169 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/modules/academy_org/service.py
CHANGED
|
@@ -1,14 +1,16 @@
|
|
| 1 |
"""Academy groups (N28-N29), private coach notes (N30-N31), roster additions (N32-N33) and the library (N35-N36)."""
|
| 2 |
|
| 3 |
-
from datetime import UTC, datetime
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
| 8 |
from app.common.academy_access import Staff, require_player, visible_player_ids
|
| 9 |
-
from app.common.
|
|
|
|
|
|
|
| 10 |
from app.core.errors import Conflict, NotFound, Unprocessable
|
| 11 |
-
from app.core.pagination import PageParams,
|
| 12 |
from app.integrations.storage import StorageClient
|
| 13 |
from app.modules.academy.models import LibraryDrill, PlayerGroup
|
| 14 |
from app.modules.academy_org.repository import OrgRepository
|
|
@@ -29,15 +31,6 @@ def _dedupe(ids: list[UUID]) -> list[UUID]:
|
|
| 29 |
return list(dict.fromkeys(ids))
|
| 30 |
|
| 31 |
|
| 32 |
-
def _page(items: list, limit: int, created_at) -> Page:
|
| 33 |
-
"""items holds up to limit+1 rows; created_at(item) gives (created_at, id) for the cursor."""
|
| 34 |
-
next_cursor = None
|
| 35 |
-
if len(items) > limit:
|
| 36 |
-
items = items[:limit]
|
| 37 |
-
next_cursor = encode_cursor(*created_at(items[-1]))
|
| 38 |
-
return Page(items=items, next_cursor=next_cursor)
|
| 39 |
-
|
| 40 |
-
|
| 41 |
class OrgService:
|
| 42 |
def __init__(self, db: AsyncSession, storage: StorageClient):
|
| 43 |
self.db = db
|
|
@@ -67,7 +60,8 @@ class OrgService:
|
|
| 67 |
visible = None if staff.sees_all else set(await visible_player_ids(self.db, staff))
|
| 68 |
outs = await self._group_outs(rows, visible)
|
| 69 |
by_id = {g.id: g for g in rows}
|
| 70 |
-
|
|
|
|
| 71 |
|
| 72 |
async def create_group(self, staff: Staff, body: GroupIn) -> GroupOut:
|
| 73 |
team_id = staff.team_id
|
|
@@ -124,7 +118,8 @@ class OrgService:
|
|
| 124 |
created = {r.id: r.created_at for r in rows}
|
| 125 |
items = [MemberOut(id=r.id, name=r.name or "", focus=r.focus, level=r.level, group_ids=groups.get(r.id, []))
|
| 126 |
for r in rows]
|
| 127 |
-
|
|
|
|
| 128 |
|
| 129 |
async def add_to_roster(self, staff: Staff, body: RosterAddIn) -> RosterAddOut:
|
| 130 |
player_ids = _dedupe(body.player_ids)
|
|
@@ -146,8 +141,7 @@ class OrgService:
|
|
| 146 |
drill, author, key = row
|
| 147 |
media = None
|
| 148 |
if drill.upload_id is not None and key is not None:
|
| 149 |
-
|
| 150 |
-
media = MediaRef(upload_id=drill.upload_id, url=self.storage.presign_get(key), expires_at=expires)
|
| 151 |
return LibraryDrillOut(id=drill.id, name=drill.name, fixes=drill.fixes, fault_tags=list(drill.fault_tags),
|
| 152 |
by=author, author_id=drill.author_id, mode=drill.mode, media=media,
|
| 153 |
created_at=drill.created_at)
|
|
@@ -157,22 +151,20 @@ class OrgService:
|
|
| 157 |
if staff.team_id is None:
|
| 158 |
return Page[LibraryDrillOut](items=[])
|
| 159 |
rows = await self.repo.library(staff.team_id, mode, fault_tag, paging.cursor, paging.limit + 1)
|
| 160 |
-
|
|
|
|
| 161 |
|
| 162 |
async def publish_drill(self, staff: Staff, body: LibraryDrillIn) -> LibraryDrillOut:
|
| 163 |
staff.require("library")
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
if await self.storage.head(upload.object_key) is None:
|
| 172 |
-
raise Conflict("The video has not finished uploading.", code="UPLOAD_NOT_READY")
|
| 173 |
drill = LibraryDrill(team_id=staff.team_id, author_id=staff.id, name=body.name, fixes=body.fixes,
|
| 174 |
-
mode=body.mode, fault_tags=body.fault_tags, upload_id=
|
| 175 |
self.db.add(drill)
|
| 176 |
await self.db.flush()
|
| 177 |
-
await self.repo.attach(upload, datetime.now(UTC))
|
| 178 |
return self._drill_out(await self.repo.library_row(drill.id))
|
|
|
|
| 1 |
"""Academy groups (N28-N29), private coach notes (N30-N31), roster additions (N32-N33) and the library (N35-N36)."""
|
| 2 |
|
| 3 |
+
from datetime import UTC, datetime
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
| 8 |
from app.common.academy_access import Staff, require_player, visible_player_ids
|
| 9 |
+
from app.common.media import media_ref
|
| 10 |
+
from app.common.schemas import Page
|
| 11 |
+
from app.common.uploads import UploadErrors, claim_upload
|
| 12 |
from app.core.errors import Conflict, NotFound, Unprocessable
|
| 13 |
+
from app.core.pagination import PageParams, paginate
|
| 14 |
from app.integrations.storage import StorageClient
|
| 15 |
from app.modules.academy.models import LibraryDrill, PlayerGroup
|
| 16 |
from app.modules.academy_org.repository import OrgRepository
|
|
|
|
| 31 |
return list(dict.fromkeys(ids))
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
class OrgService:
|
| 35 |
def __init__(self, db: AsyncSession, storage: StorageClient):
|
| 36 |
self.db = db
|
|
|
|
| 60 |
visible = None if staff.sees_all else set(await visible_player_ids(self.db, staff))
|
| 61 |
outs = await self._group_outs(rows, visible)
|
| 62 |
by_id = {g.id: g for g in rows}
|
| 63 |
+
items, next_cursor = paginate(outs, paging.limit, lambda o: (by_id[o.id].created_at, o.id))
|
| 64 |
+
return Page[GroupOut](items=items, next_cursor=next_cursor)
|
| 65 |
|
| 66 |
async def create_group(self, staff: Staff, body: GroupIn) -> GroupOut:
|
| 67 |
team_id = staff.team_id
|
|
|
|
| 118 |
created = {r.id: r.created_at for r in rows}
|
| 119 |
items = [MemberOut(id=r.id, name=r.name or "", focus=r.focus, level=r.level, group_ids=groups.get(r.id, []))
|
| 120 |
for r in rows]
|
| 121 |
+
items, next_cursor = paginate(items, paging.limit, lambda m: (created[m.id], m.id))
|
| 122 |
+
return Page[MemberOut](items=items, next_cursor=next_cursor)
|
| 123 |
|
| 124 |
async def add_to_roster(self, staff: Staff, body: RosterAddIn) -> RosterAddOut:
|
| 125 |
player_ids = _dedupe(body.player_ids)
|
|
|
|
| 141 |
drill, author, key = row
|
| 142 |
media = None
|
| 143 |
if drill.upload_id is not None and key is not None:
|
| 144 |
+
media = media_ref(self.storage, drill.upload_id, key)
|
|
|
|
| 145 |
return LibraryDrillOut(id=drill.id, name=drill.name, fixes=drill.fixes, fault_tags=list(drill.fault_tags),
|
| 146 |
by=author, author_id=drill.author_id, mode=drill.mode, media=media,
|
| 147 |
created_at=drill.created_at)
|
|
|
|
| 151 |
if staff.team_id is None:
|
| 152 |
return Page[LibraryDrillOut](items=[])
|
| 153 |
rows = await self.repo.library(staff.team_id, mode, fault_tag, paging.cursor, paging.limit + 1)
|
| 154 |
+
items, next_cursor = paginate([self._drill_out(r) for r in rows], paging.limit)
|
| 155 |
+
return Page[LibraryDrillOut](items=items, next_cursor=next_cursor)
|
| 156 |
|
| 157 |
async def publish_drill(self, staff: Staff, body: LibraryDrillIn) -> LibraryDrillOut:
|
| 158 |
staff.require("library")
|
| 159 |
+
await claim_upload(
|
| 160 |
+
self.db, self.storage, body.upload_id, owner_id=staff.id, kind="drill_video",
|
| 161 |
+
errors=UploadErrors(
|
| 162 |
+
invalid=NotFound("Upload not found."),
|
| 163 |
+
used=Conflict("This video is already in use.", code="UPLOAD_ALREADY_USED"),
|
| 164 |
+
not_ready=Conflict("The video has not finished uploading.", code="UPLOAD_NOT_READY"),
|
| 165 |
+
wrong_kind=Unprocessable("This upload is not a drill video.", code="INVALID_MEDIA")))
|
|
|
|
|
|
|
| 166 |
drill = LibraryDrill(team_id=staff.team_id, author_id=staff.id, name=body.name, fixes=body.fixes,
|
| 167 |
+
mode=body.mode, fault_tags=body.fault_tags, upload_id=body.upload_id)
|
| 168 |
self.db.add(drill)
|
| 169 |
await self.db.flush()
|
|
|
|
| 170 |
return self._drill_out(await self.repo.library_row(drill.id))
|
backend/app/modules/academy_staff/controller.py
CHANGED
|
@@ -6,7 +6,6 @@ from uuid import UUID
|
|
| 6 |
|
| 7 |
from fastapi import APIRouter, Header, Query, Response
|
| 8 |
from fastapi.responses import JSONResponse
|
| 9 |
-
from pydantic import BaseModel
|
| 10 |
|
| 11 |
from app.common.academy_access import CurrentAdmin, CurrentStaff, staff_context
|
| 12 |
from app.common.schemas import Page
|
|
@@ -32,13 +31,6 @@ router = APIRouter(prefix="/v1", tags=["academy_staff"])
|
|
| 32 |
IdempotencyKey = Annotated[str | None, Header(max_length=128)]
|
| 33 |
|
| 34 |
|
| 35 |
-
class _Scoped(BaseModel):
|
| 36 |
-
"""Idempotency payload that also covers the path id, so one key cannot replay across targets."""
|
| 37 |
-
|
| 38 |
-
target: UUID
|
| 39 |
-
body: dict
|
| 40 |
-
|
| 41 |
-
|
| 42 |
@router.get("/me/coach-access", response_model=CoachAccessBody)
|
| 43 |
async def get_coach_access(db: Db, account: CurrentAccount) -> CoachAccessBody:
|
| 44 |
return CoachAccessBody(coach_access=await StaffService(db).coach_access(account, await staff_context(db, account)))
|
|
@@ -92,9 +84,9 @@ async def list_requests(db: Db, staff: CurrentAdmin, paging: Paging,
|
|
| 92 |
@router.post("/academy/coach-requests/{request_id}/decision", response_model=DecisionOut)
|
| 93 |
async def decide_request(request_id: UUID, body: DecisionIn, db: Db, staff: CurrentAdmin,
|
| 94 |
idempotency_key: IdempotencyKey = None) -> JSONResponse:
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
|
| 99 |
|
| 100 |
@router.get("/academy/staff-codes", response_model=Page[StaffCodeOut])
|
|
|
|
| 6 |
|
| 7 |
from fastapi import APIRouter, Header, Query, Response
|
| 8 |
from fastapi.responses import JSONResponse
|
|
|
|
| 9 |
|
| 10 |
from app.common.academy_access import CurrentAdmin, CurrentStaff, staff_context
|
| 11 |
from app.common.schemas import Page
|
|
|
|
| 31 |
IdempotencyKey = Annotated[str | None, Header(max_length=128)]
|
| 32 |
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
@router.get("/me/coach-access", response_model=CoachAccessBody)
|
| 35 |
async def get_coach_access(db: Db, account: CurrentAccount) -> CoachAccessBody:
|
| 36 |
return CoachAccessBody(coach_access=await StaffService(db).coach_access(account, await staff_context(db, account)))
|
|
|
|
| 84 |
@router.post("/academy/coach-requests/{request_id}/decision", response_model=DecisionOut)
|
| 85 |
async def decide_request(request_id: UUID, body: DecisionIn, db: Db, staff: CurrentAdmin,
|
| 86 |
idempotency_key: IdempotencyKey = None) -> JSONResponse:
|
| 87 |
+
return await run_idempotent(db, staff.id, idempotency_key, body,
|
| 88 |
+
lambda: StaffService(db).decide(staff, request_id, body), status_code=200,
|
| 89 |
+
scope=request_id)
|
| 90 |
|
| 91 |
|
| 92 |
@router.get("/academy/staff-codes", response_model=Page[StaffCodeOut])
|
backend/app/modules/academy_staff/repository.py
CHANGED
|
@@ -55,10 +55,17 @@ class StaffRepository(BaseRepository[AcademyMembership]):
|
|
| 55 |
|
| 56 |
# ----- groups -----
|
| 57 |
async def group_ids(self, team_id: UUID, coach_id: UUID) -> list[UUID]:
|
| 58 |
-
return
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
async def count_groups(self, team_id: UUID, group_ids: list[UUID]) -> int:
|
| 64 |
return await self.session.scalar(select(func.count()).select_from(PlayerGroup).where(
|
|
@@ -88,21 +95,26 @@ class StaffRepository(BaseRepository[AcademyMembership]):
|
|
| 88 |
await self.add_groups(to_id, old)
|
| 89 |
|
| 90 |
# ----- activity -----
|
| 91 |
-
async def review_activity(self, team_id: UUID,
|
| 92 |
-
|
|
|
|
| 93 |
seconds = func.extract("epoch", Review.updated_at - SwingSession.created_at)
|
| 94 |
-
|
| 95 |
-
select(func.count(), func.avg(seconds) / 3600)
|
| 96 |
.select_from(Review).join(SwingSession, SwingSession.id == Review.session_id)
|
| 97 |
.join(Account, Account.id == SwingSession.owner_id)
|
| 98 |
-
.where(Account.team_id == team_id, Review.coach_id
|
| 99 |
-
Review.updated_at >= start, Review.updated_at < end)
|
| 100 |
-
return
|
| 101 |
-
|
| 102 |
-
async def drills_set(self, team_id: UUID,
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
DrillAssignment.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
async def count(self, query) -> int:
|
| 108 |
return await self.session.scalar(select(func.count()).select_from(query.subquery())) or 0
|
|
|
|
| 55 |
|
| 56 |
# ----- groups -----
|
| 57 |
async def group_ids(self, team_id: UUID, coach_id: UUID) -> list[UUID]:
|
| 58 |
+
return (await self.group_ids_many(team_id, [coach_id])).get(coach_id, [])
|
| 59 |
+
|
| 60 |
+
async def group_ids_many(self, team_id: UUID, coach_ids: list[UUID]) -> dict[UUID, list[UUID]]:
|
| 61 |
+
rows = await self.session.execute(
|
| 62 |
+
select(GroupCoach.coach_id, GroupCoach.group_id).join(PlayerGroup, PlayerGroup.id == GroupCoach.group_id)
|
| 63 |
+
.where(PlayerGroup.team_id == team_id, GroupCoach.coach_id.in_(coach_ids))
|
| 64 |
+
.order_by(PlayerGroup.created_at, PlayerGroup.id))
|
| 65 |
+
grouped: dict[UUID, list[UUID]] = {}
|
| 66 |
+
for coach_id, group_id in rows:
|
| 67 |
+
grouped.setdefault(coach_id, []).append(group_id)
|
| 68 |
+
return grouped
|
| 69 |
|
| 70 |
async def count_groups(self, team_id: UUID, group_ids: list[UUID]) -> int:
|
| 71 |
return await self.session.scalar(select(func.count()).select_from(PlayerGroup).where(
|
|
|
|
| 95 |
await self.add_groups(to_id, old)
|
| 96 |
|
| 97 |
# ----- activity -----
|
| 98 |
+
async def review_activity(self, team_id: UUID, coach_ids: list[UUID], start: datetime, end: datetime
|
| 99 |
+
) -> dict[UUID, tuple[int, float | None]]:
|
| 100 |
+
"""coach id -> (reviews, avg hours from session creation to the review) for reviews written in [start, end)."""
|
| 101 |
seconds = func.extract("epoch", Review.updated_at - SwingSession.created_at)
|
| 102 |
+
rows = await self.session.execute(
|
| 103 |
+
select(Review.coach_id, func.count(), func.avg(seconds) / 3600)
|
| 104 |
.select_from(Review).join(SwingSession, SwingSession.id == Review.session_id)
|
| 105 |
.join(Account, Account.id == SwingSession.owner_id)
|
| 106 |
+
.where(Account.team_id == team_id, Review.coach_id.in_(coach_ids), SwingSession.deleted_at.is_(None),
|
| 107 |
+
Review.updated_at >= start, Review.updated_at < end).group_by(Review.coach_id))
|
| 108 |
+
return {c: (n, round(float(avg), 1) if avg is not None else None) for c, n, avg in rows}
|
| 109 |
+
|
| 110 |
+
async def drills_set(self, team_id: UUID, coach_ids: list[UUID], start: datetime, end: datetime
|
| 111 |
+
) -> dict[UUID, int]:
|
| 112 |
+
rows = await self.session.execute(
|
| 113 |
+
select(DrillAssignment.assigned_by_id, func.count()).where(
|
| 114 |
+
DrillAssignment.team_id == team_id, DrillAssignment.assigned_by_id.in_(coach_ids),
|
| 115 |
+
DrillAssignment.created_at >= start, DrillAssignment.created_at < end)
|
| 116 |
+
.group_by(DrillAssignment.assigned_by_id))
|
| 117 |
+
return dict(rows.all())
|
| 118 |
|
| 119 |
async def count(self, query) -> int:
|
| 120 |
return await self.session.scalar(select(func.count()).select_from(query.subquery())) or 0
|
backend/app/modules/academy_staff/service.py
CHANGED
|
@@ -9,9 +9,10 @@ from uuid import UUID
|
|
| 9 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
|
| 11 |
from app.common.academy_access import Staff, normalize_permissions, visible_players_query
|
|
|
|
| 12 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable
|
| 13 |
-
from app.core.pagination import PageParams,
|
| 14 |
-
from app.core.rate_limit import
|
| 15 |
from app.modules.academy.models import AcademyMembership, CoachAccessRequest, StaffCode
|
| 16 |
from app.modules.academy_staff.repository import StaffRepository
|
| 17 |
from app.modules.academy_staff.schemas import (
|
|
@@ -30,8 +31,6 @@ from app.modules.accounts.models import Account
|
|
| 30 |
from app.modules.teams.models import Team
|
| 31 |
|
| 32 |
CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # no 0/O/1/I/L
|
| 33 |
-
COACHES_LABEL = {"h": "Hitting", "p": "Pitching", "both": "Both"}
|
| 34 |
-
_apply_limiter = RateLimiter(10, 60.0)
|
| 35 |
|
| 36 |
|
| 37 |
def normalize_code(code: str) -> str:
|
|
@@ -91,7 +90,7 @@ class StaffService:
|
|
| 91 |
|
| 92 |
async def apply(self, account: Account, raw_code: str) -> tuple[CoachAccessOut, bool]:
|
| 93 |
"""Returns (coach_access, created). Uses are counted at submission and a decline does not give one back."""
|
| 94 |
-
|
| 95 |
code = normalize_code(raw_code)
|
| 96 |
row = await self.repo.code_row(code, lock=True)
|
| 97 |
if row is None:
|
|
@@ -155,20 +154,30 @@ class StaffService:
|
|
| 155 |
return start, end
|
| 156 |
|
| 157 |
async def _out(self, team: Team, member: Member, me_id: UUID, start: date, end: date) -> CoachOut:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
lo = datetime.combine(start, time.min, UTC)
|
| 159 |
hi = datetime.combine(end + timedelta(days=1), time.min, UTC)
|
| 160 |
-
|
| 161 |
-
reviews
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
async def list_coaches(self, staff: Staff, status: str | None) -> list[CoachOut]:
|
| 174 |
team = await self._team(staff)
|
|
@@ -179,7 +188,7 @@ class StaffService:
|
|
| 179 |
owner = await self.repo.account(team.coach_id)
|
| 180 |
members.insert(0, self._owner(team, owner)) # type: ignore[arg-type]
|
| 181 |
start, end = self._period(None, None)
|
| 182 |
-
items =
|
| 183 |
if staff.role != "admin": # colleagues' staff code, permissions and activity are admin-only
|
| 184 |
items = [c.model_copy(update={"joined_with": None, "permissions": None, "activity": None})
|
| 185 |
if not c.is_me else c for c in items]
|
|
@@ -257,8 +266,7 @@ class StaffService:
|
|
| 257 |
|
| 258 |
async def list_requests(self, staff: Staff, status: str, paging: PageParams) -> RequestPage:
|
| 259 |
rows = await self.repo.requests(staff.team_id, status, paging.limit, paging.cursor) # type: ignore[arg-type]
|
| 260 |
-
page = rows
|
| 261 |
-
next_cursor = encode_cursor(page[-1][0].created_at, page[-1][0].id) if len(rows) > paging.limit else None
|
| 262 |
return RequestPage(items=[self._request_out(r, a) for r, a in page], next_cursor=next_cursor,
|
| 263 |
total_pending=await self.repo.total_pending(staff.team_id)) # type: ignore[arg-type]
|
| 264 |
|
|
@@ -316,8 +324,7 @@ class StaffService:
|
|
| 316 |
async def list_codes(self, staff: Staff, status: str, paging: PageParams):
|
| 317 |
now = _now()
|
| 318 |
rows = await self.repo.codes(staff.team_id, status, now, paging.limit, paging.cursor) # type: ignore[arg-type]
|
| 319 |
-
page = rows
|
| 320 |
-
next_cursor = encode_cursor(page[-1].created_at, page[-1].id) if len(rows) > paging.limit else None
|
| 321 |
return [code_out(c, now) for c in page], next_cursor
|
| 322 |
|
| 323 |
async def create_code(self, staff: Staff, body: StaffCodeCreate) -> StaffCodeOut:
|
|
|
|
| 9 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
|
| 11 |
from app.common.academy_access import Staff, normalize_permissions, visible_players_query
|
| 12 |
+
from app.common.labels import FOCUS_LABEL
|
| 13 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable
|
| 14 |
+
from app.core.pagination import PageParams, paginate
|
| 15 |
+
from app.core.rate_limit import get_academy_apply_limiter
|
| 16 |
from app.modules.academy.models import AcademyMembership, CoachAccessRequest, StaffCode
|
| 17 |
from app.modules.academy_staff.repository import StaffRepository
|
| 18 |
from app.modules.academy_staff.schemas import (
|
|
|
|
| 31 |
from app.modules.teams.models import Team
|
| 32 |
|
| 33 |
CODE_ALPHABET = "ABCDEFGHJKMNPQRSTUVWXYZ23456789" # no 0/O/1/I/L
|
|
|
|
|
|
|
| 34 |
|
| 35 |
|
| 36 |
def normalize_code(code: str) -> str:
|
|
|
|
| 90 |
|
| 91 |
async def apply(self, account: Account, raw_code: str) -> tuple[CoachAccessOut, bool]:
|
| 92 |
"""Returns (coach_access, created). Uses are counted at submission and a decline does not give one back."""
|
| 93 |
+
get_academy_apply_limiter().hit(f"coach_apply:{account.id}")
|
| 94 |
code = normalize_code(raw_code)
|
| 95 |
row = await self.repo.code_row(code, lock=True)
|
| 96 |
if row is None:
|
|
|
|
| 154 |
return start, end
|
| 155 |
|
| 156 |
async def _out(self, team: Team, member: Member, me_id: UUID, start: date, end: date) -> CoachOut:
|
| 157 |
+
return (await self._outs(team, [member], me_id, start, end))[0]
|
| 158 |
+
|
| 159 |
+
async def _outs(self, team: Team, members: list[Member], me_id: UUID, start: date, end: date) -> list[CoachOut]:
|
| 160 |
+
"""Activity and group queries run once for all members; only the visible-player count is per member."""
|
| 161 |
lo = datetime.combine(start, time.min, UTC)
|
| 162 |
hi = datetime.combine(end + timedelta(days=1), time.min, UTC)
|
| 163 |
+
ids = [m.account.id for m in members]
|
| 164 |
+
reviews = await self.repo.review_activity(team.id, ids, lo, hi)
|
| 165 |
+
drills = await self.repo.drills_set(team.id, ids, lo, hi)
|
| 166 |
+
groups = await self.repo.group_ids_many(team.id, ids)
|
| 167 |
+
out = []
|
| 168 |
+
for member in members:
|
| 169 |
+
who = Staff(member.account, team.id, member.role, member.sees_all, member.permissions)
|
| 170 |
+
count, avg_hours = reviews.get(member.account.id, (0, None))
|
| 171 |
+
activity = ActivityOut(
|
| 172 |
+
reviews=count, avg_reply_hours=avg_hours, players=await self.repo.count(visible_players_query(who)),
|
| 173 |
+
drills_set=drills.get(member.account.id, 0), period_start=start, period_end=end)
|
| 174 |
+
out.append(CoachOut(
|
| 175 |
+
id=member.account.id, name=member.account.name, coaches=FOCUS_LABEL[member.account.focus],
|
| 176 |
+
joined=member.joined, joined_with=member.joined_with, role=member.role,
|
| 177 |
+
is_me=member.account.id == me_id, sees_all=member.sees_all,
|
| 178 |
+
group_ids=groups.get(member.account.id, []), permissions=member.permissions,
|
| 179 |
+
activity=activity, status=member.status, version=member.version))
|
| 180 |
+
return out
|
| 181 |
|
| 182 |
async def list_coaches(self, staff: Staff, status: str | None) -> list[CoachOut]:
|
| 183 |
team = await self._team(staff)
|
|
|
|
| 188 |
owner = await self.repo.account(team.coach_id)
|
| 189 |
members.insert(0, self._owner(team, owner)) # type: ignore[arg-type]
|
| 190 |
start, end = self._period(None, None)
|
| 191 |
+
items = await self._outs(team, members, staff.id, start, end)
|
| 192 |
if staff.role != "admin": # colleagues' staff code, permissions and activity are admin-only
|
| 193 |
items = [c.model_copy(update={"joined_with": None, "permissions": None, "activity": None})
|
| 194 |
if not c.is_me else c for c in items]
|
|
|
|
| 266 |
|
| 267 |
async def list_requests(self, staff: Staff, status: str, paging: PageParams) -> RequestPage:
|
| 268 |
rows = await self.repo.requests(staff.team_id, status, paging.limit, paging.cursor) # type: ignore[arg-type]
|
| 269 |
+
page, next_cursor = paginate(rows, paging.limit, lambda r: (r[0].created_at, r[0].id))
|
|
|
|
| 270 |
return RequestPage(items=[self._request_out(r, a) for r, a in page], next_cursor=next_cursor,
|
| 271 |
total_pending=await self.repo.total_pending(staff.team_id)) # type: ignore[arg-type]
|
| 272 |
|
|
|
|
| 324 |
async def list_codes(self, staff: Staff, status: str, paging: PageParams):
|
| 325 |
now = _now()
|
| 326 |
rows = await self.repo.codes(staff.team_id, status, now, paging.limit, paging.cursor) # type: ignore[arg-type]
|
| 327 |
+
page, next_cursor = paginate(rows, paging.limit)
|
|
|
|
| 328 |
return [code_out(c, now) for c in page], next_cursor
|
| 329 |
|
| 330 |
async def create_code(self, staff: Staff, body: StaffCodeCreate) -> StaffCodeOut:
|
backend/app/modules/api_audit/service.py
CHANGED
|
@@ -7,7 +7,7 @@ from app.common.schemas import Page
|
|
| 7 |
from app.core.config import get_settings
|
| 8 |
from app.core.database import get_session_factory
|
| 9 |
from app.core.errors import ValidationFailed
|
| 10 |
-
from app.core.pagination import
|
| 11 |
from app.modules.api_audit.models import ApiRequestLog
|
| 12 |
from app.modules.api_audit.repository import AuditLogRepository
|
| 13 |
from app.modules.api_audit.schemas import AuditLogDetail, AuditLogSummary
|
|
@@ -38,10 +38,9 @@ class AuditLogService:
|
|
| 38 |
if paging.cursor and paging.cursor.created_at.utcoffset() is None:
|
| 39 |
raise ValidationFailed(fields={"cursor": "Cursor timestamp needs a timezone."})
|
| 40 |
rows = await self.repo.search(paging, filters, since, until)
|
| 41 |
-
|
| 42 |
-
rows = rows[:paging.limit]
|
| 43 |
return Page[AuditLogSummary](items=[AuditLogSummary.model_validate(row) for row in rows],
|
| 44 |
-
next_cursor=
|
| 45 |
|
| 46 |
async def get(self, log_id):
|
| 47 |
return AuditLogDetail.model_validate(await self.repo.get_or_404(log_id))
|
|
|
|
| 7 |
from app.core.config import get_settings
|
| 8 |
from app.core.database import get_session_factory
|
| 9 |
from app.core.errors import ValidationFailed
|
| 10 |
+
from app.core.pagination import paginate
|
| 11 |
from app.modules.api_audit.models import ApiRequestLog
|
| 12 |
from app.modules.api_audit.repository import AuditLogRepository
|
| 13 |
from app.modules.api_audit.schemas import AuditLogDetail, AuditLogSummary
|
|
|
|
| 38 |
if paging.cursor and paging.cursor.created_at.utcoffset() is None:
|
| 39 |
raise ValidationFailed(fields={"cursor": "Cursor timestamp needs a timezone."})
|
| 40 |
rows = await self.repo.search(paging, filters, since, until)
|
| 41 |
+
rows, next_cursor = paginate(rows, paging.limit)
|
|
|
|
| 42 |
return Page[AuditLogSummary](items=[AuditLogSummary.model_validate(row) for row in rows],
|
| 43 |
+
next_cursor=next_cursor)
|
| 44 |
|
| 45 |
async def get(self, log_id):
|
| 46 |
return AuditLogDetail.model_validate(await self.repo.get_or_404(log_id))
|
backend/app/modules/assignments/controller.py
CHANGED
|
@@ -4,7 +4,6 @@ from typing import Annotated, Literal
|
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from fastapi import APIRouter, Depends, Header, Query
|
| 7 |
-
from pydantic import BaseModel
|
| 8 |
|
| 9 |
from app.common.academy_access import CurrentStaff
|
| 10 |
from app.core.dependencies import CurrentAccount, CurrentPlayer, Db, Paging, Storage
|
|
@@ -16,13 +15,6 @@ from app.modules.idempotency.service import run_idempotent
|
|
| 16 |
router = APIRouter(prefix="/v1", tags=["assignments"])
|
| 17 |
|
| 18 |
|
| 19 |
-
class _Scoped(BaseModel):
|
| 20 |
-
"""Idempotency payload that also covers the path id, so one key cannot replay across targets."""
|
| 21 |
-
|
| 22 |
-
target: UUID
|
| 23 |
-
body: dict
|
| 24 |
-
|
| 25 |
-
|
| 26 |
@router.get("/drill-assignments", response_model=AssignmentPage)
|
| 27 |
async def list_assignments(
|
| 28 |
mode: Annotated[Mode, Query()], account: CurrentAccount, db: Db, storage: Storage, paging: Paging,
|
|
@@ -42,8 +34,7 @@ async def assign_drill(
|
|
| 42 |
async def handler() -> AssignmentEnvelope:
|
| 43 |
return AssignmentEnvelope(assignment=await service.assign(staff, player_id, body))
|
| 44 |
|
| 45 |
-
|
| 46 |
-
return await run_idempotent(db, staff.id, idempotency_key, scoped, handler, status_code=201)
|
| 47 |
|
| 48 |
|
| 49 |
@router.post("/drill-assignments/{assignment_id}/sets", status_code=201, response_model=SetResult)
|
|
@@ -56,6 +47,5 @@ async def log_set(
|
|
| 56 |
async def handler() -> SetResult:
|
| 57 |
return await service.log_set(player, assignment_id, body)
|
| 58 |
|
| 59 |
-
return await run_idempotent(db, player.id, idempotency_key,
|
| 60 |
-
|
| 61 |
-
status_code=201)
|
|
|
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from fastapi import APIRouter, Depends, Header, Query
|
|
|
|
| 7 |
|
| 8 |
from app.common.academy_access import CurrentStaff
|
| 9 |
from app.core.dependencies import CurrentAccount, CurrentPlayer, Db, Paging, Storage
|
|
|
|
| 15 |
router = APIRouter(prefix="/v1", tags=["assignments"])
|
| 16 |
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
@router.get("/drill-assignments", response_model=AssignmentPage)
|
| 19 |
async def list_assignments(
|
| 20 |
mode: Annotated[Mode, Query()], account: CurrentAccount, db: Db, storage: Storage, paging: Paging,
|
|
|
|
| 34 |
async def handler() -> AssignmentEnvelope:
|
| 35 |
return AssignmentEnvelope(assignment=await service.assign(staff, player_id, body))
|
| 36 |
|
| 37 |
+
return await run_idempotent(db, staff.id, idempotency_key, body, handler, status_code=201, scope=player_id)
|
|
|
|
| 38 |
|
| 39 |
|
| 40 |
@router.post("/drill-assignments/{assignment_id}/sets", status_code=201, response_model=SetResult)
|
|
|
|
| 47 |
async def handler() -> SetResult:
|
| 48 |
return await service.log_set(player, assignment_id, body)
|
| 49 |
|
| 50 |
+
return await run_idempotent(db, player.id, idempotency_key, body, handler, status_code=201,
|
| 51 |
+
scope=assignment_id)
|
|
|
backend/app/modules/assignments/repository.py
CHANGED
|
@@ -4,9 +4,9 @@ from uuid import UUID
|
|
| 4 |
from sqlalchemy import Select, exists, func, select, tuple_
|
| 5 |
|
| 6 |
from app.common.base_repository import BaseRepository
|
|
|
|
| 7 |
from app.core.pagination import Cursor
|
| 8 |
from app.modules.academy.models import LibraryDrill
|
| 9 |
-
from app.modules.accounts.models import Account
|
| 10 |
from app.modules.assignments.models import AssignmentSet, DrillAssignment
|
| 11 |
from app.modules.drills.models import DrillLog
|
| 12 |
from app.modules.sessions.models import SwingSession
|
|
@@ -33,11 +33,7 @@ class AssignmentRepository(BaseRepository[DrillAssignment]):
|
|
| 33 |
select(func.count()).select_from(AssignmentSet).where(AssignmentSet.assignment_id == assignment_id)) or 0
|
| 34 |
|
| 35 |
async def names(self, ids: set[UUID | None]) -> dict[UUID, str]:
|
| 36 |
-
|
| 37 |
-
if not ids:
|
| 38 |
-
return {}
|
| 39 |
-
rows = await self.session.execute(select(Account.id, Account.name).where(Account.id.in_(ids)))
|
| 40 |
-
return {i: n for i, n in rows}
|
| 41 |
|
| 42 |
def list_query(self, *, mode: str, status: str, player_ids: Select | None, player_id: UUID | None,
|
| 43 |
team_id: UUID | None) -> Select:
|
|
|
|
| 4 |
from sqlalchemy import Select, exists, func, select, tuple_
|
| 5 |
|
| 6 |
from app.common.base_repository import BaseRepository
|
| 7 |
+
from app.common.names import account_names
|
| 8 |
from app.core.pagination import Cursor
|
| 9 |
from app.modules.academy.models import LibraryDrill
|
|
|
|
| 10 |
from app.modules.assignments.models import AssignmentSet, DrillAssignment
|
| 11 |
from app.modules.drills.models import DrillLog
|
| 12 |
from app.modules.sessions.models import SwingSession
|
|
|
|
| 33 |
select(func.count()).select_from(AssignmentSet).where(AssignmentSet.assignment_id == assignment_id)) or 0
|
| 34 |
|
| 35 |
async def names(self, ids: set[UUID | None]) -> dict[UUID, str]:
|
| 36 |
+
return await account_names(self.session, ids)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
def list_query(self, *, mode: str, status: str, player_ids: Select | None, player_id: UUID | None,
|
| 39 |
team_id: UUID | None) -> Select:
|
backend/app/modules/assignments/service.py
CHANGED
|
@@ -1,10 +1,8 @@
|
|
| 1 |
"""Drill assignments (N20-N22). Progress is the number of AssignmentSet rows; each set also writes one drill log."""
|
| 2 |
|
| 3 |
-
from datetime import UTC, date, datetime
|
| 4 |
-
from functools import cache
|
| 5 |
from uuid import UUID
|
| 6 |
|
| 7 |
-
from ai_coach.knowledge import all_drills
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
|
| 10 |
from app.common.academy_access import (
|
|
@@ -14,10 +12,11 @@ from app.common.academy_access import (
|
|
| 14 |
staff_context,
|
| 15 |
visible_players_query,
|
| 16 |
)
|
|
|
|
|
|
|
| 17 |
from app.common.notify import notify
|
| 18 |
-
from app.common.schemas import MediaRef
|
| 19 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 20 |
-
from app.core.pagination import PageParams,
|
| 21 |
from app.integrations.push import PushClient
|
| 22 |
from app.integrations.storage import StorageClient
|
| 23 |
from app.modules.accounts.models import Account
|
|
@@ -25,13 +24,6 @@ from app.modules.assignments.models import DrillAssignment
|
|
| 25 |
from app.modules.assignments.repository import AssignmentRepository
|
| 26 |
from app.modules.assignments.schemas import AssignIn, AssignmentOut, AssignmentPage, SetIn, SetLogOut, SetResult
|
| 27 |
|
| 28 |
-
DISCIPLINES = {"h": "hitting", "p": "pitching"}
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
@cache
|
| 32 |
-
def _catalog() -> dict[str, dict]:
|
| 33 |
-
return {d["id"]: d for d in all_drills()}
|
| 34 |
-
|
| 35 |
|
| 36 |
def due_label(due: date, today: date) -> str:
|
| 37 |
days = (due - today).days
|
|
@@ -61,8 +53,7 @@ class AssignmentService:
|
|
| 61 |
ref = None
|
| 62 |
if a.drill_source == "library" and self.storage is not None and UUID(a.drill_id) in media:
|
| 63 |
upload_id, key = media[UUID(a.drill_id)]
|
| 64 |
-
ref =
|
| 65 |
-
expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl))
|
| 66 |
out.append(AssignmentOut(
|
| 67 |
id=a.id, player_id=a.player_id, mode=a.mode, drill_id=a.drill_id, drill_source=a.drill_source,
|
| 68 |
name=a.name, fixes=a.fixes, sets=a.sets, reps=a.reps, due=due_label(a.due_date, today),
|
|
@@ -90,15 +81,14 @@ class AssignmentService:
|
|
| 90 |
query = self.repo.list_query(mode=mode, status=status, player_ids=visible_players_query(staff),
|
| 91 |
player_id=player_id, team_id=staff.team_id)
|
| 92 |
rows = await self.repo.page(query, paging.cursor, paging.limit)
|
| 93 |
-
page = rows
|
| 94 |
items = await self._outs([(a, n) for a, n in page])
|
| 95 |
-
cursor = encode_cursor(page[-1][0].created_at, page[-1][0].id) if len(rows) > paging.limit else None
|
| 96 |
return AssignmentPage(items=items, next_cursor=cursor)
|
| 97 |
|
| 98 |
async def _source(self, staff: Staff, body: AssignIn) -> tuple[str, str]:
|
| 99 |
"""(name, fixes) snapshot of the drill, or the error to raise."""
|
| 100 |
if body.drill_source == "catalog":
|
| 101 |
-
drill =
|
| 102 |
if drill is None:
|
| 103 |
raise NotFound("Drill not found.", code="DRILL_NOT_FOUND")
|
| 104 |
if drill["discipline"] != DISCIPLINES[body.mode]:
|
|
|
|
| 1 |
"""Drill assignments (N20-N22). Progress is the number of AssignmentSet rows; each set also writes one drill log."""
|
| 2 |
|
| 3 |
+
from datetime import UTC, date, datetime
|
|
|
|
| 4 |
from uuid import UUID
|
| 5 |
|
|
|
|
| 6 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
|
| 8 |
from app.common.academy_access import (
|
|
|
|
| 12 |
staff_context,
|
| 13 |
visible_players_query,
|
| 14 |
)
|
| 15 |
+
from app.common.labels import DISCIPLINES, drill_catalog
|
| 16 |
+
from app.common.media import media_ref
|
| 17 |
from app.common.notify import notify
|
|
|
|
| 18 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 19 |
+
from app.core.pagination import PageParams, paginate
|
| 20 |
from app.integrations.push import PushClient
|
| 21 |
from app.integrations.storage import StorageClient
|
| 22 |
from app.modules.accounts.models import Account
|
|
|
|
| 24 |
from app.modules.assignments.repository import AssignmentRepository
|
| 25 |
from app.modules.assignments.schemas import AssignIn, AssignmentOut, AssignmentPage, SetIn, SetLogOut, SetResult
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def due_label(due: date, today: date) -> str:
|
| 29 |
days = (due - today).days
|
|
|
|
| 53 |
ref = None
|
| 54 |
if a.drill_source == "library" and self.storage is not None and UUID(a.drill_id) in media:
|
| 55 |
upload_id, key = media[UUID(a.drill_id)]
|
| 56 |
+
ref = media_ref(self.storage, upload_id, key)
|
|
|
|
| 57 |
out.append(AssignmentOut(
|
| 58 |
id=a.id, player_id=a.player_id, mode=a.mode, drill_id=a.drill_id, drill_source=a.drill_source,
|
| 59 |
name=a.name, fixes=a.fixes, sets=a.sets, reps=a.reps, due=due_label(a.due_date, today),
|
|
|
|
| 81 |
query = self.repo.list_query(mode=mode, status=status, player_ids=visible_players_query(staff),
|
| 82 |
player_id=player_id, team_id=staff.team_id)
|
| 83 |
rows = await self.repo.page(query, paging.cursor, paging.limit)
|
| 84 |
+
page, cursor = paginate(rows, paging.limit, lambda r: (r[0].created_at, r[0].id))
|
| 85 |
items = await self._outs([(a, n) for a, n in page])
|
|
|
|
| 86 |
return AssignmentPage(items=items, next_cursor=cursor)
|
| 87 |
|
| 88 |
async def _source(self, staff: Staff, body: AssignIn) -> tuple[str, str]:
|
| 89 |
"""(name, fixes) snapshot of the drill, or the error to raise."""
|
| 90 |
if body.drill_source == "catalog":
|
| 91 |
+
drill = drill_catalog().get(body.drill_id)
|
| 92 |
if drill is None:
|
| 93 |
raise NotFound("Drill not found.", code="DRILL_NOT_FOUND")
|
| 94 |
if drill["discipline"] != DISCIPLINES[body.mode]:
|
backend/app/modules/catalog/service.py
CHANGED
|
@@ -2,10 +2,9 @@
|
|
| 2 |
|
| 3 |
from ai_coach.swing_report import repository as registry
|
| 4 |
|
|
|
|
| 5 |
from app.modules.catalog.schemas import CatalogOut, DrillOut, GroupOut, MetricOut
|
| 6 |
|
| 7 |
-
DISCIPLINES = {"h": "hitting", "p": "pitching"}
|
| 8 |
-
|
| 9 |
|
| 10 |
class CatalogService:
|
| 11 |
def metrics(self, mode: str) -> CatalogOut:
|
|
|
|
| 2 |
|
| 3 |
from ai_coach.swing_report import repository as registry
|
| 4 |
|
| 5 |
+
from app.common.labels import DISCIPLINES
|
| 6 |
from app.modules.catalog.schemas import CatalogOut, DrillOut, GroupOut, MetricOut
|
| 7 |
|
|
|
|
|
|
|
| 8 |
|
| 9 |
class CatalogService:
|
| 10 |
def metrics(self, mode: str) -> CatalogOut:
|
backend/app/modules/coach/service.py
CHANGED
|
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|
| 8 |
from app.common.academy_access import Staff, require_player, sessions_shared, visible_players_query
|
| 9 |
from app.common.schemas import Page
|
| 10 |
from app.core.errors import Forbidden
|
| 11 |
-
from app.core.pagination import PageParams,
|
| 12 |
from app.integrations.storage import StorageClient
|
| 13 |
from app.modules.accounts.models import Account
|
| 14 |
from app.modules.coach.repository import (
|
|
@@ -74,10 +74,7 @@ class CoachService:
|
|
| 74 |
raise Forbidden("This player does not share sessions with coaches.", code="SESSIONS_PRIVATE")
|
| 75 |
query = player_sessions_query(player_id, mode, paging.cursor, paging.limit + 1)
|
| 76 |
items = await load_summaries(self.db, self.storage, query)
|
| 77 |
-
next_cursor =
|
| 78 |
-
if len(items) > paging.limit:
|
| 79 |
-
items = items[:paging.limit]
|
| 80 |
-
next_cursor = encode_cursor(items[-1].created_at, items[-1].id)
|
| 81 |
return Page[SessionSummary](items=items, next_cursor=next_cursor)
|
| 82 |
|
| 83 |
async def queue(self, staff: Staff, since: datetime | None) -> QueueResponse:
|
|
|
|
| 8 |
from app.common.academy_access import Staff, require_player, sessions_shared, visible_players_query
|
| 9 |
from app.common.schemas import Page
|
| 10 |
from app.core.errors import Forbidden
|
| 11 |
+
from app.core.pagination import PageParams, paginate
|
| 12 |
from app.integrations.storage import StorageClient
|
| 13 |
from app.modules.accounts.models import Account
|
| 14 |
from app.modules.coach.repository import (
|
|
|
|
| 74 |
raise Forbidden("This player does not share sessions with coaches.", code="SESSIONS_PRIVATE")
|
| 75 |
query = player_sessions_query(player_id, mode, paging.cursor, paging.limit + 1)
|
| 76 |
items = await load_summaries(self.db, self.storage, query)
|
| 77 |
+
items, next_cursor = paginate(items, paging.limit)
|
|
|
|
|
|
|
|
|
|
| 78 |
return Page[SessionSummary](items=items, next_cursor=next_cursor)
|
| 79 |
|
| 80 |
async def queue(self, staff: Staff, since: datetime | None) -> QueueResponse:
|
backend/app/modules/goals/service.py
CHANGED
|
@@ -13,7 +13,7 @@ from app.common.academy_access import Staff, can_see_player, require_player, sta
|
|
| 13 |
from app.common.notify import notify
|
| 14 |
from app.common.schemas import Page
|
| 15 |
from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed
|
| 16 |
-
from app.core.pagination import PageParams,
|
| 17 |
from app.integrations.push import PushClient
|
| 18 |
from app.modules.accounts.models import Account
|
| 19 |
from app.modules.goals.models import Goal
|
|
@@ -169,20 +169,16 @@ class GoalService:
|
|
| 169 |
async def history(self, account: Account, player_id: UUID, mode: str, paging: PageParams) -> Page[GoalHistoryOut]:
|
| 170 |
team_id = await self._authorize_read(account, player_id)
|
| 171 |
rows = list(await self.goals.ended(player_id, mode, paging.cursor, paging.limit, team_id=team_id))
|
| 172 |
-
page = rows
|
| 173 |
items = [GoalHistoryOut(id=g.id, text=_text(g), range=_range(g), met=_met(g), outcome=g.outcome,
|
| 174 |
start_at=g.created_at, end_at=g.ended_at, evaluated_session_id=g.evaluated_session_id)
|
| 175 |
for g in page]
|
| 176 |
-
|
| 177 |
-
return Page[GoalHistoryOut](items=items, next_cursor=encode_cursor(page[-1].created_at, page[-1].id)
|
| 178 |
-
if more else None)
|
| 179 |
|
| 180 |
async def milestones(self, account: Account, mode: str, paging: PageParams) -> Page[MilestoneOut]:
|
| 181 |
rows = list(await self.goals.ended(account.id, mode, paging.cursor, paging.limit, met_only=True))
|
| 182 |
-
page = rows
|
| 183 |
items = [MilestoneOut(id=g.id, icon="flag", tone="b", title=f"Goal met: {_text(g)}",
|
| 184 |
when=_fmt(g.ended_at, True), occurred_at=g.ended_at, source_goal_id=g.id) # type: ignore[arg-type]
|
| 185 |
for g in page]
|
| 186 |
-
|
| 187 |
-
return Page[MilestoneOut](items=items, next_cursor=encode_cursor(page[-1].created_at, page[-1].id)
|
| 188 |
-
if more else None)
|
|
|
|
| 13 |
from app.common.notify import notify
|
| 14 |
from app.common.schemas import Page
|
| 15 |
from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed
|
| 16 |
+
from app.core.pagination import PageParams, paginate
|
| 17 |
from app.integrations.push import PushClient
|
| 18 |
from app.modules.accounts.models import Account
|
| 19 |
from app.modules.goals.models import Goal
|
|
|
|
| 169 |
async def history(self, account: Account, player_id: UUID, mode: str, paging: PageParams) -> Page[GoalHistoryOut]:
|
| 170 |
team_id = await self._authorize_read(account, player_id)
|
| 171 |
rows = list(await self.goals.ended(player_id, mode, paging.cursor, paging.limit, team_id=team_id))
|
| 172 |
+
page, next_cursor = paginate(rows, paging.limit)
|
| 173 |
items = [GoalHistoryOut(id=g.id, text=_text(g), range=_range(g), met=_met(g), outcome=g.outcome,
|
| 174 |
start_at=g.created_at, end_at=g.ended_at, evaluated_session_id=g.evaluated_session_id)
|
| 175 |
for g in page]
|
| 176 |
+
return Page[GoalHistoryOut](items=items, next_cursor=next_cursor)
|
|
|
|
|
|
|
| 177 |
|
| 178 |
async def milestones(self, account: Account, mode: str, paging: PageParams) -> Page[MilestoneOut]:
|
| 179 |
rows = list(await self.goals.ended(account.id, mode, paging.cursor, paging.limit, met_only=True))
|
| 180 |
+
page, next_cursor = paginate(rows, paging.limit)
|
| 181 |
items = [MilestoneOut(id=g.id, icon="flag", tone="b", title=f"Goal met: {_text(g)}",
|
| 182 |
when=_fmt(g.ended_at, True), occurred_at=g.ended_at, source_goal_id=g.id) # type: ignore[arg-type]
|
| 183 |
for g in page]
|
| 184 |
+
return Page[MilestoneOut](items=items, next_cursor=next_cursor)
|
|
|
|
|
|
backend/app/modules/idempotency/service.py
CHANGED
|
@@ -6,6 +6,7 @@ Usage in a controller:
|
|
| 6 |
|
| 7 |
The first call runs the handler and stores its response; a retry with the same key and body replays it;
|
| 8 |
the same key with a different body is a 409.
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
import hashlib
|
|
@@ -22,8 +23,11 @@ from app.core.errors import Conflict
|
|
| 22 |
from app.modules.idempotency.models import IdempotencyKey
|
| 23 |
|
| 24 |
|
| 25 |
-
def _hash(body: BaseModel) -> str:
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
|
| 29 |
async def run_idempotent(
|
|
@@ -34,10 +38,11 @@ async def run_idempotent(
|
|
| 34 |
handler: Callable[[], Awaitable[BaseModel]],
|
| 35 |
*,
|
| 36 |
status_code: int,
|
|
|
|
| 37 |
) -> JSONResponse:
|
| 38 |
if not key:
|
| 39 |
return JSONResponse(jsonable_encoder(await handler()), status_code=status_code)
|
| 40 |
-
request_hash = _hash(body)
|
| 41 |
stored = await db.get(IdempotencyKey, (account_id, key))
|
| 42 |
if stored is not None:
|
| 43 |
if stored.request_hash != request_hash:
|
|
|
|
| 6 |
|
| 7 |
The first call runs the handler and stores its response; a retry with the same key and body replays it;
|
| 8 |
the same key with a different body is a 409.
|
| 9 |
+
Pass scope=<path id> when the route has a target id, so one key cannot replay across targets.
|
| 10 |
"""
|
| 11 |
|
| 12 |
import hashlib
|
|
|
|
| 23 |
from app.modules.idempotency.models import IdempotencyKey
|
| 24 |
|
| 25 |
|
| 26 |
+
def _hash(body: BaseModel, scope: UUID | None) -> str:
|
| 27 |
+
payload = body.model_dump(mode="json")
|
| 28 |
+
if scope is not None:
|
| 29 |
+
payload = {"target": str(scope), "body": payload}
|
| 30 |
+
return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
|
| 31 |
|
| 32 |
|
| 33 |
async def run_idempotent(
|
|
|
|
| 38 |
handler: Callable[[], Awaitable[BaseModel]],
|
| 39 |
*,
|
| 40 |
status_code: int,
|
| 41 |
+
scope: UUID | None = None,
|
| 42 |
) -> JSONResponse:
|
| 43 |
if not key:
|
| 44 |
return JSONResponse(jsonable_encoder(await handler()), status_code=status_code)
|
| 45 |
+
request_hash = _hash(body, scope)
|
| 46 |
stored = await db.get(IdempotencyKey, (account_id, key))
|
| 47 |
if stored is not None:
|
| 48 |
if stored.request_hash != request_hash:
|
backend/app/modules/notifications/service.py
CHANGED
|
@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
|
|
| 7 |
|
| 8 |
from app.common.schemas import Page
|
| 9 |
from app.core.errors import NotFound
|
| 10 |
-
from app.core.pagination import PageParams,
|
| 11 |
from app.modules.accounts.models import Account
|
| 12 |
from app.modules.notifications.repository import NotificationRepository
|
| 13 |
from app.modules.notifications.schemas import NotificationOut, UnreadCount
|
|
@@ -19,10 +19,9 @@ class NotificationService:
|
|
| 19 |
|
| 20 |
async def list(self, account: Account, paging: PageParams) -> Page[NotificationOut]:
|
| 21 |
rows = await self.notifications.page(account.id, paging.cursor, paging.limit + 1)
|
| 22 |
-
next_cursor =
|
| 23 |
-
if len(rows) > paging.limit else None
|
| 24 |
items = [NotificationOut(id=r.id, kind=r.kind, title=r.title, body=r.body, at=r.created_at,
|
| 25 |
-
read=r.read_at is not None, target=r.target) for r in
|
| 26 |
return Page[NotificationOut](items=items, next_cursor=next_cursor)
|
| 27 |
|
| 28 |
async def unread_count(self, account: Account) -> UnreadCount:
|
|
|
|
| 7 |
|
| 8 |
from app.common.schemas import Page
|
| 9 |
from app.core.errors import NotFound
|
| 10 |
+
from app.core.pagination import PageParams, paginate
|
| 11 |
from app.modules.accounts.models import Account
|
| 12 |
from app.modules.notifications.repository import NotificationRepository
|
| 13 |
from app.modules.notifications.schemas import NotificationOut, UnreadCount
|
|
|
|
| 19 |
|
| 20 |
async def list(self, account: Account, paging: PageParams) -> Page[NotificationOut]:
|
| 21 |
rows = await self.notifications.page(account.id, paging.cursor, paging.limit + 1)
|
| 22 |
+
page, next_cursor = paginate(rows, paging.limit)
|
|
|
|
| 23 |
items = [NotificationOut(id=r.id, kind=r.kind, title=r.title, body=r.body, at=r.created_at,
|
| 24 |
+
read=r.read_at is not None, target=r.target) for r in page]
|
| 25 |
return Page[NotificationOut](items=items, next_cursor=next_cursor)
|
| 26 |
|
| 27 |
async def unread_count(self, account: Account) -> UnreadCount:
|
backend/app/modules/reporting/service.py
CHANGED
|
@@ -22,12 +22,12 @@ import re
|
|
| 22 |
import uuid
|
| 23 |
from datetime import UTC, datetime, timedelta
|
| 24 |
|
| 25 |
-
import httpx
|
| 26 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 27 |
|
| 28 |
from app.common.academy_access import Staff
|
|
|
|
| 29 |
from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed
|
| 30 |
-
from app.core.pagination import Cursor,
|
| 31 |
from app.integrations.storage import StorageClient
|
| 32 |
from app.modules.reporting.repository import ReportingRepository
|
| 33 |
from app.modules.reporting.schemas import (
|
|
@@ -47,7 +47,6 @@ from app.modules.reporting.schemas import (
|
|
| 47 |
REVENUE_UNAVAILABLE = "Revenue ledger not configured"
|
| 48 |
EXPORT_MAX_ROWS = 5000
|
| 49 |
_MONTH = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
| 50 |
-
_FOCUS = {"h": "Hitting", "p": "Pitching", "both": "Both"}
|
| 51 |
_FORMULA_PREFIX = ("=", "+", "-", "@", "\t", "\r")
|
| 52 |
|
| 53 |
|
|
@@ -89,7 +88,7 @@ class ReportingService:
|
|
| 89 |
denominator, improved = await repo.improving(team, start, end)
|
| 90 |
scores = await repo.latest_scores(team, end)
|
| 91 |
reviews = await repo.reviews_by_coach(team, start, end)
|
| 92 |
-
coaches = [CoachActivity(id=cid, name=name, coaches=
|
| 93 |
for cid, name, focus in await repo.coach_rows(team)]
|
| 94 |
return DashboardResponse(dashboard=Dashboard(
|
| 95 |
month=label,
|
|
@@ -98,8 +97,7 @@ class ReportingService:
|
|
| 98 |
improving_pct=round(100 * improved / denominator) if denominator else None,
|
| 99 |
analyses_this_week=await repo.analyses_since(team, now - timedelta(days=7)),
|
| 100 |
avg_review_hours=await repo.avg_review_hours(team, start, end),
|
| 101 |
-
cards=Cards(
|
| 102 |
-
r=sum(s < 60 for s in scores)),
|
| 103 |
coaches=coaches,
|
| 104 |
pending_requests=await repo.pending_requests(team),
|
| 105 |
not_filmed_7d=await repo.not_filmed_since(team, now - timedelta(days=7)),
|
|
@@ -141,8 +139,7 @@ class ReportingService:
|
|
| 141 |
await self._scope(staff, group_id)
|
| 142 |
accepted, ai_opt_in = await self.repo.consent_totals(staff.team_id, group_id)
|
| 143 |
rows = await self.repo.consent_rows(staff.team_id, group_id, limit + 1, cursor)
|
| 144 |
-
page = rows
|
| 145 |
-
next_cursor = encode_cursor(page[-1]["created_at"], page[-1]["player_id"]) if len(rows) > limit else None
|
| 146 |
return ConsentPage(items=[self._item(r) for r in page], next_cursor=next_cursor,
|
| 147 |
accepted=accepted, ai_opt_in=ai_opt_in)
|
| 148 |
|
|
@@ -168,10 +165,7 @@ class ReportingService:
|
|
| 168 |
now = datetime.now(UTC)
|
| 169 |
export_id = uuid.uuid4()
|
| 170 |
key = f"exports/{staff.team_id}/{export_id}.csv"
|
| 171 |
-
|
| 172 |
-
response = await http.put(self.storage.presign_put(key, "text/csv"), content=buffer.getvalue().encode(),
|
| 173 |
-
headers={"Content-Type": "text/csv"})
|
| 174 |
-
response.raise_for_status()
|
| 175 |
expires_at = now + timedelta(seconds=self.storage.download_ttl)
|
| 176 |
filename = f"consent-{now:%Y-%m-%d}.csv"
|
| 177 |
job = await self.repo.add_export(id=export_id, requester_id=staff.id, team_id=staff.team_id,
|
|
|
|
| 22 |
import uuid
|
| 23 |
from datetime import UTC, datetime, timedelta
|
| 24 |
|
|
|
|
| 25 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 26 |
|
| 27 |
from app.common.academy_access import Staff
|
| 28 |
+
from app.common.labels import FOCUS_LABEL, tone_counts
|
| 29 |
from app.core.errors import Conflict, Forbidden, NotFound, ValidationFailed
|
| 30 |
+
from app.core.pagination import Cursor, paginate
|
| 31 |
from app.integrations.storage import StorageClient
|
| 32 |
from app.modules.reporting.repository import ReportingRepository
|
| 33 |
from app.modules.reporting.schemas import (
|
|
|
|
| 47 |
REVENUE_UNAVAILABLE = "Revenue ledger not configured"
|
| 48 |
EXPORT_MAX_ROWS = 5000
|
| 49 |
_MONTH = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
|
|
|
| 50 |
_FORMULA_PREFIX = ("=", "+", "-", "@", "\t", "\r")
|
| 51 |
|
| 52 |
|
|
|
|
| 88 |
denominator, improved = await repo.improving(team, start, end)
|
| 89 |
scores = await repo.latest_scores(team, end)
|
| 90 |
reviews = await repo.reviews_by_coach(team, start, end)
|
| 91 |
+
coaches = [CoachActivity(id=cid, name=name, coaches=FOCUS_LABEL.get(focus, "Both"), reviews=reviews.get(cid, 0))
|
| 92 |
for cid, name, focus in await repo.coach_rows(team)]
|
| 93 |
return DashboardResponse(dashboard=Dashboard(
|
| 94 |
month=label,
|
|
|
|
| 97 |
improving_pct=round(100 * improved / denominator) if denominator else None,
|
| 98 |
analyses_this_week=await repo.analyses_since(team, now - timedelta(days=7)),
|
| 99 |
avg_review_hours=await repo.avg_review_hours(team, start, end),
|
| 100 |
+
cards=Cards(**tone_counts(scores)),
|
|
|
|
| 101 |
coaches=coaches,
|
| 102 |
pending_requests=await repo.pending_requests(team),
|
| 103 |
not_filmed_7d=await repo.not_filmed_since(team, now - timedelta(days=7)),
|
|
|
|
| 139 |
await self._scope(staff, group_id)
|
| 140 |
accepted, ai_opt_in = await self.repo.consent_totals(staff.team_id, group_id)
|
| 141 |
rows = await self.repo.consent_rows(staff.team_id, group_id, limit + 1, cursor)
|
| 142 |
+
page, next_cursor = paginate(rows, limit, lambda r: (r["created_at"], r["player_id"]))
|
|
|
|
| 143 |
return ConsentPage(items=[self._item(r) for r in page], next_cursor=next_cursor,
|
| 144 |
accepted=accepted, ai_opt_in=ai_opt_in)
|
| 145 |
|
|
|
|
| 165 |
now = datetime.now(UTC)
|
| 166 |
export_id = uuid.uuid4()
|
| 167 |
key = f"exports/{staff.team_id}/{export_id}.csv"
|
| 168 |
+
await self.storage.put_bytes(key, buffer.getvalue().encode(), "text/csv")
|
|
|
|
|
|
|
|
|
|
| 169 |
expires_at = now + timedelta(seconds=self.storage.download_ttl)
|
| 170 |
filename = f"consent-{now:%Y-%m-%d}.csv"
|
| 171 |
job = await self.repo.add_export(id=export_id, requester_id=staff.id, team_id=staff.team_id,
|
backend/app/modules/reviews/repository.py
CHANGED
|
@@ -46,9 +46,6 @@ class ReviewRepository(BaseRepository[Review]):
|
|
| 46 |
async def upload(self, upload_id: UUID) -> Upload | None:
|
| 47 |
return await self.session.get(Upload, upload_id)
|
| 48 |
|
| 49 |
-
async def locked_upload(self, upload_id: UUID) -> Upload | None:
|
| 50 |
-
return await self.session.scalar(select(Upload).where(Upload.id == upload_id).with_for_update())
|
| 51 |
-
|
| 52 |
async def locked_session_thread(self, session: SwingSession, coach_id: UUID, team_id: UUID | None) -> Thread:
|
| 53 |
"""The session's one thread, created if missing, locked for the counter update."""
|
| 54 |
query = select(Thread).where(Thread.session_id == session.id).with_for_update()
|
|
|
|
| 46 |
async def upload(self, upload_id: UUID) -> Upload | None:
|
| 47 |
return await self.session.get(Upload, upload_id)
|
| 48 |
|
|
|
|
|
|
|
|
|
|
| 49 |
async def locked_session_thread(self, session: SwingSession, coach_id: UUID, team_id: UUID | None) -> Thread:
|
| 50 |
"""The session's one thread, created if missing, locked for the counter update."""
|
| 51 |
query = select(Thread).where(Thread.session_id == session.id).with_for_update()
|
backend/app/modules/reviews/service.py
CHANGED
|
@@ -6,30 +6,22 @@ number so the player sees it as unread again) and the notification.
|
|
| 6 |
|
| 7 |
import hashlib
|
| 8 |
import json
|
| 9 |
-
from datetime import UTC, datetime, timedelta
|
| 10 |
-
from functools import cache
|
| 11 |
from uuid import UUID
|
| 12 |
|
| 13 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 14 |
|
| 15 |
from app.common.academy_access import Staff, can_see_player, sessions_shared
|
|
|
|
|
|
|
| 16 |
from app.common.notify import notify
|
| 17 |
from app.common.schemas import MediaRef
|
|
|
|
| 18 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 19 |
from app.integrations.push import PushClient
|
| 20 |
from app.integrations.storage import StorageClient
|
| 21 |
from app.modules.reviews.repository import ReviewRepository
|
| 22 |
from app.modules.reviews.schemas import ReviewOut, ReviewSubmit, ReviewSubmitted
|
| 23 |
|
| 24 |
-
_DISCIPLINES = {"h": "hitting", "p": "pitching"}
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
@cache
|
| 28 |
-
def drill_ids(discipline: str) -> frozenset[str]:
|
| 29 |
-
from ai_coach.knowledge import all_drills
|
| 30 |
-
|
| 31 |
-
return frozenset(d["id"] for d in all_drills() if d["discipline"] == discipline)
|
| 32 |
-
|
| 33 |
|
| 34 |
def _content_key(values: dict) -> str:
|
| 35 |
"""Same review content -> same key, so a byte-identical resend never notifies twice."""
|
|
@@ -56,7 +48,7 @@ class ReviewService:
|
|
| 56 |
raise Forbidden()
|
| 57 |
|
| 58 |
fields: dict[str, str] = {}
|
| 59 |
-
if body.drill_id
|
| 60 |
fields["drill_id"] = "Unknown drill for this session."
|
| 61 |
metric_ids = {m.get("metric_id") for m in (session.report or {}).get("measurements", [])}
|
| 62 |
for key in body.verdicts:
|
|
@@ -107,24 +99,20 @@ class ReviewService:
|
|
| 107 |
return {"voice_upload_id": upload_id, "voice_seconds": seconds}
|
| 108 |
|
| 109 |
async def _claim_audio(self, coach_id: UUID, upload_id: UUID, session_id: UUID) -> None:
|
| 110 |
-
|
| 111 |
-
if upload is None or upload.owner_id != coach_id or upload.kind != "audio":
|
| 112 |
-
raise Unprocessable("Not a valid audio upload.", code="INVALID_UPLOAD")
|
| 113 |
-
if await self.storage.head(upload.object_key) is None:
|
| 114 |
-
raise Conflict("The upload has not finished. Please try again.", code="UPLOAD_NOT_READY")
|
| 115 |
-
if upload.attached_at is not None:
|
| 116 |
current = await self.repo.get(session_id)
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
async def _voice_ref(self, review) -> MediaRef | None:
|
| 123 |
if review.voice_upload_id is None:
|
| 124 |
return None
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
return None
|
| 128 |
-
return MediaRef(upload_id=upload.id, url=self.storage.presign_get(upload.object_key),
|
| 129 |
-
expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl),
|
| 130 |
-
seconds=float(review.voice_seconds) if review.voice_seconds is not None else None)
|
|
|
|
| 6 |
|
| 7 |
import hashlib
|
| 8 |
import json
|
|
|
|
|
|
|
| 9 |
from uuid import UUID
|
| 10 |
|
| 11 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
|
| 13 |
from app.common.academy_access import Staff, can_see_player, sessions_shared
|
| 14 |
+
from app.common.labels import DISCIPLINES, drill_catalog
|
| 15 |
+
from app.common.media import upload_ref
|
| 16 |
from app.common.notify import notify
|
| 17 |
from app.common.schemas import MediaRef
|
| 18 |
+
from app.common.uploads import UploadErrors, claim_upload
|
| 19 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 20 |
from app.integrations.push import PushClient
|
| 21 |
from app.integrations.storage import StorageClient
|
| 22 |
from app.modules.reviews.repository import ReviewRepository
|
| 23 |
from app.modules.reviews.schemas import ReviewOut, ReviewSubmit, ReviewSubmitted
|
| 24 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
def _content_key(values: dict) -> str:
|
| 27 |
"""Same review content -> same key, so a byte-identical resend never notifies twice."""
|
|
|
|
| 48 |
raise Forbidden()
|
| 49 |
|
| 50 |
fields: dict[str, str] = {}
|
| 51 |
+
if drill_catalog().get(body.drill_id, {}).get("discipline") != DISCIPLINES[session.mode]:
|
| 52 |
fields["drill_id"] = "Unknown drill for this session."
|
| 53 |
metric_ids = {m.get("metric_id") for m in (session.report or {}).get("measurements", [])}
|
| 54 |
for key in body.verdicts:
|
|
|
|
| 99 |
return {"voice_upload_id": upload_id, "voice_seconds": seconds}
|
| 100 |
|
| 101 |
async def _claim_audio(self, coach_id: UUID, upload_id: UUID, session_id: UUID) -> None:
|
| 102 |
+
async def own_voice_note() -> bool: # the same review re-sending its own voice note
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
current = await self.repo.get(session_id)
|
| 104 |
+
return current is not None and current.voice_upload_id == upload_id
|
| 105 |
+
|
| 106 |
+
await claim_upload(
|
| 107 |
+
self.db, self.storage, upload_id, owner_id=coach_id, kind="audio",
|
| 108 |
+
errors=UploadErrors(
|
| 109 |
+
invalid=Unprocessable("Not a valid audio upload.", code="INVALID_UPLOAD"),
|
| 110 |
+
used=Unprocessable("This audio was already used.", code="UPLOAD_ALREADY_USED"),
|
| 111 |
+
not_ready=Conflict("The upload has not finished. Please try again.", code="UPLOAD_NOT_READY")),
|
| 112 |
+
reusable=own_voice_note)
|
| 113 |
|
| 114 |
async def _voice_ref(self, review) -> MediaRef | None:
|
| 115 |
if review.voice_upload_id is None:
|
| 116 |
return None
|
| 117 |
+
seconds = float(review.voice_seconds) if review.voice_seconds is not None else None
|
| 118 |
+
return upload_ref(self.storage, await self.repo.upload(review.voice_upload_id), seconds)
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/modules/sessions/repository.py
CHANGED
|
@@ -9,7 +9,6 @@ from app.modules.accounts.models import Account
|
|
| 9 |
from app.modules.reviews.models import Review
|
| 10 |
from app.modules.sessions.models import SwingSession
|
| 11 |
from app.modules.sessions.summary import summary_query
|
| 12 |
-
from app.modules.settings.models import ConsentEvent
|
| 13 |
from app.modules.uploads.models import Upload
|
| 14 |
|
| 15 |
|
|
@@ -53,14 +52,6 @@ class SessionRepository(BaseRepository[SwingSession]):
|
|
| 53 |
.where(Review.session_id == session_id))).first()
|
| 54 |
return (row[0], row[1] or "") if row else None
|
| 55 |
|
| 56 |
-
async def analysis_consent_blocked(self, account_id: UUID, require_accepted: bool) -> bool:
|
| 57 |
-
"""True when the latest analysis consent is a withdrawal, or (when required) there is no acceptance."""
|
| 58 |
-
action = await self.session.scalar(
|
| 59 |
-
select(ConsentEvent.action)
|
| 60 |
-
.where(ConsentEvent.account_id == account_id, ConsentEvent.category == "analysis")
|
| 61 |
-
.order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1))
|
| 62 |
-
return action == "withdrawn" or (require_accepted and action is None)
|
| 63 |
-
|
| 64 |
def summaries_query(self, owner_id: UUID, *, mode: str | None, is_self: bool | None, athlete_name: str | None,
|
| 65 |
since: datetime | None, cursor: Cursor | None, limit: int) -> Select:
|
| 66 |
query = summary_query().where(SwingSession.owner_id == owner_id)
|
|
|
|
| 9 |
from app.modules.reviews.models import Review
|
| 10 |
from app.modules.sessions.models import SwingSession
|
| 11 |
from app.modules.sessions.summary import summary_query
|
|
|
|
| 12 |
from app.modules.uploads.models import Upload
|
| 13 |
|
| 14 |
|
|
|
|
| 52 |
.where(Review.session_id == session_id))).first()
|
| 53 |
return (row[0], row[1] or "") if row else None
|
| 54 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
def summaries_query(self, owner_id: UUID, *, mode: str | None, is_self: bool | None, athlete_name: str | None,
|
| 56 |
since: datetime | None, cursor: Cursor | None, limit: int) -> Select:
|
| 57 |
query = summary_query().where(SwingSession.owner_id == owner_id)
|
backend/app/modules/sessions/service.py
CHANGED
|
@@ -8,10 +8,12 @@ from uuid import UUID
|
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
|
| 10 |
from app.common.academy_access import can_see_player, sessions_shared, staff_context
|
| 11 |
-
from app.common.
|
|
|
|
|
|
|
| 12 |
from app.core.config import get_settings
|
| 13 |
from app.core.errors import Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 14 |
-
from app.core.pagination import PageParams,
|
| 15 |
from app.integrations.storage import StorageClient
|
| 16 |
from app.modules.accounts.models import Account
|
| 17 |
from app.modules.billing.entitlement import EntitlementService
|
|
@@ -91,7 +93,7 @@ class SessionService:
|
|
| 91 |
# D2
|
| 92 |
async def create(self, account: Account, body: SessionIn) -> SessionOut:
|
| 93 |
validate_marks(body)
|
| 94 |
-
if await
|
| 95 |
raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
|
| 96 |
await EntitlementService(self.db).ensure_can_analyze(account.id)
|
| 97 |
|
|
@@ -161,10 +163,8 @@ class SessionService:
|
|
| 161 |
if r.voice_upload_id is not None:
|
| 162 |
voice_keys = await self.uploads.object_keys(r.voice_upload_id)
|
| 163 |
if r.voice_upload_id in voice_keys:
|
| 164 |
-
voice_note =
|
| 165 |
-
|
| 166 |
-
expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl),
|
| 167 |
-
seconds=float(r.voice_seconds) if r.voice_seconds is not None else None)
|
| 168 |
review = ReviewOut(coach_id=r.coach_id, coach_name=coach_name, cue=r.cue, drill_id=r.drill_id,
|
| 169 |
verdicts=r.verdicts, at=r.updated_at, voice_note=voice_note)
|
| 170 |
previous = await self.sessions.previous(s)
|
|
@@ -191,10 +191,7 @@ class SessionService:
|
|
| 191 |
query = self.sessions.summaries_query(owner.id, mode=mode, is_self=is_self, athlete_name=athlete_name,
|
| 192 |
since=since, cursor=paging.cursor, limit=paging.limit + 1)
|
| 193 |
items = await load_summaries(self.db, self.storage, query)
|
| 194 |
-
next_cursor =
|
| 195 |
-
if len(items) > paging.limit:
|
| 196 |
-
items = items[:paging.limit]
|
| 197 |
-
next_cursor = encode_cursor(items[-1].created_at, items[-1].id)
|
| 198 |
return Page[SessionSummary](items=items, next_cursor=next_cursor)
|
| 199 |
|
| 200 |
# D5
|
|
|
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 9 |
|
| 10 |
from app.common.academy_access import can_see_player, sessions_shared, staff_context
|
| 11 |
+
from app.common.consent import analysis_consent_blocked
|
| 12 |
+
from app.common.media import media_ref
|
| 13 |
+
from app.common.schemas import Page
|
| 14 |
from app.core.config import get_settings
|
| 15 |
from app.core.errors import Forbidden, NotFound, Unprocessable, ValidationFailed
|
| 16 |
+
from app.core.pagination import PageParams, paginate
|
| 17 |
from app.integrations.storage import StorageClient
|
| 18 |
from app.modules.accounts.models import Account
|
| 19 |
from app.modules.billing.entitlement import EntitlementService
|
|
|
|
| 93 |
# D2
|
| 94 |
async def create(self, account: Account, body: SessionIn) -> SessionOut:
|
| 95 |
validate_marks(body)
|
| 96 |
+
if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent):
|
| 97 |
raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
|
| 98 |
await EntitlementService(self.db).ensure_can_analyze(account.id)
|
| 99 |
|
|
|
|
| 163 |
if r.voice_upload_id is not None:
|
| 164 |
voice_keys = await self.uploads.object_keys(r.voice_upload_id)
|
| 165 |
if r.voice_upload_id in voice_keys:
|
| 166 |
+
voice_note = media_ref(self.storage, r.voice_upload_id, voice_keys[r.voice_upload_id],
|
| 167 |
+
float(r.voice_seconds) if r.voice_seconds is not None else None)
|
|
|
|
|
|
|
| 168 |
review = ReviewOut(coach_id=r.coach_id, coach_name=coach_name, cue=r.cue, drill_id=r.drill_id,
|
| 169 |
verdicts=r.verdicts, at=r.updated_at, voice_note=voice_note)
|
| 170 |
previous = await self.sessions.previous(s)
|
|
|
|
| 191 |
query = self.sessions.summaries_query(owner.id, mode=mode, is_self=is_self, athlete_name=athlete_name,
|
| 192 |
since=since, cursor=paging.cursor, limit=paging.limit + 1)
|
| 193 |
items = await load_summaries(self.db, self.storage, query)
|
| 194 |
+
items, next_cursor = paginate(items, paging.limit)
|
|
|
|
|
|
|
|
|
|
| 195 |
return Page[SessionSummary](items=items, next_cursor=next_cursor)
|
| 196 |
|
| 197 |
# D5
|
backend/app/modules/swing_reports/repository.py
CHANGED
|
@@ -4,7 +4,6 @@ from sqlalchemy import select
|
|
| 4 |
|
| 5 |
from app.common.base_repository import BaseRepository
|
| 6 |
from app.modules.sessions.models import SwingSession
|
| 7 |
-
from app.modules.settings.models import ConsentEvent
|
| 8 |
|
| 9 |
|
| 10 |
class SwingReportRepository(BaseRepository[SwingSession]):
|
|
@@ -16,11 +15,3 @@ class SwingReportRepository(BaseRepository[SwingSession]):
|
|
| 16 |
select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None))
|
| 17 |
.with_for_update())
|
| 18 |
return result.scalars().first()
|
| 19 |
-
|
| 20 |
-
async def analysis_consent_blocked(self, account_id: UUID, require_accepted: bool) -> bool:
|
| 21 |
-
"""True when the latest analysis consent is a withdrawal, or (when required) there is no acceptance."""
|
| 22 |
-
action = await self.session.scalar(
|
| 23 |
-
select(ConsentEvent.action)
|
| 24 |
-
.where(ConsentEvent.account_id == account_id, ConsentEvent.category == "analysis")
|
| 25 |
-
.order_by(ConsentEvent.created_at.desc(), ConsentEvent.id.desc()).limit(1))
|
| 26 |
-
return action == "withdrawn" or (require_accepted and action is None)
|
|
|
|
| 4 |
|
| 5 |
from app.common.base_repository import BaseRepository
|
| 6 |
from app.modules.sessions.models import SwingSession
|
|
|
|
| 7 |
|
| 8 |
|
| 9 |
class SwingReportRepository(BaseRepository[SwingSession]):
|
|
|
|
| 15 |
select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None))
|
| 16 |
.with_for_update())
|
| 17 |
return result.scalars().first()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/modules/swing_reports/service.py
CHANGED
|
@@ -15,6 +15,7 @@ from ai_coach.config import get_settings as get_coach_settings
|
|
| 15 |
from ai_coach.swing_report import AthleteContext, InvalidPayload, build_report, validate_payload
|
| 16 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
|
|
|
|
| 18 |
from app.core.config import get_settings
|
| 19 |
from app.core.errors import Conflict, Forbidden, NotFound, ServiceUnavailable, Unprocessable
|
| 20 |
from app.modules.accounts.models import Account
|
|
@@ -68,8 +69,8 @@ class SwingReportService:
|
|
| 68 |
# Validation is cheap and runs first, so a broken payload never reaches the plan check or the model.
|
| 69 |
parsed, problems = validate_payload(payload)
|
| 70 |
if parsed is None:
|
| 71 |
-
raise Unprocessable("The payload does not follow swing analysis contract 1.0.",
|
| 72 |
-
fields=problems)
|
| 73 |
|
| 74 |
if session.report is not None:
|
| 75 |
if session.analysis_id != parsed.analysis_id:
|
|
@@ -78,7 +79,7 @@ class SwingReportService:
|
|
| 78 |
return session.report
|
| 79 |
if parsed.analysis_revision < (session.analysis_revision or 0):
|
| 80 |
raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION")
|
| 81 |
-
if await
|
| 82 |
raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
|
| 83 |
ensure_coach_configured()
|
| 84 |
if session.analyzed_at is None:
|
|
@@ -90,7 +91,17 @@ class SwingReportService:
|
|
| 90 |
except InvalidPayload as exc: # defensive: the builder re-validates
|
| 91 |
raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
await self.sessions.update(
|
| 94 |
session, measurement_payload=payload, report=report, analysis_id=parsed.analysis_id,
|
| 95 |
-
analysis_revision=parsed.analysis_revision,
|
|
|
|
| 96 |
return report
|
|
|
|
| 15 |
from ai_coach.swing_report import AthleteContext, InvalidPayload, build_report, validate_payload
|
| 16 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
|
| 18 |
+
from app.common.consent import analysis_consent_blocked
|
| 19 |
from app.core.config import get_settings
|
| 20 |
from app.core.errors import Conflict, Forbidden, NotFound, ServiceUnavailable, Unprocessable
|
| 21 |
from app.modules.accounts.models import Account
|
|
|
|
| 69 |
# Validation is cheap and runs first, so a broken payload never reaches the plan check or the model.
|
| 70 |
parsed, problems = validate_payload(payload)
|
| 71 |
if parsed is None:
|
| 72 |
+
raise Unprocessable("The payload does not follow swing analysis contract 1.0 or 1.1.",
|
| 73 |
+
code="INVALID_PAYLOAD", fields=problems)
|
| 74 |
|
| 75 |
if session.report is not None:
|
| 76 |
if session.analysis_id != parsed.analysis_id:
|
|
|
|
| 79 |
return session.report
|
| 80 |
if parsed.analysis_revision < (session.analysis_revision or 0):
|
| 81 |
raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION")
|
| 82 |
+
if await analysis_consent_blocked(self.db, account.id, get_settings().require_analysis_consent):
|
| 83 |
raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
|
| 84 |
ensure_coach_configured()
|
| 85 |
if session.analyzed_at is None:
|
|
|
|
| 91 |
except InvalidPayload as exc: # defensive: the builder re-validates
|
| 92 |
raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc
|
| 93 |
|
| 94 |
+
marks = dict(session.marks or {})
|
| 95 |
+
for event_name, mark_name in (("stride_start", "stride_start_frame"),
|
| 96 |
+
("front_foot_down", "stride_end_frame"), ("contact", "contact_frame")):
|
| 97 |
+
event = getattr(parsed.events, event_name)
|
| 98 |
+
if event.status != "unavailable" and event.source_frame_index is not None:
|
| 99 |
+
marks[mark_name] = event.source_frame_index
|
| 100 |
+
if event_name == "contact":
|
| 101 |
+
marks["contact_offset"] = 0
|
| 102 |
+
marks["contact_source"] = "manual" if event.source == "manual_review" else "detected"
|
| 103 |
await self.sessions.update(
|
| 104 |
session, measurement_payload=payload, report=report, analysis_id=parsed.analysis_id,
|
| 105 |
+
analysis_revision=parsed.analysis_revision, marks=marks,
|
| 106 |
+
analyzed_at=session.analyzed_at or datetime.now(UTC))
|
| 107 |
return report
|
backend/app/modules/threads/controller.py
CHANGED
|
@@ -4,7 +4,6 @@ from typing import Annotated
|
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from fastapi import APIRouter, Depends, Header, Query, Response, status
|
| 7 |
-
from pydantic import BaseModel
|
| 8 |
|
| 9 |
from app.common.academy_access import CurrentStaff
|
| 10 |
from app.common.schemas import Page
|
|
@@ -22,11 +21,6 @@ def get_thread_service(db: Db, storage: Storage,
|
|
| 22 |
return ThreadService(db, storage, push)
|
| 23 |
|
| 24 |
|
| 25 |
-
class _Scoped(BaseModel):
|
| 26 |
-
thread_id: str
|
| 27 |
-
body: dict
|
| 28 |
-
|
| 29 |
-
|
| 30 |
Service = Annotated[ThreadService, Depends(get_thread_service)]
|
| 31 |
|
| 32 |
|
|
@@ -59,9 +53,8 @@ async def mark_read(thread_id: UUID, body: ReadIn, account: CurrentAccount, serv
|
|
| 59 |
async def send_message(thread_id: UUID, body: MessageIn, account: CurrentAccount, db: Db, service: Service,
|
| 60 |
idempotency_key: Annotated[str | None, Header()] = None):
|
| 61 |
# The key is scoped to the account, so the thread id is part of what must match on replay.
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
status_code=status.HTTP_201_CREATED)
|
| 65 |
|
| 66 |
|
| 67 |
@router.post("/coach/players/{player_id}/thread", status_code=status.HTTP_201_CREATED,
|
|
|
|
| 4 |
from uuid import UUID
|
| 5 |
|
| 6 |
from fastapi import APIRouter, Depends, Header, Query, Response, status
|
|
|
|
| 7 |
|
| 8 |
from app.common.academy_access import CurrentStaff
|
| 9 |
from app.common.schemas import Page
|
|
|
|
| 21 |
return ThreadService(db, storage, push)
|
| 22 |
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
Service = Annotated[ThreadService, Depends(get_thread_service)]
|
| 25 |
|
| 26 |
|
|
|
|
| 53 |
async def send_message(thread_id: UUID, body: MessageIn, account: CurrentAccount, db: Db, service: Service,
|
| 54 |
idempotency_key: Annotated[str | None, Header()] = None):
|
| 55 |
# The key is scoped to the account, so the thread id is part of what must match on replay.
|
| 56 |
+
return await run_idempotent(db, account.id, idempotency_key, body, lambda: service.send(account, thread_id, body),
|
| 57 |
+
status_code=status.HTTP_201_CREATED, scope=thread_id)
|
|
|
|
| 58 |
|
| 59 |
|
| 60 |
@router.post("/coach/players/{player_id}/thread", status_code=status.HTTP_201_CREATED,
|
backend/app/modules/threads/repository.py
CHANGED
|
@@ -9,7 +9,7 @@ from sqlalchemy.dialects.postgresql import insert
|
|
| 9 |
from sqlalchemy.orm import aliased
|
| 10 |
|
| 11 |
from app.common.base_repository import BaseRepository
|
| 12 |
-
from app.
|
| 13 |
from app.modules.reviews.models import Review
|
| 14 |
from app.modules.sessions.models import SwingSession
|
| 15 |
from app.modules.threads.models import Message, Thread
|
|
@@ -91,8 +91,7 @@ class ThreadRepository(BaseRepository[Thread]):
|
|
| 91 |
update(Thread).where(Thread.id == thread_id).values({column.key: func.greatest(column, seq)}))
|
| 92 |
|
| 93 |
async def names(self, ids: set[UUID]) -> dict[UUID, str]:
|
| 94 |
-
|
| 95 |
-
return {i: n or "" for i, n in rows.all()}
|
| 96 |
|
| 97 |
async def session_row(self, session_id: UUID) -> SwingSession | None:
|
| 98 |
return await self.session.get(SwingSession, session_id)
|
|
@@ -122,12 +121,6 @@ class ThreadRepository(BaseRepository[Thread]):
|
|
| 122 |
return {}
|
| 123 |
return {u.id: u for u in await self.session.scalars(select(Upload).where(Upload.id.in_(ids)))}
|
| 124 |
|
| 125 |
-
async def upload(self, upload_id: UUID) -> Upload | None:
|
| 126 |
-
return await self.session.get(Upload, upload_id)
|
| 127 |
-
|
| 128 |
-
async def locked_upload(self, upload_id: UUID) -> Upload | None:
|
| 129 |
-
return await self.session.scalar(select(Upload).where(Upload.id == upload_id).with_for_update())
|
| 130 |
-
|
| 131 |
async def upload_in_use(self, upload_id: UUID) -> bool:
|
| 132 |
"""Backstop for rows attached before attached_at was reliably set."""
|
| 133 |
used = await self.session.scalar(select(Message.id).where(Message.upload_id == upload_id).limit(1))
|
|
|
|
| 9 |
from sqlalchemy.orm import aliased
|
| 10 |
|
| 11 |
from app.common.base_repository import BaseRepository
|
| 12 |
+
from app.common.names import account_names
|
| 13 |
from app.modules.reviews.models import Review
|
| 14 |
from app.modules.sessions.models import SwingSession
|
| 15 |
from app.modules.threads.models import Message, Thread
|
|
|
|
| 91 |
update(Thread).where(Thread.id == thread_id).values({column.key: func.greatest(column, seq)}))
|
| 92 |
|
| 93 |
async def names(self, ids: set[UUID]) -> dict[UUID, str]:
|
| 94 |
+
return {i: n or "" for i, n in (await account_names(self.session, ids)).items()}
|
|
|
|
| 95 |
|
| 96 |
async def session_row(self, session_id: UUID) -> SwingSession | None:
|
| 97 |
return await self.session.get(SwingSession, session_id)
|
|
|
|
| 121 |
return {}
|
| 122 |
return {u.id: u for u in await self.session.scalars(select(Upload).where(Upload.id.in_(ids)))}
|
| 123 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
async def upload_in_use(self, upload_id: UUID) -> bool:
|
| 125 |
"""Backstop for rows attached before attached_at was reliably set."""
|
| 126 |
used = await self.session.scalar(select(Message.id).where(Message.upload_id == upload_id).limit(1))
|
backend/app/modules/threads/service.py
CHANGED
|
@@ -7,8 +7,7 @@ Thread.last_seq is the counter, incremented under a row lock.
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
from dataclasses import dataclass
|
| 10 |
-
from datetime import UTC, datetime
|
| 11 |
-
from functools import cache
|
| 12 |
from uuid import UUID
|
| 13 |
|
| 14 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
@@ -21,10 +20,13 @@ from app.common.academy_access import (
|
|
| 21 |
staff_context,
|
| 22 |
visible_players_query,
|
| 23 |
)
|
|
|
|
|
|
|
| 24 |
from app.common.notify import notify
|
| 25 |
from app.common.schemas import MediaRef, Page
|
|
|
|
| 26 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable
|
| 27 |
-
from app.core.pagination import PageParams,
|
| 28 |
from app.integrations.push import PushClient
|
| 29 |
from app.integrations.storage import StorageClient
|
| 30 |
from app.modules.accounts.models import Account
|
|
@@ -46,24 +48,9 @@ from app.modules.threads.schemas import (
|
|
| 46 |
from app.modules.uploads.models import Upload
|
| 47 |
|
| 48 |
LIST_MESSAGES = 20 # messages included per thread in the list
|
| 49 |
-
TONE_GREEN_MIN = 80 # overall score at or above: "g"; at or above TONE_YELLOW_MIN: "y"; below: "r"
|
| 50 |
-
TONE_YELLOW_MIN = 60
|
| 51 |
_SESSION_WORD = {"h": "Swing", "p": "Pitch"}
|
| 52 |
|
| 53 |
|
| 54 |
-
@cache
|
| 55 |
-
def drill_names() -> dict[str, str]:
|
| 56 |
-
from ai_coach.knowledge import all_drills
|
| 57 |
-
|
| 58 |
-
return {d["id"]: d["name"] for d in all_drills()}
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
def tone(score: int | None) -> str:
|
| 62 |
-
if score is None:
|
| 63 |
-
return "y"
|
| 64 |
-
return "g" if score >= TONE_GREEN_MIN else "y" if score >= TONE_YELLOW_MIN else "r"
|
| 65 |
-
|
| 66 |
-
|
| 67 |
@dataclass
|
| 68 |
class Access:
|
| 69 |
thread: Thread
|
|
@@ -110,9 +97,8 @@ class ThreadService:
|
|
| 110 |
team_id=scoped.team_id if scoped else None, visible=visible, mode=mode,
|
| 111 |
filter_player_id=player_id, unread=unread, cursor_at=cursor.created_at if cursor else None,
|
| 112 |
cursor_id=cursor.id if cursor else None, limit=paging.limit + 1))
|
| 113 |
-
page =
|
| 114 |
out = await self._render(page, LIST_MESSAGES)
|
| 115 |
-
next_cursor = encode_cursor(page[-1].updated_at, page[-1].id) if len(rows) > paging.limit else None
|
| 116 |
return Page[ThreadOut](items=out, next_cursor=next_cursor)
|
| 117 |
|
| 118 |
async def get(self, account: Account, thread_id: UUID, cursor: str | None, limit: int) -> ThreadOut:
|
|
@@ -191,14 +177,13 @@ class ThreadService:
|
|
| 191 |
return (await self._render([thread], LIST_MESSAGES))[0], created
|
| 192 |
|
| 193 |
async def _claim_audio(self, account: Account, upload_id: UUID) -> None:
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
await self.repo.update(upload, attached_at=datetime.now(UTC))
|
| 202 |
|
| 203 |
async def _check_session(self, access: Access, session_id: UUID) -> None:
|
| 204 |
session = await self.repo.session_row(session_id)
|
|
@@ -279,7 +264,7 @@ class ThreadService:
|
|
| 279 |
return ReviewMessageOut(
|
| 280 |
**common, cue=review.cue, voice_seconds=seconds, audio=ctx.media(review.voice_upload_id, seconds),
|
| 281 |
findings=_findings(review, session), drill_id=review.drill_id,
|
| 282 |
-
drill_name=
|
| 283 |
|
| 284 |
|
| 285 |
@dataclass
|
|
@@ -292,10 +277,7 @@ class _Context:
|
|
| 292 |
|
| 293 |
def media(self, upload_id: UUID | None, seconds: float | None) -> MediaRef | None:
|
| 294 |
upload = self.uploads.get(upload_id) if upload_id else None
|
| 295 |
-
|
| 296 |
-
return None
|
| 297 |
-
return MediaRef(upload_id=upload.id, url=self.storage.presign_get(upload.object_key),
|
| 298 |
-
expires_at=datetime.now(UTC) + timedelta(seconds=self.storage.download_ttl), seconds=seconds)
|
| 299 |
|
| 300 |
|
| 301 |
def _label(session: SwingSession, ordinal: int) -> str:
|
|
|
|
| 7 |
"""
|
| 8 |
|
| 9 |
from dataclasses import dataclass
|
| 10 |
+
from datetime import UTC, datetime
|
|
|
|
| 11 |
from uuid import UUID
|
| 12 |
|
| 13 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 20 |
staff_context,
|
| 21 |
visible_players_query,
|
| 22 |
)
|
| 23 |
+
from app.common.labels import drill_catalog, tone
|
| 24 |
+
from app.common.media import upload_ref
|
| 25 |
from app.common.notify import notify
|
| 26 |
from app.common.schemas import MediaRef, Page
|
| 27 |
+
from app.common.uploads import UploadErrors, claim_upload
|
| 28 |
from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable
|
| 29 |
+
from app.core.pagination import PageParams, paginate
|
| 30 |
from app.integrations.push import PushClient
|
| 31 |
from app.integrations.storage import StorageClient
|
| 32 |
from app.modules.accounts.models import Account
|
|
|
|
| 48 |
from app.modules.uploads.models import Upload
|
| 49 |
|
| 50 |
LIST_MESSAGES = 20 # messages included per thread in the list
|
|
|
|
|
|
|
| 51 |
_SESSION_WORD = {"h": "Swing", "p": "Pitch"}
|
| 52 |
|
| 53 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
@dataclass
|
| 55 |
class Access:
|
| 56 |
thread: Thread
|
|
|
|
| 97 |
team_id=scoped.team_id if scoped else None, visible=visible, mode=mode,
|
| 98 |
filter_player_id=player_id, unread=unread, cursor_at=cursor.created_at if cursor else None,
|
| 99 |
cursor_id=cursor.id if cursor else None, limit=paging.limit + 1))
|
| 100 |
+
page, next_cursor = paginate(rows, paging.limit, lambda t: (t.updated_at, t.id))
|
| 101 |
out = await self._render(page, LIST_MESSAGES)
|
|
|
|
| 102 |
return Page[ThreadOut](items=out, next_cursor=next_cursor)
|
| 103 |
|
| 104 |
async def get(self, account: Account, thread_id: UUID, cursor: str | None, limit: int) -> ThreadOut:
|
|
|
|
| 177 |
return (await self._render([thread], LIST_MESSAGES))[0], created
|
| 178 |
|
| 179 |
async def _claim_audio(self, account: Account, upload_id: UUID) -> None:
|
| 180 |
+
await claim_upload(
|
| 181 |
+
self.db, self.storage, upload_id, owner_id=account.id, kind="audio",
|
| 182 |
+
errors=UploadErrors(
|
| 183 |
+
invalid=Unprocessable("Not a valid audio upload.", code="INVALID_UPLOAD"),
|
| 184 |
+
used=Unprocessable("This audio was already used.", code="UPLOAD_ALREADY_USED"),
|
| 185 |
+
not_ready=Conflict("The upload has not finished. Please try again.", code="UPLOAD_NOT_READY")),
|
| 186 |
+
in_use=lambda: self.repo.upload_in_use(upload_id))
|
|
|
|
| 187 |
|
| 188 |
async def _check_session(self, access: Access, session_id: UUID) -> None:
|
| 189 |
session = await self.repo.session_row(session_id)
|
|
|
|
| 264 |
return ReviewMessageOut(
|
| 265 |
**common, cue=review.cue, voice_seconds=seconds, audio=ctx.media(review.voice_upload_id, seconds),
|
| 266 |
findings=_findings(review, session), drill_id=review.drill_id,
|
| 267 |
+
drill_name=drill_catalog().get(review.drill_id, {}).get("name"))
|
| 268 |
|
| 269 |
|
| 270 |
@dataclass
|
|
|
|
| 277 |
|
| 278 |
def media(self, upload_id: UUID | None, seconds: float | None) -> MediaRef | None:
|
| 279 |
upload = self.uploads.get(upload_id) if upload_id else None
|
| 280 |
+
return upload_ref(self.storage, upload, seconds)
|
|
|
|
|
|
|
|
|
|
| 281 |
|
| 282 |
|
| 283 |
def _label(session: SwingSession, ordinal: int) -> str:
|
backend/docs/openapi.json
CHANGED
|
The diff for this file is too large to render.
See raw diff
|
|
|
backend/tests/integration/test_swing_reports.py
CHANGED
|
@@ -1,9 +1,11 @@
|
|
| 1 |
"""H1: POST /v1/sessions/{id}/swing-report."""
|
| 2 |
|
| 3 |
import copy
|
|
|
|
| 4 |
import uuid
|
| 5 |
from datetime import UTC, datetime
|
| 6 |
from decimal import Decimal
|
|
|
|
| 7 |
|
| 8 |
import pytest
|
| 9 |
from ai_coach.swing_report import build_report
|
|
@@ -147,6 +149,39 @@ async def test_higher_revision_rebuilds_and_replaces(client, builds):
|
|
| 147 |
assert len(builds) == 2
|
| 148 |
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
async def test_lower_revision_is_stale(client):
|
| 151 |
owner, headers = await make_account()
|
| 152 |
sid = await make_session(owner)
|
|
@@ -175,7 +210,7 @@ async def test_invalid_payload(client):
|
|
| 175 |
assert response.status_code == 422
|
| 176 |
error = response.json()["error"]
|
| 177 |
assert error["code"] == "INVALID_PAYLOAD"
|
| 178 |
-
assert error["message"] == "The payload does not follow swing analysis contract 1.0."
|
| 179 |
assert error["fields"] == {
|
| 180 |
"measurements[1].reasons": "A limited result needs at least one reason code.",
|
| 181 |
"events.stride_start.video_time_s": "Must be before front_foot_down.",
|
|
@@ -279,6 +314,8 @@ async def test_payload_batting_hand_wins(client):
|
|
| 279 |
sid = await make_session(owner, athlete={**ATHLETE, "bats": "L"})
|
| 280 |
response = await client.post(url(sid), json=PAYLOAD, headers=headers)
|
| 281 |
assert response.json()["measurements"][0]["benchmark"]["benchmark_id"].endswith(".right.college")
|
|
|
|
|
|
|
| 282 |
|
| 283 |
|
| 284 |
async def test_missing_gemini_key_is_an_error_not_a_template_report(client, monkeypatch):
|
|
|
|
| 1 |
"""H1: POST /v1/sessions/{id}/swing-report."""
|
| 2 |
|
| 3 |
import copy
|
| 4 |
+
import json
|
| 5 |
import uuid
|
| 6 |
from datetime import UTC, datetime
|
| 7 |
from decimal import Decimal
|
| 8 |
+
from pathlib import Path
|
| 9 |
|
| 10 |
import pytest
|
| 11 |
from ai_coach.swing_report import build_report
|
|
|
|
| 149 |
assert len(builds) == 2
|
| 150 |
|
| 151 |
|
| 152 |
+
async def test_v11_report_revision_updates_exact_source_marks(client):
|
| 153 |
+
owner, headers = await make_account()
|
| 154 |
+
sid = await make_session(owner)
|
| 155 |
+
p = json.loads((Path(__file__).resolve().parents[3] / "docs/motion-coach-payload-v1.1.example.json").read_text())
|
| 156 |
+
first = await client.post(url(sid), json=p, headers=headers)
|
| 157 |
+
assert first.status_code == 200, first.text
|
| 158 |
+
assert all(group["score"] is not None for group in first.json()["groups"])
|
| 159 |
+
row = await load_session(sid)
|
| 160 |
+
assert row.marks == {"stride_start_frame": 3, "stride_end_frame": 10, "contact_frame": 20,
|
| 161 |
+
"contact_offset": 0, "contact_source": "manual"}
|
| 162 |
+
p["analysis_revision"] = 2
|
| 163 |
+
p["events"]["contact"].update(source_frame_index=21, video_time_s=0.7, capture_time_s=0.7)
|
| 164 |
+
p["events"]["follow_through"].update(source_frame_index=24, video_time_s=0.8, capture_time_s=0.8)
|
| 165 |
+
revised = await client.post(url(sid), json=p, headers=headers)
|
| 166 |
+
assert revised.status_code == 200, revised.text
|
| 167 |
+
row = await load_session(sid)
|
| 168 |
+
assert row.marks["contact_frame"] == 21 and row.measurement_payload == p
|
| 169 |
+
assert row.report == revised.json() and row.analysis_revision == 2
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
async def test_legacy_report_preserves_marks_without_guessing_frames_from_times(client):
|
| 173 |
+
owner, headers = await make_account()
|
| 174 |
+
sid = await make_session(owner)
|
| 175 |
+
original = {"contact_frame": 75, "contact_offset": 0, "contact_source": "manual"}
|
| 176 |
+
async with get_session_factory()() as db:
|
| 177 |
+
row = await db.get(SwingSession, sid)
|
| 178 |
+
row.marks = original
|
| 179 |
+
await db.commit()
|
| 180 |
+
response = await client.post(url(sid), json=PAYLOAD, headers=headers)
|
| 181 |
+
assert response.status_code == 200, response.text
|
| 182 |
+
assert (await load_session(sid)).marks == original
|
| 183 |
+
|
| 184 |
+
|
| 185 |
async def test_lower_revision_is_stale(client):
|
| 186 |
owner, headers = await make_account()
|
| 187 |
sid = await make_session(owner)
|
|
|
|
| 210 |
assert response.status_code == 422
|
| 211 |
error = response.json()["error"]
|
| 212 |
assert error["code"] == "INVALID_PAYLOAD"
|
| 213 |
+
assert error["message"] == "The payload does not follow swing analysis contract 1.0 or 1.1."
|
| 214 |
assert error["fields"] == {
|
| 215 |
"measurements[1].reasons": "A limited result needs at least one reason code.",
|
| 216 |
"events.stride_start.video_time_s": "Must be before front_foot_down.",
|
|
|
|
| 314 |
sid = await make_session(owner, athlete={**ATHLETE, "bats": "L"})
|
| 315 |
response = await client.post(url(sid), json=PAYLOAD, headers=headers)
|
| 316 |
assert response.json()["measurements"][0]["benchmark"]["benchmark_id"].endswith(".right.college")
|
| 317 |
+
assert "batting_hand_conflict" in {n["code"] for n in response.json()["data_quality"]}
|
| 318 |
+
assert response.json()["focus_area"]["kind"] == "general"
|
| 319 |
|
| 320 |
|
| 321 |
async def test_missing_gemini_key_is_an_error_not_a_template_report(client, monkeypatch):
|
baseball_batting/api.py
CHANGED
|
@@ -78,7 +78,7 @@ def create_app(settings=None, service=None):
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
-
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
|
|
|
| 78 |
service.start()
|
| 79 |
try: yield
|
| 80 |
finally: service.stop()
|
| 81 |
+
app = FastAPI(title="Baseball Swing Engine and Coach", version="1.19.0", lifespan=lifespan,
|
| 82 |
description="GPU batting/load timing with separate bat keypoint and baseball models. Single-view visual contact; physical miss/shift require synchronized calibrated views. Accuracy validation pending.")
|
| 83 |
app.state.service = service
|
| 84 |
app.add_middleware(UploadGuard, settings=settings, service=service)
|
baseball_batting/coach_geometry.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Contract 1.1 geometry shared by video export and reference-data calibration.
|
| 2 |
+
|
| 3 |
+
Inputs are anatomical joint centres in any fixed orthonormal frame, in metres.
|
| 4 |
+
These are kinematic descriptions, not measurements of force or energy transfer.
|
| 5 |
+
"""
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
EXTENDED_METRICS = (
|
| 10 |
+
'torso_inclination_at_stride_start',
|
| 11 |
+
'hip_shoulder_separation_at_stride_start',
|
| 12 |
+
'pelvis_rotation_to_contact',
|
| 13 |
+
'lead_knee_extension_to_contact',
|
| 14 |
+
'torso_inclination_at_contact',
|
| 15 |
+
'shoulder_rotation_after_contact',
|
| 16 |
+
)
|
| 17 |
+
FOLLOW_THROUGH_SECONDS = .1
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def inclination(hips, shoulders, up):
|
| 21 |
+
torso = np.asarray(shoulders) - np.asarray(hips)
|
| 22 |
+
vertical = torso @ np.asarray(up)
|
| 23 |
+
horizontal = torso - vertical[..., None] * np.asarray(up)
|
| 24 |
+
angle = np.degrees(np.arctan2(np.linalg.norm(horizontal, axis=-1), vertical))
|
| 25 |
+
return np.where(vertical > .05, angle, np.nan)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def knee_angle(hip, knee, ankle):
|
| 29 |
+
a, b = np.asarray(hip) - knee, np.asarray(ankle) - knee
|
| 30 |
+
denominator = np.linalg.norm(a, axis=-1) * np.linalg.norm(b, axis=-1)
|
| 31 |
+
cosine = np.divide(np.sum(a * b, axis=-1), denominator,
|
| 32 |
+
out=np.full_like(denominator, np.nan), where=denominator > 1e-8)
|
| 33 |
+
return np.degrees(np.arccos(np.clip(cosine, -1, 1)))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def rotation_amount(headings, start, end):
|
| 37 |
+
"""Magnitude of net unwrapped horizontal rotation; never a peak-speed proxy."""
|
| 38 |
+
if start is None or end is None or start >= end:
|
| 39 |
+
return np.nan
|
| 40 |
+
values = np.asarray(headings)[start:end + 1]
|
| 41 |
+
if not np.isfinite(values).all():
|
| 42 |
+
return np.nan
|
| 43 |
+
return float(abs(np.degrees(np.unwrap(np.radians(values))[-1] - np.radians(values[0]))))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def follow_through_frame(times, contact, end):
|
| 47 |
+
"""Nearest original sample to contact + 100 ms; a complete interval is required."""
|
| 48 |
+
if contact is None:
|
| 49 |
+
return None
|
| 50 |
+
times = np.asarray(times, float)
|
| 51 |
+
if not np.isfinite(times[contact:end + 1]).all() or np.any(np.diff(times[contact:end + 1]) <= 0):
|
| 52 |
+
return None
|
| 53 |
+
target = times[contact] + FOLLOW_THROUGH_SECONDS
|
| 54 |
+
if times[end] < target:
|
| 55 |
+
return None
|
| 56 |
+
i = int(np.argmin(np.abs(times[contact:end + 1] - target))) + contact
|
| 57 |
+
return i if i > contact else None
|
baseball_batting/motion_api.py
CHANGED
|
@@ -5,7 +5,7 @@ from pathlib import Path
|
|
| 5 |
import shutil
|
| 6 |
from typing import Annotated
|
| 7 |
from fastapi import Depends, File, Form, HTTPException, Request, UploadFile
|
| 8 |
-
from fastapi.responses import JSONResponse
|
| 9 |
from pydantic import ValidationError
|
| 10 |
from .motion_contract import MotionInput, MotionManifest, MotionFrame, ProjectionFrame, RevisionRequest, ADAPTER_VERSION
|
| 11 |
from .sam_motion import MHR
|
|
@@ -193,12 +193,13 @@ def register(app,service,authenticated):
|
|
| 193 |
'detail':'Submit athlete information and single_swing=true, or create a revision with those options'})
|
| 194 |
handle,_=open_verified_media(artifact_path(directory,asset),asset.sha256,asset.size_bytes)
|
| 195 |
try:
|
| 196 |
-
with handle:
|
|
|
|
| 197 |
except (ValueError,ValidationError):
|
| 198 |
raise HTTPException(500,'Stored coach payload is invalid') from None
|
| 199 |
if payload.analysis_id!=manifest.analysis_id or payload.analysis_revision!=manifest.analysis_revision:
|
| 200 |
raise HTTPException(500,'Coach payload differs from the analysis revision')
|
| 201 |
-
return
|
| 202 |
|
| 203 |
@app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
|
| 204 |
@app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
|
|
|
|
| 5 |
import shutil
|
| 6 |
from typing import Annotated
|
| 7 |
from fastapi import Depends, File, Form, HTTPException, Request, UploadFile
|
| 8 |
+
from fastapi.responses import JSONResponse, Response
|
| 9 |
from pydantic import ValidationError
|
| 10 |
from .motion_contract import MotionInput, MotionManifest, MotionFrame, ProjectionFrame, RevisionRequest, ADAPTER_VERSION
|
| 11 |
from .sam_motion import MHR
|
|
|
|
| 193 |
'detail':'Submit athlete information and single_swing=true, or create a revision with those options'})
|
| 194 |
handle,_=open_verified_media(artifact_path(directory,asset),asset.sha256,asset.size_bytes)
|
| 195 |
try:
|
| 196 |
+
with handle:raw_payload=handle.read()
|
| 197 |
+
payload=MotionCoachPayload.model_validate_json(raw_payload)
|
| 198 |
except (ValueError,ValidationError):
|
| 199 |
raise HTTPException(500,'Stored coach payload is invalid') from None
|
| 200 |
if payload.analysis_id!=manifest.analysis_id or payload.analysis_revision!=manifest.analysis_revision:
|
| 201 |
raise HTTPException(500,'Coach payload differs from the analysis revision')
|
| 202 |
+
return Response(raw_payload,media_type='application/json',headers={'Cache-Control':'no-store'})
|
| 203 |
|
| 204 |
@app.get(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)])
|
| 205 |
@app.head(PREFIX+'/{identifier}/artifacts/{name}',dependencies=[Depends(authenticated)],include_in_schema=False)
|
baseball_batting/motion_coach.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
-
"""Export
|
| 2 |
|
| 3 |
The selected source frames are manual review, not automatic event detections.
|
| 4 |
They identify sampled video moments, not measured ground force or subframe contact.
|
| 5 |
"""
|
| 6 |
import numpy as np
|
| 7 |
from .motion_coach_contract import (CoachEvents, CoachEvent, MotionCoachPayload,
|
| 8 |
-
SeparationAtFootDown, RelativeStride, SeparationAtContact)
|
|
|
|
| 9 |
from .sam_measurements import frame_curves, wrap180
|
| 10 |
from .sam_motion import MHR
|
| 11 |
|
|
@@ -18,7 +19,7 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
|
|
| 18 |
if options.athlete is None:
|
| 19 |
return None
|
| 20 |
if not options.single_swing or len(contexts) > 1:
|
| 21 |
-
raise ValueError('
|
| 22 |
n = len(video_times)
|
| 23 |
options.validate_frame_count(n)
|
| 24 |
window = options.windows[0] if options.windows else None
|
|
@@ -28,18 +29,22 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
|
|
| 28 |
lead = options.lead_foot or {'right': 'left', 'left': 'right'}.get(options.handedness)
|
| 29 |
athlete = options.athlete.model_copy(update={'batting_hand': options.handedness, 'lead_foot': lead})
|
| 30 |
|
| 31 |
-
def event(index, missing_reason):
|
| 32 |
if index is None:
|
| 33 |
return CoachEvent(status='unavailable', video_time_s=None, capture_time_s=None,
|
| 34 |
source=None, reasons=[missing_reason])
|
| 35 |
return CoachEvent(status='limited', video_time_s=float(video_times[index]),
|
| 36 |
capture_time_s=float(capture_times[index]) if np.isfinite(capture_times[index]) else None,
|
| 37 |
-
source=
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
events = CoachEvents(stride_start=event(stride_start, 'event_not_detected'),
|
| 40 |
front_foot_down=event(landing, 'event_not_detected'),
|
| 41 |
contact=event(contact, 'contact_not_applicable' if options.context.practice_type == 'dry_swing'
|
| 42 |
-
else 'contact_not_verified')
|
|
|
|
| 43 |
if contexts:
|
| 44 |
context = contexts[0]
|
| 45 |
curves = context['curves']
|
|
@@ -76,7 +81,7 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
|
|
| 76 |
if missing:
|
| 77 |
return model(value=None, status='unavailable', confidence=None,
|
| 78 |
uses_interpolated_input=interpolated, reasons=missing)
|
| 79 |
-
reasons = list(dict.fromkeys([*timing, *warnings]))
|
| 80 |
return model(value=value, status='limited' if reasons else 'available', confidence=None,
|
| 81 |
uses_interpolated_input=interpolated, reasons=reasons)
|
| 82 |
|
|
@@ -95,8 +100,32 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
|
|
| 95 |
missing.append('required_landmarks_unusable')
|
| 96 |
return result(model, value, missing, selected_event.reasons, interpolated, warnings)
|
| 97 |
|
| 98 |
-
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
interpolated, missing, warnings = quality([stride_start, landing],
|
| 101 |
['left_hip', 'right_hip', 'left_ankle', 'right_ankle'])
|
| 102 |
timing = []
|
|
@@ -126,6 +155,67 @@ def build_coach_payload(options, lineage, corrected, video_times, capture_times,
|
|
| 126 |
else:
|
| 127 |
missing.append('required_landmarks_unusable')
|
| 128 |
stride_metric = result(RelativeStride, stride, missing, timing, interpolated, warnings)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
return MotionCoachPayload(analysis_id=lineage['analysis_id'], analysis_revision=lineage['analysis_revision'],
|
| 130 |
swing_id=swing_identity(options, lineage['analysis_id']), athlete=athlete, context=options.context,
|
| 131 |
-
events=events, measurements=[foot_angle, stride_metric, contact_angle])
|
|
|
|
| 1 |
+
"""Export versioned coach measurements from the same corrected motion as replay.
|
| 2 |
|
| 3 |
The selected source frames are manual review, not automatic event detections.
|
| 4 |
They identify sampled video moments, not measured ground force or subframe contact.
|
| 5 |
"""
|
| 6 |
import numpy as np
|
| 7 |
from .motion_coach_contract import (CoachEvents, CoachEvent, MotionCoachPayload,
|
| 8 |
+
SeparationAtFootDown, RelativeStride, SeparationAtContact, ExtendedMeasurement, ValueInterval)
|
| 9 |
+
from .coach_geometry import follow_through_frame, inclination, knee_angle, rotation_amount
|
| 10 |
from .sam_measurements import frame_curves, wrap180
|
| 11 |
from .sam_motion import MHR
|
| 12 |
|
|
|
|
| 19 |
if options.athlete is None:
|
| 20 |
return None
|
| 21 |
if not options.single_swing or len(contexts) > 1:
|
| 22 |
+
raise ValueError('The coach contract requires one swing per video')
|
| 23 |
n = len(video_times)
|
| 24 |
options.validate_frame_count(n)
|
| 25 |
window = options.windows[0] if options.windows else None
|
|
|
|
| 29 |
lead = options.lead_foot or {'right': 'left', 'left': 'right'}.get(options.handedness)
|
| 30 |
athlete = options.athlete.model_copy(update={'batting_hand': options.handedness, 'lead_foot': lead})
|
| 31 |
|
| 32 |
+
def event(index, missing_reason, source='manual_review'):
|
| 33 |
if index is None:
|
| 34 |
return CoachEvent(status='unavailable', video_time_s=None, capture_time_s=None,
|
| 35 |
source=None, reasons=[missing_reason])
|
| 36 |
return CoachEvent(status='limited', video_time_s=float(video_times[index]),
|
| 37 |
capture_time_s=float(capture_times[index]) if np.isfinite(capture_times[index]) else None,
|
| 38 |
+
source=source, source_frame_index=index, reasons=['event_timing_uncertain'])
|
| 39 |
+
|
| 40 |
+
finish = follow_through_frame(capture_times, contact, window.end_frame if window else n - 1)
|
| 41 |
+
finish_reason = 'capture_time_unknown' if not np.isfinite(capture_times).all() else 'follow_through_not_recorded'
|
| 42 |
|
| 43 |
events = CoachEvents(stride_start=event(stride_start, 'event_not_detected'),
|
| 44 |
front_foot_down=event(landing, 'event_not_detected'),
|
| 45 |
contact=event(contact, 'contact_not_applicable' if options.context.practice_type == 'dry_swing'
|
| 46 |
+
else 'contact_not_verified'),
|
| 47 |
+
follow_through=event(finish, finish_reason, 'derived_from_contact'))
|
| 48 |
if contexts:
|
| 49 |
context = contexts[0]
|
| 50 |
curves = context['curves']
|
|
|
|
| 81 |
if missing:
|
| 82 |
return model(value=None, status='unavailable', confidence=None,
|
| 83 |
uses_interpolated_input=interpolated, reasons=missing)
|
| 84 |
+
reasons = list(dict.fromkeys([*timing, *warnings, 'model_accuracy_unvalidated']))
|
| 85 |
return model(value=value, status='limited' if reasons else 'available', confidence=None,
|
| 86 |
uses_interpolated_input=interpolated, reasons=reasons)
|
| 87 |
|
|
|
|
| 100 |
missing.append('required_landmarks_unusable')
|
| 101 |
return result(model, value, missing, selected_event.reasons, interpolated, warnings)
|
| 102 |
|
| 103 |
+
def add_interval(metric, evaluate, indices, names):
|
| 104 |
+
if metric.value is None or any(i is None for i in indices):
|
| 105 |
+
return metric
|
| 106 |
+
from itertools import product
|
| 107 |
+
lo, hi = (window.start_frame, window.end_frame) if window else (0, n - 1)
|
| 108 |
+
values = [metric.value]
|
| 109 |
+
for ids in product(*(range(max(lo, i - 1), min(hi, i + 1) + 1) for i in indices)):
|
| 110 |
+
if len(ids) > 1 and ids[0] >= ids[-1]:
|
| 111 |
+
continue
|
| 112 |
+
checked = list(range(ids[0], ids[-1] + 1)) if len(ids) > 1 else ids
|
| 113 |
+
if quality(checked, names)[1]:
|
| 114 |
+
return metric # A partial neighborhood cannot bound event sensitivity.
|
| 115 |
+
value = evaluate(*ids)
|
| 116 |
+
if not np.isfinite(value):
|
| 117 |
+
return metric
|
| 118 |
+
values.append(float(value))
|
| 119 |
+
# A wrapped angle can straddle -180/+180; a linear interval would be misleading.
|
| 120 |
+
if metric.reference == 'signed_horizontal_shoulder_minus_hip_heading' and max(values) - min(values) > 180:
|
| 121 |
+
return metric
|
| 122 |
+
metric.value_interval = ValueInterval(lower=min(values), upper=max(values))
|
| 123 |
+
return metric
|
| 124 |
+
|
| 125 |
+
sep = lambda i: curves['hip_shoulder_separation_deg'][i]
|
| 126 |
+
torso_names = ['left_hip', 'right_hip', 'left_shoulder', 'right_shoulder']
|
| 127 |
+
foot_angle = add_interval(separation(SeparationAtFootDown, landing, events.front_foot_down), sep, [landing], torso_names)
|
| 128 |
+
contact_angle = add_interval(separation(SeparationAtContact, contact, events.contact), sep, [contact], torso_names)
|
| 129 |
interpolated, missing, warnings = quality([stride_start, landing],
|
| 130 |
['left_hip', 'right_hip', 'left_ankle', 'right_ankle'])
|
| 131 |
timing = []
|
|
|
|
| 155 |
else:
|
| 156 |
missing.append('required_landmarks_unusable')
|
| 157 |
stride_metric = result(RelativeStride, stride, missing, timing, interpolated, warnings)
|
| 158 |
+
if oriented is not None and lead is not None:
|
| 159 |
+
li, ri = (MHR['left_ankle'], MHR['right_ankle']) if lead == 'left' else (MHR['right_ankle'], MHR['left_ankle'])
|
| 160 |
+
def stride_value(a, b):
|
| 161 |
+
return 100 * np.linalg.norm(((oriented[b, li] - oriented[b, ri]) -
|
| 162 |
+
(oriented[a, li] - oriented[a, ri]))[:2])
|
| 163 |
+
add_interval(stride_metric, stride_value, [stride_start, landing],
|
| 164 |
+
['left_hip', 'right_hip', 'left_ankle', 'right_ankle'])
|
| 165 |
+
|
| 166 |
+
hip_names = ['left_hip', 'right_hip']
|
| 167 |
+
torso_names = [*hip_names, 'left_shoulder', 'right_shoulder']
|
| 168 |
+
lean = np.full(n, np.nan)
|
| 169 |
+
knee = np.full(n, np.nan)
|
| 170 |
+
if oriented is not None:
|
| 171 |
+
lean = inclination((oriented[:, 9] + oriented[:, 10]) / 2,
|
| 172 |
+
(oriented[:, 5] + oriented[:, 6]) / 2, [0, 0, 1])
|
| 173 |
+
if lead is not None:
|
| 174 |
+
knee = knee_angle(oriented[:, MHR[lead + '_hip']], oriented[:, MHR[lead + '_knee']],
|
| 175 |
+
oriented[:, MHR[lead + '_ankle']])
|
| 176 |
+
event_map = {'stride_start': events.stride_start, 'front_foot_down': events.front_foot_down,
|
| 177 |
+
'contact': events.contact, 'follow_through': events.follow_through}
|
| 178 |
+
def extra(metric_id, group, reference_name, names, ids, event_ids, evaluate, *, lead_required=False):
|
| 179 |
+
checked = list(range(ids[0], ids[-1] + 1)) if len(ids) == 2 and all(i is not None for i in ids) else ids
|
| 180 |
+
interp, absent, warns = quality(checked, names)
|
| 181 |
+
event_reasons = []
|
| 182 |
+
for key in event_ids:
|
| 183 |
+
ev = event_map[key]
|
| 184 |
+
if ev.status == 'unavailable':
|
| 185 |
+
absent += ['required_event_unavailable', *ev.reasons]
|
| 186 |
+
else:
|
| 187 |
+
event_reasons += ev.reasons
|
| 188 |
+
if lead_required and lead is None:
|
| 189 |
+
absent.append('lead_foot_unknown')
|
| 190 |
+
value = evaluate(*ids) if not absent else np.nan
|
| 191 |
+
if not absent and not np.isfinite(value):
|
| 192 |
+
absent.append('required_landmarks_unusable')
|
| 193 |
+
common = dict(metric_id=metric_id, group=group, reference=reference_name)
|
| 194 |
+
common.update({'event_id': event_ids[0]} if len(event_ids) == 1 else
|
| 195 |
+
{'start_event_id': event_ids[0], 'end_event_id': event_ids[-1]})
|
| 196 |
+
rounded = round(float(value), 3) if np.isfinite(value) else None
|
| 197 |
+
if rounded is not None and reference_name == 'signed_horizontal_shoulder_minus_hip_heading':
|
| 198 |
+
rounded = float(wrap180(rounded))
|
| 199 |
+
row = result(lambda **fields: ExtendedMeasurement(**common, **fields), rounded,
|
| 200 |
+
absent, event_reasons, interp, warns)
|
| 201 |
+
return add_interval(row, evaluate, ids, names)
|
| 202 |
+
extended = [
|
| 203 |
+
extra('torso_inclination_at_stride_start', 'balance_load', 'torso_angle_from_vertical',
|
| 204 |
+
torso_names, [stride_start], ['stride_start'], lambda i: lean[i]),
|
| 205 |
+
extra('hip_shoulder_separation_at_stride_start', 'balance_load',
|
| 206 |
+
'signed_horizontal_shoulder_minus_hip_heading', torso_names, [stride_start], ['stride_start'], sep),
|
| 207 |
+
extra('pelvis_rotation_to_contact', 'power_move', 'absolute_net_horizontal_rotation',
|
| 208 |
+
hip_names, [landing, contact], ['front_foot_down', 'contact'],
|
| 209 |
+
lambda a, b: rotation_amount(curves['hip_heading_deg'], a, b)),
|
| 210 |
+
extra('lead_knee_extension_to_contact', 'power_move', 'change_in_3d_lead_knee_angle',
|
| 211 |
+
[lead + '_' + part for part in ('hip', 'knee', 'ankle')] if lead else hip_names,
|
| 212 |
+
[landing, contact], ['front_foot_down', 'contact'], lambda a, b: knee[b] - knee[a], lead_required=True),
|
| 213 |
+
extra('torso_inclination_at_contact', 'contact_follow_through', 'torso_angle_from_vertical',
|
| 214 |
+
torso_names, [contact], ['contact'], lambda i: lean[i]),
|
| 215 |
+
extra('shoulder_rotation_after_contact', 'contact_follow_through', 'absolute_net_horizontal_rotation',
|
| 216 |
+
['left_shoulder', 'right_shoulder'], [contact, finish], ['contact', 'follow_through'],
|
| 217 |
+
lambda a, b: rotation_amount(curves['shoulder_heading_deg'], a, b)),
|
| 218 |
+
]
|
| 219 |
return MotionCoachPayload(analysis_id=lineage['analysis_id'], analysis_revision=lineage['analysis_revision'],
|
| 220 |
swing_id=swing_identity(options, lineage['analysis_id']), athlete=athlete, context=options.context,
|
| 221 |
+
events=events, measurements=[foot_angle, stride_metric, contact_angle, *extended])
|
baseball_batting/motion_coach_contract.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
"""
|
| 2 |
from typing import Literal
|
| 3 |
from pydantic import Field, model_validator
|
| 4 |
from .sam_batting_contract import Strict
|
|
|
|
| 5 |
|
| 6 |
|
| 7 |
class CoachAthlete(Strict):
|
|
@@ -22,20 +23,22 @@ Reason = Literal['contact_not_verified', 'contact_not_applicable', 'event_not_de
|
|
| 22 |
'event_timing_uncertain', 'required_event_unavailable', 'required_event_limited',
|
| 23 |
'lead_foot_unknown', 'required_landmarks_unusable', 'ground_plane_unknown',
|
| 24 |
'scale_is_model_estimated', 'scale_unknown', 'excessive_interpolation',
|
| 25 |
-
'occlusion_unresolved', 'temporal_inconsistency'
|
|
|
|
| 26 |
|
| 27 |
|
| 28 |
class CoachEvent(Strict):
|
| 29 |
video_time_s: float | None = Field(ge=0)
|
| 30 |
capture_time_s: float | None = Field(ge=0)
|
| 31 |
status: Literal['available', 'limited', 'unavailable']
|
| 32 |
-
source: Literal['manual_review', 'pose_estimated', 'bat_ball_detector'] | None
|
| 33 |
reasons: list[Reason]
|
|
|
|
| 34 |
|
| 35 |
@model_validator(mode='after')
|
| 36 |
def consistent(self):
|
| 37 |
if self.status == 'unavailable':
|
| 38 |
-
if any(v is not None for v in (self.video_time_s, self.capture_time_s, self.source)):
|
| 39 |
raise ValueError('Unavailable events must have null times and source')
|
| 40 |
elif self.video_time_s is None or self.source is None:
|
| 41 |
raise ValueError('Usable events need video time and source')
|
|
@@ -48,6 +51,19 @@ class CoachEvents(Strict):
|
|
| 48 |
stride_start: CoachEvent
|
| 49 |
front_foot_down: CoachEvent
|
| 50 |
contact: CoachEvent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
class CoachMeasurement(Strict):
|
|
@@ -57,6 +73,7 @@ class CoachMeasurement(Strict):
|
|
| 57 |
uses_interpolated_input: bool
|
| 58 |
reasons: list[Reason]
|
| 59 |
benchmark: None = None
|
|
|
|
| 60 |
|
| 61 |
@model_validator(mode='after')
|
| 62 |
def consistent(self):
|
|
@@ -66,6 +83,9 @@ class CoachMeasurement(Strict):
|
|
| 66 |
raise ValueError('Unavailable measurements have null confidence')
|
| 67 |
if (self.status == 'available') != (not self.reasons):
|
| 68 |
raise ValueError('Only available measurements have an empty reasons list')
|
|
|
|
|
|
|
|
|
|
| 69 |
return self
|
| 70 |
|
| 71 |
|
|
@@ -97,9 +117,26 @@ class SeparationAtContact(CoachMeasurement):
|
|
| 97 |
value: float | None = Field(ge=-180, lt=180)
|
| 98 |
|
| 99 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
class MotionCoachPayload(Strict):
|
| 101 |
-
schema_version: Literal['1.0'] = '1.
|
| 102 |
-
measurement_definitions_version: Literal['1.0'] = '1.
|
| 103 |
analysis_id: str = Field(min_length=1)
|
| 104 |
analysis_revision: int = Field(ge=1)
|
| 105 |
swing_id: str = Field(min_length=1)
|
|
@@ -107,10 +144,23 @@ class MotionCoachPayload(Strict):
|
|
| 107 |
athlete: CoachAthlete
|
| 108 |
context: CoachContext
|
| 109 |
events: CoachEvents
|
| 110 |
-
measurements: list[SeparationAtFootDown | RelativeStride | SeparationAtContact] = Field(min_length=3, max_length=
|
| 111 |
|
| 112 |
@model_validator(mode='after')
|
| 113 |
def metric_set(self):
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
raise ValueError('Each registered metric must appear exactly once')
|
| 116 |
return self
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned coach measurements for one recorded swing; old stored payloads remain readable."""
|
| 2 |
from typing import Literal
|
| 3 |
from pydantic import Field, model_validator
|
| 4 |
from .sam_batting_contract import Strict
|
| 5 |
+
from .coach_geometry import EXTENDED_METRICS
|
| 6 |
|
| 7 |
|
| 8 |
class CoachAthlete(Strict):
|
|
|
|
| 23 |
'event_timing_uncertain', 'required_event_unavailable', 'required_event_limited',
|
| 24 |
'lead_foot_unknown', 'required_landmarks_unusable', 'ground_plane_unknown',
|
| 25 |
'scale_is_model_estimated', 'scale_unknown', 'excessive_interpolation',
|
| 26 |
+
'occlusion_unresolved', 'temporal_inconsistency', 'capture_time_unknown',
|
| 27 |
+
'follow_through_not_recorded', 'model_accuracy_unvalidated']
|
| 28 |
|
| 29 |
|
| 30 |
class CoachEvent(Strict):
|
| 31 |
video_time_s: float | None = Field(ge=0)
|
| 32 |
capture_time_s: float | None = Field(ge=0)
|
| 33 |
status: Literal['available', 'limited', 'unavailable']
|
| 34 |
+
source: Literal['manual_review', 'pose_estimated', 'bat_ball_detector', 'derived_from_contact'] | None
|
| 35 |
reasons: list[Reason]
|
| 36 |
+
source_frame_index: int | None = Field(default=None, ge=0, strict=True)
|
| 37 |
|
| 38 |
@model_validator(mode='after')
|
| 39 |
def consistent(self):
|
| 40 |
if self.status == 'unavailable':
|
| 41 |
+
if any(v is not None for v in (self.video_time_s, self.capture_time_s, self.source, self.source_frame_index)):
|
| 42 |
raise ValueError('Unavailable events must have null times and source')
|
| 43 |
elif self.video_time_s is None or self.source is None:
|
| 44 |
raise ValueError('Usable events need video time and source')
|
|
|
|
| 51 |
stride_start: CoachEvent
|
| 52 |
front_foot_down: CoachEvent
|
| 53 |
contact: CoachEvent
|
| 54 |
+
follow_through: CoachEvent | None = None
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ValueInterval(Strict):
|
| 58 |
+
lower: float
|
| 59 |
+
upper: float
|
| 60 |
+
source: Literal['adjacent_event_frames'] = 'adjacent_event_frames'
|
| 61 |
+
|
| 62 |
+
@model_validator(mode='after')
|
| 63 |
+
def ordered(self):
|
| 64 |
+
if self.lower > self.upper:
|
| 65 |
+
raise ValueError('Measurement interval must be ordered')
|
| 66 |
+
return self
|
| 67 |
|
| 68 |
|
| 69 |
class CoachMeasurement(Strict):
|
|
|
|
| 73 |
uses_interpolated_input: bool
|
| 74 |
reasons: list[Reason]
|
| 75 |
benchmark: None = None
|
| 76 |
+
value_interval: ValueInterval | None = None
|
| 77 |
|
| 78 |
@model_validator(mode='after')
|
| 79 |
def consistent(self):
|
|
|
|
| 83 |
raise ValueError('Unavailable measurements have null confidence')
|
| 84 |
if (self.status == 'available') != (not self.reasons):
|
| 85 |
raise ValueError('Only available measurements have an empty reasons list')
|
| 86 |
+
if self.value_interval is not None and (self.value is None or not
|
| 87 |
+
self.value_interval.lower <= self.value <= self.value_interval.upper):
|
| 88 |
+
raise ValueError('The event sensitivity interval must include the measurement value')
|
| 89 |
return self
|
| 90 |
|
| 91 |
|
|
|
|
| 117 |
value: float | None = Field(ge=-180, lt=180)
|
| 118 |
|
| 119 |
|
| 120 |
+
class ExtendedMeasurement(CoachMeasurement):
|
| 121 |
+
metric_id: Literal['torso_inclination_at_stride_start', 'hip_shoulder_separation_at_stride_start',
|
| 122 |
+
'pelvis_rotation_to_contact', 'lead_knee_extension_to_contact',
|
| 123 |
+
'torso_inclination_at_contact', 'shoulder_rotation_after_contact']
|
| 124 |
+
group: Literal['balance_load', 'power_move', 'contact_follow_through']
|
| 125 |
+
unit: Literal['deg'] = 'deg'
|
| 126 |
+
reference: Literal['torso_angle_from_vertical', 'signed_horizontal_shoulder_minus_hip_heading',
|
| 127 |
+
'absolute_net_horizontal_rotation', 'change_in_3d_lead_knee_angle']
|
| 128 |
+
event_id: Literal['stride_start', 'contact'] | None = None
|
| 129 |
+
start_event_id: Literal['front_foot_down', 'contact'] | None = None
|
| 130 |
+
end_event_id: Literal['contact', 'follow_through'] | None = None
|
| 131 |
+
|
| 132 |
+
def model_dump(self, **kwargs):
|
| 133 |
+
data = super().model_dump(**kwargs)
|
| 134 |
+
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}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
class MotionCoachPayload(Strict):
|
| 138 |
+
schema_version: Literal['1.0', '1.1'] = '1.1'
|
| 139 |
+
measurement_definitions_version: Literal['1.0', '1.1'] = '1.1'
|
| 140 |
analysis_id: str = Field(min_length=1)
|
| 141 |
analysis_revision: int = Field(ge=1)
|
| 142 |
swing_id: str = Field(min_length=1)
|
|
|
|
| 144 |
athlete: CoachAthlete
|
| 145 |
context: CoachContext
|
| 146 |
events: CoachEvents
|
| 147 |
+
measurements: list[SeparationAtFootDown | RelativeStride | SeparationAtContact | ExtendedMeasurement] = Field(min_length=3, max_length=9)
|
| 148 |
|
| 149 |
@model_validator(mode='after')
|
| 150 |
def metric_set(self):
|
| 151 |
+
expected = {'hip_shoulder_separation_at_foot_down', 'stride_relative_length', 'hip_shoulder_separation_at_contact'}
|
| 152 |
+
if self.schema_version == '1.1':
|
| 153 |
+
expected.update(EXTENDED_METRICS)
|
| 154 |
+
if self.measurement_definitions_version != self.schema_version:
|
| 155 |
+
raise ValueError('Schema and measurement definitions versions must match')
|
| 156 |
+
if {m.metric_id for m in self.measurements} != expected or len(self.measurements) != len(expected):
|
| 157 |
raise ValueError('Each registered metric must appear exactly once')
|
| 158 |
return self
|
| 159 |
+
|
| 160 |
+
def model_dump(self, **kwargs):
|
| 161 |
+
data = super().model_dump(**kwargs)
|
| 162 |
+
for row in data['measurements']:
|
| 163 |
+
for key in ('event_id', 'start_event_id', 'end_event_id'):
|
| 164 |
+
if row.get(key, 'absent') is None:
|
| 165 |
+
row.pop(key)
|
| 166 |
+
return data
|