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.

16.6 KB
Raw Blame
// 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, Fuobe
// Soul's looks, AI Influencer's character types, the Character Sheet, Storyboard and Elements examples), 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 preset clips' peak frames (scripts/gen-preset-peaks.mjs): where a tile that shows a preset's cover rests. */
export const PEAKS_FILE = path.join(REPO_DIR, "src", "lib", "preset-peaks.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", "soul", "influencer", "examples", "starters"];

/** At most this many frames per tile: the cover and up to five more (a contact sheet's 2x2, a carousel's slides, an example storyboard). */
const MAX_FRAMES = 6;
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`);
  }
}

/** The presets' peak frames ({ "<preset id>": { at, from, v } }); none when there is no file yet. */
export function readPresetPeaks(file = PEAKS_FILE) {
  let text;
  try {
    text = fs.readFileSync(file, "utf8");
  } catch (e) {
    if (e?.code === "ENOENT") return {};
    throw e;
  }
  const at = text.indexOf("export const PRESET_PEAKS");
  if (at < 0) throw new Error(`${file} has no PRESET_PEAKS`);
  return JSON.parse(text.slice(text.indexOf("=", at) + 1).trim().replace(/;\s*$/, ""));
}

/**
 * A tile that shows a preset's cover: its poster and clip, or, for a clip with a peak frame, that frame and where it
 * is in the clip, so the tile rests on the change (a look already drawn) as Home's cards do (onPeak), not on the photo
 * the clip starts from.
 */
export function presetCoverEntry(id, cover, peak) {
  if (cover.video !== undefined && peak) return { poster: `/previews/presets/peak/${id}.jpg?v=${peak.v}`, video: cover.video, at: peak.at };
  return { poster: cover.poster, ...(cover.video !== undefined && { video: cover.video }) };
}

/** 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-6 (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
 *                    ({ "rest": 2.4 }: the frame at 2.4 s is, for a clip whose telling moment comes before its end),
 *                    or { "same": "<preset id>" }: the tile shows that preset's cover (no files of its own),
 *                    resting on its clip's peak frame when it has one (presetCoverEntry).
 * 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, peaks?: 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 peaks = readPresetPeaks(opts.peaks);
  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 = presetCoverEntry(m.meta.same, p, peaks[m.meta.same]);
        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" ? undefined : m.meta.rest === "end" ? "end" : typeof m.meta.rest === "number" && Number.isFinite(m.meta.rest) && m.meta.rest >= 0 ? m.meta.rest : 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`);
      // A clip that rests on its end and comes with that last frame full size (poster.png, Kinetic's covers): the tile's
      // still is made from it at the still size, sharper than a frame of the small clip.
      const full = kind === "video" && rest === "end" && fs.existsSync(path.join(folder, "poster.png")) ? path.join(folder, "poster.png") : null;
      const sources = [src, ...m.frames, ...(full ? [full] : []), ...(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;
        if (full) encode(full, "image", base);
        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 });
  }
}