dsh-pdf-workbench 1.3.2 → 1.3.3

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 (53) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +199 -199
  3. package/client.js +5 -12
  4. package/docs/RELEASE.md +119 -119
  5. package/icon.svg +6 -6
  6. package/package.json +1 -1
  7. package/screenshots.json +8 -8
  8. package/src/client/host-ui-entry.js +11 -11
  9. package/src/client/react-jsx-runtime.cjs +21 -21
  10. package/src/client/viewer.js +80 -80
  11. package/tools/AGENTS.md +33 -33
  12. package/tools/README.md +138 -138
  13. package/tools/auto_chapters.py +122 -122
  14. package/tools/dsfile.mjs +198 -198
  15. package/tools/export_chapter.py +108 -108
  16. package/tools/export_page.py +91 -91
  17. package/tools/md2overlay.py +200 -200
  18. package/tools/md2tex.py +422 -422
  19. package/tools/node.cmd +3 -0
  20. package/tools/pdf_blocks.py +110 -110
  21. package/tools/pdf_fontsize.py +20 -20
  22. package/tools/pdf_merge.py +15 -15
  23. package/tools/pdf_pagesizes.py +8 -8
  24. package/tools/pdf_raster.py +21 -21
  25. package/tools/pdfkit.py +896 -896
  26. package/tools/py.cmd +3 -0
  27. package/tools/realign_overlay.py +248 -248
  28. package/tools/rebuild_overlay.py +55 -55
  29. package/tools/rename_chapters.py +93 -93
  30. package/tools//350/247/204/350/214/203/00_/345/205/261/345/220/214/347/272/246/345/256/232.md +142 -142
  31. package/tools//350/247/204/350/214/203/01_/346/226/207/346/234/254/346/217/220/345/217/226.md +204 -204
  32. package/tools//350/247/204/350/214/203/02_/347/255/224/347/226/221.md +61 -61
  33. package/tools//350/247/204/350/214/203/03_/344/271/240/351/242/230/350/247/243/347/255/224.md +77 -77
  34. package/tools//350/247/204/350/214/203/api/346/217/220/347/244/272/350/257/215_/346/217/220/345/217/226.md +11 -11
  35. package/vendor/cmaps/LICENSE.txt +36 -36
  36. package/vendor/fonts/excalifont/OFL.txt +98 -98
  37. package/vendor/fonts/zhhand/OFL.txt +99 -99
  38. package/vendor/host-ui.cjs +1719 -1719
  39. package/vendor/host-ui.css +799 -799
  40. package/vendor/pdf.min.mjs +28 -28
  41. package/vendor/pdf.worker.min.mjs +28 -28
  42. package/vendor/pdfjs-LICENSE.txt +177 -177
  43. package/vendor/rough/LICENSE +21 -21
  44. package/vendor/rough/rough.mjs +1 -1
  45. package/vendor/wasm/LICENSE_JBIG2 +196 -196
  46. package/vendor/wasm/LICENSE_OPENJPEG +39 -39
  47. package/vendor/wasm/LICENSE_PDFJS_JBIG2 +13 -13
  48. package/vendor/wasm/LICENSE_PDFJS_OPENJPEG +22 -22
  49. package/vendor/wasm/LICENSE_PDFJS_QCMS +19 -19
  50. package/vendor/wasm/LICENSE_QCMS +21 -21
  51. package/vendor/wasm/jbig2_nowasm_fallback.js +15 -15
  52. package/vendor/wasm/openjpeg_nowasm_fallback.js +17 -17
  53. package//345/256/211/350/243/205/344/270/216/345/210/206/345/217/221.md +1 -1
