File size: 19,452 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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
"""Human-in-the-loop layer (standard sections 7.3, 8.3, 9.2).

Reviewers never edit measurements.json. Every edit is appended to
results/annotations/review.jsonl with who/when/previous value, and `merge_delivery`
overlays the latest edit per field on the automatic values. So the automatic
proposal, the correction and the history are all kept (raw stays immutable).

Record kinds
  event        field=<event name>, value={"t_clip": s} or null (= event absent)
  event_verify field=<event name>, value=true      (automatic value confirmed)
  label        field=<label name>, value=<vocab value or player id>
  coach        value={observation, evidence, consequence, correction, confidence,
                      cf_question, cf_answer}
  status       field=annotation_status, value=human_verified|expert_gold|...
  calibration  source_id or delivery_id, value={points_px, camera_end, frame_size}
"""
import copy
import json
import re
import uuid
from collections import Counter, defaultdict
from pathlib import Path

import numpy as np

from common import now_iso, prov
from events import front_leg_label, posture_features

KINDS = {"event", "event_verify", "label", "coach", "status", "calibration", "ball_label", "bat_label", "checklist"}
PLAYER_ID = re.compile(r"^P\d{3,6}$")


def review_path(R):
    return Path(R) / "annotations" / "review.jsonl"


def load_review(R):
    p = review_path(R)
    if not p.exists():
        return []
    return [json.loads(l) for l in open(p) if l.strip()]


def load_people():
    from common import CODE, load_yaml
    p = CODE / "registry" / "people.yaml"
    return load_yaml(p) if p.exists() else {"enforce": False, "people": {}, "roles": {}}


def allowed(rec, people):
    """Role check (section 11.3). Returns an error string or None."""
    if not people.get("enforce"):
        return None
    who = people["people"].get(rec["annotator_id"])
    if not who:
        return f"unknown reviewer ID {rec['annotator_id']!r}: add it to code/registry/people.yaml"
    perms = set(people["roles"].get(who["role"], []))
    key = rec["kind"] + (f":{rec['value']}" if rec["kind"] == "status" else "")
    if rec["kind"] not in perms and key not in perms:
        return f"role {who['role']!r} may not write {key}"
    return None


