dsh-gallery 1.4.2 → 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.
package/host/http.js CHANGED
@@ -23,10 +23,10 @@ import {
23
23
  import { scanGallery, resolveSessionScope, parentDirOf } from './scan.js'
24
24
  import { locateSessionDir, readSessionLogText } from './session.js'
25
25
  import { extractSessionTitleFast } from './session-index.js'
26
- import { DEFAULT_SESSIONS_DIR } from './constants.js'
26
+ import { DEFAULT_SESSIONS_DIR, DSH_HOME } from './constants.js'
27
27
  import { makeDerivedName, bumpName, pngBufferFrom, imageBufferFrom, tmpPathFor } from './derive.js'
28
28
  import { readClipboardFilePaths, writeClipboardFilePaths, internalClipboardPaths, pasteFilesIntoDir } from './clipboard.js'
29
- import { buildLinkedMaskIndex, framesFilePath } from './frames.js'
29
+ import { buildLinkedMaskIndex, framesFilePath, readFrames } from './frames.js'
30
30
 
31
31
  /**
32
32
  * 列表请求的短缓存 + 并发去重(加载提速,不改变返回内容与分组顺序)。
@@ -100,6 +100,69 @@ function groupsCacheKey(kind, scope, sessionId, resolved, settingsStamp, derived
100
100
  }
101
101
 
102
102
  /** 只裁每组明细,不动整组计数:counts / fileCount 仍是全量,顶部数字才对得上。 */
103
+ /**
104
+ * 导出目录:放在 DSH_HOME 下,**绝不能**放进扫描根。
105
+ * 清单是 .csv / .json,而扫描扩展名里正好有这两个(host/constants.js 第 106–109 行)——
106
+ * 写进产出目录,下次刷新它就成了一个「文件资产」出现在资产台里,越导越多。
107
+ */
108
+ function manifestExportDir() {
109
+ return path.join(DSH_HOME, 'gallery-exports')
110
+ }
111
+
112
+ /** 同名不覆盖:加 -2 / -3。连点两次导出,两份都留着。 */
113
+ async function uniqueFilePath(dir, filename) {
114
+ const ext = path.extname(filename)
115
+ const stem = filename.slice(0, filename.length - ext.length)
116
+ let candidate = path.join(dir, filename)
117
+ for (let i = 2; i <= 99; i += 1) {
118
+ try {
119
+ await fsp.access(candidate)
120
+ } catch {
121
+ return candidate
122
+ }
123
+ candidate = path.join(dir, `${stem}-${i}${ext}`)
124
+ }
125
+ return path.join(dir, `${stem}-${Date.now()}${ext}`)
126
+ }
127
+
128
+ /**
129
+ * 收集「某个视图下的全部条目」。
130
+ * categoryPaths(按分类圈选)与 exportManifest(导出清单)都走这里 ——
131
+ * 两处各写一份,迟早出现「圈中 300 张、导出只有 60 张」这种对不上的事。
132
+ */
133
+ async function collectAllEntries(config, kind, scope, sessionId, optsResolved, settingsStamp, derived) {
134
+ const entries = []
135
+ let truncated = false
136
+ if (scope === 'global') {
137
+ const gKey = groupsCacheKey(kind, scope, sessionId, optsResolved, settingsStamp, derived)
138
+ const hit = groupsFullCache.get(gKey)
139
+ if (hit !== undefined && Date.now() - hit.at < GROUPS_FULL_CACHE_MS) {
140
+ for (const g of hit.groups) {
141
+ for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
142
+ }
143
+ } else {
144
+ const fresh = await scanGallery(config, kind, scope, sessionId, 1)
145
+ const groups = Array.isArray(fresh?.groups) ? fresh.groups : []
146
+ groupsFullCache.set(gKey, { at: Date.now(), groups })
147
+ pruneGroupsFullCache(Date.now())
148
+ for (const g of groups) {
149
+ for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
150
+ }
151
+ for (const f of (Array.isArray(fresh?.items) ? fresh.items : [])) entries.push(f)
152
+ }
153
+ } else {
154
+ // 5000 是这一路的上限:单个对话的产出远到不了这个量
155
+ const full = await scanGallery(config, kind, scope, sessionId, 1, { maxItems: 5000 })
156
+ const got = Array.isArray(full?.items) ? full.items : []
157
+ for (const f of got) entries.push(f)
158
+ for (const g of (Array.isArray(full?.groups) ? full.groups : [])) {
159
+ for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
160
+ }
161
+ if (got.length >= 5000) truncated = true
162
+ }
163
+ return { entries, truncated }
164
+ }
165
+
103
166
  function slimGroups(value, pageSize) {
104
167
  if (!Array.isArray(value?.groups)) return value
105
168
  return {
@@ -127,15 +190,19 @@ let changeTracker = null
127
190
  export function setChangeTracker(t) { changeTracker = t }
128
191
 
129
192
  import { MARK_ACTIONS, readMarks, writeMarks, setMark, setMarksBatch, marksFilePath } from './marks.js'
130
- import { readFeedback, setFeedback, setFeedbackBatch, ackFeedback, clearFeedback } from './feedback.js'
193
+ import { readFeedback, setFeedback, setFeedbackBatch, ackFeedback, clearFeedback, feedbackFilePath } from './feedback.js'
131
194
  // 阶段 3 / C1:记下「人正在看哪张图」,单独一份临时状态文件
132
- import { writeContext, writePanel } from './context.js'
195
+ import { writeContext, writePanel, readState, contextFilePath } from './context.js'
133
196
  // v0.16.4 A 档:把待处理反馈渲染成成稿文本(纯函数,不碰落盘数据)
134
197
  import { makeFeedback, renderFeedbackText } from './feedback-text.js'
135
198
  import { LABEL_CATEGORIES, readLabels, setLabel, setLabelsBatch, deleteLabels, labelsFilePath } from './labels.js'
136
199
  import {
137
200
  registerFrame, deleteFrames, frameTimecode, makeFrameName, makeMaskName, maskPolygonMeta,
138
201
  } from './frames.js'
202
+ // v1.5.0:交付清单。一个内核两个出口 —— 导出(这里)与 gallery_manifest 工具(tools.js)
203
+ // 共用 manifest.js,保证「您看到的清单」和「我读到的清单」永远是同一份数字。
204
+ import { writeFileAtomic } from './atomic.js'
205
+ import { buildManifest, manifestToCsv, manifestToJson, manifestFileBase } from './manifest.js'
139
206
 
140
207
  /** reveal 相关的排查日志(失败/异常时便于定位,不影响功能)。 */
141
208
  /**
@@ -711,36 +778,10 @@ export function registerOpsRoute(ctx, config) {
711
778
  try { settingsStamp = (await fsp.stat(optsResolved.settingsFile)).mtimeMs } catch { /* 文件还不存在 */ }
712
779
  const derived = await derivedStamp(optsResolved)
713
780
 
714
- const entries = []
715
- let truncated = false
716
-
717
- if (scope === 'global') {
718
- const gKey = groupsCacheKey(kind, scope, sessionId, optsResolved, settingsStamp, derived)
719
- const hit = groupsFullCache.get(gKey)
720
- if (hit !== undefined && Date.now() - hit.at < GROUPS_FULL_CACHE_MS) {
721
- for (const g of hit.groups) {
722
- for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
723
- }
724
- } else {
725
- const fresh = await scanGallery(config, kind, scope, sessionId, 1)
726
- const groups = Array.isArray(fresh?.groups) ? fresh.groups : []
727
- groupsFullCache.set(gKey, { at: Date.now(), groups })
728
- pruneGroupsFullCache(Date.now())
729
- for (const g of groups) {
730
- for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
731
- }
732
- for (const f of (Array.isArray(fresh?.items) ? fresh.items : [])) entries.push(f)
733
- }
734
- } else {
735
- // 5000 是这一路的上限:单个对话的产出远到不了这个量
736
- const full = await scanGallery(config, kind, scope, sessionId, 1, { maxItems: 5000 })
737
- const got = Array.isArray(full?.items) ? full.items : []
738
- for (const f of got) entries.push(f)
739
- for (const g of (Array.isArray(full?.groups) ? full.groups : [])) {
740
- for (const f of (Array.isArray(g?.files) ? g.files : [])) entries.push(f)
741
- }
742
- if (got.length >= 5000) truncated = true
743
- }
781
+ // 与 exportManifest 共用同一个收集函数:圈中多少张,导出的就得是多少张
782
+ const collected = await collectAllEntries(config, kind, scope, sessionId, optsResolved, settingsStamp, derived)
783
+ const entries = collected.entries
784
+ const truncated = collected.truncated
744
785
 
745
786
  const paths = []
746
787
  const seen = new Set()
@@ -763,6 +804,197 @@ export function registerOpsRoute(ctx, config) {
763
804
 
764
805
  }
765
806
 
807
+ // v1.5.0:导出交付清单。落 CSV / JSON,给人看、进 Excel 做物料表。
808
+ // 与 gallery_manifest 工具共用 buildManifest —— 两边数字永远一致。
809
+ if (op === 'exportManifest') {
810
+
811
+ try {
812
+
813
+ const kind = body?.kind === 'file' ? 'file'
814
+ : body?.kind === 'media' ? 'media'
815
+ : 'image'
816
+ const scope = body?.scope === 'session' ? 'session' : 'global'
817
+ const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : ''
818
+ const format = body?.format === 'json' ? 'json'
819
+ : body?.format === 'both' ? 'both' : 'csv'
820
+ const allowed = ['final', 'input', 'intermediate', 'unknown']
821
+ const categories = Array.isArray(body?.categories)
822
+ ? body.categories.map((c) => String(c ?? '')).filter((c) => allowed.includes(c))
823
+ : []
824
+ const relPaths = Array.isArray(body?.relPaths)
825
+ ? body.relPaths.map((p) => String(p ?? '')).filter((p) => p !== '')
826
+ : []
827
+ const includeNotes = body?.includeNotes !== false
828
+
829
+ const optsResolved = resolveOptions(config)
830
+ let settingsStamp = 0
831
+ try { settingsStamp = (await fsp.stat(optsResolved.settingsFile)).mtimeMs } catch { /* 还没有设置文件 */ }
832
+ const derived = await derivedStamp(optsResolved)
833
+
834
+ const collected = await collectAllEntries(config, kind, scope, sessionId, optsResolved, settingsStamp, derived)
835
+
836
+ // 四个登记一次读齐:补「来源视频 / 时间码」「是否人工改过」「反馈备注」「配套遮罩」。
837
+ // 遮罩必须走 buildLinkedMaskIndex:扫描条目里没有 maskPath 字段,
838
+ // 只有这个索引知道哪张原图配哪张遮罩图。
839
+ const [labelsDoc, framesDoc, feedbackDoc, maskIndex] = await Promise.all([
840
+ readLabels(optsResolved.settingsFile),
841
+ readFrames(optsResolved.settingsFile),
842
+ readFeedback(optsResolved.settingsFile, optsResolved),
843
+ buildLinkedMaskIndex(optsResolved.settingsFile),
844
+ ])
845
+
846
+ const manifest = await buildManifest({
847
+ entries: collected.entries,
848
+ relPaths,
849
+ categories,
850
+ frames: framesDoc?.frames ?? {},
851
+ labels: labelsDoc?.labels ?? {},
852
+ feedback: feedbackDoc?.feedback ?? {},
853
+ masks: Object.fromEntries(maskIndex ?? []),
854
+ scope,
855
+ kind,
856
+ includeNotes,
857
+ // 显式指名的一批就必须全导(含带「继承 / 共享」角标的);
858
+ // 只有按分类整批扫(未指名)时才排除,避免父子会话重复计数。
859
+ includeInherited: relPaths.length > 0,
860
+ maxItems: 20000, // 全库实测 6930 条,5000 会把尾巴截掉
861
+ })
862
+
863
+ if (manifest.items.length === 0) {
864
+ return json({
865
+ ok: false,
866
+ error: {
867
+ code: 'empty',
868
+ message: '这批没有可导出的文件(可能还没打分类)',
869
+ },
870
+ }, 400)
871
+ }
872
+
873
+ const dir = manifestExportDir()
874
+ const base = manifestFileBase(manifest, { categories })
875
+ const exts = format === 'both' ? ['csv', 'json'] : [format]
876
+ const files = []
877
+ for (const ext of exts) {
878
+ const target = await uniqueFilePath(dir, `${base}.${ext}`)
879
+ const content = ext === 'csv'
880
+ ? manifestToCsv(manifest, { withNotes: includeNotes })
881
+ : manifestToJson(manifest)
882
+ await writeFileAtomic(target, content)
883
+ files.push({ ext, path: target, bytes: Buffer.byteLength(content, 'utf8') })
884
+ }
885
+
886
+ return json({
887
+ ok: true,
888
+ dir,
889
+ base,
890
+ files,
891
+ count: manifest.items.length,
892
+ summary: manifest.summary,
893
+ truncated: manifest.truncated || collected.truncated,
894
+ })
895
+
896
+ } catch (error) {
897
+
898
+ return json({ ok: false, error: { code: 'export-failed', message: String(error?.message ?? error) } }, 500)
899
+
900
+ }
901
+
902
+ }
903
+
904
+ // v1.5.0 隐私:清空本地登记(浏览记录 / 手动标签 / 截帧登记 / 反馈 / 判定标记)。
905
+ // 两阶段:先 dryRun 报数并发一个 digest,确认时必须回传同一个 digest 才动手。
906
+ // 这批数据不可再生(手动标签是人的判断),误触不是「再点一次就好」。
907
+ // **只清登记文件,绝不碰任何资产文件。**
908
+ if (op === 'clearState') {
909
+
910
+ try {
911
+
912
+ const asked = String(body?.scope ?? '')
913
+ const single = ['context', 'labels', 'frames', 'feedback', 'marks']
914
+ const scope = asked === 'annotations' ? 'annotations'
915
+ : (single.includes(asked) ? asked : '')
916
+ if (scope === '') {
917
+ return json({
918
+ ok: false,
919
+ error: { code: 'invalid-scope', message: 'scope 只能是 context / labels / frames / feedback / marks / annotations' },
920
+ }, 400)
921
+ }
922
+
923
+ const optsResolved = resolveOptions(config)
924
+ const settingsFile = optsResolved.settingsFile
925
+ const targets = scope === 'annotations' ? ['labels', 'frames', 'feedback', 'marks'] : [scope]
926
+
927
+ const counts = {}
928
+ for (const name of targets) {
929
+ try {
930
+ if (name === 'context') {
931
+ const st = await readState(settingsFile)
932
+ counts.context = (Array.isArray(st?.recent) ? st.recent.length : 0) + ((st?.item ?? null) === null ? 0 : 1)
933
+ } else if (name === 'labels') {
934
+ const doc = await readLabels(settingsFile)
935
+ counts.labels = Object.keys(doc?.labels ?? {}).length
936
+ } else if (name === 'frames') {
937
+ const doc = await readFrames(settingsFile)
938
+ counts.frames = Object.keys(doc?.frames ?? {}).length
939
+ } else if (name === 'feedback') {
940
+ const doc = await readFeedback(settingsFile, optsResolved)
941
+ counts.feedback = Object.keys(doc?.feedback ?? {}).length
942
+ } else if (name === 'marks') {
943
+ const doc = await readMarks(settingsFile)
944
+ counts.marks = Object.keys(doc?.marks ?? {}).length
945
+ }
946
+ } catch {
947
+ counts[name] = 0
948
+ }
949
+ }
950
+
951
+ const digest = createHash('sha1')
952
+ .update(JSON.stringify([scope, counts]))
953
+ .digest('hex')
954
+ .slice(0, 12)
955
+
956
+ if (body?.dryRun !== false) {
957
+ return json({ ok: true, dryRun: true, scope, counts, digest })
958
+ }
959
+ if (String(body?.digest ?? '') !== digest) {
960
+ return json({
961
+ ok: false,
962
+ error: { code: 'digest-mismatch', message: '这期间登记有变化,请重新确认后再清空' },
963
+ }, 409)
964
+ }
965
+
966
+ const cleared = {}
967
+ for (const name of targets) {
968
+ try {
969
+ if (name === 'context') {
970
+ // 浏览记录是临时状态文件,直接删;读路径对「文件不存在」本来就是容错的
971
+ await fsp.rm(contextFilePath(settingsFile), { force: true })
972
+ cleared.context = counts.context ?? 0
973
+ } else {
974
+ const file = name === 'labels' ? labelsFilePath(settingsFile)
975
+ : name === 'frames' ? framesFilePath(settingsFile)
976
+ : name === 'feedback' ? feedbackFilePath(settingsFile)
977
+ : marksFilePath(settingsFile)
978
+ // 写回空结构而不是删文件:保留 schema 与文件权限,读侧无需处理「缺失」
979
+ await writeFileAtomic(file, JSON.stringify({ schema: 1, [name]: {} }, null, 2))
980
+ cleared[name] = counts[name] ?? 0
981
+ }
982
+ } catch (error) {
983
+ cleared[name] = -1
984
+ LOG_RESOLVE('clearState: 单项失败', { name, message: String(error?.message ?? error) })
985
+ }
986
+ }
987
+
988
+ return json({ ok: true, dryRun: false, scope, cleared, counts })
989
+
990
+ } catch (error) {
991
+
992
+ return json({ ok: false, error: { code: 'clear-failed', message: String(error?.message ?? error) } }, 500)
993
+
994
+ }
995
+
996
+ }
997
+
766
998
  if (op === 'groupMore') {
767
999
  try {
768
1000
  const kind = body?.kind === 'file' ? 'file'