@li-canghai/dsh-paper 0.8.0 → 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/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
- const inSource = source.includes(glossQuote), inTranslation = translated.includes(glossQuote)
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.includes(segment.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
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.includes(body.quote)) return json({ error: '选区与 PDF 原页文字不符,请重新选择' }, 400)
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,
@@ -1,35 +1,35 @@
1
- $ErrorActionPreference = 'Stop'
2
- [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
3
- [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
4
-
5
- try {
6
- $Request = [Console]::In.ReadToEnd() | ConvertFrom-Json
7
- if ($Request.task -eq 'certificates') {
8
- $Certificates = @()
9
- foreach ($Location in @('CurrentUser', 'LocalMachine')) {
10
- foreach ($StoreName in @('Root', 'CertificateAuthority')) {
11
- $Store = New-Object System.Security.Cryptography.X509Certificates.X509Store($StoreName, $Location)
12
- try {
13
- $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
14
- foreach ($Certificate in $Store.Certificates) {
15
- $Certificates += '-----BEGIN CERTIFICATE-----' + "`n" + [Convert]::ToBase64String($Certificate.RawData) + "`n-----END CERTIFICATE-----"
16
- }
17
- } finally { $Store.Close() }
18
- }
19
- }
20
- @{ certificates = @($Certificates) } | ConvertTo-Json -Compress
21
- exit 0
22
- }
23
- $Destination = [Uri]$Request.url
24
- if ($Destination.Scheme -notin @('http', 'https')) { exit 1 }
25
- $SystemProxy = [System.Net.WebRequest]::GetSystemWebProxy()
26
- $ProxyAddress = $SystemProxy.GetProxy($Destination)
27
- $Address = $null
28
- if ($null -ne $ProxyAddress -and $ProxyAddress.AbsoluteUri -ne $Destination.AbsoluteUri) {
29
- $Address = $ProxyAddress.AbsoluteUri
30
- }
31
- @{ proxy = $Address } | ConvertTo-Json -Compress
32
- } catch {
33
- # Configuration values and proxy authentication details stay out of diagnostics.
34
- exit 1
35
- }
1
+ $ErrorActionPreference = 'Stop'
2
+ [Console]::InputEncoding = New-Object System.Text.UTF8Encoding($false)
3
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)
4
+
5
+ try {
6
+ $Request = [Console]::In.ReadToEnd() | ConvertFrom-Json
7
+ if ($Request.task -eq 'certificates') {
8
+ $Certificates = @()
9
+ foreach ($Location in @('CurrentUser', 'LocalMachine')) {
10
+ foreach ($StoreName in @('Root', 'CertificateAuthority')) {
11
+ $Store = New-Object System.Security.Cryptography.X509Certificates.X509Store($StoreName, $Location)
12
+ try {
13
+ $Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadOnly)
14
+ foreach ($Certificate in $Store.Certificates) {
15
+ $Certificates += '-----BEGIN CERTIFICATE-----' + "`n" + [Convert]::ToBase64String($Certificate.RawData) + "`n-----END CERTIFICATE-----"
16
+ }
17
+ } finally { $Store.Close() }
18
+ }
19
+ }
20
+ @{ certificates = @($Certificates) } | ConvertTo-Json -Compress
21
+ exit 0
22
+ }
23
+ $Destination = [Uri]$Request.url
24
+ if ($Destination.Scheme -notin @('http', 'https')) { exit 1 }
25
+ $SystemProxy = [System.Net.WebRequest]::GetSystemWebProxy()
26
+ $ProxyAddress = $SystemProxy.GetProxy($Destination)
27
+ $Address = $null
28
+ if ($null -ne $ProxyAddress -and $ProxyAddress.AbsoluteUri -ne $Destination.AbsoluteUri) {
29
+ $Address = $ProxyAddress.AbsoluteUri
30
+ }
31
+ @{ proxy = $Address } | ConvertTo-Json -Compress
32
+ } catch {
33
+ # Configuration values and proxy authentication details stay out of diagnostics.
34
+ exit 1
35
+ }
@@ -92,26 +92,37 @@ def _text_page(page, index: int, output_dir: Path, page_count: int):
92
92
  raise ValueError("PDF text coordinate conversion failed")
