dsh-mo-image 0.5.1 → 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/CHANGELOG.md +18 -0
- package/README.md +468 -409
- package/icon.png +0 -0
- package/lib/adapter-kit.js +670 -0
- package/lib/adapters/async.js +578 -0
- package/lib/adapters/cn.js +108 -0
- package/lib/adapters/openai.js +252 -0
- package/lib/adapters.js +1112 -454
- package/lib/client.js +1006 -150
- package/lib/comfy-workflow.js +528 -0
- package/lib/config-store.js +692 -0
- package/lib/image-execution.js +835 -0
- package/lib/image-jobs.js +333 -0
- package/lib/image-queue.js +195 -0
- package/lib/image-service.js +226 -0
- package/lib/image-worker.js +195 -0
- package/lib/index.js +517 -739
- package/lib/localized-error.js +1 -0
- package/lib/png-scale.js +103 -28
- package/lib/prompt-profiles.js +160 -68
- package/lib/request-auth.js +143 -0
- package/lib/retry.js +162 -0
- package/lib/settings-memory.js +33 -0
- package/lib/status.js +187 -0
- package/locale/messages.csv +49 -3
- package/package.json +3 -1
- package/skills/mo-image-editing/SKILL.md +34 -72
- package/skills/mo-image-generation/SKILL.md +59 -152
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 异步队列型协议:BFL / fal.ai / Replicate / 魔搭 ModelScope。
|
|
3
|
+
*
|
|
4
|
+
* 这些平台的共同点是「提交 → 轮询 → 拿一个会过期的 URL」,差异全部收敛到
|
|
5
|
+
* async 描述符:build / submitPath / pollUrl / pollHeaders / statusOf / resolve。
|
|
6
|
+
* 拿到 URL 必须立刻下载,不能交给上层。
|
|
7
|
+
*/
|
|
8
|
+
import { request } from '../net.js';
|
|
9
|
+
import {
|
|
10
|
+
baseUrlOf, headersFor, authHeaders, readJsonResponse, dataUrlOf, nearestAspect, resolutionFor
|
|
11
|
+
} from '../adapter-kit.js';
|
|
12
|
+
|
|
13
|
+
function hostOf(provider) {
|
|
14
|
+
return String((provider && provider.baseUrl) || '').replace(/^https?:\/\//i, '').split('/')[0].toLowerCase();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/* ------------------------------------------------------- 结果地址的凭据范围 */
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 结果地址不一定是「自己家」的接口:队列服务常常直接给一个对象存储/CDN 的
|
|
21
|
+
* 预签名地址。预签名本来就带授权,不需要我们的 Key;反过来,把 Key 发给
|
|
22
|
+
* 一个没见过的主机就是凭据泄漏。所以默认只对同源带凭据,跨源必须显式声明。
|
|
23
|
+
*/
|
|
24
|
+
function originOf(url) {
|
|
25
|
+
try {
|
|
26
|
+
return new URL(String(url)).origin;
|
|
27
|
+
} catch (_error) {
|
|
28
|
+
return '';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** 同源比较的是 origin(协议 + 主机 + 端口):http→https 或换端口都算换了目标。 */
|
|
33
|
+
function isSameOrigin(url, provider) {
|
|
34
|
+
const origin = originOf(url);
|
|
35
|
+
if (!origin) return false;
|
|
36
|
+
const base = originOf(baseUrlOf(provider));
|
|
37
|
+
return !!base && origin === base;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 描述符可以用 resultAuthOrigins 声明确实需要凭据的跨源结果域名;
|
|
42
|
+
* 元素可以是完整 origin(https://api.example.com),也可以是 hostname。
|
|
43
|
+
*/
|
|
44
|
+
function isDeclaredResultOrigin(url, origins) {
|
|
45
|
+
const list = Array.isArray(origins) ? origins : [];
|
|
46
|
+
if (!list.length) return false;
|
|
47
|
+
let parsed;
|
|
48
|
+
try {
|
|
49
|
+
parsed = new URL(String(url));
|
|
50
|
+
} catch (_error) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
return list.some((entry) => {
|
|
54
|
+
const text = String(entry || '').trim();
|
|
55
|
+
if (!text) return false;
|
|
56
|
+
if (/^https?:\/\//i.test(text)) return text.replace(/\/+$/, '') === parsed.origin;
|
|
57
|
+
return text.toLowerCase() === parsed.hostname.toLowerCase();
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** 下载/解析结果地址时该带什么头:同源或已声明才带该适配器的鉴权头,否则裸请求。 */
|
|
62
|
+
function resultHeaders(provider, url, authHeader, origins) {
|
|
63
|
+
if (!isSameOrigin(url, provider) && !isDeclaredResultOrigin(url, origins)) return {};
|
|
64
|
+
return authHeaders(provider, { authHeader: authHeader });
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function promptWithNegative(input) {
|
|
68
|
+
const prompt = String((input && input.prompt) || '');
|
|
69
|
+
const negative = String((input && input.negativePrompt) || '').trim();
|
|
70
|
+
return negative ? prompt + '\n\nAvoid: ' + negative : prompt;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function imagesOf(input) {
|
|
74
|
+
return (Array.isArray(input && input.images) ? input.images : [])
|
|
75
|
+
.filter((image) => image && image.buffer && image.contentType);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sizeOf(input) {
|
|
79
|
+
const fitted = input && input.fitted;
|
|
80
|
+
if (!fitted || fitted.omit || fitted.size === 'none' || fitted.size === 'auto') return null;
|
|
81
|
+
if (!fitted.width || !fitted.height) return null;
|
|
82
|
+
return { width: fitted.width, height: fitted.height, aspect: fitted.aspect || '', tier: fitted.tier || '' };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/* ------------------------------------------------------------------ BFL */
|
|
86
|
+
|
|
87
|
+
const BFL_SUCCESS = new Set(['READY']);
|
|
88
|
+
const BFL_FAILURE = new Set([
|
|
89
|
+
'ERROR', 'REQUEST MODERATED', 'CONTENT MODERATED', 'NO CARD GENERATED', 'TASK NOT FOUND'
|
|
90
|
+
]);
|
|
91
|
+
|
|
92
|
+
function bflBuild(input) {
|
|
93
|
+
const model = String(input.model || '');
|
|
94
|
+
const images = imagesOf(input);
|
|
95
|
+
const body = { prompt: promptWithNegative(input) };
|
|
96
|
+
const size = sizeOf(input) || { width: 1024, height: 1024 };
|
|
97
|
+
|
|
98
|
+
// FLUX 3 只认 aspect_ratio / resolution / images,未知字段直接 422。
|
|
99
|
+
if (/^flux-3/i.test(model)) {
|
|
100
|
+
body.aspect_ratio = size.aspect || nearestAspect(size.width, size.height);
|
|
101
|
+
if (size.tier) body.resolution = String(size.tier);
|
|
102
|
+
if (images.length) body.images = images.slice(0, 10).map(dataUrlOf);
|
|
103
|
+
return body;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Kontext / Ultra 用 aspect_ratio,没有 width/height。
|
|
107
|
+
if (/kontext|ultra/i.test(model)) {
|
|
108
|
+
body.aspect_ratio = nearestAspect(size.width, size.height);
|
|
109
|
+
body.output_format = 'png';
|
|
110
|
+
if (images.length) {
|
|
111
|
+
body.input_image = dataUrlOf(images[0]);
|
|
112
|
+
for (let index = 1; index < images.length && index < 4; index++) {
|
|
113
|
+
body['input_image_' + (index + 1)] = dataUrlOf(images[index]);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return body;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
body.width = size.width;
|
|
120
|
+
body.height = size.height;
|
|
121
|
+
body.output_format = 'png';
|
|
122
|
+
if (input.seed !== undefined && input.seed !== null && input.seed !== '') body.seed = input.seed;
|
|
123
|
+
if (images.length) {
|
|
124
|
+
body.input_image = dataUrlOf(images[0]);
|
|
125
|
+
for (let index = 1; index < images.length && index < 8; index++) {
|
|
126
|
+
body['input_image_' + (index + 1)] = dataUrlOf(images[index]);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return body;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/* ------------------------------------------------------------------ fal */
|
|
133
|
+
|
|
134
|
+
function falModelPath(model) {
|
|
135
|
+
return '/' + String(model || '').trim().replace(/^\/+/, '');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function falBuild(input) {
|
|
139
|
+
const body = { prompt: promptWithNegative(input), num_images: 1, output_format: 'jpeg' };
|
|
140
|
+
const size = sizeOf(input);
|
|
141
|
+
if (size) body.image_size = { width: size.width, height: size.height };
|
|
142
|
+
const images = imagesOf(input);
|
|
143
|
+
// fal 的单图端点用 image_url、多图端点用 image_urls,混用会 422。
|
|
144
|
+
if (images.length === 1) body.image_url = dataUrlOf(images[0]);
|
|
145
|
+
else if (images.length > 1) body.image_urls = images.map(dataUrlOf);
|
|
146
|
+
return body;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/* -------------------------------------------------------------- Replicate */
|
|
150
|
+
|
|
151
|
+
const schemaCache = new Map();
|
|
152
|
+
/** 进行中的 schema 请求:同一模型的并发 build 只发一次,别让参考图和尺寸各查一遍。 */
|
|
153
|
+
const schemaInflight = new Map();
|
|
154
|
+
const SCHEMA_TTL = 10 * 60 * 1000;
|
|
155
|
+
|
|
156
|
+
/** 测试用:清掉模型 schema 缓存与进行中的请求占位。 */
|
|
157
|
+
export function resetAsyncSchemaCache() {
|
|
158
|
+
schemaCache.clear();
|
|
159
|
+
schemaInflight.clear();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function replicateName(model) {
|
|
163
|
+
return String(model || '').trim().replace(/^\/+/, '');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const SCHEMA_CACHE_LIMIT = 100;
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 凭据版本引用:换了 Key 之后能访问的模型可能不同(私有模型),所以凭据要参与缓存键;
|
|
170
|
+
* 但键会长期留在内存里,不能出现明文 Key。这里只留长度 + FNV-1a 哈希做版本引用。
|
|
171
|
+
*
|
|
172
|
+
* 这个函数在 adapters.js 里也有一份:本文件被 adapters.js import,反向 import 会成环,
|
|
173
|
+
* 而这段逻辑只有十来行,复制一份比制造循环依赖安全。
|
|
174
|
+
*/
|
|
175
|
+
function credentialRef(provider) {
|
|
176
|
+
const key = String((provider && provider.key) || '');
|
|
177
|
+
if (!key) return 'anon';
|
|
178
|
+
let hash = 0x811c9dc5;
|
|
179
|
+
for (let i = 0; i < key.length; i++) {
|
|
180
|
+
hash ^= key.charCodeAt(i);
|
|
181
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
182
|
+
}
|
|
183
|
+
return key.length + ':' + hash.toString(16);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** 读模型 Input schema;失败就返回 null,且不缓存失败(瞬时 503 不该让后面 10 分钟都退化)。 */
|
|
187
|
+
async function inputSchemaOf(provider, model, signal) {
|
|
188
|
+
const name = replicateName(model);
|
|
189
|
+
if (!name.includes('/')) return null;
|
|
190
|
+
const key = baseUrlOf(provider) + '|' + name + '|' + credentialRef(provider);
|
|
191
|
+
const cached = schemaCache.get(key);
|
|
192
|
+
if (cached && Date.now() - cached.at < SCHEMA_TTL) return cached.value;
|
|
193
|
+
const pending = schemaInflight.get(key);
|
|
194
|
+
if (pending) return pending;
|
|
195
|
+
const task = (async () => {
|
|
196
|
+
try {
|
|
197
|
+
const response = await request(baseUrlOf(provider) + '/models/' + name, {
|
|
198
|
+
headers: headersFor(provider, false), signal: signal
|
|
199
|
+
});
|
|
200
|
+
if (!response.ok) throw new Error('schema ' + response.status);
|
|
201
|
+
const payload = await readJsonResponse(response, 5 * 1024 * 1024);
|
|
202
|
+
const schema = payload
|
|
203
|
+
&& payload.latest_version
|
|
204
|
+
&& payload.latest_version.openapi_schema
|
|
205
|
+
&& payload.latest_version.openapi_schema.components
|
|
206
|
+
&& payload.latest_version.openapi_schema.components.schemas
|
|
207
|
+
&& payload.latest_version.openapi_schema.components.schemas.Input;
|
|
208
|
+
const properties = schema && schema.properties ? schema.properties : null;
|
|
209
|
+
if (!properties) return null;
|
|
210
|
+
if (schemaCache.size >= SCHEMA_CACHE_LIMIT) {
|
|
211
|
+
const oldest = schemaCache.keys().next().value;
|
|
212
|
+
if (oldest) schemaCache.delete(oldest);
|
|
213
|
+
}
|
|
214
|
+
schemaCache.set(key, { at: Date.now(), value: properties });
|
|
215
|
+
return properties;
|
|
216
|
+
} catch (_error) {
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
})();
|
|
220
|
+
// 失败同样经过 finally:占位必须清掉,下一次 build 才能重新请求(失败不缓存)。
|
|
221
|
+
let tracked;
|
|
222
|
+
tracked = task.finally(() => {
|
|
223
|
+
if (schemaInflight.get(key) === tracked) schemaInflight.delete(key);
|
|
224
|
+
});
|
|
225
|
+
schemaInflight.set(key, tracked);
|
|
226
|
+
return tracked;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const SCALAR_IMAGE_FIELDS = ['input_image', 'image', 'image_url'];
|
|
230
|
+
const ARRAY_IMAGE_FIELDS = ['images', 'image_urls'];
|
|
231
|
+
|
|
232
|
+
function isImageString(spec) {
|
|
233
|
+
return !!spec && (spec.type === 'string' || spec.format === 'uri');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 只认 schema 里声明过的图片字段,并且要求类型对得上。
|
|
238
|
+
* Replicate 对未知字段是静默忽略的,猜错会让参考图被丢掉还照常出图。
|
|
239
|
+
*/
|
|
240
|
+
function imageFieldOf(properties) {
|
|
241
|
+
if (!properties) return null;
|
|
242
|
+
for (const name of SCALAR_IMAGE_FIELDS) {
|
|
243
|
+
if (isImageString(properties[name])) return { name: name, array: false };
|
|
244
|
+
}
|
|
245
|
+
for (const name of ARRAY_IMAGE_FIELDS) {
|
|
246
|
+
const spec = properties[name];
|
|
247
|
+
if (!spec) continue;
|
|
248
|
+
if (spec.type === 'array') return { name: name, array: true };
|
|
249
|
+
if (isImageString(spec)) return { name: name, array: false };
|
|
250
|
+
}
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function sizeFieldsOf(properties, size) {
|
|
255
|
+
if (!properties || !size) return null;
|
|
256
|
+
const widthSpec = properties.width;
|
|
257
|
+
const heightSpec = properties.height;
|
|
258
|
+
const numeric = (spec) => !!spec && (spec.type === 'integer' || spec.type === 'number');
|
|
259
|
+
if (numeric(widthSpec) && numeric(heightSpec)) {
|
|
260
|
+
return { width: size.width, height: size.height };
|
|
261
|
+
}
|
|
262
|
+
if (properties.aspect_ratio) {
|
|
263
|
+
const allowed = Array.isArray(properties.aspect_ratio.enum) ? properties.aspect_ratio.enum : undefined;
|
|
264
|
+
return { aspect_ratio: nearestAspect(size.width, size.height, allowed) };
|
|
265
|
+
}
|
|
266
|
+
return null;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
async function replicateBuild(input, provider, signal) {
|
|
270
|
+
const images = imagesOf(input);
|
|
271
|
+
const properties = await inputSchemaOf(provider, input.model, signal);
|
|
272
|
+
const payload = { prompt: promptWithNegative(input) };
|
|
273
|
+
const notes = [];
|
|
274
|
+
|
|
275
|
+
if (images.length) {
|
|
276
|
+
const field = imageFieldOf(properties);
|
|
277
|
+
if (!field) {
|
|
278
|
+
notes.push('未识别模型输入字段,已省略参考图');
|
|
279
|
+
} else if (field.array) {
|
|
280
|
+
payload[field.name] = images.map(dataUrlOf);
|
|
281
|
+
} else {
|
|
282
|
+
payload[field.name] = dataUrlOf(images[0]);
|
|
283
|
+
if (images.length > 1) notes.push('该模型只接受一张参考图,已只用第一张');
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const size = sizeOf(input);
|
|
288
|
+
if (size) {
|
|
289
|
+
const sizeFields = sizeFieldsOf(properties, size);
|
|
290
|
+
if (sizeFields) Object.assign(payload, sizeFields);
|
|
291
|
+
else notes.push('未识别模型的尺寸字段,已省略尺寸;要锁定尺寸请开启严格模式');
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
return notes.length ? { body: { input: payload }, note: notes.join(';') } : { body: { input: payload } };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/* ------------------------------------------------------------ ModelScope */
|
|
298
|
+
|
|
299
|
+
const MODELSCOPE_SUCCESS = new Set(['SUCCEED', 'SUCCEEDED', 'SUCCESS']);
|
|
300
|
+
const MODELSCOPE_FAILURE = new Set(['FAILED', 'CANCELED', 'CANCELLED', 'ERROR']);
|
|
301
|
+
|
|
302
|
+
/** 魔搭的 OpenAI 兼容地址可能带 /v1,也可能只给站点根;统一到站点根再拼 /v1/...。 */
|
|
303
|
+
function modelscopeRoot(provider) {
|
|
304
|
+
return baseUrlOf(provider).replace(/\/v1$/i, '');
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* 魔搭的失败载荷可能是 message 字符串、errors:{message} 对象或 errors[] 数组,
|
|
309
|
+
* 逐层挖出第一句可读文本,别把 [object Object] 抛给用户。
|
|
310
|
+
*/
|
|
311
|
+
function firstMessage(value, depth = 0) {
|
|
312
|
+
if (depth > 4 || value === null || value === undefined) return '';
|
|
313
|
+
if (typeof value === 'string') return value.trim();
|
|
314
|
+
if (typeof value !== 'object') return '';
|
|
315
|
+
if (Array.isArray(value)) {
|
|
316
|
+
for (const item of value) {
|
|
317
|
+
const text = firstMessage(item, depth + 1);
|
|
318
|
+
if (text) return text;
|
|
319
|
+
}
|
|
320
|
+
return '';
|
|
321
|
+
}
|
|
322
|
+
for (const key of ['message', 'msg', 'detail', 'error', 'errors', 'reason', 'logs']) {
|
|
323
|
+
if (value[key] === undefined) continue;
|
|
324
|
+
const text = firstMessage(value[key], depth + 1);
|
|
325
|
+
if (text) return text;
|
|
326
|
+
}
|
|
327
|
+
return '';
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function modelscopeBuild(input) {
|
|
331
|
+
const body = {
|
|
332
|
+
model: String((input && input.model) || ''),
|
|
333
|
+
prompt: String((input && input.prompt) || '')
|
|
334
|
+
};
|
|
335
|
+
// 魔搭原生支持 negative_prompt:照字段发,不要像不支持的平台那样拼进 prompt。
|
|
336
|
+
const negative = String((input && input.negativePrompt) || '').trim();
|
|
337
|
+
if (negative) body.negative_prompt = negative;
|
|
338
|
+
const size = sizeOf(input);
|
|
339
|
+
if (size) body.size = size.width + 'x' + size.height;
|
|
340
|
+
const images = imagesOf(input);
|
|
341
|
+
if (images.length) {
|
|
342
|
+
// 图片字段是 image_url:一张发字符串、多张发数组;网关吃 data URI。
|
|
343
|
+
const urls = images.slice(0, 10).map(dataUrlOf);
|
|
344
|
+
body.image_url = urls.length === 1 ? urls[0] : urls;
|
|
345
|
+
}
|
|
346
|
+
return body;
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function modelscopePollUrl(submission, provider) {
|
|
350
|
+
const taskId = String((submission && submission.task_id) || '');
|
|
351
|
+
if (!taskId) {
|
|
352
|
+
throw new Error('ModelScope 提交后没有返回 task_id:'
|
|
353
|
+
+ JSON.stringify(submission || {}).slice(0, 200));
|
|
354
|
+
}
|
|
355
|
+
return modelscopeRoot(provider) + '/v1/tasks/' + encodeURIComponent(taskId);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/* ----------------------------------------------------------------- 描述符 */
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* fal 的 response_url 正常就是 queue.fal.run 上的接口地址(同源时不需要这里声明),
|
|
362
|
+
* 结果图则落在 v3.fal.media 这类 CDN 上——那是预签名地址,不需要 Key。
|
|
363
|
+
* 这里只列 fal 自家确实要凭据的跨源域名:把 baseUrl 配成 fal.run 时,
|
|
364
|
+
* response_url 仍会落在 queue.fal.run,丢掉 Key 反而会让结果读不出来。
|
|
365
|
+
*/
|
|
366
|
+
const FAL_RESULT_AUTH_ORIGINS = ['https://queue.fal.run'];
|
|
367
|
+
|
|
368
|
+
export const ASYNC_ADAPTERS = [
|
|
369
|
+
{
|
|
370
|
+
id: 'bfl',
|
|
371
|
+
label: 'Black Forest Labs (FLUX)',
|
|
372
|
+
match: (provider) => /(^|\.)bfl\.ai$/i.test(hostOf(provider)),
|
|
373
|
+
authHeader: 'x-key',
|
|
374
|
+
local: false,
|
|
375
|
+
endpoints: { generate: '/v1', edit: '/v1' },
|
|
376
|
+
transport: { generate: 'json', edit: 'json' },
|
|
377
|
+
editFields: [],
|
|
378
|
+
maxN: 1,
|
|
379
|
+
// FLUX.2 只吃 width/height;FLUX 3 换成「比例 + 小写档位」,两代 schema 不能共用。
|
|
380
|
+
size: { control: 'wh', style: 'width-height', minSide: 64, maxPixels: 4194304 },
|
|
381
|
+
sizeByModel: [
|
|
382
|
+
{
|
|
383
|
+
match: /flux-?3/i,
|
|
384
|
+
size: {
|
|
385
|
+
control: 'aspect', style: 'aspect', field: 'aspect_ratio',
|
|
386
|
+
aspects: ['21:9', '2:1', '16:9', '3:2', '7:5', '4:3', '5:4', '1:1', '4:5', '3:4', '5:7', '2:3', '9:16', '1:2', '9:21', 'auto'],
|
|
387
|
+
tiers: [
|
|
388
|
+
{ value: '768sq', pixels: 589824 }, { value: '1k', pixels: 1048576 },
|
|
389
|
+
{ value: '1.5k', pixels: 2359296 }, { value: '2k', pixels: 4194304 }, { value: '4k', pixels: 16777216 }
|
|
390
|
+
],
|
|
391
|
+
minSide: 256, maxSide: 6256, maxPixels: 16822272
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
],
|
|
395
|
+
async listModels() {
|
|
396
|
+
return [
|
|
397
|
+
'flux-2-pro', 'flux-2-max', 'flux-2-flex', 'flux-2-klein-9b', 'flux-2-klein-4b',
|
|
398
|
+
'flux-3-image', 'flux-3-image-klein', 'flux-kontext-pro', 'flux-kontext-max',
|
|
399
|
+
'flux-pro-1.1', 'flux-pro-1.1-ultra'
|
|
400
|
+
];
|
|
401
|
+
},
|
|
402
|
+
async: {
|
|
403
|
+
edit: true,
|
|
404
|
+
build: bflBuild,
|
|
405
|
+
submitPath: (input) => '/' + String(input.model || '').trim().replace(/^\/+/, ''),
|
|
406
|
+
pollUrl: (submission) => String(submission.polling_url || ''),
|
|
407
|
+
pollHeaders: (provider) => ({ 'x-key': String((provider && provider.key) || '') }),
|
|
408
|
+
statusOf: (payload) => {
|
|
409
|
+
const status = String((payload && payload.status) || '').toUpperCase();
|
|
410
|
+
if (BFL_SUCCESS.has(status)) return { state: 'success', status: status };
|
|
411
|
+
if (BFL_FAILURE.has(status)) {
|
|
412
|
+
return { state: 'failure', status: status, message: String((payload && payload.detail) || status) };
|
|
413
|
+
}
|
|
414
|
+
return { state: 'pending', status: status };
|
|
415
|
+
},
|
|
416
|
+
resolve: async (payload) => {
|
|
417
|
+
const sample = payload && payload.result && payload.result.sample;
|
|
418
|
+
if (!sample) throw new Error('BFL 任务完成了但没有返回图片');
|
|
419
|
+
return { url: sample };
|
|
420
|
+
},
|
|
421
|
+
intervalMs: 1000,
|
|
422
|
+
timeoutMs: 300000
|
|
423
|
+
}
|
|
424
|
+
},
|
|
425
|
+
{
|
|
426
|
+
id: 'fal',
|
|
427
|
+
label: 'fal.ai',
|
|
428
|
+
match: (provider) => /(^|\.)(queue\.)?fal(run)?\.(run|com)$/i.test(hostOf(provider)),
|
|
429
|
+
authHeader: 'fal-key',
|
|
430
|
+
local: false,
|
|
431
|
+
// 跨源结果地址的白名单;resolve() 与下载侧都按同一个声明判断能不能带 Key。
|
|
432
|
+
resultAuthOrigins: FAL_RESULT_AUTH_ORIGINS,
|
|
433
|
+
endpoints: { generate: '/', edit: '/' },
|
|
434
|
+
transport: { generate: 'json', edit: 'json' },
|
|
435
|
+
editFields: [],
|
|
436
|
+
maxN: 1,
|
|
437
|
+
async listModels(provider, signal) {
|
|
438
|
+
const response = await request('https://api.fal.ai/v1/models?category=text-to-image', {
|
|
439
|
+
headers: headersFor(provider, false), signal: signal
|
|
440
|
+
});
|
|
441
|
+
const payload = await readJsonResponse(response, 5 * 1024 * 1024);
|
|
442
|
+
return (payload && Array.isArray(payload.models) ? payload.models : [])
|
|
443
|
+
.map((item) => String((item && item.endpoint_id) || '').trim())
|
|
444
|
+
.filter(Boolean)
|
|
445
|
+
.slice(0, 200);
|
|
446
|
+
},
|
|
447
|
+
async: {
|
|
448
|
+
edit: true,
|
|
449
|
+
build: falBuild,
|
|
450
|
+
submitPath: (input) => falModelPath(input.model),
|
|
451
|
+
pollUrl: (submission) => String(submission.status_url || ''),
|
|
452
|
+
pollHeaders: (provider) => authHeaders(provider, { authHeader: 'fal-key' }),
|
|
453
|
+
statusOf: (payload) => {
|
|
454
|
+
const status = String((payload && payload.status) || '').toUpperCase();
|
|
455
|
+
if (status === 'COMPLETED') {
|
|
456
|
+
if (payload && payload.error) {
|
|
457
|
+
return { state: 'failure', status: status, message: String(payload.error) };
|
|
458
|
+
}
|
|
459
|
+
return { state: 'success', status: status };
|
|
460
|
+
}
|
|
461
|
+
return { state: 'pending', status: status };
|
|
462
|
+
},
|
|
463
|
+
resolve: async (payload, provider, signal, submission) => {
|
|
464
|
+
const url = (submission && submission.response_url) || (payload && payload.response_url);
|
|
465
|
+
if (!url) throw new Error('fal 任务完成了但没有 response_url');
|
|
466
|
+
// response_url 可能是同源的队列接口,也可能是第三方 CDN;后者不该收到 Key。
|
|
467
|
+
const headers = resultHeaders(provider, url, 'fal-key', FAL_RESULT_AUTH_ORIGINS);
|
|
468
|
+
const response = await request(url, { headers: headers, signal: signal });
|
|
469
|
+
const result = await readJsonResponse(response, 64 * 1024 * 1024);
|
|
470
|
+
const first = result && Array.isArray(result.images) ? result.images[0] : null;
|
|
471
|
+
if (!first || !first.url) throw new Error('fal 没有返回图片');
|
|
472
|
+
return { url: String(first.url) };
|
|
473
|
+
},
|
|
474
|
+
intervalMs: 1000,
|
|
475
|
+
timeoutMs: 300000
|
|
476
|
+
}
|
|
477
|
+
},
|
|
478
|
+
{
|
|
479
|
+
id: 'replicate',
|
|
480
|
+
label: 'Replicate',
|
|
481
|
+
match: (provider) => hostOf(provider) === 'api.replicate.com',
|
|
482
|
+
authHeader: 'bearer',
|
|
483
|
+
local: false,
|
|
484
|
+
endpoints: { generate: '/', edit: '/' },
|
|
485
|
+
transport: { generate: 'json', edit: 'json' },
|
|
486
|
+
editFields: [],
|
|
487
|
+
maxN: 1,
|
|
488
|
+
async listModels(provider, signal) {
|
|
489
|
+
const response = await request(baseUrlOf(provider) + '/models', {
|
|
490
|
+
headers: headersFor(provider, false), signal: signal
|
|
491
|
+
});
|
|
492
|
+
const payload = await readJsonResponse(response, 5 * 1024 * 1024);
|
|
493
|
+
return (payload && Array.isArray(payload.results) ? payload.results : [])
|
|
494
|
+
.map((item) => (item && item.owner && item.name ? item.owner + '/' + item.name : ''))
|
|
495
|
+
.filter(Boolean)
|
|
496
|
+
.slice(0, 200);
|
|
497
|
+
},
|
|
498
|
+
async: {
|
|
499
|
+
edit: true,
|
|
500
|
+
build: replicateBuild,
|
|
501
|
+
submitPath: (input) => '/models/' + replicateName(input.model) + '/predictions',
|
|
502
|
+
pollUrl: (submission) => String((submission && submission.urls && submission.urls.get) || ''),
|
|
503
|
+
pollHeaders: (provider) => headersFor(provider, false),
|
|
504
|
+
statusOf: (payload) => {
|
|
505
|
+
const status = String((payload && payload.status) || '').toLowerCase();
|
|
506
|
+
if (status === 'succeeded') return { state: 'success', status: status };
|
|
507
|
+
if (['failed', 'canceled', 'aborted'].includes(status)) {
|
|
508
|
+
return { state: 'failure', status: status, message: String((payload && payload.error) || status) };
|
|
509
|
+
}
|
|
510
|
+
return { state: 'pending', status: status };
|
|
511
|
+
},
|
|
512
|
+
resolve: async (payload) => {
|
|
513
|
+
const output = payload && payload.output;
|
|
514
|
+
const url = Array.isArray(output) ? output[0] : output;
|
|
515
|
+
if (!url) throw new Error('Replicate 任务完成了但没有返回图片');
|
|
516
|
+
return { url: String(url) };
|
|
517
|
+
},
|
|
518
|
+
intervalMs: 1000,
|
|
519
|
+
timeoutMs: 300000
|
|
520
|
+
}
|
|
521
|
+
},
|
|
522
|
+
{
|
|
523
|
+
id: 'modelscope',
|
|
524
|
+
label: '魔搭 ModelScope',
|
|
525
|
+
match: (provider) => /(^|\.)api-inference\.modelscope\.(cn|ai)$/i.test(hostOf(provider)),
|
|
526
|
+
authHeader: 'bearer',
|
|
527
|
+
local: false,
|
|
528
|
+
endpoints: { generate: '/v1/images/generations', edit: '/v1/images/generations' },
|
|
529
|
+
transport: { generate: 'json', edit: 'json' },
|
|
530
|
+
// 图片生成是任务制:不带这个头拿不到 task_id。
|
|
531
|
+
headers: { 'X-ModelScope-Async-Mode': 'true' },
|
|
532
|
+
editFields: [],
|
|
533
|
+
maxN: 1,
|
|
534
|
+
// 网关按每边 [64, 2048] 校验;再对齐到 16 的倍数,减少模型侧的取整与拒绝。
|
|
535
|
+
// 但不同模型族上限差很多(Qwen-Image 只到 1664),按模型覆盖。
|
|
536
|
+
size: {
|
|
537
|
+
style: 'string', field: 'size', multiple: 16, minSide: 64, maxSide: 2048,
|
|
538
|
+
default: '1024x1024', onUnsupported: 'nearest'
|
|
539
|
+
},
|
|
540
|
+
sizeByModel: [
|
|
541
|
+
{ match: /flux/i, size: { style: 'string', field: 'size', multiple: 16, minSide: 64, maxSide: 1024, default: '1024x1024' } },
|
|
542
|
+
{ match: /qwen-image/i, size: { style: 'string', field: 'size', multiple: 16, minSide: 64, maxSide: 1664, default: '1024x1024' } },
|
|
543
|
+
{ match: /z-image/i, size: { style: 'string', field: 'size', multiple: 16, minSide: 512, maxSide: 2048, default: '1024x1024' } }
|
|
544
|
+
],
|
|
545
|
+
async: {
|
|
546
|
+
edit: true,
|
|
547
|
+
build: modelscopeBuild,
|
|
548
|
+
submitPath: (input, provider) => modelscopeRoot(provider) + '/v1/images/generations',
|
|
549
|
+
pollUrl: modelscopePollUrl,
|
|
550
|
+
// 轮询要声明任务类型,图片生成是 image_generation(视频是另一套)。
|
|
551
|
+
pollHeaders: (provider) => Object.assign(
|
|
552
|
+
{ 'X-ModelScope-Task-Type': 'image_generation' },
|
|
553
|
+
authHeaders(provider, { authHeader: 'bearer' })
|
|
554
|
+
),
|
|
555
|
+
statusOf: (payload) => {
|
|
556
|
+
const status = String((payload && payload.task_status) || '').toUpperCase();
|
|
557
|
+
if (MODELSCOPE_SUCCESS.has(status)) return { state: 'success', status: status };
|
|
558
|
+
if (MODELSCOPE_FAILURE.has(status)) {
|
|
559
|
+
return { state: 'failure', status: status, message: firstMessage(payload) || status };
|
|
560
|
+
}
|
|
561
|
+
return { state: 'pending', status: status };
|
|
562
|
+
},
|
|
563
|
+
// 提交响应可能提前回 SUCCEED 但还没有图,所以结果只认轮询到的 output_images。
|
|
564
|
+
resolve: async (payload) => {
|
|
565
|
+
const images = Array.isArray(payload && payload.output_images) ? payload.output_images : [];
|
|
566
|
+
for (const item of images) {
|
|
567
|
+
const url = typeof item === 'string' ? item : (item && (item.url || item.image_url));
|
|
568
|
+
if (url) return { url: String(url) };
|
|
569
|
+
}
|
|
570
|
+
const first = payload && Array.isArray(payload.data) ? payload.data[0] : null;
|
|
571
|
+
if (first && first.url) return { url: String(first.url) };
|
|
572
|
+
throw new Error('ModelScope 任务完成了但没有返回图片');
|
|
573
|
+
},
|
|
574
|
+
intervalMs: 2000,
|
|
575
|
+
timeoutMs: 300000
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
];
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 国内厂商里协议形状和 OpenAI Images 不一致的两家。
|
|
3
|
+
*
|
|
4
|
+
* - 百炼 Qwen-Image:原生多模态同步接口,size 用 `*` 分隔,图片在 output.choices[].message.content[].image
|
|
5
|
+
* - 智谱 BigModel:形状像 OpenAI,但不接受 n / response_format,一次只回一张 url
|
|
6
|
+
*/
|
|
7
|
+
import { request } from '../net.js';
|
|
8
|
+
import { baseUrlOf, headersFor, readJsonResponse, fetchImageUrl, base64ToImage } from '../adapter-kit.js';
|
|
9
|
+
|
|
10
|
+
function promptOf(input) {
|
|
11
|
+
const prompt = String((input && input.prompt) || '');
|
|
12
|
+
const negative = String((input && input.negativePrompt) || '').trim();
|
|
13
|
+
return negative ? prompt + '\n\nAvoid: ' + negative : prompt;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function sizeOf(input) {
|
|
17
|
+
const fitted = input && input.fitted;
|
|
18
|
+
if (!fitted || fitted.omit || fitted.size === 'none' || fitted.size === 'auto') return '';
|
|
19
|
+
if (fitted.width && fitted.height) return fitted.width + 'x' + fitted.height;
|
|
20
|
+
return String(fitted.size || '');
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
async function urlToImage(url, signal) {
|
|
24
|
+
return fetchImageUrl(String(url), signal);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export const CN_ADAPTERS = [
|
|
28
|
+
{
|
|
29
|
+
id: 'dashscope-qwen-image',
|
|
30
|
+
label: '阿里云百炼 · Qwen-Image',
|
|
31
|
+
match: (provider, model) => /dashscope\.aliyuncs\.com/i.test(baseUrlOf(provider)) && /qwen-image/i.test(String(model || '')),
|
|
32
|
+
local: false,
|
|
33
|
+
endpoints: { generate: '/services/aigc/multimodal-generation/generation', edit: '' },
|
|
34
|
+
transport: { generate: 'json', edit: 'json' },
|
|
35
|
+
maxN: 6,
|
|
36
|
+
editFields: [],
|
|
37
|
+
// 百炼原生:size 用星号分隔,512²–2048²,比例 1:8–8:1。
|
|
38
|
+
size: {
|
|
39
|
+
control: 'wh', style: 'string', field: 'size', separator: '*', allowCustom: true,
|
|
40
|
+
minPixels: 262144, maxPixels: 4194304, hint: 'modelDecides'
|
|
41
|
+
},
|
|
42
|
+
async execute(kind, provider, input, signal) {
|
|
43
|
+
if (kind === 'edit') throw new Error('百炼 Qwen-Image 暂未支持参考图编辑;请换用支持编辑的模型。');
|
|
44
|
+
const fitted = input.fitted && !input.fitted.omit ? input.fitted : { width: 1024, height: 1024 };
|
|
45
|
+
const parameters = { n: 1, size: fitted.width + '*' + fitted.height };
|
|
46
|
+
if (input.negativePrompt) parameters.negative_prompt = String(input.negativePrompt);
|
|
47
|
+
const body = {
|
|
48
|
+
model: input.model,
|
|
49
|
+
input: { messages: [{ role: 'user', content: [{ text: promptOf(input) }] }] },
|
|
50
|
+
parameters: parameters
|
|
51
|
+
};
|
|
52
|
+
const response = await request(baseUrlOf(provider) + '/services/aigc/multimodal-generation/generation', {
|
|
53
|
+
method: 'POST',
|
|
54
|
+
headers: headersFor(provider, false, null, this),
|
|
55
|
+
body: JSON.stringify(body),
|
|
56
|
+
signal: signal
|
|
57
|
+
});
|
|
58
|
+
const payload = await readJsonResponse(response, 32 * 1024 * 1024);
|
|
59
|
+
const content = payload && payload.output && payload.output.choices
|
|
60
|
+
&& payload.output.choices[0] && payload.output.choices[0].message
|
|
61
|
+
&& payload.output.choices[0].message.content;
|
|
62
|
+
for (const item of Array.isArray(content) ? content : []) {
|
|
63
|
+
if (item && item.image) return urlToImage(item.image, signal);
|
|
64
|
+
}
|
|
65
|
+
throw new Error('百炼 Qwen-Image 没有返回图片');
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
id: 'zhipu',
|
|
70
|
+
label: '智谱 BigModel',
|
|
71
|
+
match: (provider) => /(^|\.)bigmodel\.cn$/i.test(String((provider && provider.baseUrl) || '').replace(/^https?:\/\//i, '').split('/')[0]),
|
|
72
|
+
local: false,
|
|
73
|
+
endpoints: { generate: '/images/generations', edit: '' },
|
|
74
|
+
transport: { generate: 'json', edit: 'json' },
|
|
75
|
+
maxN: 1,
|
|
76
|
+
editFields: [],
|
|
77
|
+
// glm-image 与 cogview 的限制不一样:前者 1024–2048 且 32 的倍数,后者 512–2048 且 16 的倍数。
|
|
78
|
+
size: { control: 'wh', style: 'string', field: 'size', allowCustom: true, multiple: 32, minSide: 1024, maxSide: 2048, maxPixels: 4194304 },
|
|
79
|
+
sizeByModel: [
|
|
80
|
+
{
|
|
81
|
+
match: /cogview/i,
|
|
82
|
+
size: { control: 'wh', style: 'string', field: 'size', allowCustom: true, multiple: 16, minSide: 512, maxSide: 2048, maxPixels: 2097152 }
|
|
83
|
+
}
|
|
84
|
+
],
|
|
85
|
+
async execute(kind, provider, input, signal) {
|
|
86
|
+
if (kind === 'edit') throw new Error('智谱 BigModel 暂未支持参考图编辑;请换用支持编辑的模型。');
|
|
87
|
+
const body = { model: input.model, prompt: promptOf(input) };
|
|
88
|
+
const size = sizeOf(input);
|
|
89
|
+
if (size) body.size = size;
|
|
90
|
+
const quality = String(input.quality || '').trim().toLowerCase();
|
|
91
|
+
if (quality && quality !== 'off' && quality !== 'auto') body.quality = quality;
|
|
92
|
+
const response = await request(baseUrlOf(provider) + '/images/generations', {
|
|
93
|
+
method: 'POST',
|
|
94
|
+
headers: headersFor(provider, false, null, this),
|
|
95
|
+
body: JSON.stringify(body),
|
|
96
|
+
signal: signal
|
|
97
|
+
});
|
|
98
|
+
const payload = await readJsonResponse(response, 32 * 1024 * 1024);
|
|
99
|
+
const first = payload && Array.isArray(payload.data) ? payload.data[0] : null;
|
|
100
|
+
if (first && first.url) return urlToImage(first.url, signal);
|
|
101
|
+
if (first && first.b64_json) {
|
|
102
|
+
const decoded = base64ToImage(first.b64_json);
|
|
103
|
+
if (decoded) return decoded;
|
|
104
|
+
}
|
|
105
|
+
throw new Error('智谱 BigModel 没有返回图片');
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
];
|