def validate(rec, onto, people=None):
    """Return an error string, or None if the record is acceptable."""
    if rec.get("kind") not in KINDS:
        return f"unknown kind {rec.get('kind')!r}"
    if not rec.get("annotator_id") or not re.match(r"^[A-Za-z0-9_.-]{2,40}$", rec["annotator_id"]):
        return "annotator_id required (letters, digits, _ . -)"
    if not (rec.get("delivery_id") or (rec["kind"] in ("calibration", "checklist") and rec.get("source_id"))
            or rec["kind"] in ("ball_label", "bat_label")):
        return "delivery_id required"
    if people is not None:
        e = allowed(rec, people)
        if e:
            return e
    k, f, v = rec["kind"], rec.get("field"), rec.get("value")
    if k in ("event", "event_verify"):
        if f not in onto["events"]:
            return f"unknown event {f!r}"
        if k == "event" and v is not None and not (isinstance(v, dict) and isinstance(v.get("t_clip"), (int, float))
                                                    and v["t_clip"] >= 0):
            return "event value must be {t_clip: seconds} or null"
    if k == "label":
        groups = {name: vocab for g in onto["labels"].values() for name, vocab in g.items()}
        if f in ("bowler_id", "batter_id"):
            if v not in (None, "") and not PLAYER_ID.match(str(v)):
                return "player ids must be pseudonymous like P0023 (never names)"
        elif f not in groups:
            return f"unknown label {f!r}"
        elif v not in (None, "") and v not in onto["vocab"][groups[f]]:
            return f"{v!r} is not in vocabulary {groups[f]}"
    if k == "status" and v not in onto["vocab"]["annotation_status"]:
        return f"status must be one of {onto['vocab']['annotation_status']}"
    if k == "coach":
        if not isinstance(v, dict) or not (v.get("observation") or "").strip():
            return "coach note needs at least an observation"
        if v.get("confidence") not in onto["vocab"]["confidence"]:
            return "coach confidence must be high, medium or low"
    if k == "ball_label":
        if not f or not isinstance(v, dict):
            return "ball_label needs field=<frame id> and a value"
        if v.get("visible") is False:
            return None
        if not all(isinstance(v.get(c), (int, float)) and v[c] >= 0 for c in ("x", "y")):
            return "ball_label needs x and y in pixels, or visible: false"
    if k == "bat_label":
        if not f or not isinstance(v, dict):
            return "bat_label needs field=<frame id> and a value"
        if v.get("visible") is not False:
            pts = [v.get("handle"), v.get("toe")]
            if not all(isinstance(p, list) and len(p) == 2 and all(isinstance(c, (int, float)) for c in p) for p in pts):
                return "bat_label needs handle [x, y] and toe [x, y], or visible: false"
    if k == "checklist" and not isinstance(v, dict):
        return "checklist value must be an object of item -> true/false/n.a."
    if k == "calibration":
        from geometry3d import WORLD
        pts = (v or {}).get("points_px")
        named = (v or {}).get("named_px") or {}
        if pts is not None and not (isinstance(pts, list) and len(pts) == 4 and all(isinstance(p, list) and len(p) == 2 for p in pts)):
            return "points_px must be the 4 crease corners"
        if any(n not in WORLD or not (isinstance(p, list) and len(p) == 2) for n, p in named.items()):
            return "named_px must map known pitch points to [x, y]"
        ground = (4 if pts else 0) + sum(1 for n in named if not n.endswith("_top") and n not in (
            ["bowler_left", "bowler_right", "batter_left", "batter_right"] if pts else []))
        if ground < 4:
            return "calibration needs at least 4 points on the ground (crease corners or stump bases)"
        if v.get("camera_end") not in onto["vocab"]["camera_end"]:
            return "camera_end must be bowler or batter"
    return None


def stamp(rec, onto):
    rec = dict(rec)
    rec.setdefault("id", uuid.uuid4().hex[:12])
    rec["created_at"] = now_iso()
    rec["ontology_version"] = onto["ontology_version"]
    return rec


def _latest(records):
    """Latest record per (kind, field)."""
    out = {}
    for r in sorted(records, key=lambda r: r["created_at"]):
        out[(r["kind"], r.get("field"))] = r
    return out


def _per_annotator(records):
    """(kind, field) -> {annotator: latest value}, for agreement and disputes."""
    out = defaultdict(dict)
    for r in sorted(records, key=lambda r: r["created_at"]):
        out[(r["kind"], r.get("field"))][r["annotator_id"]] = r["value"]
    return out


def _disagree(kind, values, fps):
    vals = list(values.values())
    if len(vals) < 2:
        return False
    if kind == "event":
        ts = [None if v is None else v["t_clip"] for v in vals]
        if None in ts:
            return len(set(t is None for t in ts)) > 1
        return max(ts) - min(ts) > 2.0 / fps
    return len({json.dumps(v, sort_keys=True) for v in vals}) > 1


def calibrations(review):
    """source_id/delivery_id -> latest calibration (with a stable calibration_id)."""
    out, count = {}, Counter()
    for r in sorted((r for r in review if r["kind"] == "calibration"), key=lambda r: r["created_at"]):
        scope = r.get("delivery_id") or r["source_id"]
        count[scope] += 1
        out[scope] = dict(r["value"], calibration_id=f"CAL_{scope}_{count[scope]:02d}",
                          created_by=r["annotator_id"], created_at=r["created_at"], status="direct",
                          ref_delivery_id=r["value"].get("ref_delivery_id") or r.get("delivery_id"))
    return out


