319 lines
9.8 KiB
JavaScript
319 lines
9.8 KiB
JavaScript
import { Buffer } from 'node:buffer';
|
||
import {
|
||
existsSync,
|
||
mkdirSync,
|
||
readFileSync,
|
||
readdirSync,
|
||
writeFileSync,
|
||
} from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
const repoRoot = process.cwd();
|
||
const outputDir = path.join(
|
||
repoRoot,
|
||
'public',
|
||
'branding',
|
||
'taonier-logo-abstract-mascot-minimal-concepts',
|
||
);
|
||
const defaultTimeoutMs = 420000;
|
||
|
||
const concepts = [
|
||
{
|
||
id: 'taonier-minimal-clay-core',
|
||
title: '泥芯主标',
|
||
prompt:
|
||
'为中文产品“陶泥儿”设计一个无文字 Logo。方向是抽象陶泥角色 / 吉祥物,但不要人形,不要脸,不要手脚。主体是一枚极简陶泥胚,只有一个主轮廓、一个偏心孔或作品核、一个小星点,像会呼吸的陶泥主标。必须扁平、几何、简洁、亲和、主流 App icon 风格。配色:奶油白、陶土橙、深墨底、少量金色。禁止文字、字母、汉字、水印、复杂五官、聊天气泡、播放三角、儿童玩具、3D、厚阴影、背景场景。',
|
||
},
|
||
{
|
||
id: 'taonier-minimal-clay-token',
|
||
title: '泥标小偶',
|
||
prompt:
|
||
'为“陶泥儿”设计无文字品牌 Logo。主体不是人物,而是一枚像被捏出来的软陶 token:圆润、稳定、边缘有手捏感,内部只有一个极简星核或孔洞,不要眼睛鼻子嘴巴。风格:flat vector mascot mark, simple, memorable, logo-ready, cute but mature. 配色限制在 3 色到 4 色:奶白、陶土橙、深墨、暖黄。禁止文字、字母、汉字、表情包、聊天气泡、播放按钮、真实陶艺工具、复杂碎片、3D、照片感。',
|
||
},
|
||
{
|
||
id: 'taonier-minimal-seed-glyph',
|
||
title: '泥种图符',
|
||
prompt:
|
||
'为中文产品“陶泥儿”设计一个无文字 Logo 图标。主题是“抽象陶泥角色”,但造型不使用人体。图形像一颗被轻轻捏过的种子,或者一枚从模具里长出的泥符,轮廓简单,记忆点集中在一个偏心洞和一颗小星核。要求简洁、几何、扁平、可注册、适合 App icon。配色:奶油白主体、暖陶土点缀、深墨背景、少量金黄。禁止文字、字母、汉字、水印、五官、手脚、动物、聊天气泡、播放三角、厚阴影、3D、背景道具。',
|
||
},
|
||
{
|
||
id: 'taonier-minimal-mold-bud',
|
||
title: '模胚小芽',
|
||
prompt:
|
||
'为“陶泥儿”设计无文字 Logo。主体像一枚从模具里鼓起来的陶泥小芽,只有一个主形、一个缺口、一个闪光点,不要人形,不要头像,不要复杂装饰。整体要像能代表 AI 创作、UGC 造物、轻休闲平台的品牌主标。风格:minimal flat mascot logo, clean, playful, premium, scalable. 配色:深墨、奶白、陶土橙、薄荷青或暖黄。禁止文字、字母、汉字、真实脸、聊天气泡、播放键、儿童卡通、3D、金属质感、摄影背景。',
|
||
},
|
||
];
|
||
|
||
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);
|
||
}
|
||
}
|
||
|
||
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 || defaultTimeoutMs),
|
||
10,
|
||
),
|
||
};
|
||
}
|
||
|
||
function buildUrl(baseUrl) {
|
||
return baseUrl.endsWith('/v1')
|
||
? `${baseUrl}/images/generations`
|
||
: `${baseUrl}/v1/images/generations`;
|
||
}
|
||
|
||
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 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}`);
|
||
}
|
||
return Buffer.from(await response.arrayBuffer());
|
||
} catch (error) {
|
||
if (error?.name === 'AbortError') {
|
||
throw new Error(`Generated image download timed out after ${timeoutMs}ms`);
|
||
}
|
||
throw error;
|
||
} finally {
|
||
clearTimeout(timer);
|
||
}
|
||
}
|
||
|
||
async function generateConcept(env, concept) {
|
||
const requestBody = {
|
||
model: 'gpt-image-2-all',
|
||
quality: String(args.get('--quality') || 'low'),
|
||
prompt: concept.prompt,
|
||
n: 1,
|
||
size: '1024x1024',
|
||
};
|
||
const payload = await fetchJson(
|
||
buildUrl(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 bytes;
|
||
if (urls[0]) {
|
||
bytes = await downloadUrl(urls[0], env.timeoutMs);
|
||
} else if (b64Images[0]) {
|
||
bytes = Buffer.from(b64Images[0], 'base64');
|
||
} else {
|
||
throw new Error(`VectorEngine returned no image for ${concept.id}`);
|
||
}
|
||
|
||
mkdirSync(outputDir, { recursive: true });
|
||
const extension = inferExtensionFromBytes(bytes);
|
||
const outputPath = path.join(outputDir, `${concept.id}.${extension}`);
|
||
writeFileSync(outputPath, bytes);
|
||
return outputPath;
|
||
}
|
||
|
||
const dryRun = args.has('--dry-run') || !args.has('--live');
|
||
const onlyIds = String(args.get('--only') || '')
|
||
.split(',')
|
||
.map((value) => value.trim())
|
||
.filter(Boolean);
|
||
const limit = Number.parseInt(String(args.get('--limit') || '0'), 10);
|
||
const selected = concepts
|
||
.filter((concept) => !onlyIds.length || onlyIds.includes(concept.id))
|
||
.slice(0, limit > 0 ? limit : concepts.length);
|
||
|
||
if (dryRun) {
|
||
console.log(
|
||
JSON.stringify(
|
||
{
|
||
mode: 'dry-run',
|
||
outputDir,
|
||
count: selected.length,
|
||
requests: selected.map((concept) => ({
|
||
id: concept.id,
|
||
title: concept.title,
|
||
body: {
|
||
model: 'gpt-image-2-all',
|
||
quality: String(args.get('--quality') || 'low'),
|
||
prompt: concept.prompt,
|
||
n: 1,
|
||
size: '1024x1024',
|
||
},
|
||
})),
|
||
},
|
||
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 concept of selected) {
|
||
console.log(`Generating ${concept.id}...`);
|
||
generated.push(await generateConcept(env, concept));
|
||
}
|
||
|
||
console.log(
|
||
JSON.stringify(
|
||
{
|
||
ok: true,
|
||
count: generated.length,
|
||
files: generated,
|
||
verifiedFiles: readdirSync(outputDir).sort(),
|
||
},
|
||
null,
|
||
2,
|
||
),
|
||
);
|