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.
Files changed (66) hide show
  1. odforge/__init__.py +1 -0
  2. odforge/benchmark.py +287 -0
  3. odforge/check.py +416 -0
  4. odforge/cli.py +1027 -0
  5. odforge/components.py +270 -0
  6. odforge/critic.py +1260 -0
  7. odforge/docfonts.py +104 -0
  8. odforge/editor_api.py +33 -0
  9. odforge/editor_launch.py +134 -0
  10. odforge/editor_routes.py +131 -0
  11. odforge/extract.py +478 -0
  12. odforge/feedback.py +86 -0
  13. odforge/fontembed.py +166 -0
  14. odforge/ir.py +1181 -0
  15. odforge/layoutcheck.py +602 -0
  16. odforge/llm.py +1865 -0
  17. odforge/localguard.py +42 -0
  18. odforge/mcp_server.py +552 -0
  19. odforge/media.py +352 -0
  20. odforge/odpedit.py +1219 -0
  21. odforge/package.py +114 -0
  22. odforge/pagefacts.py +388 -0
  23. odforge/preview.py +104 -0
  24. odforge/references.py +153 -0
  25. odforge/render/__init__.py +40 -0
  26. odforge/render/odp.py +5687 -0
  27. odforge/render/ods.py +155 -0
  28. odforge/render/odt.py +223 -0
  29. odforge/scene.py +657 -0
  30. odforge/setup_agents.py +274 -0
  31. odforge/skills/odforge-design/SKILL.md +298 -0
  32. odforge/skills/odforge-design/themes/academic.md +52 -0
  33. odforge/skills/odforge-design/themes/clay.md +53 -0
  34. odforge/skills/odforge-design/themes/color-system.md +59 -0
  35. odforge/skills/odforge-design/themes/crimson.md +53 -0
  36. odforge/skills/odforge-design/themes/dark.md +53 -0
  37. odforge/skills/odforge-design/themes/forest.md +54 -0
  38. odforge/skills/odforge-design/themes/gold.md +53 -0
  39. odforge/skills/odforge-design/themes/minimal.md +53 -0
  40. odforge/skills/odforge-design/themes/navy.md +56 -0
  41. odforge/skills/odforge-design/themes/plum.md +53 -0
  42. odforge/skills/odforge-design/themes/sky.md +53 -0
  43. odforge/skills/odforge-design/themes/slate.md +53 -0
  44. odforge/skills/odforge-design/themes/teal.md +53 -0
  45. odforge/skills/odforge-design/themes/violet.md +56 -0
  46. odforge/templates.py +250 -0
  47. odforge/textmetrics.py +616 -0
  48. odforge/textutil.py +24 -0
  49. odforge/themes.py +886 -0
  50. odforge/validate.py +403 -0
  51. odforge/watch.py +266 -0
  52. odforge/webapi.py +2617 -0
  53. odforge/webui/assets/editor-CjpYXM1a.css +1 -0
  54. odforge/webui/assets/editor-DPToJGio.js +3 -0
  55. odforge/webui/assets/jsx-runtime-C7KMcVI_.js +8 -0
  56. odforge/webui/assets/main-BLOs7Hnk.js +7 -0
  57. odforge/webui/assets/main-D21yFVE6.css +1 -0
  58. odforge/webui/editor.html +14 -0
  59. odforge/webui/index.html +25 -0
  60. odforge/xmlsafe.py +46 -0
  61. odforge/zipguard.py +91 -0
  62. odforge-0.3.0.dist-info/METADATA +95 -0
  63. odforge-0.3.0.dist-info/RECORD +66 -0
  64. odforge-0.3.0.dist-info/WHEEL +4 -0
  65. odforge-0.3.0.dist-info/entry_points.txt +3 -0
  66. odforge-0.3.0.dist-info/licenses/LICENSE +21 -0
