CRICKET / code /release.py
d9993r's picture
Add files using upload-large-folder tool
14c58d8 verified
Raw History Blame Contribute Delete
11.4 kB
"""Stage 6 - dataset release builder (standard section 13, Appendix D).
Splits by SOURCE VIDEO (= session), never by frame or camera view, so near-duplicate
footage cannot leak between train and test. Writes manifests, per-split SFT JSONL,
a data card and an automatic Appendix-D readiness checklist.
With today's sources every record is training_allowed: false, so the build is
labelled release_kind = "dev_only": usable to test training code, not to ship."""
import hashlib
import json
from collections import Counter
from datetime import datetime
from common import write_json, write_jsonl
REQ_RIGHTS = ["source_id", "source_category", "provider", "rights_basis", "training_allowed", "commercial_use_allowed"]
def _split_groups(groups, gold_groups=()):
"""Deterministic group -> split, roughly 70/15/15 by delivery count.
Sources holding expert-gold deliveries go to test first, so the gold
evaluation set stays frozen and never leaks into training (section 13.2)."""
out = {g: "test" for g in gold_groups if g in groups}
order = sorted((g for g in groups if g not in out), key=lambda g: hashlib.md5(g.encode()).hexdigest())
total = sum(groups[g] for g in order) or 1
acc = 0
for i, g in enumerate(order):
frac = acc / total
if len(order) >= 3 and i == len(order) - 1 and "test" not in out.values(): # always have a test split
out[g] = "test"
elif len(order) >= 3 and i == len(order) - 2 and "val" not in out.values():
out[g] = "val"
else:
out[g] = "train" if frac < 0.7 else ("val" if frac < 0.85 else "test")
acc += groups[g]
return out
def build_release(deliveries, sources, sft_rows, onto, exp, cfg, R, schema_report):
src = {s["source_id"]: s for s in sources}
eligible = [d for d in deliveries if d["qc"]["status"] != "fail" and d.get("media", {}).get("clip")]
gkey = lambda d: (d.get("multiview") or {}).get("session_id") or d["source_id"] # all views of a session together
groups = Counter(gkey(d) for d in eligible)
gold_groups = {gkey(d) for d in eligible if d["annotation_status"] == "expert_gold"}
split_of_group = _split_groups(groups, gold_groups)
split = {d["delivery_id"]: split_of_group[gkey(d)] for d in eligible}
for r in cfg.get("_mv_records") or []: # multi-view samples follow their views
sp = {split.get(v["delivery_id"]) for v in r["views"]} - {None}
if len(sp) == 1:
split[r["mv_delivery_id"]] = sp.pop()
allowed = all(src[d["source_id"]]["rights"]["training_allowed"] for d in eligible) if eligible else False
kind = "train" if allowed else "dev_only"
# leakage checks
leaks = []
for g in groups:
ss = {split[d["delivery_id"]] for d in eligible if gkey(d) == g}
if len(ss) > 1:
leaks.append(f"source {g} appears in {sorted(ss)}")
sft_by_split = {"train": [], "val": [], "test": []}
for r in sft_rows:
if r["delivery_id"] in split:
sft_by_split[split[r["delivery_id"]]].append(r)
for sp, rows in sft_by_split.items():
bad = [r["id"] for r in rows if split[r["delivery_id"]] != sp]
if bad:
leaks.append(f"{len(bad)} SFT records in wrong split {sp}")
gold = [d["delivery_id"] for d in eligible if d["annotation_status"] == "expert_gold"]
gold_in_train = [g for g in gold if split[g] == "train"]
if gold_in_train:
leaks.append(f"{len(gold_in_train)} expert-gold deliveries fall in train (move or hold out their source)")
ver = cfg["project"]["pipeline_version"]
ids = sorted(split)
h = hashlib.sha256(json.dumps([ids, onto["ontology_version"], cfg.get("_config_hash"), ver,
sorted((r["id"], r["answer"]) for r in sft_rows if r["delivery_id"] in split)]).encode()).hexdigest()
release_id = f"DSV0-{kind.upper()}-{datetime.now():%Y%m%d}-{h[:8]}"
# Appendix D checklist
n = max(1, len(eligible))
with_cal = sum(1 for d in eligible if d.get("calibration"))
prov_ok = all(e.get("provenance") for d in eligible for e in d["events"].values()) and \
all(v.get("provenance") for d in eligible for v in (d.get("labels") or {}).values())
onto_versions = {d["ontology_version"] for d in eligible}
warns = sum(1 for d in eligible if d["qc"]["status"] == "warn")
t1 = schema_report.get("tier1_completeness", 0)
C = lambda item, status, detail: {"item": item, "status": status, "detail": detail}
checklist = [
C("Raw sources hashed and immutable", "ok" if all(s.get("sha256") for s in sources) else "fail",
f"{len(sources)} sources with sha256; originals never modified"),
C("Source-rights registry complete", "ok" if all(all(k in s["rights"] for k in REQ_RIGHTS) for s in sources) else "fail",
"all mandatory registry fields present" + ("" if allowed else "; training NOT allowed for these sources")),
C("Calibration / camera config versions present", "ok" if with_cal == len(eligible) and eligible else "warn",
f"{with_cal}/{len(eligible)} deliveries have a pitch calibration_id"),
C("Capture QC thresholds met or exceptions documented", "ok",
f"{len(deliveries) - len(eligible)} failed deliveries excluded; {warns} warnings kept with reasons"),
C("Required Tier-1 metadata completeness met", "ok" if t1 >= 0.99 else "warn",
f"{t1:.0%} of expected Tier-1 fields filled (target 99%)"),
C("Ontology version frozen for release", "ok" if len(onto_versions) <= 1 else "fail", ", ".join(sorted(onto_versions)) or "-"),
C("Annotation provenance populated", "ok" if prov_ok else "fail", "every event and label carries source_type/review_state"),
C("Gold subset reviewed", "ok" if gold else "warn", f"{len(gold)} expert_gold deliveries"),
C("Train/val/test leakage checks passed", "ok" if not leaks else "fail", "; ".join(leaks) or "split by source video"),
C("Challenge slices documented", "ok", "see data card"),
C("Data card completed", "ok", "data_card.md"),
C("Build code/config/version recorded", "ok", f"pipeline {ver}, config {cfg.get('_config_hash')}"),
C("Release tag/hash assigned", "ok", release_id),
C("Model team acceptance recorded", "manual", "record sign-off outside the pipeline"),
]
slices = {"video_type": Counter(d["category"] for d in eligible),
"bowling_arm": Counter((d.get("bowler") or {}).get("bowling_arm") or "unknown" for d in eligible),
"annotation_status": Counter(d["annotation_status"] for d in eligible),
"has_bounce": Counter("yes" if "ball_bounce" in d["events"] else "no" for d in eligible),
"has_bat_contact": Counter("yes" if "bat_ball_contact" in d["events"] else "no" for d in eligible),
"calibrated": Counter("yes" if d.get("calibration") else "no" for d in eligible)}
counts = {sp: sum(1 for v in split.values() if v == sp) for sp in ("train", "val", "test")}
answer_types = Counter(r["answer_type"] for r in sft_rows if r["delivery_id"] in split)
review_states = Counter(r["provenance"]["review_state"] for r in sft_rows if r["delivery_id"] in split)
out = R / "releases" / release_id
out.mkdir(parents=True, exist_ok=True)
for sp in ("train", "val", "test"):
write_jsonl(out / f"manifest_{sp}.jsonl",
[{"delivery_id": d["delivery_id"], "source_id": d["source_id"], "clip": d["media"]["clip"],
"annotated": d["media"].get("annotated"), "annotation_status": d["annotation_status"]}
for d in eligible if split[d["delivery_id"]] == sp])
write_jsonl(out / f"sft_{sp}.jsonl", sft_by_split[sp])
write_jsonl(out / f"multiview_{sp}.jsonl", [r for r in (cfg.get("_mv_records") or []) if split.get(r["mv_delivery_id"]) == sp])
write_jsonl(out / "gold_eval.jsonl", [{"delivery_id": g} for g in gold])
card = [f"# Data card: {release_id}", "",
f"Release kind: **{kind}**" + ("" if allowed else " (sources are not cleared for model training)"),
f"Experiment: {exp.get('experiment_id')} (protocol {exp.get('protocol_version')})",
f"Question: {exp.get('model_question', '').strip()}", f"Ontology: {onto['ontology_version']}",
f"Pipeline: {ver}, config {cfg.get('_config_hash')}", "",
"## Contents",
f"{len(eligible)} deliveries from {len(groups)} split groups (source videos or multi-view sessions); {sum(len(v) for v in sft_by_split.values())} SFT pairs.",
f"Split by source video: train {counts['train']}, val {counts['val']}, test {counts['test']}.", "",
"## Source mix"] + [f"- {g}: {src[g]['title']} ({n} deliveries, {src[g]['category']}, "
f"{'training allowed' if src[g]['rights']['training_allowed'] else 'not cleared for training'})"
for g, n in sorted(Counter(d["source_id"] for d in eligible).items())] + [
f"- multi-view session {r}: views of the same deliveries kept in one split" for r in sorted(
{(d.get("multiview") or {}).get("session_id") for d in eligible} - {None})] + ["",
"## Label provenance",
"Answer types: " + ", ".join(f"{k} {v}" for k, v in answer_types.most_common()),
"Review state of answers: " + ", ".join(f"{k} {v}" for k, v in review_states.most_common()), "",
"## Missingness (share of deliveries with the field)"] + \
[f"- {k}: {v:.0%}" for k, v in schema_report.get("completeness", {}).items() if k in schema_report.get("tier1_expected_fields", [])
or k in ("actual_length", "actual_line", "shot_type", "bat_ball_contact_ts")] + ["",
"## Recommended evaluation slices"] + [f"- {name}: " + ", ".join(f"{k} {v}" for k, v in c.items()) for name, c in slices.items()] + ["",
"## Known limitations and biases",
"- Found footage: no controlled variables, no experiment intent unless a reviewer entered it.",
"- All geometry is 2D from one camera; line/length only where a reviewer calibrated the pitch.",
"- No radar: speed is absent. Slow-motion time_scale may be unverified.",
"- Automatic events come from a COCO pose model and a COCO ball class not trained on cricket.", "",
"## Readiness checklist (Appendix D)"] + [f"- [{'x' if c['status'] == 'ok' else ' '}] {c['item']} ({c['status']}): {c['detail']}"
for c in checklist]
(out / "data_card.md").write_text("\n".join(card) + "\n")
info = {"release_id": release_id, "release_kind": kind, "hash": h, "created_at": datetime.now().isoformat(timespec="seconds"),
"counts": counts, "deliveries": len(eligible), "sft_pairs": {k: len(v) for k, v in sft_by_split.items()},
"split_by": "source_id, or multi-view session", "split_of_source": split_of_group, "gold": gold, "leaks": leaks,
"checklist": checklist, "slices": {k: dict(v) for k, v in slices.items()},
"data_card": f"releases/{release_id}/data_card.md"}
write_json(out / "release.json", info)
write_json(R / "releases" / "latest.json", info)
return info