pdftran 0.2.0__py3-none-any.whl

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 (56) hide show
  1. pdftran/__init__.py +9 -0
  2. pdftran/adoc.py +93 -0
  3. pdftran/archive.py +145 -0
  4. pdftran/carry.py +68 -0
  5. pdftran/cli.py +175 -0
  6. pdftran/credentials.py +35 -0
  7. pdftran/desktop.py +406 -0
  8. pdftran/export.py +248 -0
  9. pdftran/extract.py +456 -0
  10. pdftran/glossary.py +80 -0
  11. pdftran/paths.py +45 -0
  12. pdftran/pipeline.py +474 -0
  13. pdftran/py.typed +0 -0
  14. pdftran/server.py +357 -0
  15. pdftran/static/app.js +833 -0
  16. pdftran/static/desktop.js +149 -0
  17. pdftran/static/gedit.js +435 -0
  18. pdftran/static/index.html +171 -0
  19. pdftran/static/logo/pdftran-macos.png +0 -0
  20. pdftran/static/logo/pdftran.icns +0 -0
  21. pdftran/static/logo/pdftran.ico +0 -0
  22. pdftran/static/logo/pdftran.svg +19 -0
  23. pdftran/static/style.css +275 -0
  24. pdftran/static/vendor/asciidoctor.min.js +1483 -0
  25. pdftran/static/vendor/katex/LICENSE +21 -0
  26. pdftran/static/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
  27. pdftran/static/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
  28. pdftran/static/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
  29. pdftran/static/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
  30. pdftran/static/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
  31. pdftran/static/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
  32. pdftran/static/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
  33. pdftran/static/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
  34. pdftran/static/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
  35. pdftran/static/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
  36. pdftran/static/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
  37. pdftran/static/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
  38. pdftran/static/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
  39. pdftran/static/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
  40. pdftran/static/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
  41. pdftran/static/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
  42. pdftran/static/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
  43. pdftran/static/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
  44. pdftran/static/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
  45. pdftran/static/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
  46. pdftran/static/vendor/katex/katex.min.css +1 -0
  47. pdftran/static/vendor/katex/katex.min.js +1 -0
  48. pdftran/static/vendor/pdf.min.mjs +28 -0
  49. pdftran/static/vendor/pdf.worker.min.mjs +28 -0
  50. pdftran/translate.py +237 -0
  51. pdftran/winctl.py +431 -0
  52. pdftran-0.2.0.dist-info/METADATA +338 -0
  53. pdftran-0.2.0.dist-info/RECORD +56 -0
  54. pdftran-0.2.0.dist-info/WHEEL +4 -0
  55. pdftran-0.2.0.dist-info/entry_points.txt +4 -0
  56. pdftran-0.2.0.dist-info/licenses/LICENSE +674 -0
