@li-canghai/dsh-paper 0.8.2 → 0.8.3

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/pdf-page.js CHANGED
@@ -202,21 +202,384 @@ export function pdfQuoteInText(text, quote) {
202
202
  */
203
203
  const STRUCTURAL_KINDS = new Set(['image', 'figure', 'table', 'chart', 'code'])
204
204
 
205
+ /**
206
+ * **页边材料**:页眉、页脚、脚注、页码、侧栏批注 —— 它们不在正文流程里。
207
+ *
208
+ * 🔴 排到**整页正文之后**,不参与正文的阅读顺序。理由是这个功能的直接用途:
209
+ * 用户框选一段正文时,浏览器取的是 DOM 里两端点之间的全部节点,所以夹在正文流程
210
+ * 中间的脚注会被一并涂蓝。用户实测报的就是这个(「框选正文时下面的小字说明也被框进来了」)。
211
+ *
212
+ * 判据用块类型,不用几何位置:脚注在物理上位于页面底部,但按「左栏从上到下、
213
+ * 再右栏从上到下」的顺序,它正好落在左栏正文之后、右栏之前 —— 用户从摘要一路往下拖到
214
+ * 右栏就跨过了它。几何位置算不出「它不属于正文」这件事,块类型可以。
215
+ *
216
+ * 🔴 **口径是译文块类型(`splitBlocks` 的产出),不是 MinerU 的原始 type。**
217
+ * 这一层拿到的 `blocks` 已经过归一:`page_footnote` → `note`,而 `aside_text` /
218
+ * `header` / `footer` / `page_number` 在切块阶段就被整类跳过、根本不存在对应块
219
+ * (见 blocks.js 的 `SKIPPED_TYPES`,它们不占页内序号)。所以真正会走到这里的页边
220
+ * 材料只有 `note` 一种。
221
+ *
222
+ * 曾经在这里写的是 MinerU 原名(`page_footnote` 等),结果一个都匹配不上、整段空转:
223
+ * 实测 GrainGrasp 第 1 页脚注仍排在左栏正文之后、右栏之前,拖选正文照样把它涂蓝。
224
+ * 旧用例之所以是绿的,是因为夹具直接喂了原名,绕过了 `splitBlocks` 这一层归一。
225
+ *
226
+ * 原始名一并留着:这一层是导出的纯函数,调用方未必都走切块(测试、离线工具)。
227
+ *
228
+ * 🔴 `ref_text` → `references` **不在此列**:它是参考文献条目,属于正文流程
229
+ * (用户读综述时会框它)。
230
+ */
231
+ const MARGIN_KINDS = new Set(['note', 'page_footnote', 'aside_text', 'header', 'footer', 'page_number'])
232
+
233
+ /**
234
+ * 这一行是不是**竖排文字**(旋转 90° 的 arXiv 侧栏章、书脊、侧边水印)。
235
+ *
236
+ * 🔴 为什么必须单独判:这类文字在 PDF 里是「一整串字符沿 y 推进、每个字符自己只占
237
+ * 一个字宽」,抽出来的词只有一个、bbox 却是一根瘦高的长条(实测 GrainGrasp 第 1 页
238
+ * `arXiv:2405.09310v2`:x=23–59、y=497–707,宽 36 高 210)。它离它下面那段正文的
239
+ * 距离只有 20 出头,**几何上就是"紧挨着"**,于是被兜底分支吸进最近的正文块 ——
240
+ * 那个块因此被拆成上下两段(摘要 p1-p2 → 印章段 + 摘要段),DOM 顺序里凭空多出一个
241
+ * 跨了半页的容器:用户从摘要首字拖下去,印章跟着涂蓝,而中间那段正文则被拆散。
242
+ *
243
+ * 判据落在**字符推进方向**上,不落在外框长宽比:公式里的分式、表格里的竖排表头
244
+ * 同样是瘦高外框,但它们的字符仍沿 x 推进。只看 bbox 比例会误伤。
245
+ *
246
+ * @param {object[]} words 同一物理行的词
247
+ * @returns {boolean} 字符主要沿 y 推进,且这一行明显是竖的
248
+ */
249
+ function rotatedWord(word) {
250
+ const chars = Array.isArray(word.chars) ? word.chars : []
251
+ if (chars.length < 2) return false
252
+ let down = 0, across = 0
253
+ for (let i = 1; i < chars.length; i += 1) {
254
+ const previous = chars[i - 1].bbox
255
+ const current = chars[i].bbox
256
+ down += Math.abs((current[1] + current[3]) / 2 - (previous[1] + previous[3]) / 2)
257
+ across += Math.abs((current[0] + current[2]) / 2 - (previous[0] + previous[2]) / 2)
258
+ }
259
+ // 只认推进方向,**不看外框长宽比**:同一串竖排文字里,单个词的外框可能是宽的
260
+ // (实测 `16` 两字符:宽 36、高 25,仍是沿 y 推进)。用长宽比筛会把这类词漏掉,
261
+ // 于是同一道竖排章里几个词分到两边 —— 一部分当页边材料、一部分留在正文,
262
+ // 那一段正文照样被拆成两截。
263
+ return down > across * 3
264
+ }
265
+
266
+ /** 一行是不是竖排:这一行里**全部**可判定的词都沿 y 推进。 */
267
+ function rotatedLine(words) {
268
+ let measured = 0
269
+ for (const word of words) {
270
+ if (!Array.isArray(word.chars) || word.chars.length < 2) continue
271
+ measured += 1
272
+ if (!rotatedWord(word)) return false
273
+ }
274
+ return measured > 0
275
+ }
276
+
277
+ /**
278
+ * 一行文字离段落块的最大允许距离(0–1000 归一化坐标)。
279
+ *
280
+ * 实测口径:正常归属的行离自己的块为 0;跨栏续接的段落会把对侧栏的行拉进来,
281
+ * 那批行离块 211–602。取 50 既容得下块框与实际排版之间的常规偏差(实测最大 38),
282
+ * 也挡得住跨栏的那一批。
283
+ */
284
+ const MAX_BLOCK_DISTANCE = 50
285
+
286
+ /**
287
+ * 内容匹配命中时仍允许的最大距离。比 {@link MAX_BLOCK_DISTANCE} 宽,因为图注、
288
+ * 续行这类同栏文字离块框可以很远(实测回归用例里图注离图框 120)。
289
+ *
290
+ * 上限来自实测:图内标注文字离它被误配的块 596,而真正的图注续行 ≤ 120。
291
+ * 取 200 落在两者中间,两头都分得开。
292
+ */
293
+ const MAX_MATCHED_DISTANCE = 200
294
+
295
+ /**
296
+ * 三个**版面尺度**,全部以行高为单位。
297
+ *
298
+ * 🔴 绝对值在这里没有普适性:8pt 的双栏会议模板与 12pt 的单栏讲义,栏间空隙、行距、段距
299
+ * 全都不同;行高是唯一随版面一起缩放的单位,所以阈值只能用它的倍数表达。
300
+ *
301
+ * · {@link COLUMN_GUTTER_UNITS} —— 一道竖向空白至少这么宽才可能是栏间沟;
302
+ * · {@link ROW_GUTTER_UNITS} —— 一道横向空白至少这么高才值得当成上下两段版面;
303
+ * · {@link GUTTER_TOLERANCE} —— 沟里被别的行压住的比例上限。通栏标题、满宽图注会横穿
304
+ * 栏间沟;只按「完全为空」判,带通栏标题的双栏页就再也找不到栏了。
305
+ */
306
+ const COLUMN_GUTTER_UNITS = 1.6
307
+ const ROW_GUTTER_UNITS = 0.55
308
+ const GUTTER_TOLERANCE = 0.12
309
+
310
+ /** 拼正文用的两个字面量。写成常量只为让下面那一行不受模板串转义影响。 */
311
+ const SPACE = ' '
312
+ const EMPTY = ''
313
+
314
+ /** y 序比较器:递归切不动时的兜底,也是同一段内从左到右的次序。 */
315
+ const readingTop = (a, b) => a.box[1] - b.box[1] || a.box[0] - b.box[0]
316
+
317
+ /**
318
+ * 把一组物理行按**视觉阅读顺序**排好 —— 递归 XY 切分。
319
+ *
320
+ * 🔴 为什么要重排:浏览器画原生选区只认 DOM 顺序,不看物理位置。两个视觉上相邻、DOM 上
321
+ * 却隔着一整个右栏的块,用户从左栏一路往下拖就会把中间那些行一起涂蓝。
322
+ *
323
+ * 判据只有一条:**先找栏,找不到栏再分段,都没有就按 y 排**。
324
+ * · 栏:投影覆盖为空的那条竖向空白(允许 {@link GUTTER_TOLERANCE} 的例外,见上);
325
+ * · 段:横向空白,判据同理;
326
+ * · 两级都切不动时,这个局部版面就真的是单栏单段,y 序即阅读序。
327
+ *
328
+ * 🔴 不用「通栏行宽度 ≥ 页宽 55%」那个口径:它要求先知道页宽,而页宽会被页边竖排水印、
329
+ * arXiv 章这类边角元素撑大 —— 于是真正的通栏标题反而算不上通栏。实测 GrainGrasp 第 1 页:
330
+ * 左侧 arXiv 章把页宽撑到 889,标题只有 728(不到 55%),整页因此退化成左右交替。
331
+ * 投影覆盖只问「这一条竖线上有没有字」,与页宽无关,也就没有这个失效模式。
332
+ *
333
+ * 递归必然终止:每层把行切成 ≥2 个非空组,组内行数严格减少。
334
+ *
335
+ * @param {Array<{groupId: string, box: number[]}>} lines 物理行
336
+ * @returns {Array<object>} 同一批行,按阅读顺序
337
+ */
338
+ function lineReadingOrder(lines) {
339
+ if (lines.length <= 1) return lines
340
+ const heights = lines.map(line => line.box[3] - line.box[1]).filter(height => height > 0).sort((a, b) => a - b)
341
+ const unit = heights.length > 0 ? heights[heights.length >> 1] : 0
342
+ return unit > 0 ? orderRegion(lines, unit) : [...lines].sort(readingTop)
343
+ }
344
+
345
+ /** 一个局部版面的递归切分:能切栏就切栏,否则切段,否则按 y。 */
346
+ function orderRegion(lines, unit) {
347
+ if (lines.length <= 1) return lines
348
+ const columns = splitAxis(lines, unit, 0, COLUMN_GUTTER_UNITS)
349
+ if (columns !== null) return columnOrder(lines, columns, unit)
350
+ const rows = splitAxis(lines, unit, 1, ROW_GUTTER_UNITS)
351
+ if (rows !== null) return sliceByCuts(lines, 1, rows.map(gap => (gap.from + gap.to) / 2)).flatMap(row => orderRegion(row, unit))
352
+ return [...lines].sort(readingTop)
353
+ }
354
+
355
+ /** 按切割中线把行分到各区(按中心点),丢弃空区,保持顺序。 */
356
+ function sliceByCuts(lines, axis, cuts) {
357
+ const groups = cuts.map(() => [])
358
+ groups.push([])
359
+ for (const line of lines) {
360
+ const center = (line.box[axis] + line.box[axis + 2]) / 2
361
+ let index = 0
362
+ while (index < cuts.length && center >= cuts[index]) index += 1
363
+ groups[index].push(line)
364
+ }
365
+ return groups.filter(group => group.length > 0)
366
+ }
367
+
368
+ /**
369
+ * 切出栏之后的排序:**跨栏的行自成一条分隔带**,先把页面分成上下几截,每截内再按栏读。
370
+ *
371
+ * 🔴 这是 XY 切分里最容易被漏掉的一步。只按「中心落在哪一栏」分配是不够的:通栏标题
372
+ * (实测 GrainGrasp 第 1 页 x=136–864、栏间沟在 495)中心落在右栏,于是标题被排到了脚注
373
+ * 之后 —— 用户从摘要拖到 INTRODUCTION 时,选区就把整个右栏一并扫了进去。
374
+ *
375
+ * 分隔带的位置由**行自己的 y** 决定:一条跨栏行把它上方的行与下方的行隔开。于是通栏标题
376
+ * 回到顶部、右栏图注留在右栏该在的高度,左右两栏各自成段,DOM 顺序与视觉顺序一致。
377
+ *
378
+ * 带内的行一律**整行**落在某一侧(跨栏的已经全被抽走),所以这里按左沿分栏不会出错。
379
+ *
380
+ * @param {object[]} lines 同一局部版面的行
381
+ * @param {number[]} cuts 栏间沟的中线(升序)
382
+ * @param {number} unit 行高
383
+ * @returns {object[]} 按阅读顺序
384
+ */
385
+ function columnOrder(lines, gaps, unit) {
386
+ // 🔴 **跨栏**的意思是"横穿整道沟",不是"碰到沟"。只按切割中线判会把**探进沟里**但没
387
+ // 穿过去的那一行也算成跨栏 —— 实测夹具里左栏段落右沿到 420、沟是 300–514,它只是
388
+ // 探进沟里 120,却被当成跨栏行抽走,于是整页顺序错位。判据必须是两端都在沟外。
389
+ const spanning = new Set(lines.filter(line => gaps.some(gap => line.box[0] < gap.from && line.box[2] > gap.to)))
390
+ const separators = [...spanning].sort(readingTop)
391
+ const bands = separators.map(() => [])
392
+ bands.push([])
393
+ for (const line of lines) {
394
+ if (spanning.has(line)) continue
395
+ const center = (line.box[1] + line.box[3]) / 2
396
+ let index = 0
397
+ while (index < separators.length && (separators[index].box[1] + separators[index].box[3]) / 2 < center) index += 1
398
+ bands[index].push(line)
399
+ }
400
+ const cuts = gaps.map(gap => (gap.from + gap.to) / 2)
401
+ const ordered = []
402
+ for (let i = 0; i < bands.length; i += 1) {
403
+ for (const column of sliceByCuts(bands[i], 0, cuts)) ordered.push(...orderRegion(column, unit))
404
+ if (i < separators.length) ordered.push(separators[i])
405
+ }
406
+ return ordered
407
+ }
408
+
409
+ /**
410
+ * 沿 axis 找出可切的空档并合并,返回切割中线(升序);切不开时返回 null。
411
+ *
412
+ * 两侧都得有整行才算切开 —— 横跨过去的那一行本来就不属于任何一侧,不能凭它判定沟成立。
413
+ * 单栏页上由此得到的"沟"两侧必有一侧没有整行(正文横跨整页),于是被这条判据挡掉,
414
+ * 不会把单栏页切成两半。
415
+ */
416
+ function splitAxis(lines, unit, axis, units) {
417
+ const gaps = freeIntervals(lines, axis, unit)
418
+ .filter(([from, to]) => to - from >= unit * units)
419
+ .filter(([from, to]) => lines.some(line => line.box[axis + 2] <= from) && lines.some(line => line.box[axis] >= to))
420
+ // 🔴 每层只切**一道**最宽的沟。递归会在每一栏内部继续找下一道,所以多栏页面照样
421
+ // 切得出来;但同一层切好几刀时,一道被落单的字劈开的沟会被当成两道,中间凭空多出
422
+ // 一栏(只装那一个字),两侧正文反而落到更远的栏里。
423
+ .map(([from, to]) => ({ from, to, width: to - from }))
424
+ .sort((a, b) => b.width - a.width)
425
+ .slice(0, 1)
426
+ return gaps.length > 0 ? gaps : null
427
+ }
428
+ /**
429
+ * 局部版面里**被字压得足够少**的区间:axis=0 得到栏间沟,axis=1 得到段间带。
430
+ *
431
+ * 覆盖按**另一根轴**的长度加权:一条行在 x 上占的那一格,挡住的是它自己那么高的一条竖线。
432
+ * 于是"这条竖线上一共有多少高度被字压着"才是判据,行宽不参与运算 —— 通栏标题压过栏间沟
433
+ * 时也只贡献它自己那一行的高度,不会像"找最宽空隙"那样把整条沟一票否决。
434
+ *
435
+ * 🔴 两端必须显式入表(`bump(from, 0)` / `bump(to, 0)`)。投影只在**词框边界**上取值,
436
+ * 而一道沟的右沿往往没有词从那里开始(右侧栏的文字从更右边才起头),那个位置就永远
437
+ * 不会成为扫描点,沟的右半截也就丢掉了 —— 实测 GrainGrasp 第 3 页的栏间沟因此只剩左半。
438
+ *
439
+ * 相邻的空档间隔不到半个行高时合并:它们视觉上是同一道沟,被某个落单的字切开而已。
440
+ * 不合并就会在同一道沟里切出两刀,中间凭空多出一栏,那一栏里的行又会变成跨栏行。
441
+ *
442
+ * @param {object[]} lines 同一局部的行
443
+ * @param {0|1} axis 0 = 找竖向空白(栏),1 = 找横向空白(段)
444
+ * @param {number} unit 行高
445
+ * @returns {Array<[number, number]>} 按位置升序的空白区间
446
+ */
447
+ function freeIntervals(lines, axis, unit) {
448
+ const across = axis === 0 ? 1 : 0
449
+ const from = Math.min(...lines.map(line => line.box[axis]))
450
+ const to = Math.max(...lines.map(line => line.box[axis + 2]))
451
+ const total = Math.max(...lines.map(line => line.box[across + 2])) - Math.min(...lines.map(line => line.box[across]))
452
+ if (!(to > from) || !(total > 0)) return []
453
+ // 🔴 **判据是「有没有字」,但阈值不能取字面的 0。**
454
+ //
455
+ // 曾经用「被压住的长度 ≤ 页面高度的 12%」当**语义**容差,两处都出错:一列只有 6 行、
456
+ // 却纵向铺开小半页的边缘元素(arXiv 印章)比值很低,于是那一列被判成空白,印章被并进
457
+ // 正文;反过来行数很少的页面上,几行正文的高度占比就能超过 12%,栏间沟又判不出来。
458
+ // 语义容差确实只会引入这两种相反的失效 —— 那部分结论仍然成立。
459
+ //
460
+ // 但阈值也不能是**字面的 0**:depth 是浮点累加量,一道真正空着的沟算出来可能不是 0。
461
+ // 实测(Grounding Agent Memory p2,双栏 A4):沟宽 25.7,depth 停在 2.84e-14 ——
462
+ // 正的,于是 `depth > 0` 把整条沟跳过,freeIntervals 返回空,splitAxis 判本页无栏,
463
+ // 阅读顺序退化成一维 y 序,DOM 里左右两栏逐行交替。用户从左栏往下拖,浏览器按 DOM
464
+ // 线性区间铺选区,右栏几十行跟着涂蓝。
465
+ //
466
+ // 残差从哪来:同一行的 weight 加进去又减出来,两次累加的**顺序不同**(进入按 x 排序、
467
+ // 离开按另一处顺序),IEEE 754 加法不满足结合律,误差就留下了。
468
+ //
469
+ // 所以容差必须是**量纲化的**:取 total(本区另一根轴上字的总跨度)的 1e-9。它远大于
470
+ // 任何浮点残差(上例 total≈836,容差 8.4e-7,是残差的 3000 万倍),又远小于任何一个
471
+ // 真实字形的高度(最小也是 1 单位量级)—— 真有一行压在这条竖线上,depth 至少是它的
472
+ // 高度,不可能被这个容差吃掉。两个方向都留了足够的安全边界。
473
+ //
474
+ // 落单的字横穿沟不吃紧:它只盖住沟的一小截,剩下的仍然够宽;真被劈成两半时,下面
475
+ // 按半个行高合并的那一步会把它们并回去。
476
+ const epsilon = total * 1e-9
477
+ const deltas = new Map()
478
+ const bump = (key, value) => deltas.set(key, (deltas.get(key) ?? 0) + value)
479
+ bump(from, 0)
480
+ bump(to, 0)
481
+ // 🔴 **通栏行不算挡路**:标题、满宽图注、跨栏表格横穿栏间沟都是正常排版。把它们也
482
+ // 算进覆盖,带一个通栏标题的双栏页就再也找不到栏了。
483
+ //
484
+ // 判据取「宽度 ≥ 本区中位行宽的 1.5 倍」,不按整页宽度算。按整页宽度算会在**子区**里
485
+ // 失效:切出左栏之后再找左栏内部的沟时,正文行本身就占了该区八成宽,于是被当成通栏行
486
+ // 豁免掉,左侧竖排章(arXiv 印章)反而切不出来 —— 实测 GrainGrasp 第 1 页的竖排章
487
+ // 因此与摘要交替排布,摘要被拆成 5 段。中位数随区域缩放,没有这个失效模式。
488
+ //
489
+ // 🔴 **中位数只统计正文行,不统计结构性块(图片 / 图表 / 表格 / 代码)里的字。**
490
+ // 这是同一个"判据的输入被它要判的对象污染"的失效,只是绕了一层:
491
+ //
492
+ // 实测(Grounding Agent Memory 第 4 页):页面顶部一张横跨两栏的大图,图内小字 79 行,
493
+ // 行宽中位数 77.6;正文段落 54 行,行宽中位数 366.5。**全部行**的中位数被图内碎字拉到
494
+ // 154.5,通栏门槛于是变成 231.8 —— 正文行(366.5)个个超标,全被当成通栏豁免掉,
495
+ // 图内碎字反倒成了唯一的遮挡源。栏间沟因此找不到,整页 DOM 又退回左右交替。
496
+ //
497
+ // 图里的字不是**正文流**,它不构成版面网格,拿它估计正文的行宽尺度必然失真。按块类型
498
+ // 剔除之后,这一页的 typical 回到 366.5、门槛 549.8,正文行不再被误判。
499
+ //
500
+ // 整页都是结构性块时(纯图页)没有正文可估,退回全部行 —— 那时的"正文尺度"就是它自己。
501
+ const widthsOf = filter => lines.filter(filter).map(line => line.box[axis + 2] - line.box[axis]).filter(width => width > 0).sort((a, b) => a - b)
502
+ const textWidths = widthsOf(line => line.structural !== true)
503
+ const widths = textWidths.length > 0 ? textWidths : widthsOf(() => true)
504
+ const typical = widths.length > 0 ? widths[widths.length >> 1] : 0
505
+ const spanning = line => typical > 0 && line.box[axis + 2] - line.box[axis] >= typical * 1.5
506
+ for (const line of lines) {
507
+ const start = line.box[axis]
508
+ const end = line.box[axis + 2]
509
+ const weight = line.box[across + 2] - line.box[across]
510
+ if (!(end > start) || !(weight > 0) || spanning(line)) continue
511
+ bump(start, weight)
512
+ bump(end, -weight)
513
+ }
514
+ const positions = [...deltas.keys()].sort((a, b) => a - b)
515
+ const raw = []
516
+ let depth = 0
517
+ for (let i = 0; i < positions.length - 1; i += 1) {
518
+ depth += deltas.get(positions[i])
519
+ // 容差而不是 0:depth 是浮点累加量,见上面 epsilon 的说明。
520
+ if (depth > epsilon) continue
521
+ const start = positions[i]
522
+ const end = positions[i + 1]
523
+ if (end > start) raw.push([start, end])
524
+ }
525
+ const merged = []
526
+ for (const gap of raw) {
527
+ const last = merged.at(-1)
528
+ if (last !== undefined && gap[0] - last[1] < unit * 0.5) last[1] = gap[1]
529
+ else merged.push([gap[0], gap[1]])
530
+ }
531
+ return merged
532
+ }
533
+
534
+ /**
535
+ * 一个块在某一页上的**完整正文**(所有 part 合起来)。
536
+ *
537
+ * 块可能被拆成多段 DOM(见 splitRuns),但划线校验、高亮定位、对齐都按**整块**做 ——
538
+ * 只取第一段会漏掉被图或公式隔开的另一半。
539
+ *
540
+ * @param {object[]} groups pdfPageGroups 的产物
541
+ * @param {string} blockId 块 id
542
+ * @returns {string} 整块正文;这一页没有这个块时返回空串
543
+ */
544
+ export function pdfBlockText(groups, blockId) {
545
+ const parts = (Array.isArray(groups) ? groups : []).filter(group => group?.id === blockId)
546
+ if (parts.length === 0) return ''
547
+ return parts[0].fullText ?? parts.map(part => part.text).join(' ')
548
+ }
549
+
205
550
  export function pdfPageGroups(page, blocks) {
206
551
  const rows = (Array.isArray(blocks) ? blocks : []).filter(block => block.page === page.page && validBox(block.bbox))
207
552
  const texts = new Map(rows.map(row => [row.id, matchingText(row.sourceText ?? '')]))
208
553
  // 块类型:结构性块不参与正文词归属(见 STRUCTURAL_KINDS)。
209
554
  const styles = new Map(rows.map(row => [row.id, String(row.type ?? '')]))
555
+ // 🔴 切行时**竖排词单独成行**:竖排文字沿 y 推进,同一串字的每个词在 bbox 上纵向
556
+ // 紧挨着、横向完全重合,而横向排版的行是按 x 排的 —— 用 `sameLine` 判会让竖排章被
557
+ // 反复切断或与旁边的正文行合并。先按推进方向决定「能不能接在同一条行上」,
558
+ // 竖排词只接竖排词,横排词只接横排词。
210
559
  const lines = []
211
560
  for (const word of page.words) {
212
561
  const previous = lines.at(-1)?.words.at(-1)
213
562
  const gap = previous ? (word.bbox[0] - previous.bbox[2]) * page.width : 0
214
563
  const height = (word.bbox[3] - word.bbox[1]) * page.height
215
- if (!previous || !sameLine(previous.bbox, word.bbox) || gap > height * 3) lines.push({ words: [] })
564
+ const sameOrientation = previous !== undefined && rotatedWord(previous) === rotatedWord(word)
565
+ if (!previous || !sameOrientation || !sameLine(previous.bbox, word.bbox) || gap > height * 3) lines.push({ words: [] })
216
566
  lines.at(-1).words.push(word)
217
567
  }
568
+ // 🔴 竖排文字(侧栏 arXiv 章、水印、书脊)**不参与归属**:它离下面那段正文几何上紧挨着,
569
+ // 兜底分支必然把它吸进最近的正文档,那块因此被拆成"印章段 + 正文段"两截,DOM 里凭空
570
+ // 多出一个跨半页的容器 —— 用户从那段正文首字拖下去就把印章一起涂蓝。
571
+ // 直接丢掉而不是另立一段:这类文字是版面装饰,不该成为标注锚点,而块 id 由上游给定,
572
+ // 这里凭空造一个会和重解析对齐规则冲突。
573
+ //
574
+ // 🔴 整页多数行都竖着时**不这么判**:那是扫描件整页旋转(页面本身横过来了),
575
+ // 全部丢弃会让这一页一个字都选不中。此时按普通版面处理,交给 XY 切分去排。
576
+ for (const line of lines) line.rotated = rotatedLine(line.words)
577
+ if (lines.filter(line => line.rotated).length * 2 > lines.length) {
578
+ for (const line of lines) line.rotated = false
579
+ }
218
580
  const grouped = new Map()
219
581
  for (const line of lines) {
582
+ if (line.rotated) continue
220
583
  const text = matchingText(line.words.map(word => word.text).join(' '))
221
584
  const matches = text.length >= 12 ? rows.filter(row => texts.get(row.id).includes(text)) : []
222
585
  const x = (line.words[0].bbox[0] + line.words.at(-1).bbox[2]) / 2
@@ -253,23 +616,70 @@ export function pdfPageGroups(page, blocks) {
253
616
  && !STRUCTURAL_KINDS.has(styles.get(other.id))
254
617
  && row.bbox[0] < other.bbox[2] && other.bbox[0] < row.bbox[2]
255
618
  && row.bbox[1] < other.bbox[3] && other.bbox[1] < row.bbox[3])
256
- const pick = (candidates) => {
619
+ /**
620
+ * 在候选里挑最近的块。
621
+ *
622
+ * 🔴 几何闸门**所有轮次都生效**,内容匹配也不例外。原因是一次实测:
623
+ * 「跨栏续接的段落」MinerU 给的 bbox 只有它起头那一栏的一小截,sourceText 却是整段。
624
+ * 右栏中部的行能在它的 sourceText 里找到,于是内容匹配命中、几何被完全忽略 ——
625
+ * 实测 ResNet 风格的双栏页上,一个 bbox 在左栏底部的块收走了右栏中部 12 行
626
+ * (最远距离 436)。这些行进了同一个 DOM 容器,浏览器按 DOM 顺序铺原生选区,
627
+ * 用户从左栏往下拖就把右栏整片涂蓝(本机第 4 页实测:选区横跨 32 个 DOM 节点,
628
+ * 其中 28 行是右栏)。
629
+ *
630
+ * 闸门只在**最后一轮**放开:三轮都够不着时按纯距离取最近块,
631
+ * 宁可把一行安置到远处,也不能让它掉出分组(掉词会让这一行永远选不中)。
632
+ */
633
+ /**
634
+ * 内容匹配命中时,这一行还算不算这个块的。两条都要满足:
635
+ *
636
+ * ① **同一栏**(横向重叠 ≥ 较窄者宽度的 25%)。只按距离判断会漏掉跨栏续接的段落:
637
+ * bbox 在左栏、sourceText 却是整段,右栏中部那些行内容全对得上而横向完全不沾边
638
+ * (实测第 4 页:x 507–881 对 x 112–489,中间隔着栏间空隙)—— 收进来就让 DOM
639
+ * 跨栏,选区整片涂蓝。图注续行与图框几乎完全重叠,跨栏的两侧重叠为负,这个判据
640
+ * 两头都分得开。
641
+ * ② **不算隔得太远**({@link MAX_MATCHED_DISTANCE})。同栏也会出问题:实测第 4 页
642
+ * 图内两行 `Coreference Resolution via / Structural Alignment` 在图框里(y≈266),
643
+ * 而 blk-38 的 sourceText 正是以这句开头,于是被内容匹配抓走(距离 596)——
644
+ * 这个块因此纵跨 y=266~921,按首行位置排序就跑到页面中段去了。
645
+ */
646
+ const lineLeft = line.words[0].bbox[0]
647
+ const lineRight = line.words.at(-1).bbox[2]
648
+ const sameColumn = row => {
649
+ const overlap = Math.min(lineRight, row.bbox[2]) - Math.max(lineLeft, row.bbox[0])
650
+ const narrower = Math.min(lineRight - lineLeft, row.bbox[2] - row.bbox[0])
651
+ return narrower > 0 && overlap >= narrower * 0.25
652
+ }
653
+ /**
654
+ * 在候选里挑最近的块。
655
+ *
656
+ * 闸门分两档:
657
+ * · `matched` —— 这一行的内容在候选块里找得到,或用整页块兜底时,只要求**同栏**;
658
+ * · 其余情况(纯几何归属)仍用 {@link MAX_BLOCK_DISTANCE}。
659
+ */
660
+ const pick = (candidates, { column = false } = {}) => {
257
661
  let chosenRow = null, bestScore = Infinity
258
662
  for (const row of candidates) {
259
663
  const { distance, score } = scoreOf(row)
260
- if (!matches.length && distance > 50) continue
664
+ if (column ? (!sameColumn(row) || distance > MAX_MATCHED_DISTANCE) : distance > MAX_BLOCK_DISTANCE) continue
261
665
  if (score < bestScore) { bestScore = score; chosenRow = row }
262
666
  }
263
667
  return chosenRow
264
668
  }
265
669
  const pool = matches.length ? matches : rows
266
670
  // 第一轮:内容匹配里有没有文字块 —— 有就直接在那些里挑(公式行的 matches 为空,走第二轮)。
671
+ // 这一轮用**同栏**闸门而不是距离:图注类文字离图框可以很远,但它与图框横向重合。
267
672
  const textMatched = matches.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)))
268
- let chosen = textMatched.length > 0 ? pick(textMatched) : null
673
+ let chosen = textMatched.length > 0 ? pick(textMatched, { column: true }) : null
269
674
  // 第二轮:在**不与文字块重叠**的候选里挑。文字块永远在内,结构性块看它是否压着正文。
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)
675
+ // 内容匹配过但不同栏(跨栏续接的段落)会在这一轮落到几何上真正罩着它的块。
676
+ if (chosen === null) chosen = pick(pool.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)) || !overlapsText(row)), { column: matches.length > 0 })
677
+ // 第三轮:整页候选里挑,闸门口径同上一轮。
678
+ //
679
+ // 🔴 够不着时**宁可丢掉这一行**,不放开闸门。远处的词是页眉、水印、页码一类的版面噪声:
680
+ // 把它们硬塞进某个正文块,会让那个块的 DOM 里混进一批视觉上在别处的节点,选区照样跨栏
681
+ // (这也是回归用例「远处水印不归入正文」钉住的行为)。
682
+ if (chosen === null) chosen = pick(rows, { column: matches.length > 0 })
273
683
  if (!chosen) continue
