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.

35.2 KB
Raw Blame
#!/usr/bin/env node
// Writes the generated suites from the research, so the case files can't drift from it:
//   cases/soul.json  one case per Soul look (139, ids from docs/research/parity-image-studios.json)
//   cases/soul-cinema.json  Soul Cinema's one look (research soul.soulCinema) on cinematic scenes
//   cases/soul-hex.json  Soul HEX: Fuobe's own palettes in the prompt, and the open engine's palette lock
//   cases/dop.json   one case per DoP motion / effect that the research gives a LoRA, a camera pose or a camera LoRA
//   cases/dop-mix.json  Fuobe DoP's Mix: a move and an effect on one run, against the move alone
//   cases/dop-mixed-media.json  DoP's Mixed Media effects in the cloud, blind: Fuobe DoP against Kling 2.5 Turbo
//   cases/separation.json  soundtrack separation (DBS D4): DBS-TIGER vs DBS-BSRNN, mono vs each channel, DBS vs MelBand for the dub, Demucs
//   cases/case.schema.json  the suite format as JSON Schema (for editors)
// The prompts are Fuobe's own (never copied from the parity studio). Run: node scripts/eval/gen-cases.mjs [--check]
import fs from "node:fs";
import path from "node:path";
import { pathToFileURL } from "node:url";
import { CASES_DIR, REPO_DIR } from "./lib/paths.mjs";
import { pinnedLora, research, slug, soulLooks } from "./lib/recipes.mjs";
import { schemaJson } from "./lib/schema.mjs";

/** Subjects every look is tried on; the first two go to every look (so looks compare on the same scenes and seeds). */
const SOUL_PROMPTS = [
  { id: "portrait", seed: 1001, text: "a young woman with freckles and loose dark hair looks over her shoulder on a quiet city street" },
  { id: "street", seed: 2002, text: "a man in a long camel coat crosses a pedestrian crossing, full body, morning light" },
  { id: "friends", seed: 3003, text: "two friends laughing together on a rooftop at dusk, the skyline behind them" },
  { id: "kitchen", seed: 3003, text: "a cosy kitchen in morning light, a woman pours coffee while a cat sits on the counter" },
  { id: "fisherman", seed: 3003, text: "an old fisherman mending a net on a wooden pier, weathered hands, overcast sky" },
  { id: "skater", seed: 3003, text: "a teenager on a skateboard under neon shop signs at night, motion in the background" },
  { id: "cyclist", seed: 3003, text: "a lone cyclist on a coastal road between green cliffs and the sea" },
  { id: "perfume", seed: 3003, text: "a glass perfume bottle on a marble table beside a sprig of white flowers" },
  { id: "dog", seed: 3003, text: "a golden retriever with sunglasses in the passenger seat of a convertible" },
  { id: "dancer", seed: 3003, text: "a dancer mid-leap in an empty rehearsal studio with tall windows" },
  { id: "market", seed: 3003, text: "a woman choosing oranges at a busy outdoor market stall" },
  { id: "musician", seed: 3003, text: "a guitarist playing on a small stage in a dim bar, people in the foreground" },
];

/** Stable pick of the third subject per look (a hash of the look id). */
function thirdPrompt(id) {
  let h = 0;
  for (const ch of id) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
  const rest = SOUL_PROMPTS.slice(2);
  return rest[h % rest.length];
}

const HEADER = "Generated by scripts/eval/gen-cases.mjs from the research files; edit the generator, not this file.";

