@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,308 @@
1
+ """把 PDF 页渲染成 WEBP 字节,写到磁盘后只回传路径与元数据。
2
+
3
+ 图片字节**不走 stdout**:Node 侧把 stdout 上限钉在 1 MiB(lib/page-image.js 的
4
+ MAX_STDOUT_BYTES),而一页 1200px 的 WEBP 就有 200 KB 上下,多页内联必然顶穿。helper 直接
5
+ 把文件写到 outputDir,stdout 只回传路径/宽高/字节数。
6
+
7
+ 缓存键的「内容标识」与页码-宽度拼文件名都由 Node 侧决定,这里只认 request 里的参数。
8
+ """
9
+
10
+ import json
11
+ import os
12
+ import sys
13
+ import time
14
+ from pathlib import Path
15
+
16
+ RESULT_BEGIN = "DSH-PAPER-PAGE-BEGIN"
17
+ RESULT_END = "DSH-PAPER-PAGE-END"
18
+
19
+
20
+ def _pin_utf8_stdio() -> None:
21
+ """把 stdin/stdout 钉成 UTF-8。
22
+
23
+ 🔴 **这是「换台电脑就渲染不出原页」的头号原因**,而本机测不到:Python 在 Windows 上
24
+ 按**系统 ANSI 代码页**解管道(中文简体机是 cp936/GBK,繁体是 cp950),不是 UTF-8。
25
+ Node 侧写进来的是 UTF-8 字节,于是带中文的 pdfPath 要么解成乱码(找不到文件),
26
+ 要么直接 UnicodeDecodeError —— 整页图全丢,且错误看起来像「PDF 打不开」。
27
+ 本机 ACP=65001 时一切正常,所以这个 bug 只能靠这行代码修,测不出来也得有。
28
+
29
+ 只用 reconfigure 不够可靠(受 PYTHONIOENCODING 影响),所以 Node 侧同时用字节流读写。
30
+ """
31
+ for stream in (sys.stdin, sys.stdout):
32
+ reconfigure = getattr(stream, "reconfigure", None)
33
+ if reconfigure is not None:
34
+ try:
35
+ reconfigure(encoding="utf-8")
36
+ except (ValueError, OSError):
37
+ pass
38
+
39
+ # Windows 上 os.replace 可能被占用句柄挡住(杀软扫描/并发读取),报 PermissionError。
40
+ # 与 mineru-sdk-helper.py 同样的处置:退避重试;不重试的话一次抖动就丢掉整页图。
41
+ REPLACE_ATTEMPTS = 10
42
+
43
+
44
+ def _replace(temporary: Path, target: Path) -> None:
45
+ for attempt in range(REPLACE_ATTEMPTS):
46
+ try:
47
+ os.replace(temporary, target)
48
+ return
49
+ except PermissionError:
50
+ if attempt == REPLACE_ATTEMPTS - 1:
51
+ raise
52
+ time.sleep(0.02 * (attempt + 1))
53
+
54
+
55
+ def _render_page(page, index: int, scale: float, request: dict, output_dir: Path, crop=None):
56
+ """渲染单页并落盘,返回回传用的元数据。
57
+
58
+ crop 是 PDF 画布单位的 (左切, 下切, 右切, 上切) —— pypdfium2 的 render(crop=...) 就吃这个形状,
59
+ 且下/上按画布方向(y 向上)计。实测反向解释会有 46% 的像素对不上。
60
+ """
61
+ format_name = request["format"]
62
+ width = request["width"]
63
+ quality = request["quality"]
64
+ bitmap = page.render(scale=scale, rotation=0, crop=crop) if crop else page.render(scale=scale, rotation=0)
65
+ image = bitmap.to_pil()
66
+ # 文件名由 Node 侧定形(它才是缓存身份的拥有者):裁边档带 -crop 后缀,两档互不覆盖。
67
+ suffix = request.get("fileSuffix") or ""
68
+ target = output_dir / f"{index}@{width}{suffix}.{format_name}"
69
+ temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
70
+ image.save(temporary, format="WEBP", quality=quality, method=4)
71
+ _replace(temporary, target)
72
+ return {
73
+ "page": index,
74
+ "path": str(target),
75
+ "width": image.width,
76
+ "height": image.height,
77
+ "bytes": target.stat().st_size,
78
+ }
79
+
80
+
81
+ def _text_page(page, index: int, output_dir: Path, page_count: int):
82
+ """Extract native PDF words in the same rotated/cropped coordinates as the bitmap."""
83
+ import ctypes
84
+ import pypdfium2.raw as pdfium
85
+
86
+ width, height = page.get_size()
87
+ device_width, device_height = round(width * 10), round(height * 10)
88
+
89
+ def point(x, y):
90
+ px, py = ctypes.c_int(), ctypes.c_int()
91
+ if not pdfium.FPDF_PageToDevice(page.raw, 0, 0, device_width, device_height, 0, x, y, ctypes.byref(px), ctypes.byref(py)):
92
+ raise ValueError("PDF text coordinate conversion failed")
93
+ return [px.value * 1000 / device_width, py.value * 1000 / device_height]
94
+
95
+ def char_box(at):
96
+ left, bottom, right, top = text.get_charbox(at, loose=True)
97
+ corners = [point(left, bottom), point(left, top), point(right, bottom), point(right, top)]
98
+ return [min(p[0] for p in corners), min(p[1] for p in corners),
99
+ max(p[0] for p in corners), max(p[1] for p in corners)]
100
+
101
+ words = []
102
+ letters, boxes, glyphs = [], [], []
103
+
104
+ def flush():
105
+ if letters and boxes:
106
+ words.append({"text": "".join(letters), "bbox": [
107
+ min(box[0] for box in boxes), min(box[1] for box in boxes),
108
+ max(box[2] for box in boxes), max(box[3] for box in boxes),
109
+ ], "chars": list(glyphs)})
110
+ letters.clear()
111
+ boxes.clear()
112
+ glyphs.clear()
113
+
114
+ text = page.get_textpage()
115
+ try:
116
+ for at in range(text.count_chars()):
117
+ letter = text.get_text_range(at, 1)
118
+ # PDFium replaces a discretionary line-end hyphen with U+FFFE and
119
+ # omits the line break. The sentinel still has a native char box:
120
+ # preserve it so a page-final "high-" remains character-aligned.
121
+ if letter == "\ufffe":
122
+ box = char_box(at)
123
+ letters.append("-")
124
+ boxes.append(box)
125
+ glyphs.append({"text": "-", "bbox": box})
126
+ flush()
127
+ continue
128
+ if not letter or letter.isspace() or ord(letter[0]) < 32:
129
+ flush()
130
+ continue
131
+ left, bottom, right, top = text.get_charbox(at, loose=True)
132
+ corners = [point(left, bottom), point(left, top), point(right, bottom), point(right, top)]
133
+ box = [min(p[0] for p in corners), min(p[1] for p in corners), max(p[0] for p in corners), max(p[1] for p in corners)]
134
+ letters.append(letter)
135
+ boxes.append(box)
136
+ # 与 PDFium 每一个原生字符一一对应;不能只保存整词 bbox:
137
+ # 等宽/斜体/压缩字体的字内位置与浏览器 serif 差异可超过 10 PDF px。
138
+ glyphs.append({"text": letter, "bbox": box})
139
+ flush()
140
+ finally:
141
+ text.close()
142
+ result = {"schemaVersion": 3, "page": index, "pageCount": page_count, "width": width, "height": height, "words": words}
143
+ target = output_dir / f"{index}.text.json"
144
+ temporary = target.with_name(f".{target.name}.{os.getpid()}.tmp")
145
+ temporary.write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
146
+ _replace(temporary, target)
147
+ return {"page": index, "path": str(target)}
148
+
149
+
150
+ def _ink_rect(page, probe_width: int, threshold: int):
151
+ """低分辨率渲一遍,量出真实墨迹的外接框。返回 (左, 上, 右, 下) 的 0–1 占比,空页返回 None。
152
+
153
+ 🔴 **只认像素,不认 PDF 的对象框。** 实测(176 篇真实论文):页面里的跨页背景矩形会把
154
+ `FPDF_GetPageBoundingBox` 与矢量对象框一起撑满整页,而 matplotlib 画的曲线图同样走矢量
155
+ 路径 —— 靠对象类型区分两者必然错一边。像素法对矢量图、扫描件、页眉装饰、水印一视同仁。
156
+ """
157
+ width, _ = page.get_size()
158
+ bitmap = page.render(scale=probe_width / width, rotation=0)
159
+ image = bitmap.to_pil().convert("L")
160
+ left, top, right, bottom = image.width, image.height, -1, -1
161
+ pixels = image.load()
162
+ for y in range(image.height):
163
+ for x in range(image.width):
164
+ if pixels[x, y] < threshold:
165
+ if x < left:
166
+ left = x
167
+ if x > right:
168
+ right = x
169
+ if y < top:
170
+ top = y
171
+ if y > bottom:
172
+ bottom = y
173
+ if right < 0:
174
+ return None
175
+ return (left / image.width, top / image.height,
176
+ (right + 1) / image.width, (bottom + 1) / image.height)
177
+
178
+
179
+ def _canvas_for(document, page_count: int, probe_width: int, threshold: int, pad: float):
180
+ """整篇统一画布:每页的墨迹框取并集,再按页宽/页高的占比外扩 pad。
181
+
182
+ 🔴 **为什么是整篇并集、不是逐页自己裁。** 逐页裁的收益更大(实测中位 18.3% vs 13.7%),
183
+ 但每页裁出来的宽度各不相同,阅读器把它们拉伸到同一个面板宽度后,翻页时字号会忽大忽小
184
+ —— 实测同一篇内各页宽度偏差中位 10.4%。整篇一个画布就一个字都不会跳。
185
+
186
+ 封面(第 1 页)不参与并集:实测 20/24 篇的封面比正文宽出 15% 以上(标题、作者、arXiv 印记),
187
+ 并进去等于白裁。并集为空(整篇都是空页)时退回满页,等价于不裁。
188
+ """
189
+ rects = []
190
+ for index in range(1, page_count + 1):
191
+ page = document[index - 1]
192
+ try:
193
+ rect = _ink_rect(page, probe_width, threshold)
194
+ if rect is not None and index > 1:
195
+ rects.append(rect)
196
+ finally:
197
+ page.close()
198
+ if not rects:
199
+ return {"left": 0.0, "top": 0.0, "right": 0.0, "bottom": 0.0}
200
+ left = min(rect[0] for rect in rects)
201
+ top = min(rect[1] for rect in rects)
202
+ right = max(rect[2] for rect in rects)
203
+ bottom = max(rect[3] for rect in rects)
204
+ return {
205
+ "left": round(max(0.0, left - pad), 6),
206
+ "top": round(max(0.0, top - pad), 6),
207
+ "right": round(max(0.0, 1.0 - right - pad), 6),
208
+ "bottom": round(max(0.0, 1.0 - bottom - pad), 6),
209
+ }
210
+
211
+
212
+ def _read_canvas(path: Path):
213
+ try:
214
+ value = json.loads(path.read_text(encoding="utf-8"))
215
+ except (OSError, ValueError):
216
+ return None
217
+ if not isinstance(value, dict):
218
+ return None
219
+ for key in ("left", "top", "right", "bottom"):
220
+ if not isinstance(value.get(key), (int, float)) or not 0 <= value[key] < 1:
221
+ return None
222
+ return value
223
+
224
+
225
+ def _write_canvas(path: Path, canvas: dict) -> None:
226
+ temporary = path.with_name(f".{path.name}.{os.getpid()}.tmp")
227
+ temporary.write_text(json.dumps(canvas), encoding="utf-8")
228
+ _replace(temporary, path)
229
+
230
+
231
+ def main() -> dict:
232
+ _pin_utf8_stdio()
233
+ request = json.loads(sys.stdin.read())
234
+ import pypdfium2
235
+
236
+ output_dir = Path(request["outputDir"])
237
+ output_dir.mkdir(parents=True, exist_ok=True)
238
+ # 页码是 1-based;单页失败不炸整次调用,进 skipped 让 Node 侧如实回报。
239
+ requested = request.get("pages") or None
240
+ skip_pages = {int(value) for value in (request.get("skipPages") or [])}
241
+ topic_width = request.get("width", 1200)
242
+ canvas = None
243
+
244
+ document = pypdfium2.PdfDocument(request["pdfPath"])
245
+ try:
246
+ page_count = len(document)
247
+ if requested is None:
248
+ limit = int(request.get("limit") or page_count)
249
+ requested = [index for index in range(1, min(page_count, limit) + 1) if index not in skip_pages]
250
+ else:
251
+ requested = [int(value) for value in requested]
252
+ # 裁边画布:显式关掉时保持满页(与接入前逐字节一致),开启时才探测并落盘。
253
+ # 画布随缓存目录走 —— 同一篇的每一档宽度共用它,不会各算一套。
254
+ if request.get("cropPages") and not request.get("textOnly"):
255
+ canvas_path = output_dir / "canvas.json"
256
+ canvas = _read_canvas(canvas_path)
257
+ if canvas is None:
258
+ canvas = _canvas_for(
259
+ document, page_count,
260
+ int(request.get("probeWidth") or 300),
261
+ int(request.get("inkThreshold") or 254),
262
+ float(request.get("cropPad") or 0.004),
263
+ )
264
+ _write_canvas(canvas_path, canvas)
265
+ images = []
266
+ skipped = []
267
+ # 命中判定只由 Node 侧做(它同时检查文件大小与 WEBP 头),这里照单渲染:
268
+ # 在 helper 里再判一次会让「大小 > 0 但头读不动」的缓存被两边都跳过,静默丢页。
269
+ for index in requested:
270
+ if index < 1 or index > page_count:
271
+ skipped.append({"page": index, "reason": f"页码超出文档范围 1-{page_count}"})
272
+ continue
273
+ page = document[index - 1]
274
+ size = page.get_size()
275
+ try:
276
+ if request.get("textOnly"):
277
+ images.append(_text_page(page, index, output_dir, page_count))
278
+ else:
279
+ crop = None
280
+ if canvas is not None:
281
+ crop = (
282
+ canvas["left"] * size[0], canvas["bottom"] * size[1],
283
+ canvas["right"] * size[0], canvas["top"] * size[1],
284
+ )
285
+ if size[0] - crop[0] - crop[2] <= 1 or size[1] - crop[1] - crop[3] <= 1:
286
+ crop = None
287
+ visible = (size[0] - (crop[0] + crop[2])) if crop else size[0]
288
+ scale = topic_width / visible
289
+ images.append(_render_page(page, index, scale, request, output_dir, crop))
290
+ except Exception as error: # 单页失败只丢这一页,其余照常返回
291
+ skipped.append({"page": index, "reason": f"{type(error).__name__}: {error}"})
292
+ finally:
293
+ page.close()
294
+ return {"pageCount": page_count, "canvas": canvas, "images": images, "skipped": skipped}
295
+ finally:
296
+ document.close()
297
+
298
+
299
+ try:
300
+ response = {"ok": True, "result": main()}
301
+ except Exception as error: # Node 调用方把这条有界消息转成 PAGE_IMAGE_UNAVAILABLE
302
+ response = {"ok": False, "error": f"{type(error).__name__}: {error}"}
303
+
304
+ print(RESULT_BEGIN)
305
+ print(json.dumps(response, ensure_ascii=False))
306
+ print(RESULT_END)
307
+ if not response["ok"]:
308
+ raise SystemExit(1)