274
684
  if (!grouped.has(chosen.id)) grouped.set(chosen.id, { id: chosen.id, words: [] })
275
685
  for (const word of line.words) {
@@ -284,7 +694,7 @@ export function pdfPageGroups(page, blocks) {
284
694
  })
285
695
  }
286
696
  }
287
- return [...grouped.values()].filter(group => group.words.length > 0).map(group => {
697
+ const shaped = [...grouped.values()].filter(group => group.words.length > 0).map(group => {
288
698
  // 先把词按物理行归堆,再给**每一行**算一个统一的行带。
289
699
  //
290
700
  // 🔴 行带的高度**不能**取这一行所有词框的 min/max:行内只要有一个比正文高得多的字形
@@ -329,6 +739,9 @@ export function pdfPageGroups(page, blocks) {
329
739
  : word.bbox
330
740
  return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox,
331
741
  ...(chars ? { chars } : {}),
742
+ // 断词连写:与该词前一个词之间不补任何分隔符。跨 DOM 段重拼正文时要用它
743
+ // (splitRuns 只按行接缝补空格,缺了这条会把 gen- 与 erated 拆成两个词)。
744
+ continuation: joined === true,
332
745
  line: [word.line.top, word.line.bottom], gap: sameLine ? Math.max(0, next.bbox[0] - word.bbox[2]) : 0 }
333
746
  })
334
747
  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])