def _human(r, state):
    return prov("annotator", r.get("ontology_version"), 1.0, r.get("id"), r["annotator_id"], state)


def merge_delivery(m, records, calib_map, onto, cfg, delivery_dir):
    """Automatic measurements + reviewer edits -> final delivery record."""
    d = copy.deepcopy(m)
    latest = _latest(records)
    per_ann = _per_annotator(records)
    w = d["window"]
    corrected, verified, disputed = [], [], []

    for (kind, field), r in latest.items():
        if kind == "event":
            auto = d["events"].get(field)
            if r["value"] is None:
                if auto:
                    d.setdefault("removed_events", {})[field] = auto
                    d["events"].pop(field, None)
                    corrected.append(field)
                continue
            tc = round(float(r["value"]["t_clip"]), 3)
            ev = {"t_clip": tc, "t_video": round(w["first_frame"] / w["fps"] + tc, 3),
                  "frame": int(w["first_frame"] + round(tc * w["fps"])), "confidence": 1.0,
                  "provenance": _human(r, "corrected")}
            if auto:
                ev["auto_t_clip"] = auto["t_clip"]
                ev["correction_ms_real"] = round(abs(tc - auto["t_clip"]) / w["time_scale"] * 1000, 1)
                for k in ("xy_px", "turn_deg"):
                    if k in auto and abs(tc - auto["t_clip"]) < 1.5 / w["fps"]:
                        ev[k] = auto[k]
            if _disagree("event", per_ann[("event", field)], w["fps"]):
                ev["provenance"]["review_state"] = "disputed"
                ev["alternatives"] = {a: (v or {}).get("t_clip") for a, v in per_ann[("event", field)].items()}
                disputed.append(field)
            d["events"][field] = ev
            corrected.append(field)
    for (kind, field), r in latest.items():
        if kind == "event_verify" and field in d["events"] and field not in corrected:
            d["events"][field]["provenance"]["review_state"] = "verified"
            d["events"][field]["provenance"]["reviewed_by"] = r["annotator_id"]
            verified.append(field)

    # Bounce pixel for a corrected bounce: nearest tracked ball point (if any)
    b = d["events"].get("ball_bounce")
    if b and "xy_px" not in b and d["ball"]["points"]:
        q = min(d["ball"]["points"], key=lambda q: abs(q["t_clip"] - b["t_clip"]))
        if abs(q["t_clip"] - b["t_clip"]) <= 2.0 / w["fps"]:
            b["xy_px"] = [q["x"], q["y"]]

    # Posture follows corrected release / front-foot times
    pose_file = Path(delivery_dir) / "bowler_pose.npz"
    if pose_file.exists() and {"ball_release", "front_foot_contact"} & set(corrected) and "ball_release" in d["events"]:
        z = np.load(pose_file)
        side = str(z["side"])
        idx = lambda e: int(np.argmin(np.abs(z["frames"] - d["events"][e]["frame"])))
        i_ffc = idx("front_foot_contact") if "front_foot_contact" in d["events"] else None
        po = posture_features(z["kpts"], idx("ball_release"), i_ffc, side)
        kf = po.get("front_knee_angle_ffc_deg", {}).get("value")
        kr = po.get("front_knee_angle_release_deg", {}).get("value")
        po["front_leg"] = {"value": front_leg_label(kf, kr), "confidence": 0.8, "space": "image_2d"}
        for v in po.values():
            v["provenance"] = prov("deterministic_rule", "posture_at_reviewed_events", v.get("confidence"),
                                   "pose:bowler at human-corrected event frames")
        d["posture"] = po

    # Labels (intent / actual / context / player ids)
    d["labels"] = {}
    for (kind, field), r in latest.items():
        if kind == "label" and r["value"] not in (None, ""):
            d["labels"][field] = {"value": r["value"], "provenance": _human(r, "corrected")}
            if _disagree("label", per_ann[("label", field)], w["fps"]):
                d["labels"][field]["provenance"]["review_state"] = "disputed"
                d["labels"][field]["alternatives"] = per_ann[("label", field)]
                disputed.append(field)
    for pid in ("bowler_id", "batter_id"):
        if pid in d["labels"]:
            d.setdefault("identity", {})[pid] = d["labels"][pid]["value"]

    # Pitch calibration -> bounce in metres -> line / length (section 8.2)
    from pitch import derive_line_length
    cal = calib_map.get(d["delivery_id"]) or calib_map.get(d["source_id"])
    d["measurements"] = {}
    if cal and cal.get("ref_delivery_id") and cal["ref_delivery_id"] != d["delivery_id"] \
            and calib_map.get(d["delivery_id"]) is None:
        from camera_motion import transfer_calibration
        cal = transfer_calibration(cal, Path(delivery_dir).parent, d["delivery_id"])
    if cal and cal.get("status") == "invalid":
        d["calibration"] = {k: cal.get(k) for k in ("calibration_id", "camera_end", "created_by", "created_at", "status", "reason")}
        cal = None
    if cal:
        d["calibration"] = {k: cal.get(k) for k in ("calibration_id", "camera_end", "created_by", "created_at",
                                                     "points_px", "named_px", "status", "reason", "shift_px")}
        b = d["events"].get("ball_bounce")
        from pitch import ground_points
        if b and b.get("xy_px") and len(ground_points(cal)) >= 4:
            hand = d["labels"].get("batter_handedness", {}).get("value", "unknown")
            res = derive_line_length(b["xy_px"], cal, hand, onto)
            res["provenance"] = prov("deterministic_rule", f"{onto['ontology_version']}+pitch_homography",
                                     None, f"ball_bounce xy_px + {cal['calibration_id']}")
            d["measurements"]["pitch"] = res
            for lab in ("actual_length", "actual_line"):
                if res.get(lab) and lab not in d["labels"]:
                    d["labels"][lab] = {"value": res[lab], "provenance": res["provenance"]}

    # Bat geometry and movement (7.4) + feet on the calibrated pitch
    from bat import bat_motion, ground_measures, load_equipment
    bp, wp_ = Path(delivery_dir) / "batter_pose.npz", Path(delivery_dir) / "bowler_pose.npz"
    batter = dict(np.load(bp)) if bp.exists() else None
    bowler = dict(np.load(wp_)) if wp_.exists() else None
    if batter is not None:
        det = None
        if "bat_pts" in batter:
            det = {"pts": batter["bat_pts"], "conf": batter["bat_conf"]}
        bm = bat_motion(batter["t"], batter["kpts"], w["time_scale"], w["first_frame"] / w["fps"], d["events"],
                        load_equipment(), d.get("labels", {}).get("batter_id", {}).get("value"), det)
        if bm:
            bm["provenance"] = prov("model" if bm["source"] == "model" else "deterministic_rule",
                                    "bat_v1:" + bm["source"], bm["confidence"], "pose:batter hands and forearms"
                                    if bm["source"] != "model" else "bat keypoint model")
            d["bat"] = bm
    if cal:
        from pitch import ground_points, homography, to_pitch
    if cal and len(ground_points(cal)) >= 4:
        Hm = homography(cal)
        gm = ground_measures(bowler, batter, d["events"], lambda xy: to_pitch(Hm, xy), w,
                             (d.get("bowler") or {}).get("bowling_arm"))
        if gm:
            gm["provenance"] = prov("deterministic_rule", f"pitch_homography+pose:{cal['calibration_id']}", None,
                                    "ankle keypoints mapped to the pitch plane")
            d["measurements"]["ground"] = gm
            if gm.get("batter_movement") and "batter_movement" not in d["labels"]:
                d["labels"]["batter_movement"] = {"value": gm["batter_movement"], "provenance": gm["provenance"]}

    # Coach layer (7.5) - kept apart from measured facts
    c = latest.get(("coach", None)) or latest.get(("coach", "note"))
    if c:
        d["coach"] = {**c["value"], "provenance": prov("coach_expert", onto["ontology_version"], None, c.get("id"),
                                                       c["annotator_id"], "verified")}

    s = latest.get(("status", "annotation_status"))
    if s:
        status = s["value"]
    elif corrected or any((v.get("provenance") or {}).get("source_type") == "annotator" for v in d["labels"].values()) or c:
        status = "human_corrected"
    elif verified:
        status = "human_verified"
    else:
        status = "auto"
    d["annotation_status"] = status
    d["review"] = {"corrected_events": corrected, "verified_events": verified, "disputed": disputed, "edits": len(records),
                   "last_edit": max((r["created_at"] for r in records), default=None),
                   "annotators": sorted({r["annotator_id"] for r in records})}
    d["ontology_version"] = onto["ontology_version"]
    return d


