Download code/run_all.py from d9993r/CRICKET: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/d9993r/CRICKET/resolve/main/code/run_all.py
- Command line
-
hf download hf://datasets/d9993r/CRICKET/code/run_all.py
-
curl -L -o run_all.py https://huggingface.co/datasets/d9993r/CRICKET/resolve/main/code/run_all.py
12.2 kB
| #!/usr/bin/env python3 | |
| """Run the whole pipeline. Works from any directory; all paths come from code/config.yaml | |
| and are relative to the project root. | |
| python code/run_all.py # everything | |
| python code/run_all.py --stages sft,tables,release,web # rebuild outputs from results + review edits | |
| python code/run_all.py --sources SRC_YT_0004 --max-per-video 3 # quick look at one video | |
| python code/run_all.py --force # recompute instead of reusing results | |
| """ | |
| import argparse | |
| import shutil | |
| import sys | |
| import time | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from common import absp, load_config, load_experiment, load_ontology, read_json, rel, write_json # noqa: E402 | |
| def load_yaml_safe(p): | |
| import yaml | |
| return yaml.safe_load(open(p)) if Path(p).exists() else {} | |
| def apply_multiview_labels(final, mv_records, onto): | |
| """3D bounce (2+ cameras) beats a single-view estimate: set actual length/line from it | |
| unless a reviewer already labelled them.""" | |
| from common import prov | |
| from pitch import bucket | |
| by_mid = {r["mv_delivery_id"]: r for r in mv_records} | |
| for d in final: | |
| mv = d.get("multiview") | |
| r = by_mid.get((mv or {}).get("mv_delivery_id")) | |
| if not r or not r.get("ball_3d"): | |
| continue | |
| b = r["ball_3d"] | |
| p = prov("deterministic_rule", f"{onto['ontology_version']}+3d_triangulation", None, r["mv_delivery_id"]) | |
| th = onto["thresholds"] | |
| cur = d.setdefault("labels", {}) | |
| if (cur.get("actual_length") or {}).get("provenance", {}).get("source_type") != "annotator": | |
| ln = bucket(b["length_from_batter_stumps_m"], th["length_from_batter_stumps_m"]) | |
| if ln: | |
| cur["actual_length"] = {"value": ln, "provenance": p} | |
| hand = (cur.get("batter_handedness") or {}).get("value") | |
| if hand in ("right", "left") and (cur.get("actual_line") or {}).get("provenance", {}).get("source_type") != "annotator": | |
| off = -b["bounce_xyz"][0] if hand == "right" else b["bounce_xyz"][0] # world x = right, seen from behind the bowler | |
| li = bucket(off, th["line_offside_from_middle_stump_m"]) | |
| if li: | |
| cur["actual_line"] = {"value": li, "provenance": p} | |
| CODE_DIR = Path(__file__).resolve().parent | |
| STAGES = ["ingest", "segment", "analyze", "audio", "label", "sft", "tables", "evaluate", "release", "web"] | |
| POST = ["sft", "tables", "evaluate", "release", "web"] # cheap stages that only read results/ | |
| def bar(prefix): | |
| last = [-1] | |
| def f(x): | |
| p = int(x * 100) | |
| if p != last[0]: | |
| last[0] = p | |
| print(f"\r {prefix} {p:3d}%", end="", flush=True) | |
| return f | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--stages", default=",".join(STAGES)) | |
| ap.add_argument("--backend", default="ultralytics", choices=["ultralytics", "fake", "fake_mv"]) | |
| ap.add_argument("--sources", help="comma-separated source_ids to process") | |
| ap.add_argument("--max-per-video", type=int, default=0, help="analyse at most N deliveries per video") | |
| ap.add_argument("--force", action="store_true", help="recompute windows and deliveries") | |
| ap.add_argument("--rescan", action="store_true", help="also redo the pass-1 pose scan (slow)") | |
| ap.add_argument("--retranscribe", action="store_true", help="redo speech transcription only") | |
| ap.add_argument("--config") | |
| a = ap.parse_args() | |
| stages = [s.strip() for s in a.stages.split(",")] | |
| cfg = load_config(a.config) | |
| import hashlib, json | |
| cfg["_config_hash"] = hashlib.sha256(json.dumps({k: v for k, v in cfg.items() if not k.startswith("_")}, | |
| sort_keys=True, default=str).encode()).hexdigest()[:12] | |
| onto, exp = load_ontology(), load_experiment(cfg) | |
| cfg["_experiment"] = exp | |
| R = cfg["_paths"]["results"] | |
| t_start = time.time() | |
| print("ingest") | |
| if "ingest" in stages: | |
| from ingest import run_ingest | |
| sources = run_ingest(cfg) | |
| else: | |
| sources = read_json(R / "registry" / "sources.json") | |
| todo = [s for s in sources if not a.sources or s["source_id"] in a.sources.split(",")] | |
| vision = None | |
| if "segment" in stages or "analyze" in stages: | |
| from vision import build_vision | |
| vision = build_vision(a.backend, cfg) | |
| segments = {} | |
| print("segment (pass 1: cuts + release candidates)") | |
| for s in sources: | |
| p = R / "segments" / f"{s['source_id']}.json" | |
| if s in todo and "segment" in stages and (a.force or a.rescan or not p.exists()): | |
| from segment import load_or_scan, windows_from_scan | |
| print(f" {s['source_id']} {s['title'][:60]}") | |
| scan, cached = load_or_scan(s, cfg, vision, R / "segments", a.rescan, progress=bar("scanning")) | |
| seg = windows_from_scan(s, scan, cfg) | |
| rs = seg["release_search"] | |
| print(f"\r {'reused pose cache, ' if cached else ''}{seg['frames_analysed']} frames analysed, " | |
| f"people in {seg['frames_with_people']}, {seg['n_tracks']} tracks, {len(seg['cuts'])} cuts") | |
| print(f" release search: {rs.get('peaks', 0)} high-wrist peaks, " | |
| f"{rs.get('rej_not_from_low', 0)} rejected (arm not from low), " | |
| f"{rs.get('rej_too_slow', 0)} rejected (too slow) -> {len(seg['windows'])} delivery windows") | |
| if not seg["windows"]: | |
| print(f" tip: python code/diagnose.py {s['source_id']}") | |
| write_json(p, seg) | |
| for old in (R / "deliveries").glob(f"{s['session_id']}_D*"): | |
| shutil.rmtree(old) # windows changed -> old deliveries are stale | |
| if p.exists(): | |
| segments[s["source_id"]] = read_json(p) | |
| print("analyze (pass 2: pose, events, ball, QC, clips)") | |
| if "analyze" in stages: | |
| from analyze import analyze_window, ffmpeg_ok | |
| if not ffmpeg_ok(): | |
| print(" ! ffmpeg not found - clips will not be exported (conda install -c conda-forge ffmpeg)") | |
| for s in todo: | |
| wins = segments.get(s["source_id"], {}).get("windows", []) | |
| if a.max_per_video: | |
| wins = wins[:a.max_per_video] | |
| for k, w in enumerate(wins, 1): | |
| did = f"{s['session_id']}_D{k:04d}" | |
| out = R / "deliveries" / did | |
| if (out / "measurements.json").exists() and not a.force: | |
| continue | |
| m = analyze_window(s, w, did, cfg, vision, out) | |
| ev = m["events"] | |
| short = {"run_up_start": "run", "back_foot_contact": "bfc", "front_foot_contact": "ffc", | |
| "ball_release": "rel", "followthrough_end": "ft", "ball_bounce": "bounce", | |
| "batter_trigger_start": "trig", "bat_ball_contact": "bat", "shot_followthrough_end": "shot"} | |
| evs = " ".join(f"{short[k]}={ev[k]['t_clip']}" for k in short if k in ev) | |
| print(f" {did} {m['qc']['status']:<4} arm={m['bowler'].get('bowling_arm')} {evs} " | |
| f"{'; '.join(m['qc']['reasons'][:2])}") | |
| sessions = {s["session_id"] for s in sources} | |
| deliveries = [read_json(p) for p in sorted((R / "deliveries").glob("*/measurements.json")) | |
| if p.parent.name.rsplit("_D", 1)[0] in sessions] | |
| old = [m["delivery_id"] for m in deliveries if "first_frame" not in m.get("window", {})] | |
| if old: | |
| print(f" ! {len(old)} deliveries were made by an older pipeline version and are skipped; " | |
| "rerun with --force to upgrade them") | |
| deliveries = [m for m in deliveries if m["delivery_id"] not in old] | |
| if "audio" in stages and cfg.get("audio", {}).get("transcribe"): | |
| from audio import transcribe | |
| acfg = cfg.get("audio", {}) | |
| print("audio: transcribing speech (faster-whisper)") | |
| for s in todo: | |
| outp = R / "audio" / f"{s['source_id']}_transcript.json" | |
| if outp.exists() and not (a.force or a.retranscribe): | |
| continue | |
| res = transcribe(absp(s["path"]), acfg, outp) | |
| print(f" {s['source_id']}: {res.get('status')} {len(res.get('segments', []))} segments {res.get('reason', '')}") | |
| if "label" in stages: | |
| from labeling import extract_label_frames | |
| items = extract_label_frames(deliveries, cfg, R, cfg.get("labeling", {}).get("frames_per_delivery", 4), a.force) | |
| print(f"label: {len(items)} frames ready in the Ball labels tab") | |
| final, sft_rows, report, rel_info, evaluation = deliveries, [], {}, None, None | |
| if any(st in stages for st in POST): | |
| from review import merge_all | |
| final, review, cal = merge_all(deliveries, R, onto, cfg) | |
| print(f" merged {len(review)} review edits, {len(cal)} pitch calibrations") | |
| mv_records = [] | |
| if (cfg.get("multiview") or {}).get("sessions"): | |
| from multiview import run_multiview | |
| from review_points import review_points | |
| dev = (load_yaml_safe(CODE_DIR / "registry" / "devices.yaml") or {}).get("devices", {}) | |
| roles = {k: v.get("view", k) for k, v in dev.items()} | |
| mv_records = run_multiview(final, sources, cfg, R, cal, roles, force=a.force) | |
| apply_multiview_labels(final, mv_records, onto) | |
| for d in final: | |
| if d.get("multiview"): | |
| d["review_points"] = review_points(d, onto) | |
| print(f"multiview: {len(mv_records)} multi-view deliveries from {len(cfg['multiview']['sessions'])} sessions, " | |
| f"{sum(1 for r in mv_records if r.get('ball_3d'))} with a 3D ball track") | |
| cfg["_mv_records"] = mv_records | |
| print("sft") | |
| if any(st in stages for st in ("sft", "release", "web")): | |
| from sft import build_sft | |
| sft_rows = build_sft(final, sources, cfg, R / "jsonl", cfg.get("_mv_records") or []) | |
| print(f" {len(sft_rows)} Q/A pairs from {len(final)} deliveries -> {rel(R / 'jsonl')}/") | |
| print("tables") | |
| if any(st in stages for st in ("tables", "release", "web")): | |
| from tables import build_tables | |
| report = build_tables(final, onto, R, cfg.get("_mv_records") or []) | |
| print(f" Tier-1 table: {report['rows']} rows, schema {'OK' if report['passed'] else str(report['n_errors']) + ' errors'}, " | |
| f"completeness {report['tier1_completeness']:.0%} -> {rel(R / 'tables')}/") | |
| print("evaluate") | |
| if "evaluate" in stages or "web" in stages: | |
| from evaluate import build_evaluation | |
| from review import load_review | |
| evaluation = build_evaluation(final, load_review(R), onto, R) | |
| tm = evaluation["timing"].get("ball_release", {}) | |
| print(f" reviewed {evaluation['reviewed_deliveries']}, gold {evaluation['gold_deliveries']}, " | |
| f"release timing MAE {tm.get('mae_ms')} ms over {tm.get('scored')} reviewed") | |
| print("release") | |
| if "release" in stages or "web" in stages: | |
| from release import build_release | |
| rel_info = build_release(final, sources, sft_rows, onto, exp, cfg, R, report) | |
| print(f" {rel_info['release_id']}: train {rel_info['counts']['train']}, val {rel_info['counts']['val']}, " | |
| f"test {rel_info['counts']['test']}, leaks {len(rel_info['leaks'])}") | |
| print("web") | |
| if "web" in stages: | |
| from build_web import build_web | |
| page = build_web(cfg, sources, final, sft_rows, segments, onto, exp, rel_info, report, evaluation) | |
| print(f" open {rel(page)} (or: python code/serve.py to review and correct in the browser)") | |
| qc = {k: sum(1 for m in final if m["qc"]["status"] == k) for k in ("pass", "warn", "fail")} | |
| summary = {"videos": len(sources), "deliveries": len(final), "qc": qc, "sft_pairs": len(sft_rows), | |
| "release": rel_info and rel_info["release_id"], "runtime_s": round(time.time() - t_start, 1), | |
| "backend": a.backend} | |
| write_json(R / "qa" / "run_summary.json", summary) | |
| print("done:", summary) | |
| if __name__ == "__main__": | |
| main() | |