pdftran/desktop.py ADDED
@@ -0,0 +1,406 @@
1
+ """Desktop app: the FastAPI server in a background thread + a pywebview window.
2
+
3
+ `pdftran` with no arguments (or `pdftran-app`, or the packaged PDFTran.exe) opens this window.
4
+ Needs the optional `desktop` extra when run from source: uv sync --extra desktop
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ctypes
10
+ import math
11
+ import os
12
+ import secrets
13
+ import socket
14
+ import sys
15
+ import threading
16
+ import time
17
+ from pathlib import Path
18
+
19
+ from . import winctl
20
+ from .paths import FROZEN, data_dir, migrate_legacy_data
21
+ from .server import STATIC, create_app
22
+
23
+ TITLE = "PDFTran"
24
+ APP_ID = "PDFTran.App" # Windows AppUserModelID: groups the taskbar button and shows our icon, not python.exe's
25
+ # Held for the whole run so a second launch can detect the first one (single instance).
26
+ INSTANCE_PORT = int(os.environ.get("PDFTRAN_INSTANCE_PORT", "49213"))
27
+
28
+
29
+ def icon_path() -> Path:
30
+ # macOS gets the rounded plate with padding; the plain tile looks oversized in the Dock
31
+ return STATIC / "logo" / ("pdftran-macos.png" if sys.platform == "darwin" else "pdftran.ico")
32
+
33
+
34
+ def _acquire_single_instance() -> socket.socket | None:
35
+ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
36
+ try:
37
+ s.bind(("127.0.0.1", INSTANCE_PORT))
38
+ s.listen(1)
39
+ return s
40
+ except OSError:
41
+ s.close()
42
+ return None
43
+
44
+
45
+ def _free_port() -> int:
46
+ with socket.socket() as s:
47
+ s.bind(("127.0.0.1", 0))
48
+ return s.getsockname()[1]
49
+
50
+
51
+ def _set_app_user_model_id() -> None:
52
+ if sys.platform == "win32":
53
+ try:
54
+ ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(APP_ID)
55
+ except (OSError, AttributeError):
56
+ pass
57
+
58
+
59
+ def _enable_per_monitor_dpi() -> bool:
60
+ """Declare per-monitor DPI awareness before any window exists.
61
+
62
+ pywebview itself only declares system-DPI awareness; with several monitors at different scales Windows
63
+ then rescales the window a second time and window managers (PowerToys...) get size and position wrong.
64
+ """
65
+ if sys.platform != "win32":
66
+ return False
67
+ try:
68
+ if ctypes.windll.user32.SetProcessDpiAwarenessContext(ctypes.c_void_p(-4)): # PER_MONITOR_AWARE_V2
69
+ return True
70
+ return ctypes.windll.shcore.SetProcessDpiAwareness(2) == 0 # Windows 8.1
71
+ except (OSError, AttributeError):
72
+ return False
73
+
74
+
75
+ def failure_text(exc: BaseException, folder: str, log: str) -> str:
76
+ return (
77
+ "PDFTran 無法開啟桌面視窗。\n\n"
78
+ f"錯誤:{type(exc).__name__}: {exc}\n\n"
79
+ "最常見的原因:ZIP 是從網路下載的,Windows 把裡面的檔案標記成「來自網際網路」而封鎖了。處理方式:\n"
80
+ "1. 對 ZIP 檔按右鍵 →「內容」→ 勾選「解除封鎖」→ 確定,再重新解壓縮;或\n"
81
+ f'2. 在 PowerShell 執行:Get-ChildItem "{folder}" -Recurse | Unblock-File\n\n'
82
+ "也可以改用瀏覽器模式:PDFTran.exe serve,再用瀏覽器開啟 http://127.0.0.1:8765/\n\n"
83
+ f"詳細記錄:{log}\n\n"
84
+ "PDFTran could not open its desktop window. Most often the downloaded ZIP is blocked by Windows: "
85
+ "right-click the ZIP -> Properties -> Unblock, then extract it again (or run Unblock-File on the folder). "
86
+ "You can also run `PDFTran.exe serve` and use a browser."
87
+ )
88
+
89
+
90
+ def _report_failure(exc: BaseException, data: Path) -> int:
91
+ """A windowed build has no console; explain in a dialog instead of dumping a traceback."""
92
+ import traceback
93
+
94
+ traceback.print_exception(exc, file=sys.stderr) # the full trace goes to the log file
95
+ text = failure_text(exc, str(Path(sys.executable).parent), str(data / "pdftran.log"))
96
+ try:
97
+ ctypes.windll.user32.MessageBoxW(None, text, TITLE, 0x10) # MB_ICONERROR
98
+ except (OSError, AttributeError):
99
+ print(text, file=sys.stderr)
100
+ return 1
101
+
102
+
103
+ MIN_WINDOW_SIZE = (900, 600)
104
+
105
+
106
+ class _DesktopApi:
107
+ """The bridge the page calls (window.pywebview.api).
108
+
109
+ pywebview scans the public attributes of this object, so internal state always starts with an underscore.
110
+ `custom_chrome`: the window has no system title bar or frame; the page draws the window buttons and handles
111
+ dragging and edge resizing (Windows only; macOS / Linux keep the system title bar).
112
+ """
113
+
114
+ def __init__(self, custom_chrome: bool = False):
115
+ self._window = None
116
+ self._custom = custom_chrome
117
+ self._maximized = False
118
+ self._max_rect = None # the maximize button inside the client area (physical px), reported by the page
119
+ self._max_state = 0 # pointer on the maximize button: 0 none, 1 hover, 2 pressed
120
+ self._max_pushing = False
121
+ self._resize = None
122
+ self._moving = False
123
+ self._unsaved = "" # the page's "there are unsaved edits" message ("" = none); the closing event uses it
124
+ self._close_confirmed = False # the page's own close button already asked: don't ask a second time
125
+ self._asking = False
126
+
127
+ # ---- window handle / state ----
128
+ def _hwnd(self):
129
+ if sys.platform != "win32":
130
+ return None
131
+ try:
132
+ return int(self._window.native.Handle.ToInt64())
133
+ except Exception: # noqa: BLE001 - fall back to finding the window by title
134
+ return winctl.find_window(TITLE)
135
+
136
+ def _apply_resizable_frame(self):
137
+ """Keep WS_THICKFRAME (without drawing a frame). Window managers (FancyZones...) use it to decide whether a
138
+ window can be resized. On Windows 11 the native frame is kept so Snap Layouts can appear."""
139
+ if not self._custom or self._window is None:
140
+ return
141
+ try:
142
+ hwnd = self._hwnd()
143
+ if hwnd:
144
+ winctl.install_resizable_frame(hwnd, keep_native_frame=winctl.snap_layouts_supported())
145
+ except Exception as e: # noqa: BLE001 - only costs "resizable by window managers"; never crash
146
+ print(f"cannot set the resizable-window style: {e}", file=sys.stderr)
147
+
148
+ def _on_shown(self):
149
+ self._apply_resizable_frame()
150
+
151
+ def _sync_maximized(self):
152
+ if self._custom:
153
+ hwnd = self._hwnd()
154
+ if hwnd:
155
+ self._maximized = winctl.is_zoomed(hwnd)
156
+
157
+ def window_state(self):
158
+ self._sync_maximized()
159
+ return {"custom": self._custom, "maximized": self._maximized}
160
+
161
+ # ---- the custom window buttons ----
162
+ def window_minimize(self):
163
+ if self._custom and self._window is not None:
164
+ self._window.minimize()
165
+
166
+ def window_toggle_maximize(self):
167
+ """Always the system maximize (button, Win+Up, snapping, Snap Layouts, FancyZones): it keeps the native frame
168
+ right, and restoring returns to the previous size and position."""
169
+ hwnd = self._hwnd() if self._custom else None
170
+ if hwnd:
171
+ if winctl.is_zoomed(hwnd):
172
+ winctl.restore(hwnd)
173
+ self._maximized = False
174
+ else:
175
+ winctl.maximize(hwnd)
176
+ self._maximized = True
177
+ return self.window_state()
178
+
179
+ def window_close(self):
180
+ if self._window is not None:
181
+ self._close_confirmed = True # the page already confirmed (it asks first when there are unsaved edits)
182
+ self._window.destroy()
183
+
184
+ # ---- exporting: the page builds the file through the server, then asks here where to save it ----
185
+ def save_file(self, filename, b64data):
186
+ """Show the system "save as" dialog and write the bytes there. Returns the path, or None if cancelled."""
187
+ import base64
188
+
189
+ import webview
190
+
191
+ name = Path(str(filename)).name or "export"
192
+ ext = Path(name).suffix.lower()
193
+ kinds = {".pdf": "PDF (*.pdf)", ".epub": "ePUB (*.epub)", ".adoc": "AsciiDoc (*.adoc)", ".zip": "Zip 壓縮檔 (*.zip)"}
194
+ save_type = webview.FileDialog.SAVE if hasattr(webview, "FileDialog") else webview.SAVE_DIALOG
195
+ chosen = self._window.create_file_dialog(
196
+ save_type, directory=str(Path.home() / "Documents"), save_filename=name, file_types=(kinds.get(ext, "所有檔案 (*.*)"),)
197
+ )
198
+ if not chosen:
199
+ return None
200
+ path = Path(chosen if isinstance(chosen, (str, Path)) else chosen[0])
201
+ if ext and path.suffix.lower() != ext:
202
+ path = path.with_name(path.name + ext)
203
+ path.write_bytes(base64.b64decode(b64data))
204
+ return str(path)
205
+
206
+ # ---- unsaved edits: closing by Alt+F4 / the taskbar never reaches the page, so the page reports in advance ----
207
+ def set_unsaved(self, message):
208
+ self._unsaved = str(message or "").strip()[:300]
209
+ return True
210
+
211
+ def _on_closing(self):
212
+ """pywebview's `closing` event (runs on the UI thread; returning False cancels the close).
213
+
214
+ With unsaved edits: cancel this close and ask the page instead; if the user confirms, the page calls
215
+ window_close. evaluate_js can't be called here (it would deadlock on the UI thread), so ask from a thread."""
216
+ if self._close_confirmed or not self._unsaved or sys.platform != "win32" or self._window is None:
217
+ return None
218
+ if not self._asking:
219
+ self._asking = True
220
+ threading.Thread(target=self._ask_close, name="ask-close", daemon=True).start()
221
+ return False
222
+
223
+ def _ask_close(self):
224
+ try:
225
+ hwnd = self._hwnd()
226
+ if hwnd and winctl.is_iconic(hwnd):
227
+ self._window.restore() # closed from the taskbar while minimized: show the window so the user can answer
228
+ shown = self._window.evaluate_js("(window.askLeaveThenClose ? (window.askLeaveThenClose(), true) : false)")
229
+ if shown is not True:
230
+ raise RuntimeError("the page did not respond")
231
+ except Exception: # noqa: BLE001
232
+ try:
233
+ ok = bool(self._window.create_confirmation_dialog(TITLE, self._unsaved))
234
+ except Exception: # noqa: BLE001
235
+ ok = True # never make the program impossible to close
236
+ if ok:
237
+ self.window_close()
238
+ finally:
239
+ self._asking = False
240
+
241
+ # ---- moving: the drag itself is pywebview's (.pywebview-drag-region); we only tell the system ----
242
+ def window_move_begin(self):
243
+ """FancyZones shows its zones (Shift-drag) and snaps the window in only if it hears the move-start / move-end events."""
244
+ hwnd = self._hwnd() if self._custom and not self._maximized else None
245
+ if hwnd and not self._moving:
246
+ self._moving = True
247
+ winctl.notify_move_size(hwnd, True)
248
+
249
+ def window_move_end(self):
250
+ if self._moving:
251
+ self._moving = False
252
+ hwnd = self._hwnd()
253
+ if hwnd:
254
+ winctl.notify_move_size(hwnd, False)
255
+
256
+ # ---- edge resizing: the page calls begin on pointerdown, reports movement (physical px), then end ----
257
+ def resize_begin(self, edge, dpr=1.0):
258
+ self._sync_maximized()
259
+ hwnd = self._hwnd() if self._custom and not self._maximized else None
260
+ if hwnd and edge in winctl.EDGES:
261
+ self._resize = {"hwnd": hwnd, "rect": winctl.get_rect(hwnd), "dpr": max(0.5, min(float(dpr), 8.0)), "seq": 0}
262
+
263
+ def resize_to(self, edge, dx, dy, seq):
264
+ rs = self._resize
265
+ if not rs or edge not in winctl.EDGES or int(seq) <= rs["seq"]: # bridge calls may arrive out of order: drop old ones
266
+ return
267
+ rs["seq"] = int(seq)
268
+ min_w, min_h = (int(v * rs["dpr"]) for v in MIN_WINDOW_SIZE)
269
+ winctl.set_rect(rs["hwnd"], *winctl.resized_rect(rs["rect"], edge, dx, dy, min_w, min_h))
270
+
271
+ def resize_end(self):
272
+ self._resize = None
273
+
274
+ # ---- Windows 11 Snap Layouts on the maximize button (see docs/en/windows-titlebar.md) ----
275
+ def set_max_button(self, left, top, width, height, dpr):
276
+ """The page reports where its maximize button is (CSS px; width or height 0 = not on screen). Windows 11 needs a
277
+ transparent child window over that spot (WebView2 keeps the mouse away from the top-level window)."""
278
+ if not self._custom or not winctl.snap_layouts_supported() or self._window is None:
279
+ return False
280
+ try:
281
+ left, top, width, height, dpr = (float(v) for v in (left, top, width, height, dpr))
282
+ except (TypeError, ValueError):
283
+ return False
284
+ if not all(map(math.isfinite, (left, top, width, height, dpr))) or not 0.5 <= dpr <= 8 or not 0 <= width <= 400 or not 0 <= height <= 200:
285
+ return False
286
+ if width < 1 or height < 1:
287
+ self._max_rect = None
288
+ else:
289
+ self._max_rect = (round(left * dpr), round(top * dpr), max(1, round(width * dpr)), max(1, round(height * dpr)))
290
+ return self._place_max_overlay()
291
+
292
+ def _place_max_overlay(self):
293
+ """The overlay must be created and used on the UI thread, so hop over to it."""
294
+ if self._window is None or sys.platform != "win32" or not winctl.snap_layouts_supported():
295
+ return False
296
+ hwnd = self._hwnd()
297
+ if not hwnd:
298
+ return False
299
+ rect = self._max_rect
300
+
301
+ def run():
302
+ try:
303
+ winctl.place_max_button_overlay(hwnd, rect, self._push_max_state)
304
+ except Exception as e: # noqa: BLE001 - only the flyout is lost; the button itself still works
305
+ print(f"cannot place the maximize-button overlay: {e}", file=sys.stderr)
306
+
307
+ try:
308
+ from System import Func, Type
309
+
310
+ self._window.native.Invoke(Func[Type](run))
311
+ except Exception as e: # noqa: BLE001
312
+ print(f"cannot switch to the UI thread: {e}", file=sys.stderr)
313
+ return False
314
+ return True
315
+
316
+ def _push_max_state(self, state):
317
+ """The overlay (UI thread) reports hover / pressed. Tell the page from a worker thread (evaluate_js on the UI
318
+ thread deadlocks) and only ever push the latest state, so fast transitions cannot arrive out of order."""
319
+ self._max_state = state
320
+ if self._max_pushing:
321
+ return
322
+ self._max_pushing = True
323
+
324
+ def worker():
325
+ sent = None
326
+ try:
327
+ while sent != self._max_state:
328
+ sent = self._max_state
329
+ self._window.evaluate_js(f"window.__maxButtonState && window.__maxButtonState({int(sent)})")
330
+ except Exception: # noqa: BLE001 - the page is gone
331
+ pass
332
+ finally:
333
+ self._max_pushing = False
334
+
335
+ threading.Thread(target=worker, name="max-button-state", daemon=True).start()
336
+
337
+
338
+ def run_desktop(data: Path | None = None, native_titlebar: bool = False) -> int:
339
+ try:
340
+ import webview
341
+ except ImportError:
342
+ print("桌面模式需要 pywebview:uv sync --extra desktop(或改用瀏覽器模式:pdftran serve)", file=sys.stderr)
343
+ return 1
344
+ import uvicorn
345
+
346
+ data = data or data_dir()
347
+ migrate_legacy_data(data)
348
+ data.mkdir(parents=True, exist_ok=True)
349
+
350
+ lock = _acquire_single_instance()
351
+ if lock is None:
352
+ print("PDFTran 已經在執行中。", file=sys.stderr)
353
+ return 1
354
+
355
+ _enable_per_monitor_dpi()
356
+ _set_app_user_model_id()
357
+
358
+ token = secrets.token_urlsafe(32) # per launch; other local programs can't use the API without it
359
+ port = _free_port()
360
+ server = uvicorn.Server(
361
+ uvicorn.Config(create_app(data, token=token), host="127.0.0.1", port=port, log_level="warning")
362
+ )
363
+ thread = threading.Thread(target=server.run, name="backend", daemon=True)
364
+ thread.start()
365
+ deadline = time.time() + 30
366
+ while not server.started and thread.is_alive() and time.time() < deadline:
367
+ time.sleep(0.05)
368
+ if not server.started:
369
+ print(f"伺服器啟動失敗,詳細原因請看記錄檔:{data / 'pdftran.log'}", file=sys.stderr)
370
+ lock.close()
371
+ return 1
372
+
373
+ try:
374
+ # No system title bar on Windows: the toolbar doubles as the title bar (docs/en/windows-titlebar.md).
375
+ # macOS / Linux keep the system title bar (their frameless support is untested), and so does --native-titlebar.
376
+ custom = sys.platform == "win32" and not native_titlebar
377
+ api = _DesktopApi(custom_chrome=custom)
378
+ # easy_drag=False: the default "drag from anywhere" would swallow text selection and sliders; only
379
+ # .pywebview-drag-region (empty toolbar space) drags, and DIRECT_TARGET_ONLY keeps buttons inside it clickable.
380
+ webview.settings["DRAG_REGION_DIRECT_TARGET_ONLY"] = True
381
+ api._window = webview.create_window(
382
+ TITLE, f"http://127.0.0.1:{port}/?token={token}", width=1360, height=860, min_size=MIN_WINDOW_SIZE,
383
+ js_api=api, frameless=custom, easy_drag=False,
384
+ )
385
+ api._window.events.shown += api._on_shown
386
+ api._window.events.closing += api._on_closing
387
+ # private_mode=False + storage_path: the web view's cache lives in the data folder, not the install dir.
388
+ # icon: title bar / taskbar icon (without it Windows shows python.exe's icon when run from source).
389
+ webview.start(private_mode=False, storage_path=str(data / "webview"), icon=str(icon_path()))
390
+ except Exception as e: # noqa: BLE001
391
+ if not FROZEN:
392
+ raise # from source, show the full traceback
393
+ return _report_failure(e, data)
394
+ finally:
395
+ server.should_exit = True
396
+ thread.join(timeout=5)
397
+ lock.close()
398
+ return 0
399
+
400
+
401
+ def main() -> int:
402
+ return run_desktop(native_titlebar='--native-titlebar' in sys.argv[1:])
403
+
404
+
405
+ if __name__ == "__main__":
406
+ raise SystemExit(main())
pdftran/export.py ADDED
@@ -0,0 +1,248 @@
1
+ """Export the translation as a PDF or an ePUB.
2
+
3
+ The page renders the AsciiDoc to HTML (Asciidoctor.js, the same as the viewer) and sends it here as *chapters*
4
+ (`{"title": str, "xhtml": str}`, well-formed XHTML from XMLSerializer). Python only lays it out:
5
+ * ePUB: a plain EPUB 3 zip (nav + ncx for older readers), one XHTML file per chapter;
6
+ * PDF: PyMuPDF's Story (HTML → pages); its built-in CJK fallback font covers Traditional Chinese,
7
+ and the headings become the PDF outline (bookmarks).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import datetime as _dt
13
+ import io
14
+ import re
15
+ import uuid
16
+ import xml.etree.ElementTree as ET
17
+ import zipfile
18
+ from dataclasses import dataclass
19
+ from pathlib import Path
20
+ from xml.sax.saxutils import escape
21
+
22
+ import pymupdf
23
+
24
+ XHTML_NS = "http://www.w3.org/1999/xhtml"
25
+ MAX_OUTLINE_LEVEL = 4
26
+
27
+
28
+ @dataclass
29
+ class Chapter:
30
+ title: str
31
+ xhtml: str
32
+
33
+
34
+ def parse_chapters(raw) -> list[Chapter]:
35
+ """Validate the request body's chapter list; raises ValueError with a message the user can read."""
36
+ if not isinstance(raw, list) or not raw:
37
+ raise ValueError("沒有可匯出的內容(尚未翻譯任何頁面)")
38
+ chapters = []
39
+ for i, c in enumerate(raw, 1):
40
+ if not isinstance(c, dict) or not isinstance(c.get("xhtml"), str):
41
+ raise ValueError(f"第 {i} 章格式不正確")
42
+ xhtml = c["xhtml"]
43
+ try:
44
+ ET.fromstring(f"<root>{_strip_ns(xhtml)}</root>")
45
+ except ET.ParseError as e:
46
+ raise ValueError(f"第 {i} 章不是合法的 XHTML:{e}") from e
47
+ chapters.append(Chapter(str(c.get("title") or f"章節 {i}").strip(), xhtml))
48
+ return chapters
49
+
50
+
51
+ def _strip_ns(xhtml: str) -> str:
52
+ return xhtml.replace(f' xmlns="{XHTML_NS}"', "")
53
+
54
+
55
+ # ---------------------------------------------------------------- ePUB
56
+ EPUB_CSS = """\
57
+ body { font-family: serif; line-height: 1.7; margin: 0 4%; }
58
+ h1, h2, h3, h4, h5 { font-family: sans-serif; line-height: 1.3; margin: 1.6em 0 .6em; }
59
+ h1.doc-title { text-align: center; margin-top: 30%; }
60
+ p { margin: .7em 0; text-align: justify; }
61
+ pre { background: #f4f4f4; padding: .6em .8em; white-space: pre-wrap; word-wrap: break-word; font-size: .88em; }
62
+ code { font-family: monospace; font-size: .92em; }
63
+ table { border-collapse: collapse; margin: 1em 0; }
64
+ td, th { border: 1px solid #999; padding: .3em .6em; vertical-align: top; }
65
+ th { background: #eee; }
66
+ blockquote { margin: 1em 0; padding: 0 1em; border-left: 3px solid #bbb; color: #444; }
67
+ li > p { margin: .2em 0; }
68
+ .admonitionblock { border-left: 4px solid #6a9fd8; background: #f1f6fc; padding: .4em .8em; margin: 1em 0; }
69
+ .admonitionblock table, .admonitionblock td { border: 0; padding: 0 .4em; }
70
+ img { max-width: 100%; }
71
+ """
72
+
73
+
74
+ def _xhtml_doc(title: str, body: str, css: bool = True) -> str:
75
+ return (
76
+ '<?xml version="1.0" encoding="utf-8"?>\n'
77
+ f'<html xmlns="{XHTML_NS}" xmlns:epub="http://www.idpf.org/2007/ops" lang="zh-Hant" xml:lang="zh-Hant">\n'
78
+ f"<head><meta charset=\"utf-8\"/><title>{escape(title)}</title>"
79
+ '<link rel="stylesheet" type="text/css" href="style.css"/></head>\n'
80
+ f"<body>{body}</body>\n</html>\n"
81
+ )
82
+
83
+
84
+ _IMG_SRC = re.compile(r'''\bsrc="images/([\w\-]+\.(?:png|jpg|svg))"''')
85
+ _IMG_TYPES = {"png": "image/png", "jpg": "image/jpeg", "svg": "image/svg+xml"}
86
+ PDF_SVG_ZOOM = 3.0 # a figure's SVG is drawn into the PDF layout as a picture this many times its size (pt -> px)
87
+
88
+
89
+ def _used_images(chapters: list[Chapter], images_dir: Path | None) -> list[str]:
90
+ """Names of the pictures the chapters refer to (`src="images/<name>"`) that really exist in `images_dir`."""
91
+ if images_dir is None:
92
+ return []
93
+ names = sorted({m for c in chapters for m in _IMG_SRC.findall(c.xhtml)})
94
+ return [n for n in names if (Path(images_dir) / n).is_file()]
95
+
96
+
97
+ def build_epub(title: str, chapters: list[Chapter], author: str = "", images_dir: Path | None = None) -> bytes:
98
+ title = title.strip() or "PDFTran"
99
+ pictures = _used_images(chapters, images_dir)
100
+ uid = f"urn:uuid:{uuid.uuid4()}"
101
+ modified = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
102
+ files: list[tuple[str, str, str]] = [] # (id, href, chapter title)
103
+ docs: dict[str, str] = {}
104
+ cover = f'<h1 class="doc-title">{escape(title)}</h1>'
105
+ docs["title.xhtml"] = _xhtml_doc(title, cover)
106
+ files.append(("title", "title.xhtml", title))
107
+ for i, c in enumerate(chapters, 1):
108
+ href = f"ch{i:03d}.xhtml"
109
+ docs[href] = _xhtml_doc(c.title, c.xhtml)
110
+ files.append((f"ch{i:03d}", href, c.title))
111
+
112
+ def item(i: str, h: str) -> str:
113
+ math = ' properties="mathml"' if "<math" in docs[h] else "" # EPUB 3 wants this flag on pages with MathML
114
+ return f'<item id="{i}" href="{h}" media-type="application/xhtml+xml"{math}/>'
115
+
116
+ manifest = "".join(item(i, h) for i, h, _ in files)
117
+ image_items = "".join(
118
+ f'<item id="img{k}" href="images/{n}" media-type="{_IMG_TYPES[n.rsplit(".", 1)[1]]}"/>' for k, n in enumerate(pictures, 1)
119
+ )
120
+ spine = "".join(f'<itemref idref="{i}"/>' for i, _, _ in files)
121
+ opf = (
122
+ '<?xml version="1.0" encoding="utf-8"?>\n'
123
+ '<package xmlns="http://www.idpf.org/2007/opf" version="3.0" unique-identifier="bookid" xml:lang="zh-Hant">\n'
124
+ '<metadata xmlns:dc="http://purl.org/dc/elements/1.1/">'
125
+ f'<dc:identifier id="bookid">{uid}</dc:identifier><dc:title>{escape(title)}</dc:title>'
126
+ "<dc:language>zh-Hant</dc:language>"
127
+ + (f"<dc:creator>{escape(author)}</dc:creator>" if author else "")
128
+ + f'<meta property="dcterms:modified">{modified}</meta></metadata>\n'
129
+ f'<manifest><item id="nav" href="nav.xhtml" media-type="application/xhtml+xml" properties="nav"/>'
130
+ f'<item id="ncx" href="toc.ncx" media-type="application/x-dtbncx+xml"/>'
131
+ f'<item id="css" href="style.css" media-type="text/css"/>{manifest}{image_items}</manifest>\n'
132
+ f'<spine toc="ncx">{spine}</spine>\n</package>\n'
133
+ )
134
+ nav_items = "".join(f'<li><a href="{h}">{escape(t)}</a></li>' for _, h, t in files)
135
+ nav = _xhtml_doc(title, f'<nav epub:type="toc" id="toc"><h1>目錄</h1><ol>{nav_items}</ol></nav>')
136
+ points = "".join(
137
+ f'<navPoint id="n{n}" playOrder="{n}"><navLabel><text>{escape(t)}</text></navLabel><content src="{h}"/></navPoint>'
138
+ for n, (_, h, t) in enumerate(files, 1)
139
+ )
140
+ ncx = (
141
+ '<?xml version="1.0" encoding="utf-8"?>\n<ncx xmlns="http://www.daisy.org/z3986/2005/ncx/" version="2005-1">'
142
+ f'<head><meta name="dtb:uid" content="{uid}"/></head><docTitle><text>{escape(title)}</text></docTitle>'
143
+ f"<navMap>{points}</navMap></ncx>\n"
144
+ )
145
+ container = (
146
+ '<?xml version="1.0"?>\n<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">'
147
+ '<rootfiles><rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/></rootfiles></container>\n'
148
+ )
149
+ buf = io.BytesIO()
150
+ with zipfile.ZipFile(buf, "w") as z:
151
+ z.writestr(zipfile.ZipInfo("mimetype"), "application/epub+zip", compress_type=zipfile.ZIP_STORED) # must be first, stored
152
+ z.writestr("META-INF/container.xml", container, compress_type=zipfile.ZIP_DEFLATED)
153
+ z.writestr("OEBPS/content.opf", opf, compress_type=zipfile.ZIP_DEFLATED)
154
+ z.writestr("OEBPS/nav.xhtml", nav, compress_type=zipfile.ZIP_DEFLATED)
155
+ z.writestr("OEBPS/toc.ncx", ncx, compress_type=zipfile.ZIP_DEFLATED)
156
+ z.writestr("OEBPS/style.css", EPUB_CSS, compress_type=zipfile.ZIP_DEFLATED)
157
+ for href, doc in docs.items():
158
+ z.writestr(f"OEBPS/{href}", doc, compress_type=zipfile.ZIP_DEFLATED)
159
+ for n in pictures:
160
+ z.write(Path(images_dir) / n, f"OEBPS/images/{n}", compress_type=zipfile.ZIP_STORED) # already compressed
161
+ return buf.getvalue()
162
+
163
+
164
+ # ---------------------------------------------------------------- PDF
165
+ PDF_CSS = """\
166
+ body { font-family: sans-serif; line-height: 1.55; }
167
+ h1, h2, h3, h4, h5 { font-family: sans-serif; font-weight: bold; margin-top: 14pt; margin-bottom: 5pt; }
168
+ h1 { font-size: 22pt; }
169
+ h2 { font-size: 16pt; border-bottom: 0.6pt solid #bbbbbb; padding-bottom: 2pt; }
170
+ h3 { font-size: 13pt; }
171
+ h4, h5 { font-size: 11.5pt; }
172
+ h1.doc-title { text-align: center; margin-top: 200pt; margin-bottom: 40pt; page-break-after: always; }
173
+ p { margin-top: 0; margin-bottom: 6pt; }
174
+ li p { margin: 0; }
175
+ ul, ol { margin-top: 2pt; margin-bottom: 6pt; }
176
+ pre { font-family: monospace; font-size: 9pt; background-color: #f1f1f1; padding: 5pt; margin: 6pt 0; white-space: pre-wrap; }
177
+ code { font-family: monospace; }
178
+ code.math { color: #7a3e9d; }
179
+ table { border-collapse: collapse; margin: 6pt 0; }
180
+ td, th { border: 0.5pt solid #999999; padding: 3pt; vertical-align: top; }
181
+ th { background-color: #eeeeee; }
182
+ blockquote { margin: 6pt 0 6pt 8pt; padding-left: 8pt; border-left: 2pt solid #bbbbbb; color: #444444; }
183
+ a { color: #1a56b0; }
184
+ """
185
+
186
+
187
+ def build_pdf(title: str, chapters: list[Chapter], images_dir: Path | None = None) -> bytes:
188
+ title = title.strip() or "PDFTran"
189
+ body = f'<h1 class="doc-title">{escape(title)}</h1>' + "".join(_strip_ns(c.xhtml) for c in chapters)
190
+ pictures = _used_images(chapters, images_dir)
191
+ archive = pymupdf.Archive() if pictures else None # lets Story find `images/<name>`
192
+ for n in pictures:
193
+ path = Path(images_dir) / n
194
+ if n.endswith(".svg"): # drawn at PDF_SVG_ZOOM times its size as a PNG: crisp, and the layout needs no SVG support
195
+ with pymupdf.open(str(path)) as svg:
196
+ rect = svg[0].rect
197
+ png = svg[0].get_pixmap(matrix=pymupdf.Matrix(PDF_SVG_ZOOM, PDF_SVG_ZOOM), alpha=False).tobytes("png")
198
+ width, shown = rect.width, n[:-4] + ".png"
199
+ archive.add(png, f"images/{shown}")
200
+ else:
201
+ pix = pymupdf.Pixmap(str(path))
202
+ width, shown = pix.width * 0.5, n # their size follows the pixels
203
+ archive.add(path.read_bytes(), f"images/{n}")
204
+ width = max(40, min(width, 420)) # an explicit width (pt) keeps pictures inside the page
205
+ body = re.sub(rf'<img\b([^>]*?)src="images/{re.escape(n)}"', rf'<img\1src="images/{shown}" width="{width:.0f}"', body)
206
+ story = pymupdf.Story(html=f"<html><body>{body}</body></html>", user_css=PDF_CSS, em=10.5, archive=archive)
207
+ buf = io.BytesIO()
208
+ writer = pymupdf.DocumentWriter(buf)
209
+ mediabox = pymupdf.paper_rect("a4")
210
+ where = mediabox + (56, 60, -56, -64)
211
+ headings: list[tuple[int, str, int]] = [] # (heading level, text, 1-based page)
212
+
213
+ def record(pos):
214
+ if pos.heading and (pos.open_close & 1) and pos.text and pos.text.strip():
215
+ headings.append((pos.heading, " ".join(pos.text.split()), pos.pg))
216
+
217
+ page_no, more = 0, 1
218
+ while more:
219
+ dev = writer.begin_page(mediabox)
220
+ more, _ = story.place(where)
221
+ page_no += 1
222
+ story.element_positions(record, {"pg": page_no})
223
+ story.draw(dev)
224
+ writer.end_page()
225
+ writer.close()
226
+
227
+ doc = pymupdf.open("pdf", buf.getvalue())
228
+ for i, page in enumerate(doc, 1):
229
+ if i == 1:
230
+ continue # the title page carries no number
231
+ label = str(i)
232
+ w = pymupdf.get_text_length(label, fontname="helv", fontsize=9)
233
+ page.insert_text(((mediabox.width - w) / 2, mediabox.height - 36), label, fontname="helv", fontsize=9, color=(0.45, 0.45, 0.45))
234
+ toc, prev = [], 0
235
+ shallow = [h for h in headings if h[0] <= MAX_OUTLINE_LEVEL]
236
+ if shallow:
237
+ base = min(h[0] for h in shallow)
238
+ for level, text, pg in shallow:
239
+ lv = max(1, min(level - base + 1, prev + 1))
240
+ toc.append([lv, text, pg])
241
+ prev = lv
242
+ doc.set_toc(toc)
243
+ doc.set_metadata({"title": title, "producer": "PDFTran"})
244
+ try:
245
+ doc.subset_fonts() # the CJK fallback font is ~1.7 MB whole; keep only the glyphs used
246
+ except Exception: # noqa: BLE001 - a bigger file is better than no file
247
+ pass
248
+ return doc.tobytes(garbage=3, deflate=True)