def priority(d, cat_counts):
    """Active-learning score: which delivery should a human look at next, and why."""
    if d["review"].get("disputed"):
        return 0.9, ["reviewers disagree on: " + ", ".join(d["review"]["disputed"])]
    if (d.get("calibration") or {}).get("status") == "invalid":
        return 0.7, ["camera moved since calibration: recalibrate this delivery"]
    if d.get("annotation_status") not in (None, "auto"):
        return 0.0, ["already reviewed"]
    score, why = 0.0, []
    if d["qc"]["status"] == "fail":
        return 0.05, ["failed QC: " + "; ".join(d["qc"]["reasons"][:2])]
    if d["qc"]["status"] == "warn":
        score += 0.3; why.append("QC warning: " + "; ".join(d["qc"]["reasons"][:2]))
    for e in ("ball_release", "front_foot_contact", "ball_bounce"):
        ev = d["events"].get(e)
        if ev is None:
            score += 0.2; why.append(f"no {e.replace('_', ' ')} found")
        elif ev["confidence"] < 0.6:
            score += 0.6 - ev["confidence"]; why.append(f"low confidence {e.replace('_', ' ')} ({ev['confidence']:.2f})")
    n = cat_counts.get(d["category"], 1)
    if n <= max(cat_counts.values()) / 3:
        score += 0.1; why.append(f"rare video type ({d['category']}, {n} deliveries)")
    return round(score, 3), why or ["routine check"]


