dsh-paper-workbench 1.1.1 → 1.2.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,348 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 默认只读、离线全库检查;stdout 始终为 JSON。不会调用云端解析/OCR。
4
+ * node scripts/audit-library.mjs --data=<库目录> [--id=<id>] [--rebuild]
5
+ * --rebuild 的逐篇备份及可恢复进度位于 <库>/.library-audit/,失败不删除历史 revision。
6
+ */
7
+ import fs from 'node:fs/promises'
8
+ import { createReadStream } from 'node:fs'
9
+ import { createHash, randomUUID } from 'node:crypto'
10
+ import path from 'node:path'
11
+ import os from 'node:os'
12
+ import { fileURLToPath } from 'node:url'
13
+ import { spawnSync } from 'node:child_process'
14
+ import { createLayoutArchive, fingerprintPdf } from '../lib/layout-archive.js'
15
+ import { qualitySummary } from '../lib/layout-ir.js'
16
+ import { LAYOUT_BUILD, LAYOUT_VERSION } from '../lib/layout.js'
17
+
18
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
19
+ const ID = /^[a-z0-9][a-z0-9._-]{0,79}$/
20
+ const HASH = /^[a-f0-9]{64}$/
21
+ const args = process.argv.slice(2)
22
+ const options = { data: process.env.DSH_PAPER_WORKBENCH_DATA || path.join(os.homedir(), '.dsh', 'paper-workbench'), ids: [], rebuild: false }
23
+ let argumentError = ''
24
+ for (let i = 0; i < args.length; i++) {
25
+ const arg = args[i]
26
+ if ((arg === '--data' || arg === '--id') && (!args[i + 1] || args[i + 1].startsWith('--'))) { argumentError = '参数缺少值:' + arg; break }
27
+ if (arg === '--rebuild') options.rebuild = true
28
+ else if (arg === '--help' || arg === '-h') options.help = true
29
+ else if (arg === '--data') options.data = args[++i]
30
+ else if (arg.startsWith('--data=')) options.data = arg.slice(7)
31
+ else if (arg === '--id') options.ids.push(args[++i])
32
+ else if (arg.startsWith('--id=')) options.ids.push(arg.slice(5))
33
+ else { argumentError = '未知参数:' + arg; break }
34
+ }
35
+ const data = path.resolve(options.data || '')
36
+ process.env.DSH_PAPER_WORKBENCH_DATA = data
37
+ const { DOC_VERSION, buildDoc, buildLayoutDoc, outlineFingerprint, writeRebuiltDoc } = await import('../lib/doc.js')
38
+ const store = await import('../lib/store.js')
39
+ const paperFile = (id, name) => {
40
+ if (!ID.test(id)) throw new Error('非法的论文 id:' + id)
41
+ return path.join(data, 'papers', id, name)
42
+ }
43
+ const archive = createLayoutArchive({ store: { paperFile } })
44
+ async function read(file, fallback = null) {
45
+ try { return JSON.parse(await fs.readFile(file, 'utf8')) }
46
+ catch (error) { if (error.code === 'ENOENT') return fallback; throw error }
47
+ }
48
+ const names = async dir => fs.readdir(dir).catch(error => { if (error.code === 'ENOENT') return []; throw error })
49
+ const coverage = (values, total) => {
50
+ const represented = [...new Set(values)].sort((a, b) => a - b)
51
+ const missing = Array.from({ length: total }, (_, i) => i + 1).filter(n => !represented.includes(n))
52
+ const invalid = values.filter(n => !Number.isSafeInteger(n) || n < 1 || n > total)
53
+ return { expected: total, represented, missing, invalid, complete: total > 0 && missing.length === 0 && invalid.length === 0 }
54
+ }
55
+ async function sha1(file) {
56
+ const hash = createHash('sha1')
57
+ for await (const chunk of createReadStream(file)) hash.update(chunk)
58
+ return hash.digest('hex')
59
+ }
60
+ async function pdfCommand(file, action = 'info') {
61
+ // lib/pdf.findPython() 读取配置时会 ensureDirs;审计走同一 Python CLI,避免隐式写入。
62
+ const config = await read(path.join(data, 'config.json'), {})
63
+ const candidates = [...new Set([process.env.DSH_PAPER_PYTHON, process.env.PYTHON, config.python, process.platform === 'win32' ? 'python' : 'python3', 'python'].filter(Boolean))]
64
+ for (const command of candidates) {
65
+ const result = spawnSync(command, [path.join(HERE, '..', 'assets', 'pdf_tool.py'), action], { input: JSON.stringify({ path: file }), encoding: 'utf8', env: { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' }, timeout: 60000, maxBuffer: 8 * 1024 * 1024, windowsHide: true })
66
+ if (result.status === 0) {
67
+ const value = JSON.parse(result.stdout)
68
+ if (value.ok && (action !== 'info' || Number.isSafeInteger(value.pages) && value.pages > 0)) return value
69
+ }
70
+ }
71
+ throw new Error('无法离线读取 PDF 页数;请设置 DSH_PAPER_PYTHON 为安装了 PyMuPDF 的解释器')
72
+ }
73
+ async function auditPaper(id, indexed = {}) {
74
+ const issues = []
75
+ const add = (code, state = 'invalid', detail = '') => issues.push({ code, state, detail })
76
+ const load = async (name, fallback = null) => {
77
+ try { return await read(paperFile(id, name), fallback) }
78
+ catch (error) { add('invalid-' + name, 'invalid', error.message); return fallback }
79
+ }
80
+ const storedMeta = await load('meta.json')
81
+ const meta = storedMeta || indexed
82
+ if (!storedMeta) add('missing-meta', 'missing')
83
+ const pdf = { exists: false }
84
+ for (const file of [paperFile(id, 'paper.pdf'), meta.srcPath && path.resolve(meta.srcPath)].filter(Boolean)) {
85
+ const stat = await fs.stat(file).catch(error => { if (error.code === 'ENOENT') return null; throw error })
86
+ if (!stat?.isFile() || stat.size === 0) continue
87
+ pdf.exists = true
88
+ try {
89
+ // PyMuPDF 也能识别非 PDF 格式;先确认来源确实是 PDF。
90
+ const handle = await fs.open(file, 'r')
91
+ try {
92
+ const header = Buffer.alloc(1024)
93
+ const { bytesRead } = await handle.read(header, 0, header.length, 0)
94
+ if (!header.subarray(0, bytesRead).includes('%PDF-')) throw new Error('来源文件不是有效的 PDF,请补齐原件')
95
+ } finally { await handle.close() }
96
+ Object.assign(pdf, await fingerprintPdf(file), { sha1: await sha1(file), pages: (await pdfCommand(file)).pages })
97
+ } catch (error) { add('invalid-pdf', 'invalid', error.message) }
98
+ break
99
+ }
100
+ if (!pdf.exists) add('missing-pdf', 'missing')
101
+ let layout = null
102
+ try { layout = await archive.readPublished(id) } catch (error) { add('invalid-current-revision', 'invalid', error.message) }
103
+ const pointer = await load('layout-data/current.json')
104
+ const rawFiles = (await names(paperFile(id, 'layout-data/raw'))).filter(name => HASH.test(name.slice(0, -6)) && name.endsWith('.jsonl'))
105
+ const revisions = (await names(paperFile(id, 'layout-data/revisions'))).filter(name => name.endsWith('.json'))
106
+ const raw = { files: rawFiles.length, verified: [], errors: [] }
107
+ const refs = [...new Set((layout?.pages || []).map(p => p.rawRef?.hash).filter(Boolean))]
108
+ for (const hash of refs.length ? refs : rawFiles.map(name => name.slice(0, -6))) {
109
+ try { await archive.readRaw(id, { hash }); raw.verified.push(hash) }
110
+ catch (error) { raw.errors.push({ hash, error: error.message }); add('invalid-raw', 'invalid', hash + ': ' + error.message) }
111
+ }
112
+ if (!rawFiles.length) add('missing-raw', 'missing')
113
+ const total = pdf.pages || Number(meta.pageCount) || layout?.pageCount || 0
114
+ const layoutReport = { exists: Boolean(layout), schemaVersion: layout?.schemaVersion ?? null, build: layout?.build ?? null, revision: layout?.revision ?? null,
115
+ current: pointer, revisions: revisions.length, raw, coverage: coverage((layout?.pages || []).map(p => p.n), total), quality: layout?.quality?.status || null }
116
+ if (!layout) add('missing-layout', 'missing')
117
+ else {
118
+ if (layout.version !== LAYOUT_VERSION || layout.schemaVersion !== 2 || layout.build !== LAYOUT_BUILD) add('old-layout-build', 'stale')
119
+ if (!layoutReport.coverage.complete || layout.pages.length !== total || layout.pageCount !== total || layout.pages.some(p => p.status === 'failed')) add('incomplete-layout-pages', 'invalid')
120
+ if (pdf.sha256 && layout.source?.sha256 !== pdf.sha256) add('layout-pdf-mismatch', 'stale')
121
+ if (pointer?.revision && pointer.sourceHash !== layout.source?.sha256) add('pointer-source-mismatch', 'invalid')
122
+ if (!['passed', 'needs_review'].includes(layout.quality?.status)) add('invalid-layout-quality', 'invalid')
123
+ }
124
+ const doc = await load('doc.json')
125
+ const docReport = { exists: Boolean(doc), source: doc?.source || null, version: doc?.version ?? null, revision: doc?.revision ?? null,
126
+ coverage: coverage((doc?.paragraphs || []).map(p => p.page), total) }
127
+ if (!doc) add('missing-doc', 'missing')
128
+ else {
129
+ if (doc.version !== DOC_VERSION || !['layout', 'pdf-text', 'ocr', 'synthetic'].includes(doc.source)) add('old-doc-version', 'stale')
130
+ if (doc.parserBuild !== LAYOUT_BUILD) add('old-doc-parser', 'stale')
131
+ if (doc.pdf?.sha1 && pdf.sha1 && doc.pdf.sha1 !== pdf.sha1) add('doc-pdf-mismatch', 'stale')
132
+ if (doc.outlineHash !== outlineFingerprint(meta.outline)) add('old-doc-outline', 'stale')
133
+ if (layout && (doc.source !== 'layout' || (doc.revision || null) !== (layout.revision || null) || doc.layoutBuild !== LAYOUT_BUILD)) add('old-doc-layout', 'stale')
134
+ if (!Array.isArray(doc.paragraphs) || !doc.paragraphs.length || !Array.isArray(doc.sections)) add('invalid-doc-structure', 'invalid')
135
+ if (!docReport.coverage.complete) add('doc-page-coverage-gap', 'informational', '跨页段落/纯图页也可能没有起始段落;缺页需对原页检查')
136
+ }
137
+ const quality = qualitySummary(layout?.quality?.issues || [])
138
+ const status = ['invalid', 'missing', 'stale'].find(state => issues.some(i => i.state === state)) || (layout?.quality?.status === 'needs_review' ? 'needs_review' : 'complete')
139
+ return { id, title: meta.title || '', status, pdf, layout: layoutReport, doc: docReport, issues, quality }
140
+ }
141
+ async function discover() {
142
+ const indexed = await read(path.join(data, 'index.json'), { papers: [] })
143
+ const records = new Map((indexed.papers || []).filter(p => ID.test(p.id)).map(p => [p.id, p]))
144
+ const dirs = await fs.readdir(path.join(data, 'papers'), { withFileTypes: true }).catch(error => { if (error.code === 'ENOENT') return []; throw error })
145
+ for (const dir of dirs) if (dir.isDirectory() && ID.test(dir.name) && !records.has(dir.name)) records.set(dir.name, { id: dir.name })
146
+ for (const id of options.ids) {
147
+ if (!ID.test(id)) throw new Error('非法的论文 id:' + id)
148
+ if (!records.has(id)) records.set(id, { id })
149
+ }
150
+ return [...records].filter(([id]) => !options.ids.length || options.ids.includes(id)).sort(([a], [b]) => a.localeCompare(b))
151
+ }
152
+ const WORK = path.join(data, '.library-audit')
153
+ const MANIFEST = path.join(WORK, 'manifest.json')
154
+ const MUTABLE = ['layout-data/current.json', 'layout.json', 'doc.json', 'meta.json']
155
+ const bytesHash = bytes => createHash('sha256').update(bytes).digest('hex')
156
+ async function atomic(file, bytes) {
157
+ await fs.mkdir(path.dirname(file), { recursive: true })
158
+ const temp = file + '.' + randomUUID() + '.tmp'
159
+ try { await fs.writeFile(temp, bytes); await fs.rename(temp, file) }
160
+ finally { await fs.rm(temp, { force: true }).catch(() => {}) }
161
+ }
162
+ const saveManifest = value => atomic(MANIFEST, JSON.stringify(value, null, 2) + '\n')
163
+ async function assertContained(file) {
164
+ const root = await fs.realpath(data)
165
+ let probe = path.resolve(file)
166
+ while (true) {
167
+ try {
168
+ const resolved = await fs.realpath(probe)
169
+ if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new Error('路径越出所选库目录,拒绝重建:' + file)
170
+ return
171
+ } catch (error) {
172
+ if (error.code !== 'ENOENT') throw error
173
+ const parent = path.dirname(probe)
174
+ if (parent === probe) throw error
175
+ probe = parent
176
+ }
177
+ }
178
+ }
179
+ async function assertPaperScope(id) {
180
+ for (const name of ['', 'layout-data', 'layout-data/raw', 'layout-data/revisions', 'layout-data/inputs', 'layout-data/legacy', ...MUTABLE]) await assertContained(paperFile(id, name))
181
+ await assertContained(path.join(WORK, 'backups'))
182
+ }
183
+ async function backup(id) {
184
+ await assertPaperScope(id)
185
+ const dir = path.join('backups', randomUUID(), id), files = {}
186
+ for (const name of MUTABLE) {
187
+ const bytes = await fs.readFile(paperFile(id, name)).catch(error => { if (error.code === 'ENOENT') return null; throw error })
188
+ files[name] = bytes === null ? { exists: false } : { exists: true, sha256: bytesHash(bytes) }
189
+ if (bytes !== null) await atomic(path.join(WORK, dir, name), bytes)
190
+ }
191
+ return { dir, files, annotations: await store.readAnnotations(id) }
192
+ }
193
+ async function restore(id, saved) {
194
+ await assertPaperScope(id)
195
+ const dir = path.resolve(WORK, saved?.dir || '')
196
+ if (!dir.startsWith(path.join(WORK, 'backups') + path.sep) || !saved?.files) throw new Error('恢复备份路径不合法,拒绝修改数据')
197
+ await assertContained(dir)
198
+ const buffers = new Map()
199
+ for (const name of MUTABLE) {
200
+ const file = saved.files[name]
201
+ if (typeof file?.exists !== 'boolean') throw new Error('恢复清单不完整:' + name)
202
+ const bytes = file.exists ? await fs.readFile(path.join(dir, name)) : null
203
+ if (bytes !== null && bytesHash(bytes) !== file.sha256) throw new Error('恢复备份 hash 校验失败:' + name)
204
+ buffers.set(name, bytes)
205
+ }
206
+ // 先校验全部备份,再恢复权威指针;历史 raw/revision 只增不删。
207
+ for (const name of [...MUTABLE].reverse()) {
208
+ const bytes = buffers.get(name)
209
+ if (bytes === null) await fs.rm(paperFile(id, name), { force: true })
210
+ else await atomic(paperFile(id, name), bytes)
211
+ }
212
+ if (Array.isArray(saved.annotations) && saved.annotations.length) await store.saveAnnotations(id, saved.annotations)
213
+ }
214
+ async function takeLock() {
215
+ await assertContained(WORK)
216
+ await fs.mkdir(WORK, { recursive: true })
217
+ const file = path.join(WORK, 'lock.json')
218
+ try { const handle = await fs.open(file, 'wx'); await handle.writeFile(JSON.stringify({ pid: process.pid })); await handle.close() }
219
+ catch (error) {
220
+ if (error.code !== 'EEXIST') throw error
221
+ const previous = await read(file)
222
+ if (!Number.isSafeInteger(previous?.pid) || previous.pid <= 0) throw new Error('审计写锁损坏,请人工检查 .library-audit/lock.json')
223
+ try { process.kill(previous.pid, 0); throw new Error('另一进程仍在重建文库:' + previous.pid) }
224
+ catch (probe) { if (probe.code !== 'ESRCH') throw probe }
225
+ await fs.rm(file)
226
+ return takeLock()
227
+ }
228
+ return () => fs.rm(file, { force: true })
229
+ }
230
+ async function rebuildPaper(paper, manifest) {
231
+ const previous = manifest.papers[paper.id]
232
+ const needsLayout = !paper.layout.exists || paper.layout.build !== LAYOUT_BUILD || paper.layout.schemaVersion !== 2 || !paper.layout.coverage.complete
233
+ const needsDoc = !paper.doc.exists || paper.issues.some(i => /doc/.test(i.code) && i.state !== 'informational')
234
+ let blocked = ''
235
+ if (!paper.pdf.sha256) blocked = '原 PDF 缺失或无法校验,无法安全关联 raw'
236
+ else if (paper.issues.some(i => i.code === 'layout-pdf-mismatch')) blocked = 'PDF 内容已改变,旧 raw 不能用于新 PDF;需云端重新解析'
237
+ else if (!paper.layout.exists || paper.layout.schemaVersion !== 2) blocked = '缺少 schemaVersion 2 几何页证据,现有离线重建器不支持;需云端解析'
238
+ else if (!paper.layout.raw.verified.length && !paper.layout.raw.errors.length) blocked = '缺少可校验的 raw,需云端重新解析,未执行任何云端请求'
239
+ else if (!paper.layout.raw.files) blocked = '缺少 raw 文件,需云端重新解析,未执行任何云端请求'
240
+ if (blocked) {
241
+ const operation = { status: 'needs-cloud', reason: blocked, attempts: previous?.attempts || 0 }
242
+ if (needsDoc && paper.pdf.sha256) {
243
+ operation.status = 'running'
244
+ operation.attempts += 1
245
+ operation.backup = await backup(paper.id)
246
+ manifest.papers[paper.id] = operation
247
+ await saveManifest(manifest)
248
+ try {
249
+ const meta = await read(paperFile(paper.id, 'meta.json'), { id: paper.id })
250
+ let text = await read(paperFile(paper.id, 'text.json')).catch(() => null)
251
+ if (!text?.source || text.source.size !== paper.pdf.size || Math.round(text.source.mtimeMs) !== Math.round(paper.pdf.mtimeMs)) text = await pdfCommand(paper.pdf.path, 'text')
252
+ const doc = buildDoc({ meta, text, outline: meta.outline || [], pdf: { path: paper.pdf.path, sha1: paper.pdf.sha1, bytes: paper.pdf.size, mtimeMs: paper.pdf.mtimeMs } })
253
+ if (doc.source !== 'pdf-text' || doc.degraded || !doc.paragraphs.length) throw new Error('本地文本不足以建立文档;保留旧数据,未请求 OCR')
254
+ if ((await fingerprintPdf(paper.pdf.path)).sha256 !== paper.pdf.sha256) throw new Error('补文档期间 PDF 已变化')
255
+ await writeRebuiltDoc(paper.id, await store.readDoc(paper.id), doc)
256
+ Object.assign(operation, { status: 'needs-cloud', docRebuilt: true, finishedAt: new Date().toISOString() })
257
+ await saveManifest(manifest)
258
+ return { ...await auditPaper(paper.id, meta), operation }
259
+ } catch (error) {
260
+ operation.error = error.message
261
+ try { await restore(paper.id, operation.backup); operation.status = 'needs-cloud'; operation.rolledBack = true }
262
+ catch (rollback) { operation.status = 'recovery-required'; operation.rollbackError = rollback.message }
263
+ }
264
+ }
265
+ manifest.papers[paper.id] = { ...previous, ...operation, at: new Date().toISOString() }
266
+ await saveManifest(manifest)
267
+ return { ...paper, operation }
268
+ }
269
+ if (!needsLayout && !needsDoc) {
270
+ if (!previous) {
271
+ manifest.papers[paper.id] = { status: 'already-current', attempts: 0, at: new Date().toISOString() }
272
+ await saveManifest(manifest)
273
+ }
274
+ return { ...paper, operation: { status: 'already-current' } }
275
+ }
276
+ const operation = { status: 'running', attempts: (previous?.attempts || 0) + 1, at: new Date().toISOString(), backup: await backup(paper.id) }
277
+ manifest.papers[paper.id] = operation
278
+ await saveManifest(manifest)
279
+ try {
280
+ if (paper.layout.raw.errors.length) throw new Error('raw 归档损坏,拒绝离线重建')
281
+ if (needsLayout) {
282
+ const result = spawnSync(process.execPath, [path.join(HERE, 'quality', 'rebuild-layout.mjs'), paper.id, '--data=' + data, '--apply'], { encoding: 'utf8', env: { ...process.env, DSH_PAPER_WORKBENCH_DATA: data, PYTHONUTF8: '1' }, timeout: 10 * 60 * 1000, maxBuffer: 8 * 1024 * 1024, windowsHide: true })
283
+ if (result.status !== 0) throw new Error('离线重建失败:' + (result.stderr || result.error?.message || result.stdout || result.signal).trim())
284
+ }
285
+ const layout = await archive.readPublished(paper.id)
286
+ const meta = await read(paperFile(paper.id, 'meta.json'))
287
+ const currentSource = await fingerprintPdf(paper.pdf.path)
288
+ if (currentSource.sha256 !== paper.pdf.sha256) throw new Error('重建期间 PDF 已变化,已停止发布文档')
289
+ const doc = buildLayoutDoc({ layout, meta, pdf: { path: paper.pdf.path, sha1: paper.pdf.sha1, bytes: currentSource.size, mtimeMs: currentSource.mtimeMs } })
290
+ if (!doc.paragraphs.length) throw new Error('重建文档没有正文段落,保留旧文档')
291
+ await writeRebuiltDoc(paper.id, await store.readDoc(paper.id), doc)
292
+ const after = await auditPaper(paper.id, meta)
293
+ if (after.issues.some(i => i.state === 'invalid' || i.state === 'stale' || i.code === 'missing-doc')) throw new Error('重建后检查未通过:' + after.issues.map(i => i.code).join(', '))
294
+ Object.assign(operation, { status: 'succeeded', revision: layout.revision, finishedAt: new Date().toISOString() })
295
+ await saveManifest(manifest)
296
+ return { ...after, operation }
297
+ } catch (error) {
298
+ operation.status = 'failed'
299
+ operation.error = error.message
300
+ try { await restore(paper.id, operation.backup); operation.rolledBack = true }
301
+ catch (rollback) { operation.status = 'recovery-required'; operation.rollbackError = rollback.message }
302
+ await saveManifest(manifest)
303
+ return { ...paper, operation }
304
+ }
305
+ }
306
+ async function main() {
307
+ if (argumentError || !String(options.data || '').trim()) throw new Error(argumentError || '参数中的库目录不能为空')
308
+ if (options.help) { console.log('用法:node scripts/audit-library.mjs --data=<目录> [--id=<id>] [--rebuild];默认只读,始终离线。重建前请停止文库并发写入;进度和恢复备份位于 .library-audit。'); return }
309
+ const papers = [], records = await discover()
310
+ let release, manifest
311
+ try {
312
+ if (options.rebuild) {
313
+ release = await takeLock()
314
+ manifest = await read(MANIFEST, { version: 1, data, papers: {} })
315
+ if (manifest.version !== 1 || manifest.data !== data || !manifest.papers || typeof manifest.papers !== 'object') throw new Error('审计进度清单不兼容,请检查 .library-audit/manifest.json')
316
+ }
317
+ for (const [id, meta] of records) {
318
+ const pending = manifest?.papers[id]
319
+ try {
320
+ if (pending && ['running', 'recovery-required'].includes(pending.status)) {
321
+ await restore(id, pending.backup)
322
+ Object.assign(pending, { status: 'recovered', recoveredAt: new Date().toISOString() })
323
+ await saveManifest(manifest)
324
+ }
325
+ const paper = await auditPaper(id, meta)
326
+ papers.push(options.rebuild ? await rebuildPaper(paper, manifest) : paper)
327
+ } catch (error) {
328
+ const operation = { ...pending, status: pending && ['running', 'recovery-required'].includes(pending.status) ? 'recovery-required' : 'failed', attempts: pending?.attempts || 1, error: error.message }
329
+ if (manifest) { manifest.papers[id] = operation; await saveManifest(manifest) }
330
+ papers.push({ id, title: meta.title || '', status: 'invalid', issues: [{ code: 'paper-io-failure', state: 'invalid', detail: error.message }], quality: { blocking: 0, informational: 0 }, ...(manifest ? { operation } : {}) })
331
+ }
332
+ }
333
+ } finally { if (release) await release() }
334
+ const summary = { total: papers.length, states: {}, quality: { blocking: 0, informational: 0 }, findings: { blocking: 0, informational: 0 } }
335
+ for (const paper of papers) {
336
+ summary.states[paper.status] = (summary.states[paper.status] || 0) + 1
337
+ summary.quality.blocking += paper.quality.blocking
338
+ summary.quality.informational += paper.quality.informational
339
+ for (const issue of paper.issues) summary.findings[issue.state === 'informational' ? 'informational' : 'blocking'] += 1
340
+ }
341
+ if (options.rebuild) {
342
+ summary.operations = {}
343
+ for (const paper of papers) summary.operations[paper.operation.status] = (summary.operations[paper.operation.status] || 0) + 1
344
+ if (papers.some(p => ['failed', 'recovery-required', 'needs-cloud'].includes(p.operation.status))) process.exitCode = 1
345
+ }
346
+ console.log(JSON.stringify({ mode: options.rebuild ? 'rebuild' : 'audit', network: 'disabled', data, ...(options.rebuild ? { manifest: MANIFEST } : {}), expected: { layoutBuild: LAYOUT_BUILD, layoutVersion: LAYOUT_VERSION, docVersion: DOC_VERSION }, papers, summary }, null, 2))
347
+ }
348
+ main().catch(error => { console.log(JSON.stringify({ error: error.message, network: 'disabled' })); process.exitCode = 1 }).finally(() => store.closeDb())
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs/promises'
3
+ import path from 'node:path'
4
+ import { randomUUID } from 'node:crypto'
5
+ import * as store from '../lib/store.js'
6
+ import * as pdf from '../lib/pdf.js'
7
+ import * as ocr from '../lib/ocr.js'
8
+ import { createLayout, LAYOUT_BUILD, LAYOUT_PARTIAL } from '../lib/layout.js'
9
+ import { createLayoutArchive, fingerprintPdf } from '../lib/layout-archive.js'
10
+ import * as doc from '../lib/doc.js'
11
+ import * as figures from '../lib/figures.js'
12
+
13
+ const args = process.argv.slice(2)
14
+ const has = flag => args.includes(flag)
15
+ const work = path.join(store.DATA_ROOT, '.batch-layout')
16
+ const file = path.join(work, 'manifest.json')
17
+ const archive = createLayoutArchive({ store })
18
+ const controller = new AbortController()
19
+ const { signal } = controller
20
+ const pause = () => controller.abort()
21
+ const read = (id, name) => store.readJson(store.paperFile(id, name), null)
22
+ const numbers = pages => pages.map(page => page.n).sort((left, right) => left - right)
23
+ const complete = (pages, total) => pages.length === total && pages.every((page, index) => page === index + 1)
24
+ const fresh = () => ({ status: 'queued', stage: 'inspect', pdf: null, coveredPages: [], jobIds: [], attempts: 0, error: null })
25
+
26
+ async function published(id, source) {
27
+ try {
28
+ const layout = await archive.readPublished(id)
29
+ const pointer = await read(id, 'layout-data/current.json')
30
+ if (layout?.schemaVersion !== 2 || layout.build !== LAYOUT_BUILD || !pointer?.revision || layout.revision !== pointer.revision ||
31
+ pointer.sourceHash !== source.sha256 || layout.source?.sha256 !== source.sha256 || layout.pageCount !== source.pages ||
32
+ !complete(numbers(layout.pages), source.pages) || layout.pages.some(page => page.status === 'failed') ||
33
+ !['passed', 'needs_review'].includes(layout.quality?.status) || !layout.rawRefs?.length) return null
34
+ for (const ref of layout.rawRefs) await archive.readRaw(id, ref)
35
+ return layout
36
+ } catch { return null }
37
+ }
38
+
39
+ async function derived(id, layout, source) {
40
+ const cached = await read(id, 'doc.json')
41
+ const images = await read(id, 'figures.json')
42
+ const projection = await read(id, 'layout.json')
43
+ return JSON.stringify(projection) === JSON.stringify(layout) && cached?.version === doc.DOC_VERSION &&
44
+ cached.source === 'layout' && cached.revision === layout.revision && cached.parserBuild === LAYOUT_BUILD &&
45
+ cached.paragraphs?.length > 0 && Array.isArray(cached.sections) && images?.version === figures.FIGURES_VERSION &&
46
+ Array.isArray(images.figures) && images.source?.size === source.size && Math.round(images.source?.mtimeMs) === source.mtimeMs &&
47
+ (!layout.figures?.length || images.layoutAt === layout.at && images.figures.length === layout.figures.length)
48
+ }
49
+
50
+ async function backup(id) {
51
+ const dir = path.join(work, 'backups', randomUUID(), store.assertId(id))
52
+ for (const name of ['layout-data/current.json', 'layout.json', 'layout.partial.json', 'meta.json', 'doc.json', 'figures.json', 'ocr.md']) {
53
+ const destination = path.join(dir, name)
54
+ await fs.mkdir(path.dirname(destination), { recursive: true })
55
+ try { await fs.copyFile(store.paperFile(id, name), destination) }
56
+ catch (error) { if (error.code !== 'ENOENT') throw error }
57
+ }
58
+ }
59
+
60
+ async function main() {
61
+ if (has('--help') || has('-h')) {
62
+ console.log('用法:node scripts/batch-layout.mjs [--resume | --retry-failed] [--concurrency=2] [--refill-existing] [--force] [--no-upgrade-v1] [--dry-run] [--id=<id>]')
63
+ return
64
+ }
65
+ const concurrency = Math.max(1, Math.min(16, Math.trunc(Number(args.find(arg => arg.startsWith('--concurrency='))?.slice(14)) || 2)))
66
+ const ids = args.filter(arg => arg.startsWith('--id=')).map(arg => store.assertId(arg.slice(5)))
67
+ const dry = has('--dry-run')
68
+ let manifest
69
+ try { manifest = JSON.parse(await fs.readFile(file, 'utf8')) }
70
+ catch (error) { if (error.code !== 'ENOENT') throw new Error('批次清单无法读取,请检查 ' + file); manifest = { version: 1, papers: {} } }
71
+ if (manifest?.version !== 1 || !manifest.papers || typeof manifest.papers !== 'object' || Array.isArray(manifest.papers)) throw new Error('不支持的批次清单,请检查 ' + file)
72
+ manifest.papers = Object.assign(Object.create(null), manifest.papers)
73
+ const config = await store.getConfig()
74
+ const token = String(config.ocr?.token || '').trim()
75
+ const selected = (await store.listPapers()).filter(({ id }) => (!ids.length || ids.includes(id)) &&
76
+ (!has('--resume') || Object.hasOwn(manifest.papers, id)) && (!has('--retry-failed') || manifest.papers[id]?.status === 'failed'))
77
+ for (const { id } of selected) manifest.papers[store.assertId(id)] ??= fresh()
78
+ let writes = Promise.resolve()
79
+ const save = () => dry ? Promise.resolve() : (writes = writes.then(() => store.writeJsonAtomic(file, manifest)))
80
+ process.on('SIGINT', pause)
81
+ process.on('SIGTERM', pause)
82
+ const cloud = Object.fromEntries(['submitJob', 'pollJob', 'fetchResults'].map(name => [name, options => ocr[name]({ ...options, maxRetries: 0, signal })]))
83
+ let failed = 0
84
+
85
+ async function processPaper({ id, hasText }) {
86
+ let record = manifest.papers[id]
87
+ try {
88
+ const { path: pdfPath } = await store.resolvePdf(id)
89
+ const source = await fingerprintPdf(pdfPath)
90
+ source.pages = (await pdf.info(pdfPath)).pages
91
+ if (!Number.isSafeInteger(source.pages) || source.pages < 1) throw new Error('无法确认 PDF 页数')
92
+ const same = record.pdf?.sha256 === source.sha256 && record.pdf?.pages === source.pages
93
+ if (!same) record = manifest.papers[id] = fresh()
94
+ record.pdf = { sha256: source.sha256, pages: source.pages }
95
+ let layout = await published(id, source)
96
+ const ocrReady = () => store.readOcr(id).then(text => complete([...text.matchAll(/^## p\.(\d+)\s*$/gm)].map(match => Number(match[1])), source.pages))
97
+ const needsOcr = hasText === false && (!(record.ocrComplete || layout) || !(await ocrReady()))
98
+ const force = has('--force') || record.forcePending === true
99
+ const refill = has('--refill-existing') && layout && !force
100
+ const finish = () => Object.assign(record, { status: 'done', stage: 'complete', error: null, forcePending: false,
101
+ coveredPages: numbers(layout.pages), jobIds: [...new Set([...record.jobIds, ...layout.rawRefs.map(ref => ref.jobId).filter(Boolean)])] })
102
+ if (!needsOcr && layout && !force && !refill && await derived(id, layout, source)) {
103
+ finish(); console.log(`[跳过] ${id} · ${source.pages} 页已校验`); return
104
+ }
105
+ if (has('--no-upgrade-v1') && !force && (await archive.readPublished(id).catch(() => null))?.schemaVersion !== 2 && (await read(id, 'layout.json'))?.blocks) {
106
+ record.status = 'skipped'; record.stage = 'legacy'; return
107
+ }
108
+ if (dry) { console.log(`[干跑] ${id} · ${source.pages} 页 · ${layout && !force ? '离线重建' : '云端解析'}`); return }
109
+ if (record.status === 'failed' && !has('--retry-failed') && !has('--force')) { failed++; console.error(`[待重试] ${id} · ${record.error}`); return }
110
+ signal.throwIfAborted()
111
+ await backup(id)
112
+ if (record.status === 'failed' || has('--force') || record.status === 'done') record.autoRetries = 0
113
+ const partial = await read(id, LAYOUT_PARTIAL)
114
+ const canResume = partial?.source?.sha256 === source.sha256 && !has('--force')
115
+ record.coveredPages = layout ? numbers(layout.pages) : canResume && Array.isArray(partial.pages) ? numbers(partial.pages) : []
116
+ record.status = 'running'
117
+ record.error = null
118
+ record.forcePending = force
119
+ await save()
120
+ const partialPath = store.paperFile(id, LAYOUT_PARTIAL)
121
+ const runner = createLayout({ pdf, ocr: cloud, store: { ...store, async writeJsonAtomic(target, value) {
122
+ if (target === partialPath) value.source = { ...value.source, sha256: source.sha256 }
123
+ await store.writeJsonAtomic(target, value)
124
+ if (target === partialPath) {
125
+ record.coveredPages = numbers(value.pages)
126
+ record.jobIds = [...new Set([...record.jobIds, ...(value.jobs || []), ...(value.pending?.jobId ? [value.pending.jobId] : [])])]
127
+ await save()
128
+ }
129
+ } } })
130
+ if (needsOcr || !layout || force) {
131
+ record.stage = needsOcr ? 'ocr' : 'layout'
132
+ if (!token) throw new Error('请在设置中填写 PaddleOCR Token 后重试')
133
+ for (let retry = 0; ; retry++) {
134
+ record.attempts++
135
+ try {
136
+ signal.throwIfAborted()
137
+ if (needsOcr && !(record.ocrComplete && await ocrReady())) {
138
+ record.stage = 'ocr'; await save()
139
+ if (!record.ocrJobId) {
140
+ const result = await cloud.submitJob({ token, filePath: pdfPath, model: config.ocr.model || ocr.DEFAULT_MODEL,
141
+ optionalPayload: { useDocOrientationClassify: Boolean(config.ocr.orient), useDocUnwarping: false } })
142
+ record.ocrJobId = result.jobId; record.jobIds.push(result.jobId); await save()
143
+ }
144
+ const { jsonUrl } = await cloud.pollJob({ token, jobId: record.ocrJobId })
145
+ const { pages } = await cloud.fetchResults({ jsonUrl, jobId: record.ocrJobId })
146
+ if (!complete(numbers(pages), source.pages)) throw new Error('OCR 返回页覆盖不全,请检查云端结果')
147
+ await store.writeOcr(id, ocr.pagesToMarkdown(pages).markdown)
148
+ record.ocrComplete = true; await save()
149
+ }
150
+ if (!layout || force) {
151
+ record.stage = 'layout'; await save()
152
+ await runner.runLayout(id, { model: 'PP-StructureV3', resume: canResume || retry > 0, signal })
153
+ }
154
+ break
155
+ } catch (error) {
156
+ if (signal.aborted) throw error
157
+ if (/^(OCR 任务失败(job |OCR 返回页覆盖不全|第 \d+-\d+ 页的版面结果不完整)/.test(error.message)) {
158
+ if (record.stage === 'ocr') record.ocrJobId = null
159
+ else {
160
+ const partial = await runner.readPartial(id)
161
+ if (partial?.pending) await store.writeJsonAtomic(partialPath, { ...partial, pending: null })
162
+ }
163
+ }
164
+ if (record.autoRetries || retry >= 1) throw error
165
+ record.autoRetries = 1; await save()
166
+ console.log(`[自动重试] ${id} · ${record.stage}`)
167
+ }
168
+ }
169
+ } else if (refill) {
170
+ record.stage = 'refill'; await save(); await runner.refillText(id)
171
+ }
172
+ signal.throwIfAborted()
173
+ record.stage = 'derived'; record.forcePending = false; await save()
174
+ layout = await published(id, source)
175
+ if (!layout) throw new Error('发布产物未通过 PDF 指纹、页覆盖或原始归档校验')
176
+ if (JSON.stringify(await read(id, 'layout.json')) !== JSON.stringify(layout)) await store.writeJsonAtomic(store.paperFile(id, 'layout.json'), layout)
177
+ await doc.getDoc(id, { rebuild: true })
178
+ await figures.listFigures(id, { refresh: true })
179
+ if (!await derived(id, layout, source)) throw new Error('文档或配图缓存校验失败,请重试')
180
+ finish(); console.log(`[完成] ${id} · ${source.pages} 页`)
181
+ } catch (error) {
182
+ record.status = signal.aborted ? 'paused' : 'failed'
183
+ const message = String(error.message || error)
184
+ record.error = signal.aborted ? null : (token ? message.split(token).join('[已隐藏]') : message)
185
+ if (!signal.aborted) { failed++; console.error(`[失败] ${id} · ${record.error}`) }
186
+ } finally { await save() }
187
+ }
188
+
189
+ try {
190
+ await save()
191
+ console.log(`批次 ${selected.length} 篇 · 并发 ${concurrency} · 数据目录 ${store.DATA_ROOT}`)
192
+ let cursor = 0
193
+ await Promise.all(Array.from({ length: Math.min(concurrency, selected.length) }, async () => {
194
+ while (!signal.aborted && cursor < selected.length) await processPaper(selected[cursor++])
195
+ }))
196
+ if (signal.aborted) { console.log('批次已暂停,可用 --resume 继续'); process.exitCode = 130 }
197
+ else if (failed) process.exitCode = 1
198
+ } finally { process.off('SIGINT', pause); process.off('SIGTERM', pause) }
199
+ }
200
+
201
+ main().catch(error => { console.error('批量版面处理失败:' + error.message); process.exitCode = 1 })
@@ -12,7 +12,7 @@ import os from 'node:os'
12
12
  const args = process.argv.slice(2)
13
13
  const id = args.find(a => !a.startsWith('--'))
14
14
  const dataArg = args.find(a => a.startsWith('--data='))
15
- const dataRoot = dataArg ? dataArg.slice(7) : path.join(os.homedir(), '.dsh', 'paper-workbench')
15
+ const dataRoot = dataArg ? dataArg.slice(7) : process.env.DSH_PAPER_WORKBENCH_DATA || path.join(os.homedir(), '.dsh', 'paper-workbench')
16
16
  const apply = args.includes('--apply')
17
17
  if (!id) {
18
18
  console.error('用法:node scripts/quality/rebuild-layout.mjs <paperId> [--data=<数据根>] [--apply]')
@@ -116,6 +116,11 @@ if (!apply) {
116
116
  process.exit(0)
117
117
  }
118
118
  const input = await archive.readInput(id, layout.revision)
119
+ const previous = await store.readDoc(id)
120
+ const meta = await store.getMeta(id)
121
+ const { buildLayoutDoc, writeRebuiltDoc } = await import('../../lib/doc.js')
119
122
  const result = await archive.publishDerived(id, next, input || {})
120
- await store.clearDocCache(id).catch(() => {})
123
+ const doc = buildLayoutDoc({ layout: await archive.readPublished(id), meta, outline: meta.outline || [], pdf: previous?.pdf || null })
124
+ await writeRebuiltDoc(id, previous, doc)
125
+ await store.closeDb()
121
126
  console.log('已发布新 revision:' + result.revision)