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/ir.py ADDED
@@ -0,0 +1,1181 @@
1
+ """ODForge Document IR (Intermediate Representation).
2
+
3
+ Pydantic v2 data models describing the JSON contract an LLM produces and the
4
+ deterministic renderers consume. This module contains data models only — no
5
+ rendering logic.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import re
12
+ from typing import Annotated, List, Literal, NamedTuple, Optional, Union
13
+
14
+ from pydantic import (
15
+ BaseModel,
16
+ ConfigDict,
17
+ Field,
18
+ TypeAdapter,
19
+ field_validator,
20
+ model_validator,
21
+ )
22
+
23
+ # themes.py is pure data and imports nothing from this module at runtime (its
24
+ # only ir reference is a TYPE_CHECKING annotation), so this direction is safe
25
+ # and gives the IR a single source of truth for which themes exist.
26
+ from odforge.themes import STYLES, THEMES
27
+
28
+
29
+ class StrictModel(BaseModel):
30
+ """Base for every IR model: an unknown field is an error, not a shrug.
31
+
32
+ Pydantic's default is to drop keys it does not recognise. For a contract an
33
+ LLM fills in, that default is the worst possible one: ``"bullet": [...]``
34
+ (singular) validated happily and rendered an empty page, and
35
+ ``"page": "big-fact"`` silently became the default layout. The model got no
36
+ signal, the retry loop had nothing to retry on, and the user got a blank
37
+ slide with no explanation.
38
+
39
+ Forbidding extras turns each of those into a message naming the offending
40
+ key — which is exactly what the generation retry needs in order to fix it.
41
+ """
42
+
43
+ model_config = ConfigDict(extra="forbid")
44
+
45
+
46
+ # Content limits. These are ABUSE guards, not layout guards. Deciding whether content fits a
47
+ # given frame is the budget gate's job (``textmetrics.check_budget``), which can
48
+ # see the theme, the font size and the frame — and which repairs or degrades
49
+ # rather than rejecting. Setting these low enough to enforce fit would take that
50
+ # decision away from the component that can actually make it, and would reject
51
+ # decks the budget gate knows how to fix. So they sit well above any layout's
52
+ # real capacity: they exist to stop a runaway model from handing the renderer
53
+ # thousands of items or a megabyte of prose.
54
+ MAX_TITLE_CHARS = 300
55
+ MAX_SUBTITLE_CHARS = 400
56
+ MAX_BULLET_CHARS = 600
57
+ MAX_BULLETS = 60
58
+ MAX_CHILDREN = 12
59
+ MAX_COLUMN_ITEMS = 40
60
+ MAX_NOTES_CHARS = 4000
61
+ MAX_FACT_CHARS = 400
62
+ MAX_QUOTE_CHARS = 800
63
+ MAX_SLIDES = 60
64
+ # The product's own page ceiling, shared by the outline model and the web API so
65
+ # there is exactly one number to change.
66
+ MAX_OUTLINE_PAGES = 30
67
+ MIN_OUTLINE_PAGES = 1
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # Text document blocks (discriminated on "kind")
71
+ # ---------------------------------------------------------------------------
72
+
73
+
74
+ class HeadingBlock(StrictModel):
75
+ kind: Literal["heading"] = "heading"
76
+ level: int = Field(ge=1, le=6)
77
+ text: str
78
+
79
+
80
+ class ParagraphBlock(StrictModel):
81
+ kind: Literal["paragraph"] = "paragraph"
82
+ text: str
83
+ style: Literal["body", "quote", "note"] = "body"
84
+
85
+
86
+ class ListBlock(StrictModel):
87
+ kind: Literal["list"] = "list"
88
+ ordered: bool = False
89
+ items: List[str]
90
+
91
+
92
+ class TableBlock(StrictModel):
93
+ kind: Literal["table"] = "table"
94
+ header: List[str]
95
+ # Numbers are what LLMs most often put in table cells (年度、金額、數量),
96
+ # pydantic v2 lax mode does NOT coerce int/float → str, and the renderer
97
+ # handles numbers natively — so a str-only row type hard-failed the whole
98
+ # document on realistic output. Mirrors ``Sheet.rows``.
99
+ rows: List[List[Union[str, int, float, None]]]
100
+
101
+
102
+ class TocBlock(StrictModel):
103
+ kind: Literal["toc"] = "toc"
104
+
105
+
106
+ class PageBreakBlock(StrictModel):
107
+ kind: Literal["pagebreak"] = "pagebreak"
108
+
109
+
110
+ Block = Annotated[
111
+ Union[
112
+ HeadingBlock,
113
+ ParagraphBlock,
114
+ ListBlock,
115
+ TableBlock,
116
+ TocBlock,
117
+ PageBreakBlock,
118
+ ],
119
+ Field(discriminator="kind"),
120
+ ]
121
+
122
+
123
+ class TextDoc(StrictModel):
124
+ type: Literal["text"] = "text"
125
+ title: str
126
+ lang: str = "zh-TW"
127
+ blocks: List[Block] = Field(default_factory=list)
128
+
129
+
130
+ # ---------------------------------------------------------------------------
131
+ # Presentation
132
+ # ---------------------------------------------------------------------------
133
+
134
+
135
+ # ``min_length=1`` counts characters, and a space is a character. Every content
136
+ # invariant in this file was built on that: ``bullets=[" "]`` satisfied "at
137
+ # least one item", rendered a page with a heading and nothing under it, and left
138
+ # LibreOffice perfectly happy to open the result. Emptiness has to be measured
139
+ # after stripping, or "not empty" means "contains at least one keystroke".
140
+ def _reject_blank(label: str, value: str) -> str:
141
+ if not value.strip():
142
+ raise ValueError(
143
+ f"{label} is whitespace-only; a page cannot be filled with blanks "
144
+ "— write real content or drop the field"
145
+ )
146
+ return value
147
+
148
+
149
+ def _text_of(item: object) -> str:
150
+ """The visible text of a bullet, whether it is a ``str`` or a ``BulletItem``."""
151
+ return item if isinstance(item, str) else getattr(item, "text", "")
152
+
153
+
154
+ class BulletItem(StrictModel):
155
+ """A nested bullet: a line of ``text`` with an optional list of ``children``.
156
+
157
+ ``Slide.bullets`` accepts either a plain ``str`` (a leaf bullet — the v1
158
+ shape, still valid) or a ``BulletItem`` carrying children. The renderer lowers
159
+ a ``BulletItem`` onto the ``(text, children)`` tuple its semantic-list builder
160
+ already understands (Task 13.2 contract). Children are one level deep (plain
161
+ strings) — all the two-level bullet list style renders.
162
+ """
163
+
164
+ text: str = Field(min_length=1, max_length=MAX_BULLET_CHARS)
165
+ children: List[str] = Field(default_factory=list, max_length=MAX_CHILDREN)
166
+
167
+ @field_validator("text")
168
+ @classmethod
169
+ def _text_is_not_blank(cls, value: str) -> str:
170
+ return _reject_blank("bullet text", value)
171
+
172
+ @field_validator("children")
173
+ @classmethod
174
+ def _children_within_limits(cls, items: List[str]) -> List[str]:
175
+ for item in items:
176
+ if len(item) > MAX_BULLET_CHARS:
177
+ raise ValueError(
178
+ f"nested bullet exceeds {MAX_BULLET_CHARS} characters; "
179
+ "split it into separate points"
180
+ )
181
+ _reject_blank("nested bullet", item)
182
+ return items
183
+
184
+
185
+ class ChartSpec(StrictModel):
186
+ """A horizontal bar chart's data, drawn as data-proportional ``draw:rect``\\ s.
187
+
188
+ Standalone in Phase 13.5 — the ``chart`` slide layout and the ``Slide.chart``
189
+ field that carry one onto a page arrive in Task 14.1; the renderer already
190
+ knows how to draw one via ``render.odp._chart_xml``.
191
+
192
+ Kept deliberately small: at most **8 bars**. More than that reads as a table,
193
+ not a chart, so it is rejected ("不支援就閉嘴") rather than crammed. ``values``
194
+ must be non-negative (a bar's width can't be negative) and equal in count to
195
+ ``labels``. ``highlight`` — when given — names the one bar the renderer fills
196
+ with the accent colour and must index an existing bar.
197
+ """
198
+
199
+ labels: List[str] = Field(min_length=1)
200
+ values: List[float] = Field(min_length=1)
201
+ unit: str = ""
202
+ highlight: Optional[int] = None
203
+
204
+ @field_validator("labels")
205
+ @classmethod
206
+ def _labels_are_not_blank(cls, labels: List[str]) -> List[str]:
207
+ for label in labels:
208
+ _reject_blank("chart label", label)
209
+ return labels
210
+
211
+ @field_validator("values")
212
+ @classmethod
213
+ def _values_non_negative(cls, values: List[float]) -> List[float]:
214
+ # ``NaN < 0`` and ``inf < 0`` are both False, so the sign check alone
215
+ # waves them through — and the renderer then dies converting NaN bar
216
+ # widths. Reject here, where the message says which value is wrong.
217
+ if any(not math.isfinite(v) for v in values):
218
+ raise ValueError("chart values must be finite numbers")
219
+ if any(v < 0 for v in values):
220
+ raise ValueError("chart values must be non-negative (>= 0)")
221
+ return values
222
+
223
+ @model_validator(mode="after")
224
+ def _check_shape(self) -> ChartSpec:
225
+ n = len(self.values)
226
+ if len(self.labels) != n:
227
+ raise ValueError(
228
+ f"labels/values length mismatch: {len(self.labels)} labels "
229
+ f"vs {n} values — they must pair up one-to-one"
230
+ )
231
+ if n > 8:
232
+ raise ValueError(
233
+ f"chart supports at most 8 bars, got {n} — split it into "
234
+ f"multiple charts (不支援就閉嘴)"
235
+ )
236
+ if self.highlight is not None and not 0 <= self.highlight < n:
237
+ raise ValueError(
238
+ f"highlight index {self.highlight} out of range for {n} bars "
239
+ f"(expected 0..{n - 1})"
240
+ )
241
+ return self
242
+
243
+
244
+ # The 10 page layouts a slide can render. Shared verbatim by ``Slide.layout``
245
+ # and ``PageRole.role`` (Task 15.1) — an outline page names the layout its
246
+ # stage-2 slide will use, so the two vocabularies must never drift apart.
247
+ class ProcessStep(StrictModel):
248
+ """One concise step in a shape-rendered process flow."""
249
+
250
+ title: str = Field(min_length=1, max_length=24)
251
+ detail: str = Field(default="", max_length=56)
252
+
253
+ @field_validator("title")
254
+ @classmethod
255
+ def _not_blank(cls, value: str) -> str:
256
+ return _reject_blank("step title", value)
257
+
258
+
259
+ class TimelineEvent(StrictModel):
260
+ """One event in a shape-rendered horizontal timeline."""
261
+
262
+ label: str = Field(min_length=1, max_length=18)
263
+ title: str = Field(min_length=1, max_length=24)
264
+ detail: str = Field(default="", max_length=48)
265
+
266
+ @field_validator("label", "title")
267
+ @classmethod
268
+ def _not_blank(cls, value: str) -> str:
269
+ return _reject_blank("timeline text", value)
270
+
271
+
272
+ class MetricSpec(StrictModel):
273
+ """One headline metric rendered as a large-number card."""
274
+
275
+ value: str = Field(min_length=1, max_length=18)
276
+ label: str = Field(min_length=1, max_length=24)
277
+ detail: str = Field(default="", max_length=56)
278
+
279
+ @field_validator("value", "label")
280
+ @classmethod
281
+ def _not_blank(cls, value: str) -> str:
282
+ return _reject_blank("metric text", value)
283
+
284
+
285
+ class TableSpec(StrictModel):
286
+ """A compact comparison table: header ``columns``, text ``rows``, and an
287
+ optional ``highlight`` row index (e.g. one's own product in a competitor
288
+ matrix). Deliberately small — beyond 8 rows it reads as a spreadsheet, and
289
+ the .ods renderer is the right tool for that."""
290
+
291
+ columns: List[str] = Field(min_length=2, max_length=6)
292
+ rows: List[List[str]] = Field(min_length=1, max_length=8)
293
+ highlight: Optional[int] = None
294
+
295
+ @field_validator("columns")
296
+ @classmethod
297
+ def _column_labels(cls, value: List[str]) -> List[str]:
298
+ for label in value:
299
+ _reject_blank("a table column label", label)
300
+ if len(label) > 16:
301
+ raise ValueError("table column labels must be ≤16 characters")
302
+ return value
303
+
304
+ @model_validator(mode="after")
305
+ def _rows_match_columns(self) -> TableSpec:
306
+ width = len(self.columns)
307
+ for i, row in enumerate(self.rows):
308
+ if len(row) != width:
309
+ raise ValueError(
310
+ f"table row {i} has {len(row)} cells; expected {width} "
311
+ "(one per column)"
312
+ )
313
+ for cell in row:
314
+ if len(cell) > 40:
315
+ raise ValueError("table cells must be ≤40 characters")
316
+ if self.highlight is not None and not 0 <= self.highlight < len(self.rows):
317
+ raise ValueError(
318
+ f"table highlight index {self.highlight} is out of range "
319
+ f"(0..{len(self.rows) - 1})"
320
+ )
321
+ return self
322
+
323
+
324
+ class DiagramNode(StrictModel):
325
+ """One editable node in a relationship or hierarchy diagram."""
326
+
327
+ id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,16}$")
328
+ title: str = Field(min_length=1, max_length=24)
329
+ detail: str = Field(default="", max_length=48)
330
+ emphasis: bool = False
331
+
332
+ @field_validator("title")
333
+ @classmethod
334
+ def _not_blank(cls, value: str) -> str:
335
+ return _reject_blank("node title", value)
336
+
337
+
338
+ class DiagramEdge(StrictModel):
339
+ """A directed semantic relationship between two diagram nodes."""
340
+
341
+ source: str
342
+ target: str
343
+ label: str = Field(default="", max_length=18)
344
+
345
+
346
+ class DiagramSpec(StrictModel):
347
+ """A small editable diagram with deterministic node placement."""
348
+
349
+ kind: Literal["hub", "hierarchy"] = "hub"
350
+ nodes: List[DiagramNode] = Field(min_length=2, max_length=6)
351
+ edges: List[DiagramEdge] = Field(min_length=1, max_length=8)
352
+
353
+ @model_validator(mode="after")
354
+ def _check_graph(self) -> DiagramSpec:
355
+ ids = [node.id for node in self.nodes]
356
+ if len(ids) != len(set(ids)):
357
+ raise ValueError("diagram node ids must be unique")
358
+ known = set(ids)
359
+ for edge in self.edges:
360
+ if edge.source not in known or edge.target not in known:
361
+ raise ValueError(
362
+ "diagram edges must reference existing node ids"
363
+ )
364
+ if edge.source == edge.target:
365
+ raise ValueError("diagram edges cannot connect a node to itself")
366
+ return self
367
+
368
+
369
+ class SourceRef(StrictModel):
370
+ """A concise source label with an optional clickable HTTP(S) URL."""
371
+
372
+ label: str = Field(min_length=1, max_length=32)
373
+ url: str = Field(default="", max_length=500)
374
+
375
+ @field_validator("label")
376
+ @classmethod
377
+ def _not_blank(cls, value: str) -> str:
378
+ return _reject_blank("source label", value)
379
+
380
+ @field_validator("url")
381
+ @classmethod
382
+ def _http_url_when_present(cls, value: str) -> str:
383
+ if value and not re.match(r"^https?://", value, flags=re.IGNORECASE):
384
+ raise ValueError("source url must start with http:// or https://")
385
+ return value
386
+
387
+
388
+ class MediaAssetRef(StrictModel):
389
+ """Application-owned image asset made available to the slide writer.
390
+
391
+ The model sees only the stable ``id`` and descriptive metadata. It never
392
+ receives a local filesystem path.
393
+ """
394
+
395
+ id: str = Field(pattern=r"^[A-Za-z0-9_-]{1,48}$")
396
+ description: str = Field(min_length=1, max_length=240)
397
+ credit: str = Field(default="", max_length=160)
398
+
399
+
400
+ class ImageSpec(StrictModel):
401
+ """One raster image placed on a slide.
402
+
403
+ ``src`` may be an app-managed ``asset://`` reference, an HTTPS URL, or a
404
+ PNG/JPEG data URI. Remote fetching is disabled unless the host application
405
+ explicitly opts in. ``prompt`` is used only when a configured image
406
+ provider is available.
407
+ """
408
+
409
+ src: str = Field(default="", max_length=12_000_000)
410
+ prompt: str = Field(default="", max_length=800)
411
+ alt: str = Field(min_length=1, max_length=240)
412
+ caption: str = Field(default="", max_length=180)
413
+ credit: str = Field(default="", max_length=160)
414
+ fit: Literal["contain", "fill"] = "contain"
415
+
416
+ @field_validator("alt")
417
+ @classmethod
418
+ def _alt_is_not_blank(cls, value: str) -> str:
419
+ # Alt text is the accessibility contract. Spaces satisfy a screen reader
420
+ # exactly as well as an empty string does.
421
+ return _reject_blank("image alt text", value)
422
+
423
+ @field_validator("src")
424
+ @classmethod
425
+ def _safe_source_scheme(cls, value: str) -> str:
426
+ if not value:
427
+ return value
428
+ if value.startswith("asset://"):
429
+ asset_id = value.removeprefix("asset://")
430
+ if not re.fullmatch(r"[A-Za-z0-9_-]{1,48}", asset_id):
431
+ raise ValueError("asset image src must use asset://<safe-id>")
432
+ return value
433
+ if re.match(
434
+ r"^data:image/(?:png|jpeg);base64,", value, flags=re.IGNORECASE
435
+ ):
436
+ return value
437
+ if re.match(r"^https://", value, flags=re.IGNORECASE):
438
+ return value
439
+ raise ValueError(
440
+ "image src must use asset://, https://, or a PNG/JPEG data URI"
441
+ )
442
+
443
+ @model_validator(mode="after")
444
+ def _source_or_prompt(self) -> ImageSpec:
445
+ if not self.src and not self.prompt.strip():
446
+ raise ValueError("image requires either src or prompt")
447
+ return self
448
+
449
+
450
+ PageRoleName = Literal[
451
+ "title", "title-content", "two-col", "section", "big-fact",
452
+ "quote", "agenda", "comparison", "chart", "closing",
453
+ "process", "timeline", "metrics", "cards", "diagram",
454
+ "image-focus", "image-split", "dashboard", "table",
455
+ ]
456
+
457
+
458
+ class Slide(StrictModel):
459
+ layout: PageRoleName
460
+ title: str = Field(default="", max_length=MAX_TITLE_CHARS)
461
+ subtitle: str = Field(default="", max_length=MAX_SUBTITLE_CHARS)
462
+ # Either plain strings (v1) or nested ``BulletItem``\\ s. Coerced by pydantic's
463
+ # smart union: a str stays a str, a dict/object becomes a BulletItem — so v1
464
+ # all-string decks pass through transparently.
465
+ bullets: List[Union[str, BulletItem]] = Field(
466
+ default_factory=list, max_length=MAX_BULLETS
467
+ )
468
+ left: List[str] = Field(default_factory=list, max_length=MAX_COLUMN_ITEMS)
469
+ right: List[str] = Field(default_factory=list, max_length=MAX_COLUMN_ITEMS)
470
+ fact: str = Field(default="", max_length=MAX_FACT_CHARS)
471
+ # Task 14.1 page-role fields. ``quote``/``attribution`` feed the quote layout;
472
+ # ``kicker`` is an eyebrow above a content-page title; ``chart`` carries a
473
+ # ChartSpec onto the chart layout.
474
+ quote: str = Field(default="", max_length=MAX_QUOTE_CHARS)
475
+ attribution: str = Field(default="", max_length=120)
476
+ kicker: str = Field(default="", max_length=60)
477
+ chart: Optional[ChartSpec] = None
478
+ steps: List[ProcessStep] = Field(default_factory=list, max_length=5)
479
+ events: List[TimelineEvent] = Field(default_factory=list, max_length=5)
480
+ metrics: List[MetricSpec] = Field(default_factory=list, max_length=4)
481
+ diagram: Optional[DiagramSpec] = None
482
+ image: Optional[ImageSpec] = None
483
+ table: Optional[TableSpec] = None
484
+ # A one-sentence conclusion rendered as an inverted band at the foot of a
485
+ # content page — the "so what" of the slide, visually distinct from bullets.
486
+ takeaway: str = Field(default="", max_length=90)
487
+ sources: List[SourceRef] = Field(default_factory=list, max_length=3)
488
+ notes: str = Field(default="", max_length=MAX_NOTES_CHARS)
489
+
490
+ @field_validator("bullets", "left", "right")
491
+ @classmethod
492
+ def _items_within_length(cls, items: list) -> list:
493
+ for item in items:
494
+ text = _text_of(item)
495
+ if len(text) > MAX_BULLET_CHARS:
496
+ raise ValueError(
497
+ f"a bullet exceeds {MAX_BULLET_CHARS} characters and cannot "
498
+ "fit any layout; shorten it or split it across pages"
499
+ )
500
+ _reject_blank("a bullet", text)
501
+ return items
502
+
503
+ @model_validator(mode="after")
504
+ def _check_layout_fields(self) -> Slide:
505
+ """Cross-field checks: a layout must carry the content it draws.
506
+
507
+ Every layout below draws something specific. A page that names a layout
508
+ and then omits what the layout draws does not render "mostly right" — it
509
+ renders an empty frame under a heading, which is worse than a validation
510
+ error because nothing reports it.
511
+ """
512
+ # Minimum content invariants. Previously only the specialised layouts
513
+ # were checked, so ``title-content`` with no bullets, ``two-col`` with one
514
+ # empty column and ``summary``-style pages with nothing on them all
515
+ # rendered as blank slides that still counted toward the page total.
516
+ # ``filled`` — not the raw list. The two differ exactly when the model
517
+ # padded a page out with blanks to satisfy a count.
518
+ def filled(items: list) -> list:
519
+ return [item for item in items if _text_of(item).strip()]
520
+
521
+ bullets, left, right = filled(self.bullets), filled(self.left), filled(self.right)
522
+ if self.layout in {"title-content", "agenda"} and not bullets:
523
+ raise ValueError(
524
+ f'layout="{self.layout}" requires at least one item in '
525
+ "Slide.bullets — an empty content page renders as a bare heading."
526
+ )
527
+ if self.layout == "two-col" and not (left and right):
528
+ raise ValueError(
529
+ 'layout="two-col" requires content in BOTH Slide.left and '
530
+ "Slide.right; a one-sided two-column page renders half-empty."
531
+ )
532
+ if self.layout == "comparison" and not (left and right):
533
+ raise ValueError(
534
+ 'layout="comparison" requires content in BOTH Slide.left and '
535
+ "Slide.right — a comparison with one side is not a comparison."
536
+ )
537
+ if self.layout == "big-fact" and not self.fact.strip():
538
+ raise ValueError(
539
+ 'layout="big-fact" requires a non-empty Slide.fact — that number '
540
+ "is the entire page."
541
+ )
542
+ if self.layout in {"title", "section", "closing"} and not self.title.strip():
543
+ raise ValueError(
544
+ f'layout="{self.layout}" requires a non-empty Slide.title.'
545
+ )
546
+ if self.layout == "chart" and self.chart is None:
547
+ raise ValueError(
548
+ 'layout="chart" requires a chart: set Slide.chart to a ChartSpec '
549
+ "(labels/values). Got chart=None."
550
+ )
551
+ if self.layout == "quote" and not self.quote.strip():
552
+ raise ValueError(
553
+ 'layout="quote" requires non-empty quote text: set Slide.quote. '
554
+ "Got an empty quote."
555
+ )
556
+ if self.layout == "process" and len(self.steps) < 2:
557
+ raise ValueError(
558
+ 'layout="process" requires 2 to 5 steps in Slide.steps.'
559
+ )
560
+ if self.layout == "timeline" and len(self.events) < 2:
561
+ raise ValueError(
562
+ 'layout="timeline" requires 2 to 5 events in Slide.events.'
563
+ )
564
+ if self.layout == "metrics" and len(self.metrics) < 2:
565
+ raise ValueError(
566
+ 'layout="metrics" requires 2 to 4 metrics in Slide.metrics.'
567
+ )
568
+ if self.layout == "cards" and not 2 <= len(bullets) <= 4:
569
+ raise ValueError(
570
+ 'layout="cards" requires 2 to 4 items in Slide.bullets.'
571
+ )
572
+ if self.layout == "dashboard":
573
+ # The composite page draws both: a stat strip AND a card grid.
574
+ if len(self.metrics) < 2:
575
+ raise ValueError(
576
+ 'layout="dashboard" requires 2 to 4 metrics in '
577
+ "Slide.metrics (the stat strip)."
578
+ )
579
+ if not 2 <= len(bullets) <= 4:
580
+ raise ValueError(
581
+ 'layout="dashboard" requires 2 to 4 items in '
582
+ "Slide.bullets (the card grid)."
583
+ )
584
+ if self.layout == "table" and self.table is None:
585
+ raise ValueError(
586
+ 'layout="table" requires a TableSpec in Slide.table.'
587
+ )
588
+ if self.layout == "diagram" and self.diagram is None:
589
+ raise ValueError(
590
+ 'layout="diagram" requires a DiagramSpec in Slide.diagram.'
591
+ )
592
+ if self.layout in {"image-focus", "image-split"} and self.image is None:
593
+ raise ValueError(
594
+ f'layout="{self.layout}" requires an ImageSpec in Slide.image.'
595
+ )
596
+ return self
597
+
598
+
599
+ # ---------------------------------------------------------------------------
600
+ # Design tokens (per-deck visual variation, validated before it reaches the
601
+ # renderer). An LLM designs a palette + font pairing per presentation; these
602
+ # models guarantee the tokens are well-formed and legible.
603
+ # ---------------------------------------------------------------------------
604
+
605
+ FONT_WHITELIST = ["Noto Sans TC", "Noto Serif TC", "微軟正黑體", "標楷體"]
606
+
607
+ _HEX_RE = re.compile(r"^#[0-9A-Fa-f]{6}$")
608
+
609
+
610
+ def _relative_luminance(hex_color: str) -> float:
611
+ """WCAG 2.x relative luminance of a ``#RRGGBB`` sRGB colour (0..1)."""
612
+ r = int(hex_color[1:3], 16)
613
+ g = int(hex_color[3:5], 16)
614
+ b = int(hex_color[5:7], 16)
615
+
616
+ def _linearize(channel: int) -> float:
617
+ c = channel / 255
618
+ return c / 12.92 if c <= 0.03928 else ((c + 0.055) / 1.055) ** 2.4
619
+
620
+ return 0.2126 * _linearize(r) + 0.7152 * _linearize(g) + 0.0722 * _linearize(b)
621
+
622
+
623
+ def contrast_ratio(fg: str, bg: str) -> float:
624
+ """WCAG contrast ratio between two ``#RRGGBB`` colours (1..21)."""
625
+ l1 = _relative_luminance(fg)
626
+ l2 = _relative_luminance(bg)
627
+ lighter, darker = (l1, l2) if l1 >= l2 else (l2, l1)
628
+ return (lighter + 0.05) / (darker + 0.05)
629
+
630
+
631
+ class Palette(StrictModel):
632
+ """A five-colour deck palette. Hex format and legibility are validated so
633
+ unreadable colour choices never reach the renderer."""
634
+
635
+ bg: str
636
+ surface: str
637
+ text: str
638
+ muted: str
639
+ accent: str
640
+
641
+ @field_validator("bg", "surface", "text", "muted", "accent")
642
+ @classmethod
643
+ def _valid_hex(cls, value: str) -> str:
644
+ if not _HEX_RE.match(value):
645
+ raise ValueError(
646
+ f'invalid colour {value!r}: expected 6-digit hex "#RRGGBB"'
647
+ )
648
+ return value
649
+
650
+ @model_validator(mode="after")
651
+ def _check_contrast(self) -> Palette:
652
+ # (name, colour, backdrop-name, backdrop, minimum ratio) — WCAG floors.
653
+ # ``surface`` is a first-class backdrop, not decoration: cards, metric
654
+ # tiles and closing actions all paint text on it. Checking only ``bg``
655
+ # accepted a light-bg/dark-surface palette whose dark text was invisible
656
+ # on every card. All built-in themes clear these bars comfortably.
657
+ checks = [
658
+ ("text", self.text, "bg", self.bg, 4.5),
659
+ ("accent", self.accent, "bg", self.bg, 3.0),
660
+ ("muted", self.muted, "bg", self.bg, 3.0),
661
+ ("text", self.text, "surface", self.surface, 4.5),
662
+ ("accent", self.accent, "surface", self.surface, 3.0),
663
+ ("muted", self.muted, "surface", self.surface, 3.0),
664
+ ]
665
+ failures = []
666
+ for name, colour, back_name, backdrop, minimum in checks:
667
+ ratio = contrast_ratio(colour, backdrop)
668
+ if ratio < minimum:
669
+ failures.append(
670
+ f"{name}/{back_name} contrast {ratio:.2f} < {minimum} "
671
+ f"required ({colour} on {backdrop})"
672
+ )
673
+ if failures:
674
+ raise ValueError("insufficient contrast — " + "; ".join(failures))
675
+ return self
676
+
677
+
678
+ class FontPair(StrictModel):
679
+ """Display + body typefaces, restricted to fonts we know ship with CJK
680
+ coverage on the target machines."""
681
+
682
+ display: str
683
+ body: str
684
+
685
+ @field_validator("display", "body")
686
+ @classmethod
687
+ def _in_whitelist(cls, value: str) -> str:
688
+ if value not in FONT_WHITELIST:
689
+ raise ValueError(
690
+ f"font {value!r} not allowed; choose from FONT_WHITELIST "
691
+ f"{FONT_WHITELIST}"
692
+ )
693
+ return value
694
+
695
+
696
+ class DesignSpec(StrictModel):
697
+ """Per-deck design tokens: colour palette, font pairing, and density knobs."""
698
+
699
+ palette: Palette
700
+ fonts: FontPair
701
+ scale: Literal["compact", "standard", "display"] = "standard"
702
+ mode: Literal["detailed", "presenter"] = "presenter"
703
+
704
+
705
+ LOGO_PLACEMENTS = ("cover", "cover-closing", "all")
706
+
707
+ # Output languages the generator writes decks in. Lives here (the data module)
708
+ # rather than in llm.py so the IR can validate the field without importing the
709
+ # generation layer. "bilingual" is 中英對照: Chinese first, English in brackets.
710
+ LANGUAGES: dict[str, str] = {
711
+ "zh-TW": "繁體中文",
712
+ "en": "English",
713
+ "bilingual": "中英對照",
714
+ }
715
+
716
+
717
+ class Branding(StrictModel):
718
+ """Deck-level cover branding: who is presenting, and the organisation mark.
719
+
720
+ Application-owned, not model-owned: the web/CLI layer overwrites whatever a
721
+ model may have invented here with what the user actually typed and uploaded.
722
+ ``logo`` uses the same ``asset://`` vocabulary as :class:`ImageSpec.src` so
723
+ the renderer resolves it through the one asset map it already has.
724
+ """
725
+
726
+ byline: str = Field(default="", max_length=160)
727
+ logo: str = Field(default="", max_length=400)
728
+ placement: Literal["cover", "cover-closing", "all"] = "cover-closing"
729
+
730
+ @field_validator("logo")
731
+ @classmethod
732
+ def _asset_reference_only(cls, value: str) -> str:
733
+ # A cover mark is app-supplied. Allowing https:// or data: here would
734
+ # hand a model-authored deck an outbound fetch on every render.
735
+ if value and not value.startswith("asset://"):
736
+ raise ValueError('logo must be an "asset://<id>" reference')
737
+ return value
738
+
739
+
740
+ class Presentation(StrictModel):
741
+ type: Literal["presentation"] = "presentation"
742
+ title: str = Field(min_length=1, max_length=MAX_TITLE_CHARS)
743
+ # Validated against the theme registry rather than a hand-kept Literal, so a
744
+ # new built-in preset is one edit in themes.py instead of three copies that
745
+ # drift. ``json_schema_extra`` keeps the tool schema an enum, which is what
746
+ # stops a model inventing a theme name in the first place.
747
+ theme: str = Field(
748
+ default="academic", json_schema_extra={"enum": sorted(THEMES)}
749
+ )
750
+ # 版式: the layout personality (cover composition, heading marks, divider
751
+ # treatment, footer furniture). Orthogonal to ``theme``/``design``, which
752
+ # only decide colour and type. Omitted → the palette's paired default.
753
+ style: Optional[str] = Field(
754
+ default=None, json_schema_extra={"enum": sorted(STYLES)}
755
+ )
756
+ slides: List[Slide] = Field(
757
+ default_factory=list, min_length=1, max_length=MAX_SLIDES
758
+ )
759
+ # Optional per-deck design tokens. Absent (``None``) keeps v1 behaviour.
760
+ design: Optional[DesignSpec] = None
761
+ # Cover byline / logo. Absent (``None``) renders exactly as before.
762
+ branding: Optional[Branding] = None
763
+
764
+ @field_validator("theme")
765
+ @classmethod
766
+ def _known_theme(cls, value: str) -> str:
767
+ if value not in THEMES:
768
+ raise ValueError(
769
+ f"unknown theme {value!r}; choose from {sorted(THEMES)}"
770
+ )
771
+ return value
772
+
773
+ @field_validator("style")
774
+ @classmethod
775
+ def _known_style(cls, value: Optional[str]) -> Optional[str]:
776
+ if value is not None and value not in STYLES:
777
+ raise ValueError(
778
+ f"unknown style {value!r}; choose from {sorted(STYLES)}"
779
+ )
780
+ return value
781
+
782
+
783
+ # ---------------------------------------------------------------------------
784
+ # Outline — stage-1 of the two-stage LLM pipeline (Task 15.1)
785
+ #
786
+ # Before any content is written, the model designs the deck's art direction
787
+ # (``DesignSpec``) and a page-role outline in one call. Stage 2 later fills each
788
+ # ``PageRole`` with real content. These models are plain, JSON-serializable
789
+ # pydantic so the front-end cockpit can consume an Outline directly.
790
+ # ---------------------------------------------------------------------------
791
+
792
+ class PageRole(StrictModel):
793
+ """One page in an :class:`Outline`.
794
+
795
+ ``role`` is the layout the page will render as (the ``PageRoleName``
796
+ vocabulary shared with ``Slide.layout``); ``title`` is its heading;
797
+ ``gist`` is a one-line summary of what the page says. ``gist`` is required
798
+ and non-blank — stage 2 depends on it for per-page guidance, so a missing
799
+ or empty gist must fail validation (and trigger the retry path) rather
800
+ than slip through silently.
801
+ """
802
+
803
+ role: PageRoleName
804
+ title: str = Field(max_length=MAX_TITLE_CHARS)
805
+ gist: str = Field(min_length=1, max_length=600)
806
+ visual_intent: str = Field(default="", max_length=160)
807
+
808
+
809
+ class Outline(StrictModel):
810
+ """Stage-1 blueprint: the deck's art direction plus a page-role outline.
811
+
812
+ ``design`` is optional — when the model's palette can't pass contrast the
813
+ pipeline strips it (``None``) and the renderer falls back to a preset theme,
814
+ rather than crashing on a bad palette. ``mode`` picks the narrative register
815
+ (``presenter`` = 講者型, large-type/minimal; ``detailed`` = 自讀型, complete
816
+ text). At least one page is required.
817
+ """
818
+
819
+ design: Optional[DesignSpec] = None
820
+ # 版式 chosen for the occasion (審查 → report, 口試 → academic, …). Without
821
+ # it every generated deck fell back to one composition, because a per-deck
822
+ # palette leaves ``theme`` at its default and the default's paired style is
823
+ # "classic". A user-picked style still overrides this downstream.
824
+ style: Optional[str] = Field(
825
+ default=None, json_schema_extra={"enum": sorted(STYLES)}
826
+ )
827
+ mode: Literal["detailed", "presenter"] = "presenter"
828
+ # Capped at the product's own page ceiling. A model that returns 80 pages is
829
+ # not "ambitious", it is about to spend eighty stage-2 generations and render
830
+ # a deck nobody asked for — catch it before the first one.
831
+ pages: List[PageRole] = Field(
832
+ min_length=MIN_OUTLINE_PAGES, max_length=MAX_OUTLINE_PAGES
833
+ )
834
+ # Application-owned context copied from the user's original request after
835
+ # stage 1 so the content-writing model keeps the full brief.
836
+ source_prompt: str = ""
837
+ media_assets: List[MediaAssetRef] = Field(default_factory=list, max_length=12)
838
+ image_generation_available: bool = False
839
+ # Which language stage 2 writes the deck in. Application-owned like the
840
+ # fields above: the caller overwrites whatever stage 1 returned with the
841
+ # user's actual choice, so a model that ignores the enum cannot silently
842
+ # switch the deck's language.
843
+ language: str = Field(
844
+ default="zh-TW", json_schema_extra={"enum": sorted(LANGUAGES)}
845
+ )
846
+
847
+ @field_validator("style")
848
+ @classmethod
849
+ def _known_outline_style(cls, value: Optional[str]) -> Optional[str]:
850
+ # An unknown style is dropped, not fatal: it is a taste call, and
851
+ # failing the whole outline over it would cost a retry for nothing.
852
+ return value if value in STYLES else None
853
+
854
+ @field_validator("language")
855
+ @classmethod
856
+ def _known_language(cls, value: str) -> str:
857
+ if value not in LANGUAGES:
858
+ raise ValueError(
859
+ f"unknown language {value!r}; choose from {sorted(LANGUAGES)}"
860
+ )
861
+ return value
862
+
863
+
864
+ # ---------------------------------------------------------------------------
865
+ # Spreadsheet
866
+ # ---------------------------------------------------------------------------
867
+
868
+
869
+ # A1-style reference: column letters + 1-based row (``B5``, ``AA12``). Optional
870
+ # ``$`` anchors are accepted because OpenFormula writes them for absolute refs.
871
+ _CELL_REF_RE = re.compile(r"^\$?([A-Za-z]{1,3})\$?([1-9][0-9]*)$")
872
+
873
+ # Functions we will actually emit and that LibreOffice computes. Anything outside
874
+ # this set is refused rather than written out and left to resolve as ``#NAME?``
875
+ # in the user's spreadsheet — the project's standing "不支援就閉嘴" rule. Growing
876
+ # the list is one edit; shipping a broken formula is a broken deliverable.
877
+ OPENFORMULA_FUNCTIONS = frozenset(
878
+ """
879
+ ABS AND AVERAGE AVERAGEIF CEILING CONCATENATE COUNT COUNTA COUNTIF DATE DAY
880
+ EXP FLOOR HLOOKUP IF IFERROR INDEX INT LARGE LEFT LEN LN LOG LOG10 LOWER
881
+ MATCH MAX MEDIAN MID MIN MOD MONTH NOT NOW OR POWER PRODUCT RANK RIGHT ROUND
882
+ ROUNDDOWN ROUNDUP SIGN SMALL SQRT STDEV SUM SUMIF SUMPRODUCT TEXT TODAY TRIM
883
+ TRUNC UPPER VAR VLOOKUP YEAR
884
+ """.split()
885
+ )
886
+
887
+ _FUNCTION_CALL_RE = re.compile(r"([A-Za-z][A-Za-z0-9._]*)\s*\(")
888
+
889
+ # --- reference scanning ----------------------------------------------------
890
+ #
891
+ # Two syntaxes reach us and BOTH have to be understood, because the bounds check
892
+ # downstream is only as good as this scanner. Reading just one of them is worse
893
+ # than reading neither: it reports "references verified" over a formula whose
894
+ # references were never looked at.
895
+ #
896
+ # ``[.B2]``, ``[.B2:.B7]``, ``[Sheet2.B2]``, ``['My Sheet'.B2]``
897
+ # OpenFormula's bracketed form — what the renderer emits.
898
+ # ``B2``, ``A1:A999``, ``$A$1``, ``Sheet2.B2``
899
+ # the bare form models emit constantly. Previously invisible, which is how
900
+ # ``of:=SUM(A1:A999)`` passed validation on a seven-row sheet and shipped a
901
+ # spreadsheet full of empty-cell arithmetic.
902
+ _A1 = r"\$?[A-Za-z]{1,3}\$?[0-9]+"
903
+ _SHEET_NAME = r"(?:'(?:[^']|'')*'|\$?[A-Za-z_一-鿿][\w一-鿿]*)"
904
+ _BRACKET_BODY_RE = re.compile(r"\[([^\]]*)\]")
905
+ _BRACKET_PART_RE = re.compile(rf"^\s*(?:({_SHEET_NAME})\s*)?\.?({_A1})\s*$")
906
+ # Guards, in order: not preceded by an identifier character (so the ``LOG`` of
907
+ # ``LOG10(`` cannot be read as column LOG row 10); optional ``Sheet2.`` prefix;
908
+ # the A1 body; and not followed by an identifier character or ``(`` (so a
909
+ # function name can never be mistaken for a cell).
910
+ _BARE_REF_RE = re.compile(
911
+ r"(?<![A-Za-z0-9_.$])"
912
+ rf"(?:({_SHEET_NAME})\.)?"
913
+ rf"({_A1})"
914
+ r"(?![A-Za-z0-9_(])"
915
+ )
916
+ # Double-quoted string literals are data, not references: ``TEXT(A1,"B5")``
917
+ # names one cell, not two.
918
+ _STRING_LITERAL_RE = re.compile(r'"(?:[^"\\]|\\.)*"')
919
+
920
+
921
+ class CellReference(NamedTuple):
922
+ """One cell a formula names. ``sheet`` is ``None`` for a same-sheet ref."""
923
+
924
+ sheet: Optional[str]
925
+ column: int
926
+ row: int
927
+
928
+
929
+ def _unquote_sheet(name: str) -> str:
930
+ """``'My Sheet'`` → ``My Sheet``; ``$Sheet2`` → ``Sheet2``."""
931
+ name = name.strip().lstrip("$")
932
+ if name.startswith("'") and name.endswith("'") and len(name) >= 2:
933
+ return name[1:-1].replace("''", "'")
934
+ return name
935
+
936
+
937
+ def _column_index(letters: str) -> int:
938
+ """``A`` → 0, ``B`` → 1, ``AA`` → 26."""
939
+ index = 0
940
+ for char in letters.upper():
941
+ index = index * 26 + (ord(char) - ord("A") + 1)
942
+ return index - 1
943
+
944
+
945
+ def _format_ref(column: int, row: int) -> str:
946
+ """``(1, 4)`` → ``B5`` — so a bounds error names the cell the model wrote."""
947
+ letters = ""
948
+ index = column
949
+ while True:
950
+ letters = chr(ord("A") + index % 26) + letters
951
+ index = index // 26 - 1
952
+ if index < 0:
953
+ break
954
+ return f"{letters}{row + 1}"
955
+
956
+
957
+ def parse_cell_ref(ref: str) -> tuple[int, int]:
958
+ """``"B5"`` → ``(column=1, row=4)``, both 0-based. Raises on a bad ref."""
959
+ match = _CELL_REF_RE.match(ref.strip())
960
+ if match is None:
961
+ raise ValueError(
962
+ f"invalid cell reference {ref!r}: expected A1 style, e.g. 'B5' or 'AA12'"
963
+ )
964
+ return _column_index(match.group(1)), int(match.group(2)) - 1
965
+
966
+
967
+ class FormulaSpec(StrictModel):
968
+ cell: str
969
+ formula: str
970
+
971
+ @field_validator("cell")
972
+ @classmethod
973
+ def _target_is_a_cell_ref(cls, value: str) -> str:
974
+ parse_cell_ref(value) # raises with the offending ref in the message
975
+ return value
976
+
977
+ @field_validator("formula")
978
+ @classmethod
979
+ def _must_use_of_namespace(cls, value: str) -> str:
980
+ if not value.startswith("of:="):
981
+ raise ValueError('formula must start with "of:="')
982
+ body = value[len("of:=") :]
983
+ if not body.strip():
984
+ raise ValueError("formula body is empty after the 'of:=' prefix")
985
+ if body.count("(") != body.count(")"):
986
+ raise ValueError(
987
+ f"unbalanced parentheses in formula {value!r} — LibreOffice will "
988
+ "refuse to parse it"
989
+ )
990
+ unknown = sorted(
991
+ {
992
+ name.upper()
993
+ for name in _FUNCTION_CALL_RE.findall(body)
994
+ if name.upper() not in OPENFORMULA_FUNCTIONS
995
+ }
996
+ )
997
+ if unknown:
998
+ raise ValueError(
999
+ f"unsupported spreadsheet function(s): {', '.join(unknown)}. "
1000
+ "ODForge only emits functions it has verified LibreOffice "
1001
+ f"computes; supported: {', '.join(sorted(OPENFORMULA_FUNCTIONS))}"
1002
+ )
1003
+ return value
1004
+
1005
+ def references(self) -> List[CellReference]:
1006
+ """Every cell the formula body names, bracketed or bare, 0-based.
1007
+
1008
+ Range endpoints only — a range's interior cannot be out of bounds if both
1009
+ ends are in bounds, so checking the endpoints is sufficient and cheap.
1010
+ """
1011
+ body = self.formula
1012
+ found: List[CellReference] = []
1013
+ for bracket in _BRACKET_BODY_RE.findall(body):
1014
+ # Within one bracket the range end inherits the start's sheet:
1015
+ # ``[Sheet2.B2:.B9]`` is Sheet2 twice, not Sheet2 and then here.
1016
+ inherited: Optional[str] = None
1017
+ for part in bracket.split(":"):
1018
+ match = _BRACKET_PART_RE.match(part)
1019
+ if match is None:
1020
+ continue
1021
+ sheet, ref = match.groups()
1022
+ name = _unquote_sheet(sheet) if sheet else inherited
1023
+ inherited = inherited or name
1024
+ column, row = parse_cell_ref(ref)
1025
+ found.append(CellReference(name, column, row))
1026
+ # Bracketed refs are consumed before the bare scan so the same cell is not
1027
+ # reported twice, and string literals are blanked so their contents cannot
1028
+ # masquerade as references.
1029
+ remainder = _STRING_LITERAL_RE.sub('""', _BRACKET_BODY_RE.sub("", body))
1030
+ for sheet, ref in _BARE_REF_RE.findall(remainder):
1031
+ column, row = parse_cell_ref(ref)
1032
+ found.append(
1033
+ CellReference(_unquote_sheet(sheet) if sheet else None, column, row)
1034
+ )
1035
+ return found
1036
+
1037
+ def referenced_cells(self) -> List[tuple[int, int]]:
1038
+ """Same-sheet ``(column, row)`` pairs only — cross-sheet refs are resolved
1039
+ by :class:`Spreadsheet`, which is the only scope that knows the sizes of
1040
+ the other sheets."""
1041
+ return [(ref.column, ref.row) for ref in self.references() if ref.sheet is None]
1042
+
1043
+
1044
+ class Sheet(StrictModel):
1045
+ name: str = Field(min_length=1, max_length=120)
1046
+ columns: List[str] = Field(min_length=1, max_length=64)
1047
+ # ``None`` marks an intentionally empty cell — typically a formula target
1048
+ # the LLM leaves null because a formula computes its value.
1049
+ rows: List[List[Union[str, int, float, None]]] = Field(max_length=5000)
1050
+ formulas: List[FormulaSpec] = Field(default_factory=list, max_length=500)
1051
+
1052
+ @field_validator("rows")
1053
+ @classmethod
1054
+ def _numbers_must_be_finite(
1055
+ cls, rows: List[List[Union[str, int, float, None]]]
1056
+ ) -> List[List[Union[str, int, float, None]]]:
1057
+ """NaN/±Infinity are not numbers a spreadsheet can hold.
1058
+
1059
+ ODF has no representation for them: the renderer writes
1060
+ ``office:value="nan"`` and LibreOffice shows ``#VALUE!`` — a broken cell
1061
+ in a file we certified as valid. Reject at the contract, where the
1062
+ message can name the row and column.
1063
+ """
1064
+ for r, row in enumerate(rows):
1065
+ for c, value in enumerate(row):
1066
+ if isinstance(value, bool) or not isinstance(value, float):
1067
+ continue
1068
+ if not math.isfinite(value):
1069
+ raise ValueError(
1070
+ f"cell at row {r + 1}, column {c + 1} is {value!r}; "
1071
+ "spreadsheet numbers must be finite "
1072
+ "(NaN/Infinity have no ODF representation)"
1073
+ )
1074
+ return rows
1075
+
1076
+ @model_validator(mode="after")
1077
+ def _check_formula_targets(self) -> Sheet:
1078
+ """Formula targets must be unique, in range, and reference real cells.
1079
+
1080
+ The sheet's addressable area is the header row plus its data rows; a
1081
+ formula that writes to (or reads from) outside it produces a cell
1082
+ LibreOffice cannot resolve, which is exactly the ``#REF!``/``#NAME?``
1083
+ class of failure a "valid ODF" claim must not cover for.
1084
+ """
1085
+ width = len(self.columns)
1086
+ # Row 1 is the header; data rows follow. A formula may target the row
1087
+ # immediately after the data (a totals row the IR leaves implicit).
1088
+ height = 1 + len(self.rows) + 1
1089
+ seen: dict[str, int] = {}
1090
+ for index, spec in enumerate(self.formulas):
1091
+ column, row = parse_cell_ref(spec.cell)
1092
+ key = spec.cell.replace("$", "").upper()
1093
+ if key in seen:
1094
+ raise ValueError(
1095
+ f"duplicate formula target {spec.cell!r} (formulas "
1096
+ f"{seen[key] + 1} and {index + 1}) — the second would "
1097
+ "silently overwrite the first"
1098
+ )
1099
+ seen[key] = index
1100
+ if not (0 <= column < width and 0 <= row < height):
1101
+ raise ValueError(
1102
+ f"formula target {spec.cell!r} is outside sheet "
1103
+ f"{self.name!r} ({width} columns × {height} rows)"
1104
+ )
1105
+ for ref in spec.references():
1106
+ if ref.sheet is not None:
1107
+ # Resolved by ``Spreadsheet`` — a sheet cannot see its siblings.
1108
+ continue
1109
+ if not (0 <= ref.column < width and 0 <= ref.row < height):
1110
+ raise ValueError(
1111
+ f"formula for {spec.cell!r} references "
1112
+ f"{_format_ref(ref.column, ref.row)}, outside sheet "
1113
+ f"{self.name!r} ({width} columns × {height} rows)"
1114
+ )
1115
+ return self
1116
+
1117
+
1118
+ class Spreadsheet(StrictModel):
1119
+ type: Literal["spreadsheet"] = "spreadsheet"
1120
+ title: str
1121
+ sheets: List[Sheet] = Field(default_factory=list, min_length=1)
1122
+
1123
+ @model_validator(mode="after")
1124
+ def _check_cross_sheet_references(self) -> Spreadsheet:
1125
+ """Resolve ``Sheet2.B2`` / ``[Sheet2.B2]`` against the sheet it names.
1126
+
1127
+ This is the only scope that can: a ``Sheet`` validator sees its own
1128
+ dimensions and nothing else, so a cross-sheet reference reaching it can
1129
+ only be waved through. Waved through is how ``#REF!`` gets certified as
1130
+ valid ODF.
1131
+ """
1132
+ sizes = {
1133
+ sheet.name: (len(sheet.columns), 1 + len(sheet.rows) + 1)
1134
+ for sheet in self.sheets
1135
+ }
1136
+ # LibreOffice resolves sheet names case-insensitively; a model that writes
1137
+ # ``sheet2.B2`` for a sheet called ``Sheet2`` means the same sheet.
1138
+ folded = {name.casefold(): name for name in sizes}
1139
+ for sheet in self.sheets:
1140
+ for spec in sheet.formulas:
1141
+ for ref in spec.references():
1142
+ if ref.sheet is None:
1143
+ continue
1144
+ target = folded.get(ref.sheet.casefold())
1145
+ if target is None:
1146
+ raise ValueError(
1147
+ f"formula for {spec.cell!r} on sheet {sheet.name!r} "
1148
+ f"references unknown sheet {ref.sheet!r}; this "
1149
+ f"spreadsheet has {sorted(sizes)}"
1150
+ )
1151
+ width, height = sizes[target]
1152
+ if not (0 <= ref.column < width and 0 <= ref.row < height):
1153
+ raise ValueError(
1154
+ f"formula for {spec.cell!r} on sheet {sheet.name!r} "
1155
+ f"references {target}.{_format_ref(ref.column, ref.row)}, "
1156
+ f"outside that sheet ({width} columns × {height} rows)"
1157
+ )
1158
+ return self
1159
+
1160
+
1161
+ # ---------------------------------------------------------------------------
1162
+ # Top-level parsing (discriminated on "type")
1163
+ # ---------------------------------------------------------------------------
1164
+
1165
+ Document = Annotated[
1166
+ Union[TextDoc, Presentation, Spreadsheet],
1167
+ Field(discriminator="type"),
1168
+ ]
1169
+
1170
+ _document_adapter: TypeAdapter[Union[TextDoc, Presentation, Spreadsheet]] = TypeAdapter(
1171
+ Document
1172
+ )
1173
+
1174
+
1175
+ def parse_ir(data: dict) -> Union[TextDoc, Presentation, Spreadsheet]:
1176
+ """Validate a raw dict into the matching Document IR model.
1177
+
1178
+ Dispatches on the ``type`` discriminator. Raises ``pydantic.ValidationError``
1179
+ for unknown types or invalid payloads.
1180
+ """
1181
+ return _document_adapter.validate_python(data)