def attach_speech(d, R):
    """Transcript segments (if run_all transcribed the source) for this delivery."""
    from audio import segments_in_window
    p = Path(R) / "audio" / f"{d['source_id']}_transcript.json"
    if not p.exists():
        return
    tr = json.load(open(p))
    if tr.get("status") != "ok":
        return
    w = d["window"]
    segs = segments_in_window(tr, w["first_frame"] / w["fps"], w["first_frame"] / w["fps"] + w["duration_video_s"])
    if segs:
        d["speech"] = {"segments": segs,
                       "provenance": prov("model_asr", tr.get("model"), None, f"audio/{d['source_id']}_transcript.json")}


def merge_all(deliveries, R, onto, cfg):
    review = load_review(R)
    by_d = defaultdict(list)
    for r in review:
        if r.get("delivery_id") and r["kind"] not in ("calibration", "ball_label", "bat_label", "checklist"):
            by_d[r["delivery_id"]].append(r)
    cal = calibrations(review)
    out = [merge_delivery(m, by_d.get(m["delivery_id"], []), cal, onto, cfg,
                          Path(R) / "deliveries" / m["delivery_id"]) for m in deliveries]
    from review_points import review_points
    for d in out:
        attach_speech(d, R)
        d["review_points"] = review_points(d, onto)
    cats = Counter(d["category"] for d in out)
    for d in out:
        d["review"]["priority"], d["review"]["why_selected"] = priority(d, cats)
    return out, review, cal