"""Pure functions on keypoint and ball series - no models, no video, fully testable. Keypoints are COCO-17 in image pixels (y grows downward), shape (N, 17, 3) = x, y, conf. Times are VIDEO seconds; divide by time_scale to get REAL seconds (slow motion). All lengths are normalised by the bowler's torso length so thresholds work at any zoom level, and every derived value is a 2D image-plane estimate. """ import numpy as np SIDES = { "left": dict(sh=5, el=7, wr=9, hip=11, kn=13, an=15), "right": dict(sh=6, el=8, wr=10, hip=12, kn=14, an=16), } OPP = {"left": "right", "right": "left"} SKELETON = [(5, 7), (7, 9), (6, 8), (8, 10), (5, 6), (5, 11), (6, 12), (11, 12), (11, 13), (13, 15), (12, 14), (14, 16), (0, 5), (0, 6)] KCONF = 0.3 def _pt(k, i): return k[..., i, :2] def torso_length(kpts): """Median shoulder-mid to hip-mid distance over frames where all four are confident.""" c = np.minimum.reduce([kpts[:, i, 2] for i in (5, 6, 11, 12)]) sh = (kpts[:, 5, :2] + kpts[:, 6, :2]) / 2 hp = (kpts[:, 11, :2] + kpts[:, 12, :2]) / 2 d = np.linalg.norm(sh - hp, axis=1) d = d[(c > KCONF) & (d > 5)] return float(np.median(d)) if d.size else float("nan") def angle3(a, b, c): """Angle ABC in degrees.""" v1, v2 = np.asarray(a) - b, np.asarray(c) - b n = np.linalg.norm(v1) * np.linalg.norm(v2) if n < 1e-6: return float("nan") return float(np.degrees(np.arccos(np.clip(np.dot(v1, v2) / n, -1, 1)))) def _speed(t_real, xy, valid, tl, incoming_only=False): """Point speed in torso lengths per real second; nan where not computable. Default: max of the segments touching a sample. incoming_only: the segment arriving at the sample (used to find when a foot has come to rest).""" sp = np.full(len(t_real), np.nan) idx = np.flatnonzero(valid) for a, b in zip(idx[:-1], idx[1:]): dt = t_real[b] - t_real[a] if dt > 0: v = np.linalg.norm(xy[b] - xy[a]) / dt / tl sp[b] = v if np.isnan(sp[b]) else max(sp[b], v) if not incoming_only: sp[a] = v if np.isnan(sp[a]) else max(sp[a], v) return sp def body_up(kpts): """Per-frame unit vector from hip-centre to shoulder-centre ('up' for the body). Measuring arm height along this axis, not image vertical, keeps the detector working for leaning bowlers, tilted cameras and sideways (rotated) phone video.""" c = np.minimum.reduce([kpts[:, i, 2] for i in (5, 6, 11, 12)]) v = (kpts[:, 5, :2] + kpts[:, 6, :2]) / 2 - (kpts[:, 11, :2] + kpts[:, 12, :2]) / 2 n = np.linalg.norm(v, axis=1, keepdims=True) ok = (c > KCONF) & (n[:, 0] > 5) up = np.where(ok[:, None], v / np.maximum(n, 1e-6), np.nan) med = np.nanmedian(up[ok], axis=0) if ok.any() else np.array([0.0, -1.0]) med = med / max(np.linalg.norm(med), 1e-6) up[~ok] = med return up def wrist_height(kpts, side, tl): """Height of the wrist above the shoulder along the body axis, in torso lengths. When the wrist is blurred out (common at release) but the elbow is visible, the elbow height x2 stands in for it (elbow is about half way up the arm).""" s = SIDES[side] up = body_up(kpts) sh = kpts[:, s["sh"], :2] hw = np.einsum("ij,ij->i", kpts[:, s["wr"], :2] - sh, up) / tl he = 2 * np.einsum("ij,ij->i", kpts[:, s["el"], :2] - sh, up) / tl csh, cwr, cel = kpts[:, s["sh"], 2], kpts[:, s["wr"], 2], kpts[:, s["el"], 2] h = np.where(cwr >= KCONF, hw, np.where(cel >= KCONF, he, np.nan)) h[csh < KCONF] = np.nan return h def find_releases(t, kpts, time_scale, cfg, stats=None): """Release = the bowling wrist peaks high above the shoulder, moving fast, having come from below shoulder height (an over-arm action, not a wave). Returns candidates sorted by time with a 0-1 score. If `stats` (a dict) is given, it is filled with why peaks were rejected - used by diagnose.py.""" st = stats if stats is not None else {} for k in ("tracks", "no_torso", "peaks", "rej_not_from_low", "rej_too_slow", "accepted"): st.setdefault(k, 0) st.setdefault("max_wrist_height", float("-inf")); st.setdefault("max_wrist_speed", 0.0) st["tracks"] += 1 t = np.asarray(t, float) if len(t) < 5: return [] tl = torso_length(kpts) if not np.isfinite(tl): st["no_torso"] += 1 return [] from_low = cfg.get("from_below", 0.2) tr = t / time_scale min_h, min_v = cfg.get("min_wrist_height", 0.8), cfg.get("min_wrist_speed", 8.0) out = [] for side, s in SIDES.items(): h = wrist_height(kpts, side, tl) valid = np.isfinite(h) sp = _speed(tr, kpts[:, s["wr"], :2], valid, tl) if valid.any(): st["max_wrist_height"] = max(st["max_wrist_height"], float(np.nanmax(h))) if np.isfinite(sp).any(): st["max_wrist_speed"] = max(st["max_wrist_speed"], float(np.nanmax(sp))) for i in np.flatnonzero(valid & (h >= min_h)): near = valid & (np.abs(tr - tr[i]) <= 0.1) if h[i] < np.nanmax(np.where(near, h, -np.inf)): continue # not the local peak st["peaks"] += 1 before = valid & (tr >= tr[i] - 0.6) & (tr <= tr[i] - 0.03) after = valid & (tr >= tr[i] + 0.03) & (tr <= tr[i] + 0.6) if not before.any() or np.nanmin(h[before]) > from_low: st["rej_not_from_low"] += 1 continue # arm never came from low win = (np.abs(tr - tr[i]) <= 0.15) & np.isfinite(sp) vmax = float(np.nanmax(sp[win])) if win.any() else 0.0 if vmax < min_v: st["rej_too_slow"] += 1 continue st["accepted"] += 1 after_ok = bool(after.any() and np.nanmin(h[after]) < 0.4) kc = float(np.mean([kpts[i, s[j], 2] for j in ("sh", "el", "wr")])) score = 0.35 * min(h[i] / 1.5, 1) + 0.35 * min(vmax / (2 * min_v), 1) \ + 0.15 * after_ok + 0.15 * kc out.append({"i": int(i), "t": float(t[i]), "side": side, "wrist_height": float(h[i]), "wrist_speed": vmax, "arm_comes_down": after_ok, "score": round(float(score), 3)}) return dedupe(out, cfg.get("refractory_s", 3.0) * time_scale) def dedupe(cands, min_gap): keep = [] for c in sorted(cands, key=lambda c: -c["score"]): if all(abs(c["t"] - k["t"]) >= min_gap for k in keep): keep.append(c) return sorted(keep, key=lambda c: c["t"]) def _foot_plant(t, kpts, i_end, ankle, time_scale, search_s, thr): """Earliest index of the final still period of `ankle` that is still at i_end.""" tl = torso_length(kpts) tr = np.asarray(t, float) / time_scale valid = kpts[:, ankle, 2] > KCONF sp = _speed(tr, kpts[:, ankle, :2], valid, tl, incoming_only=True) lo = tr[i_end] - search_s j = None for k in range(i_end, -1, -1): if tr[k] < lo: break if not valid[k]: continue if np.isfinite(sp[k]) and sp[k] < thr: j = k elif j is not None: break return j def find_ffc(t, kpts, i_rel, side, time_scale, cfg): """Front-foot contact: the front ankle (opposite the bowling arm) comes to rest before release.""" an = SIDES[OPP[side]]["an"] j = _foot_plant(t, kpts, i_rel, an, time_scale, cfg.get("search_s", 0.4), cfg.get("max_ankle_speed", 2.0)) if j is None or j == i_rel: return None return {"i": int(j), "t": float(t[j]), "ankle_conf": float(kpts[j, an, 2])} def find_bfc(t, kpts, i_ffc, side, time_scale, cfg): """Back-foot contact: the back ankle (same side as the bowling arm) lands before front-foot contact and is still planted when the front foot lands.""" an = SIDES[side]["an"] j = _foot_plant(t, kpts, i_ffc, an, time_scale, cfg.get("bfc_search_s", 0.5), cfg.get("max_ankle_speed", 2.0)) if j is None or j >= i_ffc: return None return {"i": int(j), "t": float(t[j]), "ankle_conf": float(kpts[j, an, 2])} def hip_speed(t, kpts, time_scale): tl = torso_length(kpts) c = np.minimum(kpts[:, 11, 2], kpts[:, 12, 2]) hp = (kpts[:, 11, :2] + kpts[:, 12, :2]) / 2 return _speed(np.asarray(t, float) / time_scale, hp, c > KCONF, tl, incoming_only=True) def _smooth(x, n): if n <= 1: return x y = np.copy(x) for i in range(len(x)): w = x[max(0, i - n // 2): i + n // 2 + 1] w = w[np.isfinite(w)] y[i] = w.mean() if w.size else np.nan return y def find_runup_start(t, kpts, i_end, time_scale, cfg): """Start of the continuous approach that ends at i_end (back-foot contact or release): walk back while the (smoothed) hip speed stays above run_speed.""" t = np.asarray(t, float) fps_real = (len(t) - 1) / max(1e-6, (t[-1] - t[0]) / time_scale) if len(t) > 1 else 30 sp = _smooth(hip_speed(t, kpts, time_scale), max(1, int(0.2 * fps_real))) thr = cfg.get("run_speed", 1.0) moving = np.flatnonzero(np.isfinite(sp[:i_end + 1]) & (sp[:i_end + 1] > thr)) if not moving.size: return None k = moving[-1] while k > 0 and (not np.isfinite(sp[k - 1]) or sp[k - 1] > thr * 0.6): k -= 1 starts_before_clip = k == 0 return {"i": int(k), "t": float(t[k]), "starts_before_clip": bool(starts_before_clip), "confidence": 0.3 if starts_before_clip else 0.6} def find_followthrough_end(t, kpts, i_rel, side, time_scale, cfg): """First moment after release when the bowling wrist has slowed to a fraction of its peak speed and the body has stopped travelling quickly.""" t = np.asarray(t, float) tl = torso_length(kpts) tr = t / time_scale wr = SIDES[side]["wr"] sw = _speed(tr, kpts[:, wr, :2], kpts[:, wr, 2] > KCONF, tl) near = np.abs(tr - tr[i_rel]) <= 0.15 peak = np.nanmax(np.where(near, sw, np.nan)) if np.isfinite(np.where(near, sw, np.nan)).any() else np.nan if not np.isfinite(peak): return None hs = hip_speed(t, kpts, time_scale) frac, need = cfg.get("followthrough_fraction", 0.2), 2 run = 0 for k in range(i_rel + 1, len(t)): if tr[k] - tr[i_rel] < 0.15: continue if tr[k] - tr[i_rel] > cfg.get("followthrough_max_s", 1.5): break still = np.isfinite(sw[k]) and sw[k] < frac * peak and (not np.isfinite(hs[k]) or hs[k] < 2 * cfg.get("run_speed", 1.0)) run = run + 1 if still else 0 if run >= need: j = k - need + 1 return {"i": int(j), "t": float(t[j]), "confidence": 0.5} return None def posture_features(kpts, i_rel, i_ffc, side): """2D posture at release (and front-foot contact when found).""" s, f = SIDES[side], SIDES[OPP[side]] k = kpts[i_rel] tl = torso_length(kpts) out = {} def conf(*ids, kk=k): return float(min(kk[i, 2] for i in ids)) out["elbow_angle_release_deg"] = (angle3(k[s["sh"], :2], k[s["el"], :2], k[s["wr"], :2]), conf(s["sh"], s["el"], s["wr"])) out["front_knee_angle_release_deg"] = (angle3(k[f["hip"], :2], k[f["kn"], :2], k[f["an"], :2]), conf(f["hip"], f["kn"], f["an"])) sh = (k[5, :2] + k[6, :2]) / 2 hp = (k[11, :2] + k[12, :2]) / 2 v = sh - hp tilt = float(np.degrees(np.arctan2(abs(v[0]), -v[1]))) if np.linalg.norm(v) > 1 else float("nan") out["trunk_tilt_release_deg"] = (tilt, conf(5, 6, 11, 12)) out["wrist_height_release_torso"] = (float((k[s["sh"], 1] - k[s["wr"], 1]) / tl), conf(s["sh"], s["wr"])) if i_ffc is not None: kf = kpts[i_ffc] out["front_knee_angle_ffc_deg"] = (angle3(kf[f["hip"], :2], kf[f["kn"], :2], kf[f["an"], :2]), conf(f["hip"], f["kn"], f["an"], kk=kf)) out["stride_length_ffc_torso"] = (float(np.linalg.norm(kf[15, :2] - kf[16, :2]) / tl), conf(15, 16, kk=kf)) return {name: {"value": None if not np.isfinite(v) else round(v, 2), "confidence": round(c, 3), "space": "image_2d"} for name, (v, c) in out.items()} def front_leg_label(knee_ffc, knee_rel): """Coach vocabulary from two 2D knee angles (180 = straight).""" if knee_ffc is None or knee_rel is None: return None flex = knee_ffc - knee_rel # positive = knee bending more if flex <= 8: return "braced" if flex >= 20: return "flexing" return "slightly flexing" def link_ball(seq, start_xy, tl, time_scale, max_start_s=0.35): """Greedy constant-velocity linking of per-frame ball detections. seq: [(t, [(x, y, conf), ...]), ...] in time order.""" track, last, vel = [], None, None t0 = seq[0][0] if seq else 0 for t, dets in seq: if not dets: continue pts = np.array([d[:2] for d in dets], float) if last is None: if (t - t0) / time_scale > max_start_s: break if start_xy is not None: d = np.linalg.norm(pts - start_xy, axis=1) j = int(np.argmin(d)) if d[j] > 4 * tl: continue else: j = int(np.argmax([d[2] for d in dets])) else: dt = t - last[0] pred = last[1] + (vel * dt if vel is not None else 0) gate = max(2.0 * tl, (np.linalg.norm(vel) * dt * 0.7 if vel is not None else 0) + tl) d = np.linalg.norm(pts - pred, axis=1) j = int(np.argmin(d)) if d[j] > gate: continue vel = (pts[j] - last[1]) / dt if dt > 0 else vel x, y, c = dets[j] track.append({"t": float(t), "x": float(x), "y": float(y), "conf": float(c)}) last = (t, pts[j]) return track def _turns(track): """Direction change (degrees) at each interior ball point.""" p = np.array([[q["t"], q["x"], q["y"]] for q in track]) v = np.diff(p[:, 1:], axis=0) / np.maximum(np.diff(p[:, 0]), 1e-6)[:, None] out = [] for k in range(1, len(v)): a, b = v[k - 1], v[k] n = np.linalg.norm(a) * np.linalg.norm(b) ang = float(np.degrees(np.arccos(np.clip(np.dot(a, b) / n, -1, 1)))) if n > 1e-6 else 0.0 out.append((k, ang)) return out def find_bounce(track, min_turn_deg=20.0): """Bounce = the FIRST sharp change in 2D travel direction after release, with at least two ball points before it (a later turn may be bat contact).""" if len(track) < 5: return None turns = [(k, a) for k, a in _turns(track) if k >= 2 and k <= len(track) - 2 and a >= min_turn_deg] if not turns: return None k, ang = turns[0] q = track[k] conf = min(1.0, len(track) / 12) * min(1.0, ang / 45) return {"i": k, "t": q["t"], "x": q["x"], "y": q["y"], "turn_deg": round(ang, 1), "confidence": round(conf, 3)} def find_contact(track, bounce_i, batter_box_at, min_turn_deg=25.0): """Bat contact = a sharp turn after the bounce that happens inside (or right next to) the batter's box. batter_box_at(t) returns [x1,y1,x2,y2] or None.""" if bounce_i is None or len(track) < bounce_i + 3: return None for k, ang in _turns(track): if k <= bounce_i + 1 or ang < min_turn_deg: # the turn right after a bounce is the bounce itself continue q = track[k] box = batter_box_at(q["t"]) if box is None: continue x1, y1, x2, y2 = box m = 0.25 * (y2 - y1) if x1 - m <= q["x"] <= x2 + m and y1 - m <= q["y"] <= y2 + m: return {"i": k, "t": q["t"], "x": q["x"], "y": q["y"], "turn_deg": round(ang, 1), "confidence": round(min(0.6, ang / 90), 3)} return None class IoUTracker: """Tiny IoU tracker so person IDs persist across frames (no extra deps).""" def __init__(self, iou_thr=0.3, max_age=6): self.iou_thr, self.max_age = iou_thr, max_age self.tracks, self.next_id = {}, 1 @staticmethod def iou(a, b): x1, y1 = max(a[0], b[0]), max(a[1], b[1]) x2, y2 = min(a[2], b[2]), min(a[3], b[3]) inter = max(0, x2 - x1) * max(0, y2 - y1) u = (a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter return inter / u if u > 0 else 0.0 def reset(self): self.tracks = {} def update(self, boxes): ids = [None] * len(boxes) pairs = sorted(((self.iou(tb, b), tid, j) for tid, (tb, _) in self.tracks.items() for j, b in enumerate(boxes)), reverse=True) used_t, used_b = set(), set() for s, tid, j in pairs: if s < self.iou_thr or tid in used_t or j in used_b: continue ids[j] = tid used_t.add(tid); used_b.add(j) for j, b in enumerate(boxes): # fallback: nearest centre within half a box height if ids[j] is not None: continue cx, cy, bh = (b[0] + b[2]) / 2, (b[1] + b[3]) / 2, b[3] - b[1] best, bt = 0.5 * bh, None for tid, (tb, _) in self.tracks.items(): if tid in used_t: continue d = ((cx - (tb[0] + tb[2]) / 2) ** 2 + (cy - (tb[1] + tb[3]) / 2) ** 2) ** 0.5 if d < best: best, bt = d, tid if bt is not None: ids[j] = bt used_t.add(bt) for j, b in enumerate(boxes): if ids[j] is None: ids[j] = self.next_id self.next_id += 1 self.tracks[ids[j]] = (list(b), 0) for tid in list(self.tracks): if tid not in ids: b, age = self.tracks[tid] if age + 1 > self.max_age: del self.tracks[tid] else: self.tracks[tid] = (b, age + 1) return ids # ---------------- batter events (section 7.3) ---------------- def _wrists(kpts): c = np.minimum(kpts[:, 9, 2], kpts[:, 10, 2]) return (kpts[:, 9, :2] + kpts[:, 10, :2]) / 2, c > KCONF def find_batter_trigger(t, kpts, t_release, time_scale, cfg): """Batter trigger start: the first sustained movement of the batter's hips or feet after standing still, in the window around the bowler's release.""" t = np.asarray(t, float) if len(t) < 5: return None tl = torso_length(kpts) if not np.isfinite(tl): return None tr = t / time_scale hip = hip_speed(t, kpts, time_scale) an = (kpts[:, 15, :2] + kpts[:, 16, :2]) / 2 ank = _speed(tr, an, np.minimum(kpts[:, 15, 2], kpts[:, 16, 2]) > KCONF, tl, incoming_only=True) move = np.fmax(hip, ank) lo, hi = t_release / time_scale - cfg.get("trigger_before_s", 0.8), t_release / time_scale + cfg.get("trigger_after_s", 0.4) thr = cfg.get("trigger_speed", 0.8) still = 0 for k in range(len(t)): if tr[k] < lo or not np.isfinite(move[k]): continue if tr[k] > hi: break if move[k] < thr * 0.5: still += 1 elif move[k] > thr and still >= 2 and k + 1 < len(t) and np.isfinite(move[k + 1]) and move[k + 1] > thr * 0.7: return {"i": int(k), "t": float(t[k]), "confidence": 0.4} return None def find_shot_end(t, kpts, t_after, time_scale, cfg): """Shot follow-through end: after the shot (contact, or ball arrival), the batter's hands slow to a fraction of their peak speed and stay slow.""" t = np.asarray(t, float) tl = torso_length(kpts) if len(t) < 5 or not np.isfinite(tl): return None tr = t / time_scale w, ok = _wrists(kpts) sp = _speed(tr, w, ok, tl) after = (tr >= t_after / time_scale - 0.2) & np.isfinite(sp) if not after.any(): return None peak = float(np.nanmax(sp[after])) if peak < cfg.get("shot_min_speed", 3.0): return None i_peak = int(np.flatnonzero(after)[np.argmax(sp[after])]) run = 0 for k in range(i_peak + 1, len(t)): if tr[k] - tr[i_peak] > cfg.get("shot_max_s", 1.5): break run = run + 1 if (np.isfinite(sp[k]) and sp[k] < cfg.get("followthrough_fraction", 0.2) * peak) else 0 if run >= 2: j = k - 1 return {"i": int(j), "t": float(t[j]), "confidence": 0.4} return None