Download code/multiview.py from d9993r/CRICKET: direct link, hf CLI and curl.
- Browser
- Download file 16.6 kB
-
https://huggingface.co/datasets/d9993r/CRICKET/resolve/main/code/multiview.py
- Command line
-
hf download hf://datasets/d9993r/CRICKET/code/multiview.py
-
curl -L -o multiview.py https://huggingface.co/datasets/d9993r/CRICKET/resolve/main/code/multiview.py
16.6 kB
| """Multi-view sessions: one delivery, several cameras (standard sections 2, 6, 9.1, 13.2). | |
| Without this stage, the same ball filmed from three angles becomes three unrelated | |
| deliveries. Here, videos listed together in config.yaml `multiview.sessions` are: | |
| 1. synchronised: audio offset (clap / bat sound) for a coarse shift, then refined so | |
| the bowler's release lines up across views; | |
| 2. matched: deliveries whose releases coincide (after sync) become ONE multi-view | |
| delivery with a views[] list; | |
| 3. calibrated in 3D: each camera's focal length, orientation and position are solved | |
| from the clicked pitch points (geometry3d.py); | |
| 4. reconstructed: ball path, release point, bounce point and speed, and the bowler's | |
| 3D joints at release / front-foot contact, by triangulation; | |
| 5. fused: events agreed across views (spread reported as a quality check), and the | |
| per-view records are tagged with the shared sample id so training, splits and | |
| SFT treat them as one sample.""" | |
| import json | |
| from collections import defaultdict | |
| from pathlib import Path | |
| import numpy as np | |
| from common import absp, now_iso, prov, write_json, write_jsonl | |
| from geometry3d import angle3, calibrate_camera, project, triangulate | |
| from pitch import BATTER_STUMPS_Y_M | |
| EVENTS = ["run_up_start", "back_foot_contact", "front_foot_contact", "ball_release", "followthrough_end", | |
| "ball_bounce", "batter_trigger_start", "bat_ball_contact", "shot_followthrough_end"] | |
| def _sess_time(d, t_clip, shift): | |
| w = d["window"] | |
| return (w["first_frame"] / w["fps"] + t_clip) / w["time_scale"] + shift | |
| def _release_times(dels): | |
| out = [] | |
| for d in dels: | |
| r = d["events"].get("ball_release") | |
| if r: | |
| out.append((d, (d["window"]["first_frame"] / d["window"]["fps"] + r["t_clip"]) / d["window"]["time_scale"])) | |
| return out | |
| def estimate_shift(ref_rel, view_rel, tol, audio_shift=None): | |
| """Shift s with time_in_reference = time_in_view + s that lines up most releases.""" | |
| if not ref_rel or not view_rel: | |
| return (audio_shift, 0, "audio" if audio_shift is not None else "none") | |
| cands = [r - v for r in ref_rel for v in view_rel] | |
| if audio_shift is not None: | |
| near = [c for c in cands if abs(c - audio_shift) <= 0.5] | |
| cands = near or [audio_shift] | |
| best = None | |
| for s in cands: | |
| res = [min((abs(r - (v + s)) for r in ref_rel)) for v in view_rel] | |
| hits = [x for x in res if x <= tol] | |
| key = (len(hits), -np.mean(hits) if hits else -1e9) | |
| if best is None or key > best[0]: | |
| best = (key, s) | |
| s = best[1] | |
| resid = [min(ref_rel, key=lambda r: abs(r - (v + s))) - (v + s) for v in view_rel] | |
| resid = [x for x in resid if abs(x) <= tol] | |
| if resid: | |
| s += float(np.median(resid)) | |
| if audio_shift is not None and abs(s - audio_shift) <= 0.05: | |
| # releases agree with the sound; sound is finer than one video frame, so keep it | |
| return (round(float(audio_shift), 4), len(resid), "audio (confirmed by releases)") | |
| return (round(float(s), 4), len(resid), "audio+release" if audio_shift is not None else "release") | |
| def _interp_track(d, shift): | |
| pts = d.get("ball", {}).get("points") or [] | |
| if len(pts) < 2: | |
| return None | |
| t = np.array([_sess_time(d, p["t_clip"], shift) for p in pts]) | |
| xy = np.array([[p["x"], p["y"]] for p in pts]) | |
| return t, xy, 2.0 / d["window"]["fps"] | |
| def _at(track, t): | |
| ts, xy, gap = track | |
| if t < ts[0] or t > ts[-1]: | |
| return None | |
| j = int(np.searchsorted(ts, t)) | |
| if j == 0: | |
| return xy[0] | |
| a, b = j - 1, min(j, len(ts) - 1) | |
| if ts[b] - ts[a] > gap: | |
| return None | |
| w = 0 if ts[b] == ts[a] else (t - ts[a]) / (ts[b] - ts[a]) | |
| return xy[a] * (1 - w) + xy[b] * w | |
| def ball_3d(views, t_release, time_scale_real=1.0): | |
| """Triangulated ball path from 2+ calibrated views with ball tracks.""" | |
| tracks = {v["camera_id"]: (_interp_track(v["d"], v["shift"]), v["P"]) for v in views if v.get("P")} | |
| tracks = {k: tv for k, tv in tracks.items() if tv[0] is not None} | |
| if len(tracks) < 2: | |
| return None | |
| base = max(tracks, key=lambda k: len(tracks[k][0][0])) | |
| path = [] | |
| for t in tracks[base][0][0]: | |
| if t < t_release - 0.05: | |
| continue | |
| Ps, uvs = [], [] | |
| for k, (tr, P) in tracks.items(): | |
| uv = _at(tr, t) | |
| if uv is not None: | |
| Ps.append(P); uvs.append(uv) | |
| if len(Ps) >= 2: | |
| X, err = triangulate(Ps, uvs) | |
| if err < 12 and -5 < X[1] < 25 and -0.2 < X[2] < 4: | |
| path.append({"t": round(float(t - t_release), 4), "xyz": [round(float(c), 3) for c in X], | |
| "views": len(Ps), "reproj_px": round(err, 2)}) | |
| if len(path) < 3: | |
| return None | |
| out = {"path": path} | |
| T = np.array([p["t"] for p in path]); X = np.array([p["xyz"] for p in path]) | |
| ib = int(np.argmin(X[:, 2])) | |
| # Before it pitches, the ball's height must follow gravity: z = z0 + vz*t - g/2*t^2. | |
| # Fixing the g term makes the fit robust, and the best-fitting cut-off tells us which | |
| # samples are still before the bounce. | |
| g2 = 9.81 / 2 | |
| best = None | |
| for k in range(max(2, ib - 2), min(len(T), ib + 2)): | |
| Tp, Zp = T[:k + 1], X[:k + 1, 2] | |
| A = np.vstack([np.ones_like(Tp), Tp]).T | |
| coef, *_ = np.linalg.lstsq(A, Zp + g2 * Tp ** 2, rcond=None) | |
| rms = float(np.sqrt(np.mean((A @ coef - g2 * Tp ** 2 - Zp) ** 2))) | |
| if best is None or rms < best[0] - 1e-4 or (abs(rms - best[0]) <= 1e-4 and k > best[1]): | |
| best = (rms, k, coef) | |
| _, k, (z0, vz) = best | |
| pre = slice(0, k + 1) | |
| Tp, Xp = T[pre], X[pre] | |
| cx, cy = np.polyfit(Tp, Xp[:, 0], 1), np.polyfit(Tp, Xp[:, 1], 1) | |
| cz = np.array([-g2, vz, z0]) | |
| at = lambda t: [round(float(np.polyval(cx, t)), 3), round(float(np.polyval(cy, t)), 3), round(float(np.polyval(cz, t)), 3)] | |
| out["release_xyz"] = at(0.0) # extrapolated to the fused release moment | |
| roots = [r.real for r in np.roots(cz) if abs(r.imag) < 1e-9 and 0 < r.real < 1.5] | |
| tb = min(roots, key=lambda r: abs(r - T[ib])) if roots else float(T[ib]) | |
| bx = at(tb); bx[2] = 0.0 | |
| out["bounce_xyz"] = bx | |
| out["bounce_t_after_release_s"] = round(float(tb), 4) | |
| v = np.array([cx[0], cy[0], (np.polyval(np.polyder(cz), 0.0))]) | |
| out["speed_kmh"] = round(float(np.linalg.norm(v) * 3.6), 1) | |
| out["speed_from_points"] = int(len(Tp)) | |
| out["fit"] = f"x,y linear; z with gravity fixed; {len(Tp)} pre-bounce points, rms {best[0]:.3f} m" | |
| out["length_from_batter_stumps_m"] = round(BATTER_STUMPS_Y_M - out["bounce_xyz"][1], 2) | |
| return out | |
| def pose_3d(views, t_session, side): | |
| """Bowler joints in 3D at one moment (nearest frame in each calibrated view).""" | |
| Ps, K2 = [], [] | |
| for v in views: | |
| p = Path(v["dir"]) / "bowler_pose.npz" | |
| if not v.get("P") or not p.exists(): | |
| continue | |
| z = np.load(p) | |
| w = v["d"]["window"] | |
| ts = z["frames"] / w["fps"] / w["time_scale"] + v["shift"] | |
| i = int(np.argmin(np.abs(ts - t_session))) | |
| if abs(ts[i] - t_session) > 1.5 / w["fps"]: | |
| continue | |
| Ps.append(v["P"]); K2.append(z["kpts"][i]) | |
| if len(Ps) < 2: | |
| return None | |
| J = np.full((17, 3), np.nan); errs = [] | |
| for j in range(17): | |
| sel = [(P, k[j, :2]) for P, k in zip(Ps, K2) if k[j, 2] > 0.3] | |
| if len(sel) >= 2: | |
| X, e = triangulate([s[0] for s in sel], [s[1] for s in sel]) | |
| J[j] = X; errs.append(e) | |
| S = {"left": (5, 7, 9, 11, 13, 15), "right": (6, 8, 10, 12, 14, 16)} | |
| arm, front = S.get(side, S["right"]), S["left" if side == "right" else "right"] | |
| m = {"views": len(Ps), "reproj_px": round(float(np.mean(errs)), 2) if errs else None, | |
| "joints": [[None if not np.isfinite(c) else round(float(c), 3) for c in J[j]] for j in range(17)]} | |
| if np.isfinite(J[[arm[0], arm[1], arm[2]]]).all(): | |
| m["elbow_angle_deg"] = round(angle3(J[arm[0]], J[arm[1]], J[arm[2]]), 1) | |
| if np.isfinite(J[[front[3], front[4], front[5]]]).all(): | |
| m["front_knee_angle_deg"] = round(angle3(J[front[3]], J[front[4]], J[front[5]]), 1) | |
| if np.isfinite(J[[5, 6, 11, 12]]).all(): | |
| v = (J[5] + J[6]) / 2 - (J[11] + J[12]) / 2 | |
| m["trunk_lateral_tilt_deg"] = round(float(np.degrees(np.arctan2(abs(v[0]), v[2]))), 1) | |
| m["trunk_forward_tilt_deg"] = round(float(np.degrees(np.arctan2(v[1], v[2]))), 1) | |
| if np.isfinite(J[arm[2]]).all(): | |
| m["wrist_height_m"] = round(float(J[arm[2]][2]), 2) | |
| if np.isfinite(J[[15, 16]]).all(): | |
| m["feet_apart_m"] = round(float(np.linalg.norm(J[15] - J[16])), 2) | |
| return m | |
| def _camera_cache(R): | |
| p = R / "multiview" / "cameras.json" | |
| return p, (json.load(open(p)) if p.exists() else {}) | |
| def run_multiview(final, sources, cfg, R, cal_map, roles_desc, force=False): | |
| mcfg = cfg.get("multiview") or {} | |
| sessions = mcfg.get("sessions") or [] | |
| if not sessions: | |
| return [] | |
| tol = float(mcfg.get("match_tolerance_s", 0.25)) | |
| by_path = {Path(s["path"]).as_posix(): s for s in sources} | |
| by_src = defaultdict(list) | |
| for d in final: | |
| by_src[d["source_id"]].append(d) | |
| cam_path, cam_cache = _camera_cache(R) | |
| records = [] | |
| for sess in sessions: | |
| sid = sess["id"] | |
| views = {} | |
| for cam, f in sess["views"].items(): | |
| key = Path(cfg["paths"]["datasets"], f).as_posix() | |
| src = by_path.get(key) | |
| if src: | |
| views[cam] = src | |
| else: | |
| print(f" ! multiview {sid}: {f} not found among ingested videos") | |
| if len(views) < 2: | |
| continue | |
| ref = sess.get("reference") or sorted(views)[0] | |
| sync_p = R / "multiview" / sid / "sync.json" | |
| sync = json.load(open(sync_p)) if sync_p.exists() and not force else {} | |
| ref_rel = [t for _, t in _release_times(by_src[views[ref]["source_id"]])] | |
| shifts = {ref: {"shift_s": 0.0, "matches": len(ref_rel), "method": "reference"}} | |
| for cam, src in views.items(): | |
| if cam == ref: | |
| continue | |
| audio = sync.get(cam, {}).get("audio_shift_s") | |
| if audio is None and mcfg.get("use_audio", True) and cam not in sync: | |
| from audio import av_offset | |
| res = av_offset(absp(views[ref]["path"]), absp(src["path"])) | |
| audio = None if not res or res["confidence"] < 0.3 else -res["offset_s"] | |
| v_rel = [t for _, t in _release_times(by_src[src["source_id"]])] | |
| s, n, how = estimate_shift(ref_rel, v_rel, tol, audio) | |
| shifts[cam] = {"shift_s": s, "matches": n, "method": how, "audio_shift_s": audio} | |
| write_json(sync_p, shifts) | |
| # camera calibration (3D) per view | |
| cams = {} | |
| for cam, src in views.items(): | |
| cal = cal_map.get(src["source_id"]) | |
| if not cal: | |
| continue | |
| import hashlib | |
| ck = cal["calibration_id"] + "|" + hashlib.md5(json.dumps([cal.get("points_px"), cal.get("named_px"), | |
| cal.get("extra_px"), cal.get("focal_px")], | |
| sort_keys=True).encode()).hexdigest()[:10] | |
| if ck not in cam_cache or force: | |
| cc = calibrate_camera(cal, (src["width"], src["height"]), (cal.get("focal_px") or None)) | |
| cam_cache[ck] = cc | |
| if cam_cache[ck]: | |
| cams[cam] = dict(cam_cache[ck], calibration_id=cal["calibration_id"]) | |
| # match deliveries across views | |
| items = [] | |
| for cam, src in views.items(): | |
| if shifts[cam]["shift_s"] is None: | |
| continue | |
| for d, t in _release_times(by_src[src["source_id"]]): | |
| items.append((t + shifts[cam]["shift_s"], cam, d)) | |
| items.sort(key=lambda x: x[0]) | |
| groups, used = [], set() | |
| for i, (t, cam, d) in enumerate(items): | |
| if id(d) in used: | |
| continue | |
| g = {cam: (t, d)}; used.add(id(d)) | |
| for t2, cam2, d2 in items[i + 1:]: | |
| if t2 - t > tol: | |
| break | |
| if cam2 not in g and id(d2) not in used: | |
| g[cam2] = (t2, d2); used.add(id(d2)) | |
| groups.append(g) | |
| for k, g in enumerate(groups, 1): | |
| mid = f"{sid}_D{k:04d}" | |
| vlist = [] | |
| for cam, (t, d) in sorted(g.items()): | |
| vlist.append({"camera_id": cam, "d": d, "shift": shifts[cam]["shift_s"], "P": cams.get(cam, {}).get("P"), | |
| "dir": R / "deliveries" / d["delivery_id"]}) | |
| t_rel = float(np.median([t for t, _ in g.values()])) | |
| fused = {} | |
| for e in EVENTS: | |
| per = {v["camera_id"]: round(_sess_time(v["d"], v["d"]["events"][e]["t_clip"], v["shift"]) - t_rel, 4) | |
| for v in vlist if e in v["d"]["events"]} | |
| if per: | |
| vals = list(per.values()) | |
| fused[e] = {"t_rel_release_s": round(float(np.median(vals)), 4), "per_view": per, | |
| "spread_ms": round((max(vals) - min(vals)) * 1000, 1), "views": len(per)} | |
| arms = [(v["d"].get("bowler") or {}).get("bowling_arm") for v in vlist] | |
| arms = [a for a in arms if a] | |
| side = max(set(arms), key=arms.count) if arms else "right" | |
| rec = {"mv_delivery_id": mid, "session_id": sid, "reference_camera": ref, "n_views": len(vlist), | |
| "views": [{"camera_id": v["camera_id"], "role": roles_desc.get(v["camera_id"], v["camera_id"]), | |
| "delivery_id": v["d"]["delivery_id"], "source_id": v["d"]["source_id"], | |
| "shift_s": v["shift"], "clip": v["d"]["media"].get("clip"), | |
| "annotated": v["d"]["media"].get("annotated"), | |
| "window_start_session_s": round(_sess_time(v["d"], 0.0, v["shift"]), 4), | |
| "time_scale": v["d"]["window"]["time_scale"], "calibrated_3d": bool(v["P"])} for v in vlist], | |
| "release_session_s": round(t_rel, 4), | |
| "release_spread_ms": round((max(t for t, _ in g.values()) - min(t for t, _ in g.values())) * 1000, 1), | |
| "events_fused": fused, "bowling_arm": side} | |
| b3 = ball_3d(vlist, t_rel) | |
| if b3: | |
| rec["ball_3d"] = b3 | |
| p_rel = pose_3d(vlist, t_rel, side) | |
| if p_rel: | |
| rec["bowler_3d_release"] = p_rel | |
| ffc = fused.get("front_foot_contact") | |
| if ffc: | |
| p_ffc = pose_3d(vlist, t_rel + ffc["t_rel_release_s"], side) | |
| if p_ffc: | |
| rec["bowler_3d_ffc"] = p_ffc | |
| rec["provenance"] = prov("deterministic_rule", f"multiview_v1:{cfg['project']['pipeline_version']}", None, | |
| f"{len(vlist)} views, sync {', '.join(shifts[c]['method'] for c in g)}") | |
| records.append(rec) | |
| summary = {"mv_delivery_id": mid, "session_id": sid, "n_views": len(vlist), | |
| "cameras": [v["camera_id"] for v in vlist]} | |
| if b3: | |
| summary.update({k: b3.get(k) for k in ("speed_kmh", "release_xyz", "bounce_xyz", "length_from_batter_stumps_m")}) | |
| for v in vlist: | |
| v["d"]["multiview"] = dict(summary, camera_id=v["camera_id"]) | |
| rec_cams = {c: {k: cams[c][k] for k in ("focal_px", "reprojection_px", "position_m", "points_used", "calibration_id")} | |
| for c in cams} | |
| write_json(R / "multiview" / sid / "session.json", {"session_id": sid, "reference": ref, "sync": shifts, | |
| "cameras": rec_cams, "views": {c: s["source_id"] for c, s in views.items()}, | |
| "deliveries": len(groups), "created_at": now_iso()}) | |
| for r in records: | |
| if r["session_id"] == sid: | |
| r["cameras"] = rec_cams | |
| r["sync"] = shifts | |
| write_json(cam_path, cam_cache) | |
| for r in records: | |
| write_json(R / "multiview" / r["session_id"] / f"{r['mv_delivery_id']}.json", r) | |
| write_jsonl(R / "jsonl" / "multiview_deliveries.jsonl", records) | |
| return records | |