package/tools/pdfkit.py CHANGED
@@ -1,896 +1,896 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- """
4
- pdfkit.py —— 数学课本工作流的 PDF 处理小工具
5
-
6
- 依赖:poppler(pdftotext / pdftoppm / pdfinfo,已在 PATH)+ Pillow(校验缩略图与分带)
7
- 不联网、不写缓存目录以外的地方。
8
-
9
- 子命令
10
- info <pdf> 报告页数、页面尺寸、文字层状况、是否扫描版
11
- text <pdf> --out DIR [--pages 12-14] 逐页导出文字层 txt(定位用,非成品)
12
- render <pdf> --out DIR --pages 12-14 ... 逐页渲染 PNG,可横向分带;已存在则跳过
13
- sheet <pdf> --out FILE --pages 1-24 缩略图拼版(扫描版快速找页码用)
14
- find <pdf> 关键词 [关键词...] 在文字层里检索,返回命中页码
15
- verify <文件> [--tex] 格式自检:禁用结构 / $ 配对 / LaTeX 可编译
16
- """
17
- import argparse
18
- import json
19
- import os
20
- import re
21
- import shutil
22
- import subprocess
23
- import sys
24
- from pathlib import Path
25
-
26
- try:
27
- sys.stdout.reconfigure(encoding="utf-8", errors="replace")
28
- sys.stderr.reconfigure(encoding="utf-8", errors="replace")
29
- except Exception:
30
- pass
31
-
32
-
33
- # ---------------------------------------------------------------- 基础工具
34
-
35
- def die(msg, code=2):
36
- print(f"[pdfkit] 错误: {msg}", file=sys.stderr)
37
- sys.exit(code)
38
-
39
-
40
- def need(tool):
41
- if shutil.which(tool) is None:
42
- die(f"找不到 {tool},请确认 poppler 已加入 PATH")
43
-
44
-
45
- def run(cmd, **kw):
46
- return subprocess.run(
47
- [str(c) for c in cmd],
48
- capture_output=True, text=True, encoding="utf-8", errors="replace", **kw
49
- )
50
-
51
-
52
- def pdf_pages(pdf):
53
- need("pdfinfo")
54
- r = run(["pdfinfo", pdf])
55
- m = re.search(r"^Pages:\s+(\d+)", r.stdout or "", re.M)
56
- if not m:
57
- die(f"pdfinfo 读不到页数:{pdf}({r.returncode} {r.stderr[:200]})")
58
- return int(m.group(1))
59
-
60
-
61
- def parse_pages(spec, total):
62
- """'12-14,20' -> [12,13,14,20];空 -> 全部"""
63
- if not spec or not spec.strip():
64
- return list(range(1, total + 1))
65
- out = []
66
- for part in spec.split(","):
67
- part = part.strip()
68
- if not part:
69
- continue
70
- m = re.fullmatch(r"(\d+)\s*-\s*(\d*)", part)
71
- if m:
72
- a = int(m.group(1))
73
- b = int(m.group(2)) if m.group(2) else total
74
- if b < a:
75
- die(f"页码范围倒序: {part}")
76
- out.extend(range(a, b + 1))
77
- elif part.isdigit():
78
- out.append(int(part))
79
- else:
80
- die(f"看不懂的页码片段: {part!r}")
81
- pages = [p for p in dict.fromkeys(out) if 1 <= p <= total]
82
- if not pages:
83
- die(f"页码范围 {spec!r} 在 1-{total} 内没有任何有效页")
84
- return pages
85
-
86
-
87
- def whole_text(pdf):
88
- """整本文字层,按 \\f 切页。无文字层时返回 ['', '', ...]"""
89
- need("pdftotext")
90
- out = scratch("text") / "all.txt"
91
- run(["pdftotext", "-layout", "-enc", "UTF-8", pdf, out])
92
- raw = out.read_text(encoding="utf-8", errors="replace") if out.exists() else ""
93
- chunks = raw.split("\f")
94
- while chunks and not chunks[-1].strip():
95
- chunks.pop()
96
- return chunks
97
-
98
-
99
- def nospace_len(s):
100
- return len(re.sub(r"\s+", "", s or ""))
101
-
102
-
103
- def read_text_any(path):
104
- """容忍 UTF-8 / UTF-8-BOM / UTF-16(带 BOM) / GB18030 —— Windows 上重定向出来的文件常是 UTF-16"""
105
- raw = Path(path).read_bytes()
106
- if raw.startswith(b"\xff\xfe") or raw.startswith(b"\xfe\xff"):
107
- return raw.decode("utf-16", errors="replace")
108
- if raw.startswith(b"\xef\xbb\xbf"):
109
- return raw.decode("utf-8-sig", errors="replace")
110
- try:
111
- return raw.decode("utf-8")
112
- except UnicodeDecodeError:
113
- return raw.decode("gb18030", errors="replace")
114
-
115
-
116
- # 临时产物一律落在工作区内的缓存目录(沙箱下系统 %TEMP% 的清理会被拒绝),
117
- # 按进程号隔离,多个窗口并发跑同一个 PDF 也不会互相覆盖。
118
- CACHE_ROOT = Path(__file__).resolve().parent.parent / "缓存"
119
- SCRATCH = CACHE_ROOT / "_scratch"
120
-
121
-
122
- def scratch(*parts):
123
- d = SCRATCH.joinpath(f"run{os.getpid()}", *parts)
124
- d.mkdir(parents=True, exist_ok=True)
125
- return d
126
-
127
-
128
- def default_out(pdf, kind):
129
- """缓存按『书名/用途』分目录。多本书共用一个工作区时,靠这个避免 p0001.png 串书。"""
130
- stem = re.sub(r'[<>:"/\\|?*]', "_", Path(pdf).stem).strip() or "book"
131
- d = CACHE_ROOT / stem / kind
132
- d.mkdir(parents=True, exist_ok=True)
133
- return d
134
-
135
-
136
- def dir_size(p):
137
- p = Path(p)
138
- if p.is_file():
139
- return p.stat().st_size
140
- return sum(f.stat().st_size for f in p.rglob("*") if f.is_file())
141
-
142
-
143
- # ---------------------------------------------------------------- info
144
-
145
- def cmd_info(a):
146
- pdf = Path(a.pdf)
147
- if not pdf.exists():
148
- die(f"文件不存在: {pdf}")
149
- total = pdf_pages(pdf)
150
- r = run(["pdfinfo", pdf])
151
- meta = {}
152
- for line in (r.stdout or "").splitlines():
153
- if ":" in line:
154
- k, v = line.split(":", 1)
155
- meta[k.strip()] = v.strip()
156
- counts = [nospace_len(c) for c in whole_text(pdf)]
157
- counts += [0] * (total - len(counts))
158
- counts = counts[:total]
159
- med = sorted(counts)[len(counts) // 2] if counts else 0
160
- withtext = sum(1 for c in counts if c >= 30)
161
- is_scan = withtext < total * 0.5 or med < 30
162
- if is_scan:
163
- rec = "扫描/图片版:文字层不可用于转写。用 sheet 定位页码、render 出图后逐页读图转写。"
164
- elif med < 400:
165
- rec = "疑似带 OCR 文字层:文字层可用于关键词定位(find),转写仍以页面图为准。"
166
- else:
167
- rec = "文字版:可用 text/find 快速定位并粗读;公式仍以页面图为准做结构化转写。"
168
- print(json.dumps({
169
- "pdf": str(pdf),
170
- "pages": total,
171
- "page_size": meta.get("Page size", ""),
172
- "producer": meta.get("Producer", ""),
173
- "has_text_layer": not is_scan,
174
- "is_scan": is_scan,
175
- "median_chars_per_page": med,
176
- "pages_with_text": withtext,
177
- "chars_per_page_head": counts[:12],
178
- "recommendation": rec,
179
- }, ensure_ascii=False, indent=2))
180
-
181
-
182
- # ---------------------------------------------------------------- text
183
-
184
- def cmd_text(a):
185
- pdf = Path(a.pdf)
186
- total = pdf_pages(pdf)
187
- pages = parse_pages(a.pages, total)
188
- outdir = Path(a.out) if a.out else default_out(pdf, "txt")
189
- outdir.mkdir(parents=True, exist_ok=True)
190
- written = []
191
- for p in pages:
192
- dst = outdir / f"p{p:04d}.txt"
193
- if dst.exists() and not a.force:
194
- written.append(str(dst))
195
- continue
196
- r = run(["pdftotext", "-layout", "-enc", "UTF-8",
197
- "-f", p, "-l", p, pdf, dst])
198
- if r.returncode != 0 or not dst.exists():
199
- dst.write_text("", encoding="utf-8")
200
- written.append(str(dst))
201
- print(json.dumps({"ok": True, "pages": pages, "files": written},
202
- ensure_ascii=False, indent=2))
203
-
204
-
205
- # ---------------------------------------------------------------- render
206
-
207
- def cmd_render(a):
208
- need("pdftoppm")
209
- pdf = Path(a.pdf)
210
- total = pdf_pages(pdf)
211
- pages = parse_pages(a.pages, total)
212
- outdir = Path(a.out) if a.out else default_out(pdf, "pages")
213
- outdir.mkdir(parents=True, exist_ok=True)
214
- bands = max(1, a.bands)
215
- overlap = min(0.3, max(0.0, a.overlap))
216
-
217
- def targets_for(p):
218
- base = outdir / f"p{p:04d}"
219
- if bands == 1:
220
- return [outdir / f"p{p:04d}.png"]
221
- return [outdir / f"p{p:04d}-{i + 1}.png" for i in range(bands)]
222
-
223
- produced, skipped = [], []
224
- for p in pages:
225
- tg = targets_for(p)
226
- if all(t.exists() for t in tg) and not a.force:
227
- skipped.append(p)
228
- continue
229
- with_tmp = scratch("render")
230
- raw = with_tmp / f"raw_p{p:04d}"
231
- r = run(["pdftoppm", "-r", str(a.dpi), "-f", p, "-l", p,
232
- "-png", "-singlefile", pdf, raw])
233
- if r.returncode != 0 or not raw.with_suffix(".png").exists():
234
- die(f"第 {p} 页渲染失败: {(r.stderr or '')[:300]}")
235
- if bands == 1 and not a.gray:
236
- shutil.copyfile(raw.with_suffix(".png"), tg[0])
237
- produced.append(str(tg[0]))
238
- continue
239
- from PIL import Image
240
- im = Image.open(raw.with_suffix(".png"))
241
- if a.gray:
242
- im = im.convert("L")
243
- w, h = im.size
244
- if bands == 1:
245
- im.save(tg[0])
246
- produced.append(str(tg[0]))
247
- continue
248
- bh = -(-h // bands)
249
- ov = int(bh * overlap)
250
- for i in range(bands):
251
- top = max(0, i * bh - (ov if i else 0))
252
- bot = min(h, (i + 1) * bh + (ov if i < bands - 1 else 0))
253
- im.crop((0, top, w, bot)).save(tg[i])
254
- produced.append(str(tg[i]))
255
- print(json.dumps({
256
- "ok": True, "dpi": a.dpi, "bands": bands,
257
- "produced": produced, "skipped_existing": skipped,
258
- "note": "bands>1 时每页切成上下多带,按 -1/-2 顺序交给读图工具,接缝有重叠。",
259
- }, ensure_ascii=False, indent=2))
260
-
261
-
262
- # ---------------------------------------------------------------- sheet
263
-
264
- def cmd_sheet(a):
265
- need("pdftoppm")
266
- from PIL import Image, ImageDraw
267
- try:
268
- from PIL import ImageFont
269
- font = ImageFont.load_default(size=17)
270
- except Exception:
271
- font = None
272
- pdf = Path(a.pdf)
273
- total = pdf_pages(pdf)
274
- pages = parse_pages(a.pages, total)
275
- cols = max(1, a.cols)
276
- thumbs = []
277
- td = scratch("sheet")
278
- for p in pages:
279
- raw = td / f"p{p}"
280
- r = run(["pdftoppm", "-r", str(a.dpi), "-f", p, "-l", p,
281
- "-png", "-singlefile", pdf, raw])
282
- if r.returncode != 0 or not raw.with_suffix(".png").exists():
283
- die(f"第 {p} 页渲染失败: {(r.stderr or '')[:300]}")
284
- thumbs.append((p, Image.open(raw.with_suffix(".png")).convert("RGB").copy()))
285
- cw = max(im.width for _, im in thumbs)
286
- ch = max(im.height for _, im in thumbs)
287
- pad, lab = 8, 22
288
- rows = -(-len(thumbs) // cols)
289
- W = cols * (cw + pad) + pad
290
- H = rows * (ch + lab + pad) + pad
291
- sheet = Image.new("RGB", (W, H), "white")
292
- d = ImageDraw.Draw(sheet)
293
- for i, (p, im) in enumerate(thumbs):
294
- cx = pad + (i % cols) * (cw + pad)
295
- cy = pad + (i // cols) * (ch + lab + pad)
296
- d.rectangle([cx, cy, cx + cw, cy + lab], fill="#e8e8e8")
297
- d.text((cx + 4, cy + 3), f"p.{p}", fill="black", font=font)
298
- sheet.paste(im, (cx, cy + lab))
299
- out = Path(a.out) if a.out else default_out(pdf, "sheets")
300
- if out.suffix.lower() not in (".png", ".jpg", ".jpeg"):
301
- out.mkdir(parents=True, exist_ok=True)
302
- out = out / f"sheet_p{pages[0]:04d}-{pages[-1]:04d}.png"
303
- out.parent.mkdir(parents=True, exist_ok=True)
304
- sheet.save(out)
305
- print(json.dumps({
306
- "ok": True, "file": str(out), "pages": pages,
307
- "size": [W, H], "cell": [cw, ch],
308
- "note": "低分辨率拼版,只用于辨认页码与章节标题;公式细节务必再 render 高清图。",
309
- }, ensure_ascii=False, indent=2))
310
-
311
-
312
- # ---------------------------------------------------------------- find
313
-
314
- def cmd_find(a):
315
- pdf = Path(a.pdf)
316
- chunks = whole_text(pdf)
317
- if not any(c.strip() for c in chunks):
318
- die("这本 PDF 没有可用文字层(扫描版),find 无法检索;改用 sheet 缩略图定位页码。", 3)
319
- result = {}
320
- for kw in a.keywords:
321
- hits = []
322
- for i, c in enumerate(chunks, start=1):
323
- n = c.count(kw)
324
- if n:
325
- hits.append({"page": i, "count": n})
326
- result[kw] = hits
327
- print(json.dumps({"pdf": str(pdf), "hits": result,
328
- "note": "命中来自文字层,可能有 OCR 错字导致漏检;未命中不等于没有。"},
329
- ensure_ascii=False, indent=2))
330
- if a.context:
331
- print("\n--- 上下文 ---")
332
- for kw in a.keywords:
333
- for h in result[kw][:a.context]:
334
- c = chunks[h["page"] - 1]
335
- for line in c.splitlines():
336
- if kw in line:
337
- print(f"[p.{h['page']}] {line.strip()[:160]}")
338
-
339
-
340
- # ---------------------------------------------------------------- verify
341
-
342
- FORBIDDEN = [
343
- (r"(?<!\\)\\\[", "\\[ (行间公式必须用 $$…$$)"),
344
- (r"(?<!\\)\\\]", "\\] (行间公式必须用 $$…$$)"),
345
- (r"(?<!\\)\\\(", "\\("),
346
- (r"(?<!\\)\\\)", "\\)"),
347
- ]
348
- WARN_ENVS = ["equation", "align", "gather", "eqnarray", "displaymath", "multline", "math"]
349
-
350
-
351
- def math_segments(text):
352
- """粗切 $...$ / $$...$$,跳过 \\$ 转义"""
353
- disp, inline = [], []
354
- i, n = 0, len(text)
355
- while i < n:
356
- ch = text[i]
357
- if ch == "\\" and i + 1 < n:
358
- i += 2
359
- continue
360
- if text.startswith("$$", i):
361
- j = text.find("$$", i + 2)
362
- if j == -1:
363
- break
364
- disp.append(text[i + 2:j])
365
- i = j + 2
366
- continue
367
- if ch == "$":
368
- j = i + 1
369
- while j < n:
370
- if text[j] == "\\":
371
- j += 2
372
- continue
373
- if text[j] == "$":
374
- break
375
- j += 1
376
- if j >= n:
377
- break
378
- inline.append(text[i + 1:j])
379
- i = j + 1
380
- continue
381
- i += 1
382
- return disp, inline
383
-
384
-
385
- def cmd_verify(a):
386
- src = Path(a.file)
387
- if not src.exists():
388
- die(f"文件不存在: {src}")
389
- text = read_text_any(src)
390
- errors, warns = [], []
391
-
392
- for pat, name in FORBIDDEN:
393
- for m in re.finditer(pat, text):
394
- line = text.count("\n", 0, m.start()) + 1
395
- errors.append(f"第 {line} 行出现禁用结构 {name}")
396
-
397
- for env in WARN_ENVS:
398
- for m in re.finditer(r"\\begin\{" + env + r"\}", text):
399
- line = text.count("\n", 0, m.start()) + 1
400
- warns.append(f"第 {line} 行 \\begin{{{env}}}:建议改写为 $$…$$(课本转写统一用 $/$$)")
401
-
402
- # $ 配对(跳过 \$)
403
- i, n, single, dbl = 0, len(text), 0, 0
404
- while i < n:
405
- if text[i] == "\\":
406
- i += 2
407
- continue
408
- if text.startswith("$$", i):
409
- dbl += 1
410
- i += 2
411
- continue
412
- if text[i] == "$":
413
- single += 1
414
- i += 1
415
- if single % 2:
416
- errors.append(f"$ 未配对:单个 $ 出现 {single} 次(应为偶数),行内公式缺了收尾符")
417
- if dbl % 2:
418
- errors.append(f"$$ 未配对:$$ 出现 {dbl} 次(应为偶数)")
419
-
420
- disp, inline = math_segments(text)
421
- result = {
422
- "file": str(src),
423
- "ok": not errors,
424
- "errors": errors,
425
- "warnings": warns[:20],
426
- "math": {"display": len(disp), "inline": len(inline)},
427
- "size_chars": len(text),
428
- }
429
-
430
- if a.tex and (disp or inline) and not errors:
431
- need("xelatex")
432
- body = []
433
- for s in disp:
434
- body.append("\\[\n" + s.strip() + "\n\\]")
435
- for s in inline:
436
- body.append("$" + s.strip() + "$")
437
- tex = ("\\documentclass[12pt]{article}\n"
438
- "\\usepackage{amsmath,amssymb,amsfonts,bm}\n"
439
- "\\usepackage{ctex}\n\\pagestyle{empty}\n"
440
- "\\begin{document}\n" + "\n".join(body) + "\n\\end{document}\n")
441
- td = scratch("texverify")
442
- (td / "v.tex").write_text(tex, encoding="utf-8")
443
- env = os.environ.copy()
444
- env["TEXMFVAR"] = str(td / "tv")
445
- env["TEXMFCACHE"] = str(td / "tv")
446
- # 关键:cwd 切到目录、只传相对文件名。TeX 在 Windows 上处理含中文的
447
- # 命令行路径会按本地代码页解码,中文路径直接编译失败。
448
- r = run(["xelatex", "-interaction=nonstopmode", "-halt-on-error", "v.tex"],
449
- cwd=td, env=env, timeout=180)
450
- log = td / "v.log"
451
- logtext = read_text_any(log) if log.exists() else ""
452
- lerrs = [ln for ln in logtext.splitlines() if ln.startswith("! ")]
453
- ctx = []
454
- for ln in logtext.splitlines():
455
- if ln.startswith("l."):
456
- ctx.append(ln[:160])
457
- result["tex_compile"] = {
458
- "ok": r.returncode == 0 and not lerrs,
459
- "errors": (lerrs[:8] if lerrs else ([f"xelatex 返回码 {r.returncode}"] if r.returncode != 0 else [])),
460
- "lines": ctx[:8],
461
- "stderr_tail": (r.stderr or "")[-400:] if r.returncode != 0 else "",
462
- }
463
- if not result["tex_compile"]["ok"]:
464
- result["ok"] = False
465
-
466
- print(json.dumps(result, ensure_ascii=False, indent=2))
467
- sys.exit(0 if result["ok"] else 1)
468
-
469
-
470
- # ---------------------------------------------------------------- prune
471
-
472
- def cmd_prune(a):
473
- import time
474
- if not CACHE_ROOT.exists():
475
- print(json.dumps({"ok": True, "removed": [], "freed_bytes": 0,
476
- "remaining_bytes": 0, "note": "缓存目录还不存在"},
477
- ensure_ascii=False, indent=2))
478
- return
479
- now = time.time()
480
- entries = [p for p in CACHE_ROOT.iterdir() if p.name != "api_files.json"]
481
- if a.all:
482
- targets = entries
483
- elif a.days > 0:
484
- cutoff = now - a.days * 86400
485
- targets = [p for p in entries if p.stat().st_mtime < cutoff]
486
- else:
487
- targets = []
488
- freed = sum(dir_size(p) for p in targets)
489
- removed = []
490
- for p in targets:
491
- try:
492
- if p.is_dir():
493
- shutil.rmtree(p, ignore_errors=True)
494
- else:
495
- p.unlink(missing_ok=True)
496
- removed.append(p.name)
497
- except Exception:
498
- pass
499
- remaining = sum(dir_size(p) for p in CACHE_ROOT.iterdir() if p.name != "api_files.json")
500
- print(json.dumps({
501
- "ok": True,
502
- "removed": removed,
503
- "freed_mb": round(freed / 1048576, 2),
504
- "remaining_mb": round(remaining / 1048576, 2),
505
- "note": "days=0 只统计不删;--all 全清;缓存内容都是可重建的渲染图。",
506
- }, ensure_ascii=False, indent=2))
507
-
508
-
509
- # ---------------------------------------------------------------- split
510
-
511
- BOOK_DIR = Path(__file__).resolve().parent.parent / "分片"
512
-
513
-
514
- def split_ranges(spec, total):
515
- """'1-36,37-80' -> [(1,36),(37,80)]"""
516
- out = []
517
- for part in spec.split(","):
518
- part = part.strip()
519
- if not part:
520
- continue
521
- m = re.fullmatch(r"(\d+)\s*-\s*(\d+)", part)
522
- if m:
523
- a, b = int(m.group(1)), int(m.group(2))
524
- elif part.isdigit():
525
- a = b = int(part)
526
- else:
527
- die(f"看不懂的页范围: {part!r}")
528
- if not (1 <= a <= b <= total):
529
- die(f"页范围 {part} 超出本书 1-{total} 页")
530
- out.append((a, b))
531
- if not out:
532
- die("没有有效的页范围")
533
- return out
534
-
535
-
536
- def cmd_split(a):
537
- """按页范围切成一章一个文件,命名 <前缀>_cNN_p起-止[_章名].pdf。
538
- 产物落到 分片/<书名>/;已存在则跳过(加 --force 覆盖)。"""
539
- need("pdftocairo")
540
- pdf = Path(a.pdf)
541
- total = pdf_pages(pdf)
542
- groups = split_ranges(a.ranges, total)
543
- if a.titles:
544
- titles = [t.strip() for t in a.titles.split(",")]
545
- if len(titles) != len(groups):
546
- die(f"--titles 给了 {len(titles)} 个,页范围却有 {len(groups)} 个")
547
- else:
548
- titles = [""] * len(groups)
549
-
550
- outdir = Path(a.out) if a.out else (BOOK_DIR / re.sub(r'[<>:"/\\|?*]', "_", pdf.stem))
551
- outdir.mkdir(parents=True, exist_ok=True)
552
- prefix = a.prefix or pdf.stem
553
- made = []
554
- for i, ((s, e), title) in enumerate(zip(groups, titles), 1):
555
- name = f"{prefix}_c{i:02d}_p{s}-{e}" + (f"_{title}" if title else "") + ".pdf"
556
- dst = outdir / name
557
- if dst.exists() and not a.force:
558
- made.append({"file": str(dst), "from": s, "to": e, "skipped": "已存在"})
559
- continue
560
- # pdftocairo 在 Windows 上无法接受「含中文的绝对输出路径」:
561
- # 切到目标目录 + 纯 ASCII 相对文件名就正常,最后再用 Python 改名成中文。
562
- tmpname = f"__part{i:03d}.pdf"
563
- tmp = outdir / tmpname
564
- r = run(["pdftocairo", "-pdf", "-f", s, "-l", e, pdf, tmpname], cwd=outdir)
565
- if r.returncode != 0 or not tmp.exists():
566
- die(f"第 {i} 段 ({s}-{e}) 拆分失败: {(r.stderr or '')[:300]}")
567
- os.replace(tmp, dst)
568
- made.append({"file": str(dst), "from": s, "to": e,
569
- "pages": pdf_pages(dst), "expect": e - s + 1})
570
- bad = [m for m in made if m.get("pages") and m["pages"] != m["expect"]]
571
- print(json.dumps({
572
- "ok": not bad, "source": str(pdf), "total_pages": total,
573
- "outdir": str(outdir), "chunks": made,
574
- "note": "命名已带页码,resolve 可直接用;页数与预期不符的会列在上面。",
575
- }, ensure_ascii=False, indent=2))
576
- if bad:
577
- sys.exit(1)
578
-
579
-
580
- # ---------------------------------------------------------------- resolve
581
-
582
- RANGE_RE = re.compile(r"(?:^|[_\-\s((]|(?<=p))(\d+)\s*[-\u2013\u2014~]\s*(\d+)(?!\d)")
583
-
584
-
585
- def cmd_resolve(a):
586
- """把「书第 N 页」解析成「哪个分片文件 + 片内第几页」。
587
- 页码范围从文件名里的 _A-B 推断(A 为 0 视为 0 基,即从第 1 页算起)。"""
588
- d = Path(a.dir)
589
- if not d.is_dir():
590
- die(f"不是目录: {d}")
591
- pdfs = sorted(p for p in d.rglob("*.pdf") if p.is_file())
592
- if not pdfs:
593
- die(f"目录里没有 PDF: {d}")
594
-
595
- items = []
596
- for f in pdfs:
597
- m = RANGE_RE.search(f.stem)
598
- try:
599
- npages = pdf_pages(f)
600
- except SystemExit:
601
- npages = None
602
- if m:
603
- s, e = int(m.group(1)), int(m.group(2))
604
- start, end = (1, e) if s == 0 else (s, e)
605
- items.append({"name": f.name, "file": str(f), "from": start, "to": end,
606
- "declared_pages": end - start + 1, "actual_pages": npages})
607
- else:
608
- items.append({"name": f.name, "file": str(f), "from": None, "to": None,
609
- "actual_pages": npages})
610
-
611
- ranged = sorted([i for i in items if i["from"]], key=lambda x: x["from"])
612
- no_range = [i["name"] for i in items if not i["from"]]
613
- issues = []
614
- for prev, cur in zip(ranged, ranged[1:]):
615
- if cur["from"] > prev["to"] + 1:
616
- issues.append(f"缺页:{prev['to'] + 1}-{cur['from'] - 1} 无分片覆盖")
617
- elif cur["from"] <= prev["to"]:
618
- issues.append(f"重叠:{prev['name']} 与 {cur['name']}")
619
- for i in ranged:
620
- if i["actual_pages"] and i["actual_pages"] != i["declared_pages"]:
621
- issues.append(f"页数不符:{i['name']} 声明 {i['declared_pages']} 页 / 实际 {i['actual_pages']} 页")
622
-
623
- out = {"dir": str(d), "chunks": len(pdfs), "ranged": ranged,
624
- "no_range": no_range, "issues": issues}
625
- if a.page:
626
- hit = next((i for i in ranged if i["from"] <= a.page <= i["to"]), None)
627
- out["page"] = a.page
628
- if hit:
629
- local = a.page - hit["from"] + 1
630
- out["result"] = {"file": hit["file"], "name": hit["name"], "local_page": local,
631
- "chunk_range": [hit["from"], hit["to"]]}
632
- if hit["actual_pages"] and not (1 <= local <= hit["actual_pages"]):
633
- out["warning"] = f"片内第 {local} 页超出该文件实际页数 {hit['actual_pages']}"
634
- else:
635
- out["result"] = None
636
- out["error"] = f"第 {a.page} 页没有被任何分片覆盖"
637
- print(json.dumps(out, ensure_ascii=False, indent=2))
638
- if out.get("error"):
639
- sys.exit(1)
640
-
641
-
642
- # ---------------------------------------------------------------- lookup
643
-
644
- BOOKS_SPLIT = Path(__file__).resolve().parent.parent / "分片"
645
- BOOKS_FULL = Path(__file__).resolve().parent.parent / "书库"
646
- SPLIT_MARK = "拆分后常用课本" # 全本库会递归看到它,检索时要排除
647
-
648
- _CN = {"零": 0, "〇": 0, "一": 1, "二": 2, "两": 2, "三": 3, "四": 4,
649
- "五": 5, "六": 6, "七": 7, "八": 8, "九": 9}
650
-
651
-
652
- def cn2int(s):
653
- """'四' -> 4, '十二' -> 12, '4' -> 4, 'XIII' -> 13"""
654
- s = s.strip()
655
- if s.isdigit():
656
- return int(s)
657
- u = s.upper()
658
- if re.fullmatch(r"[IVXLC]+", u):
659
- vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100}
660
- total, prev = 0, 0
661
- for ch in reversed(u):
662
- v = vals[ch]
663
- total = total - v if v < prev else total + v
664
- prev = max(prev, v)
665
- return total
666
- if "十" in s:
667
- a, _, b = s.partition("十")
668
- tens = _CN.get(a, 1) if a else 1
669
- ones = _CN.get(b, 0) if b else 0
670
- return tens * 10 + ones
671
- return _CN.get(s)
672
-
673
-
674
- def _norm(s):
675
- return re.sub(r"[\s_\-()()【】\[\].,、·]+", "", s.lower())
676
-
677
-
678
- def _chunk_range(f):
679
- m = RANGE_RE.search(f.stem)
680
- if not m:
681
- return None, None
682
- s, e = int(m.group(1)), int(m.group(2))
683
- return (1, e) if s == 0 else (s, e)
684
-
685
-
686
- def _book_chunks(d):
687
- out = []
688
- for f in sorted(Path(d).glob("*.pdf")):
689
- s, e = _chunk_range(f)
690
- code = chapter = label = None
691
- m = re.search(r"_(c\d{2})_(.+?)(?:_p\d+-\d+)?$", f.stem)
692
- if m:
693
- code = m.group(1)
694
- label = m.group(2)
695
- cm = re.search(r"第([零〇一二三四五六七八九十]{1,3})章", label)
696
- if cm:
697
- chapter = cn2int(cm.group(1))
698
- elif code in ("c00", "c99"):
699
- chapter = 0 if code == "c00" else 99
700
- out.append({"name": f.name, "file": str(f), "from": s, "to": e,
701
- "code": code, "chapter": chapter, "label": label,
702
- "pages": pdf_pages(f)})
703
- return out
704
-
705
-
706
- def cmd_lookup(a):
707
- """先查 分片(拆分后的常用课本),查不到再查 书库(全本)。"""
708
- kws = a.words or []
709
-
710
- def hit(name):
711
- n = _norm(name)
712
- return all(_norm(k) in n for k in kws)
713
-
714
- split_books, seen = [], set()
715
- if BOOKS_SPLIT.is_dir():
716
- for d in sorted(p for p in BOOKS_SPLIT.iterdir() if p.is_dir()):
717
- if not kws or hit(d.name):
718
- split_books.append(d); seen.add(str(d))
719
- for f in sorted(BOOKS_SPLIT.rglob("*.pdf")):
720
- if kws and hit(f.name) and str(f.parent) not in seen:
721
- split_books.append(f.parent); seen.add(str(f.parent))
722
-
723
- result = {"query": " ".join(kws), "split_root": str(BOOKS_SPLIT),
724
- "split_books": [], "full_books": [], "advice": ""}
725
- for d in split_books[:4]:
726
- chunks = _book_chunks(d)
727
- ranged = sorted([c for c in chunks if c["from"]], key=lambda c: c["from"])
728
- issues = []
729
- for prev, cur in zip(ranged, ranged[1:]):
730
- if cur["from"] > prev["to"] + 1:
731
- issues.append(f"缺页 {prev['to'] + 1}-{cur['from'] - 1}")
732
- elif cur["from"] <= prev["to"]:
733
- issues.append(f"重叠 {prev['name']} / {cur['name']}")
734
- no_range = [c["name"] for c in chunks if not c["from"]]
735
- result["split_books"].append({
736
- "book": d.name, "dir": str(d), "chunks": len(chunks),
737
- "ranged": ranged, "all": chunks, "no_range": no_range, "issues": issues,
738
- })
739
-
740
- if not split_books and BOOKS_FULL.is_dir():
741
- for f in sorted(BOOKS_FULL.rglob("*.pdf")):
742
- if SPLIT_MARK in str(f):
743
- continue
744
- if hit(f.name):
745
- result["full_books"].append({"name": f.name, "file": str(f),
746
- "pages": pdf_pages(f)})
747
- if len(result["full_books"]) >= 10:
748
- break
749
-
750
- if a.chapter is not None:
751
- n = cn2int(str(a.chapter)) if not str(a.chapter).isdigit() else int(a.chapter)
752
- res = {"chapter": a.chapter, "chapter_num": n}
753
- if n is None:
754
- res["error"] = f"看不懂的章号:{a.chapter}(给 4 或 四)"
755
- else:
756
- hits = []
757
- for b in result["split_books"]:
758
- chunks_all = b.get("all") or b.get("ranged", [])
759
- for c in chunks_all:
760
- if c.get("chapter") == n:
761
- hits.append((b, c, "chapter"))
762
- break
763
- if not hits:
764
- for b in result["split_books"]:
765
- for c in (b.get("all") or b.get("ranged", [])):
766
- if c.get("code") == f"c{n:02d}":
767
- hits.append((b, c, "code"))
768
- break
769
- if len(hits) == 1:
770
- b, c, _ = hits[0]
771
- res["result"] = {"book": b["book"], "file": c["file"], "name": c["name"],
772
- "pages": c["pages"],
773
- "chunk_range": [c["from"], c["to"]] if c["from"] else None}
774
- elif len(hits) > 1:
775
- res["result"] = None
776
- res["candidates"] = [{"book": b["book"], "name": c["name"], "file": c["file"]}
777
- for b, c, _ in hits]
778
- res["error"] = (f"{len(hits)} 本书都命中,无法确定是哪本;"
779
- "让用户补一个能区分的词(如「白皮书」「第四版」)。")
780
- else:
781
- res["result"] = None
782
- res["error"] = ("分片里没有这一章。可能这本还没按章重命名"
783
- "(看 split_books 里各片的 code/chapter 字段)。")
784
- result["chapter_lookup"] = res
785
-
786
- if a.page:
787
- target = next((b for b in result["split_books"] if b["ranged"]), None)
788
- result["page"] = a.page
789
- if target:
790
- c = next((x for x in target["ranged"] if x["from"] <= a.page <= x["to"]), None)
791
- if c:
792
- result["result"] = {"book": target["book"], "file": c["file"],
793
- "name": c["name"], "local_page": a.page - c["from"] + 1,
794
- "chunk_range": [c["from"], c["to"]]}
795
- else:
796
- result["result"] = None
797
- result["error"] = f"第 {a.page} 页没被这本的分片覆盖(见 issues)"
798
- elif result["split_books"]:
799
- result["result"] = None
800
- result["error"] = "这本的分片文件名里没有页码(章节式命名),无法按原书页码定位;改用章名,或先看该章首页的印刷页码。"
801
- else:
802
- result["result"] = None
803
- result["error"] = "分片库里没有匹配的书,见 full_books:只有全本,需要先 split。"
804
-
805
- if result["split_books"]:
806
- result["advice"] = "优先用 split_books:这些是已拆好的常用课本。"
807
- elif result["full_books"]:
808
- result["advice"] = "分片库没有,退回 full_books(全本);要按章工作就先 split 这本。"
809
- else:
810
- result["advice"] = "两个库都没有匹配;换个关键词(作者、书名片段)再试。"
811
-
812
- print(json.dumps(result, ensure_ascii=False, indent=2))
813
-
814
-
815
- # ---------------------------------------------------------------- main
816
-
817
- def main():
818
- ap = argparse.ArgumentParser(description="数学课本工作流 PDF 工具")
819
- sub = ap.add_subparsers(dest="cmd", required=True)
820
-
821
- p = sub.add_parser("info")
822
- p.add_argument("pdf")
823
- p.set_defaults(fn=cmd_info)
824
-
825
- p = sub.add_parser("text")
826
- p.add_argument("pdf")
827
- p.add_argument("--out", default="")
828
- p.add_argument("--pages", default="")
829
- p.add_argument("--force", action="store_true")
830
- p.set_defaults(fn=cmd_text)
831
-
832
- p = sub.add_parser("render")
833
- p.add_argument("pdf")
834
- p.add_argument("--out", default="")
835
- p.add_argument("--pages", default="")
836
- p.add_argument("--dpi", type=int, default=200)
837
- p.add_argument("--bands", type=int, default=1)
838
- p.add_argument("--overlap", type=float, default=0.06)
839
- p.add_argument("--gray", action="store_true")
840
- p.add_argument("--force", action="store_true")
841
- p.set_defaults(fn=cmd_render)
842
-
843
- p = sub.add_parser("sheet")
844
- p.add_argument("pdf")
845
- p.add_argument("--out", default="")
846
- p.add_argument("--pages", default="")
847
- p.add_argument("--cols", type=int, default=4)
848
- p.add_argument("--dpi", type=int, default=70)
849
- p.set_defaults(fn=cmd_sheet)
850
-
851
- p = sub.add_parser("find")
852
- p.add_argument("pdf")
853
- p.add_argument("keywords", nargs="+")
854
- p.add_argument("--context", type=int, default=0)
855
- p.set_defaults(fn=cmd_find)
856
-
857
- p = sub.add_parser("verify")
858
- p.add_argument("file")
859
- p.add_argument("--tex", action="store_true")
860
- p.set_defaults(fn=cmd_verify)
861
-
862
- p = sub.add_parser("prune")
863
- p.add_argument("--days", type=int, default=0, help="删掉超过 N 天没动过的缓存;0 表示只统计")
864
- p.add_argument("--all", action="store_true", help="删掉全部缓存(api_files.json 除外)")
865
- p.set_defaults(fn=cmd_prune)
866
-
867
- p = sub.add_parser("resolve")
868
- p.add_argument("dir", help="装分片 PDF 的目录")
869
- p.add_argument("--page", type=int, default=0, help="书的页码,解析成「哪个分片 + 片内第几页」")
870
- p.set_defaults(fn=cmd_resolve)
871
-
872
- p = sub.add_parser("split")
873
- p.add_argument("pdf")
874
- p.add_argument("--ranges", required=True, help="如 1-36,37-80(一章一段)")
875
- p.add_argument("--out", default="")
876
- p.add_argument("--prefix", default="", help="文件名前缀,默认用原书名")
877
- p.add_argument("--titles", default="", help="章名,逗号分隔,与页范围一一对应")
878
- p.add_argument("--force", action="store_true")
879
- p.set_defaults(fn=cmd_split)
880
-
881
- p = sub.add_parser("lookup")
882
- p.add_argument("words", nargs="*", help="书名 / 作者关键词,可多个(同时满足)")
883
- p.add_argument("--page", type=int, default=0, help="顺带解析原书页码")
884
- p.add_argument("--chapter", default=None, help="按章号取,如 4 或 四")
885
- p.set_defaults(fn=cmd_lookup)
886
-
887
- a = ap.parse_args()
888
- try:
889
- a.fn(a)
890
- finally:
891
- # 每次运行结束清掉本次的临时目录,避免缓存里堆一堆 run<pid>
892
- shutil.rmtree(SCRATCH / f"run{os.getpid()}", ignore_errors=True)
893
-
894
-
895
- if __name__ == "__main__":
896
- main()
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ pdfkit.py —— 数学课本工作流的 PDF 处理小工具
5
+
6
+ 依赖:poppler(pdftotext / pdftoppm / pdfinfo,已在 PATH)+ Pillow(校验缩略图与分带)
7
+ 不联网、不写缓存目录以外的地方。
8
+
9
+ 子命令
10
+ info <pdf> 报告页数、页面尺寸、文字层状况、是否扫描版
11
+ text <pdf> --out DIR [--pages 12-14] 逐页导出文字层 txt(定位用,非成品)
12
+ render <pdf> --out DIR --pages 12-14 ... 逐页渲染 PNG,可横向分带;已存在则跳过
13
+ sheet <pdf> --out FILE --pages 1-24 缩略图拼版(扫描版快速找页码用)
14
+ find <pdf> 关键词 [关键词...] 在文字层里检索,返回命中页码
15
+ verify <文件> [--tex] 格式自检:禁用结构 / $ 配对 / LaTeX 可编译
16
+ """
17
+ import argparse
18
+ import json
19
+ import os
20
+ import re
21
+ import shutil
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ try:
27
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
28
+ sys.stderr.reconfigure(encoding="utf-8", errors="replace")
29
+ except Exception:
30
+ pass
31
+
32
+
33
+ # ---------------------------------------------------------------- 基础工具
34
+
35
+ def die(msg, code=2):
36
+ print(f"[pdfkit] 错误: {msg}", file=sys.stderr)
37
+ sys.exit(code)
38
+
39
+
40
+ def need(tool):
41
+ if shutil.which(tool) is None:
42
+ die(f"找不到 {tool},请确认 poppler 已加入 PATH")
43
+
44
+
45
+ def run(cmd, **kw):
46
+ return subprocess.run(
47
+ [str(c) for c in cmd],
48
+ capture_output=True, text=True, encoding="utf-8", errors="replace", **kw
49
+ )
50
+
51
+
52
+ def pdf_pages(pdf):
53
+ need("pdfinfo")
54
+ r = run(["pdfinfo", pdf])
55
+ m = re.search(r"^Pages:\s+(\d+)", r.stdout or "", re.M)
56
+ if not m:
57
+ die(f"pdfinfo 读不到页数:{pdf}({r.returncode} {r.stderr[:200]})")
58
+ return int(m.group(1))
59
+
60
+
61
+ def parse_pages(spec, total):
62
+ """'12-14,20' -> [12,13,14,20];空 -> 全部"""
63
+ if not spec or not spec.strip():
64
+ return list(range(1, total + 1))
65
+ out = []
66
+ for part in spec.split(","):
67
+ part = part.strip()
68
+ if not part:
69
+ continue
70
+ m = re.fullmatch(r"(\d+)\s*-\s*(\d*)", part)
71
+ if m:
72
+ a = int(m.group(1))
73
+ b = int(m.group(2)) if m.group(2) else total
74
+ if b < a:
75
+ die(f"页码范围倒序: {part}")
76
+ out.extend(range(a, b + 1))
77
+ elif part.isdigit():
78
+ out.append(int(part))
79
+ else:
80
+ die(f"看不懂的页码片段: {part!r}")
81
+ pages = [p for p in dict.fromkeys(out) if 1 <= p <= total]
82
+ if not pages:
83
+ die(f"页码范围 {spec!r} 在 1-{total} 内没有任何有效页")
84
+ return pages
85
+
86
+
87
+ def whole_text(pdf):
88
+ """整本文字层,按 \\f 切页。无文字层时返回 ['', '', ...]"""
89
+ need("pdftotext")
90
+ out = scratch("text") / "all.txt"
91
+ run(["pdftotext", "-layout", "-enc", "UTF-8", pdf, out])
92
+ raw = out.read_text(encoding="utf-8", errors="replace") if out.exists() else ""
93
+ chunks = raw.split("\f")
94
+ while chunks and not chunks[-1].strip():
95
+ chunks.pop()
96
+ return chunks
97
+
98
+
99
+ def nospace_len(s):
100
+ return len(re.sub(r"\s+", "", s or ""))
101
+
102
+
103
+ def read_text_any(path):
104
+ """容忍 UTF-8 / UTF-8-BOM / UTF-16(带 BOM) / GB18030 —— Windows 上重定向出来的文件常是 UTF-16"""
105
+ raw = Path(path).read_bytes()
106
+ if raw.startswith(b"\xff\xfe") or raw.startswith(b"\xfe\xff"):
107
+ return raw.decode("utf-16", errors="replace")
108
+ if raw.startswith(b"\xef\xbb\xbf"):
109
+ return raw.decode("utf-8-sig", errors="replace")
110
+ try:
111
+ return raw.decode("utf-8")
112
+ except UnicodeDecodeError:
113
+ return raw.decode("gb18030", errors="replace")
114
+
115
+
116
+ # 临时产物一律落在工作区内的缓存目录(沙箱下系统 %TEMP% 的清理会被拒绝),
117
+ # 按进程号隔离,多个窗口并发跑同一个 PDF 也不会互相覆盖。
118
+ CACHE_ROOT = Path(__file__).resolve().parent.parent / "缓存"
119
+ SCRATCH = CACHE_ROOT / "_scratch"
120
+
121
+
122
+ def scratch(*parts):
123
+ d = SCRATCH.joinpath(f"run{os.getpid()}", *parts)
124
+ d.mkdir(parents=True, exist_ok=True)
125
+ return d
126
+
127
+
128
+ def default_out(pdf, kind):
129
+ """缓存按『书名/用途』分目录。多本书共用一个工作区时,靠这个避免 p0001.png 串书。"""
130
+ stem = re.sub(r'[<>:"/\\|?*]', "_", Path(pdf).stem).strip() or "book"
131
+ d = CACHE_ROOT / stem / kind
132
+ d.mkdir(parents=True, exist_ok=True)
133
+ return d
134
+
135
+
136
+ def dir_size(p):
137
+ p = Path(p)
138
+ if p.is_file():
139
+ return p.stat().st_size
140
+ return sum(f.stat().st_size for f in p.rglob("*") if f.is_file())
141
+
142
+
143
+ # ---------------------------------------------------------------- info
144
+
145
+ def cmd_info(a):
146
+ pdf = Path(a.pdf)
147
+ if not pdf.exists():
148
+ die(f"文件不存在: {pdf}")
149
+ total = pdf_pages(pdf)
150
+ r = run(["pdfinfo", pdf])
151
+ meta = {}
152
+ for line in (r.stdout or "").splitlines():
153
+ if ":" in line:
154
+ k, v = line.split(":", 1)
155
+ meta[k.strip()] = v.strip()
156
+ counts = [nospace_len(c) for c in whole_text(pdf)]
157
+ counts += [0] * (total - len(counts))
158
+ counts = counts[:total]
159
+ med = sorted(counts)[len(counts) // 2] if counts else 0
160
+ withtext = sum(1 for c in counts if c >= 30)
161
+ is_scan = withtext < total * 0.5 or med < 30
162
+ if is_scan:
163
+ rec = "扫描/图片版:文字层不可用于转写。用 sheet 定位页码、render 出图后逐页读图转写。"
164
+ elif med < 400:
165
+ rec = "疑似带 OCR 文字层:文字层可用于关键词定位(find),转写仍以页面图为准。"
166
+ else:
167
+ rec = "文字版:可用 text/find 快速定位并粗读;公式仍以页面图为准做结构化转写。"
168
+ print(json.dumps({
169
+ "pdf": str(pdf),
170
+ "pages": total,
171
+ "page_size": meta.get("Page size", ""),
172
+ "producer": meta.get("Producer", ""),
173
+ "has_text_layer": not is_scan,
174
+ "is_scan": is_scan,
175
+ "median_chars_per_page": med,
176
+ "pages_with_text": withtext,
177
+ "chars_per_page_head": counts[:12],
178
+ "recommendation": rec,
179
+ }, ensure_ascii=False, indent=2))
180
+
181
+
182
+ # ---------------------------------------------------------------- text
183
+
184
+ def cmd_text(a):
185
+ pdf = Path(a.pdf)
186
+ total = pdf_pages(pdf)
187
+ pages = parse_pages(a.pages, total)
188
+ outdir = Path(a.out) if a.out else default_out(pdf, "txt")
189
+ outdir.mkdir(parents=True, exist_ok=True)
190
+ written = []
191
+ for p in pages:
192
+ dst = outdir / f"p{p:04d}.txt"
193
+ if dst.exists() and not a.force:
194
+ written.append(str(dst))
195
+ continue
196
+ r = run(["pdftotext", "-layout", "-enc", "UTF-8",
197
+ "-f", p, "-l", p, pdf, dst])
198
+ if r.returncode != 0 or not dst.exists():
199
+ dst.write_text("", encoding="utf-8")
200
+ written.append(str(dst))
201
+ print(json.dumps({"ok": True, "pages": pages, "files": written},
202
+ ensure_ascii=False, indent=2))
203
+
204
+
205
+ # ---------------------------------------------------------------- render
206
+
207
+ def cmd_render(a):
208
+ need("pdftoppm")
209
+ pdf = Path(a.pdf)
210
+ total = pdf_pages(pdf)
211
+ pages = parse_pages(a.pages, total)
212
+ outdir = Path(a.out) if a.out else default_out(pdf, "pages")
213
+ outdir.mkdir(parents=True, exist_ok=True)
214
+ bands = max(1, a.bands)
215
+ overlap = min(0.3, max(0.0, a.overlap))
216
+
217
+ def targets_for(p):
218
+ base = outdir / f"p{p:04d}"
219
+ if bands == 1:
220
+ return [outdir / f"p{p:04d}.png"]
221
+ return [outdir / f"p{p:04d}-{i + 1}.png" for i in range(bands)]
222
+
223
+ produced, skipped = [], []
224
+ for p in pages:
225
+ tg = targets_for(p)
226
+ if all(t.exists() for t in tg) and not a.force:
227
+ skipped.append(p)
228
+ continue
229
+ with_tmp = scratch("render")
230
+ raw = with_tmp / f"raw_p{p:04d}"
231
+ r = run(["pdftoppm", "-r", str(a.dpi), "-f", p, "-l", p,
232
+ "-png", "-singlefile", pdf, raw])
233
+ if r.returncode != 0 or not raw.with_suffix(".png").exists():
234
+ die(f"第 {p} 页渲染失败: {(r.stderr or '')[:300]}")
235
+ if bands == 1 and not a.gray:
236
+ shutil.copyfile(raw.with_suffix(".png"), tg[0])
237
+ produced.append(str(tg[0]))
238
+ continue
239
+ from PIL import Image
240
+ im = Image.open(raw.with_suffix(".png"))
241
+ if a.gray:
242
+ im = im.convert("L")
243
+ w, h = im.size
244
+ if bands == 1:
245
+ im.save(tg[0])
246
+ produced.append(str(tg[0]))
247
+ continue
248
+ bh = -(-h // bands)
249
+ ov = int(bh * overlap)
250
+ for i in range(bands):
251
+ top = max(0, i * bh - (ov if i else 0))
252
+ bot = min(h, (i + 1) * bh + (ov if i < bands - 1 else 0))
253
+ im.crop((0, top, w, bot)).save(tg[i])
254
+ produced.append(str(tg[i]))
255
+ print(json.dumps({
256
+ "ok": True, "dpi": a.dpi, "bands": bands,
257
+ "produced": produced, "skipped_existing": skipped,
258
+ "note": "bands>1 时每页切成上下多带,按 -1/-2 顺序交给读图工具,接缝有重叠。",
259
+ }, ensure_ascii=False, indent=2))
260
+
261
+
262
+ # ---------------------------------------------------------------- sheet
263
+
264
+ def cmd_sheet(a):
265
+ need("pdftoppm")
266
+ from PIL import Image, ImageDraw
267
+ try:
268
+ from PIL import ImageFont
269
+ font = ImageFont.load_default(size=17)
270
+ except Exception:
271
+ font = None
272
+ pdf = Path(a.pdf)
273
+ total = pdf_pages(pdf)
274
+ pages = parse_pages(a.pages, total)
275
+ cols = max(1, a.cols)
276
+ thumbs = []
277
+ td = scratch("sheet")
278
+ for p in pages:
279
+ raw = td / f"p{p}"
280
+ r = run(["pdftoppm", "-r", str(a.dpi), "-f", p, "-l", p,
281
+ "-png", "-singlefile", pdf, raw])
282
+ if r.returncode != 0 or not raw.with_suffix(".png").exists():
283
+ die(f"第 {p} 页渲染失败: {(r.stderr or '')[:300]}")
284
+ thumbs.append((p, Image.open(raw.with_suffix(".png")).convert("RGB").copy()))
285
+ cw = max(im.width for _, im in thumbs)
286
+ ch = max(im.height for _, im in thumbs)
287
+ pad, lab = 8, 22
288
+ rows = -(-len(thumbs) // cols)
289
+ W = cols * (cw + pad) + pad
290
+ H = rows * (ch + lab + pad) + pad
291
+ sheet = Image.new("RGB", (W, H), "white")
292
+ d = ImageDraw.Draw(sheet)
293
+ for i, (p, im) in enumerate(thumbs):
294
+ cx = pad + (i % cols) * (cw + pad)
295
+ cy = pad + (i // cols) * (ch + lab + pad)
296
+ d.rectangle([cx, cy, cx + cw, cy + lab], fill="#e8e8e8")
297
+ d.text((cx + 4, cy + 3), f"p.{p}", fill="black", font=font)
298
+ sheet.paste(im, (cx, cy + lab))
299
+ out = Path(a.out) if a.out else default_out(pdf, "sheets")
300
+ if out.suffix.lower() not in (".png", ".jpg", ".jpeg"):
301
+ out.mkdir(parents=True, exist_ok=True)
302
+ out = out / f"sheet_p{pages[0]:04d}-{pages[-1]:04d}.png"
303
+ out.parent.mkdir(parents=True, exist_ok=True)
304
+ sheet.save(out)
305
+ print(json.dumps({
306
+ "ok": True, "file": str(out), "pages": pages,
307
+ "size": [W, H], "cell": [cw, ch],
308
+ "note": "低分辨率拼版,只用于辨认页码与章节标题;公式细节务必再 render 高清图。",
309
+ }, ensure_ascii=False, indent=2))
310
+
311
+
312
+ # ---------------------------------------------------------------- find
313
+
314
+ def cmd_find(a):
315
+ pdf = Path(a.pdf)
316
+ chunks = whole_text(pdf)
317
+ if not any(c.strip() for c in chunks):
318
+ die("这本 PDF 没有可用文字层(扫描版),find 无法检索;改用 sheet 缩略图定位页码。", 3)
319
+ result = {}
320
+ for kw in a.keywords:
321
+ hits = []
322
+ for i, c in enumerate(chunks, start=1):
323
+ n = c.count(kw)
324
+ if n:
325
+ hits.append({"page": i, "count": n})
326
+ result[kw] = hits
327
+ print(json.dumps({"pdf": str(pdf), "hits": result,
328
+ "note": "命中来自文字层,可能有 OCR 错字导致漏检;未命中不等于没有。"},
329
+ ensure_ascii=False, indent=2))
330
+ if a.context:
331
+ print("\n--- 上下文 ---")
332
+ for kw in a.keywords:
333
+ for h in result[kw][:a.context]:
334
+ c = chunks[h["page"] - 1]
335
+ for line in c.splitlines():
336
+ if kw in line:
337
+ print(f"[p.{h['page']}] {line.strip()[:160]}")
338
+
339
+
340
+ # ---------------------------------------------------------------- verify
341
+
342
+ FORBIDDEN = [
343
+ (r"(?<!\\)\\\[", "\\[ (行间公式必须用 $$…$$)"),
344
+ (r"(?<!\\)\\\]", "\\] (行间公式必须用 $$…$$)"),
345
+ (r"(?<!\\)\\\(", "\\("),
346
+ (r"(?<!\\)\\\)", "\\)"),
347
+ ]
348
+ WARN_ENVS = ["equation", "align", "gather", "eqnarray", "displaymath", "multline", "math"]
349
+
350
+
351
+ def math_segments(text):
352
+ """粗切 $...$ / $$...$$,跳过 \\$ 转义"""
353
+ disp, inline = [], []
354
+ i, n = 0, len(text)
355
+ while i < n:
356
+ ch = text[i]
357
+ if ch == "\\" and i + 1 < n:
358
+ i += 2
359
+ continue
360
+ if text.startswith("$$", i):
361
+ j = text.find("$$", i + 2)
362
+ if j == -1:
363
+ break
364
+ disp.append(text[i + 2:j])
365
+ i = j + 2
366
+ continue
367
+ if ch == "$":
368
+ j = i + 1
369
+ while j < n:
370
+ if text[j] == "\\":
371
+ j += 2
372
+ continue
373
+ if text[j] == "$":
374
+ break
375
+ j += 1
376
+ if j >= n:
377
+ break
378
+ inline.append(text[i + 1:j])
379
+ i = j + 1
380
+ continue
381
+ i += 1
382
+ return disp, inline
383
+
384
+
385
+ def cmd_verify(a):
386
+ src = Path(a.file)
387
+ if not src.exists():
388
+ die(f"文件不存在: {src}")
389
+ text = read_text_any(src)
390
+ errors, warns = [], []
391
+
392
+ for pat, name in FORBIDDEN:
393
+ for m in re.finditer(pat, text):
394
+ line = text.count("\n", 0, m.start()) + 1
395
+ errors.append(f"第 {line} 行出现禁用结构 {name}")
396
+
397
+ for env in WARN_ENVS:
398
+ for m in re.finditer(r"\\begin\{" + env + r"\}", text):
399
+ line = text.count("\n", 0, m.start()) + 1
400
+ warns.append(f"第 {line} 行 \\begin{{{env}}}:建议改写为 $$…$$(课本转写统一用 $/$$)")
401
+
402
+ # $ 配对(跳过 \$)
403
+ i, n, single, dbl = 0, len(text), 0, 0
404
+ while i < n:
405
+ if text[i] == "\\":
406
+ i += 2
407
+ continue
408
+ if text.startswith("$$", i):
409
+ dbl += 1
410
+ i += 2
411
+ continue
412
+ if text[i] == "$":
413
+ single += 1
414
+ i += 1
415
+ if single % 2:
416
+ errors.append(f"$ 未配对:单个 $ 出现 {single} 次(应为偶数),行内公式缺了收尾符")
417
+ if dbl % 2:
418
+ errors.append(f"$$ 未配对:$$ 出现 {dbl} 次(应为偶数)")
419
+
420
+ disp, inline = math_segments(text)
421
+ result = {
422
+ "file": str(src),
423
+ "ok": not errors,
424
+ "errors": errors,
425
+ "warnings": warns[:20],
426
+ "math": {"display": len(disp), "inline": len(inline)},
427
+ "size_chars": len(text),
428
+ }
429
+
430
+ if a.tex and (disp or inline) and not errors:
431
+ need("xelatex")
432
+ body = []
433
+ for s in disp:
434
+ body.append("\\[\n" + s.strip() + "\n\\]")
435
+ for s in inline:
436
+ body.append("$" + s.strip() + "$")
437
+ tex = ("\\documentclass[12pt]{article}\n"
438
+ "\\usepackage{amsmath,amssymb,amsfonts,bm}\n"
439
+ "\\usepackage{ctex}\n\\pagestyle{empty}\n"
440
+ "\\begin{document}\n" + "\n".join(body) + "\n\\end{document}\n")
441
+ td = scratch("texverify")
442
+ (td / "v.tex").write_text(tex, encoding="utf-8")
443
+ env = os.environ.copy()
444
+ env["TEXMFVAR"] = str(td / "tv")
445
+ env["TEXMFCACHE"] = str(td / "tv")
446
+ # 关键:cwd 切到目录、只传相对文件名。TeX 在 Windows 上处理含中文的
447
+ # 命令行路径会按本地代码页解码,中文路径直接编译失败。
448
+ r = run(["xelatex", "-interaction=nonstopmode", "-halt-on-error", "v.tex"],
449
+ cwd=td, env=env, timeout=180)
450
+ log = td / "v.log"
451
+ logtext = read_text_any(log) if log.exists() else ""
452
+ lerrs = [ln for ln in logtext.splitlines() if ln.startswith("! ")]
453
+ ctx = []
454
+ for ln in logtext.splitlines():
455
+ if ln.startswith("l."):
456
+ ctx.append(ln[:160])
457
+ result["tex_compile"] = {
458
+ "ok": r.returncode == 0 and not lerrs,
459
+ "errors": (lerrs[:8] if lerrs else ([f"xelatex 返回码 {r.returncode}"] if r.returncode != 0 else [])),
460
+ "lines": ctx[:8],
461
+ "stderr_tail": (r.stderr or "")[-400:] if r.returncode != 0 else "",
462
+ }
463
+ if not result["tex_compile"]["ok"]:
464
+ result["ok"] = False
465
+
466
+ print(json.dumps(result, ensure_ascii=False, indent=2))
467
+ sys.exit(0 if result["ok"] else 1)
468
+
469
+
470
+ # ---------------------------------------------------------------- prune
471
+
472
+ def cmd_prune(a):
473
+ import time
474
+ if not CACHE_ROOT.exists():
475
+ print(json.dumps({"ok": True, "removed": [], "freed_bytes": 0,
476
+ "remaining_bytes": 0, "note": "缓存目录还不存在"},
477
+ ensure_ascii=False, indent=2))
478
+ return
479
+ now = time.time()
480
+ entries = [p for p in CACHE_ROOT.iterdir() if p.name != "api_files.json"]
481
+ if a.all:
482
+ targets = entries
483
+ elif a.days > 0:
484
+ cutoff = now - a.days * 86400
485
+ targets = [p for p in entries if p.stat().st_mtime < cutoff]
486
+ else:
487
+ targets = []
488
+ freed = sum(dir_size(p) for p in targets)
489
+ removed = []
490
+ for p in targets:
491
+ try:
492
+ if p.is_dir():
493
+ shutil.rmtree(p, ignore_errors=True)
494
+ else:
495
+ p.unlink(missing_ok=True)
496
+ removed.append(p.name)
497
+ except Exception:
498
+ pass
499
+ remaining = sum(dir_size(p) for p in CACHE_ROOT.iterdir() if p.name != "api_files.json")
500
+ print(json.dumps({
501
+ "ok": True,
502
+ "removed": removed,
503
+ "freed_mb": round(freed / 1048576, 2),
504
+ "remaining_mb": round(remaining / 1048576, 2),
505
+ "note": "days=0 只统计不删;--all 全清;缓存内容都是可重建的渲染图。",
506
+ }, ensure_ascii=False, indent=2))
507
+
508
+
509
+ # ---------------------------------------------------------------- split
510
+
511
+ BOOK_DIR = Path(__file__).resolve().parent.parent / "分片"
512
+
513
+
514
+ def split_ranges(spec, total):
515
+ """'1-36,37-80' -> [(1,36),(37,80)]"""
516
+ out = []
517
+ for part in spec.split(","):
518
+ part = part.strip()
519
+ if not part:
520
+ continue
521
+ m = re.fullmatch(r"(\d+)\s*-\s*(\d+)", part)
522
+ if m:
523
+ a, b = int(m.group(1)), int(m.group(2))
524
+ elif part.isdigit():
525
+ a = b = int(part)
526
+ else:
527
+ die(f"看不懂的页范围: {part!r}")
528
+ if not (1 <= a <= b <= total):
529
+ die(f"页范围 {part} 超出本书 1-{total} 页")
530
+ out.append((a, b))
531
+ if not out:
532
+ die("没有有效的页范围")
533
+ return out
534
+
535
+
536
+ def cmd_split(a):
537
+ """按页范围切成一章一个文件,命名 <前缀>_cNN_p起-止[_章名].pdf。
538
+ 产物落到 分片/<书名>/;已存在则跳过(加 --force 覆盖)。"""
539
+ need("pdftocairo")
540
+ pdf = Path(a.pdf)
541
+ total = pdf_pages(pdf)
542
+ groups = split_ranges(a.ranges, total)
543
+ if a.titles:
544
+ titles = [t.strip() for t in a.titles.split(",")]
545
+ if len(titles) != len(groups):
546
+ die(f"--titles 给了 {len(titles)} 个,页范围却有 {len(groups)} 个")
547
+ else:
548
+ titles = [""] * len(groups)
549
+
550
+ outdir = Path(a.out) if a.out else (BOOK_DIR / re.sub(r'[<>:"/\\|?*]', "_", pdf.stem))
551
+ outdir.mkdir(parents=True, exist_ok=True)
552
+ prefix = a.prefix or pdf.stem
553
+ made = []
554
+ for i, ((s, e), title) in enumerate(zip(groups, titles), 1):
555
+ name = f"{prefix}_c{i:02d}_p{s}-{e}" + (f"_{title}" if title else "") + ".pdf"
556
+ dst = outdir / name
557
+ if dst.exists() and not a.force:
558
+ made.append({"file": str(dst), "from": s, "to": e, "skipped": "已存在"})
559
+ continue
560
+ # pdftocairo 在 Windows 上无法接受「含中文的绝对输出路径」:
561
+ # 切到目标目录 + 纯 ASCII 相对文件名就正常,最后再用 Python 改名成中文。
562
+ tmpname = f"__part{i:03d}.pdf"
563
+ tmp = outdir / tmpname
564
+ r = run(["pdftocairo", "-pdf", "-f", s, "-l", e, pdf, tmpname], cwd=outdir)
565
+ if r.returncode != 0 or not tmp.exists():
566
+ die(f"第 {i} 段 ({s}-{e}) 拆分失败: {(r.stderr or '')[:300]}")
567
+ os.replace(tmp, dst)
568
+ made.append({"file": str(dst), "from": s, "to": e,
569
+ "pages": pdf_pages(dst), "expect": e - s + 1})
570
+ bad = [m for m in made if m.get("pages") and m["pages"] != m["expect"]]
571
+ print(json.dumps({
572
+ "ok": not bad, "source": str(pdf), "total_pages": total,
573
+ "outdir": str(outdir), "chunks": made,
574
+ "note": "命名已带页码,resolve 可直接用;页数与预期不符的会列在上面。",
575
+ }, ensure_ascii=False, indent=2))
576
+ if bad:
577
+ sys.exit(1)
578
+
579
+
580
+ # ---------------------------------------------------------------- resolve
581
+
582
+ RANGE_RE = re.compile(r"(?:^|[_\-\s((]|(?<=p))(\d+)\s*[-\u2013\u2014~]\s*(\d+)(?!\d)")
583
+
584
+
585
+ def cmd_resolve(a):
586
+ """把「书第 N 页」解析成「哪个分片文件 + 片内第几页」。
587
+ 页码范围从文件名里的 _A-B 推断(A 为 0 视为 0 基,即从第 1 页算起)。"""
588
+ d = Path(a.dir)
589
+ if not d.is_dir():
590
+ die(f"不是目录: {d}")
591
+ pdfs = sorted(p for p in d.rglob("*.pdf") if p.is_file())
592
+ if not pdfs:
593
+ die(f"目录里没有 PDF: {d}")
594
+
595
+ items = []
596
+ for f in pdfs:
597
+ m = RANGE_RE.search(f.stem)
598
+ try:
599
+ npages = pdf_pages(f)
600
+ except SystemExit:
601
+ npages = None
602
+ if m:
603
+ s, e = int(m.group(1)), int(m.group(2))
604
+ start, end = (1, e) if s == 0 else (s, e)
605
+ items.append({"name": f.name, "file": str(f), "from": start, "to": end,
606
+ "declared_pages": end - start + 1, "actual_pages": npages})
607
+ else:
608
+ items.append({"name": f.name, "file": str(f), "from": None, "to": None,
609
+ "actual_pages": npages})
610
+
611
+ ranged = sorted([i for i in items if i["from"]], key=lambda x: x["from"])
612
+ no_range = [i["name"] for i in items if not i["from"]]
613
+ issues = []
614
+ for prev, cur in zip(ranged, ranged[1:]):
615
+ if cur["from"] > prev["to"] + 1:
616
+ issues.append(f"缺页:{prev['to'] + 1}-{cur['from'] - 1} 无分片覆盖")
617
+ elif cur["from"] <= prev["to"]:
618
+ issues.append(f"重叠:{prev['name']} 与 {cur['name']}")
619
+ for i in ranged:
620
+ if i["actual_pages"] and i["actual_pages"] != i["declared_pages"]:
621
+ issues.append(f"页数不符:{i['name']} 声明 {i['declared_pages']} 页 / 实际 {i['actual_pages']} 页")
622
+
623
+ out = {"dir": str(d), "chunks": len(pdfs), "ranged": ranged,
624
+ "no_range": no_range, "issues": issues}
625
+ if a.page:
626
+ hit = next((i for i in ranged if i["from"] <= a.page <= i["to"]), None)
627
+ out["page"] = a.page
628
+ if hit:
629
+ local = a.page - hit["from"] + 1
630
+ out["result"] = {"file": hit["file"], "name": hit["name"], "local_page": local,
631
+ "chunk_range": [hit["from"], hit["to"]]}
632
+ if hit["actual_pages"] and not (1 <= local <= hit["actual_pages"]):
633
+ out["warning"] = f"片内第 {local} 页超出该文件实际页数 {hit['actual_pages']}"
634
+ else:
635
+ out["result"] = None
636
+ out["error"] = f"第 {a.page} 页没有被任何分片覆盖"
637
+ print(json.dumps(out, ensure_ascii=False, indent=2))
638
+ if out.get("error"):
639
+ sys.exit(1)
640
+
641
+
642
+ # ---------------------------------------------------------------- lookup
643
+
644
+ BOOKS_SPLIT = Path(__file__).resolve().parent.parent / "分片"
645
+ BOOKS_FULL = Path(__file__).resolve().parent.parent / "书库"
646
+ SPLIT_MARK = "拆分后常用课本" # 全本库会递归看到它,检索时要排除
647
+
648
+ _CN = {"零": 0, "〇": 0, "一": 1, "二": 2, "两": 2, "三": 3, "四": 4,
649
+ "五": 5, "六": 6, "七": 7, "八": 8, "九": 9}
650
+
651
+
652
+ def cn2int(s):
653
+ """'四' -> 4, '十二' -> 12, '4' -> 4, 'XIII' -> 13"""
654
+ s = s.strip()
655
+ if s.isdigit():
656
+ return int(s)
657
+ u = s.upper()
658
+ if re.fullmatch(r"[IVXLC]+", u):
659
+ vals = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100}
660
+ total, prev = 0, 0
661
+ for ch in reversed(u):
662
+ v = vals[ch]
663
+ total = total - v if v < prev else total + v
664
+ prev = max(prev, v)
665
+ return total
666
+ if "十" in s:
667
+ a, _, b = s.partition("十")
668
+ tens = _CN.get(a, 1) if a else 1
669
+ ones = _CN.get(b, 0) if b else 0
670
+ return tens * 10 + ones
671
+ return _CN.get(s)
672
+
673
+
674
+ def _norm(s):
675
+ return re.sub(r"[\s_\-()()【】\[\].,、·]+", "", s.lower())
676
+
677
+
678
+ def _chunk_range(f):
679
+ m = RANGE_RE.search(f.stem)
680
+ if not m:
681
+ return None, None
682
+ s, e = int(m.group(1)), int(m.group(2))
683
+ return (1, e) if s == 0 else (s, e)
684
+
685
+
686
+ def _book_chunks(d):
687
+ out = []
688
+ for f in sorted(Path(d).glob("*.pdf")):
689
+ s, e = _chunk_range(f)
690
+ code = chapter = label = None
691
+ m = re.search(r"_(c\d{2})_(.+?)(?:_p\d+-\d+)?$", f.stem)
692
+ if m:
693
+ code = m.group(1)
694
+ label = m.group(2)
695
+ cm = re.search(r"第([零〇一二三四五六七八九十]{1,3})章", label)
696
+ if cm:
697
+ chapter = cn2int(cm.group(1))
698
+ elif code in ("c00", "c99"):
699
+ chapter = 0 if code == "c00" else 99
700
+ out.append({"name": f.name, "file": str(f), "from": s, "to": e,
701
+ "code": code, "chapter": chapter, "label": label,
702
+ "pages": pdf_pages(f)})
703
+ return out
704
+
705
+
706
+ def cmd_lookup(a):
707
+ """先查 分片(拆分后的常用课本),查不到再查 书库(全本)。"""
708
+ kws = a.words or []
709
+
710
+ def hit(name):
711
+ n = _norm(name)
712
+ return all(_norm(k) in n for k in kws)
713
+
714
+ split_books, seen = [], set()
715
+ if BOOKS_SPLIT.is_dir():
716
+ for d in sorted(p for p in BOOKS_SPLIT.iterdir() if p.is_dir()):
717
+ if not kws or hit(d.name):
718
+ split_books.append(d); seen.add(str(d))
719
+ for f in sorted(BOOKS_SPLIT.rglob("*.pdf")):
720
+ if kws and hit(f.name) and str(f.parent) not in seen:
721
+ split_books.append(f.parent); seen.add(str(f.parent))
722
+
723
+ result = {"query": " ".join(kws), "split_root": str(BOOKS_SPLIT),
724
+ "split_books": [], "full_books": [], "advice": ""}
725
+ for d in split_books[:4]:
726
+ chunks = _book_chunks(d)
727
+ ranged = sorted([c for c in chunks if c["from"]], key=lambda c: c["from"])
728
+ issues = []
729
+ for prev, cur in zip(ranged, ranged[1:]):
730
+ if cur["from"] > prev["to"] + 1:
731
+ issues.append(f"缺页 {prev['to'] + 1}-{cur['from'] - 1}")
732
+ elif cur["from"] <= prev["to"]:
733
+ issues.append(f"重叠 {prev['name']} / {cur['name']}")
734
+ no_range = [c["name"] for c in chunks if not c["from"]]
735
+ result["split_books"].append({
736
+ "book": d.name, "dir": str(d), "chunks": len(chunks),
737
+ "ranged": ranged, "all": chunks, "no_range": no_range, "issues": issues,
738
+ })
739
+
740
+ if not split_books and BOOKS_FULL.is_dir():
741
+ for f in sorted(BOOKS_FULL.rglob("*.pdf")):
742
+ if SPLIT_MARK in str(f):
743
+ continue
744
+ if hit(f.name):
745
+ result["full_books"].append({"name": f.name, "file": str(f),
746
+ "pages": pdf_pages(f)})
747
+ if len(result["full_books"]) >= 10:
748
+ break
749
+
750
+ if a.chapter is not None:
751
+ n = cn2int(str(a.chapter)) if not str(a.chapter).isdigit() else int(a.chapter)
752
+ res = {"chapter": a.chapter, "chapter_num": n}
753
+ if n is None:
754
+ res["error"] = f"看不懂的章号:{a.chapter}(给 4 或 四)"
755
+ else:
756
+ hits = []
757
+ for b in result["split_books"]:
758
+ chunks_all = b.get("all") or b.get("ranged", [])
759
+ for c in chunks_all:
760
+ if c.get("chapter") == n:
761
+ hits.append((b, c, "chapter"))
762
+ break
763
+ if not hits:
764
+ for b in result["split_books"]:
765
+ for c in (b.get("all") or b.get("ranged", [])):
766
+ if c.get("code") == f"c{n:02d}":
767
+ hits.append((b, c, "code"))
768
+ break
769
+ if len(hits) == 1:
770
+ b, c, _ = hits[0]
771
+ res["result"] = {"book": b["book"], "file": c["file"], "name": c["name"],
772
+ "pages": c["pages"],
773
+ "chunk_range": [c["from"], c["to"]] if c["from"] else None}
774
+ elif len(hits) > 1:
775
+ res["result"] = None
776
+ res["candidates"] = [{"book": b["book"], "name": c["name"], "file": c["file"]}
777
+ for b, c, _ in hits]
778
+ res["error"] = (f"{len(hits)} 本书都命中,无法确定是哪本;"
779
+ "让用户补一个能区分的词(如「白皮书」「第四版」)。")
780
+ else:
781
+ res["result"] = None
782
+ res["error"] = ("分片里没有这一章。可能这本还没按章重命名"
783
+ "(看 split_books 里各片的 code/chapter 字段)。")
784
+ result["chapter_lookup"] = res
785
+
786
+ if a.page:
787
+ target = next((b for b in result["split_books"] if b["ranged"]), None)
788
+ result["page"] = a.page
789
+ if target:
790
+ c = next((x for x in target["ranged"] if x["from"] <= a.page <= x["to"]), None)
791
+ if c:
792
+ result["result"] = {"book": target["book"], "file": c["file"],
793
+ "name": c["name"], "local_page": a.page - c["from"] + 1,
794
+ "chunk_range": [c["from"], c["to"]]}
795
+ else:
796
+ result["result"] = None
797
+ result["error"] = f"第 {a.page} 页没被这本的分片覆盖(见 issues)"
798
+ elif result["split_books"]:
799
+ result["result"] = None
800
+ result["error"] = "这本的分片文件名里没有页码(章节式命名),无法按原书页码定位;改用章名,或先看该章首页的印刷页码。"
801
+ else:
802
+ result["result"] = None
803
+ result["error"] = "分片库里没有匹配的书,见 full_books:只有全本,需要先 split。"
804
+
805
+ if result["split_books"]:
806
+ result["advice"] = "优先用 split_books:这些是已拆好的常用课本。"
807
+ elif result["full_books"]:
808
+ result["advice"] = "分片库没有,退回 full_books(全本);要按章工作就先 split 这本。"
809
+ else:
810
+ result["advice"] = "两个库都没有匹配;换个关键词(作者、书名片段)再试。"
811
+
812
+ print(json.dumps(result, ensure_ascii=False, indent=2))
813
+
814
+
815
+ # ---------------------------------------------------------------- main
816
+
817
+ def main():
818
+ ap = argparse.ArgumentParser(description="数学课本工作流 PDF 工具")
819
+ sub = ap.add_subparsers(dest="cmd", required=True)
820
+
821
+ p = sub.add_parser("info")
822
+ p.add_argument("pdf")
823
+ p.set_defaults(fn=cmd_info)
824
+
825
+ p = sub.add_parser("text")
826
+ p.add_argument("pdf")
827
+ p.add_argument("--out", default="")
828
+ p.add_argument("--pages", default="")
829
+ p.add_argument("--force", action="store_true")
830
+ p.set_defaults(fn=cmd_text)
831
+
832
+ p = sub.add_parser("render")
833
+ p.add_argument("pdf")
834
+ p.add_argument("--out", default="")
835
+ p.add_argument("--pages", default="")
836
+ p.add_argument("--dpi", type=int, default=200)
837
+ p.add_argument("--bands", type=int, default=1)
838
+ p.add_argument("--overlap", type=float, default=0.06)
839
+ p.add_argument("--gray", action="store_true")
840
+ p.add_argument("--force", action="store_true")
841
+ p.set_defaults(fn=cmd_render)
842
+
843
+ p = sub.add_parser("sheet")
844
+ p.add_argument("pdf")
845
+ p.add_argument("--out", default="")
846
+ p.add_argument("--pages", default="")
847
+ p.add_argument("--cols", type=int, default=4)
848
+ p.add_argument("--dpi", type=int, default=70)
849
+ p.set_defaults(fn=cmd_sheet)
850
+
851
+ p = sub.add_parser("find")
852
+ p.add_argument("pdf")
853
+ p.add_argument("keywords", nargs="+")
854
+ p.add_argument("--context", type=int, default=0)
855
+ p.set_defaults(fn=cmd_find)
856
+
857
+ p = sub.add_parser("verify")
858
+ p.add_argument("file")
859
+ p.add_argument("--tex", action="store_true")
860
+ p.set_defaults(fn=cmd_verify)
861
+
862
+ p = sub.add_parser("prune")
863
+ p.add_argument("--days", type=int, default=0, help="删掉超过 N 天没动过的缓存;0 表示只统计")
864
+ p.add_argument("--all", action="store_true", help="删掉全部缓存(api_files.json 除外)")
865
+ p.set_defaults(fn=cmd_prune)
866
+
867
+ p = sub.add_parser("resolve")
868
+ p.add_argument("dir", help="装分片 PDF 的目录")
869
+ p.add_argument("--page", type=int, default=0, help="书的页码,解析成「哪个分片 + 片内第几页」")
870
+ p.set_defaults(fn=cmd_resolve)
871
+
872
+ p = sub.add_parser("split")
873
+ p.add_argument("pdf")
874
+ p.add_argument("--ranges", required=True, help="如 1-36,37-80(一章一段)")
875
+ p.add_argument("--out", default="")
876
+ p.add_argument("--prefix", default="", help="文件名前缀,默认用原书名")
877
+ p.add_argument("--titles", default="", help="章名,逗号分隔,与页范围一一对应")
878
+ p.add_argument("--force", action="store_true")
879
+ p.set_defaults(fn=cmd_split)
880
+
881
+ p = sub.add_parser("lookup")
882
+ p.add_argument("words", nargs="*", help="书名 / 作者关键词,可多个(同时满足)")
883
+ p.add_argument("--page", type=int, default=0, help="顺带解析原书页码")
884
+ p.add_argument("--chapter", default=None, help="按章号取,如 4 或 四")
885
+ p.set_defaults(fn=cmd_lookup)
886
+
887
+ a = ap.parse_args()
888
+ try:
889
+ a.fn(a)
890
+ finally:
891
+ # 每次运行结束清掉本次的临时目录,避免缓存里堆一堆 run<pid>
892
+ shutil.rmtree(SCRATCH / f"run{os.getpid()}", ignore_errors=True)
893
+
894
+
895
+ if __name__ == "__main__":
896
+ main()