function soulSuite() {
  const looks = soulLooks();
  if (looks.length !== 139) throw new Error(`expected 139 Soul looks, found ${looks.length}`);
  const missing = looks.filter((l) => !l.recipe).map((l) => l.id);
  if (missing.length) throw new Error(`no research recipe for ${missing.join(", ")}`);
  const qwen = { open: ["oss-qwen-image"], demo: ["oss-qwen-image"], cloud: ["fuobe-soul-hd"] };
  return {
    $schema: "./case.schema.json",
    suite: "soul",
    title: "Fuobe Soul · the 139 looks",
    description: `${HEADER} Each look on three subjects with pinned seeds: the research recipe (look template, triggers, LoRAs at their listed strengths) against the same words without LoRAs, half-strength LoRAs, the bare prompt, and the shipped Original (fuobe-soul; Soul HD for a lettering look). The Original's grade and overlay are applied in the browser after generation, so its scores are of the raw picture. Style references (your own or licensed images, never copied previews) go in local/references/soul/<look>/.`,
    original: ["fuobe-soul", "fuobe-soul-hd"],
    kind: "image",
    recipe: "soul-look",
    targets: {
      // Today's bases; the Soul recipe (§4) is applied by the harness. fal's Z-Image LoRA endpoint takes the LoRAs.
      open: { models: ["oss-z-image-turbo"], extra: { steps: 8, shift: 3 } },
      cloud: { models: ["z-image-turbo-cloud"], extra: { num_inference_steps: 8, enable_prompt_expansion: false, output_format: "png" } },
      demo: { models: ["oss-z-image-turbo"] },
    },
    defaults: {
      seeds: [1001],
      params: { aspectRatio: "3:4" },
      metrics: ["clip", "aesthetic", "style"],
      variant: "recipe",
      timeoutSeconds: 900,
    },
    variants: {
      recipe: { description: "The research recipe: look template, LoRA triggers and LoRAs at the listed strengths" },
      "prompt-only": { description: "The look's words without LoRAs: does each LoRA earn its slot?", loras: "none" },
      "half-strength": { description: "The recipe with every LoRA at half strength (over-cooking check)", loraScale: 0.5 },
      plain: { description: "The base model with the subject prompt alone", template: false, loras: "none" },
      original: {
        description: "The shipped Original on the server (O2's fuobe-soul, on the engine the run names): the look's Fuobe id (v1-general) goes in presetId and the server applies its own recipe",
        models: { open: ["fuobe-soul"], cloud: ["fuobe-soul"], demo: ["fuobe-soul"] },
        lookParam: "presetId",
      },
    },
    cases: looks.map((l) => ({
      id: `soul/${l.slug}`,
      title: `Soul ${l.family === "v1" ? "v1" : "2.0"} · ${l.name}`,
      look: l.id,
      // A lettering look is made for Qwen-Image 2512: the Original that runs it is Fuobe Soul HD.
      ...(l.recipe.base === "qwen-image-2512" && { models: qwen, variantModels: { original: { open: ["fuobe-soul-hd"], cloud: ["fuobe-soul-hd"], demo: ["fuobe-soul-hd"] } }, extra: { steps: 20 } }),
      prompts: [SOUL_PROMPTS[0], SOUL_PROMPTS[1], thirdPrompt(l.id)],
      references: `local/references/soul/${l.slug}`,
      tags: [l.family, slug(l.category) || "all", slug(l.recipe.coverage), ...(l.recipe.trainOwn ? ["train-own"] : []), ...(l.recipe.needsCivitaiToken ? ["civitai"] : [])],
    })),
  };
}

/** Today's Z-Image Turbo bases with Soul's sampler settings (§4); the Originals apply their own. */
const SOUL_TARGETS = {
  open: { models: ["oss-z-image-turbo"], extra: { steps: 8, shift: 3 } },
  cloud: { models: ["z-image-turbo-cloud"], extra: { num_inference_steps: 8, enable_prompt_expansion: false, output_format: "png" } },
  demo: { models: ["oss-z-image-turbo"] },
};
const everywhere = (id) => ({ open: [id], cloud: [id], demo: [id] });

/** A research library LoRA (loraLibrary[key]) as a case's LoRA, at the recipe's strength. */
function libraryLora(key, strength) {
  const l = research().recipes.loraLibrary.find((x) => x.key === key);
  if (!l) throw new Error(`no LoRA ${key} in the research's loraLibrary`);
  return {
    name: l.name,
    file: l.file,
    // Pinned to the research's commit, as the app's LoRA library downloads it.
    url: pinnedLora(l).url,
    ...(l.hostedUrl && { hostedUrl: l.hostedUrl }),
    strength,
    ...(l.trigger && { trigger: l.trigger }),
    base: l.base,
    licence: l.licence,
    commercial: l.commercial !== false,
    hostedOk: l.hostedOk !== false,
    download: l.download ?? (/civitai\.com/.test(l.url ?? "") ? "civitai-token" : "direct"),
  };
}

/** Cinematic scenes for Soul Cinema (Fuobe's own words), one pinned seed each. */
const CINEMA_SCENES = [
  { id: "diner", seed: 4101, text: "a waitress refills a coffee cup for a tired trucker in an empty roadside diner at night" },
  { id: "platform", seed: 4102, text: "a woman in a trench coat waits alone on a rain-soaked train platform, wide shot" },
  { id: "rooftop", seed: 4103, text: "two detectives argue on a rooftop above a city at blue hour" },
  { id: "desert", seed: 4104, text: "a lone rider crosses a desert ridge at sunset, long shadow, wide landscape" },
  { id: "kitchen", seed: 4105, text: "a family eats breakfast in a sunlit farmhouse kitchen, the youngest spills milk" },
  { id: "corridor", seed: 4106, text: "a nurse walks down a hospital corridor at 3am under flickering lights" },
];

