@li-canghai/dsh-paper 0.0.0-stage → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +150 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2762 -0
- package/lib/client-parts/02-author-year.js +95 -0
- package/lib/client.js +10381 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +308 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +261 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 行内文本清理:把 LaTeX 片段变成读者在 PDF 上看到的那串字。
|
|
3
|
+
*
|
|
4
|
+
* 单独成模块是为了避免循环依赖:切块层与表格层都要用它,而表格层又要被切块层引用。
|
|
5
|
+
*
|
|
6
|
+
* 目标是「读者看到的那串字」,所以:格式命令只留参数、引用命令变成方括号、转义字符还原、
|
|
7
|
+
* 连字与波浪号按 LaTeX 语义展开。**数学区整段跳过** —— 里面的逗号间距、下划线、希腊字母
|
|
8
|
+
* 都是 KaTeX 要看的语义,动了就渲染不出来。
|
|
9
|
+
*
|
|
10
|
+
* 收尾那一步(删掉所有剩余命令名)是这套转换的兜底:正文里出现 \Comment{record timestamp}
|
|
11
|
+
* 这类原文是明确错误 —— 读者在 PDF 上看到的是批注文字,不是命令名。而绝大多数命令的参数
|
|
12
|
+
* 本来就是正文内容,所以「删名留参」是这种情况下最接近原文的取法。
|
|
13
|
+
*/
|
|
14
|
+
const BACKSLASH = String.fromCharCode(92)
|
|
15
|
+
|
|
16
|
+
/** 行内数学的占位符:清理文本时不能碰 $...$ 里的内容。 */
|
|
17
|
+
const MATH_SLOT = String.fromCharCode(1)
|
|
18
|
+
|
|
19
|
+
/** 少数几个命令有确定的字面意义,删掉会丢信息。 */
|
|
20
|
+
const SYMBOLS = new Map([
|
|
21
|
+
['checkmark', '✓'],
|
|
22
|
+
['ldots', '…'],
|
|
23
|
+
['dots', '…'],
|
|
24
|
+
['textellipsis', '…'],
|
|
25
|
+
['textendash', '–'],
|
|
26
|
+
['textemdash', '—'],
|
|
27
|
+
['textbackslash', BACKSLASH],
|
|
28
|
+
])
|
|
29
|
+
|
|
30
|
+
export function inlineText(raw, options) {
|
|
31
|
+
let text = typeof raw === 'string' ? raw : ''
|
|
32
|
+
if (text === '') return ''
|
|
33
|
+
const slots = []
|
|
34
|
+
// 行内公式占位。允许跨行(源码里一个公式写成两三行很常见),但**限长 200 字符**:
|
|
35
|
+
// 不设上限时,一个未闭合的 `$` 会一路配到下一个 `$`,把大段正文当成公式跳过清理 ——
|
|
36
|
+
// 实测那种残片会在正文里留下 `\ \mathrm { 4 } \ : ( 3 \mathrm { = }`。
|
|
37
|
+
text = text.replace(/\$[^$]{0,200}\$/g, match => {
|
|
38
|
+
slots.push(match)
|
|
39
|
+
return MATH_SLOT + (slots.length - 1) + MATH_SLOT
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
// 声明式字体命令({\em xxx} 这种):去掉命令本身,花括号里的内容留下。
|
|
43
|
+
text = text.replace(/\{\\(?:em|bf|it|sc|sl|tt|rm|sf|normalfont|small)\s+/g, '{')
|
|
44
|
+
text = text.replace(/\\(?:em|bf|it|sc|sl|tt|rm|sf|normalfont|small)\s+/g, '')
|
|
45
|
+
// 零参命令:删掉即可(xspace 是「按需加空格」,maketitle 在切块层已经当块边界处理)。
|
|
46
|
+
text = text.replace(/\\(?:xspace|relax|protect|noindent|indent|maketitle|hfill|vfill|centering|copyright)\s*/g, '')
|
|
47
|
+
// 带参命令:整条删掉(它们的参数不该进正文)。
|
|
48
|
+
text = text.replace(/\\(?:label|index|vspace\*?|hspace\*?|phantom|protect|zref|nocite|arrayrulecolor)\s*\{[^{}]*\}/g, '')
|
|
49
|
+
// 带**两组**参数的长度设置:只删一组会留下 `{0.5pt}` → 花括号再删就成了正文里的 `0.5pt`
|
|
50
|
+
// (实测表格单元格 `0.5pt1pt1ptblack Evaluation Granularity`)。
|
|
51
|
+
text = text.replace(/\\(?:setlength|addtolength|renewcommand|newcommand)\s*\{[^{}]*\}\s*\{[^{}]*\}/g, '')
|
|
52
|
+
// 🔴 颜色与线宽也不是正文。兜底那一步只删命令名,`\\cellcolor{gray!60}` 会留下 `gray!60` ——
|
|
53
|
+
// 实测表格单元格因此变成 `gray!600.5pt1pt1ptblack Evaluation Granularity`,段落里也有
|
|
54
|
+
// `blue!55!blackblue!6 -2-2 Overall:`。读者与模型都会把颜色名当内容读。
|
|
55
|
+
// 带内容参数的先只留内容,其余整条删。
|
|
56
|
+
text = text.replace(/\\(?:textcolor|colorbox)\s*(?:\[[^\]]*\])?\s*\{[^{}]*\}\s*\{([^{}]*)\}/g, '$1')
|
|
57
|
+
text = text.replace(/\\(?:cellcolor|rowcolor|columncolor|color|pagecolor)\s*(?:\[[^\]]*\])?\s*\{[^{}]*\}/g, '')
|
|
58
|
+
// 兜底:漏出来的颜色表达式 `blue!55!black`(宏展开或列修饰里已成碎片)。
|
|
59
|
+
// 颜色语法 `word!数字` 在正文里没有别的含义。
|
|
60
|
+
text = text.replace(/\b[a-z]+!\d+(?:![a-z]+)?/g, ' ')
|
|
61
|
+
// `\\rule{宽}{高}` 只是画线;两段参数都要吃掉,否则会留下 `0.5pt1pt`。
|
|
62
|
+
text = text.replace(/\\rule\s*(?:\[[^\]]*\])?\s*\{[^{}]*\}\s*\{[^{}]*\}/g, '')
|
|
63
|
+
text = text.replace(/\\specialrule\s*\{[^{}]*\}\s*\{[^{}]*\}\s*\{[^{}]*\}/g, '')
|
|
64
|
+
// 🔴 图片命令整条删掉:路径与 `[width=…]` 选项都不是正文。图本身由 tex-figures 单独落盘,
|
|
65
|
+
// 漏在正文里就是 `-0.1[width=0.4cm]latex/0_abstract/hg_logo.png`(实测 DRIFTLENS 首页拼图)。
|
|
66
|
+
text = text.replace(/\\(?:includegraphics|includesvg)\*?\s*(?:\[[^\]]*\])?\s*\{[^{}]*\}/g, '')
|
|
67
|
+
// 🔴 环境定界符也要整条删。兜底那一步只删命令名,`\\begin{center}` 会留下 `{center}`,
|
|
68
|
+
// 再删花括号就变成正文里的一个 `center` —— 这才是「杂音」里最容易被忽略的一类。
|
|
69
|
+
// 🔴 环境名后面的**可选参数**不是正文:`\begin{tcolorbox}[colback=blue!5!white, title=…]`
|
|
70
|
+
// 漏进去的话,读者与模型都会把 `colback=blue!5!white` 当正文读。实测全库 34 处 blue、
|
|
71
|
+
// 16 处 colback/colframe、16 处 title、13 处 darkgray —— 都是这类环境的键值对。
|
|
72
|
+
// 紧跟在 `\begin{X}` / `\end{X}` 之后的 `[...]` 在正文里没有别的含义,一并吃掉。
|
|
73
|
+
text = text.replace(/\\(?:begin|end)\s*\{[^{}]*\}\s*(?:\[[^\[\]]*\])?/g, ' ')
|
|
74
|
+
// 链接:读者看到的是链接文字,不是地址参数。
|
|
75
|
+
text = text.replace(/\\href\s*\{[^{}]*\}\s*\{([^{}]*)\}/g, '$1')
|
|
76
|
+
text = text.replace(/\\url\s*\{([^{}]*)\}/g, '$1')
|
|
77
|
+
// 格式命令:只留参数。跑三遍以吃掉嵌套(\textbf{\emph{x}})。
|
|
78
|
+
for (let round = 0; round < 3; round += 1) {
|
|
79
|
+
const before = text
|
|
80
|
+
text = text.replace(
|
|
81
|
+
/\\(?:textbf|textit|emph|texttt|textrm|textsf|textsc|textsl|textup|textnormal|underline|mbox|text|mathrm|textsuperscript|textsubscript)\s*\{([^{}]*)\}/g,
|
|
82
|
+
'$1',
|
|
83
|
+
)
|
|
84
|
+
if (text === before) break
|
|
85
|
+
}
|
|
86
|
+
// 引用与交叉引用。
|
|
87
|
+
// 🔴 **不能把引用键当正文**:`\cite{packer2023memgpt}` 原样输出会得到 `[packer2023memgpt]`,
|
|
88
|
+
// 而读者在 PDF 上看到的是 `[24]`。有 bibitem 编号映射时用编号,没有就整条删掉 ——
|
|
89
|
+
// 少一个编号只是少了点信息,留一个键名是把排版垃圾写进正文。
|
|
90
|
+
text = text.replace(/\\(?:cite|citep|citet|citealp|citeauthor|citeyear|parencite|textcite|citealt|citeyearpar|Cite|Parencite)\*?(?:\s*\[[^\]]*\])*\s*\{([^{}]*)\}/g,
|
|
91
|
+
(whole, keys) => citeLabel(keys, options),
|
|
92
|
+
)
|
|
93
|
+
text = text.replace(/\\eqref\s*\{([^{}]*)\}/g, '($1)')
|
|
94
|
+
// 交叉引用同理:`tab:data` 是标签名,读者看到的是 `Table 4`。
|
|
95
|
+
text = text.replace(/\\(?:ref|autoref|cref|Cref|pageref|nameref)\s*\{([^{}]*)\}/g, (whole, key) => refLabel(key, options))
|
|
96
|
+
// 脚注内联展开:内容不丢,位置仍在原句后面。
|
|
97
|
+
text = text.replace(/\\footnote\s*\{([^{}]*)\}/g, ' (注:$1)')
|
|
98
|
+
|
|
99
|
+
// 有确定字面意义的命令先换成字符(必须在「删名留参」之前)。
|
|
100
|
+
for (const [name, glyph] of SYMBOLS) {
|
|
101
|
+
text = text.split(BACKSLASH + name).join(glyph)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// `\\` 是 LaTeX 的强制换行(表格行分隔也是它),读者看到的是空格。必须在删命令名之前处理:
|
|
105
|
+
// 否则两个反斜杠里只会有一个被吃掉,剩下的 `\\` 会和后面的词粘成 `\Ayesha` 这种假命令。
|
|
106
|
+
text = text.replace(/\\\\(?:\s*\[[^\]]*\])?/g, ' ')
|
|
107
|
+
// 兜底:仍然剩下的命令名只删名字,参数里的内容留下。
|
|
108
|
+
text = text.replace(/\\[a-zA-Z@]+\s*/g, '')
|
|
109
|
+
// 非字母的短命令(\, \; \: \! 与反斜杠空格)都是间距,没有正文意义。
|
|
110
|
+
text = text.replace(/\\(?:[,;:!]|\s)/g, '')
|
|
111
|
+
// 参数分组用的花括号不是正文;被转义的字面花括号(\{)要留着,交给下面还原。
|
|
112
|
+
text = text.replace(/(?<![\\])[{}]/g, '')
|
|
113
|
+
|
|
114
|
+
// 转义与排版符号。
|
|
115
|
+
text = text
|
|
116
|
+
// `\\~n` / `\\~{n}` 是重音符,读者看到的是字母本身(要在「不间断空格」之前处理)。
|
|
117
|
+
.replace(/\\~\{?([a-zA-Z])\}?/g, '$1')
|
|
118
|
+
// 🔴 波浪号是 LaTeX 的不间断空格,读者看到的是空格:`Mem0~achieves` 应收成
|
|
119
|
+
// `Mem0 achieves`(实测 Mem0 一篇里有 79 处)。原先只折连续的 `~~~~`,单个 `~` 全部漏网。
|
|
120
|
+
.replace(/~/g, ' ')
|
|
121
|
+
// LaTeX 引号:`` 是左引号、'' 是右引号。
|
|
122
|
+
.replace(/``/g, '\u201c')
|
|
123
|
+
.replace(/''/g, '\u201d')
|
|
124
|
+
.replace(/\\(?:%|&|_|#|\$|\{|\})/g, match => match.slice(1))
|
|
125
|
+
.replace(/~~~~~~~~~~~~~~~~~~~~/g, '~~')
|
|
126
|
+
.replace(/---/g, '—')
|
|
127
|
+
.replace(/--/g, '–')
|
|
128
|
+
.replace(/~~/g, ' ')
|
|
129
|
+
.replace(/\s+/g, ' ')
|
|
130
|
+
// 控制字符一律清掉:切块层用 U+0003 给交叉引用做占位哨兵(见 tex-blocks 的 REF_MARK),
|
|
131
|
+
// 段落那条路会自己剥掉,但标题与表格单元格是直接调 inlineText 的,需要一个统一的兜底。
|
|
132
|
+
// 🔴 必须跳过 U+0001(MATH_SLOT):那是行内公式的占位符,清掉它公式就再也插回不来了。
|
|
133
|
+
.replace(/[\u0000\u0002-\u0008\u000b\u000c\u000e-\u001f]/g, '')
|
|
134
|
+
// 段首孤零零的尺寸(`\hspace*{-1.5pt}` 之类被删后留下的 `-1.5pt`):只清段首,
|
|
135
|
+
// 句中 `≤0.5pt` 是真实读数,一律不动。
|
|
136
|
+
.replace(/^[-+]?\d+(?:\.\d+)?(?:pt|em|ex|bp)\s+/i, '')
|
|
137
|
+
.trim()
|
|
138
|
+
|
|
139
|
+
return text.replace(new RegExp(MATH_SLOT + '([0-9]+)' + MATH_SLOT, 'g'), (whole, index) => slots[Number(index)] ?? whole)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* 引用键 → 读者看到的方括号编号。
|
|
144
|
+
*
|
|
145
|
+
* `options.citeIndex` 是切块层扫 `\\bibitem{key}` 得到的 key → 序号表(从 1 起)。
|
|
146
|
+
* 查不到映射时返回空串:**宁可少一个编号,也不要把键名写进正文** —— 读者在 PDF 上看到的是
|
|
147
|
+
* `[24]`,`[packer2023memgpt]` 是排版垃圾。
|
|
148
|
+
*/
|
|
149
|
+
function citeLabel(keys, options) {
|
|
150
|
+
const table = options?.citeIndex
|
|
151
|
+
if (!(table instanceof Map)) return ''
|
|
152
|
+
const numbers = String(keys)
|
|
153
|
+
.split(',')
|
|
154
|
+
.map(key => table.get(key.trim()))
|
|
155
|
+
.filter(value => Number.isInteger(value))
|
|
156
|
+
if (numbers.length === 0) return ''
|
|
157
|
+
return '[' + numbers.join(', ') + ']'
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** 交叉引用 → 编号;没有编号映射时返回空串(取舍同 {@link citeLabel})。 */
|
|
161
|
+
function refLabel(key, options) {
|
|
162
|
+
const table = options?.labelIndex
|
|
163
|
+
if (!(table instanceof Map)) return ''
|
|
164
|
+
const value = table.get(String(key).trim())
|
|
165
|
+
return typeof value === 'string' ? value : ''
|
|
166
|
+
}
|
package/lib/tex-merge.js
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 合并层:把源码块与 MinerU 块逐块择优,产出一份新的 content_list。
|
|
3
|
+
*
|
|
4
|
+
* 三条规则,都来自实测:
|
|
5
|
+
* - 相似度 ≥ 0.85:两边是同一块,**内容用源码**(源码是作者写的,MinerU 是 OCR 结果);
|
|
6
|
+
* - 0.5 ≤ 相似度 < 0.85:仍用源码,但标 medium —— 交给调用方记进旁挂 JSON,
|
|
7
|
+
* 将来出问题能查;
|
|
8
|
+
* - < 0.5:**保留 MinerU**。这条是「不接受变差」的兜底:配不上就说明我们对不上,
|
|
9
|
+
* 此时换成源码等于拿不确定的内容替换已经能读的内容。
|
|
10
|
+
*
|
|
11
|
+
* 🔴 位置永远来自 PDF:page_idx 与 bbox **一律保留 MinerU 那一份**。源码里没有页码,
|
|
12
|
+
* 对齐层给的是推算值;MinerU 的 page_idx 是上游服务按真实页面给的。
|
|
13
|
+
*
|
|
14
|
+
* 纯函数:无 IO、无时钟。
|
|
15
|
+
*/
|
|
16
|
+
import { plainInlineText } from './inline-html.js'
|
|
17
|
+
import { similarity, tokenize } from './text-similarity.js'
|
|
18
|
+
|
|
19
|
+
/** 高置信阈值:内容直接采用。 */
|
|
20
|
+
const HIGH_SIMILARITY = 0.85
|
|
21
|
+
/** 低置信阈值:低于此值保留 MinerU。 */
|
|
22
|
+
const MEDIUM_SIMILARITY = 0.5
|
|
23
|
+
/** 每块最多往后找多少个 MinerU 块。块序基本一致,200 条足够跨过一张表或一节参考文献。 */
|
|
24
|
+
const MATCH_WINDOW = 220
|
|
25
|
+
/** 只有这三类允许「源码有、MinerU 没有」时插入(有明确的环境边界,插错位置也不会误导读)。 */
|
|
26
|
+
// 图也允许插入:MinerU 把图识别成 chart 或干脆漏掉都有实测,而漏掉的图用户无法恢复;
|
|
27
|
+
// 重复的图看得见、删得掉。
|
|
28
|
+
const INSERTABLE_KINDS = new Set(['math', 'table', 'code', 'figure'])
|
|
29
|
+
/**
|
|
30
|
+
* medium 档(0.5 ≤ 相似度 < 0.85)额外要求的词元长度比区间。
|
|
31
|
+
*
|
|
32
|
+
* 只在 high 档之外加这一道,是因为实测 medium 档里混着两类明确的错误替换:
|
|
33
|
+
* ① MinerU 把相邻两三段并成一个块 —— 「A+B」整块被换成「B」,A 的内容静默消失;
|
|
34
|
+
* ② 根本配错段 —— 实测相似度 0.59 的两段(「Recent advancements in LLMs…」与
|
|
35
|
+
* 「These agents typically employ an LLM…」)被当成同一段替换掉了。
|
|
36
|
+
* 两类都有一个共同的可测特征:两边的词元数差得多(实测 45/74、61/80、113/183)。
|
|
37
|
+
* 同一段的两个版本不会差这么多,所以 medium 档要求长度比落在 [0.8, 1.25]。
|
|
38
|
+
* high 档不加:那时两边已经逐字相近,再卡长度只会误伤公式与引用编号造成的偏差。
|
|
39
|
+
*/
|
|
40
|
+
const MIN_MEDIUM_RATIO = 0.8
|
|
41
|
+
const MAX_MEDIUM_RATIO = 1.25
|
|
42
|
+
|
|
43
|
+
/** 块类型判定:与 blocks.js 的 blockKindOf 同口径,保证两边数的是同一种块。 */
|
|
44
|
+
function kindOf(item) {
|
|
45
|
+
const type = typeof item?.type === 'string' ? item.type : ''
|
|
46
|
+
if (type === 'text') return Number.isInteger(item.text_level) ? 'heading' : 'para'
|
|
47
|
+
if (type === 'equation') return 'math'
|
|
48
|
+
if (type === 'table') return 'table'
|
|
49
|
+
if (type === 'image' || type === 'chart') return 'figure'
|
|
50
|
+
if (type === 'code') return 'code'
|
|
51
|
+
if (type === 'ref_text') return 'references'
|
|
52
|
+
return 'para'
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 数学区的占位词元:两边公式的形态差异很大,让它参与比较只会稀释正文的相似度。 */
|
|
56
|
+
const MATH_TOKEN = ' mathtoken '
|
|
57
|
+
/** 标题编号:`2.1. Mem0` 里的 `2.1.` 是排版产物,作者写的是 `\\section{Mem0}`。 */
|
|
58
|
+
const HEADING_NUMBER = /^\s*(?:\d+(?:\.\d+)*|[A-Z](?:\.\d+)*)\.?\s+/
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 比较用的文本:正文取 text,图表取 caption(与对齐层同口径)。
|
|
62
|
+
*
|
|
63
|
+
* 🔴 **比较前必须折掉 MinerU 写进正文的行内标签。** 块的对齐指纹({@link fingerprintOf})
|
|
64
|
+
* 要留原文,但「两块是不是同一段」问的是读者看到的字:实测 Mem0 的 MinerU 版是
|
|
65
|
+
* `Lar<sub>g</sub>e Lan<sub>g</sub>ua<sub>g</sub>e Models`,源码版是 `Large Language Models`,
|
|
66
|
+
* 词元交集为 0 —— 同一段的两版被判成不相似,全篇相似度中位数只有 0.082、高置信匹配仅 1 块。
|
|
67
|
+
* 折掉标签后中位数 0.500、高置信 45 块。
|
|
68
|
+
*
|
|
69
|
+
* 公式同样归一成一个占位词元:MinerU 的 `$\\left( m _ { t - 1 } , m _ { t } \\right)$` 与源码的
|
|
70
|
+
* `$(m_{t-1}, m_t)$` 词元形态差得远,参与比较会把整段拉到阈值以下。
|
|
71
|
+
*
|
|
72
|
+
* 标题去掉编号再比:源码 `Mem0` 对 MinerU `2.1. Mem0` 的 Jaccard 只有 0.33,够不到 medium。
|
|
73
|
+
*/
|
|
74
|
+
function compareTextOf(item) {
|
|
75
|
+
let raw = ''
|
|
76
|
+
if (typeof item?.text === 'string' && item.text !== '') raw = item.text
|
|
77
|
+
else if (typeof item?.caption === 'string' && item.caption !== '') raw = item.caption
|
|
78
|
+
if (raw === '') return ''
|
|
79
|
+
const kind = kindOf(item)
|
|
80
|
+
let text = plainInlineText(raw)
|
|
81
|
+
// 🔴 **公式块不能做公式归一**:归一之后任何两个公式都只剩同一个占位词元,相似度恒为 1,
|
|
82
|
+
// 于是每一对不同的公式都被判成 high,cursor 一路推进到错误的位置,后面的块全部错位。
|
|
83
|
+
// 正文块归一,公式块按原样比(公式本来就该靠符号决出胜负,见 text-similarity 的注释)。
|
|
84
|
+
if (kind !== 'math') text = text.replace(/\$\$[\s\S]*?\$\$/g, MATH_TOKEN).replace(/\$[^$\n]*\$/g, MATH_TOKEN)
|
|
85
|
+
if (kind === 'heading') text = text.replace(HEADING_NUMBER, '')
|
|
86
|
+
return text
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 对齐指纹用的原文:MinerU 那一份 text(没有就取 caption 拼接)。
|
|
91
|
+
*
|
|
92
|
+
* 必须单独留下来:markdown 里那串字是 MinerU 写的,块的 text 一旦换成源码,
|
|
93
|
+
* 用源码文本去 markdown 里找位置必然找不到 —— 实测一篇论文因此从 352 个块标记
|
|
94
|
+
* 掉到 213 个,牵连划线笔记挂载、大纲的块 id 区间,以及下次重解析保留旧 id 的依据。
|
|
95
|
+
*/
|
|
96
|
+
function fingerprintOf(item) {
|
|
97
|
+
if (typeof item?.text === 'string' && item.text.trim() !== '') return item.text
|
|
98
|
+
for (const key of ['table_caption', 'image_caption', 'chart_caption', 'code_caption']) {
|
|
99
|
+
const value = item?.[key]
|
|
100
|
+
if (!Array.isArray(value)) continue
|
|
101
|
+
const joined = value.filter(entry => typeof entry === 'string' && entry.trim() !== '').map(entry => entry.trim()).join('\n')
|
|
102
|
+
if (joined !== '') return joined
|
|
103
|
+
}
|
|
104
|
+
return ''
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 把源码块的内容字段搬到 MinerU 块上,位置字段不动。 */
|
|
108
|
+
function applyContent(target, source) {
|
|
109
|
+
const next = { ...target }
|
|
110
|
+
const original = fingerprintOf(target)
|
|
111
|
+
if (original !== '') next.mineru_source = original
|
|
112
|
+
if (typeof source.text === 'string' && source.text !== '') next.text = source.text
|
|
113
|
+
if (typeof source.table_body === 'string' && source.table_body !== '') next.table_body = source.table_body
|
|
114
|
+
if (typeof source.img_path === 'string' && source.img_path !== '') next.img_path = source.img_path
|
|
115
|
+
if (typeof source.code_body === 'string' && source.code_body !== '') next.code_body = source.code_body
|
|
116
|
+
return next
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 插入位置:按页码与 y 坐标找第一个「排在它后面」的 MinerU 块。 */
|
|
120
|
+
function insertionIndex(list, item) {
|
|
121
|
+
const page = Number.isInteger(item?.page_idx) ? item.page_idx : 0
|
|
122
|
+
const top = Array.isArray(item?.bbox) ? item.bbox[1] : Number.POSITIVE_INFINITY
|
|
123
|
+
for (let index = 0; index < list.length; index += 1) {
|
|
124
|
+
const other = list[index]
|
|
125
|
+
const otherPage = Number.isInteger(other?.page_idx) ? other.page_idx : 0
|
|
126
|
+
if (otherPage > page) return index
|
|
127
|
+
if (otherPage < page) continue
|
|
128
|
+
const otherTop = Array.isArray(other?.bbox) ? other.bbox[1] : Number.POSITIVE_INFINITY
|
|
129
|
+
if (otherTop > top) return index
|
|
130
|
+
}
|
|
131
|
+
return list.length
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 逐块择优。
|
|
136
|
+
*
|
|
137
|
+
* @param {Array<object>} mineruList MinerU 的原始 content_list
|
|
138
|
+
* @param {Array<object>} texItems 源码块(已过对齐层,带 page_idx/bbox)
|
|
139
|
+
* @param {{high?: number, medium?: number, window?: number}} [options]
|
|
140
|
+
* @returns {{list: Array<object>, stats: {total: number, matched: number, high: number,
|
|
141
|
+
* medium: number, kept: number, inserted: number},
|
|
142
|
+
* applied: Array<{kind: string, confidence: string, similarity: number}>}}
|
|
143
|
+
*/
|
|
144
|
+
|
|
145
|
+
/** 图表/算法的编号:`Table 4`、`Figure 2`、`Algorithm 1`。 */
|
|
146
|
+
const REF_NUMBER = /\b(Table|Figure|Fig\.|Algorithm)\s*(\d+(?:\.\d+)*)/g
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* 块级的交叉引用校验:源码这一段里的编号,与 MinerU 那一份(PDF 上印的)是否完全一致。
|
|
150
|
+
*
|
|
151
|
+
* 篇级自检(tex-pipeline 的 crossRefTrust)只能挡住「整体偏移」的论文;实测还有个别论文
|
|
152
|
+
* 整体差异很小、个别块却偏了(Mem0 的 `Figure 2` 被算成 `Figure 1`)。配对成功之后再做一次
|
|
153
|
+
* 逐块比对,偏了就放弃这一块 —— 方向始终是「宁可保留 MinerU」,不会反过来。
|
|
154
|
+
*
|
|
155
|
+
* 两边任一侧没有编号时判为一致:没有比对依据就不该否定。
|
|
156
|
+
*/
|
|
157
|
+
function refsAgree(sourceText, targetText) {
|
|
158
|
+
const mine = new Map()
|
|
159
|
+
for (const match of String(sourceText ?? '').matchAll(REF_NUMBER)) {
|
|
160
|
+
const kind = match[1] === 'Fig.' ? 'Figure' : match[1]
|
|
161
|
+
if (!mine.has(kind)) mine.set(kind, new Set())
|
|
162
|
+
mine.get(kind).add(match[2])
|
|
163
|
+
}
|
|
164
|
+
if (mine.size === 0) return true
|
|
165
|
+
const truth = new Map()
|
|
166
|
+
for (const match of plainInlineText(String(targetText ?? '')).matchAll(REF_NUMBER)) {
|
|
167
|
+
const kind = match[1] === 'Fig.' ? 'Figure' : match[1]
|
|
168
|
+
if (!truth.has(kind)) truth.set(kind, new Set())
|
|
169
|
+
truth.get(kind).add(match[2])
|
|
170
|
+
}
|
|
171
|
+
if (truth.size === 0) return true
|
|
172
|
+
for (const [kind, set] of mine) {
|
|
173
|
+
const other = truth.get(kind)
|
|
174
|
+
if (other === undefined) return false
|
|
175
|
+
if (set.size !== other.size) return false
|
|
176
|
+
for (const value of set) if (!other.has(value)) return false
|
|
177
|
+
}
|
|
178
|
+
return true
|
|
179
|
+
}
|
|
180
|
+
export function mergeContentList(mineruList, texItems, options = {}) {
|
|
181
|
+
const base = Array.isArray(mineruList) ? mineruList : []
|
|
182
|
+
const source = Array.isArray(texItems) ? texItems : []
|
|
183
|
+
const high = Number.isFinite(options.high) ? options.high : HIGH_SIMILARITY
|
|
184
|
+
const medium = Number.isFinite(options.medium) ? options.medium : MEDIUM_SIMILARITY
|
|
185
|
+
const window = Number.isFinite(options.window) ? options.window : MATCH_WINDOW
|
|
186
|
+
|
|
187
|
+
const list = base.map(item => ({ ...item }))
|
|
188
|
+
const stats = { total: list.length, matched: 0, high: 0, medium: 0, kept: 0, inserted: 0, granularity: 0, unresolved: 0 }
|
|
189
|
+
const applied = []
|
|
190
|
+
const consumed = new Set()
|
|
191
|
+
let cursor = 0
|
|
192
|
+
const pending = []
|
|
193
|
+
|
|
194
|
+
for (const item of source) {
|
|
195
|
+
// 切块层标了 unresolved 的块(引用编号无从得知,见 tex-blocks 的 CITE_CALL):
|
|
196
|
+
// 采用它就等于把原文里的 `[24]` 丢掉,宁可保留 MinerU 那一份。
|
|
197
|
+
if (item?.unresolved !== undefined) {
|
|
198
|
+
stats.kept += 1
|
|
199
|
+
stats.unresolved += 1
|
|
200
|
+
continue
|
|
201
|
+
}
|
|
202
|
+
// 交叉引用编号与 PDF 对不上(或压根算不出来)时,带引用的段落同样退回 MinerU。
|
|
203
|
+
if (item?.codeRef === true && options.refTrust === false) {
|
|
204
|
+
stats.kept += 1
|
|
205
|
+
stats.unresolved += 1
|
|
206
|
+
continue
|
|
207
|
+
}
|
|
208
|
+
const kind = kindOf(item)
|
|
209
|
+
const needle = new Set(tokenize(compareTextOf(item)))
|
|
210
|
+
if (needle.size === 0) {
|
|
211
|
+
// 没有可比文本的块(图就是这种)不参与匹配,但可插入的类型仍要进队列 ——
|
|
212
|
+
// 直接跳过会让源码侧好不容易转出来的图白丢。
|
|
213
|
+
if (INSERTABLE_KINDS.has(kind)) pending.push(item)
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
const limit = Math.min(list.length, cursor + window)
|
|
217
|
+
let best = null
|
|
218
|
+
for (let index = cursor; index < limit; index += 1) {
|
|
219
|
+
if (consumed.has(index)) continue
|
|
220
|
+
if (kindOf(list[index]) !== kind) continue
|
|
221
|
+
const score = similarity(needle, new Set(tokenize(compareTextOf(list[index]))))
|
|
222
|
+
if (best === null || score > best.score) best = { index, score }
|
|
223
|
+
}
|
|
224
|
+
if (best === null || best.score < medium) {
|
|
225
|
+
// 配不上:源码这一块不采用。可插入的类型先排队,等全部匹配完再定位置。
|
|
226
|
+
if (INSERTABLE_KINDS.has(kind)) pending.push(item)
|
|
227
|
+
stats.kept += 1
|
|
228
|
+
continue
|
|
229
|
+
}
|
|
230
|
+
// medium 档再加一道长度比(见 MIN_MEDIUM_RATIO):相似度够不代表两边说的是同一段。
|
|
231
|
+
const sourceTokens = needle.size
|
|
232
|
+
const targetTokens = new Set(tokenize(compareTextOf(list[best.index]))).size
|
|
233
|
+
const confidence = best.score >= high ? 'high' : 'medium'
|
|
234
|
+
if (confidence === 'medium' && targetTokens > 0) {
|
|
235
|
+
const ratio = sourceTokens / targetTokens
|
|
236
|
+
if (ratio < MIN_MEDIUM_RATIO || ratio > MAX_MEDIUM_RATIO) {
|
|
237
|
+
if (INSERTABLE_KINDS.has(kind)) pending.push(item)
|
|
238
|
+
stats.kept += 1
|
|
239
|
+
stats.granularity += 1
|
|
240
|
+
continue
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
// 块级交叉引用校验:编号对不上就保留 MinerU 那一份(那边有 PDF 上印的编号)。
|
|
244
|
+
if (item?.codeRef === true && options.refTrust !== false && !refsAgree(item.text, list[best.index]?.text)) {
|
|
245
|
+
if (INSERTABLE_KINDS.has(kind)) pending.push(item)
|
|
246
|
+
stats.kept += 1
|
|
247
|
+
stats.unresolved += 1
|
|
248
|
+
continue
|
|
249
|
+
}
|
|
250
|
+
consumed.add(best.index)
|
|
251
|
+
cursor = best.index
|
|
252
|
+
list[best.index] = applyContent(list[best.index], item)
|
|
253
|
+
stats.matched += 1
|
|
254
|
+
if (confidence === 'high') stats.high += 1
|
|
255
|
+
else stats.medium += 1
|
|
256
|
+
applied.push({ kind, confidence, similarity: Number(best.score.toFixed(4)) })
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// 源码独有的公式/表格/代码:按页码与纵坐标插进列表,插完立刻重算,保持顺序稳定。
|
|
260
|
+
for (const item of pending) {
|
|
261
|
+
const at = insertionIndex(list, item)
|
|
262
|
+
// 🔴 打上 inserted:源码独有的块在 Markdown 里**没有对应文字**(那串字是 MinerU 从没写过
|
|
263
|
+
// 的内容),拿它的正文去定位只会误配 —— 实测一个插入表格的 caption 落在 Markdown 靠后
|
|
264
|
+
// 的位置,把单调游标推过 99 个本该配上的块,整节正文的块标记全丢。
|
|
265
|
+
const inserted = { ...item, inserted: true }
|
|
266
|
+
// 位置来自对齐层;对齐层没给就用插入点前一块的位置,至少页码不跳。
|
|
267
|
+
if (!Number.isInteger(inserted.page_idx)) {
|
|
268
|
+
inserted.page_idx = Number.isInteger(list[at - 1]?.page_idx) ? list[at - 1].page_idx : 0
|
|
269
|
+
}
|
|
270
|
+
list.splice(at, 0, inserted)
|
|
271
|
+
stats.inserted += 1
|
|
272
|
+
stats.total += 1
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
return { list, stats, applied }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** 导出阈值,供测试与调参引用。 */
|
|
279
|
+
export const MERGE_LIMITS = { HIGH_SIMILARITY, MEDIUM_SIMILARITY, MATCH_WINDOW }
|