CRICKET / code /diagnose.py
d9993r's picture
Add files using upload-large-folder tool
14c58d8 verified
Raw History Blame Contribute Delete
9.69 kB
#!/usr/bin/env python3
"""Explain why a video produced few or no delivery windows.
python code/diagnose.py SRC_YT_0004
Prints what the pose model saw and why release candidates were rejected,
suggests config values, and saves a plot to results/qa/diagnose_<source>.png.
Reuses the pass-1 pose cache, so it is fast after the first run."""
import json
import shutil
import subprocess
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import numpy as np # noqa: E402
from common import absp, load_config, read_json, rel # noqa: E402
from events import SIDES, _speed, torso_length, wrist_height # noqa: E402
from segment import load_or_scan, pass1_stride, windows_from_scan # noqa: E402
def main():
if len(sys.argv) < 2:
raise SystemExit("usage: python code/diagnose.py SRC_YT_0004")
sid = sys.argv[1]
cfg = load_config()
R = cfg["_paths"]["results"]
src = next((s for s in read_json(R / "registry" / "sources.json") if s["source_id"] == sid), None)
if not src:
raise SystemExit(f"{sid} not in results/registry/sources.json")
print(f"{sid}: {src['title']}")
print(f" file {src['path']} {src['width']}x{src['height']} {src['fps']} fps "
f"{src['frame_count']} frames {src['duration_s']} s time_scale {src['time_scale']}")
if shutil.which("ffprobe"):
out = subprocess.run(["ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries",
"stream=codec_name,avg_frame_rate,r_frame_rate:stream_side_data=rotation:stream_tags=rotate",
"-of", "json",
str(absp(src["path"]))], capture_output=True, text=True).stdout
st = (json.loads(out or "{}").get("streams") or [{}])[0]
rot = (st.get("tags") or {}).get("rotate") or next(
(d.get("rotation") for d in st.get("side_data_list") or [] if "rotation" in d), 0)
print(f" codec {st.get('codec_name')} avg_frame_rate {st.get('avg_frame_rate')} "
f"r_frame_rate {st.get('r_frame_rate')} rotation {rot}")
from vision import build_vision
vision = None
if not (R / "segments" / f"{sid}_pose.pkl").exists():
vision = build_vision("ultralytics", cfg)
elif cfg["models"].get("device", "auto") != "cpu":
from vision import pick_device
if pick_device(cfg["models"].get("device", "auto"))[0] == "cpu":
for sec, vals in (cfg.get("cpu_overrides") or {}).items():
cfg[sec].update(vals)
scan, cached = load_or_scan(src, cfg, vision, R / "segments")
seg = windows_from_scan(src, scan, cfg)
exp = (src["frame_count"] or 0) // scan["stride"]
hz_video = src["fps"] / scan["stride"]
hz_real = hz_video * src["time_scale"]
print(f"\n sampling: every {scan['stride']} frame(s) = {hz_video:.1f} samples per video second "
f"= {hz_real:.0f} per real second (time_scale {src['time_scale']})")
if hz_real < 40:
print(" ! under ~40 samples per real second the moment the wrist is above the head can fall between\n"
" samples, so the wrist looks lower than it really gets. Use stride 1 and a lower min_wrist_height.")
print(f"\n pass 1 {'(cached)' if cached else ''}: analysed {scan['frames_analysed']} frames "
f"(expected about {exp}); people in {scan['frames_with_people']}; "
f"{len(scan['tracks'])} tracks; {len(scan['cuts'])} cuts")
if scan["frames_analysed"] < 0.8 * exp:
print(" ! OpenCV stopped reading early - the codec may not be supported. Convert with:\n"
f" ffmpeg -i \"{src['path']}\" -c:v libx264 -crf 18 fixed.mp4 (then replace the file)")
print(f" release search: {json.dumps(seg['release_search'])}")
print(f" windows found: {len(seg['windows'])}")
ts = src["time_scale"]
rc = cfg["release"]
tracks = sorted(scan["tracks"].items(), key=lambda kv: -len(kv[1]["t"]))[:5]
print("\n longest tracks (per side: max wrist height in torso lengths, max wrist speed in torso/real s):")
best_h, best_v, plots = [], [], []
for key, tr in tracks:
k = tr["k"]
tl = torso_length(k)
line = f" track {key}: {len(tr['t'])} samples, {tr['t'][0]:.1f}-{tr['t'][-1]:.1f} s, torso {tl:.0f}px"
if not np.isfinite(tl):
print(line + " (shoulders/hips never confident - pose too unreliable)")
continue
for side, s in SIDES.items():
h = wrist_height(k, side, tl)
sp = _speed(tr["t"] / ts, k[:, s["wr"], :2], np.isfinite(h), tl)
mh = np.nanmax(h) if np.isfinite(h).any() else float("nan")
mv = np.nanmax(sp) if np.isfinite(sp).any() else float("nan")
wc = float(np.mean(k[:, s["wr"], 2]))
line += f"\n {side:5s}: max height {mh:5.2f} max speed {mv:6.1f} wrist conf {wc:.2f}"
if np.isfinite(mh):
best_h.append(mh); best_v.append(mv)
plots.append((key, side, tr["t"], h, sp))
print(line)
print("\n suggestions:")
if not best_h:
print(" - the pose model rarely sees a full body; try pose_imgsz 960 for this folder")
else:
if max(best_h) < rc["min_wrist_height"]:
print(f" - wrist never rises above {rc['min_wrist_height']}: set release.min_wrist_height: "
f"{max(0.4, round(max(best_h) * 0.85, 2))}")
v = [x for x in best_v if np.isfinite(x)]
if v and max(v) < rc["min_wrist_speed"]:
print(f" - wrist never moves faster than {rc['min_wrist_speed']}: set release.min_wrist_speed: "
f"{max(2.0, round(max(v) * 0.7, 1))} (or time_scale for this video is wrong)")
rs = seg["release_search"]
if rs.get("rej_not_from_low", 0) and rs.get("rej_not_from_low", 0) >= rs.get("peaks", 1) / 2:
print(" - most peaks rejected because the arm was never seen low before them: "
"set release.from_below: 0.5")
print(" after editing code/config.yaml: python code/run_all.py --sources", sid, "--force (reuses the pose cache)")
contact_sheet(src, scan, R / "qa" / f"diagnose_{sid}_frames.jpg")
try:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 1, figsize=(12, 6), sharex=True)
for key, side, t, h, sp in plots[:6]:
axes[0].plot(t, h, label=f"{key} {side}")
axes[1].plot(t, sp, label=f"{key} {side}")
axes[0].axhline(rc["min_wrist_height"], color="k", ls="--", lw=1)
axes[1].axhline(rc["min_wrist_speed"], color="k", ls="--", lw=1)
for w in seg["windows"]:
for ax in axes:
ax.axvline(w["release_t_pass1"], color="red", lw=1)
axes[0].set_ylabel("wrist height (torso)"); axes[1].set_ylabel("wrist speed (torso/real s)")
axes[1].set_xlabel("video time (s)"); axes[0].legend(fontsize=7, ncol=3)
out = R / "qa" / f"diagnose_{sid}.png"
out.parent.mkdir(parents=True, exist_ok=True)
fig.tight_layout(); fig.savefig(out, dpi=110)
print(f"\n plot: {rel(out)} (dashed = thresholds, red = detected releases)")
except ImportError:
pass
def contact_sheet(src, scan, out):
"""12 frames from the most active track with its skeleton drawn, so you can see
what the pose model sees (is the arm found at the top? is the video sideways?)."""
import cv2
from events import SKELETON
cand = [(k, v) for k, v in scan["tracks"].items() if len(v["t"]) >= 10]
if not cand:
return
def activity(tr):
k = tr["k"]
return float(np.nanmax(np.linalg.norm(np.diff(k[:, [9, 10], :2], axis=0), axis=2))) if len(k) > 1 else 0
key, tr = max(cand, key=lambda kv: activity(kv[1]))
tl = torso_length(tr["k"])
hs = {sd: wrist_height(tr["k"], sd, tl) for sd in SIDES}
idx = np.linspace(0, len(tr["t"]) - 1, 12).astype(int)
cap = cv2.VideoCapture(str(absp(src["path"])))
tiles = []
for i in idx:
cap.set(cv2.CAP_PROP_POS_FRAMES, int(round(tr["t"][i] * src["fps"])))
ok, img = cap.read()
if not ok:
continue
k = tr["k"][i]
for a, b in SKELETON:
if k[a, 2] > 0.3 and k[b, 2] > 0.3:
cv2.line(img, tuple(map(int, k[a, :2])), tuple(map(int, k[b, :2])), (255, 255, 255), 3)
for j in (9, 10):
col = (0, 220, 0) if k[j, 2] > 0.3 else (0, 0, 255)
cv2.circle(img, tuple(map(int, k[j, :2])), 10, col, 3)
x1, y1, x2, y2 = map(int, tr["box"][i])
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 200, 255), 2)
txt = f"t={tr['t'][i]:.2f}s hL={hs['left'][i]:.2f} hR={hs['right'][i]:.2f}"
img = cv2.resize(img, (480, int(480 * img.shape[0] / img.shape[1])))
cv2.rectangle(img, (0, 0), (480, 26), (0, 0, 0), -1)
cv2.putText(img, txt, (6, 19), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (255, 255, 255), 1, cv2.LINE_AA)
tiles.append(img)
cap.release()
if not tiles:
return
h = max(t.shape[0] for t in tiles)
tiles = [cv2.copyMakeBorder(t, 0, h - t.shape[0], 0, 0, cv2.BORDER_CONSTANT) for t in tiles]
while len(tiles) % 4:
tiles.append(np.zeros_like(tiles[0]))
sheet = np.vstack([np.hstack(tiles[r:r + 4]) for r in range(0, len(tiles), 4)])
out.parent.mkdir(parents=True, exist_ok=True)
cv2.imwrite(str(out), sheet, [cv2.IMWRITE_JPEG_QUALITY, 85])
print(f" frames: {rel(out)} (track {key}; green circle = wrist found, red = wrist missing)")
if __name__ == "__main__":
main()