dsh-gallery 1.0.0 → 1.1.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,572 @@
1
+ /**
2
+ * 产出台 · 区域感知(2026-11-16)
3
+ *
4
+ * 为什么要有这个文件:
5
+ * 老板在产出台里框了一块区域(左键逐点多边形 → 进反馈篮),然后跟助手说
6
+ * 「框选区域的字母改为小雨点」。实测下来助手要花 **97 秒翻 7 次文件**才
7
+ * 发现「哦,用户刚框了一块」,再花 150 秒自己写 PIL 反复算坐标。
8
+ * 根因是:批注只在 feedback.json 里,前端看得见,助手看不见 ——
9
+ * gallery_context 只肯说「你在看哪张图」,不说「这张图上框了哪儿」。
10
+ *
11
+ * 本文件负责把那块坐标变成助手能直接吃的东西:
12
+ * · 归一化坐标 → 整图像素矩形
13
+ * · 外扩一圈后的裁剪小图(存临时目录,不登记、不污染产出台)
14
+ * · 需要时按前端口径生成 RGBA 遮罩(全尺寸、RGB 留原图、选区内 alpha=0)
15
+ *
16
+ * 遮罩口径必须与 client.js 的 buildMaskPng 逐字节对齐,否则 ComfyUI 那边
17
+ * 会拿到一张「框位置正确但 alpha 反了」的图。对齐依据:
18
+ * · maskPixelRect —— 归一化 → 整图像素矩形
19
+ * · maskAlphaAt —— 框内 0、框外 255
20
+ * · polygonAlphaLayer —— 多边形填充后强制二值
21
+ *
22
+ * 红线:不写 feedback / 不改标记 / 不发消息。裁剪图只落系统临时目录。
23
+ */
24
+ import path from 'node:path'
25
+ import os from 'node:os'
26
+ import { promises as fsp } from 'node:fs'
27
+ import { execFile } from 'node:child_process'
28
+
29
+ /** 裁剪图外扩比例:框太小的时候至少留这么一圈上下文,否则看不清框的是啥。 */
30
+ const CROP_MARGIN_RATIO = 0.12
31
+ const CROP_MARGIN_MIN_PX = 16
32
+ /** 遮罩像素上限:超过就不生成,避免一次性吃掉几百 MB。 */
33
+ const MASK_MAX_PIXELS = 40_000_000
34
+ const PYTHON_TIMEOUT_MS = 20_000
35
+
36
+ /** 读 PNG / JPEG / GIF 的宽高(不依赖任何图像库,只解析文件头)。 */
37
+ export function imageSizeOf(buf) {
38
+ if (!Buffer.isBuffer(buf) || buf.length < 24) return null
39
+ // PNG:8 字节魔数 + 4 长度 + 4 'IHDR',宽高在 16 / 20
40
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {
41
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20), format: 'png' }
42
+ }
43
+ // GIF:'GIF87a' / 'GIF89a',宽高是小端 16 位
44
+ if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46) {
45
+ return { width: buf.readUInt16LE(6), height: buf.readUInt16LE(8), format: 'gif' }
46
+ }
47
+ // JPEG:扫段找 SOFn
48
+ if (buf[0] === 0xff && buf[1] === 0xd8) {
49
+ let i = 2
50
+ while (i + 9 < buf.length) {
51
+ if (buf[i] !== 0xff) { i += 1; continue }
52
+ const marker = buf[i + 1]
53
+ // SOF0..SOF15,排除 DHT(C4) / JPG(C8) / DAC(CC)
54
+ if (marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc) {
55
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7), format: 'jpeg' }
56
+ }
57
+ const len = buf.readUInt16BE(i + 2)
58
+ if (len < 2) return null
59
+ i += 2 + len
60
+ }
61
+ return null
62
+ }
63
+ // WebP:VP8X / VP8 / VP8L
64
+ if (buf.length > 30 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') {
65
+ const kind = buf.toString('ascii', 12, 16)
66
+ if (kind === 'VP8X') {
67
+ return {
68
+ width: 1 + buf.readUIntLE(24, 3),
69
+ height: 1 + buf.readUIntLE(27, 3),
70
+ format: 'webp',
71
+ }
72
+ }
73
+ if (kind === 'VP8 ') {
74
+ return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff, format: 'webp' }
75
+ }
76
+ if (kind === 'VP8L') {
77
+ const bits = buf.readUInt32LE(21)
78
+ return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1, format: 'webp' }
79
+ }
80
+ }
81
+ return null
82
+ }
83
+
84
+ const clamp01 = (v) => {
85
+ const n = Number(v)
86
+ if (!Number.isFinite(n)) return 0
87
+ return n < 0 ? 0 : (n > 1 ? 1 : n)
88
+ }
89
+
90
+ /**
91
+ * 🔴 两种形态必须都认,否则坐标会抓空:
92
+ * · 内存形态:{ x, y, w, h, polygon?, shape?, note } (normalizeAnnotation 产出)
93
+ * · 落盘形态:{ id, note, region: { x, y, w, h, polygon?, shape? }, markedAt }
94
+ * —— feedback.json 里存的是这一种(见 client.js 的 toStoredAnnot)。
95
+ * 第一版漏了这一层,读出来的框全是 0×0。这里统一压成平铺,
96
+ * 下游(算像素矩形、算裁剪框、给模型看)只认平铺。
97
+ */
98
+ export function flattenAnnotation(a) {
99
+ if (a === null || typeof a !== 'object') return null
100
+ const region = (a.region !== null && typeof a.region === 'object') ? a.region : a
101
+ const x = Number(region.x)
102
+ const y = Number(region.y)
103
+ const w = Number(region.w)
104
+ const h = Number(region.h)
105
+ if (![x, y, w, h].every((n) => Number.isFinite(n))) return null
106
+ const polygon = Array.isArray(region.polygon) ? region.polygon : (Array.isArray(a.polygon) ? a.polygon : null)
107
+ const shape = region.shape ?? a.shape ?? (polygon !== null ? 'polygon' : 'rect')
108
+ return {
109
+ x, y, w, h,
110
+ shape: String(shape),
111
+ polygon,
112
+ note: typeof a.note === 'string' ? a.note : '',
113
+ fillColor: typeof region.fillColor === 'string' ? region.fillColor : '',
114
+ id: typeof a.id === 'string' ? a.id : '',
115
+ }
116
+ }
117
+
118
+ /** 从 feedback.json 的若干条目里取出某张图的批注(没有就是空数组)。 */
119
+ export function annotationsFor(feedback, relPath) {
120
+ const key = String(relPath ?? '').replace(/\\/g, '/')
121
+ const entry = feedback !== null && typeof feedback === 'object' ? feedback[key] : null
122
+ if (entry === null || typeof entry !== 'object') return []
123
+ const list = Array.isArray(entry.annotations) ? entry.annotations : []
124
+ const flat = list.map(flattenAnnotation).filter((a) => a !== null)
125
+ if (flat.length > 0) return flat
126
+ // 老格式 / 只记了单条 region:退回顶层 region
127
+ const single = flattenAnnotation(entry)
128
+ return single !== null ? [single] : []
129
+ }
130
+
131
+ /**
132
+ * 全库「每张图最后一次被标注」的时间表(relPath → 毫秒)。
133
+ *
134
+ * 为什么要它:老板定的排序口径里「最近标注」排在「生成 / 改动」之前 ——
135
+ * 标注是人主动划的一笔,比文件时间戳更能说明「我在这张图上动脑子了」。
136
+ * 只返回时间,不返回内容:排序只需要一个数,明细留给 annotationsFor。
137
+ */
138
+ export function latestAnnotationAt(feedback) {
139
+ const out = new Map()
140
+ if (feedback === null || typeof feedback !== 'object') return out
141
+ for (const [rel, entry] of Object.entries(feedback)) {
142
+ if (entry === null || typeof entry !== 'object') continue
143
+ const list = Array.isArray(entry.annotations) ? entry.annotations : [entry]
144
+ let best = 0
145
+ for (const a of list) {
146
+ if (a === null || typeof a !== 'object') continue
147
+ const t = Number(a.markedAt ?? a.createdAt ?? 0) || 0
148
+ if (t > best) best = t
149
+ }
150
+ // 有的一整条反馈只有一个顶层时间(老格式 / 只记单条 region 的情况)
151
+ const top = Number(entry.markedAt ?? entry.updatedAt ?? 0) || 0
152
+ if (top > best) best = top
153
+ if (best > 0) out.set(String(rel).replace(/\\/g, '/'), best)
154
+ }
155
+ return out
156
+ }
157
+
158
+ /**
159
+ * 与 client.js 的 maskPixelRect 同一算法:归一化框 → 整图像素矩形。
160
+ * 助手拿到的就是这里的数字,必须和前端画出来的那一块严格一致。
161
+ */
162
+ export function maskPixelRect(annotation, width, height) {
163
+ const w = Math.max(1, Math.round(Number(width) || 0))
164
+ const h = Math.max(1, Math.round(Number(height) || 0))
165
+ const x = clamp01(annotation?.x)
166
+ const y = clamp01(annotation?.y)
167
+ let nw = clamp01(annotation?.w)
168
+ let nh = clamp01(annotation?.h)
169
+ if (nw > 0 && x + nw > 1) nw = 1 - x
170
+ if (nh > 0 && y + nh > 1) nh = 1 - y
171
+ const x0 = Math.min(w - 1, Math.max(0, Math.round(x * w)))
172
+ const y0 = Math.min(h - 1, Math.max(0, Math.round(y * h)))
173
+ const x1 = Math.min(w, Math.max(x0 + 1, Math.round((x + nw) * w)))
174
+ const y1 = Math.min(h, Math.max(y0 + 1, Math.round((y + nh) * h)))
175
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0, width: w, height: h }
176
+ }
177
+
178
+ /** 把一条批注整理成助手看得懂的一行事实。 */
179
+ export function describeAnnotation(annotation, index, imageSize) {
180
+ const size = imageSize ?? { width: 0, height: 0 }
181
+ const known = Number(size.width) > 0 && Number(size.height) > 0
182
+ const rect = maskPixelRect(annotation, size.width, size.height)
183
+ const isPolygon = annotation?.shape === 'polygon' && Array.isArray(annotation?.polygon)
184
+ return {
185
+ index: index + 1,
186
+ shape: String(annotation?.shape ?? 'rect'),
187
+ // 归一化(前端存的就是这个):助手要用现成脚本时按这个算比例
188
+ xPct: Math.round(clamp01(annotation?.x) * 1000) / 10,
189
+ yPct: Math.round(clamp01(annotation?.y) * 1000) / 10,
190
+ wPct: Math.round(clamp01(annotation?.w) * 1000) / 10,
191
+ hPct: Math.round(clamp01(annotation?.h) * 1000) / 10,
192
+ // 整图像素矩形(已换算好,助手不用自己算)。
193
+ // 尺寸未知时给全 0 —— 给个「1×1 在左上角」的假数字比不给更糟,
194
+ // 模型会照着它去裁一块空白。
195
+ px: known
196
+ ? { x: rect.x, y: rect.y, w: rect.w, h: rect.h }
197
+ : { x: 0, y: 0, w: 0, h: 0 },
198
+ note: typeof annotation?.note === 'string' ? annotation.note : '',
199
+ pointCount: isPolygon ? annotation.polygon.length : 0,
200
+ points: isPolygon
201
+ ? annotation.polygon.map((p) => [
202
+ Math.round(clamp01(Array.isArray(p) ? p[0] : p?.x) * 1000) / 10,
203
+ Math.round(clamp01(Array.isArray(p) ? p[1] : p?.y) * 1000) / 10,
204
+ ])
205
+ : [],
206
+ fillColor: typeof annotation?.fillColor === 'string' ? annotation.fillColor : '',
207
+ }
208
+ }
209
+
210
+ /**
211
+ * 外扩一圈但不越界。框贴着图边时自动收回来。
212
+ */
213
+ export function expandBox(px, imageSize, marginRatio = CROP_MARGIN_RATIO) {
214
+ const w = Math.max(1, Math.round(Number(imageSize?.width) || 0))
215
+ const h = Math.max(1, Math.round(Number(imageSize?.height) || 0))
216
+ const mx = Math.max(CROP_MARGIN_MIN_PX, Math.round(px.w * marginRatio))
217
+ const my = Math.max(CROP_MARGIN_MIN_PX, Math.round(px.h * marginRatio))
218
+ const x0 = Math.max(0, px.x - mx)
219
+ const y0 = Math.max(0, px.y - my)
220
+ const x1 = Math.min(w, px.x + px.w + mx)
221
+ const y1 = Math.min(h, px.y + px.h + my)
222
+ return { x: x0, y: y0, w: Math.max(1, x1 - x0), h: Math.max(1, y1 - y0) }
223
+ }
224
+
225
+ /** 找不到宿主自带 python 时的候选路径(本机实测装在这里,见归档)。 */
226
+ function pythonCandidates() {
227
+ const list = []
228
+ if (process.env.DSH_PYTHON) list.push(process.env.DSH_PYTHON)
229
+ const home = os.homedir()
230
+ list.push(path.join(home, '.dsh', 'dsh-runtimes', 'dsh-primary-runtime', 'dependencies', 'python', 'python.exe'))
231
+ list.push(path.join(home, '.dsh', 'dsh-runtimes', 'dsh-primary-runtime', 'dependencies', 'python', 'bin', 'python3'))
232
+ if (process.platform === 'win32') list.push('python.exe')
233
+ else list.push('python3')
234
+ return list
235
+ }
236
+
237
+ // 未探测用 undefined 表示;探不到记成空串(区分「还没探」和「探过没有」)
238
+ let pythonCache
239
+
240
+ /** 探测一个能用 PIL 的 python;探不到返回 null(调用方降级,不能抛)。 */
241
+ export async function resolvePython() {
242
+ if (pythonCache !== undefined) return pythonCache === '' ? null : pythonCache
243
+ for (const candidate of pythonCandidates()) {
244
+ const ok = await new Promise((resolve) => {
245
+ try {
246
+ execFile(candidate, ['-c', 'import PIL, numpy'], { timeout: 6000, windowsHide: true }, (err) => {
247
+ resolve(err === null)
248
+ })
249
+ } catch {
250
+ resolve(false)
251
+ }
252
+ })
253
+ if (ok) { pythonCache = candidate; return candidate }
254
+ }
255
+ pythonCache = ''
256
+ return null
257
+ }
258
+
259
+ /** 供测试注入:把探测结果钉死,别让测试依赖本机装没装 python。 */
260
+ export function __setPythonForTest(value) {
261
+ pythonCache = value
262
+ }
263
+
264
+ /**
265
+ * 真正干活的一步:把请求写成 JSON 交给 python,拿回裁剪图 / 遮罩。
266
+ * 走文件而不是命令行参数 —— 中文路径 + 引号 + 长度都容易翻车。
267
+ */
268
+ function runPythonJob(python, jobFile, timeoutMs = PYTHON_TIMEOUT_MS) {
269
+ const script = String.raw`
270
+ import json, sys, os
271
+ sys.stdout.reconfigure(encoding="utf-8")
272
+ from PIL import Image, ImageDraw
273
+ import numpy as np
274
+
275
+ with open(sys.argv[1], "r", encoding="utf-8") as f:
276
+ job = json.load(f)
277
+
278
+ src = job["image"]
279
+ out = {"ok": True, "regions": [], "image": {}}
280
+ try:
281
+ base = Image.open(src)
282
+ base.load()
283
+ base = base.convert("RGBA")
284
+ except Exception as e:
285
+ print(json.dumps({"ok": False, "error": "open-failed: %s" % e}, ensure_ascii=False))
286
+ sys.exit(0)
287
+
288
+ W, H = base.size
289
+ out["image"] = {"width": W, "height": H}
290
+ os.makedirs(job["cropDir"], exist_ok=True)
291
+
292
+ # 分支二:用户手动画好的遮罩文件(右键逐点填充 → 导出遮罩)。
293
+ # 这时根本不用算坐标 —— 遮罩里 alpha=0 的地方就是他要改的地方,
294
+ # 直接量出包围盒 + 裁一张小图给他看清框住哪个字即可。
295
+ if job.get("mode") == "mask":
296
+ try:
297
+ mk = Image.open(job["mask"])
298
+ mk.load()
299
+ except Exception as e:
300
+ print(json.dumps({"ok": False, "error": "mask-open-failed: %s" % e}, ensure_ascii=False))
301
+ sys.exit(0)
302
+ if tuple(mk.size) != (W, H):
303
+ print(json.dumps({"ok": False, "error": "mask-size-mismatch: 遮罩 %dx%d 与原图 %dx%d 不一致" % (mk.size[0], mk.size[1], W, H)}, ensure_ascii=False))
304
+ sys.exit(0)
305
+ if "A" in mk.getbands():
306
+ alpha = np.array(mk.convert("RGBA").getchannel("A"))
307
+ else:
308
+ # 没有 alpha 的遮罩(灰度 / 黑白图):按「黑=要改」处理,与常见约定一致
309
+ gray = np.array(mk.convert("L"))
310
+ alpha = np.where(gray < 128, 0, 255).astype(np.uint8)
311
+ sel = alpha < 128
312
+ n = int(sel.sum())
313
+ if n == 0:
314
+ print(json.dumps({"ok": False, "error": "mask-empty: 遮罩里没有任何选区(整张都是不透明)"}, ensure_ascii=False))
315
+ sys.exit(0)
316
+ ys, xs = np.where(sel)
317
+ bx0, bx1, by0, by1 = int(xs.min()), int(xs.max()), int(ys.min()), int(ys.max())
318
+ bw, bh = bx1 - bx0 + 1, by1 - by0 + 1
319
+ out["px"] = {"x": bx0, "y": by0, "w": bw, "h": bh}
320
+ out["pixels"] = n
321
+ if job.get("withCrop"):
322
+ patch = max(16, int(round(max(bw, bh) * 0.12)))
323
+ cx0 = max(0, bx0 - patch); cy0 = max(0, by0 - patch)
324
+ cx1 = min(W, bx1 + 1 + patch); cy1 = min(H, by1 + 1 + patch)
325
+ crop = base.crop((cx0, cy0, cx1, cy1))
326
+ cp = os.path.join(job["cropDir"], "mask-region.png")
327
+ crop.save(cp, "PNG")
328
+ out["cropPath"] = cp
329
+ out["cropBox"] = {"x": cx0, "y": cy0, "w": cx1 - cx0, "h": cy1 - cy0}
330
+ print(json.dumps(out, ensure_ascii=False))
331
+ sys.exit(0)
332
+
333
+ for r in job["regions"]:
334
+ one = {"index": r["index"], "cropPath": "", "maskPath": ""}
335
+ cb = r["cropBox"]
336
+ x0 = max(0, min(W, int(cb["x"]))); y0 = max(0, min(H, int(cb["y"])))
337
+ x1 = max(x0 + 1, min(W, x0 + int(cb["w"])))
338
+ y1 = max(y0 + 1, min(H, y0 + int(cb["h"])))
339
+ if r.get("withCrop"):
340
+ crop = base.crop((x0, y0, x1, y1))
341
+ p = os.path.join(job["cropDir"], "region-%02d.png" % r["index"])
342
+ crop.save(p, "PNG")
343
+ one["cropPath"] = p
344
+ one["cropBox"] = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0}
345
+ if r.get("withMask"):
346
+ # 与 client.js 同口径:全尺寸、RGB 保留原图、选区内 alpha=0、框外 255
347
+ alpha = Image.new("L", (W, H), 255)
348
+ d = ImageDraw.Draw(alpha)
349
+ pts = r.get("polygon")
350
+ if pts:
351
+ px = []
352
+ for p2 in pts:
353
+ nx = min(1.0, max(0.0, float(p2[0])))
354
+ ny = min(1.0, max(0.0, float(p2[1])))
355
+ px.append((nx * W, ny * H))
356
+ d.polygon(px, fill=0)
357
+ else:
358
+ pb = r["px"]
359
+ ax0 = max(0, min(W, int(pb["x"]))); ay0 = max(0, min(H, int(pb["y"])))
360
+ ax1 = max(ax0 + 1, min(W, ax0 + int(pb["w"])))
361
+ ay1 = max(ay0 + 1, min(H, ay0 + int(pb["h"])))
362
+ d.rectangle([ax0, ay0, ax1 - 1, ay1 - 1], fill=0)
363
+ masked = base.copy()
364
+ masked.putalpha(alpha)
365
+ mp = os.path.join(job["cropDir"], "mask-%02d.png" % r["index"])
366
+ masked.save(mp, "PNG")
367
+ one["maskPath"] = mp
368
+ out["regions"].append(one)
369
+
370
+ print(json.dumps(out, ensure_ascii=False))
371
+ `
372
+ return new Promise((resolve) => {
373
+ try {
374
+ execFile(python, ['-c', script, jobFile], {
375
+ timeout: timeoutMs,
376
+ windowsHide: true,
377
+ maxBuffer: 4 * 1024 * 1024,
378
+ env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
379
+ }, (err, stdout, stderr) => {
380
+ if (err) {
381
+ resolve({ ok: false, error: String(stderr || err.message || err).slice(0, 400) })
382
+ return
383
+ }
384
+ try {
385
+ const text = String(stdout ?? '').trim()
386
+ const lastLine = text.split('\n').filter((l) => l.trim() !== '').pop() ?? ''
387
+ resolve(JSON.parse(lastLine))
388
+ } catch (e) {
389
+ resolve({ ok: false, error: 'parse-failed: ' + String(e?.message ?? e) })
390
+ }
391
+ })
392
+ } catch (e) {
393
+ resolve({ ok: false, error: String(e?.message ?? e) })
394
+ }
395
+ })
396
+ }
397
+
398
+ function hashName(input) {
399
+ let h = 5381
400
+ const s = String(input ?? '')
401
+ for (let i = 0; i < s.length; i += 1) h = ((h * 33) ^ s.charCodeAt(i)) >>> 0
402
+ return h.toString(36)
403
+ }
404
+
405
+ /**
406
+ * 主入口:给一张图和它的批注,产出「助手能直接看的东西」。
407
+ *
408
+ * 设计上的取舍:
409
+ * · python 探不到就**不报错**,返回坐标 + 一句「自己裁」的说明。宁可少给,
410
+ * 也不能让工具调用抛异常把模型这一轮废掉(宿主的 tool 失败代价很高)。
411
+ * · 裁剪图落系统临时目录,**不进产出台**。派生资产要登记 frame 才算数,
412
+ * 这里只是给模型看的中间物,登记了反而会让用户看到一堆垃圾。
413
+ */
414
+ export async function materializeRegions({
415
+ absPath,
416
+ annotations,
417
+ withCrop = true,
418
+ withMask = false,
419
+ } = {}) {
420
+ const list = (Array.isArray(annotations) ? annotations : [])
421
+ .map(flattenAnnotation)
422
+ .filter((a) => a !== null)
423
+ const result = {
424
+ ok: true,
425
+ image: { width: 0, height: 0 },
426
+ regions: [],
427
+ degraded: '',
428
+ }
429
+ if (list.length === 0) {
430
+ result.ok = true
431
+ result.degraded = '这张图上没有任何框选批注'
432
+ return result
433
+ }
434
+ let size = null
435
+ try {
436
+ const head = Buffer.alloc(64 * 1024)
437
+ const handle = await fsp.open(absPath, 'r')
438
+ try {
439
+ const { bytesRead } = await handle.read(head, 0, head.length, 0)
440
+ size = imageSizeOf(head.subarray(0, bytesRead))
441
+ } finally {
442
+ await handle.close()
443
+ }
444
+ } catch {
445
+ size = null
446
+ }
447
+ if (size !== null) result.image = { width: size.width, height: size.height }
448
+ const imageSize = size ?? { width: 0, height: 0 }
449
+
450
+ const prepared = list.map((a, i) => {
451
+ const fact = describeAnnotation(a, i, imageSize)
452
+ const cropBox = expandBox(fact.px, imageSize)
453
+ return { fact, cropBox, raw: a }
454
+ })
455
+ result.regions = prepared.map((p) => ({
456
+ ...p.fact,
457
+ cropBox: p.cropBox,
458
+ // 先给空串占位:降级路径(没 python)也必须有这两个字段,
459
+ // 否则前端 / 模型拿到 undefined,判断「有没有裁剪图」会出错。
460
+ cropPath: '',
461
+ maskPath: '',
462
+ }))
463
+
464
+ const python = await resolvePython()
465
+ if (python === null) {
466
+ result.degraded = '本机没探到可用的 python(PIL),只给了坐标;裁剪图需要自行生成'
467
+ return result
468
+ }
469
+ const totalPixels = imageSize.width * imageSize.height
470
+ const wantMask = withMask === true && totalPixels > 0 && totalPixels <= MASK_MAX_PIXELS
471
+ if (withMask === true && !wantMask) {
472
+ result.degraded = '图太大,没有生成遮罩(超过 4000 万像素)'
473
+ }
474
+
475
+ const cropDir = path.join(os.tmpdir(), 'dsh-gallery-regions', hashName(absPath + '|' + list.length))
476
+ await fsp.mkdir(cropDir, { recursive: true }).catch(() => {})
477
+ const jobFile = path.join(cropDir, `job-${Date.now().toString(36)}.json`)
478
+ const job = {
479
+ image: absPath,
480
+ cropDir,
481
+ regions: prepared.map((p, i) => ({
482
+ index: i + 1,
483
+ px: p.fact.px,
484
+ cropBox: p.cropBox,
485
+ polygon: p.fact.shape === 'polygon' && p.fact.points.length >= 4
486
+ ? p.raw.polygon.map((pt) => [clamp01(Array.isArray(pt) ? pt[0] : pt?.x), clamp01(Array.isArray(pt) ? pt[1] : pt?.y)])
487
+ : null,
488
+ withCrop: withCrop === true,
489
+ withMask: wantMask,
490
+ })),
491
+ }
492
+ try {
493
+ await fsp.writeFile(jobFile, JSON.stringify(job), 'utf8')
494
+ } catch (e) {
495
+ result.degraded = '临时目录不可写:' + String(e?.message ?? e)
496
+ return result
497
+ }
498
+ const ran = await runPythonJob(python, jobFile)
499
+ await fsp.unlink(jobFile).catch(() => {})
500
+ if (ran?.ok !== true) {
501
+ result.degraded = 'python 处理失败(' + String(ran?.error ?? '未知') + '),只给了坐标'
502
+ return result
503
+ }
504
+ const byIndex = new Map((ran.regions ?? []).map((r) => [r.index, r]))
505
+ result.regions = result.regions.map((r) => {
506
+ const got = byIndex.get(r.index) ?? {}
507
+ return { ...r, cropPath: String(got.cropPath ?? ''), maskPath: String(got.maskPath ?? '') }
508
+ })
509
+ return result
510
+ }
511
+
512
+ /**
513
+ * 「用户已经画好遮罩」这条路的入口。
514
+ *
515
+ * 现实场景(2026-11-16 实测 8 分 39 秒那次):用户在产出台右键逐点填充 → 导出遮罩,
516
+ * 遮罩文件已经躺在产出目录里,gallery_context 也把路径报给了模型 ——
517
+ * 但模型没有「一次拿到范围 + 裁剪图」的通道,只能自己写 PIL 脚本
518
+ * 量 alpha 像素、画包围盒、放大看图,光确认「框住的是哪个字」就耗掉三分半钟。
519
+ *
520
+ * 这里就干一件事:把遮罩读出来,给包围盒 + 一张外扩裁剪图。
521
+ * 遮罩本身**原样复用**,绝不重新生成 —— 用户画的边界以他为准。
522
+ */
523
+ export async function materializeMaskRegion({ absPath, maskPath, withCrop = true } = {}) {
524
+ const result = { ok: true, image: { width: 0, height: 0 }, region: null, degraded: '' }
525
+ const python = await resolvePython()
526
+ if (python === null) {
527
+ result.degraded = '本机没探到可用的 python(PIL),读不出遮罩覆盖范围;遮罩文件本身可以直接用'
528
+ return result
529
+ }
530
+ const cropDir = path.join(os.tmpdir(), 'dsh-gallery-regions', hashName(absPath + '|mask'))
531
+ await fsp.mkdir(cropDir, { recursive: true }).catch(() => {})
532
+ const jobFile = path.join(cropDir, `job-mask-${Date.now().toString(36)}.json`)
533
+ try {
534
+ await fsp.writeFile(jobFile, JSON.stringify({
535
+ mode: 'mask', image: absPath, mask: maskPath, cropDir, withCrop: withCrop === true,
536
+ }), 'utf8')
537
+ } catch (e) {
538
+ result.degraded = '临时目录不可写:' + String(e?.message ?? e)
539
+ return result
540
+ }
541
+ const ran = await runPythonJob(python, jobFile)
542
+ await fsp.unlink(jobFile).catch(() => {})
543
+ if (ran?.ok !== true) {
544
+ result.degraded = '读遮罩失败:' + String(ran?.error ?? '未知')
545
+ return result
546
+ }
547
+ const width = Number(ran?.image?.width) || 0
548
+ const height = Number(ran?.image?.height) || 0
549
+ result.image = { width, height }
550
+ const px = ran?.px ?? { x: 0, y: 0, w: 0, h: 0 }
551
+ // 百分比顺手算好:模型拿它写 prompt 或跟用户对话时不用再乘除
552
+ const pct = (v, base) => (base > 0 ? Math.round((Number(v) || 0) / base * 1000) / 10 : 0)
553
+ result.region = {
554
+ px: { x: Number(px.x) || 0, y: Number(px.y) || 0, w: Number(px.w) || 0, h: Number(px.h) || 0 },
555
+ xPct: pct(px.x, width),
556
+ yPct: pct(px.y, height),
557
+ wPct: pct(px.w, width),
558
+ hPct: pct(px.h, height),
559
+ // 只报数字不报含义:这里是「被选中的像素个数」,不是给模型做覆盖率验收用的
560
+ pixelCount: Number(ran?.pixels) || 0,
561
+ cropPath: String(ran?.cropPath ?? ''),
562
+ cropBox: ran?.cropBox ?? null,
563
+ }
564
+ return result
565
+ }
566
+
567
+ export const REGION_LIMITS = {
568
+ CROP_MARGIN_RATIO,
569
+ CROP_MARGIN_MIN_PX,
570
+ MASK_MAX_PIXELS,
571
+ PYTHON_TIMEOUT_MS,
572
+ }