@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.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -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 +2607 -0
  19. package/lib/client.js +9569 -0
  20. package/lib/code-source.js +68 -0
  21. package/lib/concurrency-gate.js +91 -0
  22. package/lib/context.js +233 -0
  23. package/lib/csl/SOURCES.md +10 -0
  24. package/lib/csl/gb-t-7714.csl +441 -0
  25. package/lib/csl/ieee.csl +520 -0
  26. package/lib/csl/locales-zh-CN.xml +438 -0
  27. package/lib/csl/nature.csl +190 -0
  28. package/lib/discussion.js +400 -0
  29. package/lib/documents.js +67 -0
  30. package/lib/export.js +848 -0
  31. package/lib/file-lock.js +177 -0
  32. package/lib/gloss.js +181 -0
  33. package/lib/glossary.js +279 -0
  34. package/lib/index.js +3862 -0
  35. package/lib/inline-html.js +53 -0
  36. package/lib/install-dependency.js +120 -0
  37. package/lib/item-ops.js +83 -0
  38. package/lib/job-facade.js +58 -0
  39. package/lib/json-store.js +54 -0
  40. package/lib/library-model.js +132 -0
  41. package/lib/library-service.js +180 -0
  42. package/lib/library-tool.js +982 -0
  43. package/lib/library.js +814 -0
  44. package/lib/markdown-assets.js +138 -0
  45. package/lib/markdown-literals.js +93 -0
  46. package/lib/metadata-enrichment.js +516 -0
  47. package/lib/metadata-fetch.js +146 -0
  48. package/lib/metadata-node.js +158 -0
  49. package/lib/metadata-proxy.ps1 +35 -0
  50. package/lib/mineru-config.js +95 -0
  51. package/lib/mineru-sdk-helper.py +123 -0
  52. package/lib/mineru-sdk.js +182 -0
  53. package/lib/mineru.js +268 -0
  54. package/lib/mirror-export.js +240 -0
  55. package/lib/outline.js +296 -0
  56. package/lib/page-image-helper.py +294 -0
  57. package/lib/page-image.js +454 -0
  58. package/lib/paper-metadata.js +242 -0
  59. package/lib/parse-export.js +631 -0
  60. package/lib/pdf-analysis-tool.js +750 -0
  61. package/lib/pdf-metadata-helper.py +75 -0
  62. package/lib/pdf-metadata.js +141 -0
  63. package/lib/pdf-page.js +183 -0
  64. package/lib/pdf-scan.js +134 -0
  65. package/lib/pdf-text.js +68 -0
  66. package/lib/picker.js +305 -0
  67. package/lib/portable.js +379 -0
  68. package/lib/purge.js +170 -0
  69. package/lib/read-tool.js +660 -0
  70. package/lib/reader-store.js +497 -0
  71. package/lib/reading-order.js +207 -0
  72. package/lib/rename-document.js +480 -0
  73. package/lib/rename.js +372 -0
  74. package/lib/renderer-status.js +161 -0
  75. package/lib/resolver.js +1152 -0
  76. package/lib/result-archive.js +157 -0
  77. package/lib/revisions.js +330 -0
  78. package/lib/search-database.js +62 -0
  79. package/lib/search-index.js +601 -0
  80. package/lib/search-scan.js +185 -0
  81. package/lib/search-source.js +23 -0
  82. package/lib/search-terms.js +539 -0
  83. package/lib/section-audit.js +209 -0
  84. package/lib/selection-message.js +332 -0
  85. package/lib/serial-tail.js +21 -0
  86. package/lib/slicing.js +425 -0
  87. package/lib/source-resolver.js +581 -0
  88. package/lib/stem-repair.js +189 -0
  89. package/lib/storage.js +562 -0
  90. package/lib/store-paths.js +253 -0
  91. package/lib/table-gfm.js +236 -0
  92. package/lib/tasks.js +270 -0
  93. package/lib/tex-align.js +509 -0
  94. package/lib/tex-blocks.js +653 -0
  95. package/lib/tex-fetch.js +455 -0
  96. package/lib/tex-figures.js +140 -0
  97. package/lib/tex-inline.js +166 -0
  98. package/lib/tex-merge.js +279 -0
  99. package/lib/tex-pipeline.js +242 -0
  100. package/lib/tex-prepare.js +746 -0
  101. package/lib/tex-tables.js +210 -0
  102. package/lib/text-similarity.js +85 -0
  103. package/lib/tool-contract.js +86 -0
  104. package/lib/tool-host.js +1058 -0
  105. package/lib/tool-identity.js +214 -0
  106. package/lib/translatable-text.js +48 -0
  107. package/lib/translate-prompts.js +709 -0
  108. package/lib/translate-queue.js +418 -0
  109. package/lib/translate-task.js +158 -0
  110. package/lib/translate.js +909 -0
  111. package/lib/update-check.js +438 -0
  112. package/lib/update-contracts.js +75 -0
  113. package/lib/usage.js +282 -0
  114. package/package.json +55 -4