function soulCinemaSuite() {
  const { soul } = research().recipes;
  const cinema = soul.soulCinema;
  const tail = soul.template.tails[cinema.tail];
  if (!tail) throw new Error(`no "${cinema.tail}" tail in the research's soul.template.tails`);
  const loras = cinema.loras.map((l) => libraryLora(l.key, l.strength));
  return {
    $schema: "./case.schema.json",
    suite: "soul-cinema",
    title: "Fuobe Soul Cinema · one film look",
    description: `${HEADER} Soul Cinema has one fixed look (research soul.soulCinema): ${loras.map((l) => `${l.name} at ${l.strength}`).join(" + ")}, the "${cinema.tail}" tail, a ${cinema.grades.join(" or ")} grade after generation (in the browser, so the Original's scores are of the raw picture) and ${cinema.defaultAspect} by default. The recipe on today's base against its words alone, the bare prompt, and the shipped Original (fuobe-soul-cinema). A civitai LoRA without a mirrored copy is left out on the cloud (the runner says so). Style references (your own or licensed film stills) go in local/references/soul-cinema/.`,
    original: "fuobe-soul-cinema",
    kind: "image",
    targets: SOUL_TARGETS,
    defaults: {
      seeds: [1001],
      params: { aspectRatio: cinema.defaultAspect },
      metrics: ["clip", "aesthetic", "style"],
      variant: "recipe",
      timeoutSeconds: 900,
    },
    variants: {
      recipe: { description: "Soul Cinema's research recipe on today's base: its LoRAs with their triggers, then the cine tail", loras, words: tail },
      "prompt-only": { description: "The cine tail without the LoRAs: do they earn their slots?", loras: "none", words: tail },
      plain: { description: "The base model with the scene alone", template: false, loras: "none" },
      original: { description: "The shipped Original (fuobe-soul-cinema): the server adds its LoRAs, tail and grade", models: everywhere("fuobe-soul-cinema"), loras: "none" },
    },
    cases: CINEMA_SCENES.map((p) => ({
      id: `soul-cinema/${p.id}`,
      title: `Soul Cinema · ${p.id}`,
      prompts: [p],
      references: "local/references/soul-cinema",
      tags: ["cinema"],
    })),
  };
}

/** Fuobe's own palettes for Soul HEX (never copied from the parity studio), five colours each, dark to light. */
const HEX_PALETTES = [
  { id: "teal-dusk", name: "Teal dusk", colors: ["#0B1D2A", "#1F4E5F", "#2A9D8F", "#E9C46A", "#F4A261"] },
  { id: "candy-pop", name: "Candy pop", colors: ["#118AB2", "#06D6A0", "#FF5DA2", "#FFD166", "#FDF6EC"] },
  { id: "green-editorial", name: "Green editorial", colors: ["#1B1B1B", "#0F3D2E", "#2E7D4F", "#A7C957", "#F2E8CF"] },
];

const HEX_PROMPTS = [
  { id: "portrait", seed: 5101, text: "a woman in a knitted sweater sits by a window with a cup of tea, half-length portrait" },
  { id: "still-life", seed: 5102, text: "a still life of fruit, a ceramic jug and a folded cloth on a wooden table" },
];

/** The palette sentence the composer's Color signature adds (src/lib/catalog/palettes.ts palettePrompt, no background). */
export const hexWords = (colors) => `Color palette: use only these colors, in roughly this balance: ${colors.map((c) => c.toUpperCase()).join(", ")}.`;

function soulHexSuite() {
  return {
    $schema: "./case.schema.json",
    suite: "soul-hex",
    title: "Fuobe Soul HEX · palettes",
    description: `${HEADER} A palette on Fuobe Soul, as the composer's Color signature sends it: the colours in the prompt on both engines, and on the open engine the palette lock after it (oss-palette-image, POST /api/palettes/lock: on by default for Fuobe Soul). Against the same words on today's base, Z-Image Turbo · Palette (the open engine's palette model before the Originals) and Fuobe Soul without the palette. The palette metric scores how closely each picture keeps to the colours (mean ΔE to the nearest one, and how many of them it uses). The palettes are Fuobe's own.`,
    original: "fuobe-soul",
    kind: "image",
    targets: SOUL_TARGETS,
    defaults: {
      seeds: [1001],
      params: { aspectRatio: "3:4" },
      metrics: ["palette", "clip", "aesthetic"],
      variant: "words",
      timeoutSeconds: 900,
    },
    variants: {
      words: { description: "Fuobe Soul (its General look) with the palette in the prompt: the cloud's Soul HEX", models: everywhere("fuobe-soul") },
      lock: {
        description: "Fuobe Soul with the palette in the prompt, then the palette lock (strength 0.8): the open engine's Soul HEX",
        models: { open: ["fuobe-soul"], demo: ["fuobe-soul"] },
        engines: ["demo", "open"],
        submit: { route: "/api/palettes/lock", body: { request: "{{request}}", colors: "{{request.params.palette}}" }, estimate: false },
      },
      base: { description: "The palette in the prompt on today's base, no look" },
      "palette-model": {
        description: "Z-Image Turbo · Palette: the provider writes the colours into the prompt and locks them in one graph (open engine)",
        models: { open: ["oss-zimage-palette"], demo: ["oss-zimage-palette"] },
        engines: ["demo", "open"],
        template: false,
      },
      plain: { description: "Fuobe Soul without the palette's words (the control)", models: everywhere("fuobe-soul"), template: false },
    },
    cases: HEX_PALETTES.map((p) => ({
      id: `soul-hex/${p.id}`,
      title: `Soul HEX · ${p.name}`,
      words: hexWords(p.colors),
      params: { palette: p.colors },
      prompts: HEX_PROMPTS,
      tags: ["hex"],
    })),
  };
}

