"""Stage 4 - turn final (automatic + reviewed) deliveries into SFT records. Answers are generated from measured or reviewed fields by templates, never invented. Section 7.6: factual description, expert interpretation and counterfactual advice are different answer_types and never mixed in one answer. Outputs (results/jsonl/): deliveries.jsonl one row per delivery: automatic values + reviewer edits merged sft_records.jsonl one row per Q/A, with grounding, confidence, provenance, rights sft_chat.jsonl the same pairs in chat format for a video-LLM trainer """ import hashlib from common import EVENT_NAMES, write_jsonl ARM = {"right": "right-arm", "left": "left-arm"} CONF = {"high": 0.9, "medium": 0.7, "low": 0.5} ORDER = ["run_up_start", "back_foot_contact", "front_foot_contact", "ball_release", "followthrough_end", "ball_bounce", "batter_trigger_start", "bat_ball_contact", "shot_followthrough_end"] def _pick(options, key): return options[int(hashlib.md5(key.encode()).hexdigest(), 16) % len(options)] def _t(t): return f"{t:.2f} s" def _state(*provs): states = {(p or {}).get("review_state", "unreviewed") for p in provs} return "corrected" if "corrected" in states else ("verified" if states == {"verified"} else "unreviewed") def qa_for_delivery(d, cfg): """Yield (task, question, answer, answer_type, confidence, grounding, review_state).""" did, ev, po, lab = d["delivery_id"], d.get("events", {}), d.get("posture", {}), d.get("labels", {}) arm = (d.get("bowler") or {}).get("bowling_arm") rel, ffc, bfc = ev.get("ball_release"), ev.get("front_foot_contact"), ev.get("back_foot_contact") bounce, contact = ev.get("ball_bounce"), ev.get("bat_ball_contact") slow = d["window"]["time_scale"] > 1 P = lambda e: (e or {}).get("provenance") yield ("view", _pick(["What kind of camera view is this cricket clip?", "Describe the camera setup in this clip."], did), f"This is {d['view_description']}.", "dataset_label", 1.0, {"category": d["category"]}, "verified") if rel and arm: yield ("bowling_arm", _pick(["Is this a right-arm or left-arm bowler?", "Which arm does the bowler bowl with?"], did), f"{ARM[arm].capitalize()}. The {arm} arm goes over the top at release, about {_t(rel['t_clip'])} into the clip.", "measured_fact", rel["confidence"], {"bowling_arm": arm, "ball_release_t_clip": rel["t_clip"]}, _state(P(rel))) yield ("release_time", _pick(["At what moment does the bowler release the ball?", "When is the ball released?"], did), f"The ball is released at about {_t(rel['t_clip'])} into the clip" + (" (clip time; the video is slowed down)." if slow else "."), "measured_fact", rel["confidence"], {"ball_release_t_clip": rel["t_clip"]}, _state(P(rel))) present = sorted((e for e in ORDER if e in ev), key=lambda e: ev[e]["t_clip"]) if len(present) >= 3: parts = [f"{EVENT_NAMES[e].lower()} at {_t(ev[e]['t_clip'])}" for e in present] yield ("event_timeline", "List the key moments of this delivery with their times.", "In clip time: " + "; ".join(parts) + ".", "measured_fact", min(ev[e]["confidence"] for e in present), {e: ev[e]["t_clip"] for e in present}, _state(*[P(ev[e]) for e in present])) if rel and ffc: ts, real = d["window"]["time_scale"], d["window"]["time_scale_verified"] stride = (f"; back foot lands at {_t(bfc['t_clip'])}, front foot at {_t(ffc['t_clip'])}" if bfc else f"; front foot lands at {_t(ffc['t_clip'])}") timing = f" Front-foot contact to release takes about {(rel['t_clip'] - ffc['t_clip']) / ts * 1000:.0f} ms in real time." if real else "" yield ("phases", "Break the bowling action into phases with timestamps.", f"Run-up and gather{(' from ' + _t(ev['run_up_start']['t_clip'])) if 'run_up_start' in ev else ''}{stride}; " f"release at {_t(rel['t_clip'])}; follow-through" f"{(' until ' + _t(ev['followthrough_end']['t_clip'])) if 'followthrough_end' in ev else ' after release'}.{timing}", "measured_fact", min(rel["confidence"], ffc["confidence"]), {k: ev[k]["t_clip"] for k in ORDER if k in ev}, _state(P(rel), P(ffc))) leg = po.get("front_leg", {}) kf, kr = po.get("front_knee_angle_ffc_deg", {}).get("value"), po.get("front_knee_angle_release_deg", {}).get("value") if leg.get("value") and kf is not None and kr is not None: yield ("front_leg", "Is the front leg braced or flexing between front-foot contact and release?", f"It looks {leg['value']}: the front knee goes from about {kf:.0f}° at front-foot contact to about " f"{kr:.0f}° at release (180° is straight). This is a 2D estimate from one camera view.", "derived_label", leg["confidence"], {"front_knee_angle_ffc_deg": kf, "front_knee_angle_release_deg": kr}, _state(P(leg))) tilt = po.get("trunk_tilt_release_deg", {}) if tilt.get("value") is not None: word = "fairly upright" if tilt["value"] < 15 else ("leaning noticeably" if tilt["value"] < 30 else "leaning strongly") yield ("trunk_tilt", "How upright is the bowler's trunk at release?", f"The trunk is {word}, about {tilt['value']:.0f}° from vertical in this view (2D estimate; camera angle affects it).", "measured_fact", tilt["confidence"], {"trunk_tilt_release_deg": tilt["value"]}, _state(P(tilt))) el = po.get("elbow_angle_release_deg", {}) if el.get("value") is not None: yield ("bowling_arm_shape", "How straight does the bowling arm look at release?", f"In this view the bowling arm looks {'close to straight' if el['value'] >= 160 else 'visibly bent'} " f"(about {el['value']:.0f}° at the elbow). This is a 2D video estimate, not a legality assessment.", "measured_fact", el["confidence"] * 0.8, {"elbow_angle_release_deg": el["value"]}, _state(P(el))) if bounce: yield ("bounce", "Does the ball pitch within the clip? If so, when?", f"Yes. The ball pitches at about {_t(bounce['t_clip'])}.", "measured_fact", bounce["confidence"], {"ball_bounce_t_clip": bounce["t_clip"]}, _state(P(bounce))) pitch = d.get("measurements", {}).get("pitch") if pitch and pitch.get("valid"): bm = pitch["bounce_m"] line = f", {pitch['actual_line'].replace('_', ' ')} line" if pitch.get("actual_line") else "" yield ("pitch_location", "Where did the ball pitch?", f"About {bm['length_from_batter_stumps_m']:.1f} m from the batter's stumps, which is a " f"{pitch['actual_length'].replace('_', ' ')} length{line}. Measured on the pitch plane from a single " "calibrated camera.", "measured_fact", 0.7 * (bounce or {}).get("confidence", 0.5) + 0.3, {**bm, "calibration_id": pitch["calibration_id"]}, _state(P(bounce))) if contact: yield ("bat_contact", "Does the batter hit the ball? When?", f"Yes, bat and ball meet at about {_t(contact['t_clip'])}.", "measured_fact", contact["confidence"], {"bat_ball_contact_t_clip": contact["t_clip"]}, _state(P(contact))) L = lambda k: (lab.get(k) or {}).get("value") if L("shot_type"): yield ("shot_type", "What shot does the batter play?", f"A {L('shot_type').replace('_', ' ')}.", "human_label", 1.0, {"shot_type": L("shot_type")}, "verified") if L("delivery_type"): yield ("delivery_type", "What type of delivery is this?", f"A {L('delivery_type').replace('_', ' ')} delivery.", "human_label", 1.0, {"delivery_type": L("delivery_type")}, "verified") if L("target_length") and L("actual_length"): hit = L("target_length") == L("actual_length") yield ("execution_length", "Did the bowler hit the intended length?", f"{'Yes' if hit else 'No'}: the target was {L('target_length').replace('_', ' ')} and the ball pitched " f"{L('actual_length').replace('_', ' ')}.", "measured_fact", 0.8, {"target_length": L("target_length"), "actual_length": L("actual_length")}, "verified") c = d.get("coach") if c: cf = CONF.get(c.get("confidence"), 0.6) obs = " ".join(x.strip() for x in [c.get("observation", ""), c.get("evidence", ""), c.get("consequence", "")] if x and x.strip()) yield ("coach_observation", "What would a coach point out about this delivery?", obs, "expert_interpretation", cf, {"coach_confidence": c.get("confidence")}, "verified") if (c.get("correction") or "").strip(): yield ("coach_correction", "What should the player change?", c["correction"].strip(), "expert_advice", cf, {"coach_confidence": c.get("confidence")}, "verified") if (c.get("cf_question") or "").strip() and (c.get("cf_answer") or "").strip(): yield ("counterfactual", c["cf_question"].strip(), c["cf_answer"].strip(), "counterfactual", cf, {"coach_confidence": c.get("confidence")}, "verified") sp = d.get("speech") if sp and sp.get("segments"): lines = "; ".join(f'"{x["text"]}" (at {_t(x["t_clip_start"])})' for x in sp["segments"][:4]) yield ("speech", "What is said during this delivery, and when?", lines, "transcribed_speech", 0.6, {"segments": len(sp["segments"])}, "unreviewed") bat = d.get("bat") if bat and bat.get("backlift_top"): bl = bat["backlift_top"] how = "detected by the bat model" if bat["source"] == "model" else "estimated from the batter's hands (no bat detector yet)" txt = f"The backlift peaks at {_t(bl['t_clip'])} with the bat about {bl['angle_deg']:.0f}° from hanging straight down" if bat.get("peak_swing"): txt += f"; the downswing is fastest at {_t(bat['peak_swing']['t_clip'])} (about {bat['peak_swing']['angular_speed_deg_s']:.0f}°/s in this view)" if bat.get("at_contact"): txt += f"; at contact the bat is about {bat['at_contact']['angle_deg']:.0f}° from vertical" yield ("bat_movement", "Describe the batter's bat movement.", txt + f". 2D, {how}.", "measured_fact" if bat["source"] == "model" else "estimated_measure", max(bat["confidence"], 0.45) if bat["source"] == "model" else 0.45, {"backlift_top_t_clip": bl["t_clip"], "source": bat["source"]}, "unreviewed") g = (d.get("measurements") or {}).get("ground") or {} if g.get("bowler_front_foot"): f = g["bowler_front_foot"] where = (f"about {abs(f['behind_popping_crease_cm']):.0f} cm behind the popping crease" if f["behind_popping_crease_cm"] >= 0 else f"about {abs(f['behind_popping_crease_cm']):.0f} cm beyond the popping crease (possible no-ball)") yield ("front_foot_position", "Where does the bowler's front foot land relative to the crease?", f"The front ankle lands {where}. Measured on the calibrated pitch from the ankle keypoint, so allow about 15 cm.", "measured_fact", 0.5, {k: f[k] for k in ("y_from_bowler_popping_m", "behind_popping_crease_cm")}, "unreviewed") if g.get("batter_movement"): yield ("batter_movement", "Does the batter go forward or back?", {"front_foot": "Forward, onto the front foot", "back_foot": "Back, onto the back foot", "stayed": "Neither: the feet stay roughly where they started"}[g["batter_movement"]] + f" (feet moved {g['batter_feet_move_m']:+.2f} m towards the bowler on the calibrated pitch).", "measured_fact", 0.55, {"batter_feet_move_m": g["batter_feet_move_m"]}, "unreviewed") rp = d.get("review_points") if rp: def verdict(rows): done = [r for r in rows if r["status"] in ("match", "mismatch")] return done, " ".join(f"{r['aspect']}: expected {r['expected']}, performed {r['performed']} " f"({'as expected' if r['status'] == 'match' else 'not as expected'})." for r in done) done, text = verdict(rp["bowler"]) if done: ok = all(r["status"] == "match" for r in done) yield ("bowler_review", "Did the bowler execute the intended delivery?", ("Yes. " if ok else "Not fully. ") + text, "execution_review", 0.8, {r["aspect"]: r["status"] for r in done}, "verified") done, text = verdict(rp["batter"]) if done: ok = all(r["status"] == "match" for r in done) yield ("batter_review", "Did the batter respond as expected to this delivery?", ("Yes. " if ok else "Not fully. ") + text + " Expected responses come from provisional coaching rules.", "coaching_rule_review", 0.7, {r["aspect"]: r["status"] for r in done}, "verified") trg, se = ev.get("batter_trigger_start"), ev.get("shot_followthrough_end") if trg or contact or se: parts = [p for p in [f"trigger movement starts at {_t(trg['t_clip'])}" if trg else None, f"bat meets ball at {_t(contact['t_clip'])}" if contact else None, f"the shot's follow-through ends at {_t(se['t_clip'])}" if se else None] if p] yield ("batter_timeline", "What does the batter do, and when?", "The batter's " + "; ".join(parts) + ".", "measured_fact", min(x["confidence"] for x in (trg, contact, se) if x), {k: ev[k]["t_clip"] for k in ("batter_trigger_start", "bat_ball_contact", "shot_followthrough_end") if k in ev}, _state(P(trg), P(contact), P(se))) acts = [] if ffc: acts.append(f"lands the front foot at {_t(ffc['t_clip'])}") if rel: acts.append(f"releases the ball at {_t(rel['t_clip'])}" + (f" with a {leg['value']} front leg" if leg.get("value") else "")) if bounce: acts.append(f"the ball pitches at {_t(bounce['t_clip'])}" + (f" ({pitch['actual_length'].replace('_', ' ')})" if pitch and pitch.get("actual_length") else "")) if contact: acts.append(f"the batter makes contact at {_t(contact['t_clip'])}") body = (", ".join(acts[:-1]) + ", and " + acts[-1]) if len(acts) > 1 else (acts[0] if acts else "is seen bowling") who = f"A {ARM[arm]} bowler" if arm else "The bowler" vd = d["view_description"] yield ("caption", _pick(["Describe this delivery.", "Summarise what happens in this clip."], did + "c"), f"{vd[0].upper()}{vd[1:]}. {who} {body}.", "composed_from_measurements", min([x["confidence"] for x in (rel, ffc) if x] or [0.5]), {}, _state(P(rel), P(ffc))) def mv_pairs(r): """Questions that need ALL views of one delivery (3D, cross-view timing).""" fz, b3, p3 = r.get("events_fused", {}), r.get("ball_3d"), r.get("bowler_3d_release") cams = ", ".join(f"{v['camera_id']} ({v['role']})" for v in r["views"]) yield ("mv_views", "From which camera angles is this delivery filmed?", f"{r['n_views']} synchronised views: {cams}.", "dataset_label", 1.0, {"cameras": [v["camera_id"] for v in r["views"]]}) rel_order = [e for e in ("run_up_start", "back_foot_contact", "front_foot_contact", "ball_bounce", "bat_ball_contact") if e in fz] if rel_order: parts = [] for e in rel_order: ms = fz[e]["t_rel_release_s"] * 1000 parts.append(f"{EVENT_NAMES[e].lower()} {abs(ms):.0f} ms {'before' if ms < 0 else 'after'} release") worst = max(fz[e]["spread_ms"] for e in rel_order) yield ("mv_timeline", "Using all views, give the timing of the key moments relative to release.", "; ".join(parts) + f". The views agree to within {worst:.0f} ms.", "measured_fact", 0.8 if worst < 70 else 0.5, {e: fz[e]["t_rel_release_s"] for e in rel_order}) if b3: if b3.get("speed_kmh"): yield ("mv_speed", "How fast is the ball bowled?", f"About {b3['speed_kmh']:.0f} km/h out of the hand, from the ball's 3D path in {r['n_views']} calibrated views.", "measured_fact_3d", 0.75, {"speed_kmh": b3["speed_kmh"]}) x, y, z = b3["release_xyz"]; bx, by, _ = b3["bounce_xyz"] yield ("mv_release_point", "Where is the ball released, in 3D?", f"About {z:.2f} m above the ground and {y:+.2f} m from the bowler's popping crease " f"({'beyond' if y > 0 else 'behind'} it), {abs(x):.2f} m {'right' if x > 0 else 'left'} of the middle-stump line seen from behind the bowler.", "measured_fact_3d", 0.75, {"release_xyz": b3["release_xyz"]}) yield ("mv_bounce", "Where does the ball pitch?", f"{b3['length_from_batter_stumps_m']:.1f} m from the batter's stumps and {abs(bx):.2f} m " f"{'right' if bx > 0 else 'left'} of the middle-stump line (seen from behind the bowler), from 3D triangulation.", "measured_fact_3d", 0.75, {"bounce_xyz": b3["bounce_xyz"]}) if p3 and p3.get("elbow_angle_deg") is not None: txt = f"In 3D the bowling arm is at {p3['elbow_angle_deg']:.0f}° at the elbow at release" if p3.get("front_knee_angle_deg") is not None: txt += f", the front knee at {p3['front_knee_angle_deg']:.0f}°" if p3.get("trunk_lateral_tilt_deg") is not None: txt += f", and the trunk leans {p3['trunk_lateral_tilt_deg']:.0f}° sideways" yield ("mv_release_posture", "Describe the bowler's body at release using all camera views.", txt + ". This is a video-based 3D estimate, not a legality test.", "measured_fact_3d", 0.7, {k: p3.get(k) for k in ("elbow_angle_deg", "front_knee_angle_deg", "trunk_lateral_tilt_deg")}) def build_sft(deliveries, sources, cfg, out_dir, mv_records=None): src = {s["source_id"]: s for s in sources} min_c = cfg["sft"]["min_confidence"] rows, chat = [], [] for d in deliveries: if d["qc"]["status"] == "fail" or not d.get("media", {}).get("clip"): continue s = src[d["source_id"]] for task, q, a, atype, conf, grounding, state in qa_for_delivery(d, cfg): if conf < min_c or not a: continue rid = f"{d['delivery_id']}_{task}" rec = {"id": rid, "delivery_id": d["delivery_id"], "source_id": d["source_id"], "sample_id": (d.get("multiview") or {}).get("mv_delivery_id") or d["delivery_id"], "view": (d.get("multiview") or {}).get("camera_id"), "experiment_id": d.get("experiment_id"), "task": task, "question": q, "answer": a, "answer_type": atype, "confidence": round(float(conf), 3), "grounding": grounding, "media": {"video": d["media"]["clip"], "annotated_video": d["media"].get("annotated"), "clip_start_s": d["window"]["start_s"], "clip_end_s": d["window"]["end_s"]}, "context": {"category": d["category"], "time_scale": d["window"]["time_scale"], "qc_status": d["qc"]["status"], "annotation_status": d["annotation_status"]}, "provenance": {"generator": "template_v2", "pipeline_version": cfg["project"]["pipeline_version"], "models": d["provenance"]["models"], "ontology_version": d["ontology_version"], "measurement_space": "image_2d", "review_state": state}, "rights": {"training_allowed": s["rights"]["training_allowed"], "rights_basis": s["rights"]["rights_basis"]}} rows.append(rec) chat.append({"id": rid, "messages": [ {"role": "system", "content": cfg["sft"]["system_prompt"]}, {"role": "user", "content": [{"type": "video", "video": d["media"]["clip"]}, {"type": "text", "text": q}]}, {"role": "assistant", "content": a}], "metadata": {"delivery_id": d["delivery_id"], "answer_type": atype, "confidence": rec["confidence"], "review_state": state, "training_allowed": s["rights"]["training_allowed"]}}) # one multi-view sample per delivery seen from several cameras (all clips in one record) mv_rows = [] for r in mv_records or []: clips = [{"type": "video", "video": v["clip"], "camera": v["camera_id"], "role": v["role"]} for v in r["views"] if v.get("clip")] if len(clips) < 2: continue allowed = all(src[v["source_id"]]["rights"]["training_allowed"] for v in r["views"]) for task, q, a, atype, conf, grounding in mv_pairs(r): rid = f"{r['mv_delivery_id']}_{task}" rec = {"id": rid, "sample_id": r["mv_delivery_id"], "delivery_id": r["mv_delivery_id"], "session_id": r["session_id"], "views": [v["delivery_id"] for v in r["views"]], "task": task, "question": q, "answer": a, "answer_type": atype, "confidence": round(float(conf), 3), "grounding": grounding, "media": {"videos": clips, "sync_shift_s": {v["camera_id"]: v["shift_s"] for v in r["views"]}}, "context": {"n_views": r["n_views"], "qc_status": "pass"}, "provenance": {"generator": "template_mv_v1", "pipeline_version": cfg["project"]["pipeline_version"], "measurement_space": "world_3d" if "3d" in atype else "multi_view", "review_state": "unreviewed"}, "rights": {"training_allowed": allowed, "rights_basis": "all views' source rights"}} rows.append(rec); mv_rows.append(rec) chat.append({"id": rid, "messages": [ {"role": "system", "content": cfg["sft"]["system_prompt"]}, {"role": "user", "content": clips + [{"type": "text", "text": q}]}, {"role": "assistant", "content": a}], "metadata": {"sample_id": r["mv_delivery_id"], "answer_type": atype, "confidence": rec["confidence"], "n_views": r["n_views"], "training_allowed": allowed}}) write_jsonl(out_dir / "deliveries.jsonl", deliveries) write_jsonl(out_dir / "sft_records.jsonl", rows) write_jsonl(out_dir / "sft_chat.jsonl", chat) return rows