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/validate.py ADDED
@@ -0,0 +1,403 @@
1
+ """Three-gate ODF validation.
2
+
3
+ ``validate_odf`` runs up to three independent gates over a generated ODF
4
+ file and reports the outcome of each without ever raising:
5
+
6
+ 1. ``"structure"`` - zip opens; first entry is a ZIP_STORED ``mimetype``
7
+ whose value matches the file extension; ``META-INF/manifest.xml`` exists
8
+ and every listed full-path (other than ``"/"``) is present in the zip.
9
+ 2. ``"xml"`` - every ``.xml`` member parses as well-formed XML via lxml.
10
+ 3. ``"soffice"`` - only when ``with_soffice=True`` and LibreOffice is found;
11
+ round-trips the file through ``soffice --convert-to pdf`` and checks that
12
+ a PDF is produced.
13
+
14
+ Depends only on the stdlib, lxml and the mimetype constants from
15
+ ``package.py`` - never on ``render/*`` or the IR.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import shutil
21
+ import subprocess
22
+ import tempfile
23
+ import zipfile
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ from lxml import etree
28
+
29
+ from .package import ODP_MIMETYPE, ODS_MIMETYPE, ODT_MIMETYPE
30
+ from .xmlsafe import safe_fromstring
31
+ from .zipguard import (
32
+ MAX_MANIFEST_MEMBER,
33
+ MAX_MIMETYPE_MEMBER,
34
+ MAX_XML_MEMBER,
35
+ ArchiveLimitError,
36
+ inspect_archive,
37
+ read_member,
38
+ read_xml_member,
39
+ )
40
+
41
+ _MANIFEST_NS = "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"
42
+ _MANIFEST_PATH = "META-INF/manifest.xml"
43
+
44
+ _EXT_MIMETYPE = {
45
+ ".odt": ODT_MIMETYPE,
46
+ ".odp": ODP_MIMETYPE,
47
+ ".ods": ODS_MIMETYPE,
48
+ }
49
+
50
+ _SOFFICE_TIMEOUT = 120
51
+
52
+ # Parts that, when present in the package, must not be empty. Presence is
53
+ # not enforced here - the rule is "if a required-named part exists and is
54
+ # empty, fail" (e.g. settings.xml need not exist at all).
55
+ _REQUIRED_PARTS = {"content.xml", "styles.xml", "meta.xml", "settings.xml", "META-INF/manifest.xml"}
56
+
57
+
58
+ @dataclass
59
+ class ValidationReport:
60
+ ok: bool # 所有跑過的 gate 都 True
61
+ # gate 名 → (通過?, 訊息);鍵:"structure" | "xml" | "soffice"
62
+ gates: dict[str, tuple[bool, str]]
63
+
64
+
65
+ def find_soffice() -> Path | None:
66
+ """Locate the LibreOffice ``soffice`` executable, or ``None``."""
67
+ found = shutil.which("soffice")
68
+ if found:
69
+ return Path(found)
70
+ for candidate in (
71
+ r"C:\Program Files\LibreOffice\program\soffice.exe",
72
+ r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
73
+ ):
74
+ p = Path(candidate)
75
+ if p.exists():
76
+ return p
77
+ return None
78
+
79
+
80
+ def _gate_structure(path: Path) -> tuple[bool, str]:
81
+ """Gate 1: zip layout, mimetype-first-stored, extension match, manifest."""
82
+ if not zipfile.is_zipfile(path):
83
+ return False, f"not a valid zip file: {path.name}"
84
+ with zipfile.ZipFile(path) as z:
85
+ try:
86
+ infos = inspect_archive(z)
87
+ except ArchiveLimitError as exc:
88
+ return False, f"archive exceeds safety limits: {exc}"
89
+ if not infos:
90
+ return False, "empty zip archive"
91
+
92
+ first = infos[0]
93
+ if first.filename != "mimetype":
94
+ return False, f"first entry is {first.filename!r}, expected 'mimetype'"
95
+ if first.compress_type != zipfile.ZIP_STORED:
96
+ return False, "mimetype entry is not stored (ZIP_STORED)"
97
+
98
+ try:
99
+ mimetype = read_member(
100
+ z, "mimetype", max_bytes=MAX_MIMETYPE_MEMBER
101
+ ).decode("utf-8", errors="replace").strip()
102
+ except ArchiveLimitError as exc:
103
+ return False, f"archive exceeds safety limits: {exc}"
104
+ expected = _EXT_MIMETYPE.get(path.suffix.lower())
105
+ if expected is None:
106
+ return False, f"unknown extension {path.suffix!r}"
107
+ if mimetype != expected:
108
+ return False, (
109
+ f"mimetype {mimetype!r} does not match extension "
110
+ f"{path.suffix!r} (expected {expected!r})"
111
+ )
112
+
113
+ names = set(z.namelist())
114
+ if _MANIFEST_PATH not in names:
115
+ return False, f"missing {_MANIFEST_PATH}"
116
+
117
+ try:
118
+ # Untrusted input: hardened parse (no external-entity resolution).
119
+ root = safe_fromstring(
120
+ read_xml_member(z, _MANIFEST_PATH, max_bytes=MAX_MANIFEST_MEMBER)
121
+ )
122
+ except ArchiveLimitError as exc:
123
+ return False, f"archive exceeds safety limits: {exc}"
124
+ except etree.XMLSyntaxError as exc:
125
+ return False, f"manifest is not well-formed XML: {exc}"
126
+
127
+ missing = []
128
+ for entry in root.iter(f"{{{_MANIFEST_NS}}}file-entry"):
129
+ full_path = entry.get(f"{{{_MANIFEST_NS}}}full-path")
130
+ if not full_path or full_path == "/":
131
+ continue
132
+ if full_path.endswith("/"):
133
+ # Directory entry: satisfied if any member lives under it.
134
+ if not any(n.startswith(full_path) for n in names):
135
+ missing.append(full_path)
136
+ elif full_path not in names:
137
+ missing.append(full_path)
138
+ if missing:
139
+ return False, f"manifest lists parts absent from zip: {', '.join(sorted(missing))}"
140
+
141
+ return True, "structure ok"
142
+
143
+
144
+ def _gate_xml(path: Path) -> tuple[bool, str]:
145
+ """Gate 2: every .xml member is well-formed."""
146
+ if not zipfile.is_zipfile(path):
147
+ return False, f"not a valid zip file: {path.name}"
148
+ bad = []
149
+ with zipfile.ZipFile(path) as z:
150
+ try:
151
+ infos = inspect_archive(z)
152
+ except ArchiveLimitError as exc:
153
+ return False, f"archive exceeds safety limits: {exc}"
154
+ for info in infos:
155
+ name = info.filename
156
+ if not name.lower().endswith(".xml"):
157
+ continue
158
+ try:
159
+ data = read_xml_member(z, name, max_bytes=MAX_XML_MEMBER)
160
+ except ArchiveLimitError as exc:
161
+ return False, f"archive exceeds safety limits: {exc}"
162
+ if not data.strip():
163
+ # Mandatory document parts must carry content; other empty
164
+ # placeholders (e.g. Configurations2/.../current.xml) are
165
+ # emitted by real ODF producers and are fine.
166
+ if name in _REQUIRED_PARTS:
167
+ bad.append(f"{name}: empty/whitespace-only required part")
168
+ continue
169
+ try:
170
+ # Untrusted input: hardened parse (no external-entity resolution,
171
+ # bounded expansion) — well-formedness is all this gate asserts.
172
+ safe_fromstring(data)
173
+ except etree.XMLSyntaxError as exc:
174
+ bad.append(f"{name}: {exc}")
175
+ if bad:
176
+ return False, "malformed XML in " + "; ".join(bad)
177
+ return True, "all xml well-formed"
178
+
179
+
180
+ def _build_soffice_cmd(
181
+ soffice: Path, src: Path, fmt: str, outdir: Path, profile_dir: Path
182
+ ) -> list[str]:
183
+ """Build the soffice conversion argv (pure function, so it is testable).
184
+
185
+ Always injects ``-env:UserInstallation=<file URI>`` (single-dash env switch)
186
+ so the headless conversion uses a private profile and never collides with a
187
+ desktop LibreOffice instance the user may have open.
188
+ """
189
+ return [
190
+ str(soffice),
191
+ "--headless",
192
+ f"-env:UserInstallation={profile_dir.as_uri()}",
193
+ "--convert-to",
194
+ fmt,
195
+ "--outdir",
196
+ str(outdir),
197
+ str(src),
198
+ ]
199
+
200
+
201
+ def run_soffice_convert(
202
+ soffice: Path,
203
+ src: Path,
204
+ fmt: str,
205
+ outdir: Path,
206
+ timeout: int = _SOFFICE_TIMEOUT,
207
+ ) -> subprocess.CompletedProcess:
208
+ """Convert ``src`` to ``fmt`` in ``outdir`` via an isolated soffice profile.
209
+
210
+ The single shared entry point for every soffice ``--convert-to`` call in the
211
+ codebase. Creates a throwaway profile directory, passes it as
212
+ ``-env:UserInstallation``, captures stdout/stderr and cleans the profile up.
213
+ Raises :class:`subprocess.TimeoutExpired` on timeout (callers handle it).
214
+ """
215
+ profile_dir = Path(tempfile.mkdtemp(prefix="odforge-soffice-profile-"))
216
+ try:
217
+ return subprocess.run(
218
+ _build_soffice_cmd(soffice, src, fmt, outdir, profile_dir),
219
+ # stdin must NOT be inherited: under an MCP/stdio host the parent's
220
+ # stdin is an overlapped named pipe (anyio/Node create these on
221
+ # Windows), and soffice blocks forever on it after profile init —
222
+ # every conversion then dies at the timeout. A headless converter
223
+ # has no business reading stdin, so hand it the null device.
224
+ stdin=subprocess.DEVNULL,
225
+ capture_output=True,
226
+ text=True,
227
+ timeout=timeout,
228
+ )
229
+ finally:
230
+ shutil.rmtree(profile_dir, ignore_errors=True)
231
+
232
+
233
+ # The error values LibreOffice writes into a cell whose formula it could not
234
+ # resolve. Finding one of these means the file opens *and is wrong*: a formula
235
+ # named a function LibreOffice does not have, pointed at a deleted cell, or was
236
+ # handed the wrong argument type. "It opened" is not the claim the gate makes.
237
+ _CALC_ERROR_TOKENS = (
238
+ "#NAME?",
239
+ "#VALUE!",
240
+ "#REF!",
241
+ "#DIV/0!",
242
+ "#NUM!",
243
+ "#N/A",
244
+ "#NULL!",
245
+ "Err:",
246
+ )
247
+
248
+
249
+ def _scan_calc_errors(csv_text: str) -> list[str]:
250
+ """Every distinct Calc error token present in a converted sheet's CSV."""
251
+ return [token for token in _CALC_ERROR_TOKENS if token in csv_text]
252
+
253
+
254
+ # ``--convert-to csv`` exports the FIRST sheet and stops. Every sheet after it
255
+ # was certified without being looked at: a workbook whose sheet 1 totals cleanly
256
+ # and whose sheet 2 is solid ``#DIV/0!`` passed with "formulas evaluated without
257
+ # errors". This filter string is the same CSV export with the trailing token set
258
+ # to ``-1`` — "every sheet", one ``{stem}-{SheetName}.csv`` each.
259
+ _CSV_ALL_SHEETS = "csv:Text - txt - csv (StarCalc):44,34,76,1,,0,false,true,true,false,false,-1"
260
+
261
+ _TABLE_TAG = "{urn:oasis:names:tc:opendocument:xmlns:table:1.0}table"
262
+
263
+
264
+ def _sheet_count(path: Path) -> int:
265
+ """How many sheets ``path`` declares, straight from its own content.xml.
266
+
267
+ The number the export has to match. Without it there is no way to tell "one
268
+ CSV because there is one sheet" from "one CSV because this LibreOffice
269
+ ignored the all-sheets token" — and those two must not be reported alike.
270
+ Returns ``0`` when the package cannot be read; the caller treats that as
271
+ "cannot verify" rather than "verified".
272
+ """
273
+ try:
274
+ with zipfile.ZipFile(path) as z:
275
+ data = read_xml_member(z, "content.xml", max_bytes=MAX_XML_MEMBER)
276
+ return len(safe_fromstring(data).findall(f".//{_TABLE_TAG}"))
277
+ except (ArchiveLimitError, KeyError, OSError, zipfile.BadZipFile,
278
+ etree.XMLSyntaxError):
279
+ return 0
280
+
281
+
282
+ def _gate_formulas(path: Path, soffice: Path, tmpdir: Path) -> tuple[bool, str]:
283
+ """Spreadsheets only: make LibreOffice *compute*, then read *every* result.
284
+
285
+ Converting to PDF proves the file opens. It does not prove the formulas
286
+ work — a sheet full of ``#NAME?`` renders to a perfectly valid PDF. Round-
287
+ tripping through CSV forces evaluation and hands back the computed values as
288
+ text, where a broken formula is visible.
289
+
290
+ Every sheet is exported and scanned, and the export is *counted* against the
291
+ workbook's own sheet count. If they disagree the gate fails rather than
292
+ reporting on the subset it happened to receive: a partial check reported as a
293
+ pass is the failure mode this gate exists to remove. HTML export is the
294
+ fallback for a LibreOffice too old for the all-sheets CSV token — it writes
295
+ every sheet into one document.
296
+ """
297
+ expected = _sheet_count(path)
298
+ if expected == 0:
299
+ return False, "could not read the sheet list from content.xml"
300
+
301
+ outdir = tmpdir / "calc"
302
+ outdir.mkdir(parents=True, exist_ok=True)
303
+ proc = run_soffice_convert(soffice, path, _CSV_ALL_SHEETS, outdir)
304
+ produced = sorted(outdir.glob("*.csv"))
305
+ if proc.returncode != 0 or not produced:
306
+ stderr = (proc.stderr or proc.stdout or "").strip()
307
+ return False, f"soffice could not evaluate the sheets: {stderr[:300]}"
308
+
309
+ if len(produced) < expected:
310
+ # This LibreOffice ignored the all-sheets token. Fall back rather than
311
+ # quietly grade the workbook on its first sheet.
312
+ htmldir = tmpdir / "calc-html"
313
+ htmldir.mkdir(parents=True, exist_ok=True)
314
+ html_proc = run_soffice_convert(soffice, path, "html", htmldir)
315
+ exported = sorted(htmldir.glob("*.htm*"))
316
+ if html_proc.returncode != 0 or not exported:
317
+ return False, (
318
+ f"only {len(produced)} of {expected} sheets could be evaluated; "
319
+ "refusing to certify the rest unchecked"
320
+ )
321
+ produced = exported
322
+
323
+ errors: dict[str, list[str]] = {}
324
+ for exported in produced:
325
+ found = _scan_calc_errors(
326
+ exported.read_text(encoding="utf-8", errors="replace")
327
+ )
328
+ if found:
329
+ errors[exported.stem] = found
330
+ if errors:
331
+ detail = "; ".join(
332
+ f"{name}: {', '.join(tokens)}" for name, tokens in sorted(errors.items())
333
+ )
334
+ return False, (
335
+ f"LibreOffice computed formula errors in {len(errors)} of {expected} "
336
+ f"sheet(s) — {detail} — the file opens but its numbers are wrong"
337
+ )
338
+ return True, f"formulas evaluated without errors across {expected} sheet(s)"
339
+
340
+
341
+ def _gate_soffice(path: Path, soffice: Path) -> tuple[bool, str]:
342
+ """Gate 3: round-trip through soffice --convert-to pdf.
343
+
344
+ For ``.ods`` the gate additionally makes LibreOffice evaluate the sheet and
345
+ checks the computed cells for error values — opening cleanly is a weaker
346
+ claim than computing correctly, and only the latter is worth certifying.
347
+ """
348
+ tmpdir = Path(tempfile.mkdtemp(prefix="odforge-validate-"))
349
+ try:
350
+ proc = run_soffice_convert(soffice, path, "pdf", tmpdir)
351
+ if proc.returncode != 0:
352
+ stderr = (proc.stderr or proc.stdout or "").strip()
353
+ return False, f"soffice exited {proc.returncode}: {stderr[:500]}"
354
+ pdf = tmpdir / (path.stem + ".pdf")
355
+ if not pdf.exists():
356
+ stderr = (proc.stderr or proc.stdout or "").strip()
357
+ return False, f"soffice produced no pdf: {stderr[:500]}"
358
+ detail = f"converted to pdf ({pdf.stat().st_size} bytes)"
359
+ if path.suffix.lower() == ".ods":
360
+ ok, message = _gate_formulas(path, soffice, tmpdir)
361
+ if not ok:
362
+ return False, message
363
+ detail = f"{detail}; {message}"
364
+ return True, detail
365
+ except subprocess.TimeoutExpired:
366
+ return False, f"soffice timed out after {_SOFFICE_TIMEOUT}s"
367
+ finally:
368
+ shutil.rmtree(tmpdir, ignore_errors=True)
369
+
370
+
371
+ def validate_odf(path: Path, *, with_soffice: bool = False) -> ValidationReport:
372
+ """Validate an ODF file through the structure/xml/(soffice) gates.
373
+
374
+ Never raises: any unexpected exception inside a gate becomes a
375
+ ``(False, message)`` result for that gate. Gates run independently so a
376
+ failure in an earlier gate does not stop later gates from reporting.
377
+ """
378
+ path = Path(path)
379
+ gates: dict[str, tuple[bool, str]] = {}
380
+
381
+ for name, fn in (("structure", _gate_structure), ("xml", _gate_xml)):
382
+ try:
383
+ gates[name] = fn(path)
384
+ except Exception as exc:
385
+ gates[name] = (False, f"{name} gate raised {type(exc).__name__}: {exc}")
386
+
387
+ if with_soffice and not all(
388
+ gates[gate][0] for gate in ("structure", "xml")
389
+ ):
390
+ gates["soffice"] = (
391
+ False,
392
+ "skipped because structure or xml preflight failed",
393
+ )
394
+ elif with_soffice:
395
+ soffice = find_soffice()
396
+ if soffice is not None:
397
+ try:
398
+ gates["soffice"] = _gate_soffice(path, soffice)
399
+ except Exception as exc:
400
+ gates["soffice"] = (False, f"soffice gate raised {type(exc).__name__}: {exc}")
401
+
402
+ ok = all(passed for passed, _ in gates.values())
403
+ return ValidationReport(ok=ok, gates=gates)
odforge/watch.py ADDED
@@ -0,0 +1,266 @@
1
+ """Live preview (``odforge preview``): watch a Document IR file, keep the cockpit current.
2
+
3
+ In this mode ODForge writes no content. The user's own agent (Claude Code,
4
+ Codex…) edits a presentation IR file on disk; every time the file changes, this
5
+ module re-renders it, lays it out with LibreOffice, and pushes the result to the
6
+ web cockpit that is already open in the browser — pages, the format gates, and
7
+ where text overflows (跑版). LibreOffice never shows a window: it only renders.
8
+
9
+ The cockpit is reused as is. A preview is an ordinary :class:`~odforge.webapi.Job`
10
+ marked ``watching``: each reload replaces its event log with a fresh, complete
11
+ one (``reload`` → ``outline`` → pages → gates → previews → ``layout_report`` →
12
+ ``complete``), so a browser that connects at any moment replays exactly the
13
+ current version and nothing older.
14
+
15
+ A file that does not parse (a half-written save, a schema error) does not wipe
16
+ the screen: the last good version stays up and an ``error`` event says what is
17
+ wrong with the new one.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import contextlib
24
+ import json
25
+ import os
26
+ import shutil
27
+ import tempfile
28
+ import time
29
+ import uuid
30
+ from pathlib import Path
31
+ from typing import Any, AsyncIterator, Callable, Optional, Tuple
32
+
33
+ from fastapi import FastAPI
34
+ from pydantic import ValidationError
35
+
36
+ from .ir import Outline, PageRole, Presentation, parse_ir
37
+ from .layoutcheck import LayoutReport, check_layout_pdf
38
+ from .preview import PreviewUnavailable, convert_to_pdf, rasterise_pdf
39
+ from .render import render
40
+ from .validate import validate_odf
41
+ from .webapi import (
42
+ Job,
43
+ _download_url,
44
+ _emit,
45
+ _emit_gate,
46
+ _preview_url,
47
+ _prune_preview_versions,
48
+ create_app,
49
+ )
50
+
51
+ POLL_SECONDS = 0.4
52
+ # An agent's save may land in several writes; wait for the file to sit still
53
+ # this long before reading it, so a half-written file is the exception.
54
+ SETTLE_SECONDS = 0.3
55
+
56
+ _DESIGN_NOTE = "預覽模式:內容由你的 agent 撰寫,不跑視覺審稿;版面問題請看跑版檢查。"
57
+
58
+
59
+ class SourceError(ValueError):
60
+ """The watched file could not be turned into a presentation (shown to the user)."""
61
+
62
+
63
+ def outline_for(ir: Presentation) -> Outline:
64
+ """The outline rail's rows, derived from the deck itself (no stage 1 here)."""
65
+ return Outline(
66
+ design=ir.design,
67
+ style=ir.style,
68
+ mode=ir.design.mode if ir.design is not None else "presenter",
69
+ pages=[
70
+ PageRole(
71
+ role=slide.layout,
72
+ title=slide.title,
73
+ gist=(slide.subtitle or slide.title or slide.layout)[:600],
74
+ )
75
+ for slide in ir.slides
76
+ ],
77
+ )
78
+
79
+
80
+ def load_presentation(source: Path) -> Presentation:
81
+ """Read and validate the watched file, with errors a person can act on."""
82
+ try:
83
+ data = json.loads(source.read_text(encoding="utf-8"))
84
+ except FileNotFoundError as exc:
85
+ raise SourceError(f"找不到 {source}") from exc
86
+ except json.JSONDecodeError as exc:
87
+ raise SourceError(f"{source.name} 不是合法的 JSON(第 {exc.lineno} 行):{exc.msg}") from exc
88
+ if not isinstance(data, dict):
89
+ raise SourceError(f"{source.name} 的最外層必須是 JSON 物件")
90
+ data.setdefault("type", "presentation")
91
+ try:
92
+ ir = parse_ir(data)
93
+ except ValidationError as exc:
94
+ problems = "; ".join(
95
+ f"{'.'.join(str(p) for p in err['loc'])}: {err['msg']}"
96
+ for err in exc.errors()[:5]
97
+ )
98
+ raise SourceError(f"{source.name} 不符合簡報格式:{problems}") from exc
99
+ if not isinstance(ir, Presentation):
100
+ raise SourceError("預覽目前只支援簡報(type 必須是 presentation)")
101
+ return ir
102
+
103
+
104
+ def _render_and_measure(
105
+ ir: Presentation, job: Job, version_dir: Path
106
+ ) -> Tuple[dict, list, str, LayoutReport]:
107
+ """Blocking half of a reload: render, validate, rasterise, measure.
108
+
109
+ Returns ``(gates, pngs, libreoffice_status, layout)``. Raises
110
+ :class:`SourceError` when the deck fails a blocking gate.
111
+ """
112
+ candidate = job.dir / "deck.candidate.odp"
113
+ render(ir, candidate)
114
+ report = validate_odf(candidate)
115
+ gates = {
116
+ "zip": "pass" if report.gates["structure"][0] else "fail",
117
+ "xml": "pass" if report.gates["xml"][0] else "fail",
118
+ }
119
+ if "fail" in gates.values():
120
+ problems = "; ".join(m for ok, m in report.gates.values() if not ok)
121
+ candidate.unlink(missing_ok=True)
122
+ raise SourceError(f"產出的檔案沒有通過格式驗證:{problems}")
123
+ os.replace(candidate, job.odp_path)
124
+
125
+ workdir = Path(tempfile.mkdtemp(prefix="odforge-watch-"))
126
+ try:
127
+ try:
128
+ pdf = convert_to_pdf(job.odp_path, workdir)
129
+ except PreviewUnavailable:
130
+ return gates, [], "skipped", LayoutReport(
131
+ "unavailable", "找不到 LibreOffice(soffice),無法預覽與檢查跑版"
132
+ )
133
+ except Exception as exc:
134
+ return gates, [], "fail", LayoutReport(
135
+ "unavailable", f"LibreOffice 轉檔失敗:{exc}"
136
+ )
137
+ shutil.rmtree(version_dir, ignore_errors=True)
138
+ pngs = rasterise_pdf(pdf, version_dir)
139
+ return gates, pngs, "pass", check_layout_pdf(job.odp_path, pdf)
140
+ finally:
141
+ shutil.rmtree(workdir, ignore_errors=True)
142
+
143
+
144
+ Announce = Callable[[str], None]
145
+
146
+
147
+ async def reload(
148
+ job: Job, source: Path, out: Optional[Path], announce: Optional[Announce] = None
149
+ ) -> None:
150
+ """Re-render ``source`` and replace the job's event log with the new version.
151
+
152
+ ``announce`` receives a short plain-text summary of each outcome. The agent
153
+ that started ``odforge preview`` cannot see the browser; this is how it
154
+ learns which page overflowed without asking the user.
155
+ """
156
+ say = announce or (lambda _text: None)
157
+ try:
158
+ ir = load_presentation(source)
159
+ gates, pngs, libreoffice, layout = await asyncio.to_thread(
160
+ _render_and_measure, ir, job, job.preview_dir_for(job.preview_version + 1)
161
+ )
162
+ except SourceError as exc:
163
+ # Keep the last good version on screen; say what is wrong with this one.
164
+ job.error = {"message": str(exc), "stage": "source"}
165
+ await _emit(job, "error", job.error)
166
+ say(f"讀不進來,畫面維持上一版:{exc}")
167
+ return
168
+
169
+ job.ir = ir
170
+ job.outline = outline_for(ir)
171
+ job.error = None
172
+ job.artifact_version += 1
173
+ job.validated_version = job.artifact_version
174
+ if pngs:
175
+ job.preview_version += 1
176
+ _prune_preview_versions(job)
177
+ if out is not None:
178
+ out.parent.mkdir(parents=True, exist_ok=True)
179
+ shutil.copyfile(job.odp_path, out)
180
+
181
+ # Swap in a fresh log; open streams see the epoch change and replay it.
182
+ job.events = []
183
+ job.event_epoch += 1
184
+ job.gates = {}
185
+ job.status = "rendering"
186
+ await _emit(job, "reload", {"source": source.name, "out": str(out) if out else None})
187
+ await _emit(job, "outline", job.outline.model_dump(mode="json"))
188
+ for n, slide in enumerate(ir.slides, start=1):
189
+ payload = {"n": n, "slide": slide.model_dump(mode="json")}
190
+ await _emit(job, "slide_done", payload)
191
+ for gate, status in gates.items():
192
+ await _emit_gate(job, gate, status)
193
+ await _emit_gate(job, "libreoffice", libreoffice)
194
+ for n in range(1, len(pngs) + 1):
195
+ await _emit(job, "preview_ready", {"n": n, "url": _preview_url(job, n)})
196
+ await _emit(
197
+ job,
198
+ "layout_report",
199
+ {
200
+ "status": layout.status,
201
+ "message": layout.message,
202
+ "findings": [
203
+ {"slide_no": f.page, "issue": f.detail()} for f in layout.findings
204
+ ],
205
+ },
206
+ )
207
+ await _emit_gate(job, "design", "skipped", _DESIGN_NOTE)
208
+ job.status = "complete"
209
+ job.finished_at = time.time()
210
+ await _emit(job, "complete", {"download_url": _download_url(job)})
211
+
212
+ summary = f"第 {job.artifact_version} 版:{len(ir.slides)} 頁,{layout.message}"
213
+ say("\n".join([summary, *(f" - {f.describe()}" for f in layout.findings)]))
214
+
215
+
216
+ def _stamp(source: Path) -> Optional[Tuple[int, int]]:
217
+ try:
218
+ stat = source.stat()
219
+ except OSError:
220
+ return None
221
+ return stat.st_mtime_ns, stat.st_size
222
+
223
+
224
+ async def watch_loop(
225
+ job: Job, source: Path, out: Optional[Path], announce: Optional[Announce] = None
226
+ ) -> None:
227
+ """Reload whenever ``source`` changes (and once at start)."""
228
+ last: Any = object()
229
+ while True:
230
+ stamp = _stamp(source)
231
+ if stamp != last:
232
+ await asyncio.sleep(SETTLE_SECONDS)
233
+ if _stamp(source) == stamp:
234
+ last = stamp
235
+ await reload(job, source, out, announce)
236
+ continue
237
+ await asyncio.sleep(POLL_SECONDS)
238
+
239
+
240
+ def create_preview_app(
241
+ source: Path,
242
+ out: Optional[Path],
243
+ jobs_dir: Optional[Path] = None,
244
+ announce: Optional[Announce] = None,
245
+ ) -> Tuple[FastAPI, Job]:
246
+ """A cockpit app with one watching job for ``source``; the watcher runs with it."""
247
+ source = Path(source).resolve()
248
+ out = Path(out).resolve() if out is not None else None
249
+ base = Path(jobs_dir) if jobs_dir else Path(tempfile.mkdtemp(prefix="odforge-preview-"))
250
+ job_id = uuid.uuid4().hex
251
+ job = Job(id=job_id, dir=base / job_id, prompt=f"預覽 {source.name}", watching=True)
252
+ job.dir.mkdir(parents=True, exist_ok=True)
253
+
254
+ @contextlib.asynccontextmanager
255
+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
256
+ task = asyncio.create_task(watch_loop(job, source, out, announce))
257
+ try:
258
+ yield
259
+ finally:
260
+ task.cancel()
261
+ with contextlib.suppress(asyncio.CancelledError):
262
+ await task
263
+
264
+ app = create_app(base, lifespan=lifespan)
265
+ app.state.jobs[job.id] = job
266
+ return app, job