/** Preset names the catalog has (motions.ts specs), so every DoP case's presetId exists. */
function catalogPresetNames() {
  const src = fs.readFileSync(path.join(REPO_DIR, "src/lib/catalog/motions.ts"), "utf8");
  const effectsAt = src.indexOf("const EFFECT_SPECS");
  const names = (text) => new Set([...text.matchAll(/\{\s*name: "([^"]+)"/g)].map((m) => m[1]));
  const endFrames = new Set([...src.matchAll(/\{\s*name: "([^"]+)"[^\n]*endFrame: true/g)].map((m) => m[1]));
  return { motion: names(src.slice(0, effectsAt)), effect: names(src.slice(effectsAt)), endFrames };
}

/** Research statuses with a LoRA to A/B (§7.2); prompt-only presets have nothing to compare yet. */
const LORA_STATUSES = new Set(["add-lora", "alias", "replace", "weak-candidate", "local-only", "relight-route"]);

/**
 * The models a DoP preset runs on when it isn't Fuobe DoP's Wan (src/lib/catalog/dop.ts): an LTX-2.3 LoRA runs on Fuobe
 * DoP · LTX on both engines; an LTX-2.5 LoRA on the open LTX-2.5 graph only. In the cloud the harness measures Fuobe
 * DoP on its words, against the partner model the catalog keeps there until a run promotes it.
 */
function dopModels(m) {
  const bases = (m.loras ?? []).map((l) => l.base ?? "");
  if (m.status === "relight-route" || bases.some((b) => /^wan2\.[12]/.test(b))) return undefined;
  if (bases.some((b) => /^ltx-2(\.3-|-19b)/.test(b))) return everywhere("fuobe-dop-ltx");
  if (bases.some((b) => /^ltx-2\.5/.test(b))) return { open: ["oss-ltx25"], demo: ["oss-ltx25"], cloud: ["fuobe-dop"] };
  return undefined;
}

function dopSuite() {
  const catalog = catalogPresetNames();
  const cases = [];
  const later = [];
  for (const m of research().recipes.motionsEffects) {
    if (!LORA_STATUSES.has(m.status) || !(m.loras ?? []).length) continue;
    for (const name of m.presets) {
      if (!catalog[m.kind].has(name)) {
        later.push(name);
        continue;
      }
      const transition = catalog.endFrames.has(name);
      const models = dopModels(m);
      cases.push({
        id: `dop/${m.kind}-${slug(name)}`,
        title: `DoP ${m.kind} · ${name}`,
        motion: name,
        presetId: `${m.kind}-${slug(name)}`,
        ...(transition && { op: "flf2v" }),
        ...(models && { models }),
        inputs: { images: ["local/dop/start.png"], ...(transition && { endImage: "local/dop/end.png" }) },
        demoInputs: { images: ["fixtures/start-frame.png"], ...(transition && { endImage: "fixtures/end-frame.png" }) },
        ...(m.status === "local-only" && { engines: ["demo", "open"], note: "local-only LoRAs (civitai RentCivit): open engine only" }),
        tags: [m.kind, m.status, ...(transition ? ["transition"] : [])],
      });
    }
  }
  // The camera moves the map v2 gives a pose or a camera LoRA (§7.3): Wan 2.2 Fun Camera on the GPU, LTX-2.3's camera
  // LoRA (or LTX-2.5's move) in the cloud. Prompt-only (preset strength 0) turns the camera LoRA off.
  const ids = new Set(cases.map((c) => c.id));
  for (const m of research().recipes.motionsEffects) {
    for (const name of m.presets) {
      const lora = m.cameraLora?.[name];
      const move = m.cameraMotion?.[name];
      const pose = m.funCamera?.[name];
      const id = `dop/${m.kind}-${slug(name)}`;
      if ((!lora && !move && !pose) || ids.has(id) || !catalog[m.kind].has(name)) continue;
      ids.add(id);
      const transition = catalog.endFrames.has(name);
      const cloud = move ? "ltx-2-5-fast" : lora ? "fuobe-dop-ltx" : "fuobe-dop";
      cases.push({
        id,
        title: `DoP ${m.kind} · ${name} (camera)`,
        motion: name,
        presetId: `${m.kind}-${slug(name)}`,
        ...(transition && { op: "flf2v" }),
        ...(cloud !== "fuobe-dop" && { models: { open: ["fuobe-dop"], demo: ["fuobe-dop"], cloud: [cloud] } }),
        inputs: { images: ["local/dop/start.png"], ...(transition && { endImage: "local/dop/end.png" }) },
        demoInputs: { images: ["fixtures/start-frame.png"], ...(transition && { endImage: "fixtures/end-frame.png" }) },
        ...(move && { params: { duration: 6 } }),
        tags: [m.kind, m.status, "camera", ...(pose && !transition ? ["fun-camera"] : []), ...(lora ? ["camera-lora"] : []), ...(transition ? ["transition"] : [])],
        note: [pose && !transition ? `GPU: Wan 2.2 Fun Camera "${pose}"` : "", lora ? `cloud: LTX-2.3 camera_lora ${lora}` : "", move ? `cloud: LTX-2.5 camera_motion ${move}` : ""].filter(Boolean).join(" · "),
      });
    }
  }
  return {
    suite: {
      $schema: "./case.schema.json",
      suite: "dop",
      title: "Fuobe DoP · camera motions and effects with LoRAs",
      description: `${HEADER} Every motion and effect the research gives a LoRA (§7.2), on your start frame (local/dop/start.png, plus local/dop/end.png for transitions; a photo of a person on a bridge matches the prompt), on the Original that runs it: Fuobe DoP (Wan 2.2 on your GPU, fal's Wan 2.2 LoRA endpoint in the cloud), Fuobe DoP · LTX for the LTX-2.3 LoRAs, the open LTX-2.5 graph for the LTX-2.5 ones. Variants: the catalog preset as it ships (the map v2), its prompt without LoRAs (preset strength 0), the research's LoRAs at their listed strengths sent by the harness (the same request as the catalog's until the strengths are tuned), and the preset's words on a partner model (Kling 2.5 Turbo). Not in the catalog yet: ${later.length ? later.join(", ") : "none"}.`,
      original: ["fuobe-dop", "fuobe-dop-ltx"],
      kind: "video",
      recipe: "motion",
      targets: {
        open: { models: ["fuobe-dop"], params: { duration: 5 } },
        cloud: { models: ["fuobe-dop"], params: { duration: 5 } },
        demo: { models: ["fuobe-dop"], params: { duration: 5 } },
      },
      defaults: {
        seeds: [1001, 2002],
        prompts: [{ id: "bridge", text: "a woman in a red coat on a city bridge at golden hour" }],
        metrics: ["temporal", "clip"],
        variant: "catalog",
        candidate: "research",
        timeoutSeconds: 2700,
      },
      variants: {
        catalog: { description: "The catalog preset as it ships on Fuobe DoP (prompt template + the LoRA map v2)" },
        "prompt-only": { description: "The preset's prompt without LoRAs (preset strength 0)", presetStrength: 0 },
        research: { description: "The research's LoRA map v2 at the listed strengths on the preset's prompt", presetStrength: 0, loras: "recipe" },
        partner: { description: "The preset's words on a partner model (Kling 2.5 Turbo), for reference", models: { cloud: ["kling-2-5-turbo"] }, engines: ["cloud"] },
      },
      cases,
    },
    later,
  };
}

/** Fuobe's own Mix pairs (a move and an effect, research §7.5): the second preset's LoRAs stack on the first's model. */
const MIX_PAIRS = [
  ["motion-overhead", "effect-building-explosion"],
  ["motion-handheld", "effect-glitch"],
  ["motion-robo-arm", "effect-money-rain"],
  ["motion-dolly-in", "effect-hero-flight"],
  // A camera LoRA in the cloud (LTX-2.3) with a Wan effect: the effect joins as words there.
  ["motion-jib-up", "effect-freezing"],
];

function dopMixSuite() {
  const catalog = catalogPresetNames();
  const name = (id) => [...catalog.motion, ...catalog.effect].find((n) => id.endsWith(`-${slug(n)}`) && (id.startsWith("motion-") ? catalog.motion.has(n) : catalog.effect.has(n)));
  const cases = MIX_PAIRS.map(([first, second]) => {
    const [a, b] = [name(first), name(second)];
    if (!a || !b) throw new Error(`Mix pair ${first} + ${second}: not in the catalog`);
    return {
      id: `dop-mix/${slug(a)}--${slug(b)}`,
      title: `Mix · ${a} + ${b}`,
      presetId: first,
      mix: { presetId: second, strength: 0.6 },
      ...(first === "motion-jib-up" && { models: { open: ["fuobe-dop"], demo: ["fuobe-dop"], cloud: ["fuobe-dop-ltx"] } }),
      inputs: { images: ["local/dop/start.png"] },
      demoInputs: { images: ["fixtures/start-frame.png"] },
      tags: ["mix"],
    };
  });
  return {
    $schema: "./case.schema.json",
    suite: "dop-mix",
    title: "Fuobe DoP · Mix (a move and an effect on one run)",
    description: `${HEADER} Fuobe DoP's Mix on both engines: the second preset's LoRAs stack on the first's model, each scaled by its strength (0.6 here), and its words join the prompt. A LoRA for another base (a Wan effect on an LTX-2.3 camera move) joins as words only. Variants: the Mix, and the first preset alone.`,
    original: ["fuobe-dop", "fuobe-dop-ltx"],
    kind: "video",
    targets: {
      open: { models: ["fuobe-dop"], params: { duration: 5 } },
      cloud: { models: ["fuobe-dop"], params: { duration: 5 } },
      demo: { models: ["fuobe-dop"], params: { duration: 5 } },
    },
    defaults: {
      seeds: [1001, 2002],
      prompts: [{ id: "bridge", text: "a woman in a red coat on a city bridge at golden hour" }],
      metrics: ["temporal", "clip"],
      variant: "first",
      candidate: "mix",
      timeoutSeconds: 2700,
    },
    variants: {
      mix: { description: "Both presets: the first at full strength, the second's LoRAs at 0.6" },
      first: { description: "The first preset alone (no Mix)", mix: false },
    },
    cases,
  };
}

/**
 * DoP's Mixed Media effects (research motionsEffects[status mixed-media-route], 32 of them) that the comparison runs: drawn,
 * film, craft and colour looks, five with a look LoRA and three on their words (src/lib/catalog/mixed-media-looks.ts).
 */
const MIXED_MEDIA_PICKS = ["Sketch", "Noir", "Vintage", "Paper", "Hand Paint", "Comic", "Two Color", "Broken Mirror"];

/** The DoP Mixed Media default since 2026-10-30. */
export const DOP_MIXED_MEDIA_RULE =
  "Fuobe DoP stays the cloud default for DoP's 32 Mixed Media effects unless it clearly loses this blind comparison: in one cloud run with at least 6 blind ratings per case, Kling 2.5 Turbo takes at least two thirds of all non-tie ratings and more than half of them in at least 6 of the 8 cases. Then the default goes back to Kling 2.5 Turbo, in a reviewed code change (src/lib/catalog/dop.ts); anything less keeps Fuobe DoP.";

function dopMixedMediaSuite() {
  const catalog = catalogPresetNames();
  const effects = research().recipes.motionsEffects.filter((m) => m.status === "mixed-media-route").flatMap((m) => m.presets);
  if (effects.length !== 32) throw new Error(`expected DoP's 32 Mixed Media effects, found ${effects.length}`);
  const cases = MIXED_MEDIA_PICKS.map((name) => {
    if (!effects.includes(name) || !catalog.effect.has(name)) throw new Error(`Mixed Media effect ${name}: not in the research's 32 or not in the catalog`);
    return {
      id: `dop-mixed-media/${slug(name)}`,
      title: `DoP Mixed Media · ${name}`,
      motion: name,
      presetId: `effect-${slug(name)}`,
      inputs: { images: ["local/dop/start.png"] },
      demoInputs: { images: ["fixtures/start-frame.png"] },
      tags: ["effect", "mixed-media-route"],
    };
  });
  return {
    $schema: "./case.schema.json",
    suite: "dop-mixed-media",
    title: "Fuobe DoP · Mixed Media effects against Kling 2.5 Turbo (blind)",
    description: `${HEADER} The first suite to run once you have paid keys. ${cases.length} of DoP's ${effects.length} Mixed Media effects on your start frame (local/dop/start.png, a person on a bridge), in the cloud, rated blind: the preset as it ships (Fuobe Mixed Media draws the still in the look, then Fuobe DoP animates it) against the preset's words on Kling 2.5 Turbo, its cloud default before build plan O9. The demo engine runs the Original only, to check the suite.`,
    original: ["fuobe-dop"],
    kind: "video",
    recipe: "motion",
    runFirst: "paid-keys",
    decides: DOP_MIXED_MEDIA_RULE,
    targets: {
      cloud: { models: ["fuobe-dop"], params: { duration: 5 } },
      demo: { models: ["fuobe-dop"], params: { duration: 5 } },
    },
    defaults: {
      seeds: [1001, 2002],
      prompts: [{ id: "bridge", text: "a woman in a red coat on a city bridge at golden hour" }],
      metrics: ["temporal", "clip"],
      variant: "original",
      candidate: "original",
      timeoutSeconds: 2700,
    },
    variants: {
      original: { description: "The preset as it ships in the cloud: the still drawn in the look by Fuobe Mixed Media, then Fuobe DoP" },
      partner: { description: "The preset's words on Kling 2.5 Turbo (the default before O9), on your unchanged start frame", models: { cloud: ["kling-2-5-turbo"] }, engines: ["cloud"] },
    },
    cases,
  };
}

/**
 * The separation suite's test mixes (scripts/eval/fixtures/make-separation.py writes them, with their known stems, into
 * local/separation/<id>/): what each one checks. "real" is your own clip, for the blind A/B page only.
 */
const SEPARATION_MIXES = [
  { id: "centre", title: "Dialogue in the centre over music and effects", checks: "the reference mix: every stem against its known part" },
  { id: "off-centre", title: "Dialogue panned left over the same music and effects", checks: "the fast stereo bed (mono speech subtracted from each channel) leaves part of off-centre speech in the bed" },
  { id: "hum", title: "Dialogue with a steady 50 Hz mains hum", checks: "where steady hum goes (noiseInVoice: the share left in the dialogue)" },
  { id: "hiss", title: "Dialogue with steady tape hiss", checks: "where steady hiss goes" },
  { id: "loud", title: "A loud master that peaks at −0.1 dBFS", checks: "a loud master whose peaks are the dialogue's: the bed stays well under full scale (bedLevel, bedPeak)" },
  { id: "loud-bed", title: "A loud master whose music and effects reach full scale", checks: "AudioMerge scales a bed that peaks over full scale down as a whole (bedScale, bedLevel, bedPeak; the known bed's own peak is in meta.json)" },
  { id: "video", title: "The centre mix inside a video (H.264 + AAC)", checks: "a video source: the soundtrack read straight from the clip", video: true },
];

/** The DBS weights' licence from the research (information, recorded with the suite). */
function dbsLicences() {
  const doc = JSON.parse(fs.readFileSync(path.join(REPO_DIR, "docs/research/dbs-separation-7.json"), "utf8"));
  return doc.models.map((m) => `${m.name} ${m.licence} (${m.repo}@${m.revision.slice(0, 8)}; trained on ${m.trainedOn})`).join("; ");
}

export const SEPARATION_RULE =
  "Defaults change only on these numbers, in a reviewed code change: the open split's model per host (src/lib/av/split.ts) is the faster model unless the other wins dialogue SI-SDR by more than 1 dB on most mixes at a speed the host can live with (a minute of audio in under 5 minutes on a CPU); stereo stems (each channel) become the default only if the fast stereo bed loses its stereo image (bed stereo gap over 0.1) or its level (over 1 dB) on the centred mixes; the dub's voice split (src/lib/av/dub.ts DEFAULT_VOICE_SPLIT) moves to DBS when its dialogue WER is no worse than MelBand RoFormer's and its bed keeps the music and effects (background SI-SDR at least 3 dB higher).";

function separationSuite() {
  const asr = { asrModel: "Qwen/Qwen3-ASR-0.6B-hf" };
  const cases = SEPARATION_MIXES.map((m) => ({
    id: `separation/${m.id}`,
    title: m.title,
    inputs: m.video ? { video: `local/separation/${m.id}/clip.mp4` } : { audio: `local/separation/${m.id}/mix.flac` },
    demoInputs: { audio: "fixtures/voice.wav" },
    references: `local/separation/${m.id}`,
    tags: ["synthetic", ...(m.video ? ["video"] : ["audio-only"])],
    note: m.checks,
  }));
  cases.push({
    id: "separation/real",
    title: "Your own clip (a film scene, a vlog, a podcast with music): for the blind A/B page",
    inputs: { video: "local/separation/real/clip.mp4" },
    demoInputs: { audio: "fixtures/voice.wav" },
    metrics: ["separation"],
    tags: ["real", "video"],
    note: "No known stems: the scores are speed and whether the stems add up; listen on pnpm eval:review. Use a clip you own or may use.",
  });
  return {
    $schema: "./case.schema.json",
    suite: "separation",
    title: "Soundtrack separation · dialogue, music and effects",
    description: `${HEADER} Synthetic 12 s mixes with known stems (python3 -I scripts/eval/fixtures/make-separation.py --speech <folder> --speech-licence "<source, licence>" writes them into local/separation/; the speech is yours to bring with its words and its licence, the music, effects, hum and hiss are synthesized there, CC0; the measured runs used LibriSpeech dev-clean speaker 1272, CC BY 4.0) and your own clip for the blind review. Scores each stem against its known part (SI-SDR, SDR), whether voice + bed add back up to the input, the bed's level, peak and stereo image against the known bed, where a steady hum or hiss goes, the dialogue's word error rate (Whisper base.en, pnpm eval:setup --asr; werInput is the same ASR on the input as it is, which is "Clean the voice first" off) and the speed from ComfyUI-DBS's report. Clean up dialogue (clean-dialogue: one file with the bed at −18 dB) is scored against the voice plus the known bed at that level (remixSiSdr), with the bed's level in it (bedLevel), the noise left in it and its WER. Licences (information): ${dbsLicences()}; ComfyUI-DBS MIT; MelBand RoFormer MIT; Demucs MIT; DeepFilterNet 3 MIT OR Apache-2.0; VEED Clean Audio a hosted paid API; the test mixes' sources are recorded in each mix's meta.json. SAM Audio isn't here: it is not offered on the cloud engine.`,
    original: ["oss-dbs-separate", "oss-dbs-voice-separate"],
    kind: "audio",
    decides: SEPARATION_RULE,
    targets: {
      open: { models: ["oss-dbs-separate"], op: "separate-audio" },
      cloud: { models: ["demucs"], op: "separate-audio" },
      demo: { models: ["oss-dbs-separate"], op: "separate-audio" },
    },
    defaults: {
      seeds: [1001],
      metrics: ["separation", "wer"],
      variant: "bsrnn-mono",
      candidate: "bsrnn-mono",
      timeoutSeconds: 3600,
    },
    variants: {
      "bsrnn-mono": { description: "DBS-BSRNN (fast), mono: stems from the channels' mean, the bed is the original minus the speech (the fast stereo bed)", extra: { separationModel: "DBS-BSRNN-DnR", channels: "mono" }, engines: ["open", "demo"] },
      "bsrnn-stereo": { description: "DBS-BSRNN, each channel: every channel separated on its own (twice the time for stereo)", extra: { separationModel: "DBS-BSRNN-DnR", channels: "each channel" }, engines: ["open"] },
      "tiger-mono": { description: "DBS-TIGER (best), mono", extra: { separationModel: "DBS-TIGER-DnR", channels: "mono" }, engines: ["open"] },
      "tiger-stereo": { description: "DBS-TIGER, each channel", extra: { separationModel: "DBS-TIGER-DnR", channels: "each channel" }, engines: ["open"] },
      "dbs-dub": { description: "The dub's first step with DBS (graph B: DBS-BSRNN voice and bed, then Qwen3-ASR 0.6B on the voice)", models: { open: ["oss-dbs-voice-separate"] }, extra: { separationModel: "DBS-BSRNN-DnR", ...asr }, engines: ["open"] },
      melband: { description: "The dub's first step with MelBand RoFormer (a vocals model; voice and background only, then Qwen3-ASR 0.6B)", models: { open: ["oss-voice-separate"] }, extra: asr, engines: ["open"] },
      demucs: { description: "Demucs (htdemucs on fal, as today's cloud dub uses it): vocals against drums, bass and other, summed into the bed", models: { cloud: ["demucs"] }, engines: ["cloud"] },
      // Clean up dialogue (D5): graph C gives one file, the dialogue with the music and effects back under it at −18 dB.
      "clean-dialogue": { description: "Clean up dialogue, open (graph C: DBS-BSRNN dialogue with the music and effects at −18 dB, one file)", models: { open: ["oss-dbs-remix"] }, extra: { separationModel: "DBS-BSRNN-DnR", channels: "mono", voiceDb: 0, musicDb: -18, effectsDb: -18 }, engines: ["open"] },
      "clean-veed": { description: "Clean up dialogue, cloud: VEED Clean Audio (the voice with nothing under it)", models: { cloud: ["veed-clean-audio"] }, op: "enhance-voice", engines: ["cloud"] },
      "clean-deepfilternet": { description: "Clean up dialogue, cloud: DeepFilterNet 3 on fal (audio only; a denoiser, so music stays)", models: { cloud: ["deepfilternet3"] }, op: "enhance-voice", engines: ["cloud"] },
    },
    cases,
  };
}

const write = (name, data, check) => {
  const file = path.join(CASES_DIR, name);
  const text = `${JSON.stringify(data, null, 2)}\n`;
  if (check) {
    // A Windows checkout may have CRLF line endings: the same content.
    const now = fs.existsSync(file) ? fs.readFileSync(file, "utf8").replace(/\r\n/g, "\n") : "";
    if (now !== text) throw new Error(`${path.relative(REPO_DIR, file)} is out of date: run node scripts/eval/gen-cases.mjs`);
    return;
  }
  fs.writeFileSync(file, text);
  console.log(`Wrote ${path.relative(REPO_DIR, file)}`);
};

export function generated() {
  const dop = dopSuite();
  return {
    "soul.json": soulSuite(),
    "soul-cinema.json": soulCinemaSuite(),
    "soul-hex.json": soulHexSuite(),
    "dop.json": dop.suite,
    "dop-mix.json": dopMixSuite(),
    "dop-mixed-media.json": dopMixedMediaSuite(),
    "separation.json": separationSuite(),
    "case.schema.json": schemaJson(),
    later: dop.later,
  };
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const check = process.argv.includes("--check");
  const out = generated();
  for (const name of ["soul.json", "soul-cinema.json", "soul-hex.json", "dop.json", "dop-mix.json", "dop-mixed-media.json", "separation.json", "case.schema.json"]) write(name, out[name], check);
  console.log(`soul: ${out["soul.json"].cases.length} looks · dop: ${out["dop.json"].cases.length} presets · dop-mix: ${out["dop-mix.json"].cases.length} pairs · dop-mixed-media: ${out["dop-mixed-media.json"].cases.length} effects · separation: ${out["separation.json"].cases.length} mixes${out.later.length ? ` (${out.later.length} research names not in the catalog yet)` : ""}`);
}