File size: 4,637 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
"""Stage 7 - write the review site to results/web/.

data.js holds every record (loaded with a <script> tag, so index.html also opens
straight from disk, read-only). Run `python code/serve.py` to review and correct
in the browser: edits go to results/annotations/review.jsonl and the outputs are
rebuilt. Media paths are relative to results/web/."""
import json
import os
import shutil
from collections import Counter
from datetime import datetime

from common import CODE, EVENT_NAMES, ROOT
from review import load_review


def _label_frames(R, review, wp):
    p = R / "labeling" / "manifest.json"
    if not p.exists():
        return []
    labels, bats = {}, {}
    for r in sorted((r for r in review if r["kind"] in ("ball_label", "bat_label")), key=lambda r: r["created_at"]):
        (labels if r["kind"] == "ball_label" else bats)[r["field"]] = dict(r["value"], by=r["annotator_id"])
    items = json.load(open(p))
    for it in items:
        it["image"] = wp(it["image"])
        it["label"] = labels.get(it["id"])
        it["bat"] = bats.get(it["id"])
    return items


def _checklists(review):
    out = {}
    for r in sorted((r for r in review if r["kind"] == "checklist"), key=lambda r: r["created_at"]):
        out[r["source_id"]] = dict(r["value"], by=r["annotator_id"], at=r["created_at"])
    return out


def _equipment():
    from bat import load_equipment
    return load_equipment()


def _people():
    from review import load_people
    p = load_people()
    return {k: v["role"] for k, v in p.get("people", {}).items()}


def _devices():
    p = CODE / "registry" / "devices.yaml"
    import yaml
    return yaml.safe_load(open(p)) if p.exists() else {}


def build_web(cfg, sources, deliveries, sft_rows, segments, onto, exp, rel_info, schema_report, evaluation=None):
    R = cfg["_paths"]["results"]
    web = R / "web"
    web.mkdir(parents=True, exist_ok=True)

    def wp(p):
        return None if not p else os.path.relpath(ROOT / p, web).replace(os.sep, "/")

    dl = []
    for m in deliveries:
        d = dict(m)
        med = dict(m.get("media", {}))
        for k in ("clip", "annotated", "thumbnail", "calib_frame"):
            med[k] = wp(med.get(k))
        med["keyframes"] = {k: wp(v) for k, v in med.get("keyframes", {}).items()}
        d["media"] = med
        dl.append(d)
    per_src = Counter(m["source_id"] for m in deliveries)
    qc = Counter(m["qc"]["status"] for m in deliveries)
    review = load_review(R)
    res_rel = lambda p: wp(os.path.relpath(p, ROOT)) if p else None
    files = {"sft_records.jsonl": R / "jsonl" / "sft_records.jsonl", "sft_chat.jsonl": R / "jsonl" / "sft_chat.jsonl",
             "deliveries.jsonl": R / "jsonl" / "deliveries.jsonl", "review.jsonl": R / "annotations" / "review.jsonl"}
    for f in (schema_report or {}).get("files", {}).values():
        files[os.path.basename(f)] = f
    if rel_info:
        files["data_card.md"] = R / rel_info["data_card"]
    data = {
        "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M"),
        "pipeline_version": cfg["project"]["pipeline_version"],
        "annotator_default": cfg["project"].get("annotator_default", ""),
        "summary": {"videos": len(sources),
                    "windows": sum(len(s.get("windows", [])) for s in segments.values()),
                    "deliveries": len(deliveries), "qc": dict(qc), "sft_pairs": len(sft_rows),
                    "reviewed": sum(1 for d in deliveries if d.get("annotation_status", "auto") != "auto")},
        "sources": [dict(s, deliveries=per_src.get(s["source_id"], 0),
                         cuts=len(segments.get(s["source_id"], {}).get("cuts", []))) for s in sources],
        "deliveries": dl, "sft": sft_rows, "ontology": onto, "experiment": exp,
        "event_names": EVENT_NAMES, "release": rel_info, "schema": schema_report,
        "recent_edits": review[-40:][::-1],
        "evaluation": evaluation,
        "label_frames": _label_frames(R, review, wp),
        "checklists": _checklists(review),
        "people": _people(), "devices": _devices(), "equipment": _equipment(),
        "multiview": [dict(r, views=[dict(v, clip=wp(v.get("clip")), annotated=wp(v.get("annotated"))) for v in r["views"]])
                      for r in (cfg.get("_mv_records") or [])],
        "files": {k: res_rel(v) for k, v in files.items() if v and os.path.exists(v)},
    }
    with open(web / "data.js", "w") as f:
        f.write("window.FOUNDRY = ")
        json.dump(data, f, ensure_ascii=False, default=str)
        f.write(";\n")
    shutil.copy(CODE / "web_template.html", web / "index.html")
    return web / "index.html"