Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Evaluation harness: renders become preset covers, and over-cooked strengths can be lowered in the research

Claude343a2b942f43
diff --git a/bin/lib/commands.mjs b/bin/lib/commands.mjs
index bedd2fbd..6cb6e4c4 100644
--- a/bin/lib/commands.mjs
+++ b/bin/lib/commands.mjs
@@ -889,7 +889,7 @@ export const COMMANDS = {
},
eval: {
summary: "Measure Fuobe Originals: run a suite, score, review blind, compare runs",
- usage: "fuobe eval <run|report|review|compare|promote|history|validate|setup|trash> [options] (from a Fuobe checkout)",
+ usage: "fuobe eval <run|report|review|compare|promote|covers|history|validate|setup|trash> [options] (from a Fuobe checkout)",
examples: ["fuobe eval run --suite selftest --engine demo", "fuobe eval run --suite soul --engine open --looks v1-general --variants recipe,prompt-only", "fuobe eval compare latest~1 latest --fail-on clip --threshold 1"],
passthrough: true,
run: evalHarness,
diff --git a/package.json b/package.json
index a1774b11..a285195e 100644
--- a/package.json
+++ b/package.json
@@ -26,7 +26,8 @@
"eval:history": "node scripts/eval/eval.mjs history",
"eval:validate": "node scripts/eval/eval.mjs validate",
"eval:setup": "node scripts/eval/eval.mjs setup",
- "eval:trash": "node scripts/eval/eval.mjs trash"
+ "eval:trash": "node scripts/eval/eval.mjs trash",
+ "eval:covers": "node scripts/eval/eval.mjs covers"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.135.0",
diff --git a/scripts/eval/README.md b/scripts/eval/README.md
index ae488e94..2478deab 100644
--- a/scripts/eval/README.md
+++ b/scripts/eval/README.md
@@ -76,7 +76,8 @@ harness measures what a user gets.
| `pnpm eval:report <runId\|latest>` | Scores again (only what changed) and rewrites `summary.json`, `report.html` and the history lines |
| `pnpm eval:review <runId>` | Serves the blind A/B page and saves ratings next to the run |
| `pnpm eval:compare <runA> <runB>` | Wins, losses and mean gain per metric. Exits 1 when a guarded metric regresses |
-| `pnpm eval:promote <runId>` | Applies the promote rule. `--record` writes the verdicts into the research JSON |
+| `pnpm eval:promote <runId>` | Applies the promote rule. `--record` writes the verdicts into the research JSON; `--apply-strengths` also lowers over-cooked strengths there |
+| `pnpm eval:covers <runId>` | Turns each promoted case's best render into its preset's cover (`public/previews/`, `src/lib/preset-previews.generated.ts`) |
| `pnpm eval:history` | Lists runs, newest first, and the per-case scores of one case (`--case soul/v1-general`) |
| `pnpm eval:validate` | Checks every case file, and that the generated suites match the research |
| `pnpm eval:setup` | Creates the metrics venv with uv (`--identity`, `--download`, `--dinov2`, `--torch-backend`) |
@@ -392,12 +393,30 @@ entry. Each record holds:
- the LoRAs it ran, and the strengths to try when half strength won.
A newer record for the same engine and case replaces the older one. The file keeps its format, so
-the diff shows only the records. Recording never changes a recipe, a strength or a default. Those
-remain code changes that a person reviews:
-
-1. Edit the research JSON.
-2. Regenerate the catalog.
-3. Check both engines.
+the diff shows only the records. Recording alone never changes a recipe, a strength or a default.
+
+`--record --apply-strengths` does lower strengths that over-cook: where half strength won, the entry's
+LoRAs take the strengths that variant ran, and the record lists each change (`appliedStrengths`). It
+still lands as a diff for a person to review. Defaults stay code changes that a person reviews:
+
+1. Review the research JSON's diff (or edit it).
+2. Regenerate the catalog (`pnpm gen:catalog`).
+3. Measure both engines again.
+
+## Covers: the renders become the preview media
+
+`pnpm eval:covers <runId>` takes the best render of each **promoted** case (best on the case's main
+metric) and makes it that preset's cover. A still becomes a JPEG of at most 768 px; a clip becomes its
+first 4 seconds, muted, at most 512 px, with its first frame as the poster. They go to
+`public/previews/<suite>/`, and `src/lib/preset-previews.generated.ts` lists them by preset id (a
+DoP preset, `effect-thunder-god`) or look id (`v1-general`). The gallery cards play a listed cover
+instead of their procedural preview.
+
+- `--variant catalog` takes that variant's renders for every case instead, such as what ships today.
+- `--dry-run` lists what it would pick.
+- Only Fuobe's own renders become covers: a demo run never does, nor a render whose LoRAs aren't
+ commercial. No Higgsfield preview is used anywhere.
+- It needs ffmpeg. Look at the media and the generated file's diff before committing them.
## Tests
diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjs
index 9c2a596f..f88621d7 100644
--- a/scripts/eval/eval.mjs
+++ b/scripts/eval/eval.mjs
@@ -8,6 +8,7 @@ import path from "node:path";
import { parseArgs } from "node:util";
import { loadSuite, suiteFiles, validateAll } from "./lib/cases.mjs";
import { compareRuns, compareText, promote, promoteText, researchRecords } from "./lib/compare.mjs";
+import { makeCovers } from "./lib/covers.mjs";
import { scoreRun } from "./lib/metrics.mjs";
import { METRICS_DIR, REPO_DIR, resultsDir } from "./lib/paths.mjs";
import { RECIPES_FILE } from "./lib/recipes.mjs";
@@ -54,7 +55,16 @@ const HELP = {
report: "pnpm eval:report <runId|latest> [--no-metrics] [--metrics clip,style] [--device cpu|cuda|auto] [--style-model clip|dinov2] [--force]",
review: "pnpm eval:review <runId|latest> [--against variants|references|<otherRunId>] [--port 4173] [--no-serve] [--limit n]",
compare: "pnpm eval:compare <runA[:variant]> <runB[:variant]> [--fail-on clip,aesthetic] [--threshold 1|5%] [--per-case]",
- promote: "pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain] [--record [--research file]] --record writes the verdicts into the research JSON",
+ promote: `pnpm eval:promote <runId> [--candidate recipe] [--against prompt-only,half-strength,plain] [--record [--apply-strengths] [--research file]]
+
+ --record writes each case's verdict into the research JSON entry it measured
+ --apply-strengths with --record: where half strength won, lowers that entry's LoRA strengths to the ones it ran
+ (review the diff, then pnpm gen:catalog and run both engines again)`,
+ covers: `pnpm eval:covers <runId> [--variant <name>] [--dry-run] [--public-dir public] [--manifest src/lib/preset-previews.generated.ts]
+
+ The best render of each promoted case becomes its preset's cover: encoded small into public/previews/<suite>/
+ and listed in src/lib/preset-previews.generated.ts, which the gallery cards show. --variant takes that
+ variant's renders for every case instead (catalog: what ships today). Demo runs never make covers.`,
history: "pnpm eval:history [--suite soul] [--case soul/v1-general] [--limit 20]",
validate: "pnpm eval:validate [suite files…] checks every case file and that the generated suites match the research",
trash: "pnpm eval:trash <runId> [--dry-run] moves the run's generations to that Fuobe's Trash (its results here stay)",
@@ -87,7 +97,7 @@ export async function main(argv, io = {}) {
print(rest[0] && HELP[rest[0]] ? HELP[rest[0]] : usage());
return 0;
}
- const commands = { run, report, review, compare, promote: promoteCmd, history, validate, setup, trash };
+ const commands = { run, report, review, compare, promote: promoteCmd, history, validate, setup, trash, covers };
if (!commands[command]) {
note(`Unknown command “${command}”.\n${usage()}`);
return 2;
@@ -294,15 +304,16 @@ async function compare(args, ctx) {
}
async function promoteCmd(args, ctx) {
- const { values: v, positionals } = parse(args, { candidate: { type: "string" }, against: { type: "string" }, record: { type: "boolean" }, research: { type: "string" } }, { positionals: true });
+ const { values: v, positionals } = parse(args, { candidate: { type: "string" }, against: { type: "string" }, record: { type: "boolean" }, "apply-strengths": { type: "boolean" }, research: { type: "string" } }, { positionals: true });
if (v.help) return ctx.print(HELP.promote), 0;
const { dir } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
const doc = promote(dir, { candidate: v.candidate, alternatives: list(v.against) });
ctx.print(v.json ? JSON.stringify(doc, null, 2) : promoteText(doc));
+ if (v["apply-strengths"] && !v.record) throw new Usage("--apply-strengths goes with --record");
if (!v.record) return 0;
// --record: the verdicts go into the research JSON for a person to review (git diff), never a default.
if (doc.engine === "demo") throw new Error("A demo run measures the harness, not models: there is nothing to record in the research.");
- const records = researchRecords(doc);
+ const records = researchRecords(doc, { applyStrengths: v["apply-strengths"] });
if (!records.length) return ctx.note("No look or motion in this run to record."), 0;
const file = path.resolve(v.research ?? path.join(REPO_DIR, RECIPES_FILE));
const recordsFile = path.join(dir, "research-records.json");
@@ -313,6 +324,11 @@ async function promoteCmd(args, ctx) {
if (r.status !== 0) throw new Error(`Recording failed: ${(r.stderr || r.stdout).trim().split("\n").at(-1)}`);
const res = JSON.parse(r.stdout);
ctx.note(`Recorded ${res.recorded} result${res.recorded === 1 ? "" : "s"} in ${path.relative(REPO_DIR, file) || file} (each entry's "eval" list). Review the diff; recipes and defaults change only by hand.`);
+ if (res.lowered?.length) {
+ ctx.note(`Lowered the strengths of ${res.lowered.length} LoRA${res.lowered.length === 1 ? "" : "s"} where half strength won:`);
+ for (const l of res.lowered) ctx.note(` ${l.entry}: ${l.file} ${l.from} → ${l.to}`);
+ ctx.note("Review the diff, run pnpm gen:catalog, and measure both engines again before committing.");
+ }
for (const m of res.missing) ctx.note(` not in the research: ${JSON.stringify(m)}`);
return 0;
}
@@ -386,6 +402,20 @@ async function trash(args, ctx) {
return 0;
}
+async function covers(args, ctx) {
+ const { values: v, positionals } = parse(args, { variant: { type: "string" }, "dry-run": { type: "boolean" }, "public-dir": { type: "string" }, manifest: { type: "string" } }, { positionals: true });
+ if (v.help) return ctx.print(HELP.covers), 0;
+ const { dir } = resolveRun(root(v, ctx.env), positionals[0] ?? "latest");
+ const r = makeCovers(dir, { variant: v.variant, dryRun: v["dry-run"], publicDir: v["public-dir"] && path.resolve(v["public-dir"]), manifest: v.manifest && path.resolve(v.manifest) });
+ if (v.json) return ctx.print(JSON.stringify(r, null, 2)), 0;
+ ctx.print(`${r.covers.length} cover${r.covers.length === 1 ? "" : "s"} from ${r.runId} (${r.engine}, ${r.variant})${v["dry-run"] ? " would be made" : ""}`);
+ for (const c of r.covers) ctx.print(` ${c.key} ← ${c.job}${c.metric ? ` (best ${c.metric}${c.score != null ? ` ${Number(c.score).toFixed(3)}` : ""})` : ""}`);
+ for (const sk of r.skipped.slice(0, 10)) ctx.print(` · ${sk.caseId}: ${sk.why}`);
+ if (r.skipped.length > 10) ctx.print(` · and ${r.skipped.length - 10} more`);
+ if (r.covers.length && !v["dry-run"]) ctx.note("Look at the media and the diff of src/lib/preset-previews.generated.ts before committing them.");
+ return 0;
+}
+
async function setup(args, ctx) {
const { values: v } = parse(args, { identity: { type: "boolean" }, dinov2: { type: "boolean" }, download: { type: "boolean" }, "torch-backend": { type: "string" } });
if (v.help) return ctx.print(HELP.setup), 0;
diff --git a/scripts/eval/lib/compare.mjs b/scripts/eval/lib/compare.mjs
index 1d4e46fa..b6be5800 100644
--- a/scripts/eval/lib/compare.mjs
+++ b/scripts/eval/lib/compare.mjs
@@ -287,7 +287,7 @@ const round = (x) => (typeof x === "number" ? Math.round(x * 10000) / 10000 : x)
* The records `promote --record` writes into the research JSON (fuobe_metrics/research.py puts them in
* place): one per case that measured a look or a motion. Demo runs have nothing to record.
*/
-export function researchRecords(doc, { date = new Date().toISOString().slice(0, 10) } = {}) {
+export function researchRecords(doc, { date = new Date().toISOString().slice(0, 10), applyStrengths = false } = {}) {
if (doc.engine === "demo") return [];
return doc.results
.filter((r) => r.target)
@@ -305,6 +305,8 @@ export function researchRecords(doc, { date = new Date().toISOString().slice(0,
against: r.against.map((a) => Object.fromEntries(Object.entries(a).map(([k, v]) => [k, v && typeof v === "object" ? { candidate: round(v.candidate), alternative: round(v.alternative) } : v]))),
loras: r.recipe?.loras ?? [],
...(r.suggested && { suggestedLoras: r.suggested }),
+ // --apply-strengths: research.py lowers the entry's LoRAs to the strengths half strength won with.
+ ...(applyStrengths && r.verdict === "lower strengths" && r.suggested?.length && { applyStrengths: true }),
}));
}
diff --git a/scripts/eval/lib/covers.mjs b/scripts/eval/lib/covers.mjs
new file mode 100644
index 00000000..ceba17ac
--- /dev/null
+++ b/scripts/eval/lib/covers.mjs
@@ -0,0 +1,159 @@
+// Real preset covers from measured runs (O8: "the renders become the preview media"). For each case of a
+// run, the best render of the variant that earned it (the promoted candidate, or a variant you name, such
+// as `catalog`: what ships today) is encoded small into public/previews/<suite>/ and listed in
+// src/lib/preset-previews.generated.ts, which the gallery cards read instead of their procedural preview.
+// Only Fuobe's own renders become covers: demo media never does, nor a render whose LoRAs aren't
+// commercial. A person reviews the media and the generated file before committing them.
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { promote } from "./compare.mjs";
+import { METRIC_INFO } from "./metric-info.mjs";
+import { REPO_DIR, safeName } from "./paths.mjs";
+import { jobScores, loadRun } from "./report.mjs";
+
+export const COVERS_DIR = path.join(REPO_DIR, "public", "previews");
+export const MANIFEST_FILE = path.join(REPO_DIR, "src", "lib", "preset-previews.generated.ts");
+
+/** Longest side of a cover still, and of a cover clip (px); a clip's first seconds. */
+const STILL_PX = 768;
+const CLIP_PX = 512;
+const CLIP_SECONDS = 4;
+
+const HEADER = `/**
+ * Real preset covers: renders from measured runs of the evaluation harness (scripts/eval, pnpm eval:covers),
+ * keyed by preset id (a DoP motion or effect: "effect-thunder-god") or Soul look id ("v1-general"). The gallery
+ * cards show them instead of the procedural preview. Generated by pnpm eval:covers: run it again rather than editing.
+ */
+export interface PresetPreviewMedia {
+ /** A still (the clip's first frame for motions and effects), under /previews. */
+ poster: string;
+ /** A short muted clip, for motions and effects. */
+ video?: string;
+ /** Where it came from: the run, its engine, the model and variant that made it. */
+ run: string;
+ engine: string;
+ model: string;
+ variant: string;
+}
+
+export const PRESET_PREVIEWS: Record<string, PresetPreviewMedia> = `;
+
+/** The manifest's entries as they stand (the JSON literal after the header). */
+export function readManifest(file = MANIFEST_FILE) {
+ try {
+ const text = fs.readFileSync(file, "utf8");
+ const at = text.indexOf("export const PRESET_PREVIEWS");
+ const json = text.slice(text.indexOf("=", at) + 1).trim().replace(/;\s*$/, "");
+ return JSON.parse(json);
+ } catch {
+ return {};
+ }
+}
+
+export function writeManifest(entries, file = MANIFEST_FILE) {
+ const sorted = Object.fromEntries(Object.entries(entries).sort(([a], [b]) => a.localeCompare(b)));
+ fs.mkdirSync(path.dirname(file), { recursive: true });
+ fs.writeFileSync(file, `${HEADER}${JSON.stringify(sorted, null, 2)};\n`);
+}
+
+/** The preset a case's cover belongs to: a DoP preset id, a Soul look's Fuobe id, else the case id. */
+function coverKey(row) {
+ if (row.recipe?.kind === "soul-look" && row.recipe.look?.slug) return row.recipe.look.slug;
+ return row.request?.presetId ?? row.caseId;
+}
+
+const mainOutput = (row) => (row.outputs ?? []).find((o) => (o.kind === "image" || o.kind === "video") && !["mask", "first-frame", "depth"].includes(o.role));
+
+/** The best succeeded job of a case and variant on `metric` (the first one when nothing is scored). */
+function bestJob(rows, metricsDoc, metric) {
+ const better = METRIC_INFO[metric]?.better === "lower" ? (a, b) => a < b : (a, b) => a > b;
+ let best = null;
+ let score = null;
+ for (const r of rows) {
+ if (!mainOutput(r)) continue;
+ const s = metric ? jobScores(r, metricsDoc)[metric] : undefined;
+ if (!best || (typeof s === "number" && (score == null || better(s, score)))) {
+ best = r;
+ score = typeof s === "number" ? s : score;
+ }
+ }
+ return best;
+}
+
+/** ffmpeg, or why there's none. */
+function run(args) {
+ const r = spawnSync(process.env.FUOBE_FFMPEG ?? "ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", ...args], { encoding: "utf8" });
+ if (r.error) throw new Error("eval:covers needs ffmpeg to make small covers (install it, or set FUOBE_FFMPEG)");
+ if (r.status !== 0) throw new Error(`ffmpeg failed: ${(r.stderr || "").trim().split("\n").at(-1)}`);
+}
+
+/** A still at most STILL_PX wide/tall, or a clip's first seconds at most CLIP_PX with its first frame as the poster. */
+function encode(src, kind, destBase) {
+ const fit = (px) => `scale='if(gt(iw,ih),min(${px},iw),-2)':'if(gt(iw,ih),-2,min(${px},ih))'`;
+ if (kind === "video") {
+ run(["-i", src, "-t", String(CLIP_SECONDS), "-an", "-vf", `${fit(CLIP_PX)},fps=24`, "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-movflags", "+faststart", `${destBase}.mp4`]);
+ run(["-i", `${destBase}.mp4`, "-frames:v", "1", "-q:v", "4", `${destBase}.jpg`]);
+ return { poster: `${destBase}.jpg`, video: `${destBase}.mp4` };
+ }
+ run(["-i", src, "-vf", fit(STILL_PX), "-frames:v", "1", "-q:v", "3", `${destBase}.jpg`]);
+ return { poster: `${destBase}.jpg` };
+}
+
+/**
+ * Make covers from a run.
+ * @param {string} dir the run folder
+ * @param {{ variant?: string, dryRun?: boolean, publicDir?: string, manifest?: string }} [opts]
+ * variant: take this variant's renders for every case (default: the promoted candidate's, promoted cases only)
+ * publicDir: the site's public folder (covers go to <publicDir>/previews/<suite>/); manifest: the generated file
+ */
+export function makeCovers(dir, opts = {}) {
+ const L = loadRun(dir);
+ if (L.run.engine === "demo") throw new Error("A demo run's media is the demo provider's, not Fuobe's: it never becomes a cover");
+ const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);
+ const outDir = path.join(publicDir, "previews", safeName(L.run.suite));
+ // The promote verdicts (as the run's scores and ratings stand now) say which cases earned a cover, and on which metric to pick the render.
+ const doc = promote(dir);
+ const byCase = new Map(doc.results.map((r) => [r.caseId, r]));
+ const variant = opts.variant ?? doc.candidate;
+ const picked = [];
+ const skipped = [];
+ for (const caseId of [...new Set(L.rows.map((r) => r.caseId))]) {
+ const verdict = byCase.get(caseId);
+ if (!opts.variant && verdict?.verdict !== "promote") {
+ skipped.push({ caseId, why: `${verdict?.verdict ?? "no verdict"}: only a promoted recipe's render becomes a cover (--variant <name> takes another variant's, such as what ships today)` });
+ continue;
+ }
+ const rows = L.rows.filter((r) => r.caseId === caseId && r.variant === variant && r.status === "succeeded");
+ // Licence: a render whose LoRAs can't be sold isn't shipped as a cover.
+ const lib = new Map((rows[0]?.recipe?.loras ?? []).map((l) => [l.file, l]));
+ const blocked = (rows[0]?.recipe?.applied ?? []).filter((l) => lib.get(l.file)?.commercial === false);
+ if (rows[0]?.recipe?.commercialOk === false || blocked.length) {
+ skipped.push({ caseId, why: `non-commercial LoRA${blocked.length > 1 ? "s" : ""} ${blocked.map((l) => l.file).join(", ")}`.trim() });
+ continue;
+ }
+ const metric = verdict?.mainMetric ?? null;
+ const best = bestJob(rows, L.metrics, metric);
+ if (!best) {
+ skipped.push({ caseId, why: `no ${variant} render` });
+ continue;
+ }
+ picked.push({ caseId, key: coverKey(best), row: best, metric, score: metric ? (jobScores(best, L.metrics)[metric] ?? null) : null });
+ }
+ const result = { runId: L.run.runId, engine: L.run.engine, variant, covers: [], skipped };
+ if (opts.dryRun) {
+ result.covers = picked.map((p) => ({ key: p.key, caseId: p.caseId, job: p.row.id, metric: p.metric, score: p.score }));
+ return result;
+ }
+ if (picked.length) fs.mkdirSync(outDir, { recursive: true });
+ const manifest = readManifest(opts.manifest);
+ for (const p of picked) {
+ const out = mainOutput(p.row);
+ const files = encode(path.join(dir, out.file), out.kind, path.join(outDir, safeName(p.key)));
+ const web = (f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`;
+ manifest[p.key] = { poster: web(files.poster), ...(files.video && { video: web(files.video) }), run: L.run.runId, engine: L.run.engine, model: p.row.model?.id ?? "", variant };
+ result.covers.push({ key: p.key, caseId: p.caseId, job: p.row.id, metric: p.metric, score: p.score, ...manifest[p.key] });
+ }
+ if (picked.length) writeManifest(manifest, opts.manifest);
+ return result;
+}
diff --git a/scripts/eval/metrics/fuobe_metrics/research.py b/scripts/eval/metrics/fuobe_metrics/research.py
index 870a6f7a..69fc086c 100644
--- a/scripts/eval/metrics/fuobe_metrics/research.py
+++ b/scripts/eval/metrics/fuobe_metrics/research.py
@@ -2,8 +2,10 @@
Each record lands in the `eval` list of the entry it measured: a Soul look's `presets[]` entry (by id)
or the `motionsEffects[]` entry that lists the motion or effect. A newer record for the same engine and
-case replaces the older one. Strengths and defaults are never changed here: the record says what the
-run found (and the lower strengths it suggests); a person changes the recipe in a reviewed commit.
+case replaces the older one. Strengths change only when a record asks (`applyStrengths`, from
+`--apply-strengths`, where half strength won): the entry's LoRAs take the strengths that run used, and
+the record lists each change. Nothing else in a recipe changes, and a person reviews the diff, runs
+gen:catalog and commits it.
Standard library only, so any Python 3 runs it. The file is written the way the research tools write
it (indent 1, UTF-8 kept, a final newline), so the diff shows only the records.
@@ -20,8 +22,8 @@ from pathlib import Path
CONVENTION = (
"eval: results from the evaluation harness (scripts/eval, pnpm eval:promote <run> --record), one per "
"engine and case: run id, date, candidate variant, verdict (promote / lower strengths / hold) and why, "
- "the look's main metric against each alternative, the LoRAs it ran and suggested lower strengths. "
- "A record never changes a recipe or a default; a person does, in a reviewed commit."
+ "the look's main metric against each alternative, the LoRAs it ran and suggested lower strengths "
+ "(appliedStrengths when --apply-strengths lowered them here). A person reviews and commits any change."
)
@@ -37,17 +39,37 @@ def _find(doc: dict, target: dict) -> dict | None:
return None
+def _lower(entry: dict, suggested: list[dict]) -> list[dict]:
+ """Set the entry's LoRAs (by file) to the suggested strengths; returns the changes made."""
+ changes = []
+ want = {s.get("file"): s.get("strength") for s in suggested if s.get("file") and isinstance(s.get("strength"), (int, float))}
+ for lora in entry.get("loras", []) or []:
+ to = want.get(lora.get("file"))
+ if to is None or lora.get("strength") == to:
+ continue
+ changes.append({"file": lora.get("file"), "from": lora.get("strength"), "to": to})
+ lora["strength"] = to
+ return changes
+
+
def apply_records(doc: dict, records: list[dict]) -> dict:
- """Put each record into its entry; returns {"recorded": n, "missing": [targets not found]}."""
+ """Put each record into its entry; returns {"recorded": n, "missing": [targets not found], "lowered": [changes]}."""
recorded = 0
missing = []
+ lowered = []
for rec in records:
target = rec.get("target") or {}
entry = _find(doc, target)
if entry is None:
missing.append(target)
continue
- body = {k: v for k, v in rec.items() if k != "target"}
+ body = {k: v for k, v in rec.items() if k not in ("target", "applyStrengths")}
+ if rec.get("applyStrengths") and rec.get("suggestedLoras"):
+ changes = _lower(entry, rec["suggestedLoras"])
+ if changes:
+ body["appliedStrengths"] = changes
+ name = target.get("look") or target.get("motion")
+ lowered.extend({"entry": entry.get("name") or name, **c} for c in changes)
if target.get("motion"):
body = {"preset": target["motion"], **body}
kept = [r for r in entry.get("eval", []) if not (r.get("engine") == body.get("engine") and r.get("case") == body.get("case"))]
@@ -55,7 +77,7 @@ def apply_records(doc: dict, records: list[dict]) -> dict:
recorded += 1
if recorded:
doc.setdefault("conventions", {})["eval"] = CONVENTION
- return {"recorded": recorded, "missing": missing}
+ return {"recorded": recorded, "missing": missing, "lowered": lowered}
def main(argv: list[str]) -> int:
diff --git a/scripts/eval/metrics/tests/test_research.py b/scripts/eval/metrics/tests/test_research.py
index 655218bb..5b15dead 100644
--- a/scripts/eval/metrics/tests/test_research.py
+++ b/scripts/eval/metrics/tests/test_research.py
@@ -20,7 +20,7 @@ def record(engine="open", case="soul/v1-general", verdict="hold", **target):
def test_records_land_in_their_entry_and_replace_the_same_engine_and_case():
d = doc()
out = research.apply_records(d, [record(), record(engine="cloud"), record(motion="crane up", case="dop/motion-crane-up")])
- assert out == {"recorded": 3, "missing": []}
+ assert out == {"recorded": 3, "missing": [], "lowered": []}
assert [r["engine"] for r in d["presets"][0]["eval"]] == ["open", "cloud"]
assert "target" not in d["presets"][0]["eval"][0]
assert d["motionsEffects"][0]["eval"][0]["preset"] == "crane up"
@@ -50,3 +50,18 @@ def test_the_file_keeps_its_format(tmp_path):
assert "Café → film" in text and "\\u" not in text
assert text.endswith("}\n") and text.startswith('{\n "conventions"')
assert json.loads(text)["presets"][0]["loras"][0]["strength"] == 1.0
+
+
+def test_apply_strengths_lowers_only_the_entry_it_measured_and_says_so():
+ d = doc()
+ suggested = [{"file": "a.safetensors", "strength": 0.5}, {"file": "not-in-entry.safetensors", "strength": 0.2}]
+ lower = {**record(verdict="lower strengths"), "suggestedLoras": suggested}
+ # Without applyStrengths the suggestion is only recorded.
+ research.apply_records(d, [lower])
+ assert d["presets"][0]["loras"][0]["strength"] == 1.0
+ out = research.apply_records(d, [{**lower, "applyStrengths": True}])
+ assert d["presets"][0]["loras"][0]["strength"] == 0.5
+ assert out["lowered"] == [{"entry": "General", "file": "a.safetensors", "from": 1.0, "to": 0.5}]
+ rec = d["presets"][0]["eval"][-1]
+ assert rec["appliedStrengths"] == [{"file": "a.safetensors", "from": 1.0, "to": 0.5}]
+ assert "applyStrengths" not in rec
diff --git a/src/lib/preset-cards.ts b/src/lib/preset-cards.ts
index bb3586ee..55a2977a 100644
--- a/src/lib/preset-cards.ts
+++ b/src/lib/preset-cards.ts
@@ -3,11 +3,12 @@
*
* Gallery pages are server components: they map the full catalog `Preset` (prompt templates,
* routes, LoRA URLs, parity notes) to `PresetCardData` here, so only what a card shows reaches
- * the browser. Until real preview clips exist, every card gets a procedural preview: a camera
- * move over a bundled layered still for motions, a per-category animated treatment for effects
- * and apps. Pure module, safe on both sides.
+ * the browser. A preset with a real cover (a measured render, see preset-previews.generated.ts) shows
+ * it; the others get a procedural preview: a camera move over a bundled layered still for motions, a
+ * per-category animated treatment for effects and apps. Pure module, safe on both sides.
*/
import type { Preset } from "./catalog/types";
+import { PRESET_PREVIEWS } from "./preset-previews.generated";
/** Bundled sample stills (public/samples/previews, see scripts/gen-preview-scenes.mjs). */
export type PreviewScene = "landscape" | "portrait" | "city" | "product";
@@ -381,6 +382,9 @@ export function previewScene(p: Pick<Preset, "type" | "name" | "category"> & { i
export function previewFor(p: Pick<Preset, "id" | "type" | "name" | "category">): PresetPreview {
const scene = previewScene(p);
+ // A real cover, rendered and measured by the evaluation harness (pnpm eval:covers), replaces the procedural one.
+ const real = PRESET_PREVIEWS[p.id];
+ if (real) return { poster: real.poster, ...(real.video && { video: real.video }), scene };
return {
poster: scenePoster(scene),
scene,
diff --git a/src/lib/preset-previews.generated.ts b/src/lib/preset-previews.generated.ts
new file mode 100644
index 00000000..b7c815f8
--- /dev/null
+++ b/src/lib/preset-previews.generated.ts
@@ -0,0 +1,18 @@
+/**
+ * Real preset covers: renders from measured runs of the evaluation harness (scripts/eval, pnpm eval:covers),
+ * keyed by preset id (a DoP motion or effect: "effect-thunder-god") or Soul look id ("v1-general"). The gallery
+ * cards show them instead of the procedural preview. Generated by pnpm eval:covers: run it again rather than editing.
+ */
+export interface PresetPreviewMedia {
+ /** A still (the clip's first frame for motions and effects), under /previews. */
+ poster: string;
+ /** A short muted clip, for motions and effects. */
+ video?: string;
+ /** Where it came from: the run, its engine, the model and variant that made it. */
+ run: string;
+ engine: string;
+ model: string;
+ variant: string;
+}
+
+export const PRESET_PREVIEWS: Record<string, PresetPreviewMedia> = {};
diff --git a/tests/eval-harness.test.ts b/tests/eval-harness.test.ts
index b0d5e4a2..81ebbed6 100644
--- a/tests/eval-harness.test.ts
+++ b/tests/eval-harness.test.ts
@@ -538,6 +538,53 @@ describe("report, blind review, compare and promote", () => {
expect(fs.readFileSync(copy, "utf8")).not.toMatch(/\\u[0-9a-f]{4}/);
// Demo runs have nothing to record.
expect((await run(["fake-demo-1"])).stderr).toMatch(/demo run measures the harness/);
+ // --apply-strengths: where half strength won, the entry's LoRAs take the strengths it ran (AWPortrait-Z 0.6 → 0.3), and the record says so.
+ const halves = store.latestJobs(runDir).map((r) => (r.variant === "half-strength" ? { ...r, recipe: { ...r.recipe, applied: [{ file: "AWPortrait-Z.safetensors", strength: 0.3 }] } } : r));
+ fs.writeFileSync(path.join(runDir, "jobs.jsonl"), halves.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ const lowered = await run(["fake-open-2", "--apply-strengths"]);
+ expect(lowered.code, lowered.stderr).toBe(0);
+ expect(lowered.stderr).toMatch(/General: AWPortrait-Z\.safetensors 0\.6 → 0\.3/);
+ const changed = JSON.parse(fs.readFileSync(copy, "utf8"));
+ const e2 = changed.presets.find((p: { id: string }) => p.id === look);
+ expect(e2.loras.map((l: { file: string; strength: number }) => [l.file, l.strength])).toEqual([["AWPortrait-Z.safetensors", 0.3], ["lenovo_z.safetensors", 0.35]]);
+ expect(e2.eval[0].appliedStrengths).toEqual([{ file: "AWPortrait-Z.safetensors", from: 0.6, to: 0.3 }]);
+ expect((await evalCli.main(["promote", "fake-open-2", "--apply-strengths"], { stdout: sink().stream, stderr: sink().stream, env: { ...process.env, FUOBE_EVAL_RESULTS: results } }))).toBe(2);
+ });
+
+ it("covers: the best render of each promoted case becomes its preset's cover, small, and listed for the gallery", async () => {
+ const pub = path.join(dir, "covers-public");
+ const out = path.join(pub, "previews", "soul");
+ const manifest = path.join(dir, "covers-manifest.ts");
+ const covers = (args: string[]) => cli(["covers", ...args, "--public-dir", pub, "--manifest", manifest]);
+ // A DoP run of clips: research beats catalog on its words, and the review agreed.
+ const clip = (c: number, w: number) => ({ clip: c, warp: w, drift: 0.02 });
+ const scores = Object.fromEntries(["s1001", "s2002", "s3003"].flatMap((s, i) => [[`effect-thunder-god--bridge--${s}--research`, clip(32 + i, 0.01)], [`effect-thunder-god--bridge--${s}--catalog`, clip(28, 0.02)]]));
+ const runDir = fakeRun("fake-dop-covers", "open", scores, { request: { presetId: "effect-thunder-god" } } as Partial<Row>, { candidate: "research", variants: ["catalog", "research"] });
+ const rows = store.latestJobs(runDir).map((r) => {
+ fs.copyFileSync(path.join(process.cwd(), "public/samples/demo-portrait.mp4"), path.join(runDir, "outputs", `${r.id}.mp4`));
+ return { ...r, outputs: [{ file: `outputs/${r.id}.mp4`, kind: "video" }] };
+ });
+ fs.writeFileSync(path.join(runDir, "jobs.jsonl"), rows.map((r) => JSON.stringify(r)).join("\n") + "\n");
+ // Not reviewed yet: held, so no cover.
+ expect((await covers(["fake-dop-covers"])).stdout).toMatch(/0 covers[\s\S]*hold: only a promoted recipe's render becomes a cover/);
+ review3(runDir);
+ rateFor(runDir, "research");
+ const dry = await covers(["fake-dop-covers", "--dry-run"]);
+ expect(dry.stdout).toMatch(/1 cover from fake-dop-covers \(open, research\) would be made\n effect-thunder-god ← effect-thunder-god--bridge--s3003--research \(best clip 34\.000\)/);
+ expect(fs.existsSync(out)).toBe(false);
+ if (spawnSync("ffmpeg", ["-version"]).status !== 0) return; // encoding needs ffmpeg
+ const r = await covers(["fake-dop-covers"]);
+ expect(r.code, r.stderr).toBe(0);
+ const entry = (await import("../scripts/eval/lib/covers.mjs")).readManifest(manifest)["effect-thunder-god"];
+ expect(entry).toEqual({ poster: "/previews/soul/effect-thunder-god.jpg", video: "/previews/soul/effect-thunder-god.mp4", run: "fake-dop-covers", engine: "open", model: "", variant: "research" });
+ const probe = JSON.parse(spawnSync("ffprobe", ["-v", "error", "-show_entries", "stream=width,height:format=duration", "-of", "json", path.join(out, "effect-thunder-god.mp4")], { encoding: "utf8" }).stdout);
+ expect(Math.max(probe.streams[0].width, probe.streams[0].height)).toBeLessThanOrEqual(512);
+ expect(Number(probe.format.duration)).toBeLessThanOrEqual(4.1);
+ expect(fs.statSync(path.join(out, "effect-thunder-god.jpg")).size).toBeGreaterThan(0);
+ // The gallery reads the manifest's format: a TS module whose entries round-trip.
+ expect(fs.readFileSync(manifest, "utf8")).toMatch(/^\/\*\*[\s\S]*export const PRESET_PREVIEWS: Record<string, PresetPreviewMedia> = \{\n {2}"effect-thunder-god": \{/m);
+ // Demo media never becomes a cover.
+ expect((await cli(["covers", "fake-demo-1"])).stderr).toMatch(/never becomes a cover/);
});
it("compare prints wins and losses and fails when a chosen metric regresses beyond the threshold", async () => {
diff --git a/tests/preset-cards.test.ts b/tests/preset-cards.test.ts
index bf9b9cc3..a6f29413 100644
--- a/tests/preset-cards.test.ts
+++ b/tests/preset-cards.test.ts
@@ -1,5 +1,10 @@
-import { describe, expect, it } from "vitest";
+import { describe, expect, it, vi } from "vitest";
import { APPS, EFFECTS, MOTIONS } from "@/lib/catalog";
+
+// One measured cover (pnpm eval:covers writes this file), for a preset id the catalog doesn't have.
+vi.mock("@/lib/preset-previews.generated", () => ({
+ PRESET_PREVIEWS: { "effect-measured-cover": { poster: "/previews/dop/effect-measured-cover.jpg", video: "/previews/dop/effect-measured-cover.mp4", run: "r", engine: "open", model: "oss-wan22-14b", variant: "research" } },
+}));
import {
appFx,
CAMERA_MOVES,
@@ -282,3 +287,13 @@ describe("preset how-to line", () => {
expect(presetHowTo({ type: "app", userPrompt: "none", inputs: [] })).toBe("Press Generate — no inputs needed.");
});
});
+
+describe("real covers", () => {
+ it("a preset with a measured cover shows that clip and its poster instead of the procedural preview", () => {
+ const measured = previewFor({ id: "effect-measured-cover", type: "effect", name: "Measured", category: "Elements" });
+ expect(measured).toMatchObject({ poster: "/previews/dop/effect-measured-cover.jpg", video: "/previews/dop/effect-measured-cover.mp4" });
+ expect(measured.fx).toBeUndefined();
+ // The others keep their procedural preview.
+ expect(previewFor({ id: "effect-other", type: "effect", name: "Other", category: "Elements" }).video).toBeUndefined();
+ });
+});