@li-canghai/dsh-paper 0.0.0-stage → 0.8.1
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/LICENSE +21 -0
- package/README.md +150 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2762 -0
- package/lib/client-parts/02-author-year.js +95 -0
- package/lib/client.js +10381 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +308 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +261 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
package/lib/translate.js
ADDED
|
@@ -0,0 +1,909 @@
|
|
|
1
|
+
// lib/translate.js —— 翻译引擎:分批、调用模型、解析回复、写回译文。
|
|
2
|
+
//
|
|
3
|
+
// 块是**身份单位**,批次是**上下文单位**:默认一个请求携带多个相邻块(含公式前后文),
|
|
4
|
+
// 模型逐 id 返回译文。例外是 `plain` 协议(D139):专用 MT 模型的回复里没有任何标记可对,
|
|
5
|
+
// 于是退化成"一块一请求",对齐由插件自己保证。
|
|
6
|
+
//
|
|
7
|
+
// 本模块只做"把一批块翻出来"与"把一篇排出来",顺序执行;并发、暂停、取消、失败重试
|
|
8
|
+
// 是上层(T12)的事。页面图渲染通过 deps.renderPages **注入**,本模块不直接依赖渲染器。
|
|
9
|
+
|
|
10
|
+
import { createHash } from 'node:crypto'
|
|
11
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
12
|
+
import { dirname } from 'node:path'
|
|
13
|
+
import { replaceStateFile } from './storage.js'
|
|
14
|
+
import { plainInlineText } from './inline-html.js'
|
|
15
|
+
import { buildBatchPrompt, documentReferenceOf, parseBatchReply, parsePlainReply, pendingBlocksOf } from './translate-prompts.js'
|
|
16
|
+
import { sameTableShape } from './table-gfm.js'
|
|
17
|
+
import { tableBodyOf, translatableTextOf } from './translatable-text.js'
|
|
18
|
+
|
|
19
|
+
/** 每批最多几页。 */
|
|
20
|
+
export const DEFAULT_BATCH_PAGES = 2
|
|
21
|
+
/** 每批最多几个块 —— 单页块数可以很多(参考文献页尤其),页数限制挡不住它。 */
|
|
22
|
+
export const DEFAULT_MAX_BLOCKS_PER_BATCH = 40
|
|
23
|
+
/** 单请求最多几张图。vision token 成本随图数线性上升,不是字节上限的问题。 */
|
|
24
|
+
export const DEFAULT_IMAGES_PER_BATCH = 4
|
|
25
|
+
/** 页面图交给模型的宽度变体(UI 取 1200 的高清变体,见 page-image.js)。 */
|
|
26
|
+
export const DEFAULT_PAGE_IMAGE_WIDTH = 896
|
|
27
|
+
/** 畸形回复的重试次数(不含首次)。0 = 不重试,只试一次。 */
|
|
28
|
+
export const DEFAULT_RETRIES = 2
|
|
29
|
+
/** 译文文件的 schemaVersion(dsh-paper 自有的持久 JSON 都带,见 D39/D48)。 */
|
|
30
|
+
export const TRANSLATION_SCHEMA_VERSION = 1
|
|
31
|
+
|
|
32
|
+
/** 块原文的 sha256 —— 译文是否过期靠它判,不靠时间戳。纯函数,入参不改。 */
|
|
33
|
+
export function sourceHashOf(block) {
|
|
34
|
+
// 🔴 哈希的是**送出去的文本**(`translatableTextOf`),不是 sourceText:
|
|
35
|
+
// 表格块的正文在 html 里,只哈希 caption 的话「表体改了」判不出来,旧译文会永远留着。
|
|
36
|
+
return createHash('sha256').update(translatableTextOf(block), 'utf8').digest('hex')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function positiveInt(value, fallback, name) {
|
|
40
|
+
if (value === undefined || value === null || value === '') return fallback
|
|
41
|
+
const number = Number(value)
|
|
42
|
+
if (!Number.isSafeInteger(number) || number <= 0) throw new Error(`翻译的 ${name} 必须是正整数`)
|
|
43
|
+
return number
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 允许 0 的整数。`retries: 0` 是"不重试,只试一次",`imagesPerBatch: 0` 是"这一批不要图" ——
|
|
48
|
+
* 两者都是合法配置,用正整数校验会把它们误判成错误输入。
|
|
49
|
+
*/
|
|
50
|
+
function nonNegativeInt(value, fallback, name) {
|
|
51
|
+
if (value === undefined || value === null || value === '') return fallback
|
|
52
|
+
const number = Number(value)
|
|
53
|
+
if (!Number.isSafeInteger(number) || number < 0) throw new Error(`翻译的 ${name} 必须是非负整数`)
|
|
54
|
+
return number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 有界并发地跑一串任务,结果与输入**同序**。
|
|
59
|
+
*
|
|
60
|
+
* 🔴 整篇翻译的批次必须是并发的:队列的并发数是**跨文档**的(taskId 是 documentId),
|
|
61
|
+
* 一篇论文只占一个队列位 —— 串行跑 20 个批次就是 20 倍等待(实测单批 22–35 秒)。
|
|
62
|
+
* 首个抛错让整次调用 reject(与串行时的语义一致);已经在跑的批次自然跑完,由调用方 abort。
|
|
63
|
+
*
|
|
64
|
+
* @param {unknown[]} items
|
|
65
|
+
* @param {number} limit 并发上限(≥1)
|
|
66
|
+
* @param {(item: unknown, index: number) => Promise<unknown>} worker
|
|
67
|
+
* @returns {Promise<unknown[]>} 与 items 同序的结果
|
|
68
|
+
*/
|
|
69
|
+
async function mapLimit(items, limit, worker) {
|
|
70
|
+
const list = Array.isArray(items) ? items : []
|
|
71
|
+
const results = new Array(list.length)
|
|
72
|
+
if (list.length === 0) return results
|
|
73
|
+
let next = 0
|
|
74
|
+
const size = Math.max(1, Math.min(limit, list.length))
|
|
75
|
+
const runners = Array.from({ length: size }, async () => {
|
|
76
|
+
for (;;) {
|
|
77
|
+
const index = next
|
|
78
|
+
next += 1
|
|
79
|
+
if (index >= list.length) return
|
|
80
|
+
results[index] = await worker(list[index], index)
|
|
81
|
+
}
|
|
82
|
+
})
|
|
83
|
+
await Promise.all(runners)
|
|
84
|
+
return results
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* 一批原文的**字符预算**。
|
|
89
|
+
*
|
|
90
|
+
* 提示词装不下就会被硬截断(translate-prompts 的 USER_LIMIT = 60000,其中还有 id 标签与
|
|
91
|
+
* 拼接开销),而被截断的请求等于只译了一半原文 —— 模型照样给出一份看起来完整的译文。
|
|
92
|
+
* 排批阶段先按这个预算切,正常论文根本走不到截断那条兜底路径;单个块本身就超预算时它会
|
|
93
|
+
* 独占一批,由 attemptBatch 明确拒绝(不能只译半段)。
|
|
94
|
+
*/
|
|
95
|
+
export const MAX_BATCH_CHARS = 48000
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 排批:按页聚簇,每批不超过 `batchPages` 页、不超过 `maxBlocksPerBatch` 个块,
|
|
99
|
+
* 且原文合计不超过 `maxChars` 字符。
|
|
100
|
+
*
|
|
101
|
+
* 没有 `page` 的块(content_list 降级、或上游给不出页码)**归入一个 pages: [] 的特殊批次**,
|
|
102
|
+
* 不丢 —— 它们照样是读者要看的内容。空 sourceText 的块不进批(没东西可译)。
|
|
103
|
+
*
|
|
104
|
+
* 纯函数:幂等、不修改入参。
|
|
105
|
+
*
|
|
106
|
+
* @param {unknown} blocks
|
|
107
|
+
* @param {{batchPages?: number, maxBlocksPerBatch?: number, maxChars?: number}} [options]
|
|
108
|
+
* @returns {Array<{pages: number[], blockIds: string[]}>}
|
|
109
|
+
*/
|
|
110
|
+
export function planBatches(blocks, options = {}) {
|
|
111
|
+
const batchPages = positiveInt(options.batchPages, DEFAULT_BATCH_PAGES, 'batchPages')
|
|
112
|
+
const maxBlocksPerBatch = positiveInt(options.maxBlocksPerBatch, DEFAULT_MAX_BLOCKS_PER_BATCH, 'maxBlocksPerBatch')
|
|
113
|
+
const maxChars = positiveInt(options.maxChars, MAX_BATCH_CHARS, 'maxChars')
|
|
114
|
+
const batches = []
|
|
115
|
+
if (!Array.isArray(blocks)) return batches
|
|
116
|
+
|
|
117
|
+
// 只保留"有 id 且 sourceText 非空"的块,并保持输入顺序。
|
|
118
|
+
const paginated = []
|
|
119
|
+
const unpaginated = []
|
|
120
|
+
for (const block of blocks) {
|
|
121
|
+
if (block === null || typeof block !== 'object') continue
|
|
122
|
+
if (typeof block.id !== 'string' || block.id === '') continue
|
|
123
|
+
if (translatableTextOf(block).trim() === '') continue
|
|
124
|
+
if (Number.isSafeInteger(block.page) && block.page > 0) paginated.push(block)
|
|
125
|
+
else unpaginated.push(block)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const byPage = new Map()
|
|
129
|
+
for (const block of paginated) {
|
|
130
|
+
if (!byPage.has(block.page)) byPage.set(block.page, [])
|
|
131
|
+
byPage.get(block.page).push(block)
|
|
132
|
+
}
|
|
133
|
+
const pages = [...byPage.keys()].sort((left, right) => left - right)
|
|
134
|
+
for (let index = 0; index < pages.length; index += batchPages) {
|
|
135
|
+
// 一个页组里的块可能超过上限(单页几十个参考文献条目),再按块数切。
|
|
136
|
+
const group = pages.slice(index, index + batchPages).flatMap(page => byPage.get(page))
|
|
137
|
+
for (const counted of withinCharBudget(group, maxBlocksPerBatch, maxChars)) {
|
|
138
|
+
batches.push({
|
|
139
|
+
pages: [...new Set(counted.map(block => block.page))].sort((left, right) => left - right),
|
|
140
|
+
blockIds: counted.map(block => block.id),
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const counted of withinCharBudget(unpaginated, maxBlocksPerBatch, maxChars)) {
|
|
145
|
+
batches.push({ pages: [], blockIds: counted.map(block => block.id) })
|
|
146
|
+
}
|
|
147
|
+
return batches
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 按**块数**与**字符预算**两条上限切一批块。
|
|
152
|
+
*
|
|
153
|
+
* 单块自己就超预算时让它独占一批(不丢、不拆)—— 拆块的代价是译文要在片段边界上重组,
|
|
154
|
+
* 那属于另一层的能力;这里只保证「发出去的原文就是整块」,装不下由调用方明确拒绝。
|
|
155
|
+
*
|
|
156
|
+
* @param {object[]} blocks 已过滤过的块(有 id、原文非空)。
|
|
157
|
+
* @param {number} maxBlocks 一批最多几个块。
|
|
158
|
+
* @param {number} maxChars 一批原文合计最多多少字符。
|
|
159
|
+
* @returns {object[][]}
|
|
160
|
+
*/
|
|
161
|
+
function withinCharBudget(blocks, maxBlocks, maxChars) {
|
|
162
|
+
const groups = []
|
|
163
|
+
let current = []
|
|
164
|
+
let size = 0
|
|
165
|
+
for (const block of blocks) {
|
|
166
|
+
// 与 buildUser 同一口径:送出去的是折掉行内标签的纯文本,长度按它算才准。
|
|
167
|
+
const cost = sourceTextOf(block).length + 1
|
|
168
|
+
if (current.length > 0 && (current.length >= maxBlocks || size + cost > maxChars)) {
|
|
169
|
+
groups.push(current)
|
|
170
|
+
current = []
|
|
171
|
+
size = 0
|
|
172
|
+
}
|
|
173
|
+
current.push(block)
|
|
174
|
+
size += cost
|
|
175
|
+
}
|
|
176
|
+
if (current.length > 0) groups.push(current)
|
|
177
|
+
return groups
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* 翻译范围选择:从一篇块里挑出**这一轮要处理**的那部分,其余带上跳过原因。
|
|
182
|
+
*
|
|
183
|
+
* 与排批({@link planBatches})分工不同:这里决定"译不译",排批决定"怎么分批"。
|
|
184
|
+
* 三种模式:`all`(整篇)、`body`(只译正文,剔参考文献与附录)、`pages`(只译指定页区间)。
|
|
185
|
+
*/
|
|
186
|
+
|
|
187
|
+
/** 附录起始标题的三种写法(大小写不敏感):`Appendix A` / `附录 A` / `A. Appendix`。 */
|
|
188
|
+
const APPENDIX_PATTERNS = [
|
|
189
|
+
/^\s*(appendix|appendices)\b/i,
|
|
190
|
+
/^\s*(附\s*录)/,
|
|
191
|
+
/^\s*[A-D]\.\s*(appendix|附加|附录)/i,
|
|
192
|
+
]
|
|
193
|
+
|
|
194
|
+
/** 认得的范围模式;给别的值(含缺省)一律按 `all` 处理 —— 宁可多译,也别让一个拼错的值把整篇译空。 */
|
|
195
|
+
const SCOPE_MODES = ['all', 'body', 'pages']
|
|
196
|
+
|
|
197
|
+
function isObject(value) {
|
|
198
|
+
return value !== null && typeof value === 'object'
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** 块的非空 id,取不到就是空串(调用方据此判"缺 id")。 */
|
|
202
|
+
function blockIdOf(block) {
|
|
203
|
+
return isObject(block) && typeof block.id === 'string' && block.id !== '' ? block.id : ''
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** 送去翻译的文本:与提示词、待译判定、源哈希**同一口径**(含表格正文)。 */
|
|
207
|
+
function sourceTextOf(block) {
|
|
208
|
+
return translatableTextOf(block)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 允许缺省的正整数:缺省、非数字、非正数一律 null,调用方据此退回"不过滤"。不抛错。 */
|
|
212
|
+
function positiveIntOrNull(value) {
|
|
213
|
+
if (value === undefined || value === null || value === '') return null
|
|
214
|
+
const number = Number(value)
|
|
215
|
+
return Number.isSafeInteger(number) && number > 0 ? number : null
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* 这个块是不是**附录的起始标题**。只认 heading —— 参考文献块(type 是 references)
|
|
220
|
+
* 里出现 "Appendix" 不算,正文段落里提到附录也不算。非法入参返回 false,不抛错。
|
|
221
|
+
*
|
|
222
|
+
* @param {unknown} block
|
|
223
|
+
* @returns {boolean}
|
|
224
|
+
*/
|
|
225
|
+
export function isAppendixHeading(block) {
|
|
226
|
+
if (!isObject(block) || block.type !== 'heading') return false
|
|
227
|
+
const text = sourceTextOf(block)
|
|
228
|
+
return APPENDIX_PATTERNS.some(pattern => pattern.test(text))
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* 挑出本轮要翻译的块。规则**顺序执行**,每个块只归入一边;`selected` 与 `skipped`
|
|
233
|
+
* 都保持输入顺序,且**不改入参**(纯函数、幂等)。
|
|
234
|
+
*
|
|
235
|
+
* `pages` 模式:`pageFrom` / `pageTo` 任缺省或非正整数时**不按页过滤**(视为全选),
|
|
236
|
+
* 但没有 `page` 的块仍要记一条 `块没有页码` —— 不能静默吞掉。范围成立时没有 `page` 的块
|
|
237
|
+
* 一般圈不进来,按 `不在页码范围 N-M 内` 跳过。
|
|
238
|
+
*
|
|
239
|
+
* `all` 模式(含 mode 缺省或给了不认识的值):除了缺 id 与空原文,其余全进 `selected`。
|
|
240
|
+
*
|
|
241
|
+
* `body` 模式:`references` 块,以及第一个附录标题(含它自己)之后的所有块,都不算正文。
|
|
242
|
+
*
|
|
243
|
+
* @param {unknown} blocks
|
|
244
|
+
* @param {{mode?: string, pageFrom?: number, pageTo?: number}} [options]
|
|
245
|
+
* @returns {{selected: object[], skipped: Array<{id: string, reason: string}>}}
|
|
246
|
+
*/
|
|
247
|
+
export function selectScope(blocks, options = {}) {
|
|
248
|
+
const result = { selected: [], skipped: [] }
|
|
249
|
+
if (!Array.isArray(blocks)) return result
|
|
250
|
+
|
|
251
|
+
const requested = isObject(options) ? options.mode : undefined
|
|
252
|
+
const mode = SCOPE_MODES.includes(requested) ? requested : 'all'
|
|
253
|
+
const pageFrom = positiveIntOrNull(isObject(options) ? options.pageFrom : undefined)
|
|
254
|
+
const pageTo = positiveIntOrNull(isObject(options) ? options.pageTo : undefined)
|
|
255
|
+
const hasPageRange = pageFrom !== null && pageTo !== null
|
|
256
|
+
// 附录起点只找一次;找到之后(含起点自己)的块都随它一起被剔出正文。
|
|
257
|
+
const appendixAt = mode === 'body' ? blocks.findIndex(block => isAppendixHeading(block)) : -1
|
|
258
|
+
|
|
259
|
+
for (let index = 0; index < blocks.length; index += 1) {
|
|
260
|
+
const block = blocks[index]
|
|
261
|
+
if (blockIdOf(block) === '') {
|
|
262
|
+
result.skipped.push({ id: '', reason: '块缺少 id' })
|
|
263
|
+
continue
|
|
264
|
+
}
|
|
265
|
+
if (sourceTextOf(block).trim() === '') {
|
|
266
|
+
result.skipped.push({ id: block.id, reason: '译文块没有原文' })
|
|
267
|
+
continue
|
|
268
|
+
}
|
|
269
|
+
if (mode === 'pages') {
|
|
270
|
+
const page = block.page
|
|
271
|
+
if (hasPageRange) {
|
|
272
|
+
if (!(Number.isSafeInteger(page) && page >= pageFrom && page <= pageTo)) {
|
|
273
|
+
result.skipped.push({ id: block.id, reason: `不在页码范围 ${pageFrom}-${pageTo} 内` })
|
|
274
|
+
continue
|
|
275
|
+
}
|
|
276
|
+
} else if (!(Number.isSafeInteger(page) && page > 0)) {
|
|
277
|
+
// 范围不成立时不按页过滤,但"这块没有页码"必须记下来
|
|
278
|
+
result.skipped.push({ id: block.id, reason: '块没有页码' })
|
|
279
|
+
continue
|
|
280
|
+
}
|
|
281
|
+
result.selected.push(block)
|
|
282
|
+
continue
|
|
283
|
+
}
|
|
284
|
+
if (mode === 'body') {
|
|
285
|
+
if (block.type === 'references') {
|
|
286
|
+
result.skipped.push({ id: block.id, reason: '参考文献不计入正文' })
|
|
287
|
+
continue
|
|
288
|
+
}
|
|
289
|
+
if (appendixAt >= 0 && index >= appendixAt) {
|
|
290
|
+
result.skipped.push({ id: block.id, reason: '附录不计入正文' })
|
|
291
|
+
continue
|
|
292
|
+
}
|
|
293
|
+
result.selected.push(block)
|
|
294
|
+
continue
|
|
295
|
+
}
|
|
296
|
+
result.selected.push(block)
|
|
297
|
+
}
|
|
298
|
+
return result
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* 增量模式要译哪些块(返回 id,保持输入顺序)。
|
|
303
|
+
*
|
|
304
|
+
* 口径**比 {@link translateDocument} 默认的 sourceHash 更保守**:只要 `existing[id].zh`
|
|
305
|
+
* 是非空字符串就不再重译,**哪怕原文已经变了**。它换来的是"只补没译过的块"这种快而稳的补译,
|
|
306
|
+
* 代价是原文改动过、译文已过期的那部分不会被它刷新(那要走全译)。
|
|
307
|
+
*
|
|
308
|
+
* 纯函数:不改入参、幂等;`existing` 不是对象、`blocks` 不是数组都按"还没有译文"处理,不抛错。
|
|
309
|
+
*
|
|
310
|
+
* @param {unknown} blocks
|
|
311
|
+
* @param {unknown} existing
|
|
312
|
+
* @returns {string[]}
|
|
313
|
+
*/
|
|
314
|
+
/** 表格块连续结构不符后的终态原因:保留原文,不再自动重排(用户裁定 2026-10-26)。 */
|
|
315
|
+
export const TABLE_SKIPPED_REASON = '表格结构与原文不一致,保留原文表格'
|
|
316
|
+
|
|
317
|
+
export function pendingForIncremental(blocks, existing) {
|
|
318
|
+
const pending = []
|
|
319
|
+
if (!Array.isArray(blocks)) return pending
|
|
320
|
+
const lookup = isObject(existing) ? existing : {}
|
|
321
|
+
for (const block of blocks) {
|
|
322
|
+
const id = blockIdOf(block)
|
|
323
|
+
if (id === '') continue
|
|
324
|
+
if (sourceTextOf(block).trim() === '') continue
|
|
325
|
+
const previous = lookup[id]
|
|
326
|
+
if (isObject(previous) && typeof previous.zh === 'string' && previous.zh !== '') continue
|
|
327
|
+
// 表格块已判终态(结构对不上、保留原文):不再自动重排 —— 否则每次「一键翻译」或
|
|
328
|
+
// 「重试失败」都会再撞同一张表,用户看到的就是"点了没反应"。整篇重译(translateAll)
|
|
329
|
+
// 不走这里,换了更强的模型仍可覆盖。
|
|
330
|
+
if (isObject(previous) && previous.status === 'skipped' && previous.error === TABLE_SKIPPED_REASON) continue
|
|
331
|
+
// 旧记录可能**没有 error 字段**(漏写 error 那条缺陷留下的,实测 Gemma 2 / DeepSeek-V2 各有一两条)。
|
|
332
|
+
// 只认严格相等的话这些块会永远重排、永远撞同一张表 —— 正是用户看到的「总有块反复出现」。
|
|
333
|
+
// 「是表格 + 原文没变过」足以确认它就是当初被判掉的那一块:结构校验是确定性的,
|
|
334
|
+
// 同一张表重试必然同样失败;换了表会换 sourceHash,那时确实该重新试。
|
|
335
|
+
if (isObject(previous) && previous.status === 'skipped' && previous.error === undefined
|
|
336
|
+
&& isObject(block) && block.type === 'table' && previous.sourceHash === sourceHashOf(block)) continue
|
|
337
|
+
pending.push(id)
|
|
338
|
+
}
|
|
339
|
+
return pending
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** 从 batch / deps 里取本批的块对象。 */
|
|
343
|
+
function blocksOfBatch(batch, deps) {
|
|
344
|
+
if (Array.isArray(batch?.blocks)) return batch.blocks
|
|
345
|
+
const lookup = deps?.blocksById
|
|
346
|
+
if (lookup === undefined || lookup === null) return []
|
|
347
|
+
const get = typeof lookup.get === 'function' ? id => lookup.get(id) : id => lookup[id]
|
|
348
|
+
return (Array.isArray(batch?.blockIds) ? batch.blockIds : []).map(get).filter(block => block !== undefined && block !== null)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function warn(logger, message) {
|
|
352
|
+
logger?.warn?.(message)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* 渲染本批的页面图。任何失败都只记一行警告并退回纯文本 —— 没有页面图是降级,
|
|
357
|
+
* 让整篇翻译失败才是事故。
|
|
358
|
+
*/
|
|
359
|
+
async function renderImages(batch, deps) {
|
|
360
|
+
const pages = Array.isArray(batch?.pages) ? batch.pages : []
|
|
361
|
+
if (typeof deps?.renderPages !== 'function' || pages.length === 0) return []
|
|
362
|
+
try {
|
|
363
|
+
const result = await deps.renderPages({ pages, width: deps.pageImageWidth })
|
|
364
|
+
return (Array.isArray(result?.images) ? result.images : []).filter(image => image && image.data instanceof Uint8Array)
|
|
365
|
+
} catch (error) {
|
|
366
|
+
warn(deps?.logger, `dsh-paper translate: 第 ${pages.join(',')} 页页面图渲染失败,本批退回纯文本:${error?.message ?? error}`)
|
|
367
|
+
return []
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
/**
|
|
372
|
+
* 把模型的原始回复折成一行诊断,附在失败原因后面。
|
|
373
|
+
*
|
|
374
|
+
* 🔴 只说「解析不出数组」等于什么都没说:用户看到的是一次「点一下就完成」,
|
|
375
|
+
* 下次要能一眼分出**模型什么都没返回**、**返回的不是 JSON**、**被输出上限截断**三种情况 ——
|
|
376
|
+
* 它们的修法完全不同(换模型 / 改提示词契约 / 抬 maxTokens)。
|
|
377
|
+
*
|
|
378
|
+
* @param {unknown} raw 本次尝试收到的全部文本增量。
|
|
379
|
+
* @param {string} finish 终止原因 kind(stop / max-tokens / …),未知时为空串。
|
|
380
|
+
* @returns {string} 单行诊断,绝不进译文。
|
|
381
|
+
*/
|
|
382
|
+
function replyDigest(raw, finish) {
|
|
383
|
+
const text = typeof raw === 'string' ? raw : ''
|
|
384
|
+
const trimmed = text.trim()
|
|
385
|
+
const head = trimmed === '' ? '模型没有返回任何文本' : `模型返回 ${text.length} 字符`
|
|
386
|
+
const reason = finish === '' || finish === 'stop' ? '' : `,终止原因 ${finish}`
|
|
387
|
+
const snippet = trimmed.replace(/\s+/g, ' ').slice(0, 120)
|
|
388
|
+
return snippet === '' ? `${head}${reason}` : `${head}${reason}:${snippet}`
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* 发一次请求并解析回复。`preparedCall` 每次都要重新准备 —— 宿主的一次性句柄二次派发会抛
|
|
393
|
+
* INVALID_PREPARED_CALL,所以重试路径不能复用它。
|
|
394
|
+
*
|
|
395
|
+
* @returns {{translations: Array<{id: string, zh: string}>, detail: string, malformed: boolean, missing: string[]}|null}
|
|
396
|
+
*/
|
|
397
|
+
async function attemptBatch(batch, deps, acquireImages, messages) {
|
|
398
|
+
const model = deps.model ?? {}
|
|
399
|
+
const prepared = await deps.llm.prepareCall({
|
|
400
|
+
provider: model.provider,
|
|
401
|
+
model: model.model,
|
|
402
|
+
maxTokens: deps.maxTokens,
|
|
403
|
+
temperature: deps.temperature,
|
|
404
|
+
}, deps.signal)
|
|
405
|
+
|
|
406
|
+
// 🔴 只有模型**明确声明**接受图像时才附图。inputModalities 为 undefined 是"能力未知",
|
|
407
|
+
// 乐观假设会在运行期换来一次必然失败的请求;保守假设只损失一次图像上下文(决策 D66)。
|
|
408
|
+
const supportsImages = Array.isArray(prepared.inputModalities) && prepared.inputModalities.includes('image')
|
|
409
|
+
// glossary 是**用户维护的术语表片段**(glossary.js 的 buildGlossaryBlock 产物)。
|
|
410
|
+
// 缺省 undefined 时 buildBatchPrompt 产出的 system 与加这个功能之前逐字节一致。
|
|
411
|
+
const text = buildBatchPrompt({ blocks: messages.blocks, targetLanguage: deps.targetLanguage, glossary: deps.glossary, protocol: deps.protocol, previousContext: deps.previousContext })
|
|
412
|
+
// 🔴 提示词被截断 = 原文没有全部发送。这种请求**根本不发**:模型会照收到的前半段给一份
|
|
413
|
+
// 看起来完整的译文,而 sourceHash 是按完整原块算的 —— 于是半段译文被当成完整且未过期存下来,
|
|
414
|
+
// 后半段永远没人译(实测 61000 字符的块,模型只收到前 60012 字符,末尾标记收不到)。
|
|
415
|
+
// 明确失败交给上层:重试(同样的输入还是会超,除非换了模型/上限)与「保留旧完整译文」都已有路径。
|
|
416
|
+
if (text.truncated === true) {
|
|
417
|
+
const sizes = messages.blocks.map(block => ({ id: block?.id ?? '', size: sourceTextOf(block).length }))
|
|
418
|
+
const biggest = sizes.slice().sort((left, right) => right.size - left.size)[0]
|
|
419
|
+
return {
|
|
420
|
+
translations: [],
|
|
421
|
+
detail: `本批原文超出单次请求上限(${
|
|
422
|
+
sizes.reduce((sum, item) => sum + item.size, 0)} 字符,最大一块 ${biggest.id} 有 ${biggest.size} 字符),已拒绝发送:只译半段会被当成完整译文存下来`,
|
|
423
|
+
malformed: true,
|
|
424
|
+
missing: [...batch.blockIds],
|
|
425
|
+
usage: undefined,
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
const content = [{ type: 'text', text: text.user }]
|
|
429
|
+
// 图**在这之后**才去取:能力不支持视觉时连附件都不该写(渲染与落盘都是有代价的副作用)。
|
|
430
|
+
const imageRefs = supportsImages ? await acquireImages() : []
|
|
431
|
+
for (const ref of imageRefs) content.push({ type: 'image', attachment: ref })
|
|
432
|
+
const request = {
|
|
433
|
+
provider: model.provider,
|
|
434
|
+
model: model.model,
|
|
435
|
+
messages: [{ role: 'user', content }],
|
|
436
|
+
system: text.system,
|
|
437
|
+
maxTokens: deps.maxTokens,
|
|
438
|
+
temperature: deps.temperature,
|
|
439
|
+
signal: deps.signal,
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
let raw = ''
|
|
443
|
+
// 终止原因要留住:`max-tokens` 意味着回复被输出上限截断(推理型模型可能把额度全花在推理上、
|
|
444
|
+
// 一个 text-delta 都不发),这与「模型答非所问」是两种故障,修法也不同。
|
|
445
|
+
let finish = ''
|
|
446
|
+
// 宿主在终止 finish 之前发一次 { type: 'usage', usage }(packages/llm/llm/src/types.ts:458)。
|
|
447
|
+
// 以前这里直接把它丢掉,于是翻译的 token 用量全库无从统计(T24)。只收不发,不改变任何控制流:
|
|
448
|
+
// 没有 usage 的适配器照常跑,failed / malformed 分支也照常返回(用量随返回值一起带走)。
|
|
449
|
+
let usage
|
|
450
|
+
for await (const chunk of prepared.stream(request)) {
|
|
451
|
+
if (chunk?.type === 'text-delta' && typeof chunk.text === 'string') raw += chunk.text
|
|
452
|
+
else if (chunk?.type === 'usage') usage = chunk.usage
|
|
453
|
+
else if (chunk?.type === 'finish' && chunk.reason?.kind === 'error') {
|
|
454
|
+
return { translations: [], detail: chunk.reason.failure?.message ?? '模型调用失败', malformed: true, missing: [...batch.blockIds], usage }
|
|
455
|
+
} else if (chunk?.type === 'finish') finish = typeof chunk.reason?.kind === 'string' ? chunk.reason.kind : ''
|
|
456
|
+
}
|
|
457
|
+
// 🔴 先判**完整性**,再接受内容:`max-tokens` 意味着回复被输出上限截断。plain 档下它照样
|
|
458
|
+
// 是一个合法字符串,lines / json 也常常解析得出来 —— 于是半截译文被当成完整译文存下来
|
|
459
|
+
// (实测:终止原因明确是 max-tokens、正文只有半句,结果仍是 translated:1 / status:ok)。
|
|
460
|
+
// 终止原因为空(适配器不发 finish)时不作判断,保持与加这条规则之前一致。
|
|
461
|
+
if (finish !== '' && finish !== 'stop') {
|
|
462
|
+
return {
|
|
463
|
+
translations: [],
|
|
464
|
+
detail: `回复没有正常结束(终止原因 ${finish}),不收取被截断的译文;${replyDigest(raw, finish)}`,
|
|
465
|
+
malformed: true,
|
|
466
|
+
missing: [...batch.blockIds],
|
|
467
|
+
usage,
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
// 协议决定解析器:plain 的回复就是译文本身(没有 id 可对),lines / json 都走带 id 的那条。
|
|
471
|
+
const parsed = deps.protocol === 'plain' ? parsePlainReply(raw, batch.blockIds) : parseBatchReply(raw, batch.blockIds)
|
|
472
|
+
if (parsed.malformed) parsed.detail = `${parsed.detail};${replyDigest(raw, finish)}`
|
|
473
|
+
return { ...parsed, imagesAttached: imageRefs.length, usage }
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* 翻译一批。返回的 `translations` 只含**确实解析出来且 id 在期望列表里**的项 ——
|
|
478
|
+
* 畸形回复一律重试,重试仍失败就报错,**绝不写入半截或猜测的译文**。
|
|
479
|
+
*
|
|
480
|
+
* 并发/暂停/取消由上层驱动;这里是一次同步的批次执行。
|
|
481
|
+
*
|
|
482
|
+
* @param {{pages?: number[], blockIds: string[], blocks?: object[]}} batch
|
|
483
|
+
* @param {object} deps
|
|
484
|
+
* @returns {Promise<{translations: Array<{id: string, zh: string}>, images: number, attempts: number, error?: string}>}
|
|
485
|
+
*/
|
|
486
|
+
/** 默认的等待实现;测试用 `deps.wait` 注入,避免真的睡几秒。 */
|
|
487
|
+
const defaultWait = ms => new Promise(resolve => setTimeout(resolve, ms))
|
|
488
|
+
|
|
489
|
+
/** 限流退避的起点与上限(毫秒)。第一次 4s、第二次 8s,最多 30s。 */
|
|
490
|
+
const RATE_LIMIT_BASE_MS = 4000
|
|
491
|
+
const RATE_LIMIT_MAX_MS = 30000
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* 这个错误是不是**限流**(429 / RPM / too many requests / 频控)。
|
|
495
|
+
*
|
|
496
|
+
* 宿主适配器给的错误没有结构化 code,只能看文本 —— 实测样本:
|
|
497
|
+
* `429: {"message":"The request rate exceeds the current model RPM limit 60. Please reduce the request frequency…"}`。
|
|
498
|
+
* 识别它的意义不在分类,而在**决定要不要等**:见 translateBatch 里的退避。
|
|
499
|
+
*/
|
|
500
|
+
function isRateLimited(error) {
|
|
501
|
+
const text = String(error?.message ?? error ?? '')
|
|
502
|
+
return /\b429\b|rate[ _-]?limit|RPM limit|too many requests|reduce the request frequency/i.test(text)
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/**
|
|
506
|
+
* 这个错误是不是**账户级**的(额度耗尽 / 未授权 / 无权访问)—— 重发多少次都是同一个结果。
|
|
507
|
+
*
|
|
508
|
+
* 与限流的分工:限流(429)等一等有用;账户级错误只能换模型或充值,等多久都一样。
|
|
509
|
+
* 实测样本(腾讯 hy-mt2-pro 免费额度耗尽,2026-11-01):同一批 46 篇、每篇每批重试 3 次,
|
|
510
|
+
* 撞的全是同一个 `402: {"type":"permission_error","code":"401008",…}`,界面上就是「0/46 不动」。
|
|
511
|
+
*/
|
|
512
|
+
function isAccountError(error) {
|
|
513
|
+
const text = String(error?.message ?? error ?? '')
|
|
514
|
+
if (/\b(401|402|403)\b/.test(text)) return true
|
|
515
|
+
return /permission_error|insufficient_quota|unauthorized|invalid[ _-]?api[ _-]?key|insufficient[ _-]?balance/i.test(text)
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* 限流后该等多久:优先用错误自带的 `retryAfterMs`(有的适配器会带),否则按次数指数退避。
|
|
520
|
+
*
|
|
521
|
+
* 为什么必须等:服务端按**分钟窗口**计 RPM,立刻重发的请求必然还在同一个窗口里 ——
|
|
522
|
+
* 实测三次重试全部撞在同一个 60 RPM 窗口上,于是 14 篇论文直接进了「需手动重试」。
|
|
523
|
+
*/
|
|
524
|
+
function rateLimitDelayMs(attempt, error) {
|
|
525
|
+
const hinted = Number(error?.retryAfterMs)
|
|
526
|
+
if (Number.isFinite(hinted) && hinted > 0) return Math.min(Math.round(hinted), RATE_LIMIT_MAX_MS)
|
|
527
|
+
return Math.min(RATE_LIMIT_BASE_MS * 2 ** Math.max(0, attempt - 1), RATE_LIMIT_MAX_MS)
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
export async function translateBatch(batch, deps = {}) {
|
|
531
|
+
const blocks = blocksOfBatch(batch, deps)
|
|
532
|
+
const retries = nonNegativeInt(deps.retries, DEFAULT_RETRIES, 'retries')
|
|
533
|
+
const imagesPerBatch = nonNegativeInt(deps.imagesPerBatch, DEFAULT_IMAGES_PER_BATCH, 'imagesPerBatch')
|
|
534
|
+
const pageImageWidth = positiveInt(deps.pageImageWidth, DEFAULT_PAGE_IMAGE_WIDTH, 'pageImageWidth')
|
|
535
|
+
|
|
536
|
+
// 页面图是**惰性**的:只有模型确实要图时才渲染并写附件存储。渲染与落盘都是有代价的
|
|
537
|
+
// 副作用,模型看不到图时不该付。整段只做一次(重试复用同一批 ref),失败只降级不抛。
|
|
538
|
+
let imagesAcquired = false
|
|
539
|
+
let imageRefs = []
|
|
540
|
+
const acquireImages = async () => {
|
|
541
|
+
if (imagesAcquired) return imageRefs
|
|
542
|
+
imagesAcquired = true
|
|
543
|
+
const rendered = await renderImages(batch, { ...deps, pageImageWidth })
|
|
544
|
+
const picked = rendered.slice(0, imagesPerBatch)
|
|
545
|
+
if (rendered.length > picked.length) {
|
|
546
|
+
warn(deps.logger, `dsh-paper translate: 本批渲染了 ${rendered.length} 页,单请求上限 ${imagesPerBatch} 张,只带前 ${picked.length} 张`)
|
|
547
|
+
}
|
|
548
|
+
if (picked.length === 0) return imageRefs
|
|
549
|
+
if (typeof deps.attachments?.saveImages !== 'function') {
|
|
550
|
+
warn(deps.logger, 'dsh-paper translate: 没有附件服务,本批退回纯文本')
|
|
551
|
+
return imageRefs
|
|
552
|
+
}
|
|
553
|
+
try {
|
|
554
|
+
imageRefs = await deps.attachments.saveImages(picked.map(image => ({
|
|
555
|
+
data: image.data,
|
|
556
|
+
mediaType: 'image/webp',
|
|
557
|
+
name: `page-${image.page}.webp`,
|
|
558
|
+
})))
|
|
559
|
+
} catch (error) {
|
|
560
|
+
warn(deps.logger, `dsh-paper translate: 页面图存附件失败,本批退回纯文本:${error?.message ?? error}`)
|
|
561
|
+
imageRefs = []
|
|
562
|
+
}
|
|
563
|
+
return imageRefs
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
const all = blocks.length > 0 ? blocks : (Array.isArray(batch?.blockIds) ? batch.blockIds.map(id => ({ id, sourceText: id })) : [])
|
|
567
|
+
const order = all.map(block => block.id)
|
|
568
|
+
const byId = new Map(all.map(block => [block.id, block]))
|
|
569
|
+
// 🔴 **只重发还缺的那些块**,而不是整批重发。实测(本地 hy-mt2 1.8B,40 块/批、4 并发)里
|
|
570
|
+
// 局部缺行的批次占多数:整批重发一次要 ~70 秒、还要再赌一次 40 行全对;而缺的那几行单独发
|
|
571
|
+
// 只要 1–3 秒、命中率也高得多(输出越短越不容易跑偏)。契约不变:一次 translateBatch 要么
|
|
572
|
+
// 交出**全部**块的译文,要么报错 —— 中途收到的译文先存在这里,最后一次性交付。
|
|
573
|
+
const pending = new Map(byId)
|
|
574
|
+
const collected = new Map()
|
|
575
|
+
/** 译文结构对不上原文的表格块(重试仍不行就进错误信息,便于定位是哪一张表)。 */
|
|
576
|
+
const tableMismatch = new Set()
|
|
577
|
+
let attempts = 0
|
|
578
|
+
let lastDetail = ''
|
|
579
|
+
let lastMissing = [...order]
|
|
580
|
+
let images = 0
|
|
581
|
+
// 一次批次最多 retry 次,每次都真的发了请求 —— 用量按**调用次数**累加,
|
|
582
|
+
// 只留最后一次会把重试花的 token 从账本里抹掉(那正是最该看见的部分)。
|
|
583
|
+
// 🔴 用加法而不是覆盖:这里统计的是"这个批次一共花了多少",不是"最后一次花了多少"。
|
|
584
|
+
let usage
|
|
585
|
+
while (attempts <= retries && pending.size > 0) {
|
|
586
|
+
attempts += 1
|
|
587
|
+
const target = [...pending.values()]
|
|
588
|
+
const request = { blocks: target }
|
|
589
|
+
let parsed = null
|
|
590
|
+
try {
|
|
591
|
+
// 🔴 全局并发闸门(D157):一次 attemptBatch = **一次模型请求**,许可在这里取、请求结束
|
|
592
|
+
// 就还。闸门**不在更外层**(整批 / 整篇 / 队列)——那样一来重试这类额外请求就逃出了计数,
|
|
593
|
+
// 而它们同样打给模型提供方。
|
|
594
|
+
//
|
|
595
|
+
// 为什么需要它:队列的并发按 documentId 分流(一篇占一个位),单篇内又各有自己的批次并发。
|
|
596
|
+
// 两层相乘 = 并发数 × 论文数,与本设置"同时几个请求"的含义不符,也正是本地推理服务
|
|
597
|
+
// 被压垮、回复被截断成畸形 JSON 的直接原因。
|
|
598
|
+
const send = () => attemptBatch({ ...batch, blockIds: target.map(block => block.id), blocks: target }, { ...deps, pageImageWidth }, acquireImages, request)
|
|
599
|
+
parsed = deps.gate === undefined ? await send() : await deps.gate.run(send)
|
|
600
|
+
} catch (error) {
|
|
601
|
+
if (deps.signal?.aborted) throw error
|
|
602
|
+
lastDetail = String(error?.message ?? error)
|
|
603
|
+
// 🔴 账户级错误**不重试**:额度耗尽 / 未授权时,重发几次都是同一个 402,只会让整批任务
|
|
604
|
+
// 在界面上停在「0/N」,用户等到最后才知道全都没可能成功。原因里直接给下一步。
|
|
605
|
+
if (!isRateLimited(error) && isAccountError(error)) {
|
|
606
|
+
lastDetail += ';这是模型账户的额度或权限问题,重试不会成功:请在设置页换一个模型,或为该模型开通额度'
|
|
607
|
+
break
|
|
608
|
+
}
|
|
609
|
+
// 🔴 限流必须**等**再重试(见 rateLimitDelayMs 的实测说明)。等待期间用户取消就直接收手,
|
|
610
|
+
// 不能在取消后又发一次请求 —— 那笔钱不该花。
|
|
611
|
+
if (attempts <= retries && isRateLimited(error)) {
|
|
612
|
+
const waitMs = rateLimitDelayMs(attempts, error)
|
|
613
|
+
warn(deps.logger, `dsh-paper translate: 触发限流,${waitMs} ms 后重试(第 ${attempts} 次)`)
|
|
614
|
+
await (typeof deps.wait === 'function' ? deps.wait : defaultWait)(waitMs)
|
|
615
|
+
if (deps.signal?.aborted) throw error
|
|
616
|
+
}
|
|
617
|
+
continue
|
|
618
|
+
}
|
|
619
|
+
if (parsed === null) continue
|
|
620
|
+
usage = addUsage(usage, parsed.usage)
|
|
621
|
+
images = Math.max(images, parsed.imagesAttached ?? 0)
|
|
622
|
+
for (const item of parsed.translations) {
|
|
623
|
+
if (!pending.has(item.id)) continue
|
|
624
|
+
// 🔴 表格译文的**结构校验**:行列数、每行格数、数字多重集必须与原文一致。
|
|
625
|
+
// 表格可以翻,数值不可以变 —— 而模型把 0.8 写成 0.9、把一整行吞掉时,除了这里
|
|
626
|
+
// 没有任何别的信号能发现(论文表格的价值全在这些数与对应关系上)。
|
|
627
|
+
// 对不上就当这块没译好:留在 pending 里重试,重试完仍不行就整批报失败,绝不入库。
|
|
628
|
+
const body = tableBodyOf(byId.get(item.id))
|
|
629
|
+
if (body !== '' && !sameTableShape(body, item.zh)) {
|
|
630
|
+
tableMismatch.add(item.id)
|
|
631
|
+
continue
|
|
632
|
+
}
|
|
633
|
+
collected.set(item.id, item.zh)
|
|
634
|
+
pending.delete(item.id)
|
|
635
|
+
}
|
|
636
|
+
if (pending.size === 0) {
|
|
637
|
+
return { translations: order.filter(id => collected.has(id)).map(id => ({ id, zh: collected.get(id) })), images, attempts, usage }
|
|
638
|
+
}
|
|
639
|
+
lastDetail = tableMismatch.size > 0
|
|
640
|
+
? `表格结构与原文不一致(行列数或数值被改动):${[...tableMismatch].join(', ')}`
|
|
641
|
+
: parsed.malformed ? parsed.detail : `缺少 id:${[...pending.keys()].join(', ')}`
|
|
642
|
+
lastMissing = [...pending.keys()]
|
|
643
|
+
}
|
|
644
|
+
// 表格块连续对不上:不再重试,也不再让整批失败 —— 保留原文表格,记 skipped + 原因。
|
|
645
|
+
// 依据(用户裁定 2026-10-26):版面框与几十个数字的大表模型基本过不去,卡在这里等于整篇
|
|
646
|
+
// 永远翻不完;"不写不合格译文"这条不受影响(skipped 的 zh 仍然不写新值)。
|
|
647
|
+
const tableSkipped = order.filter(id => tableMismatch.has(id) && !collected.has(id))
|
|
648
|
+
if (tableSkipped.length > 0) {
|
|
649
|
+
return {
|
|
650
|
+
translations: order.filter(id => collected.has(id)).map(id => ({ id, zh: collected.get(id) })),
|
|
651
|
+
skipped: tableSkipped.map(id => ({ id, reason: TABLE_SKIPPED_REASON })),
|
|
652
|
+
images,
|
|
653
|
+
attempts,
|
|
654
|
+
usage,
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
return {
|
|
658
|
+
translations: [],
|
|
659
|
+
images,
|
|
660
|
+
attempts,
|
|
661
|
+
usage,
|
|
662
|
+
// 限流失败要给**可操作**的下一步:光说「429」用户不知道该怎么办。
|
|
663
|
+
error: `翻译批次失败(尝试 ${attempts} 次):${lastDetail || '未知原因'}${lastMissing.length > 0 ? `;仍缺 ${lastMissing.length} 个块` : ''}${isRateLimited(lastDetail) ? ';这是模型提供方的限流(RPM),稍后点「重试失败」或把设置页的并发调低再试' : ''}`,
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/**
|
|
668
|
+
* 把两次调用的用量相加。**只用于同一批次的多次尝试之间**,不是账本口径 ——
|
|
669
|
+
* 账本的幂等键是 jobId(见 lib/usage.js 的 mergeUsage),它按"同一次调用只记一次"去重;
|
|
670
|
+
* 而这里要的恰恰是"这个批次一共发了 N 次请求、合起来花了多少"。
|
|
671
|
+
*
|
|
672
|
+
* 字段口径与宿主 TokenUsage 一致(不相交计数):totalTokens 缺一个就按各项之和补,
|
|
673
|
+
* 两边都缺则退回 input + output(绝不让一个 undefined 传染成 NaN)。
|
|
674
|
+
* 任一入参不是对象就返回另一个 —— 没有 usage 的适配器(返回 undefined)不会把账算成 NaN。
|
|
675
|
+
*/
|
|
676
|
+
function addUsage(left, right) {
|
|
677
|
+
const a = left && typeof left === 'object' ? left : null
|
|
678
|
+
const b = right && typeof right === 'object' ? right : null
|
|
679
|
+
if (a === null) return b ?? undefined
|
|
680
|
+
if (b === null) return a
|
|
681
|
+
const sum = (x, y) => (Number.isFinite(x) ? x : 0) + (Number.isFinite(y) ? y : 0)
|
|
682
|
+
const inputTokens = sum(a.inputTokens, b.inputTokens)
|
|
683
|
+
const outputTokens = sum(a.outputTokens, b.outputTokens)
|
|
684
|
+
const cacheReadTokens = sum(a.cacheReadTokens, b.cacheReadTokens)
|
|
685
|
+
const cacheWriteTokens = sum(a.cacheWriteTokens, b.cacheWriteTokens)
|
|
686
|
+
const reasoningTokens = sum(a.reasoningTokens, b.reasoningTokens)
|
|
687
|
+
const declared = sum(a.totalTokens, b.totalTokens)
|
|
688
|
+
return {
|
|
689
|
+
inputTokens,
|
|
690
|
+
outputTokens,
|
|
691
|
+
cacheReadTokens,
|
|
692
|
+
cacheWriteTokens,
|
|
693
|
+
reasoningTokens,
|
|
694
|
+
totalTokens: declared > 0 ? declared : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens,
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
function revisionFor(previous, translated) {
|
|
699
|
+
const base = Number.isSafeInteger(previous?.revision) && previous.revision > 0 ? previous.revision : 0
|
|
700
|
+
return translated ? base + 1 : (base > 0 ? base : 1)
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
/**
|
|
704
|
+
* 跳过分支要**原样搬走**的只有 error 一个字段。
|
|
705
|
+
*
|
|
706
|
+
* 🔴 它是**状态**不是附注:{@link pendingForIncremental} 靠 `previous.error === TABLE_SKIPPED_REASON`
|
|
707
|
+
* 认出「这张表已判终态、别再试了」。跳过分支重写记录时漏掉它,下一轮就认不出终态,
|
|
708
|
+
* 重新排上、撞同一张表、再花一次模型请求 —— 每次「一键翻译」转一圈,永远不会停。
|
|
709
|
+
*
|
|
710
|
+
* 值必须在场才写入:undefined / 非字符串一律不产出键,免得凭空给记录添一个空 error。
|
|
711
|
+
*/
|
|
712
|
+
function previousErrorOf(previous) {
|
|
713
|
+
return isObject(previous) && typeof previous.error === 'string' && previous.error !== '' ? { error: previous.error } : {}
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* 翻译一整篇。**增量**:`existing` 里 sourceHash 与当前块一致的译文直接跳过,不重发请求;
|
|
718
|
+
* `translateAll` 为真时全部重译。
|
|
719
|
+
*
|
|
720
|
+
* `incremental`(默认 false)是**另一档更保守的增量**:只处理 {@link pendingForIncremental}
|
|
721
|
+
* 挑出来的块(没 id、没原文、或已有非空译文都不译),**哪怕原文变了也不重译**。
|
|
722
|
+
* 🔴 它给不出"译文是否过期"的答案,要刷新过期译文仍得走全译。
|
|
723
|
+
*
|
|
724
|
+
* 🔴 `incremental` 与 `translateAll` 同时为真时**以 `translateAll` 为准**(全译)——
|
|
725
|
+
* "全译"是二者的并集,这条优先级让"删掉 incremental 就能强制重译"始终成立。
|
|
726
|
+
*
|
|
727
|
+
* 🔴 结果与输入块**一一对应、无孤儿**:id 集合与顺序都跟 `input.blocks` 一致,
|
|
728
|
+
* 空 sourceText 的块与跳过/失败的块同样出现在结果里(带各自的 status)。
|
|
729
|
+
*
|
|
730
|
+
* @param {{blocks?: object[], targetLanguage?: string, existing?: object, batchPages?: number, maxBlocksPerBatch?: number, translateAll?: boolean, incremental?: boolean, protocol?: 'json'|'lines'}} input
|
|
731
|
+
* @param {object} deps 见 {@link translateBatch}
|
|
732
|
+
* @returns {Promise<{blocks: object[], stats: object}>}
|
|
733
|
+
*/
|
|
734
|
+
export async function translateDocument(input = {}, deps = {}) {
|
|
735
|
+
const source = Array.isArray(input.blocks) ? input.blocks : []
|
|
736
|
+
const existing = input.existing !== null && typeof input.existing === 'object' ? input.existing : {}
|
|
737
|
+
const translateAll = input.translateAll === true
|
|
738
|
+
const incremental = input.incremental === true
|
|
739
|
+
const model = deps.model ?? {}
|
|
740
|
+
// incremental 与 translateAll 同时为真 → translateAll 赢(见上面的注释):
|
|
741
|
+
// 让 incremental 只在"不打算全译"时收窄范围,两种意图不打架。
|
|
742
|
+
const pendingIds = incremental && !translateAll
|
|
743
|
+
? new Set(pendingForIncremental(source, input.existing))
|
|
744
|
+
: null
|
|
745
|
+
|
|
746
|
+
const results = new Map()
|
|
747
|
+
const toTranslate = []
|
|
748
|
+
for (const block of source) {
|
|
749
|
+
if (block === null || typeof block !== 'object' || typeof block.id !== 'string' || block.id === '') continue
|
|
750
|
+
const sourceHash = sourceHashOf(block)
|
|
751
|
+
const previous = existing[block.id]
|
|
752
|
+
const empty = translatableTextOf(block).trim() === ''
|
|
753
|
+
if (pendingIds !== null && !pendingIds.has(block.id)) {
|
|
754
|
+
// 🔴 error 必须跟着走:表格块的终态判据是 previous.error === TABLE_SKIPPED_REASON
|
|
755
|
+
// (见 pendingForIncremental)。这里把它丢了,下一轮就认不出终态、重新排上,
|
|
756
|
+
// 于是每次「一键翻译」都撞同一张表、再花一次模型请求,永远转圈(实测的死循环)。
|
|
757
|
+
results.set(block.id, { id: block.id, zh: typeof previous?.zh === 'string' ? previous.zh : '', sourceHash: previous?.sourceHash, model: previous?.model ?? model, revision: revisionFor(previous, false), status: 'skipped', ...previousErrorOf(previous) })
|
|
758
|
+
continue
|
|
759
|
+
}
|
|
760
|
+
if (!empty && !translateAll && previous?.sourceHash === sourceHash && typeof previous.zh === 'string' && previous.zh !== '') {
|
|
761
|
+
results.set(block.id, { id: block.id, zh: previous.zh, sourceHash, model: previous.model ?? model, revision: revisionFor(previous, false), status: 'skipped' })
|
|
762
|
+
continue
|
|
763
|
+
}
|
|
764
|
+
if (empty) {
|
|
765
|
+
results.set(block.id, { id: block.id, zh: typeof previous?.zh === 'string' ? previous.zh : '', sourceHash: previous?.sourceHash ?? sourceHash, model: previous?.model ?? model, revision: revisionFor(previous, false), status: 'skipped', ...previousErrorOf(previous) })
|
|
766
|
+
continue
|
|
767
|
+
}
|
|
768
|
+
toTranslate.push(block)
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
// plain 协议一次只翻一个块(回复就是译文本身,没有 id 可对):整篇 = 块数那么多次请求,
|
|
772
|
+
// 靠下面的批次并发把总时长压回来(435 块 × ~1 秒 ÷ 4 并发 ≈ 2 分钟)。
|
|
773
|
+
const plain = input.protocol === 'plain'
|
|
774
|
+
const plan = planBatches(toTranslate, {
|
|
775
|
+
batchPages: input.batchPages,
|
|
776
|
+
maxBlocksPerBatch: plain ? 1 : input.maxBlocksPerBatch,
|
|
777
|
+
})
|
|
778
|
+
const byId = new Map(toTranslate.map(block => [block.id, block]))
|
|
779
|
+
// 整篇的标题与摘要:模型每批只看得到一小段,给一份背景能稳住术语与文体(D140)。
|
|
780
|
+
const reference = documentReferenceOf(source)
|
|
781
|
+
let images = 0
|
|
782
|
+
// 各批次的 token 用量累加成整篇的一次调用记账(T24)。onUsage 由上层注入(见 translate-task.js):
|
|
783
|
+
// 本模块不认识账本,也不碰磁盘 —— 与页面图渲染走 deps.renderPages 注入是同一分工。
|
|
784
|
+
// 返回的批次携带的是**这一批全部尝试之和**,这里只需逐批相加。
|
|
785
|
+
let usage
|
|
786
|
+
// 并发上限:设置页那一档(deps.concurrency),非法或没给按 1(串行)。
|
|
787
|
+
// 它同时是队列的跨文档并发数(见 index.js 的 enqueue),两层各限各的。
|
|
788
|
+
const outcomes = await mapLimit(plan, positiveInt(deps.concurrency, 1, 'concurrency'), batch => translateBatch(
|
|
789
|
+
{ ...batch, blocks: batch.blockIds.map(id => byId.get(id)).filter(Boolean) },
|
|
790
|
+
{
|
|
791
|
+
...deps,
|
|
792
|
+
blocksById: byId,
|
|
793
|
+
targetLanguage: input.targetLanguage,
|
|
794
|
+
glossary: input.glossary,
|
|
795
|
+
// 输出协议随批次走(与 targetLanguage 同路):专用翻译模型用 lines / plain,通用模型用默认 json。
|
|
796
|
+
protocol: input.protocol,
|
|
797
|
+
// 参考段(标题 + 摘要)只给模型当背景,明确不翻译(D140)。一次算好、每个批次都用同一份。
|
|
798
|
+
previousContext: reference,
|
|
799
|
+
},
|
|
800
|
+
))
|
|
801
|
+
// 汇总放在全部批次跑完之后:并发下"边跑边累加"会因为交错而丢掉用量。
|
|
802
|
+
for (const [index, batch] of plan.entries()) {
|
|
803
|
+
const outcome = outcomes[index]
|
|
804
|
+
usage = addUsage(usage, outcome.usage)
|
|
805
|
+
images += outcome.images
|
|
806
|
+
const translated = new Map(outcome.translations.map(item => [item.id, item.zh]))
|
|
807
|
+
for (const id of batch.blockIds) {
|
|
808
|
+
const block = byId.get(id)
|
|
809
|
+
const sourceHash = sourceHashOf(block)
|
|
810
|
+
const previous = existing[id]
|
|
811
|
+
const zh = translated.get(id)
|
|
812
|
+
if (typeof zh === 'string') {
|
|
813
|
+
results.set(id, { id, zh, sourceHash, model, revision: revisionFor(previous, true), status: 'ok' })
|
|
814
|
+
continue
|
|
815
|
+
}
|
|
816
|
+
const tableSkip = (Array.isArray(outcome.skipped) ? outcome.skipped : [])
|
|
817
|
+
.find(item => item !== null && typeof item === 'object' && item.id === id)
|
|
818
|
+
if (tableSkip !== undefined) {
|
|
819
|
+
// 表格块保留原文:zh 沿用旧值(没有旧值就是空串),整篇照常算完成。
|
|
820
|
+
results.set(id, {
|
|
821
|
+
id,
|
|
822
|
+
zh: typeof previous?.zh === 'string' ? previous.zh : '',
|
|
823
|
+
sourceHash: typeof previous?.zh === 'string' && previous.zh !== '' ? previous.sourceHash : sourceHash,
|
|
824
|
+
model: previous?.model ?? model,
|
|
825
|
+
revision: revisionFor(previous, false),
|
|
826
|
+
status: 'skipped',
|
|
827
|
+
error: typeof tableSkip.reason === 'string' && tableSkip.reason !== '' ? tableSkip.reason : TABLE_SKIPPED_REASON,
|
|
828
|
+
})
|
|
829
|
+
continue
|
|
830
|
+
}
|
|
831
|
+
results.set(id, {
|
|
832
|
+
id,
|
|
833
|
+
zh: typeof previous?.zh === 'string' ? previous.zh : '',
|
|
834
|
+
sourceHash: typeof previous?.zh === 'string' && previous.zh !== '' ? previous.sourceHash : sourceHash,
|
|
835
|
+
model: previous?.model ?? model,
|
|
836
|
+
revision: revisionFor(previous, false),
|
|
837
|
+
status: 'failed',
|
|
838
|
+
error: outcome.error ?? '本批没有返回该块的译文',
|
|
839
|
+
})
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
// 结果按输入顺序输出,保证与 input.blocks 一一对应;没有进 any 批的块(空 sourceText 之外
|
|
844
|
+
// 只可能是入参本身不合法)也要占位,绝不静默丢掉一个块。
|
|
845
|
+
const out = []
|
|
846
|
+
const counts = { requested: source.length, translated: 0, skipped: 0, failed: 0 }
|
|
847
|
+
for (const block of source) {
|
|
848
|
+
const id = block !== null && typeof block === 'object' ? block.id : undefined
|
|
849
|
+
const entry = typeof id === 'string' ? results.get(id) : undefined
|
|
850
|
+
if (entry === undefined) {
|
|
851
|
+
out.push({ id: typeof id === 'string' ? id : '', zh: '', sourceHash: sourceHashOf(block), model, revision: 1, status: 'skipped', ...previousErrorOf(existing[typeof id === 'string' ? id : '']) })
|
|
852
|
+
counts.skipped += 1
|
|
853
|
+
continue
|
|
854
|
+
}
|
|
855
|
+
if (entry.status === 'ok') counts.translated += 1
|
|
856
|
+
else if (entry.status === 'failed') counts.failed += 1
|
|
857
|
+
else counts.skipped += 1
|
|
858
|
+
out.push(entry)
|
|
859
|
+
}
|
|
860
|
+
if (usage !== undefined && typeof deps.onUsage === 'function') {
|
|
861
|
+
// 记账是**副作用**,绝不让它影响翻译结果:账本写不进去(磁盘满、被占用、权限)时
|
|
862
|
+
// 整篇翻译照常返回,只记一行警告 —— 用户要的是译文,账是附属品。
|
|
863
|
+
try {
|
|
864
|
+
await deps.onUsage(usage, { batches: plan.length, model })
|
|
865
|
+
} catch (error) {
|
|
866
|
+
warn(deps.logger, `dsh-paper translate: 用量记账失败,本篇译文不受影响:${error?.message ?? error}`)
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
return { blocks: out, stats: { ...counts, batches: plan.length, images } }
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* 读译文文件。文件不存在、不是 JSON、顶层不是对象,一律返回 null —— 调用方据此按"还没翻译"
|
|
874
|
+
* 处理,而不是把一次坏读变成整篇不可用。
|
|
875
|
+
*
|
|
876
|
+
* @param {string} path
|
|
877
|
+
* @returns {Promise<{schemaVersion?: number, blocks?: object[], stats?: object}|null>}
|
|
878
|
+
*/
|
|
879
|
+
export async function readTranslation(path) {
|
|
880
|
+
try {
|
|
881
|
+
const parsed = JSON.parse(await readFile(path, 'utf8'))
|
|
882
|
+
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
|
|
883
|
+
return parsed
|
|
884
|
+
} catch {
|
|
885
|
+
return null
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/**
|
|
890
|
+
* 原子写译文文件:临时文件 + {@link replaceStateFile}(已处理 Windows 上 rename 被占用句柄的
|
|
891
|
+
* 退避重试)。临时名带 pid 与时间戳,并发写不会互相覆盖。
|
|
892
|
+
*
|
|
893
|
+
* @param {string} path
|
|
894
|
+
* @param {object} payload
|
|
895
|
+
*/
|
|
896
|
+
/** 见 library.js 的 temporarySequence:同毫秒并发的写必须有**独占的**临时名,否则 rename ENOENT。 */
|
|
897
|
+
let translateTemporarySequence = 0
|
|
898
|
+
|
|
899
|
+
export async function writeTranslation(path, payload) {
|
|
900
|
+
const body = { schemaVersion: TRANSLATION_SCHEMA_VERSION, ...payload }
|
|
901
|
+
const directory = dirname(path)
|
|
902
|
+
await mkdir(directory, { recursive: true })
|
|
903
|
+
// 序号见 library.js 的 temporarySequence:只用 pid + 毫秒会让同毫秒的并发写撞名 → rename ENOENT。
|
|
904
|
+
translateTemporarySequence += 1
|
|
905
|
+
const temporary = `${path}.${process.pid}.${Date.now()}.${translateTemporarySequence}.tmp`
|
|
906
|
+
await writeFile(temporary, JSON.stringify(body, null, 2), 'utf8')
|
|
907
|
+
await replaceStateFile(temporary, path)
|
|
908
|
+
return body
|
|
909
|
+
}
|