@@ -344,4 +757,101 @@ export function pdfPageGroups(page, blocks) {
344
757
  }, '')
345
758
  return { ...group, bbox, words, text }
346
759
  })
760
+ // 🔴 **DOM 顺序必须是视觉阅读顺序**,不能照抄 MinerU 的数组顺序。
761
+ //
762
+ // 浏览器画原生选区只认 DOM 顺序,不看物理位置:两个视觉上相邻、DOM 上隔着一整个
763
+ // 右栏的块,用户从左栏一路往下拖就会把中间那些行一起涂蓝。实测第 4 页的跨栏续接
764
+ // 段落正是这种形状(bbox 在左栏底部,数组位置却在左栏其余段落之前)。
765
+ //
766
+ // 块的位置取它**第一行的阅读顺序位置**。为什么不逐行重排:块是标注的锚点单位
767
+ // (blockId 决定划线落到哪一段),一个块的各行必须留在同一个容器里;而归属修好之后
768
+ // 每个块的行基本已经连续,取首个位置就够准。
769
+ //
770
+ // 用**实际词框**算,不是 MinerU 给的原框:归属修正后两者已经不同,DOM 里真正的落点
771
+ // 由词框决定。
772
+ // 页边材料(页眉 / 页脚 / 脚注 / 页码 / 侧栏批注)单独排到整页正文之后,不参与正文的
773
+ // 阅读顺序。理由见 MARGIN_KINDS:夹在正文中间的脚注会被框选一并涂蓝。
774
+ const isMargin = id => MARGIN_KINDS.has(styles.get(id))
775
+ // 逐行铺开:同一块的同一条物理行归一行,并记下这一行**是不是页边材料**。
776
+ // 判据只有块类型一条 —— 竖排文字在上面的归属阶段就已经被丢掉了,走不到这里。
777
+ const physical = []
778
+ for (const group of shaped) {
779
+ const marginBlock = isMargin(group.id)
780
+ // 🔴 结构性块(图片 / 图表 / 表格 / 代码)里的字不是正文流:它们不构成版面网格,
781
+ // 拿它们估计"正文行宽的中位数"会把通栏判据整体带偏(见 freeIntervals 里的实测)。
782
+ const structuralBlock = STRUCTURAL_KINDS.has(styles.get(group.id))
783
+ for (const word of group.words) {
784
+ const top = word.line?.[0]
785
+ const last = physical.at(-1)
786
+ if (last !== undefined && last.groupId === group.id && last.top === top) {
787
+ last.words.push(word)
788
+ last.box[0] = Math.min(last.box[0], word.bbox[0])
789
+ last.box[2] = Math.max(last.box[2], word.bbox[2])
790
+ } else {
791
+ physical.push({ groupId: group.id, top, margin: marginBlock, structural: structuralBlock,
792
+ box: [word.bbox[0], word.line[0], word.bbox[2], word.line[1]], words: [word] })
793
+ }
794
+ }
795
+ }
796
+ // 正文按阅读顺序铺开;页边材料自己按 y 排(同一块内从上到下),整段接在正文之后。
797
+ return splitRuns(shaped, [
798
+ ...lineReadingOrder(physical.filter(line => !line.margin)),
799
+ ...lineReadingOrder(physical.filter(line => line.margin)),
800
+ ])
347
801
  }
