sjtu-thesis 0.1.0__tar.gz

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 (36) hide show
  1. sjtu_thesis-0.1.0/LICENSE +21 -0
  2. sjtu_thesis-0.1.0/PKG-INFO +153 -0
  3. sjtu_thesis-0.1.0/README.md +113 -0
  4. sjtu_thesis-0.1.0/pyproject.toml +74 -0
  5. sjtu_thesis-0.1.0/setup.cfg +4 -0
  6. sjtu_thesis-0.1.0/sjtu_thesis/__init__.py +3 -0
  7. sjtu_thesis-0.1.0/sjtu_thesis/assemble.py +123 -0
  8. sjtu_thesis-0.1.0/sjtu_thesis/auth.py +260 -0
  9. sjtu_thesis-0.1.0/sjtu_thesis/batch.py +156 -0
  10. sjtu_thesis-0.1.0/sjtu_thesis/cli/__init__.py +0 -0
  11. sjtu_thesis-0.1.0/sjtu_thesis/cli/app.py +46 -0
  12. sjtu_thesis-0.1.0/sjtu_thesis/cli/batch.py +152 -0
  13. sjtu_thesis-0.1.0/sjtu_thesis/cli/common.py +55 -0
  14. sjtu_thesis-0.1.0/sjtu_thesis/cli/deps.py +53 -0
  15. sjtu_thesis-0.1.0/sjtu_thesis/cli/doctor.py +134 -0
  16. sjtu_thesis-0.1.0/sjtu_thesis/cli/download.py +162 -0
  17. sjtu_thesis-0.1.0/sjtu_thesis/cli/info.py +66 -0
  18. sjtu_thesis-0.1.0/sjtu_thesis/cli/lib.py +253 -0
  19. sjtu_thesis-0.1.0/sjtu_thesis/cli/login.py +38 -0
  20. sjtu_thesis-0.1.0/sjtu_thesis/cli/search.py +120 -0
  21. sjtu_thesis-0.1.0/sjtu_thesis/client.py +164 -0
  22. sjtu_thesis-0.1.0/sjtu_thesis/detail.py +95 -0
  23. sjtu_thesis-0.1.0/sjtu_thesis/download.py +188 -0
  24. sjtu_thesis-0.1.0/sjtu_thesis/errors.py +72 -0
  25. sjtu_thesis-0.1.0/sjtu_thesis/images.py +170 -0
  26. sjtu_thesis-0.1.0/sjtu_thesis/models.py +35 -0
  27. sjtu_thesis-0.1.0/sjtu_thesis/paths.py +55 -0
  28. sjtu_thesis-0.1.0/sjtu_thesis/reader.py +85 -0
  29. sjtu_thesis-0.1.0/sjtu_thesis/search.py +116 -0
  30. sjtu_thesis-0.1.0/sjtu_thesis/store.py +380 -0
  31. sjtu_thesis-0.1.0/sjtu_thesis.egg-info/PKG-INFO +153 -0
  32. sjtu_thesis-0.1.0/sjtu_thesis.egg-info/SOURCES.txt +34 -0
  33. sjtu_thesis-0.1.0/sjtu_thesis.egg-info/dependency_links.txt +1 -0
  34. sjtu_thesis-0.1.0/sjtu_thesis.egg-info/entry_points.txt +2 -0
  35. sjtu_thesis-0.1.0/sjtu_thesis.egg-info/requires.txt +15 -0
  36. sjtu_thesis-0.1.0/sjtu_thesis.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joe Hoye Dow
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: sjtu-thesis
3
+ Version: 0.1.0
4
+ Summary: CLI for searching, downloading and managing SJTU degree theses
5
+ Author-email: Joe Hoye Dow <luxunisgod123@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/MaybeBio/sjtu-thesis
8
+ Project-URL: Repository, https://github.com/MaybeBio/sjtu-thesis
9
+ Project-URL: Issues, https://github.com/MaybeBio/sjtu-thesis/issues
10
+ Keywords: sjtu,thesis,dissertation,pdf,cli,scraper
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Education
21
+ Classifier: Topic :: Utilities
22
+ Requires-Python: >=3.11
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: typer>=0.12
26
+ Requires-Dist: rich>=13
27
+ Requires-Dist: requests>=2.31
28
+ Requires-Dist: lxml>=5
29
+ Requires-Dist: pymupdf>=1.24
30
+ Requires-Dist: playwright>=1.40
31
+ Requires-Dist: segno>=1.6
32
+ Requires-Dist: zxing-cpp>=2.2
33
+ Requires-Dist: pillow>=10
34
+ Requires-Dist: platformdirs>=4
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest>=8; extra == "dev"
37
+ Requires-Dist: ruff; extra == "dev"
38
+ Requires-Dist: mypy; extra == "dev"
39
+ Dynamic: license-file
40
+
41
+ <div align="center">
42
+
43
+ # 📚 sjtu-thesis
44
+
45
+ **上海交大学位论文 → 离线 PDF,一条命令**
46
+
47
+ 扫码登录一次 · 检索 · 批量下载 · 本地建库
48
+
49
+ [![Stars](https://img.shields.io/github/stars/MaybeBio/sjtu-thesis?style=flat&color=yellow)](https://github.com/MaybeBio/sjtu-thesis)
50
+ [![Python](https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
51
+ [![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS-lightgrey)](#)
52
+ [![Network](https://img.shields.io/badge/network-%E6%A0%A1%E5%86%85%E7%BD%91%20%7C%20VPN-orange)](#-常见问题)
53
+ [![Use](https://img.shields.io/badge/use-%E4%B8%AA%E4%BA%BA%E5%AD%A6%E4%B9%A0%E7%A0%94%E7%A9%B6-red)](#-声明)
54
+
55
+ </div>
56
+
57
+ ---
58
+
59
+ ## ✨ 它解决什么
60
+
61
+ | 站点的问题 | 这里的做法 |
62
+ |---|---|
63
+ | 加载慢、翻页痛苦 | 一次检索批量采元数据,一次下载整篇 PDF |
64
+ | 不能离线、手机难读 | 产出标准 PDF,任何阅读器都能看 |
65
+ | 缺页、超时、断了不知道 | 每页校验,缺页列号,可断点续传 |
66
+ | 会话过期后整批静默失败 | 自动静默刷新一次,失败给可执行提示 |
67
+
68
+ ## 🚀 快速开始
69
+
70
+ ```bash
71
+ git clone https://github.com/MaybeBio/sjtu-thesis && cd sjtu-thesis
72
+ uv venv .venv && uv pip install -e .
73
+ .venv/bin/python -m playwright install chromium # 仅登录需要
74
+ source .venv/bin/activate # 之后直接用 sjtu-thesis
75
+ ```
76
+
77
+ > 想装成全局命令:`pipx install .`(之后用 pipx 环境里的 python 执行上面那行 playwright 安装)。
78
+
79
+ ```bash
80
+ sjtu-thesis login # ① 手机扫码(交我办 / 微信),只需一次
81
+ sjtu-thesis search "量子纠缠" --by title --save # ② 检索并入本地库
82
+ sjtu-thesis download 160315 # ③ 下载、合成 PDF 到 ./theses
83
+ ```
84
+
85
+ ## 🧰 命令速查
86
+
87
+ | 命令 | 用途 |
88
+ |---|---|
89
+ | `login` | 扫码登录;会话存 `~/.config/sjtu-thesis/session.json`(0600,不存密码) |
90
+ | `doctor` | 四项自检:代理 / 主站 / 会话 / 正文图片 |
91
+ | `search` | 按主题、题名、关键词、作者、院系、专业、导师、年份检索;`--json` `--csv` `--save` |
92
+ | `info` | 单篇元数据与摘要 |
93
+ | `download` | `download <paperid>` 或 `--title "完整题名"`;`--jobs` 并发,`--force` 重下 |
94
+ | `batch` | `harvest` 采元数据、`download` 按队列下载、`retry` 失败重入队 |
95
+ | `lib` | `search` / `list` / `stats` / `verify` / `export --format` csv / json / bibtex |
96
+
97
+ ```bash
98
+ sjtu-thesis batch harvest "机器学习" --max-pages 5 # 默认只抓第 1 页,--all 才全量
99
+ sjtu-thesis batch download --jobs 2
100
+ sjtu-thesis lib verify # 校验文件、sha256、页数、缺页
101
+ ```
102
+
103
+ > 题名匹配是**规范化后精确匹配**;命中多篇会列出候选并退出(码 2),绝不替你挑。缺页默认**不生成 PDF**(码 1,列出缺页号),需要带占位页的版本才加 `--allow-placeholders`。
104
+
105
+ ## ❓ 常见问题
106
+
107
+ <details>
108
+ <summary><b>提示「不能打开」,或 <code>doctor</code> 的 image 项失败</b></summary>
109
+
110
+ 正文图片只对校内网络出口提供。连校园 VPN/代理,并确认它对命令行生效(`echo $https_proxy`)。工具会识别这种 82 字节的假页面直接报错,不会当成图片损坏反复重试。
111
+ </details>
112
+
113
+ <details>
114
+ <summary><b>提示需要重新登录(退出码 3)</b></summary>
115
+
116
+ 会话过期。先直接重跑命令——工具会用已存 cookie 静默刷新一次;仍失败再 `sjtu-thesis login`。
117
+ </details>
118
+
119
+ <details>
120
+ <summary><b>某篇论文缺页</b></summary>
121
+
122
+ 页面图片由服务端异步生成,通常 20 秒内齐全。工具会自动轮询;超时后列出缺页号并记为 `failed`,稍后 `batch retry` 一般能补齐。长期缺页多半是源 PDF 本身有问题。
123
+ </details>
124
+
125
+ <details>
126
+ <summary><b>「论文保密」怎么办</b></summary>
127
+
128
+ 这类论文没有正文入口。工具记为 `embargoed`,批量时计数但不算失败。
129
+ </details>
130
+
131
+ <details>
132
+ <summary><b>退出码含义</b></summary>
133
+
134
+ `0` 成功 · `1` 一般失败 · `2` 题名歧义 · `3` 需要登录 · `4` 需要校内网络
135
+ </details>
136
+
137
+ ## 🛠 开发
138
+
139
+ ```bash
140
+ uv venv .venv && uv pip install -e ".[dev]"
141
+ .venv/bin/pytest -q # 离线单测
142
+ SJTU_LIVE=1 .venv/bin/pytest -m live -v # 需会话 + 校内网
143
+ .venv/bin/ruff check . && .venv/bin/mypy sjtu_thesis
144
+ ```
145
+
146
+ ## 📌 后续
147
+
148
+ - **PDF → Markdown**:这些 PDF 是纯图片、没有文字层,需 OCR 与版面还原
149
+ - **局域网阅读器 / OPDS**:手机平板直接浏览本地库
150
+
151
+ ## 声明
152
+
153
+ 仅供个人学习研究,下载内容受版权保护,请勿传播或公开分享。保密论文不提供正文,工具如实记录并跳过。
@@ -0,0 +1,113 @@
1
+ <div align="center">
2
+
3
+ # 📚 sjtu-thesis
4
+
5
+ **上海交大学位论文 → 离线 PDF,一条命令**
6
+
7
+ 扫码登录一次 · 检索 · 批量下载 · 本地建库
8
+
9
+ [![Stars](https://img.shields.io/github/stars/MaybeBio/sjtu-thesis?style=flat&color=yellow)](https://github.com/MaybeBio/sjtu-thesis)
10
+ [![Python](https://img.shields.io/badge/python-3.11%2B-3776AB?logo=python&logoColor=white)](https://www.python.org/)
11
+ [![Platform](https://img.shields.io/badge/platform-Linux%20%7C%20macOS-lightgrey)](#)
12
+ [![Network](https://img.shields.io/badge/network-%E6%A0%A1%E5%86%85%E7%BD%91%20%7C%20VPN-orange)](#-常见问题)
13
+ [![Use](https://img.shields.io/badge/use-%E4%B8%AA%E4%BA%BA%E5%AD%A6%E4%B9%A0%E7%A0%94%E7%A9%B6-red)](#-声明)
14
+
15
+ </div>
16
+
17
+ ---
18
+
19
+ ## ✨ 它解决什么
20
+
21
+ | 站点的问题 | 这里的做法 |
22
+ |---|---|
23
+ | 加载慢、翻页痛苦 | 一次检索批量采元数据,一次下载整篇 PDF |
24
+ | 不能离线、手机难读 | 产出标准 PDF,任何阅读器都能看 |
25
+ | 缺页、超时、断了不知道 | 每页校验,缺页列号,可断点续传 |
26
+ | 会话过期后整批静默失败 | 自动静默刷新一次,失败给可执行提示 |
27
+
28
+ ## 🚀 快速开始
29
+
30
+ ```bash
31
+ git clone https://github.com/MaybeBio/sjtu-thesis && cd sjtu-thesis
32
+ uv venv .venv && uv pip install -e .
33
+ .venv/bin/python -m playwright install chromium # 仅登录需要
34
+ source .venv/bin/activate # 之后直接用 sjtu-thesis
35
+ ```
36
+
37
+ > 想装成全局命令:`pipx install .`(之后用 pipx 环境里的 python 执行上面那行 playwright 安装)。
38
+
39
+ ```bash
40
+ sjtu-thesis login # ① 手机扫码(交我办 / 微信),只需一次
41
+ sjtu-thesis search "量子纠缠" --by title --save # ② 检索并入本地库
42
+ sjtu-thesis download 160315 # ③ 下载、合成 PDF 到 ./theses
43
+ ```
44
+
45
+ ## 🧰 命令速查
46
+
47
+ | 命令 | 用途 |
48
+ |---|---|
49
+ | `login` | 扫码登录;会话存 `~/.config/sjtu-thesis/session.json`(0600,不存密码) |
50
+ | `doctor` | 四项自检:代理 / 主站 / 会话 / 正文图片 |
51
+ | `search` | 按主题、题名、关键词、作者、院系、专业、导师、年份检索;`--json` `--csv` `--save` |
52
+ | `info` | 单篇元数据与摘要 |
53
+ | `download` | `download <paperid>` 或 `--title "完整题名"`;`--jobs` 并发,`--force` 重下 |
54
+ | `batch` | `harvest` 采元数据、`download` 按队列下载、`retry` 失败重入队 |
55
+ | `lib` | `search` / `list` / `stats` / `verify` / `export --format` csv / json / bibtex |
56
+
57
+ ```bash
58
+ sjtu-thesis batch harvest "机器学习" --max-pages 5 # 默认只抓第 1 页,--all 才全量
59
+ sjtu-thesis batch download --jobs 2
60
+ sjtu-thesis lib verify # 校验文件、sha256、页数、缺页
61
+ ```
62
+
63
+ > 题名匹配是**规范化后精确匹配**;命中多篇会列出候选并退出(码 2),绝不替你挑。缺页默认**不生成 PDF**(码 1,列出缺页号),需要带占位页的版本才加 `--allow-placeholders`。
64
+
65
+ ## ❓ 常见问题
66
+
67
+ <details>
68
+ <summary><b>提示「不能打开」,或 <code>doctor</code> 的 image 项失败</b></summary>
69
+
70
+ 正文图片只对校内网络出口提供。连校园 VPN/代理,并确认它对命令行生效(`echo $https_proxy`)。工具会识别这种 82 字节的假页面直接报错,不会当成图片损坏反复重试。
71
+ </details>
72
+
73
+ <details>
74
+ <summary><b>提示需要重新登录(退出码 3)</b></summary>
75
+
76
+ 会话过期。先直接重跑命令——工具会用已存 cookie 静默刷新一次;仍失败再 `sjtu-thesis login`。
77
+ </details>
78
+
79
+ <details>
80
+ <summary><b>某篇论文缺页</b></summary>
81
+
82
+ 页面图片由服务端异步生成,通常 20 秒内齐全。工具会自动轮询;超时后列出缺页号并记为 `failed`,稍后 `batch retry` 一般能补齐。长期缺页多半是源 PDF 本身有问题。
83
+ </details>
84
+
85
+ <details>
86
+ <summary><b>「论文保密」怎么办</b></summary>
87
+
88
+ 这类论文没有正文入口。工具记为 `embargoed`,批量时计数但不算失败。
89
+ </details>
90
+
91
+ <details>
92
+ <summary><b>退出码含义</b></summary>
93
+
94
+ `0` 成功 · `1` 一般失败 · `2` 题名歧义 · `3` 需要登录 · `4` 需要校内网络
95
+ </details>
96
+
97
+ ## 🛠 开发
98
+
99
+ ```bash
100
+ uv venv .venv && uv pip install -e ".[dev]"
101
+ .venv/bin/pytest -q # 离线单测
102
+ SJTU_LIVE=1 .venv/bin/pytest -m live -v # 需会话 + 校内网
103
+ .venv/bin/ruff check . && .venv/bin/mypy sjtu_thesis
104
+ ```
105
+
106
+ ## 📌 后续
107
+
108
+ - **PDF → Markdown**:这些 PDF 是纯图片、没有文字层,需 OCR 与版面还原
109
+ - **局域网阅读器 / OPDS**:手机平板直接浏览本地库
110
+
111
+ ## 声明
112
+
113
+ 仅供个人学习研究,下载内容受版权保护,请勿传播或公开分享。保密论文不提供正文,工具如实记录并跳过。
@@ -0,0 +1,74 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "sjtu-thesis"
7
+ version = "0.1.0"
8
+ description = "CLI for searching, downloading and managing SJTU degree theses"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "Joe Hoye Dow", email = "luxunisgod123@gmail.com" }]
13
+ keywords = ["sjtu", "thesis", "dissertation", "pdf", "cli", "scraper"]
14
+ requires-python = ">=3.11"
15
+ dependencies = [
16
+ "typer>=0.12",
17
+ "rich>=13",
18
+ "requests>=2.31",
19
+ "lxml>=5",
20
+ "pymupdf>=1.24",
21
+ "playwright>=1.40",
22
+ "segno>=1.6",
23
+ "zxing-cpp>=2.2",
24
+ "pillow>=10",
25
+ "platformdirs>=4",
26
+ ]
27
+ classifiers = [
28
+ "Development Status :: 4 - Beta",
29
+ "Environment :: Console",
30
+ "Intended Audience :: Science/Research",
31
+ "Operating System :: POSIX :: Linux",
32
+ "Operating System :: MacOS",
33
+ "Programming Language :: Python :: 3",
34
+ "Programming Language :: Python :: 3.11",
35
+ "Programming Language :: Python :: 3.12",
36
+ "Programming Language :: Python :: 3.13",
37
+ "Topic :: Education",
38
+ "Topic :: Utilities",
39
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://github.com/MaybeBio/sjtu-thesis"
43
+ Repository = "https://github.com/MaybeBio/sjtu-thesis"
44
+ Issues = "https://github.com/MaybeBio/sjtu-thesis/issues"
45
+
46
+ [project.optional-dependencies]
47
+ dev = ["pytest>=8", "ruff", "mypy"]
48
+
49
+ [project.scripts]
50
+ sjtu-thesis = "sjtu_thesis.cli.app:main"
51
+
52
+ [tool.setuptools.packages.find]
53
+ include = ["sjtu_thesis*"]
54
+
55
+ [tool.pytest.ini_options]
56
+ testpaths = ["tests"]
57
+ markers = ["live: needs campus network and a real session"]
58
+
59
+ [tool.ruff]
60
+ line-length = 100
61
+ target-version = "py311"
62
+
63
+ [tool.ruff.lint]
64
+ select = ["E", "F", "W", "I", "UP", "B"]
65
+ ignore = [
66
+ "B008", # typer.Option/Argument/Fixture in defaults is the documented API
67
+ ]
68
+
69
+ [tool.ruff.lint.per-file-ignores]
70
+ "tests/**" = ["E501"]
71
+
72
+ [tool.mypy]
73
+ python_version = "3.11"
74
+ ignore_missing_imports = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """SJTU degree thesis CLI."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,123 @@
1
+ """Assemble page images into a PDF, refusing to hide missing pages."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass, field
7
+ from pathlib import Path
8
+
9
+ try: # PyMuPDF >= 1.24 exposes `pymupdf`; older builds only `fitz`
10
+ import pymupdf
11
+ except ImportError: # pragma: no cover
12
+ import fitz as pymupdf # type: ignore[no-redef]
13
+
14
+ from PIL import Image, ImageDraw, ImageFont
15
+
16
+ from .errors import IncompleteThesis
17
+ from .models import ReadSession
18
+
19
+
20
+ @dataclass
21
+ class PDFResult:
22
+ path: Path
23
+ pages: int
24
+ bytes: int
25
+ missing: list[int] = field(default_factory=list)
26
+
27
+
28
+ def _page_path(pages_dir: Path, page: int) -> Path:
29
+ return Path(pages_dir) / f"P01_{page:05d}.jpg"
30
+
31
+
32
+ def missing_pages(pages_dir: Path, total: int) -> list[int]:
33
+ return [n for n in range(1, total + 1) if not _page_path(pages_dir, n).exists()]
34
+
35
+
36
+ def _font(size: int):
37
+ for candidate in (
38
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
39
+ "/usr/share/fonts/TTF/DejaVuSans.ttf",
40
+ ):
41
+ try:
42
+ return ImageFont.truetype(candidate, size)
43
+ except OSError:
44
+ continue
45
+ return ImageFont.load_default()
46
+
47
+
48
+ def _placeholder(page_no: int, size: tuple[int, int]) -> Image.Image:
49
+ image = Image.new("RGB", size, "white")
50
+ draw = ImageDraw.Draw(image)
51
+ text = f"PAGE {page_no} UNAVAILABLE\n(page image was not generated by the server)"
52
+ font = _font(max(14, size[0] // 28))
53
+ box = draw.multiline_textbbox((0, 0), text, font=font, align="center")
54
+ draw.multiline_text(
55
+ ((size[0] - box[2]) / 2, (size[1] - box[3]) / 2),
56
+ text,
57
+ fill="black",
58
+ font=font,
59
+ align="center",
60
+ )
61
+ return image
62
+
63
+
64
+ def build_pdf(
65
+ pages_dir: Path,
66
+ out_path: Path,
67
+ *,
68
+ read: ReadSession,
69
+ meta: dict,
70
+ allow_placeholders: bool = False,
71
+ ) -> PDFResult:
72
+ """Build the PDF in one pass; never publish a file with silent gaps."""
73
+ pages_dir = Path(pages_dir)
74
+ out_path = Path(out_path)
75
+ missing = missing_pages(pages_dir, read.page_total)
76
+ if missing and not allow_placeholders:
77
+ listed = ", ".join(str(n) for n in missing[:20])
78
+ more = " 等" if len(missing) > 20 else ""
79
+ raise IncompleteThesis(
80
+ f"缺少 {len(missing)} 页正文({listed}{more}),未生成 PDF。"
81
+ "可用 --allow-placeholders 生成带占位页的版本,或稍后重试补齐。",
82
+ missing=missing,
83
+ )
84
+
85
+ doc = pymupdf.open()
86
+ try:
87
+ for page_no in range(1, read.page_total + 1):
88
+ page = doc.new_page(width=read.page_width, height=read.page_height)
89
+ source = _page_path(pages_dir, page_no)
90
+ if source.exists():
91
+ page.insert_image(page.rect, filename=str(source))
92
+ else:
93
+ placeholder = _placeholder(page_no, (read.page_width, read.page_height))
94
+ page.insert_image(page.rect, stream=_png_bytes(placeholder))
95
+ doc.set_metadata(
96
+ {
97
+ "title": meta.get("title", ""),
98
+ "author": meta.get("author", ""),
99
+ "subject": meta.get("subject", ""),
100
+ "keywords": meta.get("keywords", ""),
101
+ }
102
+ )
103
+ out_path.parent.mkdir(parents=True, exist_ok=True)
104
+ tmp = out_path.with_suffix(out_path.suffix + ".tmp")
105
+ doc.save(tmp, garbage=3, deflate=True)
106
+ finally:
107
+ doc.close()
108
+
109
+ os.replace(tmp, out_path)
110
+ return PDFResult(
111
+ path=out_path,
112
+ pages=read.page_total,
113
+ bytes=out_path.stat().st_size,
114
+ missing=missing,
115
+ )
116
+
117
+
118
+ def _png_bytes(image: Image.Image) -> bytes:
119
+ import io
120
+
121
+ buffer = io.BytesIO()
122
+ image.save(buffer, "PNG")
123
+ return buffer.getvalue()