dsh-pdf-workbench 1.5.0 → 1.5.2

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.
@@ -0,0 +1,82 @@
1
+ """Render one normalized rectangle of a PDF page to a lossless WebP.
2
+
3
+ Used by the workbench's question marks: the model gets a picture of exactly the
4
+ framed region, which works for scanned pages that have no text layer. Lossless
5
+ WebP keeps the pixels exact while halving the size of an equivalent PNG.
6
+
7
+ Usage:
8
+ py crop_question.py <pdf> <page> <x> <y> <w> <h> <out.webp>
9
+
10
+ The rectangle is normalized to the page box (0..1), the same coordinates the
11
+ browser stores for a question mark.
12
+ """
13
+ import argparse
14
+ import io
15
+ import os
16
+ import sys
17
+
18
+ try:
19
+ import fitz
20
+ except ImportError: # pragma: no cover - PyMuPDF is a plugin dependency
21
+ raise SystemExit("需要 PyMuPDF:py -m pip install pymupdf")
22
+
23
+ try:
24
+ from PIL import Image
25
+ except ImportError: # pragma: no cover - Pillow ships with the PDF tools
26
+ raise SystemExit("需要 Pillow:py -m pip install pillow")
27
+
28
+
29
+ def clamp(value):
30
+ return max(0.0, min(1.0, float(value)))
31
+
32
+
33
+ def main(argv=None):
34
+ parser = argparse.ArgumentParser(description="把 PDF 的一页框选区域渲染成无损 WebP")
35
+ parser.add_argument("pdf")
36
+ parser.add_argument("page", type=int)
37
+ parser.add_argument("x", type=float)
38
+ parser.add_argument("y", type=float)
39
+ parser.add_argument("w", type=float)
40
+ parser.add_argument("h", type=float)
41
+ parser.add_argument("out")
42
+ args = parser.parse_args(argv)
43
+
44
+ doc = fitz.open(args.pdf)
45
+ try:
46
+ if args.page < 1 or args.page > doc.page_count:
47
+ raise SystemExit("页码超出文档")
48
+ page = doc.load_page(args.page - 1)
49
+ box = page.rect
50
+ x = clamp(args.x)
51
+ y = clamp(args.y)
52
+ w = max(0.001, min(1.0 - x, clamp(args.w)))
53
+ h = max(0.001, min(1.0 - y, clamp(args.h)))
54
+ clip = fitz.Rect(
55
+ box.x0 + x * box.width,
56
+ box.y0 + y * box.height,
57
+ box.x0 + (x + w) * box.width,
58
+ box.y0 + (y + h) * box.height,
59
+ )
60
+ if clip.is_empty:
61
+ raise SystemExit("框选区域为空")
62
+ # Enough pixels to read a small band, capped so a full-page box does not
63
+ # produce a huge image.
64
+ scale = max(2.0, min(8.0, 1400.0 / max(1.0, clip.width)))
65
+ pix = page.get_pixmap(matrix=fitz.Matrix(scale, scale), clip=clip, alpha=False)
66
+ image = Image.open(io.BytesIO(pix.tobytes("png")))
67
+ if image.mode not in ("RGB", "RGBA"):
68
+ image = image.convert("RGB")
69
+ target = os.path.abspath(args.out)
70
+ if not target.lower().endswith(".webp"):
71
+ target += ".webp"
72
+ os.makedirs(os.path.dirname(target), exist_ok=True)
73
+ # Lossless: exact pixels, roughly half of PNG's size for this kind of scan.
74
+ image.save(target, format="WEBP", lossless=True, quality=100, method=6)
75
+ print(target)
76
+ return 0
77
+ finally:
78
+ doc.close()
79
+
80
+
81
+ if __name__ == "__main__":
82
+ sys.exit(main())
@@ -0,0 +1,78 @@
1
+ """Render page thumbnails for the split panel, and report the page layout.
2
+
3
+ usage: pdf_thumbs.py <pdf> <cache-dir> <width> <from> <to>
4
+
5
+ `cache-dir` is the per-file cache root (the caller keys it by PDF identity);
6
+ page images land in `<cache-dir>/<width>/pNNNN.jpg` and the page geometry in
7
+ `<cache-dir>/info.json`. Pages already present are left alone, so a scroll that
8
+ re-asks an overlapping range costs almost nothing. JSON on stdout:
9
+
10
+ {"pages": 340, "pageWidth": 495.0, "pageHeight": 718.0, "rendered": [1, 2]}
11
+
12
+ PyMuPDF renders a page at thumbnail size in a few milliseconds; Pillow writes
13
+ the JPEG (a few KB) because PyMuPDF's own `save` always emits PNG here.
14
+ """
15
+ import json
16
+ import os
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ import fitz
21
+ from PIL import Image
22
+
23
+ WIDTH_MIN = 80
24
+ WIDTH_MAX = 480
25
+
26
+
27
+ def main() -> int:
28
+ if len(sys.argv) < 6:
29
+ print("usage: pdf_thumbs.py <pdf> <cache-dir> <width> <from> <to>", file=sys.stderr)
30
+ return 2
31
+ pdf_path = sys.argv[1]
32
+ cache_root = Path(sys.argv[2])
33
+ width = max(WIDTH_MIN, min(WIDTH_MAX, int(float(sys.argv[3]))))
34
+ first = max(1, int(sys.argv[4]))
35
+ last = max(first, int(sys.argv[5]))
36
+
37
+ document = fitz.open(pdf_path)
38
+ pages = document.page_count
39
+ if pages <= 0:
40
+ raise SystemExit("PDF 没有页面")
41
+ first = min(first, pages)
42
+ last = min(last, pages)
43
+ first_page = document[0]
44
+ info = {
45
+ "pages": pages,
46
+ "pageWidth": round(first_page.rect.width, 2),
47
+ "pageHeight": round(first_page.rect.height, 2),
48
+ }
49
+ cache_root.mkdir(parents=True, exist_ok=True)
50
+ info_path = cache_root / "info.json"
51
+ info_tmp = cache_root / "info.json.tmp"
52
+ info_tmp.write_text(json.dumps(info, ensure_ascii=False), encoding="utf-8")
53
+ os.replace(info_tmp, info_path)
54
+
55
+ page_dir = cache_root / str(width)
56
+ page_dir.mkdir(parents=True, exist_ok=True)
57
+ rendered = []
58
+ for number in range(first, last + 1):
59
+ target = page_dir / f"p{number:04d}.jpg"
60
+ if target.is_file() and target.stat().st_size > 0:
61
+ rendered.append(number)
62
+ continue
63
+ page = document[number - 1]
64
+ scale = width / page.rect.width
65
+ pixmap = page.get_pixmap(matrix=fitz.Matrix(scale, scale), alpha=False, colorspace=fitz.csRGB)
66
+ image = Image.frombytes("RGB", (pixmap.width, pixmap.height), pixmap.samples)
67
+ temporary = page_dir / f"p{number:04d}.tmp"
68
+ image.save(str(temporary), "JPEG", quality=80, optimize=True)
69
+ os.replace(temporary, target)
70
+ rendered.append(number)
71
+
72
+ document.close()
73
+ print(json.dumps({**info, "rendered": rendered, "thumbWidth": width}, ensure_ascii=False))
74
+ return 0
75
+
76
+
77
+ if __name__ == "__main__":
78
+ raise SystemExit(main())
@@ -26,7 +26,7 @@
26
26
  ## 方式 C:npm(推荐给市场与更新)
