odforge 0.3.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.
- odforge/__init__.py +1 -0
- odforge/benchmark.py +287 -0
- odforge/check.py +416 -0
- odforge/cli.py +1027 -0
- odforge/components.py +270 -0
- odforge/critic.py +1260 -0
- odforge/docfonts.py +104 -0
- odforge/editor_api.py +33 -0
- odforge/editor_launch.py +134 -0
- odforge/editor_routes.py +131 -0
- odforge/extract.py +478 -0
- odforge/feedback.py +86 -0
- odforge/fontembed.py +166 -0
- odforge/ir.py +1181 -0
- odforge/layoutcheck.py +602 -0
- odforge/llm.py +1865 -0
- odforge/localguard.py +42 -0
- odforge/mcp_server.py +552 -0
- odforge/media.py +352 -0
- odforge/odpedit.py +1219 -0
- odforge/package.py +114 -0
- odforge/pagefacts.py +388 -0
- odforge/preview.py +104 -0
- odforge/references.py +153 -0
- odforge/render/__init__.py +40 -0
- odforge/render/odp.py +5687 -0
- odforge/render/ods.py +155 -0
- odforge/render/odt.py +223 -0
- odforge/scene.py +657 -0
- odforge/setup_agents.py +274 -0
- odforge/skills/odforge-design/SKILL.md +298 -0
- odforge/skills/odforge-design/themes/academic.md +52 -0
- odforge/skills/odforge-design/themes/clay.md +53 -0
- odforge/skills/odforge-design/themes/color-system.md +59 -0
- odforge/skills/odforge-design/themes/crimson.md +53 -0
- odforge/skills/odforge-design/themes/dark.md +53 -0
- odforge/skills/odforge-design/themes/forest.md +54 -0
- odforge/skills/odforge-design/themes/gold.md +53 -0
- odforge/skills/odforge-design/themes/minimal.md +53 -0
- odforge/skills/odforge-design/themes/navy.md +56 -0
- odforge/skills/odforge-design/themes/plum.md +53 -0
- odforge/skills/odforge-design/themes/sky.md +53 -0
- odforge/skills/odforge-design/themes/slate.md +53 -0
- odforge/skills/odforge-design/themes/teal.md +53 -0
- odforge/skills/odforge-design/themes/violet.md +56 -0
- odforge/templates.py +250 -0
- odforge/textmetrics.py +616 -0
- odforge/textutil.py +24 -0
- odforge/themes.py +886 -0
- odforge/validate.py +403 -0
- odforge/watch.py +266 -0
- odforge/webapi.py +2617 -0
- odforge/webui/assets/editor-CjpYXM1a.css +1 -0
- odforge/webui/assets/editor-DPToJGio.js +3 -0
- odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
- odforge/webui/assets/main-BLOs7Hnk.js +7 -0
- odforge/webui/assets/main-D21yFVE6.css +1 -0
- odforge/webui/editor.html +14 -0
- odforge/webui/index.html +25 -0
- odforge/xmlsafe.py +46 -0
- odforge/zipguard.py +91 -0
- odforge-0.3.0.dist-info/METADATA +95 -0
- odforge-0.3.0.dist-info/RECORD +66 -0
- odforge-0.3.0.dist-info/WHEEL +4 -0
- odforge-0.3.0.dist-info/entry_points.txt +3 -0
- odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/layoutcheck.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
1
|
+
"""Rendered layout check (跑版檢查): where the text actually landed.
|
|
2
|
+
|
|
3
|
+
:func:`odforge.textmetrics.check_budget` *estimates* whether text fits, from the
|
|
4
|
+
IR and a width table, before anything is rendered. That is the right tool while
|
|
5
|
+
generating, and the wrong one for everything else: it cannot see a file that
|
|
6
|
+
ODForge did not make, and even on its own output an estimate can be wrong
|
|
7
|
+
(fallback fonts, LibreOffice's line breaking, autofit that never kicks in).
|
|
8
|
+
|
|
9
|
+
This module asks LibreOffice instead. It converts the document to PDF, reads
|
|
10
|
+
back every rendered line of text with its position, and compares it with the
|
|
11
|
+
box the document declared for it:
|
|
12
|
+
|
|
13
|
+
* ``.odp`` — each rendered line is matched to the text frame it came from (by
|
|
14
|
+
its text; the nearest frame wins when two frames share a phrase) and reported
|
|
15
|
+
when it pokes out of that frame or off the slide. A line that lands on another
|
|
16
|
+
frame's text is named as such, because that is what a reader sees as 跑版.
|
|
17
|
+
* ``.odt`` — text reflows, so frames are not the question; text that runs past
|
|
18
|
+
the right margin (a table or an unbreakable string too wide for the page) or
|
|
19
|
+
off the page is.
|
|
20
|
+
* ``.ods`` — no fixed page layout to overrun; reported as unsupported.
|
|
21
|
+
|
|
22
|
+
Lines that match no frame (page numbers, master-page decoration, fields) are
|
|
23
|
+
left alone rather than guessed at. The check never raises: a missing LibreOffice
|
|
24
|
+
or a failed conversion comes back as ``status="unavailable"`` with the reason,
|
|
25
|
+
and unavailable is never presented as a pass.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import re
|
|
31
|
+
import shutil
|
|
32
|
+
import subprocess
|
|
33
|
+
import tempfile
|
|
34
|
+
import zipfile
|
|
35
|
+
from dataclasses import dataclass, field
|
|
36
|
+
from pathlib import Path
|
|
37
|
+
from typing import Dict, List, Literal, Optional
|
|
38
|
+
|
|
39
|
+
# `pymupdf`, never the `fitz` alias: the alias prints to stdout, which corrupts
|
|
40
|
+
# the MCP stdio stream (see preview.py).
|
|
41
|
+
import pymupdf
|
|
42
|
+
from lxml import etree
|
|
43
|
+
|
|
44
|
+
from .validate import run_soffice_convert
|
|
45
|
+
from .xmlsafe import safe_fromstring
|
|
46
|
+
|
|
47
|
+
_NS = {
|
|
48
|
+
"draw": "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
|
|
49
|
+
"svg": "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
|
|
50
|
+
"style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
|
|
51
|
+
"fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
|
|
52
|
+
"text": "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
|
|
53
|
+
"presentation": "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
_SOFFICE_TIMEOUT = 120
|
|
57
|
+
_PT_TO_CM = 2.54 / 72
|
|
58
|
+
|
|
59
|
+
# A rendered line box includes the font's ascent and descent, so a one-line
|
|
60
|
+
# label in a frame sized to its glyphs pokes out of the frame by a few
|
|
61
|
+
# millimetres while looking perfectly placed. Vertically, a line therefore only
|
|
62
|
+
# counts as outside once its *centre* is — more than half of it has left the
|
|
63
|
+
# frame, which no padding or line-height slack explains.
|
|
64
|
+
_MIN_TOLERANCE_CM = 0.1
|
|
65
|
+
# Horizontally the glyph boxes are tight, so a small fixed slack is enough.
|
|
66
|
+
_HORIZONTAL_TOLERANCE_CM = 0.15
|
|
67
|
+
# LibreOffice clips whatever lies past the page when it exports the PDF, so
|
|
68
|
+
# off-page text is never *seen* beyond the edge — it shows up as a line that
|
|
69
|
+
# runs right up to it. No real layout sets text flush against the paper edge,
|
|
70
|
+
# so a line within this distance of an edge counts as running off the page.
|
|
71
|
+
_PAGE_TOLERANCE_CM = 0.05
|
|
72
|
+
|
|
73
|
+
# Text extraction must see what lies beyond the page: PyMuPDF clips to the
|
|
74
|
+
# mediabox by default, which would hide exactly the text this check looks for.
|
|
75
|
+
_TEXT_FLAGS = pymupdf.TEXTFLAGS_DICT & ~pymupdf.TEXT_MEDIABOX_CLIP
|
|
76
|
+
|
|
77
|
+
_EXCERPT_CHARS = 16
|
|
78
|
+
|
|
79
|
+
_EDGE_LABEL = {"bottom": "下緣", "top": "上緣", "right": "右緣", "left": "左緣"}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@dataclass(frozen=True)
|
|
83
|
+
class _Box:
|
|
84
|
+
x: float
|
|
85
|
+
y: float
|
|
86
|
+
w: float
|
|
87
|
+
h: float
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def right(self) -> float:
|
|
91
|
+
return self.x + self.w
|
|
92
|
+
|
|
93
|
+
@property
|
|
94
|
+
def bottom(self) -> float:
|
|
95
|
+
return self.y + self.h
|
|
96
|
+
|
|
97
|
+
def distance(self, other: _Box) -> float:
|
|
98
|
+
dx = max(self.x - other.right, other.x - self.right, 0.0)
|
|
99
|
+
dy = max(self.y - other.bottom, other.y - self.bottom, 0.0)
|
|
100
|
+
return (dx * dx + dy * dy) ** 0.5
|
|
101
|
+
|
|
102
|
+
def overlaps_horizontally(self, other: _Box) -> bool:
|
|
103
|
+
return min(self.right, other.right) > max(self.x, other.x)
|
|
104
|
+
|
|
105
|
+
def overlap_area(self, other: _Box) -> float:
|
|
106
|
+
w = min(self.right, other.right) - max(self.x, other.x)
|
|
107
|
+
h = min(self.bottom, other.bottom) - max(self.y, other.y)
|
|
108
|
+
return w * h if w > 0 and h > 0 else 0.0
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class _Frame:
|
|
113
|
+
box: _Box
|
|
114
|
+
key: str
|
|
115
|
+
excerpt: str
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class _Line:
|
|
120
|
+
box: _Box
|
|
121
|
+
text: str
|
|
122
|
+
key: str
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class LayoutFinding:
|
|
127
|
+
"""One place where rendered text left the space it was given."""
|
|
128
|
+
|
|
129
|
+
page: int
|
|
130
|
+
kind: Literal["frame", "page", "margin"]
|
|
131
|
+
excerpt: str
|
|
132
|
+
edge: str
|
|
133
|
+
overshoot_cm: float
|
|
134
|
+
collides_with: str = ""
|
|
135
|
+
|
|
136
|
+
def describe(self) -> str:
|
|
137
|
+
return f"第 {self.page} 頁{self.detail()}"
|
|
138
|
+
|
|
139
|
+
def detail(self) -> str:
|
|
140
|
+
"""The finding without its page number, for lists already grouped by page."""
|
|
141
|
+
where = f"「{self.excerpt}」"
|
|
142
|
+
if self.kind == "frame":
|
|
143
|
+
text = f"{where}文字超出框的{_EDGE_LABEL[self.edge]} {self.overshoot_cm:.2f} cm"
|
|
144
|
+
if self.collides_with:
|
|
145
|
+
text += f",壓到「{self.collides_with}」"
|
|
146
|
+
return text
|
|
147
|
+
if self.kind == "margin":
|
|
148
|
+
return f"{where}超出右邊界 {self.overshoot_cm:.2f} cm"
|
|
149
|
+
# The clipped part is not in the PDF, so there is no honest distance.
|
|
150
|
+
return f"{where}文字延伸到頁面{_EDGE_LABEL[self.edge]}外,超出的部分會被裁掉"
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
@dataclass
|
|
154
|
+
class LayoutReport:
|
|
155
|
+
"""``status``: ``ok`` / ``overflow`` / ``unavailable`` / ``unsupported``."""
|
|
156
|
+
|
|
157
|
+
status: Literal["ok", "overflow", "unavailable", "unsupported"]
|
|
158
|
+
message: str
|
|
159
|
+
findings: List[LayoutFinding] = field(default_factory=list)
|
|
160
|
+
|
|
161
|
+
@property
|
|
162
|
+
def ok(self) -> bool:
|
|
163
|
+
return self.status == "ok"
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def _key(text: str) -> str:
|
|
167
|
+
"""Letters, digits and CJK only — bullets, spaces and punctuation vary
|
|
168
|
+
between the XML and the rendered glyph stream, the words do not."""
|
|
169
|
+
return re.sub(r"[\W_]+", "", text)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _excerpt(text: str) -> str:
|
|
173
|
+
text = " ".join(text.split())
|
|
174
|
+
return text if len(text) <= _EXCERPT_CHARS else text[:_EXCERPT_CHARS] + "…"
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _cm(value: Optional[str]) -> float:
|
|
178
|
+
if not value:
|
|
179
|
+
return 0.0
|
|
180
|
+
match = re.match(r"^(-?[0-9.]+)\s*([a-z]*)$", value.strip())
|
|
181
|
+
if not match:
|
|
182
|
+
return 0.0
|
|
183
|
+
number, unit = float(match.group(1)), match.group(2)
|
|
184
|
+
return {
|
|
185
|
+
"mm": number / 10,
|
|
186
|
+
"in": number * 2.54,
|
|
187
|
+
"pt": number * _PT_TO_CM,
|
|
188
|
+
}.get(unit, number)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def _read_parts(path: Path) -> tuple[etree._Element, etree._Element]:
|
|
192
|
+
with zipfile.ZipFile(path) as package:
|
|
193
|
+
content = safe_fromstring(package.read("content.xml"))
|
|
194
|
+
try:
|
|
195
|
+
styles = safe_fromstring(package.read("styles.xml"))
|
|
196
|
+
except KeyError:
|
|
197
|
+
styles = content
|
|
198
|
+
return content, styles
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
# ---------------------------------------------------------------------------
|
|
202
|
+
# Declared geometry
|
|
203
|
+
# ---------------------------------------------------------------------------
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _hidden_page_styles(roots: tuple[etree._Element, ...]) -> set[str]:
|
|
207
|
+
hidden: set[str] = set()
|
|
208
|
+
for root in roots:
|
|
209
|
+
for style in root.iter(f"{{{_NS['style']}}}style"):
|
|
210
|
+
for props in style.iter(f"{{{_NS['style']}}}drawing-page-properties"):
|
|
211
|
+
if props.get(f"{{{_NS['presentation']}}}visibility") == "hidden":
|
|
212
|
+
hidden.add(style.get(f"{{{_NS['style']}}}name", ""))
|
|
213
|
+
return hidden
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
_PARAGRAPH = f"{{{_NS['text']}}}p"
|
|
217
|
+
_SPACERS = {
|
|
218
|
+
f"{{{_NS['text']}}}{tag}" for tag in ("s", "tab", "line-break")
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def _plain_text(element: etree._Element) -> str:
|
|
223
|
+
"""The element's text with ``<text:s>``/tabs/breaks as spaces, so excerpts
|
|
224
|
+
read "17 輸出順序" rather than "17輸出順序"."""
|
|
225
|
+
parts: List[str] = []
|
|
226
|
+
for node in element.iter():
|
|
227
|
+
if node.tag in _SPACERS or (node.tag == _PARAGRAPH and parts):
|
|
228
|
+
parts.append(" ")
|
|
229
|
+
if node.text:
|
|
230
|
+
parts.append(node.text)
|
|
231
|
+
if node is not element and node.tail:
|
|
232
|
+
parts.append(node.tail)
|
|
233
|
+
return "".join(parts)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _page_frames(page: etree._Element) -> List[_Frame]:
|
|
237
|
+
"""Text-bearing frames and shapes on one slide, speaker notes excluded."""
|
|
238
|
+
frames: List[_Frame] = []
|
|
239
|
+
notes = f"{{{_NS['presentation']}}}notes"
|
|
240
|
+
text_box = f"{{{_NS['draw']}}}text-box"
|
|
241
|
+
shape_tags = {
|
|
242
|
+
f"{{{_NS['draw']}}}{tag}"
|
|
243
|
+
for tag in ("custom-shape", "rect", "ellipse", "circle")
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
def walk(element: etree._Element) -> None:
|
|
247
|
+
for child in element:
|
|
248
|
+
if child.tag == notes:
|
|
249
|
+
continue
|
|
250
|
+
if child.get(f"{{{_NS['draw']}}}transform"):
|
|
251
|
+
# Rotated or skewed: the declared box is not where it renders.
|
|
252
|
+
continue
|
|
253
|
+
if child.tag == f"{{{_NS['draw']}}}frame":
|
|
254
|
+
box_el = child.find(text_box)
|
|
255
|
+
if box_el is not None:
|
|
256
|
+
_add(child, box_el)
|
|
257
|
+
continue
|
|
258
|
+
if child.tag in shape_tags:
|
|
259
|
+
_add(child, child)
|
|
260
|
+
continue
|
|
261
|
+
walk(child)
|
|
262
|
+
|
|
263
|
+
def _add(holder: etree._Element, text_root: etree._Element) -> None:
|
|
264
|
+
text = _plain_text(text_root)
|
|
265
|
+
key = _key(text)
|
|
266
|
+
if not key:
|
|
267
|
+
return
|
|
268
|
+
frames.append(
|
|
269
|
+
_Frame(
|
|
270
|
+
_Box(
|
|
271
|
+
_cm(holder.get(f"{{{_NS['svg']}}}x")),
|
|
272
|
+
_cm(holder.get(f"{{{_NS['svg']}}}y")),
|
|
273
|
+
_cm(holder.get(f"{{{_NS['svg']}}}width")),
|
|
274
|
+
_cm(holder.get(f"{{{_NS['svg']}}}height")),
|
|
275
|
+
),
|
|
276
|
+
key,
|
|
277
|
+
_excerpt(text),
|
|
278
|
+
)
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
walk(page)
|
|
282
|
+
return frames
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _slides(content: etree._Element, styles: etree._Element) -> List[List[_Frame]]:
|
|
286
|
+
"""Frames per *exported* slide — hidden slides are not in the PDF."""
|
|
287
|
+
hidden = _hidden_page_styles((content, styles))
|
|
288
|
+
slides: List[List[_Frame]] = []
|
|
289
|
+
for page in content.iter(f"{{{_NS['draw']}}}page"):
|
|
290
|
+
if page.get(f"{{{_NS['draw']}}}style-name") in hidden:
|
|
291
|
+
continue
|
|
292
|
+
slides.append(_page_frames(page))
|
|
293
|
+
return slides
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _text_area_right_margins(
|
|
297
|
+
content: etree._Element, styles: etree._Element
|
|
298
|
+
) -> Dict[float, float]:
|
|
299
|
+
"""Page width (cm, rounded) → right margin (cm) of the page layouts in use.
|
|
300
|
+
|
|
301
|
+
A document usually carries several page layouts (Standard, Endnote, HTML…)
|
|
302
|
+
and only some are used. Only the master pages the text actually asks for
|
|
303
|
+
count — ``Standard`` when nothing asks — and where two in-use layouts share
|
|
304
|
+
a width the narrower margin wins, so text is never called out for using
|
|
305
|
+
space one of its own pages grants.
|
|
306
|
+
"""
|
|
307
|
+
style, fo = _NS["style"], _NS["fo"]
|
|
308
|
+
used = {
|
|
309
|
+
name
|
|
310
|
+
for root in (content, styles)
|
|
311
|
+
for el in root.iter()
|
|
312
|
+
if (name := el.get(f"{{{style}}}master-page-name"))
|
|
313
|
+
} or {"Standard"}
|
|
314
|
+
layouts = {
|
|
315
|
+
el.get(f"{{{style}}}name"): el
|
|
316
|
+
for el in styles.iter(f"{{{style}}}page-layout")
|
|
317
|
+
}
|
|
318
|
+
chosen = [
|
|
319
|
+
layouts[el.get(f"{{{style}}}page-layout-name")]
|
|
320
|
+
for el in styles.iter(f"{{{style}}}master-page")
|
|
321
|
+
if el.get(f"{{{style}}}name") in used
|
|
322
|
+
and el.get(f"{{{style}}}page-layout-name") in layouts
|
|
323
|
+
] or list(layouts.values())
|
|
324
|
+
margins: Dict[float, float] = {}
|
|
325
|
+
for layout in chosen:
|
|
326
|
+
for props in layout.iter(f"{{{style}}}page-layout-properties"):
|
|
327
|
+
width = _cm(props.get(f"{{{fo}}}page-width"))
|
|
328
|
+
if width <= 0:
|
|
329
|
+
continue
|
|
330
|
+
key = round(width, 1)
|
|
331
|
+
margin = _cm(props.get(f"{{{fo}}}margin-right"))
|
|
332
|
+
margins[key] = min(margin, margins.get(key, margin))
|
|
333
|
+
return margins
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
# ---------------------------------------------------------------------------
|
|
337
|
+
# Rendered geometry
|
|
338
|
+
# ---------------------------------------------------------------------------
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def _rendered_lines(page: pymupdf.Page) -> List[_Line]:
|
|
342
|
+
lines: List[_Line] = []
|
|
343
|
+
for block in page.get_text("dict", flags=_TEXT_FLAGS)["blocks"]:
|
|
344
|
+
for line in block.get("lines", []):
|
|
345
|
+
text = "".join(span["text"] for span in line["spans"])
|
|
346
|
+
key = _key(text)
|
|
347
|
+
if not key:
|
|
348
|
+
continue
|
|
349
|
+
x0, y0, x1, y1 = (v * _PT_TO_CM for v in line["bbox"])
|
|
350
|
+
lines.append(_Line(_Box(x0, y0, x1 - x0, y1 - y0), text, key))
|
|
351
|
+
return lines
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def _page_overrun(line: _Line, width: float, height: float) -> tuple[str, float]:
|
|
355
|
+
box = line.box
|
|
356
|
+
edges = {
|
|
357
|
+
"bottom": box.bottom - height,
|
|
358
|
+
"top": -box.y,
|
|
359
|
+
"right": box.right - width,
|
|
360
|
+
"left": -box.x,
|
|
361
|
+
}
|
|
362
|
+
edge = max(edges, key=edges.__getitem__)
|
|
363
|
+
return edge, edges[edge]
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def _frame_overshoot(line: _Box, frame: _Box) -> tuple[float, str]:
|
|
367
|
+
"""How far ``line`` sits outside ``frame`` (0 when it counts as inside)."""
|
|
368
|
+
centre = line.y + line.h / 2
|
|
369
|
+
vertical = {"bottom": line.bottom - frame.bottom, "top": frame.y - line.y}
|
|
370
|
+
horizontal = {"right": line.right - frame.right, "left": frame.x - line.x}
|
|
371
|
+
outside: Dict[str, float] = {}
|
|
372
|
+
if centre > frame.bottom + _MIN_TOLERANCE_CM or centre < frame.y - _MIN_TOLERANCE_CM:
|
|
373
|
+
outside.update(vertical)
|
|
374
|
+
outside.update(
|
|
375
|
+
{edge: over for edge, over in horizontal.items() if over > _HORIZONTAL_TOLERANCE_CM}
|
|
376
|
+
)
|
|
377
|
+
if not outside:
|
|
378
|
+
return 0.0, ""
|
|
379
|
+
edge = max(outside, key=outside.__getitem__)
|
|
380
|
+
return outside[edge], edge
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _assign(frames: List[_Frame], lines: List[_Line]) -> List[Optional[int]]:
|
|
384
|
+
"""Which frame each rendered line came from (``None`` when none did).
|
|
385
|
+
|
|
386
|
+
LibreOffice writes a frame's lines one after another, so the lines of one
|
|
387
|
+
frame arrive as a run whose keys concatenate to the frame's key. Following
|
|
388
|
+
that run keeps wrapped-out lines with the frame they spilled from: the tail
|
|
389
|
+
of an overflowing label ("輸出" "順序") stays with "17 輸出順序" instead of
|
|
390
|
+
being handed to whichever frame below happens to be nearer.
|
|
391
|
+
|
|
392
|
+
A line that starts no run falls back to the nearest frame containing it.
|
|
393
|
+
Either way the frame must share horizontal span with the line — overflow
|
|
394
|
+
runs down or sideways, never into another column; without that, a page
|
|
395
|
+
number "2" was matched to an agenda frame that says "02".
|
|
396
|
+
"""
|
|
397
|
+
|
|
398
|
+
def nearest(indices: List[int], line: _Line) -> Optional[int]:
|
|
399
|
+
indices = [i for i in indices if frames[i].box.overlaps_horizontally(line.box)]
|
|
400
|
+
if not indices:
|
|
401
|
+
return None
|
|
402
|
+
return min(indices, key=lambda i: frames[i].box.distance(line.box))
|
|
403
|
+
|
|
404
|
+
assigned: List[Optional[int]] = []
|
|
405
|
+
current: Optional[int] = None
|
|
406
|
+
remaining = ""
|
|
407
|
+
started: set[int] = set()
|
|
408
|
+
for line in lines:
|
|
409
|
+
if current is not None and remaining.startswith(line.key):
|
|
410
|
+
assigned.append(current)
|
|
411
|
+
remaining = remaining[len(line.key):]
|
|
412
|
+
if not remaining:
|
|
413
|
+
current = None
|
|
414
|
+
continue
|
|
415
|
+
index = nearest(
|
|
416
|
+
[i for i, f in enumerate(frames) if i not in started and f.key.startswith(line.key)],
|
|
417
|
+
line,
|
|
418
|
+
)
|
|
419
|
+
if index is not None:
|
|
420
|
+
started.add(index)
|
|
421
|
+
current, remaining = index, frames[index].key[len(line.key):]
|
|
422
|
+
if not remaining:
|
|
423
|
+
current = None
|
|
424
|
+
else:
|
|
425
|
+
current = None
|
|
426
|
+
index = nearest([i for i, f in enumerate(frames) if line.key in f.key], line)
|
|
427
|
+
assigned.append(index)
|
|
428
|
+
return assigned
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _slide_findings(
|
|
432
|
+
number: int, frames: List[_Frame], lines: List[_Line], width: float, height: float
|
|
433
|
+
) -> List[LayoutFinding]:
|
|
434
|
+
worst: Dict[int, tuple[float, str, str]] = {} # frame index → overshoot, edge, hit
|
|
435
|
+
off_page: Optional[tuple[float, str, str]] = None
|
|
436
|
+
|
|
437
|
+
for line, index in zip(lines, _assign(frames, lines), strict=True):
|
|
438
|
+
edge, overrun = _page_overrun(line, width, height)
|
|
439
|
+
if overrun > -_PAGE_TOLERANCE_CM and (off_page is None or overrun > off_page[0]):
|
|
440
|
+
off_page = (overrun, edge, _excerpt(line.text))
|
|
441
|
+
if index is None:
|
|
442
|
+
continue
|
|
443
|
+
frame = frames[index].box
|
|
444
|
+
overshoot, edge = _frame_overshoot(line.box, frame)
|
|
445
|
+
if overshoot <= 0:
|
|
446
|
+
continue
|
|
447
|
+
hit = next(
|
|
448
|
+
(
|
|
449
|
+
other.excerpt
|
|
450
|
+
for j, other in enumerate(frames)
|
|
451
|
+
if j != index
|
|
452
|
+
and other.box.overlap_area(line.box) > 0.3 * line.box.w * line.box.h
|
|
453
|
+
),
|
|
454
|
+
"",
|
|
455
|
+
)
|
|
456
|
+
previous = worst.get(index)
|
|
457
|
+
if previous is None or overshoot > previous[0]:
|
|
458
|
+
worst[index] = (overshoot, edge, hit or (previous[2] if previous else ""))
|
|
459
|
+
|
|
460
|
+
findings = [
|
|
461
|
+
LayoutFinding(number, "frame", frames[i].excerpt, edge, round(over, 2), hit)
|
|
462
|
+
for i, (over, edge, hit) in sorted(worst.items())
|
|
463
|
+
]
|
|
464
|
+
if off_page is not None:
|
|
465
|
+
over, edge, excerpt = off_page
|
|
466
|
+
findings.append(LayoutFinding(number, "page", excerpt, edge, round(over, 2)))
|
|
467
|
+
return findings
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
def _text_page_findings(
|
|
471
|
+
number: int, lines: List[_Line], width: float, height: float, right_margin: float
|
|
472
|
+
) -> List[LayoutFinding]:
|
|
473
|
+
findings: List[LayoutFinding] = []
|
|
474
|
+
off_page: Optional[tuple[float, str, str]] = None
|
|
475
|
+
past_margin: Optional[tuple[float, str]] = None
|
|
476
|
+
text_right = width - right_margin
|
|
477
|
+
for line in lines:
|
|
478
|
+
edge, overrun = _page_overrun(line, width, height)
|
|
479
|
+
if overrun > -_PAGE_TOLERANCE_CM:
|
|
480
|
+
if off_page is None or overrun > off_page[0]:
|
|
481
|
+
off_page = (overrun, edge, _excerpt(line.text))
|
|
482
|
+
continue
|
|
483
|
+
if right_margin <= 0:
|
|
484
|
+
continue
|
|
485
|
+
over = line.box.right - text_right
|
|
486
|
+
if over > _HORIZONTAL_TOLERANCE_CM and (past_margin is None or over > past_margin[0]):
|
|
487
|
+
past_margin = (over, _excerpt(line.text))
|
|
488
|
+
if past_margin is not None:
|
|
489
|
+
findings.append(
|
|
490
|
+
LayoutFinding(number, "margin", past_margin[1], "right", round(past_margin[0], 2))
|
|
491
|
+
)
|
|
492
|
+
if off_page is not None:
|
|
493
|
+
over, edge, excerpt = off_page
|
|
494
|
+
findings.append(LayoutFinding(number, "page", excerpt, edge, round(over, 2)))
|
|
495
|
+
return findings
|
|
496
|
+
|
|
497
|
+
|
|
498
|
+
# ---------------------------------------------------------------------------
|
|
499
|
+
# Entry point
|
|
500
|
+
# ---------------------------------------------------------------------------
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
def _convert_to_pdf(path: Path, soffice: Path, outdir: Path) -> Path:
|
|
504
|
+
try:
|
|
505
|
+
proc = run_soffice_convert(soffice, path, "pdf", outdir, timeout=_SOFFICE_TIMEOUT)
|
|
506
|
+
except subprocess.TimeoutExpired as exc:
|
|
507
|
+
raise RuntimeError(f"LibreOffice 轉 PDF 逾時({_SOFFICE_TIMEOUT} 秒)") from exc
|
|
508
|
+
pdf = outdir / (path.stem + ".pdf")
|
|
509
|
+
if proc.returncode != 0 or not pdf.exists():
|
|
510
|
+
detail = (proc.stderr or proc.stdout or "").strip()[:300]
|
|
511
|
+
raise RuntimeError(f"LibreOffice 轉 PDF 失敗:{detail or proc.returncode}")
|
|
512
|
+
return pdf
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
def check_layout(path: Path, soffice: Optional[Path]) -> LayoutReport:
|
|
516
|
+
"""Render ``path`` with LibreOffice and report text that left its space.
|
|
517
|
+
|
|
518
|
+
``soffice`` is passed in (usually :func:`~odforge.validate.find_soffice`)
|
|
519
|
+
rather than looked up here, so the caller's choice — including "none" — is
|
|
520
|
+
the one that holds. Never raises.
|
|
521
|
+
"""
|
|
522
|
+
path = Path(path)
|
|
523
|
+
unsupported = _unsupported(path)
|
|
524
|
+
if unsupported is not None:
|
|
525
|
+
return unsupported
|
|
526
|
+
if soffice is None:
|
|
527
|
+
return LayoutReport("unavailable", "找不到 LibreOffice(soffice),無法檢查跑版")
|
|
528
|
+
|
|
529
|
+
workdir = Path(tempfile.mkdtemp(prefix="odforge-layout-"))
|
|
530
|
+
try:
|
|
531
|
+
pdf = _convert_to_pdf(path, soffice, workdir)
|
|
532
|
+
except Exception as exc:
|
|
533
|
+
shutil.rmtree(workdir, ignore_errors=True)
|
|
534
|
+
return LayoutReport("unavailable", f"跑版檢查無法執行:{type(exc).__name__}: {exc}")
|
|
535
|
+
try:
|
|
536
|
+
return check_layout_pdf(path, pdf)
|
|
537
|
+
finally:
|
|
538
|
+
shutil.rmtree(workdir, ignore_errors=True)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _unsupported(path: Path) -> Optional[LayoutReport]:
|
|
542
|
+
ext = path.suffix.lower()
|
|
543
|
+
if ext == ".ods":
|
|
544
|
+
return LayoutReport("unsupported", "試算表沒有固定版面,不做跑版檢查")
|
|
545
|
+
if ext not in (".odp", ".odt"):
|
|
546
|
+
return LayoutReport("unsupported", f"不支援 {ext or '(無副檔名)'} 的跑版檢查")
|
|
547
|
+
return None
|
|
548
|
+
|
|
549
|
+
|
|
550
|
+
def check_layout_pdf(path: Path, pdf: Path) -> LayoutReport:
|
|
551
|
+
"""Like :func:`check_layout`, against a PDF LibreOffice already made of ``path``.
|
|
552
|
+
|
|
553
|
+
For callers that convert anyway (the live preview rasterises the same PDF),
|
|
554
|
+
so one document is not laid out twice. Never raises.
|
|
555
|
+
"""
|
|
556
|
+
path = Path(path)
|
|
557
|
+
unsupported = _unsupported(path)
|
|
558
|
+
if unsupported is not None:
|
|
559
|
+
return unsupported
|
|
560
|
+
try:
|
|
561
|
+
content, styles = _read_parts(path)
|
|
562
|
+
findings: List[LayoutFinding] = []
|
|
563
|
+
with pymupdf.open(pdf) as doc:
|
|
564
|
+
if path.suffix.lower() == ".odp":
|
|
565
|
+
slides = _slides(content, styles)
|
|
566
|
+
if len(slides) != doc.page_count:
|
|
567
|
+
return LayoutReport(
|
|
568
|
+
"unavailable",
|
|
569
|
+
f"投影片數({len(slides)})與轉出的頁數({doc.page_count})對不上,"
|
|
570
|
+
"無法逐頁比對",
|
|
571
|
+
)
|
|
572
|
+
for number, (frames, page) in enumerate(
|
|
573
|
+
zip(slides, doc, strict=True), start=1
|
|
574
|
+
):
|
|
575
|
+
findings.extend(
|
|
576
|
+
_slide_findings(
|
|
577
|
+
number,
|
|
578
|
+
frames,
|
|
579
|
+
_rendered_lines(page),
|
|
580
|
+
page.rect.width * _PT_TO_CM,
|
|
581
|
+
page.rect.height * _PT_TO_CM,
|
|
582
|
+
)
|
|
583
|
+
)
|
|
584
|
+
else:
|
|
585
|
+
margins = _text_area_right_margins(content, styles)
|
|
586
|
+
for number, page in enumerate(doc, start=1):
|
|
587
|
+
width = page.rect.width * _PT_TO_CM
|
|
588
|
+
findings.extend(
|
|
589
|
+
_text_page_findings(
|
|
590
|
+
number,
|
|
591
|
+
_rendered_lines(page),
|
|
592
|
+
width,
|
|
593
|
+
page.rect.height * _PT_TO_CM,
|
|
594
|
+
margins.get(round(width, 1), 0.0),
|
|
595
|
+
)
|
|
596
|
+
)
|
|
597
|
+
except Exception as exc:
|
|
598
|
+
return LayoutReport("unavailable", f"跑版檢查無法執行:{type(exc).__name__}: {exc}")
|
|
599
|
+
|
|
600
|
+
if not findings:
|
|
601
|
+
return LayoutReport("ok", "沒有文字超出框或頁面")
|
|
602
|
+
return LayoutReport("overflow", f"發現 {len(findings)} 處跑版", findings)
|