dsh-mo-image 0.6.0 → 1.0.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.
@@ -0,0 +1,189 @@
1
+ /**
2
+ * 成图管道:收尾尺寸、严格模式缩放、Worker 卸载与成品保存。
3
+ *
4
+ * 这些逻辑原来长在 lib/index.js 里,和执行器/配置/路由混在一起。拆出来以后
5
+ * index.js 只负责装配与工具入口;这里只依赖适配器层的纯函数和 Worker 客户端,
6
+ * 不读配置、不发请求,测试也就能直接针对成图行为。
7
+ */
8
+ import { mkdir, open, rename, unlink, writeFile } from 'node:fs/promises';
9
+ import path from 'node:path';
10
+ import { randomUUID } from 'node:crypto';
11
+
12
+ import { aspectLabel, comfySizeWritable, imageSizeOf, resizeTo } from './adapters.js';
13
+ import { resizeInWorker } from './image-worker.js';
14
+ import { isPng } from './png-scale.js';
15
+
16
+ /** 从 content-type 猜扩展名;只有成品文件名用它,认不出按 png。 */
17
+ export function safeExt(contentType) {
18
+ const type = String(contentType || '').toLowerCase();
19
+ if (type.includes('jpeg') || type.includes('jpg')) return 'jpg';
20
+ if (type.includes('webp')) return 'webp';
21
+ if (type.includes('gif')) return 'gif';
22
+ return 'png';
23
+ }
24
+
25
+ /** 工具结果/日志里给人看的尺寸标签。 */
26
+ export function sizeLabel(fitted) {
27
+ if (!fitted) return '';
28
+ if (fitted.omit || fitted.size === 'none') return 'auto';
29
+ if (fitted.size === 'auto') return fitted.width && fitted.height ? fitted.width + 'x' + fitted.height : 'auto';
30
+ return fitted.size;
31
+ }
32
+
33
+ /**
34
+ * 模型不接收尺寸参数时的降级:把尺寸写进提示词。
35
+ * 生图模型对英文尺寸句最稳,所以这句固定英文。
36
+ */
37
+ export function stitchSizePrompt(prompt, fitted) {
38
+ const text = String(prompt || '');
39
+ if (!fitted || fitted.omit || !fitted.width || !fitted.height) return text;
40
+ return text + '\n\nOutput size: ' + fitted.width + 'x' + fitted.height
41
+ + ' (' + aspectLabel(fitted.width, fitted.height) + ').';
42
+ }
43
+
44
+ /** 描述符声明了 stitch,或 ComfyUI 自定义工作流根本写不进尺寸时,把尺寸补进提示词。 */
45
+ export function applySizeStitch(prompt, fitted, adapter, provider, model) {
46
+ const declared = fitted && fitted.stitch === true;
47
+ // ComfyUI 自定义工作流:宽高既没有占位符也没有映射时,尺寸根本进不了图。
48
+ let blind = false;
49
+ if (adapter && adapter.id === 'comfyui' && provider) {
50
+ try { blind = !comfySizeWritable(provider, model); } catch (_error) { blind = false; }
51
+ }
52
+ if (!declared && !blind) return { prompt: prompt, note: '' };
53
+ const next = stitchSizePrompt(prompt, fitted);
54
+ if (next === prompt) return { prompt: prompt, note: '' };
55
+ return {
56
+ prompt: next,
57
+ note: '该模型不接收尺寸参数,尺寸 ' + fitted.width + 'x' + fitted.height + ' 已写进提示词'
58
+ };
59
+ }
60
+
61
+ const WORKER_MIN_PIXELS = 512 * 1024;
62
+
63
+ /** 只用请求里明确给出的宽高做缩放目标,档位名没有固定像素尺寸。 */
64
+ function resizePlan(result, options) {
65
+ const strict = options?.strict === true;
66
+ const fitted = result.fitted;
67
+ const requested = fitted?.requested;
68
+ const wanted = requested?.width && requested?.height ? requested : null;
69
+ const actual = imageSizeOf(result.bytes);
70
+ const sourcePixels = actual ? actual.width * actual.height : 0;
71
+ const targetPixels = wanted ? wanted.width * wanted.height : 0;
72
+ const fittedPixels = (fitted?.width || 0) * (fitted?.height || 0);
73
+ const matches = Boolean(actual && wanted && actual.width === wanted.width && actual.height === wanted.height);
74
+ // 非严格模式只有在尺寸适配时抬大过请求,才尝试缩回去。
75
+ const downscale = fitted?.adjusted && wanted && wanted.text !== fitted.size && fittedPixels > targetPixels;
76
+ const resize = Boolean(wanted && !matches && (strict ? actual : downscale));
77
+ return { strict, wanted, actual, sourcePixels, targetPixels, fittedPixels, matches, resize };
78
+ }
79
+
80
+ function withSize(fitted, dimensions, adjusted) {
81
+ const { width, height } = dimensions;
82
+ return { ...fitted, size: width + 'x' + height, width, height, omit: false, adjusted };
83
+ }
84
+
85
+ function finalizeResult(result, plan, resized, log) {
86
+ const { strict, wanted, actual, sourcePixels, targetPixels, fittedPixels, matches, resize } = plan;
87
+ const { bytes, contentType, fitted } = result;
88
+ const generated = actual ? actual.width + 'x' + actual.height : '';
89
+ const output = { bytes, contentType, fitted, note: String(result.note || ''), generated };
90
+ const appendNote = (text) => { output.note = output.note ? output.note + ';' + text : text; };
91
+ if (strict && !wanted) {
92
+ const omit = !fitted || fitted.omit || fitted.size === 'none';
93
+ appendNote(omit
94
+ ? '自动尺寸且请求未带尺寸,严格模式未生效'
95
+ : '该模型按档位出图,没有固定像素目标,严格模式未生效');
96
+ return output;
97
+ }
98
+ const target = wanted ? wanted.width + 'x' + wanted.height : '';
99
+ if (resize && resized) {
100
+ output.bytes = resized.bytes;
101
+ output.contentType = resized.contentType;
102
+ output.fitted = withSize(fitted, wanted, false);
103
+ if (strict) {
104
+ output.original = bytes;
105
+ appendNote('严格模式:上游出图 ' + generated + ',已' + (resized.cropped ? '裁切并' : '')
106
+ + '缩放到 ' + target + (sourcePixels < targetPixels ? '(已放大,画质有损)' : ''));
107
+ } else {
108
+ log('resize ' + (generated || fitted.size) + ' → ' + target);
109
+ }
110
+ } else if (resize || (strict && !actual)) {
111
+ if (actual) output.fitted = withSize(fitted, actual, true);
112
+ const upstream = generated ? '上游出图 ' + generated : '无法读取上游出图尺寸';
113
+ appendNote((strict ? '严格模式:' : '') + upstream + ',未能缩放到 ' + target + ',已保留原图');
114
+ log('resize unavailable, keep original ' + generated + '(用户要 ' + target + ')');
115
+ } else if (matches) {
116
+ output.fitted = withSize(fitted, wanted, false);
117
+ } else if (!strict && fitted?.adjusted && wanted && fittedPixels < targetPixels) {
118
+ appendNote('该模型上限为 ' + fitted.size + ',已按上限生成(请求 ' + target + ',未放大)。');
119
+ log('keep model max ' + fitted.size + '(用户要 ' + target + ',不放大)');
120
+ }
121
+ return output;
122
+ }
123
+
124
+ export function finalizeImage(result, options, log = () => {}) {
125
+ const plan = resizePlan(result, options);
126
+ const resized = plan.resize
127
+ ? resizeTo(result.bytes, plan.wanted.width, plan.wanted.height, plan.strict ? 'cover' : undefined)
128
+ : null;
129
+ return finalizeResult(result, plan, resized, log);
130
+ }
131
+
132
+ /** 大 PNG 只交给 Worker,失败时保留原图。小图和其他格式沿用原有缩放路径。 */
133
+ export async function finalizeImageAsync(result, options, log = () => {}) {
134
+ const plan = resizePlan(result, options);
135
+ let resized = null;
136
+ if (plan.resize) {
137
+ const { width, height } = plan.wanted;
138
+ const mode = plan.strict ? 'cover' : undefined;
139
+ if (isPng(result.bytes) && Math.max(plan.sourcePixels, plan.targetPixels) >= WORKER_MIN_PIXELS) {
140
+ resized = await resizeInWorker(result.bytes, width, height, mode);
141
+ } else {
142
+ resized = resizeTo(result.bytes, width, height, mode);
143
+ }
144
+ }
145
+ return finalizeResult(result, plan, resized, log);
146
+ }
147
+
148
+ /** 生成图旁边留一份上游原图(严格模式缩过图时用)。 */
149
+ export async function saveSidecar(bytes, contentType, file, log = () => {}) {
150
+ try {
151
+ const ext = safeExt(contentType);
152
+ const base = path.basename(file, path.extname(file));
153
+ const target = path.join(path.dirname(file), base + '-original.' + ext);
154
+ await writeFile(target, bytes);
155
+ return target;
156
+ } catch (error) {
157
+ log('save original failed: ' + String(error && error.message ? error.message : error));
158
+ return '';
159
+ }
160
+ }
161
+
162
+ /** 把成品写进调用方选定的目录(当前项目 generated-images 或 DSH 状态目录)。 */
163
+ export async function saveImage(bytes, contentType, provider, model, size, dir) {
164
+ await mkdir(dir, { recursive: true });
165
+ const ext = safeExt(contentType);
166
+ const filename = 'mo-' + Date.now() + '-' + randomUUID().slice(0, 8) + '.' + ext;
167
+ const file = path.join(dir, filename);
168
+ const tmp = file + '.tmp';
169
+ try {
170
+ await writeFile(tmp, bytes, { flag: 'wx' });
171
+ await rename(tmp, file);
172
+ } catch (error) {
173
+ if (error.code !== 'EEXIST') await unlink(tmp).catch(() => {});
174
+ throw error;
175
+ }
176
+ return { file, filename, provider: provider.name || provider.id, model, size, bytes: bytes.length, contentType };
177
+ }
178
+
179
+ /** 提交付费请求前确认能在目标目录创建文件,兼容 Windows 的目录 ACL。 */
180
+ export async function checkImageOutput(dir) {
181
+ await mkdir(dir, { recursive: true });
182
+ const probe = path.join(dir, '.mo-write-' + randomUUID() + '.tmp');
183
+ const file = await open(probe, 'wx', 0o600);
184
+ try {
185
+ await file.close();
186
+ } finally {
187
+ await unlink(probe);
188
+ }
189
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * 大图处理的受控 Worker(OPTIMIZATION_PLAN 阶段 D2)。
3
+ *
4
+ * 主线程只负责收图和落盘;解码、裁切、缩放、编码都在 Worker 里做。
5
+ * 主线程串行提交,只有正在处理的图片需要复制并转移到 Worker。
6
+ *
7
+ * 失败返回 null,调用方可以保留上游原图。运行中的任务超时后停止整个 Worker,
8
+ * 等它退出后再处理队列,避免同时有两份像素缓冲区和缩放任务。
9
+ */
10
+ import { isMainThread, parentPort, Worker } from 'node:worker_threads';
11
+ import { Buffer } from 'node:buffer';
12
+
13
+ import { decodePng, encodePng, pngHeaderOf, resizeRgba } from './png-scale.js';
14
+
15
+ const MAX_SIDE = 16384;
16
+ const MAX_PIXELS = 32 * 1024 * 1024;
17
+ const DEFAULT_TIMEOUT_MS = 30000;
18
+
19
+ function targetOk(width, height) {
20
+ return Number.isSafeInteger(width) && Number.isSafeInteger(height)
21
+ && width > 0 && height > 0
22
+ && width <= MAX_SIDE && height <= MAX_SIDE
23
+ && width * height <= MAX_PIXELS;
24
+ }
25
+
26
+ /** 居中裁切一段 RGBA;和 adapters.js 的 cover 语义保持一致。 */
27
+ function cropRgba(rgba, width, height, left, top, cropWidth, cropHeight) {
28
+ const out = new Uint8Array(cropWidth * cropHeight * 4);
29
+ for (let y = 0; y < cropHeight; y++) {
30
+ const from = ((top + y) * width + left) * 4;
31
+ out.set(rgba.subarray(from, from + cropWidth * 4), y * cropWidth * 4);
32
+ }
33
+ return out;
34
+ }
35
+
36
+ function coverCrop(image, targetWidth, targetHeight) {
37
+ const targetRatio = targetWidth / targetHeight;
38
+ const ratio = image.width / image.height;
39
+ if (Math.abs(ratio - targetRatio) <= 0.01) return null;
40
+ let cropWidth = image.width;
41
+ let cropHeight = Math.round(image.width / targetRatio);
42
+ if (cropHeight > image.height) {
43
+ cropHeight = image.height;
44
+ cropWidth = Math.round(image.height * targetRatio);
45
+ }
46
+ if (cropWidth <= 0 || cropHeight <= 0) return null;
47
+ const left = Math.max(0, Math.floor((image.width - cropWidth) / 2));
48
+ const top = Math.max(0, Math.floor((image.height - cropHeight) / 2));
49
+ return {
50
+ width: cropWidth,
51
+ height: cropHeight,
52
+ rgba: cropRgba(image.rgba, image.width, image.height, left, top, cropWidth, cropHeight)
53
+ };
54
+ }
55
+
56
+ /* --------------------------------------------------------------- worker 侧 */
57
+
58
+ if (!isMainThread && parentPort) {
59
+ parentPort.on('message', (message) => {
60
+ const id = message && message.id;
61
+ try {
62
+ const width = Number(message && message.width);
63
+ const height = Number(message && message.height);
64
+ if (!id || !targetOk(width, height)) {
65
+ parentPort.postMessage({ id: id, ok: false });
66
+ return;
67
+ }
68
+ const bytes = Buffer.from(message.bytes);
69
+ const image = decodePng(bytes);
70
+ if (!image) {
71
+ parentPort.postMessage({ id: id, ok: false });
72
+ return;
73
+ }
74
+ let source = image;
75
+ let cropped = false;
76
+ if (message.mode === 'cover') {
77
+ const next = coverCrop(image, width, height);
78
+ if (next) { source = next; cropped = true; }
79
+ }
80
+ const rgba = resizeRgba(source.rgba, source.width, source.height, width, height);
81
+ const encoded = encodePng(rgba, width, height);
82
+ // 复制到独立的 ArrayBuffer 再转移:Buffer.concat 返回的底层 buffer
83
+ // 可能来自共享池,直接写进 transfer list 会被 worker_threads 拒绝。
84
+ const out = new Uint8Array(encoded);
85
+ parentPort.postMessage({ id: id, ok: true, bytes: out.buffer, cropped: cropped }, [out.buffer]);
86
+ } catch (error) {
87
+ parentPort.postMessage({ id: id, ok: false, error: String(error && error.message ? error.message : error) });
88
+ }
89
+ });
90
+ }
91
+
92
+ /* ----------------------------------------------------------------- 主线程 */
93
+
94
+ let worker = null;
95
+ let stopping = false;
96
+ let running = null;
97
+ let nextId = 1;
98
+ const queue = new Map();
99
+
100
+ function settle(job, result) {
101
+ clearTimeout(job.timer);
102
+ job.resolve(result);
103
+ }
104
+
105
+ function clearQueue() {
106
+ for (const job of queue.values()) settle(job, null);
107
+ queue.clear();
108
+ }
109
+
110
+ function stopWorker() {
111
+ if (!worker || stopping) return;
112
+ stopping = true;
113
+ // exit() 恢复调度。新 Worker 必须等旧 Worker 释放计算和缓冲区后再启动。
114
+ void worker.terminate().catch(() => {});
115
+ }
116
+
117
+ function completeRunning(result) {
118
+ const job = running;
119
+ running = null;
120
+ if (job) settle(job, result);
121
+ }
122
+
123
+ function createWorker() {
124
+ const created = new Worker(new URL('./image-worker.js', import.meta.url));
125
+ created.on('message', (message) => {
126
+ if (worker !== created || stopping || !running || running.id !== message?.id) return;
127
+ completeRunning(message.ok && message.bytes ? {
128
+ bytes: Buffer.from(message.bytes),
129
+ contentType: 'image/png',
130
+ resized: true,
131
+ cropped: !!message.cropped
132
+ } : null);
133
+ dispatchNext();
134
+ });
135
+ created.on('error', () => { if (worker === created) stopWorker(); });
136
+ created.on('exit', () => {
137
+ if (worker !== created) return;
138
+ worker = null;
139
+ stopping = false;
140
+ completeRunning(null);
141
+ dispatchNext();
142
+ });
143
+ return created;
144
+ }
145
+
146
+ function dispatchNext() {
147
+ if (stopping || running) return;
148
+ const job = queue.values().next().value;
149
+ if (!job) {
150
+ worker?.unref();
151
+ return;
152
+ }
153
+ queue.delete(job.id);
154
+ running = job;
155
+ try {
156
+ worker ??= createWorker();
157
+ worker.ref();
158
+ // 独立的 ArrayBuffer 可以转移,同时保留调用方的原图(包括 Buffer 池切片)。
159
+ const copy = new Uint8Array(job.bytes);
160
+ worker.postMessage({ id: job.id, bytes: copy.buffer, width: job.width, height: job.height, mode: job.mode }, [copy.buffer]);
161
+ } catch (_error) {
162
+ completeRunning(null);
163
+ if (worker) stopWorker();
164
+ else clearQueue();
165
+ }
166
+ }
167
+
168
+ /**
169
+ * 在 Worker 里把 PNG 缩放/裁切到目标尺寸。
170
+ *
171
+ * @param {Buffer} bytes 原始 PNG
172
+ * @param {number} width 目标宽
173
+ * @param {number} height 目标高
174
+ * @param {string} [mode] 'cover' 先居中裁切
175
+ * @param {{timeoutMs?:number}} [options]
176
+ * @returns {Promise<{bytes:Buffer,contentType:string,resized:boolean,cropped:boolean}|null>}
177
+ */
178
+ export function resizeInWorker(bytes, width, height, mode, options = {}) {
179
+ const targetWidth = Number(width);
180
+ const targetHeight = Number(height);
181
+ if (!targetOk(targetWidth, targetHeight)) return Promise.resolve(null);
182
+ const header = pngHeaderOf(bytes);
183
+ if (!header || header.bitDepth !== 8 || header.interlace !== 0 || !targetOk(header.width, header.height)) {
184
+ return Promise.resolve(null);
185
+ }
186
+ const timeoutMs = options?.timeoutMs === undefined ? DEFAULT_TIMEOUT_MS : Number(options.timeoutMs);
187
+ if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) return Promise.resolve(null);
188
+ return new Promise((resolve) => {
189
+ const id = nextId++;
190
+ const timer = setTimeout(() => {
191
+ if (queue.delete(id)) {
192
+ resolve(null);
193
+ } else if (running?.id === id) {
194
+ stopWorker();
195
+ completeRunning(null);
196
+ }
197
+ }, timeoutMs);
198
+ queue.set(id, { id, bytes, width: targetWidth, height: targetHeight, mode, resolve, timer });
199
+ dispatchNext();
200
+ });
201
+ }
202
+
203
+ /** 关闭 Worker,未完成的请求返回 null。以后提交的请求可以启动新 Worker。 */
204
+ export function closeImageWorker() {
205
+ stopWorker();
206
+ completeRunning(null);
207
+ clearQueue();
208
+ }