27
27
 
28
28
  ```bash
29
- dsh plugin add dsh-pdf-workbench@1.5.0
29
+ dsh plugin add dsh-pdf-workbench@1.5.2
30
30
  ```
31
31
 
32
32
  旧包 `dsh-pdf-math-desk` 已从 npm 删除,请用新包名 `dsh-pdf-workbench`。
@@ -41,10 +41,22 @@ dsh plugin add dsh-pdf-workbench@1.5.0
41
41
  - 想固定一个库:在 DSH profile 的 patch 层给 `pdfdesk` 行加
42
42
  `config: { libraryDir: 'D:\你的书库' }`,或第一次启动后直接在书库页添加。
43
43
 
44
+ ## Python 依赖(拆分 / 翻译 / 导出,可选)
45
+
46
+ **只阅读 PDF 不需要 Python。** 要用按页拆分、整章翻译、扫描件文本提取与导出,需要 Python 3 加两个包:
47
+
48
+ ```bash
49
+ py -m pip install pymupdf pillow
50
+ ```
51
+
52
+ - **PyMuPDF(`fitz`)**:拆分、按页取文字、页面栅格化与叠加排版。安装说明:<https://pymupdf.readthedocs.io/en/latest/installation.html>
53
+ - **Pillow(`PIL`)**:`pdfkit.py` 与框选截图工具 `crop_question.py`。
54
+ - 插件**不会**自动安装 Python 包;缺少时 Host 会直接把可执行的 pip 命令作为错误提示返回,而不是抛 traceback。
55
+
44
56
  ## 拆分工具
45
57
 
46
58
  - 书库页的「拆分工具:开一个会话」会把 `tools\` 复制到 `<库根>\工具\`,并新开一个会话,提示词里已写好当前书库的路径、命名规则和“按章节手动拆”的要求。
47
- - 运行 `pdfkit.py` 需要 **Python 3 + Pillow**;不装也能用:你可以用任意 PDF 工具按章节切,再照命名规则改名(工具本质是重命名/校验)。
59
+ - 运行 `pdfkit.py` 需要 **Python 3 + PyMuPDF + Pillow**(见上节);不装也能用:你可以用任意 PDF 工具按章节切,再照命名规则改名(工具本质是重命名/校验)。
48
60
 
49
61
  ## 已知限制
50
62
 
@@ -53,6 +65,12 @@ dsh plugin add dsh-pdf-workbench@1.5.0
53
65
  - 阅读器基于 pdf.js;个别扫描版 PDF 的封面图可能缺字体资源,不影响正文阅读。
54
66
  - 拆分的“按章节”判断由人做:插件不识别书的内容,也不做 OCR。
55
67
 
68
+ ## 版权
69
+
70
+ - 插件与分发包**不附带任何书籍 PDF**,也不提供下载书籍或破解 DRM 的能力;导入的文件需使用者自行确认版权。
71
+ - 拆分、翻译与导出结果仅供个人学习研究,请不要和插件分发包一起传播版权材料;演示截图也请使用自己有权的文件。
72
+ - 排版的默认引擎 Typst 按需下载、不随包分发(Apache-2.0);其余第三方许可见 README 的「许可与致谢」和 `vendor/`。
73
+
56
74
 
57
75
  ## 排版引擎(Typst,可选)
58
76