93
93
  return [px.value * 1000 / device_width, py.value * 1000 / device_height]
94
94
 
95
+ def char_box(at):
96
+ left, bottom, right, top = text.get_charbox(at, loose=True)
97
+ corners = [point(left, bottom), point(left, top), point(right, bottom), point(right, top)]
98
+ return [min(p[0] for p in corners), min(p[1] for p in corners),
99
+ max(p[0] for p in corners), max(p[1] for p in corners)]
100
+
95
101
  words = []
96
- letters, boxes = [], []
102
+ letters, boxes, glyphs = [], [], []
97
103
 
98
104
  def flush():
99
105
  if letters and boxes:
100
106
  words.append({"text": "".join(letters), "bbox": [
101
107
  min(box[0] for box in boxes), min(box[1] for box in boxes),
102
108
  max(box[2] for box in boxes), max(box[3] for box in boxes),
103
- ]})
109
+ ], "chars": list(glyphs)})
104
110
  letters.clear()
105
111
  boxes.clear()
112
+ glyphs.clear()
106
113
 
107
114
  text = page.get_textpage()
108
115
  try:
109
116
  for at in range(text.count_chars()):
110
117
  letter = text.get_text_range(at, 1)
111
118
  # PDFium replaces a discretionary line-end hyphen with U+FFFE and
112
- # omits the line break. Keep its physical word on this line.
119
+ # omits the line break. The sentinel still has a native char box:
120
+ # preserve it so a page-final "high-" remains character-aligned.
113
121
  if letter == "\ufffe":
122
+ box = char_box(at)
114
123
  letters.append("-")
124
+ boxes.append(box)
125
+ glyphs.append({"text": "-", "bbox": box})
115
126
  flush()
116
127
  continue
117
128
  if not letter or letter.isspace() or ord(letter[0]) < 32:
@@ -122,10 +133,13 @@ def _text_page(page, index: int, output_dir: Path, page_count: int):
122
133
  box = [min(p[0] for p in corners), min(p[1] for p in corners), max(p[0] for p in corners), max(p[1] for p in corners)]
123
134
  letters.append(letter)
124
135
  boxes.append(box)
136
+ # 与 PDFium 每一个原生字符一一对应;不能只保存整词 bbox:
137
+ # 等宽/斜体/压缩字体的字内位置与浏览器 serif 差异可超过 10 PDF px。
138
+ glyphs.append({"text": letter, "bbox": box})
125
139
  flush()
126
140
  finally:
127
141
  text.close()
128
- result = {"schemaVersion": 2, "page": index, "pageCount": page_count, "width": width, "height": height, "words": words}
142
+ result = {"schemaVersion": 3, "page": index, "pageCount": page_count, "width": width, "height": height, "words": words}
129
143
  target = output_dir / f"{index}.text.json"
130
144
  temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
131
145
  temporary.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
