situate-diffuse / app.js
Schnowflake's picture
Serve the scenes from the Space: scenes.json, WebP pictures, masks and objects
7dca415 verified
Raw History Blame Contribute Delete
12.6 kB
const BATCH = 12; // scenes drawn at a time while scrolling
const MODELS = { // column -> shown name, as the models are called in settings.py
ideogram_4_reprompt: ["Ideogram 4", "ideogram-4-reprompt"],
fibo_2_edit_turbo: ["FIBO 2 Edit Turbo", "fibo-2-edit-turbo"],
flux_3_klein_reprompt: ["FLUX.3 klein", "flux-3-klein-reprompt"],
hidream_o1_image_reprompt: ["HiDream-O1-Image", "hidream-o1-image-reprompt"],
krea_2_turbo: ["Krea 2 Turbo", "krea-2-turbo"],
ming_image_0_1_design: ["Ming-Image 0.1 Design", "ming-image-0.1-design"],
moss_image_sft: ["MOSS-Image SFT", "moss-image-sft"],
qwen_image_2_1_turbo_reprompt: ["Qwen-Image-2.1-Turbo", "qwen-image-2.1-turbo-reprompt"],
qwen_image_2512_lightning: ["Qwen-Image-2512 Lightning", "qwen-image-2512-lightning"],
};
const CATEGORIES = ["billiard", "checkers", "chess", "cupcake_candles", "fruitcake", "nuts", "shelf", "table"];
const UNSCORED = { chess: ["pawns"] }; // listed, not scored, as in 3_score.py
let scenes = [];
let order = Object.keys(MODELS); // best total first, once the scores are known
let shown = [];
let drawn = 0;
let viewing = null; // [scene, model index] of the open picture
const $ = (id) => document.getElementById(id);
function readScene(row) {
const scene = { ...row, expected: JSON.parse(row.expected), models: {} };
for (const model of Object.keys(MODELS)) {
scene.models[model] = {
picture: `pictures/${model}/${row.scene_id}.webp`,
masks: `masks/${model}/${row.scene_id}.png`,
found: JSON.parse(row[`${model}_found`]),
points: row[`${model}_points`],
rewrite: row[`${model}_rewrite`] ?? row.hidream_o1_image_reprompt_rewrite,
ownRewrite: `${model}_rewrite` in row,
};
}
const ratios = Object.values(scene.models).map((result) => result.points / scene.possible_points);
scene.mean = ratios.reduce((sum, ratio) => sum + ratio, 0) / ratios.length;
scene.solved = ratios.some((ratio) => ratio === 1);
scene.disagree = new Set(ratios).size > 1;
return scene;
}
function kind(scene, check) { // as in scoring.py: "point", "extra", "flaw" (yes/no) or "listed"
const expected = scene.expected[check];
if (expected === null || (UNSCORED[scene.category] ?? []).includes(check)) {
return "listed";
}
if (typeof expected === "boolean") {
return "flaw";
}
if (expected === 0) {
return "extra";
}
return "point";
}
function verdict(scene, check, found) { // chip colour: "ok" +1, "wrong" no point or -1, "none" nothing to win or lose
const expected = scene.expected[check];
const type = kind(scene, check);
if (type === "point") {
return found === expected ? "ok" : "wrong";
}
if (type === "extra" || type === "flaw") {
return found === expected ? "none" : "wrong";
}
return "none";
}
function value(number) {
if (number === true) {
return "✓";
}
if (number === false) {
return "✗";
}
if (number === null || number === undefined) {
return "?";
}
return String(number);
}
function scoreTable() {
const totals = {};
for (const model of Object.keys(MODELS)) {
const perCategory = {};
for (const category of CATEGORIES) {
const inCategory = scenes.filter((scene) => scene.category === category);
const points = inCategory.reduce((sum, scene) => sum + scene.models[model].points, 0);
const possible = inCategory.reduce((sum, scene) => sum + scene.possible_points, 0);
perCategory[category] = points / possible;
}
const total = CATEGORIES.reduce((sum, category) => sum + perCategory[category], 0) / CATEGORIES.length;
totals[model] = { total, ...perCategory };
}
order = Object.keys(MODELS).sort((a, b) => totals[b].total - totals[a].total);
const head = ["<th>model</th>", "<th>total</th>"];
for (const category of CATEGORIES) {
head.push(`<th class="category" data-category="${category}">${category.replace("_", " ")}</th>`);
}
$("score-head").innerHTML = head.join("");
const body = [];
for (const model of order) {
const cells = [`<td title="${MODELS[model][1]}">${MODELS[model][0]}</td>`, `<td class="total">${totals[model].total.toFixed(3)}</td>`];
for (const category of CATEGORIES) {
const score = totals[model][category];
cells.push(`<td style="background: rgba(var(--tint), ${(0.08 + 0.55 * score).toFixed(2)})">${score.toFixed(3)}</td>`);
}
body.push(`<tr>${cells.join("")}</tr>`);
}
$("score-body").innerHTML = body.join("");
for (const header of document.querySelectorAll("th.category")) {
header.addEventListener("click", () => {
const category = header.dataset.category;
$("category").value = $("category").value === category ? "all" : category;
update();
});
}
}
function fillFilters() {
const categories = ['<option value="all">all</option>'];
for (const category of CATEGORIES) {
categories.push(`<option value="${category}">${category.replace("_", " ")}</option>`);
}
$("category").innerHTML = categories.join("");
const counts = [...new Set(scenes.map((scene) => scene.objects))].sort((a, b) => a - b);
const options = counts.map((count) => `<option value="${count}">${count}</option>`).join("");
$("min-objects").innerHTML = options;
$("max-objects").innerHTML = options;
$("max-objects").value = counts[counts.length - 1];
for (const id of ["category", "min-objects", "max-objects", "show", "sort"]) {
$(id).addEventListener("change", update);
}
$("masks").addEventListener("change", () => document.body.classList.toggle("masks", $("masks").checked));
}
function update() {
const category = $("category").value;
const least = Number($("min-objects").value);
const most = Number($("max-objects").value);
const show = $("show").value;
shown = scenes.filter((scene) => {
if (category !== "all" && scene.category !== category) {
return false;
}
if (scene.objects < least || scene.objects > most) {
return false;
}
if (show === "disagree") {
return scene.disagree;
}
if (show === "failed") {
return !scene.solved;
}
if (show === "solved") {
return scene.solved;
}
return true;
});
if ($("sort").value === "hardest") {
shown.sort((a, b) => a.mean - b.mean);
}
if ($("sort").value === "easiest") {
shown.sort((a, b) => b.mean - a.mean);
}
for (const header of document.querySelectorAll("th.category")) {
header.classList.toggle("active", header.dataset.category === category);
}
$("count").textContent = `${shown.length} of ${scenes.length} scenes`;
$("scenes").innerHTML = shown.length ? "" : '<p class="status">No scene fits these filters.</p>';
drawn = 0;
drawMore();
}
function drawMore() {
const next = shown.slice(drawn, drawn + BATCH);
drawn += next.length;
for (const scene of next) {
$("scenes").append(sceneCard(scene));
}
}
function chips(scene, result) {
const parts = [];
for (const check of Object.keys(scene.expected)) {
const found = result.found[check];
const type = kind(scene, check);
const point = type === "point" ? " point" : "";
const title = `${check}: found ${value(found)}, expected ${value(scene.expected[check])}${type === "listed" ? " (not scored)" : ""}`;
parts.push(`<span class="chip ${verdict(scene, check, found)}${point}" title="${title}">${value(found)}</span>`);
}
return parts.join("");
}
function sceneCard(scene) {
const card = document.createElement("article");
card.className = "scene";
const expected = Object.entries(scene.expected).map(([check, number]) => `<div><b>${value(number)}</b><small>${check}</small></div>`);
const tiles = order.map((model, index) => {
const result = scene.models[model];
const full = result.points === scene.possible_points ? "full" : "part";
return `<div class="tile">
<div class="stack" data-index="${index}">
<img src="${result.picture}" alt="${MODELS[model][0]}: ${scene.scene_id}" loading="lazy">
<img class="mask" src="${result.masks}" alt="" loading="lazy">
</div>
<div class="tile-head"><span class="name" title="${MODELS[model][1]}">${MODELS[model][0]}</span>
<span class="score ${full}">${result.points}/${scene.possible_points}</span></div>
<div class="chips">${chips(scene, result)}</div>
</div>`;
});
const rewrites = order.filter((model) => scene.models[model].ownRewrite)
.map((model) => `<p><b>${MODELS[model][0]}:</b> ${scene.models[model].rewrite}</p>`);
card.innerHTML = `
<div class="scene-head"><h2>${scene.scene_id}</h2><span>${scene.objects} objects · seed ${scene.seed}</span></div>
<p class="prompt">${scene.prompt}</p>
<div class="expected"><span class="expected-label">EXPECTED</span>${expected.join("")}</div>
<div class="tiles">${tiles.join("")}</div>
<details><summary>Rewritten prompts</summary>${rewrites.join("")}
<p class="exact">The other 5 models drew HiDream-O1-Image's rewrite.</p></details>`;
for (const stack of card.querySelectorAll(".stack")) {
stack.addEventListener("click", () => openViewer(scene, Number(stack.dataset.index)));
}
return card;
}
async function openViewer(scene, index) {
viewing = [scene, (index + order.length) % order.length];
const model = order[viewing[1]];
const result = scene.models[model];
if (!scene.sam) { // what Sam kept, per model; objects/ holds it apart to keep scenes.json small
scene.sam = await (await fetch(`objects/${scene.scene_id}.json`)).json();
}
const boxes = scene.sam[model].map((thing) => {
const [x1, y1, x2, y2] = thing.box.map((v) => v / 10.24);
const label = [thing.what, thing.colour, thing.zone].filter(Boolean).join(" · ");
return `<div class="box" title="${label}" style="left: ${x1}%; top: ${y1}%; width: ${x2 - x1}%; height: ${y2 - y1}%"></div>`;
});
$("viewer-stack").innerHTML = `<img src="${result.picture}" alt="${MODELS[model][0]}: ${scene.scene_id}">
<img class="mask" src="${result.masks}" alt="">${boxes.join("")}`;
$("viewer-model").textContent = `${viewing[1] + 1} / ${order.length}`;
const rows = Object.keys(scene.expected).map((check) => {
const found = result.found[check];
return `<tr><td>${check}</td><td>${value(scene.expected[check])}</td>
<td><span class="chip ${verdict(scene, check, found)}${kind(scene, check) === "point" ? " point" : ""}">${value(found)}</span></td></tr>`;
});
const whose = result.ownRewrite ? "its own rewrite" : "HiDream-O1-Image's rewrite";
$("viewer-side").innerHTML = `
<h3>${MODELS[model][0]}</h3>
<div class="exact">${MODELS[model][1]} · ${scene.scene_id}</div>
<p><b class="score ${result.points === scene.possible_points ? "full" : "part"}">${result.points}/${scene.possible_points} points</b></p>
<table><tr><th>check</th><th>expected</th><th>found</th></tr>${rows.join("")}</table>
<p class="exact">Drew ${whose}:</p><p class="rewrite">${result.rewrite}</p>
<p class="exact">← → other models · M masks · Esc close · hover an object for what SAM read</p>`;
$("viewer").hidden = false;
}
function closeViewer() {
$("viewer").hidden = true;
viewing = null;
}
function keys(event) {
if (!viewing) {
return;
}
if (event.key === "Escape") {
closeViewer();
}
if (event.key === "ArrowRight") {
openViewer(viewing[0], viewing[1] + 1);
}
if (event.key === "ArrowLeft") {
openViewer(viewing[0], viewing[1] - 1);
}
if (event.key === "m" || event.key === "M") {
$("masks").checked = !$("masks").checked;
document.body.classList.toggle("masks", $("masks").checked);
}
}
async function start() {
try {
const response = await fetch("scenes.json");
scenes = (await response.json()).map(readScene);
} catch (error) {
$("status").textContent = `Could not load the scenes (${error.message}).`;
return;
}
scoreTable();
fillFilters();
update();
new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && drawn < shown.length) {
drawMore();
}
}, { rootMargin: "1200px" }).observe($("more"));
$("close").addEventListener("click", closeViewer);
$("previous").addEventListener("click", () => openViewer(viewing[0], viewing[1] - 1));
$("next").addEventListener("click", () => openViewer(viewing[0], viewing[1] + 1));
$("viewer").addEventListener("click", (event) => event.target === $("viewer") && closeViewer());
document.addEventListener("keydown", keys);
}
start();