dsh-game-material-master 0.4.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +101 -12
- package/README.md +86 -11
- package/lib/ark.js +1 -1
- package/lib/{tilemedia.js → bitmap.js} +21 -3
- package/lib/client.js +3295 -158
- package/lib/config.js +70 -2
- package/lib/customimage.js +518 -0
- package/lib/imagegen.js +15 -15
- package/lib/imageprovider.js +151 -0
- package/lib/index.js +305 -9
- package/lib/jsonio.js +24 -3
- package/lib/links.js +11 -2
- package/lib/mapauto.js +126 -0
- package/lib/mapdoc.js +617 -0
- package/lib/mapexport.js +188 -0
- package/lib/mapgen.js +1591 -0
- package/lib/mapgeom.js +320 -0
- package/lib/maprender.js +484 -0
- package/lib/mapsample.js +36 -0
- package/lib/mapsamplegen.js +760 -0
- package/lib/maptiles.js +253 -0
- package/lib/media.js +34 -0
- package/lib/pipeline.js +197 -15
- package/lib/rigexport.js +29 -98
- package/lib/riggen.js +34 -30
- package/lib/rigpath.js +47 -10
- package/lib/rigpreview.js +91 -84
- package/lib/rigsemantics.js +4 -4
- package/lib/rigvalidate.js +72 -14
- package/lib/spine.js +147 -80
- package/lib/store.js +12 -3
- package/lib/tilegen.js +7 -11
- package/lib/tilegeom.js +1 -1
- package/lib/tools.js +253 -29
- package/lib/wire.js +198 -3
- package/lib/zip.js +127 -0
- package/package.json +10 -4
package/lib/config.js
CHANGED
|
@@ -85,7 +85,55 @@ export async function migrateLegacyDataRoot() {
|
|
|
85
85
|
return false;
|
|
86
86
|
}
|
|
87
87
|
}
|
|
88
|
+
/**
|
|
89
|
+
* 生图后端。
|
|
90
|
+
*
|
|
91
|
+
* `ark` = 火山方舟 Seedream(默认,也是唯一「开箱即用」的云端选择);
|
|
92
|
+
* `custom` = 用户自己的生图服务,协议再分 OpenAI / ComfyUI / Stable Diffusion WebUI。
|
|
93
|
+
* 换后端只改这一个字段:所有生图调用点都走 `imageprovider.generateImageWithProvider`。
|
|
94
|
+
*/
|
|
95
|
+
export const IMAGE_PROVIDERS = ["ark", "custom"];
|
|
96
|
+
/** 自定义生图服务的协议。 */
|
|
97
|
+
export const CUSTOM_PROTOCOLS = ["openai", "comfyui", "sdwebui"];
|
|
98
|
+
/**
|
|
99
|
+
* 各协议的默认地址。
|
|
100
|
+
*
|
|
101
|
+
* 设置页在**协议切换**时会拿它做「原来那个地址还是默认值吗」的判断,
|
|
102
|
+
* 是就顺手换成新协议的默认地址(和 MiniMax 切「优云智算版」同一套做法)——
|
|
103
|
+
* 手动改过地址的用户不会被覆盖。
|
|
104
|
+
*/
|
|
105
|
+
export const CUSTOM_PROTOCOL_DEFAULTS = {
|
|
106
|
+
openai: {
|
|
107
|
+
baseUrl: "https://api.openai.com/v1",
|
|
108
|
+
label: "OpenAI API",
|
|
109
|
+
hint: "POST {base}/images/generations(带参考图时优先 POST {base}/images/edits)"
|
|
110
|
+
},
|
|
111
|
+
comfyui: {
|
|
112
|
+
baseUrl: "http://127.0.0.1:8188",
|
|
113
|
+
label: "ComfyUI API",
|
|
114
|
+
hint: "POST {base}/prompt + GET {base}/history/{id} + GET {base}/view(需要用 API 格式的工作流 JSON)"
|
|
115
|
+
},
|
|
116
|
+
sdwebui: {
|
|
117
|
+
baseUrl: "http://127.0.0.1:7860",
|
|
118
|
+
label: "Stable Diffusion WebUI API",
|
|
119
|
+
hint: "POST {base}/sdapi/v1/txt2img(带参考图时走 /sdapi/v1/img2img,需要启动时加 --api)"
|
|
120
|
+
}
|
|
121
|
+
};
|
|
88
122
|
export const DEFAULT_CONFIG = {
|
|
123
|
+
imageProvider: "ark",
|
|
124
|
+
customProtocol: "openai",
|
|
125
|
+
customBaseUrl: CUSTOM_PROTOCOL_DEFAULTS.openai.baseUrl,
|
|
126
|
+
customApiKey: "",
|
|
127
|
+
customModel: "gpt-image-1",
|
|
128
|
+
customSize: "1024x1024",
|
|
129
|
+
customNegativePrompt: "",
|
|
130
|
+
customSteps: 28,
|
|
131
|
+
customCfgScale: 7,
|
|
132
|
+
customSampler: "DPM++ 2M Karras",
|
|
133
|
+
customDenoising: 0.65,
|
|
134
|
+
customSeed: -1,
|
|
135
|
+
customWorkflow: "",
|
|
136
|
+
customTimeoutMs: 300000,
|
|
89
137
|
arkApiKey: "",
|
|
90
138
|
arkBaseUrl: "https://ark.cn-beijing.volces.com/api/v3",
|
|
91
139
|
/**
|
|
@@ -210,6 +258,24 @@ export function normalizeConfig(input) {
|
|
|
210
258
|
const minimaxDuration = normalizeDuration(minimaxModel, raw.minimaxDuration ?? DEFAULT_CONFIG.minimaxDuration);
|
|
211
259
|
const minimaxResolution = normalizeResolution(minimaxModel, raw.minimaxResolution ?? DEFAULT_CONFIG.minimaxResolution);
|
|
212
260
|
return {
|
|
261
|
+
imageProvider: raw.imageProvider === "custom" ? "custom" : "ark",
|
|
262
|
+
customProtocol: CUSTOM_PROTOCOLS.includes(String(raw.customProtocol))
|
|
263
|
+
? raw.customProtocol
|
|
264
|
+
: DEFAULT_CONFIG.customProtocol,
|
|
265
|
+
customBaseUrl: asString(raw.customBaseUrl, DEFAULT_CONFIG.customBaseUrl).replace(/\/+$/, ""),
|
|
266
|
+
customApiKey: asString(raw.customApiKey, DEFAULT_CONFIG.customApiKey),
|
|
267
|
+
customModel: asString(raw.customModel, DEFAULT_CONFIG.customModel),
|
|
268
|
+
customSize: asString(raw.customSize, DEFAULT_CONFIG.customSize),
|
|
269
|
+
customNegativePrompt: asString(raw.customNegativePrompt, DEFAULT_CONFIG.customNegativePrompt),
|
|
270
|
+
customSteps: asInt(raw.customSteps, DEFAULT_CONFIG.customSteps, 1, 150),
|
|
271
|
+
// 上限放到 30:有些后端把 CFG 当纯缩放用;下限 0 = 完全不看提示词(罕见但合法)。
|
|
272
|
+
customCfgScale: asNumber(raw.customCfgScale, DEFAULT_CONFIG.customCfgScale, 0, 30),
|
|
273
|
+
customSampler: asString(raw.customSampler, DEFAULT_CONFIG.customSampler),
|
|
274
|
+
customDenoising: asNumber(raw.customDenoising, DEFAULT_CONFIG.customDenoising, 0, 1),
|
|
275
|
+
// -1 是「随机」的约定值,其余收敛到 32 位无符号范围(ComfyUI 的 KSampler 是 int)。
|
|
276
|
+
customSeed: asInt(raw.customSeed, DEFAULT_CONFIG.customSeed, -1, 2147483647),
|
|
277
|
+
customWorkflow: asString(raw.customWorkflow, DEFAULT_CONFIG.customWorkflow),
|
|
278
|
+
customTimeoutMs: asInt(raw.customTimeoutMs, DEFAULT_CONFIG.customTimeoutMs, 10000, 3600000),
|
|
213
279
|
arkApiKey: asString(raw.arkApiKey, DEFAULT_CONFIG.arkApiKey),
|
|
214
280
|
arkBaseUrl: asString(raw.arkBaseUrl, DEFAULT_CONFIG.arkBaseUrl).replace(/\/+$/, ""),
|
|
215
281
|
arkModel: asString(raw.arkModel, DEFAULT_CONFIG.arkModel),
|
|
@@ -270,7 +336,7 @@ export async function saveConfig(patch) {
|
|
|
270
336
|
return next;
|
|
271
337
|
}
|
|
272
338
|
export function maskConfig(config) {
|
|
273
|
-
const { arkApiKey, minimaxApiKey, ...rest } = config;
|
|
339
|
+
const { arkApiKey, minimaxApiKey, customApiKey, ...rest } = config;
|
|
274
340
|
return {
|
|
275
341
|
...rest,
|
|
276
342
|
rowOrder: [...config.rowOrder],
|
|
@@ -279,7 +345,9 @@ export function maskConfig(config) {
|
|
|
279
345
|
arkApiKeySet: arkApiKey.trim() !== "",
|
|
280
346
|
arkApiKeyHint: hintOf(arkApiKey),
|
|
281
347
|
minimaxApiKeySet: minimaxApiKey.trim() !== "",
|
|
282
|
-
minimaxApiKeyHint: hintOf(minimaxApiKey)
|
|
348
|
+
minimaxApiKeyHint: hintOf(minimaxApiKey),
|
|
349
|
+
customApiKeySet: customApiKey.trim() !== "",
|
|
350
|
+
customApiKeyHint: hintOf(customApiKey)
|
|
283
351
|
};
|
|
284
352
|
}
|
|
285
353
|
function hintOf(key) {
|
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 自定义生图后端:OpenAI API / ComfyUI API / Stable Diffusion WebUI API。
|
|
3
|
+
*
|
|
4
|
+
* 三个协议的共同点是「都返回图片字节」,差异全在**怎么问**:
|
|
5
|
+
*
|
|
6
|
+
* | 协议 | 生图 | 带参考图 | 取结果 |
|
|
7
|
+
* |---|---|---|---|
|
|
8
|
+
* | `openai` | `POST {base}/images/generations` | `POST {base}/images/edits`(multipart),
|
|
9
|
+
* 端点不存在时退回 generations 的 `image` 字段 | `data[0].b64_json` 或 `data[0].url` |
|
|
10
|
+
* | `sdwebui` | `POST {base}/sdapi/v1/txt2img` | `POST {base}/sdapi/v1/img2img`(`init_images`) | `images[0]`(base64) |
|
|
11
|
+
* | `comfyui` | `POST {base}/prompt` + 轮询 `/history` + `GET /view` | 先 `POST {base}/upload/image`,把文件名写进工作流 | `/view` 返回的图片字节 |
|
|
12
|
+
*
|
|
13
|
+
* 这里**只负责一次调用**,不做重试、不碰落盘:重试与产物管理在各自的模块里。
|
|
14
|
+
*/
|
|
15
|
+
import { sniffExt } from "./ark.js";
|
|
16
|
+
import { CUSTOM_PROTOCOL_DEFAULTS } from "./config.js";
|
|
17
|
+
export class CustomImageError extends Error {
|
|
18
|
+
status;
|
|
19
|
+
constructor(message, status) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.name = "CustomImageError";
|
|
22
|
+
this.status = status;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function protocolLabel(protocol) {
|
|
26
|
+
return CUSTOM_PROTOCOL_DEFAULTS[protocol]?.label ?? protocol;
|
|
27
|
+
}
|
|
28
|
+
/** 拼端点:容忍用户把末尾斜杠写多了。 */
|
|
29
|
+
function joinUrl(baseUrl, path) {
|
|
30
|
+
return `${baseUrl.replace(/\/+$/, "")}${path}`;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 鉴权头。
|
|
34
|
+
*
|
|
35
|
+
* 三种情况都要照顾到:没有 Key(本地服务,最常见)、`user:pass`(A1111 的 `--api-auth`
|
|
36
|
+
* 是 HTTP Basic)、以及普通 Bearer Token(云端 OpenAI 兼容服务)。
|
|
37
|
+
*/
|
|
38
|
+
function authHeaders(apiKey) {
|
|
39
|
+
const key = apiKey.trim();
|
|
40
|
+
if (key === "")
|
|
41
|
+
return {};
|
|
42
|
+
if (key.includes(":")) {
|
|
43
|
+
return { Authorization: `Basic ${Buffer.from(key, "utf8").toString("base64")}` };
|
|
44
|
+
}
|
|
45
|
+
return { Authorization: `Bearer ${key}` };
|
|
46
|
+
}
|
|
47
|
+
function makeSignalContext(protocol, timeoutMs, signal) {
|
|
48
|
+
const timeout = AbortSignal.timeout(Math.max(10000, timeoutMs));
|
|
49
|
+
return {
|
|
50
|
+
protocol,
|
|
51
|
+
timeoutMs,
|
|
52
|
+
signal,
|
|
53
|
+
timeout,
|
|
54
|
+
composed: signal === undefined ? timeout : AbortSignal.any([signal, timeout])
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/** 统一的网络错误翻译:超时 / 主动取消 / 连不上,三种要给用户完全不同的提示。 */
|
|
58
|
+
function networkError(context, error) {
|
|
59
|
+
const label = protocolLabel(context.protocol);
|
|
60
|
+
if (context.timeout.aborted) {
|
|
61
|
+
return new CustomImageError(`${label} 请求超时(${Math.round(context.timeoutMs / 1000)} 秒)`);
|
|
62
|
+
}
|
|
63
|
+
if (context.signal?.aborted === true)
|
|
64
|
+
return new CustomImageError(`${label} 请求已被取消`);
|
|
65
|
+
return new CustomImageError(`无法连接 ${label}:${error instanceof Error ? error.message : String(error)}`);
|
|
66
|
+
}
|
|
67
|
+
async function fetchOrThrow(url, init, context) {
|
|
68
|
+
try {
|
|
69
|
+
return await fetch(url, { ...init, signal: context.composed });
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw networkError(context, error);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** 读错误体:不同后端给的字段名差很远,能捞到一句人话就够。 */
|
|
76
|
+
async function errorMessageOf(response) {
|
|
77
|
+
const text = await response.text().catch(() => "");
|
|
78
|
+
if (text.trim() === "")
|
|
79
|
+
return `HTTP ${response.status} ${response.statusText}`;
|
|
80
|
+
try {
|
|
81
|
+
const parsed = JSON.parse(text);
|
|
82
|
+
const candidate = parsed?.error ?? parsed;
|
|
83
|
+
const message = typeof candidate?.message === "string"
|
|
84
|
+
? candidate.message
|
|
85
|
+
: typeof candidate?.error === "string"
|
|
86
|
+
? candidate.error
|
|
87
|
+
: typeof parsed?.detail === "string"
|
|
88
|
+
? JSON.stringify(parsed.detail)
|
|
89
|
+
: text.slice(0, 400);
|
|
90
|
+
return message;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return text.slice(0, 400);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
async function ensureOk(response, context, what) {
|
|
97
|
+
if (response.ok)
|
|
98
|
+
return;
|
|
99
|
+
const detail = await errorMessageOf(response);
|
|
100
|
+
throw new CustomImageError(`${protocolLabel(context.protocol)} ${what}失败(HTTP ${response.status}):${detail}`, response.status);
|
|
101
|
+
}
|
|
102
|
+
// ── 尺寸 ──────────────────────────────────────────────────────────────
|
|
103
|
+
/**
|
|
104
|
+
* 把尺寸写成 `宽x高`。
|
|
105
|
+
*
|
|
106
|
+
* 三种写法都认:`1024x1024` / `1024×1024` / `1K`(→1024) `2K`(→2048) `4K`(→4096)。
|
|
107
|
+
* 认不出来返回 undefined —— 各协议据此决定「不传尺寸、用服务端默认」,
|
|
108
|
+
* 而不是硬塞一个可能让请求 400 的值。
|
|
109
|
+
*/
|
|
110
|
+
export function parseSizeSpec(size) {
|
|
111
|
+
const text = size.trim().toLowerCase().replace("×", "x");
|
|
112
|
+
const explicit = /^(\d{2,5})\s*x\s*(\d{2,5})$/.exec(text);
|
|
113
|
+
if (explicit !== null) {
|
|
114
|
+
const width = Number.parseInt(explicit[1], 10);
|
|
115
|
+
const height = Number.parseInt(explicit[2], 10);
|
|
116
|
+
if (width > 0 && height > 0)
|
|
117
|
+
return { width, height };
|
|
118
|
+
}
|
|
119
|
+
const bucket = /^(\d)\s*k$/.exec(text);
|
|
120
|
+
if (bucket !== null) {
|
|
121
|
+
const side = Number.parseInt(bucket[1], 10) * 1024;
|
|
122
|
+
return { width: side, height: side };
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
/** 把 data URI / http URL 统一取成字节。 */
|
|
127
|
+
async function readBytes(source, context) {
|
|
128
|
+
const match = /^data:([^;,]+)?;base64,(.*)$/s.exec(source);
|
|
129
|
+
if (match !== null)
|
|
130
|
+
return Buffer.from(match[2], "base64");
|
|
131
|
+
if (/^https?:/i.test(source)) {
|
|
132
|
+
const response = await fetchOrThrow(source, { method: "GET" }, context);
|
|
133
|
+
await ensureOk(response, context, "下载参考图");
|
|
134
|
+
return Buffer.from(await response.arrayBuffer());
|
|
135
|
+
}
|
|
136
|
+
throw new CustomImageError("参考图既不是 data URI 也不是 http(s) 地址,无法发送给自定义后端");
|
|
137
|
+
}
|
|
138
|
+
function mimeOfBytes(bytes, fallback) {
|
|
139
|
+
if (bytes.length >= 8 && bytes[0] === 0x89 && bytes[1] === 0x50)
|
|
140
|
+
return "image/png";
|
|
141
|
+
if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8)
|
|
142
|
+
return "image/jpeg";
|
|
143
|
+
if (bytes.length >= 12 && bytes.toString("ascii", 8, 12) === "WEBP")
|
|
144
|
+
return "image/webp";
|
|
145
|
+
return fallback;
|
|
146
|
+
}
|
|
147
|
+
/** data URI / URL → Blob(multipart 上传要用)。 */
|
|
148
|
+
async function toBlob(source, context, name) {
|
|
149
|
+
const bytes = await readBytes(source, context);
|
|
150
|
+
const mime = mimeOfBytes(bytes, "image/png");
|
|
151
|
+
const ext = mime === "image/jpeg" ? "jpg" : mime === "image/webp" ? "webp" : "png";
|
|
152
|
+
const filename = /\.[a-z0-9]{2,4}$/i.test(name) ? name : `${name}.${ext}`;
|
|
153
|
+
return { blob: new Blob([new Uint8Array(bytes)], { type: mime }), filename };
|
|
154
|
+
}
|
|
155
|
+
/** data URI / URL → 纯 base64(A1111 的 `init_images` 要这个形态)。 */
|
|
156
|
+
async function toBase64(source, context) {
|
|
157
|
+
const bytes = await readBytes(source, context);
|
|
158
|
+
return bytes.toString("base64");
|
|
159
|
+
}
|
|
160
|
+
/** 结果字节里的 base64 可能带 data URI 前缀,剥掉再解码。 */
|
|
161
|
+
function decodeBase64Image(value) {
|
|
162
|
+
return Buffer.from(value.replace(/^data:[^;]+;base64,/, ""), "base64");
|
|
163
|
+
}
|
|
164
|
+
async function readOpenAiPayload(payload, context) {
|
|
165
|
+
const item = (payload?.data?.[0] ?? undefined);
|
|
166
|
+
if (item === undefined) {
|
|
167
|
+
throw new CustomImageError(`OpenAI 兼容接口的返回里没有图片:${JSON.stringify(payload).slice(0, 400)}`);
|
|
168
|
+
}
|
|
169
|
+
if (typeof item.b64_json === "string" && item.b64_json !== "") {
|
|
170
|
+
const bytes = decodeBase64Image(item.b64_json);
|
|
171
|
+
return { bytes, ext: sniffExt(bytes), usage: payload?.usage };
|
|
172
|
+
}
|
|
173
|
+
if (typeof item.url === "string" && item.url !== "") {
|
|
174
|
+
const download = await fetchOrThrow(item.url, { method: "GET" }, context);
|
|
175
|
+
await ensureOk(download, context, "下载生成结果");
|
|
176
|
+
const bytes = Buffer.from(await download.arrayBuffer());
|
|
177
|
+
return { bytes, ext: sniffExt(bytes), remoteUrl: item.url, usage: payload?.usage };
|
|
178
|
+
}
|
|
179
|
+
throw new CustomImageError(`OpenAI 兼容接口返回里既没有 url 也没有 b64_json:${JSON.stringify(item).slice(0, 400)}`);
|
|
180
|
+
}
|
|
181
|
+
async function generateOpenAi(request, context) {
|
|
182
|
+
const auth = authHeaders(request.apiKey);
|
|
183
|
+
const size = parseSizeSpec(request.size);
|
|
184
|
+
const base = request.baseUrl;
|
|
185
|
+
/**
|
|
186
|
+
* 带参考图时先走官方的 `images/edits`。
|
|
187
|
+
*
|
|
188
|
+
* ⚠️ 这条**只在端点真的不存在时**退回:404 / 405 说明对方是「纯 generations」的
|
|
189
|
+
* 兼容实现(很多自建网关就是这样),退回时把参考图塞进 generations 的 `image`
|
|
190
|
+
* 字段(火山方舟 / DashScope 那一系的写法)。用 400 当信号是不行的 ——
|
|
191
|
+
* 400 往往意味着模型不接受参考图,静默退回只会把一个真实错误变成一次「没带参考图
|
|
192
|
+
* 的生成」,用户拿到的是丢弃了设定的图。
|
|
193
|
+
*/
|
|
194
|
+
if (request.images.length > 0) {
|
|
195
|
+
const form = new FormData();
|
|
196
|
+
form.set("model", request.model);
|
|
197
|
+
form.set("prompt", request.prompt);
|
|
198
|
+
form.set("n", "1");
|
|
199
|
+
if (size !== undefined)
|
|
200
|
+
form.set("size", `${size.width}x${size.height}`);
|
|
201
|
+
for (const [index, image] of request.images.entries()) {
|
|
202
|
+
const { blob, filename } = await toBlob(image, context, `reference-${index + 1}.png`);
|
|
203
|
+
form.append(index === 0 ? "image" : "image[]", blob, filename);
|
|
204
|
+
}
|
|
205
|
+
const edits = await fetchOrThrow(joinUrl(base, "/images/edits"), { method: "POST", headers: auth, body: form }, context);
|
|
206
|
+
if (edits.status !== 404 && edits.status !== 405) {
|
|
207
|
+
await ensureOk(edits, context, "图生图(images/edits)");
|
|
208
|
+
const payload = (await edits.json().catch(() => undefined));
|
|
209
|
+
return readOpenAiPayload(payload, context);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const body = { model: request.model, prompt: request.prompt, n: 1 };
|
|
213
|
+
if (size !== undefined)
|
|
214
|
+
body.size = `${size.width}x${size.height}`;
|
|
215
|
+
// 不主动写 response_format:`gpt-image-1` 固定回 b64_json,写了反而可能被拒;
|
|
216
|
+
// 下面两种返回形态都处理了。
|
|
217
|
+
if (request.images.length === 1)
|
|
218
|
+
body.image = request.images[0];
|
|
219
|
+
else if (request.images.length > 1)
|
|
220
|
+
body.image = request.images;
|
|
221
|
+
const response = await fetchOrThrow(joinUrl(base, "/images/generations"), { method: "POST", headers: { ...auth, "Content-Type": "application/json" }, body: JSON.stringify(body) }, context);
|
|
222
|
+
await ensureOk(response, context, "生图");
|
|
223
|
+
const payload = (await response.json().catch(() => undefined));
|
|
224
|
+
return readOpenAiPayload(payload, context);
|
|
225
|
+
}
|
|
226
|
+
// ── Stable Diffusion WebUI(A1111)协议 ────────────────────────────────
|
|
227
|
+
async function generateSdWebui(request, context) {
|
|
228
|
+
const size = parseSizeSpec(request.size) ?? { width: 512, height: 512 };
|
|
229
|
+
const body = {
|
|
230
|
+
prompt: request.prompt,
|
|
231
|
+
negative_prompt: request.negativePrompt,
|
|
232
|
+
width: size.width,
|
|
233
|
+
height: size.height,
|
|
234
|
+
steps: request.steps,
|
|
235
|
+
cfg_scale: request.cfgScale,
|
|
236
|
+
sampler_name: request.sampler,
|
|
237
|
+
// A1111 的约定:-1 = 每次随机。
|
|
238
|
+
seed: request.seed < 0 ? -1 : request.seed,
|
|
239
|
+
batch_size: 1,
|
|
240
|
+
n_iter: 1,
|
|
241
|
+
save_images: false
|
|
242
|
+
};
|
|
243
|
+
let path = "/sdapi/v1/txt2img";
|
|
244
|
+
if (request.images.length > 0) {
|
|
245
|
+
path = "/sdapi/v1/img2img";
|
|
246
|
+
body.init_images = await Promise.all(request.images.map((image) => toBase64(image, context)));
|
|
247
|
+
body.denoising_strength = request.denoising;
|
|
248
|
+
}
|
|
249
|
+
const response = await fetchOrThrow(joinUrl(request.baseUrl, path), {
|
|
250
|
+
method: "POST",
|
|
251
|
+
headers: { ...authHeaders(request.apiKey), "Content-Type": "application/json" },
|
|
252
|
+
body: JSON.stringify(body)
|
|
253
|
+
}, context);
|
|
254
|
+
if (!response.ok) {
|
|
255
|
+
const detail = await errorMessageOf(response);
|
|
256
|
+
// 最常见的两个坑:没加 --api、或者 /sdapi 被禁用(`--nowebui` / 只开了 webui 端口)。
|
|
257
|
+
const hint = response.status === 404
|
|
258
|
+
? "(确认 WebUI 是用 `--api` 启动的,且地址是 API 端口)"
|
|
259
|
+
: "";
|
|
260
|
+
throw new CustomImageError(`${protocolLabel("sdwebui")} 生图失败(HTTP ${response.status}):${detail}${hint}`, response.status);
|
|
261
|
+
}
|
|
262
|
+
const payload = (await response.json().catch(() => undefined));
|
|
263
|
+
const first = payload?.images?.[0];
|
|
264
|
+
if (typeof first !== "string" || first === "") {
|
|
265
|
+
throw new CustomImageError(`WebUI 返回里没有图片:${JSON.stringify(payload).slice(0, 400)}`);
|
|
266
|
+
}
|
|
267
|
+
const bytes = decodeBase64Image(first);
|
|
268
|
+
// `info` 是一串 JSON 文本,里面是本次实际用的参数(种子、模型),排错时非常有用。
|
|
269
|
+
let usage;
|
|
270
|
+
if (typeof payload?.info === "string") {
|
|
271
|
+
try {
|
|
272
|
+
usage = JSON.parse(payload.info);
|
|
273
|
+
}
|
|
274
|
+
catch {
|
|
275
|
+
usage = payload.info.slice(0, 400);
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return { bytes, ext: sniffExt(bytes), usage };
|
|
279
|
+
}
|
|
280
|
+
// ── ComfyUI 协议 ───────────────────────────────────────────────────────
|
|
281
|
+
/** 占位符 → 值。数值类会**按数字写进 JSON**(写成字符串 ComfyUI 的 int 输入会报错)。 */
|
|
282
|
+
function workflowValues(request, seed, imageNames) {
|
|
283
|
+
const size = parseSizeSpec(request.size) ?? { width: 1024, height: 1024 };
|
|
284
|
+
const values = {
|
|
285
|
+
prompt: request.prompt,
|
|
286
|
+
negative_prompt: request.negativePrompt,
|
|
287
|
+
width: size.width,
|
|
288
|
+
height: size.height,
|
|
289
|
+
seed,
|
|
290
|
+
steps: request.steps,
|
|
291
|
+
cfg: request.cfgScale,
|
|
292
|
+
sampler: request.sampler,
|
|
293
|
+
denoising: request.denoising,
|
|
294
|
+
model: request.model,
|
|
295
|
+
batch: 1
|
|
296
|
+
};
|
|
297
|
+
if (imageNames.length > 0)
|
|
298
|
+
values.image = imageNames[0];
|
|
299
|
+
imageNames.forEach((name, index) => {
|
|
300
|
+
values[`image${index + 1}`] = name;
|
|
301
|
+
});
|
|
302
|
+
return values;
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* 按 **JSON 树**替换占位符,而不是在 JSON 文本上做字符串替换。
|
|
306
|
+
*
|
|
307
|
+
* 文本替换的坑很实在:提示词里带一个引号就能把整份工作流变成非法 JSON,
|
|
308
|
+
* 而 `"{{width}}"` 这种写在引号里的占位符会变成字符串 —— ComfyUI 的
|
|
309
|
+
* `EmptyLatentImage.width` 是 int,收到 `"1024"` 直接报 type 错误。
|
|
310
|
+
* 走树替换时:整个字符串恰好等于一个占位符 → 取原始类型(数字就是数字);
|
|
311
|
+
* 嵌在字符串中间 → 取文本形态。
|
|
312
|
+
*/
|
|
313
|
+
function substituteWorkflow(node, values, used) {
|
|
314
|
+
if (typeof node === "string") {
|
|
315
|
+
const exact = /^\{\{(\w+)\}\}$/.exec(node);
|
|
316
|
+
if (exact !== null && Object.prototype.hasOwnProperty.call(values, exact[1])) {
|
|
317
|
+
used.add(exact[1]);
|
|
318
|
+
return values[exact[1]];
|
|
319
|
+
}
|
|
320
|
+
return node.replace(/\{\{(\w+)\}\}/g, (whole, key) => {
|
|
321
|
+
if (!Object.prototype.hasOwnProperty.call(values, key))
|
|
322
|
+
return whole;
|
|
323
|
+
used.add(key);
|
|
324
|
+
return String(values[key]);
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
if (Array.isArray(node))
|
|
328
|
+
return node.map((item) => substituteWorkflow(item, values, used));
|
|
329
|
+
if (node !== null && typeof node === "object") {
|
|
330
|
+
const out = {};
|
|
331
|
+
for (const [key, value] of Object.entries(node)) {
|
|
332
|
+
out[key] = substituteWorkflow(value, values, used);
|
|
333
|
+
}
|
|
334
|
+
return out;
|
|
335
|
+
}
|
|
336
|
+
return node;
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* 没写 `{{image}}` 时的兜底:直接把第一个 `LoadImage` 节点的文件名换掉。
|
|
340
|
+
*
|
|
341
|
+
* 用户从 ComfyUI 界面「导出(API)」拿到的默认工作流里,加载图片的节点就叫
|
|
342
|
+
* `LoadImage`、输入名就叫 `image` —— 这是 ComfyUI 自己的约定,不会变。
|
|
343
|
+
*/
|
|
344
|
+
function patchLoadImage(node, name) {
|
|
345
|
+
if (Array.isArray(node))
|
|
346
|
+
return node.some((item) => patchLoadImage(item, name));
|
|
347
|
+
if (node === null || typeof node !== "object")
|
|
348
|
+
return false;
|
|
349
|
+
const record = node;
|
|
350
|
+
let touched = false;
|
|
351
|
+
if (record.class_type === "LoadImage" && record.inputs !== null && typeof record.inputs === "object") {
|
|
352
|
+
record.inputs.image = name;
|
|
353
|
+
touched = true;
|
|
354
|
+
}
|
|
355
|
+
for (const value of Object.values(record)) {
|
|
356
|
+
if (patchLoadImage(value, name))
|
|
357
|
+
touched = true;
|
|
358
|
+
}
|
|
359
|
+
return touched;
|
|
360
|
+
}
|
|
361
|
+
function comfyOutputImages(outputs) {
|
|
362
|
+
const found = [];
|
|
363
|
+
if (outputs === null || typeof outputs !== "object")
|
|
364
|
+
return found;
|
|
365
|
+
for (const node of Object.values(outputs)) {
|
|
366
|
+
const images = node?.images;
|
|
367
|
+
if (!Array.isArray(images))
|
|
368
|
+
continue;
|
|
369
|
+
for (const image of images) {
|
|
370
|
+
if (typeof image?.filename === "string") {
|
|
371
|
+
found.push({
|
|
372
|
+
filename: image.filename,
|
|
373
|
+
subfolder: typeof image.subfolder === "string" ? image.subfolder : "",
|
|
374
|
+
type: typeof image.type === "string" ? image.type : "output"
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return found;
|
|
380
|
+
}
|
|
381
|
+
/** 从 `/history` 的 status 里捞执行错误(节点名 + 异常),这是排错的唯一线索。 */
|
|
382
|
+
function comfyStatusError(status) {
|
|
383
|
+
if (status === null || typeof status !== "object")
|
|
384
|
+
return undefined;
|
|
385
|
+
const messages = status.messages;
|
|
386
|
+
if (Array.isArray(messages)) {
|
|
387
|
+
for (const message of messages) {
|
|
388
|
+
if (Array.isArray(message) && message[0] === "execution_error" && typeof message[1]?.exception_message === "string") {
|
|
389
|
+
const node = message[1]?.node_type ?? message[1]?.node_id ?? "未知节点";
|
|
390
|
+
return `${node}:${message[1].exception_message}`;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
if (typeof status.status_str === "string" && status.status_str === "error")
|
|
395
|
+
return "执行失败(工作流里某个节点报错)";
|
|
396
|
+
return undefined;
|
|
397
|
+
}
|
|
398
|
+
async function generateComfyUi(request, context) {
|
|
399
|
+
if (request.workflow.trim() === "") {
|
|
400
|
+
throw new CustomImageError("ComfyUI 需要一个 API 格式的工作流 JSON:在 ComfyUI 里点「导出(API)」,把那份 JSON 整段粘进设置页");
|
|
401
|
+
}
|
|
402
|
+
let parsed;
|
|
403
|
+
try {
|
|
404
|
+
parsed = JSON.parse(request.workflow);
|
|
405
|
+
}
|
|
406
|
+
catch (error) {
|
|
407
|
+
throw new CustomImageError(`工作流 JSON 解析失败:${error instanceof Error ? error.message : String(error)}`);
|
|
408
|
+
}
|
|
409
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
410
|
+
throw new CustomImageError("工作流 JSON 必须是一个对象(API 格式),不是数组或裸值");
|
|
411
|
+
}
|
|
412
|
+
const auth = authHeaders(request.apiKey);
|
|
413
|
+
const base = request.baseUrl;
|
|
414
|
+
const seed = request.seed < 0 ? Math.floor(Math.random() * 2147483647) : request.seed;
|
|
415
|
+
// 参考图先传上去,拿到文件名再替换进工作流。
|
|
416
|
+
const imageNames = [];
|
|
417
|
+
for (const [index, image] of request.images.entries()) {
|
|
418
|
+
const { blob, filename } = await toBlob(image, context, `gmm-ref-${Date.now()}-${index + 1}.png`);
|
|
419
|
+
const form = new FormData();
|
|
420
|
+
form.set("image", blob, filename);
|
|
421
|
+
form.set("overwrite", "true");
|
|
422
|
+
const uploaded = await fetchOrThrow(joinUrl(base, "/upload/image"), { method: "POST", headers: auth, body: form }, context);
|
|
423
|
+
await ensureOk(uploaded, context, "上传参考图");
|
|
424
|
+
const info = (await uploaded.json().catch(() => undefined));
|
|
425
|
+
const name = typeof info?.name === "string" && info.name !== "" ? info.name : filename;
|
|
426
|
+
const subfolder = typeof info?.subfolder === "string" ? info.subfolder : "";
|
|
427
|
+
imageNames.push(subfolder === "" ? name : `${subfolder}/${name}`);
|
|
428
|
+
}
|
|
429
|
+
const used = new Set();
|
|
430
|
+
const workflow = substituteWorkflow(parsed, workflowValues(request, seed, imageNames), used);
|
|
431
|
+
if (imageNames.length > 0 && !used.has("image")) {
|
|
432
|
+
patchLoadImage(workflow, imageNames[0]);
|
|
433
|
+
}
|
|
434
|
+
const clientId = `gmm-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e6).toString(36)}`;
|
|
435
|
+
const queued = await fetchOrThrow(joinUrl(base, "/prompt"), {
|
|
436
|
+
method: "POST",
|
|
437
|
+
headers: { ...auth, "Content-Type": "application/json" },
|
|
438
|
+
body: JSON.stringify({ prompt: workflow, client_id: clientId })
|
|
439
|
+
}, context);
|
|
440
|
+
if (!queued.ok) {
|
|
441
|
+
const detail = await errorMessageOf(queued);
|
|
442
|
+
throw new CustomImageError(`${protocolLabel("comfyui")} 提交工作流失败(HTTP ${queued.status}):${detail}` +
|
|
443
|
+
(queued.status === 400 ? "(多半是工作流里有节点参数不合法,先在 ComfyUI 里跑通再导出 API 格式)" : ""), queued.status);
|
|
444
|
+
}
|
|
445
|
+
const queuedPayload = (await queued.json().catch(() => undefined));
|
|
446
|
+
const promptId = queuedPayload?.prompt_id;
|
|
447
|
+
if (typeof promptId !== "string" || promptId === "") {
|
|
448
|
+
throw new CustomImageError(`ComfyUI 没有返回 prompt_id:${JSON.stringify(queuedPayload).slice(0, 400)}`);
|
|
449
|
+
}
|
|
450
|
+
const nodeErrors = queuedPayload?.node_errors;
|
|
451
|
+
if (nodeErrors !== null && typeof nodeErrors === "object" && Object.keys(nodeErrors).length > 0) {
|
|
452
|
+
throw new CustomImageError(`工作流校验不通过:${JSON.stringify(nodeErrors).slice(0, 600)}`);
|
|
453
|
+
}
|
|
454
|
+
// 轮询历史。本地跑一张图几十秒起步,所以间隔取 1 秒、整体受 timeout 控制。
|
|
455
|
+
let entry;
|
|
456
|
+
for (;;) {
|
|
457
|
+
if (context.composed.aborted)
|
|
458
|
+
throw networkError(context, new Error("aborted"));
|
|
459
|
+
await sleep(1000, context);
|
|
460
|
+
const history = await fetchOrThrow(joinUrl(base, `/history/${encodeURIComponent(promptId)}`), { method: "GET", headers: auth }, context);
|
|
461
|
+
await ensureOk(history, context, "查询任务状态");
|
|
462
|
+
const payload = (await history.json().catch(() => undefined));
|
|
463
|
+
const candidate = payload?.[promptId];
|
|
464
|
+
if (candidate !== undefined) {
|
|
465
|
+
// 有的实现是「先出现条目、再补 outputs」,所以还要等到有产出或明确报错。
|
|
466
|
+
const failure = comfyStatusError(candidate?.status);
|
|
467
|
+
if (failure !== undefined)
|
|
468
|
+
throw new CustomImageError(`ComfyUI 执行失败:${failure}`);
|
|
469
|
+
const images = comfyOutputImages(candidate?.outputs);
|
|
470
|
+
if (images.length > 0) {
|
|
471
|
+
entry = { ...candidate, __images: images };
|
|
472
|
+
break;
|
|
473
|
+
}
|
|
474
|
+
const completed = candidate?.status?.completed === true || candidate?.status?.status_str === "success";
|
|
475
|
+
if (completed)
|
|
476
|
+
throw new CustomImageError("ComfyUI 执行完成,但没有任何图片输出(工作流最后接的不是 SaveImage / PreviewImage?)");
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
const first = entry.__images[0];
|
|
480
|
+
const query = new URLSearchParams({ filename: first.filename, subfolder: first.subfolder, type: first.type });
|
|
481
|
+
const view = await fetchOrThrow(joinUrl(base, `/view?${query.toString()}`), { method: "GET", headers: auth }, context);
|
|
482
|
+
await ensureOk(view, context, "下载生成结果");
|
|
483
|
+
const bytes = Buffer.from(await view.arrayBuffer());
|
|
484
|
+
return { bytes, ext: sniffExt(bytes), remoteUrl: joinUrl(base, `/view?${query.toString()}`), usage: { seed, promptId, filename: first.filename } };
|
|
485
|
+
}
|
|
486
|
+
function sleep(ms, context) {
|
|
487
|
+
return new Promise((resolve, reject) => {
|
|
488
|
+
const timer = setTimeout(() => {
|
|
489
|
+
context.composed.removeEventListener("abort", onAbort);
|
|
490
|
+
resolve();
|
|
491
|
+
}, ms);
|
|
492
|
+
function onAbort() {
|
|
493
|
+
clearTimeout(timer);
|
|
494
|
+
reject(networkError(context, new Error("aborted")));
|
|
495
|
+
}
|
|
496
|
+
if (context.composed.aborted) {
|
|
497
|
+
onAbort();
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
context.composed.addEventListener("abort", onAbort, { once: true });
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
// ── 入口 ───────────────────────────────────────────────────────────────
|
|
504
|
+
/** 调一次自定义后端。`images` 为空时是文生图,非空时按各协议的做法带上参考图。 */
|
|
505
|
+
export async function generateCustomImage(request, signal) {
|
|
506
|
+
if (request.baseUrl.trim() === "") {
|
|
507
|
+
throw new CustomImageError("尚未配置自定义生图服务的地址(设置 → 游戏素材大师 → 自定义生图模型)");
|
|
508
|
+
}
|
|
509
|
+
if (request.prompt.trim() === "" && request.protocol !== "comfyui") {
|
|
510
|
+
throw new CustomImageError("提示词为空");
|
|
511
|
+
}
|
|
512
|
+
const context = makeSignalContext(request.protocol, request.timeoutMs, signal);
|
|
513
|
+
if (request.protocol === "openai")
|
|
514
|
+
return generateOpenAi(request, context);
|
|
515
|
+
if (request.protocol === "sdwebui")
|
|
516
|
+
return generateSdWebui(request, context);
|
|
517
|
+
return generateComfyUi(request, context);
|
|
518
|
+
}
|
package/lib/imagegen.js
CHANGED
|
@@ -16,7 +16,7 @@ import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
|
|
|
16
16
|
import { basename, join, resolve, sep } from "node:path";
|
|
17
17
|
import { randomUUID } from "node:crypto";
|
|
18
18
|
import { imageJobsRoot, loadConfig } from "./config.js";
|
|
19
|
-
import {
|
|
19
|
+
import { generateImageWithProvider, imageModelOf, imageSizeOf, imageWatermarkOf, assertImageProviderReady, isCustomProvider } from "./imageprovider.js";
|
|
20
20
|
import { decodeToRgba, mimeOf, toDataUri } from "./media.js";
|
|
21
21
|
import { keyGreen } from "./chroma.js";
|
|
22
22
|
import { encodePng } from "./png.js";
|
|
@@ -56,10 +56,10 @@ export async function createImageJob(name) {
|
|
|
56
56
|
suffix: "",
|
|
57
57
|
refs: [],
|
|
58
58
|
settings: {
|
|
59
|
-
model: config
|
|
60
|
-
size: config
|
|
59
|
+
model: imageModelOf(config),
|
|
60
|
+
size: imageSizeOf(config),
|
|
61
61
|
count: 1,
|
|
62
|
-
watermark: config
|
|
62
|
+
watermark: imageWatermarkOf(config)
|
|
63
63
|
},
|
|
64
64
|
keying: {
|
|
65
65
|
enabled: false,
|
|
@@ -209,25 +209,25 @@ export async function generateImageItem(jobId, index) {
|
|
|
209
209
|
const prompt = buildPrompt(job);
|
|
210
210
|
if (prompt === "")
|
|
211
211
|
throw new Error("提示词为空,请先填写");
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
212
|
+
assertImageProviderReady(config);
|
|
213
|
+
// 生图模型同样是全局设置(设置 → 游戏素材大师 → 生图后端),任务只跟随、不覆盖。
|
|
214
|
+
job.settings.model = imageModelOf(config);
|
|
215
|
+
// 自定义后端的尺寸是全局参数(任务上的 size 是火山方舟时代的遗留),跟着配置走。
|
|
216
|
+
if (isCustomProvider(config))
|
|
217
|
+
job.settings.size = config.customSize;
|
|
216
218
|
const item = job.items[index] ?? { index, status: "empty", source: "generated" };
|
|
217
219
|
job.items[index] = { ...item, status: "running", error: undefined };
|
|
218
220
|
appendJobLog(job.log, "info", `开始生成第 ${index + 1} 张`);
|
|
219
221
|
await writeImageJob(job);
|
|
220
222
|
try {
|
|
221
223
|
const refs = await Promise.all(job.refs.map((ref) => toDataUri(imageAssetPath(jobId, ref.file), mimeOf(ref.file))));
|
|
222
|
-
const result = await
|
|
223
|
-
baseUrl: config.arkBaseUrl,
|
|
224
|
-
apiKey: config.arkApiKey,
|
|
225
|
-
model: config.arkModel,
|
|
224
|
+
const result = await generateImageWithProvider({
|
|
226
225
|
prompt,
|
|
227
226
|
images: refs,
|
|
228
|
-
size: job.settings.size || config
|
|
229
|
-
|
|
230
|
-
|
|
227
|
+
size: job.settings.size || imageSizeOf(config),
|
|
228
|
+
// 水印是火山方舟特有的参数(自定义后端忽略它)。任务上那份是旧版本留下的
|
|
229
|
+
// 覆盖位,仍然尊重;与全局设置取或,两种写法都不会让水印「突然消失」。
|
|
230
|
+
watermark: imageWatermarkOf(config) || job.settings.watermark === true
|
|
231
231
|
});
|
|
232
232
|
const relative = `out/img-${String(index).padStart(2, "0")}.${result.ext}`;
|
|
233
233
|
await writeFile(imageAssetPath(jobId, relative), result.bytes);
|