package/lib/pdf-page.js CHANGED
@@ -76,6 +76,10 @@ export function cropPdfGroups(page, groups, canvas) {
76
76
  words: group.words.map(word => ({
77
77
  ...word,
78
78
  bbox: mapBox(word.bbox),
79
+ // gap 是水平长度,不是坐标点:裁后 0–1000 画布缩窄 visible.width,
80
+ // 因此长度必须除以同一个比例。客户端随后乘裁后页宽,物理像素间距才不变。
81
+ gap: Number.isFinite(word.gap) ? word.gap / visible.width : word.gap,
82
+ ...(Array.isArray(word.chars) ? { chars: word.chars.map(char => ({ ...char, bbox: mapBox(char.bbox) })) } : {}),
79
83
  line: Array.isArray(word.line) && word.line.length === 2
80
84
  ? [mapY(word.line[0]), mapY(word.line[1])]
81
85
  : word.line,
@@ -95,10 +99,15 @@ function clamp1000(value) {
95
99
  }
96
100
 
97
101
  export function validPdfPage(value, page) {
98
- return value?.schemaVersion === 2 && value.page === page
102
+ return value?.schemaVersion === 3 && value.page === page
99
103
  && Number.isSafeInteger(value.pageCount) && value.pageCount >= page
100
104
  && Number.isFinite(value.width) && value.width > 0 && Number.isFinite(value.height) && value.height > 0
101
- && Array.isArray(value.words) && value.words.every(word => typeof word?.text === 'string' && validBox(word.bbox))
105
+ // v3 adds PDFium character positions. Also require complete text coverage:
106
+ // older v3 caches omitted the native box for PDFium's U+FFFE line-end hyphen.
107
+ // Reject them so readPdfPage rebuilds the cache with the complete glyph sequence.
108
+ && Array.isArray(value.words) && value.words.every(word => typeof word?.text === 'string' && validBox(word.bbox)
109
+ && Array.isArray(word.chars) && word.chars.every(char => typeof char?.text === 'string' && char.text.length > 0 && validBox(char.bbox))
110
+ && word.chars.map(char => char.text).join('') === word.text)
102
111
  }
103
112
 
104
113
  function validBox(box) {
@@ -109,12 +118,95 @@ function sameLine(a, b) {
109
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]
110
119
  }
111
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
+
112
165
  const matchingText = value => plainInlineText(value).normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
113
166
 
114
- /** Match physical PDF lines to parsed paragraph ids; figure boxes may exclude their captions. */
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
+
196
+ /**
197
+ * **结构性块**:文字在 caption 里,PDF 文字层的正文词永远不该归给它们。
198
+ *
199
+ * 🔴 判据必须是块类型而不是"有没有 sourceText":text 块里有 5.8% 是跨页续文的尾部
200
+ * (sourceText 为空但文字层有词),按"有没有字"判会把它们一起改坏。
201
+ * 实测全库:table / image / chart / code 四类 100% 无 sourceText,而 text 只 5.8%。
202
+ */
203
+ const STRUCTURAL_KINDS = new Set(['image', 'figure', 'table', 'chart', 'code'])
204
+
115
205
  export function pdfPageGroups(page, blocks) {
116
206
  const rows = (Array.isArray(blocks) ? blocks : []).filter(block => block.page === page.page && validBox(block.bbox))
117
207
  const texts = new Map(rows.map(row => [row.id, matchingText(row.sourceText ?? '')]))
208
+ // 块类型:结构性块不参与正文词归属(见 STRUCTURAL_KINDS)。
209
+ const styles = new Map(rows.map(row => [row.id, String(row.type ?? '')]))
118
210
  const lines = []
119
211
  for (const word of page.words) {
120
212
  const previous = lines.at(-1)?.words.at(-1)
@@ -129,27 +221,89 @@ export function pdfPageGroups(page, blocks) {
129
221
  const matches = text.length >= 12 ? rows.filter(row => texts.get(row.id).includes(text)) : []
130
222
  const x = (line.words[0].bbox[0] + line.words.at(-1).bbox[2]) / 2
131
223
  const y = line.words.reduce((sum, word) => sum + (word.bbox[1] + word.bbox[3]) / 2, 0) / line.words.length
132
- let chosen = null, best = Infinity
133
- for (const row of matches.length ? matches : rows) {
224
+ // 🔴 **结构性块(图片 / 图表 / 表格 / 代码)只在它压着正文时才退让**,其余情形照旧。
225
+ //
226
+ // 背景:图片 / 图表的 bbox 常常压在正文段落上。兜底分支按 score 挑最近的块时,第二项
227
+ // 是包含框面积,面积更小的那一方胜出 —— 于是图片块把正文行抢走。后果远不止少一行字:
228
+ // 同一段文字被拆进**两个 DOM 容器**,渲染顺序随块顺序断开,浏览器按 DOM 顺序铺开原生
229
+ // 选区,用户从段首拖到中间就整段涂蓝(实测 ResNet 第 2 页首段:image 块 blk-24 面积
230
+ // 39163 < 正文块 blk-23 的 77815,抢走 3 行含行内公式的文字,复制出来的顺序因此呈现
231
+ // "公式那几行跑到末尾")。
232
+ //
233
+ // 🔴 那一行**为什么匹配不上正文块**:blk-23 的 sourceText 是 LaTeX
234
+ // (`$\mathcal{H}(\mathbf{x})$`),经 matchingText 后是 `mathcalhmathbfx`,而 PDF 文字层
235
+ // 抽出来的是排版后的 `H(x)` —— 两者永远对不上,所以这批行必然走兜底分支。
236
+ // 也就是说,靠"内容匹配"挡不住它,判据必须落在几何上。
237
+ const scoreOf = row => {
134
238
  const [left, top, right, bottom] = row.bbox
135
239
  const dx = Math.max(left - x, 0, x - right), dy = Math.max(top - y, 0, y - bottom)
136
- const score = Math.hypot(dx, dy) * 1000000 + (right - left) * (bottom - top)
137
- if ((matches.length || Math.hypot(dx, dy) <= 50) && score < best) { best = score; chosen = row }
240
+ return { distance: Math.hypot(dx, dy), score: Math.hypot(dx, dy) * 1000000 + (right - left) * (bottom - top) }
241
+ }
242
+ /**
243
+ * 这一行抢不抢得走:结构性块(图片/图表)只有在**不与任何文字块重叠**时才配拿词。
244
+ *
245
+ * 🔴 判据必须是「几何重叠」而不是「有没有 sourceText」也不是「无条件惩罚」——
246
+ * 两者都被实测否掉了:
247
+ * · 按 sourceText 判:text 块有 5.8% 是跨页续文尾部(sourceText 空但有词),会误伤;
248
+ * · 无条件惩罚:表格自己格子里的字(ResNet p7 blk-119 的 "output map size 32×32…"
249
+ * 夹在 blk-116 与 blk-120 之间、不与任何文字块重叠)会被整批赶走。
250
+ * 而图片块 blk-24 与正文块 blk-23 重叠 69% —— 它罩住的词本来就是正文的。
251
+ */
252
+ const overlapsText = row => rows.some(other => other !== row
253
+ && !STRUCTURAL_KINDS.has(styles.get(other.id))
254
+ && row.bbox[0] < other.bbox[2] && other.bbox[0] < row.bbox[2]
255
+ && row.bbox[1] < other.bbox[3] && other.bbox[1] < row.bbox[3])
256
+ const pick = (candidates) => {
257
+ let chosenRow = null, bestScore = Infinity
258
+ for (const row of candidates) {
259
+ const { distance, score } = scoreOf(row)
260
+ if (!matches.length && distance > 50) continue
261
+ if (score < bestScore) { bestScore = score; chosenRow = row }
262
+ }
263
+ return chosenRow
138
264
  }
265
+ const pool = matches.length ? matches : rows
266
+ // 第一轮:内容匹配里有没有文字块 —— 有就直接在那些里挑(公式行的 matches 为空,走第二轮)。
267
+ const textMatched = matches.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)))
268
+ let chosen = textMatched.length > 0 ? pick(textMatched) : null
269
+ // 第二轮:在**不与文字块重叠**的候选里挑。文字块永远在内,结构性块看它是否压着正文。
270
+ if (chosen === null) chosen = pick(pool.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)) || !overlapsText(row)))
271
+ // 第三轮:实在没有候选(例如整页只有一张图),才放开限制。
272
+ if (chosen === null) chosen = pick(pool)
139
273
  if (!chosen) continue
140
274
  if (!grouped.has(chosen.id)) grouped.set(chosen.id, { id: chosen.id, words: [] })
141
275
  for (const word of line.words) {
142
276
  const text = word.text.normalize('NFKC').replace(/\u00ad/g, '')
143
- if (text) grouped.get(chosen.id).words.push({ text, bbox: word.bbox })
277
+ if (text) grouped.get(chosen.id).words.push({
278
+ text, bbox: word.bbox,
279
+ // Preserve native boxes through paragraph grouping. The browser only
280
+ // uses them when the full normalized string matches one-to-one.
281
+ ...(Array.isArray(word.chars) ? { chars: word.chars.map(char => ({
282
+ text: char.text.normalize('NFKC').replace(/\u00ad/g, ''), bbox: char.bbox,
283
+ })) } : {}),
284
+ })
144
285
  }
145
286
  }
146
287
  return [...grouped.values()].filter(group => group.words.length > 0).map(group => {
147
- let line
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 = []
148
298
  for (const word of group.words) {
149
- if (!line || !sameLine(line.last, word.bbox)) line = { top: word.bbox[1], bottom: word.bbox[3] }
150
- line.last = word.bbox
151
- line.top = Math.min(line.top, word.bbox[1]); line.bottom = Math.max(line.bottom, word.bbox[3])
152
- word.line = line
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
153
307
  }
154
308
  // 每个词后面那个词是不是**同一行**的续词、以及是不是断词连写(gen- / erated)。
155
309
  // 两条都要留到拼正文那一步用,所以先算一遍存下来。
@@ -164,7 +318,17 @@ export function pdfPageGroups(page, blocks) {
164
318
  // 「含空格的字串」等分,负字距被算大、整词的字被压窄;行末空格又被浏览器悬挂/裁掉,
165
319
  // 选区右沿于是止于倒数一个字形,末字右边那一格永远盖不住。
166
320
  const sameLine = next !== undefined && next.line === word.line
167
- return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox: word.bbox,
321
+ const nativeChars = Array.isArray(word.chars) ? word.chars : null
322
+ const trimmedHyphen = joined && nativeChars?.at(-1)?.text === '-'
323
+ const chars = trimmedHyphen ? nativeChars.slice(0, -1) : nativeChars
324
+ // When the normalized paragraph joins a line-end hyphen to the next
325
+ // line, remove it from text, glyphs, and the visible word edge together.
326
+ // A page-final hyphen is not joined and keeps its own native glyph box.
327
+ const bbox = trimmedHyphen && chars.length
328
+ ? [word.bbox[0], word.bbox[1], Math.max(...chars.map(char => char.bbox[2])), word.bbox[3]]
329
+ : word.bbox
330
+ return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox,
331
+ ...(chars ? { chars } : {}),
168
332
  line: [word.line.top, word.line.bottom], gap: sameLine ? Math.max(0, next.bbox[0] - word.bbox[2]) : 0 }
169
333
  })
170
334
  const bbox = words.reduce((box, word) => [Math.min(box[0], word.bbox[0]), Math.min(box[1], word.line[0]), Math.max(box[2], word.bbox[2]), Math.max(box[3], word.line[1])], [Infinity, Infinity, -Infinity, -Infinity])
@@ -75,7 +75,17 @@ function normalizeLanguage(targetLanguage) {
75
75
  return isNonEmptyString(targetLanguage) ? targetLanguage.trim() : 'zh'
76
76
  }
77
77
 
78
- function languageNameOf(code) {
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
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Paper Reading",
4
+ "description": "PDF transcription into stable block ids, folder scanning two levels deep, and session-scoped paper context injected or removed by dragging a selection."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "论文阅读",
4
+ "description": "把 PDF 转成稳定块号的正文,支持两级文件夹扫描,并按会话注入或移除论文上下文,可拖选批量处理。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,19 +1,22 @@
1
1
  {
2
2
  "name": "@li-canghai/dsh-paper",
3
- "version": "0.8.0",
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\"",