dsh-paper-workbench 1.1.2 → 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,198 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { promises as fs } from 'node:fs'
3
+ import { RESTART_PAUSED_REASON } from './translate-jobs.js'
4
+
5
+ export const ZHPDF_JOB_FILE = 'zhpdf.job.json'
6
+
7
+ export function createZhPdfJobManager({ store, doc, zhpdf, translateJobs }) {
8
+ const records = new Map()
9
+ const runs = new Map()
10
+ const chains = new Map()
11
+ let loading
12
+
13
+ function snapshot(record) {
14
+ return record ? structuredClone(record) : null
15
+ }
16
+
17
+ async function save(record, patch) {
18
+ Object.assign(record, patch, { updatedAt: new Date().toISOString() })
19
+ await store.writeJsonAtomic(store.paperFile(record.paperId, ZHPDF_JOB_FILE), record)
20
+ return snapshot(record)
21
+ }
22
+
23
+ function checkSource(record, check) {
24
+ if (record.sourceHash && record.sourceHash !== check.sourceHash || record.docHash && record.docHash !== check.docHash) {
25
+ throw new Error('源 PDF 或文档在生成流程中发生变化,请检查论文后重新生成中文版')
26
+ }
27
+ }
28
+
29
+ async function inspect(record) {
30
+ const built = await doc.getDoc(record.paperId)
31
+ const check = await zhpdf.inspect(record.paperId, built.doc)
32
+ checkSource(record, check)
33
+ if (record.phase === 'generating' && record.transHash && record.transHash !== check.transHash) throw new Error('生成期间译文已更新,请重新生成中文版')
34
+ const { missingKeys, ...coverage } = check
35
+ await save(record, coverage)
36
+ if (check.issues.length) {
37
+ throw new Error(check.issues.slice(0, 8).map(issue => '第 ' + (issue.page || '?') + ' 页 ' + issue.reason).join(','))
38
+ }
39
+ if (!check.readyBlocks && !check.missingKeys.length) throw new Error('没有可生成的文字,请检查文档与版面解析')
40
+ return { check, document: built.doc }
41
+ }
42
+
43
+ function launch(record, resumeTranslation = false) {
44
+ if (runs.has(record.paperId)) return
45
+ const controller = new AbortController()
46
+ const active = { controller, promise: null }
47
+ runs.set(record.paperId, active)
48
+ active.promise = (async () => {
49
+ try {
50
+ let { check, document } = await inspect(record)
51
+ controller.signal.throwIfAborted()
52
+ if (check.missingKeys.length) {
53
+ let translation = await translateJobs.status(record.paperId)
54
+ if (translation?.status === 'paused') {
55
+ if (resumeTranslation || translation.purpose === 'zhpdf' && translation.error === RESTART_PAUSED_REASON) translation = await translateJobs.resumeJob(translation.id)
56
+ else {
57
+ await save(record, { status: 'paused', phase: 'translating', translationJobId: translation.id, error: '本篇翻译已暂停,点击继续生成中文版以接续' })
58
+ return
59
+ }
60
+ }
61
+ if (translation?.status !== 'running') {
62
+ translation = await translateJobs.startJob({ id: record.paperId, keys: check.missingKeys, titles: true, purpose: 'zhpdf', target: 'zh', ...(record.requestedModel ? { model: record.requestedModel } : {}) })
63
+ record.ownsTranslation = translation.purpose === 'zhpdf'
64
+ } else record.ownsTranslation = translation.purpose === 'zhpdf'
65
+ await save(record, { phase: 'translating', translationJobId: translation.id, model: translation.model || record.model || '' })
66
+ for await (const frame of translateJobs.stream(translation.id, { signal: controller.signal })) {
67
+ if (frame.data?.model) record.model = frame.data.model
68
+ if (frame.event === 'paused') {
69
+ await save(record, { status: 'paused', error: '翻译已暂停,可继续生成中文版' })
70
+ return
71
+ }
72
+ if (frame.event === 'error' && frame.data?.fatal) throw new Error(frame.data.message || '模型翻译失败,请检查设置中的翻译模型')
73
+ }
74
+ controller.signal.throwIfAborted()
75
+ const latest = await inspect(record)
76
+ check = latest.check
77
+ document = latest.document
78
+ if (check.missingKeys.length) {
79
+ const pending = await translateJobs.status(record.paperId)
80
+ if (pending?.status !== 'done') throw new Error('本篇翻译尚未完成,请继续翻译后重试')
81
+ const extra = await translateJobs.startJob({ id: record.paperId, keys: check.missingKeys, titles: true, purpose: 'zhpdf', target: 'zh', ...(record.requestedModel ? { model: record.requestedModel } : {}) })
82
+ await save(record, { translationJobId: extra.id, ownsTranslation: extra.purpose === 'zhpdf' })
83
+ for await (const frame of translateJobs.stream(extra.id, { signal: controller.signal })) {
84
+ if (frame.data?.model) record.model = frame.data.model
85
+ if (frame.event === 'paused') {
86
+ await save(record, { status: 'paused', error: '翻译已暂停,可继续生成中文版' })
87
+ return
88
+ }
89
+ if (frame.event === 'error' && frame.data?.fatal) throw new Error(frame.data.message || '模型翻译失败')
90
+ }
91
+ controller.signal.throwIfAborted()
92
+ const final = await inspect(record)
93
+ check = final.check
94
+ document = final.document
95
+ if (check.missingKeys.length) throw new Error('仍有 ' + check.missingKeys.length + ' 项缺译,请检查翻译任务后重试')
96
+ }
97
+ }
98
+ controller.signal.throwIfAborted()
99
+ await save(record, { phase: 'generating', error: '' })
100
+ const result = await zhpdf.build(record.paperId, { doc: document, sourceHash: record.sourceHash, docHash: record.docHash, transHash: record.transHash, signal: controller.signal })
101
+ const published = await zhpdf.status(record.paperId)
102
+ if (!published.exists || published.stale) throw new Error('中文版产物校验失败,请重新生成')
103
+ await save(record, { status: 'done', phase: 'done', result: { blocks: result.blocks, pages: result.pages }, missingCount: 0, error: '' })
104
+ } catch (error) {
105
+ await save(record, { status: controller.signal.aborted ? 'paused' : 'error', error: controller.signal.aborted ? '已暂停,可继续生成中文版' : error.message }).catch(persistError => {
106
+ record.status = 'error'
107
+ record.error = '任务状态保存失败,请检查磁盘权限 ' + persistError.message
108
+ })
109
+ } finally {
110
+ if (runs.get(record.paperId) === active) runs.delete(record.paperId)
111
+ }
112
+ })()
113
+ }
114
+
115
+ async function ready() {
116
+ if (!loading) loading = (async () => {
117
+ const papers = await store.listPapers()
118
+ for (const paper of papers) {
119
+ const id = store.assertId(paper.id)
120
+ let record
121
+ try { record = JSON.parse(await fs.readFile(store.paperFile(id, ZHPDF_JOB_FILE), 'utf8')) }
122
+ catch (error) { if (error.code === 'ENOENT') continue; throw error }
123
+ if (record.version !== 1 || record.paperId !== id || record.purpose !== 'zhpdf') continue
124
+ records.set(id, record)
125
+ if (record.status === 'running') launch(record)
126
+ }
127
+ })()
128
+ return loading
129
+ }
130
+
131
+ function serialize(id, operation) {
132
+ const previous = chains.get(id) || Promise.resolve()
133
+ const next = previous.catch(() => {}).then(operation)
134
+ chains.set(id, next)
135
+ void next.finally(() => { if (chains.get(id) === next) chains.delete(id) }).catch(() => {})
136
+ return next
137
+ }
138
+
139
+ async function prepare(rawId, options = {}) {
140
+ const id = store.assertId(rawId)
141
+ await ready()
142
+ return serialize(id, async () => {
143
+ const current = records.get(id)
144
+ if (runs.has(id) || current?.status === 'paused') return snapshot(current)
145
+ if (current?.status === 'done') {
146
+ const published = await zhpdf.status(id)
147
+ if (published.exists && !published.stale) return snapshot(current)
148
+ }
149
+ const record = { version: 1, id: 'zj-' + randomUUID(), paperId: id, purpose: 'zhpdf', status: 'running', phase: 'checking', model: '', ...(options.model ? { requestedModel: options.model } : {}), createdAt: new Date().toISOString(), error: '' }
150
+ await save(record)
151
+ records.set(id, record)
152
+ launch(record)
153
+ return snapshot(record)
154
+ })
155
+ }
156
+
157
+ async function status(rawId) {
158
+ await ready()
159
+ const id = store.assertId(rawId)
160
+ const record = snapshot(records.get(id))
161
+ if (record?.status === 'running' && record.translationJobId && record.phase === 'translating') {
162
+ const translation = await translateJobs.status(record.translationJobId)
163
+ if (translation) Object.assign(record, { model: translation.model || record.model, completed: translation.completed, total: translation.total })
164
+ }
165
+ return record
166
+ }
167
+
168
+ async function pause(rawId) {
169
+ const id = store.assertId(rawId)
170
+ await ready()
171
+ return serialize(id, async () => {
172
+ const record = records.get(id)
173
+ if (!record || record.status !== 'running') return snapshot(record)
174
+ const active = runs.get(id)
175
+ active?.controller.abort()
176
+ if (record.ownsTranslation && record.translationJobId) await translateJobs.pauseJob(record.translationJobId)
177
+ await active?.promise
178
+ if (record.status === 'done') return snapshot(record)
179
+ return save(record, { status: 'paused', error: '已暂停,可继续生成中文版' })
180
+ })
181
+ }
182
+
183
+ async function resume(rawId) {
184
+ const id = store.assertId(rawId)
185
+ await ready()
186
+ return serialize(id, async () => {
187
+ const record = records.get(id)
188
+ if (!record) throw new Error('没有待继续的中文版任务,请点击生成中文版')
189
+ if (runs.has(id)) return snapshot(record)
190
+ await inspect(record)
191
+ await save(record, { status: 'running', error: '' })
192
+ launch(record, true)
193
+ return snapshot(record)
194
+ })
195
+ }
196
+
197
+ return { prepare, pause, resume, status, ready }
198
+ }
package/lib/zhpdf.js CHANGED
@@ -3,10 +3,13 @@
3
3
  *
