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.
- pdftran/__init__.py +9 -0
- pdftran/adoc.py +93 -0
- pdftran/archive.py +145 -0
- pdftran/carry.py +68 -0
- pdftran/cli.py +175 -0
- pdftran/credentials.py +35 -0
- pdftran/desktop.py +406 -0
- pdftran/export.py +248 -0
- pdftran/extract.py +456 -0
- pdftran/glossary.py +80 -0
- pdftran/paths.py +45 -0
- pdftran/pipeline.py +474 -0
- pdftran/py.typed +0 -0
- pdftran/server.py +357 -0
- pdftran/static/app.js +833 -0
- pdftran/static/desktop.js +149 -0
- pdftran/static/gedit.js +435 -0
- pdftran/static/index.html +171 -0
- pdftran/static/logo/pdftran-macos.png +0 -0
- pdftran/static/logo/pdftran.icns +0 -0
- pdftran/static/logo/pdftran.ico +0 -0
- pdftran/static/logo/pdftran.svg +19 -0
- pdftran/static/style.css +275 -0
- pdftran/static/vendor/asciidoctor.min.js +1483 -0
- pdftran/static/vendor/katex/LICENSE +21 -0
- pdftran/static/vendor/katex/fonts/KaTeX_AMS-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Caligraphic-Bold.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Caligraphic-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Fraktur-Bold.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Fraktur-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Main-Bold.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Main-BoldItalic.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Main-Italic.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Main-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Math-BoldItalic.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Math-Italic.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_SansSerif-Bold.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_SansSerif-Italic.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_SansSerif-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Script-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Size1-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Size2-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Size3-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Size4-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/fonts/KaTeX_Typewriter-Regular.woff2 +0 -0
- pdftran/static/vendor/katex/katex.min.css +1 -0
- pdftran/static/vendor/katex/katex.min.js +1 -0
- pdftran/static/vendor/pdf.min.mjs +28 -0
- pdftran/static/vendor/pdf.worker.min.mjs +28 -0
- pdftran/translate.py +237 -0
- pdftran/winctl.py +431 -0
- pdftran-0.2.0.dist-info/METADATA +338 -0
- pdftran-0.2.0.dist-info/RECORD +56 -0
- pdftran-0.2.0.dist-info/WHEEL +4 -0
- pdftran-0.2.0.dist-info/entry_points.txt +4 -0
- pdftran-0.2.0.dist-info/licenses/LICENSE +674 -0
pdftran/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"""PDFTran: PDF → Traditional Chinese AsciiDoc translator with a side-by-side viewer."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version as _dist_version
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
# pyproject.toml is the single source of truth; the frozen app ships the metadata (see packaging/PDFTran.spec)
|
|
7
|
+
__version__ = _dist_version("pdftran")
|
|
8
|
+
except PackageNotFoundError: # running from a source tree that was never installed
|
|
9
|
+
__version__ = "dev"
|
pdftran/adoc.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Assemble the AsciiDoc output and parse page markers.
|
|
2
|
+
|
|
3
|
+
Marker spec (AsciiDoc comment lines, invisible in any renderer):
|
|
4
|
+
|
|
5
|
+
// @page 5 starts the translation of source page 5
|
|
6
|
+
// @span 5-6 a paragraph that starts on page 5 and ends on page 6
|
|
7
|
+
(placed inside page 5's block; does NOT start a new section)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import re
|
|
13
|
+
|
|
14
|
+
PAGE_RE = re.compile(r"^// @page (\d+)\s*$", re.M)
|
|
15
|
+
SPAN_RE = re.compile(r"^// @span (\d+)-(\d+)\s*$", re.M)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
_TITLE_LINE = re.compile(r"^=([ \t]+\S.*)$")
|
|
19
|
+
_FENCES = ("----", "....", "++++", "////")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def fix_title_levels(text: str) -> str:
|
|
23
|
+
"""Turn a heading written with a single `=` into a level-1 section (`==`).
|
|
24
|
+
|
|
25
|
+
A single `=` is the title of the whole document (the first line of the assembled file); the model sometimes uses it
|
|
26
|
+
for a chapter title, and the viewer then hides it. Lines inside code / passthrough / comment blocks are left alone."""
|
|
27
|
+
out, fence = [], None
|
|
28
|
+
for line in text.split("\n"):
|
|
29
|
+
stripped = line.strip()
|
|
30
|
+
if fence:
|
|
31
|
+
if stripped == fence:
|
|
32
|
+
fence = None
|
|
33
|
+
elif len(stripped) >= 4 and stripped == stripped[0] * len(stripped) and stripped[0] * 4 in _FENCES:
|
|
34
|
+
fence = stripped
|
|
35
|
+
else:
|
|
36
|
+
m = _TITLE_LINE.match(line)
|
|
37
|
+
if m:
|
|
38
|
+
line = "==" + m.group(1)
|
|
39
|
+
out.append(line)
|
|
40
|
+
return "\n".join(out)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def page_block(state: dict, n: int) -> str:
|
|
44
|
+
"""The editable AsciiDoc of page n: its translation plus paragraphs carried over from n to later pages."""
|
|
45
|
+
pages = state["pages"]
|
|
46
|
+
page = pages[n - 1]
|
|
47
|
+
parts = [fix_title_levels((page.get("translation") or "").strip())]
|
|
48
|
+
for q in pages:
|
|
49
|
+
if q.get("carry_origin") == n and q.get("carry_translation"):
|
|
50
|
+
parts.append(f"// @span {n}-{q['n']}\n\n{fix_title_levels(q['carry_translation'].strip())}")
|
|
51
|
+
return "\n\n".join(p for p in parts if p)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def assemble(state: dict) -> str:
|
|
55
|
+
title = state.get("source_name") or "Translation"
|
|
56
|
+
out = [f"= {title}", ":lang: zh-Hant", ""]
|
|
57
|
+
for p in state["pages"]:
|
|
58
|
+
out.append(f"// @page {p['n']}")
|
|
59
|
+
out.append("")
|
|
60
|
+
block = page_block(state, p["n"])
|
|
61
|
+
if block:
|
|
62
|
+
out.append(block)
|
|
63
|
+
out.append("")
|
|
64
|
+
return "\n".join(out).rstrip() + "\n"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def parse_block(n: int, text: str) -> tuple[str, dict[int, str]]:
|
|
68
|
+
"""Inverse of page_block: returns (page translation, {later page: carried paragraph translation}).
|
|
69
|
+
|
|
70
|
+
A stray `// @page N` line is dropped (it would split the page); `// @span` markers whose start
|
|
71
|
+
isn't page n are ignored, so their text stays part of the page translation.
|
|
72
|
+
"""
|
|
73
|
+
text = PAGE_RE.sub("", text)
|
|
74
|
+
pieces = SPAN_RE.split(text) # [head, a, b, body, a, b, body, ...]
|
|
75
|
+
head = pieces[0]
|
|
76
|
+
carried: dict[int, str] = {}
|
|
77
|
+
for i in range(1, len(pieces), 3):
|
|
78
|
+
a, b, body = int(pieces[i]), int(pieces[i + 1]), pieces[i + 2]
|
|
79
|
+
if a == n and b > n:
|
|
80
|
+
carried[b] = body.strip()
|
|
81
|
+
else:
|
|
82
|
+
head += "\n\n" + body
|
|
83
|
+
return head.strip(), carried
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def split_pages(adoc: str) -> dict[int, str]:
|
|
87
|
+
"""Return {page number: AsciiDoc text of that page's block}."""
|
|
88
|
+
matches = list(PAGE_RE.finditer(adoc))
|
|
89
|
+
result: dict[int, str] = {}
|
|
90
|
+
for i, m in enumerate(matches):
|
|
91
|
+
end = matches[i + 1].start() if i + 1 < len(matches) else len(adoc)
|
|
92
|
+
result[int(m.group(1))] = adoc[m.end():end].strip()
|
|
93
|
+
return result
|
pdftran/archive.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""Pack a project into one .zip (backup / move to another computer) and unpack such a .zip as a new project.
|
|
2
|
+
|
|
3
|
+
The archive holds the project folder's files: `source.pdf`, `state.json`, `glossary.json` and `<id>.adoc`.
|
|
4
|
+
Only `source.pdf` and `state.json` are needed to import; the other two are regenerated from the state.
|
|
5
|
+
Nothing from outside the project (API key, settings) is ever packed.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import io
|
|
11
|
+
import json
|
|
12
|
+
import re
|
|
13
|
+
import shutil
|
|
14
|
+
import zipfile
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
import pymupdf
|
|
18
|
+
|
|
19
|
+
from .pipeline import STATE_FILE, Project, list_projects, slugify
|
|
20
|
+
|
|
21
|
+
STATUSES = {"pending", "running", "done", "stale", "error"}
|
|
22
|
+
IMAGE_NAME = re.compile(r"[\w\-]+\.(?:png|jpg|svg)") # the only file names allowed in a project's images/ folder
|
|
23
|
+
_UNSAFE_SVG = re.compile(r"<\s*(?:script|foreignObject|iframe|object|embed)|\bon\w+\s*=|javascript:|(?:href|src)\s*=\s*['\"]\s*(?!#|data:image/)", re.I)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def is_safe_svg(data: bytes) -> bool:
|
|
27
|
+
"""Our own SVGs are plain paths; one from an imported file must not carry scripts, handlers or external references."""
|
|
28
|
+
try:
|
|
29
|
+
text = data.decode("utf-8")
|
|
30
|
+
except UnicodeDecodeError:
|
|
31
|
+
return False
|
|
32
|
+
return text.lstrip().startswith(("<svg", "<?xml")) and not _UNSAFE_SVG.search(text)
|
|
33
|
+
MAX_MEMBER_BYTES = 1024 * 1024 * 1024 # refuse absurd (zip-bomb) members
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def pack(project: Project) -> bytes:
|
|
37
|
+
"""The project as a .zip (a consistent snapshot: taken under the project's lock)."""
|
|
38
|
+
buf = io.BytesIO()
|
|
39
|
+
with project.lock, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
|
|
40
|
+
for name in ("source.pdf", STATE_FILE, "glossary.json", f"{project.id}.adoc"):
|
|
41
|
+
path = project.dir / name
|
|
42
|
+
if path.exists():
|
|
43
|
+
z.write(path, name)
|
|
44
|
+
images = project.dir / "images"
|
|
45
|
+
for img in sorted(images.glob("*")) if images.is_dir() else []:
|
|
46
|
+
if IMAGE_NAME.fullmatch(img.name):
|
|
47
|
+
z.write(img, f"images/{img.name}")
|
|
48
|
+
return buf.getvalue()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _validate_state(state) -> None:
|
|
52
|
+
"""Raises ValueError unless `state` looks like a PDFTran project state; fills in optional fields."""
|
|
53
|
+
bad = ValueError("不是有效的 PDFTran 專案檔(state.json 內容不正確)")
|
|
54
|
+
if not isinstance(state, dict) or not isinstance(state.get("source_name"), str):
|
|
55
|
+
raise bad
|
|
56
|
+
pages, glossary = state.get("pages"), state.get("glossary", [])
|
|
57
|
+
if not isinstance(pages, list) or not pages or not isinstance(glossary, list):
|
|
58
|
+
raise bad
|
|
59
|
+
for i, p in enumerate(pages, 1):
|
|
60
|
+
if not isinstance(p, dict) or p.get("n") != i or p.get("status") not in STATUSES:
|
|
61
|
+
raise bad
|
|
62
|
+
if not isinstance(p.get("own"), list) or not isinstance(p.get("translation", ""), str):
|
|
63
|
+
raise bad
|
|
64
|
+
p.setdefault("translation", "")
|
|
65
|
+
imgs = p.get("images", []) # absent in projects made before pictures were extracted: stays absent (= legacy)
|
|
66
|
+
if not isinstance(imgs, list) or not all(isinstance(n, str) and IMAGE_NAME.fullmatch(n) for n in imgs):
|
|
67
|
+
raise bad
|
|
68
|
+
for key in ("carry_in", "carry_origin", "carry_translation", "error"):
|
|
69
|
+
p.setdefault(key, None)
|
|
70
|
+
for key in ("edited", "carry_edited"):
|
|
71
|
+
p.setdefault(key, False)
|
|
72
|
+
for t in glossary:
|
|
73
|
+
if not isinstance(t, dict) or not isinstance(t.get("source"), str) or not isinstance(t.get("target"), str):
|
|
74
|
+
raise bad
|
|
75
|
+
t.setdefault("note", "")
|
|
76
|
+
t.setdefault("first_page", 0)
|
|
77
|
+
t.setdefault("locked", False)
|
|
78
|
+
state["glossary"] = glossary
|
|
79
|
+
state.setdefault("version", 1)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def unpack(root: Path, data: bytes) -> Project:
|
|
83
|
+
"""Create a new project from an archive made by `pack`. Raises ValueError with a message for the user."""
|
|
84
|
+
try:
|
|
85
|
+
z = zipfile.ZipFile(io.BytesIO(data))
|
|
86
|
+
except zipfile.BadZipFile as e:
|
|
87
|
+
raise ValueError("不是有效的專案檔(需要 PDFTran 匯出的 .zip)") from e
|
|
88
|
+
with z:
|
|
89
|
+
names = set(z.namelist())
|
|
90
|
+
if "state.json" not in names or "source.pdf" not in names:
|
|
91
|
+
raise ValueError("不是 PDFTran 的專案檔(缺少 state.json 或 source.pdf)")
|
|
92
|
+
if any(z.getinfo(n).file_size > MAX_MEMBER_BYTES for n in ("state.json", "source.pdf")):
|
|
93
|
+
raise ValueError("專案檔太大")
|
|
94
|
+
try:
|
|
95
|
+
state = json.loads(z.read("state.json").decode("utf-8"))
|
|
96
|
+
except (UnicodeDecodeError, json.JSONDecodeError) as e:
|
|
97
|
+
raise ValueError("不是有效的 PDFTran 專案檔(state.json 無法讀取)") from e
|
|
98
|
+
_validate_state(state)
|
|
99
|
+
pdf = z.read("source.pdf")
|
|
100
|
+
wanted = {n for p in state["pages"] for n in p.get("images", [])}
|
|
101
|
+
pictures = {n: z.read(f"images/{n}") for n in sorted(wanted) if f"images/{n}" in names} # only what the state names
|
|
102
|
+
if wanted - set(pictures):
|
|
103
|
+
raise ValueError("專案檔缺少部分圖片(images/ 資料夾不完整)")
|
|
104
|
+
if any(n.endswith(".svg") and not is_safe_svg(d) for n, d in pictures.items()):
|
|
105
|
+
raise ValueError("專案檔裡的 SVG 圖片含有不安全的內容(腳本或外部連結),已拒絕匯入")
|
|
106
|
+
if not pdf.startswith(b"%PDF"):
|
|
107
|
+
raise ValueError("專案檔裡的 source.pdf 不是有效的 PDF")
|
|
108
|
+
try:
|
|
109
|
+
with pymupdf.open("pdf", pdf) as doc:
|
|
110
|
+
count = doc.page_count
|
|
111
|
+
except Exception as e: # noqa: BLE001
|
|
112
|
+
raise ValueError(f"專案檔裡的 PDF 無法開啟:{e}") from e
|
|
113
|
+
if count != len(state["pages"]):
|
|
114
|
+
raise ValueError(f"專案檔的內容不一致(PDF 有 {count} 頁,但狀態記錄 {len(state['pages'])} 頁)")
|
|
115
|
+
|
|
116
|
+
pid = slugify(state["source_name"] + ".pdf")
|
|
117
|
+
base, i = pid, 2
|
|
118
|
+
existing = set(list_projects(root))
|
|
119
|
+
while pid in existing:
|
|
120
|
+
pid, i = f"{base}-{i}", i + 1
|
|
121
|
+
proj = Project(root, pid)
|
|
122
|
+
proj.dir.mkdir(parents=True, exist_ok=False)
|
|
123
|
+
try:
|
|
124
|
+
proj.pdf_path.write_bytes(pdf)
|
|
125
|
+
if pictures:
|
|
126
|
+
(proj.dir / "images").mkdir()
|
|
127
|
+
for name, data_ in pictures.items():
|
|
128
|
+
(proj.dir / "images" / name).write_bytes(data_)
|
|
129
|
+
proj.state = state
|
|
130
|
+
for p in proj.pages: # an archive taken mid-run must not leave pages stuck
|
|
131
|
+
if p["status"] == "running":
|
|
132
|
+
p["status"] = "pending"
|
|
133
|
+
proj.save() # writes state.json, glossary.json and <id>.adoc
|
|
134
|
+
except Exception:
|
|
135
|
+
shutil.rmtree(proj.dir, ignore_errors=True)
|
|
136
|
+
raise
|
|
137
|
+
return proj
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def delete(root: Path, project_id: str) -> None:
|
|
141
|
+
"""Remove the project folder (source copy, translation, glossary). Refuses anything that isn't a project."""
|
|
142
|
+
target = (Path(root) / project_id).resolve()
|
|
143
|
+
if target.parent != Path(root).resolve() or not (target / STATE_FILE).exists():
|
|
144
|
+
raise ValueError("找不到專案")
|
|
145
|
+
shutil.rmtree(target)
|
pdftran/carry.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Decide whether the last paragraph of a page is unfinished (continues on next page)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import statistics
|
|
6
|
+
|
|
7
|
+
from .extract import Paragraph, caption_number
|
|
8
|
+
|
|
9
|
+
_TERMINALS = set(".?!:;。?!:;…")
|
|
10
|
+
_CLOSERS = "\"'”’))」』]】"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
FOOTNOTE_SIZE = 0.9 # a block set in less than this share of the body size is a footnote / note, not running text
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def body_size(pages: list[list[Paragraph]]) -> float:
|
|
17
|
+
"""The body font size of a document: the median over the text, weighted by length."""
|
|
18
|
+
sizes: list[float] = []
|
|
19
|
+
for paras in pages:
|
|
20
|
+
for p in paras:
|
|
21
|
+
if p.size > 0 and not p.image:
|
|
22
|
+
sizes.extend([round(p.size, 1)] * min(len(p.text), 400))
|
|
23
|
+
return statistics.median(sizes) if sizes else 0.0
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def is_float(p: Paragraph, body: float) -> bool:
|
|
27
|
+
"""A block that sits at the foot of a page without being part of the running text: a figure, its caption, a footnote."""
|
|
28
|
+
if p.image or caption_number(p.text) is not None:
|
|
29
|
+
return True
|
|
30
|
+
return bool(body) and 0 < p.size <= body * FOOTNOTE_SIZE and not p.heading
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def first_text(paras: list[Paragraph], body: float) -> Paragraph | None:
|
|
34
|
+
"""The first block of running text of a page (leading figures, captions, small running heads are skipped)."""
|
|
35
|
+
return next((p for p in paras if not is_float(p, body) and not p.heading), None)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def find_tail(paras: list[Paragraph], next_first: Paragraph | None, body: float = 0.0) -> int | None:
|
|
39
|
+
"""Index of the paragraph that continues on the next page, or None.
|
|
40
|
+
|
|
41
|
+
It is the last paragraph of running text: figures, captions and footnotes below it do not count, because a
|
|
42
|
+
figure or a footnote can sit between the unfinished sentence and the bottom of the page."""
|
|
43
|
+
i = len(paras) - 1
|
|
44
|
+
while i >= 0 and is_float(paras[i], body):
|
|
45
|
+
i -= 1
|
|
46
|
+
if i < 0:
|
|
47
|
+
return None
|
|
48
|
+
return i if is_incomplete(paras[i], next_first) else None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def is_incomplete(last: Paragraph, next_first: Paragraph | None) -> bool:
|
|
52
|
+
"""Heuristic: True if `last` obviously does not end on this page.
|
|
53
|
+
|
|
54
|
+
A false positive is cheap (a complete paragraph just gets translated with
|
|
55
|
+
the next page), so we lean towards "incomplete".
|
|
56
|
+
"""
|
|
57
|
+
text = last.text.rstrip()
|
|
58
|
+
if not text or last.heading or last.image: # a picture is always complete
|
|
59
|
+
return False
|
|
60
|
+
if text.endswith("-") or text.endswith("—") or text.endswith(","):
|
|
61
|
+
return True
|
|
62
|
+
stripped = text.rstrip(_CLOSERS)
|
|
63
|
+
ends_terminal = bool(stripped) and stripped[-1] in _TERMINALS
|
|
64
|
+
if next_first is not None and not next_first.heading and not next_first.image:
|
|
65
|
+
nxt = next_first.text.lstrip()
|
|
66
|
+
if nxt and nxt[0].islower():
|
|
67
|
+
return True
|
|
68
|
+
return not ends_terminal
|
pdftran/cli.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Command line entry.
|
|
2
|
+
|
|
3
|
+
pdftran desktop window (the packaged PDFTran.exe does this when double-clicked)
|
|
4
|
+
pdftran serve [--port N] browser mode: only start the backend
|
|
5
|
+
pdftran translate file.pdf translate a whole PDF on the command line
|
|
6
|
+
pdftran --version
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import argparse
|
|
12
|
+
import ctypes
|
|
13
|
+
import json
|
|
14
|
+
import multiprocessing
|
|
15
|
+
import os
|
|
16
|
+
import sys
|
|
17
|
+
import webbrowser
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
from .paths import FROZEN, data_dir, migrate_legacy_data
|
|
22
|
+
from .pipeline import Project, slugify
|
|
23
|
+
|
|
24
|
+
NAME = "PDFTran"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _setup_streams(data: Path, cli_use: bool) -> None:
|
|
28
|
+
"""A windowed (no console) build has sys.stdout/stderr = None, which breaks print() and logging.
|
|
29
|
+
|
|
30
|
+
- With arguments (command-line use): attach to the parent terminal.
|
|
31
|
+
- Still no output pipe (e.g. double-clicked): write to pdftran.log in the data folder.
|
|
32
|
+
"""
|
|
33
|
+
if sys.platform == "win32" and cli_use and (sys.stdout is None or sys.stderr is None):
|
|
34
|
+
try:
|
|
35
|
+
if ctypes.windll.kernel32.AttachConsole(-1): # ATTACH_PARENT_PROCESS
|
|
36
|
+
if sys.stdout is None:
|
|
37
|
+
sys.stdout = open("CONOUT$", "w", encoding="utf-8", buffering=1)
|
|
38
|
+
if sys.stderr is None:
|
|
39
|
+
sys.stderr = open("CONOUT$", "w", encoding="utf-8", buffering=1)
|
|
40
|
+
except OSError:
|
|
41
|
+
pass
|
|
42
|
+
if sys.stdout is None or sys.stderr is None:
|
|
43
|
+
data.mkdir(parents=True, exist_ok=True)
|
|
44
|
+
log = open(data / "pdftran.log", "a", encoding="utf-8", buffering=1)
|
|
45
|
+
sys.stdout = sys.stdout or log
|
|
46
|
+
sys.stderr = sys.stderr or log
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def selftest(data: Path) -> int:
|
|
50
|
+
"""Report whether each dependency loads: confirms a packaged build isn't missing anything."""
|
|
51
|
+
import importlib
|
|
52
|
+
|
|
53
|
+
out: dict = {}
|
|
54
|
+
for name in ("fastapi", "uvicorn", "pymupdf", "anthropic", "keyring", "webview"):
|
|
55
|
+
try:
|
|
56
|
+
mod = importlib.import_module(name)
|
|
57
|
+
out[name] = getattr(mod, "__version__", "ok")
|
|
58
|
+
except Exception as e: # noqa: BLE001
|
|
59
|
+
out[name] = f"FAIL: {type(e).__name__}: {e}"
|
|
60
|
+
try: # a missing credential-store backend means keys silently can't be saved
|
|
61
|
+
import keyring
|
|
62
|
+
|
|
63
|
+
backend = type(keyring.get_keyring()).__name__
|
|
64
|
+
out["keyring_backend"] = f"FAIL: {backend}" if "Fail" in backend else backend
|
|
65
|
+
except Exception as e: # noqa: BLE001
|
|
66
|
+
out["keyring_backend"] = f"FAIL: {type(e).__name__}: {e}"
|
|
67
|
+
if sys.platform == "win32":
|
|
68
|
+
# `import webview` doesn't prove .NET loads: pywebview only loads pythonnet when a window opens.
|
|
69
|
+
# Loading it here is what a desktop launch does first; on a copy marked "downloaded from the
|
|
70
|
+
# Internet" this verifies the .exe.config next to PDFTran.exe (see packaging/PDFTran.exe.config).
|
|
71
|
+
try:
|
|
72
|
+
import clr # pythonnet: loads Python.Runtime.dll
|
|
73
|
+
|
|
74
|
+
clr.AddReference("System.Windows.Forms")
|
|
75
|
+
out["pythonnet_clr"] = "ok"
|
|
76
|
+
except Exception as e: # noqa: BLE001
|
|
77
|
+
out["pythonnet_clr"] = f"FAIL: {type(e).__name__}: {e}"
|
|
78
|
+
from .server import STATIC
|
|
79
|
+
|
|
80
|
+
for f in ("index.html", "app.js", "gedit.js", "vendor/pdf.min.mjs", "vendor/asciidoctor.min.js", "logo/pdftran.ico"):
|
|
81
|
+
if not (STATIC / f).exists():
|
|
82
|
+
out[f"static/{f}"] = "FAIL: missing"
|
|
83
|
+
out["version"] = (
|
|
84
|
+
f"FAIL: the packaged build can't read its version ({__version__})" if FROZEN and __version__ == "dev" else __version__
|
|
85
|
+
)
|
|
86
|
+
out.update(frozen=FROZEN, data_dir=str(data))
|
|
87
|
+
text = json.dumps(out, ensure_ascii=False, indent=2)
|
|
88
|
+
print(text)
|
|
89
|
+
target = os.environ.get("PDFTRAN_SELFTEST_OUT") # a windowed exe has no console (e.g. in CI): also write a file
|
|
90
|
+
if target:
|
|
91
|
+
Path(target).write_text(text, encoding="utf-8")
|
|
92
|
+
return 1 if any(str(v).startswith("FAIL") for v in out.values()) else 0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
96
|
+
ap = argparse.ArgumentParser(
|
|
97
|
+
prog="pdftran",
|
|
98
|
+
description="PDF → 繁體中文 AsciiDoc 翻譯工具。不加子命令時開啟桌面視窗。",
|
|
99
|
+
)
|
|
100
|
+
ap.add_argument("--data-dir", default=None, help="資料夾(預設為使用者資料夾,或環境變數 PDFTRAN_DATA_DIR)")
|
|
101
|
+
ap.add_argument("-V", "--version", action="version", version=f"{NAME} {__version__}")
|
|
102
|
+
ap.add_argument("--native-titlebar", action="store_true", help="桌面模式使用系統標題列(預設在 Windows 上是無標題列視窗,工具列兼任標題列)")
|
|
103
|
+
ap.add_argument("--selftest", action="store_true", help=argparse.SUPPRESS) # checks a packaged build
|
|
104
|
+
sub = ap.add_subparsers(dest="cmd")
|
|
105
|
+
|
|
106
|
+
t = sub.add_parser("translate", help="命令列翻譯整份 PDF")
|
|
107
|
+
t.add_argument("pdf")
|
|
108
|
+
t.add_argument("--model", default=None)
|
|
109
|
+
|
|
110
|
+
s = sub.add_parser("serve", help="瀏覽器模式:只啟動後端")
|
|
111
|
+
s.add_argument("--host", default="127.0.0.1")
|
|
112
|
+
s.add_argument("--port", type=int, default=8765)
|
|
113
|
+
s.add_argument("--no-browser", action="store_true")
|
|
114
|
+
return ap
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def main(argv: list[str] | None = None) -> int:
|
|
118
|
+
multiprocessing.freeze_support()
|
|
119
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
120
|
+
args = build_parser().parse_args(argv)
|
|
121
|
+
data = Path(args.data_dir) if args.data_dir else data_dir()
|
|
122
|
+
_setup_streams(data, cli_use=bool(argv))
|
|
123
|
+
|
|
124
|
+
if args.selftest:
|
|
125
|
+
return selftest(data)
|
|
126
|
+
if args.cmd is None:
|
|
127
|
+
from .desktop import run_desktop
|
|
128
|
+
|
|
129
|
+
return run_desktop(data, native_titlebar=args.native_titlebar)
|
|
130
|
+
|
|
131
|
+
migrate_legacy_data(data)
|
|
132
|
+
root = data / "projects"
|
|
133
|
+
|
|
134
|
+
if args.cmd == "translate":
|
|
135
|
+
from .translate import ClaudeTranslator
|
|
136
|
+
|
|
137
|
+
pdf = Path(args.pdf)
|
|
138
|
+
pid = slugify(pdf.name)
|
|
139
|
+
if (root / pid / "state.json").exists():
|
|
140
|
+
proj = Project.load(root, pid) # resume
|
|
141
|
+
else:
|
|
142
|
+
proj = Project.create(root, pid, pdf.read_bytes(), pdf.stem)
|
|
143
|
+
total = len(proj.pages)
|
|
144
|
+
translator = ClaudeTranslator(model=args.model)
|
|
145
|
+
|
|
146
|
+
def progress(tr):
|
|
147
|
+
def wrapped(req):
|
|
148
|
+
print(f"[{req.page}/{total}] 翻譯中…", flush=True)
|
|
149
|
+
return tr(req)
|
|
150
|
+
|
|
151
|
+
return wrapped
|
|
152
|
+
|
|
153
|
+
proj.run(progress(translator))
|
|
154
|
+
bad = [p for p in proj.pages if p["status"] == "error"]
|
|
155
|
+
for p in bad:
|
|
156
|
+
print(f"第 {p['n']} 頁失敗:{p['error']}", file=sys.stderr)
|
|
157
|
+
print(f"輸出:{root / pid / (pid + '.adoc')}")
|
|
158
|
+
return 1 if bad else 0
|
|
159
|
+
|
|
160
|
+
import uvicorn
|
|
161
|
+
|
|
162
|
+
from .server import create_app
|
|
163
|
+
|
|
164
|
+
url = f"http://{args.host}:{args.port}/"
|
|
165
|
+
if not args.no_browser:
|
|
166
|
+
import threading
|
|
167
|
+
|
|
168
|
+
threading.Timer(1.0, lambda: webbrowser.open(url)).start()
|
|
169
|
+
print(f"PDFTran 介面:{url}\n資料夾:{data}", flush=True)
|
|
170
|
+
uvicorn.run(create_app(data), host=args.host, port=args.port, log_level="warning")
|
|
171
|
+
return 0
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
if __name__ == "__main__":
|
|
175
|
+
raise SystemExit(main())
|
pdftran/credentials.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Persist the API key in the OS credential store (Windows Credential Manager / macOS Keychain / Secret Service)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
SERVICE = "PDFTran"
|
|
6
|
+
ACCOUNT = "anthropic-api-key"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def load_key() -> str | None:
|
|
10
|
+
try:
|
|
11
|
+
import keyring
|
|
12
|
+
|
|
13
|
+
return keyring.get_password(SERVICE, ACCOUNT) or None
|
|
14
|
+
except Exception: # noqa: BLE001 - no usable backend (e.g. headless Linux)
|
|
15
|
+
return None
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def save_key(key: str) -> bool:
|
|
19
|
+
"""Returns True if the key was stored; False if no credential store is available."""
|
|
20
|
+
try:
|
|
21
|
+
import keyring
|
|
22
|
+
|
|
23
|
+
keyring.set_password(SERVICE, ACCOUNT, key)
|
|
24
|
+
return True
|
|
25
|
+
except Exception: # noqa: BLE001
|
|
26
|
+
return False
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def delete_key() -> None:
|
|
30
|
+
try:
|
|
31
|
+
import keyring
|
|
32
|
+
|
|
33
|
+
keyring.delete_password(SERVICE, ACCOUNT)
|
|
34
|
+
except Exception: # noqa: BLE001 - nothing stored / no backend
|
|
35
|
+
pass
|