802
+
803
+
804
+ /**
805
+ * 把「块」按阅读顺序重新打包成若干**连续的 DOM 段**。
806
+ *
807
+ * 🔴 这是整个问题的根:浏览器画原生选区只认 DOM 顺序。只要一个块的行在阅读顺序里不是
808
+ * 连续的,它的容器就必须同时罩住中间那些别的块 —— 用户拖选时被夹在中间的内容跟着涂蓝。
809
+ * 光把块排序修好只能保证**块与块之间**不串栏;块内部被拆散(跨栏续接的图注、被公式或
810
+ * 图表隔断的段落)照样会串。
811
+ *
812
+ * 做法:按阅读顺序铺开所有物理行,同一块的行**连续出现**就归一段,断开就另起一段。
813
+ * 于是 DOM 里任何一段连续节点都对应阅读顺序里连续的一段,也就是视觉上连续的一片。
814
+ * 这是排版无关的:单栏、双栏、三栏、横排表格、图文混排一视同仁,因为它只做一件事 ——
815
+ * 让 DOM 顺序就是阅读顺序。
816
+ *
817
+ * 段共用同一个 id(就是 blockId,标注的锚点单位不变),用 part 区分先后。
818
+ * 一个块没被拆散时只产出一段,part 恒为 0,字节形状与拆分前一致。
819
+ *
820
+ * @param {object[]} shaped 每块一组的词
821
+ * @param {object[]} ordered 所有物理行,按视觉阅读顺序
822
+ * @returns {object[]} 按 DOM 顺序排列的段落
823
+ */
824
+ function splitRuns(shaped, ordered) {
825
+ const runs = []
826
+ for (const line of ordered) {
827
+ const last = runs.at(-1)
828
+ if (last !== undefined && last.id === line.groupId) last.words.push(...line.words)
829
+ else runs.push({ id: line.groupId, words: [...line.words] })
830
+ }
831
+ const sources = new Map(shaped.map(group => [group.id, group]))
832
+ const seen = new Map()
833
+ return runs.filter(run => run.words.length > 0).map(run => {
834
+ const part = seen.get(run.id) ?? 0
835
+ seen.set(run.id, part + 1)
836
+ const source = sources.get(run.id) ?? {}
837
+ const words = run.words
838
+ const bbox = words.reduce((box, word) => [
839
+ Math.min(box[0], word.bbox[0]), Math.min(box[1], word.line[0]),
840
+ Math.max(box[2], word.bbox[2]), Math.max(box[3], word.line[1]),
841
+ ], [Infinity, Infinity, -Infinity, -Infinity])
842
+ const text = words.reduce((acc, word, i) => {
843
+ if (i === 0) return word.text
844
+ const previous = words[i - 1]
845
+ // 断词连写(gen- / erated):前一个词带 continuation,两段直接接,不补空格。
846
+ if (previous.continuation === true) return acc + word.text
847
+ const sameLine = previous.line[0] === word.line[0] && previous.line[1] === word.line[1]
848
+ return acc + (sameLine || acc.endsWith(SPACE) ? EMPTY : SPACE) + word.text
849
+ }, String())
850
+ // fullText 是**整块**正文(所有 part 合起来):划线校验、高亮定位、对齐都对整块做,
851
+ // 不能只看某个 part 的那一截。shaped 里那份 text 本来就是按整块拼好的,直接沿用。
852
+ return { ...source, id: run.id, part, words, bbox, text, fullText: source.text ?? text }
853
+ })
854
+ }
855
+
856
+
857
+
package/lib/picker.js CHANGED
@@ -237,11 +237,25 @@ export function folderPickerScript() {
237
237
  }
