videogen/brand/generate.mjs
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

196 lines
7.9 KiB
JavaScript

#!/usr/bin/env node
// ============================================================================
// Menivor brand asset generator — generates logos/banners FROM the locked
// identities in identities.mjs. Reads REPLICATE_API_TOKEN from env. Zero deps.
//
// Usage:
// REPLICATE_API_TOKEN=r8_... node generate.mjs # all locked brands, logos
// node generate.mjs --only aether-wallet,vertex --kind all # subset, logo+banner
// node generate.mjs --only bump --n 4 # 4 logo candidates
// node generate.mjs --draft # include draft brands (review only)
//
// Output: out/<slug>/logo-N.svg, out/<slug>/banner-N.webp, out/<slug>/manifest.json
//
// The lock discipline: a brand with status != "locked" is generated ONLY when
// --draft is passed and its assets are marked review-only in the manifest.
// ============================================================================
import { mkdir, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { BRANDS, STUDIO } from "./identities.mjs";
const HERE = dirname(fileURLToPath(import.meta.url));
const OUT = join(HERE, "out");
const API = "https://api.replicate.com/v1";
const TOKEN = process.env.REPLICATE_API_TOKEN;
const MODELS = {
// clean minimalist logo marks — Ideogram v3 "Design" style_type is built for
// logos/graphics (recraft-v3 on Replicate only exposes illustrative styles that
// inject mascots/scenes).
logo: { path: "ideogram-ai/ideogram-v3-turbo", ext: "webp", ideogram: true },
// raster marketing banners
banner: { path: "recraft-ai/recraft-v3", ext: "webp", size: "1820x1024" },
};
function parseArgs(argv) {
const a = { only: null, kind: "logo", n: 3, draft: false };
for (let i = 0; i < argv.length; i++) {
const t = argv[i];
if (t === "--only") a.only = argv[++i].split(",").map((s) => s.trim());
else if (t === "--kind") a.kind = argv[++i]; // logo | banner | all
else if (t === "--n") a.n = Math.max(1, parseInt(argv[++i], 10) || 3);
else if (t === "--draft") a.draft = true;
}
return a;
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function createPrediction(modelPath, input, attempt = 0) {
const res = await fetch(`${API}/models/${modelPath}/predictions`, {
method: "POST",
headers: {
Authorization: `Bearer ${TOKEN}`,
"Content-Type": "application/json",
Prefer: "wait", // return synchronously when possible (up to ~60s)
},
body: JSON.stringify({ input }),
});
// Retry on throttling (low-credit accounts get 6/min) and transient 5xx.
if (res.status === 429 || res.status >= 500) {
if (attempt >= 8) throw new Error(`create failed ${res.status} after ${attempt} retries`);
let waitMs = 11000;
try {
const j = await res.clone().json();
if (j.retry_after) waitMs = (Number(j.retry_after) + 1) * 1000;
} catch {}
await sleep(waitMs);
return createPrediction(modelPath, input, attempt + 1);
}
if (!res.ok) throw new Error(`create failed ${res.status}: ${await res.text()}`);
return res.json();
}
async function replicate(modelPath, input) {
let pred = await createPrediction(modelPath, input);
// poll if not already terminal
const deadline = Date.now() + 4 * 60 * 1000;
while (!["succeeded", "failed", "canceled"].includes(pred.status)) {
if (Date.now() > deadline) throw new Error("timeout polling prediction");
await sleep(2500);
const p = await fetch(pred.urls.get, { headers: { Authorization: `Bearer ${TOKEN}` } });
pred = await p.json();
}
if (pred.status !== "succeeded") throw new Error(`prediction ${pred.status}: ${pred.error || ""}`);
const out = pred.output;
return Array.isArray(out) ? out : [out];
}
async function download(url, dest) {
const r = await fetch(url);
if (!r.ok) throw new Error(`download failed ${r.status}`);
const buf = Buffer.from(await r.arrayBuffer());
await writeFile(dest, buf);
return buf.length;
}
function logoInput(brand) {
// Terse, single-object prompt. Scene-y prompts make recraft render illustrations
// with mascots; a short concrete `mark` + hard constraints keeps it an icon.
const concept = brand.mark || brand.logo;
// Ideogram honors color NAMES more reliably than hex; prefer colorWords when set.
const colors = brand.colorWords || `${brand.palette.primary} and ${brand.palette.accent}`;
const prompt =
`Minimalist flat vector logo icon of ${concept}. Use ONLY two colors: ${colors}, ` +
`as a smooth two-color duotone gradient. No rainbow, no multicolor, no other hues. ` +
`Single centered symbol on a plain white background, simple bold geometric, flat. ` +
`No text, no letters, no words, no mascot, no animal, no human figure, no scene, no photorealism.`;
// Ideogram v3 param shape
return {
prompt,
aspect_ratio: "1:1",
style_type: "Design",
magic_prompt_option: "Off",
};
}
function bannerInput(brand) {
return {
prompt: `${brand.banner}. Palette: ${brand.palette.primary}, ${brand.palette.accent}, background ${brand.palette.ink}.`,
size: MODELS.banner.size,
};
}
async function genKind(brand, kind, n, reviewOnly) {
const model = MODELS[kind];
const input = kind === "logo" ? logoInput(brand) : bannerInput(brand);
const files = [];
for (let i = 1; i <= (kind === "banner" ? Math.min(n, 2) : n); i++) {
process.stdout.write(` ${kind} ${i}/${kind === "banner" ? Math.min(n, 2) : n}… `);
try {
const urls = await replicate(model.path, input);
const dir = join(OUT, brand.slug);
await mkdir(dir, { recursive: true });
const dest = join(dir, `${kind}-${i}.${model.ext}`);
const bytes = await download(urls[0], dest);
console.log(`ok (${bytes} B) -> out/${brand.slug}/${kind}-${i}.${model.ext}`);
files.push({ kind, file: `${kind}-${i}.${model.ext}`, bytes, reviewOnly });
} catch (e) {
console.log(`FAIL: ${e.message}`);
files.push({ kind, error: e.message });
}
}
return files;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
if (!TOKEN) {
console.error(
"\n✘ REPLICATE_API_TOKEN not set.\n" +
" Provide it, then re-run, e.g.:\n" +
" REPLICATE_API_TOKEN=r8_xxx node brand/generate.mjs --only aether-wallet,vertex --kind all\n" +
" (Get one at https://replicate.com/account/api-tokens)\n"
);
process.exit(2);
}
let brands = BRANDS.filter((b) => (args.draft ? true : b.status === "locked"));
if (args.only) brands = brands.filter((b) => args.only.includes(b.slug));
if (!brands.length) {
console.error("No matching locked brands (use --draft to include drafts).");
process.exit(1);
}
const kinds = args.kind === "all" ? ["logo", "banner"] : [args.kind];
console.log(`Generating [${kinds.join(", ")}] for: ${brands.map((b) => b.slug).join(", ")}\n`);
for (const brand of brands) {
const reviewOnly = brand.status !== "locked";
console.log(`▸ ${brand.name} (${brand.slug})${reviewOnly ? " [DRAFT — review only]" : ""}`);
await mkdir(join(OUT, brand.slug), { recursive: true });
const produced = [];
for (const k of kinds) produced.push(...(await genKind(brand, k, args.n, reviewOnly)));
const manifest = {
slug: brand.slug,
name: brand.name,
status: brand.status,
lockVersion: brand.lockVersion,
palette: brand.palette,
tagline: brand.tagline,
voice: brand.voice,
generatedAtUnix: Math.floor(Date.now() / 1000),
reviewOnly,
assets: produced,
note: "Pick a logo, then set `logoAsset` in identities.mjs to lock it as canonical.",
};
await writeFile(join(OUT, brand.slug, "manifest.json"), JSON.stringify(manifest, null, 2));
console.log("");
}
console.log("Done. Review out/<slug>/, choose a logo, then set logoAsset in identities.mjs.");
}
main().catch((e) => {
console.error(e);
process.exit(1);
});