@dickpy/dsh-oil-slide 0.0.0-stage → 0.2.7

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 (97) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +89 -2
  3. package/bundled-assets/brand/empty-deck-cobalt.webp +0 -0
  4. package/bundled-assets/brand/oil-slide-mark-512.png +0 -0
  5. package/bundled-assets/skill/LICENSE +21 -0
  6. package/bundled-assets/skill/README.md +61 -0
  7. package/bundled-assets/skill/SKILL.md +185 -0
  8. package/bundled-assets/skill/references/art-directions.md +99 -0
  9. package/bundled-assets/skill/references/brand-and-canvas.md +72 -0
  10. package/bundled-assets/skill/references/design-baseline.txt +1 -0
  11. package/bundled-assets/skill/references/prompt-compiler.md +99 -0
  12. package/bundled-assets/skill/references/restore-and-pptx.md +178 -0
  13. package/bundled-assets/skill/references/staged-pptx.md +71 -0
  14. package/bundled-assets/skill/scripts/_runtime_utils.py +351 -0
  15. package/bundled-assets/skill/scripts/asset_sheet.py +528 -0
  16. package/bundled-assets/skill/scripts/brand_ref.py +776 -0
  17. package/bundled-assets/skill/scripts/crop_asset.py +1709 -0
  18. package/bundled-assets/skill/scripts/deck_shell.py +2322 -0
  19. package/bundled-assets/skill/scripts/export_images.py +280 -0
  20. package/bundled-assets/skill/scripts/extract_pptx.py +360 -0
  21. package/bundled-assets/skill/scripts/extract_slide_dom.js +1640 -0
  22. package/bundled-assets/skill/scripts/html_to_pptx.py +4042 -0
  23. package/bundled-assets/skill/scripts/measure_slide_layout.py +952 -0
  24. package/bundled-assets/skill/scripts/oiloil-connect.mjs +1493 -0
  25. package/bundled-assets/skill/scripts/oiloil-image.mjs +492 -0
  26. package/bundled-assets/skill/scripts/prepare_plate.py +412 -0
  27. package/bundled-assets/skill/scripts/render_gradient.py +258 -0
  28. package/bundled-assets/skill/scripts/slide_brand.py +111 -0
  29. package/bundled-assets/skill/scripts/slide_incremental.py +122 -0
  30. package/bundled-assets/skill/scripts/slide_workflow.py +711 -0
  31. package/bundled-assets/skill/scripts/verify_deck.py +3483 -0
  32. package/bundled-assets/skill/vendor/README.md +4 -0
  33. package/bundled-assets/skill/vendor/codex-ppt/LICENSE +21 -0
  34. package/bundled-assets/skill/vendor/codex-ppt/assemble_ppt.py +435 -0
  35. package/bundled-assets/skill/vendor/codex-ppt/codex_ppt_runtime.py +284 -0
  36. package/bundled-assets/skill/vendor/codex-ppt/image_gen.py +972 -0
  37. package/bundled-assets/skill/vendor/codex-ppt/image_providers/__init__.py +6 -0
  38. package/bundled-assets/skill/vendor/codex-ppt/image_providers/atlascloud.py +222 -0
  39. package/bundled-assets/skill/vendor/codex-ppt/image_providers/base.py +32 -0
  40. package/bundled-assets/skill/vendor/codex-ppt/image_providers/factory.py +21 -0
  41. package/bundled-assets/skill/vendor/codex-ppt/image_providers/openai_compatible.py +238 -0
  42. package/bundled-assets/skill/vendor/codex-ppt/requirements.txt +5 -0
  43. package/bundled-assets/skill/vendor/codex-ppt/styles//345/205/232/346/224/277/347/272/242/351/243/216/346/240/274.md +98 -0
  44. package/bundled-assets/skill/vendor/codex-ppt/styles//345/210/233/346/204/217/346/235/202/345/277/227/351/243/216.md +72 -0
  45. package/bundled-assets/skill/vendor/codex-ppt/styles//345/244/215/345/217/244/346/211/201/345/271/263/346/217/222/347/224/273/351/243/216.md +72 -0
  46. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/346/212/200/346/234/257/350/247/243/351/207/212/351/243/216.md +86 -0
  47. package/bundled-assets/skill/vendor/codex-ppt/styles//346/211/213/347/273/230/347/231/275/346/235/277/351/243/216.md +72 -0
  48. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/231/345/255/246/350/257/276/344/273/266/351/243/216.md +107 -0
  49. package/bundled-assets/skill/vendor/codex-ppt/styles//346/225/260/346/215/256/344/273/252/350/241/250/347/233/230/351/243/216.md +73 -0
  50. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/205/347/210/275/344/270/223/344/270/232/351/243/216.md +87 -0
  51. package/bundled-assets/skill/vendor/codex-ppt/styles//346/270/251/346/232/226/346/211/213/345/267/245/351/243/216.md +72 -0
  52. package/bundled-assets/skill/vendor/codex-ppt/styles//347/224/265/345/255/220/345/242/250/346/260/264/346/235/202/345/277/227/351/243/216.md +86 -0
  53. package/bundled-assets/skill/vendor/codex-ppt/styles//347/247/221/347/240/224/347/255/224/350/276/251/351/243/216.md +138 -0
  54. package/bundled-assets/skill/vendor/codex-ppt/styles//351/272/246/350/202/257/351/224/241/351/243/216/346/240/274.md +119 -0
  55. package/bundled-assets/skill/vendor/image-to-editable-ppt/LICENSE +21 -0
  56. package/bundled-assets/skill/vendor/image-to-editable-ppt/SKILL.md +171 -0
  57. package/bundled-assets/skill/vendor/image-to-editable-ppt/agents/openai.yaml +4 -0
  58. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/__init__.py +1 -0
  59. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/cli.py +25 -0
  60. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/__init__.py +1 -0
  61. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_input_normalization.py +355 -0
  62. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/_page_artifacts.py +132 -0
  63. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/build_pptx_from_manifest.py +1029 -0
  64. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/configure_image_backend.py +52 -0
  65. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_run_state.py +214 -0
  66. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/deck_text_hints.py +179 -0
  67. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/finalize_deck_run.py +96 -0
  68. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/formula_renderer.py +254 -0
  69. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/image_gen.py +206 -0
  70. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/main.py +795 -0
  71. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/make_page_contact_sheet.py +28 -0
  72. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/native_tables.py +140 -0
  73. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/paddle_text_hints.py +212 -0
  74. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_job_status.py +54 -0
  75. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/page_text_metrics.py +334 -0
  76. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/path_geometry.py +174 -0
  77. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/prepare_deck_run.py +209 -0
  78. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/process_asset_sheet.py +104 -0
  79. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_imagegen_result.py +118 -0
  80. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_dispatch.py +83 -0
  81. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/record_page_result.py +130 -0
  82. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/remove_chroma_key.py +441 -0
  83. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/reset_page_job.py +74 -0
  84. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/runtime_env.py +283 -0
  85. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/split_alpha_components.py +323 -0
  86. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/text_hints.py +309 -0
  87. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/editppt/runtime/validate_pptx.py +873 -0
  88. package/bundled-assets/skill/vendor/image-to-editable-ppt/cli/pyproject.toml +29 -0
  89. package/bundled-assets/skill/vendor/image-to-editable-ppt/prompts/page-worker.md +47 -0
  90. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/cli-helper.md +282 -0
  91. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/manifest-schema.md +423 -0
  92. package/bundled-assets/skill/vendor/image-to-editable-ppt/references/page-decision-tree.md +301 -0
  93. package/bundled-assets/skill/vendor/image-to-editable-ppt/scripts/build-page-worker-prompt.py +134 -0
  94. package/cordis.patch.yml +3 -0
  95. package/lib/client.js +11282 -0
  96. package/lib/index.js +2638 -0
  97. package/package.json +140 -4
