@li-canghai/dsh-paper 0.8.1 → 0.8.2
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/lib/client-parts/01-pure-helpers.js +287 -2
- package/lib/client.js +359 -6
- package/lib/gloss.js +1018 -9
- package/lib/index.js +60 -4
- package/lib/pdf-page.js +91 -5
- package/lib/translate-prompts.js +11 -1
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +5 -2
package/lib/index.js
CHANGED
|
@@ -15,7 +15,7 @@ import { PaperResolver, RETRYABLE_JOB_STATUSES } from './resolver.js'
|
|
|
15
15
|
import { mineruSdkConfig, parseWithConfiguredMineruSdk } from './mineru-sdk.js'
|
|
16
16
|
import { isWithin, mirrorParseResult } from './mirror-export.js'
|
|
17
17
|
import { normalizeCanvas, renderPageImages } from './page-image.js'
|
|
18
|
-
import { cropPdfGroups, pdfPageGroups, readPdfPage } from './pdf-page.js'
|
|
18
|
+
import { cropPdfGroups, pdfPageGroups, pdfQuoteInText, readPdfPage } from './pdf-page.js'
|
|
19
19
|
import { probeRenderer } from './renderer-status.js'
|
|
20
20
|
import { installDependency } from './install-dependency.js'
|
|
21
21
|
import { createUpdateService } from './update-check.js'
|
|
@@ -392,6 +392,18 @@ function mergeReaderBlocks(blocks, translation) {
|
|
|
392
392
|
})
|
|
393
393
|
}
|
|
394
394
|
|
|
395
|
+
/**
|
|
396
|
+
* 两侧**折掉空白后**逐字相等。
|
|
397
|
+
*
|
|
398
|
+
* 只服务「整段选区」这一个判断:PDF 原页的 group.text 在行与行之间补了空格,而选区那侧
|
|
399
|
+
* (或 DOM 的 textContent)一个分隔符都没有,同一个覆盖范围在两侧差着几个空格。
|
|
400
|
+
*/
|
|
401
|
+
function sameIgnoringSpace(left, right) {
|
|
402
|
+
const squeeze = value => String(value ?? '').replace(/[\s\u00ad\u200b\u200c\u200d\ufeff]+/gu, '')
|
|
403
|
+
const a = squeeze(left)
|
|
404
|
+
return a !== '' && a === squeeze(right)
|
|
405
|
+
}
|
|
406
|
+
|
|
395
407
|
/** 日志里的文档 id 截断:state 记录可能来自手工改过的文件,不能拿它拼无上限的日志行。 */
|
|
396
408
|
function truncateForLog(value, max = 64) {
|
|
397
409
|
const text = String(value ?? '')
|
|
@@ -3325,7 +3337,33 @@ function hasMeaningfulValue(value) {
|
|
|
3325
3337
|
if (nativeContext) sourceContext = nativeContext
|
|
3326
3338
|
}
|
|
3327
3339
|
let counterpart = ''
|
|
3340
|
+
// counterpart 属于哪一侧。对齐分支里由 fromSource 定;非对齐分支留空(那时没有 counterpart)。
|
|
3341
|
+
let counterpartKind
|
|
3328
3342
|
let selectedContext = ''
|
|
3343
|
+
/**
|
|
3344
|
+
* 把「另一语言的范围」写回这条划线。
|
|
3345
|
+
*
|
|
3346
|
+
* 🔴 写回前**按最新块重校验**:align 是一次模型调用,期间正文可能被重译、译文可能被改。
|
|
3347
|
+
* 拿旧的两侧去写 parallelQuote 会把一个已经不存在的位置记进盘里,下次打开就画错地方。
|
|
3348
|
+
* 校验口径与调用方一致:两侧都必须仍然是「latestSource 或 latestTranslation」之一。
|
|
3349
|
+
*/
|
|
3350
|
+
const writeParallel = parallelQuote => serializeMarks(async () => {
|
|
3351
|
+
const path = readerPathOf(document)
|
|
3352
|
+
if (!path) return json({reason:'no-match'})
|
|
3353
|
+
// 写入路径必须用严格读:这里要基于文件内容改写,坏读降级成空表等于把整篇划线换掉。
|
|
3354
|
+
const store = await readReaderStoreForWrite(path)
|
|
3355
|
+
const marks = Array.isArray(store?.marks) ? [...store.marks] : []
|
|
3356
|
+
const index = marks.findIndex(mark => mark.id === body.markId && mark.blockId === blockId && plainInlineText(mark.quote) === glossQuote)
|
|
3357
|
+
if (index < 0) return json({reason:'no-match',error:'划线已删除或改变'})
|
|
3358
|
+
const latestBlocks = mergeReaderBlocks((await readerBlocksOf(documentPaths(document).contentPath)).blocks, await readTranslation(translationPathOf(document)))
|
|
3359
|
+
const latest = latestBlocks.find(row=>row.id===blockId)
|
|
3360
|
+
const latestNative = nativeContext ? (await pdfPageFor(document, body.pdfPage, latestBlocks)).groups.find(group => group.id === blockId)?.text : ''
|
|
3361
|
+
const latestSource = latestNative || plainInlineText(latest?.sourceText ?? ''), latestTranslation = plainInlineText(latest?.zh ?? '')
|
|
3362
|
+
if (!([latestSource,latestTranslation].includes(sourceContext) && [latestSource,latestTranslation].includes(counterpart))) return json({reason:'no-match',error:'正文或译文已更新,请重新匹配'})
|
|
3363
|
+
marks[index] = {...marks[index],parallelQuote}
|
|
3364
|
+
await writeReaderStore(path,{...store,marks})
|
|
3365
|
+
return json({markId:body.markId,parallelQuote})
|
|
3366
|
+
})
|
|
3329
3367
|
if (body.align === true) {
|
|
3330
3368
|
const store = await readReaderStore(readerPathOf(document))
|
|
3331
3369
|
const mark = (Array.isArray(store?.marks)?store.marks:[]).find(mark=>mark.id===body.markId && mark.blockId===blockId && plainInlineText(mark.quote)===glossQuote)
|
|
@@ -3336,21 +3374,39 @@ function hasMeaningfulValue(value) {
|
|
|
3336
3374
|
const source = nativeContext || plainInlineText(block?.sourceText ?? ''), translated = plainInlineText(block?.zh ?? '')
|
|
3337
3375
|
if (!source || !translated || !glossQuote.trim()) return json({reason:'no-match'})
|
|
3338
3376
|
// Anchor against the selected language; the model must copy from the other one.
|
|
3339
|
-
|
|
3377
|
+
// 🔴 原页那侧(source 来自 group.text)与选中串的行接缝口径不同,必须走
|
|
3378
|
+
// pdfQuoteInText 的空白无关比较,理由与 /marks 的校验完全一样:group.text 在
|
|
3379
|
+
// 行与行之间补一个空格,而 DOM 的 textContent 一个分隔符都没有。用裸 includes
|
|
3380
|
+
// 时,PDF 原页上的跨行选区一律判 no-match —— 界面报「另一语言暂未定位」,
|
|
3381
|
+
// 而两侧的文字其实都在。译文那侧是同一份 plainInlineText 产物,照旧精确比较。
|
|
3382
|
+
const inSource = pdfQuoteInText(source, glossQuote), inTranslation = translated.includes(glossQuote)
|
|
3340
3383
|
const fromSource = mark.sourceLanguage === 'source' ? true : mark.sourceLanguage === 'translation' ? false : inSource
|
|
3341
3384
|
if (!mark.sourceLanguage && inSource && inTranslation) return json({reason:'already-matched'})
|
|
3342
3385
|
if (fromSource ? !inSource : !inTranslation) return json({reason:'no-match'})
|
|
3343
3386
|
sourceContext = fromSource ? source : translated
|
|
3344
3387
|
counterpart = fromSource ? translated : source
|
|
3388
|
+
counterpartKind = fromSource ? 'translation' : 'source'
|
|
3345
3389
|
if (Math.max(sourceContext.length,counterpart.length) > 60000) return json({reason:'no-match',error:'段落过长,未执行自动匹配'})
|
|
3390
|
+
// 🔴 **整段选区不需要模型**:模型那一档要它「从译文里挑最短的唯一连续子串」,而选区
|
|
3391
|
+
// 覆盖整段时正确答案就是**整段译文**,没有任何可挑的余地。实测 ResNet 第 2 页
|
|
3392
|
+
// p2-p2:用户在 PDF 原页上从头划到尾(693 字,折空白后与 group.text 的 589 字全等),
|
|
3393
|
+
// 模型被问了两次都只回 6–9 个 token(输出 NONE 一类),验收的 indexOf 必然落空,
|
|
3394
|
+
// 界面报「另一语言暂未定位」—— 两侧的文字其实都在,而且一一对应。
|
|
3395
|
+
// 判据用折空白后的相等:group.text 在行接缝补了空格,选区那侧没有。
|
|
3396
|
+
if (fromSource ? sameIgnoringSpace(source, glossQuote) : sameIgnoringSpace(translated, glossQuote)) {
|
|
3397
|
+
return await writeParallel(counterpart)
|
|
3398
|
+
}
|
|
3346
3399
|
}
|
|
3347
3400
|
const settings = state.settings
|
|
3348
3401
|
const model = await resolveTranslationModel()
|
|
3349
3402
|
translationGate.setLimit(concurrencyOf(settings))
|
|
3403
|
+
// counterpart 是哪一侧这里**确定知道**(对齐分支按 fromSource 赋值),
|
|
3404
|
+
// 传下去就不必让 gloss.js 靠字符统计去猜 —— 猜错的代价见 counterpartLanguage 的说明。
|
|
3350
3405
|
const outcome = await translateSelection({
|
|
3351
3406
|
quote: glossQuote,
|
|
3352
3407
|
context: sourceContext,
|
|
3353
3408
|
counterpart,
|
|
3409
|
+
counterpartKind,
|
|
3354
3410
|
selectedContext,
|
|
3355
3411
|
reference: documentReferenceOf(Array.isArray(blocks) ? blocks : []),
|
|
3356
3412
|
targetLanguage: settings?.translationLanguage,
|
|
@@ -3566,7 +3622,7 @@ function hasMeaningfulValue(value) {
|
|
|
3566
3622
|
// 与单段同一条校验:PDF 标注必须确实存在于原页那一段的文字里。
|
|
3567
3623
|
if (native === null) continue
|
|
3568
3624
|
const group = native.groups.find(group => group.id === segment.blockId)
|
|
3569
|
-
if (!group?.text
|
|
3625
|
+
if (!pdfQuoteInText(group?.text, segment.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
|
|
3570
3626
|
}
|
|
3571
3627
|
const groupId = randomUUID()
|
|
3572
3628
|
const created = segments.map(segment => makeMark({
|
|
@@ -3592,7 +3648,7 @@ function hasMeaningfulValue(value) {
|
|
|
3592
3648
|
if (!Number.isSafeInteger(body.pdfPage) || body.pdfPage < 1 || body.sourceLanguage !== 'source') return json({ error: 'PDF 标注页码或语言无效' }, 400)
|
|
3593
3649
|
const native = await pdfPageFor(document, body.pdfPage)
|
|
3594
3650
|
const group = native.groups.find(group => group.id === body.blockId)
|
|
3595
|
-
if (typeof body.quote !== 'string' || !body.quote.trim() || !group?.text
|
|
3651
|
+
if (typeof body.quote !== 'string' || !body.quote.trim() || !pdfQuoteInText(group?.text, body.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
|
|
3596
3652
|
}
|
|
3597
3653
|
const mark = makeMark({
|
|
3598
3654
|
blockId: body.blockId,
|
package/lib/pdf-page.js
CHANGED
|
@@ -118,8 +118,81 @@ function sameLine(a, b) {
|
|
|
118
118
|
return Math.min(a[3], b[3]) - Math.max(a[1], b[1]) > Math.min(a[3] - a[1], b[3] - b[1]) * 0.5 && b[0] >= a[0]
|
|
119
119
|
}
|
|
120
120
|
|
|
121
|
+
/** 中位数;空集返回 NaN(调用方据此走回退分支)。不改入参。 */
|
|
122
|
+
function median(values) {
|
|
123
|
+
if (values.length === 0) return NaN
|
|
124
|
+
const sorted = [...values].sort((a, b) => a - b)
|
|
125
|
+
const middle = sorted.length >> 1
|
|
126
|
+
return sorted.length % 2 === 1 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 一行文字的**行带**(满页 0–1000 坐标里的上下沿)。
|
|
131
|
+
*
|
|
132
|
+
* 🔴 高度与中心各取一次中位数,两样都不取 min/max:
|
|
133
|
+
* · 高度用 min/max 时,行内一个超高字形会把整行撑大(见 pdfPageGroups 里的实测说明);
|
|
134
|
+
* · 中心用 min/max 时,上标 / 下标会把整行往上或往下拽。
|
|
135
|
+
* 逐**字符**框取中位数而不是逐词:一个词里只要有一个字特别高(`(x)` 的括号),那个词框就
|
|
136
|
+
* 整块变高,逐词中位数还是会被它带偏;逐字符时多数派才是真正的中位数。
|
|
137
|
+
*
|
|
138
|
+
* 字框全都不可用时退回词框的 min/max —— 宁可准确度差一点,也不能没有行带。
|
|
139
|
+
*
|
|
140
|
+
* @param {object[]} words 同一物理行的词(每个词可能带 chars)。
|
|
141
|
+
* @returns {{top: number, bottom: number}} 满页坐标里的行带上、下沿。
|
|
142
|
+
*/
|
|
143
|
+
function lineBandOf(words) {
|
|
144
|
+
const heights = []
|
|
145
|
+
const centers = []
|
|
146
|
+
for (const word of words) {
|
|
147
|
+
const boxes = Array.isArray(word.chars) && word.chars.length > 0 ? word.chars : [word]
|
|
148
|
+
for (const box of boxes) {
|
|
149
|
+
const height = box.bbox[3] - box.bbox[1]
|
|
150
|
+
if (Number.isFinite(height) && height > 0) heights.push(height)
|
|
151
|
+
centers.push((box.bbox[1] + box.bbox[3]) / 2)
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const height = median(heights)
|
|
155
|
+
const center = median(centers)
|
|
156
|
+
if (!Number.isFinite(height) || !Number.isFinite(center)) {
|
|
157
|
+
return {
|
|
158
|
+
top: Math.min(...words.map(word => word.bbox[1])),
|
|
159
|
+
bottom: Math.max(...words.map(word => word.bbox[3])),
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return { top: center - height / 2, bottom: center + height / 2 }
|
|
163
|
+
}
|
|
164
|
+
|
|
121
165
|
const matchingText = value => plainInlineText(value).normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
|
|
122
166
|
|
|
167
|
+
/**
|
|
168
|
+
* 一段**屏上选中的原话**是不是确实出自这一页的原生文字。
|
|
169
|
+
*
|
|
170
|
+
* 🔴 比较必须**忽略空白**,因为两侧的行接缝本来就不同源:
|
|
171
|
+
* · {@link pdfPageGroups} 拼的 `group.text` 在行与行之间补一个空格("…problem by introducing…");
|
|
172
|
+
* · 客户端拿的是 DOM 的 `textContent`,而每一行是 `display:block` 的绝对定位 span,
|
|
173
|
+
* 行与行之间**一个分隔符都没有**("…problem byintroducing…")。
|
|
174
|
+
*
|
|
175
|
+
* 于是跨行选区在旧的 `text.includes(quote)` 下**必然**失败,报「选区与 PDF 原页文字不符」——
|
|
176
|
+
* 而用户并没有选错:他选的就是屏上那几行。实测 ResNet 第 2 页 14 个段落里 12 个都受影响,
|
|
177
|
+
* 只有不跨行的选区才能存下来。
|
|
178
|
+
*
|
|
179
|
+
* 归一范围只到空白:连字符断词两侧本来就一致(`pdfPageGroups` 已把 `high-` + `way` 拼成
|
|
180
|
+
* `highway`,DOM 里两段拼起来也是 `highway`),软连字符与零宽字符一并去掉即可。
|
|
181
|
+
*
|
|
182
|
+
* @param {string} text 这一块在原生文字层里的全文({@link pdfPageGroups} 的 `text`)。
|
|
183
|
+
* @param {string} quote 浏览器选中的那一段。
|
|
184
|
+
* @returns {boolean}
|
|
185
|
+
*/
|
|
186
|
+
export function pdfQuoteInText(text, quote) {
|
|
187
|
+
const left = String(text ?? '')
|
|
188
|
+
const right = String(quote ?? '')
|
|
189
|
+
if (right.trim() === '') return false
|
|
190
|
+
if (left.includes(right)) return true
|
|
191
|
+
const squeeze = value => value.replace(/[\s\u00ad\u200b\u200c\u200d\ufeff]+/gu, '')
|
|
192
|
+
const squeezedLeft = squeeze(left)
|
|
193
|
+
return squeezedLeft !== '' && squeezedLeft.includes(squeeze(right))
|
|
194
|
+
}
|
|
195
|
+
|
|
123
196
|
/**
|
|
124
197
|
* **结构性块**:文字在 caption 里,PDF 文字层的正文词永远不该归给它们。
|
|
125
198
|
*
|
|
@@ -212,12 +285,25 @@ export function pdfPageGroups(page, blocks) {
|
|
|
212
285
|
}
|
|
213
286
|
}
|
|
214
287
|
return [...grouped.values()].filter(group => group.words.length > 0).map(group => {
|
|
215
|
-
|
|
288
|
+
// 先把词按物理行归堆,再给**每一行**算一个统一的行带。
|
|
289
|
+
//
|
|
290
|
+
// 🔴 行带的高度**不能**取这一行所有词框的 min/max:行内只要有一个比正文高得多的字形
|
|
291
|
+
// (公式的括号、上标、根号),整行就被撑成它的高度。实测 ResNet 第 2 页 "…mapping as
|
|
292
|
+
// H(x), we let…":正文词框 8.9pt 高,`H(x)` 的括号 21.9pt,min/max 得到 17.3px 行带,
|
|
293
|
+
// 而这一页的真实行距只有 15px —— 客户端拿行带高当 font-size 与行高,浏览器再把选区块
|
|
294
|
+
// 画成约 1.45×font-size 的文字矩形(25.1px),于是上下各压掉相邻行一截:用户看到的就是
|
|
295
|
+
// 「蓝色块互相重叠」。纯文字行没被撑大,所以症状是**部分重叠、部分正常**。
|
|
296
|
+
// 中位数对单个超高字形免疫:8.9pt 的正文词占多数,行带就还是 8.9pt。
|
|
297
|
+
const lines = []
|
|
216
298
|
for (const word of group.words) {
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
word
|
|
299
|
+
const previous = lines.at(-1)
|
|
300
|
+
if (!previous || !sameLine(previous.last, word.bbox)) lines.push({ last: word.bbox, words: [] })
|
|
301
|
+
lines.at(-1).last = word.bbox
|
|
302
|
+
lines.at(-1).words.push(word)
|
|
303
|
+
}
|
|
304
|
+
for (const line of lines) {
|
|
305
|
+
const band = lineBandOf(line.words)
|
|
306
|
+
for (const word of line.words) word.line = band
|
|
221
307
|
}
|
|
222
308
|
// 每个词后面那个词是不是**同一行**的续词、以及是不是断词连写(gen- / erated)。
|
|
223
309
|
// 两条都要留到拼正文那一步用,所以先算一遍存下来。
|
package/lib/translate-prompts.js
CHANGED
|
@@ -75,7 +75,17 @@ function normalizeLanguage(targetLanguage) {
|
|
|
75
75
|
return isNonEmptyString(targetLanguage) ? targetLanguage.trim() : 'zh'
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
-
|
|
78
|
+
/**
|
|
79
|
+
* 目标语言的**显示名**(`zh` → `简体中文`)。未登记的代码原样回显。
|
|
80
|
+
*
|
|
81
|
+
* 🔴 导出给 gloss.js 的对齐档用:那一档要明写「译成什么语言」。写成「译成 targetText
|
|
82
|
+
* 的语言」会翻车 —— 实测 2026-11-19 本地 hy-mt2 把英文短语译成了**泰语**,而 targetText
|
|
83
|
+
* 明明是简体中文。语言只能由设置说了算,不能留给模型猜。
|
|
84
|
+
*
|
|
85
|
+
* @param {string} code
|
|
86
|
+
* @returns {string}
|
|
87
|
+
*/
|
|
88
|
+
export function languageNameOf(code) {
|
|
79
89
|
return LANGUAGE_NAMES[code] || code
|
|
80
90
|
}
|
|
81
91
|
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@li-canghai/dsh-paper",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.2",
|
|
4
4
|
"description": "PDF transcription with stable block ids, folder scanning up to two sub-levels, and session-scoped paper context with drag-select batch injection and removal for DSH.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./lib/index.js",
|
|
9
9
|
"./client": "./lib/client.js",
|
|
10
|
+
"./locale/en.json": "./locale/en.json",
|
|
11
|
+
"./locale/zh.json": "./locale/zh.json",
|
|
10
12
|
"./package.json": "./package.json"
|
|
11
13
|
},
|
|
12
14
|
"files": [
|
|
13
15
|
"lib",
|
|
14
16
|
"cordis.patch.yml",
|
|
15
17
|
"README.md",
|
|
16
|
-
"LICENSE"
|
|
18
|
+
"LICENSE",
|
|
19
|
+
"locale"
|
|
17
20
|
],
|
|
18
21
|
"scripts": {
|
|
19
22
|
"test": "node --test \"test/*.test.js\"",
|