@li-canghai/dsh-paper 0.0.0-stage → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +137 -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 +2607 -0
- package/lib/client.js +9569 -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 +294 -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 +183 -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/tex-align.js
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 对齐层:把源码块放回 PDF 的页码与坐标上。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要这一层:内容以源码为准,但**位置只有 PDF 有**(页码、bbox、页图、阅读游标
|
|
5
|
+
* 全都依赖它)。源码里没有页码概念,所以必须靠文本把两边对上。
|
|
6
|
+
*
|
|
7
|
+
* 做法分三步,每一步都为一条实测失败设计的:
|
|
8
|
+
* 1. 词级锚点:把块文本切成词元,在 PDF 文本行序列上找覆盖率最高的连续行窗口。
|
|
9
|
+
* 不用「精确子串」—— 实测精确匹配在同一种排版下从 71.4% 掉到 21.2%(PDF 文本层会
|
|
10
|
+
* 在公式周围插空格、把连字符断词写成两个词)。
|
|
11
|
+
* 2. 单调约束:锚点位置只增不减。正文里同一句话出现多次是常态(摘要与正文、正文与附录),
|
|
12
|
+
* 不约束就会把后出现的块配到前一个位置上,产生逆序。
|
|
13
|
+
* 3. 区间插值:没锚到的块(公式、表格这类没有可比文本的)落在前后锚点之间按比例分配,
|
|
14
|
+
* 保证每块都有页码。实测这一步把页码覆盖率从 69% 补到 100%。
|
|
15
|
+
*
|
|
16
|
+
* 纯函数:PDF 文本层由调用方解析好传进来({@link parseBboxLayout}),这一层不碰磁盘。
|
|
17
|
+
*/
|
|
18
|
+
import { tokenize } from './text-similarity.js'
|
|
19
|
+
|
|
20
|
+
const BACKSLASH = '\\'
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 覆盖率门槛:块的**权重**有多大比例必须出现在窗口里。
|
|
24
|
+
*
|
|
25
|
+
* 权重而不是词数 —— 这是这套对齐最关键的一处口径。按词数算,the / of / and 这些词让任意
|
|
26
|
+
* 英文段落都能刷到 50% 以上,于是「配到哪儿」由运气决定;实测一篇真实论文里,一个 31 词元
|
|
27
|
+
* 的段落拿到了 score 0.968 的「最佳匹配」,而那个窗口有 31 行、词元数是段落本身的 7 倍,
|
|
28
|
+
* 配的是完全无关的另一节。按 IDF 加权后,通用词的贡献趋近于零,只有内容词说了算。
|
|
29
|
+
*/
|
|
30
|
+
const MIN_COVERAGE = 0.5
|
|
31
|
+
/** 窗口行数下限:短标题("Introduction")也要能和它所在那一行比。 */
|
|
32
|
+
const MIN_WINDOW = 4
|
|
33
|
+
/**
|
|
34
|
+
* 窗口行数上限。
|
|
35
|
+
*
|
|
36
|
+
* 固定 14 行是另一个系统性失配源:一个 300 词元的段落在 12 词/行的排版里要 25 行以上才
|
|
37
|
+
* 装得下,窗口不够时覆盖率天然上不去,长段落成片失配。90 行是按最粗的切块粒度定的 ——
|
|
38
|
+
* 实测一篇 218 块 / 4334 行的论文,单块平均 20 行正文,600 词元的块要 70 行以上。
|
|
39
|
+
*/
|
|
40
|
+
const MAX_WINDOW = 90
|
|
41
|
+
/** 每个块最多往后扫多少行找锚点。正常文档里块是顺序的,120 行足够跨过一个图或一张表。 */
|
|
42
|
+
// 实测:140 行窗口在一篇 1868 行的论文上会把直连率打到 14.6% —— 正文块被一大段
|
|
43
|
+
// 表格数字与图注隔开时,窗口够不到下一段正文,而 cursor 只在命中时前进,于是永久失配。
|
|
44
|
+
const MAX_SCAN = 400
|
|
45
|
+
/** 命中到这个分数就不再往后扫(已经足够确定,继续扫只会更慢且更容易配到重复段落)。 */
|
|
46
|
+
const EARLY_EXIT = 0.88
|
|
47
|
+
/**
|
|
48
|
+
* 窗口词元数允许比块文本多出的比例。
|
|
49
|
+
*
|
|
50
|
+
* 超出就是「把相邻段落一起框进来了」:这种窗口靠通用词就能拿到高覆盖,但位置没有意义。
|
|
51
|
+
* 实测那类假匹配的比值在 7 倍以上,而正确窗口通常在 0.8–1.6 之间。
|
|
52
|
+
*/
|
|
53
|
+
const MAX_WINDOW_RATIO = 2.5
|
|
54
|
+
/** 超出比例的绝对余量:短块(3–5 词元的标题)旁边多出几个行首编号是常态。 */
|
|
55
|
+
const WINDOW_SLACK = 8
|
|
56
|
+
/**
|
|
57
|
+
* 推进游标所需的最小词元数。
|
|
58
|
+
*
|
|
59
|
+
* 一两个词元的块("Mem0"、"Dataset"、"Introduction")没有定位能力:同一个词在页眉、
|
|
60
|
+
* 图注、正文里反复出现,任何一处都能拿到 score 1。允许它们**定锚**,但不允许它们
|
|
61
|
+
* **推动游标** —— 一次误配把游标推到文末,后面几十个正文块会一起落在扫描区间之外。
|
|
62
|
+
*/
|
|
63
|
+
const CURSOR_MIN_TOKENS = 4
|
|
64
|
+
/** 推进游标所需的最小分数:位置不确定的命中不该把后面的块锁进错误区间。 */
|
|
65
|
+
const CURSOR_MIN_SCORE = 0.75
|
|
66
|
+
/**
|
|
67
|
+
* 单次推进允许跨过的「块篇幅」倍数。
|
|
68
|
+
*
|
|
69
|
+
* 一个块正常只比前一个块往后几行到几十行。一次跳过相当于十几个块的篇幅,要么中间
|
|
70
|
+
* 隔着大图大表,要么就是配错了 —— 实测一篇 532 块的论文里,第 190 块被配到第 2531 行
|
|
71
|
+
* (文末),游标从此锁死,其后 283 个块全部失配;而这些块在 PDF 里的覆盖率是 1.0,
|
|
72
|
+
* 根本不存在「文本对不上」的问题。
|
|
73
|
+
*/
|
|
74
|
+
const MAX_JUMP_BLOCKS = 12
|
|
75
|
+
/** 跨越幅度超过 jumpLimit 时,必须达到这个分数才允许推进游标。 */
|
|
76
|
+
const CURSOR_STRICT_SCORE = 0.97
|
|
77
|
+
/** 第二遍(区间重搜)与第四遍(反扫)用的宽松门槛。 */
|
|
78
|
+
const SEARCH_LOOSE = 0.7
|
|
79
|
+
/** 反扫时允许收窄搜索上界的锚点分数:低分锚点不该决定「后面还有多远」。 */
|
|
80
|
+
const REVERSE_TRUST_SCORE = 0.9
|
|
81
|
+
/**
|
|
82
|
+
* 「块里有、PDF 里根本没出现过」的词元权重。
|
|
83
|
+
*
|
|
84
|
+
* 公式源码(\$m_{t-1}\$)、命令名、编号都属于这一类:它们既不能证实也不能否证位置,
|
|
85
|
+
* 按未验证词处理、只给很小的权重,免得含公式的段落被自己的公式拖低分数。
|
|
86
|
+
*/
|
|
87
|
+
const UNSEEN_WEIGHT = 0.1
|
|
88
|
+
|
|
89
|
+
/** 解析 XML 属性(只认双引号:pdftotext 输出恒为双引号)。
|
|
90
|
+
* 不用 new RegExp 拼名字:字符串里的反斜杠转义层数容易写错,而这里只需要「前面是空白」。
|
|
91
|
+
*/
|
|
92
|
+
function attrOf(tag, name) {
|
|
93
|
+
const pattern = name + '="'
|
|
94
|
+
let index = tag.indexOf(pattern)
|
|
95
|
+
while (index !== -1) {
|
|
96
|
+
const before = index === 0 ? ' ' : tag[index - 1]
|
|
97
|
+
if (/[ \t\n\r]/.test(before)) break
|
|
98
|
+
index = tag.indexOf(pattern, index + 1)
|
|
99
|
+
}
|
|
100
|
+
if (index === -1) return null
|
|
101
|
+
const start = index + pattern.length
|
|
102
|
+
const end = tag.indexOf('"', start)
|
|
103
|
+
return end === -1 ? null : tag.slice(start, end)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 解析 {pdftotext -bbox-layout} 的输出,返回逐行文本。
|
|
108
|
+
*
|
|
109
|
+
* 为什么要行而不是词:锚点按「连续若干行」合成一个窗口,行是天然的最小单元;按词会把
|
|
110
|
+
* 同一行拆成多个节点,窗口边界就不再对应排版上的行。
|
|
111
|
+
*
|
|
112
|
+
* 每行带 page(**1 起**)、text、bbox([x0, y0, x1, y1])与 height(用于标题识别)。
|
|
113
|
+
* 解析是防御式的:缺属性、空行、嵌套结构异常都只是跳过,不抛错 —— 文本层拿不全时
|
|
114
|
+
* 应该降级对齐,而不是让整篇解析失败。
|
|
115
|
+
*/
|
|
116
|
+
export function parseBboxLayout(xml) {
|
|
117
|
+
const source = typeof xml === 'string' ? xml : ''
|
|
118
|
+
const lines = []
|
|
119
|
+
let page = 0
|
|
120
|
+
const pagePattern = /<page\b[^>]*>/g
|
|
121
|
+
let pageMatch
|
|
122
|
+
// 先切页,再在每页里切行:<line> 不跨页,但页属性要跟着走。
|
|
123
|
+
while ((pageMatch = pagePattern.exec(source)) !== null) {
|
|
124
|
+
page += 1
|
|
125
|
+
const pageStart = pageMatch.index + pageMatch[0].length
|
|
126
|
+
const pageEnd = source.indexOf('</page>', pageStart)
|
|
127
|
+
const body = source.slice(pageStart, pageEnd === -1 ? source.length : pageEnd)
|
|
128
|
+
const linePattern = /<line\b[^>]*>([\s\S]*?)<\/line>/g
|
|
129
|
+
let lineMatch
|
|
130
|
+
while ((lineMatch = linePattern.exec(body)) !== null) {
|
|
131
|
+
const tag = lineMatch[0].slice(0, lineMatch[0].indexOf('>') + 1)
|
|
132
|
+
const x0 = Number(attrOf(tag, 'xMin'))
|
|
133
|
+
const y0 = Number(attrOf(tag, 'yMin'))
|
|
134
|
+
const x1 = Number(attrOf(tag, 'xMax'))
|
|
135
|
+
const y1 = Number(attrOf(tag, 'yMax'))
|
|
136
|
+
const words = [...lineMatch[1].matchAll(/<word[^>]*>([\s\S]*?)<\/word>/g)].map(word => decodeXml(word[1]))
|
|
137
|
+
const text = words.join(' ').replace(/\s+/g, ' ').trim()
|
|
138
|
+
if (text === '') continue
|
|
139
|
+
lines.push({
|
|
140
|
+
page,
|
|
141
|
+
text,
|
|
142
|
+
bbox: [Number.isFinite(x0) ? x0 : 0, Number.isFinite(y0) ? y0 : 0, Number.isFinite(x1) ? x1 : 0, Number.isFinite(y1) ? y1 : 0],
|
|
143
|
+
height: Number.isFinite(y1) && Number.isFinite(y0) ? y1 - y0 : 0,
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return lines
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** XML 实体还原(pdftotext 只用基本的五个)。 */
|
|
151
|
+
function decodeXml(text) {
|
|
152
|
+
return String(text ?? '')
|
|
153
|
+
.replace(/</g, '<')
|
|
154
|
+
.replace(/>/g, '>')
|
|
155
|
+
.replace(/"/g, '"')
|
|
156
|
+
.replace(/'/g, "'")
|
|
157
|
+
.replace(/&/g, '&')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 块的比较文本:正文取 text,图表类取 caption。取不到给空串。 */
|
|
161
|
+
function compareTextOf(item) {
|
|
162
|
+
// 公式的 tex 里全是 a、b、x 这种单字母,拿去正文里匹配必然误中(实测把公式配到任意一行)。
|
|
163
|
+
// 公式的位置由相邻块插值决定。
|
|
164
|
+
if (item?.type === 'equation') return ''
|
|
165
|
+
if (typeof item?.text === 'string' && item.text !== '') return item.text
|
|
166
|
+
if (typeof item?.caption === 'string' && item.caption !== '') return item.caption
|
|
167
|
+
return ''
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 两行是否在同页且垂直邻近(用来判断联合 bbox 是否跨页)。 */
|
|
171
|
+
function unionBbox(rows) {
|
|
172
|
+
if (rows.length === 0) return undefined
|
|
173
|
+
let x0 = Infinity
|
|
174
|
+
let y0 = Infinity
|
|
175
|
+
let x1 = -Infinity
|
|
176
|
+
let y1 = -Infinity
|
|
177
|
+
for (const row of rows) {
|
|
178
|
+
const [left, top, right, bottom] = row.bbox
|
|
179
|
+
if (left < x0) x0 = left
|
|
180
|
+
if (top < y0) y0 = top
|
|
181
|
+
if (right > x1) x1 = right
|
|
182
|
+
if (bottom > y1) y1 = bottom
|
|
183
|
+
}
|
|
184
|
+
if (!Number.isFinite(x0) || !Number.isFinite(y0) || !Number.isFinite(x1) || !Number.isFinite(y1)) return undefined
|
|
185
|
+
return [x0, y0, x1, y1]
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* 在 PDF 行序列上给每个源码块找位置。
|
|
190
|
+
*
|
|
191
|
+
* @param {Array<object>} items 源码块(blocksOfDocument 的产出)
|
|
192
|
+
* @param {Array<{page: number, text: string, bbox: number[], height: number}>} lines PDF 文本行
|
|
193
|
+
* @param {{minCoverage?: number, maxWindow?: number, maxScan?: number}} [options]
|
|
194
|
+
* @returns {{items: Array<object>, stats: {total: number, direct: number, interpolated: number,
|
|
195
|
+
* directRatio: number, coverage: number}}}
|
|
196
|
+
*/
|
|
197
|
+
export function alignBlocks(items, lines, options = {}) {
|
|
198
|
+
const list = Array.isArray(items) ? items : []
|
|
199
|
+
const rows = Array.isArray(lines) ? lines : []
|
|
200
|
+
const minCoverage = Number.isFinite(options.minCoverage) ? options.minCoverage : MIN_COVERAGE
|
|
201
|
+
const maxWindow = Number.isFinite(options.maxWindow) ? options.maxWindow : MAX_WINDOW
|
|
202
|
+
const maxScan = Number.isFinite(options.maxScan) ? options.maxScan : MAX_SCAN
|
|
203
|
+
const diagnostics = options.diagnose === true ? [] : null
|
|
204
|
+
if (list.length === 0) return { items: [], stats: { total: 0, direct: 0, interpolated: 0, directRatio: 0, coverage: 0 } }
|
|
205
|
+
if (rows.length === 0) {
|
|
206
|
+
// 没有文本层:所有块都放第 1 页、无坐标。页码仍是有效信息(MinerU 的 page 从 1 起)。
|
|
207
|
+
return {
|
|
208
|
+
items: list.map(item => ({ ...item, page_idx: 0, bbox: undefined })),
|
|
209
|
+
stats: { total: list.length, direct: 0, interpolated: list.length, directRatio: 0, coverage: 0 },
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const prepared = rows.map((row, index) => {
|
|
214
|
+
const tokens = new Set(tokenize(row.text))
|
|
215
|
+
const text = row.text.trim()
|
|
216
|
+
// 行尾连字符重连:学术 PDF 是双栏窄行,断词遍布正文,不重连的话
|
|
217
|
+
// applications 与 applica-/tions 永远对不上。
|
|
218
|
+
if (text.endsWith('-') && index + 1 < rows.length) {
|
|
219
|
+
const head = rows[index + 1].text.trim().split(/\s+/)[0] ?? ''
|
|
220
|
+
if (head !== '') for (const token of tokenize(text.slice(0, -1) + head)) tokens.add(token)
|
|
221
|
+
}
|
|
222
|
+
return { ...row, tokens }
|
|
223
|
+
})
|
|
224
|
+
/**
|
|
225
|
+
* 词元的文档频率与权重。
|
|
226
|
+
*
|
|
227
|
+
* 用 IDF 而不是词数:一篇论文里 the / of / and 占正文词元的三成以上,按词数算覆盖率
|
|
228
|
+
* 等价于「这段话里有多少个常见词」,任何两段英文都能互相匹配。IDF 让稀有词主导分数,
|
|
229
|
+
* 「配到哪儿」才由内容决定。
|
|
230
|
+
*/
|
|
231
|
+
const total = prepared.length
|
|
232
|
+
const frequency = new Map()
|
|
233
|
+
for (const row of prepared) {
|
|
234
|
+
for (const token of row.tokens) frequency.set(token, (frequency.get(token) ?? 0) + 1)
|
|
235
|
+
}
|
|
236
|
+
const weightOf = token => {
|
|
237
|
+
const count = frequency.get(token)
|
|
238
|
+
if (count === undefined) return UNSEEN_WEIGHT
|
|
239
|
+
return Math.log((total + 1) / (count + 1)) + 0.15
|
|
240
|
+
}
|
|
241
|
+
const needles = list.map(item => {
|
|
242
|
+
const weights = new Map()
|
|
243
|
+
let sum = 0
|
|
244
|
+
for (const token of tokenize(compareTextOf(item))) {
|
|
245
|
+
if (weights.has(token)) continue
|
|
246
|
+
const weight = weightOf(token)
|
|
247
|
+
weights.set(token, weight)
|
|
248
|
+
sum += weight
|
|
249
|
+
}
|
|
250
|
+
return { weights, sum, size: weights.size }
|
|
251
|
+
})
|
|
252
|
+
|
|
253
|
+
/** 每行平均多少词元:窗口行数按它从块大小换算出来。 */
|
|
254
|
+
const perLine = prepared.length === 0
|
|
255
|
+
? 10
|
|
256
|
+
: prepared.reduce((sum, row) => sum + row.tokens.size, 0) / prepared.length
|
|
257
|
+
|
|
258
|
+
/** 在 [from, to) 区间里给第 index 块找最佳窗口。 */
|
|
259
|
+
const search = (index, from, to) => {
|
|
260
|
+
const needle = needles[index]
|
|
261
|
+
if (needle.size === 0) return null
|
|
262
|
+
// 窗口按块大小自适应:短块 4 行,300 词元的段落要 30 行上下才装得下。
|
|
263
|
+
const wanted = Math.ceil(needle.size / Math.max(4, perLine)) + 3
|
|
264
|
+
const span = Math.max(MIN_WINDOW, Math.min(maxWindow, wanted))
|
|
265
|
+
// 词元数超过这个数的窗口一律不算候选(见 MAX_WINDOW_RATIO)。
|
|
266
|
+
const ceiling = needle.size * MAX_WINDOW_RATIO + WINDOW_SLACK
|
|
267
|
+
let best = null
|
|
268
|
+
const limit = Math.min(prepared.length, to)
|
|
269
|
+
const counts = new Map()
|
|
270
|
+
for (let start = Math.max(0, from); start < limit; start += 1) {
|
|
271
|
+
counts.clear()
|
|
272
|
+
let weightSum = 0
|
|
273
|
+
let unionSize = 0
|
|
274
|
+
for (let width = 1; width <= span && start + width <= prepared.length; width += 1) {
|
|
275
|
+
for (const token of prepared[start + width - 1].tokens) {
|
|
276
|
+
const seen = counts.get(token)
|
|
277
|
+
if (seen !== undefined) { counts.set(token, seen + 1); continue }
|
|
278
|
+
counts.set(token, 1)
|
|
279
|
+
unionSize += 1
|
|
280
|
+
const weight = needle.weights.get(token)
|
|
281
|
+
if (weight !== undefined) weightSum += weight
|
|
282
|
+
}
|
|
283
|
+
// 窗口已经比块本身宽太多:继续加行只会更宽,换下一个起点。
|
|
284
|
+
if (unionSize > ceiling) break
|
|
285
|
+
const score = weightSum / needle.sum
|
|
286
|
+
if (score < minCoverage) continue
|
|
287
|
+
const ratio = unionSize / needle.size
|
|
288
|
+
const better = best === null || score > best.score + 1e-9
|
|
289
|
+
|| (Math.abs(score - best.score) <= 1e-9 && ratio < best.ratio)
|
|
290
|
+
if (better) best = { start, end: start + width - 1, value: score, score, ratio }
|
|
291
|
+
if (score >= EARLY_EXIT && ratio <= 1.25) break
|
|
292
|
+
}
|
|
293
|
+
if (best !== null && best.score >= EARLY_EXIT && best.ratio <= 1.25) break
|
|
294
|
+
}
|
|
295
|
+
return best
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const anchors = new Array(list.length).fill(null)
|
|
299
|
+
/** 块与行的比例:判断一次推进是不是跳过了不合常理的篇幅。 */
|
|
300
|
+
const perBlockLines = prepared.length / Math.max(1, list.length)
|
|
301
|
+
const jumpLimit = Math.max(40, perBlockLines * MAX_JUMP_BLOCKS)
|
|
302
|
+
let cursor = 0
|
|
303
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
304
|
+
const best = search(index, cursor, cursor + maxScan)
|
|
305
|
+
anchors[index] = best
|
|
306
|
+
if (best === null) {
|
|
307
|
+
// 失配时游标缓慢前进:原地不动会让后面全部连锁失配(实测一篇 1868 行的论文里
|
|
308
|
+
// 一次卡死就把直连率从 47% 打到 9%)。
|
|
309
|
+
cursor = Math.min(cursor + 2, Math.max(0, prepared.length - 1))
|
|
310
|
+
continue
|
|
311
|
+
}
|
|
312
|
+
// 只有可信命中才推进游标(理由见 CURSOR_MIN_TOKENS):实测一篇 142 块的论文里,
|
|
313
|
+
// 一个 1 词元的 "Mem0" 小节标题把游标从第 109 行推到第 469 行,其后 30 多个
|
|
314
|
+
// 正文块连锁失配,直连率只剩 13.7%。
|
|
315
|
+
if (best.score >= CURSOR_MIN_SCORE && needles[index].size >= CURSOR_MIN_TOKENS) {
|
|
316
|
+
const jump = best.start - cursor
|
|
317
|
+
// 跨越幅度不合常理时只有「几乎确定」才放行;不放行也不影响这一块自己的锚点,
|
|
318
|
+
// 只是不让它把后面的块一起拖走。
|
|
319
|
+
if (jump <= jumpLimit || best.score >= CURSOR_STRICT_SCORE) {
|
|
320
|
+
cursor = Math.max(cursor, best.start)
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* 第二遍:在「前后已命中块之间的空档」里重新搜。
|
|
327
|
+
*
|
|
328
|
+
* 单调游标一旦被一段表格数字或图注隔开,后面的块就永远落在 maxScan 之外。这一遍用两侧
|
|
329
|
+
* 锚点把搜索区间夹住:既不受 maxScan 限制,也不会跨到别的小节去。分数不够就保持 null,
|
|
330
|
+
* 交给插值 —— 宁可按比例分,也不要配错位置。
|
|
331
|
+
*/
|
|
332
|
+
const known = []
|
|
333
|
+
for (let index = 0; index < list.length; index += 1) if (anchors[index] !== null) known.push(index)
|
|
334
|
+
/**
|
|
335
|
+
* 重扫用的边界只取**高置信**锚点。
|
|
336
|
+
*
|
|
337
|
+
* 这是实测出来的关键差别:混用低分锚点会把文档切成很多碎区间,一个「凑巧 0.8 分」
|
|
338
|
+
* 的误配就夹出一段只有几十行的区间,真正的块永远进不去。只认高置信锚点时,区间变大、
|
|
339
|
+
* 碎块消失 —— 实测一篇 345 块的论文里,失配块中有 164 块在全文里能拿到 0.9 以上,
|
|
340
|
+
* 它们全都是被这些碎区间挡住的。
|
|
341
|
+
*/
|
|
342
|
+
/** 重扫边界:高置信锚点优先,太少时退回全部锚点。 */
|
|
343
|
+
const trustedBounds = () => {
|
|
344
|
+
const edges = []
|
|
345
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
346
|
+
if (anchors[index] === null) continue
|
|
347
|
+
if (anchors[index].score >= REVERSE_TRUST_SCORE && needles[index].size >= CURSOR_MIN_TOKENS) edges.push(index)
|
|
348
|
+
}
|
|
349
|
+
return edges.length >= 2 ? edges : known.slice()
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* 第二遍:在「高置信锚点之间」的空档里重新搜。返回这一轮补上的块数。
|
|
354
|
+
*
|
|
355
|
+
* 单调游标一旦被一段表格数字或图注隔开,后面的块就永远落在 maxScan 之外。这一遍用两侧
|
|
356
|
+
* 锚点把搜索区间夹住:既不受 maxScan 限制,也不会跨到别的小节去。
|
|
357
|
+
*
|
|
358
|
+
* 包成函数并按轮调用:一轮补上的锚点会重新切分区间,把上一轮被碎区间挡住的块放进来。
|
|
359
|
+
*/
|
|
360
|
+
const rescanGaps = () => {
|
|
361
|
+
const bounds = trustedBounds()
|
|
362
|
+
let added = 0
|
|
363
|
+
for (let slot = 0; slot < bounds.length - 1; slot += 1) {
|
|
364
|
+
const left = bounds[slot]
|
|
365
|
+
const right = bounds[slot + 1]
|
|
366
|
+
if (right - left <= 1) continue // 相邻两个命中之间没有空档
|
|
367
|
+
const from = anchors[left].start
|
|
368
|
+
const to = anchors[right].end + 1
|
|
369
|
+
for (let index = left + 1; index < right; index += 1) {
|
|
370
|
+
if (anchors[index] !== null) continue
|
|
371
|
+
const best = search(index, from, to)
|
|
372
|
+
// 判据比第一遍松一点:区间已经被两侧锚点夹住,错配的空间很小;实测真实论文里
|
|
373
|
+
// 大量正确块的分数在 0.7–0.85(公式、引用编号会拉低分数),用 0.88 卡会全丢掉。
|
|
374
|
+
if (best !== null && best.score >= SEARCH_LOOSE) { anchors[index] = best; added += 1 }
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return added
|
|
378
|
+
}
|
|
379
|
+
for (let round = 0; round < 3; round += 1) if (rescanGaps() === 0) break
|
|
380
|
+
|
|
381
|
+
// 头部与尾部:第一遍最多只覆盖到「最后一个能扫到的命中」,尾部那一大段全落在窗口外。
|
|
382
|
+
// 这两段各自从已知锚点往外单向扫描,命中一个就把下界推进一格。
|
|
383
|
+
const headBounds = trustedBounds()
|
|
384
|
+
if (headBounds.length > 0) {
|
|
385
|
+
const head = headBounds[0]
|
|
386
|
+
for (let index = 0; index < head; index += 1) {
|
|
387
|
+
const best = search(index, 0, anchors[head].start + 1)
|
|
388
|
+
if (best !== null && best.score >= SEARCH_LOOSE) anchors[index] = best
|
|
389
|
+
}
|
|
390
|
+
let from = anchors[headBounds[headBounds.length - 1]].end
|
|
391
|
+
for (let index = headBounds[headBounds.length - 1] + 1; index < list.length; index += 1) {
|
|
392
|
+
const best = search(index, from, prepared.length)
|
|
393
|
+
if (best !== null && best.score >= SEARCH_LOOSE) {
|
|
394
|
+
anchors[index] = best
|
|
395
|
+
from = best.end
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* 第四遍:反向补扫。
|
|
402
|
+
*
|
|
403
|
+
* 前两遍都是「从前往后」,这带来一个结构性弱点:只要某个块被配到了靠后的位置,它后面
|
|
404
|
+
* 的块就再没有机会回头 —— 而那些块在 PDF 里是**存在且可匹配**的(实测覆盖率 1.0)。
|
|
405
|
+
* 这一遍从文末往前扫,一个块定位成功就把上界往前挪一格,把被游标甩掉的尾部块锚回来。
|
|
406
|
+
*
|
|
407
|
+
* 只补前几遍没锚上的块,门槛也更严(0.75):反扫是在「顺序未知」的区域里工作,
|
|
408
|
+
* 宁可留给插值,也不要为了填满直连率而配错位置。
|
|
409
|
+
*/
|
|
410
|
+
let upper = prepared.length - 1
|
|
411
|
+
for (let index = list.length - 1; index >= 0; index -= 1) {
|
|
412
|
+
if (anchors[index] !== null) {
|
|
413
|
+
// 只有高置信锚点才能收窄上界:零星的低分锚点会把上界拖到文档开头,
|
|
414
|
+
// 于是「覆盖率 1.0」的块也搜不到(实测一篇附录里 score 1.0 的小节标题因此 MISS)。
|
|
415
|
+
if (anchors[index].score >= REVERSE_TRUST_SCORE && anchors[index].start - 1 < upper) {
|
|
416
|
+
upper = anchors[index].start - 1
|
|
417
|
+
}
|
|
418
|
+
continue
|
|
419
|
+
}
|
|
420
|
+
if (upper < 0) break
|
|
421
|
+
const best = search(index, 0, upper + 1)
|
|
422
|
+
if (best !== null && best.score >= SEARCH_LOOSE && best.end <= upper) {
|
|
423
|
+
anchors[index] = best
|
|
424
|
+
upper = best.start - 1
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
// 反扫补上的锚点同样会切出新区间:再补几轮,把新区间里的块放进来。
|
|
428
|
+
for (let round = 0; round < 2; round += 1) if (rescanGaps() === 0) break
|
|
429
|
+
// 反扫新增了锚点,插值用的边界列表要按最新的重算。
|
|
430
|
+
known.length = 0
|
|
431
|
+
for (let index = 0; index < list.length; index += 1) if (anchors[index] !== null) known.push(index)
|
|
432
|
+
|
|
433
|
+
/** 把行区间换算成块的位置字段。 */
|
|
434
|
+
const place = (start, end) => {
|
|
435
|
+
const from = Math.max(0, Math.min(start, prepared.length - 1))
|
|
436
|
+
const to = Math.max(from, Math.min(end, prepared.length - 1))
|
|
437
|
+
const window = prepared.slice(from, to + 1)
|
|
438
|
+
const pageIdx = prepared[from].page - 1
|
|
439
|
+
return { page_idx: pageIdx >= 0 ? pageIdx : 0, bbox: unionBbox(window) }
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const marks = new Array(list.length).fill(null)
|
|
443
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
444
|
+
if (anchors[index] !== null) marks[index] = place(anchors[index].start, anchors[index].end)
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* 插值:没锚到的块落在前后已定位块之间,按「块序号比例」分配行号。
|
|
449
|
+
*
|
|
450
|
+
* 按比例而不是按词数:这一段的准确位置本来就未知,按块数均分至少保证**顺序正确**,
|
|
451
|
+
* 而顺序错会让阅读器把「第 3 节的公式」显示在第 2 节里。
|
|
452
|
+
*/
|
|
453
|
+
if (known.length === 0) {
|
|
454
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
455
|
+
const from = Math.floor((index / list.length) * prepared.length)
|
|
456
|
+
const to = Math.max(from, Math.floor(((index + 1) / list.length) * prepared.length) - 1)
|
|
457
|
+
marks[index] = place(from, to)
|
|
458
|
+
}
|
|
459
|
+
} else {
|
|
460
|
+
const first = known[0]
|
|
461
|
+
for (let index = 0; index < first; index += 1) marks[index] = marks[first]
|
|
462
|
+
for (let slot = 0; slot < known.length - 1; slot += 1) {
|
|
463
|
+
const leftIndex = known[slot]
|
|
464
|
+
const rightIndex = known[slot + 1]
|
|
465
|
+
const gap = rightIndex - leftIndex - 1
|
|
466
|
+
if (gap <= 0) continue
|
|
467
|
+
const startLine = (anchors[leftIndex]?.end ?? 0) + 1
|
|
468
|
+
const endLine = (anchors[rightIndex]?.start ?? prepared.length) - 1
|
|
469
|
+
for (let step = 0; step < gap; step += 1) {
|
|
470
|
+
const position = startLine + Math.floor((step / gap) * (endLine - startLine + 1))
|
|
471
|
+
marks[leftIndex + 1 + step] = place(Math.max(0, position), Math.max(0, position))
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
const last = known[known.length - 1]
|
|
475
|
+
for (let index = last + 1; index < list.length; index += 1) marks[index] = marks[last]
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const output = list.map((item, index) => {
|
|
479
|
+
const mark = marks[index] ?? { page_idx: 0, bbox: undefined }
|
|
480
|
+
return { ...item, page_idx: mark.page_idx, bbox: mark.bbox }
|
|
481
|
+
})
|
|
482
|
+
if (diagnostics !== null) {
|
|
483
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
484
|
+
diagnostics.push({
|
|
485
|
+
index, kind: list[index].type, needle: needles[index].size,
|
|
486
|
+
start: anchors[index] === null ? -1 : anchors[index].start,
|
|
487
|
+
score: anchors[index] === null ? 0 : Number(anchors[index].score.toFixed(3)),
|
|
488
|
+
ratio: anchors[index] === null ? 0 : Number(anchors[index].ratio.toFixed(2)),
|
|
489
|
+
})
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
const direct = anchors.filter(anchor => anchor !== null).length
|
|
493
|
+
// 🔴 分母只算「有可比文本的块」:公式与表格没有可比文本(needle 为空),
|
|
494
|
+
// 它们本来就只能靠插值定位,算进分母会让直连率永远上不去(实测一篇真实论文里
|
|
495
|
+
// 43 个公式/表格块把 53.4% 压到 47.6%,于是整篇被误判降级)。
|
|
496
|
+
const alignable = needles.filter(needle => needle.size > 0).length
|
|
497
|
+
return {
|
|
498
|
+
items: output,
|
|
499
|
+
stats: {
|
|
500
|
+
total: list.length,
|
|
501
|
+
direct,
|
|
502
|
+
interpolated: list.length - direct,
|
|
503
|
+
alignable,
|
|
504
|
+
directRatio: alignable === 0 ? 0 : direct / alignable,
|
|
505
|
+
coverage: 1,
|
|
506
|
+
...(diagnostics === null ? {} : { diagnostics }),
|
|
507
|
+
},
|
|
508
|
+
}
|
|
509
|
+
}
|