"""Shared helpers. Every path is resolved from the project root, which is the parent of the folder this file lives in (CRICKET-SFT-DATA/code/common.py).""" import hashlib import json import os import re from pathlib import Path import cv2 import yaml ROOT = Path(__file__).resolve().parent.parent CODE = ROOT / "code" def load_config(path=None): cfg = yaml.safe_load(open(path or CODE / "config.yaml")) cfg["_paths"] = {k: ROOT / v for k, v in cfg["paths"].items()} return cfg def rel(p) -> str: """Path relative to the project root, with forward slashes (portable in JSON).""" return Path(os.path.relpath(Path(p).resolve(), ROOT)).as_posix() def absp(relpath) -> Path: return ROOT / relpath def sha256_file(path, chunk=1 << 20): h = hashlib.sha256() with open(path, "rb") as f: while True: b = f.read(chunk) if not b: break h.update(b) return h.hexdigest() def write_json(path, obj): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") with open(tmp, "w") as f: json.dump(obj, f, indent=2, default=_jsonable) tmp.replace(path) def read_json(path): return json.load(open(path)) def write_jsonl(path, rows): path = Path(path) path.parent.mkdir(parents=True, exist_ok=True) with open(path, "w") as f: for r in rows: f.write(json.dumps(r, default=_jsonable, ensure_ascii=False) + "\n") def read_jsonl(path): return [json.loads(l) for l in open(path) if l.strip()] def _jsonable(o): try: import numpy as np if isinstance(o, np.integer): return int(o) if isinstance(o, np.floating): return None if o != o else round(float(o), 4) if isinstance(o, np.ndarray): return o.tolist() except ImportError: pass if isinstance(o, Path): return o.as_posix() raise TypeError(f"not JSON serialisable: {type(o)}") def probe_video(path): cap = cv2.VideoCapture(str(path)) if not cap.isOpened(): raise RuntimeError(f"cannot open video {path}") fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 if not (1 < fps < 1000): fps = 30.0 n = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) cap.release() return {"fps": round(float(fps), 3), "frame_count": n, "width": w, "height": h, "duration_s": round(n / fps, 2) if n > 0 else None} def clean_title(name: str) -> str: t = Path(name).stem t = re.sub(r"^vidssave\.com\s*", "", t) t = re.sub(r"\s*\d{3,4}P$", "", t) return t.replace("_", " ").strip() def r4(x): return None if x is None or x != x else round(float(x), 4) def now_iso(): from datetime import datetime, timezone return datetime.now(timezone.utc).isoformat(timespec="seconds") def prov(source_type, source_version, confidence=None, parent=None, created_by="foundry.pipeline", review_state="unreviewed"): """Label provenance record (standard section 8.3).""" return {"source_type": source_type, "source_version": source_version, "created_by": created_by, "confidence": None if confidence is None else round(float(confidence), 3), "review_state": review_state, "created_at": now_iso(), "parent_artifact": parent} def load_yaml(path): return yaml.safe_load(open(path)) def load_ontology(): return load_yaml(CODE / "ontology.yaml") def load_experiment(cfg): return load_yaml(CODE / cfg["project"]["experiment_file"]) EVENT_NAMES = {"run_up_start": "Run-up start", "back_foot_contact": "Back-foot contact", "front_foot_contact": "Front-foot contact", "ball_release": "Release", "ball_bounce": "Bounce", "batter_trigger_start": "Batter trigger", "bat_ball_contact": "Bat contact", "shot_followthrough_end": "Shot follow-through end", "followthrough_end": "Follow-through end"}