odforge/textmetrics.py ADDED
@@ -0,0 +1,616 @@
1
+ """Programmatic layout-budget gate — does a slide's text fit its frames?
2
+
3
+ This is a *deterministic* pre-render overflow check: the thing open-slide asks
4
+ its prompt to police, ODForge enforces in code. It is pure (no I/O, no rendering)
5
+ and depends only on the layout geometry (:data:`odforge.themes.LAYOUTS`) and the
6
+ resolved design tokens (:class:`odforge.themes.Theme`).
7
+
8
+ Two public functions:
9
+
10
+ * :func:`estimate_height_cm` — a monospace-ish text-height model. Each glyph is
11
+ charged an em-width (CJK ≈ 1.0em, Latin per its measured advance in
12
+ :data:`_ASCII_WIDTHS`, anything else 0.6em); the run wraps at the frame width
13
+ and each wrapped line is one ``size_pt * PT_TO_CM * line_height``
14
+ tall. Newlines split the text into independent paragraphs.
15
+ * :func:`check_budget` — walks a slide's frames, accumulates each frame's content
16
+ height (paragraph heights + inter-item margins for bullet lists), and returns a
17
+ human-readable message for every frame whose content overruns its box. An empty
18
+ list means the slide fits.
19
+
20
+ **Mirroring the renderer.** The estimator only works if it charges each frame the
21
+ same font size the renderer draws it at. :func:`_frame_content_height` therefore
22
+ follows ``render.odp._page_xml`` branch-for-branch: legacy roles render at their
23
+ ``Frame.size_pt`` while the Task-14.1 roles are re-sized from theme tokens
24
+ (quote → ``h1_pt``, attribution → ``caption_pt``, message → ``h1_pt``,
25
+ items → ``body_pt``, insights → ``caption_pt``, fact → ``display_pt``). Bullet
26
+ lists carry the renderer's 145% line-height and 0.35cm inter-item margin; nested
27
+ (level-2) children render ~1cm narrower. Chart bars auto-fit, so ``chart-area``
28
+ is never estimated — but a chart page's ``insights`` bullets are.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import math
34
+ import re
35
+
36
+ from odforge.ir import BulletItem, Slide
37
+ from odforge.themes import (
38
+ LIST_ROLES,
39
+ PLAIN_LAYOUTS,
40
+ TAKEAWAY_Y,
41
+ Frame,
42
+ Theme,
43
+ slide_frames,
44
+ )
45
+
46
+ # ── constants ──────────────────────────────────────────────────────────────
47
+ # Points → centimetres (1pt = 1/72in, 1in = 2.54cm ⇒ 0.035277…; rounded).
48
+ PT_TO_CM = 0.03528
49
+
50
+ # Per-glyph advance widths, in em (fraction of the point size). A CJK ideograph
51
+ # is ~square; Latin is measured per glyph (_ASCII_WIDTHS), anything else ~0.6em.
52
+ _CJK_EM = 1.0
53
+ _ASCII_EM = 0.6
54
+
55
+ # The renderer's loose-bullet typography (render/odp.py): list paragraphs get a
56
+ # 145% line-height and a 0.35cm bottom margin, and level-2 children indent deeper
57
+ # (≈1cm less usable text width than a level-1 item).
58
+ _LINE_HEIGHT = 1.45
59
+ _MARGIN_BOTTOM_CM = 0.35
60
+ _LEVEL2_NARROW_CM = 1.0
61
+
62
+ # Vertical breathing room a text-box eats top+bottom before content can overflow.
63
+ # Small on purpose: the gate should fire on real overruns, not hairline ones.
64
+ _FRAME_PADDING_CM = 0.2
65
+
66
+ # Lowest y (cm) a big-fact caption may extend to before it collides with the
67
+ # master-page footer furniture (render.odp._FOOTER_LINE_Y == 14.72). Duplicated
68
+ # here rather than imported: render.odp imports textmetrics, never the reverse,
69
+ # so this module must stay free of a render dependency.
70
+ _BIGFACT_USABLE_BOTTOM_CM = 14.72
71
+
72
+ # PLAIN_LAYOUTS (bare title frames) and LIST_ROLES (semantic bullet lists) are
73
+ # imported from odforge.themes — the single source shared with render.odp so the
74
+ # budget gate can never drift from what the renderer actually draws.
75
+
76
+ # CJK / full-width Unicode blocks charged a full em. Kept deliberately small and
77
+ # documented rather than exhaustive (the brief's "keep it simple"):
78
+ # 3000–303F CJK symbols & punctuation
79
+ # 3040–30FF Hiragana + Katakana
80
+ # 3400–4DBF CJK Unified Ideographs Extension A
81
+ # 4E00–9FFF CJK Unified Ideographs
82
+ # FF00–FF60 Full-width ASCII variants + full-width punctuation
83
+ # FFE0–FFE6 Full-width signs
84
+ # Anything else (Latin, digits, half-width punctuation) is charged ASCII width.
85
+ _CJK_RANGES: tuple[tuple[int, int], ...] = (
86
+ (0x3000, 0x303F),
87
+ (0x3040, 0x30FF),
88
+ (0x3400, 0x4DBF),
89
+ (0x4E00, 0x9FFF),
90
+ (0xFF00, 0xFF60),
91
+ (0xFFE0, 0xFFE6),
92
+ # Drawn full-width by CJK fonts: circled numbers, geometric shapes (the
93
+ # "○" in 陳○○ masking), radicals, bopomofo, enclosed/compat ideographs,
94
+ # and the supplementary ideograph planes. Counting them as 0.55em made a
95
+ # table row one line short and its text printed into the next row.
96
+ (0x0370, 0x03FF), # Greek (κ, α…) — full-width in the CJK face
97
+ (0x2190, 0x21FF),
98
+ (0x2200, 0x22FF),
99
+ (0x2460, 0x24FF),
100
+ (0x25A0, 0x25FF),
101
+ (0x2E80, 0x2FDF),
102
+ (0x3100, 0x312F),
103
+ (0x3200, 0x33FF),
104
+ (0xF900, 0xFAFF),
105
+ (0x20000, 0x3134F),
106
+ )
107
+
108
+
109
+ def _is_cjk(ch: str) -> bool:
110
+ """True when ``ch`` is a full-width (CJK / kana / full-width form) glyph."""
111
+ cp = ord(ch)
112
+ return any(lo <= cp <= hi for lo, hi in _CJK_RANGES)
113
+
114
+
115
+ # Printable ASCII advance widths (em), the wider of Noto Sans / Serif TC
116
+ # regular and bold, read off the font files. A flat 0.55em undercharged Latin
117
+ # by ~9% on average and by nearly half for 「m」「W」: at display sizes a
118
+ # 「520→160ms」 sized to one line wrapped, and its 「s」 printed on the label.
119
+ _ASCII_WIDTHS: dict[str, float] = {
120
+ ch: w
121
+ for chars, w in (
122
+ (' ', 0.26),
123
+ ("'", 0.33),
124
+ (',.:;j|', 0.34),
125
+ ('il', 0.35),
126
+ ('!-', 0.37),
127
+ ('[]{}', 0.38),
128
+ ('()/\\f', 0.4),
129
+ ('t', 0.42),
130
+ ('I', 0.43),
131
+ ('rs', 0.5),
132
+ ('*?', 0.51),
133
+ ('z', 0.52),
134
+ ('c', 0.56),
135
+ ('"J', 0.57),
136
+ ('evy', 0.58),
137
+ ('$012345678_a', 0.59),
138
+ ('+9<=>^gx~', 0.6),
139
+ ('#', 0.61),
140
+ ('S', 0.62),
141
+ ('Z`o', 0.63),
142
+ ('Lq', 0.64),
143
+ ('Fk', 0.65),
144
+ ('d', 0.66),
145
+ ('EPbp', 0.67),
146
+ ('u', 0.68),
147
+ ('Thn', 0.69),
148
+ ('CY', 0.7),
149
+ ('B', 0.71),
150
+ ('VX', 0.73),
151
+ ('AR', 0.75),
152
+ ('G', 0.76),
153
+ ('K', 0.77),
154
+ ('DOQ', 0.79),
155
+ ('&', 0.8),
156
+ ('N', 0.81),
157
+ ('U', 0.82),
158
+ ('H', 0.86),
159
+ ('w', 0.87),
160
+ ('%', 0.97),
161
+ ('M', 1.0),
162
+ ('@m', 1.01),
163
+ ('W', 1.09),
164
+ )
165
+ for ch in chars
166
+ }
167
+
168
+
169
+ def _em_width(text: str) -> float:
170
+ """Total advance width of ``text`` in em (CJK 1.0, measured Latin, else
171
+ 0.6)."""
172
+ return sum(
173
+ _CJK_EM if _is_cjk(ch) else _ASCII_WIDTHS.get(ch, _ASCII_EM) for ch in text
174
+ )
175
+
176
+
177
+ def text_width_cm(text: str, size_pt: int) -> float:
178
+ """Width (cm) ``text`` needs on a single line at ``size_pt``.
179
+
180
+ The companion to :func:`estimate_height_cm`, under the same em-width model
181
+ (CJK ≈ 1.0em, Latin measured per glyph). Used where a box must be sized *to* its text
182
+ rather than the text wrapped into a fixed box — a diagram's edge-label chip,
183
+ for instance, which at a fixed width covered the whole connector it sat on.
184
+ """
185
+ return _em_width(text) * size_pt * PT_TO_CM
186
+
187
+
188
+ _LINE_END_WASTE_EM = 0.9
189
+
190
+
191
+ def estimate_height_cm(
192
+ text: str, size_pt: int, width_cm: float, line_height: float = _LINE_HEIGHT
193
+ ) -> float:
194
+ """Estimate the rendered height (cm) of ``text`` in a ``width_cm``-wide box.
195
+
196
+ Model: each glyph advances an em-width (CJK ≈ 1.0em, Latin measured per glyph); a
197
+ paragraph's em-run is ``size_pt * PT_TO_CM`` cm/em wide and wraps at
198
+ ``width_cm``; every wrapped line is ``size_pt * PT_TO_CM * line_height`` tall
199
+ (minimum one line, even for empty text). ``\\n`` splits the text into
200
+ independent paragraphs whose heights sum.
201
+ """
202
+ width = width_cm if width_cm > 0 else 0.01 # guard degenerate widths
203
+ line_cm = size_pt * PT_TO_CM * line_height
204
+ total = 0.0
205
+ em_cm = size_pt * PT_TO_CM
206
+ for paragraph in text.split("\n"):
207
+ run_cm = _em_width(paragraph) * em_cm
208
+ lines = max(1, math.ceil(run_cm / width))
209
+ if lines > 1:
210
+ # A wrapped line rarely ends flush: the next glyph does not fit,
211
+ # or kinsoku keeps 「,」 off a line start, or a Latin word moves
212
+ # down whole. Charge each line ~half an em of that waste — in a
213
+ # 5cm card column it is the difference between the two-line
214
+ # estimate and the three lines LibreOffice actually sets.
215
+ usable = max(width - _LINE_END_WASTE_EM * em_cm, em_cm)
216
+ lines = max(1, math.ceil(run_cm / usable))
217
+ total += lines * line_cm
218
+ return total
219
+
220
+
221
+ def fact_font_size_pt(
222
+ text: str, width_cm: float, display_pt: int, h1_pt: int
223
+ ) -> int:
224
+ """Largest big-fact font size (pt) that keeps ``text`` on a single line.
225
+
226
+ Steps down 1pt at a time from ``display_pt`` and returns the first size at
227
+ which ``text`` fits one line in a ``width_cm``-wide box under the same
228
+ em-width model :func:`estimate_height_cm` uses (CJK ≈ 1.0em, Latin measured per glyph).
229
+ ``h1_pt`` is a hard floor: if even at ``h1_pt`` the text still wraps, ``h1_pt``
230
+ is returned (the renderer then drops the caption to keep the two from
231
+ overlapping, and — in the unrescuable extreme — :func:`check_budget` reports).
232
+
233
+ Shared by the renderer (the size it draws) and the budget gate (the size it
234
+ charges) so the two can never disagree. Deterministic; a pure function of the
235
+ text, width and the two size bounds.
236
+ """
237
+ width = width_cm if width_cm > 0 else 0.01
238
+ em = _em_width(text)
239
+ if em <= 0:
240
+ return display_pt
241
+ for size in range(display_pt, h1_pt, -1):
242
+ if em * size * PT_TO_CM <= width:
243
+ return size
244
+ return h1_pt
245
+
246
+
247
+ def heading_pt(text: str, frame_w: float, size_pt: int) -> int:
248
+ """The size a heading is drawn at: its frame size, unless a step of up to
249
+ ~18% down keeps it on one line.
250
+
251
+ A title one or two characters too long for its line wrapped and left a
252
+ lone character on line two — the most visible tell of an unedited deck.
253
+ When one line is out of reach even at the floor, the full size stands
254
+ (two honest lines beat one cramped one). ``frame_w`` is the frame width;
255
+ the 0.5cm is LibreOffice's text-box inset, as in the renderer.
256
+ """
257
+ floor = max(12, round(size_pt * 0.82))
258
+ width = frame_w - 0.5
259
+ em = _em_width(text)
260
+ for size in range(size_pt, floor - 1, -1):
261
+ if em * size * PT_TO_CM <= width:
262
+ return size
263
+ return size_pt
264
+
265
+
266
+ # ── frame content resolution (mirrors render.odp) ──────────────────────────
267
+
268
+
269
+ def _item_text_children(item) -> tuple[str, list]:
270
+ """Return ``(text, children)`` for a bullet item (``str`` or ``BulletItem``)."""
271
+ if isinstance(item, BulletItem):
272
+ return item.text, list(item.children)
273
+ return str(item), []
274
+
275
+
276
+ def _role_lines(slide: Slide, role: str) -> list:
277
+ """The content items a frame's ``role`` contributes — mirrors
278
+ ``render.odp._role_lines`` (an empty list means the frame is skipped)."""
279
+ if role == "title":
280
+ return [slide.title] if slide.title else []
281
+ if role in ("subtitle", "lede"):
282
+ return [slide.subtitle] if slide.subtitle else []
283
+ if role == "takeaway":
284
+ return [slide.takeaway] if slide.takeaway else []
285
+ if role == "fact":
286
+ return [slide.fact] if slide.fact else []
287
+ if role == "quote":
288
+ return [slide.quote] if slide.quote else []
289
+ if role == "attribution":
290
+ return [slide.attribution] if slide.attribution else []
291
+ if role == "message":
292
+ return [slide.title] if slide.title else []
293
+ if role in ("bullets", "items", "insights"):
294
+ return list(slide.bullets)
295
+ if role == "left":
296
+ return list(slide.left)
297
+ if role == "right":
298
+ return list(slide.right)
299
+ return []
300
+
301
+
302
+ def _list_height(items: list, size_pt: int, width_cm: float) -> float:
303
+ """Accumulated height of a bullet list: each item's paragraph height plus a
304
+ ``_MARGIN_BOTTOM_CM`` inter-item gap; nested children render ~1cm narrower.
305
+ """
306
+ total = 0.0
307
+ for item in items:
308
+ text, children = _item_text_children(item)
309
+ total += estimate_height_cm(text, size_pt, width_cm) + _MARGIN_BOTTOM_CM
310
+ for child in children:
311
+ child_text, _ = _item_text_children(child)
312
+ total += (
313
+ estimate_height_cm(child_text, size_pt, width_cm - _LEVEL2_NARROW_CM)
314
+ + _MARGIN_BOTTOM_CM
315
+ )
316
+ return total
317
+
318
+
319
+ def _plain_height(lines: list, size_pt: int, width_cm: float) -> float:
320
+ """Accumulated height of bare (non-list) paragraphs — one per line, no gap."""
321
+ total = 0.0
322
+ for line in lines:
323
+ text, _ = _item_text_children(line)
324
+ total += estimate_height_cm(text, size_pt, width_cm)
325
+ return total
326
+
327
+
328
+ def _frame_content_height(
329
+ slide: Slide, theme: Theme, frame: Frame, layout: str
330
+ ) -> float | None:
331
+ """Estimated content height (cm) for one frame, or ``None`` when the frame
332
+ draws nothing (empty content) or auto-fitting shapes (``chart-area``).
333
+
334
+ Branch order mirrors ``render.odp._page_xml`` exactly so the size charged to
335
+ each role matches what the renderer actually draws.
336
+ """
337
+ role = frame.role
338
+
339
+ # Shape-rendered areas fit their content inside the assigned box.
340
+ if role in {"chart-area", "closing-actions", "table-area"}:
341
+ return None
342
+
343
+ lines = _role_lines(slide, role)
344
+ if not lines:
345
+ return None
346
+
347
+ # lede: the renderer steps it down (heading_pt) to keep it on one line;
348
+ # charging the full size reported a lede that drew on one line as 1.6cm.
349
+ if role == "lede":
350
+ size = heading_pt(slide.subtitle, frame.w, frame.size_pt)
351
+ if text_width_cm(slide.subtitle, size) <= frame.w - 0.5:
352
+ return estimate_height_cm("一", size, frame.w)
353
+ return estimate_height_cm(slide.subtitle, size, frame.w)
354
+
355
+ # closing message: title at h1_pt (+ optional subtitle at body_pt), plain.
356
+ if role == "message":
357
+ h = estimate_height_cm(slide.title, theme.h1_pt, frame.w)
358
+ if slide.subtitle:
359
+ h += estimate_height_cm(slide.subtitle, theme.body_pt, frame.w)
360
+ return h
361
+
362
+ # agenda: numbered items at body_pt with loose-bullet spacing. The renderer
363
+ # (_numbered_items_xml) draws only each item's top-level text via _line_text
364
+ # — BulletItem children are silently dropped — so children are NOT charged.
365
+ if role == "items":
366
+ total = 0.0
367
+ for item in lines:
368
+ text, _ = _item_text_children(item)
369
+ total += (
370
+ estimate_height_cm(text, theme.body_pt, frame.w) + _MARGIN_BOTTOM_CM
371
+ )
372
+ return total
373
+
374
+ # chart insights: a caption-size bullet list.
375
+ if role == "insights":
376
+ return _list_height(lines, theme.caption_pt, frame.w)
377
+
378
+ # comparison columns: bold header (body_pt, plain) + the rest as a body_pt list.
379
+ if layout == "comparison" and role in ("left", "right"):
380
+ header_text, _ = _item_text_children(lines[0])
381
+ h = estimate_height_cm(header_text, theme.body_pt, frame.w)
382
+ rest = lines[1:]
383
+ if rest:
384
+ h += _list_height(rest, theme.body_pt, frame.w)
385
+ return h
386
+
387
+ # content-page title: optional kicker eyebrow (caption_pt) + title (size_pt).
388
+ if role == "title":
389
+ h = 0.0
390
+ if slide.kicker and layout not in PLAIN_LAYOUTS:
391
+ h += estimate_height_cm(slide.kicker, theme.caption_pt, frame.w)
392
+ for line in lines:
393
+ text, _ = _item_text_children(line)
394
+ h += estimate_height_cm(
395
+ text, heading_pt(text, frame.w, frame.size_pt), frame.w
396
+ )
397
+ return h
398
+
399
+ # standard semantic list (title-content bullets, two-col columns).
400
+ if role in LIST_ROLES and not frame.center:
401
+ return _list_height(lines, frame.size_pt, frame.w)
402
+
403
+ # bare centred / single-line text (subtitle, fact, quote, attribution,
404
+ # big-fact caption bullets). Size follows the renderer's per-role re-sizing.
405
+ size_pt = frame.size_pt
406
+ if role == "fact":
407
+ size_pt = theme.display_pt
408
+ elif role == "quote":
409
+ size_pt = theme.h1_pt
410
+ elif role == "attribution":
411
+ size_pt = theme.caption_pt
412
+ return _plain_height(lines, size_pt, frame.w)
413
+
414
+
415
+ def frame_content_height(
416
+ slide: Slide, theme: Theme, frame: Frame, layout: str
417
+ ) -> float | None:
418
+ """Public name for :func:`_frame_content_height` — the renderer sizes the
419
+ two-column cards to exactly the height this gate charges."""
420
+ return _frame_content_height(slide, theme, frame, layout)
421
+
422
+
423
+ def _check_big_fact(slide: Slide, theme: Theme, label: str, style=None) -> list[str]:
424
+ """Budget check for the big-fact layout — closes the fact-frame blind spot.
425
+
426
+ The renderer auto-rescues an over-long fact: it shrinks the fact toward the
427
+ ``h1_pt`` floor to keep it on one line and drops the caption below the fact's
428
+ real height so the two never overlap (see ``render.odp._page_xml``). A fact
429
+ that merely wraps is therefore handled in-engine and must NOT be reported.
430
+
431
+ Feedback is warranted only in the unrescuable extreme: when the fact, even
432
+ charged at its ``h1_pt`` floor, plus the caption reserved beneath it, cannot
433
+ fit above the footer line (:data:`_BIGFACT_USABLE_BOTTOM_CM`). Only then does
434
+ the message reach the Task 15.2 retry loop — self-rescue first, feedback last.
435
+ """
436
+ by_role = {f.role: f for f in slide_frames(slide, style)}
437
+ fact_frame, caption_frame = by_role["fact"], by_role["bullets"]
438
+ if not slide.fact:
439
+ return []
440
+ # Charge the fact at the shrink floor — the smallest the renderer will draw it.
441
+ floor_h = estimate_height_cm(slide.fact, theme.h1_pt, fact_frame.w)
442
+ gap = caption_frame.y - (fact_frame.y + fact_frame.h)
443
+ caption_lines = _role_lines(slide, caption_frame.role)
444
+ caption_h = (
445
+ _plain_height(caption_lines, caption_frame.size_pt, caption_frame.w)
446
+ if caption_lines
447
+ else 0.0
448
+ )
449
+ reserved = (gap + caption_h) if caption_lines else 0.0
450
+ usable_bottom = (
451
+ TAKEAWAY_Y - 0.3 if slide.takeaway.strip() else _BIGFACT_USABLE_BOTTOM_CM
452
+ )
453
+ available = usable_bottom - fact_frame.y - reserved
454
+ if floor_h > available:
455
+ return [
456
+ f"投影片「{label}」的 fact「{slide.fact}」即使縮到最小字級"
457
+ f"({theme.h1_pt}pt)仍需約 {floor_h:.1f}cm > 可用 {available:.1f}cm"
458
+ f"(與下方說明文字疊放後會超出版面)— 請縮短 fact 文字。"
459
+ ]
460
+ return []
461
+
462
+
463
+ _SHAPE_LAYOUTS = frozenset(
464
+ {"process", "timeline", "metrics", "dashboard", "diagram", "chart", "closing", "table"}
465
+ )
466
+
467
+
468
+ def check_budget(slide: Slide, theme: Theme, style=None) -> list[str]:
469
+ """Return an overflow message for every frame whose text overruns its box.
470
+
471
+ Walks ``LAYOUTS[slide.layout]``; for each frame, estimates the content height
472
+ and compares it against the frame height less a small padding allowance
473
+ (:data:`_FRAME_PADDING_CM`, 0.2cm total). An empty list means the whole slide
474
+ fits. Messages name the slide, the frame role, and the estimated vs available
475
+ height in cm — actionable feedback the retry loop (Task 15.2) feeds back to
476
+ the LLM.
477
+
478
+ The big-fact layout is special-cased (:func:`_check_big_fact`): because the
479
+ renderer auto-shrinks the fact and pushes the caption clear of it, a plain
480
+ per-frame walk would both mis-charge the fact (it is no longer drawn at
481
+ ``display_pt``) and miss the true failure mode (fact + caption running off the
482
+ page). That combined, floor-aware check replaces the walk for big-fact.
483
+ """
484
+ label = slide.title or slide.fact or slide.quote or "(未命名投影片)"
485
+ if slide.layout == "big-fact":
486
+ return _check_big_fact(slide, theme, label, style)
487
+ messages: list[str] = []
488
+ if slide.layout == "cards":
489
+ # cards-area is shape-rendered (this walk charges it nothing) but rides
490
+ # on unbounded ``bullets``. The renderer owns the fit, so it owns the
491
+ # check — imported lazily because render.odp imports this module. The
492
+ # walk below still covers the page-title frame.
493
+ from odforge.render.odp import cards_budget_warnings
494
+
495
+ messages.extend(cards_budget_warnings(slide, theme, style))
496
+ elif slide.layout in _SHAPE_LAYOUTS:
497
+ # Same ownership argument for every other shape layout: the renderer's
498
+ # fit loop is the authority on what gets cut, so ask it.
499
+ from odforge.render.odp import table_budget_warnings, truncation_warnings
500
+
501
+ messages.extend(truncation_warnings(slide, theme, style))
502
+ messages.extend(table_budget_warnings(slide, theme, style))
503
+ for frame in slide_frames(slide, style):
504
+ if frame.role == "takeaway" and frame.h > 3:
505
+ continue # a side panel: its text is fitted by the renderer
506
+ content_h = _frame_content_height(slide, theme, frame, slide.layout)
507
+ if content_h is None:
508
+ continue
509
+ available = frame.h - _FRAME_PADDING_CM
510
+ if content_h > available:
511
+ messages.append(
512
+ f"投影片「{label}」的「{frame.role}」框內容超出版面:"
513
+ f"預估 {content_h:.1f}cm > 可用 {available:.1f}cm"
514
+ f"(frame 高 {frame.h:g}cm)— 請精簡文字或改用其他版面。"
515
+ )
516
+ return messages
517
+
518
+
519
+ # ── deck-level checks ───────────────────────────────────────────────────────
520
+
521
+ _STRUCTURAL = frozenset({"agenda", "section", "quote", "big-fact"})
522
+ _REPEATABLE = frozenset({"cards", "process", "timeline", "metrics", "two-col", "comparison"})
523
+ _CN_DIGITS = dict(zip("兩二三四五六七八九十", (2, 2, 3, 4, 5, 6, 7, 8, 9, 10), strict=True))
524
+ # 「七項指標」「三大原因」「5 步」: a count the page promises. 個 counts only
525
+ # before a list noun — 「兩個月」「三個縣市」 are measures, not the page's items.
526
+ _TITLE_COUNT = re.compile(
527
+ r"(\d{1,2}|[兩二三四五六七八九十])\s*"
528
+ r"(項|大|條|步|點|件|招|種|道|題"
529
+ r"|個\s*(?:建議|原則|問題|重點|步驟|目標|原因|指標|階段|面向|關鍵|方向|策略|行動"
530
+ r"|轉折|教訓|功能|模組|成果|請求|決議|坑|挑戰|風險))"
531
+ )
532
+
533
+
534
+ def _slide_items(slide: Slide) -> int | None:
535
+ """How many parallel items the page itself shows, when it has one list."""
536
+ if slide.layout == "process":
537
+ return len(slide.steps)
538
+ if slide.layout == "timeline":
539
+ return len(slide.events)
540
+ if slide.layout == "metrics":
541
+ return len(slide.metrics)
542
+ if slide.layout == "table" and slide.table is not None:
543
+ return len(slide.table.rows)
544
+ if slide.layout in {"cards", "title-content", "closing"}:
545
+ return len(slide.bullets) or None
546
+ return None
547
+
548
+
549
+ def deck_warnings(slides: list[Slide]) -> list[str]:
550
+ """Pacing and consistency problems no single page shows: too many
551
+ structural pages, one card layout repeated through the deck, a title
552
+ promising a count its page does not deliver. Advisory, like the budget."""
553
+ total = len(slides)
554
+ out: list[str] = []
555
+ layouts = [s.layout for s in slides]
556
+ structural = sum(1 for lay in layouts if lay in _STRUCTURAL)
557
+ cap = max(2, round(total * 0.18))
558
+ if structural > cap:
559
+ out.append(
560
+ f"結構頁過多:{total} 頁中有 {structural} 頁是目錄/章節/引言/大數字頁"
561
+ f"(建議不超過 {cap} 頁)— 把部分章節頁併入內容頁的眉標,大數字改用 metrics。"
562
+ )
563
+ sections = layouts.count("section")
564
+ if sections and total < 20:
565
+ out.append(
566
+ f"{total} 頁的簡報不需要章節分隔頁(目前 {sections} 頁)— 章節改寫在各頁眉標即可。"
567
+ )
568
+ if layouts.count("quote") > 1:
569
+ out.append("引言頁超過 1 頁 — 只留最有力的一句。")
570
+ for lay in sorted(_REPEATABLE):
571
+ n = layouts.count(lay)
572
+ if n > max(2, total // 5):
573
+ out.append(
574
+ f"版面「{lay}」用了 {n} 次,讀起來像同一頁重複 — 改用 table/chart/diagram/"
575
+ "comparison 等其他版面呈現其中幾頁。"
576
+ )
577
+ for i, slide in enumerate(slides, start=1):
578
+ for msg in (count_mismatch(slide), bare_cards(slide)):
579
+ if msg:
580
+ out.append(f"第 {i} 頁:{msg}")
581
+ return out
582
+
583
+
584
+ def bare_cards(slide: Slide) -> str | None:
585
+ """Cards where some carry a description and some only a title — the page
586
+ reads as left unfinished. A content fix (write the missing line), never a
587
+ space problem, so it is not part of :func:`check_budget`."""
588
+ if slide.layout not in {"cards", "dashboard", "closing"} or not slide.bullets:
589
+ return None
590
+ bare = [
591
+ i + 1
592
+ for i, item in enumerate(slide.bullets)
593
+ if not (isinstance(item, BulletItem) and item.children)
594
+ ]
595
+ if bare and len(bare) < len(slide.bullets):
596
+ return (
597
+ f"第 {'、'.join(map(str, bare))} 張卡片只有標題、沒有說明 — "
598
+ "每張卡片都補一句具體說明(children)。"
599
+ )
600
+ return None
601
+
602
+
603
+ def count_mismatch(slide: Slide) -> str | None:
604
+ """A title that promises a count (「三項」「五個建議」) its page does not show."""
605
+ m = _TITLE_COUNT.search(slide.title or "")
606
+ items = _slide_items(slide)
607
+ if not m or items is None:
608
+ return None
609
+ raw = m.group(1)
610
+ promised = int(raw) if raw.isdigit() else _CN_DIGITS[raw]
611
+ if 2 <= promised <= 12 and promised != items:
612
+ return (
613
+ f"標題說「{m.group(0)}」,這頁卻列了 {items} 項 — "
614
+ "若數字指的就是這些項目,請讓兩者一致(否則可忽略)。"
615
+ )
616
+ return None
odforge/textutil.py ADDED
@@ -0,0 +1,24 @@
1
+ """Small, dependency-free text helpers shared across ODForge entry points.
2
+
3
+ Kept deliberately import-light (stdlib only) so both the CLI and the MCP server
4
+ can use it without pulling in ``rich`` or any other UI dependency.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ # A real-API failure can carry huge pydantic error dumps (tens of KB); bound
10
+ # what reaches a terminal or an MCP client.
11
+ MAX_ERROR_LEN = 500
12
+
13
+ _TRUNCATION_MARK = "…(訊息截斷)"
14
+
15
+
16
+ def concise(message: str, *, limit: int = MAX_ERROR_LEN) -> str:
17
+ """Return ``message`` truncated to ``limit`` chars, flagging any truncation.
18
+
19
+ Plain text only — no markup escaping — so it is safe for both rich-rendered
20
+ terminals (the caller escapes) and raw MCP string responses.
21
+ """
22
+ if len(message) > limit:
23
+ return message[:limit] + _TRUNCATION_MARK
24
+ return message