File size: 6,827 Bytes
326d3cc
 
 
f771d3b
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f771d3b
326d3cc
 
 
 
 
 
 
 
 
f771d3b
326d3cc
 
f771d3b
 
326d3cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
"""Raw 2D pose plus estimated swing measurements; no coaching decisions."""
import math
import numpy as np
import yaml
from .config import CONFIG_ROOT
from .contracts import json_safe
from .batting_measurements import analyze_batting, coach_payload

KEYPOINT_ORDER = ["nose", "left_eye", "right_eye", "left_ear", "right_ear",
                  "left_shoulder", "right_shoulder", "left_elbow", "right_elbow",
                  "left_wrist", "right_wrist", "left_hip", "right_hip", "left_knee",
                  "right_knee", "left_ankle", "right_ankle"]
EXTRA_ORDER = ["left_big_toe", "left_small_toe", "left_heel",
               "right_big_toe", "right_small_toe", "right_heel"]


def constant_fps(times):
    if len(times) < 2 or any(t is None or not math.isfinite(t) for t in times):
        return None
    delta = np.diff(times)
    if np.any(delta <= 0) or not np.allclose(delta, np.median(delta), rtol=.01, atol=1e-6):
        return None
    return round(float(1 / np.median(delta)), 6)


def build_api_result(capture, observations, options, model_hashes):
    n = capture["frame_count"]
    if len(observations["frames"]) != n:
        raise ValueError("Observation and capture frame counts differ")
    width, height = capture["frames"][0]["width"], capture["frames"][0]["height"]
    if any(f["width"] != width or f["height"] != height for f in capture["frames"]):
        raise ValueError("Changing frame dimensions are unsupported")
    frames = {k: [] for k in ("t_s", "playback_t_s", "kp", "conf", "kp_extra", "conf_extra",
                              "box", "track_id", "people_count", "blur", "brightness")}
    real_times = [f["physical_s"] for f in capture["frames"]]
    known_clock = (all(t is not None and math.isfinite(t) for t in real_times)
                   and all(b > a for a, b in zip(real_times, real_times[1:])))
    if not known_clock:
        real_times = [None] * n
    for i, observed in enumerate(observations["frames"]):
        if observed["frame_id"] != i:
            raise ValueError("Observation frame order differs from capture")
        points, scores = [], []
        for j in range(23):
            point, score = observed["body_points"][j], observed["body_scores"][j]
            supported = (observed["body_states"][j] == "model_inferred"
                         and point is not None and all(x is not None and math.isfinite(x) for x in point)
                         and 0 <= point[0] < width and 0 <= point[1] < height
                         and score is not None and math.isfinite(score))
            points.append(list(map(float, point)) if supported else None)
            scores.append(float(np.clip(score, 0, 1)) if supported else 0.)
        frames["kp"].append(points[:17]); frames["conf"].append(scores[:17])
        frames["kp_extra"].append(points[17:23]); frames["conf_extra"].append(scores[17:23])
        person = observed.get("person")
        box = person["box"] if person else None
        if box is not None:
            box = np.asarray(box, float)
            if box.shape != (4,) or not np.isfinite(box).all():
                box = None
            else:
                box = np.clip(box, [0, 0, 0, 0], [width, height, width, height]).tolist()
                if box[2] <= box[0] or box[3] <= box[1]:
                    box = None
        frames["box"].append(box)
        frames["track_id"].append(1 if box else None)
        frames["people_count"].append(observed.get("people_count"))
        quality = capture["quality"][i]
        variance = quality["blur_laplacian_variance"]
        frames["blur"].append(float(1 / (1 + max(0, variance) / 100)))
        frames["brightness"].append(float(quality["mean_luminance"]))
        frames["t_s"].append(real_times[i])
        frames["playback_t_s"].append(capture["frames"][i]["playback_s"])
    warnings = ["Point scores are model scores; their accuracy has not been calibrated."]
    if not known_clock:
        warnings.append("Capture time is unknown: t_s and capture_fps are null. playback_t_s is not capture time.")
    pose_version = yaml.safe_load((CONFIG_ROOT / "resources.yaml").read_text())["resources"]["body_pose"]["version"]
    result = {"schema_version": "1.0", "status": "partial", "warnings": warnings,
        "pose_track": {"schema_version": "1.0", "discipline": "hitting", "view": options.view,
            "video": {"width": width, "height": height, "frame_count": n,
                      "capture_fps": constant_fps(real_times),
                      "playback_fps": constant_fps(frames["playback_t_s"]),
                      "rotation_degrees_applied": capture["rotation_degrees"],
                      "time_source": ("original_pts" if options.timing.kind == "unretimed" else
                                      "slowmo_rescaled" if options.timing.kind == "constant_slowdown" else
                                      "explicit_capture_times" if options.timing.kind == "explicit" else "unknown") if known_clock else "unknown"},
            "model": {"name": "RTMW-x", "version": pose_version,
                      "sha256": model_hashes["body_pose"], "person_detector": "YOLOX-m HumanArt c2c7a14a",
                      "person_detector_sha256": model_hashes["person_detector"],
                      "processing": ["score_threshold_0.35", "foot_ankle_distance_guard", "out_of_image_points_removed", "scores_clipped_0_1", "no_smoothing_or_gap_filling"],
                      "people_rule": "largest area times score initially; maximum overlap thereafter; reject overlap below 0.05; count secondary proposals only above max(15% image height, 35% athlete height)",
                      "blur_definition": "1/(1+grayscale_laplacian_variance/100); heuristic, not calibrated"},
            "keypoint_order": KEYPOINT_ORDER, "extra_keypoint_order": EXTRA_ORDER,
            "frames": frames, "reps": []},
        "capabilities": {"gpu_2d": True, "body_3d": False, "automatic_rep_splitting": True,
                         "automatic_events": True, "swing_metrics": True,
                         "estimated_only": True,
                         "coaching": False, "pitching": False},
        "validation": "reference_validation_pending"}
    pose_reps, measurement_reps, capture_check, diagnostic, method = analyze_batting(result["pose_track"], options)
    result["pose_track"]["reps"] = pose_reps
    result["measurement_method"] = method
    result["warnings"].extend(diagnostic)
    measurements = {"schema_version": "2.0", "discipline": "hitting", "view": options.view,
                    "fps": constant_fps(real_times), "capture": capture_check, "reps": measurement_reps}
    if options.level: measurements["level"] = options.level
    result["measurements"] = measurements
    result["coach_payload"] = coach_payload(measurements)
    return json_safe(result)