// 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)}`;
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 = `