Spaces:
Running on Zero

File size: 22,967 Bytes
5c58a52
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1763916
5a19b4e
 
 
1763916
5a19b4e
1763916
 
 
 
 
5a19b4e
 
 
 
 
 
 
 
 
 
1763916
5a19b4e
 
 
5c58a52
5a19b4e
 
 
 
 
 
 
 
 
 
 
1763916
5a19b4e
 
 
 
 
cc06acc
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef8d49
 
 
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef8d49
5a19b4e
 
 
 
 
 
 
 
 
 
 
cef8d49
 
 
 
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cef8d49
 
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5c58a52
 
 
 
 
5a19b4e
 
5c58a52
 
 
 
5a19b4e
cef8d49
5a19b4e
cef8d49
 
5a19b4e
cef8d49
5a19b4e
 
 
 
 
cef8d49
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
cef8d49
 
5a19b4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Tempora-1 Space page. Talks to the Gradio endpoint /segment through @gradio/client.
const CLIENT_URL = "https://cdn.jsdelivr.net/npm/@gradio/client@2.7.2/dist/index.min.js";
const BASE = (window.TEMPORA && window.TEMPORA.base) || "";
const MAX_MB = 200;
const RETURN_LINE = 'Return JSON: {"chunks":[{"start":sec,"end":sec,"label":...}]}';
const PALETTE = ["#ff5a14", "#1a110d", "#c79a7f", "#8a3a12", "#f2b38f", "#5e4a40", "#ffd2bd", "#b8592a"];
const DARK = new Set(["#ff5a14", "#1a110d", "#8a3a12", "#5e4a40", "#b8592a"]);

const S = { examples: [], src: null, result: null, active: -1, colorBy: null, colors: {}, running: false, client: null };
const $ = (id) => document.getElementById(id);
const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const fmt = (t) => { t = Math.max(0, +t || 0); const m = Math.floor(t / 60), s = t - m * 60; return `${String(m).padStart(2, "0")}:${s.toFixed(1).padStart(4, "0")}`; };
const fmtDur = (t) => { t = Math.round(+t || 0); const m = Math.floor(t / 60); return m ? `${m}m ${String(t % 60).padStart(2, "0")}s` : `${t}s`; };

