// 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) => ({ "&": "&", "<": "<", ">": ">", '"': """ }[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(``); } 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 = `${esc(ex.tag)} ${esc(ex.title)}${fmtDur(ex.duration)} · ${ex.result.chunks.length} chunks`; 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 = ` `; 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", `${fmt(t).replace(/\.\d$/, "")}`); } movePlayhead(); } function renderLegend() { const lg = $("legend"); lg.innerHTML = S.colorBy ? `${esc(S.colorBy)}` + Object.entries(S.colors).map(([v, c]) => `${esc(v)}`).join("") : ""; } function renderTable() { const t = $("table"), chunks = S.result?.chunks; if (!chunks || !chunks.length) { t.innerHTML = `${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."}`; return; } const keys = [...new Set(chunks.flatMap((c) => Object.keys(c.metadata || {})))]; t.innerHTML = `#StartEndLabel${keys.map((k) => `${esc(k)}`).join("")}` + chunks.map((c, i) => `${String(i + 1).padStart(2, "0")}${fmt(c.start)}${fmt(c.end)}${esc(c.label)}${keys.map((k) => `${esc(valueText(c.metadata?.[k]))}`).join("")}`).join("") + ""; 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]) => `
${esc(k)}
${esc(valueText(val))}
`).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 = `${esc(text)}`; 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(""); if (!partialLine) partialLine = live; partialLine.querySelector("span").textContent = `${thinkingNow ? "Thinking" : "Writing the answer"} · ${text.length.toLocaleString()} characters`; $("reasoning").textContent = text.replace("", "").split("")[0].trim(); if (!thinkingNow) $("json").textContent = text.split("").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 += `${esc(group)}`; } body += `${esc(r.name)}${r.runs > 1 ? ` · ${r.runs} runs` : ""}${esc(r.input)}
${r.seg_f1.toFixed(3)}
${r.e2e_f1.toFixed(3)}
${r.label_acc.toFixed(2)} $${r.cost.toFixed(r.cost < 1 ? 3 : 2)}${x(r)}`; }); $("bench-table").innerHTML = `ModelInputSegment F1End-to-end F1Label acc.$ / video-hourCost vs Tempora-1${body}`; } 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); })();