@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.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
@@ -0,0 +1,653 @@
1
+ /**
2
+ * 切块层:把展开后的 LaTeX 正文切成**与 MinerU content_list 同构**的块数组。
3
+ *
4
+ * 同构是这一层唯一的硬约束。上游 splitBlocks 只认这几样东西:
5
+ * type(text / equation / table / image / chart / code / ref_text)
6
+ * text + text_level(text_level 是整数就是标题)
7
+ * table_body / img_path / caption 类字段
8
+ * 产出与它对齐之后,切块、对齐、翻译、搜索、导出全都不用改一行。
9
+ *
10
+ * 第 1 批只产三类块:**标题、段落、公式**。表格、图、代码、参考文献先识别并跳过(计入
11
+ * stats.skipped),让 MinerU 那份原样留下 —— 这一层少产一块,合并时那一块就还是 MinerU 的,
12
+ * 不会变差;而把表格内容当正文吐出去才是真变差。
13
+ *
14
+ * 纯函数:无 IO、无时钟、无随机数。
15
+ */
16
+ import { readCommandName, readGroup, readOptional, skipSpaces } from './tex-prepare.js'
17
+
18
+ const BACKSLASH = '\\'
19
+
20
+ /** 块级公式环境。math 是行内环境(\begin{math}),不产块。 */
21
+ const MATH_ENVIRONMENTS = new Set([
22
+ 'equation', 'equation*', 'align', 'align*', 'gather', 'gather*', 'multline', 'multline*',
23
+ 'eqnarray', 'eqnarray*', 'displaymath', 'flalign', 'flalign*',
24
+ ])
25
+
26
+ /**
27
+ * 整块跳过的环境。
28
+ *
29
+ * 跳过的判据不是「难解析」而是「这层产不出比 MinerU 更好的东西」:表格的 HTML、图的位图、
30
+ * 参考文献的条目在后续批次里单独做,第 1 批先让 MinerU 那份留着。
31
+ */
32
+ const SKIP_ENVIRONMENTS = new Set([
33
+ 'verbatim', 'verbatim*', 'lstlisting', 'minted', 'alltt', 'comment',
34
+ 'algorithm', 'algorithm*', 'algorithm2e', 'algorithmic', 'tikzpicture',
35
+ 'subfigure', 'subtable', 'filecontents', 'filecontents*',
36
+ ])
37
+
38
+ /** 图容器:这一层只把 includegraphics 找出来,落盘与转码在 tex-figures 里做。 */
39
+ const FIGURE_CONTAINERS = new Set(['figure', 'figure*', 'wrapfigure', 'sidewaysfigure'])
40
+
41
+ /** 表格外层容器:caption 在这里,表格本体在里面的 tabular。 */
42
+ const TABLE_CONTAINERS = new Set(['table', 'table*', 'wraptable', 'sidewaystable'])
43
+
44
+ /** 表格本体:拿到它就能转 HTML。 */
45
+ const TABULAR_ENVIRONMENTS = new Set(['tabular', 'tabular*', 'tabularx', 'longtable'])
46
+
47
+ /** 列表环境:内容照常产出,但每个 \item 起一个新段落。 */
48
+ /** 参考文献环境:逐条 \bibitem 产 ref_text 块(与 MinerU 的参考文献块同构)。 */
49
+ const REFERENCE_ENVIRONMENTS = new Set(['thebibliography'])
50
+
51
+ const LIST_ENVIRONMENTS = new Set(['itemize', 'enumerate', 'description'])
52
+
53
+ /**
54
+ * 标题命令 → 块层级。
55
+ *
56
+ * 只给两级:块模型与渲染层都只有两级(实测 MinerU 也只产 1 级 91 个、2 级 2713 个)。
57
+ * paragraph / subparagraph 记 0:它们是**段首粗体小标题**,单独立块会切碎正文,所以并进段首。
58
+ */
59
+ const HEADING_LEVELS = { section: 1, subsection: 2, subsubsection: 2, paragraph: 0, subparagraph: 0 }
60
+
61
+ /** 透明容器里要跳过几个必选参数(\begin{minipage}{0.5\textwidth} 的宽度不能进正文)。 */
62
+ const TRANSPARENT_ARGUMENTS = { minipage: 1, multicols: 1, array: 1 }
63
+
64
+ /** 去掉环境名的星号后缀,用来做分类。 */
65
+ function baseEnvironment(env) {
66
+ return env.replace(/\*$/, '')
67
+ }
68
+
69
+ /**
70
+ * 读 \begin{env} 或 \end{env},返回环境名与结束位置。
71
+ *
72
+ * 用 indexOf + 手工解析而不是先把环境名拼进正则:环境名来自文档,拼正则要转义,
73
+ * 漏一处就是一个可被源码控制的注入点。
74
+ */
75
+ function readEnvironmentAt(text, at) {
76
+ const command = readCommandName(text, at)
77
+ if (command === null) return null
78
+ if (command.name !== 'begin' && command.name !== 'end') return null
79
+ const group = readGroup(text, skipSpaces(text, command.end))
80
+ if (group === null) return null
81
+ return { kind: command.name, env: group.content.trim(), end: group.end }
82
+ }
83
+
84
+ /**
85
+ * 找与 \begin{env} 配对的 \end{env}。
86
+ *
87
+ * 必须做深度计数而不是找第一个 \end:table 里嵌 tabular、figure 里嵌 subfigure 都会出现
88
+ * 结束标记,按第一个截断会把后面的正文一起吞掉。
89
+ */
90
+ function findEnvironmentEnd(text, from, env) {
91
+ let depth = 1
92
+ let cursor = from
93
+ while (cursor < text.length) {
94
+ const nextBegin = text.indexOf(BACKSLASH + 'begin', cursor)
95
+ const nextEnd = text.indexOf(BACKSLASH + 'end', cursor)
96
+ if (nextEnd === -1) return null
97
+ if (nextBegin !== -1 && nextBegin < nextEnd) {
98
+ const found = readEnvironmentAt(text, nextBegin)
99
+ if (found !== null && found.env === env) depth += 1
100
+ cursor = nextBegin + 6
101
+ continue
102
+ }
103
+ const found = readEnvironmentAt(text, nextEnd)
104
+ if (found !== null && found.env === env) {
105
+ depth -= 1
106
+ if (depth === 0) return { bodyEnd: nextEnd, end: found.end }
107
+ }
108
+ cursor = nextEnd + 4
109
+ }
110
+ return null
111
+ }
112
+
113
+ // 行内清理住在 tex-inline.js:切块层与表格层都要用它,放在本文件会形成循环依赖。
114
+ import { inlineText } from './tex-inline.js'
115
+ import { tabularToHtml } from './tex-tables.js'
116
+ import { figureOf } from './tex-figures.js'
117
+
118
+ export { inlineText }
119
+
120
+ /** 公式体规范化:去掉编号标记与 label,把多行环境换成 KaTeX 认的形态。 */
121
+ function normalizeMath(env, body) {
122
+ const base = baseEnvironment(env)
123
+ let tex = body
124
+ .replace(/\\(?:label)\s*\{[^{}]*\}/g, '')
125
+ .replace(/\\(?:nonumber|notag)\s*/g, '')
126
+ .replace(/\s+/g, ' ')
127
+ .trim()
128
+ if (base === 'align' || base === 'align*' || base === 'flalign' || base === 'flalign*' || base === 'eqnarray' || base === 'eqnarray*') {
129
+ tex = BACKSLASH + 'begin{aligned} ' + tex + ' ' + BACKSLASH + 'end{aligned}'
130
+ } else if (base === 'gather' || base === 'gather*' || base === 'multline' || base === 'multline*') {
131
+ tex = BACKSLASH + 'begin{gathered} ' + tex + ' ' + BACKSLASH + 'end{gathered}'
132
+ }
133
+ return tex
134
+ }
135
+
136
+ /**
137
+ * LaTeX 正文 → 块数组。
138
+ *
139
+ * @param {unknown} text 展开后的正文(prepareDocument 的 body)
140
+ * @returns {{items: Array<object>, stats: {paragraphs: number, headings: number, equations: number,
141
+ * lists: number, skipped: Record<string, number>}}}
142
+ * items 与 MinerU content_list 同构;page_idx / bbox 留给对齐层填。
143
+ */
144
+ /**
145
+ * 拆 thebibliography 里的条目。
146
+ *
147
+ * 每条从 \bibitem 开始、到下一条或环境结束为止。编号优先用可选的方括号标签
148
+ * (\bibitem[Vaswani et al.(2017)]{...} 这种写法在 ACL 模板里很常见),没有就按顺序编号,
149
+ * 与 PDF 上看到的 [1] 对齐。
150
+ */
151
+ function parseBibliography(body) {
152
+ const pattern = /\\bibitem\s*(?:\[([^\]]*)\])?\s*\{([^}]*)\}/g
153
+ const matches = [...body.matchAll(pattern)]
154
+ const entries = []
155
+ for (let index = 0; index < matches.length; index += 1) {
156
+ const start = matches[index].index + matches[index][0].length
157
+ const end = index + 1 < matches.length ? matches[index + 1].index : body.length
158
+ const raw = body.slice(start, end).replace(/\\newblock\s*/g, ' ')
159
+ const content = inlineText(raw)
160
+ if (content === '') continue
161
+ const label = matches[index][1]
162
+ const prefix = label === undefined ? '[' + (index + 1) + '] ' : '[' + inlineText(label) + '] '
163
+ entries.push(prefix + content)
164
+ }
165
+ return entries
166
+ }
167
+
168
+ /** 从表格容器里取 caption(可能是 \caption[short]{long})。 */
169
+ function captionOf(text) {
170
+ const at = text.indexOf(BACKSLASH + 'caption')
171
+ if (at === -1) return ''
172
+ let cursor = skipSpaces(text, at + 'caption'.length + 1)
173
+ const short = readOptional(text, cursor)
174
+ if (short !== null) cursor = skipSpaces(text, short.end)
175
+ const group = readGroup(text, cursor)
176
+ return group === null ? '' : inlineText(group.content)
177
+ }
178
+
179
+ /** 找容器里的第一个表格环境,返回列格式与本体。 */
180
+ function firstTabular(text) {
181
+ const pattern = /\\begin\s*\{(tabular\*?|tabularx|array)\}/g
182
+ const match = pattern.exec(text)
183
+ if (match === null) return null
184
+ const env = match[1]
185
+ const afterBegin = match.index + match[0].length
186
+ const spec = readGroup(text, skipSpaces(text, afterBegin))
187
+ const bodyStart = spec === null ? afterBegin : spec.end
188
+ const found = findEnvironmentEnd(text, bodyStart, env)
189
+ if (found === null) return null
190
+ return { env, columnSpec: spec === null ? '' : spec.content, body: text.slice(bodyStart, found.bodyEnd) }
191
+ }
192
+
193
+ /**
194
+ * 把 `\\cite{key}` 换成读者在 PDF 上看到的编号。
195
+ *
196
+ * 编号来自 thebibliography 里 `\\bibitem` 的**出现顺序**:LaTeX 在不被 bst 重排时就是这个顺序,
197
+ * 与 PDF 上的 `[1] [2]` 一致。ACL/EMNLP 模板常用的 `\\bibitem[Vaswani et al.(2017)]{key}` 带方括号
198
+ * 标签,那就照抄标签 —— 那种模板 PDF 上印的本来就是作者年份。
199
+ *
200
+ * 🔴 查不到的键**整条删掉**。留键名(`[packer2023memgpt]`)是明确的垃圾:读者在 PDF 上看到的
201
+ * 从来不是这个字符串。少一个编号只是少了点信息,把排版内部标识写进正文是另一回事。
202
+ *
203
+ * 纯函数、幂等:替换后的 `[1]` 不含 `\\cite`,再跑一次不会再变。
204
+ */
205
+ function linkCitations(body) {
206
+ const pattern = /\\bibitem\s*(?:\[([^\]]*)\])?\s*\{([^}]*)\}/g
207
+ const table = new Map()
208
+ let counter = 0
209
+ for (const match of body.matchAll(pattern)) {
210
+ counter += 1
211
+ const key = String(match[2]).trim()
212
+ if (key === '' || table.has(key)) continue
213
+ const label = match[1] === undefined ? String(counter) : String(match[1]).trim()
214
+ table.set(key, '[' + label + ']')
215
+ }
216
+ if (table.size === 0) return { body, resolved: false }
217
+ return { body: body.replace(
218
+ /\\(?:cite|citep|citet|citealp|citeauthor|citeyear|parencite|textcite|citealt|Cite|Parencite)\*?(?:\s*\[[^\]]*\])*\s*\{([^{}]*)\}/g,
219
+ (whole, keys) => {
220
+ const parts = String(keys)
221
+ .split(',')
222
+ .map((key) => table.get(key.trim()))
223
+ .filter((value) => value !== undefined)
224
+ if (parts.length === 0) return ''
225
+ if (parts.every((value) => /^\[\d+\]$/.test(value))) {
226
+ return '[' + parts.map((value) => value.slice(1, -1)).join(', ') + ']'
227
+ }
228
+ return parts.join('; ')
229
+ },
230
+ ), resolved: true }
231
+ }
232
+ /**
233
+ * 行间公式的合理性判据。
234
+ *
235
+ * 🔴 实测必要性(PRISM):正文里的 `2$K` 与相邻的行内公式拼出了一个假的 `$$`,于是 `$$`
236
+ * 一直配到一万七千多字符之后,整段正文被切成一个 equation 块 —— 阅读器拿 KaTeX 渲染它必然崩,
237
+ * 模型也会把这一大坨当公式读。两道判据都是「这段像不像公式」的最弱要求:
238
+ * - 长度上限:真公式不会有三万字;
239
+ * - 环境白名单:`\\begin{wrapfigure}` / `\\begin{figure}` 出现在「公式」里,说明配错了对。
240
+ */
241
+ const MAX_DISPLAY_MATH = 3000
242
+ const MATH_INNER_ENVIRONMENTS = new Set([
243
+ 'matrix', 'pmatrix', 'bmatrix', 'Bmatrix', 'vmatrix', 'Vmatrix', 'smallmatrix', 'array', 'subarray',
244
+ 'aligned', 'align', 'align*', 'alignedat', 'cases', 'split', 'gathered', 'gather', 'gather*',
245
+ 'equation', 'equation*', 'eqnarray', 'eqnarray*', 'multline', 'multline*', 'displaymath', 'flalign', 'flalign*',
246
+ ])
247
+ /**
248
+ * 段落里的引用调用。源码包没给 `.bbl` 时(全库 49/58 篇如此),编号无从得知 ——
249
+ * 这时这一段**整块不采用源码**,见下面 `unresolved` 的说明。
250
+ */
251
+ /**
252
+ * 交叉引用的占位哨兵(U+0003,正文里不会出现的控制字符)。
253
+ *
254
+ * 编号算出来之后还要知道「这一段原本有没有交叉引用」—— 合并层要靠它决定这一段用不用源码,
255
+ * 而替换成纯文本之后这个信息就没了。所以把编号包在哨兵里,切块时剥掉哨兵、记下有没有。
256
+ */
257
+ const REF_MARK = String.fromCharCode(3)
258
+
259
+ const CITE_CALL = /\\(?:cite|citep|citet|citealp|citeauthor|citeyear|parencite|textcite|citealt|Cite|Parencite)\b/
260
+
261
+ /** 只出现在正文里的命令:它们出现在「公式」里就说明 `$$` 配错了对。 */
262
+ const PROSE_COMMANDS = /\\(?:cite|citep|citet|citealp|citeauthor|citeyear|parencite|textcite|ref|autoref|cref|Cref|eqref|footnote|paragraph|section|subsection|subsubsection|caption|item)\b/
263
+ function plausibleDisplayMath(tex) {
264
+ if (tex.length > MAX_DISPLAY_MATH) return false
265
+ // 正文命令出现在公式里,说明 `$$` 配错了对(实测:一段带 `\citep{…}` 的正文被吞成公式块,
266
+ // 而公式内容不经过行内清理,于是引用键 `[auer2002finite,…]` 原样留在了模型读到的正文里)。
267
+ if (PROSE_COMMANDS.test(tex)) return false
268
+ for (const match of tex.matchAll(/\\(?:begin|end)\s*\{([^{}]*)\}/g)) {
269
+ if (!MATH_INNER_ENVIRONMENTS.has(String(match[1]).trim())) return false
270
+ }
271
+ return true
272
+ }
273
+ /** `\appendix` 之后的章节编号用字母(A、B…),与 LaTeX 一致。 */
274
+ function letterOf(value) {
275
+ let rest = value
276
+ let text = ''
277
+ do {
278
+ text = String.fromCharCode(65 + ((rest - 1) % 26)) + text
279
+ rest = Math.floor((rest - 1) / 26)
280
+ } while (rest > 0)
281
+ return text
282
+ }
283
+
284
+ /**
285
+ * 扫一遍正文,建「`\label` 名 → 读者看到的编号」表。
286
+ *
287
+ * 为什么值得认真算:读者在 PDF 上看到的是 `Table 4`、`Figure 2`、`(7)`、`3.2`,而 `\ref{tab:data}`
288
+ * 里的 `tab:data` 是排版内部标识。删掉它,句子就变成「as shown in Table」—— 比垃圾好,但信息是净损失
289
+ * (全库 2602 处 `\ref`)。编号是确定的,算得出来就该算。
290
+ *
291
+ * 规则照 LaTeX:
292
+ * - `\section` / `\subsection` / `\subsubsection` 分三级,编号 `1` / `1.1` / `1.1.1`,`\appendix` 之后用字母;
293
+ * - `\caption` 在 figure 里递增图号、在 table 里递增表号(LaTeX 也是在 caption 处 `\refstepcounter`);
294
+ * - `equation` 环境各占一个编号。
295
+ *
296
+ * 🔴 两处**故意不给编号**,因为猜错比留空更糟:
297
+ * - `align` / `gather` / `multline` / `eqnarray` 每一行都占一个编号,而编号行与 `\nonumber` 行交错,
298
+ * 在本层没有可靠依据区分;
299
+ * - 图/表里 `\caption` 之前写的 `\label`(LaTeX 允许)等 caption 出来再绑;整个环境都没有 caption 就放弃。
300
+ */
301
+ function buildLabelIndex(body) {
302
+ const events = []
303
+ const collect = (pattern, kindOf) => {
304
+ for (const match of body.matchAll(pattern)) {
305
+ const kind = kindOf(match)
306
+ if (kind === '') continue
307
+ events.push({ index: match.index, kind, key: String(match[1] ?? '').trim() })
308
+ }
309
+ }
310
+ collect(/\\(section|subsection|subsubsection)(\*?)/g, (match) => (match[2] === '*' ? '' : 'sec:' + match[1]))
311
+ collect(/\\(begin|end)\s*\{(figure|table|algorithm|equation|align|gather|multline|eqnarray)\*?\}/g, (match) => match[1] + ':' + match[2])
312
+ collect(/\\caption\b/g, () => 'caption')
313
+ collect(/\\label\s*\{([^{}]*)\}/g, (match) => 'label:' + String(match[1]).trim())
314
+ collect(/\\appendix\b/g, () => 'appendix')
315
+ events.sort((left, right) => left.index - right.index)
316
+
317
+ const index = new Map()
318
+ let sec = 0
319
+ let sub = 0
320
+ let subsub = 0
321
+ let fig = 0
322
+ let tab = 0
323
+ let alg = 0
324
+ let eq = 0
325
+ let appendix = false
326
+ const stack = []
327
+ let current = null
328
+ /** 最近的图/表/算法容器:`\caption` 可能写在更深一层的环境里(如 algorithmic 内)。 */
329
+ const containerOf = () => {
330
+ for (let at = stack.length - 1; at >= 0; at -= 1) {
331
+ const env = stack[at].env
332
+ if (env === 'figure' || env === 'table' || env === 'algorithm') return stack[at]
333
+ }
334
+ return undefined
335
+ }
336
+ const bind = (key) => { if (key !== '' && current !== null && !index.has(key)) index.set(key, current) }
337
+
338
+ for (const event of events) {
339
+ const kind = event.kind
340
+ if (kind === 'appendix') { appendix = true; continue }
341
+ if (kind.startsWith('sec:')) {
342
+ const level = kind.slice(4)
343
+ if (level === 'section') { sec += 1; sub = 0; subsub = 0 }
344
+ else if (level === 'subsection') { sub += 1; subsub = 0 }
345
+ else { subsub += 1 }
346
+ const parts = [appendix ? letterOf(sec) : String(sec)]
347
+ if (sub > 0) parts.push(String(sub))
348
+ if (subsub > 0) parts.push(String(subsub))
349
+ current = { text: parts.join('.'), type: 'Section' }
350
+ continue
351
+ }
352
+ if (kind.startsWith('begin:')) {
353
+ const env = kind.slice(6)
354
+ stack.push({ env, captioned: false })
355
+ if (env === 'equation') { eq += 1; current = { text: String(eq), type: 'Equation' } }
356
+ else if (env === 'align' || env === 'gather' || env === 'multline' || env === 'eqnarray') current = null
357
+ continue
358
+ }
359
+ if (kind.startsWith('end:')) {
360
+ if (stack.length > 0) stack.pop()
361
+ continue
362
+ }
363
+ if (kind === 'caption') {
364
+ const top = containerOf()
365
+ if (top === undefined) continue
366
+ if (top.env === 'figure') { fig += 1; current = { text: String(fig), type: 'Figure' } }
367
+ else if (top.env === 'algorithm') { alg += 1; current = { text: String(alg), type: 'Algorithm' } }
368
+ else { tab += 1; current = { text: String(tab), type: 'Table' } }
369
+ top.captioned = true
370
+ // caption 之前就写下的 label,现在才拿得到编号。
371
+ for (const key of Array.isArray(top.pending) ? top.pending : []) bind(key)
372
+ top.pending = []
373
+ continue
374
+ }
375
+ if (kind.startsWith('label:')) {
376
+ const key = kind.slice(6)
377
+ const top = containerOf()
378
+ if (top !== undefined && !top.captioned) {
379
+ // caption 还没出现:这个 label 属于本环境即将产生的编号,等 caption 出来再绑。
380
+ if (top.pending === undefined) top.pending = []
381
+ top.pending.push(key)
382
+ continue
383
+ }
384
+ bind(key)
385
+ continue
386
+ }
387
+ }
388
+ return index
389
+ }
390
+
391
+ /**
392
+ * 把 `\ref` / `\autoref` / `\eqref` 换成编号。算不出来就留空,绝不输出标签名。
393
+ */
394
+ function linkLabels(body) {
395
+ if (body.indexOf(BACKSLASH + 'label') === -1) return { body, resolved: false }
396
+ const index = buildLabelIndex(body)
397
+ if (index.size === 0) return { body, resolved: false }
398
+ const replaced = body.replace(/\\eqref\s*\{([^{}]*)\}/g, (whole, key) => {
399
+ const entry = index.get(String(key).trim())
400
+ return entry === undefined ? '' : '(' + entry.text + ')'
401
+ })
402
+ const linked = replaced.replace(/\\(?:ref|autoref|cref|Cref|pageref|nameref)\s*\{([^{}]*)\}/g, (whole, key) => {
403
+ const entry = index.get(String(key).trim())
404
+ const withType = whole.indexOf('autoref') !== -1 || whole.indexOf('cref') !== -1 || whole.indexOf('Cref') !== -1
405
+ const text = entry === undefined ? '' : (withType ? entry.type + ' ' + entry.text : entry.text)
406
+ return REF_MARK + text + REF_MARK
407
+ })
408
+ return { body: linked, resolved: true }
409
+ }
410
+
411
+ export function blocksOfDocument(text, { depth = 0 } = {}) {
412
+ const citation = typeof text === 'string' ? linkCitations(text) : { body: '', resolved: true }
413
+ const labels = linkLabels(citation.body)
414
+ const source = labels.body
415
+ const items = []
416
+ const stats = { paragraphs: 0, headings: 0, equations: 0, lists: 0, references: 0, tables: 0, figures: 0, skipped: {} }
417
+ // 图块不直接进 items:它的 img_path 要等资源落盘后才有效,所以先攒着,交给 pipeline。
418
+ const figures = []
419
+ let buffer = ''
420
+ // 列表项的缩进前缀不能写进 buffer:inlineText 会 trim,前导空格会被吃掉。
421
+ let pendingPrefix = ''
422
+ let index = 0
423
+
424
+ const flush = () => {
425
+ // 🔴 没有 bibitem 表时,这一段里的引用编号无从得知。删掉标记是「信息净损失」
426
+ // (原文 `as shown in [24]` 会变成 `as shown in`),所以整块标成 unresolved,
427
+ // 交给合并层放弃采用源码、保留 MinerU 那一份(那边已经有编号)。
428
+ const unresolved = citation.resolved === false && CITE_CALL.test(buffer)
429
+ const hasRef = buffer.indexOf(REF_MARK) !== -1
430
+ const value = inlineText(buffer.split(REF_MARK).join(''))
431
+ const prefix = pendingPrefix
432
+ buffer = ''
433
+ pendingPrefix = ''
434
+ if (value === '') return
435
+ const item = { type: 'text', text: prefix + value }
436
+ if (unresolved) item.unresolved = 'cite'
437
+ else if (hasRef) item.codeRef = labels.resolved
438
+ items.push(item)
439
+ stats.paragraphs += 1
440
+ }
441
+
442
+ const countSkip = env => {
443
+ stats.skipped[env] = (stats.skipped[env] ?? 0) + 1
444
+ }
445
+
446
+ while (index < source.length) {
447
+ const char = source[index]
448
+
449
+ if (char === BACKSLASH) {
450
+ const command = readCommandName(source, index)
451
+ if (command === null) { buffer += char; index += 1; continue }
452
+
453
+ if (command.name === 'begin') {
454
+ const group = readGroup(source, skipSpaces(source, command.end))
455
+ if (group === null) { buffer += source.slice(index, command.end); index = command.end; continue }
456
+ const env = group.content.trim()
457
+ const base = baseEnvironment(env)
458
+ const found = findEnvironmentEnd(source, group.end, env)
459
+ const bodyEnd = found === null ? source.length : found.bodyEnd
460
+ const after = found === null ? source.length : found.end
461
+ const body = source.slice(group.end, bodyEnd)
462
+
463
+ if (MATH_ENVIRONMENTS.has(base)) {
464
+ flush()
465
+ const tex = normalizeMath(env, body)
466
+ if (tex !== '') {
467
+ items.push({ type: 'equation', text: '$$\n' + tex + '\n$$' })
468
+ stats.equations += 1
469
+ }
470
+ index = after
471
+ continue
472
+ }
473
+ if (SKIP_ENVIRONMENTS.has(base)) {
474
+ flush()
475
+ countSkip(base)
476
+ index = after
477
+ continue
478
+ }
479
+ if (FIGURE_CONTAINERS.has(base)) {
480
+ flush()
481
+ const figure = figureOf(body)
482
+ if (figure === null) { countSkip(base); index = after; continue }
483
+ figures.push({ ...figure, afterIndex: items.length })
484
+ stats.figures += 1
485
+ index = after
486
+ continue
487
+ }
488
+ if (TABLE_CONTAINERS.has(base)) {
489
+ flush()
490
+ const caption = captionOf(body)
491
+ const tabular = firstTabular(body)
492
+ if (tabular === null) { countSkip('table'); index = after; continue }
493
+ const converted = tabularToHtml(tabular.body, { columnSpec: tabular.columnSpec })
494
+ if (converted.html === '') { countSkip('table'); index = after; continue }
495
+ const table = {
496
+ type: 'table',
497
+ table_body: converted.html,
498
+ ...(caption === '' ? {} : { table_caption: [caption] }),
499
+ }
500
+ // 单元格里的引用同样无从编号:整块标 unresolved,交给合并层保留 MinerU。
501
+ if (citation.resolved === false && CITE_CALL.test(body)) table.unresolved = 'cite'
502
+ items.push(table)
503
+ stats.tables += 1
504
+ index = after
505
+ continue
506
+ }
507
+ if (TABULAR_ENVIRONMENTS.has(base)) {
508
+ flush()
509
+ const spec = readGroup(source, skipSpaces(source, group.end))
510
+ const bodyStart = spec === null ? group.end : spec.end
511
+ const converted = tabularToHtml(source.slice(bodyStart, bodyEnd), {
512
+ columnSpec: spec === null ? '' : spec.content,
513
+ })
514
+ if (converted.html === '') { countSkip(base); index = after; continue }
515
+ const bare = { type: 'table', table_body: converted.html }
516
+ if (citation.resolved === false && CITE_CALL.test(source.slice(bodyStart, bodyEnd))) bare.unresolved = 'cite'
517
+ items.push(bare)
518
+ stats.tables += 1
519
+ index = after
520
+ continue
521
+ }
522
+ if (REFERENCE_ENVIRONMENTS.has(base)) {
523
+ flush()
524
+ for (const entry of parseBibliography(body)) {
525
+ items.push({ type: 'ref_text', text: entry })
526
+ stats.references += 1
527
+ }
528
+ index = after
529
+ continue
530
+ }
531
+ if (LIST_ENVIRONMENTS.has(base)) {
532
+ flush()
533
+ stats.lists += 1
534
+ const inner = blocksOfDocument(body, { depth: depth + 1 })
535
+ for (const item of inner.items) items.push(item)
536
+ stats.paragraphs += inner.stats.paragraphs
537
+ stats.headings += inner.stats.headings
538
+ stats.equations += inner.stats.equations
539
+ for (const [key, value] of Object.entries(inner.stats.skipped)) countSkip(key)
540
+ index = after
541
+ continue
542
+ }
543
+ // 透明容器:跳过 begin、它的**可选参数**与必选参数,内部文本照常进 buffer。
544
+ // 🔴 可选参数必须一起跳:`\begin{tcolorbox}[colback=blue!5!white, title=…]` 的方括号
545
+ // 若留在 buffer 里,下一段正文就以 `[colback=blue!5!white, …]` 开头 —— 实测
546
+ // Learning to Remember 有 5 段正文带着这串键值对,读者与模型都把它当内容读。
547
+ let cursor = group.end
548
+ const optional = readOptional(source, skipSpaces(source, cursor))
549
+ if (optional !== null) cursor = skipSpaces(source, optional.end)
550
+ const argumentCount = TRANSPARENT_ARGUMENTS[base] ?? 0
551
+ for (let position = 0; position < argumentCount; position += 1) {
552
+ const argument = readGroup(source, skipSpaces(source, cursor))
553
+ if (argument === null) break
554
+ cursor = argument.end
555
+ }
556
+ flush()
557
+ index = cursor
558
+ continue
559
+ }
560
+
561
+ if (command.name === 'end') {
562
+ const group = readGroup(source, skipSpaces(source, command.end))
563
+ flush()
564
+ index = group === null ? command.end : group.end
565
+ continue
566
+ }
567
+
568
+ if (command.name in HEADING_LEVELS) {
569
+ let cursor = skipSpaces(source, command.end)
570
+ if (source[cursor] === '*') cursor += 1
571
+ const short = readOptional(source, cursor)
572
+ if (short !== null) cursor = skipSpaces(source, short.end)
573
+ const group = readGroup(source, cursor)
574
+ if (group !== null) {
575
+ const title = inlineText(group.content)
576
+ const level = HEADING_LEVELS[command.name]
577
+ if (title !== '') {
578
+ if (level > 0) {
579
+ flush()
580
+ items.push({ type: 'text', text: title, text_level: level })
581
+ stats.headings += 1
582
+ } else {
583
+ buffer += title + '。'
584
+ }
585
+ }
586
+ index = group.end
587
+ continue
588
+ }
589
+ }
590
+
591
+ if (command.name === 'item') {
592
+ flush()
593
+ const optional = readOptional(source, skipSpaces(source, command.end))
594
+ if (optional !== null) {
595
+ pendingPrefix = ' '.repeat(Math.max(0, depth - 1))
596
+ buffer += inlineText(optional.content) + ':'
597
+ let after = optional.end
598
+ while (source[after] === ' ') after += 1
599
+ index = after
600
+ continue
601
+ }
602
+ pendingPrefix = ' '.repeat(Math.max(0, depth - 1)) + '- '
603
+ index = command.end
604
+ continue
605
+ }
606
+
607
+ buffer += source.slice(index, command.end)
608
+ index = command.end
609
+ continue
610
+ }
611
+
612
+ // 前一字符是反斜杠时,`\$` 是**字面美元符号**(价格、正则),不是公式定界符。
613
+ if (char === '$' && source[index - 1] !== '\\') {
614
+ // 行间公式 \$\$:包成 equation 块(display math)。
615
+ if (source[index + 1] === '$') {
616
+ const close = source.indexOf('$$', index + 2)
617
+ if (close !== -1) {
618
+ const tex = source.slice(index + 2, close).replace(/\s+/g, ' ').trim()
619
+ if (tex !== '' && plausibleDisplayMath(tex)) {
620
+ flush()
621
+ items.push({ type: 'equation', text: '$$\n' + tex + '\n$$' })
622
+ stats.equations += 1
623
+ index = close + 2
624
+ continue
625
+ }
626
+ }
627
+ }
628
+ buffer += char
629
+ index += 1
630
+ continue
631
+ }
632
+
633
+ if (char === '\n') {
634
+ // 空行 = 段落边界;单个换行在 LaTeX 里只是空格。
635
+ let cursor = index + 1
636
+ while (cursor < source.length && (source[cursor] === ' ' || source[cursor] === '\t' || source[cursor] === '\r')) cursor += 1
637
+ if (source[cursor] === '\n') {
638
+ flush()
639
+ index = cursor + 1
640
+ continue
641
+ }
642
+ buffer += ' '
643
+ index += 1
644
+ continue
645
+ }
646
+
647
+ buffer += char
648
+ index += 1
649
+ }
650
+
651
+ flush()
652
+ return { items, stats, figures }
653
+ }