@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,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
|
+
}
|
package/lib/pdf-page.js
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
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
|
+
// gap 是水平长度,不是坐标点:裁后 0–1000 画布缩窄 visible.width,
|
|
80
|
+
// 因此长度必须除以同一个比例。客户端随后乘裁后页宽,物理像素间距才不变。
|
|
81
|
+
gap: Number.isFinite(word.gap) ? word.gap / visible.width : word.gap,
|
|
82
|
+
...(Array.isArray(word.chars) ? { chars: word.chars.map(char => ({ ...char, bbox: mapBox(char.bbox) })) } : {}),
|
|
83
|
+
line: Array.isArray(word.line) && word.line.length === 2
|
|
84
|
+
? [mapY(word.line[0]), mapY(word.line[1])]
|
|
85
|
+
: word.line,
|
|
86
|
+
})),
|
|
87
|
+
}))
|
|
88
|
+
return {
|
|
89
|
+
// 尺寸也换成**可见区域**的:客户端拿它算叠加层缩放,换掉就不用改客户端的任何定位代码。
|
|
90
|
+
width: page.width * visible.width,
|
|
91
|
+
height: page.height * visible.height,
|
|
92
|
+
canvas: box,
|
|
93
|
+
groups: rows,
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function clamp1000(value) {
|
|
98
|
+
return Math.min(1000, Math.max(0, value))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function validPdfPage(value, page) {
|
|
102
|
+
return value?.schemaVersion === 3 && value.page === page
|
|
103
|
+
&& Number.isSafeInteger(value.pageCount) && value.pageCount >= page
|
|
104
|
+
&& Number.isFinite(value.width) && value.width > 0 && Number.isFinite(value.height) && value.height > 0
|
|
105
|
+
// v3 adds PDFium character positions. Also require complete text coverage:
|
|
106
|
+
// older v3 caches omitted the native box for PDFium's U+FFFE line-end hyphen.
|
|
107
|
+
// Reject them so readPdfPage rebuilds the cache with the complete glyph sequence.
|
|
108
|
+
&& Array.isArray(value.words) && value.words.every(word => typeof word?.text === 'string' && validBox(word.bbox)
|
|
109
|
+
&& Array.isArray(word.chars) && word.chars.every(char => typeof char?.text === 'string' && char.text.length > 0 && validBox(char.bbox))
|
|
110
|
+
&& word.chars.map(char => char.text).join('') === word.text)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function validBox(box) {
|
|
114
|
+
return Array.isArray(box) && box.length === 4 && box.every(Number.isFinite) && box[2] >= box[0] && box[3] >= box[1]
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function sameLine(a, b) {
|
|
118
|
+
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]
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const matchingText = value => plainInlineText(value).normalize('NFKC').toLowerCase().replace(/[^\p{L}\p{N}]/gu, '')
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* **结构性块**:文字在 caption 里,PDF 文字层的正文词永远不该归给它们。
|
|
125
|
+
*
|
|
126
|
+
* 🔴 判据必须是块类型而不是"有没有 sourceText":text 块里有 5.8% 是跨页续文的尾部
|
|
127
|
+
* (sourceText 为空但文字层有词),按"有没有字"判会把它们一起改坏。
|
|
128
|
+
* 实测全库:table / image / chart / code 四类 100% 无 sourceText,而 text 只 5.8%。
|
|
129
|
+
*/
|
|
130
|
+
const STRUCTURAL_KINDS = new Set(['image', 'figure', 'table', 'chart', 'code'])
|
|
131
|
+
|
|
132
|
+
export function pdfPageGroups(page, blocks) {
|
|
133
|
+
const rows = (Array.isArray(blocks) ? blocks : []).filter(block => block.page === page.page && validBox(block.bbox))
|
|
134
|
+
const texts = new Map(rows.map(row => [row.id, matchingText(row.sourceText ?? '')]))
|
|
135
|
+
// 块类型:结构性块不参与正文词归属(见 STRUCTURAL_KINDS)。
|
|
136
|
+
const styles = new Map(rows.map(row => [row.id, String(row.type ?? '')]))
|
|
137
|
+
const lines = []
|
|
138
|
+
for (const word of page.words) {
|
|
139
|
+
const previous = lines.at(-1)?.words.at(-1)
|
|
140
|
+
const gap = previous ? (word.bbox[0] - previous.bbox[2]) * page.width : 0
|
|
141
|
+
const height = (word.bbox[3] - word.bbox[1]) * page.height
|
|
142
|
+
if (!previous || !sameLine(previous.bbox, word.bbox) || gap > height * 3) lines.push({ words: [] })
|
|
143
|
+
lines.at(-1).words.push(word)
|
|
144
|
+
}
|
|
145
|
+
const grouped = new Map()
|
|
146
|
+
for (const line of lines) {
|
|
147
|
+
const text = matchingText(line.words.map(word => word.text).join(' '))
|
|
148
|
+
const matches = text.length >= 12 ? rows.filter(row => texts.get(row.id).includes(text)) : []
|
|
149
|
+
const x = (line.words[0].bbox[0] + line.words.at(-1).bbox[2]) / 2
|
|
150
|
+
const y = line.words.reduce((sum, word) => sum + (word.bbox[1] + word.bbox[3]) / 2, 0) / line.words.length
|
|
151
|
+
// 🔴 **结构性块(图片 / 图表 / 表格 / 代码)只在它压着正文时才退让**,其余情形照旧。
|
|
152
|
+
//
|
|
153
|
+
// 背景:图片 / 图表的 bbox 常常压在正文段落上。兜底分支按 score 挑最近的块时,第二项
|
|
154
|
+
// 是包含框面积,面积更小的那一方胜出 —— 于是图片块把正文行抢走。后果远不止少一行字:
|
|
155
|
+
// 同一段文字被拆进**两个 DOM 容器**,渲染顺序随块顺序断开,浏览器按 DOM 顺序铺开原生
|
|
156
|
+
// 选区,用户从段首拖到中间就整段涂蓝(实测 ResNet 第 2 页首段:image 块 blk-24 面积
|
|
157
|
+
// 39163 < 正文块 blk-23 的 77815,抢走 3 行含行内公式的文字,复制出来的顺序因此呈现
|
|
158
|
+
// "公式那几行跑到末尾")。
|
|
159
|
+
//
|
|
160
|
+
// 🔴 那一行**为什么匹配不上正文块**:blk-23 的 sourceText 是 LaTeX
|
|
161
|
+
// (`$\mathcal{H}(\mathbf{x})$`),经 matchingText 后是 `mathcalhmathbfx`,而 PDF 文字层
|
|
162
|
+
// 抽出来的是排版后的 `H(x)` —— 两者永远对不上,所以这批行必然走兜底分支。
|
|
163
|
+
// 也就是说,靠"内容匹配"挡不住它,判据必须落在几何上。
|
|
164
|
+
const scoreOf = row => {
|
|
165
|
+
const [left, top, right, bottom] = row.bbox
|
|
166
|
+
const dx = Math.max(left - x, 0, x - right), dy = Math.max(top - y, 0, y - bottom)
|
|
167
|
+
return { distance: Math.hypot(dx, dy), score: Math.hypot(dx, dy) * 1000000 + (right - left) * (bottom - top) }
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* 这一行抢不抢得走:结构性块(图片/图表)只有在**不与任何文字块重叠**时才配拿词。
|
|
171
|
+
*
|
|
172
|
+
* 🔴 判据必须是「几何重叠」而不是「有没有 sourceText」也不是「无条件惩罚」——
|
|
173
|
+
* 两者都被实测否掉了:
|
|
174
|
+
* · 按 sourceText 判:text 块有 5.8% 是跨页续文尾部(sourceText 空但有词),会误伤;
|
|
175
|
+
* · 无条件惩罚:表格自己格子里的字(ResNet p7 blk-119 的 "output map size 32×32…"
|
|
176
|
+
* 夹在 blk-116 与 blk-120 之间、不与任何文字块重叠)会被整批赶走。
|
|
177
|
+
* 而图片块 blk-24 与正文块 blk-23 重叠 69% —— 它罩住的词本来就是正文的。
|
|
178
|
+
*/
|
|
179
|
+
const overlapsText = row => rows.some(other => other !== row
|
|
180
|
+
&& !STRUCTURAL_KINDS.has(styles.get(other.id))
|
|
181
|
+
&& row.bbox[0] < other.bbox[2] && other.bbox[0] < row.bbox[2]
|
|
182
|
+
&& row.bbox[1] < other.bbox[3] && other.bbox[1] < row.bbox[3])
|
|
183
|
+
const pick = (candidates) => {
|
|
184
|
+
let chosenRow = null, bestScore = Infinity
|
|
185
|
+
for (const row of candidates) {
|
|
186
|
+
const { distance, score } = scoreOf(row)
|
|
187
|
+
if (!matches.length && distance > 50) continue
|
|
188
|
+
if (score < bestScore) { bestScore = score; chosenRow = row }
|
|
189
|
+
}
|
|
190
|
+
return chosenRow
|
|
191
|
+
}
|
|
192
|
+
const pool = matches.length ? matches : rows
|
|
193
|
+
// 第一轮:内容匹配里有没有文字块 —— 有就直接在那些里挑(公式行的 matches 为空,走第二轮)。
|
|
194
|
+
const textMatched = matches.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)))
|
|
195
|
+
let chosen = textMatched.length > 0 ? pick(textMatched) : null
|
|
196
|
+
// 第二轮:在**不与文字块重叠**的候选里挑。文字块永远在内,结构性块看它是否压着正文。
|
|
197
|
+
if (chosen === null) chosen = pick(pool.filter(row => !STRUCTURAL_KINDS.has(styles.get(row.id)) || !overlapsText(row)))
|
|
198
|
+
// 第三轮:实在没有候选(例如整页只有一张图),才放开限制。
|
|
199
|
+
if (chosen === null) chosen = pick(pool)
|
|
200
|
+
if (!chosen) continue
|
|
201
|
+
if (!grouped.has(chosen.id)) grouped.set(chosen.id, { id: chosen.id, words: [] })
|
|
202
|
+
for (const word of line.words) {
|
|
203
|
+
const text = word.text.normalize('NFKC').replace(/\u00ad/g, '')
|
|
204
|
+
if (text) grouped.get(chosen.id).words.push({
|
|
205
|
+
text, bbox: word.bbox,
|
|
206
|
+
// Preserve native boxes through paragraph grouping. The browser only
|
|
207
|
+
// uses them when the full normalized string matches one-to-one.
|
|
208
|
+
...(Array.isArray(word.chars) ? { chars: word.chars.map(char => ({
|
|
209
|
+
text: char.text.normalize('NFKC').replace(/\u00ad/g, ''), bbox: char.bbox,
|
|
210
|
+
})) } : {}),
|
|
211
|
+
})
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return [...grouped.values()].filter(group => group.words.length > 0).map(group => {
|
|
215
|
+
let line
|
|
216
|
+
for (const word of group.words) {
|
|
217
|
+
if (!line || !sameLine(line.last, word.bbox)) line = { top: word.bbox[1], bottom: word.bbox[3] }
|
|
218
|
+
line.last = word.bbox
|
|
219
|
+
line.top = Math.min(line.top, word.bbox[1]); line.bottom = Math.max(line.bottom, word.bbox[3])
|
|
220
|
+
word.line = line
|
|
221
|
+
}
|
|
222
|
+
// 每个词后面那个词是不是**同一行**的续词、以及是不是断词连写(gen- / erated)。
|
|
223
|
+
// 两条都要留到拼正文那一步用,所以先算一遍存下来。
|
|
224
|
+
const joins = []
|
|
225
|
+
const words = group.words.map((word, i) => {
|
|
226
|
+
const next = group.words[i + 1]
|
|
227
|
+
const joined = next && /[A-Za-z]-$/.test(word.text) && /^[a-z]/.test(next.text)
|
|
228
|
+
&& next.bbox[1] > word.bbox[1] + (word.bbox[3] - word.bbox[1]) * 0.4
|
|
229
|
+
joins.push(joined === true)
|
|
230
|
+
// 🔴 空白只在**同一行**的后继词之前才算数(PITFALLS 98)。按「后面还有词」补,行尾那个词也会
|
|
231
|
+
// 带一个空格,而它的 gap 是 0(空格跨了换行)—— 客户端把词盒宽度取成字框宽,字距却按
|
|
232
|
+
// 「含空格的字串」等分,负字距被算大、整词的字被压窄;行末空格又被浏览器悬挂/裁掉,
|
|
233
|
+
// 选区右沿于是止于倒数一个字形,末字右边那一格永远盖不住。
|
|
234
|
+
const sameLine = next !== undefined && next.line === word.line
|
|
235
|
+
const nativeChars = Array.isArray(word.chars) ? word.chars : null
|
|
236
|
+
const trimmedHyphen = joined && nativeChars?.at(-1)?.text === '-'
|
|
237
|
+
const chars = trimmedHyphen ? nativeChars.slice(0, -1) : nativeChars
|
|
238
|
+
// When the normalized paragraph joins a line-end hyphen to the next
|
|
239
|
+
// line, remove it from text, glyphs, and the visible word edge together.
|
|
240
|
+
// A page-final hyphen is not joined and keeps its own native glyph box.
|
|
241
|
+
const bbox = trimmedHyphen && chars.length
|
|
242
|
+
? [word.bbox[0], word.bbox[1], Math.max(...chars.map(char => char.bbox[2])), word.bbox[3]]
|
|
243
|
+
: word.bbox
|
|
244
|
+
return { text: (joined ? word.text.slice(0, -1) : word.text) + (sameLine && !joined ? ' ' : ''), bbox,
|
|
245
|
+
...(chars ? { chars } : {}),
|
|
246
|
+
line: [word.line.top, word.line.bottom], gap: sameLine ? Math.max(0, next.bbox[0] - word.bbox[2]) : 0 }
|
|
247
|
+
})
|
|
248
|
+
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])
|
|
249
|
+
// 逐行拼正文:行内直接连(词自己带着尾空格),行与行之间补一个空格 ——
|
|
250
|
+
// 行尾词不再带空格之后,段落正文仍然词之间有分隔;断词连写(gen- / erated)两段直接接,
|
|
251
|
+
// 连字符已在上面被去掉。
|
|
252
|
+
const text = words.reduce((acc, word, i) => {
|
|
253
|
+
if (i === 0) return word.text
|
|
254
|
+
if (joins[i - 1]) return acc + word.text
|
|
255
|
+
const prev = words[i - 1]
|
|
256
|
+
const sameLine = prev.line[0] === word.line[0] && prev.line[1] === word.line[1]
|
|
257
|
+
return acc + (sameLine || acc.endsWith(' ') ? '' : ' ') + word.text
|
|
258
|
+
}, '')
|
|
259
|
+
return { ...group, bbox, words, text }
|
|
260
|
+
})
|
|
261
|
+
}
|
package/lib/pdf-scan.js
ADDED
|
@@ -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
|
+
}
|