File size: 4,087 Bytes
14c58d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
"""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"}