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/package.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""ODF package writer: zip packaging + auto-generated manifest.
|
|
2
|
+
|
|
3
|
+
Independent module (no dependency on ir/render). Packages hand-written
|
|
4
|
+
ODF part streams (content.xml/styles.xml/...) into a valid ODF zip that
|
|
5
|
+
obeys the mimetype-first-stored rule and carries a generated
|
|
6
|
+
META-INF/manifest.xml.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import time
|
|
13
|
+
import uuid
|
|
14
|
+
import zipfile
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from xml.sax.saxutils import escape
|
|
17
|
+
|
|
18
|
+
ODT_MIMETYPE = "application/vnd.oasis.opendocument.text"
|
|
19
|
+
ODP_MIMETYPE = "application/vnd.oasis.opendocument.presentation"
|
|
20
|
+
ODS_MIMETYPE = "application/vnd.oasis.opendocument.spreadsheet"
|
|
21
|
+
|
|
22
|
+
_MANIFEST_NS = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"
|
|
23
|
+
|
|
24
|
+
# Media types inferred from the file extension of binary (bytes) parts.
|
|
25
|
+
_BINARY_MEDIA_TYPES = {
|
|
26
|
+
".otf": "application/x-font-otf",
|
|
27
|
+
".ttf": "application/x-font-ttf",
|
|
28
|
+
".png": "image/png",
|
|
29
|
+
".svg": "image/svg+xml",
|
|
30
|
+
".jpg": "image/jpeg",
|
|
31
|
+
".jpeg": "image/jpeg",
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _media_type(name: str, content: str | bytes) -> str:
|
|
36
|
+
"""Resolve the manifest media-type for a package part.
|
|
37
|
+
|
|
38
|
+
str content is treated as XML (``text/xml``); bytes content has its
|
|
39
|
+
media-type inferred from the file extension, falling back to the generic
|
|
40
|
+
``application/octet-stream`` for unknown binary extensions.
|
|
41
|
+
"""
|
|
42
|
+
if isinstance(content, str):
|
|
43
|
+
return "text/xml"
|
|
44
|
+
suffix = Path(name).suffix.lower()
|
|
45
|
+
return _BINARY_MEDIA_TYPES.get(suffix, "application/octet-stream")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_manifest(mimetype: str, parts: dict[str, str | bytes]) -> str:
|
|
49
|
+
"""Build a META-INF/manifest.xml document listing the package parts.
|
|
50
|
+
|
|
51
|
+
Pure function: given the package mimetype and the parts mapping, returns a
|
|
52
|
+
well-formed manifest XML string. The root "/" entry carries the document
|
|
53
|
+
mimetype; str parts are declared as text/xml, while bytes parts get a
|
|
54
|
+
media-type inferred from their file extension.
|
|
55
|
+
"""
|
|
56
|
+
lines = [
|
|
57
|
+
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
58
|
+
f'<manifest:manifest xmlns:manifest="{_MANIFEST_NS}" manifest:version="1.2">',
|
|
59
|
+
' <manifest:file-entry manifest:full-path="/" '
|
|
60
|
+
f'manifest:media-type="{escape(mimetype, {chr(34): """})}"/>',
|
|
61
|
+
]
|
|
62
|
+
for name, content in parts.items():
|
|
63
|
+
media_type = _media_type(name, content)
|
|
64
|
+
lines.append(
|
|
65
|
+
f' <manifest:file-entry manifest:full-path="{escape(name, {chr(34): """})}"'
|
|
66
|
+
f' manifest:media-type="{media_type}"/>'
|
|
67
|
+
)
|
|
68
|
+
lines.append("</manifest:manifest>")
|
|
69
|
+
return "\n".join(lines)
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def write_odf_package(path: Path, mimetype: str, parts: dict[str, str | bytes]) -> Path:
|
|
73
|
+
"""Write an ODF zip package to ``path`` and return that path.
|
|
74
|
+
|
|
75
|
+
The ``mimetype`` entry is written first and uncompressed (ZIP_STORED),
|
|
76
|
+
as required by the ODF spec. Remaining ``parts`` and the generated
|
|
77
|
+
manifest are written with ZIP_DEFLATED. str parts are encoded as UTF-8;
|
|
78
|
+
bytes parts (e.g. images) are written verbatim.
|
|
79
|
+
|
|
80
|
+
The zip is assembled in a sibling temp file and moved into place with
|
|
81
|
+
``os.replace``: QA repair and per-slide 重生 re-render the same path a
|
|
82
|
+
reader may be streaming at that moment (the web download endpoint), and a
|
|
83
|
+
truncate-in-place ``ZipFile(path, "w")`` hands that reader a half-written
|
|
84
|
+
archive with a 200. Windows refuses the replace while such a handle is
|
|
85
|
+
open, so it is retried briefly — a corrupt download is the one outcome
|
|
86
|
+
that must stay impossible.
|
|
87
|
+
"""
|
|
88
|
+
path = Path(path)
|
|
89
|
+
tmp_path = path.with_name(f"{path.name}.{uuid.uuid4().hex[:8]}.part")
|
|
90
|
+
try:
|
|
91
|
+
with zipfile.ZipFile(tmp_path, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
|
92
|
+
mimetype_info = zipfile.ZipInfo("mimetype")
|
|
93
|
+
mimetype_info.compress_type = zipfile.ZIP_STORED
|
|
94
|
+
z.writestr(mimetype_info, mimetype.encode("utf-8"))
|
|
95
|
+
|
|
96
|
+
for name, content in parts.items():
|
|
97
|
+
data = content.encode("utf-8") if isinstance(content, str) else content
|
|
98
|
+
z.writestr(name, data)
|
|
99
|
+
|
|
100
|
+
manifest = build_manifest(mimetype, parts)
|
|
101
|
+
z.writestr("META-INF/manifest.xml", manifest.encode("utf-8"))
|
|
102
|
+
|
|
103
|
+
last_error: OSError | None = None
|
|
104
|
+
for _ in range(5):
|
|
105
|
+
try:
|
|
106
|
+
os.replace(tmp_path, path)
|
|
107
|
+
return path
|
|
108
|
+
except PermissionError as exc:
|
|
109
|
+
last_error = exc
|
|
110
|
+
time.sleep(0.2)
|
|
111
|
+
raise last_error # a reader held the file for >1s; keep the old copy intact
|
|
112
|
+
finally:
|
|
113
|
+
if tmp_path.exists():
|
|
114
|
+
tmp_path.unlink(missing_ok=True)
|
odforge/pagefacts.py
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
"""What the renderer actually emitted, as plain facts for the design critic.
|
|
2
|
+
|
|
3
|
+
The vision critic used to receive images and a checklist and nothing else. Asked
|
|
4
|
+
to judge alignment and contrast from pixels alone, it did what anyone would: it
|
|
5
|
+
estimated, and some estimates were wrong. It reported *「三張卡片高度不一致」* on
|
|
6
|
+
a row of three 6.80cm cards, and *「對比不足」* on #1F2733 text measuring 12.52:1.
|
|
7
|
+
Worse in the other direction, a deck whose every card had been repainted on top
|
|
8
|
+
of its own text — three pages of blank boxes — drew four remarks about title
|
|
9
|
+
spacing and not one about the missing words, because nothing in its context said
|
|
10
|
+
those cards were supposed to contain anything.
|
|
11
|
+
|
|
12
|
+
An earlier version of this module answered that by checking the critic's claims
|
|
13
|
+
against measurements and overruling the ones that failed. That worked, but only
|
|
14
|
+
one defect at a time: a keyword list per claim family, extended the first time
|
|
15
|
+
the model wrote 「色塊」 instead of 「卡片」, and due for extension again at every
|
|
16
|
+
new layout and every new turn of phrase. The list is never finished.
|
|
17
|
+
|
|
18
|
+
So the measurements stay and the verdicts go. :func:`grounding_text` hands the
|
|
19
|
+
critic what the renderer worked from — boxes, colours, sizes, paint order — and
|
|
20
|
+
lets it reach its own conclusion. A controlled comparison on a deck whose text
|
|
21
|
+
was buried under its own cards showed the blind spot close: unprompted, at error
|
|
22
|
+
severity, it identified the hidden words.
|
|
23
|
+
|
|
24
|
+
A second comparison showed what the dump must *not* be, twice over. Given two
|
|
25
|
+
hex colours the critic computed 2.8:1 for a pair measuring 13:1 and cited WCAG
|
|
26
|
+
against its own wrong answer. Handed the ratio already computed, it stopped
|
|
27
|
+
miscalculating and started misjudging instead: 11.8:1 was reported as 「低於
|
|
28
|
+
WCAG AA 標準建議的 12:1」 — a threshold that does not exist — and the 96pt
|
|
29
|
+
section-number watermark, faint by design at 2.1:1, became an error. Errors per
|
|
30
|
+
run tripled. The failure is not the arithmetic and not the threshold wording; it
|
|
31
|
+
is that a colour ratio is not a judgement this model can make, computed for it
|
|
32
|
+
or not.
|
|
33
|
+
|
|
34
|
+
So contrast numbers are not supplied here at all. What is supplied is geometry:
|
|
35
|
+
boxes, sizes, paint order, and the height and gap differences already reduced —
|
|
36
|
+
the facts behind the one thing grounding measurably fixed, which is seeing that
|
|
37
|
+
text on the page is not visible on the page.
|
|
38
|
+
|
|
39
|
+
**Contract change worth knowing:** this abandons the strict independent-context
|
|
40
|
+
rule the critic was built with. It now sees the page's text, not just its
|
|
41
|
+
picture. That is the point — text that *should* be visible is the only way to
|
|
42
|
+
notice text that is not — but it does mean the critic is no longer judging
|
|
43
|
+
purely from what a viewer would see. Nothing about the *generation* reaches it:
|
|
44
|
+
no prompt, no outline, no model history. Only the finished page.
|
|
45
|
+
|
|
46
|
+
Never raises: an unreadable package yields no facts, and a critique with no
|
|
47
|
+
grounding is exactly the critique this module was added to improve.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
from __future__ import annotations
|
|
51
|
+
|
|
52
|
+
import re
|
|
53
|
+
import zipfile
|
|
54
|
+
from dataclasses import dataclass, field
|
|
55
|
+
from itertools import pairwise
|
|
56
|
+
from pathlib import Path
|
|
57
|
+
from typing import Dict, List, Sequence
|
|
58
|
+
|
|
59
|
+
from lxml import etree
|
|
60
|
+
|
|
61
|
+
from odforge.xmlsafe import safe_fromstring
|
|
62
|
+
|
|
63
|
+
_NS = {
|
|
64
|
+
"draw": "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
|
|
65
|
+
"svg": "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
|
|
66
|
+
"style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
|
|
67
|
+
"fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
|
|
68
|
+
"text": "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
|
|
69
|
+
"presentation": "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _cm(value: str | None) -> float:
|
|
74
|
+
"""Parse an ODF length like ``"6.8cm"`` into centimetres (0.0 when absent)."""
|
|
75
|
+
if not value:
|
|
76
|
+
return 0.0
|
|
77
|
+
match = re.match(r"^(-?[0-9.]+)\s*([a-z]*)$", value.strip())
|
|
78
|
+
if not match:
|
|
79
|
+
return 0.0
|
|
80
|
+
number, unit = float(match.group(1)), match.group(2)
|
|
81
|
+
if unit in ("cm", ""):
|
|
82
|
+
return number
|
|
83
|
+
if unit == "mm":
|
|
84
|
+
return number / 10
|
|
85
|
+
if unit == "in":
|
|
86
|
+
return number * 2.54
|
|
87
|
+
if unit == "pt":
|
|
88
|
+
return number * 2.54 / 72
|
|
89
|
+
return number
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _pt(value: str) -> float:
|
|
93
|
+
"""Parse an ODF font size like ``"96pt"`` into points (0.0 when unparseable)."""
|
|
94
|
+
match = re.match(r"^([0-9.]+)\s*pt$", value.strip())
|
|
95
|
+
return float(match.group(1)) if match else 0.0
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
@dataclass(frozen=True)
|
|
99
|
+
class Box:
|
|
100
|
+
"""A positioned rectangle in centimetres."""
|
|
101
|
+
|
|
102
|
+
x: float
|
|
103
|
+
y: float
|
|
104
|
+
w: float
|
|
105
|
+
h: float
|
|
106
|
+
|
|
107
|
+
def contains(self, px: float, py: float) -> bool:
|
|
108
|
+
return self.x <= px <= self.x + self.w and self.y <= py <= self.y + self.h
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
@dataclass(frozen=True)
|
|
112
|
+
class Shape:
|
|
113
|
+
"""A filled shape. ``order`` is its position in paint order."""
|
|
114
|
+
|
|
115
|
+
box: Box
|
|
116
|
+
fill: str
|
|
117
|
+
order: int = 0
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
@dataclass(frozen=True)
|
|
121
|
+
class TextRun:
|
|
122
|
+
"""A positioned text frame: its ink, size, and place in paint order."""
|
|
123
|
+
|
|
124
|
+
box: Box
|
|
125
|
+
color: str
|
|
126
|
+
text: str
|
|
127
|
+
order: int = 0
|
|
128
|
+
size_pt: float = 0.0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
@dataclass
|
|
132
|
+
class PageMeasure:
|
|
133
|
+
"""One page as the renderer emitted it. Facts only — no judgements."""
|
|
134
|
+
|
|
135
|
+
number: int
|
|
136
|
+
shapes: List[Shape] = field(default_factory=list)
|
|
137
|
+
runs: List[TextRun] = field(default_factory=list)
|
|
138
|
+
background: str = "#FFFFFF"
|
|
139
|
+
|
|
140
|
+
def backdrop(self, run: TextRun) -> str:
|
|
141
|
+
"""The fill behind ``run`` — the last shape painted *under* it.
|
|
142
|
+
|
|
143
|
+
Shapes painted after the run are covers, not backdrops; reading one as a
|
|
144
|
+
background is how a page whose text is buried under an opaque card
|
|
145
|
+
measures as perfectly legible.
|
|
146
|
+
"""
|
|
147
|
+
cx, cy = run.box.x + run.box.w / 2, run.box.y + run.box.h / 2
|
|
148
|
+
fill = self.background
|
|
149
|
+
for shape in self.shapes:
|
|
150
|
+
if shape.order < run.order and shape.box.contains(cx, cy):
|
|
151
|
+
fill = shape.fill
|
|
152
|
+
return fill
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _painted(element: etree._Element):
|
|
156
|
+
"""Walk a page's drawing elements in paint order, skipping speaker notes.
|
|
157
|
+
|
|
158
|
+
``<presentation:notes>`` is a child of ``<draw:page>`` but is never drawn on
|
|
159
|
+
the slide, so descending into it would hand the critic the presenter script
|
|
160
|
+
as though it were on the canvas.
|
|
161
|
+
"""
|
|
162
|
+
for child in element:
|
|
163
|
+
if child.tag == f"{{{_NS['presentation']}}}notes":
|
|
164
|
+
continue
|
|
165
|
+
yield child
|
|
166
|
+
yield from _painted(child)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _style_colours(
|
|
170
|
+
roots: Sequence[etree._Element],
|
|
171
|
+
) -> tuple[Dict[str, str], Dict[str, str], Dict[str, float]]:
|
|
172
|
+
"""Map style name → fill colour, → text colour, and → font size in points."""
|
|
173
|
+
fills: Dict[str, str] = {}
|
|
174
|
+
inks: Dict[str, str] = {}
|
|
175
|
+
sizes: Dict[str, float] = {}
|
|
176
|
+
for root in roots:
|
|
177
|
+
for style in root.iter(f"{{{_NS['style']}}}style"):
|
|
178
|
+
name = style.get(f"{{{_NS['style']}}}name")
|
|
179
|
+
if not name:
|
|
180
|
+
continue
|
|
181
|
+
for gp in style.iter(f"{{{_NS['style']}}}graphic-properties"):
|
|
182
|
+
fill = gp.get(f"{{{_NS['draw']}}}fill-color")
|
|
183
|
+
if fill:
|
|
184
|
+
fills[name] = fill
|
|
185
|
+
for tp in style.iter(f"{{{_NS['style']}}}text-properties"):
|
|
186
|
+
ink = tp.get(f"{{{_NS['fo']}}}color")
|
|
187
|
+
if ink:
|
|
188
|
+
inks[name] = ink
|
|
189
|
+
size = tp.get(f"{{{_NS['fo']}}}font-size")
|
|
190
|
+
if size:
|
|
191
|
+
sizes[name] = _pt(size)
|
|
192
|
+
return fills, inks, sizes
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _page_backgrounds(roots: Sequence[etree._Element]) -> Dict[str, str]:
|
|
196
|
+
"""Map drawing-page style name → its fill colour."""
|
|
197
|
+
backgrounds: Dict[str, str] = {}
|
|
198
|
+
for root in roots:
|
|
199
|
+
for style in root.iter(f"{{{_NS['style']}}}style"):
|
|
200
|
+
name = style.get(f"{{{_NS['style']}}}name")
|
|
201
|
+
if not name:
|
|
202
|
+
continue
|
|
203
|
+
for dp in style.iter(f"{{{_NS['style']}}}drawing-page-properties"):
|
|
204
|
+
fill = dp.get(f"{{{_NS['draw']}}}fill-color")
|
|
205
|
+
if fill:
|
|
206
|
+
backgrounds[name] = fill
|
|
207
|
+
return backgrounds
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _box_of(element: etree._Element) -> Box:
|
|
211
|
+
return Box(
|
|
212
|
+
_cm(element.get(f"{{{_NS['svg']}}}x")),
|
|
213
|
+
_cm(element.get(f"{{{_NS['svg']}}}y")),
|
|
214
|
+
_cm(element.get(f"{{{_NS['svg']}}}width")),
|
|
215
|
+
_cm(element.get(f"{{{_NS['svg']}}}height")),
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def page_measurements(odp_path: Path) -> Dict[int, PageMeasure]:
|
|
220
|
+
"""Measure every page of ``odp_path``: shapes, text runs, colours, sizes.
|
|
221
|
+
|
|
222
|
+
Returns ``{page_number: PageMeasure}`` (1-based, matching ``Finding.slide_no``),
|
|
223
|
+
or ``{}`` when the package cannot be read.
|
|
224
|
+
"""
|
|
225
|
+
odp_path = Path(odp_path)
|
|
226
|
+
try:
|
|
227
|
+
with zipfile.ZipFile(odp_path) as package:
|
|
228
|
+
content = safe_fromstring(package.read("content.xml"))
|
|
229
|
+
try:
|
|
230
|
+
styles = safe_fromstring(package.read("styles.xml"))
|
|
231
|
+
except KeyError:
|
|
232
|
+
styles = content
|
|
233
|
+
except (OSError, KeyError, zipfile.BadZipFile, etree.XMLSyntaxError):
|
|
234
|
+
return {}
|
|
235
|
+
|
|
236
|
+
fills, inks, sizes = _style_colours((content, styles))
|
|
237
|
+
backgrounds = _page_backgrounds((content, styles))
|
|
238
|
+
|
|
239
|
+
pages: Dict[int, PageMeasure] = {}
|
|
240
|
+
for number, page_el in enumerate(content.iter(f"{{{_NS['draw']}}}page"), start=1):
|
|
241
|
+
measure = PageMeasure(number=number)
|
|
242
|
+
measure.background = backgrounds.get(
|
|
243
|
+
page_el.get(f"{{{_NS['draw']}}}style-name"), "#FFFFFF"
|
|
244
|
+
)
|
|
245
|
+
# Document order is paint order in ODF: later siblings render on top.
|
|
246
|
+
for order, element in enumerate(_painted(page_el)):
|
|
247
|
+
tag = etree.QName(element).localname
|
|
248
|
+
style_name = element.get(f"{{{_NS['draw']}}}style-name")
|
|
249
|
+
if tag in ("rect", "custom-shape", "polygon", "circle", "ellipse"):
|
|
250
|
+
fill = fills.get(style_name)
|
|
251
|
+
if fill:
|
|
252
|
+
measure.shapes.append(Shape(_box_of(element), fill, order))
|
|
253
|
+
elif tag == "line":
|
|
254
|
+
# A connector has no fill; record its span so the critic can see
|
|
255
|
+
# where a line actually runs rather than guess from pixels.
|
|
256
|
+
measure.shapes.append(
|
|
257
|
+
Shape(
|
|
258
|
+
Box(
|
|
259
|
+
min(_cm(element.get(f"{{{_NS['svg']}}}x1")),
|
|
260
|
+
_cm(element.get(f"{{{_NS['svg']}}}x2"))),
|
|
261
|
+
min(_cm(element.get(f"{{{_NS['svg']}}}y1")),
|
|
262
|
+
_cm(element.get(f"{{{_NS['svg']}}}y2"))),
|
|
263
|
+
abs(_cm(element.get(f"{{{_NS['svg']}}}x2"))
|
|
264
|
+
- _cm(element.get(f"{{{_NS['svg']}}}x1"))),
|
|
265
|
+
abs(_cm(element.get(f"{{{_NS['svg']}}}y2"))
|
|
266
|
+
- _cm(element.get(f"{{{_NS['svg']}}}y1"))),
|
|
267
|
+
),
|
|
268
|
+
"line",
|
|
269
|
+
order,
|
|
270
|
+
)
|
|
271
|
+
)
|
|
272
|
+
elif tag == "frame":
|
|
273
|
+
paragraph = next(iter(element.iter(f"{{{_NS['text']}}}p")), None)
|
|
274
|
+
if paragraph is None:
|
|
275
|
+
continue
|
|
276
|
+
paragraph_style = paragraph.get(f"{{{_NS['text']}}}style-name")
|
|
277
|
+
ink = inks.get(paragraph_style)
|
|
278
|
+
if not ink:
|
|
279
|
+
continue
|
|
280
|
+
measure.runs.append(
|
|
281
|
+
TextRun(
|
|
282
|
+
_box_of(element),
|
|
283
|
+
ink,
|
|
284
|
+
"".join(element.itertext()),
|
|
285
|
+
order,
|
|
286
|
+
sizes.get(paragraph_style, 0.0),
|
|
287
|
+
)
|
|
288
|
+
)
|
|
289
|
+
pages[number] = measure
|
|
290
|
+
return pages
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
_GROUNDING_PREAMBLE = """\
|
|
294
|
+
以下是這份簡報的實際版面資料,由排版引擎輸出,不是推測值。座標單位公分,原點在
|
|
295
|
+
左上角;paint 為繪製順序,數字越大越後畫、越蓋在上層。請用這些數字核對你從影像
|
|
296
|
+
中看到的東西,不要憑目測估計位置、大小或顏色。若你的觀察與資料不符,以資料為準,
|
|
297
|
+
並據此修正或撤回該項判斷。
|
|
298
|
+
|
|
299
|
+
色塊高度差與間距差都已經替你算好,直接引用即可,不要自行從座標重新計算。凡是資料裡
|
|
300
|
+
寫「完全相同」或差距標為 0.00 的,就是完全一致,不要提出等高或間距方面的 finding。"""
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# A filled shape this size or larger reads as a container whose geometry a
|
|
304
|
+
# viewer would compare against its neighbours; below it is decoration (a rule, an
|
|
305
|
+
# accent bar) and belongs in no evenness summary.
|
|
306
|
+
_CONTAINER_MIN_W = 2.0
|
|
307
|
+
_CONTAINER_MIN_H = 1.0
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _containers(page: PageMeasure) -> List[Box]:
|
|
311
|
+
return [
|
|
312
|
+
s.box
|
|
313
|
+
for s in page.shapes
|
|
314
|
+
if s.fill != "line"
|
|
315
|
+
and s.box.w >= _CONTAINER_MIN_W
|
|
316
|
+
and s.box.h >= _CONTAINER_MIN_H
|
|
317
|
+
]
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _evenness(page: PageMeasure) -> str:
|
|
321
|
+
"""One line stating how even this page's containers actually are.
|
|
322
|
+
|
|
323
|
+
The arithmetic is done here because the model demonstrably cannot do it:
|
|
324
|
+
handed four x-coordinates it reported 6.11cm and 6.12cm as 「肉眼可見」
|
|
325
|
+
unevenness, and handed two hex colours it computed 2.8:1 for a pair that
|
|
326
|
+
measures 13:1 and cited WCAG against its own wrong answer. Raw numbers it
|
|
327
|
+
must reduce itself are worse than no numbers — they lend false authority to
|
|
328
|
+
a bad calculation. So the differences arrive already reduced.
|
|
329
|
+
"""
|
|
330
|
+
boxes = _containers(page)
|
|
331
|
+
if len(boxes) < 2:
|
|
332
|
+
return ""
|
|
333
|
+
heights = [b.h for b in boxes]
|
|
334
|
+
spread = max(heights) - min(heights)
|
|
335
|
+
parts = [
|
|
336
|
+
f"本頁有 {len(boxes)} 個色塊,高度差 {spread:.2f}cm"
|
|
337
|
+
+ ("(完全相同)" if spread < 0.005 else "")
|
|
338
|
+
]
|
|
339
|
+
rows: Dict[int, List[Box]] = {}
|
|
340
|
+
for box in boxes:
|
|
341
|
+
rows.setdefault(round(box.y * 20), []).append(box)
|
|
342
|
+
for row in rows.values():
|
|
343
|
+
if len(row) < 3:
|
|
344
|
+
continue
|
|
345
|
+
xs = sorted(b.x for b in row)
|
|
346
|
+
gaps = [b - a for a, b in pairwise(xs)]
|
|
347
|
+
gap_spread = max(gaps) - min(gaps)
|
|
348
|
+
parts.append(
|
|
349
|
+
f"同一列 {len(row)} 個色塊的水平間距差 {gap_spread:.2f}cm"
|
|
350
|
+
+ ("(完全相同)" if gap_spread < 0.005 else "")
|
|
351
|
+
)
|
|
352
|
+
return " " + ";".join(parts)
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def grounding_text(odp_path: Path) -> str:
|
|
356
|
+
"""Render the page facts as context for the critic (``""`` when unreadable).
|
|
357
|
+
|
|
358
|
+
Quantities the model would otherwise have to derive — contrast ratios,
|
|
359
|
+
height and spacing differences — arrive already computed; see
|
|
360
|
+
:func:`_evenness`. Text is reproduced in full: a truncated string reads as
|
|
361
|
+
text the *renderer* cut off, and gets reported as a defect.
|
|
362
|
+
"""
|
|
363
|
+
pages = page_measurements(odp_path)
|
|
364
|
+
if not pages:
|
|
365
|
+
return ""
|
|
366
|
+
lines = [_GROUNDING_PREAMBLE]
|
|
367
|
+
for number, page in sorted(pages.items()):
|
|
368
|
+
lines.append(f"\n[第 {number} 頁] 頁面背景 {page.background}")
|
|
369
|
+
evenness = _evenness(page)
|
|
370
|
+
if evenness:
|
|
371
|
+
lines.append(evenness)
|
|
372
|
+
for shape in page.shapes:
|
|
373
|
+
kind = "連接線" if shape.fill == "line" else f"色塊 填色={shape.fill}"
|
|
374
|
+
lines.append(
|
|
375
|
+
f" {kind} paint={shape.order} x={shape.box.x:.2f} y={shape.box.y:.2f} "
|
|
376
|
+
f"w={shape.box.w:.2f} h={shape.box.h:.2f}"
|
|
377
|
+
)
|
|
378
|
+
for run in page.runs:
|
|
379
|
+
text = " ".join(run.text.split())
|
|
380
|
+
if not text:
|
|
381
|
+
continue
|
|
382
|
+
backdrop = page.backdrop(run)
|
|
383
|
+
lines.append(
|
|
384
|
+
f" 文字 paint={run.order} x={run.box.x:.2f} y={run.box.y:.2f} "
|
|
385
|
+
f"w={run.box.w:.2f} h={run.box.h:.2f} {run.size_pt:.0f}pt "
|
|
386
|
+
f"色={run.color} 其後方={backdrop} 內容={text!r}"
|
|
387
|
+
)
|
|
388
|
+
return "\n".join(lines)
|
odforge/preview.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Page-to-PNG preview rendering.
|
|
2
|
+
|
|
3
|
+
``render_pages`` rasterises an ODF file to one PNG per page. It reuses
|
|
4
|
+
``validate.run_soffice_convert`` (isolated LibreOffice profile) to obtain a
|
|
5
|
+
PDF, then rasterises each PDF page with PyMuPDF (``fitz``).
|
|
6
|
+
|
|
7
|
+
Shared by the QA harness (Phase 16) and the future web API. When LibreOffice
|
|
8
|
+
is not installed, :class:`PreviewUnavailable` is raised so the caller can
|
|
9
|
+
decide how to degrade rather than the pipeline crashing opaquely.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
import tempfile
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
# `pymupdf`, never the legacy `fitz` alias: importing `fitz` makes PyMuPDF print
|
|
20
|
+
# a deprecation notice to **stdout**. For a stdio MCP server that is not cosmetic
|
|
21
|
+
# — every byte on stdout is protocol, so one stray line corrupts the stream and
|
|
22
|
+
# the host sees a broken server. (It also pollutes any CLI output piped to a
|
|
23
|
+
# file.) The alias is kept so the rest of the module reads unchanged.
|
|
24
|
+
import pymupdf as fitz
|
|
25
|
+
|
|
26
|
+
from .validate import find_soffice, run_soffice_convert
|
|
27
|
+
|
|
28
|
+
_SOFFICE_TIMEOUT = 120
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class PreviewUnavailable(Exception):
|
|
32
|
+
"""Raised when preview rendering cannot proceed (soffice not found)."""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def convert_to_pdf(odf_path: Path, outdir: Path) -> Path:
|
|
36
|
+
"""Convert ``odf_path`` to a PDF in ``outdir`` (isolated LibreOffice profile).
|
|
37
|
+
|
|
38
|
+
Raises :class:`PreviewUnavailable` when LibreOffice is not found, and a
|
|
39
|
+
:class:`RuntimeError` when the conversion itself fails.
|
|
40
|
+
"""
|
|
41
|
+
odf_path = Path(odf_path)
|
|
42
|
+
soffice = find_soffice()
|
|
43
|
+
if soffice is None:
|
|
44
|
+
raise PreviewUnavailable(
|
|
45
|
+
"LibreOffice (soffice) not found; cannot render a preview. "
|
|
46
|
+
"Install LibreOffice or check it is on PATH."
|
|
47
|
+
)
|
|
48
|
+
try:
|
|
49
|
+
proc = run_soffice_convert(
|
|
50
|
+
soffice, odf_path, "pdf", outdir, timeout=_SOFFICE_TIMEOUT
|
|
51
|
+
)
|
|
52
|
+
except subprocess.TimeoutExpired as exc:
|
|
53
|
+
raise RuntimeError(
|
|
54
|
+
f"soffice timed out after {_SOFFICE_TIMEOUT}s converting "
|
|
55
|
+
f"{odf_path.name} to pdf"
|
|
56
|
+
) from exc
|
|
57
|
+
|
|
58
|
+
if proc.returncode != 0:
|
|
59
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
60
|
+
raise RuntimeError(
|
|
61
|
+
f"soffice exited {proc.returncode} converting {odf_path.name} "
|
|
62
|
+
f"to pdf: {detail[:500]}"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
pdf_path = Path(outdir) / (odf_path.stem + ".pdf")
|
|
66
|
+
if not pdf_path.exists():
|
|
67
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
68
|
+
raise RuntimeError(
|
|
69
|
+
f"soffice produced no pdf for {odf_path.name}: {detail[:500]}"
|
|
70
|
+
)
|
|
71
|
+
return pdf_path
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def rasterise_pdf(pdf_path: Path, out_dir: Path, dpi: int = 150) -> list[Path]:
|
|
75
|
+
"""Render each page of ``pdf_path`` to ``out_dir/page-NN.png`` (1-based)."""
|
|
76
|
+
out_dir = Path(out_dir)
|
|
77
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
pngs: list[Path] = []
|
|
79
|
+
with fitz.open(pdf_path) as doc:
|
|
80
|
+
for index, page in enumerate(doc, start=1):
|
|
81
|
+
pix = page.get_pixmap(dpi=dpi)
|
|
82
|
+
png_path = out_dir / f"page-{index:02d}.png"
|
|
83
|
+
pix.save(str(png_path))
|
|
84
|
+
pngs.append(png_path)
|
|
85
|
+
return pngs
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def render_pages(odf_path: Path, out_dir: Path, dpi: int = 150) -> list[Path]:
|
|
89
|
+
"""Rasterise ``odf_path`` to one PNG per page in ``out_dir``.
|
|
90
|
+
|
|
91
|
+
Converts the ODF to PDF through an isolated-profile LibreOffice headless
|
|
92
|
+
run, then renders each PDF page to a zero-padded, 1-based PNG
|
|
93
|
+
(``page-01.png``, ``page-02.png``, ...) at ``dpi``. Returns the PNG paths
|
|
94
|
+
in page order.
|
|
95
|
+
|
|
96
|
+
Raises :class:`PreviewUnavailable` when LibreOffice is not found, and a
|
|
97
|
+
:class:`RuntimeError` when the conversion itself fails.
|
|
98
|
+
"""
|
|
99
|
+
pdf_dir = Path(tempfile.mkdtemp(prefix="odforge-preview-"))
|
|
100
|
+
try:
|
|
101
|
+
pdf_path = convert_to_pdf(odf_path, pdf_dir)
|
|
102
|
+
return rasterise_pdf(pdf_path, out_dir, dpi)
|
|
103
|
+
finally:
|
|
104
|
+
shutil.rmtree(pdf_dir, ignore_errors=True)
|