@@ -0,0 +1,3483 @@
1
+ #!/usr/bin/env python3
2
+ """Visual and structural verification for generated HTML decks and native PPTX files.
3
+
4
+ Captures headless Chrome/Chromium screenshots of `?slide=1..N`, runs a
5
+ programmatic python-pptx structural audit, renders PPTX slides via LibreOffice
6
+ (or macOS Keynote PDF export + pdftoppm), and stitches side-by-side comparison sheets.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import functools
12
+ import hashlib
13
+ import html
14
+ import http.server
15
+ import json
16
+ import math
17
+ import os
18
+ import re
19
+ import shutil
20
+ import socketserver
21
+ import statistics
22
+ import subprocess
23
+ import sys
24
+ import tempfile
25
+ import threading
26
+ import time
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ from PIL import Image, ImageChops, ImageStat
31
+
32
+ _SCRIPTS_DIR = Path(__file__).resolve().parent
33
+ if str(_SCRIPTS_DIR) not in sys.path:
34
+ sys.path.insert(0, str(_SCRIPTS_DIR))
35
+ import crop_asset as ca
36
+ import measure_slide_layout as msl
37
+
38
+
39
+ def _load_sibling_module(module_stem: str) -> Any | None:
40
+ cand_res = (Path(__file__).resolve().parent / f"{module_stem}.py").resolve()
41
+ private_name = f"_oil_slide_{module_stem.lstrip('_')}"
42
+ for mod_name in (private_name, module_stem):
43
+ mod = sys.modules.get(mod_name)
44
+ mod_file = getattr(mod, "__file__", None) if mod is not None else None
45
+ if mod_file:
46
+ try:
47
+ if Path(mod_file).resolve() == cand_res:
48
+ return mod
49
+ except OSError:
50
+ pass
51
+ if not os.path.isfile(cand_res):
52
+ return None
53
+ try:
54
+ import importlib.util
55
+
56
+ spec = importlib.util.spec_from_file_location(private_name, cand_res)
57
+ if spec is None or spec.loader is None:
58
+ return None
59
+ mod = importlib.util.module_from_spec(spec)
60
+ sys.modules[private_name] = mod
61
+ spec.loader.exec_module(mod)
62
+ return mod
63
+ except Exception:
64
+ return None
65
+
66
+
67
+ def _load_runtime_utils() -> Any | None:
68
+ return _load_sibling_module("_runtime_utils")
69
+
70
+
71
+ def _configure_utf8_stdio() -> None:
72
+ ru = _load_runtime_utils()
73
+ if ru is not None:
74
+ ru.configure_utf8_stdio()
75
+ return
76
+ for stream in (sys.stdout, sys.stderr):
77
+ if stream is not None:
78
+ try:
79
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
80
+ stream.reconfigure(encoding="utf-8", errors="replace")
81
+ except Exception:
82
+ pass
83
+
84
+
85
+ def _launch_chromium(
86
+ playwright_obj: Any,
87
+ *,
88
+ headless: bool = True,
89
+ args: list[str] | None = None,
90
+ executable_path: str | None = None,
91
+ discover_system: bool = False,
92
+ ) -> Any:
93
+ ru = _load_runtime_utils()
94
+ if ru is not None:
95
+ return ru.launch_chromium(
96
+ playwright_obj,
97
+ headless=headless,
98
+ args=args,
99
+ executable_path=executable_path,
100
+ discover_system=discover_system,
101
+ )
102
+ launch_kwargs: dict[str, Any] = {"headless": headless}
103
+ if args is not None:
104
+ launch_kwargs["args"] = list(args)
105
+ if executable_path:
106
+ launch_kwargs["executable_path"] = executable_path
107
+ return playwright_obj.chromium.launch(**launch_kwargs)
108
+
109
+
110
+ def find_chrome_binary(explicit: str | None = None) -> str | None:
111
+ ru = _load_runtime_utils()
112
+ if ru is not None:
113
+ return ru.find_chrome_binary(explicit)
114
+ if explicit and Path(explicit).is_file():
115
+ return explicit
116
+ env_bin = os.environ.get("CHROME_BIN") or os.environ.get("CHROMIUM_BIN")
117
+ if env_bin and Path(env_bin).is_file():
118
+ return env_bin
119
+
120
+ for cmd in ("google-chrome", "chromium", "chromium-browser", "chrome", "msedge"):
121
+ found = shutil.which(cmd)
122
+ if found:
123
+ return found
124
+
125
+ candidates = [
126
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
127
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
128
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
129
+ "/usr/bin/google-chrome",
130
+ "/usr/bin/chromium",
131
+ "/usr/bin/chromium-browser",
132
+ "C:/Program Files/Google/Chrome/Application/chrome.exe",
133
+ "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",
134
+ ]
135
+ for path in candidates:
136
+ if Path(path).is_file():
137
+ return path
138
+ return None
139
+
140
+
141
+ def find_soffice() -> str | None:
142
+ for candidate in (
143
+ shutil.which("soffice"),
144
+ shutil.which("libreoffice"),
145
+ "/Applications/LibreOffice.app/Contents/MacOS/soffice",
146
+ "/usr/bin/soffice",
147
+ "/usr/bin/libreoffice",
148
+ "C:/Program Files/LibreOffice/program/soffice.exe",
149
+ ):
150
+ if candidate and Path(candidate).is_file():
151
+ return str(candidate)
152
+ return None
153
+
154
+
155
+ class _QuietHandler(http.server.SimpleHTTPRequestHandler):
156
+ def do_GET(self) -> None:
157
+ if self.path.split("?", 1)[0] == "/favicon.ico":
158
+ self.send_response(204)
159
+ self.end_headers()
160
+ return
161
+ super().do_GET()
162
+
163
+ def log_message(self, format: str, *args: Any) -> None:
164
+ pass
165
+
166
+
167
+ class _ThreadingStaticServer(socketserver.ThreadingTCPServer):
168
+ allow_reuse_address = True
169
+ daemon_threads = True
170
+ request_queue_size = 64
171
+
172
+
173
+ def _start_static_server(root: Path) -> tuple[socketserver.TCPServer, int]:
174
+ handler = functools.partial(_QuietHandler, directory=str(root))
175
+ server = _ThreadingStaticServer(("127.0.0.1", 0), handler)
176
+ port = int(server.server_address[1])
177
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
178
+ thread.start()
179
+ return server, port
180
+
181
+
182
+ def _infer_serve_root(html_path: Path, spec_path: Path | None) -> tuple[Path, str]:
183
+ html_abs = html_path.resolve()
184
+ candidates = [html_abs.parent]
185
+ if html_abs.parent.parent != html_abs.parent:
186
+ candidates.append(html_abs.parent.parent)
187
+ if spec_path:
188
+ spec_abs = spec_path.resolve()
189
+ try:
190
+ common = Path(os.path.commonpath([str(html_abs.parent), str(spec_abs.parent)]))
191
+ candidates.append(common)
192
+ except ValueError:
193
+ pass
194
+ # Prefer the ancestor containing both html and assets/ or spec/
195
+ root = html_abs.parent
196
+ for cand in candidates:
197
+ if (cand / "assets").is_dir() or (cand / "spec").is_dir():
198
+ root = cand
199
+ break
200
+ rel_url = html_abs.relative_to(root).as_posix()
201
+ return root, rel_url
202
+
203
+
204
+ def _detect_verify_canvas_size(
205
+ *,
206
+ spec_path: Path | None = None,
207
+ html_path: Path | None = None,
208
+ ref_paths: list[Path | None] | None = None,
209
+ pptx_path: Path | None = None,
210
+ ratio: str | None = None,
211
+ width: int | None = None,
212
+ height: int | None = None,
213
+ ) -> tuple[int, int]:
214
+ if width is not None and height is not None and int(width) > 0 and int(height) > 0:
215
+ return int(width), int(height)
216
+ if ratio:
217
+ cw, ch, _ = msl.resolve_measure_canvas(1920, 1080, ratio=ratio)
218
+ return cw, ch
219
+ if spec_path and spec_path.is_file():
220
+ try:
221
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
222
+ if isinstance(spec, dict):
223
+ c = spec.get("canvas")
224
+ if isinstance(c, dict) and c.get("width") and c.get("height"):
225
+ return int(c["width"]), int(c["height"])
226
+ r_tok = spec.get("ratio") or spec.get("aspect_ratio") or (c.get("ratio") if isinstance(c, dict) else None)
227
+ if r_tok:
228
+ cw, ch, _ = msl.resolve_measure_canvas(1920, 1080, ratio=str(r_tok))
229
+ return cw, ch
230
+ except Exception:
231
+ pass
232
+ if html_path and html_path.is_file():
233
+ try:
234
+ txt = html_path.read_text(encoding="utf-8", errors="ignore")
235
+ m_data = re.search(r'\bdata-canvas\s*=\s*["\'](\d+)x(\d+)["\']', txt, re.I)
236
+ if m_data:
237
+ return int(m_data.group(1)), int(m_data.group(2))
238
+ m_ratio = re.search(r'\bdata-ratio\s*=\s*["\']([^"\']+)["\']', txt, re.I)
239
+ if m_ratio:
240
+ cw, ch, _ = msl.resolve_measure_canvas(1920, 1080, ratio=m_ratio.group(1))
241
+ return cw, ch
242
+ m_page = re.search(r"@page\s*\{\s*size\s*:\s*(\d+)px\s+(\d+)px", txt, re.I)
243
+ if m_page:
244
+ return int(m_page.group(1)), int(m_page.group(2))
245
+ m_stage = re.search(
246
+ r"\.(?:deck-stage|slide)\s*\{[^}]*?\bwidth\s*:\s*(\d+)px\s*;[^}]*?\bheight\s*:\s*(\d+)px",
247
+ txt,
248
+ re.I | re.S,
249
+ )
250
+ if m_stage:
251
+ return int(m_stage.group(1)), int(m_stage.group(2))
252
+ except Exception:
253
+ pass
254
+ if ref_paths:
255
+ for rp in ref_paths:
256
+ if rp and rp.is_file():
257
+ try:
258
+ with Image.open(rp) as im:
259
+ cw, ch, _ = msl.resolve_measure_canvas(im.width, im.height)
260
+ return cw, ch
261
+ except Exception:
262
+ pass
263
+ if pptx_path and pptx_path.is_file():
264
+ try:
265
+ from pptx import Presentation
266
+
267
+ prs = Presentation(str(pptx_path))
268
+ cw, ch, _ = msl.resolve_measure_canvas(int(prs.slide_width), int(prs.slide_height))
269
+ return cw, ch
270
+ except Exception:
271
+ pass
272
+ return 1920, 1080
273
+
274
+
275
+ _BLOCKED_EXTERNAL_FONT_HOSTS = (
276
+ "fonts.googleapis.com",
277
+ "fonts.gstatic.com",
278
+ "use.typekit.net",
279
+ "p.typekit.net",
280
+ "fonts.bunny.net",
281
+ "fast.fonts.net",
282
+ "fonts.loli.net",
283
+ "fonts.font.im",
284
+ "fonts.cat.net",
285
+ )
286
+
287
+
288
+ def _attach_local_font_route_guard(context: Any) -> None:
289
+ """Abort slow/blocked external webfont requests during headless capture; local CJK/Latin fonts are bundled."""
290
+ def _route_handler(route: Any) -> None:
291
+ req = route.request
292
+ req_url = str(getattr(req, "url", "") or "").lower()
293
+ is_local = req_url.startswith(
294
+ ("http://127.0.0.1", "http://localhost", "data:", "blob:", "file:")
295
+ )
296
+ res_type = str(getattr(req, "resource_type", "") or "").lower()
297
+ if not is_local and (
298
+ res_type == "font"
299
+ or any(host in req_url for host in _BLOCKED_EXTERNAL_FONT_HOSTS)
300
+ ):
301
+ route.abort("blockedbyclient")
302
+ return
303
+ route.continue_()
304
+
305
+ try:
306
+ context.route("**/*", _route_handler)
307
+ except Exception:
308
+ pass
309
+
310
+
311
+ def _safe_page_screenshot(page: Any, out_path: Path, *, timeout_ms: int = 15000) -> None:
312
+ """Capture viewport screenshot with animations disabled and CDP fallback if Playwright font-wait times out."""
313
+ try:
314
+ try:
315
+ page.screenshot(path=str(out_path), full_page=False, animations="disabled", timeout=timeout_ms)
316
+ except TypeError:
317
+ page.screenshot(path=str(out_path), full_page=False)
318
+ return
319
+ except Exception as exc:
320
+ if "timeout" not in str(exc).lower() and "timeout" not in type(exc).__name__.lower():
321
+ raise
322
+ # Fallback: CDP Page.captureScreenshot grabs the rendered frame directly without blocking on hung webfont promises.
323
+ import base64
324
+
325
+ cdp = page.context.new_cdp_session(page)
326
+ try:
327
+ cdp_params: dict[str, Any] = {"format": "png", "fromSurface": True}
328
+ vp = getattr(page, "viewport_size", None)
329
+ if isinstance(vp, dict) and vp.get("width") and vp.get("height"):
330
+ cdp_params["clip"] = {
331
+ "x": 0,
332
+ "y": 0,
333
+ "width": int(vp["width"]),
334
+ "height": int(vp["height"]),
335
+ "scale": 1,
336
+ }
337
+ res = cdp.send("Page.captureScreenshot", cdp_params)
338
+ data_b64 = res.get("data") if isinstance(res, dict) else None
339
+ if not data_b64:
340
+ raise RuntimeError("CDP Page.captureScreenshot returned empty data")
341
+ out_path.write_bytes(base64.b64decode(data_b64))
342
+ finally:
343
+ try:
344
+ cdp.detach()
345
+ except Exception:
346
+ pass
347
+
348
+
349
+ def _srgb_channel_to_linear(channel: float) -> float:
350
+ v = max(0.0, min(1.0, float(channel) / 255.0))
351
+ return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
352
+
353
+
354
+ def _wcag_contrast_ratio(
355
+ rgb1: tuple[float, float, float],
356
+ rgb2: tuple[float, float, float],
357
+ ) -> float:
358
+ l1 = (
359
+ 0.2126 * _srgb_channel_to_linear(rgb1[0])
360
+ + 0.7152 * _srgb_channel_to_linear(rgb1[1])
361
+ + 0.0722 * _srgb_channel_to_linear(rgb1[2])
362
+ )
363
+ l2 = (
364
+ 0.2126 * _srgb_channel_to_linear(rgb2[0])
365
+ + 0.7152 * _srgb_channel_to_linear(rgb2[1])
366
+ + 0.0722 * _srgb_channel_to_linear(rgb2[2])
367
+ )
368
+ hi, lo = (l1, l2) if l1 >= l2 else (l2, l1)
369
+ return (hi + 0.05) / (lo + 0.05)
370
+
371
+
372
+ def _rgb_strip_stats(
373
+ samples: list[tuple[int, int, int]],
374
+ ) -> tuple[tuple[float, float, float], float] | None:
375
+ if not samples:
376
+ return None
377
+ rs = [p[0] for p in samples]
378
+ gs = [p[1] for p in samples]
379
+ bs = [p[2] for p in samples]
380
+ med = (float(statistics.median(rs)), float(statistics.median(gs)), float(statistics.median(bs)))
381
+ if len(samples) < 2:
382
+ return med, 0.0
383
+ max_std = max(statistics.pstdev(rs), statistics.pstdev(gs), statistics.pstdev(bs))
384
+ return med, float(max_std)
385
+
386
+
387
+ def evaluate_rendered_text_contrast(
388
+ shot_path: Path,
389
+ text_boxes: list[dict[str, Any]],
390
+ *,
391
+ canvas_w: int = 1920,
392
+ canvas_h: int = 1080,
393
+ ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
394
+ """Check rendered-pixel WCAG 2.1 contrast for visible text boxes against their local outer band.
395
+
396
+ Returns `(blocking_hits, warning_hits)`:
397
+ - blocking (`low-contrast-text`): min segment contrast < 2.2 on a locally uniform backdrop.
398
+ - warning (`borderline-contrast-text`): 2.2 <= min segment contrast < 3.0 for fontSize >= 20.
399
+ """
400
+ blocking_hits: list[dict[str, Any]] = []
401
+ warning_hits: list[dict[str, Any]] = []
402
+ if not text_boxes or not shot_path or not Path(shot_path).is_file():
403
+ return blocking_hits, warning_hits
404
+
405
+ try:
406
+ with Image.open(shot_path) as raw_im:
407
+ rgb_im = raw_im.convert("RGB")
408
+ img_w, img_h = rgb_im.size
409
+ px = rgb_im.load()
410
+ except Exception:
411
+ return blocking_hits, warning_hits
412
+
413
+ if img_w < 8 or img_h < 8:
414
+ return blocking_hits, warning_hits
415
+
416
+ sx = img_w / float(max(1, canvas_w))
417
+ sy = img_h / float(max(1, canvas_h))
418
+
419
+ for tb in text_boxes:
420
+ if not isinstance(tb, dict):
421
+ continue
422
+ text = str(tb.get("text") or "").strip()
423
+ if not text:
424
+ continue
425
+ color_rgb = tb.get("colorRgb")
426
+ if not isinstance(color_rgb, (list, tuple)) or len(color_rgb) < 3:
427
+ continue
428
+ try:
429
+ tr, tg, tb_c = float(color_rgb[0]), float(color_rgb[1]), float(color_rgb[2])
430
+ x = float(tb.get("x", 0.0))
431
+ y = float(tb.get("y", 0.0))
432
+ w = float(tb.get("w", 0.0))
433
+ h = float(tb.get("h", 0.0))
434
+ font_size = float(tb.get("fontSize", 0.0))
435
+ alpha = max(0.0, min(1.0, float(tb.get("alpha", 1.0))))
436
+ except (TypeError, ValueError):
437
+ continue
438
+
439
+ if font_size < 12.0 or w < 4.0 or h < 4.0:
440
+ continue
441
+ if x + w <= 0.0 or y + h <= 0.0 or x >= canvas_w or y >= canvas_h:
442
+ continue
443
+
444
+ cx0 = max(0.0, x)
445
+ cy0 = max(0.0, y)
446
+ cx1 = min(float(canvas_w), x + w)
447
+ cy1 = min(float(canvas_h), y + h)
448
+ eff_w = cx1 - cx0
449
+ eff_h = cy1 - cy0
450
+ if eff_w < 4.0 or eff_h < 4.0:
451
+ continue
452
+
453
+ ty0 = max(0, min(img_h - 1, int(round(cy0 * sy))))
454
+ ty1 = max(ty0 + 1, min(img_h, int(round(cy1 * sy))))
455
+
456
+ if eff_w < 160.0:
457
+ n_segs = 1
458
+ elif eff_w < 360.0:
459
+ n_segs = 2
460
+ else:
461
+ n_segs = 3
462
+
463
+ worst_contrast: float | None = None
464
+ worst_bg: tuple[float, float, float] | None = None
465
+ worst_seg_idx = 0
466
+
467
+ for seg_idx in range(n_segs):
468
+ seg_x0 = max(0, min(img_w - 1, int(round((cx0 + eff_w * seg_idx / n_segs) * sx))))
469
+ seg_x1 = max(seg_x0 + 1, min(img_w, int(round((cx0 + eff_w * (seg_idx + 1) / n_segs) * sx))))
470
+ col_step = max(1, (seg_x1 - seg_x0) // 40)
471
+
472
+ top_rows = range(max(0, ty0 - 6), max(0, ty0 - 1))
473
+ bot_rows = range(min(img_h, ty1 + 2), min(img_h, ty1 + 7))
474
+
475
+ top_samples = [px[xx, yy] for yy in top_rows for xx in range(seg_x0, seg_x1, col_step)]
476
+ bot_samples = [px[xx, yy] for yy in bot_rows for xx in range(seg_x0, seg_x1, col_step)]
477
+
478
+ if not top_samples and not bot_samples:
479
+ row_step = max(1, (ty1 - ty0) // 20)
480
+ left_cols = range(max(0, seg_x0 - 5), max(0, seg_x0 - 1))
481
+ right_cols = range(min(img_w, seg_x1 + 2), min(img_w, seg_x1 + 6))
482
+ top_samples = [px[xx, yy] for yy in range(ty0, ty1, row_step) for xx in left_cols]
483
+ bot_samples = [px[xx, yy] for yy in range(ty0, ty1, row_step) for xx in right_cols]
484
+
485
+ combined = top_samples + bot_samples
486
+ if not combined:
487
+ continue
488
+
489
+ comb_stat = _rgb_strip_stats(combined)
490
+ top_stat = _rgb_strip_stats(top_samples)
491
+ bot_stat = _rgb_strip_stats(bot_samples)
492
+
493
+ bg_med: tuple[float, float, float] | None = None
494
+ if comb_stat is not None and comb_stat[1] < 36.0:
495
+ bg_med = comb_stat[0]
496
+ elif top_stat is not None and bot_stat is not None:
497
+ top_ok = top_stat[1] < 36.0
498
+ bot_ok = bot_stat[1] < 36.0
499
+ if top_ok and not bot_ok:
500
+ bg_med = top_stat[0]
501
+ elif bot_ok and not top_ok:
502
+ bg_med = bot_stat[0]
503
+ elif top_ok and bot_ok:
504
+ # Text straddles a sharp horizontal seam (e.g. tight card header): use higher-contrast side.
505
+ t_eff = (
506
+ tr * alpha + top_stat[0][0] * (1.0 - alpha),
507
+ tg * alpha + top_stat[0][1] * (1.0 - alpha),
508
+ tb_c * alpha + top_stat[0][2] * (1.0 - alpha),
509
+ )
510
+ b_eff = (
511
+ tr * alpha + bot_stat[0][0] * (1.0 - alpha),
512
+ tg * alpha + bot_stat[0][1] * (1.0 - alpha),
513
+ tb_c * alpha + bot_stat[0][2] * (1.0 - alpha),
514
+ )
515
+ bg_med = (
516
+ top_stat[0]
517
+ if _wcag_contrast_ratio(t_eff, top_stat[0]) >= _wcag_contrast_ratio(b_eff, bot_stat[0])
518
+ else bot_stat[0]
519
+ )
520
+ elif top_stat is not None and top_stat[1] < 36.0:
521
+ bg_med = top_stat[0]
522
+ elif bot_stat is not None and bot_stat[1] < 36.0:
523
+ bg_med = bot_stat[0]
524
+
525
+ if bg_med is None:
526
+ continue
527
+
528
+ eff_text = (
529
+ tr * alpha + bg_med[0] * (1.0 - alpha),
530
+ tg * alpha + bg_med[1] * (1.0 - alpha),
531
+ tb_c * alpha + bg_med[2] * (1.0 - alpha),
532
+ )
533
+ contrast = _wcag_contrast_ratio(eff_text, bg_med)
534
+
535
+ # Guard against tight high-contrast pills/badges where the 2..6px outer band steps
536
+ # outside the badge onto the slide canvas: if >=25% of pixels inside the text box
537
+ # already provide >=3.0:1 contrast against the text color, it sits on a local badge.
538
+ if contrast < 3.0:
539
+ ix_step = max(1, (seg_x1 - seg_x0) // 20)
540
+ iy_step = max(1, (ty1 - ty0) // 12)
541
+ inner_total = 0
542
+ inner_high = 0
543
+ for yy in range(ty0, ty1, iy_step):
544
+ for xx in range(seg_x0, seg_x1, ix_step):
545
+ inner_total += 1
546
+ bg_px = px[xx, yy]
547
+ if alpha < 0.999:
548
+ fg_eff = (
549
+ tr * alpha + bg_px[0] * (1.0 - alpha),
550
+ tg * alpha + bg_px[1] * (1.0 - alpha),
551
+ tb_c * alpha + bg_px[2] * (1.0 - alpha),
552
+ )
553
+ else:
554
+ fg_eff = (tr, tg, tb_c)
555
+ if _wcag_contrast_ratio(fg_eff, bg_px) >= 3.0:
556
+ inner_high += 1
557
+ if inner_total > 0 and (inner_high / float(inner_total)) >= 0.25:
558
+ continue
559
+
560
+ if worst_contrast is None or contrast < worst_contrast:
561
+ worst_contrast = contrast
562
+ worst_bg = bg_med
563
+ worst_seg_idx = seg_idx
564
+
565
+ if worst_contrast is None or worst_bg is None:
566
+ continue
567
+
568
+ hit = {
569
+ "id": str(tb.get("id") or ""),
570
+ "text": text[:60],
571
+ "x": round(x, 1),
572
+ "y": round(y, 1),
573
+ "w": round(w, 1),
574
+ "h": round(h, 1),
575
+ "font_size": round(font_size, 1),
576
+ "text_rgb": [int(round(tr)), int(round(tg)), int(round(tb_c))],
577
+ "bg_rgb": [int(round(c)) for c in worst_bg],
578
+ "contrast": round(worst_contrast, 2),
579
+ "segment": worst_seg_idx,
580
+ "segments": n_segs,
581
+ }
582
+ if worst_contrast < 2.2:
583
+ blocking_hits.append({"code": "low-contrast-text", **hit})
584
+ elif worst_contrast < 3.0 and font_size >= 20.0:
585
+ warning_hits.append({"code": "borderline-contrast-text", **hit})
586
+
587
+ return blocking_hits, warning_hits
588
+
589
+
590
+ def evaluate_text_card_containment(
591
+ text_boxes: list[dict[str, Any]],
592
+ visual_cards: list[dict[str, Any]],
593
+ *,
594
+ canvas_w: int = 1920,
595
+ ) -> list[dict[str, Any]]:
596
+ """Detect visible text boxes overflowing their enclosing nested or flat-sibling visual card."""
597
+ hits: list[dict[str, Any]] = []
598
+ if not text_boxes or not visual_cards:
599
+ return hits
600
+
601
+ card_by_id: dict[str, dict[str, Any]] = {}
602
+ parsed_cards: list[dict[str, Any]] = []
603
+ for c in visual_cards:
604
+ if not isinstance(c, dict):
605
+ continue
606
+ try:
607
+ cid = str(c.get("id") or "")
608
+ cx = float(c["x"])
609
+ cy = float(c["y"])
610
+ cw = float(c["w"])
611
+ ch = float(c["h"])
612
+ c_order = int(c.get("domOrder", 0))
613
+ except (KeyError, TypeError, ValueError):
614
+ continue
615
+ if cw <= 0.0 or ch <= 0.0:
616
+ continue
617
+ entry = {"id": cid, "x": cx, "y": cy, "w": cw, "h": ch, "area": cw * ch, "domOrder": c_order}
618
+ parsed_cards.append(entry)
619
+ if cid:
620
+ card_by_id[cid] = entry
621
+
622
+ if not parsed_cards:
623
+ return hits
624
+
625
+ for tb in text_boxes:
626
+ if not isinstance(tb, dict):
627
+ continue
628
+ text = str(tb.get("text") or "").strip()
629
+ if len(text) < 2:
630
+ continue
631
+ try:
632
+ tx = float(tb["x"])
633
+ ty = float(tb["y"])
634
+ tw = float(tb["w"])
635
+ th = float(tb["h"])
636
+ font_size = float(tb.get("fontSize", 0.0))
637
+ tb_order = int(tb.get("domOrder", 0))
638
+ except (KeyError, TypeError, ValueError):
639
+ continue
640
+ if font_size < 14.0 or tw <= 0.0 or th <= 0.0:
641
+ continue
642
+
643
+ ancestor_ids = {str(cid) for cid in (tb.get("ancestorCardIds") or []) if cid is not None}
644
+ candidates: list[dict[str, Any]] = []
645
+ seen_ids: set[str] = set()
646
+
647
+ for cid in ancestor_ids:
648
+ card = card_by_id.get(cid)
649
+ if card is not None:
650
+ candidates.append(card)
651
+ seen_ids.add(cid)
652
+
653
+ anchor_x = tx + min(12.0, tw * 0.2)
654
+ anchor_y = ty + th * 0.5
655
+ for card in parsed_cards:
656
+ if card["id"] and card["id"] in seen_ids:
657
+ continue
658
+ if card["domOrder"] >= tb_order:
659
+ continue
660
+ cx, cy, cw, ch = card["x"], card["y"], card["w"], card["h"]
661
+ if not (cx <= anchor_x <= cx + cw and cy <= anchor_y <= cy + ch):
662
+ continue
663
+ v_overlap = max(0.0, min(ty + th, cy + ch) - max(ty, cy))
664
+ if v_overlap >= 0.60 * th:
665
+ candidates.append(card)
666
+
667
+ if not candidates:
668
+ continue
669
+
670
+ # Filter out tiny left accent bars/pills and intentional full-canvas centered multi-column titles.
671
+ eligible: list[dict[str, Any]] = []
672
+ tb_mid_x = tx + tw * 0.5
673
+ for card in candidates:
674
+ cw = card["w"]
675
+ is_ancestor = bool(card["id"] and card["id"] in ancestor_ids)
676
+ if cw < 200.0 and tw > cw * 1.35:
677
+ continue
678
+ if (
679
+ not is_ancestor
680
+ and tw > cw * 1.5
681
+ and font_size >= 36.0
682
+ and abs(tb_mid_x - canvas_w * 0.5) <= canvas_w * 0.12
683
+ ):
684
+ continue
685
+ eligible.append(card)
686
+
687
+ if not eligible:
688
+ continue
689
+
690
+ tightest = min(eligible, key=lambda c: c["area"])
691
+ overflow_right = (tx + tw) - (tightest["x"] + tightest["w"])
692
+ overflow_bottom = (ty + th) - (tightest["y"] + tightest["h"])
693
+ if overflow_right > 18.0 or overflow_bottom > 18.0:
694
+ is_nowrap = bool(tb.get("isNowrap"))
695
+ hits.append(
696
+ {
697
+ "code": "text-overflows-card",
698
+ "id": str(tb.get("id") or ""),
699
+ "card_id": tightest["id"],
700
+ "text": text[:60],
701
+ "overflow_right_px": round(max(0.0, overflow_right), 1),
702
+ "overflow_bottom_px": round(max(0.0, overflow_bottom), 1),
703
+ "is_nowrap": is_nowrap,
704
+ "hint": (
705
+ "Remove `white-space: nowrap`, wrap inside the card container, or widen the card."
706
+ if is_nowrap
707
+ else "Wrap or shorten the text inside the card container, or widen the card."
708
+ ),
709
+ }
710
+ )
711
+
712
+ return hits
713
+
714
+
715
+ def capture_html_slides(
716
+ html_path: Path,
717
+ slide_count: int,
718
+ out_dir: Path,
719
+ width: int = 1920,
720
+ height: int = 1080,
721
+ spec_path: Path | None = None,
722
+ target_slides: list[int] | None = None,
723
+ ) -> dict[str, Any]:
724
+ if width == 1920 and height == 1080:
725
+ width, height = _detect_verify_canvas_size(spec_path=spec_path, html_path=html_path)
726
+ try:
727
+ from playwright.sync_api import sync_playwright
728
+ except ImportError as exc:
729
+ raise RuntimeError(
730
+ "playwright is required for HTML capture. Install with: pip install playwright"
731
+ ) from exc
732
+
733
+ if not html_path.is_file():
734
+ raise FileNotFoundError(f"HTML file not found: {html_path}")
735
+
736
+ if target_slides:
737
+ capture_indices = sorted({int(i) for i in target_slides if 1 <= int(i) <= slide_count})
738
+ if not capture_indices:
739
+ capture_indices = list(range(1, slide_count + 1))
740
+ else:
741
+ capture_indices = list(range(1, slide_count + 1))
742
+
743
+ out_dir.mkdir(parents=True, exist_ok=True)
744
+ serve_root, rel_url = _infer_serve_root(html_path, spec_path)
745
+ chrome_bin = find_chrome_binary()
746
+
747
+ server, port = _start_static_server(serve_root)
748
+ results: list[dict[str, Any]] = []
749
+ try:
750
+ with sync_playwright() as p:
751
+ browser = _launch_chromium(
752
+ p,
753
+ headless=True,
754
+ args=[
755
+ "--no-sandbox",
756
+ "--disable-gpu-sandbox",
757
+ "--disable-dev-shm-usage",
758
+ "--headless=new",
759
+ "--hide-scrollbars",
760
+ ],
761
+ executable_path=chrome_bin,
762
+ discover_system=False,
763
+ )
764
+ context = browser.new_context(
765
+ viewport={"width": width, "height": height},
766
+ device_scale_factor=1,
767
+ )
768
+ context.set_default_timeout(20000)
769
+ _attach_local_font_route_guard(context)
770
+ page = context.new_page()
771
+ loaded_once = False
772
+ can_fast_switch = False
773
+
774
+ for idx in capture_indices:
775
+ console_errors: list[str] = []
776
+ page_errors: list[str] = []
777
+ failed_requests: list[str] = []
778
+
779
+ def on_console(msg: Any) -> None:
780
+ if msg.type == "error":
781
+ txt = msg.text
782
+ # Ignore default favicon 404 from python http.server
783
+ if "favicon.ico" not in txt:
784
+ console_errors.append(txt)
785
+
786
+ def on_pageerror(err: Any) -> None:
787
+ page_errors.append(str(err))
788
+
789
+ def on_req_failed(req: Any) -> None:
790
+ if "favicon.ico" not in req.url:
791
+ failed_requests.append(f"{req.url} ({req.failure})")
792
+
793
+ page.on("console", on_console)
794
+ page.on("pageerror", on_pageerror)
795
+ page.on("requestfailed", on_req_failed)
796
+
797
+ switched = False
798
+ if loaded_once and can_fast_switch:
799
+ try:
800
+ switched = bool(
801
+ page.evaluate(
802
+ """(targetIdx) => {
803
+ if (window.__OIL_DECK__ && typeof window.__OIL_DECK__.goTo === 'function') {
804
+ window.__OIL_DECK__.goTo(targetIdx - 1, { instant: true });
805
+ return true;
806
+ }
807
+ return false;
808
+ }""",
809
+ idx,
810
+ )
811
+ )
812
+ except Exception:
813
+ switched = False
814
+
815
+ if not switched:
816
+ url = f"http://127.0.0.1:{port}/{rel_url}?slide={idx}"
817
+ page.goto(url, wait_until="domcontentloaded", timeout=20000)
818
+ loaded_once = True
819
+ try:
820
+ can_fast_switch = bool(
821
+ page.evaluate("() => !!(window.__OIL_DECK__ && typeof window.__OIL_DECK__.goTo === 'function')")
822
+ )
823
+ except Exception:
824
+ can_fast_switch = False
825
+
826
+ page.evaluate(
827
+ """async (targetIdx) => {
828
+ if (document.fonts && document.fonts.ready) {
829
+ await Promise.race([document.fonts.ready, new Promise(r => setTimeout(r, 2500))]);
830
+ }
831
+ const activeSlide =
832
+ document.querySelector(`.slide[data-slide="${targetIdx}"]`) ||
833
+ document.querySelector(`[data-slide="${targetIdx}"]`) ||
834
+ document.querySelector('.slide.is-active, .slide.active');
835
+ const slideImgs = activeSlide ? Array.from(activeSlide.querySelectorAll('img')) : [];
836
+ const docImgs = Array.from(document.images || []);
837
+ const imgs = Array.from(new Set([...slideImgs, ...docImgs]));
838
+ await Promise.all(imgs.map(async (img) => {
839
+ try {
840
+ if (img.loading === 'lazy' || img.getAttribute('loading') === 'lazy') {
841
+ img.loading = 'eager';
842
+ img.setAttribute('loading', 'eager');
843
+ }
844
+ img.decoding = 'sync';
845
+ const rawSrc = img.getAttribute('src') || '';
846
+ if (img.complete && img.naturalWidth === 0 && rawSrc) {
847
+ img.src = img.currentSrc || rawSrc;
848
+ }
849
+ if (!img.complete || img.naturalWidth === 0) {
850
+ await new Promise(res => {
851
+ const done = () => res();
852
+ img.addEventListener('load', done, { once: true });
853
+ img.addEventListener('error', done, { once: true });
854
+ setTimeout(done, 5000);
855
+ });
856
+ }
857
+ if (img.complete && img.naturalWidth > 0 && typeof img.decode === 'function') {
858
+ await Promise.race([img.decode().catch(() => {}), new Promise(r => setTimeout(r, 2500))]);
859
+ }
860
+ } catch (_) {}
861
+ }));
862
+ await Promise.race([
863
+ new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))),
864
+ new Promise(r => setTimeout(r, 500)),
865
+ ]);
866
+ }""",
867
+ idx,
868
+ )
869
+
870
+ metrics = page.evaluate(
871
+ """([idx, total]) => {
872
+ const docEl = document.documentElement;
873
+ const imgs = Array.from(document.images || []).map(img => ({
874
+ src: img.getAttribute('src'),
875
+ complete: img.complete,
876
+ naturalWidth: img.naturalWidth,
877
+ naturalHeight: img.naturalHeight
878
+ }));
879
+ const svgs = Array.from(document.querySelectorAll('svg')).length;
880
+ const activeSlide =
881
+ document.querySelector(`[data-slide="${idx}"]`) ||
882
+ document.querySelector('.slide.is-active, .slide.active');
883
+ const headerSelectors = [
884
+ 'header', '.slide-header', '.deck-header', '.topbar', '.brand-lockup', '.header'
885
+ ];
886
+ let headerRect = null;
887
+ for (const sel of headerSelectors) {
888
+ const el = (activeSlide || document).querySelector(sel);
889
+ if (el) {
890
+ const r = el.getBoundingClientRect();
891
+ if (r.width > 0 && r.height > 0) {
892
+ headerRect = {
893
+ selector: sel,
894
+ x: Math.round(r.x),
895
+ y: Math.round(r.y),
896
+ w: Math.round(r.width),
897
+ h: Math.round(r.height)
898
+ };
899
+ break;
900
+ }
901
+ }
902
+ }
903
+ const counterRegex = new RegExp(`^0?${idx}\\\\s*\\\\/\\\\s*0?${total}$`);
904
+ const pageNumEl = Array.from((activeSlide || document).querySelectorAll('*')).find(
905
+ el => el.children.length === 0 && counterRegex.test((el.textContent || '').trim())
906
+ );
907
+ const pageNumRect = pageNumEl ? (() => {
908
+ const r = pageNumEl.getBoundingClientRect();
909
+ return {
910
+ text: pageNumEl.textContent.trim(),
911
+ x: Math.round(r.x),
912
+ y: Math.round(r.y),
913
+ w: Math.round(r.width),
914
+ h: Math.round(r.height)
915
+ };
916
+ })() : null;
917
+
918
+ const maxBorderRadius = (s) => Math.max(
919
+ parseFloat(s.borderTopLeftRadius || '0') || 0,
920
+ parseFloat(s.borderTopRightRadius || '0') || 0,
921
+ parseFloat(s.borderBottomRightRadius || '0') || 0,
922
+ parseFloat(s.borderBottomLeftRadius || '0') || 0,
923
+ );
924
+ const maxBorderWidth = (s) => Math.max(
925
+ parseFloat(s.borderTopWidth || '0') || 0,
926
+ parseFloat(s.borderRightWidth || '0') || 0,
927
+ parseFloat(s.borderBottomWidth || '0') || 0,
928
+ parseFloat(s.borderLeftWidth || '0') || 0,
929
+ );
930
+ const hasVisibleBg = (s) => {
931
+ const bg = (s.backgroundColor || '').trim().toLowerCase();
932
+ if (bg && bg !== 'transparent' && bg !== 'rgba(0, 0, 0, 0)' && !/^rgba\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*0(?:\\.0+)?\\s*\\)$/.test(bg)) {
933
+ return true;
934
+ }
935
+ return Boolean(s.backgroundImage && s.backgroundImage !== 'none');
936
+ };
937
+ const visibleImages = Array.from((activeSlide || document).querySelectorAll('img'))
938
+ .filter(img => {
939
+ const cs = getComputedStyle(img);
940
+ if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity || '1') <= 0.01) return false;
941
+ const r = img.getBoundingClientRect();
942
+ return img.complete && img.naturalWidth >= 80 && img.naturalHeight >= 80 && r.width >= 40 && r.height >= 40;
943
+ })
944
+ .map(img => {
945
+ const r = img.getBoundingClientRect();
946
+ const cs = getComputedStyle(img);
947
+ let framed = maxBorderRadius(cs) >= 4 || maxBorderWidth(cs) >= 1 || (cs.clipPath && cs.clipPath !== 'none');
948
+ const clippedEdges = { top: false, bottom: false, left: false, right: false };
949
+ let flipX = false;
950
+ let flipY = false;
951
+ const applyFlip = (s) => {
952
+ if (s.transform && s.transform !== 'none' && typeof DOMMatrixReadOnly !== 'undefined') {
953
+ try {
954
+ const m = new DOMMatrixReadOnly(s.transform);
955
+ if (m.a < -0.01) flipX = !flipX;
956
+ if (m.d < -0.01) flipY = !flipY;
957
+ } catch (_) {}
958
+ }
959
+ };
960
+ applyFlip(cs);
961
+ let p = img.parentElement;
962
+ while (p && p !== activeSlide && p !== document.body) {
963
+ const pcs = getComputedStyle(p);
964
+ applyFlip(pcs);
965
+ if (!framed) {
966
+ if (pcs.clipPath && pcs.clipPath !== 'none') {
967
+ framed = true;
968
+ } else {
969
+ const pr = p.getBoundingClientRect();
970
+ const clipsX = pcs.overflowX === 'hidden' || pcs.overflowX === 'clip';
971
+ const clipsY = pcs.overflowY === 'hidden' || pcs.overflowY === 'clip';
972
+ if ((clipsX || clipsY) && (pr.width < window.innerWidth - 16 || pr.height < window.innerHeight - 16)) {
973
+ if (maxBorderRadius(pcs) >= 4 || maxBorderWidth(pcs) >= 1 || hasVisibleBg(pcs)) {
974
+ framed = true;
975
+ } else {
976
+ if (clipsY && r.top <= pr.top + 6) clippedEdges.top = true;
977
+ if (clipsY && r.bottom >= pr.bottom - 6) clippedEdges.bottom = true;
978
+ if (clipsX && r.left <= pr.left + 6) clippedEdges.left = true;
979
+ if (clipsX && r.right >= pr.right - 6) clippedEdges.right = true;
980
+ }
981
+ }
982
+ }
983
+ }
984
+ p = p.parentElement;
985
+ }
986
+ let paintedX = r.x;
987
+ let paintedY = r.y;
988
+ let paintedW = r.width;
989
+ let paintedH = r.height;
990
+ if ((cs.objectFit === 'contain' || cs.objectFit === 'scale-down') && img.naturalWidth > 0 && img.naturalHeight > 0 && r.width > 0 && r.height > 0) {
991
+ const natRatio = img.naturalWidth / img.naturalHeight;
992
+ const boxRatio = r.width / r.height;
993
+ let fitW = r.width;
994
+ let fitH = r.height;
995
+ if (cs.objectFit === 'scale-down' && img.naturalWidth <= r.width && img.naturalHeight <= r.height) {
996
+ fitW = img.naturalWidth;
997
+ fitH = img.naturalHeight;
998
+ } else if (natRatio > boxRatio) {
999
+ fitW = r.width;
1000
+ fitH = r.width / natRatio;
1001
+ } else {
1002
+ fitH = r.height;
1003
+ fitW = r.height * natRatio;
1004
+ }
1005
+ const posParts = (cs.objectPosition || '50% 50%').trim().split(/\\s+/);
1006
+ const parsePos = (tok, free) => {
1007
+ if (!tok || tok === 'center') return free * 0.5;
1008
+ if (tok === 'left' || tok === 'top') return 0;
1009
+ if (tok === 'right' || tok === 'bottom') return free;
1010
+ if (tok.endsWith('%')) return free * (parseFloat(tok) / 100);
1011
+ const px = parseFloat(tok);
1012
+ return Number.isFinite(px) ? px : free * 0.5;
1013
+ };
1014
+ paintedX = r.x + parsePos(posParts[0], r.width - fitW);
1015
+ paintedY = r.y + parsePos(posParts[1] || '50%', r.height - fitH);
1016
+ paintedW = fitW;
1017
+ paintedH = fitH;
1018
+ }
1019
+ return {
1020
+ src: img.getAttribute('src') || '',
1021
+ x: Math.round(paintedX),
1022
+ y: Math.round(paintedY),
1023
+ w: Math.round(paintedW),
1024
+ h: Math.round(paintedH),
1025
+ framed,
1026
+ clippedEdges,
1027
+ flipX,
1028
+ flipY,
1029
+ };
1030
+ });
1031
+
1032
+ const rootNode = activeSlide || document.body;
1033
+ const allImgSrcs = Array.from(rootNode.querySelectorAll('img')).map(
1034
+ img => img.getAttribute('src') || ''
1035
+ );
1036
+ let allVisibleImgCount = 0;
1037
+ let fullBleedImgCount = 0;
1038
+ const isHiddenImgTree = (el) => {
1039
+ let cur = el;
1040
+ while (cur && cur !== rootNode.parentElement) {
1041
+ const ccs = getComputedStyle(cur);
1042
+ if (ccs.display === 'none' || ccs.visibility === 'hidden' || parseFloat(ccs.opacity || '1') <= 0.01) {
1043
+ return true;
1044
+ }
1045
+ if (cur === rootNode) break;
1046
+ cur = cur.parentElement;
1047
+ }
1048
+ return false;
1049
+ };
1050
+ const getImgTreeEffOpacity = (el) => {
1051
+ let op = 1.0;
1052
+ let cur = el;
1053
+ while (cur && cur !== rootNode.parentElement) {
1054
+ op *= parseFloat(getComputedStyle(cur).opacity || '1');
1055
+ if (cur === rootNode) break;
1056
+ cur = cur.parentElement;
1057
+ }
1058
+ return op;
1059
+ };
1060
+ const parseImgCssAlpha = (col) => {
1061
+ if (!col) return 0;
1062
+ const s = String(col).trim().toLowerCase();
1063
+ if (!s || s === 'transparent') return 0;
1064
+ const m = s.match(/rgba?\\(\\s*[\\d.]+\\s*[,\\s]\\s*[\\d.]+\\s*[,\\s]\\s*[\\d.]+\\s*(?:[,/]\\s*([\\d.]+%?)\\s*)?\\)/i);
1065
+ if (!m) return 1;
1066
+ if (m[1] === undefined) return 1;
1067
+ if (m[1].endsWith('%')) return parseFloat(m[1]) / 100.0;
1068
+ return parseFloat(m[1]);
1069
+ };
1070
+ const isClipOverflowVal = (v) => v === 'hidden' || v === 'clip' || v === 'scroll' || v === 'auto';
1071
+ const hasCssRotOrSkew = (ecs) => {
1072
+ if ((ecs.rotate && ecs.rotate !== 'none') || (ecs.scale && ecs.scale !== 'none')) return true;
1073
+ const tf = ecs.transform;
1074
+ if (!tf || tf === 'none') return false;
1075
+ const m2 = tf.match(/^matrix\\(([^)]+)\\)$/);
1076
+ const m3 = !m2 ? tf.match(/^matrix3d\\(([^)]+)\\)$/) : null;
1077
+ let a = 1, b = 0, c = 0, d = 1;
1078
+ if (m2) {
1079
+ const p = m2[1].split(',').map(Number);
1080
+ if (p.length === 6 && p.every(Number.isFinite)) [a, b, c, d] = p;
1081
+ } else if (m3) {
1082
+ const p = m3[1].split(',').map(Number);
1083
+ if (p.length === 16 && p.every(Number.isFinite)) { a = p[0]; b = p[1]; c = p[4]; d = p[5]; }
1084
+ }
1085
+ const rotDeg = Math.atan2(b, a) * (180.0 / Math.PI);
1086
+ const dot = Math.abs(a * c + b * d);
1087
+ const l1 = Math.hypot(a, b), l2 = Math.hypot(c, d);
1088
+ const normDot = (l1 > 1e-6 && l2 > 1e-6) ? (dot / (l1 * l2)) : dot;
1089
+ return (Math.abs(rotDeg) > 0.5) || (dot > 0.02) || (normDot > 0.02);
1090
+ };
1091
+ const establishesFixedImgCB = (acs) => (
1092
+ (acs.transform && acs.transform !== 'none') ||
1093
+ (acs.rotate && acs.rotate !== 'none') ||
1094
+ (acs.scale && acs.scale !== 'none') ||
1095
+ (acs.translate && acs.translate !== 'none') ||
1096
+ (acs.filter && acs.filter !== 'none') ||
1097
+ (acs.backdropFilter && acs.backdropFilter !== 'none') ||
1098
+ (acs.webkitBackdropFilter && acs.webkitBackdropFilter !== 'none') ||
1099
+ (acs.perspective && acs.perspective !== 'none')
1100
+ );
1101
+ const establishesAbsImgCB = (acs) => acs.position !== 'static' || establishesFixedImgCB(acs);
1102
+ const isImgClippedOutByAncestor = (imgEl, ir) => {
1103
+ let curPos = getComputedStyle(imgEl).position;
1104
+ let cur = imgEl.parentElement;
1105
+ while (cur && cur !== rootNode) {
1106
+ const acs = getComputedStyle(cur);
1107
+ let skipsAnc = false;
1108
+ if (curPos === 'fixed') {
1109
+ if (!establishesFixedImgCB(acs)) skipsAnc = true;
1110
+ } else if (curPos === 'absolute') {
1111
+ if (!establishesAbsImgCB(acs)) skipsAnc = true;
1112
+ }
1113
+ if (!skipsAnc) {
1114
+ const cX = isClipOverflowVal(acs.overflowX) || isClipOverflowVal(acs.overflow);
1115
+ const cY = isClipOverflowVal(acs.overflowY) || isClipOverflowVal(acs.overflow);
1116
+ if (cX || cY) {
1117
+ const ar = cur.getBoundingClientRect();
1118
+ const isRot = hasCssRotOrSkew(acs);
1119
+ const bL = !isRot && acs.borderLeftStyle !== 'none' ? (parseFloat(acs.borderLeftWidth) || 0) : 0;
1120
+ const bR = !isRot && acs.borderRightStyle !== 'none' ? (parseFloat(acs.borderRightWidth) || 0) : 0;
1121
+ const bT = !isRot && acs.borderTopStyle !== 'none' ? (parseFloat(acs.borderTopWidth) || 0) : 0;
1122
+ const bB = !isRot && acs.borderBottomStyle !== 'none' ? (parseFloat(acs.borderBottomWidth) || 0) : 0;
1123
+ if (cX && (ir.right <= ar.left + bL + 0.5 || ir.left >= ar.right - bR - 0.5)) return true;
1124
+ if (cY && (ir.bottom <= ar.top + bT + 0.5 || ir.top >= ar.bottom - bB - 0.5)) return true;
1125
+ }
1126
+ curPos = acs.position;
1127
+ }
1128
+ cur = cur.parentElement;
1129
+ }
1130
+ return false;
1131
+ };
1132
+ const hasAtomicTransformedVisual = (el) => {
1133
+ if ((el.textContent || '').trim().length > 0) return false;
1134
+ const effOp = getImgTreeEffOpacity(el);
1135
+ if (effOp >= 0.999) return false;
1136
+ const er = el.getBoundingClientRect();
1137
+ if (er.width <= 0.25 || er.height <= 0.25 || er.right <= 0.5 || er.left >= window.innerWidth - 0.5 || er.bottom <= 0.5 || er.top >= window.innerHeight - 0.5) return false;
1138
+ const ecs = getComputedStyle(el);
1139
+ if (!hasCssRotOrSkew(ecs)) return false;
1140
+ const hasBgImg = Boolean(ecs.backgroundImage && ecs.backgroundImage !== 'none');
1141
+ const hasBgCol = parseImgCssAlpha(ecs.backgroundColor) * effOp > 0.01;
1142
+ const hasBdr = (
1143
+ (ecs.borderTopStyle !== 'none' && (parseFloat(ecs.borderTopWidth) || 0) > 0.1 && parseImgCssAlpha(ecs.borderTopColor) * effOp > 0.01) ||
1144
+ (ecs.borderRightStyle !== 'none' && (parseFloat(ecs.borderRightWidth) || 0) > 0.1 && parseImgCssAlpha(ecs.borderRightColor) * effOp > 0.01) ||
1145
+ (ecs.borderBottomStyle !== 'none' && (parseFloat(ecs.borderBottomWidth) || 0) > 0.1 && parseImgCssAlpha(ecs.borderBottomColor) * effOp > 0.01) ||
1146
+ (ecs.borderLeftStyle !== 'none' && (parseFloat(ecs.borderLeftWidth) || 0) > 0.1 && parseImgCssAlpha(ecs.borderLeftColor) * effOp > 0.01)
1147
+ );
1148
+ return hasBgImg || hasBgCol || hasBdr;
1149
+ };
1150
+ const findAtomicTransformedRoot = (imgEl) => {
1151
+ let found = null;
1152
+ let cur = imgEl.parentElement;
1153
+ while (cur && cur !== rootNode) {
1154
+ if (hasAtomicTransformedVisual(cur)) found = cur;
1155
+ cur = cur.parentElement;
1156
+ }
1157
+ return found;
1158
+ };
1159
+ const countedAtomicRoots = new Set();
1160
+ for (const img of Array.from(rootNode.querySelectorAll('img'))) {
1161
+ if (img.hasAttribute('data-export-ignore')) continue;
1162
+ if (isHiddenImgTree(img)) continue;
1163
+ if (!img.complete || img.naturalWidth <= 0) continue;
1164
+ const ir = img.getBoundingClientRect();
1165
+ if (ir.width <= 1 || ir.height <= 1) continue;
1166
+ if (ir.right <= 0.5 || ir.left >= window.innerWidth - 0.5 || ir.bottom <= 0.5 || ir.top >= window.innerHeight - 0.5) continue;
1167
+ if (isImgClippedOutByAncestor(img, ir)) continue;
1168
+ const atomicRoot = findAtomicTransformedRoot(img);
1169
+ if (atomicRoot) {
1170
+ if (!countedAtomicRoots.has(atomicRoot)) {
1171
+ countedAtomicRoots.add(atomicRoot);
1172
+ allVisibleImgCount++;
1173
+ }
1174
+ continue;
1175
+ }
1176
+ allVisibleImgCount++;
1177
+ if (ir.left <= 2 && ir.top <= 2 && ir.width >= window.innerWidth - 4 && ir.height >= window.innerHeight - 4) {
1178
+ fullBleedImgCount++;
1179
+ }
1180
+ }
1181
+ const domTextLen = (() => {
1182
+ const clone = rootNode.cloneNode(true);
1183
+ clone.querySelectorAll('script, style, #nav, .deck-nav, .slide-nav, .nav-controls, .controls, .nav-pill, .page-num, .slide-num, .slide-index').forEach(el => el.remove());
1184
+ return (clone.textContent || '').replace(/\\s+/g, '').length;
1185
+ })();
1186
+
1187
+ const parseCssRgba = (str) => {
1188
+ const raw = (str || '').trim().toLowerCase();
1189
+ if (!raw || raw === 'transparent') return [0, 0, 0, 0];
1190
+ const m = raw.match(/rgba?\\(\\s*([\\d.]+)[,\\s]+([\\d.]+)[,\\s]+([\\d.]+)(?:\\s*[,/]\\s*([\\d.]+%?))?\\s*\\)/);
1191
+ if (!m) return null;
1192
+ let a = 1.0;
1193
+ if (m[4] !== undefined) {
1194
+ a = m[4].endsWith('%') ? (parseFloat(m[4]) / 100.0) : parseFloat(m[4]);
1195
+ }
1196
+ return [
1197
+ Math.max(0, Math.min(255, Math.round(parseFloat(m[1])))),
1198
+ Math.max(0, Math.min(255, Math.round(parseFloat(m[2])))),
1199
+ Math.max(0, Math.min(255, Math.round(parseFloat(m[3])))),
1200
+ Number.isFinite(a) ? Math.max(0, Math.min(1, a)) : 1.0,
1201
+ ];
1202
+ };
1203
+ const isIgnoredNode = (el) => {
1204
+ if (!el || el.nodeType !== 1) return true;
1205
+ if (el.closest('script, style, noscript, svg, [aria-hidden="true"], #nav, .deck-nav, .slide-nav, .nav-controls, .deck-controls, .controls, .nav-pill')) return true;
1206
+ return false;
1207
+ };
1208
+ const getEffectiveVisibility = (el) => {
1209
+ let op = 1.0;
1210
+ let cur = el;
1211
+ while (cur && cur.nodeType === 1) {
1212
+ const s = getComputedStyle(cur);
1213
+ if (s.display === 'none' || s.visibility === 'hidden') return 0.0;
1214
+ const o = parseFloat(s.opacity || '1');
1215
+ if (Number.isFinite(o)) op *= o;
1216
+ if (cur === rootNode) break;
1217
+ cur = cur.parentElement;
1218
+ }
1219
+ return op;
1220
+ };
1221
+ const getClipBounds = (startEl) => {
1222
+ let left = 0;
1223
+ let top = 0;
1224
+ let right = window.innerWidth;
1225
+ let bottom = window.innerHeight;
1226
+ let cur = startEl;
1227
+ while (cur && cur.nodeType === 1) {
1228
+ const s = getComputedStyle(cur);
1229
+ const ox = (s.overflowX || '').toLowerCase();
1230
+ const oy = (s.overflowY || '').toLowerCase();
1231
+ const clipsX = ox === 'hidden' || ox === 'clip' || ox === 'scroll' || ox === 'auto';
1232
+ const clipsY = oy === 'hidden' || oy === 'clip' || oy === 'scroll' || oy === 'auto';
1233
+ if (clipsX || clipsY) {
1234
+ const cr = cur.getBoundingClientRect();
1235
+ if (clipsX) {
1236
+ left = Math.max(left, cr.left);
1237
+ right = Math.min(right, cr.right);
1238
+ }
1239
+ if (clipsY) {
1240
+ top = Math.max(top, cr.top);
1241
+ bottom = Math.min(bottom, cr.bottom);
1242
+ }
1243
+ }
1244
+ if (s.clip && /^rect\\(\\s*0(?:px)?[,\\s]+0(?:px)?[,\\s]+0(?:px)?[,\\s]+0(?:px)?\\s*\\)$/i.test(s.clip.trim())) {
1245
+ return { left: 0, top: 0, right: 0, bottom: 0 };
1246
+ }
1247
+ if (cur === rootNode) break;
1248
+ cur = cur.parentElement;
1249
+ }
1250
+ return { left, top, right, bottom };
1251
+ };
1252
+ const slideAreaPx = Math.max(1, window.innerWidth * window.innerHeight);
1253
+ const domOrderMap = new Map();
1254
+ const cardIdByEl = new Map();
1255
+ const visualCards = [];
1256
+ const allEls = Array.from(rootNode.querySelectorAll('*'));
1257
+ allEls.forEach((el, ordIdx) => {
1258
+ domOrderMap.set(el, ordIdx + 1);
1259
+ if (el === activeSlide || el === document.body || el === document.documentElement) return;
1260
+ if (isIgnoredNode(el)) return;
1261
+ const tag = (el.tagName || '').toUpperCase();
1262
+ if (tag === 'IMG' || tag === 'BR' || tag === 'HR' || tag === 'SOURCE' || tag === 'PICTURE') return;
1263
+ const cs = getComputedStyle(el);
1264
+ if (cs.display === 'inline' || cs.display === 'none' || cs.visibility === 'hidden') return;
1265
+ const effOp = getEffectiveVisibility(el);
1266
+ if (effOp < 0.30) return;
1267
+ const r = el.getBoundingClientRect();
1268
+ if (r.width < 140 || r.height < 56) return;
1269
+ const area = r.width * r.height;
1270
+ if (area < 0.025 * slideAreaPx || area > 0.82 * slideAreaPx) return;
1271
+ const bgRgba = parseCssRgba(cs.backgroundColor);
1272
+ const hasOpaqueBg = Boolean(
1273
+ (bgRgba && bgRgba[3] * effOp >= 0.70)
1274
+ || (cs.backgroundImage && cs.backgroundImage !== 'none' && effOp >= 0.70)
1275
+ );
1276
+ const borderSides = ['Top', 'Right', 'Bottom', 'Left'];
1277
+ let visibleBorderSides = 0;
1278
+ for (const side of borderSides) {
1279
+ const bw = parseFloat(cs[`border${side}Width`] || '0') || 0;
1280
+ const bs = (cs[`border${side}Style`] || 'none').toLowerCase();
1281
+ if (bw >= 1.5 && bs !== 'none' && bs !== 'hidden') {
1282
+ const bc = parseCssRgba(cs[`border${side}Color`]);
1283
+ if (bc && bc[3] * effOp >= 0.25) {
1284
+ visibleBorderSides += 1;
1285
+ }
1286
+ }
1287
+ }
1288
+ const hasVisibleBorder = visibleBorderSides >= 2;
1289
+ if (!hasOpaqueBg && !hasVisibleBorder) return;
1290
+ const cid = `card-${visualCards.length}`;
1291
+ cardIdByEl.set(el, cid);
1292
+ visualCards.push({
1293
+ id: cid,
1294
+ x: Math.round(r.x * 10) / 10,
1295
+ y: Math.round(r.y * 10) / 10,
1296
+ w: Math.round(r.width * 10) / 10,
1297
+ h: Math.round(r.height * 10) / 10,
1298
+ domOrder: ordIdx + 1,
1299
+ });
1300
+ });
1301
+
1302
+ const visibleTextBoxes = [];
1303
+ const walker = document.createTreeWalker(rootNode, NodeFilter.SHOW_TEXT);
1304
+ let tNode = walker.nextNode();
1305
+ while (tNode) {
1306
+ const txt = (tNode.nodeValue || '').replace(/\\s+/g, ' ').trim();
1307
+ if (txt.length >= 1) {
1308
+ const el = tNode.parentElement;
1309
+ if (el && !isIgnoredNode(el)) {
1310
+ const cs = getComputedStyle(el);
1311
+ const effOp = getEffectiveVisibility(el);
1312
+ const fs = parseFloat(cs.fontSize || '0') || 0;
1313
+ const col = parseCssRgba(cs.color);
1314
+ const bgClip = (cs.webkitBackgroundClip || cs.backgroundClip || '').toLowerCase();
1315
+ const textFill = parseCssRgba(cs.webkitTextFillColor);
1316
+ const isClipText = bgClip === 'text' || (textFill && textFill[3] < 0.15);
1317
+ const effAlpha = col ? Math.max(0, Math.min(1, col[3] * effOp)) : 0;
1318
+ if (effAlpha >= 0.30 && fs >= 12 && !isClipText) {
1319
+ const clipBounds = getClipBounds(el);
1320
+ const range = document.createRange();
1321
+ range.selectNodeContents(tNode);
1322
+ const rawRects = Array.from(range.getClientRects())
1323
+ .map(r => ({
1324
+ left: Math.max(r.left, clipBounds.left),
1325
+ top: Math.max(r.top, clipBounds.top),
1326
+ right: Math.min(r.right, clipBounds.right),
1327
+ bottom: Math.min(r.bottom, clipBounds.bottom),
1328
+ }))
1329
+ .filter(r => (r.right - r.left) >= 2 && (r.bottom - r.top) >= 4);
1330
+ const lineRects = [];
1331
+ for (const r of rawRects) {
1332
+ const prev = lineRects.length ? lineRects[lineRects.length - 1] : null;
1333
+ if (prev && Math.abs(r.top - prev.top) <= Math.max(4, fs * 0.45)) {
1334
+ const nx0 = Math.min(prev.left, r.left);
1335
+ const ny0 = Math.min(prev.top, r.top);
1336
+ const nx1 = Math.max(prev.right, r.right);
1337
+ const ny1 = Math.max(prev.bottom, r.bottom);
1338
+ prev.left = nx0;
1339
+ prev.top = ny0;
1340
+ prev.right = nx1;
1341
+ prev.bottom = ny1;
1342
+ } else {
1343
+ lineRects.push({ left: r.left, top: r.top, right: r.right, bottom: r.bottom });
1344
+ }
1345
+ }
1346
+ const ancestorCardIds = [];
1347
+ let p = el;
1348
+ while (p && p !== activeSlide && p !== document.body) {
1349
+ const cid = cardIdByEl.get(p);
1350
+ if (cid) ancestorCardIds.push(cid);
1351
+ p = p.parentElement;
1352
+ }
1353
+ const fwRaw = cs.fontWeight || '400';
1354
+ const fw = fwRaw === 'bold' ? 700 : (parseInt(fwRaw, 10) || 400);
1355
+ const ws = (cs.whiteSpace || '').toLowerCase();
1356
+ const isNowrap = ws.includes('nowrap') || ws === 'pre';
1357
+ const ord = domOrderMap.get(el) || 0;
1358
+ for (const lr of lineRects) {
1359
+ const lw = lr.right - lr.left;
1360
+ const lh = lr.bottom - lr.top;
1361
+ if (lw < 4 || lh < 4) continue;
1362
+ visibleTextBoxes.push({
1363
+ id: `tb-${visibleTextBoxes.length}`,
1364
+ text: txt.slice(0, 80),
1365
+ x: Math.round(lr.left * 10) / 10,
1366
+ y: Math.round(lr.top * 10) / 10,
1367
+ w: Math.round(lw * 10) / 10,
1368
+ h: Math.round(lh * 10) / 10,
1369
+ colorRgb: [col[0], col[1], col[2]],
1370
+ alpha: Math.round(effAlpha * 1000) / 1000,
1371
+ fontSize: Math.round(fs * 10) / 10,
1372
+ fontWeight: fw,
1373
+ isNowrap,
1374
+ ancestorCardIds,
1375
+ domOrder: ord,
1376
+ });
1377
+ }
1378
+ }
1379
+ }
1380
+ }
1381
+ tNode = walker.nextNode();
1382
+ }
1383
+
1384
+ const expensiveSvgFilters = [];
1385
+ const seenSvgFilters = new Set();
1386
+ const canonicalSvgPrim = {
1387
+ feturbulence: 'feTurbulence',
1388
+ fedisplacementmap: 'feDisplacementMap',
1389
+ feconvolvematrix: 'feConvolveMatrix',
1390
+ };
1391
+ const recordExpensiveFilter = (source, primKey, selector) => {
1392
+ const prim = canonicalSvgPrim[primKey] || primKey;
1393
+ const key = `${source}|${prim}|${selector}`;
1394
+ if (seenSvgFilters.has(key) || expensiveSvgFilters.length >= 12) return;
1395
+ seenSvgFilters.add(key);
1396
+ expensiveSvgFilters.push({ source, primitive: prim, selector });
1397
+ };
1398
+ const describeNode = (el, pseudo) => {
1399
+ if (!el || el.nodeType !== 1) return pseudo ? `slide${pseudo}` : 'slide';
1400
+ const tag = (el.localName || el.tagName || 'el').toLowerCase();
1401
+ const idPart = el.id ? `#${el.id}` : '';
1402
+ const clsRaw = typeof el.className === 'string'
1403
+ ? el.className
1404
+ : (el.className && typeof el.className.baseVal === 'string' ? el.className.baseVal : '');
1405
+ const clsFirst = clsRaw.trim().split(/\\s+/).filter(Boolean).slice(0, 2).map(c => `.${c}`).join('');
1406
+ return `${tag}${idPart}${clsFirst}${pseudo || ''}`;
1407
+ };
1408
+ const decodeSvgDataUris = (rawStr) => {
1409
+ if (!rawStr || rawStr === 'none') return '';
1410
+ const lower = rawStr.toLowerCase();
1411
+ if (!lower.includes('data:image/svg+xml')) return '';
1412
+ const chunks = [];
1413
+ let pos = 0;
1414
+ while (pos < rawStr.length) {
1415
+ const start = lower.indexOf('data:image/svg+xml', pos);
1416
+ if (start < 0) break;
1417
+ const quote = start > 0 && (rawStr[start - 1] === '"' || rawStr[start - 1] === "'") ? rawStr[start - 1] : '';
1418
+ let end = rawStr.length;
1419
+ if (quote) {
1420
+ let idxQ = start;
1421
+ while (idxQ < rawStr.length) {
1422
+ const nxt = rawStr.indexOf(quote, idxQ);
1423
+ if (nxt < 0) break;
1424
+ if (rawStr[nxt - 1] !== '\\\\') {
1425
+ end = nxt;
1426
+ break;
1427
+ }
1428
+ idxQ = nxt + 1;
1429
+ }
1430
+ } else if (start > 0 && rawStr.slice(Math.max(0, start - 6), start).toLowerCase().includes('url(')) {
1431
+ let depth = 1;
1432
+ let idxP = start;
1433
+ while (idxP < rawStr.length) {
1434
+ const ch = rawStr[idxP];
1435
+ if (ch === '(') depth += 1;
1436
+ else if (ch === ')') {
1437
+ depth -= 1;
1438
+ if (depth === 0) {
1439
+ end = idxP;
1440
+ break;
1441
+ }
1442
+ }
1443
+ idxP += 1;
1444
+ }
1445
+ }
1446
+ const uri = rawStr.slice(start, end);
1447
+ pos = Math.max(end, start + 18);
1448
+ const comma = uri.indexOf(',');
1449
+ if (comma < 0) continue;
1450
+ const meta = uri.slice(0, comma).toLowerCase();
1451
+ const body = uri.slice(comma + 1);
1452
+ if (meta.includes(';base64')) {
1453
+ const b64Raw = body.split('#')[0];
1454
+ try {
1455
+ chunks.push(atob(b64Raw.replace(/\\s+/g, '')));
1456
+ } catch (_) {
1457
+ try { chunks.push(atob(decodeURIComponent(b64Raw).replace(/\\s+/g, ''))); } catch (_) {}
1458
+ }
1459
+ } else {
1460
+ try {
1461
+ chunks.push(decodeURIComponent(body));
1462
+ } catch (_) {
1463
+ chunks.push(body.replace(/%([0-9a-fA-F]{2})/g, (_, h) => String.fromCharCode(parseInt(h, 16))));
1464
+ }
1465
+ }
1466
+ }
1467
+ return chunks.join('\\n');
1468
+ };
1469
+ const checkCssSvgFilterValue = (rawVal, source, selector) => {
1470
+ if (!rawVal || rawVal === 'none') return;
1471
+ const decoded = decodeSvgDataUris(rawVal);
1472
+ if (decoded) {
1473
+ const matches = decoded.match(/(?:feturbulence|fedisplacementmap|feconvolvematrix)/gi);
1474
+ if (matches) {
1475
+ for (const m of matches) {
1476
+ recordExpensiveFilter(source, m.toLowerCase(), selector);
1477
+ }
1478
+ }
1479
+ }
1480
+ if (source === 'css-filter' && rawVal.includes('#')) {
1481
+ const refRe = /url\\(\\s*["']?[^)"']*#([^)"'\\s]+)["']?\\s*\\)/gi;
1482
+ let rm;
1483
+ while ((rm = refRe.exec(rawVal)) !== null) {
1484
+ const target = document.getElementById(rm[1]);
1485
+ if (target && !rootNode.contains(target)) {
1486
+ for (const desc of [target, ...Array.from(target.querySelectorAll('*'))]) {
1487
+ const dln = (desc.localName || desc.tagName || '').toLowerCase();
1488
+ if (canonicalSvgPrim[dln]) {
1489
+ recordExpensiveFilter('referenced-svg-filter', dln, selector);
1490
+ }
1491
+ }
1492
+ }
1493
+ }
1494
+ }
1495
+ };
1496
+ const ancestorNodes = [];
1497
+ let anc = rootNode ? rootNode.parentElement : null;
1498
+ while (anc && anc.nodeType === 1) {
1499
+ ancestorNodes.push(anc);
1500
+ anc = anc.parentElement;
1501
+ }
1502
+ const svgScanNodes = [...ancestorNodes, rootNode, ...allEls];
1503
+ for (const el of svgScanNodes) {
1504
+ if (!el || el.nodeType !== 1) continue;
1505
+ const ln = (el.localName || el.tagName || '').toLowerCase();
1506
+ const sel = describeNode(el, '');
1507
+ if (canonicalSvgPrim[ln]) {
1508
+ recordExpensiveFilter('inline-svg', ln, sel);
1509
+ }
1510
+ if (ln === 'img') {
1511
+ const imgSrc = el.getAttribute('src') || '';
1512
+ if (imgSrc.toLowerCase().includes('data:image/svg+xml')) {
1513
+ checkCssSvgFilterValue(imgSrc, 'img-data-svg', sel);
1514
+ }
1515
+ }
1516
+ const attrFilter = el.getAttribute('filter') || '';
1517
+ if (attrFilter && attrFilter.includes('#')) {
1518
+ checkCssSvgFilterValue(attrFilter, 'css-filter', sel);
1519
+ }
1520
+ const cs = getComputedStyle(el);
1521
+ checkCssSvgFilterValue(cs.backgroundImage, 'css-background-image', sel);
1522
+ checkCssSvgFilterValue(cs.filter, 'css-filter', sel);
1523
+ for (const pseudo of ['::before', '::after']) {
1524
+ const pcs = getComputedStyle(el, pseudo);
1525
+ if (pcs && pcs.content && pcs.content !== 'none') {
1526
+ const psel = describeNode(el, pseudo);
1527
+ checkCssSvgFilterValue(pcs.backgroundImage, 'css-background-image', psel);
1528
+ checkCssSvgFilterValue(pcs.filter, 'css-filter', psel);
1529
+ }
1530
+ }
1531
+ }
1532
+
1533
+ return {
1534
+ innerWidth: window.innerWidth,
1535
+ innerHeight: window.innerHeight,
1536
+ scrollWidth: docEl.scrollWidth,
1537
+ scrollHeight: docEl.scrollHeight,
1538
+ overflowX: docEl.scrollWidth > window.innerWidth,
1539
+ overflowY: docEl.scrollHeight > window.innerHeight,
1540
+ brokenImages: imgs.filter(i => !i.complete || i.naturalWidth === 0),
1541
+ imageCount: imgs.length,
1542
+ allVisibleImgCount,
1543
+ fullBleedImgCount,
1544
+ visibleImages,
1545
+ visibleTextBoxes,
1546
+ visualCards,
1547
+ expensiveSvgFilters,
1548
+ allImgSrcs,
1549
+ domTextLen,
1550
+ svgCount: svgs,
1551
+ headerRect,
1552
+ pageNumRect,
1553
+ };
1554
+ }""",
1555
+ [idx, slide_count],
1556
+ )
1557
+
1558
+ shot_path = out_dir / f"html-s{idx}.png"
1559
+ _safe_page_screenshot(page, shot_path, timeout_ms=15000)
1560
+
1561
+ page.remove_listener("console", on_console)
1562
+ page.remove_listener("pageerror", on_pageerror)
1563
+ page.remove_listener("requestfailed", on_req_failed)
1564
+
1565
+ results.append(
1566
+ {
1567
+ "slide": idx,
1568
+ "screenshot": str(shot_path),
1569
+ "metrics": metrics,
1570
+ "console_errors": console_errors,
1571
+ "page_errors": page_errors,
1572
+ "failed_requests": failed_requests,
1573
+ }
1574
+ )
1575
+
1576
+ # Mandatory non-native interactive viewport scaling check (without ?slide=N)
1577
+ if width > height:
1578
+ vp_w, vp_h = 1120, 680
1579
+ elif width < height:
1580
+ vp_w, vp_h = 680, 900
1581
+ else:
1582
+ vp_w, vp_h = 820, 680
1583
+ vp_context = browser.new_context(
1584
+ viewport={"width": vp_w, "height": vp_h},
1585
+ device_scale_factor=1,
1586
+ )
1587
+ vp_context.set_default_timeout(15000)
1588
+ _attach_local_font_route_guard(vp_context)
1589
+ vp_page = vp_context.new_page()
1590
+ vp_console_errors: list[str] = []
1591
+ vp_page_errors: list[str] = []
1592
+ vp_page.on(
1593
+ "console",
1594
+ lambda msg: vp_console_errors.append(msg.text)
1595
+ if (msg.type == "error" and "favicon.ico" not in msg.text)
1596
+ else None,
1597
+ )
1598
+ vp_page.on("pageerror", lambda err: vp_page_errors.append(str(err)))
1599
+ vp_url = f"http://127.0.0.1:{port}/{rel_url}"
1600
+ vp_page.goto(vp_url, wait_until="domcontentloaded", timeout=20000)
1601
+ vp_page.evaluate(
1602
+ """async () => {
1603
+ if (document.fonts && document.fonts.ready) {
1604
+ await Promise.race([document.fonts.ready, new Promise(r => setTimeout(r, 2500))]);
1605
+ }
1606
+ await Promise.race([
1607
+ new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))),
1608
+ new Promise(r => setTimeout(r, 500)),
1609
+ ]);
1610
+ }"""
1611
+ )
1612
+ vp_page.wait_for_timeout(200)
1613
+ interactive_check = vp_page.evaluate(
1614
+ """() => {
1615
+ const selectors = ['.deck-stage', '[data-stage]', '#deck-stage', '.stage', 'main'];
1616
+ let stageEl = null;
1617
+ let matchedSelector = null;
1618
+ for (const sel of selectors) {
1619
+ const el = document.querySelector(sel);
1620
+ if (el) {
1621
+ const rect = el.getBoundingClientRect();
1622
+ if (rect.width > 0 && rect.height > 0) {
1623
+ stageEl = el;
1624
+ matchedSelector = sel;
1625
+ break;
1626
+ }
1627
+ }
1628
+ }
1629
+ const slideEl = Array.from(
1630
+ document.querySelectorAll('.slide.is-active, .slide.active, [data-slide="1"], section')
1631
+ ).find(el => {
1632
+ const r = el.getBoundingClientRect();
1633
+ return r.width > 0 && r.height > 0;
1634
+ }) || null;
1635
+ const targetEl = stageEl || slideEl;
1636
+ const rect = targetEl ? targetEl.getBoundingClientRect() : null;
1637
+ const slideRect = slideEl ? slideEl.getBoundingClientRect() : null;
1638
+ const docEl = document.documentElement;
1639
+ return {
1640
+ viewport: { width: window.innerWidth, height: window.innerHeight },
1641
+ matchedSelector,
1642
+ stageOffset: targetEl ? {
1643
+ width: targetEl.offsetWidth,
1644
+ height: targetEl.offsetHeight,
1645
+ } : null,
1646
+ slideOffset: slideEl ? {
1647
+ width: slideEl.offsetWidth,
1648
+ height: slideEl.offsetHeight,
1649
+ } : null,
1650
+ stageRect: rect ? {
1651
+ left: Math.round(rect.left * 10) / 10,
1652
+ top: Math.round(rect.top * 10) / 10,
1653
+ right: Math.round(rect.right * 10) / 10,
1654
+ bottom: Math.round(rect.bottom * 10) / 10,
1655
+ width: Math.round(rect.width * 10) / 10,
1656
+ height: Math.round(rect.height * 10) / 10,
1657
+ } : null,
1658
+ slideRect: slideRect ? {
1659
+ left: Math.round(slideRect.left * 10) / 10,
1660
+ top: Math.round(slideRect.top * 10) / 10,
1661
+ right: Math.round(slideRect.right * 10) / 10,
1662
+ bottom: Math.round(slideRect.bottom * 10) / 10,
1663
+ width: Math.round(slideRect.width * 10) / 10,
1664
+ height: Math.round(slideRect.height * 10) / 10,
1665
+ } : null,
1666
+ scrollWidth: docEl.scrollWidth,
1667
+ scrollHeight: docEl.scrollHeight,
1668
+ };
1669
+ }"""
1670
+ )
1671
+ vp_shot = out_dir / f"interactive-{vp_w}x{vp_h}.png"
1672
+ _safe_page_screenshot(vp_page, vp_shot, timeout_ms=15000)
1673
+ interactive_check["screenshot"] = str(vp_shot)
1674
+ interactive_check["console_errors"] = vp_console_errors
1675
+ interactive_check["page_errors"] = vp_page_errors
1676
+ vp_context.close()
1677
+ browser.close()
1678
+ finally:
1679
+ server.shutdown()
1680
+ server.server_close()
1681
+
1682
+ def _detect_transparent_edge_clip(img_path: Path, alpha_threshold: int = 160) -> dict[str, tuple[int, float]]:
1683
+ try:
1684
+ with Image.open(img_path) as raw_im:
1685
+ if raw_im.mode not in ("RGBA", "LA", "PA") and "transparency" not in raw_im.info:
1686
+ return {}
1687
+ rgba = raw_im.convert("RGBA")
1688
+ w, h = rgba.size
1689
+ if w < 16 or h < 16:
1690
+ return {}
1691
+ alpha = rgba.getchannel("A")
1692
+ lo, _ = alpha.getextrema()
1693
+ if lo >= 248:
1694
+ return {}
1695
+ px = alpha.load()
1696
+ edges = {
1697
+ "top": [max(int(px[x, 0]), int(px[x, min(1, h - 1)])) for x in range(w)],
1698
+ "bottom": [max(int(px[x, h - 1]), int(px[x, max(0, h - 2)])) for x in range(w)],
1699
+ "left": [max(int(px[0, y]), int(px[min(1, w - 1), y])) for y in range(h)],
1700
+ "right": [max(int(px[w - 1, y]), int(px[max(0, w - 2), y])) for y in range(h)],
1701
+ }
1702
+ except Exception:
1703
+ return {}
1704
+ stats: dict[str, tuple[int, float]] = {}
1705
+ for side_name, vals in edges.items():
1706
+ max_run = 0
1707
+ cur = 0
1708
+ for a in vals:
1709
+ if a >= alpha_threshold:
1710
+ cur += 1
1711
+ if cur > max_run:
1712
+ max_run = cur
1713
+ else:
1714
+ cur = 0
1715
+ stats[side_name] = (max_run, max_run / float(max(1, len(vals))))
1716
+ return stats
1717
+
1718
+ baked_ref_re = re.compile(
1719
+ r"assets/reference/(?:s\d+|deck-2x2|overview[^\s\"'()]*)\.(?:png|jpe?g|webp)",
1720
+ re.IGNORECASE,
1721
+ )
1722
+ crop_cutout_re = re.compile(r"(?:^|/)assets/(?:crops|cutouts)/", re.IGNORECASE)
1723
+ residual_text_cache: dict[Path, dict[str, Any]] = {}
1724
+ slide_area = float(max(1, width * height))
1725
+ issues: list[str] = []
1726
+ warnings: list[str] = []
1727
+ for item in results:
1728
+ m = item["metrics"]
1729
+ if m["overflowX"] or m["overflowY"]:
1730
+ issues.append(f"Slide {item['slide']}: viewport overflow ({m['scrollWidth']}x{m['scrollHeight']})")
1731
+ if m["brokenImages"]:
1732
+ issues.append(f"Slide {item['slide']}: {len(m['brokenImages'])} broken images")
1733
+ if item["page_errors"]:
1734
+ issues.append(f"Slide {item['slide']}: page errors {item['page_errors']}")
1735
+
1736
+ expensive_filters = m.get("expensiveSvgFilters") or []
1737
+ if expensive_filters:
1738
+ summary = ", ".join(
1739
+ f"{f.get('primitive', 'svg-filter')} ({f.get('source', 'dom')} on {f.get('selector', 'slide')})"
1740
+ for f in expensive_filters[:4]
1741
+ )
1742
+ issues.append(
1743
+ f"Slide {item['slide']}: expensive-svg-filter — detected expensive SVG filter(s): {summary}; "
1744
+ "remove feTurbulence/feDisplacementMap/feConvolveMatrix and use lightweight CSS gradients or assets/plates/."
1745
+ )
1746
+
1747
+ baked_hits = sorted(
1748
+ {
1749
+ src
1750
+ for src in (m.get("allImgSrcs") or [])
1751
+ if baked_ref_re.search(str(src or ""))
1752
+ }
1753
+ )
1754
+ if baked_hits:
1755
+ issues.append(
1756
+ f"Slide {item['slide']}: baked-reference-embed — embedded text-baked Stage-1 reference draft(s) "
1757
+ f"{baked_hits!r}; extract clean illustrations into assets/crops/ or text-free backdrops into "
1758
+ f"assets/plates/ and render all text natively in HTML."
1759
+ )
1760
+
1761
+ vis_imgs = m.get("visibleImages") or []
1762
+ dom_text_len = int(m.get("domTextLen") or 0)
1763
+ has_full_bleed_img = any(
1764
+ (int(im_info.get("w") or 0) * int(im_info.get("h") or 0)) >= 0.70 * slide_area
1765
+ for im_info in vis_imgs
1766
+ )
1767
+ if has_full_bleed_img and dom_text_len < 2:
1768
+ issues.append(
1769
+ f"Slide {item['slide']}: image-only-slide — full-bleed <img> covers >=70% of canvas with "
1770
+ f"near-zero editable HTML text (domTextLen={dom_text_len}); rebuild text and labels as native HTML."
1771
+ )
1772
+ checked_residual_paths: set[Path] = set()
1773
+ for im_info in vis_imgs:
1774
+ src_raw = str(im_info.get("src") or "").split("?", 1)[0].split("#", 1)[0]
1775
+ if not src_raw or src_raw.startswith(("http://", "https://", "data:")):
1776
+ continue
1777
+ cand_abs = (html_path.parent / src_raw).resolve()
1778
+ if not cand_abs.is_file():
1779
+ continue
1780
+ src_norm = src_raw.replace("\\", "/")
1781
+ if (
1782
+ cand_abs not in checked_residual_paths
1783
+ and (crop_cutout_re.search(src_norm) or crop_cutout_re.search(cand_abs.as_posix()))
1784
+ ):
1785
+ checked_residual_paths.add(cand_abs)
1786
+ res_txt = residual_text_cache.get(cand_abs)
1787
+ if res_txt is None:
1788
+ try:
1789
+ with Image.open(cand_abs) as crop_im:
1790
+ res_txt = ca.detect_residual_crop_text(crop_im)
1791
+ except Exception:
1792
+ res_txt = {"has_residual_text": False, "edges": [], "bands": []}
1793
+ residual_text_cache[cand_abs] = res_txt
1794
+ if res_txt.get("has_residual_text"):
1795
+ edges_lbl = "/".join(res_txt.get("edges") or [])
1796
+ band_desc = ", ".join(
1797
+ f"{b['edge']}({b['glyph_count']} glyphs, h={b['band_height']}px, gap={b['gap_px']}px)"
1798
+ for b in (res_txt.get("bands") or [])
1799
+ )
1800
+ issues.append(
1801
+ f"Slide {item['slide']}: residual-crop-text — transparent <img> {cand_abs.name!r} "
1802
+ f"contains a detached glyph-like text band near the {edges_lbl.upper()} edge ({band_desc}); "
1803
+ "tighten the crop bbox away from slide text or re-extract a clean cutout."
1804
+ )
1805
+ ix, iy, iw, ih = int(im_info["x"]), int(im_info["y"]), int(im_info["w"]), int(im_info["h"])
1806
+ if ix <= 4 and iy <= 4 and iw >= width - 8 and ih >= height - 8:
1807
+ continue
1808
+ edge_stats = _detect_transparent_edge_clip(cand_abs)
1809
+ if not edge_stats:
1810
+ continue
1811
+ # Standard rounded-rect window/card screenshots have all 4 straight edges >= 80% opaque with transparent corners — NOT chopped cutouts
1812
+ if all(edge_stats.get(side, (0, 0.0))[1] >= 0.80 for side in ("top", "bottom", "left", "right")):
1813
+ continue
1814
+
1815
+ def _abuts_sibling(side_name: str) -> bool:
1816
+ for other in vis_imgs:
1817
+ if other is im_info:
1818
+ continue
1819
+ ox, oy, ow, oh = int(other["x"]), int(other["y"]), int(other["w"]), int(other["h"])
1820
+ if side_name == "top" and abs((oy + oh) - iy) <= 4 and min(ix + iw, ox + ow) - max(ix, ox) >= 24:
1821
+ return True
1822
+ if side_name == "bottom" and abs(oy - (iy + ih)) <= 4 and min(ix + iw, ox + ow) - max(ix, ox) >= 24:
1823
+ return True
1824
+ if side_name == "left" and abs((ox + ow) - ix) <= 4 and min(iy + ih, oy + oh) - max(iy, oy) >= 24:
1825
+ return True
1826
+ if side_name == "right" and abs(ox - (ix + iw)) <= 4 and min(iy + ih, oy + oh) - max(iy, oy) >= 24:
1827
+ return True
1828
+ return False
1829
+
1830
+ is_framed = bool(im_info.get("framed"))
1831
+ clipped_edges = im_info.get("clippedEdges") if isinstance(im_info.get("clippedEdges"), dict) else {}
1832
+ flip_x = bool(im_info.get("flipX"))
1833
+ flip_y = bool(im_info.get("flipY"))
1834
+ for side_name, is_floating, gap_px in (
1835
+ ("top", iy > 4, iy),
1836
+ ("bottom", iy + ih < height - 4, height - (iy + ih)),
1837
+ ("left", ix > 4, ix),
1838
+ ("right", ix + iw < width - 4, width - (ix + iw)),
1839
+ ):
1840
+ if not is_floating or _abuts_sibling(side_name) or clipped_edges.get(side_name):
1841
+ continue
1842
+ src_side = side_name
1843
+ if flip_x and side_name in ("left", "right"):
1844
+ src_side = "right" if side_name == "left" else "left"
1845
+ elif flip_y and side_name in ("top", "bottom"):
1846
+ src_side = "bottom" if side_name == "top" else "top"
1847
+ run_px, run_ratio = edge_stats.get(src_side, (0, 0.0))
1848
+ pct = int(round(run_ratio * 100))
1849
+ if not is_framed and run_ratio >= 0.25 and run_px >= 64 and max(iw, ih) >= 160:
1850
+ issues.append(
1851
+ f"Slide {item['slide']}: floating-bleed-cutout — transparent <img> {cand_abs.name!r} has a "
1852
+ f"hard clipped {side_name.upper()} edge ({pct}% opaque flush) floating {gap_px}px from the "
1853
+ f"slide {side_name} edge; anchor it flush with `{side_name}: 0;` or re-extract unclipped."
1854
+ )
1855
+ elif run_ratio >= 0.10 and run_px >= 24:
1856
+ warnings.append(
1857
+ f"Slide {item['slide']}: floating transparent <img> {cand_abs.name!r} touches its "
1858
+ f"{side_name.upper()} edge ({pct}% opaque flush) — check visually if subject is clipped."
1859
+ )
1860
+
1861
+ vis_text_boxes = m.get("visibleTextBoxes") or []
1862
+ vis_cards = m.get("visualCards") or []
1863
+ contrast_blocks, contrast_warns = evaluate_rendered_text_contrast(
1864
+ Path(item["screenshot"]),
1865
+ vis_text_boxes,
1866
+ canvas_w=width,
1867
+ canvas_h=height,
1868
+ )
1869
+ item["contrast_issues"] = contrast_blocks
1870
+ item["contrast_warnings"] = contrast_warns
1871
+ for hit in contrast_blocks:
1872
+ issues.append(
1873
+ f"Slide {item['slide']}: low-contrast-text — {hit['text']!r} has {hit['contrast']:.2f}:1 "
1874
+ f"rendered contrast (text RGB {hit['text_rgb']} on bg RGB {hit['bg_rgb']} at ({hit['x']},{hit['y']})); "
1875
+ "fix text color or backdrop contrast."
1876
+ )
1877
+ for warn in contrast_warns:
1878
+ warnings.append(
1879
+ f"Slide {item['slide']}: borderline-contrast-text — {warn['text']!r} has {warn['contrast']:.2f}:1 "
1880
+ f"rendered contrast (text RGB {warn['text_rgb']} on bg RGB {warn['bg_rgb']})."
1881
+ )
1882
+
1883
+ card_overflows = evaluate_text_card_containment(
1884
+ vis_text_boxes,
1885
+ vis_cards,
1886
+ canvas_w=width,
1887
+ )
1888
+ item["card_overflow_issues"] = card_overflows
1889
+ for ov in card_overflows:
1890
+ issues.append(
1891
+ f"Slide {item['slide']}: text-overflows-card — {ov['text']!r} overflows card {ov['card_id']} "
1892
+ f"(right=+{ov['overflow_right_px']}px, bottom=+{ov['overflow_bottom_px']}px); {ov['hint']}"
1893
+ )
1894
+
1895
+ # Evaluate interactive viewport scaling & aspect-ratio check
1896
+ expected_aspect = float(width) / float(max(1, height))
1897
+ stage_rect = interactive_check.get("stageRect")
1898
+ slide_rect = interactive_check.get("slideRect")
1899
+ stage_off = interactive_check.get("stageOffset")
1900
+ slide_off = interactive_check.get("slideOffset")
1901
+ if not stage_rect:
1902
+ issues.append(
1903
+ f"stage-overflow: no visible stage element (.deck-stage / [data-stage] / main) found at {vp_w}x{vp_h}"
1904
+ )
1905
+ else:
1906
+ for label, r, off in (("stage", stage_rect, stage_off), ("slide", slide_rect, slide_off)):
1907
+ if not r:
1908
+ continue
1909
+ if r["left"] < -2 or r["top"] < -2 or r["right"] > vp_w + 2 or r["bottom"] > vp_h + 2:
1910
+ issues.append(
1911
+ f"stage-overflow: interactive {vp_w}x{vp_h} {label} extends outside viewport "
1912
+ f"(left={r['left']}, top={r['top']}, right={r['right']}, bottom={r['bottom']})"
1913
+ )
1914
+ elif r["width"] > vp_w + 2 or r["height"] > vp_h + 2:
1915
+ issues.append(
1916
+ f"stage-overflow: interactive {vp_w}x{vp_h} {label} failed to scale down "
1917
+ f"({r['width']}x{r['height']})"
1918
+ )
1919
+ if r["height"] > 0:
1920
+ ratio_err = abs((r["width"] / r["height"]) - expected_aspect)
1921
+ if ratio_err > 0.03:
1922
+ issues.append(
1923
+ f"stage-overflow: interactive {vp_w}x{vp_h} {label} aspect ratio distorted "
1924
+ f"({r['width']}x{r['height']}, ratio={r['width'] / r['height']:.3f} != {expected_aspect:.3f})"
1925
+ )
1926
+ if off and (off["width"] != width or off["height"] != height):
1927
+ # Allow outer <main> wrapper when inner slide itself is width x height
1928
+ if not (label == "stage" and interactive_check.get("matchedSelector") == "main" and slide_off == {"width": width, "height": height}):
1929
+ issues.append(
1930
+ f"stage-overflow: interactive {vp_w}x{vp_h} {label} logical size shrunk "
1931
+ f"(offset={off['width']}x{off['height']} != {width}x{height})"
1932
+ )
1933
+ if interactive_check.get("page_errors"):
1934
+ issues.append(f"interactive {vp_w}x{vp_h} page errors: {interactive_check['page_errors']}")
1935
+
1936
+ return {
1937
+ "ok": len(issues) == 0,
1938
+ "width": width,
1939
+ "height": height,
1940
+ "issues": issues,
1941
+ "warnings": warnings,
1942
+ "slides": results,
1943
+ "interactive_viewport_check": interactive_check,
1944
+ }
1945
+
1946
+
1947
+ def render_pptx_to_pngs(pptx_path: Path, out_dir: Path) -> dict[str, Any]:
1948
+ out_dir.mkdir(parents=True, exist_ok=True)
1949
+ for old in out_dir.glob("pptx-s*.png"):
1950
+ old.unlink()
1951
+
1952
+ pdftoppm = shutil.which("pdftoppm")
1953
+ soffice = find_soffice()
1954
+ if soffice:
1955
+ with tempfile.TemporaryDirectory(prefix="pptx-pdf-") as tmp:
1956
+ tmp_dir = Path(tmp)
1957
+ proc = subprocess.run(
1958
+ [soffice, "--headless", "--convert-to", "pdf", "--outdir", str(tmp_dir), str(pptx_path)],
1959
+ capture_output=True,
1960
+ text=True,
1961
+ timeout=90,
1962
+ )
1963
+ pdfs = list(tmp_dir.glob("*.pdf"))
1964
+ if proc.returncode == 0 and pdfs and pdftoppm:
1965
+ prefix = tmp_dir / "slide"
1966
+ p2 = subprocess.run(
1967
+ [pdftoppm, "-png", "-r", "144", str(pdfs[0]), str(prefix)],
1968
+ capture_output=True,
1969
+ text=True,
1970
+ timeout=90,
1971
+ )
1972
+ pages = sorted(tmp_dir.glob("slide-*.png"))
1973
+ if p2.returncode == 0 and pages:
1974
+ saved = []
1975
+ for i, src in enumerate(pages, start=1):
1976
+ dst = out_dir / f"pptx-s{i}.png"
1977
+ shutil.copy2(src, dst)
1978
+ saved.append(str(dst))
1979
+ return {"renderer": "libreoffice+pdftoppm", "ok": True, "images": saved}
1980
+ return {
1981
+ "renderer": "libreoffice",
1982
+ "ok": False,
1983
+ "error": f"rc={proc.returncode} stderr={proc.stderr.strip()}",
1984
+ "images": [],
1985
+ }
1986
+
1987
+ # macOS Keynote PDF export + pdftoppm fallback (avoids qlmanage PDF-in-<img> broken shapes)
1988
+ keynote_app = Path("/Applications/Keynote.app")
1989
+ if sys.platform == "darwin" and keynote_app.exists() and pdftoppm:
1990
+ import fcntl
1991
+ import time as _time
1992
+
1993
+ lock_path = Path(tempfile.gettempdir()) / "oil-ppt-keynote-export.lock"
1994
+ with open(lock_path, "w") as lock_fp:
1995
+ fcntl.flock(lock_fp.fileno(), fcntl.LOCK_EX)
1996
+ try:
1997
+ # Ensure Keynote is running in the background before AppleScript touches it (avoids -600)
1998
+ subprocess.run(
1999
+ ["open", "-g", "-a", "Keynote"],
2000
+ capture_output=True,
2001
+ text=True,
2002
+ timeout=15,
2003
+ )
2004
+ with tempfile.TemporaryDirectory(prefix="pptx-keynote-") as tmp:
2005
+ tmp_dir = Path(tmp)
2006
+ pdf_out = tmp_dir / "deck.pdf"
2007
+ abs_pptx = str(pptx_path.resolve())
2008
+ script = f'''
2009
+ tell application "Keynote"
2010
+ launch
2011
+ set theDoc to open POSIX file "{abs_pptx}"
2012
+ export theDoc to POSIX file "{pdf_out}" as PDF with properties {{PDF image quality:Best}}
2013
+ close theDoc saving no
2014
+ end tell
2015
+ '''
2016
+ proc = None
2017
+ for attempt in range(2):
2018
+ try:
2019
+ proc = subprocess.run(
2020
+ ["osascript", "-e", script],
2021
+ capture_output=True,
2022
+ text=True,
2023
+ timeout=60,
2024
+ )
2025
+ except subprocess.TimeoutExpired:
2026
+ return {
2027
+ "renderer": "keynote+pdftoppm",
2028
+ "ok": False,
2029
+ "error": "Keynote AppleScript export timed out (60s)",
2030
+ "images": [],
2031
+ }
2032
+ if proc.returncode == 0 and pdf_out.is_file():
2033
+ break
2034
+ if attempt == 0 and ("-600" in (proc.stderr or "") or "not running" in (proc.stderr or "").lower()):
2035
+ subprocess.run(["open", "-g", "-a", "Keynote"], capture_output=True, timeout=15)
2036
+ _time.sleep(2.0)
2037
+ continue
2038
+ break
2039
+
2040
+ if proc and proc.returncode == 0 and pdf_out.is_file():
2041
+ prefix = tmp_dir / "slide"
2042
+ p2 = subprocess.run(
2043
+ [pdftoppm, "-png", "-r", "144", str(pdf_out), str(prefix)],
2044
+ capture_output=True,
2045
+ text=True,
2046
+ timeout=60,
2047
+ )
2048
+ pages = sorted(tmp_dir.glob("slide-*.png"))
2049
+ if p2.returncode == 0 and pages:
2050
+ saved = []
2051
+ for i, src in enumerate(pages, start=1):
2052
+ dst = out_dir / f"pptx-s{i}.png"
2053
+ shutil.copy2(src, dst)
2054
+ saved.append(str(dst))
2055
+ return {"renderer": "keynote+pdftoppm", "ok": True, "images": saved}
2056
+ return {
2057
+ "renderer": "keynote+pdftoppm",
2058
+ "ok": False,
2059
+ "error": f"rc={proc.returncode if proc else -1} stderr={(proc.stderr if proc else '').strip()}",
2060
+ "images": [],
2061
+ }
2062
+ finally:
2063
+ fcntl.flock(lock_fp.fileno(), fcntl.LOCK_UN)
2064
+
2065
+ return {
2066
+ "renderer": "none",
2067
+ "ok": False,
2068
+ "error": "Neither LibreOffice (soffice) nor macOS Keynote+pdftoppm is available",
2069
+ "images": [],
2070
+ }
2071
+
2072
+
2073
+ def _rgb_hex(fill: Any) -> str | None:
2074
+ try:
2075
+ if fill.type is None:
2076
+ return None
2077
+ fc = fill.fore_color
2078
+ if fc and fc.rgb is not None:
2079
+ return f"#{str(fc.rgb).upper()}"
2080
+ except Exception:
2081
+ return None
2082
+ return None
2083
+
2084
+
2085
+ PPTX_SIZE_WARNING_BYTES = 15 * 1024 * 1024
2086
+
2087
+ _CROSS_PLATFORM_SAFE_FONTS = {
2088
+ "arial",
2089
+ "arial black",
2090
+ "calibri",
2091
+ "cambria",
2092
+ "consolas",
2093
+ "courier new",
2094
+ "dejavu sans",
2095
+ "dejavu serif",
2096
+ "georgia",
2097
+ "helvetica",
2098
+ "helvetica neue",
2099
+ "hiragino sans gb",
2100
+ "liberation sans",
2101
+ "liberation serif",
2102
+ "menlo",
2103
+ "microsoft yahei",
2104
+ "noto sans",
2105
+ "noto serif",
2106
+ "pingfang sc",
2107
+ "segoe ui",
2108
+ "simhei",
2109
+ "simsun",
2110
+ "songti sc",
2111
+ "source han sans",
2112
+ "source han serif",
2113
+ "stsongti-sc-black",
2114
+ "tahoma",
2115
+ "times new roman",
2116
+ "trebuchet ms",
2117
+ "verdana",
2118
+ }
2119
+
2120
+
2121
+ def audit_pptx(
2122
+ pptx_path: Path,
2123
+ spec_path: Path | None = None,
2124
+ expected_width: int | None = None,
2125
+ expected_height: int | None = None,
2126
+ ) -> dict[str, Any]:
2127
+ from pptx import Presentation
2128
+ from pptx.enum.shapes import MSO_SHAPE_TYPE
2129
+ from pptx.oxml.ns import qn
2130
+
2131
+ if not pptx_path.is_file():
2132
+ return {"ok": False, "error": f"Missing PPTX file: {pptx_path}", "issues": [f"Missing {pptx_path}"], "warnings": []}
2133
+
2134
+ spec: dict[str, Any] = {}
2135
+ if spec_path and spec_path.is_file():
2136
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
2137
+
2138
+ pptx_bytes = pptx_path.stat().st_size
2139
+ pptx_size_mb = round(pptx_bytes / (1024.0 * 1024.0), 2)
2140
+
2141
+ prs = Presentation(str(pptx_path))
2142
+ width_in = prs.slide_width.inches
2143
+ height_in = prs.slide_height.inches
2144
+ actual_ratio = width_in / max(1e-6, height_in)
2145
+ if expected_width is not None and expected_height is not None and expected_height > 0:
2146
+ target_ratios = [(float(expected_width) / float(expected_height), f"{expected_width}:{expected_height}")]
2147
+ elif isinstance(spec.get("canvas"), dict) and spec["canvas"].get("width") and spec["canvas"].get("height"):
2148
+ cw = float(spec["canvas"]["width"])
2149
+ ch = float(spec["canvas"]["height"])
2150
+ target_ratios = [(cw / ch, f"{int(cw)}:{int(ch)}")]
2151
+ else:
2152
+ target_ratios = [
2153
+ (16.0 / 9.0, "16:9"),
2154
+ (3.0 / 4.0, "3:4"),
2155
+ (9.0 / 16.0, "9:16"),
2156
+ (1.0, "1:1"),
2157
+ ]
2158
+ ratio_ok = any(abs(actual_ratio - tr) < 0.02 for tr, _ in target_ratios)
2159
+
2160
+ issues: list[str] = []
2161
+ warnings: list[str] = []
2162
+ if pptx_bytes > PPTX_SIZE_WARNING_BYTES:
2163
+ warnings.append(
2164
+ f"pptx-file-size — PPTX is {pptx_size_mb:.2f} MB (> 15 MB); "
2165
+ "compress large opaque images to JPEG or inspect embedded PNG assets."
2166
+ )
2167
+ if not ratio_ok:
2168
+ expected_lbl = target_ratios[0][1] if len(target_ratios) == 1 else "16:9 / 3:4 / 9:16 / 1:1"
2169
+ issues.append(f"Slide ratio {width_in:.3f}x{height_in:.3f} in is not {expected_lbl}")
2170
+
2171
+ spec_slides = spec.get("slides", []) if isinstance(spec, dict) else []
2172
+ if spec_slides and len(prs.slides) != len(spec_slides):
2173
+ issues.append(f"Expected {len(spec_slides)} slides from spec, got {len(prs.slides)}")
2174
+ elif not prs.slides:
2175
+ issues.append("PPTX contains 0 slides")
2176
+
2177
+ slides_report: list[dict[str, Any]] = []
2178
+ arial_black_slides: list[int] = []
2179
+ nonstandard_fonts: set[str] = set()
2180
+ for s_idx, slide in enumerate(prs.slides, start=1):
2181
+ slide_spec = spec_slides[s_idx - 1] if s_idx <= len(spec_slides) else {}
2182
+ tier = str(slide_spec.get("tier", "")).upper()
2183
+ slide_type = str(slide_spec.get("type", "")).lower()
2184
+
2185
+ text_shapes = 0
2186
+ non_empty_texts: list[str] = []
2187
+ fonts: set[str] = set()
2188
+ pictures: list[dict[str, Any]] = []
2189
+ auto_shapes = 0
2190
+ fill_counts: dict[str, int] = {}
2191
+ tile_candidates: list[tuple[float, float, str]] = []
2192
+
2193
+ bg_el = slide._element.cSld.find(qn("p:bg"))
2194
+ has_picture_bg = bool(bg_el is not None and bg_el.find(".//" + qn("a:blip")) is not None)
2195
+
2196
+ def _collect_tf_fonts(tf: Any) -> None:
2197
+ for para in tf.paragraphs:
2198
+ if para.font and para.font.name:
2199
+ fonts.add(para.font.name)
2200
+ for run in para.runs:
2201
+ if run.font and run.font.name:
2202
+ fonts.add(run.font.name)
2203
+ r_pr = run._r.find(qn("a:rPr"))
2204
+ if r_pr is not None:
2205
+ latin_el = r_pr.find(qn("a:latin"))
2206
+ if latin_el is not None and latin_el.get("typeface"):
2207
+ fonts.add(str(latin_el.get("typeface")))
2208
+
2209
+ for shape in slide.shapes:
2210
+ if shape.has_table:
2211
+ for row in shape.table.rows:
2212
+ for cell in row.cells:
2213
+ ctxt = cell.text_frame.text.strip()
2214
+ if ctxt:
2215
+ text_shapes += 1
2216
+ non_empty_texts.append(ctxt[:60])
2217
+ _collect_tf_fonts(cell.text_frame)
2218
+ elif shape.has_text_frame:
2219
+ txt = shape.text_frame.text.strip()
2220
+ if txt:
2221
+ text_shapes += 1
2222
+ non_empty_texts.append(txt[:60])
2223
+ _collect_tf_fonts(shape.text_frame)
2224
+
2225
+ if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
2226
+ blob = shape.image.blob
2227
+ pictures.append(
2228
+ {
2229
+ "name": shape.name,
2230
+ "size_px": list(shape.image.size),
2231
+ "sha256_prefix": hashlib.sha256(blob).hexdigest()[:12],
2232
+ "left_in": round(shape.left.inches, 3),
2233
+ "top_in": round(shape.top.inches, 3),
2234
+ "width_in": round(shape.width.inches, 3),
2235
+ "height_in": round(shape.height.inches, 3),
2236
+ }
2237
+ )
2238
+
2239
+ if shape.shape_type == MSO_SHAPE_TYPE.AUTO_SHAPE:
2240
+ auto_shapes += 1
2241
+ hex_c = _rgb_hex(shape.fill)
2242
+ if hex_c:
2243
+ fill_counts[hex_c] = fill_counts.get(hex_c, 0) + 1
2244
+ # Filter out tiny indicator dots (< 0.25 in) and full-width rules when checking grid tiles
2245
+ w_in = shape.width.inches
2246
+ h_in = shape.height.inches
2247
+ if 0.25 <= w_in <= 2.5 and 0.25 <= h_in <= 2.5:
2248
+ tile_candidates.append((round(shape.top.inches, 3), round(shape.left.inches, 3), hex_c))
2249
+
2250
+ for fname in fonts:
2251
+ fl = fname.strip().lower()
2252
+ if fl == "arial black":
2253
+ if s_idx not in arial_black_slides:
2254
+ arial_black_slides.append(s_idx)
2255
+ elif fl and fl not in _CROSS_PLATFORM_SAFE_FONTS and not fl.startswith("+"):
2256
+ nonstandard_fonts.add(fname)
2257
+
2258
+ if text_shapes == 0:
2259
+ issues.append(f"Slide {s_idx}: no editable non-empty text frames")
2260
+
2261
+ # T1 cover plate check
2262
+ if tier == "T1" or slide_type == "cover_t1" or (
2263
+ isinstance(slide_spec.get("background"), dict) and slide_spec["background"].get("plate")
2264
+ ):
2265
+ if not has_picture_bg and not any(
2266
+ p["width_in"] >= width_in * 0.75 and p["height_in"] >= height_in * 0.73 for p in pictures
2267
+ ):
2268
+ issues.append(f"Slide {s_idx} (T1): missing full-bleed background plate image")
2269
+
2270
+ # T3 proportion grid check when spec defines a grid
2271
+ grid_spec = slide_spec.get("grid") if isinstance(slide_spec, dict) else None
2272
+ if isinstance(grid_spec, dict):
2273
+ expected_total = int(grid_spec.get("totalTiles") or (grid_spec.get("cols", 0) * grid_spec.get("rows", 0)))
2274
+ lit_color = str(grid_spec.get("litColor", "#4D6BFE")).upper()
2275
+ expected_lit = grid_spec.get("litTiles", [])
2276
+ if expected_total > 0:
2277
+ if len(tile_candidates) < expected_total:
2278
+ issues.append(f"Slide {s_idx}: expected {expected_total} native grid tiles, found {len(tile_candidates)}")
2279
+ lit_tiles = [(t, l) for (t, l, c) in tile_candidates if c == lit_color]
2280
+ if expected_lit and len(lit_tiles) != len(expected_lit):
2281
+ issues.append(
2282
+ f"Slide {s_idx}: expected {len(expected_lit)} {lit_color} grid tiles, found {len(lit_tiles)}"
2283
+ )
2284
+ elif expected_lit and len(tile_candidates) == expected_total:
2285
+ ys = sorted({t for (t, _, _) in tile_candidates})
2286
+ xs = sorted({l for (_, l, _) in tile_candidates})
2287
+ actual_rc = sorted([ys.index(t), xs.index(l)] for (t, l) in lit_tiles)
2288
+ if actual_rc != sorted(expected_lit):
2289
+ issues.append(f"Slide {s_idx}: lit tile coords {actual_rc} != spec {sorted(expected_lit)}")
2290
+
2291
+ if slide_type == "bar_chart_t3":
2292
+ bars = slide_spec.get("bars") or []
2293
+ if auto_shapes < len(bars):
2294
+ issues.append(f"Slide {s_idx} (bar_chart_t3): expected >= {len(bars)} bar shapes, got {auto_shapes}")
2295
+ if text_shapes < len(bars) + 1:
2296
+ issues.append(f"Slide {s_idx} (bar_chart_t3): expected >= {len(bars) + 1} text frames")
2297
+ elif slide_type == "proportion_bar_t3":
2298
+ segs = slide_spec.get("segments") or []
2299
+ if auto_shapes < len(segs):
2300
+ issues.append(f"Slide {s_idx} (proportion_bar_t3): expected >= {len(segs)} segment shapes, got {auto_shapes}")
2301
+ elif slide_type == "spec_table_t3":
2302
+ rows = slide_spec.get("rows") or []
2303
+ cols = slide_spec.get("columns") or []
2304
+ if auto_shapes < len(rows):
2305
+ issues.append(f"Slide {s_idx} (spec_table_t3): expected >= {len(rows)} hairline/symbol shapes, got {auto_shapes}")
2306
+ if text_shapes < len(cols) + len(rows):
2307
+ issues.append(f"Slide {s_idx} (spec_table_t3): expected >= {len(cols) + len(rows)} text frames")
2308
+ elif slide_type == "step_columns_t3":
2309
+ cols = slide_spec.get("columns") or slide_spec.get("steps") or []
2310
+ if auto_shapes < len(cols) * 2:
2311
+ issues.append(f"Slide {s_idx} (step_columns_t3): expected >= {len(cols) * 2} shapes, got {auto_shapes}")
2312
+
2313
+ # T3 / T4 must not cheat with a full-slide raster screenshot (except gradient backdrop on proportion_bar_t3)
2314
+ bg_spec = slide_spec.get("background") if isinstance(slide_spec.get("background"), dict) else {}
2315
+ has_grad_backdrop = slide_type == "proportion_bar_t3" and (
2316
+ bool(slide_spec.get("gradient")) or bg_spec.get("type") == "monochrome-gradient"
2317
+ )
2318
+ if tier in ("T3", "T4") and not has_grad_backdrop:
2319
+ if any(p["width_in"] > width_in * 0.75 and p["height_in"] > height_in * 0.66 for p in pictures):
2320
+ issues.append(f"Slide {s_idx} ({tier}): contains full-slide raster image instead of native shapes")
2321
+
2322
+ slides_report.append(
2323
+ {
2324
+ "slide": s_idx,
2325
+ "tier": tier or None,
2326
+ "layout": slide_type or None,
2327
+ "total_shapes": len(slide.shapes),
2328
+ "editable_text_frames": text_shapes,
2329
+ "auto_shapes": auto_shapes,
2330
+ "fill_counts": fill_counts,
2331
+ "has_picture_bg": has_picture_bg,
2332
+ "pictures_count": len(pictures),
2333
+ "pictures": pictures,
2334
+ "fonts": sorted(fonts),
2335
+ "sample_texts": non_empty_texts[:6],
2336
+ }
2337
+ )
2338
+
2339
+ if arial_black_slides:
2340
+ sl_lbl = ", ".join(f"s{n}" for n in arial_black_slides)
2341
+ warnings.append(
2342
+ f"pptx-heavy-font-widening — Slide(s) {sl_lbl} use 'Arial Black' (mapped from font-weight >= 800), "
2343
+ "which renders wider than web sans fonts in Keynote/PowerPoint; verify headline wraps or use weight 700."
2344
+ )
2345
+ if nonstandard_fonts:
2346
+ f_lbl = ", ".join(sorted(nonstandard_fonts)[:6])
2347
+ warnings.append(
2348
+ f"pptx-nonstandard-font — Font(s) [{f_lbl}] may fall back on systems without local installation; "
2349
+ "verify Keynote/PowerPoint line wraps."
2350
+ )
2351
+
2352
+ try:
2353
+ _h2p = _load_sibling_module("html_to_pptx")
2354
+ if _h2p is None or not hasattr(_h2p, "audit_pptx_timing_xml"):
2355
+ issues.append(
2356
+ "pptx-timing-audit-unavailable — sibling html_to_pptx.audit_pptx_timing_xml could not be loaded."
2357
+ )
2358
+ else:
2359
+ issues.extend(_h2p.audit_pptx_timing_xml(pptx_path))
2360
+ except Exception as exc:
2361
+ issues.append(f"pptx-timing-audit-error — failed to audit OOXML <p:timing>: {exc}")
2362
+
2363
+ return {
2364
+ "ok": len(issues) == 0,
2365
+ "pptx_path": str(pptx_path),
2366
+ "pptx_bytes": pptx_bytes,
2367
+ "pptx_size_mb": pptx_size_mb,
2368
+ "dimensions_in": [round(width_in, 4), round(height_in, 4)],
2369
+ "slide_count": len(prs.slides),
2370
+ "issues": issues,
2371
+ "warnings": warnings,
2372
+ "slides": slides_report,
2373
+ }
2374
+
2375
+
2376
+ def check_html_pptx_image_parity(
2377
+ html_rep: dict[str, Any] | None,
2378
+ pptx_audit: dict[str, Any] | None,
2379
+ ) -> list[str]:
2380
+ """Fail if any PPTX slide drops a visible HTML <img> element during export."""
2381
+ if not isinstance(html_rep, dict) or not isinstance(pptx_audit, dict):
2382
+ return []
2383
+ pptx_by_slide = {
2384
+ int(s["slide"]): s
2385
+ for s in (pptx_audit.get("slides") or [])
2386
+ if isinstance(s, dict) and isinstance(s.get("slide"), int)
2387
+ }
2388
+ parity_issues: list[str] = []
2389
+ for h_slide in (html_rep.get("slides") or []):
2390
+ if not isinstance(h_slide, dict) or not isinstance(h_slide.get("slide"), int):
2391
+ continue
2392
+ s_idx = int(h_slide["slide"])
2393
+ p_slide = pptx_by_slide.get(s_idx)
2394
+ if p_slide is None:
2395
+ continue
2396
+ metrics = h_slide.get("metrics") or {}
2397
+ if "allVisibleImgCount" in metrics:
2398
+ html_img_count = int(metrics.get("allVisibleImgCount") or 0)
2399
+ full_bleed_count = int(metrics.get("fullBleedImgCount") or 0)
2400
+ else:
2401
+ vis_imgs = metrics.get("visibleImages") or []
2402
+ html_img_count = len(vis_imgs)
2403
+ cw = int(html_rep.get("width") or 1920)
2404
+ ch = int(html_rep.get("height") or 1080)
2405
+ full_bleed_count = sum(
2406
+ 1
2407
+ for im in vis_imgs
2408
+ if int(im.get("x") or 0) <= 2
2409
+ and int(im.get("y") or 0) <= 2
2410
+ and int(im.get("w") or 0) >= cw - 4
2411
+ and int(im.get("h") or 0) >= ch - 4
2412
+ )
2413
+ has_pic_bg = bool(p_slide.get("has_picture_bg"))
2414
+ pptx_pic_count = int(
2415
+ p_slide["pictures_count"]
2416
+ if "pictures_count" in p_slide
2417
+ else len(p_slide.get("pictures") or [])
2418
+ )
2419
+ promoted_bg_imgs = min(1, full_bleed_count) if has_pic_bg else 0
2420
+ expected_min_pics = max(0, html_img_count - promoted_bg_imgs)
2421
+ if pptx_pic_count < expected_min_pics:
2422
+ parity_issues.append(
2423
+ f"Slide {s_idx}: pptx-missing-image — HTML renders {html_img_count} visible <img> element(s) "
2424
+ f"(expected >= {expected_min_pics} native PPTX <p:pic> shape(s)), "
2425
+ f"but PPTX slide contains only {pptx_pic_count}."
2426
+ )
2427
+ return parity_issues
2428
+
2429
+
2430
+ def _load_font(size: int) -> Any:
2431
+ from PIL import ImageFont
2432
+
2433
+ candidates = [
2434
+ "/System/Library/Fonts/PingFang.ttc",
2435
+ "/System/Library/Fonts/STHeiti Medium.ttc",
2436
+ "/System/Library/Fonts/Supplemental/Arial.ttf",
2437
+ "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
2438
+ "C:/Windows/Fonts/msyh.ttc",
2439
+ "C:/Windows/Fonts/arial.ttf",
2440
+ ]
2441
+ for path in candidates:
2442
+ if Path(path).is_file():
2443
+ try:
2444
+ return ImageFont.truetype(path, size=size)
2445
+ except Exception:
2446
+ continue
2447
+ return ImageFont.load_default()
2448
+
2449
+
2450
+ def mean_pixel_diff_pct(img_a: Path, img_b: Path) -> float | None:
2451
+ from PIL import Image, ImageChops
2452
+
2453
+ if not img_a.is_file() or not img_b.is_file():
2454
+ return None
2455
+ a = Image.open(img_a).convert("RGB")
2456
+ b = Image.open(img_b).convert("RGB")
2457
+ if a.size != b.size:
2458
+ b = b.resize(a.size, Image.Resampling.LANCZOS)
2459
+ diff = ImageChops.difference(a, b)
2460
+ hist = diff.histogram()
2461
+ total_vals = a.size[0] * a.size[1] * 3
2462
+ changed = sum(hist[i] for c in range(3) for i in range(c * 256 + 13, (c + 1) * 256))
2463
+ return round(100.0 * changed / total_vals, 2)
2464
+
2465
+
2466
+ def stitch_side_by_side(
2467
+ pairs: list[tuple[Path | None, str, Path | None, str]],
2468
+ out_path: Path,
2469
+ title: str,
2470
+ cell_width: int = 960,
2471
+ canvas_width: int | None = None,
2472
+ canvas_height: int | None = None,
2473
+ diff_pcts: list[float | None] | None = None,
2474
+ ) -> Path:
2475
+ from PIL import Image, ImageDraw
2476
+
2477
+ cw = int(canvas_width) if canvas_width and canvas_width > 0 else 0
2478
+ ch = int(canvas_height) if canvas_height and canvas_height > 0 else 0
2479
+ if cw <= 0 or ch <= 0:
2480
+ for lp, _, rp, _ in pairs:
2481
+ for cand in (rp, lp):
2482
+ if cand and cand.is_file():
2483
+ try:
2484
+ with Image.open(cand) as im:
2485
+ cw, ch, _ = msl.resolve_measure_canvas(im.width, im.height)
2486
+ break
2487
+ except Exception:
2488
+ pass
2489
+ if cw > 0 and ch > 0:
2490
+ break
2491
+ if cw <= 0 or ch <= 0:
2492
+ cw, ch = 1920, 1080
2493
+ cell_height = round(cell_width * ch / cw)
2494
+ pad = 24
2495
+ gap = 20
2496
+ header_h = 56
2497
+ label_h = 34
2498
+
2499
+ canvas_w = pad * 2 + cell_width * 2 + gap
2500
+ row_h = label_h + cell_height + pad
2501
+ canvas_h = header_h + pad + len(pairs) * row_h
2502
+
2503
+ canvas = Image.new("RGB", (canvas_w, canvas_h), (11, 18, 32))
2504
+ draw = ImageDraw.Draw(canvas)
2505
+ title_font = _load_font(22)
2506
+ label_font = _load_font(16)
2507
+
2508
+ draw.rectangle([0, 0, canvas_w, header_h], fill=(15, 23, 42))
2509
+ draw.text((pad, 15), title, fill=(241, 245, 249), font=title_font)
2510
+
2511
+ for row_idx, (left_path, left_label, right_path, right_label) in enumerate(pairs):
2512
+ y0 = header_h + pad + row_idx * row_h
2513
+ if diff_pcts is not None and row_idx < len(diff_pcts):
2514
+ diff_pct = diff_pcts[row_idx]
2515
+ else:
2516
+ diff_pct = (
2517
+ mean_pixel_diff_pct(left_path, right_path)
2518
+ if (left_path and right_path)
2519
+ else None
2520
+ )
2521
+ diff_note = f" [diff >12: {diff_pct}%]" if diff_pct is not None else ""
2522
+
2523
+ for col_idx, (img_path, label) in enumerate([(left_path, left_label), (right_path, right_label + diff_note)]):
2524
+ x0 = pad + col_idx * (cell_width + gap)
2525
+ draw.rectangle([x0, y0, x0 + cell_width, y0 + label_h], fill=(20, 30, 51))
2526
+ draw.text((x0 + 12, y0 + 7), label, fill=(203, 213, 225), font=label_font)
2527
+
2528
+ box_y = y0 + label_h
2529
+ if img_path and img_path.is_file():
2530
+ im = Image.open(img_path).convert("RGB")
2531
+ if im.size != (cell_width, cell_height):
2532
+ im = im.resize((cell_width, cell_height), Image.Resampling.LANCZOS)
2533
+ canvas.paste(im, (x0, box_y))
2534
+ else:
2535
+ draw.rectangle([x0, box_y, x0 + cell_width, box_y + cell_height], fill=(30, 41, 59))
2536
+ draw.text((x0 + 24, box_y + 24), f"MISSING: {img_path}", fill=(248, 113, 113), font=label_font)
2537
+
2538
+ draw.rectangle([x0, y0, x0 + cell_width, box_y + cell_height], outline=(51, 65, 85), width=1)
2539
+
2540
+ out_path.parent.mkdir(parents=True, exist_ok=True)
2541
+ canvas.save(out_path, compress_level=1)
2542
+ return out_path
2543
+
2544
+
2545
+ def find_reference_images(ref_dir: Path, slide_count: int) -> list[Path | None]:
2546
+ if not ref_dir.is_dir():
2547
+ return [None] * slide_count
2548
+
2549
+ image_exts = {".png", ".jpg", ".jpeg", ".webp"}
2550
+ candidates = [
2551
+ p for p in sorted(ref_dir.iterdir())
2552
+ if p.is_file()
2553
+ and p.suffix.lower() in image_exts
2554
+ and not p.name.lower().endswith(".preview.webp")
2555
+ and not any(skip in p.stem.lower() for skip in ("overview", "2x2", "grid", "sheet", "compare", "preview"))
2556
+ ]
2557
+
2558
+ matched: list[Path | None] = []
2559
+ for idx in range(1, slide_count + 1):
2560
+ pat = re.compile(rf"(?:^|[^0-9])(?:s|slide)?0?{idx}(?:[^0-9]|$)", re.IGNORECASE)
2561
+ hits = [p for p in candidates if pat.search(p.stem)]
2562
+ if hits:
2563
+ matched.append(hits[-1])
2564
+ elif idx <= len(candidates):
2565
+ matched.append(candidates[idx - 1])
2566
+ else:
2567
+ matched.append(None)
2568
+ return matched
2569
+
2570
+
2571
+ BG_DELTA_E_THRESHOLD = 12.0
2572
+ BG_TEXTURE_REF_MIN = 1.85
2573
+ BG_TEXTURE_HTML_FLAT_MAX = 0.90
2574
+ BG_TEXTURE_RATIO_MIN = 0.48
2575
+ HEADLINE_HEIGHT_RATIO_MIN = 0.80
2576
+ HEADLINE_INK_WEIGHT_RATIO_MIN = 0.70
2577
+ EXTRA_TEXT_RATIO_MAX = 1.30
2578
+
2579
+ _HEADLINE_WINDOWS: list[tuple[str, int, int, int, int, float, int | None, int | None]] = [
2580
+ ("left_narrow", 14, 156, 33, 156, 1.08, 440, None),
2581
+ ("left", 14, 240, 33, 175, 1.12, 440, None),
2582
+ ("left_wide", 14, 336, 33, 175, 1.04, 440, None),
2583
+ ("right_narrow", 280, 466, 33, 175, 1.08, None, 1080),
2584
+ ("right", 240, 466, 33, 175, 1.05, None, 920),
2585
+ ("full", 14, 466, 33, 156, 0.96, None, None),
2586
+ ("bot_left", 14, 260, 115, 248, 0.94, 440, None),
2587
+ ]
2588
+
2589
+
2590
+ def _rgb_to_lab(rgb: tuple[int, int, int]) -> tuple[float, float, float]:
2591
+ def _lin(c: int) -> float:
2592
+ v = c / 255.0
2593
+ return v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
2594
+
2595
+ r, g, b = _lin(rgb[0]), _lin(rgb[1]), _lin(rgb[2])
2596
+ x = (r * 0.4124564 + g * 0.3575761 + b * 0.1804375) / 0.95047
2597
+ y = (r * 0.2126729 + g * 0.7151522 + b * 0.0721750) / 1.00000
2598
+ z = (r * 0.0193339 + g * 0.1191920 + b * 0.9503041) / 1.08883
2599
+
2600
+ def _f(t: float) -> float:
2601
+ return t ** (1.0 / 3.0) if t > 0.008856 else (7.787 * t + 16.0 / 116.0)
2602
+
2603
+ fx, fy, fz = _f(x), _f(y), _f(z)
2604
+ return (116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz))
2605
+
2606
+
2607
+ def delta_e_cie76(rgb1: tuple[int, int, int], rgb2: tuple[int, int, int]) -> float:
2608
+ l1, a1, b1 = _rgb_to_lab(rgb1)
2609
+ l2, a2, b2 = _rgb_to_lab(rgb2)
2610
+ return math.sqrt((l1 - l2) ** 2 + (a1 - a2) ** 2 + (b1 - b2) ** 2)
2611
+
2612
+
2613
+ def _compare_slide_backgrounds(
2614
+ r_w: Image.Image,
2615
+ r_rgb: Image.Image,
2616
+ h_w: Image.Image,
2617
+ h_rgb: Image.Image,
2618
+ ) -> dict[str, Any]:
2619
+ r_bg = msl._extract_background_and_gradient(r_w, raw_rgb=r_rgb)
2620
+ h_bg = msl._extract_background_and_gradient(h_w, raw_rgb=h_rgb)
2621
+ if r_bg["polarity"] != h_bg["polarity"]:
2622
+ ww, wh = r_w.width, r_w.height
2623
+ pw = max(6, round(20 * ww / 480))
2624
+ ph = max(6, round(14 * wh / 270))
2625
+ joint: list[tuple[dict[str, Any], dict[str, Any]]] = []
2626
+ for y_base in (4, 36, 72, 112, 148):
2627
+ y = round(y_base * wh / 270)
2628
+ for x_base in (4, 64, 140, 220, 300, 380, 456):
2629
+ x = round(x_base * ww / 480)
2630
+ rp = msl._sample_patch(r_w, x, y, pw, ph)
2631
+ hp = msl._sample_patch(h_w, x, y, pw, ph)
2632
+ if rp["std"] <= 14.0 and hp["std"] <= 14.0:
2633
+ joint.append((rp, hp))
2634
+ if len(joint) >= 3:
2635
+ r_med = (
2636
+ int(round(statistics.median(p[0]["rgb"][0] for p in joint))),
2637
+ int(round(statistics.median(p[0]["rgb"][1] for p in joint))),
2638
+ int(round(statistics.median(p[0]["rgb"][2] for p in joint))),
2639
+ )
2640
+ h_med = (
2641
+ int(round(statistics.median(p[1]["rgb"][0] for p in joint))),
2642
+ int(round(statistics.median(p[1]["rgb"][1] for p in joint))),
2643
+ int(round(statistics.median(p[1]["rgb"][2] for p in joint))),
2644
+ )
2645
+ if (msl._luminance(r_med) >= 0.5) == (msl._luminance(h_med) >= 0.5):
2646
+ r_tex = round(
2647
+ float(
2648
+ statistics.median(
2649
+ msl._patch_texture_energy(r_rgb, p[0]["rect_work"], work_size=(ww, wh)) for p in joint
2650
+ )
2651
+ ),
2652
+ 2,
2653
+ )
2654
+ h_tex = round(
2655
+ float(
2656
+ statistics.median(
2657
+ msl._patch_texture_energy(h_rgb, p[1]["rect_work"], work_size=(ww, wh)) for p in joint
2658
+ )
2659
+ ),
2660
+ 2,
2661
+ )
2662
+ return {
2663
+ "ref_bg_rgb": r_med,
2664
+ "html_bg_rgb": h_med,
2665
+ "ref_bg_hex": msl._rgb_to_hex(r_med),
2666
+ "html_bg_hex": msl._rgb_to_hex(h_med),
2667
+ "delta_e": round(delta_e_cie76(r_med, h_med), 2),
2668
+ "ref_texture": r_tex,
2669
+ "html_texture": h_tex,
2670
+ }
2671
+ return {
2672
+ "ref_bg_rgb": r_bg["bg_rgb"],
2673
+ "html_bg_rgb": h_bg["bg_rgb"],
2674
+ "ref_bg_hex": r_bg["bg_hex"],
2675
+ "html_bg_hex": h_bg["bg_hex"],
2676
+ "delta_e": round(delta_e_cie76(r_bg["bg_rgb"], h_bg["bg_rgb"]), 2),
2677
+ "ref_texture": r_bg["bg_texture_energy"],
2678
+ "html_texture": h_bg["bg_texture_energy"],
2679
+ }
2680
+
2681
+
2682
+ def _get_zone_bg_and_masks(
2683
+ im: Image.Image,
2684
+ wx0: int,
2685
+ wy0: int,
2686
+ wx1: int,
2687
+ wy1: int,
2688
+ ) -> tuple[tuple[int, int, int], str, Image.Image, Image.Image]:
2689
+ patches = []
2690
+ step_x = max(8, (wx1 - wx0) // 6)
2691
+ step_y = max(8, (wy1 - wy0) // 5)
2692
+ for y in range(max(2, wy0 - 10), min(im.height - 14, wy1 + 4), step_y):
2693
+ for x in range(wx0, max(wx0 + 1, wx1 - 16), step_x):
2694
+ patches.append(msl._sample_patch(im, x, y, 16, 12))
2695
+ smooth = [p for p in patches if p["std"] <= 16.0] or sorted(patches, key=lambda p: p["std"])[:5]
2696
+ best_cluster: list[dict[str, Any]] = []
2697
+ for seed in smooth:
2698
+ cl = [p for p in smooth if msl._rgb_dist(seed["rgb"], p["rgb"]) <= 28.0]
2699
+ if len(cl) > len(best_cluster):
2700
+ best_cluster = cl
2701
+ bg_rgb = (
2702
+ int(round(statistics.median(p["rgb"][0] for p in best_cluster))),
2703
+ int(round(statistics.median(p["rgb"][1] for p in best_cluster))),
2704
+ int(round(statistics.median(p["rgb"][2] for p in best_cluster))),
2705
+ )
2706
+ pol = "light" if msl._luminance(bg_rgb) >= 0.5 else "dark"
2707
+ gray = im.convert("L")
2708
+ bg_l = int(round(msl._luminance(bg_rgb) * 255.0))
2709
+ if pol == "light":
2710
+ ink_cut = max(20, bg_l - 62)
2711
+ lum_mask = gray.point(lambda v: 255 if v < ink_cut else 0)
2712
+ else:
2713
+ ink_cut = min(235, bg_l + 62)
2714
+ lum_mask = gray.point(lambda v: 255 if v > ink_cut else 0)
2715
+ bg_im = Image.new("RGB", im.size, bg_rgb)
2716
+ diff = ImageChops.difference(im, bg_im)
2717
+ r_d, g_d, b_d = diff.split()
2718
+ max_d = ImageChops.lighter(ImageChops.lighter(r_d, g_d), b_d)
2719
+ bg_near_mask = max_d.point(lambda v: 255 if v <= 42 else 0)
2720
+ if pol == "dark":
2721
+ chroma_mask = max_d.point(lambda v: 255 if v > 108 else 0)
2722
+ ink_mask = ImageChops.lighter(lum_mask, chroma_mask)
2723
+ else:
2724
+ ink_mask = lum_mask
2725
+ return bg_rgb, pol, ink_mask, bg_near_mask
2726
+
2727
+
2728
+ def _split_merged_bands(rc: list[int], raw_bands: list[tuple[int, int]]) -> list[tuple[int, int]]:
2729
+ queue = list(raw_bands)
2730
+ for _ in range(3):
2731
+ next_bands: list[tuple[int, int]] = []
2732
+ changed = False
2733
+ for s, e in queue:
2734
+ span = e - s
2735
+ if 26 <= span <= 130:
2736
+ mid0 = s + max(6, int(span * 0.25))
2737
+ mid1 = e - max(6, int(span * 0.25))
2738
+ if mid1 > mid0:
2739
+ min_idx = min(range(mid0, mid1), key=lambda k: rc[k])
2740
+ peak = max(rc[s:e])
2741
+ left_peak = max(rc[s:min_idx]) if min_idx > s else 0
2742
+ right_peak = max(rc[min_idx + 1 : e]) if min_idx + 1 < e else 0
2743
+ valley_cap = 0.38 if span > 42 else 0.26
2744
+ if (
2745
+ peak > 0
2746
+ and rc[min_idx] <= peak * valley_cap
2747
+ and left_peak >= peak * 0.45
2748
+ and right_peak >= peak * 0.45
2749
+ and (min_idx - s) >= 6
2750
+ and (e - (min_idx + 1)) >= 6
2751
+ ):
2752
+ next_bands.append((s, min_idx))
2753
+ next_bands.append((min_idx + 1, e))
2754
+ changed = True
2755
+ continue
2756
+ next_bands.append((s, e))
2757
+ queue = next_bands
2758
+ if not changed:
2759
+ break
2760
+ return queue
2761
+
2762
+
2763
+ def _measure_window_headline(
2764
+ im: Image.Image,
2765
+ wx0: int,
2766
+ wx1: int,
2767
+ wy0: int = 33,
2768
+ wy1: int = 175,
2769
+ max_start_x_px: int | None = None,
2770
+ min_start_x_px: int | None = None,
2771
+ ) -> dict[str, Any] | None:
2772
+ bg_rgb, pol, ink_mask, bg_near_mask = _get_zone_bg_and_masks(im, wx0, wy0, wx1, wy1)
2773
+ w = max(1, wx1 - wx0)
2774
+ scan_y0 = 4 if wy0 <= 40 else wy0
2775
+ rc, _ = msl._row_and_col_counts(ink_mask, wx0, scan_y0, wx1, wy1)
2776
+ min_row_px = max(4, int(w * 0.035))
2777
+ raw_bands = msl._extract_bands(rc, min_val=min_row_px, min_gap=1, min_span=3)
2778
+ bands = _split_merged_bands(rc, raw_bands)
2779
+
2780
+ has_big_illus = any((e - s) * msl.SCALE > 212 for s, e in bands if (scan_y0 + e) > wy0)
2781
+
2782
+ t_lines = []
2783
+ for s, e in bands:
2784
+ abs_y0 = scan_y0 + s
2785
+ abs_y1 = scan_y0 + e
2786
+ if abs_y1 <= wy0 + 2 or abs_y0 < 22:
2787
+ continue
2788
+ h_px = (e - s) * msl.SCALE
2789
+ if 24 <= h_px <= 212:
2790
+ crop = ink_mask.crop((wx0, abs_y0, wx1, abs_y1))
2791
+ bb = crop.getbbox()
2792
+ if not bb:
2793
+ continue
2794
+ x_start_px = (wx0 + bb[0]) * msl.SCALE
2795
+ if max_start_x_px is not None and x_start_px > max_start_x_px:
2796
+ continue
2797
+ if min_start_x_px is not None and x_start_px < min_start_x_px:
2798
+ continue
2799
+ bw = (bb[2] - bb[0]) * msl.SCALE
2800
+ if bw < 88:
2801
+ continue
2802
+ line_ink = crop.crop(bb)
2803
+ den = ImageStat.Stat(line_ink).mean[0] / 255.0
2804
+ line_bg = bg_near_mask.crop((wx0 + bb[0], abs_y0, wx0 + bb[2], abs_y1))
2805
+ bg_frac = ImageStat.Stat(line_bg).mean[0] / 255.0
2806
+ bimodal = min(1.0, den + bg_frac)
2807
+ if 0.10 <= den <= 1.00 and bimodal >= 0.65:
2808
+ t_lines.append((abs_y0, abs_y1, h_px, bw, den, bimodal, bb))
2809
+ if not t_lines:
2810
+ return None
2811
+ max_h = max(ln[2] for ln in t_lines)
2812
+ tall = [ln for ln in t_lines if ln[2] >= max(36, int(max_h * 0.72))]
2813
+ if not tall:
2814
+ return None
2815
+ cluster = [tall[0]]
2816
+ for ln in tall[1:]:
2817
+ if (ln[0] - cluster[-1][1]) * msl.SCALE <= 72:
2818
+ cluster.append(ln)
2819
+ else:
2820
+ break
2821
+ med_h = int(round(statistics.median(ln[2] for ln in cluster)))
2822
+ tallest_h = max(ln[2] for ln in cluster)
2823
+ line_den = statistics.mean(ln[4] for ln in cluster)
2824
+ bimodal_avg = statistics.mean(ln[5] for ln in cluster)
2825
+ max_bw = max(ln[3] for ln in cluster)
2826
+ cy0 = cluster[0][0]
2827
+ cy1 = cluster[-1][1]
2828
+ cx0 = wx0 + min(ln[6][0] for ln in cluster)
2829
+ cx1 = wx0 + max(ln[6][2] for ln in cluster)
2830
+ box_den = ImageStat.Stat(ink_mask.crop((cx0, cy0, cx1, cy1))).mean[0] / 255.0
2831
+ return {
2832
+ "med_h": med_h,
2833
+ "max_h": tallest_h,
2834
+ "line_count": len(cluster),
2835
+ "box_h": (cy1 - cy0) * msl.SCALE,
2836
+ "line_den": line_den,
2837
+ "box_den": box_den,
2838
+ "bimodal": bimodal_avg,
2839
+ "max_bw": max_bw,
2840
+ "has_big_illus": has_big_illus,
2841
+ "bg_rgb": bg_rgb,
2842
+ "pol": pol,
2843
+ "y0": cy0 * msl.SCALE,
2844
+ "y1": cy1 * msl.SCALE,
2845
+ "x0": cx0 * msl.SCALE,
2846
+ "x1": cx1 * msl.SCALE,
2847
+ }
2848
+
2849
+
2850
+ def _pick_best_headline_pair(
2851
+ r_w: Image.Image,
2852
+ h_w: Image.Image,
2853
+ ) -> tuple[float, str, dict[str, Any], dict[str, Any]] | None:
2854
+ ww, wh = r_w.width, r_w.height
2855
+ sx = ww / 480.0
2856
+ sy = wh / 270.0
2857
+ best: tuple[float, str, dict[str, Any], dict[str, Any]] | None = None
2858
+ for wname, x0, x1, y0, y1, w_prio, max_sx, min_sx in _HEADLINE_WINDOWS:
2859
+ wx0 = max(2, round(x0 * sx))
2860
+ wx1 = min(ww - 2, max(wx0 + 8, round(x1 * sx)))
2861
+ wy0 = max(4, round(y0 * sy))
2862
+ wy1 = min(wh - 4, max(wy0 + 8, round(y1 * sy)))
2863
+ scaled_max_sx = round(max_sx * sx) if max_sx is not None else None
2864
+ scaled_min_sx = round(min_sx * sx) if min_sx is not None else None
2865
+ rh = _measure_window_headline(r_w, wx0, wx1, wy0, wy1, scaled_max_sx, scaled_min_sx)
2866
+ hh = _measure_window_headline(h_w, wx0, wx1, wy0, wy1, scaled_max_sx, scaled_min_sx)
2867
+ if not rh or not hh:
2868
+ continue
2869
+ if abs(rh["y0"] - hh["y0"]) > 170 or abs(rh["x0"] - hh["x0"]) > 140:
2870
+ continue
2871
+ illus_pen = 0.65 if (hh["has_big_illus"] or rh["has_big_illus"]) else 1.0
2872
+ width_factor = 1.0 if min(rh["max_bw"], hh["max_bw"]) >= round(200 * sx) else 0.72
2873
+ min_lden = min(rh["line_den"], hh["line_den"])
2874
+ den_factor = (min_lden ** 0.65) * (0.68 if min_lden < 0.23 else 1.0)
2875
+ pos_prox = 1.0 - (abs(rh["y0"] - hh["y0"]) / 600.0)
2876
+ score = (
2877
+ (min(rh["med_h"], hh["med_h"]) * 0.6 + rh["med_h"] * 0.4)
2878
+ * (hh["bimodal"] ** 1.3)
2879
+ * (rh["bimodal"] ** 0.9)
2880
+ * den_factor
2881
+ * illus_pen
2882
+ * width_factor
2883
+ * pos_prox
2884
+ * w_prio
2885
+ )
2886
+ if best is None or score > best[0]:
2887
+ best = (score, wname, rh, hh)
2888
+ return best
2889
+
2890
+
2891
+ def _native_headline_ink_density(
2892
+ raw_rgb: Image.Image,
2893
+ bg_rgb: tuple[int, int, int],
2894
+ pol: str,
2895
+ bbox_1920: tuple[int, int, int, int],
2896
+ canvas_w: float = 1920.0,
2897
+ canvas_h: float = 1080.0,
2898
+ ) -> float:
2899
+ x0, y0, x1, y1 = bbox_1920
2900
+ sx = raw_rgb.width / float(canvas_w)
2901
+ sy = raw_rgb.height / float(canvas_h)
2902
+ crop = raw_rgb.crop(
2903
+ (
2904
+ max(0, int(x0 * sx)),
2905
+ max(0, int(y0 * sy)),
2906
+ min(raw_rgb.width, int(x1 * sx)),
2907
+ min(raw_rgb.height, int(y1 * sy)),
2908
+ )
2909
+ )
2910
+ if crop.width < 4 or crop.height < 4:
2911
+ return 0.0
2912
+ gray = crop.convert("L")
2913
+ bg_l = int(round(msl._luminance(bg_rgb) * 255.0))
2914
+ if pol == "light":
2915
+ ink_cut = max(20, bg_l - 68)
2916
+ lum_mask = gray.point(lambda v: 255 if v < ink_cut else 0)
2917
+ return ImageStat.Stat(lum_mask).mean[0] / 255.0
2918
+ ink_cut = min(235, bg_l + 68)
2919
+ lum_mask = gray.point(lambda v: 255 if v > ink_cut else 0)
2920
+ bg_im = Image.new("RGB", crop.size, bg_rgb)
2921
+ diff = ImageChops.difference(crop, bg_im)
2922
+ r_d, g_d, b_d = diff.split()
2923
+ max_d = ImageChops.lighter(ImageChops.lighter(r_d, g_d), b_d)
2924
+ chroma_mask = max_d.point(lambda v: 255 if v > 115 else 0)
2925
+ mask = ImageChops.lighter(lum_mask, chroma_mask)
2926
+ return ImageStat.Stat(mask).mean[0] / 255.0
2927
+
2928
+
2929
+ def find_prompt_file(deck_dir: Path | None, idx: int) -> Path | None:
2930
+ if deck_dir is None:
2931
+ return None
2932
+ for sub in ("prompts", "assets/prompts"):
2933
+ pdir = deck_dir / sub
2934
+ if not pdir.is_dir():
2935
+ continue
2936
+ for cand in (f"s{idx}.txt", f"s0{idx}.txt", f"slide{idx}.txt", f"slide-{idx}.txt"):
2937
+ if (pdir / cand).is_file():
2938
+ return pdir / cand
2939
+ if idx == 1:
2940
+ covers = sorted(pdir.glob("cover*.txt"))
2941
+ if covers:
2942
+ return covers[-1]
2943
+ return None
2944
+
2945
+
2946
+ def extract_prompt_text_lines(prompt_path: Path) -> list[str]:
2947
+ txt = prompt_path.read_text(encoding="utf-8", errors="ignore")
2948
+ m = re.search(r"【(?:逐字)?文字[^】]*】(.*?)(?:【|$)", txt, re.S)
2949
+ block = m.group(1) if m else txt
2950
+ lines: list[str] = []
2951
+ for raw in block.splitlines():
2952
+ s = raw.strip()
2953
+ if not s:
2954
+ continue
2955
+ if "逐字渲染" in s or "不要多余文字" in s or "每条只出现一次" in s:
2956
+ continue
2957
+ s = re.sub(r"^[-*•]?\s*(?:\[[^\]]*\]\s*)+", "", s)
2958
+ s = re.sub(r"^[-*•]\s*", "", s)
2959
+ s = re.sub(r"([^)]*(?:图标|底板|标识)[^)]*)", "", s)
2960
+ s = re.sub(r"^[^\s+]+小图标\s*\+\s*", "", s)
2961
+ s = s.strip()
2962
+ if s:
2963
+ lines.append(s)
2964
+ return lines
2965
+
2966
+
2967
+ def extract_html_slide_text_segments(html_path: Path | None, slide_idx: int) -> list[str]:
2968
+ if not html_path or not html_path.is_file():
2969
+ return []
2970
+ txt = html_path.read_text(encoding="utf-8", errors="ignore")
2971
+ m = re.search(
2972
+ rf"<section[^>]*\bdata-slide=[\"\x27]{slide_idx}[\"\x27][^>]*>(.*?)</section>",
2973
+ txt,
2974
+ re.S | re.I,
2975
+ )
2976
+ if not m:
2977
+ return []
2978
+ sec = m.group(1)
2979
+ sec = re.sub(r"<(script|style)\b[^>]*>.*?</\1>", "", sec, flags=re.S | re.I)
2980
+ parts = re.split(
2981
+ r"</?(?:div|p|h[1-6]|li|tr|td|th|header|footer|section|article|blockquote|br)\b[^>]*>",
2982
+ sec,
2983
+ flags=re.I,
2984
+ )
2985
+ segs: list[str] = []
2986
+ for part in parts:
2987
+ clean = html.unescape(re.sub(r"<[^>]+>", " ", part))
2988
+ clean = re.sub(r"\s+", " ", clean).strip()
2989
+ if re.sub(r"\s+", "", clean):
2990
+ segs.append(clean)
2991
+ return segs
2992
+
2993
+
2994
+ def _norm_visible_text(s: str) -> str:
2995
+ s = re.sub(r"\s+", "", s)
2996
+ return s.replace("“", '"').replace("”", '"').replace("‘", "'").replace("’", "'")
2997
+
2998
+
2999
+ def evaluate_slide_fidelity(
3000
+ slide_idx: int,
3001
+ ref_path: Path | None,
3002
+ html_shot_path: Path | None,
3003
+ html_path: Path | None = None,
3004
+ prompt_path: Path | None = None,
3005
+ html_text_segments: list[str] | None = None,
3006
+ ) -> dict[str, Any]:
3007
+ """Compare one slide's Stage-1 reference draft vs Stage-2 HTML render and prompt text list."""
3008
+ issues: list[str] = []
3009
+ metrics: dict[str, Any] = {"slide": slide_idx}
3010
+
3011
+ if ref_path and ref_path.is_file() and html_shot_path and html_shot_path.is_file():
3012
+ with Image.open(ref_path) as r_raw, Image.open(html_shot_path) as h_raw:
3013
+ r_rgb = r_raw.convert("RGB")
3014
+ h_rgb = h_raw.convert("RGB")
3015
+ canvas_w, canvas_h, _ = msl.resolve_measure_canvas(h_rgb.width, h_rgb.height)
3016
+ ww = max(16, canvas_w // msl.SCALE)
3017
+ wh = max(16, canvas_h // msl.SCALE)
3018
+ r_w = r_rgb.resize((ww, wh), Image.Resampling.BILINEAR)
3019
+ h_w = h_rgb.resize((ww, wh), Image.Resampling.BILINEAR)
3020
+
3021
+ # 1. Background mismatch check
3022
+ bg_cmp = _compare_slide_backgrounds(r_w, r_rgb, h_w, h_rgb)
3023
+ de = bg_cmp["delta_e"]
3024
+ r_tex = bg_cmp["ref_texture"]
3025
+ h_tex = bg_cmp["html_texture"]
3026
+ tex_ratio = round(h_tex / max(1e-6, r_tex), 3) if r_tex > 0 else 1.0
3027
+ metrics["background"] = {
3028
+ "ref_bg_hex": bg_cmp["ref_bg_hex"],
3029
+ "html_bg_hex": bg_cmp["html_bg_hex"],
3030
+ "delta_e": de,
3031
+ "ref_texture": r_tex,
3032
+ "html_texture": h_tex,
3033
+ "texture_ratio": tex_ratio,
3034
+ }
3035
+ if de > BG_DELTA_E_THRESHOLD:
3036
+ issues.append(
3037
+ f"Slide {slide_idx}: background-mismatch — 背景应为与设计稿一致的底色与纸纹"
3038
+ f"(设计稿 {bg_cmp['ref_bg_hex']} vs HTML {bg_cmp['html_bg_hex']},ΔE={de:.1f}),"
3039
+ f"用 bg-plate 或该页净板作 bg_image"
3040
+ )
3041
+ elif r_tex >= BG_TEXTURE_REF_MIN and (
3042
+ h_tex < BG_TEXTURE_HTML_FLAT_MAX or tex_ratio < BG_TEXTURE_RATIO_MIN
3043
+ ):
3044
+ issues.append(
3045
+ f"Slide {slide_idx}: background-mismatch — 背景应为与设计稿一致的纸纹肌理"
3046
+ f"(设计稿 texture={r_tex:.2f} vs HTML {h_tex:.2f}),用 bg-plate 或该页净板作 bg_image"
3047
+ )
3048
+
3049
+ # 2. Headline scale & ink weight check
3050
+ best = _pick_best_headline_pair(r_w, h_w)
3051
+ if best:
3052
+ _, wname, rh, hh = best
3053
+ hr = hh["med_h"] / max(1, rh["med_h"])
3054
+ mhr = hh["max_h"] / max(1, rh["max_h"])
3055
+ h_ratio = round(min(hr, mhr), 3)
3056
+ r_lines = int(rh.get("line_count") or 1)
3057
+ h_lines = int(hh.get("line_count") or 1)
3058
+ r_box_h = max(1, int(rh.get("box_h") or rh["max_h"]))
3059
+ h_box_h = max(1, int(hh.get("box_h") or hh["max_h"]))
3060
+ box_h_ratio = round(h_box_h / float(r_box_h), 3)
3061
+ # When the reference raster merges a multi-line headline into fewer detected bands than
3062
+ # cleanly separated HTML lines of the same total block height, evaluate against total block height
3063
+ # rather than falsely comparing 1 HTML line against 2 merged reference lines.
3064
+ if h_lines > r_lines and box_h_ratio >= HEADLINE_HEIGHT_RATIO_MIN and h_ratio < HEADLINE_HEIGHT_RATIO_MIN:
3065
+ h_ratio = round(min(1.0, box_h_ratio), 3)
3066
+ r_box = (rh["x0"], rh["y0"], rh["x1"], rh["y1"])
3067
+ h_box = (hh["x0"], hh["y0"], hh["x1"], hh["y1"])
3068
+ r_nd = _native_headline_ink_density(r_rgb, rh["bg_rgb"], rh["pol"], r_box, canvas_w=canvas_w, canvas_h=canvas_h)
3069
+ h_nd = _native_headline_ink_density(h_rgb, hh["bg_rgb"], hh["pol"], h_box, canvas_w=canvas_w, canvas_h=canvas_h)
3070
+ den_ratio = round(h_nd / max(1e-6, r_nd), 3) if r_nd > 0 else 1.0
3071
+ est_px = int(min(180, max(32, round(rh["max_h"] * 1.12))))
3072
+ metrics["headline"] = {
3073
+ "window": wname,
3074
+ "ref_height_px": rh["max_h"],
3075
+ "html_height_px": hh["max_h"],
3076
+ "ref_med_height_px": rh["med_h"],
3077
+ "html_med_height_px": hh["med_h"],
3078
+ "ref_line_count": r_lines,
3079
+ "html_line_count": h_lines,
3080
+ "box_height_ratio": box_h_ratio,
3081
+ "height_ratio": h_ratio,
3082
+ "ref_ink_density": round(r_nd, 4),
3083
+ "html_ink_density": round(h_nd, 4),
3084
+ "ink_weight_ratio": den_ratio,
3085
+ "headline_est_font_px": est_px,
3086
+ }
3087
+ if h_ratio < HEADLINE_HEIGHT_RATIO_MIN:
3088
+ pct = int(round(h_ratio * 100))
3089
+ issues.append(
3090
+ f"Slide {slide_idx}: headline-scale — 标题高度只有设计稿的 {pct}%"
3091
+ f"({hh['max_h']}px vs 设计稿 {rh['max_h']}px),"
3092
+ f"按设计稿量出的 headline_px(约 {est_px}px)设置"
3093
+ )
3094
+ elif den_ratio < HEADLINE_INK_WEIGHT_RATIO_MIN:
3095
+ dpct = int(round(den_ratio * 100))
3096
+ issues.append(
3097
+ f"Slide {slide_idx}: headline-scale — 标题墨量只有设计稿的 {dpct}%"
3098
+ f"(标题高度 {int(round(h_ratio * 100))}%),"
3099
+ f"按设计稿量出的 headline_px(约 {est_px}px)与粗字重设置"
3100
+ )
3101
+
3102
+ # 3. Extra text check against prompts/sN.txt
3103
+ if prompt_path and prompt_path.is_file():
3104
+ p_lines = extract_prompt_text_lines(prompt_path)
3105
+ h_segs = (
3106
+ html_text_segments
3107
+ if html_text_segments is not None
3108
+ else extract_html_slide_text_segments(html_path, slide_idx)
3109
+ )
3110
+ p_norm = _norm_visible_text("".join(p_lines))
3111
+ h_norm = _norm_visible_text("".join(h_segs))
3112
+ p_chars = len(p_norm)
3113
+ h_chars = len(h_norm)
3114
+ text_ratio = round(h_chars / float(p_chars), 3) if p_chars > 0 else 1.0
3115
+ metrics["text"] = {
3116
+ "prompt_file": prompt_path.name,
3117
+ "prompt_chars": p_chars,
3118
+ "html_chars": h_chars,
3119
+ "char_ratio": text_ratio,
3120
+ }
3121
+ if p_chars > 0 and h_chars > p_chars * EXTRA_TEXT_RATIO_MAX and (h_chars - p_chars) >= 6:
3122
+ extra_segs = [seg for seg in h_segs if _norm_visible_text(seg) not in p_norm]
3123
+ extra_preview = (
3124
+ " / ".join(extra_segs)[:72]
3125
+ if extra_segs
3126
+ else h_norm[p_chars : p_chars + 48]
3127
+ )
3128
+ pct_more = int(round((text_ratio - 1.0) * 100))
3129
+ issues.append(
3130
+ f"Slide {slide_idx}: extra-text — 多出设计稿没有的文字:{extra_preview}"
3131
+ f"(超出 {pct_more}%,HTML {h_chars} 字 vs 设计稿 {p_chars} 字)"
3132
+ )
3133
+
3134
+ return {
3135
+ "slide": slide_idx,
3136
+ "ok": len(issues) == 0,
3137
+ "fidelity_issues": issues,
3138
+ "metrics": metrics,
3139
+ }
3140
+
3141
+
3142
+ def evaluate_deck_fidelity(
3143
+ slide_count: int,
3144
+ ref_paths: list[Path | None],
3145
+ html_shot_paths: list[Path] | dict[int, Path],
3146
+ html_path: Path | None = None,
3147
+ deck_dir: Path | None = None,
3148
+ target_slides: list[int] | None = None,
3149
+ ) -> dict[str, Any]:
3150
+ if deck_dir is None and html_path is not None:
3151
+ serve_root, _ = _infer_serve_root(html_path, None)
3152
+ deck_dir = serve_root
3153
+ if isinstance(html_shot_paths, dict):
3154
+ shot_by_num = {int(k): v for k, v in html_shot_paths.items()}
3155
+ else:
3156
+ shot_by_num = {i + 1: p for i, p in enumerate(html_shot_paths)}
3157
+ indices = (
3158
+ sorted({int(i) for i in target_slides if 1 <= int(i) <= slide_count})
3159
+ if target_slides
3160
+ else list(range(1, slide_count + 1))
3161
+ )
3162
+ all_issues: list[str] = []
3163
+ slide_reports: list[dict[str, Any]] = []
3164
+ for idx in indices:
3165
+ rp = ref_paths[idx - 1] if idx - 1 < len(ref_paths) else None
3166
+ hp = shot_by_num.get(idx)
3167
+ pf = find_prompt_file(deck_dir, idx)
3168
+ s_rep = evaluate_slide_fidelity(
3169
+ slide_idx=idx,
3170
+ ref_path=rp,
3171
+ html_shot_path=hp,
3172
+ html_path=html_path,
3173
+ prompt_path=pf,
3174
+ )
3175
+ slide_reports.append(s_rep)
3176
+ all_issues.extend(s_rep["fidelity_issues"])
3177
+ return {
3178
+ "ok": len(all_issues) == 0,
3179
+ "fidelity_issues": all_issues,
3180
+ "slides": slide_reports,
3181
+ }
3182
+
3183
+
3184
+ def _infer_slide_count(spec_path: Path | None, html_path: Path | None, pptx_path: Path | None) -> int:
3185
+ if spec_path and spec_path.is_file():
3186
+ spec = json.loads(spec_path.read_text(encoding="utf-8"))
3187
+ n = len(spec.get("slides", []))
3188
+ if n > 0:
3189
+ return n
3190
+ if html_path and html_path.is_file():
3191
+ html_txt = html_path.read_text(encoding="utf-8", errors="ignore")
3192
+ by_sec_data = re.findall(r'<section\b[^>]*\bdata-slide\s*=\s*["\'](\d+)["\']', html_txt, flags=re.IGNORECASE)
3193
+ if by_sec_data:
3194
+ return len(by_sec_data)
3195
+ by_sec = re.findall(r'<section\b[^>]*class=["\'][^"\']*\bslide\b', html_txt, flags=re.IGNORECASE)
3196
+ if by_sec:
3197
+ return len(by_sec)
3198
+ by_data = set(re.findall(r'data-slide\s*=\s*["\'](\d+)["\']', html_txt))
3199
+ if by_data:
3200
+ return len(by_data)
3201
+ if pptx_path and pptx_path.is_file():
3202
+ try:
3203
+ from pptx import Presentation
3204
+ n = len(Presentation(str(pptx_path)).slides)
3205
+ if n > 0:
3206
+ return n
3207
+ except Exception:
3208
+ pass
3209
+ return 4
3210
+
3211
+
3212
+ def main() -> int:
3213
+ _configure_utf8_stdio()
3214
+ parser = argparse.ArgumentParser(
3215
+ description="Verify HTML & PPTX visual/structural fidelity (works HTML-first or with deck-spec.json)."
3216
+ )
3217
+ parser.add_argument("--spec", type=Path, default=None, help="Optional path to deck-spec.json (auto-detects slide count when omitted)")
3218
+ parser.add_argument("--html", type=Path, default=None, help="Path to HTML entry (e.g. web/index.html)")
3219
+ parser.add_argument("--pptx", type=Path, default=None, help="Path to generated .pptx file")
3220
+ parser.add_argument("--ref-dir", type=Path, default=None, help="Optional reference images directory")
3221
+ parser.add_argument("--out-dir", type=Path, required=True, help="Output directory for shots & reports")
3222
+ parser.add_argument("--ratio", "--aspect-ratio", dest="ratio", type=str, default=None, help="Optional canvas aspect ratio (16:9, 3:4, 9:16, 1:1); auto-detected when omitted")
3223
+ parser.add_argument("--width", type=int, default=None, help="HTML capture width (default: auto-detected or 1920)")
3224
+ parser.add_argument("--height", type=int, default=None, help="HTML capture height (default: auto-detected or 1080)")
3225
+ parser.add_argument("--skip-pptx", action="store_true", help="Skip PPTX audit & LibreOffice/Keynote rendering for fast HTML verification (~3s)")
3226
+ parser.add_argument("--slides", type=str, default=None, help="Optional comma-separated 1-based slide numbers for fast incremental HTML verification (e.g. --slides 4 or --slides 2,4)")
3227
+ parser.add_argument("--no-render", action="store_true", help="Skip PPTX-to-PNG visual rendering (audit only)")
3228
+ parser.add_argument("--json", action="store_true", help="Print full JSON report to stdout")
3229
+ args = parser.parse_args()
3230
+
3231
+ if args.spec is not None and not args.spec.is_file():
3232
+ print(f"Error: spec file not found: {args.spec}", file=sys.stderr)
3233
+ return 2
3234
+ if not args.html and not args.pptx:
3235
+ print("Error: specify at least one of --html or --pptx", file=sys.stderr)
3236
+ return 2
3237
+
3238
+ slide_count = _infer_slide_count(args.spec, args.html, args.pptx if not args.skip_pptx else None)
3239
+ target_slides: list[int] | None = None
3240
+ if args.slides:
3241
+ raw_tokens = [tok.strip() for tok in re.split(r"[,\s]+", args.slides) if tok.strip()]
3242
+ parsed_nums: list[int] = []
3243
+ for tok in raw_tokens:
3244
+ try:
3245
+ val = int(tok)
3246
+ except ValueError:
3247
+ print(f"Error: invalid slide number in --slides: {tok!r}", file=sys.stderr)
3248
+ return 2
3249
+ if 1 <= val <= slide_count:
3250
+ parsed_nums.append(val)
3251
+ target_slides = sorted(set(parsed_nums))
3252
+ if not target_slides:
3253
+ print(f"Error: --slides {args.slides!r} matched no slides in range 1..{slide_count}", file=sys.stderr)
3254
+ return 2
3255
+ out_dir = args.out_dir
3256
+ shots_dir = out_dir / "shots"
3257
+ out_dir.mkdir(parents=True, exist_ok=True)
3258
+
3259
+ ref_dir = args.ref_dir
3260
+ if ref_dir is None and args.html is not None:
3261
+ inferred_root, _ = _infer_serve_root(args.html, args.spec)
3262
+ cand_ref_dir = inferred_root / "assets" / "reference"
3263
+ if cand_ref_dir.is_dir():
3264
+ ref_dir = cand_ref_dir
3265
+ ref_paths = find_reference_images(ref_dir, slide_count) if ref_dir else []
3266
+ cap_w, cap_h = _detect_verify_canvas_size(
3267
+ spec_path=args.spec,
3268
+ html_path=args.html,
3269
+ ref_paths=ref_paths,
3270
+ pptx_path=args.pptx if not args.skip_pptx else None,
3271
+ ratio=args.ratio,
3272
+ width=args.width,
3273
+ height=args.height,
3274
+ )
3275
+
3276
+ report: dict[str, Any] = {
3277
+ "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
3278
+ "spec": str(args.spec) if args.spec else None,
3279
+ "canvas": {"width": cap_w, "height": cap_h},
3280
+ "slide_count": slide_count,
3281
+ "skip_pptx": bool(args.skip_pptx),
3282
+ }
3283
+ all_ok = True
3284
+ html_paths: list[Path] = []
3285
+ pptx_paths: list[Path] = []
3286
+ fidelity_issues: list[str] = []
3287
+
3288
+ prior_report: dict[str, Any] = {}
3289
+ prior_report_path = out_dir / "audit-report.json"
3290
+ if target_slides and prior_report_path.is_file():
3291
+ try:
3292
+ loaded_prior = json.loads(prior_report_path.read_text(encoding="utf-8"))
3293
+ if isinstance(loaded_prior, dict) and int(loaded_prior.get("slide_count") or 0) == slide_count:
3294
+ prior_covered: set[int] = set()
3295
+ if isinstance(loaded_prior.get("covered_slides"), list):
3296
+ prior_covered = {int(n) for n in loaded_prior["covered_slides"] if isinstance(n, int)}
3297
+ else:
3298
+ prev_html_obj = loaded_prior.get("html") if isinstance(loaded_prior.get("html"), dict) else {}
3299
+ prior_covered = {
3300
+ int(s["slide"])
3301
+ for s in (prev_html_obj.get("slides") or [])
3302
+ if isinstance(s, dict) and isinstance(s.get("slide"), int)
3303
+ }
3304
+ untouched = set(range(1, slide_count + 1)) - set(target_slides)
3305
+ if untouched.issubset(prior_covered):
3306
+ prior_report = loaded_prior
3307
+ except Exception:
3308
+ prior_report = {}
3309
+
3310
+ # Never write a partial false-green audit-report.json when slide_count changed or untouched slides lack prior coverage
3311
+ if target_slides and not prior_report:
3312
+ target_slides = None
3313
+
3314
+ if args.html:
3315
+ html_rep = capture_html_slides(
3316
+ args.html,
3317
+ slide_count=slide_count,
3318
+ out_dir=shots_dir,
3319
+ width=cap_w,
3320
+ height=cap_h,
3321
+ spec_path=args.spec,
3322
+ target_slides=target_slides,
3323
+ )
3324
+ html_paths = [Path(s["screenshot"]) for s in html_rep["slides"]]
3325
+ html_shot_by_num = {int(s["slide"]): Path(s["screenshot"]) for s in html_rep["slides"]}
3326
+ verified_indices = target_slides if target_slides else list(range(1, slide_count + 1))
3327
+
3328
+ inferred_root, _ = _infer_serve_root(args.html, args.spec)
3329
+ if ref_paths or (inferred_root / "prompts").is_dir() or (inferred_root / "assets" / "prompts").is_dir():
3330
+ fid_rep = evaluate_deck_fidelity(
3331
+ slide_count=slide_count,
3332
+ ref_paths=ref_paths,
3333
+ html_shot_paths=html_shot_by_num,
3334
+ html_path=args.html,
3335
+ deck_dir=inferred_root,
3336
+ target_slides=target_slides,
3337
+ )
3338
+ fidelity_issues = fid_rep["fidelity_issues"]
3339
+ html_rep["fidelity_issues"] = fidelity_issues
3340
+ html_rep["fidelity_ok"] = fid_rep["ok"]
3341
+ fid_by_slide = {int(s_fid["slide"]): s_fid for s_fid in fid_rep["slides"]}
3342
+ for s_entry in html_rep["slides"]:
3343
+ s_fid = fid_by_slide.get(int(s_entry["slide"]))
3344
+ if s_fid is not None:
3345
+ s_entry["fidelity_issues"] = s_fid["fidelity_issues"]
3346
+ s_entry["fidelity"] = s_fid["metrics"]
3347
+ if fidelity_issues:
3348
+ html_rep["ok"] = False
3349
+ else:
3350
+ html_rep["fidelity_issues"] = []
3351
+ html_rep["fidelity_ok"] = True
3352
+
3353
+ # Preserve prior blocking issues on untouched slides during incremental `--slides` verification
3354
+ if target_slides and prior_report:
3355
+ target_set = set(target_slides)
3356
+ prev_html = prior_report.get("html") if isinstance(prior_report.get("html"), dict) else {}
3357
+ carried_issues: list[str] = []
3358
+ for iss in (prev_html.get("issues") or []):
3359
+ if not isinstance(iss, str) or not iss.strip():
3360
+ continue
3361
+ m_iss = re.match(r"^Slide\s+(\d+)\b", iss.strip())
3362
+ if m_iss and int(m_iss.group(1)) not in target_set:
3363
+ carried_issues.append(iss)
3364
+ if carried_issues:
3365
+ html_rep["issues"] = carried_issues + list(html_rep.get("issues") or [])
3366
+ html_rep["ok"] = False
3367
+ carried_fid: list[str] = []
3368
+ for ferr in (prior_report.get("fidelity_issues") or []):
3369
+ if not isinstance(ferr, str) or not ferr.strip():
3370
+ continue
3371
+ m_f = re.match(r"^Slide\s+(\d+)\b", ferr.strip())
3372
+ if m_f and int(m_f.group(1)) not in target_set:
3373
+ carried_fid.append(ferr)
3374
+ if carried_fid:
3375
+ fidelity_issues = carried_fid + list(fidelity_issues)
3376
+ html_rep["fidelity_issues"] = fidelity_issues
3377
+ html_rep["fidelity_ok"] = False
3378
+ html_rep["ok"] = False
3379
+
3380
+ if target_slides:
3381
+ report["verified_slides"] = verified_indices
3382
+ report["covered_slides"] = list(range(1, slide_count + 1))
3383
+ report["html"] = html_rep
3384
+ if not html_rep["ok"]:
3385
+ all_ok = False
3386
+
3387
+ if ref_paths:
3388
+ pairs_ref_html = [
3389
+ (
3390
+ ref_paths[s_idx - 1] if s_idx - 1 < len(ref_paths) else None,
3391
+ f"S{s_idx} · Reference ({ref_paths[s_idx - 1].name if (s_idx - 1 < len(ref_paths) and ref_paths[s_idx - 1]) else 'missing'})",
3392
+ html_shot_by_num.get(s_idx),
3393
+ f"S{s_idx} · Restored HTML ({cap_w}x{cap_h})",
3394
+ )
3395
+ for s_idx in verified_indices
3396
+ ]
3397
+ sheet_ref_html = stitch_side_by_side(
3398
+ pairs_ref_html,
3399
+ out_dir / "compare-ref-vs-html.png",
3400
+ f"Visual Parity: Reference vs Restored HTML ({cap_w}x{cap_h})",
3401
+ canvas_width=cap_w,
3402
+ canvas_height=cap_h,
3403
+ )
3404
+ report["compare_ref_vs_html"] = str(sheet_ref_html)
3405
+
3406
+ if args.pptx and not args.skip_pptx:
3407
+ audit = audit_pptx(args.pptx, args.spec, expected_width=cap_w, expected_height=cap_h)
3408
+ if "html" in report:
3409
+ parity_issues = check_html_pptx_image_parity(report.get("html"), audit)
3410
+ if parity_issues:
3411
+ audit.setdefault("issues", []).extend(parity_issues)
3412
+ audit["ok"] = False
3413
+ report["pptx_audit"] = audit
3414
+ if not audit.get("ok"):
3415
+ all_ok = False
3416
+ if args.pptx.is_file() and not args.no_render:
3417
+ render_res = render_pptx_to_pngs(args.pptx, shots_dir)
3418
+ report["pptx_render"] = render_res
3419
+ if render_res.get("ok") and len(render_res.get("images", [])) == slide_count:
3420
+ pptx_paths = [Path(p) for p in render_res["images"]]
3421
+ if html_paths:
3422
+ pairs_html_pptx = [
3423
+ (
3424
+ html_shot_by_num.get(s_idx),
3425
+ f"S{s_idx} · Restored HTML",
3426
+ pptx_paths[s_idx - 1],
3427
+ f"S{s_idx} · Rendered PPTX ({render_res['renderer']})",
3428
+ )
3429
+ for s_idx in verified_indices
3430
+ if s_idx - 1 < len(pptx_paths)
3431
+ ]
3432
+ sheet_html_pptx = stitch_side_by_side(
3433
+ pairs_html_pptx,
3434
+ out_dir / "compare-html-vs-pptx.png",
3435
+ "Visual Parity: Restored HTML vs Rendered PPTX",
3436
+ canvas_width=cap_w,
3437
+ canvas_height=cap_h,
3438
+ )
3439
+ report["compare_html_vs_pptx"] = str(sheet_html_pptx)
3440
+ elif ref_paths:
3441
+ pairs_ref_pptx = [
3442
+ (
3443
+ ref_paths[i],
3444
+ f"S{i + 1} · Reference ({ref_paths[i].name if ref_paths[i] else 'missing'})",
3445
+ pptx_paths[i],
3446
+ f"S{i + 1} · Rendered PPTX ({render_res['renderer']})",
3447
+ )
3448
+ for i in range(slide_count)
3449
+ ]
3450
+ sheet_ref_pptx = stitch_side_by_side(
3451
+ pairs_ref_pptx,
3452
+ out_dir / "compare-ref-vs-pptx.png",
3453
+ "Visual Parity: Reference vs Rendered PPTX",
3454
+ canvas_width=cap_w,
3455
+ canvas_height=cap_h,
3456
+ )
3457
+ report["compare_ref_vs_pptx"] = str(sheet_ref_pptx)
3458
+
3459
+ report["fidelity_issues"] = fidelity_issues
3460
+ report["fidelity_ok"] = len(fidelity_issues) == 0
3461
+ report["verification_ok"] = all_ok
3462
+ report["ok"] = all_ok
3463
+ report_path = out_dir / "audit-report.json"
3464
+ report_path.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
3465
+
3466
+ if args.json:
3467
+ print(json.dumps(report, ensure_ascii=False, indent=2))
3468
+ else:
3469
+ print(f"verify_deck: ok={all_ok} verification_ok={all_ok} slides={slide_count} report={report_path}")
3470
+ if not all_ok:
3471
+ for src_key in ("html", "pptx_audit"):
3472
+ for err in report.get(src_key, {}).get("issues", []):
3473
+ print(f" ISSUE: {err}", file=sys.stderr)
3474
+ for ferr in fidelity_issues:
3475
+ print(f" FIDELITY_ISSUE: {ferr}", file=sys.stderr)
3476
+ for src_key in ("html", "pptx_audit"):
3477
+ for warn in report.get(src_key, {}).get("warnings", []):
3478
+ print(f" WARNING: {warn}", file=sys.stderr)
3479
+ return 0 if all_ok else 1
3480
+
3481
+
3482
+ if __name__ == "__main__":
3483
+ raise SystemExit(main())