4
4
  * 为什么单独一个模块:它既不是「文档模型」也不是「版面解析」,而是从两者派生出来的一份
5
5
  * 输出文件(`papers/<id>/paper-zh.pdf`)。生成是纯本地操作(PyMuPDF,不上传、不花钱),
6
- * 但要不要生成由用户决定 —— 段落译文缺失时那一段保留原文,所以它是「部分中文」的页面。
6
+ * 只有可安全定位的文字块全部具备译文且全部成功写入,才发布新版文件。
7
7
  */
8
8
  import crypto from 'node:crypto'
9
9
  import { promises as fsp } from 'node:fs'
10
+ import path from 'node:path'
11
+ import { looksLikeByline, paragraphKey, titleKey } from './ai.js'
12
+ import { fingerprintPdf } from './layout-archive.js'
10
13
 
11
14
  /** 文件名(和 paper.pdf 放一起,跟着论文目录走)。 */
12
15
  export const ZH_FILE = 'paper-zh.pdf'
@@ -16,6 +19,7 @@ export const ZH_FILE = 'paper-zh.pdf'
16
19
  * 只能算过期(提示重新生成),不能假装是最新的。
17
20
  */
18
21
  export const ZH_META = 'paper-zh.json'
22
+ const activeBuilds = (globalThis.__pbZhPdfBuilds ||= new Map())
19
23
 