238
238
 
239
239
  export function selectedPaths(stdout) {
240
- // CLIXML 噪声可能不带换行地与标记同行拼接,按子串定位标记而不是整行匹配。
241
- const begin = stdout.lastIndexOf('DSH-PAPER-BEGIN')
242
- const end = stdout.lastIndexOf('DSH-PAPER-END')
243
- if (begin === -1 || end === -1 || end < begin) return []
244
- return stdout.slice(begin + 'DSH-PAPER-BEGIN'.length, end).split(/\r?\n/).map(line => line.trim()).filter(Boolean)
240
+ // CLIXML 噪声可能不带换行地与标记同行拼接,所以不能整行匹配。
241
+ //
242
+ // 🔴 也不能拿 `lastIndexOf('DSH-PAPER-BEGIN')` 随便找个位置就切:路径本身可能含这几个字。
243
+ // 实测 `C:\\DSH-PAPER-BEGIN\\a.pdf` 被切成 `\a.pdf`(上一段标记本身被当成了正文),
244
+ // 而含 END 的路径会漏掉自己的尾巴。选出来的路径是要拿去开文件的,切错等于指向另一个位置。
245
+ //
246
+ // 判据改成「标记必须**独占一行**」:允许行首有 CLIXML 噪声,但标记之后到行尾不能再有内容。
247
+ // 这样路径里出现这几个字不会被误认,噪声粘连也照旧能认出来。
248
+ const beginPattern = /(?:^|[\r\n])[^\r\n]*?DSH-PAPER-BEGIN\s*(?=\r?\n|$)/g
249
+ const endPattern = /(?:^|[\r\n])[^\r\n]*?DSH-PAPER-END\s*(?=\r?\n|$)/g
250
+ let begin
251
+ for (const match of stdout.matchAll(beginPattern)) begin = match
252
+ let end
253
+ for (const match of stdout.matchAll(endPattern)) end = match
254
+ if (begin === undefined || end === undefined) return []
255
+ const from = begin.index + begin[0].length
256
+ const to = end.index
257
+ if (to < from) return []
258
+ return stdout.slice(from, to).split(/\r?\n/).map(line => line.trim()).filter(Boolean)
245
259
  }
