import { Buffer } from 'node:buffer'; import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); const repoRoot = path.resolve(__dirname, '..'); const outputDir = path.join( repoRoot, 'public', 'branding', 'taonier-logo-brief-concepts', ); const timeoutMsDefault = 180000; const args = new Map(); for (let index = 2; index < process.argv.length; index += 1) { const raw = process.argv[index]; if (!raw.startsWith('--')) { continue; } const next = process.argv[index + 1]; if (next && !next.startsWith('--')) { args.set(raw, next); index += 1; } else { args.set(raw, true); } } const logoBrief = { brand: '陶泥儿', logoType: 'symbol/icon-only mark, no wordmark', product: 'AI UGC 轻休闲小游戏创作与传播平台,用户像捏陶泥一样把脑洞、梗和灵感塑造成作品', personality: ['亲和', '精品', '创作感', '轻松', '年轻', '有传播记忆点'], mustHave: [ '闭合不规则几何底盘', '外轮廓由流畅曲线组成', '整体是一个完整符号而不是自由飘带', '32px 仍能识别', '黑白化后仍成立', '无中文、无英文、无字标', ], avoid: [ '整体方形或圆角方块', '中心星星或任何星形', '自由飘带、旋涡、S/G 字母感', '巧克力面包、甜点、饼干、糖果等食物感', '砖块、土块、泥饼、陶片、考古印章', '脸、表情、吉祥物、手、工具', ], }; const basePrompt = [ 'Create an icon-only brand logo symbol for the Chinese product named "陶泥儿"; do not render any Chinese, English, letters, numbers, wordmark, tagline, or text.', 'Brand personality: friendly, premium, creative, lightweight, young, memorable, suitable for an AI UGC casual game creation platform.', 'Core metaphor: users shape imagination like clay. The logo should communicate soft creative material becoming a refined digital product symbol.', 'Logo type: abstract symbol/icon only. Not an emblem with text, not a mascot, not an app-icon rounded-square background.', 'Main element: one closed irregular geometric base shape made from smooth flowing curves. The outer contour must be closed, continuous, recognizable, organic, and vector-friendly.', 'The shape must not be a square, rounded square, circle, ellipse, simple blob, ribbon, swirl, S shape, G shape, open ring, or loose strip. It should feel like a refined custom symbol with 5-7 soft curve turns.', 'Internal design: use only 1-2 broad smooth curve partitions or negative-shape cuts to make the mark memorable. No center icon inserted. No star, no spark, no hole shaped like a star.', 'Style: modern minimalist vector logo with very subtle matte clay warmth. Clean edges, broad shapes, high contrast, no tiny details. It must look good and recognizable at 32px favicon size.', 'Color: warm ceramic white, light terracotta, clay orange, warm brown, with optional small low-saturation teal, indigo-gray, or dark mud gray accent. Avoid sweet candy colors. No glossy highlights.', 'Food avoidance is critical: the mark must not look like bread, chocolate bread, croissant, pastry, cookie, candy, donut, cream filling, sauce, baked dough, dessert, or food packaging.', 'Material avoidance: do not make it look like brick, dirt clod, mud pie, pottery shard, stone, archaeological stamp, or rough handmade craft class object.', 'Composition: centered on a clean light background, generous safe area, no border, no UI, no watermark. Use simple readable silhouette first.', 'Validation targets: black-and-white version should still read clearly; the large shape should be recognizable at 32px.', ]; const variants = [ { id: '01-closed-curve-mark', title: '闭合曲线标', prompt: [ ...basePrompt, 'Variant focus: the cleanest closed irregular curve mark. Use two large color areas separated by one smooth internal curve. Maximize 32px readability.', ], }, { id: '02-friendly-geo-seed', title: '亲和几何种', prompt: [ ...basePrompt, 'Variant focus: a friendly seed-like closed geometric base, but not a literal seed, not food. Rounded and approachable with one teal accent curve.', ], }, { id: '03-premium-soft-contour', title: '精品软轮廓', prompt: [ ...basePrompt, 'Variant focus: premium, calm, fewer colors. Strong outer contour with a dark mud-gray internal negative curve. Very logo-like, not illustrative.', ], }, { id: '04-playful-closed-tile', title: '轻玩闭合片', prompt: [ ...basePrompt, 'Variant focus: a more playful closed irregular tile with warm terracotta and ceramic white. The internal curve should suggest creation flow, not filling.', ], }, { id: '05-monochrome-first', title: '黑白优先', prompt: [ ...basePrompt, 'Variant focus: design as if it will be converted to black and white. Use bold positive and negative shapes; color only supports the structure.', ], }, { id: '06-digital-clay-accent', title: '数字陶泥点', prompt: [ ...basePrompt, 'Variant focus: include at most two tiny geometric accent dots or notches that imply AI/UGC, but they must not look like candy sprinkles or decorative confetti.', ], }, { id: '07-compact-avatar-symbol', title: '头像紧凑标', prompt: [ ...basePrompt, 'Variant focus: compact social-avatar readability. The closed contour should be slightly fuller and more iconic, but not a rounded-square app background.', ], }, { id: '08-designer-vector-ready', title: '矢量定稿感', prompt: [ ...basePrompt, 'Variant focus: make it look like a designer-ready vector concept: 2-3 flat shapes, crisp boundaries, distinctive closed outer contour, minimal material texture.', ], }, ]; function readDotenv(fileName) { const filePath = path.join(repoRoot, fileName); if (!existsSync(filePath)) { return {}; } const values = {}; for (const line of readFileSync(filePath, 'utf8').split(/\r?\n/u)) { const trimmed = line.trim(); if (!trimmed || trimmed.startsWith('#')) { continue; } const match = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/u.exec(trimmed); if (!match) { continue; } let value = match[2].trim(); if ( (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")) ) { value = value.slice(1, -1); } values[match[1]] = value; } return values; } function resolveEnv() { const loaded = { ...readDotenv('.env.example'), ...readDotenv('.env.local'), ...readDotenv('.env.secrets.local'), ...process.env, }; return { baseUrl: String(loaded.VECTOR_ENGINE_BASE_URL || '') .trim() .replace(/\/+$/u, ''), apiKey: String(loaded.VECTOR_ENGINE_API_KEY || '').trim(), timeoutMs: Number.parseInt( String(loaded.VECTOR_ENGINE_IMAGE_REQUEST_TIMEOUT_MS || timeoutMsDefault), 10, ), }; } function buildVectorEngineImagesGenerationUrl(baseUrl) { return baseUrl.endsWith('/v1') ? `${baseUrl}/images/generations` : `${baseUrl}/v1/images/generations`; } function buildRequestBody(variant) { return { model: 'gpt-image-2-all', prompt: variant.prompt.join('\n'), n: 1, size: '1024x1024', }; } function collectStringsByKey(value, targetKey, output) { if (Array.isArray(value)) { value.forEach((entry) => collectStringsByKey(entry, targetKey, output)); return; } if (!value || typeof value !== 'object') { return; } for (const [key, nested] of Object.entries(value)) { if (key === targetKey) { if (typeof nested === 'string' && nested.trim()) { output.push(nested.trim()); } if (Array.isArray(nested)) { nested.forEach((entry) => { if (typeof entry === 'string' && entry.trim()) { output.push(entry.trim()); } }); } } collectStringsByKey(nested, targetKey, output); } } function extractImageUrls(payload) { const urls = []; collectStringsByKey(payload, 'url', urls); collectStringsByKey(payload, 'image', urls); collectStringsByKey(payload, 'image_url', urls); return [...new Set(urls)].filter((url) => /^https?:\/\//u.test(url)); } function extractBase64Images(payload) { const values = []; collectStringsByKey(payload, 'b64_json', values); return values; } function inferExtensionFromContentType(contentType) { const normalized = contentType.split(';')[0]?.trim().toLowerCase(); if (normalized === 'image/png') { return 'png'; } if (normalized === 'image/webp') { return 'webp'; } if (normalized === 'image/gif') { return 'gif'; } return 'jpg'; } function inferExtensionFromBytes(bytes) { if (bytes.subarray(0, 8).equals(Buffer.from('\x89PNG\r\n\x1A\n', 'binary'))) { return 'png'; } if (bytes.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) { return 'jpg'; } if ( bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP' ) { return 'webp'; } return 'png'; } async function fetchJson(url, options, timeoutMs) { const abortController = new AbortController(); const timer = setTimeout(() => abortController.abort(), timeoutMs); try { const response = await fetch(url, { ...options, signal: abortController.signal, }); const text = await response.text(); if (!response.ok) { throw new Error(`VectorEngine ${response.status}: ${text.slice(0, 600)}`); } return JSON.parse(text); } catch (error) { if (error?.name === 'AbortError') { throw new Error(`VectorEngine request timed out after ${timeoutMs}ms`); } throw error; } finally { clearTimeout(timer); } } async function downloadUrl(url, timeoutMs) { const abortController = new AbortController(); const timer = setTimeout(() => abortController.abort(), timeoutMs); try { const response = await fetch(url, { signal: abortController.signal }); if (!response.ok) { throw new Error(`download ${response.status}`); } const bytes = Buffer.from(await response.arrayBuffer()); return { bytes, extension: inferExtensionFromContentType( response.headers.get('content-type') || 'image/jpeg', ), }; } catch (error) { if (error?.name === 'AbortError') { throw new Error(`Generated image download timed out after ${timeoutMs}ms`); } throw error; } finally { clearTimeout(timer); } } async function generateOne(env, variant) { const requestBody = buildRequestBody(variant); const payload = await fetchJson( buildVectorEngineImagesGenerationUrl(env.baseUrl), { method: 'POST', headers: { Authorization: `Bearer ${env.apiKey}`, Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(requestBody), }, env.timeoutMs, ); const urls = extractImageUrls(payload); const b64Images = extractBase64Images(payload); let image; if (urls[0]) { image = await downloadUrl(urls[0], env.timeoutMs); } else if (b64Images[0]) { const bytes = Buffer.from(b64Images[0], 'base64'); image = { bytes, extension: inferExtensionFromBytes(bytes), }; } else { throw new Error(`VectorEngine returned no image for ${variant.id}`); } mkdirSync(outputDir, { recursive: true }); const outputPath = path.join(outputDir, `taonier-logo-brief-${variant.id}.${image.extension}`); writeFileSync(outputPath, image.bytes); return outputPath; } function writeManifest(files) { const manifestPath = path.join(outputDir, 'taonier-logo-brief-manifest.json'); writeFileSync( manifestPath, `${JSON.stringify( { model: 'gpt-image-2-all', size: '1024x1024', generatedAt: new Date().toISOString(), logoSkillSummary: { requiredReview: 'visual inspection, 32px readability, black-white viability', outputStatus: 'AI concept only; final logo needs vector cleanup', }, brief: logoBrief, variants: variants.map((variant) => { const file = files.find((item) => path.basename(item).includes(variant.id)); return { id: variant.id, title: variant.title, file: file ? path.basename(file) : null, prompt: variant.prompt.join('\n'), }; }), }, null, 2, )}\n`, 'utf8', ); return manifestPath; } const dryRun = args.has('--dry-run') || !args.has('--live'); const limit = Number.parseInt(String(args.get('--limit') || variants.length), 10); const selectedVariants = variants.slice(0, limit); if (dryRun) { console.log( JSON.stringify( { mode: 'dry-run', outputDir, count: selectedVariants.length, brief: logoBrief, requests: selectedVariants.map((variant) => ({ id: variant.id, title: variant.title, body: buildRequestBody(variant), })), }, null, 2, ), ); process.exit(0); } const env = resolveEnv(); if (!env.baseUrl || !env.apiKey) { console.error( JSON.stringify({ ok: false, error: 'Missing VECTOR_ENGINE_BASE_URL or VECTOR_ENGINE_API_KEY', hasBaseUrl: Boolean(env.baseUrl), hasApiKey: Boolean(env.apiKey), }), ); process.exit(1); } const generated = []; for (const variant of selectedVariants) { console.log(`Generating ${variant.id} ${variant.title}...`); generated.push(await generateOne(env, variant)); } const manifestPath = writeManifest(generated); console.log( JSON.stringify( { ok: true, count: generated.length, files: generated, manifest: manifestPath, }, null, 2, ), );