收口画布生图抠图选项
移除前端用户侧背景色和抠图模型选择入口,提交路径固定使用 auto 与 birefnet。 清理生成输入快照和恢复逻辑中的抠图背景色与抠图模型残留。 保留后端 BgFilter 内部兼容能力,并修正空图标描述不再兜底默认描述提交。 同步更新编辑器和项目记忆文档。
This commit is contained in:
@@ -60,9 +60,16 @@ function readPositiveIntArg(name, fallback) {
|
||||
if (!rawValue) {
|
||||
return fallback;
|
||||
}
|
||||
return parsePositiveInt(`--${name}`, rawValue);
|
||||
}
|
||||
|
||||
function parsePositiveInt(label, rawValue) {
|
||||
if (!/^\d+$/.test(rawValue)) {
|
||||
throw new Error(`${label} 必须是正整数,当前为 ${rawValue}`);
|
||||
}
|
||||
const value = Number.parseInt(rawValue, 10);
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new Error(`--${name} 必须是正整数,当前为 ${rawValue}`);
|
||||
if (value <= 0) {
|
||||
throw new Error(`${label} 必须是正整数,当前为 ${rawValue}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
@@ -168,11 +175,13 @@ const segModel =
|
||||
const token =
|
||||
readConfig('GENARRATIVE_EDITOR_BGFILTER_TOKEN') ||
|
||||
readConfig('GENARRATIVE_EDITOR_BACKGROUND_REMOVAL_TOKEN');
|
||||
const timeoutMs = Number.parseInt(
|
||||
readArg('timeout-ms') ||
|
||||
const timeoutMs = readPositiveIntArg(
|
||||
'timeout-ms',
|
||||
parsePositiveInt(
|
||||
'GENARRATIVE_EDITOR_BGFILTER_REQUEST_TIMEOUT_MS',
|
||||
readConfig('GENARRATIVE_EDITOR_BGFILTER_REQUEST_TIMEOUT_MS') ||
|
||||
`${DEFAULT_TIMEOUT_MS}`,
|
||||
10,
|
||||
`${DEFAULT_TIMEOUT_MS}`,
|
||||
),
|
||||
);
|
||||
const width = readPositiveIntArg('width', 96);
|
||||
const height = readPositiveIntArg('height', width);
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(__dirname, '..');
|
||||
const defaultTimeoutMs = 1_000_000;
|
||||
|
||||
function readArg(name) {
|
||||
const prefix = `--${name}=`;
|
||||
const value = process.argv.find((arg) => arg.startsWith(prefix));
|
||||
return value ? value.slice(prefix.length) : '';
|
||||
}
|
||||
|
||||
function resolveOutputSize() {
|
||||
const value = readArg('size') || '2048x1152';
|
||||
if (!/^\d{2,5}x\d{2,5}$/u.test(value)) {
|
||||
throw new Error(`--size 必须形如 2048x2048,当前为 ${value}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
const outputSize = resolveOutputSize();
|
||||
|
||||
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 buildImagesGenerationUrl(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 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}`);
|
||||
}
|
||||
return {
|
||||
bytes: Buffer.from(await response.arrayBuffer()),
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
function buildPrompt() {
|
||||
return [
|
||||
'按照角色描述生成游戏角色立绘。',
|
||||
'角色设定:女精灵弓箭手,修长敏捷,尖耳,银金色长发,翠绿色眼睛,穿轻便森林皮甲与深绿色披风,手持精致长弓,背负箭袋,姿态自信警觉。',
|
||||
'严格要求:画面中心构图,角色主体完整置于画面中央,完整展示头部、身体、双腿、武器和披风,禁止镜头透视,禁止特写。',
|
||||
'美术风格:高品质幻想游戏概念设定图,干净轮廓,精致但不复杂,适合作为可抠图角色素材。',
|
||||
'背景固定为单一纯色背景 浅雾蓝 #CFEFFF / RGB(207,239,255),只作为抠像底色;纯色背景必须平整无纹理、无渐变、无阴影、无地面、无环境、无道具;角色主体不得带与背景色相同或相近的描边、投影或反光。',
|
||||
'禁止生成建筑、室内布景、风景、地面道具、漂浮物、烟雾叙事元素、文字、水印、边框、UI 元素或其他角色。',
|
||||
].join('');
|
||||
}
|
||||
|
||||
const env = resolveEnv();
|
||||
if (!env.baseUrl || !env.apiKey) {
|
||||
console.error(
|
||||
`缺少配置:VECTOR_ENGINE_BASE_URL=${env.baseUrl ? '已配置' : '未配置'},VECTOR_ENGINE_API_KEY=${
|
||||
env.apiKey ? '已配置' : '未配置'
|
||||
}`,
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const requestBody = {
|
||||
model: 'gpt-image-2',
|
||||
prompt: buildPrompt(),
|
||||
n: 1,
|
||||
size: outputSize,
|
||||
};
|
||||
|
||||
console.log('gpt-image-2 生成女精灵弓箭手');
|
||||
console.log(`目标: ${buildImagesGenerationUrl(env.baseUrl)}`);
|
||||
console.log(`size: ${outputSize}`);
|
||||
console.log(`timeout_ms: ${env.timeoutMs}`);
|
||||
console.log('api_key: 已配置\n');
|
||||
|
||||
const payload = await fetchJson(
|
||||
buildImagesGenerationUrl(env.baseUrl),
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${env.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(requestBody),
|
||||
},
|
||||
env.timeoutMs,
|
||||
);
|
||||
|
||||
let image;
|
||||
const base64Images = extractBase64Images(payload);
|
||||
if (base64Images.length > 0) {
|
||||
const bytes = Buffer.from(base64Images[0], 'base64');
|
||||
image = { bytes, extension: inferExtensionFromBytes(bytes) };
|
||||
} else {
|
||||
const urls = extractImageUrls(payload);
|
||||
if (urls.length === 0) {
|
||||
throw new Error(`响应中未找到图片 URL 或 b64_json:${JSON.stringify(payload).slice(0, 600)}`);
|
||||
}
|
||||
image = await downloadUrl(urls[0], env.timeoutMs);
|
||||
}
|
||||
|
||||
const downloadsDir = path.join(os.homedir(), 'Downloads');
|
||||
mkdirSync(downloadsDir, { recursive: true });
|
||||
const outputPath = path.join(
|
||||
downloadsDir,
|
||||
`gpt-image-2-elf-archer-${outputSize}.${image.extension}`,
|
||||
);
|
||||
writeFileSync(outputPath, image.bytes);
|
||||
|
||||
console.log(`已保存: ${outputPath}`);
|
||||
console.log(`bytes: ${image.bytes.length}`);
|
||||
Reference in New Issue
Block a user