246
260
 
247
261
  async function runDialog(script, { initialDir = '', cacheDir = '', spawnImpl = spawn }, { label, manualHint }) {
@@ -155,20 +155,24 @@ const BRACKET_MIN_SIDE = 8
155
155
  /** 首尾两截合起来至少要盖住原话的这个比例。 */
156
156
  const BRACKET_MIN_COVERAGE = 0.6
157
157
 
158
- /** quote 的最长前缀中真的出现在 text 里的那一段;一段都配不上返回空串。 */
159
- function quoteHeadInText(quote, text) {
160
- for (let keep = quote.length; keep > 0; keep -= 1) {
161
- const head = quote.slice(0, keep)
162
- if (text.indexOf(head) >= 0) return head
158
+ /** quote 的最长后缀中仍出现在 text 里的那一段;一段都配不上返回空串。 */
159
+ function quoteTailInText(quote, text) {
160
+ if (typeof quote !== 'string' || typeof text !== 'string' || quote === '' || text === '') return ''
161
+ if (text.indexOf(quote) >= 0) return quote
162
+ for (let keep = quote.length - 1; keep > 0; keep -= 1) {
163
+ const tail = quote.slice(quote.length - keep)
164
+ if (text.indexOf(tail) >= 0) return tail
163
165
  }
164
166
  return ''
165
167
  }
166
168
 
167
- /** quote 的最长后缀中真的出现在 text 里的那一段;一段都配不上返回空串。 */
168
- function quoteTailInText(quote, text) {
169
- for (let keep = quote.length; keep > 0; keep -= 1) {
170
- const tail = quote.slice(quote.length - keep)
171
- if (text.indexOf(tail) >= 0) return tail
169
+ /** quote 的最长前缀中仍出现在 text 里的那一段;一段都配不上返回空串。 */
170
+ function quoteHeadInText(quote, text) {
171
+ if (typeof quote !== 'string' || typeof text !== 'string' || quote === '' || text === '') return ''
172
+ if (text.indexOf(quote) >= 0) return quote
173
+ for (let keep = quote.length - 1; keep > 0; keep -= 1) {
174
+ const head = quote.slice(0, keep)
175
+ if (text.indexOf(head) >= 0) return head
172
176
  }
173
177
  return ''
174
178
  }