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.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Covers: pnpm eval:covers --templates makes covers for the template and style tiles
Adarshe1a485b81509
diff --git a/scripts/eval/eval.mjs b/scripts/eval/eval.mjsindex 3ca9f1bf..50f28061 100644--- a/scripts/eval/eval.mjs+++ b/scripts/eval/eval.mjs@@ -10,6 +10,7 @@ import { parseArgs } from "node:util";import { loadSuite, suiteFiles, validateAll } from "./lib/cases.mjs";import { compareRuns, compareText, promote, promoteText, researchRecords } from "./lib/compare.mjs";import { coversFromMasters, makeCovers, versionCovers } from "./lib/covers.mjs";+import { templateCoversFromMasters, versionTemplateCovers } from "./lib/template-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";@@ -80,12 +81,22 @@ pnpm eval:covers --from-masters <dir> --run <name> [--engine comfyui] [--model <cover) is skipped (--replace takes it over). Run again, it encodes only new or changed masters (--force: all).Clips loop without a jump: their last frames are crossfaded into their first ones.+pnpm eval:covers --templates <dir> [--only group/id,group/id] [--force] [--dry-run] [--public-dir public]++ Covers for the studios' template and style tiles, from rendered masters: one folder per tile,+ <dir>/<group>/<tile id>/ (groups: marketing, fashion, photodump, shorts, mixed-media, canvas, content-factory,+ explainer), holding clip.mp4 or still.png, then frame-2.png… for a tile with more frames (up to frame-4), and a+ meta.json that can say { "rest": "end" } (a reveal: its last frame is the poster) or { "same": "<preset id>" }+ (the tile shows that preset's cover). Encoded like the preset covers into public/previews/templates/<group>/ and+ merged into src/lib/template-covers.generated.ts. Run again, it encodes only new or changed masters (--force: all).+pnpm eval:covers --versions [--dry-run] [--public-dir public] [--manifest …]- Every URL in the manifest ends in its file's content version (?v=, 8 hex digits of its sha256; a poster's also- covers its small copy in thumbs/), so a cover made again gets a new URL. Both commands above write them; this- one versions the manifest from the files as they are. It encodes only a poster's small copy that's missing or- older than its poster (one copied in by hand), first; --dry-run lists those and fails until they're made.`,+ Every URL in the manifests (the presets', and the template tiles') ends in its file's content version (?v=, 8 hex+ digits of its sha256; a still's also covers its small copy in thumbs/), so a cover made again gets a new URL. The+ commands above write them; this one versions both manifests from the files as they are (with --manifest, only+ that presets' manifest). It encodes only a still's small copy that's missing or older than its still (one copied+ in by hand), first; --dry-run lists those and fails until they're made.`,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)",@@ -443,11 +454,13 @@ async function covers(args, ctx) {force: { type: "boolean" },replace: { type: "boolean" },versions: { type: "boolean" },+ templates: { type: "string" },},{ positionals: true },);if (v.help) return ctx.print(HELP.covers), 0;if (v["from-masters"]) return coversFromMastersCmd(v, ctx);+ if (v.templates) return templateCoversCmd(v, ctx);if (v.versions) return versionsCmd(v, ctx);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), commercialOnly: v["commercial-only"] });@@ -467,10 +480,19 @@ async function covers(args, ctx) {*/function versionsCmd(v, ctx) {const dry = v["dry-run"];- const r = versionCovers({ dryRun: dry, publicDir: v["public-dir"] && path.resolve(v["public-dir"]), manifest: v.manifest && path.resolve(v.manifest) });- const status = r.unversioned.length || (dry && r.thumbs.length) ? 1 : 0;- if (v.json) return ctx.print(JSON.stringify(r, null, 2)), status;- ctx.print(`${r.changed} of ${r.urls} cover URLs in ${r.entries} entries ${dry ? "would get" : "got"} a new version`);+ const publicDir = v["public-dir"] && path.resolve(v["public-dir"]);+ const presets = versionCovers({ dryRun: dry, publicDir, manifest: v.manifest && path.resolve(v.manifest) });+ // The template tiles' manifest is versioned with it (its own file: --manifest names the presets' alone).+ const templates = v.manifest ? null : versionTemplateCovers({ dryRun: dry, publicDir });+ const both = [presets, templates].filter(Boolean);+ const status = both.some((r) => r.unversioned.length || (dry && r.thumbs.length)) ? 1 : 0;+ if (v.json) return ctx.print(JSON.stringify(templates ? { ...presets, templates } : presets, null, 2)), status;+ for (const r of both) versionsReport(r, r === templates ? "template tile " : "", dry, ctx);+ return status;+}++function versionsReport(r, what, dry, ctx) {+ ctx.print(`${r.changed} of ${r.urls} ${what}cover URLs in ${r.entries} entries ${dry ? "would get" : "got"} a new version`);const list = (items, why) => {for (const u of items.slice(0, 10)) ctx.print(` · ${u}: ${why}`);if (items.length > 10) ctx.print(` · and ${items.length - 10} more`);@@ -478,7 +500,29 @@ function versionsCmd(v, ctx) {list(r.thumbs, dry ? "small copy missing or older than its poster: would be made first" : "small copy made (it was missing or older than its poster)");list(r.unversioned, "no file, so no version");if ((r.changed || r.thumbs.length) && !dry) ctx.note(`Look at the diff of ${path.relative(REPO_DIR, r.manifest) || r.manifest}${r.thumbs.length ? " and the small copies it made" : ""} before committing them.`);- return status;+}++/** pnpm eval:covers --templates <dir>: the template tiles' covers from rendered masters, merged into their manifest. */+function templateCoversCmd(v, ctx) {+ const r = templateCoversFromMasters(path.resolve(v.templates), {+ only: v.only?.split(",").map((s) => s.trim()).filter(Boolean),+ force: v.force,+ dryRun: v["dry-run"],+ publicDir: v["public-dir"] && path.resolve(v["public-dir"]),+ });+ if (v.json) return ctx.print(JSON.stringify(r, null, 2)), 0;+ const n = (k, word) => `${k} ${word}${k === 1 ? "" : "s"}`;+ const clips = r.covers.filter((c) => c.video).length;+ const kept = r.covers.filter((c) => c.kept).length;+ const same = r.covers.filter((c) => c.same).length;+ const tail = v["dry-run"] ? " would be made" : kept ? `, ${kept} already up to date` : "";+ ctx.print(`${n(r.covers.length, "template tile cover")} (${n(clips, "clip")}, ${n(r.covers.length - clips, "still")}, ${same} showing a preset's cover)${tail}`);+ for (const c of r.covers.slice(0, 20)) ctx.print(` ${c.key} ← ${c.same ?? path.basename(c.from)}${c.frames ? ` + ${n(c.frames, "frame")}` : ""}${c.kept ? " · up to date" : ""}`);+ if (r.covers.length > 20) ctx.print(` and ${r.covers.length - 20} more`);+ for (const sk of r.skipped.slice(0, 10)) ctx.print(` · ${sk.key}: ${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 in ${path.relative(REPO_DIR, r.folder) || r.folder} and the diff of ${path.relative(REPO_DIR, r.manifest) || r.manifest} before committing them.`);+ return 0;}/** pnpm eval:covers --from-masters <dir>: covers from rendered masters, merged into the manifest. */diff --git a/scripts/eval/lib/covers.mjs b/scripts/eval/lib/covers.mjsindex 3849d306..cd617c45 100644--- a/scripts/eval/lib/covers.mjs+++ b/scripts/eval/lib/covers.mjs@@ -24,6 +24,8 @@ const STILL_PX = 768;const CLIP_PX = 512;const CLIP_SECONDS = 4;const CLIP_FPS = 24;+/** Longest a clip that rests on its last frame keeps (s): a reveal is cut at its own end, not at CLIP_SECONDS. */+const REST_CLIP_SECONDS = 8;/** Frames at a clip's end crossfaded into its first ones: the cards play clips with `loop`, and this hides the jump. */const LOOP_FADE = 6;/** Width of a poster's small copy (px), which the pickers' tiles show: enough for a 136 px tile on a 2x screen. */@@ -128,7 +130,7 @@ export function writeManifest(entries, file = MANIFEST_FILE) {}/** A /previews URL (versioned or not) as a file in publicDir; null for anything else. */-function previewFile(url, publicDir) {+export function previewFile(url, publicDir) {const parts = typeof url === "string" ? bareUrl(url).split("/").filter(Boolean) : [];return parts[0] === "previews" && !parts.includes("..") ? path.join(publicDir, ...parts) : null;}@@ -301,18 +303,33 @@ export function seamless(frames, fade) {/*** A still at most STILL_PX wide/tall (a 4:2:0 JPEG), or a clip's first seconds at most CLIP_PX that loops* without a jump (crossfaded, unless it loops already), with its first frame as the poster.+ *+ * With `rest: "end"` (a reveal that ends on its result), the clip keeps its own end (up to REST_CLIP_SECONDS) and+ * is not crossfaded; its poster is its last frame, whose time comes back as `at`: a card shows that frame at rest+ * and starts the clip there, so nothing jumps.+ * @param {string} src+ * @param {"image" | "video"} kind+ * @param {string} destBase+ * @param {{ rest?: "start" | "end" }} [opts]+ * @returns {{ poster: string, video?: string, at?: number }}*/-function encode(src, kind, destBase) {+export function encode(src, kind, destBase, opts = {}) {const fit = (px) => `scale='if(gt(iw,ih),min(${px},iw),-2)':'if(gt(iw,ih),-2,min(${px},ih))'`;if (kind === "video") {- // Decoded at CLIP_FPS: CLIP_SECONDS, plus the frames the crossfade takes back from the start.- const y4m = run(["-i", src, "-t", String(CLIP_SECONDS + LOOP_FADE / CLIP_FPS), "-an", "-sn", "-dn", "-vf", `${fit(CLIP_PX)},fps=${CLIP_FPS},format=yuv420p`, "-f", "yuv4mpegpipe", "-"]);+ const atEnd = opts.rest === "end";+ // Decoded at CLIP_FPS: CLIP_SECONDS, plus the frames the crossfade takes back from the start (a reveal: all of it).+ const seconds = atEnd ? REST_CLIP_SECONDS : CLIP_SECONDS + LOOP_FADE / CLIP_FPS;+ const y4m = run(["-i", src, "-t", String(seconds), "-an", "-sn", "-dn", "-vf", `${fit(CLIP_PX)},fps=${CLIP_FPS},format=yuv420p`, "-f", "yuv4mpegpipe", "-"]);const { header, frames, luma } = readY4m(y4m);if (frames.length < 2) throw new Error(`${src} has no frames to make a clip of`);const cut = frames.slice(0, CLIP_SECONDS * CLIP_FPS);- const looped = loopsAlready(cut, luma) ? cut : seamless(frames, Math.min(LOOP_FADE, Math.floor(frames.length / 4)));- const stream = Buffer.concat([Buffer.from(`${header}\n`, "latin1"), ...looped.flatMap((fr) => [Buffer.from("FRAME\n"), fr])]);- run(["-f", "yuv4mpegpipe", "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-map_metadata", "-1", "-movflags", "+faststart", `${destBase}.mp4`], stream);+ const looped = atEnd ? frames : loopsAlready(cut, luma) ? cut : seamless(frames, Math.min(LOOP_FADE, Math.floor(frames.length / 4)));+ const stream = (list) => Buffer.concat([Buffer.from(`${header}\n`, "latin1"), ...list.flatMap((fr) => [Buffer.from("FRAME\n"), fr])]);+ run(["-f", "yuv4mpegpipe", "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "28", "-map_metadata", "-1", "-movflags", "+faststart", `${destBase}.mp4`], stream(looped));+ if (atEnd) {+ run(["-f", "yuv4mpegpipe", "-i", "-", "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`], stream([looped.at(-1)]));+ return { poster: `${destBase}.jpg`, video: `${destBase}.mp4`, at: Math.round(((looped.length - 1) / CLIP_FPS) * 1000) / 1000 };+ }run(["-i", `${destBase}.mp4`, "-frames:v", "1", "-vf", "format=yuvj420p", "-q:v", "4", `${destBase}.jpg`]);return { poster: `${destBase}.jpg`, video: `${destBase}.mp4` };}@@ -405,7 +422,7 @@ function dropReplaced(old, manifest, publicDir) {const MASTER_CLIP = "clip.mp4";const MASTER_STILL = "start.png";-const newer = (file, than) => {+export const newer = (file, than) => {try {return fs.statSync(file).mtimeMs >= fs.statSync(than).mtimeMs;} catch {diff --git a/scripts/eval/lib/template-covers.mjs b/scripts/eval/lib/template-covers.mjsnew file mode 100644index 00000000..ee18ac8c--- /dev/null+++ b/scripts/eval/lib/template-covers.mjs@@ -0,0 +1,269 @@+// Real covers for the studios' template and style tiles (Marketing Studio's templates, Fashion Factory, Photodump packs,+// the Shorts and Mixed Media looks, Canvas templates, Content Factory's trending styles, the Explainer styles), from+// rendered masters: pnpm eval:covers --templates <dir>. They are encoded the way the preset covers are (covers.mjs:+// a 768 px still, a 512 px clip, a 320 px copy of each still in thumbs/) into public/previews/templates/<group>/, and+// listed in src/lib/template-covers.generated.ts, which the tiles read (src/lib/template-covers.ts). A tile that isn't+// listed keeps its drawn art.+//+// Every URL the manifest lists carries its file's content version (`?v=`, as the preset covers do), so a cover made+// again gets a new URL; pnpm eval:covers --versions versions this manifest too.+import fs from "node:fs";+import path from "node:path";+import { bareUrl, COVERS_DIR, encode, newer, previewFile, readManifest, thumbOf, urlVersion, withVersions, writeThumbs } from "./covers.mjs";+import { REPO_DIR, safeName } from "./paths.mjs";++export const TEMPLATE_MANIFEST = path.join(REPO_DIR, "src", "lib", "template-covers.generated.ts");++/** The tile groups, as the manifest's keys start (`<group>/<tile id>`) and the folders under previews/templates/ are named. */+export const TEMPLATE_GROUPS = ["marketing", "fashion", "photodump", "shorts", "mixed-media", "canvas", "content-factory", "explainer"];++/** At most this many frames per tile: the cover and up to three more (a contact sheet's 2x2, a carousel's slides). */+const MAX_FRAMES = 4;+const STILLS = ["still.png", "still.jpg", "still.webp", "start.png", "start.jpg"];+const CLIP = "clip.mp4";+const FRAME = /^frame-([2-9])\.(png|jpe?g|webp)$/;++const HEADER = `/**+ * Real covers for the studios' template and style tiles, keyed by "<group>/<tile id>" (marketing/ps-sunlit-plinth,+ * shorts/shorts-warm-glow, explainer/pixel-art…), read through templateCover (template-covers.ts). For a still at+ * /previews/templates/<group>/<id>.jpg its version, for a clip at <id>.mp4 with its poster at <id>.jpg the poster's+ * and the clip's, or the URLs of a cover kept elsewhere: a tile with more frames (\`frames\`, the ones after the+ * poster), one that rests on its clip's last frame (\`at\`, in seconds), or one that shows a preset's cover. A+ * version is the ?v= its URL ends in; a still's also stands for its 320 px copy in thumbs/ next to it.+ * Generated by pnpm eval:covers --templates: run it again rather than editing. A tile not listed keeps its drawn art.+ */+export type TemplateCoverEntry = string | [poster: string, clip: string] | { poster: string; video?: string; at?: number; frames?: string[] };++export const TEMPLATE_COVERS: Record<string, TemplateCoverEntry> = `;++const usualBase = (key) => `/previews/templates/${key}`;++/** A slim entry as a full one: { poster, video?, at?, frames? } with their URLs. */+export function expandEntry(key, e) {+ const base = usualBase(key);+ if (typeof e === "string") return { poster: `${base}.jpg?v=${e}` };+ if (Array.isArray(e)) return { poster: `${base}.jpg?v=${e[0]}`, video: `${base}.mp4?v=${e[1]}` };+ return { poster: e.poster, ...(e.video !== undefined && { video: e.video }), ...(e.at !== undefined && { at: e.at }), ...(e.frames?.length && { frames: e.frames }) };+}++/** A full entry as the manifest lists it: only its versions for a plain cover at the usual place, else its URLs. */+export function slimEntry(key, e) {+ const base = usualBase(key);+ const poster = urlVersion(e.poster);+ const clip = e.video === undefined ? undefined : urlVersion(e.video);+ const plain = e.at === undefined && !e.frames?.length;+ const usual = plain && bareUrl(e.poster) === `${base}.jpg` && poster && (e.video === undefined || (bareUrl(e.video) === `${base}.mp4` && clip));+ if (usual) return e.video === undefined ? poster : [poster, clip];+ return expandEntry(key, e);+}++/** The manifest's entries, full; none when there is no file yet. A file that can't be read as one throws. */+export function readTemplateManifest(file = TEMPLATE_MANIFEST) {+ let text;+ try {+ text = fs.readFileSync(file, "utf8");+ } catch (e) {+ if (e?.code === "ENOENT") return {};+ throw e;+ }+ try {+ const at = text.indexOf("export const TEMPLATE_COVERS");+ if (at < 0) throw new Error("no TEMPLATE_COVERS");+ const slim = JSON.parse(text.slice(text.indexOf("=", at) + 1).trim().replace(/;\s*$/, ""));+ if (!slim || typeof slim !== "object" || Array.isArray(slim)) throw new Error("not an object");+ return Object.fromEntries(Object.entries(slim).map(([k, e]) => [k, expandEntry(k, e)]));+ } catch (e) {+ throw new Error(`${file} isn't a template covers manifest pnpm eval:covers can read (${e.message}): fix or restore it before making covers`);+ }+}++/** Write the manifest (slim), a line per tile. */+export function writeTemplateManifest(entries, file = TEMPLATE_MANIFEST) {+ const lines = Object.entries(entries)+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([k, e]) => ` ${JSON.stringify(k)}: ${JSON.stringify(slimEntry(k, e))}`);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, `${HEADER}{${lines.length ? `\n${lines.join(",\n")}\n` : ""}};\n`);+}++/** Every still an entry shows (the poster, then its frames), each with a 320 px copy. */+const stillsOf = (e) => [e.poster, ...(e.frames ?? [])];++/** The 320 px copies due or made, for every still of every entry (writeThumbs on each, as a poster). */+const asPosters = (entries) => Object.fromEntries(Object.entries(entries).flatMap(([k, e]) => stillsOf(e).map((s, i) => [`${k}#${i}`, { poster: s }])));++/** The entries with every URL versioned from its file (withVersions: a still with its 320 px copy, a clip alone). */+export function withTemplateVersions(entries, publicDir = path.dirname(COVERS_DIR)) {+ return Object.fromEntries(+ Object.entries(entries).map(([k, e]) => {+ const main = withVersions({ e: { poster: e.poster, ...(e.video !== undefined && { video: e.video }) } }, publicDir).e;+ const frames = e.frames?.map((f) => withVersions({ f: { poster: f } }, publicDir).f.poster);+ return [k, { ...e, poster: main.poster, ...(main.video !== undefined && { video: main.video }), ...(frames && { frames }) }];+ }),+ );+}++/**+ * Version the manifest's URLs from its files as they are (part of pnpm eval:covers --versions), first making any+ * 320 px copy that's missing or older than its still. Says how many URLs changed, which copies it made, and any URL+ * left without a version (a missing file). A dry run writes nothing.+ * @param {{ publicDir?: string, manifest?: string, dryRun?: boolean }} [opts]+ */+export function versionTemplateCovers(opts = {}) {+ const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);+ const before = readTemplateManifest(opts.manifest);+ const posters = asPosters(before);+ const thumbs = opts.dryRun ? dueCopies(posters, publicDir) : writeThumbs(posters, publicDir);+ const after = withTemplateVersions(before, publicDir);+ const urls = (m) => Object.values(m).flatMap((e) => [...stillsOf(e), e.video].filter((u) => u !== undefined));+ const [was, now] = [urls(before), urls(after)];+ const result = {+ entries: Object.keys(after).length,+ urls: now.length,+ changed: now.filter((u, i) => u !== was[i]).length,+ thumbs: thumbs.map((f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`),+ unversioned: now.filter((u) => String(u).startsWith("/previews/") && !urlVersion(u)),+ manifest: opts.manifest ?? TEMPLATE_MANIFEST,+ };+ if (!opts.dryRun) writeTemplateManifest(after, opts.manifest);+ return result;+}++/** The 320 px copies writeThumbs would make (missing, or older than their still). */+function dueCopies(posters, publicDir) {+ const due = [];+ for (const { poster } of Object.values(posters)) {+ const file = previewFile(poster, publicDir);+ const thumb = previewFile(thumbOf(bareUrl(poster)), publicDir);+ if (file && thumb && fs.existsSync(file) && !newer(thumb, file)) due.push(thumb);+ }+ return due;+}++function readMeta(folder) {+ try {+ const meta = JSON.parse(fs.readFileSync(path.join(folder, "meta.json"), "utf8"));+ return meta && typeof meta === "object" && !Array.isArray(meta) ? meta : {};+ } catch {+ return {};+ }+}++/** What a master folder holds: a clip or a still, the frames after it (frame-2…frame-4), and its meta.json. */+function readMaster(folder) {+ const names = fs.readdirSync(folder);+ const meta = readMeta(folder);+ const clip = names.includes(CLIP) ? path.join(folder, CLIP) : null;+ const still = STILLS.find((s) => names.includes(s));+ const frames = names+ .map((n) => [n, FRAME.exec(n)])+ .filter(([, m]) => m)+ .sort(([, a], [, b]) => Number(a[1]) - Number(b[1]))+ .map(([n]) => path.join(folder, n))+ .slice(0, MAX_FRAMES - 1);+ return { meta, clip, still: still ? path.join(folder, still) : null, frames };+}++/**+ * Covers for the template tiles from rendered masters (pnpm eval:covers --templates <dir>): one folder per tile,+ * <dir>/<group>/<tile id>/, holding+ * clip.mp4 a clip cover (its first 4 s, its first frame the poster), or+ * still.png a still cover (also still.jpg / still.webp, or start.png);+ * frame-2.png … the tile's other frames, in order, up to frame-4 (a carousel's slides, a contact sheet's cells);+ * meta.json { "rest": "end" } for a reveal: the clip is kept to its end and its last frame is the poster,+ * or { "same": "<preset id>" }: the tile shows that preset's cover (no files of its own).+ * The manifest is merged: other tiles' entries stay. A tile whose cover is newer than its masters is kept (force makes+ * it again). Files a tile no longer uses (a clip that's now a still, a dropped frame) are removed.+ * @param {string} dir the masters folder+ * @param {{ only?: string[], force?: boolean, dryRun?: boolean, publicDir?: string, manifest?: string, presetManifest?: string }} [opts]+ */+export function templateCoversFromMasters(dir, opts = {}) {+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) throw new Error(`No masters folder at ${dir}`);+ const publicDir = opts.publicDir ?? path.dirname(COVERS_DIR);+ const web = (f) => `/${path.relative(publicDir, f).split(path.sep).join("/")}`;+ const only = opts.only?.length ? new Set(opts.only) : null;+ const presets = readManifest(opts.presetManifest);+ const manifest = readTemplateManifest(opts.manifest);+ const result = { covers: [], skipped: [], manifest: opts.manifest ?? TEMPLATE_MANIFEST, folder: path.join(publicDir, "previews", "templates") };+ for (const group of fs.readdirSync(dir).sort()) {+ const groupDir = path.join(dir, group);+ if (!fs.statSync(groupDir).isDirectory() || group.startsWith("_") || group.startsWith(".")) continue;+ if (!TEMPLATE_GROUPS.includes(group)) {+ result.skipped.push({ key: group, why: `not a tile group (${TEMPLATE_GROUPS.join(", ")})` });+ continue;+ }+ for (const id of fs.readdirSync(groupDir).sort()) {+ const key = `${group}/${id}`;+ const folder = path.join(groupDir, id);+ if ((only && !only.has(key)) || !fs.statSync(folder).isDirectory()) continue;+ if (safeName(id) !== id || id.startsWith("_")) {+ result.skipped.push({ key, why: "not a tile id (folders are named by tile id, such as ps-sunlit-plinth)" });+ continue;+ }+ const m = readMaster(folder);+ if (typeof m.meta.same === "string") {+ const p = presets[m.meta.same];+ if (!p) {+ result.skipped.push({ key, why: `${m.meta.same} has no cover` });+ continue;+ }+ const entry = { poster: p.poster, ...(p.video !== undefined && { video: p.video }) };+ if (!opts.dryRun) {+ dropUnused(manifest[key], entry, publicDir);+ manifest[key] = entry;+ }+ result.covers.push({ key, kind: p.video ? "video" : "image", same: m.meta.same, ...entry });+ continue;+ }+ const kind = m.clip ? "video" : m.still ? "image" : null;+ if (!kind) {+ result.skipped.push({ key, why: `no ${CLIP} or still.png yet` });+ continue;+ }+ const src = m.clip ?? m.still;+ const rest = kind === "video" && m.meta.rest === "end" ? "end" : undefined;+ const outDir = path.join(publicDir, "previews", "templates", group);+ const base = path.join(outDir, safeName(id));+ const frameFiles = m.frames.map((_, i) => `${base}-${i + 2}.jpg`);+ const sources = [src, ...m.frames, ...(fs.existsSync(path.join(folder, "meta.json")) ? [path.join(folder, "meta.json")] : [])];+ const outputs = [`${base}.jpg`, ...(kind === "video" ? [`${base}.mp4`] : []), ...frameFiles];+ const kept = !opts.force && outputs.every((o) => sources.every((s) => newer(o, s))) && manifest[key] && (kind === "video") === (manifest[key].video !== undefined);+ let at = kept ? manifest[key].at : undefined;+ if (!opts.dryRun && !kept) {+ fs.mkdirSync(outDir, { recursive: true });+ at = encode(src, kind, base, { rest }).at;+ m.frames.forEach((f, i) => encode(f, "image", `${base}-${i + 2}`));+ }+ const entry = {+ poster: web(`${base}.jpg`),+ ...(kind === "video" && { video: web(`${base}.mp4`) }),+ ...(at !== undefined && { at }),+ ...(frameFiles.length && { frames: frameFiles.map(web) }),+ };+ if (!opts.dryRun) {+ dropUnused(manifest[key], entry, publicDir);+ manifest[key] = entry;+ }+ result.covers.push({ key, kind, from: src, frames: m.frames.length, ...(kept && { kept: true }), ...entry });+ }+ }+ for (const key of only ?? []) if (!result.covers.some((c) => c.key === key) && !result.skipped.some((s) => s.key === key)) result.skipped.push({ key, why: "no folder" });+ if (result.covers.length && !opts.dryRun) {+ writeThumbs(asPosters(manifest), publicDir);+ const versioned = withTemplateVersions(manifest, publicDir);+ writeTemplateManifest(versioned, opts.manifest);+ for (const c of result.covers) Object.assign(c, versioned[c.key]);+ }+ return result;+}++/** Remove the files an old entry had under previews/templates/ that its new one doesn't use (never a preset's own). */+function dropUnused(old, now, publicDir) {+ if (!old) return;+ const files = (e) => [...stillsOf(e).flatMap((s) => [s, thumbOf(bareUrl(s))]), e.video].filter(Boolean).map(bareUrl);+ const keep = new Set(files(now));+ for (const url of files(old)) {+ const file = previewFile(url, publicDir);+ if (!keep.has(url) && file && url.startsWith("/previews/templates/")) fs.rmSync(file, { force: true });+ }+}diff --git a/src/lib/template-covers.generated.ts b/src/lib/template-covers.generated.tsnew file mode 100644index 00000000..5e91242d--- /dev/null+++ b/src/lib/template-covers.generated.ts@@ -0,0 +1,12 @@+/**+ * Real covers for the studios' template and style tiles, keyed by "<group>/<tile id>" (marketing/ps-sunlit-plinth,+ * shorts/shorts-warm-glow, explainer/pixel-art…), read through templateCover (template-covers.ts). For a still at+ * /previews/templates/<group>/<id>.jpg its version, for a clip at <id>.mp4 with its poster at <id>.jpg the poster's+ * and the clip's, or the URLs of a cover kept elsewhere: a tile with more frames (`frames`, the ones after the+ * poster), one that rests on its clip's last frame (`at`, in seconds), or one that shows a preset's cover. A+ * version is the ?v= its URL ends in; a still's also stands for its 320 px copy in thumbs/ next to it.+ * Generated by pnpm eval:covers --templates: run it again rather than editing. A tile not listed keeps its drawn art.+ */+export type TemplateCoverEntry = string | [poster: string, clip: string] | { poster: string; video?: string; at?: number; frames?: string[] };++export const TEMPLATE_COVERS: Record<string, TemplateCoverEntry> = {};diff --git a/src/lib/template-covers.ts b/src/lib/template-covers.tsnew file mode 100644index 00000000..948584fb--- /dev/null+++ b/src/lib/template-covers.ts@@ -0,0 +1,82 @@+/**+ * The real covers of the studios' template and style tiles (Marketing Studio's templates, Fashion Factory, Photodump+ * packs, the Shorts and Mixed Media looks, Canvas templates, Content Factory's trending styles, the Explainer styles),+ * from template-covers.generated.ts (pnpm eval:covers --templates). A tile that isn't listed keeps its drawn art.+ * Every URL comes from the manifest with its version (?v=): never build one here without it.+ */+import { thumbOf, type PresetPreview } from "./preset-cards";+import { TEMPLATE_COVERS, type TemplateCoverEntry } from "./template-covers.generated";++export type TemplateGroup = "marketing" | "fashion" | "photodump" | "shorts" | "mixed-media" | "canvas" | "content-factory" | "explainer";++export const TEMPLATE_GROUPS: readonly TemplateGroup[] = ["marketing", "fashion", "photodump", "shorts", "mixed-media", "canvas", "content-factory", "explainer"];++/** One still of a cover, and its 320 px copy (thumbs/ next to it, with the same version). */+export interface CoverFrame {+ src: string;+ thumb: string;+}++export interface TemplateCover {+ /** The still the tile shows at rest (a clip's first frame, or its last for a reveal: `at`). */+ poster: string;+ /** The poster's 320 px copy. */+ thumb: string;+ /** A short muted clip, played as the preset covers' are (preview-playback.ts). */+ video?: string;+ /** Where in the clip the poster is (s), when it isn't the first frame: the clip starts there, then loops from 0. */+ at?: number;+ /** Every still of the tile in order, the poster first: a carousel's slides, a contact sheet's cells. */+ frames: CoverFrame[];+}++const frame = (src: string): CoverFrame => ({ src, thumb: thumbOf(src) });++/** A manifest entry's URLs: the slim forms name a cover at /previews/templates/<group>/<id>.jpg (and .mp4) by its versions. */+function expand(key: string, e: TemplateCoverEntry): { poster: string; video?: string; at?: number; frames?: string[] } {+ const base = `/previews/templates/${key}`;+ if (typeof e === "string") return { poster: `${base}.jpg?v=${e}` };+ if (Array.isArray(e)) return { poster: `${base}.jpg?v=${e[0]}`, video: `${base}.mp4?v=${e[1]}` };+ return e;+}++/** The covers read from the manifest, each made once: a card that renders again gets the same object (memo). */+const made = new Map<string, TemplateCover>();++/** A tile's real cover, or undefined: then it shows its drawn art. */+export function templateCover(group: TemplateGroup, id: string | undefined, covers: Record<string, TemplateCoverEntry> = TEMPLATE_COVERS): TemplateCover | undefined {+ if (!id) return undefined;+ const key = `${group}/${id}`;+ if (!Object.hasOwn(covers, key)) return undefined;+ if (covers !== TEMPLATE_COVERS) return read(key, covers[key]);+ let c = made.get(key);+ if (!c) made.set(key, (c = read(key, covers[key])));+ return c;+}++function read(key: string, entry: TemplateCoverEntry): TemplateCover {+ const e = expand(key, entry);+ return {+ poster: e.poster,+ thumb: thumbOf(e.poster),+ ...(e.video && { video: e.video }),+ ...(e.video && e.at !== undefined && { at: e.at }),+ frames: [e.poster, ...(e.frames ?? [])].map(frame),+ };+}++/**+ * A cover as the preset previews take it (PresetPreview, usePreviewPlayback): its poster and clip, and for a clip+ * whose poster is a later frame, a rest on it, so the clip starts there and loops back to its start.+ */+export function templatePreview(c: TemplateCover): PresetPreview {+ return {+ poster: c.poster,+ ...(c.video && { video: c.video }),+ ...(c.video && c.at !== undefined && { rest: { src: c.poster, at: c.at, from: 0 } }),+ scene: "product",+ };+}++/** For a card without a cover: the same hooks run, with nothing to play. */+export const NO_COVER: PresetPreview = { poster: "", scene: "product" };diff --git a/tests/template-covers.test.ts b/tests/template-covers.test.tsnew file mode 100644index 00000000..09f774c7--- /dev/null+++ b/tests/template-covers.test.ts@@ -0,0 +1,196 @@+import { spawnSync } from "node:child_process";+import { createHash } from "node:crypto";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { gzipSync } from "node:zlib";+import { afterAll, describe, expect, it } from "vitest";+import { CANVAS_TEMPLATES } from "@/lib/catalog/canvas";+import { PRESETS } from "@/lib/catalog/content-factory";+import { EXPLAINER_STYLE_IDS } from "@/lib/catalog/faceless";+import { TEMPLATES } from "@/lib/catalog/marketing";+import { MIXED_PRESETS } from "@/lib/catalog/mixed-media";+import { FASHION, PACKS } from "@/lib/catalog/packs";+import { SHORTS_PRESETS } from "@/lib/catalog/shorts";+import { PRESET_PREVIEWS } from "@/lib/preset-previews.generated";+import { TEMPLATE_GROUPS, templateCover, type TemplateGroup } from "@/lib/template-covers";+import { TEMPLATE_COVERS } from "@/lib/template-covers.generated";++/*+ * The template tiles' covers manifest (src/lib/template-covers.generated.ts, written by pnpm eval:covers --templates)+ * against the catalogs and the files in public/previews, unmocked; and the generator itself, on sample media.+ * tests/template-cover-tiles.test.ts covers the tiles with a mocked manifest.+ */++type Entry = { poster: string; video?: string; at?: number; frames?: string[] };+type Made = Entry & { key: string; kind: string; kept?: true; same?: string };+const gen = (await import("../scripts/eval/lib/template-covers.mjs")) as unknown as {+ TEMPLATE_GROUPS: string[];+ slimEntry: (key: string, e: Entry) => unknown;+ readTemplateManifest: (file: string) => Record<string, Entry>;+ writeTemplateManifest: (entries: Record<string, Entry>, file: string) => void;+ templateCoversFromMasters: (dir: string, opts: Record<string, unknown>) => { covers: Made[]; skipped: { key: string; why: string }[] };+ versionTemplateCovers: (opts: { publicDir?: string; manifest?: string; dryRun?: boolean }) => { entries: number; urls: number; changed: number; thumbs: string[]; unversioned: string[] };+};++const root = process.cwd();+/** Every tile of each group, by id: what the manifest's keys may name. */+const TILES: Record<TemplateGroup, string[]> = {+ marketing: TEMPLATES.map((t) => t.id),+ fashion: FASHION.map((t) => t.id),+ photodump: PACKS.map((p) => p.id),+ shorts: SHORTS_PRESETS.map((p) => p.id),+ "mixed-media": MIXED_PRESETS.map((p) => p.id),+ canvas: CANVAS_TEMPLATES.map((t) => t.id),+ "content-factory": PRESETS.map((p) => p.id),+ explainer: [...EXPLAINER_STYLE_IDS],+};+const VERSIONED = /^(\/previews\/[^?]+)\?v=([0-9a-f]{8})$/;+const sha8 = (...files: string[]) => {+ const hash = createHash("sha256");+ for (const f of files) hash.update(fs.readFileSync(f));+ return hash.digest("hex").slice(0, 8);+};+const fileOf = (url: string, publicDir = path.join(root, "public")) => path.join(publicDir, url.split("?")[0]);+const thumbOf = (url: string) => url.replace(/\/([^/?]+)(\?|$)/, "/thumbs/$1$2");++describe("the template covers manifest", () => {+ it("lists the same groups as the generator, and only real tiles", () => {+ expect([...TEMPLATE_GROUPS]).toEqual(gen.TEMPLATE_GROUPS);+ for (const key of Object.keys(TEMPLATE_COVERS)) {+ const [group, id, ...rest] = key.split("/");+ expect(rest, key).toEqual([]);+ expect(TILES[group as TemplateGroup] ?? [], key).toContain(id);+ }+ });++ it("gives every URL its files' version: a still's with its 320 px copy, a clip's alone", () => {+ for (const key of Object.keys(TEMPLATE_COVERS)) {+ const [group, id] = key.split("/") as [TemplateGroup, string];+ const c = templateCover(group, id)!;+ for (const f of c.frames) {+ const [, , v] = VERSIONED.exec(f.src) ?? [];+ expect(v, f.src).toBeDefined();+ expect(fs.existsSync(fileOf(f.thumb)), f.thumb).toBe(true);+ expect(sha8(fileOf(f.src), fileOf(f.thumb)), f.src).toBe(v);+ }+ if (c.video) expect(VERSIONED.exec(c.video)?.[2], c.video).toBe(sha8(fileOf(c.video)));+ }+ });++ it("stays small with every tile listed: it ships with the studios' pages", () => {+ const pick = (list: { poster: string; video?: string }[], i: number) => list[i % list.length];+ const presetCovers = Object.values(PRESET_PREVIEWS);+ const v = (n: number) => n.toString(16).padStart(8, "0");+ const t = (key: string, n: number, more = "") => `/previews/templates/${key}${more}.jpg?v=${v(n)}`;+ const lines: string[] = [];+ let n = 0;+ for (const [group, ids] of Object.entries(TILES)) {+ for (const id of ids) {+ const key = `${group}/${id}`;+ n++;+ let e: Entry;+ if (group === "mixed-media" || id.startsWith("effect-chain-")) e = pick(presetCovers, n);+ else if (group === "fashion" || group === "photodump" || ["product-angles", "script-film", "table-film", "clips-film", "compare-image"].includes(id))+ e = { poster: t(key, n), frames: [2, 3, 4].slice(0, group === "photodump" ? 3 : 2).map((k) => t(key, n + k, `-${k}`)) };+ else if (group === "shorts") e = { poster: t(key, n), video: `/previews/templates/${key}.mp4?v=${v(n + 1)}`, at: 3.542 };+ else if (group === "marketing" || group === "content-factory") e = { poster: t(key, n), video: `/previews/templates/${key}.mp4?v=${v(n + 1)}` };+ else e = { poster: t(key, n) };+ lines.push(` ${JSON.stringify(key)}: ${JSON.stringify(gen.slimEntry(key, { poster: e.poster, ...(e.video && { video: e.video }), ...(e.at && { at: e.at }), ...(e.frames && { frames: e.frames }) }))}`);+ }+ }+ expect(lines).toHaveLength(228);+ const text = `{\n${lines.join(",\n")}\n}`;+ expect(text.length).toBeLessThan(36_000);+ expect(gzipSync(text).length).toBeLessThan(8_000);+ });+});++const hasFfmpeg = spawnSync("ffmpeg", ["-version"]).status === 0;+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-template-covers-"));+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }));+const SAMPLE_CLIP = path.join(root, "public", "samples", "demo-landscape.mp4");++describe.skipIf(!hasFfmpeg)("pnpm eval:covers --templates", () => {+ const masters = path.join(dir, "masters");+ const publicDir = path.join(dir, "public");+ const manifest = path.join(dir, "template-covers.generated.ts");+ const still = path.join(dir, "still.png");+ const put = (key: string, files: Record<string, string>) => {+ fs.mkdirSync(path.join(masters, key), { recursive: true });+ for (const [name, from] of Object.entries(files)) {+ if (from.startsWith("{")) fs.writeFileSync(path.join(masters, key, name), from);+ else fs.copyFileSync(from, path.join(masters, key, name));+ }+ };+ const run = (opts: Record<string, unknown> = {}) => gen.templateCoversFromMasters(masters, { publicDir, manifest, ...opts });+ const sameId = Object.keys(PRESET_PREVIEWS)[0];++ it("encodes stills, clips, reveals and frames, versions every URL, and lists a preset's cover as it is", () => {+ spawnSync("ffmpeg", ["-v", "error", "-y", "-i", SAMPLE_CLIP, "-frames:v", "1", still]);+ put("marketing/ps-sunlit-plinth", { "still.png": still });+ put("marketing/m2-sticker-pop", { "clip.mp4": SAMPLE_CLIP });+ put("shorts/shorts-warm-glow", { "clip.mp4": SAMPLE_CLIP, "meta.json": '{"rest":"end"}' });+ put("photodump/zen", { "still.png": still, "frame-2.png": still, "frame-3.png": still, "frame-4.png": still });+ put("mixed-media/mixed-sketch", { "meta.json": JSON.stringify({ same: sameId }) });+ // The preset's own files, as the site has them.+ const p = PRESET_PREVIEWS[sameId];+ for (const url of [p.poster, thumbOf(p.poster), p.video].filter((u): u is string => !!u)) {+ fs.mkdirSync(path.dirname(fileOf(url, publicDir)), { recursive: true });+ fs.copyFileSync(fileOf(url), fileOf(url, publicDir));+ }+ put("nope/x", { "still.png": still });++ const r = run();+ expect(r.covers.map((c) => c.key).sort()).toEqual(["marketing/m2-sticker-pop", "marketing/ps-sunlit-plinth", "mixed-media/mixed-sketch", "photodump/zen", "shorts/shorts-warm-glow"]);+ expect(r.skipped).toEqual([{ key: "nope", why: expect.stringMatching(/not a tile group/) }]);+ const m = gen.readTemplateManifest(manifest);+ const out = (f: string) => path.join(publicDir, "previews", "templates", f);+ expect(m["marketing/ps-sunlit-plinth"]).toEqual({ poster: `/previews/templates/marketing/ps-sunlit-plinth.jpg?v=${sha8(out("marketing/ps-sunlit-plinth.jpg"), out("marketing/thumbs/ps-sunlit-plinth.jpg"))}` });+ expect(m["marketing/m2-sticker-pop"].video).toBe(`/previews/templates/marketing/m2-sticker-pop.mp4?v=${sha8(out("marketing/m2-sticker-pop.mp4"))}`);+ // A reveal rests on its last frame: the clip is kept to its end.+ const reveal = m["shorts/shorts-warm-glow"];+ expect(reveal.at).toBeGreaterThan(1);+ expect(reveal.video).toMatch(VERSIONED);+ expect(m["photodump/zen"].frames).toEqual([2, 3, 4].map((k) => `/previews/templates/photodump/zen-${k}.jpg?v=${sha8(out(`photodump/zen-${k}.jpg`), out(`photodump/thumbs/zen-${k}.jpg`))}`));+ expect(m["mixed-media/mixed-sketch"]).toEqual({ poster: PRESET_PREVIEWS[sameId].poster, ...(PRESET_PREVIEWS[sameId].video && { video: PRESET_PREVIEWS[sameId].video }) });+ // The file lists a plain cover by its versions alone.+ const text = fs.readFileSync(manifest, "utf8");+ expect(text).toMatch(/"marketing\/ps-sunlit-plinth": "[0-9a-f]{8}"/);+ expect(text).toMatch(/"marketing\/m2-sticker-pop": \["[0-9a-f]{8}","[0-9a-f]{8}"\]/);+ expect(text).toMatch(/"shorts\/shorts-warm-glow": \{"poster":/);+ });++ it("keeps what's up to date, and removes the files a tile no longer uses", () => {+ expect(run().covers.filter((c) => !c.same).every((c) => c.kept)).toBe(true);+ // The clip becomes a still, and the pack loses a frame.+ fs.rmSync(path.join(masters, "marketing/m2-sticker-pop/clip.mp4"));+ put("marketing/m2-sticker-pop", { "still.png": still });+ fs.rmSync(path.join(masters, "photodump/zen/frame-4.png"));+ run({ only: ["marketing/m2-sticker-pop", "photodump/zen"] });+ const m = gen.readTemplateManifest(manifest);+ expect(m["marketing/m2-sticker-pop"].video).toBeUndefined();+ expect(m["photodump/zen"].frames).toHaveLength(2);+ expect(fs.existsSync(path.join(publicDir, "previews/templates/marketing/m2-sticker-pop.mp4"))).toBe(false);+ expect(fs.existsSync(path.join(publicDir, "previews/templates/photodump/zen-4.jpg"))).toBe(false);+ expect(fs.existsSync(path.join(publicDir, "previews/templates/photodump/thumbs/zen-4.jpg"))).toBe(false);+ // The other tiles stay as they were.+ expect(Object.keys(m)).toHaveLength(5);+ });++ it("versions the manifest from the files as they are (--versions), and finds nothing to do when it's current", () => {+ expect(gen.versionTemplateCovers({ publicDir, manifest, dryRun: true })).toMatchObject({ entries: 5, changed: 0, thumbs: [], unversioned: [] });+ // A still replaced by hand: its copy is made again first, then both get a new version.+ const poster = path.join(publicDir, "previews/templates/marketing/ps-sunlit-plinth.jpg");+ const was = gen.readTemplateManifest(manifest)["marketing/ps-sunlit-plinth"].poster;+ fs.appendFileSync(poster, Buffer.from([0]));+ const later = new Date(Date.now() + 5000);+ fs.utimesSync(poster, later, later);+ expect(gen.versionTemplateCovers({ publicDir, manifest, dryRun: true }).thumbs).toEqual(["/previews/templates/marketing/thumbs/ps-sunlit-plinth.jpg"]);+ const r = gen.versionTemplateCovers({ publicDir, manifest });+ expect(r.changed).toBe(1);+ const now = gen.readTemplateManifest(manifest)["marketing/ps-sunlit-plinth"].poster;+ expect(now).not.toBe(was);+ expect(now).toBe(`/previews/templates/marketing/ps-sunlit-plinth.jpg?v=${sha8(poster, fileOf(thumbOf(now), publicDir))}`);+ });+});