20
24
  /** 译文指纹:只算有内容的条目,按 hash 排序,避免对象键顺序影响结果。 */
21
25
  export function transFingerprint(trans) {
@@ -50,43 +54,166 @@ async function writeMeta(paperFile, id, value) {
50
54
  /** 哪些段落参与替换:正文类都要,公式/图/表不动(图是位图,公式换了会破坏可读性)。 */
51
55
  const REPLACE_KINDS = new Set(['body', 'heading', 'caption', 'list', 'footnote'])
52
56
 
53
- /**
54
- * 从文档模型 + 译文生成 payload。
55
- * 只带「有译文」的段落:没译文的段落保留英文,页面看起来是混排,但不会丢内容。
56
- */
57
- export function zhPayloadFromDoc(doc, trans) {
57
+ const validBox = (box) => Array.isArray(box) && box.length === 4 && box.every(Number.isFinite) && box[0] < box[2] && box[1] < box[3]
58
+ const normLine = (text) => String(text || '').normalize('NFKC').replace(/\s+/gu, '').toLowerCase()
59
+
60
+ export function docFingerprint(doc) {
61
+ return crypto.createHash('sha256').update(JSON.stringify({ revision: doc.revision, paragraphs: doc.paragraphs, sections: doc.sections })).digest('hex')
62
+ }
63
+
64
+ /** 只恢复唯一的完整行匹配;不凭相似度或版面框猜测缺失坐标。 */
65
+ function matchLocalLines(source, sheets, crossPage) {
66
+ const target = normLine(source)
67
+ if (!target) return null
68
+ const flat = sheets.flatMap(({ page, lines }) => lines.map(line => ({ page, text: line.text, bbox: [line.x, line.y, line.x2, line.y2] })))
69
+ .filter(line => normLine(line.text) && validBox(line.bbox))
70
+ let found = null
71
+ for (let i = 0; i < flat.length && flat[i].page === sheets[0].page; i++) {
72
+ let prefix = ''
73
+ for (let j = i; j < flat.length; j++) {
74
+ prefix += normLine(flat[j].text)
75
+ if (!target.startsWith(prefix)) break
76
+ if (prefix !== target) continue
77
+ if (crossPage !== (flat[i].page !== flat[j].page)) break
78
+ if (found) return null
79
+ found = flat.slice(i, j + 1)
80
+ break
81
+ }
82
+ }
83
+ if (!found) return null
84
+ const groups = new Map()
85
+ for (const { page, text, bbox } of found) {
86
+ const block = groups.get(page)
87
+ if (!block) groups.set(page, { page, text, bbox })
88
+ else {
89
+ block.text += ' ' + text
90
+ block.bbox = [Math.min(block.bbox[0], bbox[0]), Math.min(block.bbox[1], bbox[1]), Math.max(block.bbox[2], bbox[2]), Math.max(block.bbox[3], bbox[3])]
91
+ }
92
+ }
93
+ return [...groups.values()]
94
+ }
95
+
96
+ function splitTranslation(text, fragments) {
97
+ if (fragments.length === 1) return [text]
98
+ const chars = Array.from(text)
99
+ if (chars.length < fragments.length || chars.filter(char => char.trim()).length < fragments.length) return null
100
+ const weights = fragments.map(({ text }) => normLine(text).length)
101
+ const total = weights.reduce((sum, size) => sum + size, 0)
102
+ let start = 0, covered = 0
103
+ const parts = fragments.map((_, i) => {
104
+ covered += weights[i]
105
+ const remain = fragments.length - i - 1
106
+ const end = remain ? Math.min(chars.length - remain, Math.max(start + 1, Math.round(chars.length * covered / total))) : chars.length
107
+ const part = chars.slice(start, end).join('')
108
+ start = end
109
+ return part
110
+ })
111
+ return parts.every(part => part.trim()) ? parts : null
112
+ }
113
+
114
+ function formatIssues(issues) {
115
+ return issues.slice(0, 8).map(({ page, reason }) => `第 ${page || '?'} 页:${reason}`).join(';') + (issues.length > 8 ? `;另有 ${issues.length - 8} 项` : '')
116
+ }
117
+
118
+ /** 从文档和译文收集所有文字目标,不能定位的目标不能当作可忽略项。 */
119
+ export function zhPayloadFromDoc(doc, trans, resolved = new Map()) {
58
120
  const entries = trans && trans.entries && typeof trans.entries === 'object' ? trans.entries : {}
59
121
  const pages = new Map()
122
+ const issues = []
60
123
  let crossPage = 0
124
+ let unlocated = 0
125
+ const missing = new Set()
126
+ const targets = new Set()
127
+ const retained = {}
61
128
  for (const paragraph of (doc && doc.paragraphs) || []) {
62
- if (!paragraph || !REPLACE_KINDS.has(paragraph.kind)) continue
63
- // 跨页合并的段落:bbox 只覆盖第一页那几行,整段译文塞不进去(放不下就会被跳过)。
64
- // 与其让 PyMuPDF 白白试一遍、最后整段留英文,不如在这里明确计出来告诉用户。
65
- if (paragraph.crossPage === true) {
66
- crossPage += 1
129
+ if (!paragraph || !String(paragraph.text || '').trim()) continue
130
+ if (!REPLACE_KINDS.has(paragraph.kind) || looksLikeByline(paragraph.text)) {
131
+ const kind = looksLikeByline(paragraph.text) ? 'byline' : paragraph.kind
132
+ retained[kind] = (retained[kind] || 0) + 1
67
133
  continue
68
134
  }
69
- const entry = entries[paragraph.hash]
135
+ const key = paragraphKey(paragraph)
136
+ if (!key) throw new Error('文档段落没有译文标识,请先重建文档模型')
137
+ targets.add(key)
138
+ const entry = entries[key]
70
139
  const zh = entry && typeof entry === 'object' ? entry.zh : entry
71
- if (typeof zh !== 'string' || zh.trim() === '') continue
72
- const bbox = Array.isArray(paragraph.bbox) ? paragraph.bbox : null
73
- if (!bbox || bbox.length !== 4) continue
74
- const page = Math.max(1, Math.round(Number(paragraph.page) || 1))
75
- if (!pages.has(page)) pages.set(page, [])
76
- pages.get(page).push({
77
- rect: bbox.map(value => Math.round(Number(value) * 100) / 100),
78
- text: zh.trim(),
79
- source: String(paragraph.text || ''),
140
+ if (typeof zh !== 'string' || !zh.trim()) missing.add(key)
141
+ const page = Number(paragraph.page)
142
+ const source = String(paragraph.text)
143
+ const fragments = resolved.get(paragraph) || (paragraph.crossPage !== true && paragraph.geometryTrusted !== false && Number.isInteger(page) && page > 0 && validBox(paragraph.bbox) ? [{ page, bbox: paragraph.bbox, text: source }] : null)
144
+ if (paragraph.crossPage === true) crossPage += 1
145
+ if (!fragments?.length) {
146
+ unlocated += 1
147
+ issues.push({ page, reason: paragraph.crossPage === true ? '无法唯一定位跨页段落的原文行' : '无法唯一定位段落的原文行' })
148
+ continue
149
+ }
150
+ if (missing.has(key)) continue
151
+ const chunks = splitTranslation(zh.trim(), fragments)
152
+ if (!chunks) {
153
+ issues.push({ page, reason: '译文无法分配到所有跨页文字块' })
154
+ continue
155
+ }
156
+ fragments.forEach((fragment, i) => {
157
+ if (!pages.has(fragment.page)) pages.set(fragment.page, [])
158
+ pages.get(fragment.page).push({
159
+ rect: fragment.bbox.map(value => Math.round(value * 100) / 100),
160
+ text: chunks[i],
161
+ source: fragment.text,
162
+ })
80
163
  })
81
164
  }
165
+ let missingTitleCount = 0
166
+ for (const section of doc.sections || []) {
167
+ if (section.synthetic || !String(section.title || '').trim()) continue
168
+ const key = titleKey(section)
169
+ if (!key) continue
170
+ targets.add(key)
171
+ const entry = entries[key]
172
+ const text = typeof entry === 'object' ? entry?.zh : entry
173
+ if (typeof text !== 'string' || !text.trim()) {
174
+ missing.add(key)
175
+ missingTitleCount += 1
176
+ }
177
+ }
82
178
  return {
83
- pages: [...pages.entries()]
84
- .sort((a, b) => a[0] - b[0])
85
- .map(([n, blocks]) => ({ n, blocks })),
179
+ pages: [...pages.entries()].sort((a, b) => a[0] - b[0]).map(([n, blocks]) => ({ n, blocks })),
86
180
  crossPage,
181
+ unlocated,
182
+ issues,
183
+ missingKeys: [...missing],
184
+ targetCount: targets.size,
185
+ missingTitleCount,
186
+ retained,
87
187
  }
88
188
  }
89
189
 
190
+ async function recoverGeometry(doc, pdf, pdfPath) {
191
+ const result = new Map()
192
+ const cache = new Map()
193
+ const linesFor = (page) => {
194
+ if (!cache.has(page)) cache.set(page, Promise.resolve().then(() => pdf.pageLines(pdfPath, page)).then(result => result?.ok && Array.isArray(result.lines) ? result.lines : []).catch(() => []))
195
+ return cache.get(page)
196
+ }
197
+ for (const paragraph of doc.paragraphs) {
198
+ if (!paragraph || !REPLACE_KINDS.has(paragraph.kind) || !String(paragraph.text || '').trim() || looksLikeByline(paragraph.text)) continue
199
+ const page = Number(paragraph.page)
200
+ if (!Number.isInteger(page) || page < 1) continue
201
+ const cross = paragraph.crossPage === true
202
+ if (!cross && paragraph.geometryTrusted !== false && validBox(paragraph.bbox)) continue
203
+ const fragments = paragraph.pageFragments
204
+ if (cross && paragraph.geometryTrusted !== false && Array.isArray(fragments) && fragments.length >= 2 && fragments[0].page === page && fragments.every((part, i) => Number.isInteger(part.page) && (!i || part.page === fragments[i - 1].page + 1) && validBox(part.bbox) && normLine(part.text)) && normLine(fragments.map(part => part.text).join('')) === normLine(paragraph.text)) {
205
+ result.set(paragraph, fragments)
206
+ continue
207
+ }
208
+ if (typeof pdf?.pageLines !== 'function') continue
209
+ const sheets = [{ page, lines: await linesFor(page) }]
210
+ if (cross) sheets.push({ page: page + 1, lines: await linesFor(page + 1) })
211
+ const match = matchLocalLines(paragraph.text, sheets, cross)
212
+ if (match) result.set(paragraph, match)
213
+ }
214
+ return result
215
+ }
216
+
90
217
  /** 兼容旧调用方:只要 pages。 */
91
218
  export function zhPagesFromDoc(doc, trans) {
92
219
  return zhPayloadFromDoc(doc, trans).pages
@@ -100,6 +227,23 @@ export function createZhPdf({ store, pdf }) {
100
227
  return store.paperFile(id, ZH_FILE)
101
228
  }
102
229
 
230
+ async function docStamp(id) {
231
+ return fsp.stat(store.paperFile(id, 'doc.json')).then(stat => String(stat.mtimeMs), error => {
232
+ if (error.code === 'ENOENT') return ''
233
+ throw error
234
+ })
235
+ }
236
+
237
+ async function inspect(id, doc) {
238
+ if (!Array.isArray(doc?.paragraphs)) throw new Error('还没有文档模型:先打开论文等它解析完')
239
+ const { path: pdfPath } = await store.resolvePdf(id)
240
+ const resolved = await recoverGeometry(doc, pdf, pdfPath)
241
+ const trans = await store.readTrans(id)
242
+ const { pages, ...coverage } = zhPayloadFromDoc(doc, trans, resolved)
243
+ const source = await fingerprintPdf(pdfPath)
244
+ return { ...coverage, missingCount: coverage.missingKeys.length, readyBlocks: pages.reduce((sum, page) => sum + page.blocks.length, 0), sourceHash: source.sha256, docHash: docFingerprint(doc), transHash: transFingerprint(trans) }
245
+ }
246
+
103
247
  /** 中文版状态:存在与否、什么时候生成的、和当前译文/文档模型是否对得上。 */
104
248
  async function status(id) {
105
249
  const file = fileOf(id)
@@ -110,12 +254,7 @@ export function createZhPdf({ store, pdf }) {
110
254
  return { exists: false, pages: 0, blocks: 0, at: '', size: 0, stale: false }
111
255
  }
112
256
  const meta = await readMeta(store.paperFile, id)
113
- let docAt = ''
114
- try {
115
- docAt = String(Math.trunc((await fsp.stat(store.paperFile(id, 'doc.json'))).mtimeMs))
116
- } catch {
117
- docAt = ''
118
- }
257
+ const docAt = await docStamp(id).catch(() => null)
119
258
  let fingerprint = ''
120
259
  try {
121
260
  fingerprint = transFingerprint(await store.readTrans(id))
@@ -123,7 +262,8 @@ export function createZhPdf({ store, pdf }) {
123
262
  fingerprint = ''
124
263
  }
125
264
  // 三种情况都算过期:没有生成记录(老文件)、译文变了、文档模型重建过
126
- const stale = !meta || String(meta.transHash || '') !== fingerprint || String(meta.docAt || '') !== docAt
265
+ const sourceHash = await store.resolvePdf(id).then(({ path }) => fingerprintPdf(path)).then(source => source.sha256, () => null)
266
+ const stale = !meta || meta.complete !== true || sourceHash === null || meta.sourceHash !== sourceHash || String(meta.transHash || '') !== fingerprint || String(meta.docAt || '') !== docAt
127
267
  return {
128
268
  exists: true,
129
269
  pages: meta ? Number(meta.pages) || 0 : 0,
@@ -138,46 +278,91 @@ export function createZhPdf({ store, pdf }) {
138
278
  * 生成(或重新生成)中文版。
139
279
  * 返回 {ok, blocks, skipped, pages, path};没有译文时抛中文错误,让面板提示去翻译。
140
280
  */
141
- async function build(id, options = {}) {
281
+ function build(id, options = {}) {
282
+ const file = fileOf(id)
283
+ if (!activeBuilds.has(file)) {
284
+ const task = renderPdf(id, options).finally(() => activeBuilds.delete(file))
285
+ activeBuilds.set(file, task)
286
+ }
287
+ return activeBuilds.get(file)
288
+ }
289
+
290
+ async function renderPdf(id, options) {
291
+ options.signal?.throwIfAborted()
142
292
  if (!pdf || typeof pdf.callTool !== 'function') throw new Error('zhpdf 需要 pdf 依赖')
143
293
  const doc = options.doc
144
294
  if (!doc || !Array.isArray(doc.paragraphs)) throw new Error('还没有文档模型:先打开论文等它解析完')
295
+ const docAt = await docStamp(id)
296
+ if (options.docHash) {
297
+ const currentDoc = JSON.parse(await fsp.readFile(store.paperFile(id, 'doc.json'), 'utf8'))
298
+ if (docFingerprint(currentDoc) !== options.docHash) throw new Error('文档已更新,请重新生成中文版')
299
+ }
145
300
  const trans = await store.readTrans(id)
146
- const payload = zhPayloadFromDoc(doc, trans)
301
+ const transHash = transFingerprint(trans)
302
+ if (options.transHash && options.transHash !== transHash) throw new Error('译文已更新,请重新生成中文版')
303
+ const { path: pdfPath } = await store.resolvePdf(id)
304
+ const source = await fingerprintPdf(pdfPath)
305
+ if (options.sourceHash && options.sourceHash !== source.sha256 || options.docHash && options.docHash !== docFingerprint(doc)) {
306
+ throw new Error('源 PDF 或文档已更新,请重新生成中文版')
307
+ }
308
+ const payload = zhPayloadFromDoc(doc, trans, await recoverGeometry(doc, pdf, pdfPath))
309
+ if (payload.issues.length) throw new Error('无法完整生成中文版:' + formatIssues(payload.issues))
310
+ if (payload.missingKeys.length) throw new Error('还没有译文:缺少 ' + payload.missingKeys.length + ' 段可写回译文,未生成中文版')
147
311
  const pages = payload.pages
148
312
  const blocks = pages.reduce((sum, page) => sum + page.blocks.length, 0)
149
- if (blocks === 0) throw new Error('这篇还没有译文:先翻译几段(或整篇),再生成中文版')
150
- const { path: pdfPath } = await store.resolvePdf(id)
313
+ if (blocks === 0) throw new Error('没有能安全写回原版面的文字,请先检查文档模型和版面解析')
151
314
  const out = fileOf(id)
152
- const result = await pdf.callTool(
153
- 'zhpdf',
154
- { path: pdfPath, out, pages, lineheight: Number(options.lineheight) || 1.3 },
155
- { timeoutMs: 300000 },
156
- )
157
- if (!result || result.ok !== true) throw new Error('生成中文版失败:' + ((result && result.error) || '未知原因'))
158
- const blocksWritten = Number(result.blocks) || 0
159
- const pagesTotal = Number(result.pages) || 0
160
- let docAt = ''
315
+ const dir = await fsp.mkdtemp(path.join(path.dirname(out), '.zhpdf-'))
316
+ const staged = path.join(dir, ZH_FILE)
317
+ let blocksWritten
318
+ let pagesTotal
319
+ let retainBackup = false
161
320
  try {
162
- docAt = String(Math.trunc((await fsp.stat(store.paperFile(id, 'doc.json'))).mtimeMs))
163
- } catch {
164
- docAt = ''
165
- }
166
- await writeMeta(store.paperFile, id, {
167
- at: new Date().toISOString(),
168
- blocks: blocksWritten,
169
- pages: pagesTotal,
170
- docAt,
171
- transHash: transFingerprint(trans),
172
- }).catch(() => {})
173
- return {
174
- ok: true,
175
- blocks: blocksWritten,
176
- skipped: Number(result.skipped) || 0,
177
- crossPage: payload.crossPage,
178
- pages: pagesTotal,
179
- path: out,
321
+ const result = await pdf.callTool(
322
+ 'zhpdf',
323
+ { path: pdfPath, out: staged, pages, lineheight: Number(options.lineheight) || 1.3 },
324
+ { timeoutMs: 300000, signal: options.signal },
325
+ )
326
+ options.signal?.throwIfAborted()
327
+ if (result?.ok !== true) throw new Error('生成中文版失败:' + (result?.error || '未知原因'))
328
+ blocksWritten = Number(result.blocks)
329
+ pagesTotal = Number(result.pages)
330
+ if (blocksWritten !== blocks || result.skipped !== 0 || !Number.isInteger(pagesTotal) || pagesTotal < pages.at(-1).n) {
331
+ const details = Array.isArray(result.failures) && result.failures.length ? ':' + formatIssues(result.failures) : ''
332
+ throw new Error('有段落无法写回原版面,未替换已有中文版(预期 ' + blocks + ' 段,实际写入 ' + (blocksWritten || 0) + ' 段)' + details)
333
+ }
334
+ if (!(await fsp.stat(staged)).size) throw new Error('生成的中文版为空,未替换已有文件')
335
+ const currentSource = await store.resolvePdf(id).then(({ path }) => fingerprintPdf(path))
336
+ if (source.sha256 !== currentSource.sha256 || source.path !== currentSource.path || docAt !== await docStamp(id) || transHash !== transFingerprint(await store.readTrans(id))) {
337
+ throw new Error('生成期间源 PDF、文档或译文已更新,请重新生成')
338
+ }
339
+ const backup = path.join(dir, 'previous.pdf')
340
+ const hadPrevious = await fsp.copyFile(out, backup).then(() => true, error => {
341
+ if (error.code === 'ENOENT') return false
342
+ throw error
343
+ })
344
+ options.signal?.throwIfAborted()
345
+ await fsp.rename(staged, out)
346
+ try {
347
+ await writeMeta(store.paperFile, id, {
348
+ at: new Date().toISOString(), blocks: blocksWritten, pages: pagesTotal, docAt, docHash: docFingerprint(doc), transHash, sourceHash: source.sha256, complete: true,
349
+ crossPage: payload.crossPage, unlocated: payload.unlocated,
350
+ })
351
+ } catch (error) {
352
+ try {
353
+ if (hadPrevious) await fsp.rename(backup, out)
354
+ else await fsp.rm(out, { force: true })
355
+ } catch (rollbackError) {
356
+ // 回滚失败时保留备份,避免 finally 清掉唯一旧文件。
357
+ retainBackup = true
358
+ throw new Error('生成记录保存失败且旧文件恢复失败,请检查磁盘权限;备份保留于 ' + backup, { cause: rollbackError })
359
+ }
360
+ throw new Error('生成记录保存失败,已保留旧版中文版:' + error.message, { cause: error })
361
+ }
362
+ } finally {
363
+ if (!retainBackup) await fsp.rm(dir, { recursive: true, force: true }).catch(() => {})
180
364
  }
365
+ return { ok: true, blocks: blocksWritten, skipped: 0, crossPage: payload.crossPage, unlocated: payload.unlocated, pages: pagesTotal, path: out }
181
366
  }
182
367
 
183
368
  async function clear(id) {
@@ -190,5 +375,5 @@ export function createZhPdf({ store, pdf }) {
190
375
  return fileOf(id)
191
376
  }
192
377
 
193
- return { status, build, clear, readFile, fileOf }
378
+ return { status, inspect, build, clear, readFile, fileOf }
194
379
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-paper-workbench",
3
- "version": "1.1.2",
3
+ "version": "1.2.0",
4
4
  "description": "DSH 科研论文工作台:双语对照精读 + 原生 Agent 会话 + 自由并发持久翻译 + 全学科订阅/代理 + 原文页透明交互层",
5
5
  "type": "module",
6
6
  "icon": "./icon.svg",
@@ -40,11 +40,14 @@
40
40
  "scripts/install.ps1",
41
41
  "scripts/install.sh",
42
42
  "scripts/layout.mjs",
43
+ "scripts/audit-library.mjs",
44
+ "scripts/batch-layout.mjs",
43
45
  "cordis.patch.yml",
44
46
  "AGENTS.md",
45
47
  "README.md",
46
48
  "CHANGELOG.md",
47
49
  "LICENSE",
50
+ "docs/guide.md",
48
51
  "docs/v2-contracts.md",
49
52
  "docs/v3-contracts.md",
50
53
  "docs/v4-layout.md",
@@ -63,10 +66,12 @@
63
66
  "doctor": "node scripts/doctor.mjs",
64
67
  "seed": "node scripts/seed.mjs",
65
68
  "smoke": "node scripts/smoke.mjs",
66
- "test": "node scripts/test-store.mjs && node scripts/test-db.mjs && node scripts/test-db-drivers.mjs && node scripts/test-conv.mjs && node scripts/test-paper-context.mjs && node scripts/test-native-client.mjs && node scripts/test-reader-bridge.mjs && node scripts/test-native-workbench.mjs && node scripts/test-annotations-and-ui.mjs && node scripts/test-safety.mjs && node scripts/test-host-auth.mjs && node scripts/test-doctor.mjs && node scripts/test-tools.mjs && node scripts/test-explain-skills.mjs && node scripts/test-doc.mjs && node scripts/test-doc-layout.mjs && node scripts/test-page-identity.mjs && node scripts/test-layout-conservation.mjs && node scripts/test-layout-archive.mjs && node scripts/test-layout-ir.mjs && node scripts/test-layout-table.mjs && node scripts/test-layout.mjs && node scripts/test-layout-model.mjs && node scripts/test-figure-cache.mjs && node scripts/test-zhpdf.mjs && node scripts/test-ai.mjs && node scripts/test-translate-jobs.mjs && node scripts/test-review.mjs && node scripts/test-jobs.mjs && node scripts/test-figures.mjs && node scripts/test-session.mjs && node scripts/test-obsidian.mjs && node scripts/test-net-proxy.mjs && node scripts/test-arxiv.mjs && node scripts/test-arxiv-feed.mjs && node scripts/test-feed-cache-security.mjs && node scripts/test-ocr.mjs && node scripts/test-ocr-cancel.mjs && node scripts/test-install-agent.mjs && node scripts/test-release-safety.mjs && python scripts/test-pdf-quality.py && python assets/pdf_tool.py --self-test",
69
+ "test": "node scripts/test-store.mjs && node scripts/test-db.mjs && node scripts/test-db-drivers.mjs && node scripts/test-conv.mjs && node scripts/test-paper-context.mjs && node scripts/test-native-client.mjs && node scripts/test-reader-bridge.mjs && node scripts/test-native-workbench.mjs && node scripts/test-annotations-and-ui.mjs && node scripts/test-safety.mjs && node scripts/test-host-auth.mjs && node scripts/test-doctor.mjs && node scripts/test-tools.mjs && node scripts/test-explain-skills.mjs && node scripts/test-doc.mjs && node scripts/test-doc-layout.mjs && node scripts/test-toc-structure.mjs && node scripts/test-library-audit.mjs && node scripts/test-page-identity.mjs && node scripts/test-layout-conservation.mjs && node scripts/test-layout-archive.mjs && node scripts/test-layout-ir.mjs && node scripts/test-layout-table.mjs && node scripts/test-layout.mjs && node scripts/test-layout-model.mjs && node scripts/test-figure-cache.mjs && node scripts/test-zhpdf.mjs && node scripts/test-ai.mjs && node scripts/test-translate-jobs.mjs && node scripts/test-review.mjs && node scripts/test-jobs.mjs && node scripts/test-figures.mjs && node scripts/test-session.mjs && node scripts/test-obsidian.mjs && node scripts/test-net-proxy.mjs && node scripts/test-arxiv.mjs && node scripts/test-arxiv-feed.mjs && node scripts/test-search-pagination.mjs && node scripts/test-browse-history.mjs && node scripts/test-feed-cache-security.mjs && node scripts/test-ocr.mjs && node scripts/test-ocr-cancel.mjs && node scripts/test-install-agent.mjs && node scripts/test-release-safety.mjs && python scripts/test-pdf-quality.py && python assets/pdf_tool.py --self-test",
67
70
  "fix:library": "node scripts/fix-library.mjs",
68
71
  "selftest:pdf": "python assets/pdf_tool.py --self-test",
72
+ "posttest": "node scripts/test-zhpdf-jobs.mjs && node scripts/test-batch-layout.mjs",
69
73
  "layout": "node scripts/layout.mjs",
74
+ "library:audit": "node scripts/audit-library.mjs",
70
75
  "quality:score": "node scripts/quality/score-layout.mjs",
71
76
  "quality:rebuild": "node scripts/quality/rebuild-layout.mjs"
72
77
  },