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/extract.py
ADDED
|
@@ -0,0 +1,456 @@
|
|
|
1
|
+
"""Extract paragraphs from a text-based PDF with PyMuPDF."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
import statistics
|
|
7
|
+
from dataclasses import dataclass, asdict, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
import pymupdf
|
|
11
|
+
|
|
12
|
+
HEADER_FOOTER_BAND = 0.08 # fraction of page height treated as header/footer zone
|
|
13
|
+
HEADING_RATIO = 1.15 # font size vs. body size to be considered a heading
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Paragraph:
|
|
18
|
+
text: str
|
|
19
|
+
size: float = 0.0
|
|
20
|
+
bold: bool = False
|
|
21
|
+
heading: bool = False
|
|
22
|
+
y0: float = 0.0
|
|
23
|
+
y1: float = 0.0
|
|
24
|
+
image: str = "" # file name in the project's images/ folder: this "paragraph" is a picture; `text` is its marker
|
|
25
|
+
caption: str = "" # number of the figure caption belonging to this picture ("1-2" for "Figure 1-2"), if one was found
|
|
26
|
+
labels: list[str] = field(default_factory=list) # the translatable text inside the picture (a figure's labels), in reading order
|
|
27
|
+
caption: str = "" # number of the figure caption belonging to this picture ("1-2" for "Figure 1-2"), if one was found
|
|
28
|
+
image: str = "" # file name in the project's images/ folder: this "paragraph" is a picture; `text` is its marker
|
|
29
|
+
|
|
30
|
+
def to_dict(self) -> dict:
|
|
31
|
+
return asdict(self)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_dict(cls, d: dict) -> "Paragraph":
|
|
35
|
+
return cls(**d)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _join_lines(lines: list[str]) -> str:
|
|
39
|
+
out = ""
|
|
40
|
+
for line in lines:
|
|
41
|
+
line = line.strip()
|
|
42
|
+
if not line:
|
|
43
|
+
continue
|
|
44
|
+
if not out:
|
|
45
|
+
out = line
|
|
46
|
+
elif out.endswith("-") and len(out) > 1 and out[-2].isalpha() and line[:1].islower():
|
|
47
|
+
out = out[:-1] + line # de-hyphenate a soft line-break
|
|
48
|
+
elif _is_cjk(out[-1]) and _is_cjk(line[0]):
|
|
49
|
+
out += line
|
|
50
|
+
else:
|
|
51
|
+
out += " " + line
|
|
52
|
+
return out
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _is_cjk(ch: str) -> bool:
|
|
56
|
+
return "\u4e00" <= ch <= "\u9fff" or "\u3040" <= ch <= "\u30ff"
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _norm_for_repeat(text: str) -> str:
|
|
60
|
+
return re.sub(r"\d+", "#", text.strip().lower())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _raw_page(page: pymupdf.Page) -> list[dict]:
|
|
64
|
+
"""Return text blocks of a page: text, avg size, bold, bbox."""
|
|
65
|
+
blocks = []
|
|
66
|
+
for b in page.get_text("dict", sort=True)["blocks"]:
|
|
67
|
+
if b.get("type") != 0:
|
|
68
|
+
continue
|
|
69
|
+
lines, sizes, bold_chars, chars = [], [], 0, 0
|
|
70
|
+
for line in b["lines"]:
|
|
71
|
+
parts = []
|
|
72
|
+
for span in line["spans"]:
|
|
73
|
+
t = span["text"]
|
|
74
|
+
parts.append(t)
|
|
75
|
+
n = len(t.strip())
|
|
76
|
+
if n:
|
|
77
|
+
sizes.extend([span["size"]] * n)
|
|
78
|
+
chars += n
|
|
79
|
+
if span["flags"] & 16 or "bold" in span["font"].lower():
|
|
80
|
+
bold_chars += n
|
|
81
|
+
lines.append("".join(parts))
|
|
82
|
+
text = _join_lines(lines)
|
|
83
|
+
if not text:
|
|
84
|
+
continue
|
|
85
|
+
blocks.append(
|
|
86
|
+
{
|
|
87
|
+
"text": text,
|
|
88
|
+
"size": statistics.fmean(sizes) if sizes else 0.0,
|
|
89
|
+
"bold": chars > 0 and bold_chars / chars > 0.6,
|
|
90
|
+
"x0": b["bbox"][0],
|
|
91
|
+
"x1": b["bbox"][2],
|
|
92
|
+
"x0": b["bbox"][0],
|
|
93
|
+
"x1": b["bbox"][2],
|
|
94
|
+
"y0": b["bbox"][1],
|
|
95
|
+
"y1": b["bbox"][3],
|
|
96
|
+
"chars": chars,
|
|
97
|
+
}
|
|
98
|
+
)
|
|
99
|
+
return blocks
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
IMAGE_MARK = "[IMG:{}]" # how a picture appears in the page source sent to the model (see pipeline.place_images)
|
|
103
|
+
MIN_IMAGE_SIDE = 40.0 # pt: smaller pictures are bullets, icons, rules
|
|
104
|
+
MIN_IMAGE_AREA = 4000.0 # pt²
|
|
105
|
+
BACKGROUND_SHARE = 0.8 # a picture covering this much of the page is a background / scan, not a figure
|
|
106
|
+
MAX_IMAGE_EDGE = 1800 # px, long edge of the saved picture
|
|
107
|
+
INLINE_PNG_LIMIT = 600_000 # bytes: a bigger PNG is saved as a JPEG instead
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
LABEL_MAX_CHARS = 60 # a short text block lying inside a picture is one of its labels (axis ticks, legend…)
|
|
111
|
+
LABEL_TOLERANCE = 3.0 # pt
|
|
112
|
+
FIGURE_TEXT_SIZE = 0.75 # text set smaller than this share of the body size and lying in a figure is part of it, however long
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _is_figure_text(b: dict, body: float) -> bool:
|
|
116
|
+
"""A block that may belong to a figure: short, or set small (labels, a pseudocode box inside the drawing)."""
|
|
117
|
+
return len(b["text"]) <= LABEL_MAX_CHARS or (body > 0 and 0 < b["size"] <= body * FIGURE_TEXT_SIZE)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
Picture = tuple[float, float, float, float, str, str, list] # (y0, y1, x0, x1, file name, caption number, labels)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _is_label_of(b: dict, pic: Picture, body: float = 0.0) -> bool:
|
|
124
|
+
y0, y1, x0, x1 = pic[:4]
|
|
125
|
+
t = LABEL_TOLERANCE
|
|
126
|
+
inside = b["x0"] >= x0 - t and b["x1"] <= x1 + t and b["y0"] >= y0 - t and b["y1"] <= y1 + t
|
|
127
|
+
return inside and _is_figure_text(b, body)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
# ---- figure captions and vector figures
|
|
131
|
+
_CAPTION = re.compile(r"\s*(?:Figure|Fig\.?|圖)\s*(\d+(?:\s*[.\-–—−]\s*\d+)*)(.*)", re.IGNORECASE | re.DOTALL)
|
|
132
|
+
CAPTION_MAX_CHARS = 500
|
|
133
|
+
CAPTION_GAP = 40.0 # pt: a raster picture this close above / below a caption belongs to it
|
|
134
|
+
VECTOR_MAX_GAP = 60.0 # pt between a vector figure's drawings and its caption (labels such as "Input layer" sit in between)
|
|
135
|
+
GROW_GAP = 18.0 # pt: drawings this close to the figure belong to it
|
|
136
|
+
LABEL_GAP = 14.0 # pt: short text this close above / below the figure is one of its labels
|
|
137
|
+
LABEL_SIDE_GAP = 32.0 # pt: … and beside it (level with the figure), where input / output names stand further out
|
|
138
|
+
MIN_VECTOR_SIZE = (20.0, 40.0) # pt: (shorter side, longer side) - a tall narrow flow chart is a figure too
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def normalize_caption_number(num: str) -> str:
|
|
142
|
+
return re.sub(r"\s+", "", re.sub(r"[–—−]", "-", num))
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
def caption_number(text: str) -> str | None:
|
|
146
|
+
""""1-2" for a figure caption ("Figure 1-2 The perceptron", "圖 1-2 …"), else None.
|
|
147
|
+
|
|
148
|
+
Body text that merely starts with a reference ("Figure 1-7 shows these data points…") is not a caption: after the
|
|
149
|
+
number a caption has a separator (en / em space, colon, period, dash) or a capitalised / CJK word."""
|
|
150
|
+
m = _CAPTION.match(text)
|
|
151
|
+
if not m or len(text) > CAPTION_MAX_CHARS:
|
|
152
|
+
return None
|
|
153
|
+
rest = m.group(2)
|
|
154
|
+
if rest:
|
|
155
|
+
first, after = rest[0], rest.lstrip()[:1]
|
|
156
|
+
separated = first in " ::..—–-"
|
|
157
|
+
word_start = first.isspace() and (after == "" or after.isupper() or ord(after) > 0x2E7F)
|
|
158
|
+
if not (separated or word_start):
|
|
159
|
+
return None
|
|
160
|
+
return normalize_caption_number(m.group(1))
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
CAPTION_X_TOLERANCE = 60.0 # pt: a short caption need not sit under the figure, only in the same part of the page
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _x_near(a: pymupdf.Rect, b: pymupdf.Rect) -> bool:
|
|
167
|
+
return max(a.x0 - b.x1, b.x0 - a.x1, 0.0) <= CAPTION_X_TOLERANCE
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _distance(a: pymupdf.Rect, b: pymupdf.Rect) -> float:
|
|
171
|
+
return max(a.x0 - b.x1, b.x0 - a.x1, a.y0 - b.y1, b.y0 - a.y1, 0.0)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _rect(b: dict) -> pymupdf.Rect:
|
|
175
|
+
return pymupdf.Rect(b["x0"], b["y0"], b["x1"], b["y1"])
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def _caption_of(r: pymupdf.Rect, caps: list[tuple[dict, str]]) -> str:
|
|
179
|
+
"""Number of the caption right below / above the rectangle `r` ("" if none)."""
|
|
180
|
+
best: tuple[float, str] | None = None
|
|
181
|
+
for b, num in caps:
|
|
182
|
+
cr = _rect(b)
|
|
183
|
+
if not _x_near(r, cr):
|
|
184
|
+
continue
|
|
185
|
+
for d in (cr.y0 - r.y1, r.y0 - cr.y1):
|
|
186
|
+
if -6 <= d <= CAPTION_GAP and (best is None or d < best[0]):
|
|
187
|
+
best = (d, num)
|
|
188
|
+
return best[1] if best else ""
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _has_prose(r: pymupdf.Rect, blocks: list[dict], skip: dict | None = None, body: float = 0.0) -> bool:
|
|
192
|
+
"""True if a long text block lies (mostly) inside `r`: then `r` is a text box / page area, not a figure."""
|
|
193
|
+
for b in blocks:
|
|
194
|
+
if b is skip or _is_figure_text(b, body):
|
|
195
|
+
continue
|
|
196
|
+
br = _rect(b)
|
|
197
|
+
inter = br & r
|
|
198
|
+
if not inter.is_empty and inter.width * inter.height > 0.25 * max(br.width * br.height, 1.0):
|
|
199
|
+
return True
|
|
200
|
+
return False
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _grow_region(seed, clusters, blocks, cap, above, body, page_h) -> pymupdf.Rect:
|
|
204
|
+
"""Grow `seed` over nearby drawings and short labels, never past the caption."""
|
|
205
|
+
fits = (lambda r: r.y1 <= cap["y0"] - 0.5) if above else (lambda r: r.y0 >= cap["y1"] + 0.5)
|
|
206
|
+
region = pymupdf.Rect(seed)
|
|
207
|
+
for _ in range(40):
|
|
208
|
+
grew = False
|
|
209
|
+
for c in clusters:
|
|
210
|
+
if _distance(region, c) <= GROW_GAP and not _has_prose(c, blocks, cap, body):
|
|
211
|
+
new = region | c
|
|
212
|
+
if new != region and fits(new):
|
|
213
|
+
region, grew = new, True
|
|
214
|
+
for b in blocks:
|
|
215
|
+
if b is cap or not _is_figure_text(b, body) or (body and b["size"] >= body * HEADING_RATIO) or _in_band(b, page_h):
|
|
216
|
+
continue # (a running head right above the drawing is not one of its labels)
|
|
217
|
+
br = _rect(b)
|
|
218
|
+
beside = br.y1 > region.y0 and br.y0 < region.y1 # level with the figure: input labels sit further out
|
|
219
|
+
if _distance(region, br) <= (LABEL_SIDE_GAP if beside else LABEL_GAP):
|
|
220
|
+
new = region | br
|
|
221
|
+
if new != region and fits(new):
|
|
222
|
+
region, grew = new, True
|
|
223
|
+
if not grew:
|
|
224
|
+
break
|
|
225
|
+
return region
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _vector_figures(page, blocks, caps, taken, body) -> list[tuple[pymupdf.Rect, str, dict, bool]]:
|
|
229
|
+
"""Figures drawn as vector graphics: the drawings right above (or below) a figure caption, with their labels.
|
|
230
|
+
|
|
231
|
+
Tables and shaded text boxes are drawings too, but they either have no "Figure" caption or contain running text;
|
|
232
|
+
only drawings tied to a caption and free of prose count as a figure."""
|
|
233
|
+
prect = page.rect
|
|
234
|
+
try:
|
|
235
|
+
# final_filter=False keeps hairlines (an arrow or a dimension line is 0pt high): they belong to a figure. The
|
|
236
|
+
# rectangles are widened a little because a zero-height rectangle counts as empty and drops out of unions.
|
|
237
|
+
clusters = [pymupdf.Rect(c.x0 - .5, c.y0 - .5, c.x1 + .5, c.y1 + .5) for c in page.cluster_drawings(final_filter=False)]
|
|
238
|
+
except Exception: # noqa: BLE001
|
|
239
|
+
return []
|
|
240
|
+
clusters = [c for c in clusters if c.width * c.height < BACKGROUND_SHARE * prect.width * prect.height]
|
|
241
|
+
found: list[tuple[pymupdf.Rect, str, dict, bool]] = []
|
|
242
|
+
for cap, num in caps:
|
|
243
|
+
cr = _rect(cap)
|
|
244
|
+
if any(0 <= cr.y0 - t.y1 <= CAPTION_GAP and _x_near(t, cr) for t in taken):
|
|
245
|
+
continue # a raster picture right above the caption is the figure already
|
|
246
|
+
for above in (True, False):
|
|
247
|
+
gap = (lambda c: cr.y0 - c.y1) if above else (lambda c: c.y0 - cr.y1)
|
|
248
|
+
seeds = [c for c in clusters if max(c.width, c.height) >= 30 and -6 <= gap(c) <= VECTOR_MAX_GAP and _x_near(c, cr)]
|
|
249
|
+
if not seeds:
|
|
250
|
+
continue
|
|
251
|
+
seed = min(seeds, key=lambda c: (gap(c), -c.width * c.height))
|
|
252
|
+
region = _grow_region(seed, clusters, blocks, cap, above, body, prect.height)
|
|
253
|
+
ok = min(region.width, region.height) >= MIN_VECTOR_SIZE[0] and max(region.width, region.height) >= MIN_VECTOR_SIZE[1]
|
|
254
|
+
ok = ok and not _has_prose(region, blocks, cap, body) and not _in_band({"y0": region.y0, "y1": region.y1}, prect.height)
|
|
255
|
+
ok = ok and not any((region & t).get_area() > 0.3 * min(region.get_area(), t.get_area()) for t in taken)
|
|
256
|
+
ok = ok and not any((region & f[0]).get_area() > 0.5 * min(region.get_area(), f[0].get_area()) for f in found)
|
|
257
|
+
if ok:
|
|
258
|
+
found.append((region, num, cap, above))
|
|
259
|
+
break
|
|
260
|
+
return found
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def figure_labels(blocks: list[dict], r: pymupdf.Rect, skip: dict | None = None) -> list[str]:
|
|
264
|
+
"""The text inside a figure that is worth translating (words, not numbers or lone symbols), in reading order."""
|
|
265
|
+
t = LABEL_TOLERANCE
|
|
266
|
+
inside = [
|
|
267
|
+
b for b in blocks
|
|
268
|
+
if b is not skip and len(b["text"]) <= LABEL_MAX_CHARS
|
|
269
|
+
and b["x0"] >= r.x0 - t and b["x1"] <= r.x1 + t and b["y0"] >= r.y0 - t and b["y1"] <= r.y1 + t
|
|
270
|
+
]
|
|
271
|
+
inside.sort(key=lambda b: (round(b["y0"] / 6), b["x0"]))
|
|
272
|
+
out: list[str] = []
|
|
273
|
+
for b in inside:
|
|
274
|
+
text = " ".join(b["text"].split())
|
|
275
|
+
if re.search(r"[A-Za-z]{3,}", text) and text not in out:
|
|
276
|
+
out.append(text)
|
|
277
|
+
return out
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
MAX_SVG_BYTES = 3_000_000 # a figure whose vector drawing is bigger than this is saved as a PNG instead
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _save_svg(doc: pymupdf.Document, page: pymupdf.Page, clip: pymupdf.Rect, images_dir: Path, stem: str) -> str | None:
|
|
284
|
+
"""The part `clip` of the page as an SVG with the text turned into paths (no fonts needed, nothing selectable).
|
|
285
|
+
|
|
286
|
+
A one-page PDF showing just that part is made first (the drawings stay vector), then written out as SVG."""
|
|
287
|
+
try:
|
|
288
|
+
part = pymupdf.open()
|
|
289
|
+
sheet = part.new_page(width=clip.width, height=clip.height)
|
|
290
|
+
sheet.show_pdf_page(sheet.rect, doc, page.number, clip=clip)
|
|
291
|
+
svg = sheet.get_svg_image(text_as_path=True)
|
|
292
|
+
part.close()
|
|
293
|
+
except Exception: # noqa: BLE001 - the caller falls back to a PNG
|
|
294
|
+
return None
|
|
295
|
+
if not svg or len(svg) > MAX_SVG_BYTES or "<script" in svg.lower():
|
|
296
|
+
return None
|
|
297
|
+
images_dir.mkdir(parents=True, exist_ok=True)
|
|
298
|
+
name = f"{stem}.svg"
|
|
299
|
+
(images_dir / name).write_text(svg, encoding="utf-8")
|
|
300
|
+
return name
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _save_pixmap(pix: pymupdf.Pixmap, images_dir: Path, stem: str) -> str:
|
|
304
|
+
"""Save as PNG (JPEG when the PNG gets big); returns the file name."""
|
|
305
|
+
data, ext = pix.tobytes("png"), "png"
|
|
306
|
+
if len(data) > INLINE_PNG_LIMIT:
|
|
307
|
+
data, ext = pix.tobytes("jpeg", jpg_quality=85), "jpg"
|
|
308
|
+
name = f"{stem}.{ext}"
|
|
309
|
+
images_dir.mkdir(parents=True, exist_ok=True)
|
|
310
|
+
(images_dir / name).write_bytes(data)
|
|
311
|
+
return name
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _extract_images(doc: pymupdf.Document, images_dir: Path, raw: list[list[dict]], body: float) -> list[list[Picture]]:
|
|
315
|
+
"""Save the pictures of every page; per page a list of (y0, y1, x0, x1, file name, caption number), top to bottom.
|
|
316
|
+
|
|
317
|
+
Raster pictures (`p002-1.png`) and vector figures (`p003-v1.png`). A vector figure is only recognised through its
|
|
318
|
+
caption (see `_vector_figures`): drawings in real documents are mostly table rules and shaded text boxes, whose
|
|
319
|
+
text is extracted as text already, so grabbing every drawing would duplicate it.
|
|
320
|
+
"""
|
|
321
|
+
n_pages = len(doc)
|
|
322
|
+
infos: list[list[dict]] = []
|
|
323
|
+
seen_on: dict[int, set[int]] = {}
|
|
324
|
+
for i, page in enumerate(doc):
|
|
325
|
+
try:
|
|
326
|
+
found = page.get_image_info(xrefs=True)
|
|
327
|
+
except Exception: # noqa: BLE001 - a broken page must not stop the others
|
|
328
|
+
found = []
|
|
329
|
+
infos.append(found)
|
|
330
|
+
for im in found:
|
|
331
|
+
seen_on.setdefault(im["xref"], set()).add(i)
|
|
332
|
+
repeated = {x for x, pages in seen_on.items() if n_pages >= 3 and len(pages) >= max(3, n_pages // 2)} # logos, ornaments
|
|
333
|
+
|
|
334
|
+
result: list[list[Picture]] = []
|
|
335
|
+
for i, page in enumerate(doc):
|
|
336
|
+
page_rect, found, out = page.rect, infos[i], []
|
|
337
|
+
caps = [(b, n) for b in raw[i] if (n := caption_number(b["text"]))]
|
|
338
|
+
taken: list[pymupdf.Rect] = []
|
|
339
|
+
for im in found:
|
|
340
|
+
r = pymupdf.Rect(im["bbox"]) & page_rect
|
|
341
|
+
if r.is_empty or im["xref"] in repeated:
|
|
342
|
+
continue
|
|
343
|
+
if min(r.width, r.height) < MIN_IMAGE_SIDE or r.width * r.height < MIN_IMAGE_AREA:
|
|
344
|
+
continue
|
|
345
|
+
if r.width * r.height >= BACKGROUND_SHARE * page_rect.width * page_rect.height:
|
|
346
|
+
continue
|
|
347
|
+
if _in_band({"y0": r.y0, "y1": r.y1}, page_rect.height):
|
|
348
|
+
continue
|
|
349
|
+
try:
|
|
350
|
+
native = max(im.get("width") or 0, im.get("height") or 0)
|
|
351
|
+
zoom = min(4.0, max(1.0, native / max(r.width, r.height) if native else 2.0))
|
|
352
|
+
zoom = min(zoom, MAX_IMAGE_EDGE / max(r.width, r.height))
|
|
353
|
+
pix = page.get_pixmap(matrix=pymupdf.Matrix(zoom, zoom), clip=r, alpha=False)
|
|
354
|
+
name = _save_pixmap(pix, images_dir, f"p{i + 1:03d}-{len(taken) + 1}")
|
|
355
|
+
except Exception: # noqa: BLE001 - skip this picture, keep the rest
|
|
356
|
+
continue
|
|
357
|
+
taken.append(r)
|
|
358
|
+
out.append((r.y0, r.y1, r.x0, r.x1, name, _caption_of(r, caps), figure_labels(raw[i], r)))
|
|
359
|
+
try:
|
|
360
|
+
figures = _vector_figures(page, raw[i], caps, taken, body)
|
|
361
|
+
except Exception: # noqa: BLE001 - vector detection is best effort
|
|
362
|
+
figures = []
|
|
363
|
+
for k, (region, num, cap, above) in enumerate(figures, 1):
|
|
364
|
+
clip = (region + (-3, -3, 3, 3)) & page_rect
|
|
365
|
+
if above:
|
|
366
|
+
clip.y1 = min(clip.y1, cap["y0"] - 0.5) # the caption stays text
|
|
367
|
+
else:
|
|
368
|
+
clip.y0 = max(clip.y0, cap["y1"] + 0.5)
|
|
369
|
+
stem = f"p{i + 1:03d}-v{k}"
|
|
370
|
+
name = _save_svg(doc, page, clip, images_dir, stem)
|
|
371
|
+
if name is None: # a figure the SVG route cannot do (too big, odd content): a PNG is still a picture
|
|
372
|
+
try:
|
|
373
|
+
zoom = max(1.5, min(3.0, MAX_IMAGE_EDGE / max(clip.width, clip.height)))
|
|
374
|
+
pix = page.get_pixmap(matrix=pymupdf.Matrix(zoom, zoom), clip=clip, alpha=False)
|
|
375
|
+
name = _save_pixmap(pix, images_dir, stem)
|
|
376
|
+
except Exception: # noqa: BLE001
|
|
377
|
+
continue
|
|
378
|
+
out.append((region.y0, region.y1, region.x0, region.x1, name, num, figure_labels(raw[i], region, cap)))
|
|
379
|
+
out.sort()
|
|
380
|
+
result.append(out)
|
|
381
|
+
return result
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def extract_pages(pdf_path: str | Path, images_dir: str | Path | None = None) -> list[list[Paragraph]]:
|
|
385
|
+
"""Return one list of Paragraphs per page (header/footer removed).
|
|
386
|
+
|
|
387
|
+
With `images_dir`, the raster pictures are saved there and appear in the paragraph list (at their vertical
|
|
388
|
+
position) as paragraphs whose `image` is the file name."""
|
|
389
|
+
with pymupdf.open(pdf_path) as doc:
|
|
390
|
+
heights = [p.rect.height for p in doc]
|
|
391
|
+
raw = [_raw_page(p) for p in doc]
|
|
392
|
+
|
|
393
|
+
# body font size = char-weighted median
|
|
394
|
+
weighted: list[float] = []
|
|
395
|
+
for blocks in raw:
|
|
396
|
+
for b in blocks:
|
|
397
|
+
weighted.extend([round(b["size"], 1)] * min(b["chars"], 400))
|
|
398
|
+
body = statistics.median(weighted) if weighted else 0.0
|
|
399
|
+
|
|
400
|
+
pictures = _extract_images(doc, Path(images_dir), raw, body) if images_dir else [[] for _ in raw]
|
|
401
|
+
|
|
402
|
+
# repeated header/footer detection
|
|
403
|
+
n_pages = len(raw)
|
|
404
|
+
counts: dict[str, int] = {}
|
|
405
|
+
for h, blocks in zip(heights, raw):
|
|
406
|
+
seen = set()
|
|
407
|
+
for b in blocks:
|
|
408
|
+
if _in_band(b, h):
|
|
409
|
+
seen.add(_norm_for_repeat(b["text"]))
|
|
410
|
+
for k in seen:
|
|
411
|
+
counts[k] = counts.get(k, 0) + 1
|
|
412
|
+
threshold = max(2, n_pages // 2)
|
|
413
|
+
|
|
414
|
+
result: list[list[Paragraph]] = []
|
|
415
|
+
for h, blocks, pics in zip(heights, raw, pictures):
|
|
416
|
+
paras = []
|
|
417
|
+
for b in blocks:
|
|
418
|
+
if any(_is_label_of(b, pic, body) for pic in pics):
|
|
419
|
+
continue # a label inside a figure: the figure is shown as it is, its labels are not separate text
|
|
420
|
+
if _in_band(b, h):
|
|
421
|
+
key = _norm_for_repeat(b["text"])
|
|
422
|
+
if re.fullmatch(r"[#\s\-–—|]*", key) or (n_pages >= 3 and counts.get(key, 0) >= threshold):
|
|
423
|
+
continue
|
|
424
|
+
heading = body > 0 and b["size"] >= body * HEADING_RATIO and len(b["text"]) < 200
|
|
425
|
+
paras.append(
|
|
426
|
+
Paragraph(
|
|
427
|
+
text=b["text"],
|
|
428
|
+
size=round(b["size"], 1),
|
|
429
|
+
bold=b["bold"],
|
|
430
|
+
heading=heading,
|
|
431
|
+
y0=b["y0"],
|
|
432
|
+
y1=b["y1"],
|
|
433
|
+
)
|
|
434
|
+
)
|
|
435
|
+
for y0, y1, _x0, _x1, name, num, labels in pics: # a picture goes before the first paragraph that starts below its top edge
|
|
436
|
+
at = next((k for k, p in enumerate(paras) if p.y0 > y0 + 2), len(paras))
|
|
437
|
+
paras.insert(at, Paragraph(text=IMAGE_MARK.format(name), y0=y0, y1=y1, image=name, caption=num, labels=labels))
|
|
438
|
+
result.append(paras)
|
|
439
|
+
return result
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
PAGE_IMAGE_EDGE = 1400 # px, long edge: about the size Claude's vision works best with (larger images are scaled down anyway)
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def render_page_image(pdf_path: str | Path, page_number: int, max_edge: int = PAGE_IMAGE_EDGE, quality: int = 85) -> bytes:
|
|
446
|
+
"""A JPEG of page `page_number` (1-based), its long edge `max_edge` px (never magnified more than 3x)."""
|
|
447
|
+
with pymupdf.open(pdf_path) as doc:
|
|
448
|
+
page = doc[page_number - 1]
|
|
449
|
+
zoom = min(3.0, max_edge / max(page.rect.width, page.rect.height))
|
|
450
|
+
pix = page.get_pixmap(matrix=pymupdf.Matrix(zoom, zoom), alpha=False)
|
|
451
|
+
return pix.tobytes("jpeg", jpg_quality=quality)
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _in_band(b: dict, page_height: float) -> bool:
|
|
455
|
+
return b["y1"] <= page_height * HEADER_FOOTER_BAND * 1.5 or b["y0"] >= page_height * (1 - HEADER_FOOTER_BAND * 1.5)
|
|
456
|
+
|
pdftran/glossary.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Glossary accumulation, locking and impact analysis."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _key(source: str) -> str:
|
|
7
|
+
return source.strip().casefold()
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def relevant_terms(glossary: list[dict], *texts: str | None) -> list[dict]:
|
|
11
|
+
"""Terms whose source text occurs in any of the given texts."""
|
|
12
|
+
hay = "\n".join(t for t in texts if t).casefold()
|
|
13
|
+
return [t for t in glossary if _key(t["source"]) and _key(t["source"]) in hay]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def merge_terms(glossary: list[dict], new_terms: list[dict], page: int) -> list[dict]:
|
|
17
|
+
"""Add terms reported by the model. Existing sources are never overwritten."""
|
|
18
|
+
known = {_key(t["source"]) for t in glossary}
|
|
19
|
+
added = []
|
|
20
|
+
for nt in new_terms or []:
|
|
21
|
+
source = (nt.get("source") or "").strip()
|
|
22
|
+
target = (nt.get("target") or "").strip()
|
|
23
|
+
if not source or not target or _key(source) in known:
|
|
24
|
+
continue
|
|
25
|
+
known.add(_key(source))
|
|
26
|
+
term = {
|
|
27
|
+
"source": source,
|
|
28
|
+
"target": target,
|
|
29
|
+
"note": (nt.get("note") or "").strip(),
|
|
30
|
+
"first_page": page,
|
|
31
|
+
"locked": False,
|
|
32
|
+
}
|
|
33
|
+
glossary.append(term)
|
|
34
|
+
added.append(term)
|
|
35
|
+
return added
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def apply_user_edit(old: list[dict], new: list[dict]) -> tuple[list[dict], set[str]]:
|
|
39
|
+
"""Normalise a user-edited glossary.
|
|
40
|
+
|
|
41
|
+
Returns (final glossary, set of casefolded sources whose translation changed
|
|
42
|
+
or that were added/removed). Edited or added terms become locked.
|
|
43
|
+
"""
|
|
44
|
+
old_by_key = {_key(t["source"]): t for t in old}
|
|
45
|
+
final: list[dict] = []
|
|
46
|
+
changed: set[str] = set()
|
|
47
|
+
seen: set[str] = set()
|
|
48
|
+
for t in new:
|
|
49
|
+
source = (t.get("source") or "").strip()
|
|
50
|
+
k = _key(source)
|
|
51
|
+
if not k or k in seen:
|
|
52
|
+
continue
|
|
53
|
+
seen.add(k)
|
|
54
|
+
target = (t.get("target") or "").strip()
|
|
55
|
+
prev = old_by_key.get(k)
|
|
56
|
+
term = {
|
|
57
|
+
"source": source,
|
|
58
|
+
"target": target,
|
|
59
|
+
"note": (t.get("note") or "").strip(),
|
|
60
|
+
"first_page": t.get("first_page") or (prev or {}).get("first_page") or 0,
|
|
61
|
+
"locked": bool(t.get("locked")),
|
|
62
|
+
}
|
|
63
|
+
if prev is None or prev["target"] != target:
|
|
64
|
+
changed.add(k)
|
|
65
|
+
term["locked"] = True
|
|
66
|
+
final.append(term)
|
|
67
|
+
for k in old_by_key:
|
|
68
|
+
if k not in seen:
|
|
69
|
+
changed.add(k)
|
|
70
|
+
return final, changed
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def affected_pages(pages: list[dict], changed: set[str]) -> list[int]:
|
|
74
|
+
"""Page numbers whose source text contains any changed term."""
|
|
75
|
+
out = []
|
|
76
|
+
for p in pages:
|
|
77
|
+
hay = "\n".join([p.get("carry_in") or ""] + [q["text"] for q in p["own"]]).casefold()
|
|
78
|
+
if any(k and k in hay for k in changed):
|
|
79
|
+
out.append(p["n"])
|
|
80
|
+
return out
|
pdftran/paths.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""Where PDFTran keeps its data (per-user, so it also works when packaged as a desktop app).
|
|
2
|
+
|
|
3
|
+
Windows %LOCALAPPDATA%\\PDFTran
|
|
4
|
+
macOS ~/Library/Application Support/PDFTran
|
|
5
|
+
Linux $XDG_DATA_HOME/PDFTran or ~/.local/share/PDFTran
|
|
6
|
+
Override with the PDFTRAN_DATA_DIR environment variable.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import sys
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
APP_NAME = "PDFTran"
|
|
17
|
+
FROZEN = bool(getattr(sys, "frozen", False)) # running from the PyInstaller build
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def data_dir() -> Path:
|
|
21
|
+
override = os.environ.get("PDFTRAN_DATA_DIR", "").strip()
|
|
22
|
+
if override:
|
|
23
|
+
return Path(override).expanduser()
|
|
24
|
+
if sys.platform == "win32":
|
|
25
|
+
base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
|
|
26
|
+
elif sys.platform == "darwin":
|
|
27
|
+
base = Path.home() / "Library" / "Application Support"
|
|
28
|
+
else:
|
|
29
|
+
base = Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")
|
|
30
|
+
return base / APP_NAME
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def migrate_legacy_data(target: Path | None = None) -> Path | None:
|
|
34
|
+
"""Early builds kept data in %APPDATA% (Roaming). Copy it once to the new place; never delete the old one.
|
|
35
|
+
|
|
36
|
+
Returns the folder copied from, or None if nothing was done.
|
|
37
|
+
"""
|
|
38
|
+
if sys.platform != "win32" or os.environ.get("PDFTRAN_DATA_DIR", "").strip():
|
|
39
|
+
return None
|
|
40
|
+
old = Path(os.environ.get("APPDATA") or Path.home() / "AppData" / "Roaming") / APP_NAME
|
|
41
|
+
new = target or data_dir()
|
|
42
|
+
if old.is_dir() and old != new and not (new / "projects").exists():
|
|
43
|
+
shutil.copytree(old, new, dirs_exist_ok=True)
|
|
44
|
+
return old
|
|
45
|
+
return None
|