331 lines
12 KiB
JavaScript
331 lines
12 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-image2-concepts',
|
||
);
|
||
const defaultTimeoutMs = 420000;
|
||
|
||
const concepts = [
|
||
{
|
||
id: 'taonier-image2-clay-spirit-glyph',
|
||
title: '泥灵符号',
|
||
prompt:
|
||
'为中文产品“陶泥儿”设计一个无文字 Logo 图标。方向:陶泥人、陶泥手办、抽象角色 / 吉祥物,但不要做人体形象,也不要做完整角色插画。主体像一块被轻轻捏出生命感的陶泥符号:单一圆润剪影,内部一个极简星核或负形孔洞,只有很少的点状生命感。必须是扁平矢量、主流 App icon、简单几何、亲和、醒目、可记忆、小尺寸清晰。配色:奶油白主形、暖陶土橙点缀、深墨背景、少量金色星核。禁止文字、字母、汉字、水印、真实人形、手脚、复杂五官、聊天气泡、播放三角、儿童黏土课、3D、厚阴影、贴纸感。',
|
||
},
|
||
{
|
||
id: 'taonier-image2-pinched-seed-mascot',
|
||
title: '捏胚小偶',
|
||
prompt:
|
||
'为“陶泥儿”设计无文字品牌主标。把“陶泥小人 / 手办 / 吉祥物”的精神压缩成一个非人形的几何泥胚:像一颗被捏过的种子或软陶坯,带一点抽象生命感,但没有手、脚、头发、衣服。中心有一颗极简四角闪光星,表达 AI 把脑洞捏成作品。风格:flat vector mascot mark, modern, friendly, geometric, logo-ready, not illustration。颜色控制在 3 到 4 色:深墨、奶白、陶土橙、暖黄。禁止文字、字母、汉字、真实陶艺工具、儿童玩具、emoji 表情、聊天气泡、播放按钮、复杂装饰、立体渲染。',
|
||
},
|
||
{
|
||
id: 'taonier-image2-soft-totem-creature',
|
||
title: '软陶图灵',
|
||
prompt:
|
||
'为“陶泥儿”设计无文字 Logo。主体是一个抽象陶泥角色图腾,不是人,也不是动物,而是一枚软陶手办被极简化后的品牌符号:上窄下稳、边缘像手捏过,中央有一个圆形作品核和一个小泥点。要有吉祥物的亲和力,但更像成熟平台主标。风格:bold flat vector, iconic silhouette, playful premium, highly memorable, simple enough for favicon。配色:深色背景、奶油白大形、陶土橙作品核、薄荷青或金色小点。禁止中文英文、复杂脸、两只眼睛加嘴的头像感、人体、手、脚、聊天气泡、播放三角、3D 质感。',
|
||
},
|
||
{
|
||
id: 'taonier-image2-clay-pocket-token',
|
||
title: '口袋泥符',
|
||
prompt:
|
||
'为“陶泥儿”设计一个能做 App icon 的无文字主 Logo。方向是“抽象口袋陶泥手办”:它像一个可以被收藏的小软陶 token,但不能是具体人物。主图形由一个圆角几何泥块、一处被捏出的缺口、一枚小星核组成,轮廓要一眼能记住。气质年轻、Q、可爱但不幼稚,适合 AI UGC 轻休闲小游戏平台。扁平矢量感,少色,高对比。禁止文字、字母、水印、真实人脸、手脚、表情包、聊天气泡、播放按钮、过多小元素、3D、照片感。',
|
||
},
|
||
{
|
||
id: 'taonier-image2-work-core-puppet',
|
||
title: '作品泥偶',
|
||
prompt:
|
||
'为“陶泥儿”设计无文字 Logo 图标。把陶泥手办的收藏感、AI 创作的作品核、UGC 玩梗传播的轻松感融合成一个抽象泥偶符号。不要画成人体,只用几何软块和负形孔洞表现“像有生命的陶泥作品”。主体简单、厚实、圆润,中心一枚四角星或小圆核,最多两个辅助泥点。风格:minimal vector mascot logo, clean, premium cute, mainstream consumer app icon。颜色:奶白、陶土橙、深墨、暖黄,可少量青绿。禁止文字、英文、汉字、复杂背景、复杂五官、真实手办、玩具包装、儿童黏土、3D 厚重阴影。',
|
||
},
|
||
{
|
||
id: 'taonier-image2-mold-blob-companion',
|
||
title: '模团伙伴',
|
||
prompt:
|
||
'为“陶泥儿”做一个无文字 Logo 主标。方向:非人形抽象吉祥物,像一团被模具轻轻压出的陶泥伙伴。整体是一个简单几何软形,带一个偏心孔洞和一个小闪光星,让人感觉它能承载用户脑洞、生成小游戏作品。要求主流、亲和、可爱、扁平、矢量、识别强,不能像插画或头像。配色:深墨底、奶油白主体、陶土橙和暖黄点缀,最多 4 色。禁止文字、字母、汉字、水印、手脚、五官表情、聊天气泡、播放三角、复杂碎片、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,
|
||
),
|
||
);
|