dsh-gallery 1.4.1 → 1.5.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,379 @@
1
+ /**
2
+ * 交付清单组装内核(v1.5.0)
3
+ *
4
+ * 一个内核、两个出口:
5
+ * · 出口 1 —— op `exportManifest`:落盘成 CSV / JSON,给人看、进 Excel 做物料表
6
+ * · 出口 2 —— 工具 `gallery_manifest`:直接回给 Agent,驱动下一轮
7
+ * 两边都调这里,保证「您看到的清单」和「我读到的清单」永远是同一份数字。
8
+ *
9
+ * 三条硬约束:
10
+ * 1. **只读**:本模块绝不写盘。落盘由 http.js 的 op 负责(走 atomic.js)。
11
+ * 2. **不猜**:拿不到尺寸就留空,不写 0,免得客户以为图是 0×0。
12
+ * 3. **截断必须说出来**:超上限如实置 truncated,不静默少给。
13
+ *
14
+ * 为什么尺寸要自己读文件头:扫描结果里没有宽高(`context.json` 实测字段无 width/height),
15
+ * 而整图解码来拿尺寸代价太大。`regions.js` 的 `imageSizeOf()` 只解析文件头(零依赖,
16
+ * 不用任何图像库),读一次 open 同时取 stat,IO 只走一趟。
17
+ */
18
+
19
+ import { promises as fsp } from 'node:fs'
20
+
21
+ import { imageSizeOf } from './regions.js'
22
+ import { mapPool, SCAN_CONCURRENCY } from './scan.js'
23
+ // 时间码格式复用截帧那一套(`00-02-17-892`,用「-」而非「:」因为文件名不许冒号),
24
+ // 不在这里另写一份,免得清单上的时间码和文件名里的对不上。
25
+ import { frameTimecode } from './frames.js'
26
+
27
+ /** 清单格式版本:将来加列/改语义就升这个数,读的人能判断兼容性。 */
28
+ export const MANIFEST_SCHEMA = 1
29
+
30
+ /** 分类的中文名,CSV 里给人看的就是这几个字 */
31
+ export const CATEGORY_TEXT = {
32
+ final: '定稿',
33
+ input: '素材',
34
+ intermediate: '过程稿',
35
+ unknown: '未归类',
36
+ }
37
+
38
+ export const MANIFEST_CATEGORIES = ['final', 'input', 'intermediate', 'unknown']
39
+
40
+ /**
41
+ * 读文件头用的字节数。JPEG 的 SOF 段前面可能挂着 EXIF 缩略图,
42
+ * 64 字节常常看不到宽高,所以一次读 8 KB(只读头部,不读整图)。
43
+ */
44
+ const HEAD_BYTES = 8192
45
+
46
+ /**
47
+ * 需要读盘的条目上限。**只统计「扫描条目里缺 width/height/size」的那些** ——
48
+ * 扫描结果实测自带 width / height / size(见 scan.js 产出),绝大多数条目根本不用读盘。
49
+ * 真正要读盘的是老缓存、文件类资产这些,数量有限;超了就让它们留空,不硬扛。
50
+ */
51
+ const SIZE_PROBE_MAX = 4000
52
+
53
+ /** 单份清单的条目上限:全库实测 6930 条,留足余量又不至于把响应撑爆。 */
54
+ const MANIFEST_MAX_ITEMS = 20000
55
+
56
+ /** 路径统一成斜杠形态(与 labels / frames 的键口径一致,否则永远查不中)。 */
57
+ export function normalizeRelPath(value) {
58
+ return String(value ?? '').replace(/\\/g, '/').replace(/^\.\//, '').trim()
59
+ }
60
+
61
+ const pad2 = (n) => String(n).padStart(2, '0')
62
+
63
+ /**
64
+ * 取一个「大于 0 的有限数」,拿不到一律回 0。
65
+ *
66
+ * 🔴 必须用这个而不是 `Number(x) || y`:扫描条目里 width/height 可能是 null,
67
+ * `Number(null)` 是 0 但兜底到 frames 的 undefined 就成了 NaN,
68
+ * 而 **NaN 参与任何比较都是 false**(`NaN <= 0` 为 false),
69
+ * 会让「缺宽高就去读盘」的判断静默失效 —— 实测 2024 条一条都没补上。
70
+ */
71
+ function positiveNum(value) {
72
+ const n = Number(value)
73
+ return Number.isFinite(n) && n > 0 ? n : 0
74
+ }
75
+
76
+ /** 本地时间 `2026-11-25 10:43`;拿不到就留空,别写 1970。 */
77
+ export function formatLocalTime(ms) {
78
+ const n = Number(ms)
79
+ if (!Number.isFinite(n) || n <= 0) return ''
80
+ const d = new Date(n)
81
+ if (Number.isNaN(d.getTime())) return ''
82
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())} `
83
+ + `${pad2(d.getHours())}:${pad2(d.getMinutes())}`
84
+ }
85
+
86
+ /** 人类可读体积:给客户看的是「1.2 MB」而不是 1258291。 */
87
+ export function formatBytes(bytes) {
88
+ const n = Number(bytes)
89
+ if (!Number.isFinite(n) || n <= 0) return ''
90
+ if (n < 1024) return `${Math.round(n)} B`
91
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`
92
+ return `${(n / (1024 * 1024)).toFixed(1)} MB`
93
+ }
94
+
95
+ /**
96
+ * CSV 单元格转义(RFC 4180)。
97
+ * 逗号、引号、换行都必须整格包引号,内部引号写成两个 ——
98
+ * 少做一步,Excel 就会把一格拆成两列,客户拿到的清单是错位的。
99
+ */
100
+ export function csvCell(value) {
101
+ const s = value === null || value === undefined ? '' : String(value)
102
+ if (s === '') return ''
103
+ if (/[",\r\n]/.test(s)) return `"${s.replace(/"/g, '""')}"`
104
+ return s
105
+ }
106
+
107
+ /**
108
+ * 读一个文件的体积 + 宽高(一次 open 同时拿 stat 和文件头)。
109
+ * hint 是 frames 里已经记过的 imageWidth/imageHeight,有就不必再读头。
110
+ */
111
+ async function probeFile(absPath, hint) {
112
+ if (!absPath) return null
113
+ let handle = null
114
+ try {
115
+ handle = await fsp.open(absPath, 'r')
116
+ const st = await handle.stat()
117
+ if (!st.isFile()) return null
118
+ let size = null
119
+ if (hint && Number(hint.width) > 0 && Number(hint.height) > 0) {
120
+ size = { width: Number(hint.width), height: Number(hint.height), format: '' }
121
+ } else {
122
+ const buf = Buffer.alloc(HEAD_BYTES)
123
+ const { bytesRead } = await handle.read(buf, 0, HEAD_BYTES, 0)
124
+ if (bytesRead >= 24) size = imageSizeOf(buf.subarray(0, bytesRead))
125
+ }
126
+ return { bytes: st.size, width: size?.width ?? 0, height: size?.height ?? 0, format: size?.format ?? '' }
127
+ } catch {
128
+ // 文件被移走 / 没权限都走这里:清单里这一格留空,不编数
129
+ return null
130
+ } finally {
131
+ if (handle !== null) {
132
+ try { await handle.close() } catch { /* 关不掉不影响结果 */ }
133
+ }
134
+ }
135
+ }
136
+
137
+ /** 从 frames 登记里取「这条资产是从哪个视频的哪一刻截出来的」。 */
138
+ function sourceOfFrame(frame) {
139
+ if (frame === null || typeof frame !== 'object') return null
140
+ const videoName = String(frame.videoName ?? frame.sourceName ?? '')
141
+ const videoRelPath = String(frame.videoRelPath ?? frame.sourceRelPath ?? '')
142
+ const frameMs = Number(frame.frameMs)
143
+ const hasMs = Number.isFinite(frameMs) && frameMs > 0
144
+ // 老登记没有 timecode 字段只有 frameMs,这时按同一套规则补出来
145
+ const timecode = String(frame.timecode ?? '') || (hasMs ? frameTimecode(frameMs) : '')
146
+ if (videoName === '' && videoRelPath === '' && timecode === '') return null
147
+ return {
148
+ videoName,
149
+ videoRelPath,
150
+ timecode,
151
+ frameMs: hasMs ? frameMs : 0,
152
+ }
153
+ }
154
+
155
+ /** 反馈篮里对这条资产的备注(结构开放,认不出就当没有)。 */
156
+ function noteOf(record) {
157
+ if (record === null || typeof record !== 'object') return { note: '', annotationCount: 0 }
158
+ const note = typeof record.text === 'string' ? record.text
159
+ : typeof record.note === 'string' ? record.note
160
+ : typeof record.comment === 'string' ? record.comment : ''
161
+ const regions = Array.isArray(record.regions) ? record.regions
162
+ : Array.isArray(record.annotations) ? record.annotations
163
+ : Array.isArray(record.region) ? record.region : []
164
+ return { note: String(note).slice(0, 300), annotationCount: regions.length }
165
+ }
166
+
167
+ /**
168
+ * 组装交付清单。**只读,不落盘。**
169
+ *
170
+ * @param options.entries 扫描出来的条目(一定要带 relPath)
171
+ * @param options.relPaths 只要这些(批量选中时传);空 = 不限
172
+ * @param options.categories 只要这几类;空 = 不限
173
+ * @param options.frames frames.json 的 frames 映射(补来源视频与时间码)
174
+ * @param options.labels labels.json 的 labels 映射(判断是否人工改过)
175
+ * @param options.feedback feedback.json 的 feedback 映射(补备注)
176
+ * @param options.masks relPath → 配套遮罩的相对路径(buildLinkedMaskIndex 产出)
177
+ * @param options.includeSize 是否补宽高与体积(默认 true;条目自带就不读盘,只在缺字段时读文件头)
178
+ * @param options.includeNotes 是否带反馈备注(默认 false,导出交付件时才开)
179
+ * @param options.maxItems 硬上限,超出置 truncated
180
+ */
181
+ export async function buildManifest(options = {}) {
182
+ const entries = Array.isArray(options.entries) ? options.entries : []
183
+ const frames = options.frames !== null && typeof options.frames === 'object' ? options.frames : {}
184
+ const labels = options.labels !== null && typeof options.labels === 'object' ? options.labels : {}
185
+ const feedback = options.feedback !== null && typeof options.feedback === 'object' ? options.feedback : {}
186
+ // masks:relPath -> 遮罩相对路径(由 frames.js 的 buildLinkedMaskIndex 建,http.js 传进来)
187
+ const masks = options.masks !== null && typeof options.masks === 'object' ? options.masks : {}
188
+ const includeSize = options.includeSize !== false
189
+ const includeNotes = options.includeNotes === true
190
+ const maxItems = Math.max(1, Math.min(MANIFEST_MAX_ITEMS, Math.trunc(Number(options.maxItems)) || 2000))
191
+ const wantPaths = Array.isArray(options.relPaths) && options.relPaths.length > 0
192
+ ? new Set(options.relPaths.map(normalizeRelPath).filter((p) => p !== ''))
193
+ : null
194
+ const wantCats = Array.isArray(options.categories) && options.categories.length > 0
195
+ ? new Set(options.categories.map((c) => String(c ?? '')).filter((c) => MANIFEST_CATEGORIES.includes(c)))
196
+ : null
197
+
198
+ // 去重 + 过滤。同一张图可能同时出现在 items 与 groups[].files 里。
199
+ const picked = []
200
+ const seen = new Set()
201
+ for (const entry of entries) {
202
+ if (entry === null || typeof entry !== 'object') continue
203
+ const relPath = normalizeRelPath(entry.relPath)
204
+ if (relPath === '' || seen.has(relPath)) continue
205
+ // 分叉隔离:分叉会话继承来的资产默认不进交付清单(它们不属于本次产出)
206
+ if (entry.inherited === true || entry.shared === true) {
207
+ if (options.includeInherited !== true) continue
208
+ }
209
+ if (wantPaths !== null && !wantPaths.has(relPath)) continue
210
+ const manual = labels[relPath]
211
+ const category = String(entry.category ?? (manual?.category ?? 'unknown')) || 'unknown'
212
+ if (wantCats !== null && !wantCats.has(category)) continue
213
+ seen.add(relPath)
214
+ picked.push({ entry, relPath, category, manual: manual !== null && typeof manual === 'object' })
215
+ }
216
+
217
+ // 稳定顺序:按相对路径升序,同一份数据导两次的序号能对上账
218
+ picked.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0))
219
+
220
+ const truncated = picked.length > maxItems
221
+ const sliced = truncated ? picked.slice(0, maxItems) : picked
222
+
223
+ // 扫描条目本身自带 width / height / size(实测字段),能用就直接用,一次盘都不读。
224
+ // 只有缺这些字段的(老缓存、文件类资产、视频)才去读文件头。
225
+ const needProbe = []
226
+ if (includeSize) {
227
+ for (let i = 0; i < sliced.length; i += 1) {
228
+ const { entry, relPath } = sliced[i]
229
+ const fr = frames[relPath]
230
+ const w = positiveNum(entry.width) || positiveNum(fr?.imageWidth)
231
+ const h = positiveNum(entry.height) || positiveNum(fr?.imageHeight)
232
+ const size = positiveNum(entry.size)
233
+ // 写成 !(w > 0) 而不是 w <= 0:NaN 会让后者恒为 false,缺尺寸的条目会被整体漏掉
234
+ if ((!(w > 0) || !(h > 0) || !(size > 0)) && String(entry.absPath ?? '') !== '') needProbe.push(i)
235
+ }
236
+ }
237
+ const probes = new Map()
238
+ if (needProbe.length > 0 && needProbe.length <= SIZE_PROBE_MAX) {
239
+ const results = await mapPool(needProbe, SCAN_CONCURRENCY, (i) => {
240
+ const { entry, relPath } = sliced[i]
241
+ const fr = frames[relPath]
242
+ return probeFile(String(entry.absPath ?? ''), {
243
+ width: positiveNum(entry.width) || positiveNum(fr?.imageWidth),
244
+ height: positiveNum(entry.height) || positiveNum(fr?.imageHeight),
245
+ })
246
+ })
247
+ for (let k = 0; k < needProbe.length; k += 1) probes.set(needProbe[k], results[k])
248
+ }
249
+
250
+ // summary 必须基于**截断前**的 picked:total 是「筛选后一共多少条」,
251
+ // 不是「这次返回了多少条」。否则模型看到「共 8 条」会以为清单只有 8 条。
252
+ const byCategory = { final: 0, input: 0, intermediate: 0, unknown: 0 }
253
+ let withMask = 0
254
+ let fromVideo = 0
255
+ let totalBytes = 0
256
+ for (const { entry, relPath, category } of picked) {
257
+ if (Object.prototype.hasOwnProperty.call(byCategory, category)) byCategory[category] += 1
258
+ else byCategory.unknown += 1
259
+ if (normalizeRelPath(entry.maskPath ?? masks[relPath] ?? '') !== '') withMask += 1
260
+ if (sourceOfFrame(frames[relPath]) !== null) fromVideo += 1
261
+ totalBytes += positiveNum(entry.size)
262
+ }
263
+
264
+ const items = []
265
+ for (let i = 0; i < sliced.length; i += 1) {
266
+ const { entry, relPath, category, manual } = sliced[i]
267
+ const probe = probes.get(i) ?? null
268
+ const fr = frames[relPath]
269
+ const frame = sourceOfFrame(fr)
270
+ const fb = includeNotes ? noteOf(feedback[relPath]) : { note: '', annotationCount: 0 }
271
+ // 扫描条目里**没有** maskPath 字段(实测过),遮罩只能靠 frames 的关联索引反查:
272
+ // 索引的键是原图/预览图的相对路径,值是配套遮罩图。不传索引就是空的。
273
+ const maskPath = normalizeRelPath(entry.maskPath ?? masks[relPath] ?? '')
274
+ const name = String(entry.name ?? relPath.split('/').pop() ?? '')
275
+ const width = positiveNum(probe?.width) || positiveNum(entry.width) || positiveNum(fr?.imageWidth)
276
+ const height = positiveNum(probe?.height) || positiveNum(entry.height) || positiveNum(fr?.imageHeight)
277
+ const bytes = positiveNum(probe?.bytes) || positiveNum(entry.size)
278
+
279
+ items.push({
280
+ index: i + 1,
281
+ name,
282
+ relPath,
283
+ absPath: String(entry.absPath ?? ''),
284
+ category,
285
+ categoryText: CATEGORY_TEXT[category] ?? CATEGORY_TEXT.unknown,
286
+ categoryManual: manual,
287
+ width,
288
+ height,
289
+ format: probe?.format ?? '',
290
+ bytes,
291
+ bytesText: formatBytes(bytes),
292
+ mtime: Number(entry.mtime) || 0,
293
+ mtimeText: formatLocalTime(entry.mtime),
294
+ sessionId: String(entry.sessionId ?? ''),
295
+ sessionTitle: String(entry.sessionTitle ?? ''),
296
+ maskPath,
297
+ videoName: frame?.videoName ?? '',
298
+ videoRelPath: frame?.videoRelPath ?? '',
299
+ timecode: frame?.timecode ?? '',
300
+ frameMs: frame?.frameMs ?? 0,
301
+ note: fb.note,
302
+ annotationCount: fb.annotationCount,
303
+ })
304
+ }
305
+
306
+ return {
307
+ schema: MANIFEST_SCHEMA,
308
+ generatedAt: Date.now(),
309
+ generatedAtText: formatLocalTime(Date.now()),
310
+ scope: String(options.scope ?? ''),
311
+ kind: String(options.kind ?? ''),
312
+ summary: {
313
+ total: picked.length,
314
+ returned: items.length,
315
+ byCategory,
316
+ withMask,
317
+ fromVideo,
318
+ totalBytes,
319
+ totalBytesText: formatBytes(totalBytes),
320
+ probedCount: needProbe.length,
321
+ },
322
+ truncated,
323
+ items,
324
+ }
325
+ }
326
+
327
+ /** CSV 的列名(中文,给客户看的)。 */
328
+ const CSV_COLUMNS = [
329
+ '序号', '文件名', '相对路径', '分类', '尺寸', '体积',
330
+ '修改时间', '来源对话', '来源视频', '时间码', '遮罩', '备注',
331
+ ]
332
+
333
+ /**
334
+ * 序列化成 CSV。
335
+ *
336
+ * **BOM 不能省**:Excel 双击打开 CSV 时不会探测 UTF-8,没有 `EF BB BF`
337
+ * 就按系统 ANSI(中文环境是 GBK)解析,中文全变乱码。
338
+ */
339
+ export function manifestToCsv(manifest, options = {}) {
340
+ const items = Array.isArray(manifest?.items) ? manifest.items : []
341
+ const withNotes = options.withNotes === true
342
+ const columns = withNotes ? CSV_COLUMNS : CSV_COLUMNS.slice(0, -1)
343
+ const lines = [columns.join(',')]
344
+ for (const it of items) {
345
+ const size = it.width > 0 && it.height > 0 ? `${it.width}×${it.height}` : ''
346
+ const cells = [
347
+ it.index, it.name, it.relPath, it.categoryText, size, it.bytesText,
348
+ it.mtimeText, it.sessionTitle, it.videoName, it.timecode,
349
+ it.maskPath === '' ? '' : '有',
350
+ ]
351
+ if (withNotes) cells.push(it.note)
352
+ lines.push(cells.map(csvCell).join(','))
353
+ }
354
+ // 行尾用 CRLF:RFC 4180 的要求,也是 Excel 最保险的形态
355
+ return `\ufeff${lines.join('\r\n')}\r\n`
356
+ }
357
+
358
+ /** 序列化成 JSON。**不加 BOM** —— 加了 JSON.parse 会直接拒收。 */
359
+ export function manifestToJson(manifest) {
360
+ return `${JSON.stringify(manifest, null, 2)}\n`
361
+ }
362
+
363
+ /**
364
+ * 生成落盘文件名(不含扩展名):`交付清单_20261125-1043_定稿_8张`。
365
+ * 只保留 Windows 允许的字符;分类用中文名,客户一眼能看懂。
366
+ */
367
+ export function manifestFileBase(manifest, options = {}) {
368
+ const at = Number(manifest?.generatedAt) || Date.now()
369
+ const d = new Date(at)
370
+ const stamp = `${d.getFullYear()}${pad2(d.getMonth() + 1)}${pad2(d.getDate())}`
371
+ + `-${pad2(d.getHours())}${pad2(d.getMinutes())}`
372
+ const cats = Array.isArray(options.categories) ? options.categories : []
373
+ let catText = '全部'
374
+ if (cats.length === 1) catText = CATEGORY_TEXT[cats[0]] ?? '全部'
375
+ else if (cats.length > 1 && cats.length < 4) catText = cats.map((c) => CATEGORY_TEXT[c] ?? c).join('+')
376
+ const count = Array.isArray(manifest?.items) ? manifest.items.length : 0
377
+ const raw = `交付清单_${stamp}_${catText}_${count}张`
378
+ return raw.replace(/[\\/:*?"<>|\r\n]/g, '_')
379
+ }