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/pipeline.py
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
"""Page-by-page translation pipeline with resumable state."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
import threading
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Callable
|
|
11
|
+
|
|
12
|
+
from . import adoc, glossary
|
|
13
|
+
from .carry import body_size, find_tail, first_text
|
|
14
|
+
from .extract import LABEL_MAX_CHARS, Paragraph, extract_pages, normalize_caption_number, render_page_image
|
|
15
|
+
from .translate import Translator, TranslationRequest
|
|
16
|
+
|
|
17
|
+
STATE_FILE = "state.json"
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def plan_pages(extracted: list[list[Paragraph]]) -> list[dict]:
|
|
21
|
+
"""Decide per page: own paragraphs, unfinished tail, and carry-in from the previous page."""
|
|
22
|
+
pages: list[dict] = []
|
|
23
|
+
carry_text: str | None = None
|
|
24
|
+
carry_origin: int | None = None
|
|
25
|
+
last = len(extracted) - 1
|
|
26
|
+
body = body_size(extracted)
|
|
27
|
+
for i, paras in enumerate(extracted):
|
|
28
|
+
n = i + 1
|
|
29
|
+
own = list(paras)
|
|
30
|
+
tail: str | None = None
|
|
31
|
+
if own and i < last:
|
|
32
|
+
k = find_tail(own, first_text(extracted[i + 1], body), body)
|
|
33
|
+
if k is not None: # not necessarily the last block: a figure or footnote may follow the unfinished paragraph
|
|
34
|
+
tail = own.pop(k).text
|
|
35
|
+
pages.append(
|
|
36
|
+
{
|
|
37
|
+
"n": n,
|
|
38
|
+
"own": [p.to_dict() for p in own],
|
|
39
|
+
"images": [p.image for p in own if p.image], # pictures on this page (files in images/)
|
|
40
|
+
"carry_in": carry_text,
|
|
41
|
+
"carry_origin": carry_origin,
|
|
42
|
+
"status": "pending",
|
|
43
|
+
"translation": "",
|
|
44
|
+
"carry_translation": None,
|
|
45
|
+
"error": None,
|
|
46
|
+
}
|
|
47
|
+
)
|
|
48
|
+
if tail:
|
|
49
|
+
if not own and carry_text: # whole page is a continuation: pass the chain on untranslated
|
|
50
|
+
carry_text = f"{carry_text} {tail}"
|
|
51
|
+
pages[-1]["carry_in"] = None
|
|
52
|
+
pages[-1]["carry_origin"] = None
|
|
53
|
+
else:
|
|
54
|
+
carry_text, carry_origin = tail, n
|
|
55
|
+
else:
|
|
56
|
+
carry_text, carry_origin = None, None
|
|
57
|
+
return pages
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
_IMG_MARK = re.compile(r"[ \t]*\[IMG:([\w.\-]+)\][ \t]*")
|
|
61
|
+
_CAPTION = re.compile(r"[\s*_]*(?:圖|Figure|Fig\.?)\s*\d", re.IGNORECASE) # "圖 1.7:…", "Figure 1.7 …"
|
|
62
|
+
_CAPTION_NUMBER = re.compile(r"[\s*_]*(?:圖|Figure|Fig\.?)\s*(\d+(?:\s*[.\-–—−]\s*\d+)*)", re.IGNORECASE)
|
|
63
|
+
PLAN_VERSION = 2 # 1: only the last block of a page can be an unfinished paragraph; 2: figures, captions and footnotes below it are skipped
|
|
64
|
+
IMAGES_VERSION = 7 # 1: raster pictures only; 2: + vector figures found through their captions (PNG); 3: vector figures as SVG, + text inside figures; 4: + narrow tall vector figures; 5: figure blocks moved in front of bold captions ("*圖 3.2*"); 6: figures made of hairlines (arrows, dimension lines); 7: running heads no longer drawn into figures, small pseudocode boxes belong to the figure
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def insert_image_blocks(text: str, names: list[str], anchors: dict[str, str] | None = None) -> str:
|
|
68
|
+
"""Add the image blocks `text` does not contain yet.
|
|
69
|
+
|
|
70
|
+
Each goes before the caption with its number (`anchors`: file name → "1-2", matching "圖 1-2" / "Figure 1-2"),
|
|
71
|
+
else before the first figure caption, else at the end."""
|
|
72
|
+
missing = [n for n in names if f"images/{n}[" not in text]
|
|
73
|
+
if not missing:
|
|
74
|
+
return text
|
|
75
|
+
blocks = re.split(r"\n{2,}", text.strip()) if text.strip() else []
|
|
76
|
+
|
|
77
|
+
def number(block: str) -> str | None:
|
|
78
|
+
m = _CAPTION_NUMBER.match(block)
|
|
79
|
+
return normalize_caption_number(m.group(1)) if m else None
|
|
80
|
+
|
|
81
|
+
for name in missing:
|
|
82
|
+
want = (anchors or {}).get(name) or None
|
|
83
|
+
at = next((i for i, b in enumerate(blocks) if want and number(b) == want), None)
|
|
84
|
+
if at is None:
|
|
85
|
+
at = next((i for i, b in enumerate(blocks) if _CAPTION.match(b)), len(blocks))
|
|
86
|
+
blocks.insert(at, f"image::images/{name}[圖片]")
|
|
87
|
+
return "\n\n".join(blocks)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
_LABEL_BLOCK = re.compile(r"\[圖中文字\].*?\[/圖中文字\]", re.S)
|
|
91
|
+
LEGEND_TITLE = ".圖中文字"
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def legend_block(items: list[dict]) -> str:
|
|
95
|
+
"""The translated text of a figure as an AsciiDoc table (original | translation); "" when nothing is left.
|
|
96
|
+
|
|
97
|
+
`caption=""` keeps Asciidoctor from numbering it ("Table 1. …")."""
|
|
98
|
+
def cell(t: str) -> str:
|
|
99
|
+
return " ".join(str(t).split()).replace("|", "\\|")
|
|
100
|
+
|
|
101
|
+
rows = [(cell(i["source"]), cell(i["target"])) for i in items if i.get("source") and i.get("target") and i["source"] != i["target"]]
|
|
102
|
+
if not rows:
|
|
103
|
+
return ""
|
|
104
|
+
body = "\n".join(f"|{a} |{b}" for a, b in rows)
|
|
105
|
+
return f'{LEGEND_TITLE}\n[caption="",cols="1,1",options="header"]\n|===\n|原文 |譯文\n{body}\n|==='
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def add_legends(text: str, legends: dict[str, list[dict]], anchors: dict[str, str] | None = None) -> str:
|
|
109
|
+
"""Put each figure's text table under the figure: after its caption when the caption follows it, else right after it."""
|
|
110
|
+
if not legends:
|
|
111
|
+
return text
|
|
112
|
+
blocks = re.split(r"\n{2,}", text.strip())
|
|
113
|
+
for name, items in legends.items():
|
|
114
|
+
table = legend_block(items)
|
|
115
|
+
at = next((i for i, b in enumerate(blocks) if b.startswith(f"image::images/{name}[")), None)
|
|
116
|
+
if not table or at is None or (at + 1 < len(blocks) and blocks[at + 1].startswith(LEGEND_TITLE)):
|
|
117
|
+
continue
|
|
118
|
+
nxt = blocks[at + 1] if at + 1 < len(blocks) else ""
|
|
119
|
+
cap = _CAPTION_NUMBER.match(nxt)
|
|
120
|
+
wanted = (anchors or {}).get(name) or ""
|
|
121
|
+
under_caption = bool(cap) and (not wanted or normalize_caption_number(cap.group(1)) == wanted)
|
|
122
|
+
blocks.insert(at + 2 if under_caption else at + 1, table)
|
|
123
|
+
return "\n\n".join(blocks)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def relocate_images(text: str, anchors: dict[str, str]) -> str:
|
|
127
|
+
"""Move each image block to the line right before the caption with its number (a block put elsewhere by an
|
|
128
|
+
earlier version that did not recognise bold captions)."""
|
|
129
|
+
blocks = re.split(r"\n{2,}", text.strip()) if text.strip() else []
|
|
130
|
+
for name, want in anchors.items():
|
|
131
|
+
want = normalize_caption_number(want) if want else ""
|
|
132
|
+
i = next((k for k, b in enumerate(blocks) if b.startswith(f"image::images/{name}[")), None)
|
|
133
|
+
if i is None or not want:
|
|
134
|
+
continue
|
|
135
|
+
cap = next((k for k, b in enumerate(blocks) if k != i and (m := _CAPTION_NUMBER.match(b)) and normalize_caption_number(m.group(1)) == want), None)
|
|
136
|
+
if cap is None or cap - 1 == i:
|
|
137
|
+
continue
|
|
138
|
+
img = blocks.pop(i)
|
|
139
|
+
blocks.insert(cap - 1 if i < cap else cap, img)
|
|
140
|
+
return "\n\n".join(blocks)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def place_images(text: str, names: list[str], anchors: dict[str, str] | None = None,
|
|
144
|
+
legends: dict[str, list[dict]] | None = None) -> str:
|
|
145
|
+
"""Turn the `[IMG:name]` markers the model kept into AsciiDoc image blocks.
|
|
146
|
+
|
|
147
|
+
A marker the model dropped is not lost: the picture goes before its figure caption, else at the end of the
|
|
148
|
+
page. Unknown or repeated markers are removed."""
|
|
149
|
+
text = _LABEL_BLOCK.sub("", text) # the figure's text goes to `figure_texts`; a copy in the prose is dropped
|
|
150
|
+
done: set[str] = {n for n in names if f"images/{n}[" in text} # the model wrote the macro itself
|
|
151
|
+
|
|
152
|
+
def one(m: re.Match) -> str:
|
|
153
|
+
name = m.group(1)
|
|
154
|
+
if name not in names or name in done:
|
|
155
|
+
return ""
|
|
156
|
+
done.add(name)
|
|
157
|
+
return f"\n\nimage::images/{name}[圖片]\n\n"
|
|
158
|
+
|
|
159
|
+
text = _IMG_MARK.sub(one, text)
|
|
160
|
+
text = re.sub(r"\n{3,}", "\n\n", text).strip() if names else text
|
|
161
|
+
if not names:
|
|
162
|
+
return text
|
|
163
|
+
return add_legends(insert_image_blocks(text, names, anchors), legends or {}, anchors)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _paragraph_source(p: dict) -> str:
|
|
167
|
+
text = ("[H] " if p.get("heading") else "") + p["text"]
|
|
168
|
+
if p.get("image") and p.get("labels"): # the text inside a figure goes along, so it can be translated
|
|
169
|
+
text += "\n[圖中文字]\n" + "\n".join(p["labels"]) + "\n[/圖中文字]"
|
|
170
|
+
return text
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def page_source_text(page: dict) -> str:
|
|
174
|
+
return "\n\n".join(_paragraph_source(p) for p in page["own"])
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
class Project:
|
|
178
|
+
"""One PDF + its translation state, stored in `<root>/<id>/`."""
|
|
179
|
+
|
|
180
|
+
def __init__(self, root: Path, project_id: str):
|
|
181
|
+
self.id = project_id
|
|
182
|
+
self.dir = Path(root) / project_id
|
|
183
|
+
self.pdf_path = self.dir / "source.pdf"
|
|
184
|
+
self.lock = threading.RLock()
|
|
185
|
+
self.version = 0
|
|
186
|
+
self.running = False
|
|
187
|
+
self.stop_flag = False
|
|
188
|
+
self.state: dict = {}
|
|
189
|
+
|
|
190
|
+
# ---- persistence -------------------------------------------------
|
|
191
|
+
@classmethod
|
|
192
|
+
def create(cls, root: Path, project_id: str, pdf_bytes: bytes, source_name: str) -> "Project":
|
|
193
|
+
proj = cls(root, project_id)
|
|
194
|
+
proj.dir.mkdir(parents=True, exist_ok=True)
|
|
195
|
+
proj.pdf_path.write_bytes(pdf_bytes)
|
|
196
|
+
proj.state = {
|
|
197
|
+
"version": 1,
|
|
198
|
+
"images_version": IMAGES_VERSION,
|
|
199
|
+
"plan_version": PLAN_VERSION,
|
|
200
|
+
"source_name": source_name,
|
|
201
|
+
"pages": plan_pages(extract_pages(proj.pdf_path, proj.dir / "images")),
|
|
202
|
+
"glossary": [],
|
|
203
|
+
}
|
|
204
|
+
proj.save()
|
|
205
|
+
return proj
|
|
206
|
+
|
|
207
|
+
@classmethod
|
|
208
|
+
def load(cls, root: Path, project_id: str) -> "Project":
|
|
209
|
+
proj = cls(root, project_id)
|
|
210
|
+
proj.state = json.loads((proj.dir / STATE_FILE).read_text(encoding="utf-8"))
|
|
211
|
+
fixed = False
|
|
212
|
+
for p in proj.state["pages"]: # a crash mid-run must not leave pages stuck
|
|
213
|
+
if p["status"] == "running":
|
|
214
|
+
p["status"] = "pending"
|
|
215
|
+
for key in ("translation", "carry_translation"): # a chapter title the model wrote as "= …"
|
|
216
|
+
if p.get(key) and adoc.fix_title_levels(p[key]) != p[key]:
|
|
217
|
+
p[key], fixed = adoc.fix_title_levels(p[key]), True
|
|
218
|
+
if fixed:
|
|
219
|
+
proj.save()
|
|
220
|
+
return proj
|
|
221
|
+
|
|
222
|
+
def save(self) -> None:
|
|
223
|
+
with self.lock:
|
|
224
|
+
(self.dir / STATE_FILE).write_text(json.dumps(self.state, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
225
|
+
(self.dir / "glossary.json").write_text(
|
|
226
|
+
json.dumps(self.state["glossary"], ensure_ascii=False, indent=1), encoding="utf-8"
|
|
227
|
+
)
|
|
228
|
+
(self.dir / f"{self.id}.adoc").write_text(adoc.assemble(self.state), encoding="utf-8")
|
|
229
|
+
self.version += 1
|
|
230
|
+
|
|
231
|
+
# ---- queries -----------------------------------------------------
|
|
232
|
+
@property
|
|
233
|
+
def pages(self) -> list[dict]:
|
|
234
|
+
return self.state["pages"]
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def legacy(self) -> bool:
|
|
238
|
+
"""True while pictures still have to be (re-)extracted: the project predates pictures (a page has no `images`
|
|
239
|
+
list) or was extracted by an older version of the detection (`images_version` < IMAGES_VERSION)."""
|
|
240
|
+
return self.state.get("images_version", 1) < IMAGES_VERSION or any("images" not in p for p in self.pages)
|
|
241
|
+
|
|
242
|
+
def replan(self) -> bool:
|
|
243
|
+
"""Re-plan the pages of an older project from its PDF (paragraphs, pictures, what carries over to the next page).
|
|
244
|
+
|
|
245
|
+
Only done when every page is about to be translated again: the translations that exist were made for the old
|
|
246
|
+
plan and are replaced (the glossary is kept)."""
|
|
247
|
+
with self.lock:
|
|
248
|
+
try:
|
|
249
|
+
fresh = plan_pages(extract_pages(self.pdf_path, self.dir / "images"))
|
|
250
|
+
except Exception as e: # noqa: BLE001 - keep working with the old plan
|
|
251
|
+
print(f"cannot re-plan {self.id}: {type(e).__name__}: {e}", file=sys.stderr)
|
|
252
|
+
return False
|
|
253
|
+
if len(fresh) != len(self.pages):
|
|
254
|
+
return False
|
|
255
|
+
for page, new in zip(self.pages, fresh):
|
|
256
|
+
for key in ("own", "images", "carry_in", "carry_origin"):
|
|
257
|
+
page[key] = new[key]
|
|
258
|
+
page["carry_translation"] = None
|
|
259
|
+
page["carry_edited"] = False
|
|
260
|
+
self.state["plan_version"] = PLAN_VERSION
|
|
261
|
+
self.state["images_version"] = IMAGES_VERSION
|
|
262
|
+
self.save()
|
|
263
|
+
return True
|
|
264
|
+
|
|
265
|
+
def upgrade_images(self) -> int:
|
|
266
|
+
"""Bring an older project up to date with the picture extraction. Returns how many pictures were added or
|
|
267
|
+
converted.
|
|
268
|
+
|
|
269
|
+
The PDF is scanned again. A picture a page does not have yet is saved, its marker goes into the page's source
|
|
270
|
+
(so a re-translation places it) and, if the page is translated already, an image block goes into the
|
|
271
|
+
translation before its figure caption. A vector figure stored as a PNG by an earlier version becomes an SVG
|
|
272
|
+
(the translation's reference is switched). Pictures a page already has otherwise stay as they are; only their
|
|
273
|
+
figure texts (labels) are filled in. Translating the labels needs the model: it happens when the page is
|
|
274
|
+
translated again."""
|
|
275
|
+
with self.lock:
|
|
276
|
+
if self.running or not self.legacy:
|
|
277
|
+
return 0
|
|
278
|
+
try:
|
|
279
|
+
fresh = extract_pages(self.pdf_path, self.dir / "images")
|
|
280
|
+
except Exception as e: # noqa: BLE001 - the project still works without pictures
|
|
281
|
+
print(f"cannot extract the pictures of {self.id}: {type(e).__name__}: {e}", file=sys.stderr)
|
|
282
|
+
return 0
|
|
283
|
+
changed = 0
|
|
284
|
+
stem = lambda n: n.rsplit(".", 1)[0] # noqa: E731
|
|
285
|
+
for page, paras in zip(self.pages, fresh):
|
|
286
|
+
pics = [p for p in paras if p.image]
|
|
287
|
+
have = {stem(n): n for n in page.get("images", [])}
|
|
288
|
+
own = page["own"]
|
|
289
|
+
new: list = []
|
|
290
|
+
for pic in pics:
|
|
291
|
+
old = have.get(stem(pic.image))
|
|
292
|
+
if old == pic.image: # the same picture: just the figure texts are new
|
|
293
|
+
for o in own:
|
|
294
|
+
if o.get("image") == old:
|
|
295
|
+
o["labels"] = o.get("labels") or pic.labels
|
|
296
|
+
o["caption"] = o.get("caption") or pic.caption
|
|
297
|
+
elif old: # the same figure in another format (PNG -> SVG): switch over
|
|
298
|
+
page["translation"] = page["translation"].replace(f"images/{old}[", f"images/{pic.image}[")
|
|
299
|
+
own[:] = [pic.to_dict() if o.get("image") == old else o for o in own]
|
|
300
|
+
(self.dir / "images" / old).unlink(missing_ok=True)
|
|
301
|
+
changed += 1
|
|
302
|
+
else:
|
|
303
|
+
new.append(pic)
|
|
304
|
+
for pic in new:
|
|
305
|
+
own[:] = [ # drop the short labels lying inside the figure (old extraction made paragraphs of them)
|
|
306
|
+
o for o in own
|
|
307
|
+
if not (pic.y0 - 3 <= o.get("y0", -1) and o.get("y1", 1e9) <= pic.y1 + 3
|
|
308
|
+
and len(o["text"]) <= LABEL_MAX_CHARS and not o.get("heading"))
|
|
309
|
+
]
|
|
310
|
+
at = next((k for k, o in enumerate(own) if o.get("y0", 0) > pic.y0 + 2), len(own))
|
|
311
|
+
own.insert(at, pic.to_dict())
|
|
312
|
+
if new and page["translation"]:
|
|
313
|
+
page["translation"] = insert_image_blocks(
|
|
314
|
+
page["translation"], [p.image for p in new], {p.image: p.caption for p in new}
|
|
315
|
+
)
|
|
316
|
+
if page["translation"]:
|
|
317
|
+
page["translation"] = relocate_images(page["translation"], {p.image: p.caption for p in pics if p.caption})
|
|
318
|
+
page["images"] = [p.image for p in pics]
|
|
319
|
+
changed += len(new)
|
|
320
|
+
self.state["images_version"] = IMAGES_VERSION
|
|
321
|
+
self.save()
|
|
322
|
+
return changed
|
|
323
|
+
|
|
324
|
+
def todo(self, which: str | list[int] = "pending") -> list[int]:
|
|
325
|
+
"""Pages to translate: 'pending' (not done), 'stale', 'all', or explicit list."""
|
|
326
|
+
if isinstance(which, list):
|
|
327
|
+
return sorted(set(which))
|
|
328
|
+
if which == "all":
|
|
329
|
+
return [p["n"] for p in self.pages]
|
|
330
|
+
if which == "stale":
|
|
331
|
+
return [p["n"] for p in self.pages if p["status"] == "stale"]
|
|
332
|
+
return [p["n"] for p in self.pages if p["status"] in ("pending", "error", "stale")]
|
|
333
|
+
|
|
334
|
+
def summary(self) -> dict:
|
|
335
|
+
return {
|
|
336
|
+
"id": self.id,
|
|
337
|
+
"source_name": self.state["source_name"],
|
|
338
|
+
"running": self.running,
|
|
339
|
+
"version": self.version,
|
|
340
|
+
"images": sum(len(p.get("images", [])) for p in self.pages),
|
|
341
|
+
"pages": [
|
|
342
|
+
{
|
|
343
|
+
"n": p["n"],
|
|
344
|
+
"status": p["status"],
|
|
345
|
+
"error": p["error"],
|
|
346
|
+
"edited": bool(p.get("edited") or p.get("carry_edited")),
|
|
347
|
+
}
|
|
348
|
+
for p in self.pages
|
|
349
|
+
],
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
# ---- translation -------------------------------------------------
|
|
353
|
+
def translate_page(self, n: int, translator: Translator, page_images: bool = False) -> None:
|
|
354
|
+
pages = self.pages
|
|
355
|
+
page = pages[n - 1]
|
|
356
|
+
prev = pages[n - 2] if n >= 2 else None
|
|
357
|
+
with self.lock:
|
|
358
|
+
page["status"] = "running"
|
|
359
|
+
page["error"] = None
|
|
360
|
+
self.version += 1 # tell the page which one is being translated now (it drives the progress animation)
|
|
361
|
+
gl = list(self.state["glossary"])
|
|
362
|
+
src = page_source_text(page)
|
|
363
|
+
req = TranslationRequest(
|
|
364
|
+
page=n,
|
|
365
|
+
page_source=src,
|
|
366
|
+
carry_source=page["carry_in"],
|
|
367
|
+
previous_source=page_source_text(prev) if prev else None,
|
|
368
|
+
previous_translation=prev["translation"] if prev else None,
|
|
369
|
+
glossary=glossary.relevant_terms(gl, src, page["carry_in"]),
|
|
370
|
+
page_image=self._page_image(n) if page_images else None,
|
|
371
|
+
)
|
|
372
|
+
res = translator(req)
|
|
373
|
+
with self.lock:
|
|
374
|
+
anchors = {o["image"]: o.get("caption", "") for o in page["own"] if o.get("image")}
|
|
375
|
+
legends = {ft["image"]: ft["items"] for ft in getattr(res, "figure_texts", [])}
|
|
376
|
+
page["translation"] = adoc.fix_title_levels(place_images(res.page_translation, page.get("images", []), anchors, legends))
|
|
377
|
+
page["carry_translation"] = adoc.fix_title_levels(res.carry_translation) if page["carry_in"] and res.carry_translation else None
|
|
378
|
+
page["edited"] = page["carry_edited"] = False # machine output replaces manual edits
|
|
379
|
+
page["status"] = "done"
|
|
380
|
+
glossary.merge_terms(self.state["glossary"], res.new_terms, n)
|
|
381
|
+
self.save()
|
|
382
|
+
|
|
383
|
+
def _page_image(self, n: int) -> bytes | None:
|
|
384
|
+
"""The page as a JPEG for the model; if it cannot be rendered the page is still translated from its text."""
|
|
385
|
+
try:
|
|
386
|
+
return render_page_image(self.pdf_path, n)
|
|
387
|
+
except Exception as e: # noqa: BLE001
|
|
388
|
+
print(f"cannot render page {n} as an image ({type(e).__name__}: {e}); translating from the text only", file=sys.stderr)
|
|
389
|
+
return None
|
|
390
|
+
|
|
391
|
+
def run(self, translator: Translator, which: str | list[int] = "pending", page_images: bool = False) -> None:
|
|
392
|
+
"""Translate pages sequentially (later pages depend on earlier translations).
|
|
393
|
+
|
|
394
|
+
page_images: also send each page's picture to the model (the "attach page images" option)."""
|
|
395
|
+
with self.lock:
|
|
396
|
+
if self.running:
|
|
397
|
+
return
|
|
398
|
+
self.running = True
|
|
399
|
+
self.stop_flag = False
|
|
400
|
+
self.version += 1
|
|
401
|
+
try:
|
|
402
|
+
if which == "all" and self.state.get("plan_version", 1) < PLAN_VERSION:
|
|
403
|
+
self.replan() # every page is translated again anyway, so an outdated plan can be replaced now
|
|
404
|
+
for n in self.todo(which):
|
|
405
|
+
if self.stop_flag:
|
|
406
|
+
break
|
|
407
|
+
try:
|
|
408
|
+
self.translate_page(n, translator, page_images)
|
|
409
|
+
if isinstance(which, list) and n < len(self.pages) and n + 1 not in which:
|
|
410
|
+
nxt = self.pages[n] # its context (previous translation) changed
|
|
411
|
+
if nxt["status"] == "done":
|
|
412
|
+
nxt["status"] = "stale"
|
|
413
|
+
self.save()
|
|
414
|
+
except Exception as e: # noqa: BLE001 - surface to UI, stop the run
|
|
415
|
+
with self.lock:
|
|
416
|
+
self.pages[n - 1]["status"] = "error"
|
|
417
|
+
self.pages[n - 1]["error"] = f"{type(e).__name__}: {e}"
|
|
418
|
+
self.save()
|
|
419
|
+
break
|
|
420
|
+
finally:
|
|
421
|
+
with self.lock:
|
|
422
|
+
self.running = False
|
|
423
|
+
self.version += 1
|
|
424
|
+
|
|
425
|
+
# ---- manual editing ----------------------------------------------
|
|
426
|
+
def page_text(self, n: int) -> str:
|
|
427
|
+
with self.lock:
|
|
428
|
+
return adoc.page_block(self.state, n)
|
|
429
|
+
|
|
430
|
+
def edit_page(self, n: int, text: str) -> None:
|
|
431
|
+
"""Replace page n's AsciiDoc (including its `// @span` carried paragraphs) with the user's text."""
|
|
432
|
+
with self.lock:
|
|
433
|
+
translation, carried = adoc.parse_block(n, text)
|
|
434
|
+
page = self.pages[n - 1]
|
|
435
|
+
page["translation"] = translation
|
|
436
|
+
page["edited"] = True
|
|
437
|
+
if page["status"] in ("pending", "error"):
|
|
438
|
+
page["status"] = "done" # a hand-written page counts as translated
|
|
439
|
+
for q in self.pages:
|
|
440
|
+
if q.get("carry_origin") == n:
|
|
441
|
+
new = carried.get(q["n"]) or None # a deleted marker drops that carried paragraph
|
|
442
|
+
if new != q.get("carry_translation"):
|
|
443
|
+
q["carry_translation"] = new
|
|
444
|
+
q["carry_edited"] = True
|
|
445
|
+
self.save()
|
|
446
|
+
|
|
447
|
+
# ---- glossary editing -------------------------------------------
|
|
448
|
+
def update_glossary(self, new_terms: list[dict]) -> list[int]:
|
|
449
|
+
"""Apply a user-edited glossary; mark affected done pages stale. Returns their numbers."""
|
|
450
|
+
with self.lock:
|
|
451
|
+
final, changed = glossary.apply_user_edit(self.state["glossary"], new_terms)
|
|
452
|
+
self.state["glossary"] = final
|
|
453
|
+
affected = glossary.affected_pages(self.pages, changed)
|
|
454
|
+
for n in affected:
|
|
455
|
+
if self.pages[n - 1]["status"] == "done":
|
|
456
|
+
self.pages[n - 1]["status"] = "stale"
|
|
457
|
+
self.save()
|
|
458
|
+
return [n for n in affected if self.pages[n - 1]["status"] == "stale"]
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def list_projects(root: Path) -> list[str]:
|
|
462
|
+
root = Path(root)
|
|
463
|
+
if not root.exists():
|
|
464
|
+
return []
|
|
465
|
+
return sorted(p.name for p in root.iterdir() if (p / STATE_FILE).exists())
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
def slugify(name: str) -> str:
|
|
469
|
+
stem = Path(name).stem
|
|
470
|
+
slug = re.sub(r"[^\w\-.]+", "_", stem, flags=re.UNICODE).strip("._")
|
|
471
|
+
return slug or "document"
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
|
pdftran/py.typed
ADDED
|
File without changes
|