Spaces:
Running on T4
Running on T4
github-actions[bot] commited on
Commit ·
16459e8
1
Parent(s): 999db75
Automated Deploy: 0f6712d462fa0d8a00c5bbc6cfffe99ab79b85d6
Browse files- BUILD_STATUS.md +17 -0
- baseball_batting/batting_measurements.py +40 -80
- baseball_batting/measurement_quality.py +47 -65
- baseball_batting/pose_agreement.py +93 -0
- baseball_batting/swing_preparation.py +161 -0
- baseball_batting/timing_quality.py +62 -0
- docs/BATTING_2D_MEASUREMENTS.md +11 -7
- docs/NINE_MEASUREMENTS.md +9 -7
- docs/api-result.schema.json +10 -3
- notebooks/batting_2d_test.ipynb +3 -0
- notebooks/batting_measurements_test.ipynb +13 -3
- tests/test_colab_2d.py +26 -1
- tests/test_measurement_backends.py +119 -0
- tests/test_preparation_evidence.py +167 -0
- tools/build_2d_notebook.py +3 -0
- tools/build_measurement_notebook.py +10 -1
- tools/preview_swing_ranges.py +42 -5
BUILD_STATUS.md
CHANGED
|
@@ -1,5 +1,22 @@
|
|
| 1 |
# Build status
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
## 30 FPS timing support — 2026-10-12
|
| 4 |
|
| 5 |
Method `batting-2d-v5` supports documented nominal 30 FPS capture, including 29.97 FPS and variable cadence with every interval <= `1.01/30` seconds. This replaces the earlier blanket 60 FPS timing cutoff. The existing per-metric ±1-frame sensitivity checks still withhold poorly resolved durations and ratios; unknown clocks, missing events and larger timestamp gaps remain unsupported. Full-result timing diagnostics now include actual frame intervals and the shifted-event range's unit. The coach schema and estimate labels are unchanged.
|
|
|
|
| 1 |
# Build status
|
| 2 |
|
| 3 |
+
## Preparation events and measurement reliability — 2026-10-12
|
| 4 |
+
|
| 5 |
+
Method `batting-2d-v6` and `measurement-quality-v2` address the four investigated causes. The final lead-foot step uses a supported quiet reference, observed lift/return and ankle/sole settling at the new image position. Confirmation may extend shortly beyond hand onset while timestamping settling before or at onset and staying before contact. Earlier walking steps and held leg kicks do not replace the final ground reference. Hand loading and stride are no longer forced into a single order.
|
| 6 |
+
|
| 7 |
+
Stance now requires quiet hands, pelvis and ankles immediately before preparation; quiet hands while walking are insufficient. Head path is omitted with an explicit missing-stance reason for walk-throughs without a supported stance. The 3D quality layer explains named per-joint projection disagreements, verifies camera projection again, records body/segment geometry and preserves anatomical sides. Knee median filtering uses its own knee anchor, so an unsupported opposite hip cannot invalidate a supported lead knee. The provider's SAM landmark mapping was checked against its pinned official metadata; no mapping or unit correction justified shifting the disagreeing hip/shoulder predictions.
|
| 8 |
+
|
| 9 |
+
Timing checks retain documented nominal 30 FPS support and the existing ±1-frame resolution limits. Diagnostics now give contributing frame counts, event shift windows, relative sensitivity width and resolution status. Relabeling FPS or inventing intermediate frames does not make a five-frame launch sufficiently resolved. The compact nine-field coach schema, estimate labels, default 2D mode and HTTP endpoints are unchanged. Both notebooks were regenerated. Selected 3D projections appear in purple in inspection previews, with red disagreement connectors and downloadable contact/plant comparison PNGs.
|
| 10 |
+
|
| 11 |
+
Executed evidence:
|
| 12 |
+
|
| 13 |
+
- **196 tests passed, 4 skipped**, with one existing Starlette/httpx deprecation warning. The sandbox initially blocked the existing Git authentication test's temporary localhost listener; the complete suite passed with permission to bind that fixture. Added cases cover landing at different image depths, 30/60/120 FPS, settling confirmation after onset, absent/noisy foot evidence, hovering, continued travel, held leg kicks, multiple preparation steps, mirroring/anatomical sides, walking versus stance, raw support, opposite-hip independence, named disagreements, side-swap reporting, invalid model rows, projection consistency, timestamp sensitivity and comparison/ZIP export. Known constructed geometry and supplied numeric fixtures remain engineering checks, not real accuracy labels.
|
| 14 |
+
- Replayed the latest walkthrough's archived GPU 2D/SAM outputs: final foot departure frame **51**, sole return **62**, settled-foot proxy **69**, hand onset **70**, contact proxy **75**. Stride is now **43.891%** of the estimated image stature; the previously supported hip position **-18.218%** and load duration **0.533 seconds** remain. The walking drill has no supported stationary stance. Plant-to-contact spans six frame intervals and fails the timing sensitivity check; launch spans five and its ratio sensitivity still ranges approximately **2–6**. SAM's contact predictions still disagree at the right hip (**5.14%**) and shoulder (**7.28%**), so affected angles remain withheld. Archived SAM frames cover only contact: its new plant window needs fresh GPU inference, and replay reports this as partial rather than fabricating points.
|
| 15 |
+
- Real local CPU RTMW3D inference completed on **10 new walkthrough event frames** in **4.607 seconds** and **5 outdoor frames** in **2.649 seconds**, including initialization and decoding to those frames. The supplied GPU 2D tracks were reused. Walkthrough knee geometry passed the current engineering checks (**164.772°**, experimental); its trunk/plant separation were withheld for degenerate/changing predicted axes. Outdoor trunk remained **-23.586°**, while unstable knee geometry was withheld. These are execution/sensitivity results, not accuracy or GPU-performance claims.
|
| 16 |
+
- Replayed outdoor SAM contact frames retain supported knee/trunk estimates and the primary onset/contact locations at **75/79**. Both model choices on both recordings pass the full-result and compact coach schemas. A real 117-frame walkthrough preview passed its encoded frame-count/PTS checks; the SAM disagreement PNG was inspected visually. Raw 2D/3D points remain unchanged.
|
| 17 |
+
|
| 18 |
+
Fresh SAM inference for the new plant window, lightweight target-GPU execution and Docker deployment checks remain external execution tasks. Absolute point/event/measurement accuracy remains `reference_validation_pending`. Unsupported camera views, moving cameras, unknown clocks, no-stride/no-stance drills and uncertain predictions still yield explained nulls.
|
| 19 |
+
|
| 20 |
## 30 FPS timing support — 2026-10-12
|
| 21 |
|
| 22 |
Method `batting-2d-v5` supports documented nominal 30 FPS capture, including 29.97 FPS and variable cadence with every interval <= `1.01/30` seconds. This replaces the earlier blanket 60 FPS timing cutoff. The existing per-metric ±1-frame sensitivity checks still withhold poorly resolved durations and ratios; unknown clocks, missing events and larger timestamp gaps remain unsupported. Full-result timing diagnostics now include actual frame intervals and the shifted-event range's unit. The coach schema and estimate labels are unchanged.
|
baseball_batting/batting_measurements.py
CHANGED
|
@@ -8,8 +8,9 @@ estimates until independently validated. Physical times never use playback FPS.
|
|
| 8 |
import math
|
| 9 |
import numpy as np
|
| 10 |
from scipy.ndimage import median_filter
|
|
|
|
| 11 |
|
| 12 |
-
VERSION = "batting-2d-
|
| 13 |
# Nominal 30 FPS, including 29.97 and small timestamp jitter. This is an
|
| 14 |
# engineering support floor, not an accuracy guarantee. The API quality layer
|
| 15 |
# separately rejects each timing metric under ±1-frame event shifts.
|
|
@@ -329,7 +330,7 @@ def capture_checks(track, options, height, selected_frames):
|
|
| 329 |
|
| 330 |
def infer_events(track, points, options, height, direction, motion, start, end):
|
| 331 |
hands, relative, magnitude, forward, threshold = motion
|
| 332 |
-
|
| 333 |
raw = point_array(track["frames"]["kp"], 17)
|
| 334 |
raw_feet = point_array(track["frames"]["kp_extra"], 6)
|
| 335 |
feet = analysis_points(raw_feet)
|
|
@@ -386,7 +387,6 @@ def infer_events(track, points, options, height, direction, motion, start, end):
|
|
| 386 |
add("swing_start", a, "primary_swing_hand_motion_onset_v3",
|
| 387 |
"Estimated onset of the primary hand excursion; projected hand travel does not establish forward direction or exact acceleration onset.")
|
| 388 |
quiet = np.isfinite(magnitude) & (magnitude < threshold*.3)
|
| 389 |
-
quiet_runs = [(s, e) for s, e in runs(quiet[start:a]) if e-s >= minimum]
|
| 390 |
finish_start = max(b, start+grouped[0][1]) if grouped else b
|
| 391 |
for s, e in runs(quiet[finish_start:end+1]):
|
| 392 |
if e-s >= minimum and finish_start+s+minimum-1 < end:
|
|
@@ -394,9 +394,13 @@ def infer_events(track, points, options, height, direction, motion, start, end):
|
|
| 394 |
"Estimated post-swing settling; the last clip frame is not used as finish.")
|
| 395 |
break
|
| 396 |
if options.view != "face_on":
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 400 |
for key in ("load_start", "stride", "foot_contact", "foot_plant", "contact"):
|
| 401 |
missing[key] = "A declared face-on recording is required."
|
| 402 |
return events, missing
|
|
@@ -414,12 +418,6 @@ def infer_events(track, points, options, height, direction, motion, start, end):
|
|
| 414 |
"Estimated hand load start; does not establish whole-body loading.")
|
| 415 |
else:
|
| 416 |
missing["load_start"] = "No sustained backward hand load was found."
|
| 417 |
-
preparation_end = events.get("load_start", {"frame": a})["frame"]
|
| 418 |
-
quiet_runs = [(s, e) for s, e in quiet_runs if start+e <= preparation_end]
|
| 419 |
-
if quiet_runs:
|
| 420 |
-
q, stop = quiet_runs[0]
|
| 421 |
-
add("stance_set", start+q, "pre_drive_quiet_hands_v1",
|
| 422 |
-
"Stable hands are a stance estimate, not proof of a complete stance.")
|
| 423 |
lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None
|
| 424 |
contact = None
|
| 425 |
if lead is not None and direction is not None:
|
|
@@ -453,75 +451,36 @@ def infer_events(track, points, options, height, direction, motion, start, end):
|
|
| 453 |
for key in ("stride", "foot_contact", "foot_plant"):
|
| 454 |
missing[key] = "A fixed camera is required to distinguish ground-foot movement from camera movement."
|
| 455 |
elif lead is not None:
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
valid = np.isfinite(baseline).all(axis=1)
|
| 463 |
-
if valid.sum() >= minimum:
|
| 464 |
-
baseline = np.median(baseline[valid], axis=0)
|
| 465 |
-
foot = points[:, ankle]
|
| 466 |
-
displacement = np.linalg.norm(foot-baseline, axis=1)
|
| 467 |
-
lifted = (baseline[1]-foot[:, 1]) > .018*height
|
| 468 |
-
stride_ids = np.flatnonzero((displacement[start:a+1] > .025*height)
|
| 469 |
-
& np.isfinite(foot[start:a+1]).all(axis=1)) + start
|
| 470 |
-
if len(stride_ids):
|
| 471 |
-
stride = int(stride_ids[0])
|
| 472 |
-
if stride > start:
|
| 473 |
-
add("stride", stride, "lead_ankle_departure_v1",
|
| 474 |
-
"Estimated departure from the preparation foot position.", (ankle, back_ankle))
|
| 475 |
-
# The visible ground reference is the preparation foot's toe/heel
|
| 476 |
-
# level. Touchdown and subsequent settled ankle remain estimates
|
| 477 |
-
# and do not measure ground force or full body weight.
|
| 478 |
-
extra = np.arange(3*lead, 3*lead+3)
|
| 479 |
-
baseline_feet = feet[baseline_ids][:, extra, 1]
|
| 480 |
-
levels = np.max(np.where(np.isfinite(baseline_feet), baseline_feet, -np.inf), axis=1)
|
| 481 |
-
levels = levels[np.isfinite(levels)]
|
| 482 |
-
foot_level = float(np.median(levels)) if len(levels) else None
|
| 483 |
-
touchdown = None
|
| 484 |
-
limit = min(a, end) # Preserve the requested foot-plant-before-drive convention.
|
| 485 |
-
airborne = np.flatnonzero(lifted[stride:limit+1]) + stride
|
| 486 |
-
if foot_level is not None and len(airborne):
|
| 487 |
-
last_air = int(airborne[-1])
|
| 488 |
-
for i in range(last_air+1, limit+1):
|
| 489 |
-
y = feet[i, extra, 1]
|
| 490 |
-
if np.isfinite(raw_feet[i, extra]).all() and np.max(y) >= foot_level-.012*height:
|
| 491 |
-
touchdown = i
|
| 492 |
-
add("foot_contact", i, "lead_foot_ground_return_v1",
|
| 493 |
-
"Estimated first toe/heel return to the preparation ground level.", (ankle,))
|
| 494 |
-
break
|
| 495 |
-
planted = None
|
| 496 |
-
for i in range(touchdown if touchdown is not None else stride+1, limit-minimum+2):
|
| 497 |
-
segment = foot[i:i+minimum]
|
| 498 |
-
if not np.isfinite(segment).all(): continue
|
| 499 |
-
settled = np.max(np.linalg.norm(segment-segment[0], axis=1)) <= .012*height
|
| 500 |
-
ground_near = abs(segment[0, 1]-baseline[1]) <= .025*height
|
| 501 |
-
advanced = displacement[i] > .025*height
|
| 502 |
-
if settled and ground_near and advanced:
|
| 503 |
-
planted = i
|
| 504 |
-
add("foot_plant", i, "settled_lead_ankle_ground_proxy_v1",
|
| 505 |
-
"Estimated settled foot near ground; full body-weight loading is unobservable.",
|
| 506 |
-
(ankle, back_ankle))
|
| 507 |
-
break
|
| 508 |
-
if planted is None:
|
| 509 |
-
missing["foot_plant"] = "No settled, grounded lead foot before the forward drive."
|
| 510 |
-
if touchdown is None:
|
| 511 |
-
missing["foot_contact"] = "No clear lift and toe/heel touchdown; settled foot is not first contact."
|
| 512 |
-
else:
|
| 513 |
-
missing["stride"] = "No lead-foot displacement before the forward drive."
|
| 514 |
-
else:
|
| 515 |
-
missing["stride"] = missing["foot_contact"] = missing["foot_plant"] = "Preparation foot reference is unavailable."
|
| 516 |
else:
|
| 517 |
for key in ("stride", "foot_contact", "foot_plant"):
|
| 518 |
missing[key] = "Handedness is required to identify the lead foot."
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
return events, missing
|
| 526 |
|
| 527 |
|
|
@@ -589,7 +548,7 @@ def rep_metrics(track, points, options, height, height_method, direction, events
|
|
| 589 |
"load_tempo_s": timing_reason or "Load start or forward swing onset is missing.",
|
| 590 |
"load_launch_ratio": timing_reason or "Load start, forward swing onset or contact is missing.",
|
| 591 |
"head_movement_pct_height": ("A fixed camera is required; camera movement would contaminate the head path." if not fixed else
|
| 592 |
-
"
|
| 593 |
"lead_knee_angle_contact_deg": "Lead-leg identity or estimated contact is missing.",
|
| 594 |
"lateral_trunk_tilt_contact_deg": "Unavailable: face-on 2D cannot establish the requested anatomical trunk tilt.",
|
| 595 |
"hip_shoulder_separation_foot_plant_deg": "Unavailable: image-plane line angles do not measure axial hip-shoulder twist.",
|
|
@@ -659,7 +618,8 @@ def analyze_batting(track, options):
|
|
| 659 |
"pitcher_direction": "image_right" if direction == 1 else "image_left" if direction == -1 else None,
|
| 660 |
"processing": ["interior_gap_fill_max_3_frames", "hip_relative_3_frame_median",
|
| 661 |
"absolute_3_frame_median_for_fixed_camera_head_path", "raw_pose_track_unchanged",
|
| 662 |
-
"events_bounded_by_primary_hand_motion_burst"
|
|
|
|
| 663 |
"validation": "reference_validation_pending"}
|
| 664 |
|
| 665 |
|
|
|
|
| 8 |
import math
|
| 9 |
import numpy as np
|
| 10 |
from scipy.ndimage import median_filter
|
| 11 |
+
from .swing_preparation import lead_foot_events, preparation_stance
|
| 12 |
|
| 13 |
+
VERSION = "batting-2d-v6"
|
| 14 |
# Nominal 30 FPS, including 29.97 and small timestamp jitter. This is an
|
| 15 |
# engineering support floor, not an accuracy guarantee. The API quality layer
|
| 16 |
# separately rejects each timing metric under ±1-frame event shifts.
|
|
|
|
| 330 |
|
| 331 |
def infer_events(track, points, options, height, direction, motion, start, end):
|
| 332 |
hands, relative, magnitude, forward, threshold = motion
|
| 333 |
+
clock, dt = motion_clock(track["frames"])
|
| 334 |
raw = point_array(track["frames"]["kp"], 17)
|
| 335 |
raw_feet = point_array(track["frames"]["kp_extra"], 6)
|
| 336 |
feet = analysis_points(raw_feet)
|
|
|
|
| 387 |
add("swing_start", a, "primary_swing_hand_motion_onset_v3",
|
| 388 |
"Estimated onset of the primary hand excursion; projected hand travel does not establish forward direction or exact acceleration onset.")
|
| 389 |
quiet = np.isfinite(magnitude) & (magnitude < threshold*.3)
|
|
|
|
| 390 |
finish_start = max(b, start+grouped[0][1]) if grouped else b
|
| 391 |
for s, e in runs(quiet[finish_start:end+1]):
|
| 392 |
if e-s >= minimum and finish_start+s+minimum-1 < end:
|
|
|
|
| 394 |
"Estimated post-swing settling; the last clip frame is not used as finish.")
|
| 395 |
break
|
| 396 |
if options.view != "face_on":
|
| 397 |
+
stance = preparation_stance(points, raw, height, clock, start, a,
|
| 398 |
+
options.camera_stability == "fixed_verified")
|
| 399 |
+
if stance is not None:
|
| 400 |
+
frame, evidence = stance
|
| 401 |
+
add("stance_set", frame, "supported_preparation_stance_v2",
|
| 402 |
+
"Estimated quiet body before the primary motion; view remains unverified.", (9, 10, 11, 12, 15, 16))
|
| 403 |
+
if "stance_set" in events: events["stance_set"]["evidence"] = evidence
|
| 404 |
for key in ("load_start", "stride", "foot_contact", "foot_plant", "contact"):
|
| 405 |
missing[key] = "A declared face-on recording is required."
|
| 406 |
return events, missing
|
|
|
|
| 418 |
"Estimated hand load start; does not establish whole-body loading.")
|
| 419 |
else:
|
| 420 |
missing["load_start"] = "No sustained backward hand load was found."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 421 |
lead = 0 if options.handedness == "right" else 1 if options.handedness == "left" else None
|
| 422 |
contact = None
|
| 423 |
if lead is not None and direction is not None:
|
|
|
|
| 451 |
for key in ("stride", "foot_contact", "foot_plant"):
|
| 452 |
missing[key] = "A fixed camera is required to distinguish ground-foot movement from camera movement."
|
| 453 |
elif lead is not None:
|
| 454 |
+
found, foot_missing = lead_foot_events(points, raw, feet, raw_feet, lead, height,
|
| 455 |
+
clock, start, a, contact, end)
|
| 456 |
+
for key, (i, method, note, evidence) in found.items():
|
| 457 |
+
add(key, i, method, note, (15, 16))
|
| 458 |
+
if key in events: events[key]["evidence"] = evidence
|
| 459 |
+
missing.update(foot_missing)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 460 |
else:
|
| 461 |
for key in ("stride", "foot_contact", "foot_plant"):
|
| 462 |
missing[key] = "Handedness is required to identify the lead foot."
|
| 463 |
+
preparation_end = min((events[name]["frame"] for name in ("load_start", "stride", "swing_start") if name in events), default=a)
|
| 464 |
+
stance = preparation_stance(points, raw, height, clock, start, preparation_end,
|
| 465 |
+
options.camera_stability == "fixed_verified")
|
| 466 |
+
if stance is not None:
|
| 467 |
+
frame, evidence = stance
|
| 468 |
+
add("stance_set", frame, "supported_preparation_stance_v2",
|
| 469 |
+
"Estimated quiet hands, pelvis and feet immediately before this swing's preparation.",
|
| 470 |
+
(9, 10, 11, 12, 15, 16))
|
| 471 |
+
if "stance_set" in events: events["stance_set"]["evidence"] = evidence
|
| 472 |
+
else:
|
| 473 |
+
missing["stance_set"] = "No supported stationary stance connected to this swing's preparation; walking/setup is not a stance."
|
| 474 |
+
# Hand loading and lead-foot departure can overlap or occur in either order.
|
| 475 |
+
# Validate physical dependencies, not the presentation order of field names.
|
| 476 |
+
dependencies = [("stance_set", "load_start"), ("stance_set", "stride"),
|
| 477 |
+
("stride", "foot_contact"), ("foot_contact", "foot_plant"),
|
| 478 |
+
("load_start", "swing_start"), ("foot_plant", "swing_start"),
|
| 479 |
+
("swing_start", "contact"), ("contact", "finish")]
|
| 480 |
+
for before, after in dependencies:
|
| 481 |
+
if before in events and after in events and events[before]["frame"] > events[after]["frame"]:
|
| 482 |
+
events.pop(before)
|
| 483 |
+
missing[before] = f"Candidate occurs after {after}, conflicting with this event definition."
|
| 484 |
return events, missing
|
| 485 |
|
| 486 |
|
|
|
|
| 548 |
"load_tempo_s": timing_reason or "Load start or forward swing onset is missing.",
|
| 549 |
"load_launch_ratio": timing_reason or "Load start, forward swing onset or contact is missing.",
|
| 550 |
"head_movement_pct_height": ("A fixed camera is required; camera movement would contaminate the head path." if not fixed else
|
| 551 |
+
"A supported stance immediately before this swing, estimated contact or a contiguous head path is missing; walk-throughs may have no stationary stance."),
|
| 552 |
"lead_knee_angle_contact_deg": "Lead-leg identity or estimated contact is missing.",
|
| 553 |
"lateral_trunk_tilt_contact_deg": "Unavailable: face-on 2D cannot establish the requested anatomical trunk tilt.",
|
| 554 |
"hip_shoulder_separation_foot_plant_deg": "Unavailable: image-plane line angles do not measure axial hip-shoulder twist.",
|
|
|
|
| 618 |
"pitcher_direction": "image_right" if direction == 1 else "image_left" if direction == -1 else None,
|
| 619 |
"processing": ["interior_gap_fill_max_3_frames", "hip_relative_3_frame_median",
|
| 620 |
"absolute_3_frame_median_for_fixed_camera_head_path", "raw_pose_track_unchanged",
|
| 621 |
+
"events_bounded_by_primary_hand_motion_burst", "final_lead_step_with_raw_sole_confirmation",
|
| 622 |
+
"stance_requires_quiet_hands_pelvis_and_feet", "load_and_stride_may_overlap"],
|
| 623 |
"validation": "reference_validation_pending"}
|
| 624 |
|
| 625 |
|
baseball_batting/measurement_quality.py
CHANGED
|
@@ -8,6 +8,7 @@ import math
|
|
| 8 |
import numpy as np
|
| 9 |
from .batting_measurements import METRICS, analysis_body_points, analysis_points, included_angle, point_array
|
| 10 |
from .event_body3d import backproject
|
|
|
|
| 11 |
|
| 12 |
ANGLE_KEYS = {"lead_knee_angle_contact_deg", "lateral_trunk_tilt_contact_deg",
|
| 13 |
"hip_shoulder_separation_foot_plant_deg"}
|
|
@@ -58,31 +59,13 @@ def angle_value(key, points, options):
|
|
| 58 |
|
| 59 |
|
| 60 |
def checked_3d_rows(report, track, height):
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
if not height: return rows, reasons
|
| 64 |
-
for row in report.get("frames", []):
|
| 65 |
-
i = row["frame"]
|
| 66 |
-
p, px = np.asarray(row["points"], float), np.asarray(row["projection"], float)
|
| 67 |
-
if p.shape != (17, 3) or px.shape != (17, 2) or not 0 <= i < len(raw):
|
| 68 |
-
reasons[i] = "Invalid 3D row dimensions"; continue
|
| 69 |
-
# Per-joint rejection preserves supported measurements on other limbs.
|
| 70 |
-
valid = np.isfinite(p).all(axis=1) & np.isfinite(px).all(axis=1) & (p[:, 2] > 0)
|
| 71 |
-
valid &= np.isfinite(raw[i]).all(axis=1)
|
| 72 |
-
residual = np.linalg.norm(px-raw[i], axis=1)/height
|
| 73 |
-
valid &= residual <= .05
|
| 74 |
-
scores = row.get("scores", [None]*17)
|
| 75 |
-
for j, score in enumerate(scores):
|
| 76 |
-
if score is not None and (not math.isfinite(score) or score < .35): valid[j] = False
|
| 77 |
-
p = p.copy(); p[~valid] = np.nan
|
| 78 |
-
rows[i] = p
|
| 79 |
-
reasons[i] = "3D joints must agree with raw 2D observations within 5% of image stature; model agreement is not truth"
|
| 80 |
-
return rows, reasons
|
| 81 |
|
| 82 |
|
| 83 |
-
def metric_3d(key, rep, track, options, report, height):
|
| 84 |
event_name, joints = SUPPORT[key]
|
| 85 |
-
diagnostic = {"key": key, "method": "
|
| 86 |
"validation": "reference_validation_pending"}
|
| 87 |
if event_name not in rep["events"]:
|
| 88 |
return None, f"Missing {event_name} event.", diagnostic
|
|
@@ -92,14 +75,27 @@ def metric_3d(key, rep, track, options, report, height):
|
|
| 92 |
if key == "lead_knee_angle_contact_deg":
|
| 93 |
lead = 0 if options.handedness == "right" else 1
|
| 94 |
joints = [11+lead, 13+lead, 15+lead]
|
| 95 |
-
|
|
|
|
| 96 |
ids = list(range(max(rep["start_frame"], i-2), min(rep["end_frame"], i+2)+1))
|
|
|
|
|
|
|
| 97 |
if i not in rows or not np.isfinite(rows[i][joints]).all():
|
| 98 |
-
return None, "3D event
|
| 99 |
supported = [j for j in ids if j in rows and np.isfinite(rows[j][joints]).all()]
|
| 100 |
# Require raw adjacent support, not interpolation across missing frames.
|
| 101 |
if not all(j in supported for j in (i-1, i, i+1)):
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
samples = [angle_value(key, rows[j], options) for j in supported]
|
| 104 |
if any(v is None for v in samples):
|
| 105 |
return None, "3D body axes or limb geometry are degenerate.", diagnostic
|
|
@@ -107,11 +103,19 @@ def metric_3d(key, rep, track, options, report, height):
|
|
| 107 |
# concealing a depth flip or changing body proportions.
|
| 108 |
links = [(11, 13), (13, 15)] if options.handedness == "right" else [(12, 14), (14, 16)]
|
| 109 |
if key != "lead_knee_angle_contact_deg": links = [(5, 6), (11, 12)]
|
|
|
|
| 110 |
for a, b in links:
|
| 111 |
lengths = np.array([np.linalg.norm(rows[j][a]-rows[j][b]) for j in supported])
|
|
|
|
|
|
|
|
|
|
| 112 |
if not np.isfinite(lengths).all() or lengths.min() < .08 or lengths.max() > 1.2 or lengths.max()/lengths.min() > 1.25:
|
| 113 |
-
return None, "3D segment lengths change too much or fall outside broad geometry limits.", diagnostic
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
filtered = np.median(relative, axis=0)
|
| 116 |
value = angle_value(key, filtered, options)
|
| 117 |
if value is None: return None, "Filtered 3D geometry is unavailable.", diagnostic
|
|
@@ -147,7 +151,7 @@ def metric_3d(key, rep, track, options, report, height):
|
|
| 147 |
definition = {"lead_knee_angle_contact_deg": "3D interior hip-knee-ankle angle; 180° is straight",
|
| 148 |
"lateral_trunk_tilt_contact_deg": "3D trunk lean in pelvis lateral plane; positive toward the anatomical lead side",
|
| 149 |
"hip_shoulder_separation_foot_plant_deg": "3D hip/shoulder landmark-line separation about declared vertical, modulo 180°"}[key]
|
| 150 |
-
note = f"{report['backend']} estimate: {definition}. Three-frame
|
| 151 |
if geometry.get("assumed"): note += " Camera/depth assumptions used; sensitivity checks do not establish accuracy."
|
| 152 |
return round(value, 3), note, diagnostic
|
| 153 |
|
|
@@ -158,21 +162,30 @@ def apply_measurement_quality(result, options, report):
|
|
| 158 |
height = result["measurement_method"]["body_height_px"]
|
| 159 |
raw = point_array(track["frames"]["kp"], 17)
|
| 160 |
smoothed = analysis_body_points(raw)
|
|
|
|
| 161 |
diagnostics = []
|
| 162 |
for pose_rep, rep in zip(track["reps"], result["measurements"]["reps"]):
|
| 163 |
evidence = []
|
| 164 |
for metric in rep["metrics"]:
|
| 165 |
key = metric["key"]
|
| 166 |
item = {"key": key, "status": "estimated" if metric["value"] is not None else "withheld",
|
| 167 |
-
"method": "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
if options.measurement_backend != "2d" and key in ANGLE_KEYS:
|
| 169 |
-
item["method"] = "
|
| 170 |
if report["status"] not in {"ready", "partial"}:
|
| 171 |
metric.update(value=None, note="Selected 3D backend unavailable: "+report["reason"])
|
| 172 |
elif not result["measurements"]["capture"]["ok"] or options.view != "face_on":
|
| 173 |
metric.update(value=None, note="Capture/view checks failed; 3D does not override them.")
|
| 174 |
else:
|
| 175 |
-
value, note, item = metric_3d(key, pose_rep, track, options, report, height)
|
| 176 |
metric.update(value=value, note=note)
|
| 177 |
elif metric["value"] is not None and key in SUPPORT:
|
| 178 |
event, joints = SUPPORT[key]
|
|
@@ -211,39 +224,8 @@ def apply_measurement_quality(result, options, report):
|
|
| 211 |
item.update(raw_head_path_pct_height=round(raw_path, 3), filtered_head_path_pct_height=round(filtered_path, 3))
|
| 212 |
if raw_path > 2*filtered_path and raw_path-filtered_path > 3:
|
| 213 |
metric.update(value=None, note="Head path is dominated by tracking noise removed by filtering; movement cannot be measured reliably.")
|
| 214 |
-
if key in
|
| 215 |
-
|
| 216 |
-
"load_tempo_s": ("load_start", "swing_start"),
|
| 217 |
-
"load_launch_ratio": ("load_start", "swing_start", "contact")}[key]
|
| 218 |
-
if all(name in pose_rep["events"] for name in names):
|
| 219 |
-
t = track["frames"]["t_s"]
|
| 220 |
-
steps = np.diff(np.asarray(t[pose_rep["start_frame"]:pose_rep["end_frame"]+1], float))
|
| 221 |
-
if len(steps) and np.isfinite(steps).all() and (steps > 0).all():
|
| 222 |
-
item["capture_interval_ms"] = [round(float(steps.min()*1000), 3),
|
| 223 |
-
round(float(steps.max()*1000), 3)]
|
| 224 |
-
intervals = []
|
| 225 |
-
for name in names:
|
| 226 |
-
i = pose_rep["events"][name]["frame"]
|
| 227 |
-
a, b = max(pose_rep["start_frame"], i-1), min(pose_rep["end_frame"], i+1)
|
| 228 |
-
if t[a] is not None and t[b] is not None: intervals.append((t[a], t[b]))
|
| 229 |
-
if len(intervals) == len(names):
|
| 230 |
-
scale = 1000 if key.endswith("_ms") else 1
|
| 231 |
-
if len(names) == 2:
|
| 232 |
-
interval = [(intervals[1][0]-intervals[0][1])*scale,
|
| 233 |
-
(intervals[1][1]-intervals[0][0])*scale]
|
| 234 |
-
else:
|
| 235 |
-
denominator = (intervals[2][0]-intervals[1][1], intervals[2][1]-intervals[1][0])
|
| 236 |
-
interval = ([(intervals[1][0]-intervals[0][1])/denominator[1],
|
| 237 |
-
(intervals[1][1]-intervals[0][0])/denominator[0]] if denominator[0] > 0 else None)
|
| 238 |
-
item.update(event_frame_sensitivity_range=interval,
|
| 239 |
-
event_frame_sensitivity_unit=METRICS[key][0],
|
| 240 |
-
sensitivity_scope="each event shifted ±1 frame; detection error may be larger")
|
| 241 |
-
if interval is None and metric["value"] is not None:
|
| 242 |
-
metric.update(value=None, note="Launch duration is too short to resolve under ±1-frame event shifts.")
|
| 243 |
-
elif interval is not None and metric["value"] is not None:
|
| 244 |
-
width = interval[1]-interval[0]
|
| 245 |
-
if interval[0] <= 0 or width > .5*metric["value"]:
|
| 246 |
-
metric.update(value=None, note="Timing changes too much under ±1-frame event shifts; recording/event resolution is insufficient.")
|
| 247 |
item["status"] = "estimated" if metric["value"] is not None else "withheld"
|
| 248 |
item["note"] = metric["note"]
|
| 249 |
evidence.append(item)
|
|
@@ -252,7 +234,7 @@ def apply_measurement_quality(result, options, report):
|
|
| 252 |
result["experimental_body3d"] = report
|
| 253 |
result["capabilities"]["body_3d"] = report["status"] in {"ready", "partial"} and bool(report["frames"])
|
| 254 |
result["measurement_method"]["backend"] = options.measurement_backend
|
| 255 |
-
result["measurement_method"]["quality_version"] = "measurement-quality-
|
| 256 |
if options.measurement_backend != "2d":
|
| 257 |
result["warnings"].append("3D angles are experimental landmark estimates, not validated anatomical measurements. See measurement_diagnostics and experimental_body3d.")
|
| 258 |
if report["status"] == "unavailable": result["warnings"].append("3D unavailable: "+report["reason"])
|
|
|
|
| 8 |
import numpy as np
|
| 9 |
from .batting_measurements import METRICS, analysis_body_points, analysis_points, included_angle, point_array
|
| 10 |
from .event_body3d import backproject
|
| 11 |
+
from .timing_quality import TIMING_EVENTS, check_timing
|
| 12 |
|
| 13 |
ANGLE_KEYS = {"lead_knee_angle_contact_deg", "lateral_trunk_tilt_contact_deg",
|
| 14 |
"hip_shoulder_separation_foot_plant_deg"}
|
|
|
|
| 59 |
|
| 60 |
|
| 61 |
def checked_3d_rows(report, track, height):
|
| 62 |
+
from .pose_agreement import checked_rows
|
| 63 |
+
return checked_rows(report, track, height)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
|
| 66 |
+
def metric_3d(key, rep, track, options, report, height, checked=None):
|
| 67 |
event_name, joints = SUPPORT[key]
|
| 68 |
+
diagnostic = {"key": key, "method": "3d_landmark_geometry_v2", "status": "withheld",
|
| 69 |
"validation": "reference_validation_pending"}
|
| 70 |
if event_name not in rep["events"]:
|
| 71 |
return None, f"Missing {event_name} event.", diagnostic
|
|
|
|
| 75 |
if key == "lead_knee_angle_contact_deg":
|
| 76 |
lead = 0 if options.handedness == "right" else 1
|
| 77 |
joints = [11+lead, 13+lead, 15+lead]
|
| 78 |
+
from .pose_agreement import COCO_NAMES, rejected_note
|
| 79 |
+
rows, reasons = checked if checked is not None else checked_3d_rows(report, track, height)
|
| 80 |
ids = list(range(max(rep["start_frame"], i-2), min(rep["end_frame"], i+2)+1))
|
| 81 |
+
diagnostic.update(event_frame=i, required_joints=[COCO_NAMES[j] for j in joints],
|
| 82 |
+
pose_agreement=[reasons[j] for j in ids if j in reasons])
|
| 83 |
if i not in rows or not np.isfinite(rows[i][joints]).all():
|
| 84 |
+
return None, "3D event rejected: "+rejected_note(reasons.get(i), joints)+".", diagnostic
|
| 85 |
supported = [j for j in ids if j in rows and np.isfinite(rows[j][joints]).all()]
|
| 86 |
# Require raw adjacent support, not interpolation across missing frames.
|
| 87 |
if not all(j in supported for j in (i-1, i, i+1)):
|
| 88 |
+
unsupported = [f"frame {j}: "+rejected_note(reasons.get(j), joints) for j in (i-1, i+1) if j not in supported]
|
| 89 |
+
return None, "Three consecutive supported 3D frames around the event are required; "+"; ".join(unsupported)+".", diagnostic
|
| 90 |
+
up = np.asarray(options.camera_up, float); up /= np.linalg.norm(up)
|
| 91 |
+
diagnostic["body_geometry"] = []
|
| 92 |
+
for j in supported:
|
| 93 |
+
p = rows[j]
|
| 94 |
+
hip_axis, shoulder_axis = p[11]-p[12], p[5]-p[6]
|
| 95 |
+
hip_axis -= up*np.dot(hip_axis, up); shoulder_axis -= up*np.dot(shoulder_axis, up)
|
| 96 |
+
diagnostic["body_geometry"].append({"frame": j, "hip_horizontal_span_m": float(np.linalg.norm(hip_axis)),
|
| 97 |
+
"shoulder_horizontal_span_m": float(np.linalg.norm(shoulder_axis)),
|
| 98 |
+
"trunk_vertical_component_m": float(np.dot((p[5]+p[6]-p[11]-p[12])/2, up))})
|
| 99 |
samples = [angle_value(key, rows[j], options) for j in supported]
|
| 100 |
if any(v is None for v in samples):
|
| 101 |
return None, "3D body axes or limb geometry are degenerate.", diagnostic
|
|
|
|
| 103 |
# concealing a depth flip or changing body proportions.
|
| 104 |
links = [(11, 13), (13, 15)] if options.handedness == "right" else [(12, 14), (14, 16)]
|
| 105 |
if key != "lead_knee_angle_contact_deg": links = [(5, 6), (11, 12)]
|
| 106 |
+
diagnostic["segment_lengths"] = []
|
| 107 |
for a, b in links:
|
| 108 |
lengths = np.array([np.linalg.norm(rows[j][a]-rows[j][b]) for j in supported])
|
| 109 |
+
diagnostic["segment_lengths"].append({"joints": [COCO_NAMES[a], COCO_NAMES[b]],
|
| 110 |
+
"frames": supported, "lengths_m": lengths.tolist(), "min_m": float(lengths.min()),
|
| 111 |
+
"max_m": float(lengths.max()), "max_min_ratio": float(lengths.max()/lengths.min()) if lengths.min() > 0 else None})
|
| 112 |
if not np.isfinite(lengths).all() or lengths.min() < .08 or lengths.max() > 1.2 or lengths.max()/lengths.min() > 1.25:
|
| 113 |
+
return None, f"3D {COCO_NAMES[a]}–{COCO_NAMES[b]} segment lengths change too much or fall outside broad geometry limits.", diagnostic
|
| 114 |
+
# A knee angle needs its own hip/knee/ankle, not the opposite hip. Anchor
|
| 115 |
+
# at the knee so an unrelated rejected joint cannot contaminate its median.
|
| 116 |
+
anchors = [13 if options.handedness == "right" else 14] if key == "lead_knee_angle_contact_deg" else [11, 12]
|
| 117 |
+
relative = np.stack([rows[j]-np.mean(rows[j][anchors], axis=0) for j in (i-1, i, i+1)])
|
| 118 |
+
diagnostic["filter_anchor_joints"] = [COCO_NAMES[j] for j in anchors]
|
| 119 |
filtered = np.median(relative, axis=0)
|
| 120 |
value = angle_value(key, filtered, options)
|
| 121 |
if value is None: return None, "Filtered 3D geometry is unavailable.", diagnostic
|
|
|
|
| 151 |
definition = {"lead_knee_angle_contact_deg": "3D interior hip-knee-ankle angle; 180° is straight",
|
| 152 |
"lateral_trunk_tilt_contact_deg": "3D trunk lean in pelvis lateral plane; positive toward the anatomical lead side",
|
| 153 |
"hip_shoulder_separation_foot_plant_deg": "3D hip/shoulder landmark-line separation about declared vertical, modulo 180°"}[key]
|
| 154 |
+
note = f"{report['backend']} estimate: {definition}. Three-frame joint-relative median; event and angle accuracy unvalidated."
|
| 155 |
if geometry.get("assumed"): note += " Camera/depth assumptions used; sensitivity checks do not establish accuracy."
|
| 156 |
return round(value, 3), note, diagnostic
|
| 157 |
|
|
|
|
| 162 |
height = result["measurement_method"]["body_height_px"]
|
| 163 |
raw = point_array(track["frames"]["kp"], 17)
|
| 164 |
smoothed = analysis_body_points(raw)
|
| 165 |
+
checked = checked_3d_rows(report, track, height)
|
| 166 |
diagnostics = []
|
| 167 |
for pose_rep, rep in zip(track["reps"], result["measurements"]["reps"]):
|
| 168 |
evidence = []
|
| 169 |
for metric in rep["metrics"]:
|
| 170 |
key = metric["key"]
|
| 171 |
item = {"key": key, "status": "estimated" if metric["value"] is not None else "withheld",
|
| 172 |
+
"method": "2d_estimate_v6", "validation": "reference_validation_pending"}
|
| 173 |
+
if key == "head_movement_pct_height":
|
| 174 |
+
stance = pose_rep["events"].get("stance_set")
|
| 175 |
+
contact = pose_rep["events"].get("contact")
|
| 176 |
+
item.update(window_definition="supported stance through contact proxy; setup walking excluded",
|
| 177 |
+
stance_frame=stance["frame"] if stance else None,
|
| 178 |
+
contact_frame=contact["frame"] if contact else None,
|
| 179 |
+
stance_evidence=stance.get("evidence") if stance else None,
|
| 180 |
+
missing_stance_reason=pose_rep["missing_events"].get("stance_set") if not stance else None)
|
| 181 |
if options.measurement_backend != "2d" and key in ANGLE_KEYS:
|
| 182 |
+
item["method"] = "3d_landmark_geometry_v2"
|
| 183 |
if report["status"] not in {"ready", "partial"}:
|
| 184 |
metric.update(value=None, note="Selected 3D backend unavailable: "+report["reason"])
|
| 185 |
elif not result["measurements"]["capture"]["ok"] or options.view != "face_on":
|
| 186 |
metric.update(value=None, note="Capture/view checks failed; 3D does not override them.")
|
| 187 |
else:
|
| 188 |
+
value, note, item = metric_3d(key, pose_rep, track, options, report, height, checked)
|
| 189 |
metric.update(value=value, note=note)
|
| 190 |
elif metric["value"] is not None and key in SUPPORT:
|
| 191 |
event, joints = SUPPORT[key]
|
|
|
|
| 224 |
item.update(raw_head_path_pct_height=round(raw_path, 3), filtered_head_path_pct_height=round(filtered_path, 3))
|
| 225 |
if raw_path > 2*filtered_path and raw_path-filtered_path > 3:
|
| 226 |
metric.update(value=None, note="Head path is dominated by tracking noise removed by filtering; movement cannot be measured reliably.")
|
| 227 |
+
if key in TIMING_EVENTS:
|
| 228 |
+
check_timing(metric, pose_rep, track, item)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
item["status"] = "estimated" if metric["value"] is not None else "withheld"
|
| 230 |
item["note"] = metric["note"]
|
| 231 |
evidence.append(item)
|
|
|
|
| 234 |
result["experimental_body3d"] = report
|
| 235 |
result["capabilities"]["body_3d"] = report["status"] in {"ready", "partial"} and bool(report["frames"])
|
| 236 |
result["measurement_method"]["backend"] = options.measurement_backend
|
| 237 |
+
result["measurement_method"]["quality_version"] = "measurement-quality-v2"
|
| 238 |
if options.measurement_backend != "2d":
|
| 239 |
result["warnings"].append("3D angles are experimental landmark estimates, not validated anatomical measurements. See measurement_diagnostics and experimental_body3d.")
|
| 240 |
if report["status"] == "unavailable": result["warnings"].append("3D unavailable: "+report["reason"])
|
baseball_batting/pose_agreement.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Explain model disagreement without treating either model as ground truth."""
|
| 2 |
+
from collections import Counter
|
| 3 |
+
import math
|
| 4 |
+
import numpy as np
|
| 5 |
+
from .batting_measurements import point_array
|
| 6 |
+
from .geometry import project
|
| 7 |
+
|
| 8 |
+
COCO_NAMES = ("nose", "left_eye", "right_eye", "left_ear", "right_ear",
|
| 9 |
+
"left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
|
| 10 |
+
"left_wrist", "right_wrist", "left_hip", "right_hip", "left_knee",
|
| 11 |
+
"right_knee", "left_ankle", "right_ankle")
|
| 12 |
+
AGREEMENT_LIMIT_PCT = 5.
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def checked_rows(report, track, height):
|
| 16 |
+
rows, evidence = {}, {}
|
| 17 |
+
raw = point_array(track["frames"]["kp"], 17)
|
| 18 |
+
if not height or not math.isfinite(height) or height <= 0:
|
| 19 |
+
return rows, evidence
|
| 20 |
+
counts = Counter(r.get("frame") for r in report.get("frames", []) if isinstance(r.get("frame"), int))
|
| 21 |
+
for row in report.get("frames", []):
|
| 22 |
+
i = row.get("frame")
|
| 23 |
+
if not isinstance(i, int) or not 0 <= i < len(raw):
|
| 24 |
+
continue
|
| 25 |
+
item = {"frame": i, "projection_limit_pct_height": AGREEMENT_LIMIT_PCT,
|
| 26 |
+
"comparison": "model agreement, not measured accuracy", "rejected_joints": []}
|
| 27 |
+
evidence[i] = item
|
| 28 |
+
try:
|
| 29 |
+
p, px = np.asarray(row.get("points"), float), np.asarray(row.get("projection"), float)
|
| 30 |
+
scores = row.get("scores", [None]*17)
|
| 31 |
+
if p.shape != (17, 3) or px.shape != (17, 2) or len(scores) != 17 or counts[i] != 1:
|
| 32 |
+
raise ValueError("Invalid or duplicated 3D row")
|
| 33 |
+
except (ValueError, TypeError):
|
| 34 |
+
item["row_error"] = "Invalid dimensions, scores or duplicate frame"; continue
|
| 35 |
+
projection_error = np.linalg.norm(px-raw[i], axis=1)/height*100
|
| 36 |
+
projected = None
|
| 37 |
+
k = row.get("camera_intrinsics")
|
| 38 |
+
if k is None and report.get("backend") == "rtmw3d": k = report.get("geometry", {}).get("intrinsics")
|
| 39 |
+
if k is not None:
|
| 40 |
+
try:
|
| 41 |
+
projected = np.linalg.norm(project(p, k)-px, axis=1)
|
| 42 |
+
item["camera_projection_error_px"] = projected.tolist()
|
| 43 |
+
except (ValueError, TypeError):
|
| 44 |
+
item["row_error"] = "Invalid camera intrinsics"; continue
|
| 45 |
+
valid = np.ones(17, bool)
|
| 46 |
+
for j, name in enumerate(COCO_NAMES):
|
| 47 |
+
reasons = []
|
| 48 |
+
if not np.isfinite(p[j]).all() or p[j, 2] <= 0: reasons.append("invalid_camera_xyz")
|
| 49 |
+
if not np.isfinite(px[j]).all(): reasons.append("missing_model_projection")
|
| 50 |
+
if not np.isfinite(raw[i, j]).all(): reasons.append("missing_raw_2d")
|
| 51 |
+
if math.isfinite(projection_error[j]) and projection_error[j] > AGREEMENT_LIMIT_PCT:
|
| 52 |
+
reasons.append("model_projection_disagreement")
|
| 53 |
+
if projected is not None and (not math.isfinite(projected[j]) or projected[j] > 1):
|
| 54 |
+
reasons.append("camera_projection_inconsistent")
|
| 55 |
+
score = scores[j]
|
| 56 |
+
if score is not None:
|
| 57 |
+
try:
|
| 58 |
+
if not math.isfinite(score) or not .35 <= score <= 1: reasons.append("weak_or_invalid_model_score")
|
| 59 |
+
except TypeError:
|
| 60 |
+
reasons.append("weak_or_invalid_model_score")
|
| 61 |
+
if reasons:
|
| 62 |
+
valid[j] = False
|
| 63 |
+
item["rejected_joints"].append({"joint": name, "index": j, "reasons": reasons,
|
| 64 |
+
"projection_error_pct_height": float(projection_error[j])})
|
| 65 |
+
item["projection_error_pct_height"] = projection_error.tolist()
|
| 66 |
+
# A side-swap comparison is diagnostic only. Never automatically swap
|
| 67 |
+
# anatomical identities to make two models agree.
|
| 68 |
+
pairs = [(5, 6), (7, 8), (9, 10), (11, 12), (13, 14), (15, 16)]
|
| 69 |
+
normal, swapped = [], []
|
| 70 |
+
for a, b in pairs:
|
| 71 |
+
if np.isfinite(px[[a, b]]).all() and np.isfinite(raw[i, [a, b]]).all():
|
| 72 |
+
normal.extend(np.linalg.norm(px[[a, b]]-raw[i, [a, b]], axis=1))
|
| 73 |
+
swapped.extend(np.linalg.norm(px[[a, b]]-raw[i, [b, a]], axis=1))
|
| 74 |
+
if normal:
|
| 75 |
+
item["side_swap_check"] = {"original_median_pct_height": float(np.median(normal)/height*100),
|
| 76 |
+
"swapped_median_pct_height": float(np.median(swapped)/height*100),
|
| 77 |
+
"possible_side_swap": np.median(normal) > .01*height and np.median(swapped) < .5*np.median(normal),
|
| 78 |
+
"action": "report only; anatomical sides preserved"}
|
| 79 |
+
p = p.copy(); p[~valid] = np.nan
|
| 80 |
+
rows[i] = p
|
| 81 |
+
return rows, evidence
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def rejected_note(item, joints):
|
| 85 |
+
if not item: return "requested event frame was not returned"
|
| 86 |
+
if item.get("row_error"): return item["row_error"]
|
| 87 |
+
blocked = [r for r in item["rejected_joints"] if r["index"] in joints]
|
| 88 |
+
labels = []
|
| 89 |
+
for r in blocked:
|
| 90 |
+
if "model_projection_disagreement" in r["reasons"]:
|
| 91 |
+
labels.append(f"{r['joint']} differs by {r['projection_error_pct_height']:.2f}% of image stature (limit {AGREEMENT_LIMIT_PCT:g}%)")
|
| 92 |
+
else: labels.append(r["joint"]+": "+", ".join(r["reasons"]))
|
| 93 |
+
return "; ".join(labels) or "required geometry is unsupported"
|
baseball_batting/swing_preparation.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Preparation evidence in a fixed image; never a ground-force measurement.
|
| 2 |
+
|
| 3 |
+
Only raw-supported windows establish events. A settled foot may be lower in
|
| 4 |
+
the image after a step in depth. Confirmation can follow the event timestamp,
|
| 5 |
+
but cannot cross the rep boundary or borrow the follow-through.
|
| 6 |
+
"""
|
| 7 |
+
import numpy as np
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def stable_window(filtered, raw, start, stop, tolerance):
|
| 11 |
+
segment = filtered[start:stop]
|
| 12 |
+
if len(segment) < 3 or not np.isfinite(raw[start:stop]).all() or not np.isfinite(segment).all():
|
| 13 |
+
return False
|
| 14 |
+
# Diameter, rather than displacement from the first sample: a noisy first
|
| 15 |
+
# sample must not determine whether an otherwise identical window settles.
|
| 16 |
+
return bool(np.max(np.linalg.norm(segment[:, None]-segment[None, :], axis=-1)) <= tolerance)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def preparation_stance(points, raw, height, clock, start, preparation_end, fixed):
|
| 20 |
+
"""Last sustained quiet body window connected to this swing's preparation.
|
| 21 |
+
|
| 22 |
+
Quiet hands alone can occur while walking. Both ankles and the pelvis must
|
| 23 |
+
settle too. No late replacement window shortens an already-moving swing.
|
| 24 |
+
A walk-through without a supported stance deliberately has no stance event.
|
| 25 |
+
"""
|
| 26 |
+
dt = float(np.median(np.diff(clock)))
|
| 27 |
+
count = max(5, min(60, int(np.ceil(.15/dt))))
|
| 28 |
+
joints = [9, 10, 11, 12, 15, 16]
|
| 29 |
+
features = points[:, joints].copy()
|
| 30 |
+
raw_features = raw[:, joints].copy()
|
| 31 |
+
if not fixed:
|
| 32 |
+
features -= ((points[:, 11]+points[:, 12])/2)[:, None]
|
| 33 |
+
raw_features -= ((raw[:, 11]+raw[:, 12])/2)[:, None]
|
| 34 |
+
lookback = max(start, preparation_end-max(count, min(600, int(np.ceil(2./dt)))))
|
| 35 |
+
for stop in range(preparation_end+1, lookback+count-1, -1):
|
| 36 |
+
a = stop-count
|
| 37 |
+
segment = features[a:stop]
|
| 38 |
+
if not np.isfinite(raw_features[a:stop]).all() or not np.isfinite(segment).all():
|
| 39 |
+
continue
|
| 40 |
+
span = np.linalg.norm(segment[:, None]-segment[None, :], axis=-1).max(axis=(0, 1))
|
| 41 |
+
if span.max() > .012*height:
|
| 42 |
+
continue
|
| 43 |
+
# A long enough window and robust endpoint medians distinguish slow
|
| 44 |
+
# walking from pose jitter. Times are for motion detection only; this
|
| 45 |
+
# never asserts that playback timestamps are physical capture time.
|
| 46 |
+
third = max(1, count//3)
|
| 47 |
+
elapsed = float(np.median(clock[stop-third:stop])-np.median(clock[a:a+third]))
|
| 48 |
+
drift = np.linalg.norm(np.median(segment[-third:], axis=0)-np.median(segment[:third], axis=0), axis=-1)
|
| 49 |
+
if elapsed <= 0 or (drift/elapsed).max() > .03*height:
|
| 50 |
+
continue
|
| 51 |
+
# A quiet patch followed by unrelated steps is not the stance for this
|
| 52 |
+
# swing. The quiet window must reach the current preparation closely.
|
| 53 |
+
if clock[preparation_end]-clock[stop-1] > .15:
|
| 54 |
+
return None
|
| 55 |
+
return a, {"support_frames": [a, stop-1], "preparation_boundary_frame": preparation_end,
|
| 56 |
+
"definition": "last quiet hands, pelvis and ankles before this swing's preparation"}
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def lead_foot_events(points, raw, feet, raw_feet, lead, height, clock, start, onset, contact, end):
|
| 61 |
+
ankle = 15+lead
|
| 62 |
+
extra = list(range(3*lead, 3*lead+3))
|
| 63 |
+
foot = points[:, ankle]
|
| 64 |
+
raw_foot = raw[:, ankle]
|
| 65 |
+
dt = float(np.median(np.diff(clock)))
|
| 66 |
+
start = max(start, onset-max(3, min(600, int(np.ceil(2./dt)))))
|
| 67 |
+
count = max(3, min(30, int(np.ceil(.06/dt))))
|
| 68 |
+
# At most one short confirmation window after onset. A later planted foot
|
| 69 |
+
# during follow-through is not a pre-drive event.
|
| 70 |
+
limit = min(onset, end, contact-1 if contact is not None else onset)
|
| 71 |
+
found = {}
|
| 72 |
+
missing = {"stride": "No supported final lead-foot departure before the drive.",
|
| 73 |
+
"foot_contact": "No supported lift and ground-return transition.",
|
| 74 |
+
"foot_plant": "No supported lead-foot return and settling before or at the drive."}
|
| 75 |
+
if limit-start < count:
|
| 76 |
+
return found, missing
|
| 77 |
+
# Choose the last supported settling transition, working backwards for its
|
| 78 |
+
# preparation reference. This handles walk-throughs with earlier steps.
|
| 79 |
+
# Cache old quiet positions once. A held leg kick can be quiet in mid-air;
|
| 80 |
+
# it must not replace the earlier ground reference. Each candidate searches
|
| 81 |
+
# past such windows until it finds a complete supported lift/return.
|
| 82 |
+
references = []
|
| 83 |
+
for b in range(start+count-1, limit):
|
| 84 |
+
a = b-count+1
|
| 85 |
+
if stable_window(foot, raw_foot, a, b+1, .012*height):
|
| 86 |
+
references.append((a, b, np.median(foot[a:b+1], axis=0)))
|
| 87 |
+
if not references:
|
| 88 |
+
return found, missing
|
| 89 |
+
ref_ends = np.asarray([r[1] for r in references])
|
| 90 |
+
ref_positions = np.stack([r[2] for r in references])
|
| 91 |
+
candidates = []
|
| 92 |
+
for i in range(start+count, limit+1):
|
| 93 |
+
stop = i+count
|
| 94 |
+
if stop > end+1 or (contact is not None and stop > contact):
|
| 95 |
+
continue
|
| 96 |
+
if not stable_window(foot, raw_foot, i, stop, .012*height):
|
| 97 |
+
continue
|
| 98 |
+
sole_support = [j for j in extra if stable_window(feet[:, j], raw_feet[:, j], i, stop, .012*height)]
|
| 99 |
+
if len(sole_support) < 2:
|
| 100 |
+
continue # A quiet ankle alone can be a raised foot or a pose freeze.
|
| 101 |
+
eligible = (ref_ends < i) & (np.linalg.norm(ref_positions-foot[i], axis=1) > .025*height)
|
| 102 |
+
for reference_id in np.flatnonzero(eligible)[::-1]:
|
| 103 |
+
a, b, baseline = references[reference_id]
|
| 104 |
+
segment = foot[b:i+1]
|
| 105 |
+
if not np.isfinite(raw_foot[b:i+1]).all() or not np.isfinite(segment).all():
|
| 106 |
+
continue
|
| 107 |
+
# Require an observed rise and subsequent descent. Returning close to
|
| 108 |
+
# the old ankle's level is a one-sided floor check, not an equality:
|
| 109 |
+
# landing farther down the image is allowed. A landing above that level
|
| 110 |
+
# needs scene geometry we don't have and remains unconfirmed.
|
| 111 |
+
apex = b+int(np.argmin(segment[:, 1]))
|
| 112 |
+
lift = baseline[1]-foot[apex, 1]
|
| 113 |
+
descent = foot[i, 1]-foot[apex, 1]
|
| 114 |
+
if lift < .018*height or descent < .018*height or apex <= b or apex >= i:
|
| 115 |
+
continue
|
| 116 |
+
if foot[i, 1] < baseline[1]-.012*height:
|
| 117 |
+
continue
|
| 118 |
+
# The sole must also return, so ankle motion alone cannot declare ground
|
| 119 |
+
# contact. Use each landmark's own preparation level; no inferred plane
|
| 120 |
+
# through two different-depth feet is treated as a calibrated ground.
|
| 121 |
+
returned = []
|
| 122 |
+
for j in sole_support:
|
| 123 |
+
if not np.isfinite(raw_feet[a:b+1, j]).all():
|
| 124 |
+
continue
|
| 125 |
+
level = float(np.median(feet[a:b+1, j, 1]))
|
| 126 |
+
if feet[i, j, 1] >= level-.012*height:
|
| 127 |
+
returned.append((j, level))
|
| 128 |
+
if len(returned) < 2:
|
| 129 |
+
continue
|
| 130 |
+
departure = next((k for k in range(b+1, apex+1)
|
| 131 |
+
if np.linalg.norm(foot[k]-baseline) > .025*height), None)
|
| 132 |
+
if departure is None:
|
| 133 |
+
continue
|
| 134 |
+
touchdown = None
|
| 135 |
+
for k in range(apex+1, i+1):
|
| 136 |
+
if all(np.isfinite(raw_feet[k, j]).all() and feet[k, j, 1] >= level-.012*height
|
| 137 |
+
for j, level in returned):
|
| 138 |
+
touchdown = k
|
| 139 |
+
break
|
| 140 |
+
if touchdown is None:
|
| 141 |
+
continue
|
| 142 |
+
# Require deceleration into the window, rather than allowing a slow
|
| 143 |
+
# moving foot to pass a short stationarity threshold everywhere.
|
| 144 |
+
travel = np.linalg.norm(foot[apex:i]-foot[i], axis=1).max()
|
| 145 |
+
if travel <= .025*height:
|
| 146 |
+
continue
|
| 147 |
+
candidates.append((i, departure, touchdown, [a, b], stop-1, sole_support))
|
| 148 |
+
break
|
| 149 |
+
if not candidates:
|
| 150 |
+
return found, missing
|
| 151 |
+
# Earlier candidates can be an intermediate landing followed by another
|
| 152 |
+
# step. Last departure identifies the final step; its earliest confirmed
|
| 153 |
+
# settling window supplies the timestamp, not the end of that window.
|
| 154 |
+
final_departure = max(c[1] for c in candidates)
|
| 155 |
+
i, departure, touchdown, baseline_frames, confirmed, sole = next(c for c in candidates if c[1] == final_departure)
|
| 156 |
+
common = {"baseline_frames": baseline_frames, "confirmation_end_frame": confirmed,
|
| 157 |
+
"foot_landmarks": sole, "grounding": "observed lift/return and sole settling; ground force unobservable"}
|
| 158 |
+
found = {"stride": (departure, "final_lead_foot_departure_v2", "Estimated departure for the final lead-foot step.", common),
|
| 159 |
+
"foot_contact": (touchdown, "lead_sole_return_v2", "Estimated toe/heel return after the visible lift; first physical contact unconfirmed.", common),
|
| 160 |
+
"foot_plant": (i, "settled_lead_foot_return_v2", "Estimated returned, settled foot at its new image position; full weight unmeasured.", common)}
|
| 161 |
+
return found, {}
|
baseball_batting/timing_quality.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Timestamp-based resolution checks. No invented subframes or capture clocks."""
|
| 2 |
+
import numpy as np
|
| 3 |
+
from .batting_measurements import MAX_TIMING_INTERVAL_S, METRICS
|
| 4 |
+
|
| 5 |
+
TIMING_EVENTS = {"foot_plant_to_contact_ms": ("foot_plant", "contact"),
|
| 6 |
+
"load_tempo_s": ("load_start", "swing_start"),
|
| 7 |
+
"load_launch_ratio": ("load_start", "swing_start", "contact")}
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def check_timing(metric, rep, track, diagnostic):
|
| 11 |
+
key = metric['key']
|
| 12 |
+
names = TIMING_EVENTS[key]
|
| 13 |
+
missing = [name for name in names if name not in rep['events']]
|
| 14 |
+
diagnostic['missing_events'] = missing
|
| 15 |
+
if missing:
|
| 16 |
+
diagnostic['resolution_status'] = 'missing_events'
|
| 17 |
+
return
|
| 18 |
+
indices = [rep['events'][name]['frame'] for name in names]
|
| 19 |
+
diagnostic['event_frames'] = dict(zip(names, indices))
|
| 20 |
+
diagnostic['duration_frame_intervals'] = {a+'_to_'+b: j-i for a, b, i, j in
|
| 21 |
+
zip(names, names[1:], indices, indices[1:])}
|
| 22 |
+
t = np.asarray(track['frames']['t_s'], float)
|
| 23 |
+
start, end = rep['start_frame'], rep['end_frame']
|
| 24 |
+
steps = np.diff(t[start:end+1])
|
| 25 |
+
if not len(steps) or not np.isfinite(t[start:end+1]).all() or (steps <= 0).any():
|
| 26 |
+
diagnostic['resolution_status'] = 'capture_clock_unknown_or_invalid'
|
| 27 |
+
metric.update(value=None, note='Real capture timing is unknown or invalid; playback timing cannot supply it.')
|
| 28 |
+
return
|
| 29 |
+
diagnostic['capture_interval_ms'] = [round(float(steps.min()*1000), 3), round(float(steps.max()*1000), 3)]
|
| 30 |
+
if steps.max() > MAX_TIMING_INTERVAL_S+1e-6:
|
| 31 |
+
diagnostic['resolution_status'] = 'capture_cadence_insufficient'
|
| 32 |
+
metric.update(value=None, note='Timing requires nominal 30 FPS or higher capture cadence without missing capture frames.')
|
| 33 |
+
return
|
| 34 |
+
windows = [(max(start, i-1), min(end, i+1)) for i in indices]
|
| 35 |
+
diagnostic['event_shift_frames'] = dict(zip(names, [list(w) for w in windows]))
|
| 36 |
+
intervals = [(t[a], t[b]) for a, b in windows]
|
| 37 |
+
scale = 1000 if key.endswith('_ms') else 1
|
| 38 |
+
if len(names) == 2:
|
| 39 |
+
interval = [(intervals[1][0]-intervals[0][1])*scale, (intervals[1][1]-intervals[0][0])*scale]
|
| 40 |
+
nominal = (t[indices[1]]-t[indices[0]])*scale
|
| 41 |
+
else:
|
| 42 |
+
denominator = (intervals[2][0]-intervals[1][1], intervals[2][1]-intervals[1][0])
|
| 43 |
+
interval = ([(intervals[1][0]-intervals[0][1])/denominator[1],
|
| 44 |
+
(intervals[1][1]-intervals[0][0])/denominator[0]] if denominator[0] > 0 else None)
|
| 45 |
+
nominal = ((t[indices[1]]-t[indices[0]])/(t[indices[2]]-t[indices[1]])
|
| 46 |
+
if t[indices[2]] > t[indices[1]] else None)
|
| 47 |
+
diagnostic.update(event_frame_sensitivity_range=interval, event_frame_sensitivity_unit=METRICS[key][0],
|
| 48 |
+
sensitivity_scope='each event shifted ±1 frame; detection error may be larger',
|
| 49 |
+
relative_sensitivity_width_limit=.5)
|
| 50 |
+
width = interval[1]-interval[0] if interval is not None else None
|
| 51 |
+
relative_width = width/nominal if width is not None and nominal is not None and nominal > 0 else None
|
| 52 |
+
diagnostic['relative_sensitivity_width'] = relative_width
|
| 53 |
+
insufficient = interval is None or interval[0] <= 0 or relative_width is None or relative_width > .5+1e-9
|
| 54 |
+
diagnostic['resolution_status'] = 'insufficient_event_resolution' if insufficient else 'resolved_under_frame_shift_check'
|
| 55 |
+
if insufficient and metric['value'] is not None:
|
| 56 |
+
count = indices[-1]-indices[-2]
|
| 57 |
+
label = 'launch' if len(names) == 3 else 'interval'
|
| 58 |
+
if interval is None:
|
| 59 |
+
detail = 'the launch can vanish'
|
| 60 |
+
else:
|
| 61 |
+
detail = f"the {METRICS[key][0]} range is {interval[0]:.3g}–{interval[1]:.3g}"
|
| 62 |
+
metric.update(value=None, note=f'Timing is insufficient under ±1-frame event shifts: {label} spans {count} recorded frame intervals; {detail}.')
|
docs/BATTING_2D_MEASUREMENTS.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# 2D batting measurement definitions
|
| 2 |
|
| 3 |
-
Version: `batting-2d-
|
| 4 |
|
| 5 |
## Pose checkpoint and foot points
|
| 6 |
|
|
@@ -36,16 +36,20 @@ The contact proxy searches from shortly before the primary hand-speed peak (up t
|
|
| 36 |
|
| 37 |
| Event | Evidence and limitation |
|
| 38 |
|---|---|
|
| 39 |
-
| `stance_set` |
|
| 40 |
| `load_start` | Sustained backward hand excursion before forward motion, using a lower threshold than the faster drive |
|
| 41 |
-
| `stride` | Lead ankle departs
|
| 42 |
-
| `foot_contact` | After a
|
| 43 |
-
| `foot_plant` |
|
| 44 |
| `swing_start` | Primary hand excursion, with forward onset refined only inside that movement; exact acceleration onset remains unvalidated |
|
| 45 |
| `contact` | Visible lead-arm extension plateau with hands forward during the primary swinging movement; always estimated, no ball/sensor confirmation |
|
| 46 |
| `finish` | Observed post-drive hand settling; clip end is never forced as finish |
|
| 47 |
|
| 48 |
-
Events must be inside their rep and follow
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
## Numbers
|
| 51 |
|
|
@@ -79,7 +83,7 @@ Blur is the existing uncalibrated `1/(1+Laplacian variance/100)` heuristic. Pose
|
|
| 79 |
|
| 80 |
## Optional 3D and quality layer
|
| 81 |
|
| 82 |
-
The API applies `measurement-quality-
|
| 83 |
|
| 84 |
## Validation remaining
|
| 85 |
|
|
|
|
| 1 |
# 2D batting measurement definitions
|
| 2 |
|
| 3 |
+
Version: `batting-2d-v6`. Scope: face-on batting, with fixed-camera requirements only for ground-foot events and head movement. This module uses GPU pose/person outputs and CPU arithmetic, with no SAM, temporal 3D fitting, OpenSim or coaching decisions.
|
| 4 |
|
| 5 |
## Pose checkpoint and foot points
|
| 6 |
|
|
|
|
| 36 |
|
| 37 |
| Event | Evidence and limitation |
|
| 38 |
|---|---|
|
| 39 |
+
| `stance_set` | Last supported quiet hands, pelvis and ankles immediately before preparation; setup walking is excluded |
|
| 40 |
| `load_start` | Sustained backward hand excursion before forward motion, using a lower threshold than the faster drive |
|
| 41 |
+
| `stride` | Lead ankle departs a supported old position by >2.5% of height during the final preparation step |
|
| 42 |
+
| `foot_contact` | After a visible lift/descent, at least two supported sole landmarks return to or below their preparation levels; first physical contact is unconfirmed |
|
| 43 |
+
| `foot_plant` | Lead ankle and at least two sole landmarks settle at the new image position, with observed lift/return evidence; does **not** measure full body-weight loading |
|
| 44 |
| `swing_start` | Primary hand excursion, with forward onset refined only inside that movement; exact acceleration onset remains unvalidated |
|
| 45 |
| `contact` | Visible lead-arm extension plateau with hands forward during the primary swinging movement; always estimated, no ball/sensor confirmation |
|
| 46 |
| `finish` | Observed post-drive hand settling; clip end is never forced as finish |
|
| 47 |
|
| 48 |
+
Events must be inside their rep and follow their physical dependencies. Hand load and foot departure can occur in either order. Stride precedes foot return/plant; load and plant precede or coincide with onset; onset precedes contact. Conflicting candidates are omitted with a reason. Foot-plant timestamps after onset remain withheld. A short confirmation window may extend beyond onset, but stays before contact and inside the rep; the event is timestamped at the window's beginning. Capture timestamps are included only from the declared physical clock. `events_ms` uses milliseconds from the rep's start; playback time never becomes physical event time.
|
| 49 |
+
|
| 50 |
+
Foot detection looks back at most two seconds on the motion-analysis clock (capped at 600 frames). It uses quiet old positions, not a median across a moving preparation, and searches past held leg kicks. The final step is selected when there are multiple preparation steps. Settling requires at least three raw-supported frames spanning approximately 60 ms, with ankle/sole window diameter at most 1.2% of image stature. Lift/descent must each exceed 1.8%, and displacement must exceed 2.5%. These are scale-relative engineering gates, not calibrated ground-contact thresholds. A lower landing in the image is allowed; a clearly higher landing without scene geometry cannot be confirmed. Missing foot points, hovering, continued travel and no distinct step do not fabricate a plant event.
|
| 51 |
+
|
| 52 |
+
Stance uses a raw-supported window of at least five frames spanning approximately 150 ms. Hand, pelvis and ankle spans must stay within 1.2% of stature, with robust drift at most 3% of stature per analysis second. The window must end within 150 ms of preparation. Quiet hands on a walking body and old pauses followed by unrelated walking do not qualify. A walk-through may have no stationary stance, leaving head path unavailable instead of reporting its setup walking as swing movement. These gates are conservative evidence checks; they do not prove a complete biomechanical stance.
|
| 53 |
|
| 54 |
## Numbers
|
| 55 |
|
|
|
|
| 83 |
|
| 84 |
## Optional 3D and quality layer
|
| 85 |
|
| 86 |
+
The API applies `measurement-quality-v2` and optional RTMW3D/SAM event-window estimates after this 2D stage. See [NINE_MEASUREMENTS.md](NINE_MEASUREMENTS.md) for all nine definitions, camera assumptions, rejection gates and Colab/model choices. Version 6 retains support for documented nominal 30 FPS or higher physical timestamps, including variable cadence and 29.97 FPS. Every interval must be <= `1.01/30` seconds. The quality layer separately rejects poorly resolved durations/ratios under ±1-frame event shifts and records contributing frame counts and resolution status. Unknown clocks still withhold timing. This module itself does not infer 3D.
|
| 87 |
|
| 88 |
## Validation remaining
|
| 89 |
|
docs/NINE_MEASUREMENTS.md
CHANGED
|
@@ -49,20 +49,22 @@ Contact still means estimated lead-arm extension during the primary swing, not c
|
|
| 49 |
|
| 50 |
## Stability checks and evidence
|
| 51 |
|
| 52 |
-
The raw exported 2D track stays unchanged. The analytical track retains bounded three-frame interpolation/median filtering and the v3 event repair. Version `batting-2d-
|
|
|
|
|
|
|
| 53 |
|
| 54 |
30 FPS has about 33.3 ms between frames; 60 FPS has about 16.7 ms. The previous 60 FPS cutoff was an engineering choice, not a model requirement. A longer load can be estimated at 30 FPS, while a short launch or plant-to-contact interval may remain too poorly resolved. The API quality layer rejects each duration/ratio if its ±1-frame sensitivity range is nonpositive/undefined or wider than half its value. This is a resolution stress test, not a measured error limit. The full result records `capture_interval_ms`, `event_frame_sensitivity_range` and its unit. An advisory `low_fps` capture reason can remain at 30 FPS without making capture fail.
|
| 55 |
|
| 56 |
-
`measurement-quality-
|
| 57 |
|
| 58 |
- Raw joint support near measurement events; large raw-versus-filtered joint changes withhold a value.
|
| 59 |
- Nearby-frame position sensitivity for stride and hip position. More than six percentage points of variation withholds the value.
|
| 60 |
- Raw-versus-filtered head path checks to reject noise-dominated paths.
|
| 61 |
-
- Timing sensitivity when each event shifts by one frame. Nonpositive/poorly resolved durations or ratios are withheld.
|
| 62 |
-
- 3D projections must agree with raw 2D joints within 5% of image stature. This is agreement between models, not comparison to truth.
|
| 63 |
- Three consecutive supported 3D frames around the actual event. No missing-event substitution or interpolation of unavailable 3D.
|
| 64 |
- Broad segment-length bounds and at most 25% local length variation.
|
| 65 |
-
- A
|
| 66 |
- Nearby-frame angle sensitivity limits: knee 15°, trunk 12°, separation 20°. These are initial conservative engineering gates, not measured error limits.
|
| 67 |
|
| 68 |
`measurement_diagnostics` in the full result explains each value or omission. Frame-shift ranges and camera-prior sensitivity are stress checks, **not accuracy confidence intervals**. The compact coach payload keeps exactly its existing nine entries, units and `est` labels; no new keys are required by the coach.
|
|
@@ -82,13 +84,13 @@ Without intrinsics the declared prior is focal length `1.2 × max(width,height)`
|
|
| 82 |
|
| 83 |
When geometry is assumed, lightweight angles are stressed with independent ±15% focal/depth changes and withheld if they exceed the same angle sensitivity limits. The true camera can lie outside that perturbation band. Supplying accurate calibration/depth removes that particular prior check but does not validate model predictions. Inferred metre coordinates remain experimental.
|
| 84 |
|
| 85 |
-
SAM supplies its own predicted camera translation. The adapter verifies its projection/unit convention and maps native MHR landmarks to COCO-17. It does not divide already converted coordinates by 100 or flip their axes again. SAM provides no calibrated joint confidence; its exported scores remain null. 2D agreement and stability gates still apply. Its default FOV is recorded when camera calibration is absent.
|
| 86 |
|
| 87 |
## Colab comparison
|
| 88 |
|
| 89 |
Open [batting_measurements_test.ipynb](../notebooks/batting_measurements_test.ipynb). It has the familiar eight steps. In step 3 set `MEASUREMENT_BACKEND` to `rtmw3d`, `sam3d` or `2d`.
|
| 90 |
|
| 91 |
-
Run steps 1–8 for the first test. To compare another model on the same recording, change step 3 and rerun steps 3–8. A fresh job and backend-labelled ZIP are created, retaining source commit, input hash, recording options, raw points, measurements, 3D diagnostics and previews. The existing 2D-only notebook remains available separately.
|
| 92 |
|
| 93 |
For SAM, set `EXISTING_SAM_RECORD` to an earlier installed `full-worker.json` to reuse that environment/assets. Otherwise setup installs only the isolated SAM inference environment and reads `HF_TOKEN` from a Colab secret or hidden input. Provider approval is still required. Setup never runs anatomy checks or temporal reconstruction.
|
| 94 |
|
|
|
|
| 49 |
|
| 50 |
## Stability checks and evidence
|
| 51 |
|
| 52 |
+
The raw exported 2D track stays unchanged. The analytical track retains bounded three-frame interpolation/median filtering and the v3 event repair. Version `batting-2d-v6` adds supported final-step/stance evidence and retains documented nominal 30 FPS or higher timestamps, including variable cadence and 29.97 FPS. Every capture interval in the rep must be <= `1.01/30` seconds; the 1% tolerance accommodates fractional frame rates and small timestamp jitter. Larger gaps withhold timing. Playback time still never supplies physical swing time.
|
| 53 |
+
|
| 54 |
+
The final lead-foot step is tracked from a quiet old position through lift, sole return and settling at its new image position. A short confirmation window can follow onset while keeping the plant timestamp before or at onset; it cannot borrow contact/follow-through. Head path starts only at a supported quiet hands/pelvis/ankles window immediately before preparation. Walk-throughs without such a stance leave head movement unavailable. See [event evidence and thresholds](BATTING_2D_MEASUREMENTS.md#swings-and-events).
|
| 55 |
|
| 56 |
30 FPS has about 33.3 ms between frames; 60 FPS has about 16.7 ms. The previous 60 FPS cutoff was an engineering choice, not a model requirement. A longer load can be estimated at 30 FPS, while a short launch or plant-to-contact interval may remain too poorly resolved. The API quality layer rejects each duration/ratio if its ±1-frame sensitivity range is nonpositive/undefined or wider than half its value. This is a resolution stress test, not a measured error limit. The full result records `capture_interval_ms`, `event_frame_sensitivity_range` and its unit. An advisory `low_fps` capture reason can remain at 30 FPS without making capture fail.
|
| 57 |
|
| 58 |
+
`measurement-quality-v2` includes:
|
| 59 |
|
| 60 |
- Raw joint support near measurement events; large raw-versus-filtered joint changes withhold a value.
|
| 61 |
- Nearby-frame position sensitivity for stride and hip position. More than six percentage points of variation withholds the value.
|
| 62 |
- Raw-versus-filtered head path checks to reject noise-dominated paths.
|
| 63 |
+
- Timing sensitivity when each event shifts by one frame. Nonpositive/poorly resolved durations or ratios are withheld. `duration_frame_intervals`, `event_frames`, `event_shift_frames`, `relative_sensitivity_width` and `resolution_status` distinguish missing events/clocks from insufficient recording resolution. Raising a file's FPS label does not add recorded samples.
|
| 64 |
+
- 3D projections must agree with raw 2D joints within 5% of image stature. This is agreement between models, not comparison to truth. Per-frame `pose_agreement` records named rejected joints, percentage residuals, camera-projection consistency and a side-swap diagnostic. Anatomical sides and points are never shifted/swapped to force agreement.
|
| 65 |
- Three consecutive supported 3D frames around the actual event. No missing-event substitution or interpolation of unavailable 3D.
|
| 66 |
- Broad segment-length bounds and at most 25% local length variation.
|
| 67 |
+
- A three-frame relative median before 3D angle calculation; knee geometry is anchored at its knee, trunk/separation at the pelvis. An unsupported opposite hip cannot invalidate an otherwise supported knee. Raw model points remain in the experimental export.
|
| 68 |
- Nearby-frame angle sensitivity limits: knee 15°, trunk 12°, separation 20°. These are initial conservative engineering gates, not measured error limits.
|
| 69 |
|
| 70 |
`measurement_diagnostics` in the full result explains each value or omission. Frame-shift ranges and camera-prior sensitivity are stress checks, **not accuracy confidence intervals**. The compact coach payload keeps exactly its existing nine entries, units and `est` labels; no new keys are required by the coach.
|
|
|
|
| 84 |
|
| 85 |
When geometry is assumed, lightweight angles are stressed with independent ±15% focal/depth changes and withheld if they exceed the same angle sensitivity limits. The true camera can lie outside that perturbation band. Supplying accurate calibration/depth removes that particular prior check but does not validate model predictions. Inferred metre coordinates remain experimental.
|
| 86 |
|
| 87 |
+
SAM supplies its own predicted camera translation. The adapter verifies its projection/unit convention and maps native MHR landmarks to COCO-17. The [pinned provider landmark names](https://github.com/facebookresearch/sam-3d-body/blob/b5c765a0d89d789985e186d396315e7590887b94/sam_3d_body/metadata/mhr70.py) identify native hips 9/10, knees 11/12, ankles 13/14 and wrists 62/41. It does not divide already converted coordinates by 100 or flip their axes again. SAM provides no calibrated joint confidence; its exported scores remain null. 2D agreement and stability gates still apply. Its default FOV is recorded when camera calibration is absent. Valid camera conversion does not explain away disagreement between joint predictions, and the engine does not select one as ground truth.
|
| 88 |
|
| 89 |
## Colab comparison
|
| 90 |
|
| 91 |
Open [batting_measurements_test.ipynb](../notebooks/batting_measurements_test.ipynb). It has the familiar eight steps. In step 3 set `MEASUREMENT_BACKEND` to `rtmw3d`, `sam3d` or `2d`.
|
| 92 |
|
| 93 |
+
Run steps 1–8 for the first test. To update an existing runtime's engine, rerun step 1 at `REVISION="main"`, then steps 4–8; installed models/environments can be reused. To compare another model on the same recording, change step 3 and rerun steps 3–8. A fresh job and backend-labelled ZIP are created, retaining source commit, input hash, recording options, raw points, measurements, 3D diagnostics and previews. At sampled frames the preview adds purple 3D projections and red disagreement connectors; contact/plant comparison PNGs are also displayed/exported. These diagnostics never alter measurements. The existing 2D-only notebook remains available separately.
|
| 94 |
|
| 95 |
For SAM, set `EXISTING_SAM_RECORD` to an earlier installed `full-worker.json` to reuse that environment/assets. Otherwise setup installs only the isolated SAM inference environment and reads `HF_TOKEN` from a Colab secret or hidden input. Provider approval is still required. Setup never runs anatomy checks or temporal reconstruction.
|
| 96 |
|
docs/api-result.schema.json
CHANGED
|
@@ -633,8 +633,9 @@
|
|
| 633 |
"batting-2d-v1",
|
| 634 |
"batting-2d-v2",
|
| 635 |
"batting-2d-v3",
|
| 636 |
-
|
| 637 |
-
|
|
|
|
| 638 |
]
|
| 639 |
},
|
| 640 |
"body_height_px": {
|
|
@@ -671,7 +672,10 @@
|
|
| 671 |
]
|
| 672 |
},
|
| 673 |
"quality_version": {
|
| 674 |
-
"
|
|
|
|
|
|
|
|
|
|
| 675 |
}
|
| 676 |
}
|
| 677 |
},
|
|
@@ -950,6 +954,9 @@
|
|
| 950 |
},
|
| 951 |
"note": {
|
| 952 |
"type": "string"
|
|
|
|
|
|
|
|
|
|
| 953 |
}
|
| 954 |
}
|
| 955 |
},
|
|
|
|
| 633 |
"batting-2d-v1",
|
| 634 |
"batting-2d-v2",
|
| 635 |
"batting-2d-v3",
|
| 636 |
+
"batting-2d-v4",
|
| 637 |
+
"batting-2d-v5",
|
| 638 |
+
"batting-2d-v6"
|
| 639 |
]
|
| 640 |
},
|
| 641 |
"body_height_px": {
|
|
|
|
| 672 |
]
|
| 673 |
},
|
| 674 |
"quality_version": {
|
| 675 |
+
"enum": [
|
| 676 |
+
"measurement-quality-v1",
|
| 677 |
+
"measurement-quality-v2"
|
| 678 |
+
]
|
| 679 |
}
|
| 680 |
}
|
| 681 |
},
|
|
|
|
| 954 |
},
|
| 955 |
"note": {
|
| 956 |
"type": "string"
|
| 957 |
+
},
|
| 958 |
+
"evidence": {
|
| 959 |
+
"type": "object"
|
| 960 |
}
|
| 961 |
}
|
| 962 |
},
|
notebooks/batting_2d_test.ipynb
CHANGED
|
@@ -464,6 +464,9 @@
|
|
| 464 |
" if preview[\"status\"] == \"complete\":\n",
|
| 465 |
" path = JOB_ROOT / \"previews\" / preview[\"file\"]\n",
|
| 466 |
" archive.write(path, path.relative_to(JOB_ROOT))\n",
|
|
|
|
|
|
|
|
|
|
| 467 |
"print(\"Saved:\", ARCHIVE_PATH)\n",
|
| 468 |
"files.download(str(ARCHIVE_PATH))\n"
|
| 469 |
],
|
|
|
|
| 464 |
" if preview[\"status\"] == \"complete\":\n",
|
| 465 |
" path = JOB_ROOT / \"previews\" / preview[\"file\"]\n",
|
| 466 |
" archive.write(path, path.relative_to(JOB_ROOT))\n",
|
| 467 |
+
" for comparison in manifest.get(\"model_comparisons\", []):\n",
|
| 468 |
+
" path = JOB_ROOT / \"previews\" / comparison[\"file\"]\n",
|
| 469 |
+
" archive.write(path, path.relative_to(JOB_ROOT))\n",
|
| 470 |
"print(\"Saved:\", ARCHIVE_PATH)\n",
|
| 471 |
"files.download(str(ARCHIVE_PATH))\n"
|
| 472 |
],
|
notebooks/batting_measurements_test.ipynb
CHANGED
|
@@ -433,7 +433,7 @@
|
|
| 433 |
"for rep in result.get(\"measurement_diagnostics\", [])[:10]:\n",
|
| 434 |
" print(\"Stability evidence for swing\", rep[\"rep\"])\n",
|
| 435 |
" for item in rep[\"metrics\"]:\n",
|
| 436 |
-
" if \"nearby_frame_sensitivity\" in item or \"event_frame_sensitivity_range\" in item:\n",
|
| 437 |
" print(json.dumps(item, indent=2))\n"
|
| 438 |
],
|
| 439 |
"execution_count": null,
|
|
@@ -448,7 +448,9 @@
|
|
| 448 |
"\n",
|
| 449 |
"These inspection clips show body points in green, toe/heel points in orange, and estimated event labels. They preserve playback presentation positions relative to each clip's first frame. They are resized to at most 960 pixels wide, have no audio, and are separate from the API's measurement output. Preview rendering does not alter measurement results. Invalid source timestamps cause a preview to be withheld rather than retimed.\n",
|
| 450 |
"\n",
|
| 451 |
-
"The default limit is ten clips; increase it up to 100 if needed. Inspect each range for missed preparation, truncated finish, merged swings or unrelated movements.\n"
|
|
|
|
|
|
|
| 452 |
],
|
| 453 |
"id": "batting-measurements-013"
|
| 454 |
},
|
|
@@ -467,7 +469,12 @@
|
|
| 467 |
" if preview[\"status\"] == \"complete\":\n",
|
| 468 |
" display(Video(str(PREVIEW_ROOT / preview[\"file\"]), embed=True, width=720))\n",
|
| 469 |
" else:\n",
|
| 470 |
-
" print(\"Preview unavailable:\", preview[\"reason\"])\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 471 |
],
|
| 472 |
"execution_count": null,
|
| 473 |
"outputs": [],
|
|
@@ -504,6 +511,9 @@
|
|
| 504 |
" if preview[\"status\"] == \"complete\":\n",
|
| 505 |
" path = JOB_ROOT / \"previews\" / preview[\"file\"]\n",
|
| 506 |
" archive.write(path, path.relative_to(JOB_ROOT))\n",
|
|
|
|
|
|
|
|
|
|
| 507 |
"print(\"Saved:\", ARCHIVE_PATH)\n",
|
| 508 |
"files.download(str(ARCHIVE_PATH))\n"
|
| 509 |
],
|
|
|
|
| 433 |
"for rep in result.get(\"measurement_diagnostics\", [])[:10]:\n",
|
| 434 |
" print(\"Stability evidence for swing\", rep[\"rep\"])\n",
|
| 435 |
" for item in rep[\"metrics\"]:\n",
|
| 436 |
+
" if item.get(\"status\") == \"withheld\" or \"nearby_frame_sensitivity\" in item or \"event_frame_sensitivity_range\" in item:\n",
|
| 437 |
" print(json.dumps(item, indent=2))\n"
|
| 438 |
],
|
| 439 |
"execution_count": null,
|
|
|
|
| 448 |
"\n",
|
| 449 |
"These inspection clips show body points in green, toe/heel points in orange, and estimated event labels. They preserve playback presentation positions relative to each clip's first frame. They are resized to at most 960 pixels wide, have no audio, and are separate from the API's measurement output. Preview rendering does not alter measurement results. Invalid source timestamps cause a preview to be withheld rather than retimed.\n",
|
| 450 |
"\n",
|
| 451 |
+
"The default limit is ten clips; increase it up to 100 if needed. Inspect each range for missed preparation, truncated finish, merged swings or unrelated movements.\n",
|
| 452 |
+
"\n",
|
| 453 |
+
"At sampled 3D frames, purple rings show the model's image projection. Red lines mark disagreement greater than 5% of image stature. Contact and plant comparison PNGs are shown below and included in the ZIP. They help locate disagreement; they do not identify which model is correct.\n"
|
| 454 |
],
|
| 455 |
"id": "batting-measurements-013"
|
| 456 |
},
|
|
|
|
| 469 |
" if preview[\"status\"] == \"complete\":\n",
|
| 470 |
" display(Video(str(PREVIEW_ROOT / preview[\"file\"]), embed=True, width=720))\n",
|
| 471 |
" else:\n",
|
| 472 |
+
" print(\"Preview unavailable:\", preview[\"reason\"])\n",
|
| 473 |
+
"\n",
|
| 474 |
+
"from IPython.display import Image\n",
|
| 475 |
+
"for comparison in previews.get(\"model_comparisons\", [])[:6]:\n",
|
| 476 |
+
" print(\"Model comparison: swing\", comparison[\"rep\"], \"frame\", comparison[\"frame\"], comparison[\"events\"])\n",
|
| 477 |
+
" display(Image(filename=str(PREVIEW_ROOT / comparison[\"file\"])))\n"
|
| 478 |
],
|
| 479 |
"execution_count": null,
|
| 480 |
"outputs": [],
|
|
|
|
| 511 |
" if preview[\"status\"] == \"complete\":\n",
|
| 512 |
" path = JOB_ROOT / \"previews\" / preview[\"file\"]\n",
|
| 513 |
" archive.write(path, path.relative_to(JOB_ROOT))\n",
|
| 514 |
+
" for comparison in manifest.get(\"model_comparisons\", []):\n",
|
| 515 |
+
" path = JOB_ROOT / \"previews\" / comparison[\"file\"]\n",
|
| 516 |
+
" archive.write(path, path.relative_to(JOB_ROOT))\n",
|
| 517 |
"print(\"Saved:\", ARCHIVE_PATH)\n",
|
| 518 |
"files.download(str(ARCHIVE_PATH))\n"
|
| 519 |
],
|
tests/test_colab_2d.py
CHANGED
|
@@ -80,6 +80,26 @@ def test_preview_rotation_limit_and_raw_point_overlay(video, tmp_path):
|
|
| 80 |
assert foot[2] > int(foot[1])+20 and foot[1] > 120 # Orange toe point.
|
| 81 |
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
@pytest.mark.parametrize("bad_clock", [None, 0.0])
|
| 84 |
def test_bad_playback_timing_is_withheld_without_fabricating_preview(video, tmp_path, bad_clock):
|
| 85 |
result = preview_result(video)
|
|
@@ -109,9 +129,12 @@ def test_notebook_download_contains_results_and_current_previews_only(tmp_path):
|
|
| 109 |
"input.mp4", ".env", "worker.log"):
|
| 110 |
(job / name).write_text("fixture")
|
| 111 |
(previews / "swing-001.mp4").write_text("current preview")
|
|
|
|
|
|
|
| 112 |
(previews / "swing-002.mp4").write_text("stale previous preview")
|
| 113 |
(previews / "previews.json").write_text(json.dumps({"previews": [
|
| 114 |
-
{"status": "complete", "file": "swing-001.mp4"}, {"status": "unavailable", "rep": 2}]
|
|
|
|
| 115 |
downloads = []
|
| 116 |
scope = {"WORKSPACE_ROOT": tmp_path, "JOB_ROOT": job, "json": json,
|
| 117 |
"files": SimpleNamespace(download=downloads.append)}
|
|
@@ -121,4 +144,6 @@ def test_notebook_download_contains_results_and_current_previews_only(tmp_path):
|
|
| 121 |
with zipfile.ZipFile(downloads[0]) as archive:
|
| 122 |
names = set(archive.namelist())
|
| 123 |
assert {"result.json", "coach-payload.json", "previews/previews.json", "previews/swing-001.mp4"} <= names
|
|
|
|
|
|
|
| 124 |
assert not {"input.mp4", ".env", "previews/swing-002.mp4"} & names
|
|
|
|
| 80 |
assert foot[2] > int(foot[1])+20 and foot[1] > 120 # Orange toe point.
|
| 81 |
|
| 82 |
|
| 83 |
+
def test_preview_exports_model_comparison_without_changing_measurements(video, tmp_path):
|
| 84 |
+
result = preview_result(video)
|
| 85 |
+
result['pose_track']['frames']['kp'][2][0] = [50,70]
|
| 86 |
+
result['pose_track']['reps'][0]['events'] = {'contact':{'frame':2}}
|
| 87 |
+
projection = [None]*17; projection[0] = [70,70]
|
| 88 |
+
result['experimental_body3d'] = {'frames':[{'frame':2,'projection':projection}]}
|
| 89 |
+
result['measurement_method'] = {'body_height_px':100}
|
| 90 |
+
original = deepcopy(result)
|
| 91 |
+
manifest = export_previews(video,result,tmp_path/'clips',max_clips=1)
|
| 92 |
+
assert result == original
|
| 93 |
+
assert manifest['previews'][0]['status']=='complete'
|
| 94 |
+
comparison = manifest['model_comparisons'][0]
|
| 95 |
+
assert comparison['frame']==2 and comparison['events']==['contact']
|
| 96 |
+
import cv2
|
| 97 |
+
image = cv2.imread(str(tmp_path/'clips'/comparison['file']))
|
| 98 |
+
assert image[70,60,2] > 200 # Red discrepancy connector between the models.
|
| 99 |
+
assert image[70,50,1] > 150 # Raw model point is preserved.
|
| 100 |
+
assert image[70,75,0] > 200 # Purple projected 3D ring.
|
| 101 |
+
|
| 102 |
+
|
| 103 |
@pytest.mark.parametrize("bad_clock", [None, 0.0])
|
| 104 |
def test_bad_playback_timing_is_withheld_without_fabricating_preview(video, tmp_path, bad_clock):
|
| 105 |
result = preview_result(video)
|
|
|
|
| 129 |
"input.mp4", ".env", "worker.log"):
|
| 130 |
(job / name).write_text("fixture")
|
| 131 |
(previews / "swing-001.mp4").write_text("current preview")
|
| 132 |
+
(previews / "swing-001-comparison.png").write_text("current comparison")
|
| 133 |
+
(previews / "stale-comparison.png").write_text("stale comparison")
|
| 134 |
(previews / "swing-002.mp4").write_text("stale previous preview")
|
| 135 |
(previews / "previews.json").write_text(json.dumps({"previews": [
|
| 136 |
+
{"status": "complete", "file": "swing-001.mp4"}, {"status": "unavailable", "rep": 2}],
|
| 137 |
+
"model_comparisons": [{"file": "swing-001-comparison.png"}]}))
|
| 138 |
downloads = []
|
| 139 |
scope = {"WORKSPACE_ROOT": tmp_path, "JOB_ROOT": job, "json": json,
|
| 140 |
"files": SimpleNamespace(download=downloads.append)}
|
|
|
|
| 144 |
with zipfile.ZipFile(downloads[0]) as archive:
|
| 145 |
names = set(archive.namelist())
|
| 146 |
assert {"result.json", "coach-payload.json", "previews/previews.json", "previews/swing-001.mp4"} <= names
|
| 147 |
+
assert "previews/swing-001-comparison.png" in names
|
| 148 |
+
assert "previews/stale-comparison.png" not in names
|
| 149 |
assert not {"input.mp4", ".env", "previews/swing-002.mp4"} & names
|
tests/test_measurement_backends.py
CHANGED
|
@@ -85,6 +85,11 @@ def test_sam_mapping_units_and_translation_are_not_applied_twice():
|
|
| 85 |
np.testing.assert_allclose(row["points"][10], points[41]+[1, 2, 3])
|
| 86 |
np.testing.assert_allclose(row["points"][11], points[9]+[1, 2, 3])
|
| 87 |
assert row["scores"] == [None]*17 # no invented 3D confidence
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
|
| 90 |
def test_lightweight_backprojection_uses_same_units_on_all_axes():
|
|
@@ -157,6 +162,73 @@ def test_bad_3d_never_falls_back_to_a_projected_anatomical_angle(failure):
|
|
| 157 |
assert metrics["stride_pct_height"]["value"] is not None
|
| 158 |
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
def test_unknown_timing_and_moving_camera_remain_withheld_with_3d():
|
| 161 |
track = swing_track(); track["frames"]["t_s"] = [None]*180; track["video"]["capture_fps"] = None
|
| 162 |
opt = options(single_swing=True, measurement_backend="sam3d"); opt.camera_stability = "moving"
|
|
@@ -207,6 +279,53 @@ def test_30fps_frame_sensitivity_keeps_long_load_and_withholds_short_timings():
|
|
| 207 |
assert diagnostic["load_tempo_s"]["capture_interval_ms"] == [33.333, 33.333]
|
| 208 |
assert diagnostic["load_tempo_s"]["event_frame_sensitivity_range"] == pytest.approx([14/30, 18/30])
|
| 209 |
assert diagnostic["load_tempo_s"]["event_frame_sensitivity_unit"] == "s"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
|
| 212 |
def test_frame_budget_keeps_complete_event_windows():
|
|
|
|
| 85 |
np.testing.assert_allclose(row["points"][10], points[41]+[1, 2, 3])
|
| 86 |
np.testing.assert_allclose(row["points"][11], points[9]+[1, 2, 3])
|
| 87 |
assert row["scores"] == [None]*17 # no invented 3D confidence
|
| 88 |
+
# Native SAM MHR70 names: wrists are 62/41, hips 9/10, knees 11/12,
|
| 89 |
+
# ankles 13/14. Check every mapped landmark, not just the first hip.
|
| 90 |
+
from baseball_batting.event_body3d import SAM_COCO
|
| 91 |
+
np.testing.assert_allclose(row['points'], points[SAM_COCO]+[1, 2, 3])
|
| 92 |
+
np.testing.assert_allclose(row['projection'], pixels[SAM_COCO])
|
| 93 |
|
| 94 |
|
| 95 |
def test_lightweight_backprojection_uses_same_units_on_all_axes():
|
|
|
|
| 162 |
assert metrics["stride_pct_height"]["value"] is not None
|
| 163 |
|
| 164 |
|
| 165 |
+
def test_rejected_opposite_hip_does_not_poison_supported_knee_geometry():
|
| 166 |
+
result, opt, report = measurement_result()
|
| 167 |
+
contact = result['pose_track']['reps'][0]['events']['contact']['frame']
|
| 168 |
+
for row in report['frames']:
|
| 169 |
+
if abs(row['frame']-contact) <= 2: row['projection'][12][0] += 100
|
| 170 |
+
apply_measurement_quality(result, opt, report)
|
| 171 |
+
metrics = metric_map(result['coach_payload']['reps'][0])
|
| 172 |
+
assert metrics['lead_knee_angle_contact_deg']['value'] is not None
|
| 173 |
+
assert metrics['lateral_trunk_tilt_contact_deg']['value'] is None
|
| 174 |
+
assert 'right_hip' in metrics['lateral_trunk_tilt_contact_deg']['note']
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_projection_disagreement_is_explained_per_joint_without_changing_points():
|
| 178 |
+
result, opt, report = measurement_result()
|
| 179 |
+
contact = result['pose_track']['reps'][0]['events']['contact']['frame']
|
| 180 |
+
for row in report['frames']:
|
| 181 |
+
if row['frame'] == contact: row['projection'][11][0] += 24 # 6% of known 400 px stature
|
| 182 |
+
original = deepcopy(report)
|
| 183 |
+
apply_measurement_quality(result, opt, report)
|
| 184 |
+
metric = metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg']
|
| 185 |
+
assert metric['value'] is None and 'left_hip differs by 6.00%' in metric['note']
|
| 186 |
+
diagnostic = next(m for m in result['measurement_diagnostics'][0]['metrics'] if m['key']==metric['key'])
|
| 187 |
+
assert diagnostic['required_joints'] == ['left_hip', 'left_knee', 'left_ankle']
|
| 188 |
+
assert next(r for r in diagnostic['pose_agreement'] if r['frame']==contact)['rejected_joints'][0]['reasons'] == ['model_projection_disagreement']
|
| 189 |
+
assert report == original
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def test_projection_convention_is_checked_again_before_measurement():
|
| 193 |
+
result, opt, report = measurement_result()
|
| 194 |
+
for row in report['frames']:
|
| 195 |
+
row['camera_intrinsics'] = [[1000, 0, 330], [0, 1000, 350], [0, 0, 1]]
|
| 196 |
+
row['points'] = np.column_stack(((np.asarray(row['projection'])-[330,350])*.005, np.full(17, 5.))).tolist()
|
| 197 |
+
apply_measurement_quality(result, opt, deepcopy(report))
|
| 198 |
+
assert metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg']['value'] is not None
|
| 199 |
+
for row in report['frames']: row['points'][13][0] += .02
|
| 200 |
+
apply_measurement_quality(result, opt, report)
|
| 201 |
+
metric = metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg']
|
| 202 |
+
assert metric['value'] is None and 'camera_projection_inconsistent' in metric['note']
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@pytest.mark.parametrize('failure', ['bad_dimensions', 'duplicate', 'bad_scores'])
|
| 206 |
+
def test_invalid_optional_3d_rows_withhold_angles_without_losing_2d_results(failure):
|
| 207 |
+
result, opt, report = measurement_result()
|
| 208 |
+
contact = result['pose_track']['reps'][0]['events']['contact']['frame']
|
| 209 |
+
row = next(r for r in report['frames'] if r['frame']==contact)
|
| 210 |
+
if failure == 'bad_dimensions': row['points'] = [[0,0,5]]
|
| 211 |
+
elif failure == 'duplicate': report['frames'].append(deepcopy(row))
|
| 212 |
+
else: row['scores'] = [.9]
|
| 213 |
+
apply_measurement_quality(result, opt, report)
|
| 214 |
+
metrics = metric_map(result['coach_payload']['reps'][0])
|
| 215 |
+
assert metrics['lead_knee_angle_contact_deg']['value'] is None
|
| 216 |
+
assert metrics['stride_pct_height']['value'] is not None
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def test_possible_left_right_swap_is_reported_without_remapping():
|
| 220 |
+
result, opt, report = measurement_result()
|
| 221 |
+
for row in report['frames']:
|
| 222 |
+
for a,b in ((5,6),(7,8),(9,10),(11,12),(13,14),(15,16)):
|
| 223 |
+
row['projection'][a],row['projection'][b] = row['projection'][b],row['projection'][a]
|
| 224 |
+
original = deepcopy(report)
|
| 225 |
+
apply_measurement_quality(result,opt,report)
|
| 226 |
+
metric = next(m for m in result['measurement_diagnostics'][0]['metrics'] if m['key']=='lead_knee_angle_contact_deg')
|
| 227 |
+
assert any(r['side_swap_check']['possible_side_swap'] for r in metric['pose_agreement'])
|
| 228 |
+
assert metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg']['value'] is None
|
| 229 |
+
assert report == original
|
| 230 |
+
|
| 231 |
+
|
| 232 |
def test_unknown_timing_and_moving_camera_remain_withheld_with_3d():
|
| 233 |
track = swing_track(); track["frames"]["t_s"] = [None]*180; track["video"]["capture_fps"] = None
|
| 234 |
opt = options(single_swing=True, measurement_backend="sam3d"); opt.camera_stability = "moving"
|
|
|
|
| 279 |
assert diagnostic["load_tempo_s"]["capture_interval_ms"] == [33.333, 33.333]
|
| 280 |
assert diagnostic["load_tempo_s"]["event_frame_sensitivity_range"] == pytest.approx([14/30, 18/30])
|
| 281 |
assert diagnostic["load_tempo_s"]["event_frame_sensitivity_unit"] == "s"
|
| 282 |
+
assert diagnostic['load_tempo_s']['resolution_status'] == 'resolved_under_frame_shift_check'
|
| 283 |
+
assert diagnostic['load_launch_ratio']['duration_frame_intervals']['swing_start_to_contact'] == 5
|
| 284 |
+
assert diagnostic['load_launch_ratio']['resolution_status'] == 'insufficient_event_resolution'
|
| 285 |
+
assert diagnostic['load_launch_ratio']['event_frame_sensitivity_range'] == pytest.approx([2,6])
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def test_more_real_samples_resolve_ratio_and_changing_fps_alone_does_not():
|
| 289 |
+
from baseball_batting.timing_quality import check_timing
|
| 290 |
+
from test_batting_measurements import swing_track
|
| 291 |
+
for frames, fps, supported in [((20,36,41),30,False), ((20,36,41),120,False),
|
| 292 |
+
((20,84,104),120,True)]:
|
| 293 |
+
rep = {'start_frame':0, 'end_frame':179, 'events':{
|
| 294 |
+
name:{'frame':i} for name,i in zip(('load_start','swing_start','contact'),frames)}}
|
| 295 |
+
metric = {'key':'load_launch_ratio', 'value':3.2, 'note':'constructed evidence'}
|
| 296 |
+
diagnostic = {}
|
| 297 |
+
check_timing(metric,rep,swing_track(fps=fps),diagnostic)
|
| 298 |
+
assert (metric['value'] is not None) == supported
|
| 299 |
+
assert diagnostic['duration_frame_intervals']['swing_start_to_contact'] == frames[2]-frames[1]
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
def test_timing_quality_cannot_fill_clock_or_missing_event():
|
| 303 |
+
from baseball_batting.timing_quality import check_timing
|
| 304 |
+
track = swing_track(fps=30)
|
| 305 |
+
rep = {'start_frame':0, 'end_frame':179, 'events':{'load_start':{'frame':20},'swing_start':{'frame':50}}}
|
| 306 |
+
metric = {'key':'load_tempo_s','value':1.,'note':'constructed evidence'}
|
| 307 |
+
track['frames']['t_s'][25] = None
|
| 308 |
+
diagnostic = {}; check_timing(metric,rep,track,diagnostic)
|
| 309 |
+
assert metric['value'] is None and diagnostic['resolution_status']=='capture_clock_unknown_or_invalid'
|
| 310 |
+
metric = {'key':'load_launch_ratio','value':None,'note':'missing contact'}
|
| 311 |
+
diagnostic = {}; check_timing(metric,rep,track,diagnostic)
|
| 312 |
+
assert metric['value'] is None and diagnostic['missing_events']==['contact']
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def test_ratio_sensitivity_matches_exhaustive_shared_onset_shifts():
|
| 316 |
+
from itertools import product
|
| 317 |
+
from baseball_batting.timing_quality import check_timing
|
| 318 |
+
track = swing_track(fps=60)
|
| 319 |
+
times = np.r_[0,np.cumsum(np.resize([1/60,1/80],179))]
|
| 320 |
+
track['frames']['t_s'] = times.tolist()
|
| 321 |
+
load,onset,contact = 20,80,105
|
| 322 |
+
rep = {'start_frame':0,'end_frame':179,'events':{name:{'frame':i} for name,i in
|
| 323 |
+
(('load_start',load),('swing_start',onset),('contact',contact))}}
|
| 324 |
+
metric={'key':'load_launch_ratio','value':float((times[onset]-times[load])/(times[contact]-times[onset])),'note':'constructed'}
|
| 325 |
+
diagnostic={};check_timing(metric,rep,track,diagnostic)
|
| 326 |
+
ratios=[(times[onset+b]-times[load+a])/(times[contact+c]-times[onset+b])
|
| 327 |
+
for a,b,c in product((-1,0,1),repeat=3)]
|
| 328 |
+
assert diagnostic['event_frame_sensitivity_range']==pytest.approx([min(ratios),max(ratios)])
|
| 329 |
|
| 330 |
|
| 331 |
def test_frame_budget_keeps_complete_event_windows():
|
tests/test_preparation_evidence.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Event evidence checks against constructed motion, not accuracy labels."""
|
| 2 |
+
from copy import deepcopy
|
| 3 |
+
import numpy as np
|
| 4 |
+
import pytest
|
| 5 |
+
from baseball_batting.batting_measurements import analyze_batting, analysis_body_points, analysis_points, point_array
|
| 6 |
+
from baseball_batting.swing_preparation import lead_foot_events, preparation_stance
|
| 7 |
+
from test_batting_measurements import swing_track, options
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def detect_feet(track, onset=60, contact=95, lead=0):
|
| 11 |
+
raw = point_array(track['frames']['kp'], 17)
|
| 12 |
+
raw_feet = point_array(track['frames']['kp_extra'], 6)
|
| 13 |
+
return lead_foot_events(analysis_body_points(raw), raw, analysis_points(raw_feet), raw_feet,
|
| 14 |
+
lead, 400, np.asarray(track['frames']['t_s']), 0, onset, contact, 179)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
@pytest.mark.parametrize('landing_delta', [0, 20, 50])
|
| 18 |
+
@pytest.mark.parametrize('fps', [30, 60, 120])
|
| 19 |
+
def test_step_can_land_at_different_image_depth(landing_delta, fps):
|
| 20 |
+
track = swing_track(fps=fps)
|
| 21 |
+
for i in range(180):
|
| 22 |
+
change = landing_delta*np.clip((i-35)/10, 0, 1)
|
| 23 |
+
track['frames']['kp'][i][15][1] += change
|
| 24 |
+
for p in track['frames']['kp_extra'][i][:3]: p[1] += change
|
| 25 |
+
found, _ = detect_feet(track)
|
| 26 |
+
assert {'stride', 'foot_contact', 'foot_plant'} <= found.keys()
|
| 27 |
+
assert 42 <= found['foot_plant'][0] <= 46
|
| 28 |
+
assert found['stride'][0] < found['foot_contact'][0] <= found['foot_plant'][0]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_confirmation_after_onset_timestamps_the_start_of_settling():
|
| 32 |
+
track = swing_track(fps=30)
|
| 33 |
+
found, _ = detect_feet(track, onset=45)
|
| 34 |
+
assert found['foot_plant'][0] <= 45
|
| 35 |
+
assert found['foot_plant'][3]['confirmation_end_frame'] > 45
|
| 36 |
+
assert not detect_feet(track, onset=45, contact=46)[0] # no borrowing after contact
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@pytest.mark.parametrize('failure', ['hover', 'no_step', 'no_sole', 'ankle_gap', 'sole_gap', 'moving'])
|
| 40 |
+
def test_unsupported_ground_events_are_not_fabricated(failure):
|
| 41 |
+
track = swing_track(fps=30)
|
| 42 |
+
if failure in {'hover', 'moving'}:
|
| 43 |
+
for i in range(36, 180):
|
| 44 |
+
delta = -50 if failure == 'hover' else 3*(i-35)
|
| 45 |
+
track['frames']['kp'][i][15][1] += delta
|
| 46 |
+
for p in track['frames']['kp_extra'][i][:3]: p[1] += delta
|
| 47 |
+
if failure == 'no_step':
|
| 48 |
+
for i in range(180):
|
| 49 |
+
track['frames']['kp'][i][15] = [370, 620]
|
| 50 |
+
track['frames']['kp_extra'][i][:3] = [[382, 640], [378, 638], [362, 635]]
|
| 51 |
+
if failure == 'no_sole': track['frames']['kp_extra'] = [[None]*6]*180
|
| 52 |
+
if failure in {'ankle_gap', 'sole_gap'}:
|
| 53 |
+
for i in range(40, 75):
|
| 54 |
+
if failure == 'ankle_gap': track['frames']['kp'][i][15] = None
|
| 55 |
+
else: track['frames']['kp_extra'][i][:3] = [None]*3
|
| 56 |
+
found, _ = detect_feet(track)
|
| 57 |
+
assert 'foot_plant' not in found
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def test_mirror_and_anatomical_side_preserve_ground_event_times():
|
| 61 |
+
expected = detect_feet(swing_track())[0]
|
| 62 |
+
actual = detect_feet(swing_track(mirror=True))[0]
|
| 63 |
+
assert {k: v[0] for k, v in actual.items()} == {k: v[0] for k, v in expected.items()}
|
| 64 |
+
track = swing_track()
|
| 65 |
+
for p in track['frames']['kp']: p[15], p[16] = p[16], p[15]
|
| 66 |
+
for p in track['frames']['kp_extra']: p[:3], p[3:] = p[3:], p[:3]
|
| 67 |
+
actual = detect_feet(track, lead=1)[0]
|
| 68 |
+
assert {k: v[0] for k, v in actual.items()} == {k: v[0] for k, v in expected.items()}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def test_held_leg_kick_does_not_replace_the_ground_reference():
|
| 72 |
+
track = swing_track(fps=30)
|
| 73 |
+
for i in range(180):
|
| 74 |
+
p = np.interp(i, [0,25,32,44,54,179], [0,0,.5,.5,1,1])
|
| 75 |
+
foot = np.array([370+60*p, 620-40*np.sin(np.pi*p)])
|
| 76 |
+
track['frames']['kp'][i][15] = foot.tolist()
|
| 77 |
+
track['frames']['kp_extra'][i][:3] = [(foot+d).tolist() for d in ([12,20],[8,18],[-8,15])]
|
| 78 |
+
found, _ = detect_feet(track)
|
| 79 |
+
assert found['stride'][0] < 32 and found['foot_plant'][0] >= 51
|
| 80 |
+
assert found['foot_plant'][3]['baseline_frames'][1] < 32
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def test_two_preparation_steps_select_the_last_step():
|
| 84 |
+
track = swing_track(fps=30)
|
| 85 |
+
for i in range(180):
|
| 86 |
+
first = np.clip((i-20)/15, 0, 1)
|
| 87 |
+
final = np.clip((i-50)/15, 0, 1)
|
| 88 |
+
foot = np.array([370+50*first+70*final, 620-35*np.sin(np.pi*first)-40*np.sin(np.pi*final)])
|
| 89 |
+
track['frames']['kp'][i][15] = foot.tolist()
|
| 90 |
+
track['frames']['kp_extra'][i][:3] = [(foot+d).tolist() for d in ([12,20],[8,18],[-8,15])]
|
| 91 |
+
found, _ = detect_feet(track, onset=75)
|
| 92 |
+
assert 50 < found['stride'][0] < 58 and found['foot_plant'][0] >= 62
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def test_foot_departure_can_precede_hand_loading():
|
| 96 |
+
track = swing_track()
|
| 97 |
+
for i, p in enumerate(track['frames']['kp']):
|
| 98 |
+
hx = np.interp(i, [0, 35, 55, 60, 95, 110, 130, 179], [330, 330, 280, 280, 500, 510, 430, 430])
|
| 99 |
+
p[9][0] = hx; p[10][0] = hx+5
|
| 100 |
+
pose = analyze_batting(track, options(single_swing=True))[0][0]
|
| 101 |
+
assert pose['events']['stride']['frame'] < pose['events']['load_start']['frame']
|
| 102 |
+
assert 'foot_plant' in pose['events']
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def test_replay_walkthrough_returns_final_step_instead_of_averaging_its_walk():
|
| 106 |
+
import json
|
| 107 |
+
from pathlib import Path
|
| 108 |
+
from baseball_batting.api_contract import AnalysisInput
|
| 109 |
+
track = json.loads((Path(__file__).parent/'fixtures/walkthrough_pose.json').read_text())['track']
|
| 110 |
+
original = deepcopy(track)
|
| 111 |
+
opt = AnalysisInput(view='face_on', handedness='left', pitcher_direction='image_left',
|
| 112 |
+
camera_stability='fixed_verified', single_swing=True)
|
| 113 |
+
pose = analyze_batting(track, opt)[0][0]
|
| 114 |
+
assert 49 <= pose['events']['stride']['frame'] <= 54
|
| 115 |
+
assert 65 <= pose['events']['foot_plant']['frame'] <= 70
|
| 116 |
+
assert pose['events']['foot_plant']['evidence']['baseline_frames'][0] >= 40
|
| 117 |
+
assert track == original
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def stance(track, preparation_end=21, fixed=True):
|
| 121 |
+
raw = point_array(track['frames']['kp'], 17)
|
| 122 |
+
return preparation_stance(analysis_body_points(raw), raw, 400,
|
| 123 |
+
np.asarray(track['frames']['t_s']), 0, preparation_end, fixed)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_quiet_hands_do_not_make_a_walking_body_a_stance():
|
| 127 |
+
track = swing_track(fps=30)
|
| 128 |
+
for i, p in enumerate(track['frames']['kp']):
|
| 129 |
+
shift = np.array([i*3., 0])
|
| 130 |
+
track['frames']['kp'][i] = (np.asarray(p)+shift).tolist()
|
| 131 |
+
assert stance(track) is None
|
| 132 |
+
# Moving cameras still permit body-relative stance evidence, but never an
|
| 133 |
+
# absolute head-path measurement (covered by the API regression).
|
| 134 |
+
assert stance(track, fixed=False) is not None
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def test_setup_walking_stops_before_stance_and_is_excluded_from_head_path():
|
| 138 |
+
track = swing_track(fps=30)
|
| 139 |
+
for i, p in enumerate(track['frames']['kp']):
|
| 140 |
+
if i >= 12: break
|
| 141 |
+
track['frames']['kp'][i] = (np.asarray(p)+[3*(i-12), 0]).tolist()
|
| 142 |
+
result = stance(track)
|
| 143 |
+
assert result is not None and result[0] >= 12
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def test_old_quiet_patch_before_walk_through_is_not_reused():
|
| 147 |
+
track = swing_track(fps=30)
|
| 148 |
+
for i, p in enumerate(track['frames']['kp']):
|
| 149 |
+
if i >= 7: track['frames']['kp'][i] = (np.asarray(p)+[3*(i-7), 0]).tolist()
|
| 150 |
+
assert stance(track) is None
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def test_stance_uses_last_supported_window_and_keeps_swing_preparation():
|
| 154 |
+
track = swing_track(fps=120)
|
| 155 |
+
result = stance(track)
|
| 156 |
+
assert result is not None
|
| 157 |
+
a, evidence = result
|
| 158 |
+
assert a <= 20 <= evidence['support_frames'][1]
|
| 159 |
+
# It does not shorten the path by choosing a quiet pause inside the load.
|
| 160 |
+
pose = analyze_batting(track, options(single_swing=True))[0][0]
|
| 161 |
+
assert pose['events']['stance_set']['frame'] < pose['events']['load_start']['frame']
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def test_stance_requires_raw_pelvis_and_ankle_support():
|
| 165 |
+
track = swing_track(fps=30)
|
| 166 |
+
for i in range(21): track['frames']['kp'][i][11] = None
|
| 167 |
+
assert stance(track) is None
|
tools/build_2d_notebook.py
CHANGED
|
@@ -243,6 +243,9 @@ with zipfile.ZipFile(ARCHIVE_PATH, "w", zipfile.ZIP_DEFLATED) as archive:
|
|
| 243 |
if preview["status"] == "complete":
|
| 244 |
path = JOB_ROOT / "previews" / preview["file"]
|
| 245 |
archive.write(path, path.relative_to(JOB_ROOT))
|
|
|
|
|
|
|
|
|
|
| 246 |
print("Saved:", ARCHIVE_PATH)
|
| 247 |
files.download(str(ARCHIVE_PATH))
|
| 248 |
''')]
|
|
|
|
| 243 |
if preview["status"] == "complete":
|
| 244 |
path = JOB_ROOT / "previews" / preview["file"]
|
| 245 |
archive.write(path, path.relative_to(JOB_ROOT))
|
| 246 |
+
for comparison in manifest.get("model_comparisons", []):
|
| 247 |
+
path = JOB_ROOT / "previews" / comparison["file"]
|
| 248 |
+
archive.write(path, path.relative_to(JOB_ROOT))
|
| 249 |
print("Saved:", ARCHIVE_PATH)
|
| 250 |
files.download(str(ARCHIVE_PATH))
|
| 251 |
''')]
|
tools/build_measurement_notebook.py
CHANGED
|
@@ -24,6 +24,8 @@ def build():
|
|
| 24 |
"Progress shows decoding, 2D pose extraction, optional 3D event windows and completion. SAM setup/model initialization still costs time, but this run does not reconstruct every video frame.")
|
| 25 |
if "## 4." in source:
|
| 26 |
source += "\nCamera intrinsics, player height and pelvis distance are optional. They refer to the upright video. Leave them empty when unknown: the lightweight model reports its camera/depth assumptions and tests sensitivity. Unknown timing still withholds timing values; 3D cannot recover it. A moving camera still withholds ground-foot and head-path measurements.\n"
|
|
|
|
|
|
|
| 27 |
elif 'MODEL_ROOT = ' in source:
|
| 28 |
source = '''MEASUREMENT_BACKEND = "rtmw3d" # "rtmw3d", "sam3d", or "2d"
|
| 29 |
EXISTING_SAM_RECORD = "" # e.g. "/content/baseball_batting_engine/full-worker.json"
|
|
@@ -69,8 +71,15 @@ print("Camera assumptions:", json.dumps(body3d.get("geometry", {}), indent=2))
|
|
| 69 |
for rep in result.get("measurement_diagnostics", [])[:10]:
|
| 70 |
print("Stability evidence for swing", rep["rep"])
|
| 71 |
for item in rep["metrics"]:
|
| 72 |
-
if "nearby_frame_sensitivity" in item or "event_frame_sensitivity_range" in item:
|
| 73 |
print(json.dumps(item, indent=2))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
'''
|
| 75 |
elif 'ARCHIVE_PATH = ' in source:
|
| 76 |
source = source.replace('JOB_ROOT.name + "-2d-results.zip"',
|
|
|
|
| 24 |
"Progress shows decoding, 2D pose extraction, optional 3D event windows and completion. SAM setup/model initialization still costs time, but this run does not reconstruct every video frame.")
|
| 25 |
if "## 4." in source:
|
| 26 |
source += "\nCamera intrinsics, player height and pelvis distance are optional. They refer to the upright video. Leave them empty when unknown: the lightweight model reports its camera/depth assumptions and tests sensitivity. Unknown timing still withholds timing values; 3D cannot recover it. A moving camera still withholds ground-foot and head-path measurements.\n"
|
| 27 |
+
if "## 7." in source:
|
| 28 |
+
source += "\nAt sampled 3D frames, purple rings show the model's image projection. Red lines mark disagreement greater than 5% of image stature. Contact and plant comparison PNGs are shown below and included in the ZIP. They help locate disagreement; they do not identify which model is correct.\n"
|
| 29 |
elif 'MODEL_ROOT = ' in source:
|
| 30 |
source = '''MEASUREMENT_BACKEND = "rtmw3d" # "rtmw3d", "sam3d", or "2d"
|
| 31 |
EXISTING_SAM_RECORD = "" # e.g. "/content/baseball_batting_engine/full-worker.json"
|
|
|
|
| 71 |
for rep in result.get("measurement_diagnostics", [])[:10]:
|
| 72 |
print("Stability evidence for swing", rep["rep"])
|
| 73 |
for item in rep["metrics"]:
|
| 74 |
+
if item.get("status") == "withheld" or "nearby_frame_sensitivity" in item or "event_frame_sensitivity_range" in item:
|
| 75 |
print(json.dumps(item, indent=2))
|
| 76 |
+
'''
|
| 77 |
+
elif 'PREVIEW_LIMIT = ' in source:
|
| 78 |
+
source += '''
|
| 79 |
+
from IPython.display import Image
|
| 80 |
+
for comparison in previews.get("model_comparisons", [])[:6]:
|
| 81 |
+
print("Model comparison: swing", comparison["rep"], "frame", comparison["frame"], comparison["events"])
|
| 82 |
+
display(Image(filename=str(PREVIEW_ROOT / comparison["file"])))
|
| 83 |
'''
|
| 84 |
elif 'ARCHIVE_PATH = ' in source:
|
| 85 |
source = source.replace('JOB_ROOT.name + "-2d-results.zip"',
|
tools/preview_swing_ranges.py
CHANGED
|
@@ -10,9 +10,11 @@ from baseball_batting.reports import BODY_EDGES
|
|
| 10 |
from baseball_batting.storage import atomic_json, read_json, sha256_file
|
| 11 |
|
| 12 |
|
| 13 |
-
def draw_points(image, points, rep, index, events, extra_points=None):
|
| 14 |
import cv2
|
| 15 |
image = image.copy()
|
|
|
|
|
|
|
| 16 |
for a, b in BODY_EDGES:
|
| 17 |
if points[a] is not None and points[b] is not None:
|
| 18 |
cv2.line(image, tuple(np.rint(points[a]).astype(int)),
|
|
@@ -28,11 +30,31 @@ def draw_points(image, points, rep, index, events, extra_points=None):
|
|
| 28 |
if ankle is not None:
|
| 29 |
cv2.line(image, tuple(np.rint(ankle).astype(int)), pixel, (0, 180, 255), 2)
|
| 30 |
cv2.circle(image, pixel, 4, (0, 180, 255), -1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
labels = [name for name, event in events.items() if event["frame"] == index]
|
| 32 |
text = f"Swing candidate {rep} | frame {index}"
|
| 33 |
if labels: text += " | estimated " + ", ".join(labels)
|
| 34 |
-
cv2.putText(image, text, (8, 24), cv2.FONT_HERSHEY_SIMPLEX, .55,
|
| 35 |
-
(255, 255, 255), 2, cv2.LINE_AA)
|
| 36 |
return image
|
| 37 |
|
| 38 |
|
|
@@ -45,6 +67,9 @@ def export_previews(video, result, destination, max_clips=10, overlay=True):
|
|
| 45 |
destination.mkdir(parents=True, exist_ok=True)
|
| 46 |
track = result["pose_track"]
|
| 47 |
frames, info = track["frames"], track["video"]
|
|
|
|
|
|
|
|
|
|
| 48 |
selected, records = [], []
|
| 49 |
prior_end = -1
|
| 50 |
for rep in track["reps"][:max_clips]:
|
|
@@ -84,7 +109,19 @@ def export_previews(video, result, destination, max_clips=10, overlay=True):
|
|
| 84 |
raise ValueError("Source playback timestamps differ from the analysis")
|
| 85 |
if overlay:
|
| 86 |
feet = frames["kp_extra"][index] if "kp_extra" in frames else None
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
scale = min(1., 960/info["width"])
|
| 89 |
width = max(2, 2*int(info["width"]*scale/2))
|
| 90 |
height = max(2, 2*int(info["height"]*scale/2))
|
|
@@ -118,7 +155,7 @@ def export_previews(video, result, destination, max_clips=10, overlay=True):
|
|
| 118 |
decoded.close()
|
| 119 |
manifest = {"swing_candidates_total": len(track["reps"]), "preview_limit": max_clips,
|
| 120 |
"purpose": "Visual inspection only; candidate ranges and events are unvalidated estimates.",
|
| 121 |
-
"previews": records}
|
| 122 |
atomic_json(destination / "previews.json", manifest)
|
| 123 |
return manifest
|
| 124 |
|
|
|
|
| 10 |
from baseball_batting.storage import atomic_json, read_json, sha256_file
|
| 11 |
|
| 12 |
|
| 13 |
+
def draw_points(image, points, rep, index, events, extra_points=None, projection_3d=None, body_height_px=None):
|
| 14 |
import cv2
|
| 15 |
image = image.copy()
|
| 16 |
+
display_scale = max(1., image.shape[1]/960)
|
| 17 |
+
cv2.rectangle(image, (0, 0), (image.shape[1], int((56 if projection_3d is not None else 32)*display_scale)), (20, 20, 20), -1)
|
| 18 |
for a, b in BODY_EDGES:
|
| 19 |
if points[a] is not None and points[b] is not None:
|
| 20 |
cv2.line(image, tuple(np.rint(points[a]).astype(int)),
|
|
|
|
| 30 |
if ankle is not None:
|
| 31 |
cv2.line(image, tuple(np.rint(ankle).astype(int)), pixel, (0, 180, 255), 2)
|
| 32 |
cv2.circle(image, pixel, 4, (0, 180, 255), -1)
|
| 33 |
+
if projection_3d is not None:
|
| 34 |
+
from baseball_batting.pose_agreement import AGREEMENT_LIMIT_PCT
|
| 35 |
+
for j, point in enumerate(projection_3d):
|
| 36 |
+
if point is None or not np.isfinite(point).all(): continue
|
| 37 |
+
pixel = tuple(np.rint(point).astype(int))
|
| 38 |
+
cv2.circle(image, pixel, 5, (255, 90, 230), 2)
|
| 39 |
+
if points[j] is not None:
|
| 40 |
+
distance = np.linalg.norm(np.asarray(point)-points[j])
|
| 41 |
+
conflict = body_height_px and distance/body_height_px*100 > AGREEMENT_LIMIT_PCT
|
| 42 |
+
color = (50, 50, 255) if conflict else (180, 120, 180)
|
| 43 |
+
cv2.line(image, tuple(np.rint(points[j]).astype(int)), pixel, color, 1)
|
| 44 |
+
cv2.circle(image, tuple(np.rint(points[j]).astype(int)), 3, (80, 230, 90), -1)
|
| 45 |
+
if conflict:
|
| 46 |
+
from baseball_batting.pose_agreement import COCO_NAMES
|
| 47 |
+
label = f"{COCO_NAMES[j]} {distance/body_height_px*100:.1f}%"
|
| 48 |
+
cv2.putText(image, label, (pixel[0]+int(6*display_scale), pixel[1]), cv2.FONT_HERSHEY_SIMPLEX,
|
| 49 |
+
.4*display_scale, color, max(1, round(display_scale)), cv2.LINE_AA)
|
| 50 |
+
cv2.putText(image, "Green: raw 2D | Purple: 3D projection | Red: disagreement >5% stature",
|
| 51 |
+
(int(8*display_scale), int(48*display_scale)), cv2.FONT_HERSHEY_SIMPLEX, .45*display_scale,
|
| 52 |
+
(255, 255, 255), max(1, round(display_scale)), cv2.LINE_AA)
|
| 53 |
labels = [name for name, event in events.items() if event["frame"] == index]
|
| 54 |
text = f"Swing candidate {rep} | frame {index}"
|
| 55 |
if labels: text += " | estimated " + ", ".join(labels)
|
| 56 |
+
cv2.putText(image, text, (int(8*display_scale), int(24*display_scale)), cv2.FONT_HERSHEY_SIMPLEX, .55*display_scale,
|
| 57 |
+
(255, 255, 255), max(1, round(2*display_scale)), cv2.LINE_AA)
|
| 58 |
return image
|
| 59 |
|
| 60 |
|
|
|
|
| 67 |
destination.mkdir(parents=True, exist_ok=True)
|
| 68 |
track = result["pose_track"]
|
| 69 |
frames, info = track["frames"], track["video"]
|
| 70 |
+
model_rows = {r["frame"]: r for r in result.get("experimental_body3d", {}).get("frames", [])}
|
| 71 |
+
image_stature = result.get("measurement_method", {}).get("body_height_px")
|
| 72 |
+
comparisons = []
|
| 73 |
selected, records = [], []
|
| 74 |
prior_end = -1
|
| 75 |
for rep in track["reps"][:max_clips]:
|
|
|
|
| 109 |
raise ValueError("Source playback timestamps differ from the analysis")
|
| 110 |
if overlay:
|
| 111 |
feet = frames["kp_extra"][index] if "kp_extra" in frames else None
|
| 112 |
+
projection = model_rows.get(index, {}).get("projection")
|
| 113 |
+
image = draw_points(image, frames["kp"][index], rep["rep"], index, rep["events"],
|
| 114 |
+
feet, projection, image_stature)
|
| 115 |
+
names = [name for name in ("contact", "foot_plant")
|
| 116 |
+
if rep["events"].get(name, {}).get("frame") == index]
|
| 117 |
+
if projection is not None and names:
|
| 118 |
+
file = f"swing-{rep['rep']:03d}-frame-{index:06d}-comparison.png"
|
| 119 |
+
png = cv2.resize(image, (int(info["width"]*min(1., 1280/info["width"])),
|
| 120 |
+
int(info["height"]*min(1., 1280/info["width"]))))
|
| 121 |
+
if not cv2.imwrite(str(destination/file), png):
|
| 122 |
+
raise OSError("Could not save model comparison")
|
| 123 |
+
comparisons.append({"rep": rep["rep"], "frame": index, "events": names, "file": file,
|
| 124 |
+
"sha256": sha256_file(destination/file)})
|
| 125 |
scale = min(1., 960/info["width"])
|
| 126 |
width = max(2, 2*int(info["width"]*scale/2))
|
| 127 |
height = max(2, 2*int(info["height"]*scale/2))
|
|
|
|
| 155 |
decoded.close()
|
| 156 |
manifest = {"swing_candidates_total": len(track["reps"]), "preview_limit": max_clips,
|
| 157 |
"purpose": "Visual inspection only; candidate ranges and events are unvalidated estimates.",
|
| 158 |
+
"previews": records, "model_comparisons": comparisons}
|
| 159 |
atomic_json(destination / "previews.json", manifest)
|
| 160 |
return manifest
|
| 161 |
|