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/extract.py
ADDED
|
@@ -0,0 +1,478 @@
|
|
|
1
|
+
"""Style extraction from an existing ODF template (殺手功能:吃現有範本).
|
|
2
|
+
|
|
3
|
+
The cheapest source of design quality is a template the user already owns:
|
|
4
|
+
governments and schools ship public ODF templates, and ODF is open XML, so
|
|
5
|
+
sampling their look is easy. :func:`extract_design` opens such a template
|
|
6
|
+
(``.otp``/``.odp``/``.ott``/``.odt``), reads its ``styles.xml`` (and
|
|
7
|
+
``content.xml`` for automatic styles), and derives a
|
|
8
|
+
:class:`~odforge.ir.DesignSpec` that renders new content into the template's
|
|
9
|
+
look.
|
|
10
|
+
|
|
11
|
+
**MVP scope (定案):** derive the four cheap, high-signal tokens and backfill the
|
|
12
|
+
rest — this is *not* full master-page reuse.
|
|
13
|
+
|
|
14
|
+
* **bg** — the drawing-page / page background fill (a solid ``draw:fill-color``,
|
|
15
|
+
or a gradient's ``draw:start-color`` when the page is painted with one).
|
|
16
|
+
* **text / title** — the most frequent ``fo:color`` that clears the WCAG text
|
|
17
|
+
bar against ``bg``.
|
|
18
|
+
* **accent** — the most frequent *chromatic* (non-grey) ``fo:color`` that clears
|
|
19
|
+
the accent bar.
|
|
20
|
+
* **fonts** — the ``font-face-decls`` declarations mapped onto
|
|
21
|
+
:data:`~odforge.ir.FONT_WHITELIST`.
|
|
22
|
+
|
|
23
|
+
Every candidate is fed through the *same* :class:`~odforge.ir.Palette` /
|
|
24
|
+
:class:`~odforge.ir.FontPair` validators the renderer trusts. Any field
|
|
25
|
+
extraction cannot confidently fill — or that fails contrast — is backfilled from
|
|
26
|
+
the academic preset, so the result is ALWAYS a valid ``DesignSpec``. Only a
|
|
27
|
+
genuinely unreadable / corrupt file raises (:class:`TemplateExtractionError`).
|
|
28
|
+
|
|
29
|
+
**surface / muted derivation:** these two are hard to sample reliably, so they
|
|
30
|
+
are *derived* to guarantee contrast holds regardless of the extracted bg/text:
|
|
31
|
+
``surface`` is ``bg`` blended toward ``text`` by the largest "hair" that keeps
|
|
32
|
+
text (4.5:1) and accent (3:1) legible on it — cards paint real text on surface,
|
|
33
|
+
so it carries the same bars as bg — and ``muted`` is ``text`` blended toward
|
|
34
|
+
``bg`` by the largest amount that still clears the 3:1 muted bar on both bg and
|
|
35
|
+
surface (the "mutest" legible tone). If even that cannot be met, each falls
|
|
36
|
+
back to its zero-blend anchor (``bg`` / ``text``), which passes by
|
|
37
|
+
construction.
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
from __future__ import annotations
|
|
41
|
+
|
|
42
|
+
import zipfile
|
|
43
|
+
from collections import Counter
|
|
44
|
+
from pathlib import Path
|
|
45
|
+
from typing import Optional
|
|
46
|
+
|
|
47
|
+
import lxml.etree as etree
|
|
48
|
+
|
|
49
|
+
from odforge.ir import (
|
|
50
|
+
_HEX_RE,
|
|
51
|
+
FONT_WHITELIST,
|
|
52
|
+
DesignSpec,
|
|
53
|
+
FontPair,
|
|
54
|
+
Palette,
|
|
55
|
+
_relative_luminance,
|
|
56
|
+
contrast_ratio,
|
|
57
|
+
)
|
|
58
|
+
from odforge.themes import THEMES
|
|
59
|
+
from odforge.xmlsafe import SAFE_PARSER as _SAFE_XML_PARSER # noqa: F401
|
|
60
|
+
from odforge.xmlsafe import safe_fromstring
|
|
61
|
+
from odforge.zipguard import (
|
|
62
|
+
MAX_XML_MEMBER,
|
|
63
|
+
ArchiveLimitError,
|
|
64
|
+
inspect_archive,
|
|
65
|
+
read_xml_member,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
# The preset the extractor backfills from when a field can't be confidently
|
|
69
|
+
# determined or fails contrast. Academic is the project default art direction.
|
|
70
|
+
_PRESET = THEMES["academic"]
|
|
71
|
+
|
|
72
|
+
# ODF namespaces this extractor reaches into.
|
|
73
|
+
_NS = {
|
|
74
|
+
"office": "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
|
|
75
|
+
"style": "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
|
|
76
|
+
"draw": "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
|
|
77
|
+
"fo": "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
|
|
78
|
+
"svg": "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
# Parts we try to read, in priority order. styles.xml holds the master/main
|
|
82
|
+
# drawing-page + font-face-decls; content.xml carries per-page automatic styles.
|
|
83
|
+
_PARTS = ("styles.xml", "content.xml")
|
|
84
|
+
|
|
85
|
+
# ``extract_design`` parses attacker-controllable ODF templates ("eat an existing
|
|
86
|
+
# template"), so it parses through the shared hardened parser (no external-entity
|
|
87
|
+
# resolution, bounded expansion). ``_SAFE_XML_PARSER`` is re-exported from the
|
|
88
|
+
# single source of truth in :mod:`odforge.xmlsafe` for white-box tests.
|
|
89
|
+
|
|
90
|
+
# A colour counts as "chromatic" (an accent candidate, not a grey/near-white/
|
|
91
|
+
# near-black) when the spread between its max and min RGB channel exceeds this.
|
|
92
|
+
_CHROMA_MIN = 28
|
|
93
|
+
|
|
94
|
+
# WCAG bars, mirrored from ir.Palette so we can pre-filter candidates before
|
|
95
|
+
# construction (Palette re-checks them authoritatively).
|
|
96
|
+
_TEXT_MIN = 4.5
|
|
97
|
+
_ACCENT_MIN = 3.0
|
|
98
|
+
_MUTED_MIN = 3.0
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class TemplateExtractionError(Exception):
|
|
102
|
+
"""Raised when a template is unreadable — not a zip, or carrying no readable
|
|
103
|
+
ODF part (styles.xml / content.xml). A plausible-but-imperfect template never
|
|
104
|
+
raises; it is backfilled from the preset instead."""
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _q(prefix: str, local: str) -> str:
|
|
108
|
+
"""Clark-notation qualified name for an lxml attribute/element lookup."""
|
|
109
|
+
return f"{{{_NS[prefix]}}}{local}"
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
# ---------------------------------------------------------------------------
|
|
113
|
+
# Zip + XML reading
|
|
114
|
+
# ---------------------------------------------------------------------------
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _read_roots(template_path: Path) -> dict[str, etree._Element]:
|
|
118
|
+
"""Open the ODF zip and parse the parts we understand.
|
|
119
|
+
|
|
120
|
+
Returns a mapping of part name -> parsed root for every part in
|
|
121
|
+
:data:`_PARTS` that is present AND well-formed. Raises
|
|
122
|
+
:class:`TemplateExtractionError` when the file is missing, is not a zip, or
|
|
123
|
+
yields no parseable ODF part at all.
|
|
124
|
+
"""
|
|
125
|
+
path = Path(template_path)
|
|
126
|
+
if not path.is_file():
|
|
127
|
+
raise TemplateExtractionError(f"找不到範本檔案:{path}")
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
zf = zipfile.ZipFile(path)
|
|
131
|
+
except zipfile.BadZipFile as exc:
|
|
132
|
+
raise TemplateExtractionError(
|
|
133
|
+
f"範本不是有效的 ODF/zip 檔:{path}({exc})"
|
|
134
|
+
) from exc
|
|
135
|
+
|
|
136
|
+
roots: dict[str, etree._Element] = {}
|
|
137
|
+
with zf:
|
|
138
|
+
try:
|
|
139
|
+
infos = inspect_archive(zf)
|
|
140
|
+
except ArchiveLimitError as exc:
|
|
141
|
+
raise TemplateExtractionError(
|
|
142
|
+
f"template exceeds archive safety limits: {path} ({exc})"
|
|
143
|
+
) from exc
|
|
144
|
+
names = {info.filename for info in infos}
|
|
145
|
+
for part in _PARTS:
|
|
146
|
+
if part not in names:
|
|
147
|
+
continue
|
|
148
|
+
try:
|
|
149
|
+
data = read_xml_member(zf, part, max_bytes=MAX_XML_MEMBER)
|
|
150
|
+
except ArchiveLimitError as exc:
|
|
151
|
+
raise TemplateExtractionError(
|
|
152
|
+
f"template exceeds archive safety limits: {path} ({exc})"
|
|
153
|
+
) from exc
|
|
154
|
+
except (KeyError, zipfile.BadZipFile):
|
|
155
|
+
continue
|
|
156
|
+
try:
|
|
157
|
+
# Untrusted input: parse with the hardened parser (no external
|
|
158
|
+
# entity resolution, bounded expansion) — see odforge.xmlsafe.
|
|
159
|
+
roots[part] = safe_fromstring(data)
|
|
160
|
+
except etree.XMLSyntaxError:
|
|
161
|
+
# A malformed part is skipped; if every part is malformed we
|
|
162
|
+
# raise below.
|
|
163
|
+
continue
|
|
164
|
+
|
|
165
|
+
if not roots:
|
|
166
|
+
raise TemplateExtractionError(
|
|
167
|
+
f"範本不含可解析的 ODF 樣式(styles.xml / content.xml):{path}"
|
|
168
|
+
)
|
|
169
|
+
return roots
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _ordered_roots(roots: dict[str, etree._Element]) -> list[etree._Element]:
|
|
173
|
+
"""The parsed roots in priority order (styles.xml before content.xml)."""
|
|
174
|
+
return [roots[p] for p in _PARTS if p in roots]
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
# ---------------------------------------------------------------------------
|
|
178
|
+
# Colour helpers
|
|
179
|
+
# ---------------------------------------------------------------------------
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def _norm_hex(value: Optional[str]) -> Optional[str]:
|
|
183
|
+
"""Normalise a colour to upper-case ``#RRGGBB``, or None if not a 6-hex value.
|
|
184
|
+
|
|
185
|
+
Named colours, ``transparent``, and 3-digit shorthands are rejected (None) —
|
|
186
|
+
the renderer's palette only speaks ``#RRGGBB``.
|
|
187
|
+
"""
|
|
188
|
+
if not value:
|
|
189
|
+
return None
|
|
190
|
+
v = value.strip()
|
|
191
|
+
if not _HEX_RE.match(v):
|
|
192
|
+
return None
|
|
193
|
+
return v.upper()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _is_chromatic(hex_color: str) -> bool:
|
|
197
|
+
"""True when a colour is saturated enough to read as an accent (not a grey).
|
|
198
|
+
|
|
199
|
+
Filters greys, near-white, and near-black by the spread of their RGB
|
|
200
|
+
channels, so the accent candidate is an actual hue rather than the ink or
|
|
201
|
+
paper colour.
|
|
202
|
+
"""
|
|
203
|
+
r = int(hex_color[1:3], 16)
|
|
204
|
+
g = int(hex_color[3:5], 16)
|
|
205
|
+
b = int(hex_color[5:7], 16)
|
|
206
|
+
return (max(r, g, b) - min(r, g, b)) >= _CHROMA_MIN
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _blend(from_hex: str, to_hex: str, amount: float) -> str:
|
|
210
|
+
"""Return ``from_hex`` moved ``amount`` (0..1) of the way toward ``to_hex``.
|
|
211
|
+
|
|
212
|
+
Same channel-wise linear blend the renderer uses for its watermarks; used
|
|
213
|
+
here to derive ``surface`` and ``muted`` from the extracted bg/text.
|
|
214
|
+
"""
|
|
215
|
+
|
|
216
|
+
def _mix(a: int, b: int) -> int:
|
|
217
|
+
return round(a + (b - a) * amount)
|
|
218
|
+
|
|
219
|
+
r = _mix(int(from_hex[1:3], 16), int(to_hex[1:3], 16))
|
|
220
|
+
g = _mix(int(from_hex[3:5], 16), int(to_hex[3:5], 16))
|
|
221
|
+
b = _mix(int(from_hex[5:7], 16), int(to_hex[5:7], 16))
|
|
222
|
+
return f"#{r:02X}{g:02X}{b:02X}"
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _max_contrast_ink(bg: str) -> str:
|
|
226
|
+
"""A guaranteed-legible ink for ``bg`` (clears the 4.5:1 text bar).
|
|
227
|
+
|
|
228
|
+
Prefers a soft near-ink/near-paper tone; if that dips under the bar on a
|
|
229
|
+
mid-tone bg, falls back to pure black or white — for any bg one of the two
|
|
230
|
+
always clears ~4.58:1, so this can never return an illegible colour.
|
|
231
|
+
"""
|
|
232
|
+
soft = "#F5F5F5" if _relative_luminance(bg) < 0.4 else "#141414"
|
|
233
|
+
if contrast_ratio(soft, bg) >= _TEXT_MIN:
|
|
234
|
+
return soft
|
|
235
|
+
return "#FFFFFF" if _relative_luminance(bg) < 0.18 else "#000000"
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
# ---------------------------------------------------------------------------
|
|
239
|
+
# Extraction: background
|
|
240
|
+
# ---------------------------------------------------------------------------
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def _extract_bg(roots: list[etree._Element]) -> Optional[str]:
|
|
244
|
+
"""Extract the page background colour, or None if none can be read.
|
|
245
|
+
|
|
246
|
+
Walks the roots in priority order (styles.xml first, where our own decks put
|
|
247
|
+
the single main drawing-page style ``dp1``). For each ``drawing-page-
|
|
248
|
+
properties`` it reads a solid ``draw:fill-color`` directly, or resolves a
|
|
249
|
+
``draw:fill-gradient-name`` to that gradient's ``draw:start-color`` (this is
|
|
250
|
+
how the dark preset paints its background). Falls back to a page-layout's
|
|
251
|
+
``fo:background-color``. The first valid colour found wins.
|
|
252
|
+
"""
|
|
253
|
+
for root in roots:
|
|
254
|
+
gradients = {
|
|
255
|
+
g.get(_q("draw", "name")): g for g in root.iter(_q("draw", "gradient"))
|
|
256
|
+
}
|
|
257
|
+
for dpp in root.iter(_q("style", "drawing-page-properties")):
|
|
258
|
+
fill = dpp.get(_q("draw", "fill"))
|
|
259
|
+
if fill == "gradient":
|
|
260
|
+
gname = dpp.get(_q("draw", "fill-gradient-name"))
|
|
261
|
+
grad = gradients.get(gname)
|
|
262
|
+
if grad is not None:
|
|
263
|
+
start = _norm_hex(grad.get(_q("draw", "start-color")))
|
|
264
|
+
if start:
|
|
265
|
+
return start
|
|
266
|
+
continue
|
|
267
|
+
# solid (or a bare fill-color with the fill attr omitted)
|
|
268
|
+
color = _norm_hex(dpp.get(_q("draw", "fill-color")))
|
|
269
|
+
if color:
|
|
270
|
+
return color
|
|
271
|
+
# Fallback: a page background set on the page-layout itself.
|
|
272
|
+
for plp in root.iter(_q("style", "page-layout-properties")):
|
|
273
|
+
color = _norm_hex(plp.get(_q("fo", "background-color")))
|
|
274
|
+
if color:
|
|
275
|
+
return color
|
|
276
|
+
return None
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# ---------------------------------------------------------------------------
|
|
280
|
+
# Extraction: colour frequency (text / accent candidates)
|
|
281
|
+
# ---------------------------------------------------------------------------
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _colour_counts(roots: list[etree._Element]) -> Counter:
|
|
285
|
+
"""Count ``fo:color`` occurrences across every style in every root.
|
|
286
|
+
|
|
287
|
+
The frequency of a text colour among style definitions is a cheap proxy for
|
|
288
|
+
how much of the deck wears it — the body/text colour dominates, chart/accent
|
|
289
|
+
tints are rarer. Counts feed both the text pick and the accent pick.
|
|
290
|
+
"""
|
|
291
|
+
counts: Counter = Counter()
|
|
292
|
+
for root in roots:
|
|
293
|
+
for el in root.iter():
|
|
294
|
+
color = _norm_hex(el.get(_q("fo", "color")))
|
|
295
|
+
if color:
|
|
296
|
+
counts[color] += 1
|
|
297
|
+
return counts
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _sorted_by_freq(counts: Counter) -> list[str]:
|
|
301
|
+
"""Colours most-frequent first, ties broken by hex for determinism."""
|
|
302
|
+
return [c for c, _ in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))]
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _pick_text(counts: Counter, bg: str) -> str:
|
|
306
|
+
"""Pick the deck's text colour: the most frequent legible ``fo:color``.
|
|
307
|
+
|
|
308
|
+
Prefers the highest-frequency colour that isn't the bg and clears the 4.5:1
|
|
309
|
+
text bar; falls back to the preset's text (if it happens to clear against
|
|
310
|
+
this bg) and finally to a guaranteed-legible ink.
|
|
311
|
+
"""
|
|
312
|
+
for color in _sorted_by_freq(counts):
|
|
313
|
+
if color != bg and contrast_ratio(color, bg) >= _TEXT_MIN:
|
|
314
|
+
return color
|
|
315
|
+
if contrast_ratio(_PRESET.text, bg) >= _TEXT_MIN:
|
|
316
|
+
return _PRESET.text
|
|
317
|
+
return _max_contrast_ink(bg)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _pick_accent(counts: Counter, bg: str, text: str) -> str:
|
|
321
|
+
"""Pick the accent: the most frequent *chromatic* ``fo:color`` that clears
|
|
322
|
+
the 3:1 accent bar and isn't the bg or the text colour.
|
|
323
|
+
|
|
324
|
+
Falls back to the preset accent (when it clears against this bg), then to the
|
|
325
|
+
text colour (which trivially clears 3:1) so an accent always exists.
|
|
326
|
+
"""
|
|
327
|
+
for color in _sorted_by_freq(counts):
|
|
328
|
+
if color in (bg, text):
|
|
329
|
+
continue
|
|
330
|
+
if _is_chromatic(color) and contrast_ratio(color, bg) >= _ACCENT_MIN:
|
|
331
|
+
return color
|
|
332
|
+
if contrast_ratio(_PRESET.accent, bg) >= _ACCENT_MIN:
|
|
333
|
+
return _PRESET.accent
|
|
334
|
+
return text
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _derive_surface(bg: str, text: str, accent: str) -> str:
|
|
338
|
+
"""Derive ``surface`` as ``bg`` nudged toward ``text`` — panel, still legible.
|
|
339
|
+
|
|
340
|
+
``Palette`` now holds surface to the same bars as bg (text 4.5 / accent 3.0):
|
|
341
|
+
cards paint real text on it. Each blend step toward ``text`` costs contrast,
|
|
342
|
+
so take the largest "hair" that still clears both; at blend 0 surface == bg,
|
|
343
|
+
whose bars the pre-filtered text/accent already clear, so this always returns.
|
|
344
|
+
"""
|
|
345
|
+
for amount in (0.08, 0.06, 0.04, 0.02, 0.0):
|
|
346
|
+
candidate = _blend(bg, text, amount)
|
|
347
|
+
if (
|
|
348
|
+
contrast_ratio(text, candidate) >= _TEXT_MIN
|
|
349
|
+
and contrast_ratio(accent, candidate) >= _ACCENT_MIN
|
|
350
|
+
):
|
|
351
|
+
return candidate
|
|
352
|
+
return bg # unreachable (amount=0.0 == bg), kept for total-function clarity
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _derive_muted(text: str, bg: str, surface: str) -> str:
|
|
356
|
+
"""Derive ``muted`` as ``text`` blended toward ``bg`` — the mutest legible tone.
|
|
357
|
+
|
|
358
|
+
Tries progressively smaller blends toward the bg and returns the *most*
|
|
359
|
+
muted one (largest blend) that clears the 3:1 muted bar on **both** backdrops
|
|
360
|
+
it is drawn over — the page and the card surface (the binding one, since
|
|
361
|
+
surface sits between bg and text). At blend 0 the colour is ``text`` itself,
|
|
362
|
+
which clears both by construction, so this always returns.
|
|
363
|
+
"""
|
|
364
|
+
for amount in (0.5, 0.45, 0.4, 0.35, 0.3, 0.25, 0.2, 0.1, 0.0):
|
|
365
|
+
candidate = _blend(text, bg, amount)
|
|
366
|
+
if (
|
|
367
|
+
contrast_ratio(candidate, bg) >= _MUTED_MIN
|
|
368
|
+
and contrast_ratio(candidate, surface) >= _MUTED_MIN
|
|
369
|
+
):
|
|
370
|
+
return candidate
|
|
371
|
+
return text # unreachable (amount=0.0 == text), kept for total-function clarity
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _build_palette(roots: list[etree._Element]) -> Palette:
|
|
375
|
+
"""Assemble a validated :class:`~odforge.ir.Palette` from the parsed roots.
|
|
376
|
+
|
|
377
|
+
Extracts bg (preset-backfilled), picks text/accent from ``fo:color``
|
|
378
|
+
frequency, derives surface/muted to guarantee contrast, then constructs the
|
|
379
|
+
Palette. The construction is wrapped: on the off chance the derived tuple
|
|
380
|
+
still fails pydantic's validators, the whole palette falls back to the preset
|
|
381
|
+
(which is valid by construction) — so this never raises.
|
|
382
|
+
"""
|
|
383
|
+
bg = _extract_bg(roots) or _PRESET.bg
|
|
384
|
+
counts = _colour_counts(roots)
|
|
385
|
+
text = _pick_text(counts, bg)
|
|
386
|
+
accent = _pick_accent(counts, bg, text)
|
|
387
|
+
surface = _derive_surface(bg, text, accent)
|
|
388
|
+
muted = _derive_muted(text, bg, surface)
|
|
389
|
+
try:
|
|
390
|
+
return Palette(bg=bg, surface=surface, text=text, muted=muted, accent=accent)
|
|
391
|
+
except ValueError:
|
|
392
|
+
return Palette(
|
|
393
|
+
bg=_PRESET.bg,
|
|
394
|
+
surface=_PRESET.surface,
|
|
395
|
+
text=_PRESET.text,
|
|
396
|
+
muted=_PRESET.muted,
|
|
397
|
+
accent=_PRESET.accent,
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
# ---------------------------------------------------------------------------
|
|
402
|
+
# Extraction: fonts
|
|
403
|
+
# ---------------------------------------------------------------------------
|
|
404
|
+
|
|
405
|
+
|
|
406
|
+
def _map_font(name: Optional[str]) -> Optional[str]:
|
|
407
|
+
"""Map a declared font name onto a whitelist entry, or None if unknown.
|
|
408
|
+
|
|
409
|
+
Exact match against :data:`~odforge.ir.FONT_WHITELIST` after trimming quotes
|
|
410
|
+
and whitespace — we only reuse fonts we know ship with CJK coverage.
|
|
411
|
+
"""
|
|
412
|
+
if not name:
|
|
413
|
+
return None
|
|
414
|
+
cleaned = name.strip().strip("'\"").strip()
|
|
415
|
+
return cleaned if cleaned in FONT_WHITELIST else None
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def _split_family(family: Optional[str]) -> list[str]:
|
|
419
|
+
"""Split an ``svg:font-family`` CSS-style list into individual names."""
|
|
420
|
+
if not family:
|
|
421
|
+
return []
|
|
422
|
+
return list(family.split(","))
|
|
423
|
+
|
|
424
|
+
|
|
425
|
+
def _extract_fonts(roots: list[etree._Element]) -> FontPair:
|
|
426
|
+
"""Derive a :class:`~odforge.ir.FontPair` from the template's font declarations.
|
|
427
|
+
|
|
428
|
+
Primary signal is each ``<style:font-face>``'s ``style:name`` (in document
|
|
429
|
+
order); the ``svg:font-family`` fallback chain is consulted only when no
|
|
430
|
+
``style:name`` maps to the whitelist. With one whitelisted font the pairing
|
|
431
|
+
uses it for both display and body (our decks' "one product, one typeface"
|
|
432
|
+
reality); with two or more, the first is the display face and the second the
|
|
433
|
+
body face. When nothing whitelist-legal is declared, both faces fall back to
|
|
434
|
+
the preset pairing.
|
|
435
|
+
"""
|
|
436
|
+
named: list[str] = []
|
|
437
|
+
family: list[str] = []
|
|
438
|
+
for root in roots:
|
|
439
|
+
for ff in root.iter(_q("style", "font-face")):
|
|
440
|
+
mapped = _map_font(ff.get(_q("style", "name")))
|
|
441
|
+
if mapped and mapped not in named:
|
|
442
|
+
named.append(mapped)
|
|
443
|
+
for token in _split_family(ff.get(_q("svg", "font-family"))):
|
|
444
|
+
fam = _map_font(token)
|
|
445
|
+
if fam and fam not in family:
|
|
446
|
+
family.append(fam)
|
|
447
|
+
|
|
448
|
+
fonts = named or family
|
|
449
|
+
if not fonts:
|
|
450
|
+
return FontPair(display=_PRESET.font_display, body=_PRESET.font_body)
|
|
451
|
+
if len(fonts) == 1:
|
|
452
|
+
return FontPair(display=fonts[0], body=fonts[0])
|
|
453
|
+
return FontPair(display=fonts[0], body=fonts[1])
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
# ---------------------------------------------------------------------------
|
|
457
|
+
# Public entry point
|
|
458
|
+
# ---------------------------------------------------------------------------
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
def extract_design(template_path: Path) -> DesignSpec:
|
|
462
|
+
"""Derive a :class:`~odforge.ir.DesignSpec` from an existing ODF template.
|
|
463
|
+
|
|
464
|
+
Opens ``template_path`` (``.otp``/``.odp``/``.ott``/``.odt``), reads
|
|
465
|
+
``styles.xml`` and ``content.xml``, and samples the template's background,
|
|
466
|
+
text/accent colours and font declarations into a validated ``DesignSpec``.
|
|
467
|
+
Fields that can't be sampled confidently — or that fail the WCAG contrast
|
|
468
|
+
bars — are backfilled from the academic preset, so the return value is ALWAYS
|
|
469
|
+
a valid ``DesignSpec`` for a readable template.
|
|
470
|
+
|
|
471
|
+
Raises :class:`TemplateExtractionError` only when the file is missing, is not
|
|
472
|
+
a zip, or contains no parseable ODF part.
|
|
473
|
+
"""
|
|
474
|
+
roots_map = _read_roots(template_path)
|
|
475
|
+
roots = _ordered_roots(roots_map)
|
|
476
|
+
palette = _build_palette(roots)
|
|
477
|
+
fonts = _extract_fonts(roots)
|
|
478
|
+
return DesignSpec(palette=palette, fonts=fonts, scale="standard", mode="presenter")
|
odforge/feedback.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""``wait_for_feedback``: let an agent sit in the editor's loop instead of the chat.
|
|
2
|
+
|
|
3
|
+
The person works in the browser — pins comments, presses「交給 AI 修改」— and the
|
|
4
|
+
agent, which started the editor for them, waits here until that happens. The
|
|
5
|
+
handoff goes through the file itself: submitted comments are annotations marked
|
|
6
|
+
``odforge:state="submitted"``, and pressing「完成」marks the presentation
|
|
7
|
+
``odforge:session="done"``. No server has to know the agent exists.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import asyncio
|
|
13
|
+
import time
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import List, Optional, Tuple
|
|
16
|
+
|
|
17
|
+
from .odpedit import Document
|
|
18
|
+
from .scene import scene_of
|
|
19
|
+
|
|
20
|
+
POLL_SECONDS = 1.0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _stamp(path: Path) -> Optional[Tuple[int, int]]:
|
|
24
|
+
try:
|
|
25
|
+
stat = path.stat()
|
|
26
|
+
except OSError:
|
|
27
|
+
return None
|
|
28
|
+
return stat.st_mtime_ns, stat.st_size
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _text_of(element: dict) -> str:
|
|
32
|
+
text = element.get("text")
|
|
33
|
+
if not text:
|
|
34
|
+
return ""
|
|
35
|
+
joined = " / ".join("".join(r["text"] for r in p["runs"]) for p in text["paragraphs"])
|
|
36
|
+
return joined if len(joined) <= 80 else joined[:80] + "…"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def pending(path: Path) -> Tuple[List[str], bool]:
|
|
40
|
+
"""Lines describing submitted comments, and whether the person ended the session."""
|
|
41
|
+
scene = scene_of(path)
|
|
42
|
+
lines: List[str] = []
|
|
43
|
+
for index, page in enumerate(scene["pages"]):
|
|
44
|
+
by_id = {e["id"]: e for e in page["elements"]}
|
|
45
|
+
for comment in page.get("comments", []):
|
|
46
|
+
if comment.get("state") != "submitted":
|
|
47
|
+
continue
|
|
48
|
+
target = comment.get("target")
|
|
49
|
+
if target and target in by_id:
|
|
50
|
+
about = f"關於 [{target}] {by_id[target]['kind']}「{_text_of(by_id[target])}」"
|
|
51
|
+
else:
|
|
52
|
+
about = "整頁"
|
|
53
|
+
lines.append(f"- [{comment['id']}] 第 {index + 1} 頁,{about}:{comment['text']}")
|
|
54
|
+
done = Document(path).state().get("session") == "done"
|
|
55
|
+
return lines, done
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
async def wait_for_feedback(path: Path, timeout_seconds: float) -> str:
|
|
59
|
+
deadline = time.monotonic() + max(1.0, timeout_seconds)
|
|
60
|
+
last = None
|
|
61
|
+
while True:
|
|
62
|
+
stamp = _stamp(path)
|
|
63
|
+
if stamp is None:
|
|
64
|
+
return f"error: file not found: {path}"
|
|
65
|
+
if stamp != last:
|
|
66
|
+
last = stamp
|
|
67
|
+
lines, done = pending(path)
|
|
68
|
+
if lines:
|
|
69
|
+
return (
|
|
70
|
+
f"feedback: 使用者在網頁上送出 {len(lines)} 則留言:\n"
|
|
71
|
+
+ "\n".join(lines)
|
|
72
|
+
+ "\n\n請用 edit_odp 逐則修改,並在同一次呼叫裡用 comment_delete "
|
|
73
|
+
"刪掉處理完的留言(同一頁由大到小刪);需要更多版面資訊時先 outline_odp。"
|
|
74
|
+
"改完後再呼叫 wait_for_feedback 繼續等使用者的下一批。"
|
|
75
|
+
)
|
|
76
|
+
if done:
|
|
77
|
+
Document(path).apply([{"op": "session", "state": "open"}])
|
|
78
|
+
return (
|
|
79
|
+
"done: 使用者在網頁上按了「完成」,這輪協作結束。向使用者簡短回報做了哪些修改。"
|
|
80
|
+
)
|
|
81
|
+
if time.monotonic() >= deadline:
|
|
82
|
+
return (
|
|
83
|
+
"waiting: 目前還沒有新的回饋。使用者可能還在網頁上留言;"
|
|
84
|
+
"直接再呼叫一次 wait_for_feedback 繼續等。"
|
|
85
|
+
)
|
|
86
|
+
await asyncio.sleep(POLL_SECONDS)
|