dsh-gallery 0.14.4 → 0.16.2

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/cordis.patch.yml CHANGED
@@ -1,4 +1,4 @@
1
- # 产出画廊:右侧栏「产出画廊」tab 的 Host 半部(扫描 + /api 路由)。
1
+ # 产出台:右侧栏「产出台」tab 的 Host 半部(扫描 + /api 路由)。
2
2
  # 浏览器半部由 package.json 的 dsh.client 清单发现,并通过 ./client 导出。
3
3
  #
4
4
  # ⚠️ 顶层必须是「数组」,首项是 - insert:。写成对象(insert: 直接顶格)会导致 patch 无法加载,
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Windows 系统剪贴板「文件列表」(CF_HDROP / FileDropList)读写。
3
+ *
4
+ * 为什么需要:Chromium 的 paste 事件对「资源管理器里 Ctrl+C 的文件」**不给
5
+ * file item**(浏览器安全限制,文件只能来自拖放或 <input type=file>),所以
6
+ * 纯前端永远粘不到音视频 / DWG / ZIP 等任意文件。而 PowerShell 5.1 自带
7
+ * Get-Clipboard -Format FileDropList / Set-Clipboard -LiteralPath
8
+ * 能直接读写系统剪贴板的文件列表,且不需要 Add-Type 动态编译 .NET。
9
+ *
10
+ * 编码约定(实测踩坑):
11
+ * · 命令一律走 -EncodedCommand(UTF-16LE base64),避免命令行里的中文/引号被拆;
12
+ * · 路径列表经 **UTF-8 临时文件** 往返,绝不从 stdout 取中文路径
13
+ * (PowerShell 控制台默认 OEM/GBK 代码页,中文会乱码);
14
+ * · 单次调用 9 秒超时,任何异常都降级为「插件内部剪贴板」,不让功能整体失败。
15
+ *
16
+ * 非 Windows 平台不调 PowerShell,直接使用内部剪贴板(复制→粘贴仍闭环)。
17
+ */
18
+
19
+ import { spawn } from 'node:child_process'
20
+ import { promises as fsp } from 'node:fs'
21
+ import os from 'node:os'
22
+ import path from 'node:path'
23
+
24
+ import { bumpName } from './derive.js'
25
+
26
+ const PS_TIMEOUT_MS = 9000
27
+
28
+ /**
29
+ * 系统剪贴板不可用时的进程内兜底;同一 DSH 实例下所有对话共享。
30
+ * 带时间戳:只在写入后 10 分钟内有效,避免之后复制了纯文本却「幽灵粘贴」旧资产。
31
+ */
32
+ const INTERNAL_TTL_MS = 10 * 60 * 1000
33
+ let internalClipboard = { paths: [], at: 0 }
34
+
35
+ /** PowerShell 单引号字符串字面量(单引号加倍即可转义)。 */
36
+ function psQuote(value) {
37
+ return "'" + String(value).replace(/'/g, "''") + "'"
38
+ }
39
+
40
+ function encodedCommand(script) {
41
+ // PowerShell -EncodedCommand 要求 UTF-16LE 的 base64
42
+ return Buffer.from(script, 'utf16le').toString('base64')
43
+ }
44
+
45
+ function runPowerShell(script) {
46
+ return new Promise((resolve, reject) => {
47
+ let out = ''
48
+ let err = ''
49
+ let settled = false
50
+ let child
51
+ try {
52
+ child = spawn('powershell.exe', [
53
+ '-NoProfile', '-NonInteractive', '-STA',
54
+ '-EncodedCommand', encodedCommand(script),
55
+ ], { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
56
+ } catch (error) {
57
+ reject(error)
58
+ return
59
+ }
60
+ const finish = (fn, value) => {
61
+ if (settled) return
62
+ settled = true
63
+ fn(value)
64
+ }
65
+ const timer = setTimeout(() => {
66
+ try { child.kill() } catch { /* 已退出 */ }
67
+ finish(reject, new Error('PowerShell 调用超时(9s)'))
68
+ }, PS_TIMEOUT_MS)
69
+ child.stdout?.on('data', (chunk) => { out += String(chunk) })
70
+ child.stderr?.on('data', (chunk) => { err += String(chunk) })
71
+ child.on('error', (error) => {
72
+ clearTimeout(timer)
73
+ finish(reject, error)
74
+ })
75
+ child.on('close', (code) => {
76
+ clearTimeout(timer)
77
+ if (code === 0) finish(resolve, out)
78
+ else finish(reject, new Error('PowerShell exit ' + code + ': ' + err.slice(-600)))
79
+ })
80
+ })
81
+ }
82
+
83
+ function tmpFile(tag) {
84
+ return path.join(
85
+ os.tmpdir(),
86
+ 'dsh-gallery-' + tag + '-' + process.pid + '-' +
87
+ Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7) + '.txt',
88
+ )
89
+ }
90
+
91
+ /**
92
+ * 读系统剪贴板里的文件绝对路径列表。
93
+ * 剪贴板没有文件列表 / PowerShell 不可用时返回 [](不抛)。
94
+ * @returns {Promise<string[]>}
95
+ */
96
+ export async function readClipboardFilePaths() {
97
+ if (process.platform !== 'win32') return []
98
+ const outFile = tmpFile('clipread')
99
+ const script = [
100
+ "$ErrorActionPreference = 'Stop'",
101
+ '$items = @()',
102
+ 'try {',
103
+ // 🔴 不能用 `Get-Clipboard | ForEach-Object`:cmdlet 把整个 List<PSObject>
104
+ // 作为**单个**管道对象输出,[string] 转换会把多路径空格拼成一行。
105
+ // 先接住集合再 foreach 逐项展开,才是真的多文件。
106
+ ' $raw = Get-Clipboard -Format FileDropList -ErrorAction Stop',
107
+ ' if ($null -ne $raw) { foreach ($x in $raw) { $items += [string]$x } }',
108
+ '} catch { $items = @() }',
109
+ '[System.IO.File]::WriteAllLines(' + psQuote(outFile) + ', [string[]]$items, (New-Object System.Text.UTF8Encoding($false)))',
110
+ ].join('\n')
111
+ try {
112
+ await runPowerShell(script)
113
+ const text = await fsp.readFile(outFile, 'utf8')
114
+ const lines = text.split(/\r?\n/).map((s) => s.trim()).filter((s) => s !== '')
115
+ return [...new Set(lines)]
116
+ } catch {
117
+ return []
118
+ } finally {
119
+ try { await fsp.rm(outFile, { force: true }) } catch { /* 忽略 */ }
120
+ }
121
+ }
122
+
123
+ /**
124
+ * 把文件绝对路径列表写入系统剪贴板(可在资源管理器 / 其它应用 Ctrl+V)。
125
+ * 失败时退化为插件内部剪贴板,保证「复制 → 粘贴」仍然闭环。
126
+ * @param {string[]} paths
127
+ * @returns {Promise<{ ok: boolean, count: number, mode: string }>}
128
+ */
129
+ export async function writeClipboardFilePaths(paths) {
130
+ const cleaned = [...new Set((Array.isArray(paths) ? paths : [])
131
+ .map((p) => String(p ?? '').trim()).filter((p) => p !== ''))]
132
+ if (cleaned.length === 0) return { ok: false, count: 0, mode: 'none' }
133
+
134
+ // 无论系统剪贴板是否成功,都写一份内部兜底
135
+ internalClipboard = { paths: cleaned, at: Date.now() }
136
+ if (process.platform !== 'win32') {
137
+ return { ok: true, count: cleaned.length, mode: 'internal' }
138
+ }
139
+
140
+ const inFile = tmpFile('clipwrite')
141
+ const script = [
142
+ "$ErrorActionPreference = 'Stop'",
143
+ '$lines = @([System.IO.File]::ReadAllLines(' + psQuote(inFile) + ', [System.Text.Encoding]::UTF8) | Where-Object { $_ -ne \'\' })',
144
+ "if ($lines.Count -eq 0) { exit 3 }",
145
+ 'Set-Clipboard -LiteralPath $lines -ErrorAction Stop',
146
+ "Write-Output 'OK'",
147
+ ].join('\n')
148
+ try {
149
+ await fsp.writeFile(inFile, cleaned.join('\n'), 'utf8')
150
+ await runPowerShell(script)
151
+ return { ok: true, count: cleaned.length, mode: 'system' }
152
+ } catch {
153
+ return { ok: true, count: cleaned.length, mode: 'internal' }
154
+ } finally {
155
+ try { await fsp.rm(inFile, { force: true }) } catch { /* 忽略 */ }
156
+ }
157
+ }
158
+
159
+ /** 内部剪贴板(系统剪贴板读不到文件列表时的兜底,10 分钟内有效)。 */
160
+ export function internalClipboardPaths() {
161
+ if (Date.now() - internalClipboard.at > INTERNAL_TTL_MS) return []
162
+ return internalClipboard.paths.slice()
163
+ }
164
+
165
+ /**
166
+ * 把剪贴板里的文件批量复制进目标目录(当前对话目录)。
167
+ *
168
+ * 口径与 http.js 的 `pasteFile` 单文件版完全一致:2GB 上限、只收文件、
169
+ * 重名时 `<名>-n.<扩展名>` 自增(**绝不覆盖已有文件**)、返回 roots 相对路径。
170
+ * 抽成独立模块是为了能用真实临时目录做端到端测试(http.js 的 op 路由不便直调)。
171
+ *
172
+ * @param {string[]} srcPaths 源文件绝对路径
173
+ * @param {string} dir 目标目录(当前对话目录)
174
+ * @param {string} root 扫描根目录,用于算 relPath;可为空
175
+ * @returns {Promise<{ files: {name:string, absPath:string, relPath:string}[], failed: {path:string, message:string}[] }>}
176
+ */
177
+ export async function pasteFilesIntoDir(srcPaths, dir, root = '') {
178
+ const okFiles = []
179
+ const failed = []
180
+ try { await fsp.mkdir(dir, { recursive: true }) } catch { /* 下面 copyFile 会给真实错误 */ }
181
+ const list = Array.isArray(srcPaths) ? srcPaths.slice(0, 200) : []
182
+ for (const raw of list) {
183
+ const srcAbs = path.resolve(String(raw ?? '').replace(/\\/g, '/'))
184
+ try {
185
+ const st = await fsp.stat(srcAbs)
186
+ if (!st.isFile()) throw new Error('源路径不是文件')
187
+ if (st.size > 2 * 1024 * 1024 * 1024) throw new Error('文件超过 2 GB,粘贴被拒绝')
188
+ const base = path.basename(srcAbs).replace(/[\\/:*?"<>|\r\n\t]/g, '_').trim() || 'file'
189
+ // 重名自增(与 http.js 内联的 uniqueName 同口径)
190
+ let name = base
191
+ let abs = path.join(dir, name)
192
+ for (let n = 2; n <= 999; n += 1) {
193
+ let exists = true
194
+ try { await fsp.access(abs) } catch { exists = false }
195
+ if (!exists) break
196
+ name = bumpName(base, n)
197
+ abs = path.join(dir, name)
198
+ }
199
+ await fsp.copyFile(srcAbs, abs)
200
+ // 🔴 Windows 的 CopyFile 会**保留源文件 mtime**(Linux 不会)。画廊 global 视图按
201
+ // mtime 时间窗过滤,保留旧 mtime 会让「刚粘进来的旧素材」在全局视图里根本看不到。
202
+ // 粘贴语义是「现在进入本对话」,所以统一把落盘文件的时间戳刷成当前时间。
203
+ try { const now = new Date(); await fsp.utimes(abs, now, now) } catch { /* 时间戳失败不影响粘贴 */ }
204
+ const relPath = root === '' ? '' : path.relative(root, abs).split(path.sep).join('/')
205
+ okFiles.push({ name, absPath: abs, relPath })
206
+ } catch (error) {
207
+ failed.push({ path: srcAbs, message: String(error?.message ?? error) })
208
+ }
209
+ }
210
+ return { files: okFiles, failed }
211
+ }
package/host/derive.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * v0.16.0 派生资产相关的纯函数(无副作用、可单测)。
3
+ * 粘贴 / 裁剪产出的文件名与 PNG 校验都走这里,避免逻辑散落。
4
+ */
5
+
6
+ /**
7
+ * 派生资产命名:`<前缀>_<时间戳>[-n].<ext>`。
8
+ * 时间戳用本地可读串(非冒号,避免 Windows 文件名非法),重复时加 -n 由调用方决定。
9
+ * @param {string} prefix 前缀(如「粘贴」「裁剪-原图名」)
10
+ * @param {string} ext 扩展名(不含点)
11
+ * @param {string} suffix 重名后缀(如 `-2`)
12
+ */
13
+ export function makeDerivedName(prefix, ext, suffix = '') {
14
+ const safe = String(prefix).replace(/[\\/:*?"<>|\r\n\t]/g, '_').replace(/\s+/g, ' ').trim().slice(0, 60) || 'asset'
15
+ const d = new Date()
16
+ const pad = (n) => String(n).padStart(2, '0')
17
+ const ts = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
18
+ const e = String(ext || 'png').replace(/[^a-z0-9]/gi, '').toLowerCase().slice(0, 6) || 'png'
19
+ return `${safe}_${ts}${suffix}.${e}`
20
+ }
21
+
22
+ /**
23
+ * 文件名重名时的自增:在 stem 后追加 `-2 / -3 …`,保留扩展名。
24
+ * @param {string} base 原始文件名
25
+ * @param {number} n 自增序号(>=2)
26
+ */
27
+ export function bumpName(base, n) {
28
+ const dot = base.lastIndexOf('.')
29
+ const stem = dot > 0 ? base.slice(0, dot) : base
30
+ const ext = dot > 0 ? base.slice(dot) : ''
31
+ return `${stem}-${n}${ext}`
32
+ }
33
+
34
+ /**
35
+ * 原子写用的临时路径:**必须保留扩展名**。
36
+ *
37
+ * 🔴 ffmpeg 靠扩展名推断输出容器。写成 `xxx.mp4.tmp-123` 会直接报
38
+ * "Unable to choose an output format" → HTTP 500(2026-11-13 12:15 真机实测,
39
+ * 视频和音频同时失败)。随机串必须放在扩展名**之前**:`xxx.tmp-123.mp4`。
40
+ *
41
+ * @param {string} abs 最终绝对路径
42
+ * @param {string} tag 区分并发的标记(默认 pid-时间戳)
43
+ */
44
+ export function tmpPathFor(abs, tag = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`) {
45
+ const s = String(abs)
46
+ const dot = s.lastIndexOf('.')
47
+ const slash = Math.max(s.lastIndexOf('/'), s.lastIndexOf('\\'))
48
+ // 点必须在最后一个路径分隔符之后才算扩展名,否则目录名里的点会误判
49
+ if (dot <= slash + 1) return `${s}.tmp-${tag}`
50
+ return `${s.slice(0, dot)}.tmp-${tag}${s.slice(dot)}`
51
+ }
52
+
53
+ /**
54
+ * PNG 合法性校验 + base64 解码;非法(空 / 超 24MB / 非 PNG 魔数)返回 null。
55
+ * @param {string} data base64 字符串
56
+ */
57
+ export function pngBufferFrom(data) {
58
+ const buf = Buffer.from(data, 'base64')
59
+ if (buf.length < 8 || buf.length > 24 * 1024 * 1024) return null
60
+ if (!(buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47)) return null
61
+ return buf
62
+ }
@@ -102,6 +102,24 @@ export function makeItem(item) {
102
102
  frameMs: Number(item.frameOf.frameMs) || 0,
103
103
  }
104
104
  }
105
+ // v0.14.5 遮罩来源:由本条框选区域生成的 RGBA 遮罩资产,路径只随草稿带出
106
+ // v0.14.6 右键多边形:把外接框 / 顶点像素坐标 / 面积一并带出,供 Agent 精确回填。
107
+ if (item?.maskOf !== undefined && item?.maskOf !== null && typeof item.maskOf === 'object') {
108
+ out.maskOf = {
109
+ relPath: String(item.maskOf.relPath ?? ''),
110
+ sourceName: String(item.maskOf.sourceName ?? ''),
111
+ region: item.maskOf.region ?? null,
112
+ polygon: Array.isArray(item.maskOf.polygon) ? item.maskOf.polygon : null,
113
+ polygonPx: Array.isArray(item.maskOf.polygonPx) ? item.maskOf.polygonPx : null,
114
+ bboxPx: Array.isArray(item.maskOf.bboxPx) ? item.maskOf.bboxPx : null,
115
+ areaPx: Number(item.maskOf.areaPx) || 0,
116
+ imageWidth: Number(item.maskOf.imageWidth) || 0,
117
+ imageHeight: Number(item.maskOf.imageHeight) || 0,
118
+ // v0.14.7 彩色填充预览图:只用于目视核对,工作流仍用主 alpha 遮罩
119
+ overlayRelPath: String(item.maskOf.overlayRelPath ?? ''),
120
+ fillColor: String(item.maskOf.fillColor ?? ''),
121
+ }
122
+ }
105
123
  return out
106
124
  }
107
125
 
@@ -155,7 +173,7 @@ export function renderFeedbackText(feedback, options) {
155
173
  lines.push('Reply item by item using the `Annotation N:` prefix, so each decision maps to one annotation.')
156
174
  lines.push('')
157
175
  } else {
158
- lines.push(`【产出画廊反馈 · 共 ${items.length} 条】`)
176
+ lines.push(`【产出台反馈 · 共 ${items.length} 条】`)
159
177
  lines.push('')
160
178
  lines.push('请按 `Annotation 1:`、`Annotation 2:` … 逐条回应,让每条决定都对应到一个批注。')
161
179
  lines.push('')
@@ -178,6 +196,31 @@ export function renderFeedbackText(feedback, options) {
178
196
  ? `Frame source: taken from "${f.videoName}" at ${f.timecode} (${f.frameMs} ms)`
179
197
  : `帧来源:取自视频《${f.videoName}》${f.timecode}(第 ${f.frameMs} 毫秒)`)
180
198
  }
199
+ // 遮罩来源是「资产路径 + 编码说明」,不是自动指令:模型拿到后自行上传 / 回填 image 输入
200
+ if (item.maskOf !== undefined && item.maskOf !== null && String(item.maskOf.relPath ?? '') !== '') {
201
+ lines.push(locale === 'en'
202
+ ? `Mask source: ${item.maskOf.relPath} — RGBA mask from this box; alpha=0 inside the box, so ComfyUI LoadImage MASK (1 - alpha/255) marks only the area to inpaint`
203
+ : `遮罩来源:${item.maskOf.relPath} —— 由本条框选区域生成的 RGBA 遮罩,框内 alpha=0,ComfyUI LoadImage 的 MASK 输出(1 - alpha/255)即待重绘区域;可用于局部重绘 / 移除流回填 image 输入`)
204
+ const mp = item.maskOf
205
+ // v0.14.7 彩色填充预览图:只供人核对选区位置,别拿去回填工作流
206
+ if (String(mp.overlayRelPath ?? '') !== '') {
207
+ const fillName = { green: '绿', red: '红', blue: '蓝' }[String(mp.fillColor ?? '')] ?? '绿'
208
+ lines.push(locale === 'en'
209
+ ? `Mask preview: ${mp.overlayRelPath} — original image with a solid semi-transparent fill over the selection; visual check only, hand the RGBA mask above to the workflow`
210
+ : `遮罩预览:${mp.overlayRelPath} —— 原图上叠加${fillName}色半透明填充,仅用于目视核对选区位置;工作流请用上面的 RGBA 遮罩`)
211
+ }
212
+ if (Array.isArray(mp.polygonPx) && mp.polygonPx.length > 0) {
213
+ const b = Array.isArray(mp.bboxPx) ? mp.bboxPx : [0, 0, 0, 0]
214
+ const size = `${Number(mp.imageWidth) || 0}×${Number(mp.imageHeight) || 0}`
215
+ const verts = JSON.stringify(mp.polygonPx)
216
+ lines.push(locale === 'en'
217
+ ? `Mask region: ${size}px source · ${mp.polygonPx.length} vertices · bbox (${b[0]},${b[1]})-(${b[2]},${b[3]}) · ~${Number(mp.areaPx) || 0}px · vertex pixels ${verts}`
218
+ : `遮罩区域:原图 ${size}px · ${mp.polygonPx.length} 个顶点 · 外接框 (${b[0]},${b[1]})-(${b[2]},${b[3]}) · 面积约 ${Number(mp.areaPx) || 0}px · 顶点像素坐标 ${verts}`)
219
+ lines.push(locale === 'en'
220
+ ? 'Mask handoff: upload it, then replace the target workflow image input; use ONE short target phrase (e.g. change "X" to "Y", keep the original lettering), do not expand into a whole-word rewrite with extra constraints'
221
+ : '遮罩回填:上传后替换目标工作流的 image 入参;提示词用单目标短句(例如:将图中的「X」,改为「Y」,保持原有字体色调),不要扩写成整词替换加约束')
222
+ }
223
+ }
181
224
  if (item.reason !== undefined) {
182
225
  lines.push(`${locale === 'en' ? 'Reason' : '理由'}:${item.reason}`)
183
226
  }
package/host/frames.js CHANGED
@@ -113,3 +113,62 @@ export function makeFrameName(videoName, frameMs, suffix = '') {
113
113
  const safe = raw.replace(/[\\/:*?"<>|\r\n\t]/g, '_').replace(/\s+/g, ' ').trim().slice(0, 80) || 'video'
114
114
  return `${safe}_帧_${frameTimecode(frameMs)}${suffix}.png`
115
115
  }
116
+
117
+ /**
118
+ * 遮罩文件名(v0.14.5):`<原图名>_遮罩_x<左>-y<上>-w<宽>-h<高>.png`。
119
+ * 坐标用归一化百分比整数,肉眼就能看出框选位置;同框重复导出加 -2 / -3,不覆盖旧遮罩。
120
+ * 复用 frames.json 登记(kind:'mask'),扫描时据此把遮罩挂回产出它的当前对话。
121
+ */
122
+ export function makeMaskName(imageName, region, suffix = '') {
123
+ const raw = String(imageName ?? 'image').replace(/\.[^.]+$/, '')
124
+ const safe = raw.replace(/[\\/:*?"<>|\r\n\t]/g, '_').replace(/\s+/g, ' ').trim().slice(0, 60) || 'image'
125
+ const pct = (v) => {
126
+ const n = Number(v)
127
+ if (!Number.isFinite(n)) return 0
128
+ return Math.round(Math.min(1, Math.max(0, n)) * 100)
129
+ }
130
+ const r = region ?? {}
131
+ return `${safe}_遮罩_x${pct(r.x)}-y${pct(r.y)}-w${pct(r.w)}-h${pct(r.h)}${suffix}.png`
132
+ }
133
+
134
+ /**
135
+ * 多边形遮罩元数据(v0.14.6):校验归一化顶点(4–20 点),换算成原图像素坐标,
136
+ * 并给出外接框与选区面积。老板要的「记录这个区域在图片的准确位置」就落在这里——
137
+ * 像素坐标只在 Host 侧按原图真实尺寸计算,前端显示的百分比不作为准。
138
+ * 返回 null 表示不合法,调用方直接 400,绝不把脏坐标写进 frames.json。
139
+ */
140
+ export function maskPolygonMeta(polygon, width, height) {
141
+ if (!Array.isArray(polygon) || polygon.length < 4 || polygon.length > 20) return null
142
+ const w = Math.max(1, Math.round(Number(width) || 0))
143
+ const h = Math.max(1, Math.round(Number(height) || 0))
144
+ const pts = []
145
+ for (const p of polygon) {
146
+ const nx = Number(Array.isArray(p) ? p[0] : p?.x)
147
+ const ny = Number(Array.isArray(p) ? p[1] : p?.y)
148
+ if (!Number.isFinite(nx) || !Number.isFinite(ny)) return null
149
+ if (nx < 0 || nx > 1 || ny < 0 || ny > 1) return null
150
+ pts.push([Math.round(nx * w), Math.round(ny * h)])
151
+ }
152
+ const xs = pts.map((p) => p[0])
153
+ const ys = pts.map((p) => p[1])
154
+ // 右/下用开区间(与 PIL getbbox 一致),草稿里 (x0,y0)-(x1,y1) 才不会少算一列/一行。
155
+ const bboxPx = [
156
+ Math.min(...xs), Math.min(...ys),
157
+ Math.min(w, Math.max(...xs) + 1), Math.min(h, Math.max(...ys) + 1),
158
+ ]
159
+ let sum = 0
160
+ for (let i = 0, j = pts.length - 1; i < pts.length; j = i, i += 1) {
161
+ sum += (pts[j][0] * pts[i][1]) - (pts[i][0] * pts[j][1])
162
+ }
163
+ return {
164
+ polygon: polygon.map((p) => [
165
+ Number(Array.isArray(p) ? p[0] : p.x),
166
+ Number(Array.isArray(p) ? p[1] : p.y),
167
+ ]),
168
+ polygonPx: pts,
169
+ bboxPx,
170
+ areaPx: Math.round(Math.abs(sum) / 2),
171
+ imageWidth: w,
172
+ imageHeight: h,
173
+ }
174
+ }