// Python json.dumps for a list of strings (", " separator, non-ASCII escaped), so the preview equals what is sent.
function pyDumps(list) {
  const one = (s) => JSON.stringify(String(s)).replace(/[\u007f-￿]/g, (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"));
  return "[" + list.map(one).join(", ") + "]";
}
function buildPrompt(instruction, task, fields, descs) {
  instruction = instruction.trim(); task = task.trim();
  const lines = [];
  if (instruction) lines.push(instruction.includes("\n") ? `Instruction:\n${instruction}` : `Instruction: ${instruction}`);
  if (task) lines.push(`Task: ${task}`);
  if (instruction || fields.length) {
    lines.push("metadata_fields: " + pyDumps(fields));
    if (descs.some(Boolean)) lines.push("metadata_fields_description: " + pyDumps(descs));
  }
  lines.push(RETURN_LINE);
  return lines.join("\n");
}

// ---------------------------------------------------------------- decoration
function pixels() {
  document.querySelectorAll("[data-pixels]").forEach((el) => {
    let seed = el.dataset.pixels === "left" ? 7 : 19;
    const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
    const cols = 25, rows = 22, out = [];
    for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
      const d = Math.hypot(c / cols, r / rows * 0.9);
      const p = Math.max(0, 0.85 - d * 1.15);
      const on = rnd() < p;
      const accent = on && rnd() < 0.09;
      out.push(`<i style="background:${on ? (accent ? "var(--accent)" : "rgba(58,28,12," + (0.05 + rnd() * 0.13).toFixed(2) + ")") : "transparent"}"></i>`);
    }
    el.innerHTML = out.join("");
  });
  document.querySelectorAll(".frames i").forEach((el, i) => el.setAttribute("data-t", `${(i / 3).toFixed(1)}s`));
}

// ---------------------------------------------------------------- gallery + sources
function renderGallery() {
  const g = $("gallery"), up = $("upload-card");
  g.querySelectorAll(".card.ex").forEach((n) => n.remove());
  S.examples.forEach((ex) => {
    const b = document.createElement("button");
    b.type = "button"; b.className = "card ex"; b.dataset.id = ex.id;
    b.dataset.group = /robot/i.test(ex.tag) ? "robot" : /first person/i.test(ex.tag) ? "ego" : "general";
    b.innerHTML = `<img src="${BASE}${ex.poster}" alt="" loading="lazy" /><span class="tag">${esc(ex.tag)}</span>
      <span class="card-title">${esc(ex.title)}</span><span class="card-meta">${fmtDur(ex.duration)} · ${ex.result.chunks.length} chunks</span>`;
    b.addEventListener("click", () => selectExample(ex.id));
    g.appendChild(b);
  });
  document.querySelectorAll("#filters .filter").forEach((f) => f.addEventListener("click", () => {
    document.querySelectorAll("#filters .filter").forEach((x) => x.classList.toggle("on", x === f));
    g.querySelectorAll(".card.ex").forEach((c) => { c.hidden = f.dataset.group !== "all" && c.dataset.group !== f.dataset.group; });
    g.scrollLeft = 0;
  }));
}
function markCard() {
  document.querySelectorAll(".card").forEach((c) => c.classList.toggle("on",
    S.src && ((S.src.kind === "example" && c.dataset.id === S.src.ex.id) || (S.src.kind === "upload" && c.id === "upload-card"))));
}
function selectExample(id, scroll) {
  const ex = S.examples.find((e) => e.id === id);
  if (!ex || S.running) return;
  if (S.src && S.src.url) URL.revokeObjectURL(S.src.url);
  S.src = { kind: "example", ex };
  $("video").poster = BASE + ex.poster;
  $("video").src = BASE + ex.src;
  $("src-label").textContent = ex.tag;
  $("src-meta").textContent = `${ex.title} · ${fmtDur(ex.duration)}`;
  $("credit").textContent = [ex.note, ex.credit].filter(Boolean).join(" ");
  setForm(ex.instruction, ex.task, ex.fields, true);
  setResult({ ...ex.result, saved: true });
  markCard();
  if (scroll) $("demo").scrollIntoView({ behavior: "smooth" });
}
function selectUpload(file) {
  if (S.running) return;
  if (!file.type.startsWith("video/") && !/\.(mp4|mov|mkv|webm|avi|m4v)$/i.test(file.name)) return note("That file is not a video.", true);
  if (file.size > MAX_MB * 2 ** 20) return note(`Video too large (max ${MAX_MB} MB).`, true);
  if (S.src && S.src.url) URL.revokeObjectURL(S.src.url);
  const url = URL.createObjectURL(file);
  $("video").removeAttribute("poster");
  S.src = { kind: "upload", file, url };
  $("video").src = url;
  $("src-label").textContent = "Your video";
  $("src-meta").textContent = `${file.name} · ${(file.size / 2 ** 20).toFixed(1)} MB`;
  $("credit").textContent = "";
  setForm("Segment the video into its main steps", "", [], $("thinking").checked);
  setResult(null);
  markCard();
  refreshPrompt();
}

// ---------------------------------------------------------------- prompt form
function fieldRow(name = "", desc = "") {
  const row = document.createElement("div");
  row.className = "frow";
  row.innerHTML = `<input type="text" placeholder="field_name" value="${esc(name)}" aria-label="Field name" />
    <input type="text" placeholder="what it should hold (optional)" value="${esc(desc)}" aria-label="Field description" />
    <button type="button" aria-label="Remove field">×</button>`;
  row.querySelector("button").addEventListener("click", () => { row.remove(); refreshPrompt(); });
  row.querySelectorAll("input").forEach((i) => i.addEventListener("input", refreshPrompt));
  $("fields").appendChild(row);
}
function setForm(instruction, task, fields, thinking) {
  $("instruction").value = instruction || "";
  $("task").value = task || "";
  $("fields").innerHTML = "";
  (fields || []).forEach((f) => fieldRow(f.name, f.description));
  $("thinking").checked = thinking !== false;
  refreshPrompt();
}
function readForm() {
  const rows = [...$("fields").querySelectorAll(".frow")].map((r) => {
    const [n, d] = r.querySelectorAll("input"); return { name: n.value.trim(), description: d.value.trim() };
  }).filter((f) => f.name);
  return { instruction: $("instruction").value, task: $("task").value, fields: rows, thinking: $("thinking").checked };
}
function refreshPrompt() {
  const f = readForm();
  const p = buildPrompt(f.instruction, f.task, f.fields.map((x) => x.name), f.fields.map((x) => x.description));
  $("prompt-preview").textContent = p;
  const opts = [f.task.trim() && "task", f.fields.length && `${f.fields.length} field${f.fields.length > 1 ? "s" : ""}`, `thinking ${f.thinking ? "on" : "off"}`].filter(Boolean);
  $("more-sum").textContent = "More options · " + opts.join(" · ");
  $("ask-text").textContent = f.instruction.trim() || "(no instruction)";
  $("ask-meta").textContent = [f.task.trim() && `Task: ${f.task.trim()}`, f.fields.length && `Fields: ${f.fields.map((x) => x.name).join(", ")}`].filter(Boolean).join(" · ");
  let t = "";
  if (S.src && S.src.kind === "example" && S.result && S.result.saved) {
    const same = p === S.src.ex.prompt;
    t = same ? "Showing the saved output for this prompt. Run to generate it again on the GPU."
             : "Prompt changed. Run to see the model's answer to it.";
  } else if (!S.src) t = "Pick an example or upload a video.";
  if (!S.running) note(t);
}
function note(t, err) { const n = $("run-note"); n.textContent = t || ""; n.style.color = err ? "#c2410c" : ""; }

// ---------------------------------------------------------------- results
function chooseColorBy(chunks) {
  const keys = [...new Set(chunks.flatMap((c) => Object.keys(c.metadata || {})))];
  for (const k of keys) {
    const vals = [...new Set(chunks.map((c) => JSON.stringify(c.metadata?.[k] ?? null)))];
    if (vals.length >= 2 && vals.length <= 6 && vals.length < chunks.length) return k;
  }
  return null;
}
function valueText(v) { return Array.isArray(v) ? v.join(", ") : (v && typeof v === "object" ? JSON.stringify(v) : String(v ?? "")); }
function setResult(res) {
  S.result = res; S.active = -1;
  const chunks = (res && res.chunks) || [];
  S.colorBy = chooseColorBy(chunks); S.colors = {};
  if (S.colorBy) {
    [...new Set(chunks.map((c) => valueText(c.metadata?.[S.colorBy])))].forEach((v, i) => (S.colors[v] = PALETTE[i % PALETTE.length]));
  }
  $("n-chunks").textContent = res ? (res.chunks ? res.chunks.length : "0") : "";
  $("provenance").textContent = res ? (res.provenance || "") : "";
  $("json").textContent = res ? (res.raw ? pretty(res.raw) : "(no answer)") : "Run the model to see its JSON.";
  $("reasoning").textContent = res ? (res.reasoning || (res.thinking ? "(no reasoning returned)" : "Thinking was off for this output.")) : "";
  renderTable(); renderTrack(); renderLegend(); updateNow(); refreshPrompt();
}
function pretty(raw) { try { return JSON.stringify(JSON.parse(raw), null, 1); } catch { return raw; } }
function duration() { const v = $("video"); return (v.duration && isFinite(v.duration)) ? v.duration : (S.src?.ex?.duration || 0); }
function renderTrack() {
  const tr = $("track"); tr.innerHTML = "";
  const chunks = S.result?.chunks || [], d = duration();
  if (d) chunks.forEach((c, i) => {
    const el = document.createElement("div");
    const col = S.colorBy ? S.colors[valueText(c.metadata?.[S.colorBy])] : null;
    el.className = "seg" + (col && DARK.has(col) ? " dark" : "");
    el.style.left = (100 * Math.max(0, c.start) / d) + "%";
    el.style.width = Math.max(0.25, 100 * (Math.min(c.end, d) - Math.max(0, c.start)) / d) + "%";
    if (col) el.style.background = col;
    el.textContent = c.label; el.title = `${fmt(c.start)} → ${fmt(c.end)}  ${c.label}`;
    el.addEventListener("click", (e) => { e.stopPropagation(); seek(c.start + 0.01, i); });
    tr.appendChild(el);
  });
  const ru = $("ruler"); ru.innerHTML = "";
  if (d) {
    const step = [1, 2, 5, 10, 15, 30, 60, 120, 300].find((s) => d / s <= 8) || 600;
    for (let t = 0; t <= d + 1e-6; t += step) ru.insertAdjacentHTML("beforeend", `<span style="left:${100 * t / d}%">${fmt(t).replace(/\.\d$/, "")}</span>`);
  }
  movePlayhead();
}
function renderLegend() {
  const lg = $("legend");
  lg.innerHTML = S.colorBy ? `<span class="label" style="margin-right:4px">${esc(S.colorBy)}</span>` +
    Object.entries(S.colors).map(([v, c]) => `<span><i style="background:${c}"></i>${esc(v)}</span>`).join("") : "";
}
function renderTable() {
  const t = $("table"), chunks = S.result?.chunks;
  if (!chunks || !chunks.length) {
    t.innerHTML = `<tbody><tr><td class="empty">${S.result ? (S.result.truncated ? "The reasoning used the whole token budget before answering. Try again with thinking off, or a shorter clip." : "No chunks in this answer. See the JSON tab.") : "No output yet. Run the model on this video."}</td></tr></tbody>`;
    return;
  }
  const keys = [...new Set(chunks.flatMap((c) => Object.keys(c.metadata || {})))];
  t.innerHTML = `<thead><tr><th>#</th><th>Start</th><th>End</th><th>Label</th>${keys.map((k) => `<th>${esc(k)}</th>`).join("")}</tr></thead><tbody>` +
    chunks.map((c, i) => `<tr data-i="${i}"><td class="t">${String(i + 1).padStart(2, "0")}</td><td class="t">${fmt(c.start)}</td><td class="t">${fmt(c.end)}</td><td class="lab">${esc(c.label)}</td>${keys.map((k) => `<td class="m" data-k="${esc(k)}">${esc(valueText(c.metadata?.[k]))}</td>`).join("")}</tr>`).join("") + "</tbody>";
  t.querySelectorAll("tbody tr").forEach((r) => r.addEventListener("click", () => { const c = chunks[+r.dataset.i]; seek(c.start + 0.01, +r.dataset.i); }));
}
function seek(t, i) { const v = $("video"); v.currentTime = t; S.active = i ?? S.active; updateNow(); }
function activeAt(t) { const cs = S.result?.chunks || []; for (let i = cs.length - 1; i >= 0; i--) if (t >= cs[i].start && t < cs[i].end) return i; return -1; }
function movePlayhead() { const d = duration(); $("playhead").style.left = d ? `calc(${100 * $("video").currentTime / d}% - 1px)` : "0"; }
function updateNow() {
  const v = $("video"), cs = S.result?.chunks || [];
  const i = activeAt(v.currentTime);
  S.active = i;
  $("track").querySelectorAll(".seg").forEach((el, k) => el.classList.toggle("on", k === i));
  $("table").querySelectorAll("tbody tr[data-i]").forEach((el) => el.classList.toggle("on", +el.dataset.i === i));
  const row = $("table").querySelector("tbody tr.on"), wrap = $("table").parentElement;
  if (PHONE() && row) {   // keep the current chunk in view inside the list (scrolls the list, not the page)
    const top = row.offsetTop - wrap.scrollTop;
    if (top < 0 || top + row.offsetHeight > wrap.clientHeight) wrap.scrollTo({ top: row.offsetTop - 8, behavior: "smooth" });
  }
  if (i < 0) {
    $("now-idx").textContent = cs.length ? `— / ${cs.length}` : "—";
    $("now-time").textContent = fmt(v.currentTime);
    $("now-label").textContent = cs.length ? "No chunk at this moment." : (S.result ? "No chunks." : "Run the model to see chunks here.");
    $("now-meta").innerHTML = "";
    return;
  }
  const c = cs[i];
  $("now-idx").textContent = `Chunk ${String(i + 1).padStart(2, "0")} / ${cs.length}`;
  $("now-time").textContent = `${fmt(c.start)} → ${fmt(c.end)}`;
  $("now-label").textContent = c.label;
  $("now-meta").innerHTML = Object.entries(c.metadata || {}).map(([k, val]) => `<dt>${esc(k)}</dt><dd>${esc(valueText(val))}</dd>`).join("");
}
function tick() { movePlayhead(); const i = activeAt($("video").currentTime); if (i !== S.active) updateNow(); if (!$("video").paused) requestAnimationFrame(tick); }

// ---------------------------------------------------------------- running the model
function log(text, cls) {
  const ol = $("log"); ol.hidden = false;
  ol.querySelectorAll("li.live").forEach((li) => li.classList.remove("live"));
  const li = document.createElement("li");
  li.className = cls || "live";
  li.innerHTML = `<time>${((performance.now() - S.t0) / 1000).toFixed(1)}s</time><span>${esc(text)}</span>`;
  ol.appendChild(li);
  return li;
}
async function client() {
  if (S.client) return S.client;
  const { Client, handle_file } = await import(CLIENT_URL);
  S.handle_file = handle_file;
  S.client = await Client.connect(window.location.href.split(/[?#]/)[0]);
  return S.client;
}
async function run(e) {
  e.preventDefault();
  if (S.running || !S.src) return;
  const f = readForm();
  if (!f.instruction.trim() && !f.fields.length) return note("Write an instruction first.", true);
  S.running = true; S.t0 = performance.now();
  $("run").disabled = true; $("run").textContent = "Running…";
  $("log").innerHTML = "";
  note("");
  log("Connecting");
  let live = null, partialLine = null, gotDone = false;
  try {
    const c = await client();
    const payload = {
      video: S.src.kind === "upload" ? S.handle_file(S.src.file) : null,
      example: S.src.kind === "example" ? S.src.ex.id : "",
      instruction: f.instruction, task: f.task, fields: JSON.stringify(f.fields), thinking: f.thinking,
    };
    if (S.src.kind === "upload") log(`Uploading ${(S.src.file.size / 2 ** 20).toFixed(1)} MB`);
    const job = c.submit("/segment", payload);
    let lastStage = "";
    for await (const m of job) {
      if (m.type === "status") {
        if (m.stage === "pending" && m.queue && m.position != null && lastStage !== "q" + m.position) {
          lastStage = "q" + m.position; log(m.position > 0 ? `In queue, position ${m.position + 1}` : "Next in queue");
        } else if (m.stage === "error") { throw new Error(m.message || "The run failed."); }
        continue;
      }
      if (m.type !== "data") continue;
      const d = JSON.parse(m.data[0]);
      if (d.stage === "decoding" && lastStage !== "decoding") { lastStage = "decoding"; log("Sampling frames at 3 fps"); }
      else if (d.stage === "queued" && lastStage !== "queued") {
        lastStage = "queued";
        log(`${d.frames} frames · ${fmtDur(d.duration)} · ${d.input_tokens.toLocaleString()} input tokens`, "");
        live = log("Waiting for a ZeroGPU slot");
      } else if (d.stage === "generating") {
        if (lastStage !== "generating") { lastStage = "generating"; live = log(f.thinking ? "Thinking" : "Generating"); }
        if (d.partial != null) {
          const text = d.partial;
          const thinkingNow = f.thinking && !text.includes("</think>");
          if (!partialLine) partialLine = live;
          partialLine.querySelector("span").textContent = `${thinkingNow ? "Thinking" : "Writing the answer"} · ${text.length.toLocaleString()} characters`;
          $("reasoning").textContent = text.replace("<think>", "").split("</think>")[0].trim();
          if (!thinkingNow) $("json").textContent = text.split("</think>").pop().trim();
        }
      } else if (d.stage === "done") {
        if (gotDone) continue;   // the client repeats the last message when the job completes
        gotDone = true;
        const st = d.stats || {};
        log(`Done · ${(d.chunks || []).length} chunks${st.output_tokens ? ` · ${st.output_tokens.toLocaleString()} output tokens` : ""} · ${st.seconds ?? ""} s`, "");
        setResult({ chunks: d.chunks, raw: d.raw, reasoning: d.reasoning, thinking: d.thinking, truncated: d.truncated,
          provenance: `Live run · thinking ${d.thinking ? "on" : "off"}${st.mock ? " · mock" : ""}`, saved: false });
        if (!d.chunks) tab("json");
        if (PHONE()) tab(d.chunks ? "chunks" : "json");
        if (window.innerWidth <= 1080)   // output sits above the form here; on phones show the video with it
          document.querySelector(PHONE() ? ".player-panel" : ".results").scrollIntoView({ behavior: "smooth", block: "start" });
      }
    }
    if (!gotDone) throw new Error("The run ended without an answer.");
  } catch (err) {
    log(String(err && err.message || err).slice(0, 300), "err");
    note("The run failed. See the log.", true);
  } finally {
    S.running = false; $("run").disabled = false; $("run").textContent = "Run on GPU →";
    $("log").querySelectorAll("li.live").forEach((li) => li.classList.remove("live"));
  }
}

// ---------------------------------------------------------------- benchmark + tabs
async function renderBench() {
  const rows = await (await fetch(BASE + "benchmark.json")).json();
  const maxF = Math.max(...rows.map((r) => r.seg_f1));
  const x = (r) => (r.ours ? "1×" : (r.x >= 10 ? Math.round(r.x) : r.x.toFixed(1).replace(/\.0$/, "")) + "×");
  let group = null, body = "";
  rows.forEach((r) => {
    if (r.group !== group) { group = r.group; body += `<tr class="grp"><td colspan="7">${esc(group)}</td></tr>`; }
    body += `<tr class="${r.ours ? "ours" : ""}"><td>${esc(r.name)}${r.runs > 1 ? ` <span class="dim">· ${r.runs} runs</span>` : ""}</td><td class="t">${esc(r.input)}</td>
      <td class="num"><div class="bar"><i style="width:${90 * r.seg_f1 / maxF}px"></i>${r.seg_f1.toFixed(3)}</div></td>
      <td class="num"><div class="bar e2e"><i style="width:${90 * r.e2e_f1 / maxF}px"></i>${r.e2e_f1.toFixed(3)}</div></td>
      <td class="num">${r.label_acc.toFixed(2)}</td>
      <td class="num">$${r.cost.toFixed(r.cost < 1 ? 3 : 2)}</td><td class="num">${x(r)}</td></tr>`;
  });
  $("bench-table").innerHTML = `<thead><tr><th>Model</th><th>Input</th><th>Segment F1</th><th>End-to-end F1</th><th>Label acc.</th><th>$ / video-hour</th><th>Cost vs Tempora-1</th></tr></thead><tbody>${body}</tbody>`;
}
const PHONE = () => window.innerWidth <= 760;
function tab(name) {
  // "edit" exists on phones only: the form replaces the output under the same tab bar
  $("tempora-root").dataset.mtab = name;
  document.querySelectorAll(".tab").forEach((t) => t.classList.toggle("on", t.dataset.tab === name));
  if (name !== "edit") document.querySelectorAll(".tab-body").forEach((b) => (b.hidden = b.dataset.body !== name));
}

// ---------------------------------------------------------------- init
async function init() {
  pixels();
  document.querySelectorAll("details.preview, details.more").forEach((d) => (d.open = !PHONE()));   // closed on phones: they are long
  $("tempora-root").dataset.mtab = "chunks";
  S.examples = await (await fetch(BASE + "examples.json")).json();
  renderGallery();
  const v = $("video");
  v.addEventListener("loadedmetadata", () => { renderTrack(); updateNow(); });
  v.addEventListener("play", () => requestAnimationFrame(tick));
  v.addEventListener("seeked", () => { movePlayhead(); updateNow(); });
  v.addEventListener("timeupdate", () => { movePlayhead(); updateNow(); });
  $("track").addEventListener("click", (e) => { const r = $("track").getBoundingClientRect(); seek(duration() * (e.clientX - r.left) / r.width); });
  ["instruction", "task", "thinking"].forEach((id) => $(id).addEventListener("input", refreshPrompt));
  $("add-field").addEventListener("click", () => { fieldRow(); refreshPrompt(); $("fields").lastChild.querySelector("input").focus(); });
  $("form").addEventListener("submit", run);
  $("credit").addEventListener("click", () => $("credit").classList.toggle("open"));
  $("ask-edit").addEventListener("click", () => { tab("edit"); $("instruction").focus({ preventScroll: true }); });
  document.querySelectorAll(".tab").forEach((t) => t.addEventListener("click", () => tab(t.dataset.tab)));
  const card = $("upload-card"), file = $("file");
  file.addEventListener("change", () => file.files[0] && selectUpload(file.files[0]));
  card.addEventListener("dragover", (e) => { e.preventDefault(); card.classList.add("drag"); });
  card.addEventListener("dragleave", () => card.classList.remove("drag"));
  card.addEventListener("drop", (e) => { e.preventDefault(); card.classList.remove("drag"); e.dataTransfer.files[0] && selectUpload(e.dataTransfer.files[0]); });
  document.querySelectorAll('a[href="#demo"]').forEach((a) => a.addEventListener("click", () => { if (!S.src) selectExample(S.examples[0].id); }));
  selectExample(S.examples[0].id);
  renderBench();
}

(function wait() {
  if (document.getElementById("tempora-root") && document.getElementById("gallery")) init().catch((e) => console.error(e));
  else setTimeout(wait, 60);
})();