@@ -0,0 +1,75 @@
1
+ """读 PDF 的文档信息字典(Info dict),只回传标题/作者/创建时间。
2
+
3
+ 为什么要单独一个 helper:PDF 元数据只有 pypdfium2 读得到,而 Node 侧不引任何 PDF 库。
4
+ 这条链与 page-image-helper.py 完全同源(同一个 uvx + pypdfium2==5.13.0 依赖),
5
+ 因此**不新增任何依赖**,也不引入第二种 PDF 解析器。
6
+
7
+ 🔴 **不解析页面、不渲染**:只读 Info dict,因此对超大 PDF 也是毫秒级。
8
+ 输出走 stdout 的定界标记(与 page-image-helper.py 同款),元数据很小,不会顶穿上限。
9
+ """
10
+
11
+ import json
12
+ import sys
13
+
14
+ RESULT_BEGIN = "DSH-PAPER-META-BEGIN"
15
+ RESULT_END = "DSH-PAPER-META-END"
16
+
17
+
18
+ def _pin_utf8_stdio() -> None:
19
+ """把 stdin/stdout 钉成 UTF-8(与 page-image-helper.py 同一条理由)。
20
+
21
+ Python 在 Windows 上按系统 ANSI 代码页解管道;中文机上输进来的 UTF-8 路径会解成
22
+ 乱码或直接抛 UnicodeDecodeError,于是标题/作者读不出来 —— 表现为「别的电脑上
23
+ 自动改名不生效」,本机 ACP=65001 时完全看不出来。
24
+ """
25
+ for stream in (sys.stdin, sys.stdout):
26
+ reconfigure = getattr(stream, "reconfigure", None)
27
+ if reconfigure is not None:
28
+ try:
29
+ reconfigure(encoding="utf-8")
30
+ except (ValueError, OSError):
31
+ pass
32
+
33
+
34
+ def _clean(value):
35
+ """只认字符串;去掉控制字符与首尾空白。"""
36
+ if not isinstance(value, str):
37
+ return ""
38
+ # Info dict 里的值是"几乎是字符串"的字节串,可能带对不上编码的字符。
39
+ cleaned = "".join(ch for ch in value if ch >= " " or ch == "\t")
40
+ return cleaned.strip()
41
+
42
+
43
+ def main():
44
+ _pin_utf8_stdio()
45
+ request = json.load(sys.stdin)
46
+ pdf_path = request["pdfPath"]
47
+ result = {"ok": True, "title": "", "author": "", "created": ""}
48
+ doc = None
49
+ try:
50
+ import pypdfium2 as pdfium
51
+ doc = pdfium.PdfDocument(pdf_path)
52
+ # get_metadata_dict 只回文档信息字典里的键;缺失的键不会出现。
53
+ metadata = doc.get_metadata_dict() or {}
54
+ result["title"] = _clean(metadata.get("Title"))
55
+ result["author"] = _clean(metadata.get("Author"))
56
+ result["created"] = _clean(metadata.get("CreationDate"))
57
+ except Exception as error: # noqa: BLE001
58
+ # 读不出元数据**不是错误**:调用方据此回退到别的标题来源。
59
+ # 但要把原因带回去,排障时才知道是"没元数据"还是"PDF 打不开"。
60
+ result["ok"] = False
61
+ result["error"] = "%s: %s" % (type(error).__name__, error)
62
+ finally:
63
+ if doc is not None:
64
+ try:
65
+ doc.close()
66
+ except Exception: # noqa: BLE001
67
+ pass
68
+ sys.stdout.write(RESULT_BEGIN)
69
+ sys.stdout.write(json.dumps(result, ensure_ascii=False))
70
+ sys.stdout.write(RESULT_END)
71
+ sys.stdout.flush()
72
+
73
+
74
+ if __name__ == "__main__":
75
+ main()
@@ -0,0 +1,141 @@
1
+ /**
2
+ * 读 PDF 的文档信息字典(Title / Author / CreationDate)。
3
+ *
4
+ * 走 lib/pdf-metadata-helper.py —— **复用页面图那条链**(uvx + pypdfium2==5.13.0),
5
+ * 所以不新增依赖、不引第二个 PDF 解析器。读不出元数据**不是错误**:那只是这条回退链的一环,
6
+ * 由调用方继续往下试(MinerU 标题)。
7
+ */
8
+ import { spawn } from 'node:child_process'
9
+ import { fileURLToPath } from 'node:url'
10
+ import { childEnvironment } from './mineru-sdk.js'
11
+
12
+ const HELPER_PATH = fileURLToPath(new URL('./pdf-metadata-helper.py', import.meta.url))
13
+ const RESULT_BEGIN = 'DSH-PAPER-META-BEGIN'
14
+ const RESULT_END = 'DSH-PAPER-META-END'
15
+ const MAX_STDOUT_BYTES = 64 * 1024
16
+ const MAX_STDERR_BYTES = 16 * 1024
17
+ /** 默认启动器:与 page-image.js 同款白名单判定,只认 uvx。 */
18
+ const DEFAULT_COMMAND = 'uvx'
19
+ /** 包版本与 page-image.js 钉同一个:两条链共用一个 uv 环境,版本漂移会两边都出问题。 */
20
+ const PYPDFIUM_SPEC = 'pypdfium2==5.13.0'
21
+ /** 读元数据是毫秒级的;超过这个时间说明启动器本身卡住了,不必再等。 */
22
+ const DEFAULT_TIMEOUT_MS = 30000
23
+
24
+ /**
25
+ * 元数据的规范形状。取不到一律空串 —— 调用方按「这段没有」处理。
26
+ *
27
+ * @param {unknown} value
28
+ * @returns {{title: string, author: string, created: string, available: boolean}}
29
+ */
30
+ export function normalizePdfMetadata(value) {
31
+ const textOf = key => (typeof value?.[key] === 'string' ? value[key] : '')
32
+ return {
33
+ title: textOf('title'),
34
+ author: textOf('author'),
35
+ created: textOf('created'),
36
+ available: value?.ok === true,
37
+ }
38
+ }
39
+
40
+ /** 从 helper 的 stdout 里取出定界标记之间的 JSON。 */
41
+ function resultPayload(stdout) {
42
+ const begin = stdout.lastIndexOf(RESULT_BEGIN)
43
+ const end = stdout.indexOf(RESULT_END, begin + RESULT_BEGIN.length)
44
+ if (begin < 0 || end < 0) throw new Error('PDF 元数据桥接器没有返回结果标记')
45
+ return JSON.parse(stdout.slice(begin + RESULT_BEGIN.length, end).trim())
46
+ }
47
+
48
+ /**
49
+ * 启动 helper 并把 payload 喂进去(与 page-image.js 的启动形态逐条对齐)。
50
+ *
51
+ * @param {{command?: string, args: string[], env?: object, timeoutMs?: number, signal?: AbortSignal}} launch
52
+ * @param {object} payload
53
+ */
54
+ export async function runPdfMetadataHelper(launch, payload) {
55
+ return new Promise((resolve, reject) => {
56
+ const child = spawn(launch.command, launch.args, {
57
+ env: launch.env,
58
+ windowsHide: true,
59
+ stdio: ['pipe', 'pipe', 'pipe'],
60
+ })
61
+ // 🔴 **按字节累积、最后一次性解码**(与 picker.js 同一条教训,那边已经踩过):
62
+ // `stdout += chunk` 会对每个 chunk 各解一次 UTF-8,一个中文字符刚好跨在两块之间时
63
+ // 就被解成两个 U+FFFD —— 标题/作者跟着坏掉,而这里读的正是**要变成文件名的**那两段。
64
+ // 分块边界取决于管道缓冲与内容长度,换台机器就可能复现。
65
+ let stdout = Buffer.alloc(0)
66
+ let stderr = Buffer.alloc(0)
67
+ let settled = false
68
+ const finish = callback => value => {
69
+ if (settled) return
70
+ settled = true
71
+ clearTimeout(timer)
72
+ launch.signal?.removeEventListener?.('abort', abort)
73
+ callback(value)
74
+ }
75
+ const fail = finish(reject)
76
+ const succeed = finish(resolve)
77
+ const abort = () => {
78
+ child.kill()
79
+ fail(new Error('PDF 元数据读取已取消'))
80
+ }
81
+ const timer = setTimeout(() => {
82
+ child.kill()
83
+ fail(new Error('PDF 元数据读取超过 ' + launch.timeoutMs + ' ms'))
84
+ }, launch.timeoutMs)
85
+ timer.unref?.()
86
+ launch.signal?.addEventListener?.('abort', abort, { once: true })
87
+ child.stdout.on('data', chunk => {
88
+ stdout = Buffer.concat([stdout, Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8')])
89
+ if (stdout.length > MAX_STDOUT_BYTES) { child.kill(); fail(new Error('PDF 元数据桥接器输出超过限制')) }
90
+ })
91
+ child.stderr.on('data', chunk => {
92
+ // 与 stdout 同理按字节累积;只留尾部 —— 报错时的有用信息总在最后。
93
+ stderr = Buffer.concat([stderr, Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8')])
94
+ if (stderr.length > MAX_STDERR_BYTES) stderr = stderr.subarray(-MAX_STDERR_BYTES)
95
+ })
96
+ child.on('error', fail)
97
+ child.on('close', code => {
98
+ if (settled) return
99
+ try {
100
+ const detail = stderr.toString('utf8').trim()
101
+ if (code !== 0) throw new Error('PDF 元数据桥接器退出码 ' + code + (detail ? ':' + detail : ''))
102
+ succeed(resultPayload(stdout.toString('utf8')))
103
+ } catch (error) { fail(error) }
104
+ })
105
+ child.stdin.on('error', fail)
106
+ child.stdin.end(JSON.stringify(payload))
107
+ })
108
+ }
109
+
110
+ /**
111
+ * 读一份 PDF 的元数据。
112
+ *
113
+ * 🔴 **任何失败都降级成空元数据**(连同 `available: false`),绝不抛 —— 元数据只是「能不能
114
+ * 据此改名」的输入之一,读不到就该让调用方去试下一条回退,而不是让整次解析失败。
115
+ *
116
+ * @param {string} pdfPath
117
+ * @param {{command?: string, runHelper?: Function, parentEnv?: object, timeoutMs?: number, signal?: AbortSignal}} [options]
118
+ * @returns {Promise<{title: string, author: string, created: string, available: boolean, error?: string}>}
119
+ */
120
+ export async function readPdfMetadata(pdfPath, options = {}) {
121
+ const path = typeof pdfPath === 'string' ? pdfPath.trim() : ''
122
+ if (path === '') return { ...normalizePdfMetadata(null), error: 'PDF 路径为空' }
123
+ const command = typeof options.command === 'string' && options.command.trim() !== '' ? options.command.trim() : DEFAULT_COMMAND
124
+ const launch = {
125
+ command,
126
+ args: ['--from', PYPDFIUM_SPEC, 'python', HELPER_PATH],
127
+ env: childEnvironment({}, options.parentEnv ?? process.env),
128
+ timeoutMs: Number.isFinite(options.timeoutMs) && options.timeoutMs > 0 ? options.timeoutMs : DEFAULT_TIMEOUT_MS,
129
+ signal: options.signal,
130
+ }
131
+ try {
132
+ const result = await (options.runHelper ?? runPdfMetadataHelper)(launch, { pdfPath: path })
133
+ if (result?.ok !== true) {
134
+ return { ...normalizePdfMetadata(null), error: typeof result?.error === 'string' ? result.error : '未返回元数据' }
135
+ }
136
+ return normalizePdfMetadata(result)
137
+ } catch (error) {
138
+ const message = error instanceof Error ? error.message : String(error)
139
+ return { ...normalizePdfMetadata(null), error: message }
140
+ }
141
+ }
@@ -0,0 +1,183 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+ import { childEnvironment } from './mineru-sdk.js'
5
+ import { normalizeCanvas, resolveCommand, runPageImageHelper } from './page-image.js'
6
+ import { PAGE_IMAGE_PAGES_DIR } from './store-paths.js'
7
+ import { plainInlineText } from './inline-html.js'
8
+
9
+ const HELPER = fileURLToPath(new URL('./page-image-helper.py', import.meta.url))
10
+
11
+ /**
12
+ * Native word positions are cached per immutable PDF identity, independently of OCR revisions.
13
+ *
14
+ * 缓存一律按**满页口径**落:裁边只影响渲染,坐标由 {@link cropPdfGroups} 在读出后换算,
15
+ * 于是开关来回切换不必重跑子进程。
16
+ */
17
+ export async function readPdfPage(input, { cacheDir, command, runHelper = runPageImageHelper, parentEnv = process.env } = {}) {
18
+ const { documentId, pdfPath, page } = input
19
+ if (!/^[A-Za-z0-9._-]+$/.test(documentId ?? '') || documentId === '.' || documentId === '..') throw new Error('论文 ID 无效')
20
+ if (!Number.isSafeInteger(page) || page < 1) throw new Error('PDF 页码必须是正整数')
21
+ if (!cacheDir || !pdfPath) throw new Error('PDF 原页没有可用路径')
22
+ const launcher = resolveCommand(command)
23
+ const outputDir = join(cacheDir, PAGE_IMAGE_PAGES_DIR, documentId, 'text')
24
+ const path = join(outputDir, page + '.text.json')
25
+ const cached = async () => {
26
+ try {
27
+ const value = JSON.parse(await readFile(path, 'utf8'))
28
+ return validPdfPage(value, page) ? value : null
29
+ } catch { return null }
30
+ }
31
+ const previous = await cached()
32
+ if (previous) return previous
33
+ const result = await runHelper({
34
+ command: launcher, args: ['--from', 'pypdfium2==5.13.0', '--with', 'pillow==12.3.0', 'python', HELPER],
35
+ env: childEnvironment({}, parentEnv), timeoutMs: 120000,
36
+ }, { pdfPath, pages: [page], outputDir, textOnly: true })
37
+ if (page > result.pageCount) {
38
+ const error = new Error('PDF 页码超出范围'); error.status = 404; throw error
39
+ }
40
+ const value = await cached()
41
+ if (!value) throw new Error(result.skipped?.[0]?.reason || 'PDF 文字层读取失败')
42
+ return value
43
+ }
44
+
45
+ /**
46
+ * 把满页口径的段落与词坐标换算到裁边后的画布上。
47
+ *
48
+ * 🔴 **必须在 pdfPageGroups 之后做。** 那一步是靠词的物理位置去匹配段落框的,两边都用
49
+ * 满页口径才比得起来;先把词挪到裁后坐标再匹配,距离判据立刻失真、段落归属整片错位。
50
+ *
51
+ * 坐标只有这一种线性换算:先按画布切掉四边,再把剩下的区域拉回 0–1000 —— 与页面图用的是
52
+ * 同一份画布,所以选字框永远压在字上。
53
+ *
54
+ * 画布缺失或不合法时原样返回:宁可叠加层按满页对齐,也不编一套坐标。
55
+ *
56
+ * @param {{width: number, height: number, page: number, pageCount: number}} page 满页尺寸(PDF 点)。
57
+ * @param {object[]} groups pdfPageGroups 的产物(满页 0–1000 坐标)。
58
+ * @param {unknown} canvas 渲染器回传的裁边画布。
59
+ * @returns {{width: number, height: number, canvas: object|null, groups: object[]}}
60
+ */
61
+ export function cropPdfGroups(page, groups, canvas) {
62
+ const box = normalizeCanvas(canvas)
63
+ const visible = box === null ? null : {
64
+ width: 1 - box.left - box.right,
65
+ height: 1 - box.top - box.bottom,
66
+ }
67
+ if (visible === null || !(visible.width > 0) || !(visible.height > 0)) {
68
+ return { width: page.width, height: page.height, canvas: null, groups }
69
+ }
70
+ const mapX = value => clamp1000((value / 1000 - box.left) / visible.width * 1000)
71
+ const mapY = value => clamp1000((value / 1000 - box.top) / visible.height * 1000)
72
+ const mapBox = bbox => [mapX(bbox[0]), mapY(bbox[1]), mapX(bbox[2]), mapY(bbox[3])]
73
+ const rows = groups.map(group => ({
74
+ ...group,
75
+ bbox: Array.isArray(group.bbox) && group.bbox.length === 4 ? mapBox(group.bbox) : group.bbox,
76
+ words: group.words.map(word => ({
77
+ ...word,
78
+ bbox: mapBox(word.bbox),
79
+ line: Array.isArray(word.line) && word.line.length === 2
80
+ ? [mapY(word.line[0]), mapY(word.line[1])]
81
+ : word.line,
82
+ })),
83
+ }))
84
+ return {
85
+ // 尺寸也换成**可见区域**的:客户端拿它算叠加层缩放,换掉就不用改客户端的任何定位代码。
86
+ width: page.width * visible.width,
87
+ height: page.height * visible.height,
88
+ canvas: box,
89
+ groups: rows,
90
+ }
91
+ }
92
+
93
+ function clamp1000(value) {
94
+ return Math.min(1000, Math.max(0, value))
95
+ }
96
+
97
+ export function validPdfPage(value, page) {
98
+ return value?.schemaVersion === 2 && value.page === page
99
+ && Number.isSafeInteger(value.pageCount) && value.pageCount >= page
100
+ && Number.isFinite(value.width) && value.width > 0 && Number.isFinite(value.height) && value.height > 0
101
+ && Array.isArray(value.words) && value.words.every(word => typeof word?.text === 'string' && validBox(word.bbox))
102
+ }
103
+
104
+ function validBox(box) {
105
+ return Array.isArray(box) && box.length === 4 && box.every(Number.isFinite) && box[2] >= box[0] && box[3] >= box[1]
106
+ }
107
+
108
+ function sameLine(a, b) {
109
+ return Math.min(a[3], b[3]) - Math.max(a[1], b[1]) > Math.min(a[3] - a[1], b[3] - b[1]) * 0.5 && b[0] >= a[0]
110
+ }
111
+
112
+ const matchingText = value => plainInlineText(value).normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
113
+
114
+ /** Match physical PDF lines to parsed paragraph ids; figure boxes may exclude their captions. */
115
+ export function pdfPageGroups(page, blocks) {
116
+ const rows = (Array.isArray(blocks) ? blocks : []).filter(block => block.page === page.page && validBox(block.bbox))
117
+ const texts = new Map(rows.map(row => [row.id, matchingText(row.sourceText ?? '')]))
118
+ const lines = []
119
+ for (const word of page.words) {
120
+ const previous = lines.at(-1)?.words.at(-1)
121
+ const gap = previous ? (word.bbox[0] - previous.bbox[2]) * page.width : 0
122
+ const height = (word.bbox[3] - word.bbox[1]) * page.height
123
+ if (!previous || !sameLine(previous.bbox, word.bbox) || gap > height * 3) lines.push({ words: [] })
124
+ lines.at(-1).words.push(word)
125
+ }
126
+ const grouped = new Map()
127
+ for (const line of lines) {
128
+ const text = matchingText(line.words.map(word => word.text).join(' '))
129
+ const matches = text.length >= 12 ? rows.filter(row => texts.get(row.id).includes(text)) : []
130
+ const x = (line.words[0].bbox[0] + line.words.at(-1).bbox[2]) / 2
131
+ const y = line.words.reduce((sum, word) => sum + (word.bbox[1] + word.bbox[3]) / 2, 0) / line.words.length
132
+ let chosen = null, best = Infinity
133
+ for (const row of matches.length ? matches : rows) {
134
+ const [left, top, right, bottom] = row.bbox
135
+ const dx = Math.max(left - x, 0, x - right), dy = Math.max(top - y, 0, y - bottom)
136
+ const score = Math.hypot(dx, dy) * 1000000 + (right - left) * (bottom - top)
137
+ if ((matches.length || Math.hypot(dx, dy) <= 50) && score < best) { best = score; chosen = row }
138
+ }
139
+ if (!chosen) continue
140
+ if (!grouped.has(chosen.id)) grouped.set(chosen.id, { id: chosen.id, words: [] })
141
+ for (const word of line.words) {
142
+ const text = word.text.normalize('NFKC').replace(/\u00ad/g, '')
143
+ if (text) grouped.get(chosen.id).words.push({ text, bbox: word.bbox })
144
+ }
145
+ }
146
+ return [...grouped.values()].filter(group => group.words.length > 0).map(group => {
147
+ let line
148
+ for (const word of group.words) {
149
+ if (!line || !sameLine(line.last, word.bbox)) line = { top: word.bbox[1], bottom: word.bbox[3] }
150
+ line.last = word.bbox
151
+ line.top = Math.min(line.top, word.bbox[1]); line.bottom = Math.max(line.bottom, word.bbox[3])
152
+ word.line = line
153
+ }
154
+ // 每个词后面那个词是不是**同一行**的续词、以及是不是断词连写(gen- / erated)。
155
+ // 两条都要留到拼正文那一步用,所以先算一遍存下来。
156
+ const joins = []
157
+ const words = group.words.map((word, i) => {
158
+ const next = group.words[i + 1]
159
+ const joined = next && /[A-Za-z]-$/.test(word.text) && /^[a-z]/.test(next.text)
160
+ && next.bbox[1] > word.bbox[1] + (word.bbox[3] - word.bbox[1]) * 0.4
161
+ joins.push(joined === true)
162
+ // 🔴 空白只在**同一行**的后继词之前才算数(PITFALLS 98)。按「后面还有词」补,行尾那个词也会
163
+ // 带一个空格,而它的 gap 是 0(空格跨了换行)—— 客户端把词盒宽度取成字框宽,字距却按
164
+ // 「含空格的字串」等分,负字距被算大、整词的字被压窄;行末空格又被浏览器悬挂/裁掉,
165
+ // 选区右沿于是止于倒数一个字形,末字右边那一格永远盖不住。
166
+ const sameLine = next !== undefined && next.line === word.line
167
+ return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox: word.bbox,
168
+ line: [word.line.top, word.line.bottom], gap: sameLine ? Math.max(0, next.bbox[0] - word.bbox[2]) : 0 }
169
+ })
170
+ 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])
171
+ // 逐行拼正文:行内直接连(词自己带着尾空格),行与行之间补一个空格 ——
172
+ // 行尾词不再带空格之后,段落正文仍然词之间有分隔;断词连写(gen- / erated)两段直接接,
173
+ // 连字符已在上面被去掉。
174
+ const text = words.reduce((acc, word, i) => {
175
+ if (i === 0) return word.text
176
+ if (joins[i - 1]) return acc + word.text
177
+ const prev = words[i - 1]
178
+ const sameLine = prev.line[0] === word.line[0] && prev.line[1] === word.line[1]
179
+ return acc + (sameLine || acc.endsWith(' ') ? '' : ' ') + word.text
180
+ }, '')
181
+ return { ...group, bbox, words, text }
182
+ })
183
+ }
@@ -0,0 +1,134 @@
1
+ import { lstat, readdir, stat } from 'node:fs/promises'
2
+ import { homedir, platform } from 'node:os'
3
+ import { dirname, isAbsolute, join, parse, resolve } from 'node:path'
4
+
5
+ // 侧栏「选文件夹」的扫描深度:所选文件夹自身算 0 层,向下再走两层子目录。
6
+ // 论文目录的典型布局是 `Papers/<会议>/*.pdf` 或 `Papers/<年份>/<主题>/*.pdf`,两层足够;
7
+ // 更深就等于全盘递归——一次误选盘根会把解析队列和 MinerU 提交额度(45 次/分钟)整批打爆。
8
+ export const MAX_SCAN_DEPTH = 2
9
+
10
+ const PDF_NAME = /\.pdf$/i
11
+
12
+ function errorText(error) {
13
+ return String(error?.message ?? error).slice(0, 200)
14
+ }
15
+
16
+ function scanError(message, status) {
17
+ const error = new Error(message)
18
+ error.status = status
19
+ return error
20
+ }
21
+
22
+ /**
23
+ * 收集 `dir` 及其下至多 `maxDepth` 层子目录里的全部 PDF,按 UTF-16 码元序返回。
24
+ *
25
+ * 只统计真实文件条目:`readdir(..., { withFileTypes: true })` 走 lstat,所以符号链接与
26
+ * Windows 目录联结点(junction)都是 `isSymbolicLink()`——既不向下递归(防环、防跨盘),
27
+ * 也不作为结果收下(同一份 PDF 经多个链接会被重复排队)。`$` 开头的目录是 Windows 系统
28
+ * 共享(如回收站 `$RECYCLE.BIN`),既读不到也不会有论文,直接跳过。
29
+ * 子目录读不动(权限、被占用)不中断整次扫描:记进 `unreadable` 交给调用方提示。
30
+ *
31
+ * @param {string} dir 用户显式选择的文件夹绝对路径
32
+ * @param {{maxDepth?: number, readdirImpl?: typeof readdir}} [options]
33
+ * @returns {Promise<{root: string, pdfs: string[], unreadable: Array<{path: string, error: string}>}>}
34
+ */
35
+ /**
36
+ * 一条 dirent 的真实类型。
37
+ *
38
+ * 🔴 `readdir(..., { withFileTypes: true })` 在**类型不明**的文件系统上会把 `isFile()` /
39
+ * `isDirectory()` 同时判成 false —— 网络盘、部分云盘占位符、个别 FUSE 挂载都会这样。
40
+ * 照旧只认这两个谓词的话,整个目录会被当成「没有 PDF」:用户看到的是「扫了但一篇都没有」,
41
+ * 而本机(NTFS)永远不复现。类型不明时用 lstat 补一次判定,lstat 也失败就跳过这一条。
42
+ *
43
+ * @param {{isFile: Function, isDirectory: Function, isSymbolicLink: Function}} entry
44
+ * @param {string} path
45
+ * @param {Function} lstatImpl
46
+ * @returns {Promise<'file'|'dir'|'link'|'other'>}
47
+ */
48
+ async function kindOfEntry(entry, path, lstatImpl) {
49
+ if (entry.isFile()) return 'file'
50
+ if (entry.isDirectory()) return 'dir'
51
+ try {
52
+ const info = await lstatImpl(path)
53
+ if (info.isSymbolicLink()) return 'link'
54
+ if (info.isDirectory()) return 'dir'
55
+ if (info.isFile()) return 'file'
56
+ } catch { /* 读不动就跳过这一条,与"子目录读不动"同口径:不中断整次扫描 */ }
57
+ return 'other'
58
+ }
59
+
60
+ export async function scanPdfFolder(dir, { maxDepth = MAX_SCAN_DEPTH, readdirImpl = readdir, lstatImpl = lstat } = {}) {
61
+ if (typeof dir !== 'string' || dir.trim() === '') throw scanError('请选择要扫描的文件夹', 400)
62
+ if (!isAbsolute(dir)) throw scanError('文件夹路径必须是绝对路径', 400)
63
+ const root = resolve(dir)
64
+ let rootInfo
65
+ try {
66
+ rootInfo = await stat(root)
67
+ } catch (error) {
68
+ throw scanError(`无法打开文件夹:${errorText(error)}`, error?.code === 'ENOENT' ? 404 : 403)
69
+ }
70
+ if (!rootInfo.isDirectory()) throw scanError('所选路径不是文件夹', 400)
71
+
72
+ const pdfs = []
73
+ const unreadable = []
74
+ const queue = [{ path: root, depth: 0 }]
75
+ while (queue.length > 0) {
76
+ const current = queue.shift()
77
+ let entries
78
+ try {
79
+ entries = await readdirImpl(current.path, { withFileTypes: true })
80
+ } catch (error) {
81
+ // 所选目录自身读不动必须报错:否则侧栏只会说"里没有 PDF",把权限问题说成空目录。
82
+ if (current.depth === 0) throw scanError(`无法读取所选文件夹:${errorText(error)}`, 403)
83
+ unreadable.push({ path: current.path, error: errorText(error) })
84
+ continue
85
+ }
86
+ for (const entry of entries) {
87
+ if (entry.isSymbolicLink()) continue
88
+ const path = join(current.path, entry.name)
89
+ const kind = await kindOfEntry(entry, path, lstatImpl)
90
+ if (kind === 'file' && PDF_NAME.test(entry.name)) pdfs.push(path)
91
+ else if (kind === 'dir' && current.depth < maxDepth && !entry.name.startsWith('$')) {
92
+ queue.push({ path, depth: current.depth + 1 })
93
+ }
94
+ }
95
+ }
96
+ // 按 UTF-16 码元序(Array.sort 默认)而非 localeCompare:结果顺序要跨进程、跨 ICU 版本都一致,
97
+ // 队列里先解析哪篇才可复现。代价是大写名会排在小写名之前,不按人的字典习惯。
98
+ pdfs.sort()
99
+ return { root, pdfs, unreadable }
100
+ }
101
+
102
+ /** 归一化成可比较形式:Windows 上大小写与尾部分隔符都不该影响"是不是同一个位置"。 */
103
+ export function comparablePath(path, os = platform()) {
104
+ const absolute = resolve(path)
105
+ const trimmed = os === 'win32' ? absolute.replace(/[\\/]+$/, '') : absolute.replace(/\/+$/, '')
106
+ const normalized = os === 'win32' ? trimmed.toLowerCase() : trimmed
107
+ return normalized === '' ? trimmed : normalized
108
+ }
109
+
110
+ /**
111
+ * 判断所选目录是不是"大范围位置"。深度 2 并不是真正的护栏:`C:\` 往下两层照样命中成千上万个
112
+ * 目录,一次点击就能把整台机器的 PDF 推给按量计费的 MinerU,所以要单独判高危并要调用方确认。
113
+ * 拦住的是磁盘/网络位置根、UNC 共享根、用户主目录、主目录的父目录(如 `C:\Users`),以及调用方
114
+ * 补进来的数据目录(如 DSH home —— 里面有会话与凭据)。安全时返回 null。
115
+ *
116
+ * @param {string} dir 已解析过的绝对路径
117
+ * @param {{os?: string, home?: string, extra?: Array<{path: string, label: string}>}} [options]
118
+ * @returns {string|null} 高危原因文案,可直接给用户看
119
+ */
120
+ export function scanRiskOf(dir, { os = platform(), home = homedir(), extra = [] } = {}) {
121
+ if (typeof dir !== 'string' || dir.trim() === '' || !isAbsolute(dir)) return null
122
+ const target = comparablePath(dir, os)
123
+ const absoluteRoot = parse(dir).root
124
+ const comparableRoot = comparablePath(absoluteRoot, os)
125
+ const below = target.slice(comparableRoot.length).split(os === 'win32' ? /[\\/]+/ : /\/+/).filter(Boolean)
126
+ if (below.length === 0) return absoluteRoot.startsWith('\\\\') ? '网络位置的服务器根目录' : '磁盘根目录'
127
+ if (os === 'win32' && absoluteRoot.startsWith('\\\\') && below.length === 1) return '网络共享的根目录'
128
+ const absoluteHome = resolve(home)
129
+ const guarded = [[absoluteHome, '当前用户的主目录'], [dirname(absoluteHome), '用户目录的父目录'], ...extra.map(entry => [entry.path, entry.label])]
130
+ for (const [path, label] of guarded) {
131
+ if (typeof path === 'string' && path.trim() !== '' && comparablePath(path, os) === target) return label
132
+ }
133
+ return null
134
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * PDF 文本层:调 pdftotext 拿逐行文本与坐标。
3
+ *
4
+ * 为什么单独成一个模块:它是整条源码管线里**唯一需要外部命令**的一步。把它隔开之后,
5
+ * 对齐、合并、判定树全部保持纯函数,测试不需要本机装 poppler。
6
+ *
7
+ * 失败一律返回空数组(不抛错):没有文本层时上层判 align 降级、整篇退回 MinerU,
8
+ * 那本来就是正确行为;抛错会让一次「拿不到坐标」看起来像「解析失败」。
9
+ */
10
+ import { execFile } from 'node:child_process'
11
+ import { promisify } from 'node:util'
12
+
13
+ import { parseBboxLayout } from './tex-align.js'
14
+
15
+ const execFileAsync = promisify(execFile)
16
+
17
+ /** 默认执行器:pdftotext 把 XML 打到 stdout。 */
18
+ async function defaultRun(command, args) {
19
+ try {
20
+ const { stdout } = await execFileAsync(command, args, { maxBuffer: 64 * 1024 * 1024, windowsHide: true })
21
+ return { code: 0, stdout: String(stdout ?? ''), stderr: '' }
22
+ } catch (error) {
23
+ return { code: Number.isInteger(error?.code) ? error.code : 1, stdout: String(error?.stdout ?? ''), stderr: String(error?.stderr ?? '') }
24
+ }
25
+ }
26
+
27
+ /**
28
+ * 取一篇 PDF 的文本行。
29
+ *
30
+ * @param {string} pdfPath
31
+ * @param {{run?: (command: string, args: string[]) => Promise<{code?: number, stdout?: string}>}} [options]
32
+ * @returns {Promise<Array<{page: number, text: string, bbox: number[], height: number}>>}
33
+ */
34
+ export async function extractPdfLines(pdfPath, { run = defaultRun } = {}) {
35
+ if (typeof pdfPath !== 'string' || pdfPath === '') return []
36
+ if (typeof run !== 'function') return []
37
+ try {
38
+ const result = await run('pdftotext', ['-bbox-layout', pdfPath, '-'])
39
+ if (result?.code !== 0 && result?.code !== undefined) return []
40
+ return parseBboxLayout(String(result?.stdout ?? ''))
41
+ } catch {
42
+ return []
43
+ }
44
+ }
45
+
46
+ /**
47
+ * 取**某一页**的文本行(`-f n -l n`)。
48
+ *
49
+ * 存在的理由是先认来源、再取全文:出版版 PDF 首页没有 arXiv 水印,这一篇在首页就是
50
+ * 决定性证据 —— 不必为它跑一遍全文档的 bbox 抽取。失败同样返回空数组。
51
+ *
52
+ * @param {string} pdfPath
53
+ * @param {number} page 1 起;非正整数时取第一页
54
+ * @param {{run?: (command: string, args: string[]) => Promise<{code?: number, stdout?: string}>}} [options]
55
+ * @returns {Promise<Array<{page: number, text: string, bbox: number[], height: number}>>}
56
+ */
57
+ export async function extractPageLines(pdfPath, page = 1, { run = defaultRun } = {}) {
58
+ if (typeof pdfPath !== 'string' || pdfPath === '') return []
59
+ if (typeof run !== 'function') return []
60
+ const target = Number.isInteger(page) && page >= 1 ? page : 1
61
+ try {
62
+ const result = await run('pdftotext', ['-f', String(target), '-l', String(target), '-bbox-layout', pdfPath, '-'])
63
+ if (result?.code !== 0 && result?.code !== undefined) return []
64
+ return parseBboxLayout(String(result?.stdout ?? ''))
65
+ } catch {
66
+ return []
67
+ }
68
+ }