@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,4042 @@
1
+ #!/usr/bin/env python3
2
+ """Universal DOM-to-PPTX Compiler (v2) for 1920x1080 multi-slide HTML decks.
3
+
4
+ Compiles ANY 1920x1080 HTML slide deck (`web/index.html`) into a 100% natively
5
+ editable 16:9 `.pptx` via Playwright DOM geometry + computed styles + python-pptx.
6
+
7
+ Key guarantees:
8
+ - Layout-agnostic: zero hardcoded templates or fixed slide schemas.
9
+ - True paint order: respects CSS z-index stacking contexts & DOM order.
10
+ - Zero rasterized text: extracts exact rendered lines & inline runs via
11
+ TreeWalker + Range.getClientRects() into native editable PowerPoint textboxes.
12
+ - Accurate CJK & Latin font weight mapping (<a:latin> + <a:ea>).
13
+ - Crisp single-side borders (hairlines, table rules, accent bars) as thin
14
+ filled rectangles instead of 4-sided boxes.
15
+ - Faithful gradients, cropped images, and inline <svg> via 2x DPR captures.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import base64
21
+ import functools
22
+ import hashlib
23
+ import http.server
24
+ import io
25
+ import json
26
+ import math
27
+ import os
28
+ import re
29
+ import shutil
30
+ import socketserver
31
+ import sys
32
+ import tempfile
33
+ import threading
34
+ import urllib.parse
35
+ from datetime import datetime, timezone
36
+ from pathlib import Path
37
+ from typing import Any
38
+
39
+ from lxml import etree
40
+ from PIL import Image
41
+ from pptx import Presentation
42
+ from pptx.dml.color import RGBColor
43
+ from pptx.enum.dml import MSO_LINE_DASH_STYLE
44
+ from pptx.enum.shapes import MSO_CONNECTOR, MSO_SHAPE, MSO_SHAPE_TYPE
45
+ from pptx.enum.text import MSO_ANCHOR, MSO_AUTO_SIZE, PP_ALIGN
46
+ from pptx.oxml import parse_xml
47
+ from pptx.oxml.ns import qn
48
+ from pptx.util import Pt
49
+
50
+ CANVAS_W_PX = 1920.0
51
+ CANVAS_H_PX = 1080.0
52
+ EMU_PER_PX = 6350.0 # 914_400 EMU/in / 144 px/in
53
+ PT_PER_PX = 0.5 # 72 pt/in / 144 px/in (constant across all canvas ratios)
54
+ SLIDE_W_EMU = round(CANVAS_W_PX * EMU_PER_PX) # 12_192_000 (13.333333 in)
55
+ SLIDE_H_EMU = round(CANVAS_H_PX * EMU_PER_PX) # 6_858_000 (7.5 in)
56
+
57
+ _RATIO_CANVAS_PX: dict[str, tuple[int, int]] = {
58
+ "16:9": (1920, 1080),
59
+ "3:4": (1080, 1440),
60
+ "9:16": (1080, 1920),
61
+ "1:1": (1440, 1440),
62
+ "1920x1080": (1920, 1080),
63
+ "1080x1440": (1080, 1440),
64
+ "1080x1920": (1080, 1920),
65
+ "1440x1440": (1440, 1440),
66
+ }
67
+
68
+
69
+ def resolve_canvas_px(
70
+ ratio: str | None = None,
71
+ width: int | None = None,
72
+ height: int | None = None,
73
+ ) -> tuple[int, int] | None:
74
+ if width is not None and height is not None and int(width) > 0 and int(height) > 0:
75
+ return int(width), int(height)
76
+ if ratio:
77
+ tok = str(ratio).strip().lower().replace("×", "x").replace("/", ":")
78
+ if tok in _RATIO_CANVAS_PX:
79
+ return _RATIO_CANVAS_PX[tok]
80
+ m = re.fullmatch(r"(\d+)\s*x\s*(\d+)", tok)
81
+ if m and int(m.group(1)) > 0 and int(m.group(2)) > 0:
82
+ return int(m.group(1)), int(m.group(2))
83
+ raise ValueError(f"Unsupported canvas ratio/size: {ratio!r} (expected '16:9', '3:4', '9:16', '1:1', or 'WxH')")
84
+ return None
85
+
86
+
87
+ def _detect_html_canvas_size(
88
+ html_path: Path,
89
+ width: int | None = None,
90
+ height: int | None = None,
91
+ ratio: str | None = None,
92
+ ) -> tuple[int, int]:
93
+ explicit = resolve_canvas_px(ratio=ratio, width=width, height=height)
94
+ if explicit is not None:
95
+ return explicit
96
+ try:
97
+ txt = html_path.read_text(encoding="utf-8", errors="ignore")
98
+ except OSError:
99
+ txt = ""
100
+ if txt:
101
+ m_data = re.search(r'\bdata-canvas\s*=\s*["\'](\d+)x(\d+)["\']', txt, re.I)
102
+ if m_data:
103
+ return int(m_data.group(1)), int(m_data.group(2))
104
+ m_ratio = re.search(r'\bdata-ratio\s*=\s*["\']([^"\']+)["\']', txt, re.I)
105
+ if m_ratio:
106
+ try:
107
+ by_ratio = resolve_canvas_px(ratio=m_ratio.group(1))
108
+ if by_ratio is not None:
109
+ return by_ratio
110
+ except ValueError:
111
+ pass
112
+ m_page = re.search(r"@page\s*\{\s*size\s*:\s*(\d+)px\s+(\d+)px", txt, re.I)
113
+ if m_page:
114
+ return int(m_page.group(1)), int(m_page.group(2))
115
+ m_stage = re.search(
116
+ r"\.(?:deck-stage|slide)\s*\{[^}]*?\bwidth\s*:\s*(\d+)px\s*;[^}]*?\bheight\s*:\s*(\d+)px",
117
+ txt,
118
+ re.I | re.S,
119
+ )
120
+ if m_stage:
121
+ return int(m_stage.group(1)), int(m_stage.group(2))
122
+ return int(round(CANVAS_W_PX)), int(round(CANVAS_H_PX))
123
+
124
+
125
+ def px_emu(value: float) -> int:
126
+ return round(float(value) * EMU_PER_PX)
127
+
128
+
129
+ def px_pt(value: float) -> Pt:
130
+ return Pt(max(1.0, float(value) * PT_PER_PX))
131
+
132
+
133
+ def _load_runtime_utils() -> Any | None:
134
+ cand_res = (Path(__file__).resolve().parent / "_runtime_utils.py").resolve()
135
+ for mod_name in ("_oil_slide_runtime_utils", "_runtime_utils"):
136
+ mod = sys.modules.get(mod_name)
137
+ mod_file = getattr(mod, "__file__", None) if mod is not None else None
138
+ if mod_file:
139
+ try:
140
+ if Path(mod_file).resolve() == cand_res:
141
+ return mod
142
+ except OSError:
143
+ pass
144
+ if not os.path.isfile(cand_res):
145
+ return None
146
+ try:
147
+ import importlib.util
148
+
149
+ spec = importlib.util.spec_from_file_location("_oil_slide_runtime_utils", cand_res)
150
+ if spec is None or spec.loader is None:
151
+ return None
152
+ mod = importlib.util.module_from_spec(spec)
153
+ sys.modules["_oil_slide_runtime_utils"] = mod
154
+ spec.loader.exec_module(mod)
155
+ return mod
156
+ except Exception:
157
+ return None
158
+
159
+
160
+ def _configure_utf8_stdio() -> None:
161
+ ru = _load_runtime_utils()
162
+ if ru is not None:
163
+ ru.configure_utf8_stdio()
164
+ return
165
+ for stream in (sys.stdout, sys.stderr):
166
+ if stream is not None:
167
+ try:
168
+ if not stream.isatty() and hasattr(stream, "reconfigure"):
169
+ stream.reconfigure(encoding="utf-8", errors="replace")
170
+ except Exception:
171
+ pass
172
+
173
+
174
+ def _launch_chromium(
175
+ playwright_obj: Any,
176
+ *,
177
+ headless: bool = True,
178
+ args: list[str] | None = None,
179
+ executable_path: str | None = None,
180
+ chromium_sandbox: bool | None = None,
181
+ discover_system: bool = False,
182
+ ) -> Any:
183
+ ru = _load_runtime_utils()
184
+ if ru is not None:
185
+ return ru.launch_chromium(
186
+ playwright_obj,
187
+ headless=headless,
188
+ args=args,
189
+ executable_path=executable_path,
190
+ chromium_sandbox=chromium_sandbox,
191
+ discover_system=discover_system,
192
+ )
193
+ launch_kwargs: dict[str, Any] = {"headless": headless}
194
+ if args is not None:
195
+ launch_kwargs["args"] = list(args)
196
+ if chromium_sandbox is not None:
197
+ launch_kwargs["chromium_sandbox"] = chromium_sandbox
198
+ if executable_path:
199
+ launch_kwargs["executable_path"] = executable_path
200
+ return playwright_obj.chromium.launch(**launch_kwargs)
201
+
202
+
203
+ def find_chrome_binary(explicit: str | None = None) -> str | None:
204
+ ru = _load_runtime_utils()
205
+ if ru is not None:
206
+ return ru.find_chrome_binary(explicit)
207
+ if explicit and Path(explicit).is_file():
208
+ return explicit
209
+ env_bin = os.environ.get("CHROME_BIN") or os.environ.get("CHROMIUM_BIN")
210
+ if env_bin and Path(env_bin).is_file():
211
+ return env_bin
212
+ for cmd in ("google-chrome", "chromium", "chromium-browser", "chrome", "msedge"):
213
+ found = shutil.which(cmd)
214
+ if found:
215
+ return found
216
+ for path in (
217
+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
218
+ "/Applications/Chromium.app/Contents/MacOS/Chromium",
219
+ "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
220
+ "/usr/bin/google-chrome",
221
+ "/usr/bin/chromium",
222
+ "/usr/bin/chromium-browser",
223
+ ):
224
+ if Path(path).is_file():
225
+ return path
226
+ return None
227
+
228
+
229
+ class _QuietHandler(http.server.SimpleHTTPRequestHandler):
230
+ def do_GET(self) -> None:
231
+ if self.path.split("?", 1)[0] == "/favicon.ico":
232
+ self.send_response(204)
233
+ self.end_headers()
234
+ return
235
+ super().do_GET()
236
+
237
+ def log_message(self, format: str, *args: Any) -> None:
238
+ pass
239
+
240
+
241
+ class _ThreadingStaticServer(socketserver.ThreadingTCPServer):
242
+ allow_reuse_address = True
243
+ daemon_threads = True
244
+ request_queue_size = 64
245
+
246
+
247
+ def _start_static_server(root: Path) -> tuple[socketserver.TCPServer, int]:
248
+ handler = functools.partial(_QuietHandler, directory=str(root))
249
+ server = _ThreadingStaticServer(("127.0.0.1", 0), handler)
250
+ port = int(server.server_address[1])
251
+ thread = threading.Thread(target=server.serve_forever, daemon=True)
252
+ thread.start()
253
+ return server, port
254
+
255
+
256
+ def _infer_serve_root(html_path: Path) -> tuple[Path, str]:
257
+ html_abs = html_path.resolve()
258
+ parent = html_abs.parent
259
+ grandparent = parent.parent
260
+ if grandparent != parent and ((grandparent / "assets").is_dir() or parent.name == "web"):
261
+ root = grandparent
262
+ else:
263
+ root = parent
264
+ return root, html_abs.relative_to(root).as_posix()
265
+
266
+
267
+ # ---------------------------------------------------------------------------
268
+ # Color & python-pptx XML helpers
269
+ # ---------------------------------------------------------------------------
270
+
271
+ def parse_css_color(color_str: str | None) -> tuple[RGBColor, float] | None:
272
+ """Parse CSS rgb()/rgba()/#hex into (RGBColor, alpha_0_to_1). Returns None if invalid/transparent."""
273
+ if not color_str:
274
+ return None
275
+ s = color_str.strip()
276
+ if not s or s.lower() == "transparent":
277
+ return None
278
+ if s.startswith("#"):
279
+ hx = s.lstrip("#")
280
+ if len(hx) == 3:
281
+ hx = "".join(c * 2 for c in hx)
282
+ if len(hx) == 6:
283
+ return RGBColor(int(hx[0:2], 16), int(hx[2:4], 16), int(hx[4:6], 16)), 1.0
284
+ if len(hx) == 8:
285
+ return RGBColor(int(hx[0:2], 16), int(hx[2:4], 16), int(hx[4:6], 16)), int(hx[6:8], 16) / 255.0
286
+ return None
287
+ m = re.match(
288
+ r"rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[,/]\s*([\d.]+%?)\s*)?\)",
289
+ s,
290
+ re.I,
291
+ )
292
+ if m:
293
+ r = max(0, min(255, round(float(m.group(1)))))
294
+ g = max(0, min(255, round(float(m.group(2)))))
295
+ b = max(0, min(255, round(float(m.group(3)))))
296
+ a_raw = m.group(4)
297
+ if a_raw is None:
298
+ a = 1.0
299
+ elif a_raw.endswith("%"):
300
+ a = max(0.0, min(1.0, float(a_raw[:-1]) / 100.0))
301
+ else:
302
+ a = max(0.0, min(1.0, float(a_raw)))
303
+ return RGBColor(r, g, b), a
304
+ return None
305
+
306
+
307
+ def _attach_alpha(element: Any, alpha: float) -> None:
308
+ if alpha >= 0.999:
309
+ return
310
+ sf = element.find(qn("a:solidFill"))
311
+ if sf is None:
312
+ return
313
+ srgb = sf.find(qn("a:srgbClr"))
314
+ if srgb is None:
315
+ return
316
+ for old in srgb.findall(qn("a:alpha")):
317
+ srgb.remove(old)
318
+ a_el = etree.SubElement(srgb, qn("a:alpha"))
319
+ a_el.set("val", str(round(max(0.0, min(1.0, alpha)) * 100_000)))
320
+
321
+
322
+ def _clear_shape_shadow(shape: Any) -> None:
323
+ shape.shadow.inherit = False
324
+ sp_pr = shape._element.spPr
325
+ for eff in sp_pr.findall(qn("a:effectLst")):
326
+ sp_pr.remove(eff)
327
+ etree.SubElement(sp_pr, qn("a:effectLst"))
328
+
329
+
330
+ PPTX_SAFE_FORMATS = {"PNG", "JPEG", "GIF", "BMP", "TIFF"}
331
+ OPAQUE_JPEG_THRESHOLD_BYTES = 200_000
332
+ OPAQUE_JPEG_QUALITY = 88
333
+ OPAQUE_JPEG_SAVINGS_RATIO = 0.72
334
+
335
+
336
+ def _pil_has_real_alpha(im: Image.Image) -> bool:
337
+ """Return True only when an image carries meaningful transparency (alpha < 252)."""
338
+ if (
339
+ "A" in im.getbands()
340
+ or im.mode in ("RGBA", "LA", "PA")
341
+ or "transparency" in im.info
342
+ ):
343
+ alpha = im.convert("RGBA").getchannel("A")
344
+ lo, _ = alpha.getextrema()
345
+ return bool(lo < 252)
346
+ return False
347
+
348
+
349
+ def _save_optimal_pptx_image(
350
+ im: Image.Image,
351
+ target_dir: Path,
352
+ key: str,
353
+ *,
354
+ has_alpha: bool | None = None,
355
+ existing_png_path: Path | None = None,
356
+ ) -> Path:
357
+ """Save an image in a PPTX-safe format, compressing large opaque raster images to JPEG q=88 when smaller."""
358
+ target_dir.mkdir(parents=True, exist_ok=True)
359
+ real_alpha = _pil_has_real_alpha(im) if has_alpha is None else bool(has_alpha)
360
+ if real_alpha:
361
+ if existing_png_path is not None:
362
+ return existing_png_path
363
+ safe_png = target_dir / f"safe-{key}.png"
364
+ if not safe_png.is_file():
365
+ im.convert("RGBA").save(safe_png, format="PNG", optimize=True)
366
+ return safe_png
367
+
368
+ safe_jpg = target_dir / f"safe-{key}.jpg"
369
+ safe_png = target_dir / f"safe-{key}.png"
370
+ if safe_jpg.is_file():
371
+ return safe_jpg
372
+ if existing_png_path is None and safe_png.is_file():
373
+ return safe_png
374
+
375
+ rgb = im.convert("RGB")
376
+ if existing_png_path is not None:
377
+ png_size = existing_png_path.stat().st_size
378
+ if png_size <= OPAQUE_JPEG_THRESHOLD_BYTES:
379
+ return existing_png_path
380
+ jpg_buf = io.BytesIO()
381
+ rgb.save(jpg_buf, format="JPEG", quality=OPAQUE_JPEG_QUALITY, optimize=True)
382
+ jpg_bytes = jpg_buf.getvalue()
383
+ if len(jpg_bytes) < int(png_size * OPAQUE_JPEG_SAVINGS_RATIO):
384
+ safe_jpg.write_bytes(jpg_bytes)
385
+ return safe_jpg
386
+ return existing_png_path
387
+
388
+ png_buf = io.BytesIO()
389
+ rgb.save(png_buf, format="PNG", optimize=True)
390
+ png_bytes = png_buf.getvalue()
391
+ if len(png_bytes) > OPAQUE_JPEG_THRESHOLD_BYTES:
392
+ jpg_buf = io.BytesIO()
393
+ rgb.save(jpg_buf, format="JPEG", quality=OPAQUE_JPEG_QUALITY, optimize=True)
394
+ jpg_bytes = jpg_buf.getvalue()
395
+ if len(jpg_bytes) < int(len(png_bytes) * OPAQUE_JPEG_SAVINGS_RATIO):
396
+ safe_jpg.write_bytes(jpg_bytes)
397
+ return safe_jpg
398
+ safe_png.write_bytes(png_bytes)
399
+ return safe_png
400
+
401
+
402
+ def _ensure_pptx_safe_image(path: Path, tmp_dir: Path | None = None) -> Path:
403
+ """Guarantee an image file is in a format python-pptx supports natively (never WEBP/AVIF/MPO)
404
+ and compress large opaque raster images cleanly to high-quality JPEG (q=88) to keep .pptx lightweight.
405
+
406
+ Inspects actual image bytes via Pillow (even if a WEBP file is disguised with a .png extension).
407
+ Preserves RGBA alpha losslessly as PNG and leaves small/flat PNGs and existing JPEGs untouched.
408
+ """
409
+ src_abs = path.resolve()
410
+ target_dir = tmp_dir if tmp_dir is not None else Path(tempfile.gettempdir())
411
+ with Image.open(src_abs) as im:
412
+ fmt = (im.format or "").upper()
413
+ if fmt in ("JPEG", "GIF"):
414
+ return src_abs
415
+ st = src_abs.stat()
416
+ key = hashlib.sha1(f"{src_abs}:{st.st_mtime_ns}:{st.st_size}".encode("utf-8")).hexdigest()[:16]
417
+ if fmt == "PNG":
418
+ if st.st_size <= OPAQUE_JPEG_THRESHOLD_BYTES:
419
+ return src_abs
420
+ return _save_optimal_pptx_image(im, target_dir, key, existing_png_path=src_abs)
421
+ return _save_optimal_pptx_image(im, target_dir, key)
422
+
423
+
424
+ def _prepare_bg_cover_image(
425
+ img_path: Path,
426
+ tmp_dir: Path,
427
+ canvas_w: float = CANVAS_W_PX,
428
+ canvas_h: float = CANVAS_H_PX,
429
+ ) -> Path:
430
+ """Ensure slide background image is PPTX-safe and center-cropped to the slide aspect if aspect differs > 6%."""
431
+ safe_path = _ensure_pptx_safe_image(img_path, tmp_dir)
432
+ target_ratio = float(canvas_w) / float(canvas_h)
433
+ with Image.open(safe_path) as im:
434
+ w, h = im.size
435
+ if w <= 0 or h <= 0:
436
+ return safe_path
437
+ ratio = w / float(h)
438
+ if abs(ratio - target_ratio) / target_ratio <= 0.06:
439
+ return safe_path
440
+ if ratio > target_ratio:
441
+ new_w = max(1, int(round(h * target_ratio)))
442
+ x0 = (w - new_w) // 2
443
+ cropped = im.crop((x0, 0, x0 + new_w, h))
444
+ else:
445
+ new_h = max(1, int(round(w / target_ratio)))
446
+ y0 = (h - new_h) // 2
447
+ cropped = im.crop((0, y0, w, y0 + new_h))
448
+ key = hashlib.sha1(f"cover:{int(canvas_w)}x{int(canvas_h)}:{safe_path}:{w}x{h}".encode("utf-8")).hexdigest()[:16]
449
+ return _save_optimal_pptx_image(cropped, tmp_dir, f"bg-{int(canvas_w)}x{int(canvas_h)}-{key}")
450
+
451
+
452
+ def set_slide_solid_bg(slide: Any, rgb: RGBColor) -> None:
453
+ fill = slide.background.fill
454
+ fill.solid()
455
+ fill.fore_color.rgb = rgb
456
+
457
+
458
+ def set_slide_picture_bg(slide: Any, img_path: Path, tmp_dir: Path | None = None) -> None:
459
+ """Set a locked native OOXML slide background (<p:bg><p:bgPr><a:blipFill>) with SHA-1 deduplication."""
460
+ safe_path = _ensure_pptx_safe_image(img_path, tmp_dir)
461
+ _, r_id = slide.part.get_or_add_image_part(str(safe_path))
462
+
463
+ c_sld = slide._element.cSld
464
+ for old_bg in c_sld.findall(qn("p:bg")):
465
+ c_sld.remove(old_bg)
466
+
467
+ bg_el = etree.Element(qn("p:bg"))
468
+ bg_pr = etree.SubElement(bg_el, qn("p:bgPr"))
469
+ blip_fill = etree.SubElement(bg_pr, qn("a:blipFill"))
470
+ blip_fill.set("dpi", "0")
471
+ blip_fill.set("rotWithShape", "1")
472
+ blip = etree.SubElement(blip_fill, qn("a:blip"))
473
+ blip.set(qn("r:embed"), r_id)
474
+ stretch = etree.SubElement(blip_fill, qn("a:stretch"))
475
+ etree.SubElement(stretch, qn("a:fillRect"))
476
+ etree.SubElement(bg_pr, qn("a:effectLst"))
477
+
478
+ # <p:bg> must precede <p:spTree> inside <p:cSld> per OOXML schema
479
+ c_sld.insert(0, bg_el)
480
+
481
+
482
+ def add_native_shape(
483
+ slide: Any,
484
+ x: float,
485
+ y: float,
486
+ w: float,
487
+ h: float,
488
+ fill_rgba: tuple[RGBColor, float] | None = None,
489
+ border_rgba: tuple[RGBColor, float] | None = None,
490
+ border_width_px: float = 0.0,
491
+ radius_px: float = 0.0,
492
+ border_style: str = "solid",
493
+ shape_kind: str | None = None,
494
+ ) -> Any:
495
+ min_side = max(1.0, min(w, h))
496
+ aspect = (w / h) if h > 0 else 1.0
497
+ is_diamond = str(shape_kind or "").strip().lower() == "diamond"
498
+ is_oval = (not is_diamond) and (radius_px >= (min_side / 2.0) - 1.2) and (0.85 <= aspect <= 1.18)
499
+ is_rounded = (not is_diamond) and (not is_oval) and (radius_px >= 1.5)
500
+
501
+ if is_diamond:
502
+ shape_type = MSO_SHAPE.DIAMOND
503
+ elif is_oval:
504
+ shape_type = MSO_SHAPE.OVAL
505
+ elif is_rounded:
506
+ shape_type = MSO_SHAPE.ROUNDED_RECTANGLE
507
+ else:
508
+ shape_type = MSO_SHAPE.RECTANGLE
509
+
510
+ shape = slide.shapes.add_shape(
511
+ shape_type,
512
+ px_emu(x),
513
+ px_emu(y),
514
+ max(1, px_emu(w)),
515
+ max(1, px_emu(h)),
516
+ )
517
+ if is_rounded:
518
+ try:
519
+ shape.adjustments[0] = min(0.5, max(0.0, float(radius_px) / min_side))
520
+ except Exception:
521
+ pass
522
+
523
+ if fill_rgba and fill_rgba[1] > 0.01:
524
+ shape.fill.solid()
525
+ shape.fill.fore_color.rgb = fill_rgba[0]
526
+ _attach_alpha(shape.fill._xPr, fill_rgba[1])
527
+ else:
528
+ shape.fill.background()
529
+
530
+ if border_rgba and border_rgba[1] > 0.01 and border_width_px > 0.1:
531
+ shape.line.color.rgb = border_rgba[0]
532
+ shape.line.width = Pt(max(0.35, border_width_px * PT_PER_PX))
533
+ if border_style == "dashed":
534
+ shape.line.dash_style = MSO_LINE_DASH_STYLE.DASH
535
+ elif border_style == "dotted":
536
+ shape.line.dash_style = MSO_LINE_DASH_STYLE.ROUND_DOT
537
+ ln = shape._element.spPr.find(qn("a:ln"))
538
+ if ln is not None:
539
+ _attach_alpha(ln, border_rgba[1])
540
+ else:
541
+ shape.line.fill.background()
542
+
543
+ _clear_shape_shadow(shape)
544
+ return shape
545
+
546
+
547
+ def _add_styled_line(
548
+ slide: Any,
549
+ x1: float,
550
+ y1: float,
551
+ x2: float,
552
+ y2: float,
553
+ color_rgb: RGBColor,
554
+ alpha: float,
555
+ width_px: float,
556
+ style: str = "solid",
557
+ ) -> Any:
558
+ conn = slide.shapes.add_connector(
559
+ MSO_CONNECTOR.STRAIGHT,
560
+ px_emu(x1),
561
+ px_emu(y1),
562
+ px_emu(x2),
563
+ px_emu(y2),
564
+ )
565
+ conn.line.color.rgb = color_rgb
566
+ conn.line.width = Pt(max(0.5, width_px * PT_PER_PX))
567
+ if style == "dashed":
568
+ conn.line.dash_style = MSO_LINE_DASH_STYLE.DASH
569
+ elif style == "dotted":
570
+ conn.line.dash_style = MSO_LINE_DASH_STYLE.ROUND_DOT
571
+ ln = conn._element.spPr.find(qn("a:ln"))
572
+ if ln is not None:
573
+ _attach_alpha(ln, alpha)
574
+ _clear_shape_shadow(conn)
575
+ return conn
576
+
577
+
578
+ _EXPLICIT_SANS_FONTS: dict[str, str] = {
579
+ "arial": "Arial",
580
+ "segoe ui": "Segoe UI",
581
+ "calibri": "Calibri",
582
+ "verdana": "Verdana",
583
+ "tahoma": "Tahoma",
584
+ "trebuchet ms": "Trebuchet MS",
585
+ "helvetica": "Helvetica",
586
+ "helvetica neue": "Helvetica Neue",
587
+ }
588
+
589
+ _EXPLICIT_SERIF_FONTS: dict[str, str] = {
590
+ "times new roman": "Times New Roman",
591
+ "georgia": "Georgia",
592
+ }
593
+
594
+ _EXPLICIT_MONO_FONTS: dict[str, str] = {
595
+ "consolas": "Consolas",
596
+ "courier new": "Courier New",
597
+ }
598
+
599
+ _EXPLICIT_CJK_FONTS: dict[str, str] = {
600
+ "simsun": "SimSun",
601
+ "simhei": "SimHei",
602
+ "kaiti": "KaiTi",
603
+ "fangsong": "FangSong",
604
+ "microsoft yahei": "Microsoft YaHei",
605
+ "pingfang sc": "PingFang SC",
606
+ "hiragino sans gb": "Hiragino Sans GB",
607
+ "noto sans sc": "Noto Sans SC",
608
+ "noto serif sc": "Noto Serif SC",
609
+ "source han sans": "Source Han Sans",
610
+ "source han sans sc": "Source Han Sans",
611
+ "source han sans cn": "Source Han Sans",
612
+ "source han serif": "Source Han Serif",
613
+ "source han serif sc": "Source Han Serif",
614
+ "source han serif cn": "Source Han Serif",
615
+ "stsong": "STSong",
616
+ "stsongti-sc-black": "STSongti-SC-Black",
617
+ "songti sc": "Songti SC",
618
+ "stheiti": "STHeiti",
619
+ "stkaiti": "STKaiti",
620
+ }
621
+
622
+
623
+ _EXPLICIT_CJK_PREFIXES: tuple[str, ...] = (
624
+ "noto sans cjk",
625
+ "noto serif cjk",
626
+ "noto sans sc",
627
+ "noto serif sc",
628
+ "noto sans tc",
629
+ "noto serif tc",
630
+ "noto sans jp",
631
+ "noto serif jp",
632
+ "noto sans kr",
633
+ "noto serif kr",
634
+ "source han sans",
635
+ "source han serif",
636
+ "hiragino ",
637
+ "pingfang ",
638
+ "yu gothic",
639
+ "yu mincho",
640
+ "meiryo",
641
+ "malgun gothic",
642
+ "apple sd gothic",
643
+ "microsoft yahei",
644
+ "microsoft jhenghei",
645
+ "nsimsun",
646
+ "stfangsong",
647
+ "wenquanyi",
648
+ "lxgw",
649
+ "alibaba puhuiti",
650
+ "harmonyos sans",
651
+ )
652
+
653
+
654
+ def _find_explicit_cjk_font(tokens: list[str]) -> str | None:
655
+ """Return the first explicit CJK font family name from a CSS font-family token list."""
656
+ for raw_tok in tokens:
657
+ low = raw_tok.lower()
658
+ if low in _EXPLICIT_CJK_FONTS:
659
+ return _EXPLICIT_CJK_FONTS[low]
660
+ if any(low.startswith(pref) for pref in _EXPLICIT_CJK_PREFIXES):
661
+ return raw_tok
662
+ if any("\u3040" <= ch <= "\u9fff" or "\uac00" <= ch <= "\ud7af" for ch in raw_tok):
663
+ return raw_tok
664
+ return None
665
+
666
+
667
+ def map_fonts(
668
+ font_family_css: str,
669
+ font_weight: int,
670
+ *,
671
+ font_profile: str = "auto",
672
+ ) -> tuple[str, str, bool]:
673
+ """Map CSS fontFamily + numeric fontWeight to cross-platform (latin_typeface, ea_typeface, bold)."""
674
+ ff = (font_family_css or "").lower()
675
+ bold = font_weight >= 600
676
+
677
+ prof = (font_profile or "auto").strip().lower()
678
+ if prof == "auto":
679
+ if sys.platform == "win32" or os.name == "nt":
680
+ resolved_profile = "windows"
681
+ elif sys.platform == "darwin":
682
+ resolved_profile = "macos"
683
+ else:
684
+ resolved_profile = "cross-platform"
685
+ elif prof in ("windows", "macos", "cross-platform"):
686
+ resolved_profile = prof
687
+ else:
688
+ resolved_profile = "cross-platform"
689
+
690
+ tokens = [t.strip().strip("'\"").strip() for t in (font_family_css or "").split(",") if t.strip()]
691
+ tokens_lower = [t.lower() for t in tokens]
692
+ first_tok = tokens_lower[0] if tokens_lower else ""
693
+
694
+ explicit_ea = _find_explicit_cjk_font(tokens)
695
+
696
+ # Preserve explicit standard cross-platform CSS fonts when listed first
697
+ if first_tok in _EXPLICIT_MONO_FONTS:
698
+ return _EXPLICIT_MONO_FONTS[first_tok], explicit_ea or "Microsoft YaHei", bold
699
+ if first_tok in _EXPLICIT_SERIF_FONTS:
700
+ default_serif_ea = (
701
+ "SimSun"
702
+ if resolved_profile in ("windows", "cross-platform")
703
+ else ("STSongti-SC-Black" if font_weight >= 800 else "Songti SC")
704
+ )
705
+ return _EXPLICIT_SERIF_FONTS[first_tok], explicit_ea or default_serif_ea, bold
706
+ if first_tok == "arial black":
707
+ return "Arial Black", explicit_ea or "Microsoft YaHei", True
708
+ if first_tok in _EXPLICIT_SANS_FONTS:
709
+ return _EXPLICIT_SANS_FONTS[first_tok], explicit_ea or "Microsoft YaHei", bold
710
+
711
+ # Check monospace
712
+ if any(tok in ff for tok in ("menlo", "sf mono", "jetbrains mono", "fira code", "consolas", "courier new", "ui-monospace", "monospace")):
713
+ ea_mono = explicit_ea or "Microsoft YaHei"
714
+ if resolved_profile == "windows":
715
+ return "Consolas", ea_mono, bold
716
+ if resolved_profile == "cross-platform":
717
+ return "Courier New", ea_mono, bold
718
+ return "Menlo", ea_mono, bold
719
+
720
+ # Check serif (ignore generic 'sans-serif' when checking for 'serif')
721
+ ff_no_sans = ff.replace("sans-serif", "")
722
+ if any(tok in ff_no_sans for tok in ("songti", "stsong", "georgia", "serif", "times", "simsun", "mincho")):
723
+ if explicit_ea:
724
+ return "Georgia", explicit_ea, bold
725
+ if resolved_profile in ("windows", "cross-platform"):
726
+ return "Georgia", "SimSun", bold
727
+ ea = "STSongti-SC-Black" if font_weight >= 800 else "Songti SC"
728
+ return "Georgia", ea, bold
729
+
730
+ # Generic / webfont sans-serif: map >=800 heavy display weight to Arial Black across platforms
731
+ ea_sans = explicit_ea or "Microsoft YaHei"
732
+ if font_weight >= 800:
733
+ return "Arial Black", ea_sans, True
734
+ if resolved_profile == "windows":
735
+ return "Segoe UI", ea_sans, bold
736
+ if resolved_profile == "cross-platform":
737
+ return "Arial", ea_sans, bold
738
+ return "Helvetica Neue", ea_sans, bold
739
+
740
+
741
+ def _set_run_fonts(run: Any, latin_typeface: str, ea_typeface: str) -> None:
742
+ r_pr = run._r.get_or_add_rPr()
743
+ latin = r_pr.find(qn("a:latin"))
744
+ if latin is None:
745
+ latin = etree.SubElement(r_pr, qn("a:latin"))
746
+ latin.set("typeface", latin_typeface)
747
+
748
+ ea = r_pr.find(qn("a:ea"))
749
+ if ea is None:
750
+ ea = etree.SubElement(r_pr, qn("a:ea"))
751
+ ea.set("typeface", ea_typeface)
752
+
753
+
754
+ def _set_run_letter_spacing_px(run: Any, ls_px: float) -> None:
755
+ if abs(ls_px) < 0.05:
756
+ return
757
+ spc = round(ls_px * PT_PER_PX * 100.0)
758
+ run._r.get_or_add_rPr().set("spc", str(spc))
759
+
760
+
761
+ def _run_style_signature(run_data: dict[str, Any]) -> tuple[Any, ...]:
762
+ return (
763
+ str(run_data.get("fontFamily", "")),
764
+ round(float(run_data.get("fontSize", 24.0)), 2),
765
+ int(run_data.get("fontWeight", 400)),
766
+ str(run_data.get("fontStyle", "normal")).lower(),
767
+ str(run_data.get("color", "")),
768
+ round(float(run_data.get("opacity", 1.0)), 3),
769
+ round(float(run_data.get("letterSpacingPx", 0.0)), 2),
770
+ )
771
+
772
+
773
+ def _coalesce_runs(runs: list[dict[str, Any]]) -> list[dict[str, Any]]:
774
+ merged: list[dict[str, Any]] = []
775
+ prev_sig: tuple[Any, ...] | None = None
776
+ for r in runs:
777
+ txt = str(r.get("text") or "")
778
+ if not txt:
779
+ continue
780
+ sig = _run_style_signature(r)
781
+ if merged and prev_sig == sig:
782
+ merged[-1]["text"] = str(merged[-1]["text"]) + txt
783
+ else:
784
+ nr = dict(r)
785
+ nr["text"] = txt
786
+ merged.append(nr)
787
+ prev_sig = sig
788
+ return merged
789
+
790
+
791
+ def add_native_textbox(
792
+ slide: Any,
793
+ tb: dict[str, Any],
794
+ *,
795
+ canvas_w: float = CANVAS_W_PX,
796
+ font_profile: str = "auto",
797
+ wrap_mode: str = "reflow",
798
+ ) -> Any:
799
+ """Emit a native editable textbox from extracted visual lines & inline runs.
800
+
801
+ In `wrap_mode="reflow"` (default), soft-wrapped visual lines carrying `joinFromPrev`
802
+ ("space" or "direct") are merged back into logical reflowable paragraphs with
803
+ `word_wrap = True`, while single-line / hard-broken boxes preserve `word_wrap = False`
804
+ and legacy manifests without `joinFromPrev` behave identically to `exact`.
805
+ """
806
+ lines = tb.get("lines") or []
807
+ if not lines:
808
+ return None
809
+
810
+ is_rtl = str(tb.get("direction") or "ltr").strip().lower() == "rtl"
811
+ align_str = (tb.get("align") or "left").strip().lower()
812
+ if align_str == "start":
813
+ align_str = "right" if is_rtl else "left"
814
+ elif align_str == "end":
815
+ align_str = "left" if is_rtl else "right"
816
+ if align_str == "center":
817
+ pp_align = PP_ALIGN.CENTER
818
+ elif align_str == "right":
819
+ pp_align = PP_ALIGN.RIGHT
820
+ else:
821
+ pp_align = PP_ALIGN.LEFT
822
+
823
+ max_fs = max(
824
+ (float(r.get("fontSize", 24.0)) for ln in lines for r in (ln.get("runs") or [])),
825
+ default=24.0,
826
+ )
827
+ has_heavy_run = any(
828
+ int(r.get("fontWeight", 400)) >= 800
829
+ for ln in lines
830
+ for r in (ln.get("runs") or [])
831
+ )
832
+
833
+ line_lefts = [float(ln["x"]) for ln in lines]
834
+ line_rights = [float(ln["x"]) + float(ln["w"]) for ln in lines]
835
+ line_tops = [float(ln["y"]) for ln in lines]
836
+ line_bottoms = [float(ln["y"]) + float(ln["h"]) for ln in lines]
837
+
838
+ min_x = min(line_lefts)
839
+ max_x = max(line_rights)
840
+ raw_w = max(1.0, max_x - min_x)
841
+
842
+ # Defensively parse optional blockWidth (ignore non-numeric / bool / huge-int / non-positive values)
843
+ raw_bw = tb.get("blockWidth")
844
+ block_w = 0.0
845
+ if isinstance(raw_bw, (int, float)) and not isinstance(raw_bw, bool):
846
+ try:
847
+ bw_val = float(raw_bw)
848
+ except (TypeError, ValueError, OverflowError):
849
+ bw_val = 0.0
850
+ if math.isfinite(bw_val) and bw_val > 0.0:
851
+ block_w = bw_val
852
+
853
+ # Group visual lines into logical paragraphs when reflow mode is enabled and metadata exists
854
+ use_reflow = (
855
+ str(wrap_mode or "reflow").strip().lower() == "reflow"
856
+ and any("joinFromPrev" in ln for ln in lines)
857
+ )
858
+ paragraphs_data: list[dict[str, Any]] = []
859
+ if use_reflow:
860
+ for l_idx, ln in enumerate(lines):
861
+ if l_idx > 0:
862
+ raw_join = ln.get("joinFromPrev")
863
+ join_mode = raw_join.strip().lower() if isinstance(raw_join, str) else "hard"
864
+ if join_mode not in ("hard", "space", "direct"):
865
+ join_mode = "hard"
866
+ else:
867
+ join_mode = "hard"
868
+ line_runs = [dict(r) for r in (ln.get("runs") or []) if r.get("text")]
869
+ if l_idx == 0 or join_mode == "hard" or not paragraphs_data:
870
+ paragraphs_data.append({"runs": line_runs, "line_indices": [l_idx]})
871
+ else:
872
+ cur_para = paragraphs_data[-1]
873
+ if join_mode == "space" and cur_para["runs"]:
874
+ last_txt = str(cur_para["runs"][-1].get("text") or "")
875
+ if not last_txt.endswith(" "):
876
+ cur_para["runs"][-1]["text"] = last_txt + " "
877
+ cur_para["runs"].extend(line_runs)
878
+ cur_para["line_indices"].append(l_idx)
879
+ for p_obj in paragraphs_data:
880
+ p_obj["runs"] = _coalesce_runs(p_obj["runs"])
881
+ has_soft_wrapped_para = any(len(p_obj["line_indices"]) >= 2 for p_obj in paragraphs_data)
882
+ # Mixed narrow soft-wrap + overflowing nowrap line: if any line overflows block_w,
883
+ # widening the entire box to raw_w would unwrap narrow soft-wrapped lines -> fall back to exact mode.
884
+ if has_soft_wrapped_para and block_w > 0.0 and raw_w > block_w + 2.0:
885
+ paragraphs_data = [
886
+ {
887
+ "runs": [dict(r) for r in (ln.get("runs") or []) if r.get("text")],
888
+ "line_indices": [l_idx],
889
+ }
890
+ for l_idx, ln in enumerate(lines)
891
+ ]
892
+ has_soft_wrapped_para = False
893
+ else:
894
+ for l_idx, ln in enumerate(lines):
895
+ paragraphs_data.append(
896
+ {
897
+ "runs": [dict(r) for r in (ln.get("runs") or []) if r.get("text")],
898
+ "line_indices": [l_idx],
899
+ }
900
+ )
901
+ has_soft_wrapped_para = False
902
+
903
+ # Safe width padding so Keynote/PowerPoint/LibreOffice font metric differences
904
+ # (especially wider 'Arial Black' advance widths for >=800 runs) NEVER cause unintended wraps.
905
+ pad_w = max(14.0, max_fs * 0.28)
906
+ if has_heavy_run:
907
+ pad_w = max(pad_w, raw_w * 0.12 + max_fs * 0.28)
908
+
909
+ if has_soft_wrapped_para:
910
+ if block_w > 0.0:
911
+ # Keep box_w tight to block_w (plus minimal metric safety margin) so narrow wrap columns stay intact
912
+ safety = max(4.0, max_fs * 0.12)
913
+ reflow_w = max(raw_w + safety, block_w + safety)
914
+ if has_heavy_run:
915
+ reflow_w = max(reflow_w, block_w + max(6.0, max_fs * 0.16), raw_w + max(6.0, max_fs * 0.16))
916
+ else:
917
+ reflow_w = raw_w + max(8.0, max_fs * 0.22)
918
+ if has_heavy_run:
919
+ reflow_w = max(reflow_w, raw_w + pad_w)
920
+ if pp_align == PP_ALIGN.CENTER:
921
+ center_x = sum((l + r) * 0.5 for l, r in zip(line_lefts, line_rights)) / len(lines)
922
+ box_w = reflow_w
923
+ box_x = center_x - box_w * 0.5
924
+ elif pp_align == PP_ALIGN.RIGHT:
925
+ box_w = reflow_w
926
+ box_x = max_x - box_w
927
+ else:
928
+ box_x = min_x
929
+ box_w = reflow_w
930
+ else:
931
+ if pp_align == PP_ALIGN.CENTER:
932
+ center_x = sum((l + r) * 0.5 for l, r in zip(line_lefts, line_rights)) / len(lines)
933
+ box_w = raw_w + pad_w * 2.0
934
+ box_x = center_x - box_w * 0.5
935
+ elif pp_align == PP_ALIGN.RIGHT:
936
+ box_w = raw_w + pad_w
937
+ box_x = max_x - box_w
938
+ else:
939
+ box_x = min_x
940
+ box_w = raw_w + pad_w
941
+
942
+ if has_heavy_run or has_soft_wrapped_para:
943
+ max_canvas_w = max(1.0, float(canvas_w))
944
+ # Only clamp padding expansion against [min(0, min_x), max(canvas_w, max_x)]
945
+ # so intentionally off-slide text preserves its exact center-x / anchor.
946
+ min_bound = min(0.0, min_x)
947
+ max_bound = max(max_canvas_w, max_x)
948
+ avail_w = max(1.0, max_bound - min_bound)
949
+ if pp_align == PP_ALIGN.RIGHT:
950
+ anchor_right = min(max_x, max_bound)
951
+ if box_x < min_bound:
952
+ box_x = min_bound
953
+ box_w = max(1.0, anchor_right - min_bound)
954
+ elif box_x + box_w > max_bound:
955
+ box_w = min(box_w, avail_w)
956
+ box_x = max(min_bound, max_bound - box_w)
957
+ elif pp_align == PP_ALIGN.CENTER:
958
+ # Preserve exact center_x whenever the visual lines are intentionally off-slide
959
+ if min_x >= 0.0 and max_x <= max_canvas_w and (box_x < min_bound or box_x + box_w > max_bound):
960
+ if min_bound < center_x < max_bound:
961
+ half_w = min(box_w * 0.5, center_x - min_bound, max_bound - center_x)
962
+ if half_w * 2.0 >= raw_w:
963
+ box_w = max(1.0, half_w * 2.0)
964
+ box_x = center_x - half_w
965
+ else:
966
+ box_w = min(box_w, avail_w)
967
+ box_x = max(min_bound, min(center_x - box_w * 0.5, max_bound - box_w))
968
+ else:
969
+ box_w = min(box_w, avail_w)
970
+ box_x = max(min_bound, min(box_x, max_bound - box_w))
971
+ else:
972
+ if box_x < min_bound:
973
+ box_x = min_bound
974
+ if box_x + box_w > max_bound:
975
+ box_w = max(1.0, max_bound - box_x)
976
+
977
+ # Vertical geometry: use exact visual top & height
978
+ min_y = min(line_tops)
979
+ max_y = max(line_bottoms)
980
+ box_h = max(max_y - min_y + max(6.0, max_fs * 0.15), max_fs * 1.15)
981
+
982
+ # Compute per-paragraph internal line spacing strictly from consecutive soft-joined lines
983
+ # within each paragraph (never polluted by hard-break gaps between paragraphs), and compute
984
+ # explicit space_before across hard breaks when extra vertical gap exists.
985
+ para_line_steps: list[float] = []
986
+ for p_idx, p_obj in enumerate(paragraphs_data):
987
+ l_indices = p_obj["line_indices"]
988
+ internal_steps: list[float] = []
989
+ for k in range(len(l_indices) - 1):
990
+ st = float(lines[l_indices[k + 1]]["y"]) - float(lines[l_indices[k]]["y"])
991
+ if st > 1.0:
992
+ internal_steps.append(st)
993
+ if internal_steps:
994
+ para_line_steps.append(sum(internal_steps) / len(internal_steps))
995
+ else:
996
+ ln0 = lines[l_indices[0]]
997
+ p_fs = max((float(r.get("fontSize", 24.0)) for r in p_obj["runs"]), default=max_fs)
998
+ default_step = max(float(ln0["h"]), p_fs * 1.15)
999
+ # Measure compact line-to-line step for legacy manifests (no joinFromPrev) AND for
1000
+ # unmerged soft-wrapped lines (exact mode or mixed-width nowrap fallback), while keeping
1001
+ # explicit hard breaks separate so extra vertical gaps become space_before on the next paragraph.
1002
+ used_measured_step = False
1003
+ if p_idx + 1 < len(paragraphs_data):
1004
+ next_l0 = paragraphs_data[p_idx + 1]["line_indices"][0]
1005
+ next_join = lines[next_l0].get("joinFromPrev")
1006
+ next_join_norm = next_join.strip().lower() if isinstance(next_join, str) else None
1007
+ if next_join is None or next_join_norm in ("space", "direct"):
1008
+ delta = float(lines[next_l0]["y"]) - float(ln0["y"])
1009
+ if 1.0 < delta <= default_step * 1.45:
1010
+ default_step = delta
1011
+ used_measured_step = True
1012
+ if not used_measured_step and p_idx > 0:
1013
+ cur_join = ln0.get("joinFromPrev")
1014
+ cur_join_norm = cur_join.strip().lower() if isinstance(cur_join, str) else None
1015
+ if cur_join is None or cur_join_norm in ("space", "direct"):
1016
+ prev_l_last = paragraphs_data[p_idx - 1]["line_indices"][-1]
1017
+ delta_prev = float(ln0["y"]) - float(lines[prev_l_last]["y"])
1018
+ if 1.0 < delta_prev <= default_step * 1.45:
1019
+ default_step = delta_prev
1020
+ para_line_steps.append(default_step)
1021
+
1022
+ para_space_before_px: list[float] = [0.0] * len(paragraphs_data)
1023
+ for p_idx in range(1, len(paragraphs_data)):
1024
+ prev_last_l = paragraphs_data[p_idx - 1]["line_indices"][-1]
1025
+ next_first_l = paragraphs_data[p_idx]["line_indices"][0]
1026
+ prev_step = para_line_steps[p_idx - 1]
1027
+ expected_next_y = float(lines[prev_last_l]["y"]) + prev_step
1028
+ extra_gap = float(lines[next_first_l]["y"]) - expected_next_y
1029
+ if extra_gap > 2.0:
1030
+ para_space_before_px[p_idx] = extra_gap
1031
+
1032
+ # Calibrate Keynote first-line vertical baseline against Chromium Range.getClientRects():
1033
+ # - Single-line large display glyphs use Keynote default leading and sit slightly low -> lift ~4%.
1034
+ # - Multi-line blocks with tight fixed line_spacing (step < line0_h) lose top half-leading on line 0
1035
+ # in Keynote and shift upward -> compensate downward proportionally to (line0_h - step0).
1036
+ y_nudge = 0.0
1037
+ if max_fs >= 64.0:
1038
+ y_nudge = -max_fs * 0.04
1039
+ if len(lines) > 1 and para_line_steps:
1040
+ line0_h = float(lines[0]["h"])
1041
+ step0 = para_line_steps[0]
1042
+ if line0_h > step0:
1043
+ y_nudge += min(max_fs * 0.22, (line0_h - step0) * 0.45)
1044
+
1045
+ box = slide.shapes.add_textbox(
1046
+ px_emu(box_x),
1047
+ px_emu(min_y + y_nudge),
1048
+ max(1, px_emu(box_w)),
1049
+ max(1, px_emu(box_h)),
1050
+ )
1051
+ tf = box.text_frame
1052
+ tf.clear()
1053
+ tf.margin_left = tf.margin_right = tf.margin_top = tf.margin_bottom = 0
1054
+ tf.word_wrap = bool(has_soft_wrapped_para)
1055
+ tf.auto_size = MSO_AUTO_SIZE.NONE
1056
+ tf.vertical_anchor = MSO_ANCHOR.TOP
1057
+
1058
+ for p_idx, p_obj in enumerate(paragraphs_data):
1059
+ p = tf.paragraphs[0] if p_idx == 0 else tf.add_paragraph()
1060
+ p.alignment = pp_align
1061
+ if is_rtl:
1062
+ p._p.get_or_add_pPr().set("rtl", "1")
1063
+ sb_px = para_space_before_px[p_idx]
1064
+ p.space_before = Pt(round(sb_px * PT_PER_PX, 2)) if sb_px > 2.0 else Pt(0)
1065
+ p.space_after = Pt(0)
1066
+ if len(lines) > 1:
1067
+ step_px = para_line_steps[p_idx]
1068
+ p.line_spacing = Pt(max(4.0, step_px * PT_PER_PX))
1069
+
1070
+ for run_data in p_obj["runs"]:
1071
+ txt = run_data.get("text", "")
1072
+ if not txt:
1073
+ continue
1074
+ run = p.add_run()
1075
+ run.text = txt
1076
+ fs_px = float(run_data.get("fontSize", 24.0))
1077
+ fw = int(run_data.get("fontWeight", 400))
1078
+ latin, ea, is_bold = map_fonts(run_data.get("fontFamily", ""), fw, font_profile=font_profile)
1079
+ run.font.name = latin
1080
+ _set_run_fonts(run, latin, ea)
1081
+ run.font.size = px_pt(fs_px)
1082
+ run.font.bold = is_bold
1083
+ run.font.italic = str(run_data.get("fontStyle", "normal")).lower() in ("italic", "oblique")
1084
+
1085
+ parsed = parse_css_color(run_data.get("color"))
1086
+ eff_alpha = float(run_data.get("opacity", 1.0))
1087
+ if parsed:
1088
+ rgb, col_a = parsed
1089
+ run.font.color.rgb = rgb
1090
+ final_a = col_a * eff_alpha
1091
+ if final_a < 0.999:
1092
+ _attach_alpha(run._r.get_or_add_rPr(), final_a)
1093
+
1094
+ ls_px = float(run_data.get("letterSpacingPx", 0.0))
1095
+ _set_run_letter_spacing_px(run, ls_px)
1096
+
1097
+ return box
1098
+
1099
+
1100
+ # ---------------------------------------------------------------------------
1101
+ # Browser DOM Extraction Script & Versioned Slide Manifest
1102
+ # ---------------------------------------------------------------------------
1103
+ #
1104
+ # Slide Manifest Schema (manifest_version = 1):
1105
+ # {
1106
+ # "manifest_version": 1,
1107
+ # "canvas": { "width": 1920, "height": 1080 },
1108
+ # "slides": [
1109
+ # {
1110
+ # "slideIdx": 1,
1111
+ # "backgroundColor": "rgb(255, 255, 255)",
1112
+ # "hasBackgroundImage": false,
1113
+ # "backgroundImageCss": "",
1114
+ # "motionPreset": "none",
1115
+ # "transition": "auto",
1116
+ # "transitionDur": null,
1117
+ # "hasVisibleText": true,
1118
+ # "items": [ ... ], # paint-ordered DOM items from extract_slide_dom.js
1119
+ # "captureRequests": [ # descriptors for elements/backgrounds needing raster capture
1120
+ # { "captureId": "h2p-1-1", "kind": "svg", "slideIdx": 1, "rect": {...}, "hideChildren": false }
1121
+ # ]
1122
+ # }
1123
+ # ]
1124
+ # }
1125
+
1126
+ MANIFEST_VERSION = 1
1127
+ _VALID_MANIFEST_ITEM_KINDS = frozenset(
1128
+ {"box", "table", "transformed_visual", "gradient_box", "svg", "img", "text"}
1129
+ )
1130
+
1131
+
1132
+ def resolve_extract_slide_dom_js_path() -> Path:
1133
+ here = Path(__file__).resolve().parent
1134
+ candidates: list[Path] = [here / "extract_slide_dom.js"]
1135
+ for env_key in ("OIL_SLIDE_DIR", "OIL_ART_PPT_DIR"):
1136
+ env_val = (os.environ.get(env_key) or "").strip()
1137
+ if env_val:
1138
+ candidates.append(Path(env_val).resolve() / "scripts" / "extract_slide_dom.js")
1139
+ candidates.extend(
1140
+ [
1141
+ here.parent / "oil-slide" / "scripts" / "extract_slide_dom.js",
1142
+ here.parent.parent / "oil-slide" / "oil-slide" / "scripts" / "extract_slide_dom.js",
1143
+ ]
1144
+ )
1145
+ for cand in candidates:
1146
+ if cand.is_file():
1147
+ return cand.resolve()
1148
+ raise FileNotFoundError(
1149
+ f"Cannot locate extract_slide_dom.js (searched: {[str(c) for c in candidates]})"
1150
+ )
1151
+
1152
+
1153
+ _EXTRACT_SLIDE_DOM_JS_PATH_CACHE: Path | None = None
1154
+ _EXTRACT_SLIDE_DOM_JS_CACHE: str | None = None
1155
+
1156
+
1157
+ def _get_extract_slide_dom_js_path() -> Path:
1158
+ global _EXTRACT_SLIDE_DOM_JS_PATH_CACHE
1159
+ if _EXTRACT_SLIDE_DOM_JS_PATH_CACHE is None:
1160
+ _EXTRACT_SLIDE_DOM_JS_PATH_CACHE = resolve_extract_slide_dom_js_path()
1161
+ return _EXTRACT_SLIDE_DOM_JS_PATH_CACHE
1162
+
1163
+
1164
+ def _get_extract_slide_dom_js() -> str:
1165
+ global _EXTRACT_SLIDE_DOM_JS_CACHE
1166
+ if _EXTRACT_SLIDE_DOM_JS_CACHE is None:
1167
+ _EXTRACT_SLIDE_DOM_JS_CACHE = _get_extract_slide_dom_js_path().read_text(encoding="utf-8")
1168
+ return _EXTRACT_SLIDE_DOM_JS_CACHE
1169
+
1170
+
1171
+ def __getattr__(name: str) -> Any:
1172
+ if name == "EXTRACT_SLIDE_DOM_JS":
1173
+ return _get_extract_slide_dom_js()
1174
+ if name == "EXTRACT_SLIDE_DOM_JS_PATH":
1175
+ return _get_extract_slide_dom_js_path()
1176
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
1177
+
1178
+
1179
+ def _is_within_root(candidate: Path, root: Path) -> bool:
1180
+ try:
1181
+ candidate.resolve().relative_to(root.resolve())
1182
+ return True
1183
+ except ValueError:
1184
+ return False
1185
+
1186
+
1187
+ def _resolve_local_img_path(
1188
+ src: str,
1189
+ serve_root: Path,
1190
+ port: int,
1191
+ allowed_root: Path | None = None,
1192
+ ) -> Path | None:
1193
+ if not src or src.startswith("data:") or src.startswith("blob:") or "\0" in src:
1194
+ return None
1195
+ serve_abs = serve_root.resolve()
1196
+ boundary = allowed_root.resolve() if allowed_root is not None else serve_abs
1197
+ parsed = urllib.parse.urlparse(src)
1198
+ if parsed.scheme in ("http", "https"):
1199
+ # Static HTTP URLs resolve ONLY for the local render server's exact host and bound port.
1200
+ if parsed.scheme != "http" or parsed.hostname != "127.0.0.1" or parsed.port != port:
1201
+ return None
1202
+ rel = urllib.parse.unquote(parsed.path).lstrip("/")
1203
+ elif not parsed.scheme:
1204
+ if src.startswith("//"):
1205
+ return None
1206
+ rel = urllib.parse.unquote(parsed.path).lstrip("/")
1207
+ else:
1208
+ return None
1209
+
1210
+ if not rel or "\0" in rel:
1211
+ return None
1212
+ parts = [p for p in rel.replace("\\", "/").split("/") if p]
1213
+ if not parts or any(p in (".", "..") for p in parts):
1214
+ return None
1215
+
1216
+ cand = (serve_abs / Path(*parts)).resolve()
1217
+ if not _is_within_root(cand, serve_abs) or not _is_within_root(cand, boundary):
1218
+ return None
1219
+ if cand.is_file():
1220
+ return cand
1221
+ return None
1222
+
1223
+
1224
+ def _emit_box_item(slide: Any, item: dict[str, Any]) -> None:
1225
+ r = item["rect"]
1226
+ x, y, w, h = float(r["x"]), float(r["y"]), float(r["w"]), float(r["h"])
1227
+ if w <= 0.2 or h <= 0.2:
1228
+ return
1229
+
1230
+ eff_op = float(item.get("opacity", 1.0))
1231
+ radius_px = float(item.get("radiusPx", 0.0))
1232
+ shape_kind = str(item.get("shape") or "").strip().lower() or None
1233
+
1234
+ fill_rgba = None
1235
+ bg_parsed = parse_css_color(item.get("backgroundColor"))
1236
+ if bg_parsed:
1237
+ bg_alpha = bg_parsed[1] * eff_op
1238
+ if bg_alpha > 0.01:
1239
+ fill_rgba = (bg_parsed[0], bg_alpha)
1240
+
1241
+ borders = item.get("borders") or {}
1242
+ border_styles = item.get("borderStyles") or {}
1243
+ parsed_edges: dict[str, tuple[float, RGBColor, float, str]] = {}
1244
+ for side in ("top", "right", "bottom", "left"):
1245
+ bw, bcol = borders.get(side, [0, ""])
1246
+ bstyle = str(border_styles.get(side) or "solid").lower()
1247
+ bw_f = float(bw or 0.0)
1248
+ if bw_f > 0.1:
1249
+ bp = parse_css_color(bcol)
1250
+ if bp and bp[1] * eff_op > 0.01:
1251
+ parsed_edges[side] = (bw_f, bp[0], bp[1] * eff_op, bstyle)
1252
+
1253
+ # Check if all 4 edges are uniform
1254
+ uniform_border = False
1255
+ if len(parsed_edges) == 4:
1256
+ vals = list(parsed_edges.values())
1257
+ w0, c0, a0, s0 = vals[0]
1258
+ if all(abs(vw - w0) < 0.2 and vc == c0 and abs(va - a0) < 0.02 and vs == s0 for vw, vc, va, vs in vals[1:]):
1259
+ uniform_border = True
1260
+
1261
+ if uniform_border:
1262
+ w0, c0, a0, s0 = parsed_edges["top"]
1263
+ add_native_shape(
1264
+ slide,
1265
+ x,
1266
+ y,
1267
+ w,
1268
+ h,
1269
+ fill_rgba=fill_rgba,
1270
+ border_rgba=(c0, a0),
1271
+ border_width_px=w0,
1272
+ radius_px=radius_px,
1273
+ border_style=s0,
1274
+ shape_kind=shape_kind,
1275
+ )
1276
+ return
1277
+
1278
+ # Otherwise emit fill shape first (if any), then crisp individual edge bars or dashed lines
1279
+ if fill_rgba:
1280
+ add_native_shape(
1281
+ slide,
1282
+ x,
1283
+ y,
1284
+ w,
1285
+ h,
1286
+ fill_rgba=fill_rgba,
1287
+ border_rgba=None,
1288
+ border_width_px=0.0,
1289
+ radius_px=radius_px,
1290
+ shape_kind=shape_kind,
1291
+ )
1292
+
1293
+ for side, (bw_f, b_rgb, b_alpha, b_style) in parsed_edges.items():
1294
+ if b_style in ("dashed", "dotted"):
1295
+ if side == "top":
1296
+ _add_styled_line(slide, x, y + bw_f / 2.0, x + w, y + bw_f / 2.0, b_rgb, b_alpha, bw_f, b_style)
1297
+ elif side == "bottom":
1298
+ _add_styled_line(slide, x, y + h - bw_f / 2.0, x + w, y + h - bw_f / 2.0, b_rgb, b_alpha, bw_f, b_style)
1299
+ elif side == "left":
1300
+ _add_styled_line(slide, x + bw_f / 2.0, y, x + bw_f / 2.0, y + h, b_rgb, b_alpha, bw_f, b_style)
1301
+ elif side == "right":
1302
+ _add_styled_line(slide, x + w - bw_f / 2.0, y, x + w - bw_f / 2.0, y + h, b_rgb, b_alpha, bw_f, b_style)
1303
+ continue
1304
+ if side == "top":
1305
+ add_native_shape(slide, x, y, w, bw_f, fill_rgba=(b_rgb, b_alpha))
1306
+ elif side == "bottom":
1307
+ add_native_shape(slide, x, y + h - bw_f, w, bw_f, fill_rgba=(b_rgb, b_alpha))
1308
+ elif side == "left":
1309
+ add_native_shape(slide, x, y, bw_f, h, fill_rgba=(b_rgb, b_alpha))
1310
+ elif side == "right":
1311
+ add_native_shape(slide, x + w - bw_f, y, bw_f, h, fill_rgba=(b_rgb, b_alpha))
1312
+
1313
+
1314
+ def _set_cell_border_xml(
1315
+ tc_pr: Any,
1316
+ tag_name: str,
1317
+ width_px: float,
1318
+ color_css: str,
1319
+ style: str,
1320
+ eff_op: float,
1321
+ ) -> None:
1322
+ for old in tc_pr.findall(qn(tag_name)):
1323
+ tc_pr.remove(old)
1324
+ ln = etree.SubElement(tc_pr, qn(tag_name))
1325
+ parsed = parse_css_color(color_css) if width_px > 0.1 else None
1326
+ if parsed and parsed[1] * eff_op > 0.01:
1327
+ rgb, alpha = parsed[0], parsed[1] * eff_op
1328
+ ln.set("w", str(max(6350, round(width_px * PT_PER_PX * 12700))))
1329
+ ln.set("cap", "flat")
1330
+ ln.set("cmpd", "sng")
1331
+ ln.set("algn", "ctr")
1332
+ sf = etree.SubElement(ln, qn("a:solidFill"))
1333
+ srgb = etree.SubElement(sf, qn("a:srgbClr"))
1334
+ srgb.set("val", f"{rgb[0]:02X}{rgb[1]:02X}{rgb[2]:02X}")
1335
+ if alpha < 0.995:
1336
+ a_el = etree.SubElement(srgb, qn("a:alpha"))
1337
+ a_el.set("val", str(max(1000, min(100000, round(alpha * 100000)))))
1338
+ prst = etree.SubElement(ln, qn("a:prstDash"))
1339
+ if style == "dashed":
1340
+ prst.set("val", "dash")
1341
+ elif style == "dotted":
1342
+ prst.set("val", "sysDot")
1343
+ else:
1344
+ prst.set("val", "solid")
1345
+ else:
1346
+ etree.SubElement(ln, qn("a:noFill"))
1347
+
1348
+
1349
+ def _emit_table_item(slide: Any, item: dict[str, Any], *, font_profile: str = "auto") -> Any:
1350
+ """Emit a native PowerPoint table object (<a:tbl>) preserving cell geometry, typography, fill & hairlines."""
1351
+ r = item["rect"]
1352
+ x, y, w, h = float(r["x"]), float(r["y"]), float(r["w"]), float(r["h"])
1353
+ n_rows = int(item.get("nRows") or 0)
1354
+ n_cols = int(item.get("nCols") or 0)
1355
+ rows_data = item.get("rows") or []
1356
+ if n_rows < 2 or n_cols < 2 or not rows_data or w <= 2 or h <= 2:
1357
+ return None
1358
+
1359
+ tbl_shape = slide.shapes.add_table(
1360
+ n_rows,
1361
+ n_cols,
1362
+ px_emu(x),
1363
+ px_emu(y),
1364
+ max(1, px_emu(w)),
1365
+ max(1, px_emu(h)),
1366
+ )
1367
+ tbl = tbl_shape.table
1368
+
1369
+ # Disable default PowerPoint blue banding & theme table style so HTML fills/borders control appearance
1370
+ tbl_pr = tbl._tbl.find(qn("a:tblPr"))
1371
+ if tbl_pr is not None:
1372
+ for attr in ("bandRow", "bandCol", "firstRow", "lastRow", "firstCol", "lastCol"):
1373
+ tbl_pr.set(attr, "0")
1374
+ for sid in tbl_pr.findall(qn("a:tableStyleId")):
1375
+ tbl_pr.remove(sid)
1376
+
1377
+ # Measure column widths from the first unmerged full-width row (fallback to even distribution)
1378
+ col_widths_px: list[float] = [w / n_cols] * n_cols
1379
+ for row_obj in rows_data:
1380
+ cells = row_obj.get("cells") or []
1381
+ if len(cells) == n_cols and all(int(c.get("colSpan", 1)) == 1 for c in cells):
1382
+ measured = [max(8.0, float((c.get("rect") or {}).get("w") or (w / n_cols))) for c in cells]
1383
+ tot = sum(measured) or w
1384
+ col_widths_px = [mw * (w / tot) for mw in measured]
1385
+ break
1386
+
1387
+ for c_idx, cw in enumerate(col_widths_px):
1388
+ tbl.columns[c_idx].width = max(1, px_emu(cw))
1389
+
1390
+ occupied: set[tuple[int, int]] = set()
1391
+ for r_idx, row_obj in enumerate(rows_data[:n_rows]):
1392
+ row_h = max(10.0, float(row_obj.get("heightPx") or (h / n_rows)))
1393
+ tbl.rows[r_idx].height = max(1, px_emu(row_h))
1394
+ c_cursor = 0
1395
+ for cell_data in row_obj.get("cells") or []:
1396
+ while (r_idx, c_cursor) in occupied and c_cursor < n_cols:
1397
+ c_cursor += 1
1398
+ if c_cursor >= n_cols:
1399
+ break
1400
+ c_span = max(1, min(int(cell_data.get("colSpan", 1)), n_cols - c_cursor))
1401
+ r_span = max(1, min(int(cell_data.get("rowSpan", 1)), n_rows - r_idx))
1402
+ for dr in range(r_span):
1403
+ for dc in range(c_span):
1404
+ occupied.add((r_idx + dr, c_cursor + dc))
1405
+
1406
+ cell = tbl.cell(r_idx, c_cursor)
1407
+ if c_span > 1 or r_span > 1:
1408
+ try:
1409
+ cell.merge(tbl.cell(r_idx + r_span - 1, c_cursor + c_span - 1))
1410
+ except Exception:
1411
+ pass
1412
+
1413
+ eff_op = float(cell_data.get("opacity", 1.0))
1414
+ bg_alpha = float(cell_data.get("bgAlpha", 0.0))
1415
+ bg_parsed = parse_css_color(cell_data.get("backgroundColor"))
1416
+ if bg_parsed and bg_alpha > 0.01:
1417
+ cell.fill.solid()
1418
+ cell.fill.fore_color.rgb = bg_parsed[0]
1419
+ _attach_alpha(cell.fill._xPr, bg_alpha)
1420
+ else:
1421
+ cell.fill.background()
1422
+
1423
+ # Margins & vertical alignment
1424
+ cell.margin_top = px_emu(max(0.0, float(cell_data.get("padTop", 4.0)) * 0.6))
1425
+ cell.margin_bottom = px_emu(max(0.0, float(cell_data.get("padBottom", 4.0)) * 0.6))
1426
+ cell.margin_left = px_emu(max(0.0, float(cell_data.get("padLeft", 6.0)) * 0.7))
1427
+ cell.margin_right = px_emu(max(0.0, float(cell_data.get("padRight", 6.0)) * 0.7))
1428
+ va = str(cell_data.get("verticalAlign") or "middle")
1429
+ if va == "top":
1430
+ cell.vertical_anchor = MSO_ANCHOR.TOP
1431
+ elif va == "bottom":
1432
+ cell.vertical_anchor = MSO_ANCHOR.BOTTOM
1433
+ else:
1434
+ cell.vertical_anchor = MSO_ANCHOR.MIDDLE
1435
+
1436
+ # Per-side cell borders (explicit noFill on borderless sides)
1437
+ tc_pr = cell._tc.get_or_add_tcPr()
1438
+ cb = cell_data.get("borders") or {}
1439
+ for side_key, xml_tag in (("left", "a:lnL"), ("right", "a:lnR"), ("top", "a:lnT"), ("bottom", "a:lnB")):
1440
+ side_val = cb.get(side_key) or [0, "", "none"]
1441
+ bw_f = float(side_val[0] or 0.0)
1442
+ bcol = str(side_val[1] or "")
1443
+ bsty = str(side_val[2] or "solid").lower()
1444
+ _set_cell_border_xml(tc_pr, xml_tag, bw_f, bcol, bsty, eff_op)
1445
+
1446
+ # Cell text & run styling
1447
+ tf = cell.text_frame
1448
+ tf.word_wrap = True
1449
+ text_val = str(cell_data.get("text") or "")
1450
+ align_str = str(cell_data.get("textAlign") or "left")
1451
+ p_align = PP_ALIGN.RIGHT if align_str == "right" else (PP_ALIGN.CENTER if align_str == "center" else PP_ALIGN.LEFT)
1452
+ font_size = float(cell_data.get("fontSize") or 18.0)
1453
+ font_weight = int(cell_data.get("fontWeight") or (600 if cell_data.get("isHeader") else 400))
1454
+ latin_tf, ea_tf, is_bold = map_fonts(
1455
+ str(cell_data.get("fontFamily") or ""),
1456
+ font_weight,
1457
+ font_profile=font_profile,
1458
+ )
1459
+ color_parsed = parse_css_color(cell_data.get("color"))
1460
+ ls_px = float(cell_data.get("letterSpacingPx") or 0.0)
1461
+
1462
+ lines = text_val.splitlines() or [""]
1463
+ for l_idx, line_txt in enumerate(lines):
1464
+ p = tf.paragraphs[0] if l_idx == 0 else tf.add_paragraph()
1465
+ p.alignment = p_align
1466
+ p.space_before = Pt(0)
1467
+ p.space_after = Pt(0)
1468
+ run = p.add_run()
1469
+ run.text = line_txt
1470
+ run.font.size = Pt(max(6.0, font_size * PT_PER_PX))
1471
+ run.font.bold = is_bold
1472
+ run.font.italic = str(cell_data.get("fontStyle") or "") in ("italic", "oblique")
1473
+ run.font.name = latin_tf
1474
+ _set_run_fonts(run, latin_tf, ea_tf)
1475
+ _set_run_letter_spacing_px(run, ls_px)
1476
+ if color_parsed:
1477
+ run.font.color.rgb = color_parsed[0]
1478
+ alpha_val = color_parsed[1] * eff_op
1479
+ if alpha_val < 0.995:
1480
+ r_pr = run._r.get_or_add_rPr()
1481
+ sf = r_pr.find(qn("a:solidFill"))
1482
+ if sf is not None:
1483
+ _attach_alpha(sf, alpha_val)
1484
+ c_cursor += c_span
1485
+
1486
+ return tbl_shape
1487
+
1488
+
1489
+ def _capture_element_png(
1490
+ page: Any,
1491
+ slide_idx: int,
1492
+ capture_id: str,
1493
+ out_png: Path,
1494
+ hide_children: bool = False,
1495
+ *,
1496
+ clip_rect: dict[str, Any] | None = None,
1497
+ canvas_w: float = CANVAS_W_PX,
1498
+ canvas_h: float = CANVAS_H_PX,
1499
+ ) -> bool:
1500
+ sel = f'[data-h2p-id="{capture_id}"]'
1501
+ loc = page.locator(sel).first
1502
+ if loc.count() == 0:
1503
+ return False
1504
+ # Isolate ONLY the target element (hide active slide + all siblings so overlapping z-layers never bleed into capture)
1505
+ sl_rect = page.evaluate(
1506
+ """([idx, sel, hideChildren]) => {
1507
+ const sl = document.querySelector(`.slide[data-slide="${idx}"]`) ||
1508
+ document.querySelector(`[data-slide="${idx}"]`) ||
1509
+ document.querySelector('.slide.is-active, .slide.active') ||
1510
+ document.body;
1511
+ const el = document.querySelector(sel);
1512
+ if (!el) return null;
1513
+ window.__h2pIso = {
1514
+ sl,
1515
+ slVisVal: sl.style.getPropertyValue('visibility'),
1516
+ slVisPrio: sl.style.getPropertyPriority('visibility'),
1517
+ bodyBg: document.body.style.background,
1518
+ htmlBg: document.documentElement.style.background,
1519
+ el,
1520
+ elVisVal: el.style.getPropertyValue('visibility'),
1521
+ elVisPrio: el.style.getPropertyPriority('visibility'),
1522
+ elColor: el.style.color,
1523
+ hiddenNodes: [],
1524
+ };
1525
+ const keepVisible = new Set([el]);
1526
+ if (!hideChildren) {
1527
+ for (const desc of Array.from(el.querySelectorAll('*'))) {
1528
+ keepVisible.add(desc);
1529
+ }
1530
+ }
1531
+ const ancestors = new Set();
1532
+ for (let anc = el.parentElement; anc && anc !== sl; anc = anc.parentElement) {
1533
+ ancestors.add(anc);
1534
+ }
1535
+ const isoStyle = document.createElement('style');
1536
+ isoStyle.id = '__h2p-iso-style';
1537
+ isoStyle.textContent = '[data-h2p-iso-hide="1"],[data-h2p-iso-hide="1"]::before,[data-h2p-iso-hide="1"]::after{visibility:hidden!important;}';
1538
+ (document.head || document.documentElement).appendChild(isoStyle);
1539
+ window.__h2pIso.isoStyle = isoStyle;
1540
+ document.documentElement.style.background = 'transparent';
1541
+ document.body.style.background = 'transparent';
1542
+ sl.setAttribute('data-h2p-iso-hide', '1');
1543
+ sl.style.setProperty('visibility', 'hidden', 'important');
1544
+ for (const node of Array.from(sl.querySelectorAll('*'))) {
1545
+ if (keepVisible.has(node)) continue;
1546
+ const isAnc = ancestors.has(node);
1547
+ window.__h2pIso.hiddenNodes.push([
1548
+ node,
1549
+ node.style.getPropertyValue('visibility'),
1550
+ node.style.getPropertyPriority('visibility'),
1551
+ isAnc ? null : node.style.getPropertyValue('opacity'),
1552
+ isAnc ? null : node.style.getPropertyPriority('opacity'),
1553
+ ]);
1554
+ node.setAttribute('data-h2p-iso-hide', '1');
1555
+ node.style.setProperty('visibility', 'hidden', 'important');
1556
+ if (!isAnc) {
1557
+ node.style.setProperty('opacity', '0', 'important');
1558
+ }
1559
+ }
1560
+ el.style.setProperty('visibility', 'visible', 'important');
1561
+ if (hideChildren) {
1562
+ el.style.color = 'transparent';
1563
+ }
1564
+ const r = sl.getBoundingClientRect();
1565
+ return { x: r.left, y: r.top, w: r.width, h: r.height };
1566
+ }""",
1567
+ [slide_idx, sel, hide_children],
1568
+ )
1569
+ try:
1570
+ if clip_rect is not None and isinstance(sl_rect, dict):
1571
+ cw_f = max(1.0, float(canvas_w))
1572
+ ch_f = max(1.0, float(canvas_h))
1573
+ cx = max(0.0, float(clip_rect["x"]))
1574
+ cy = max(0.0, float(clip_rect["y"]))
1575
+ cw = min(cw_f, float(clip_rect["x"]) + float(clip_rect["w"])) - cx
1576
+ ch = min(ch_f, float(clip_rect["y"]) + float(clip_rect["h"])) - cy
1577
+ if cw <= 0.5 or ch <= 0.5:
1578
+ return False
1579
+ vp_scale_x = (float(sl_rect["w"]) / cw_f) if float(sl_rect.get("w") or 0) > 0 else 1.0
1580
+ vp_scale_y = (float(sl_rect["h"]) / ch_f) if float(sl_rect.get("h") or 0) > 0 else 1.0
1581
+ vp_clip = {
1582
+ "x": max(0.0, float(sl_rect["x"]) + cx * vp_scale_x),
1583
+ "y": max(0.0, float(sl_rect["y"]) + cy * vp_scale_y),
1584
+ "width": max(1.0, cw * vp_scale_x),
1585
+ "height": max(1.0, ch * vp_scale_y),
1586
+ }
1587
+ page.screenshot(path=str(out_png), clip=vp_clip, omit_background=True, animations="disabled", timeout=15000)
1588
+ else:
1589
+ loc.screenshot(path=str(out_png), omit_background=True, animations="disabled", timeout=15000)
1590
+ ok = out_png.is_file() and out_png.stat().st_size > 0
1591
+ except Exception:
1592
+ ok = False
1593
+ finally:
1594
+ page.evaluate(
1595
+ """() => {
1596
+ const st = window.__h2pIso;
1597
+ if (!st) return;
1598
+ for (const [node, prevVisVal, prevVisPrio, prevOpVal, prevOpPrio] of st.hiddenNodes) {
1599
+ node.removeAttribute('data-h2p-iso-hide');
1600
+ if (prevVisVal) {
1601
+ node.style.setProperty('visibility', prevVisVal, prevVisPrio || '');
1602
+ } else {
1603
+ node.style.removeProperty('visibility');
1604
+ }
1605
+ if (prevOpVal !== null) {
1606
+ if (prevOpVal) {
1607
+ node.style.setProperty('opacity', prevOpVal, prevOpPrio || '');
1608
+ } else {
1609
+ node.style.removeProperty('opacity');
1610
+ }
1611
+ }
1612
+ }
1613
+ st.sl.removeAttribute('data-h2p-iso-hide');
1614
+ if (st.isoStyle && st.isoStyle.parentNode) {
1615
+ st.isoStyle.parentNode.removeChild(st.isoStyle);
1616
+ }
1617
+ st.el.style.color = st.elColor || '';
1618
+ if (st.elVisVal) {
1619
+ st.el.style.setProperty('visibility', st.elVisVal, st.elVisPrio || '');
1620
+ } else {
1621
+ st.el.style.removeProperty('visibility');
1622
+ }
1623
+ if (st.slVisVal) {
1624
+ st.sl.style.setProperty('visibility', st.slVisVal, st.slVisPrio || '');
1625
+ } else {
1626
+ st.sl.style.removeProperty('visibility');
1627
+ }
1628
+ document.body.style.background = st.bodyBg || '';
1629
+ document.documentElement.style.background = st.htmlBg || '';
1630
+ delete window.__h2pIso;
1631
+ }"""
1632
+ )
1633
+ return ok
1634
+
1635
+
1636
+ def _image_has_transparency(img_path: Path) -> bool:
1637
+ try:
1638
+ with Image.open(img_path) as im:
1639
+ if im.mode in ("RGBA", "LA") or "transparency" in im.info:
1640
+ alpha = im.convert("RGBA").getchannel("A")
1641
+ lo, _ = alpha.getextrema()
1642
+ return lo < 252
1643
+ return False
1644
+ except Exception:
1645
+ return True
1646
+
1647
+
1648
+ def _capture_slide_bg_with_bottom_img(page: Any, slide_idx: int, capture_id: str, out_png: Path) -> bool:
1649
+ """Capture 1920x1080 composite of the slide background plus one full-bleed bottom <img>, hiding all other content."""
1650
+ sel = f'[data-h2p-id="{capture_id}"]'
1651
+ page.evaluate(
1652
+ """([idx, sel]) => {
1653
+ const sl = document.querySelector(`.slide[data-slide="${idx}"]`) ||
1654
+ document.querySelector(`[data-slide="${idx}"]`) ||
1655
+ document.querySelector('.slide.is-active, .slide.active');
1656
+ const target = document.querySelector(sel);
1657
+ if (!sl || !target) return;
1658
+ const keep = new Set();
1659
+ let cur = target;
1660
+ while (cur && cur !== sl) {
1661
+ keep.add(cur);
1662
+ cur = cur.parentElement;
1663
+ }
1664
+ window.__h2pBgImgHidden = [];
1665
+ for (const el of Array.from(sl.querySelectorAll('*'))) {
1666
+ if (keep.has(el)) continue;
1667
+ window.__h2pBgImgHidden.push([el, el.style.visibility]);
1668
+ el.style.visibility = 'hidden';
1669
+ }
1670
+ }""",
1671
+ [slide_idx, sel],
1672
+ )
1673
+ try:
1674
+ page.screenshot(path=str(out_png), full_page=False, animations="disabled", timeout=15000)
1675
+ ok = out_png.is_file() and out_png.stat().st_size > 0
1676
+ except Exception:
1677
+ ok = False
1678
+ finally:
1679
+ page.evaluate(
1680
+ """() => {
1681
+ for (const [el, prev] of (window.__h2pBgImgHidden || [])) {
1682
+ el.style.visibility = prev;
1683
+ }
1684
+ delete window.__h2pBgImgHidden;
1685
+ }"""
1686
+ )
1687
+ return ok
1688
+
1689
+
1690
+ def _extract_single_bg_url(bg_image_css: str | None) -> str | None:
1691
+ """Return URL string if CSS background-image is a single url(...) without gradients/multiple layers."""
1692
+ if not bg_image_css:
1693
+ return None
1694
+ m = re.match(r"""^\s*url\(\s*(['"]?)([^'")]+)\1\s*\)\s*$""", bg_image_css.strip(), re.IGNORECASE)
1695
+ return m.group(2).strip() if m else None
1696
+
1697
+
1698
+ _NS_P = "http://schemas.openxmlformats.org/presentationml/2006/main"
1699
+ _NS_P14 = "http://schemas.microsoft.com/office/powerpoint/2010/main"
1700
+ _NS_P159 = "http://schemas.microsoft.com/office/powerpoint/2015/09/main"
1701
+ _NS_MC = "http://schemas.openxmlformats.org/markup-compatibility/2006"
1702
+
1703
+ _MOTION_DEFAULTS: dict[str, dict[str, int]] = {
1704
+ "none": {"fade": 0, "push": 0, "morph": 0, "enter": 0, "stagger": 0},
1705
+ "refined": {"fade": 340, "push": 420, "morph": 840, "enter": 380, "stagger": 75},
1706
+ "cinematic": {"fade": 460, "push": 540, "morph": 1040, "enter": 480, "stagger": 95},
1707
+ }
1708
+
1709
+
1710
+ def _insert_slide_motion_node(slide: Any, node: Any, slot: str) -> None:
1711
+ """Insert <p:transition>/<mc:AlternateContent> or <p:timing> in strict ECMA-376 <p:sld> order."""
1712
+ sld = slide._element
1713
+ tag_c_sld = f"{{{_NS_P}}}cSld"
1714
+ tag_clr_map = f"{{{_NS_P}}}clrMapOvr"
1715
+ tag_trans = f"{{{_NS_P}}}transition"
1716
+ tag_timing = f"{{{_NS_P}}}timing"
1717
+ tag_ext = f"{{{_NS_P}}}extLst"
1718
+ tag_mc_ac = f"{{{_NS_MC}}}AlternateContent"
1719
+
1720
+ if slot == "transition":
1721
+ for ch in list(sld):
1722
+ if ch.tag == tag_trans:
1723
+ sld.remove(ch)
1724
+ elif ch.tag == tag_mc_ac and ch.find(f".//{{{_NS_P}}}transition") is not None:
1725
+ sld.remove(ch)
1726
+ insert_idx = 0
1727
+ for idx, ch in enumerate(list(sld)):
1728
+ if ch.tag in (tag_c_sld, tag_clr_map):
1729
+ insert_idx = idx + 1
1730
+ sld.insert(insert_idx, node)
1731
+ elif slot == "timing":
1732
+ for ch in list(sld):
1733
+ if ch.tag == tag_timing:
1734
+ sld.remove(ch)
1735
+ ext_el = sld.find(tag_ext)
1736
+ if ext_el is not None:
1737
+ sld.insert(list(sld).index(ext_el), node)
1738
+ else:
1739
+ sld.append(node)
1740
+
1741
+
1742
+ def _apply_slide_transition(slide: Any, transition_kind: str, dur_ms: int) -> str:
1743
+ """Inject native OOXML <p:transition> (or <mc:AlternateContent> p159:morph with fade fallback)."""
1744
+ kind = (transition_kind or "none").strip().lower()
1745
+ if kind == "none" or dur_ms <= 0:
1746
+ return "none"
1747
+ dur = max(150, min(2000, int(dur_ms)))
1748
+ spd = "fast" if dur <= 500 else ("med" if dur <= 1050 else "slow")
1749
+
1750
+ if kind == "morph":
1751
+ xml = (
1752
+ f'<mc:AlternateContent xmlns:mc="{_NS_MC}" xmlns:p="{_NS_P}" '
1753
+ f'xmlns:p14="{_NS_P14}" xmlns:p159="{_NS_P159}">'
1754
+ f'<mc:Choice Requires="p159">'
1755
+ f'<p:transition spd="{spd}" p14:dur="{dur}">'
1756
+ f'<p159:morph option="byObject"/>'
1757
+ f"</p:transition>"
1758
+ f"</mc:Choice>"
1759
+ f"<mc:Fallback>"
1760
+ f'<p:transition spd="fast" p14:dur="360"><p:fade/></p:transition>'
1761
+ f"</mc:Fallback>"
1762
+ f"</mc:AlternateContent>"
1763
+ )
1764
+ _insert_slide_motion_node(slide, parse_xml(xml), "transition")
1765
+ return "morph"
1766
+
1767
+ if kind == "push":
1768
+ xml = (
1769
+ f'<p:transition xmlns:p="{_NS_P}" xmlns:p14="{_NS_P14}" '
1770
+ f'spd="{spd}" p14:dur="{dur}"><p:push dir="r"/></p:transition>'
1771
+ )
1772
+ _insert_slide_motion_node(slide, parse_xml(xml), "transition")
1773
+ return "push"
1774
+
1775
+ xml = (
1776
+ f'<p:transition xmlns:p="{_NS_P}" xmlns:p14="{_NS_P14}" '
1777
+ f'spd="{spd}" p14:dur="{dur}"><p:fade/></p:transition>'
1778
+ )
1779
+ _insert_slide_motion_node(slide, parse_xml(xml), "transition")
1780
+ return "fade"
1781
+
1782
+
1783
+ def _build_entrance_effect_xml(
1784
+ spid: int,
1785
+ anim_kind: str,
1786
+ node_type: str,
1787
+ delay_ms: int,
1788
+ dur_ms: int,
1789
+ next_id: Any,
1790
+ ) -> str:
1791
+ """Build a valid OOXML <p:par> entrance node for a single shape spid."""
1792
+ kind = (anim_kind or "float-up").strip().lower()
1793
+ dur = max(120, min(1800, int(dur_ms)))
1794
+ delay = max(0, int(delay_ms))
1795
+
1796
+ preset_map = {
1797
+ "fade": ("10", "0"),
1798
+ "float-up": ("42", "0"),
1799
+ "float-left": ("42", "0"),
1800
+ "wipe": ("22", "8"),
1801
+ "scale-in": ("23", "16"),
1802
+ }
1803
+ preset_id, preset_sub = preset_map.get(kind, ("42", "0"))
1804
+
1805
+ id_outer = next_id()
1806
+ id_set = next_id()
1807
+ id_fx = next_id()
1808
+
1809
+ set_xml = (
1810
+ f"<p:set>"
1811
+ f'<p:cBhvr><p:cTn id="{id_set}" dur="1" fill="hold">'
1812
+ f'<p:stCondLst><p:cond delay="0"/></p:stCondLst></p:cTn>'
1813
+ f'<p:tgtEl><p:spTgt spid="{spid}"/></p:tgtEl>'
1814
+ f"<p:attrNameLst><p:attrName>style.visibility</p:attrName></p:attrNameLst>"
1815
+ f"</p:cBhvr>"
1816
+ f'<p:to><p:strVal val="visible"/></p:to>'
1817
+ f"</p:set>"
1818
+ )
1819
+
1820
+ if kind == "wipe":
1821
+ fx_xml = (
1822
+ f'<p:animEffect transition="in" filter="wipe(left)">'
1823
+ f'<p:cBhvr><p:cTn id="{id_fx}" dur="{dur}"/>'
1824
+ f'<p:tgtEl><p:spTgt spid="{spid}"/></p:tgtEl></p:cBhvr>'
1825
+ f"</p:animEffect>"
1826
+ )
1827
+ extra_xml = ""
1828
+ else:
1829
+ fx_xml = (
1830
+ f'<p:animEffect transition="in" filter="fade">'
1831
+ f'<p:cBhvr><p:cTn id="{id_fx}" dur="{dur}"/>'
1832
+ f'<p:tgtEl><p:spTgt spid="{spid}"/></p:tgtEl></p:cBhvr>'
1833
+ f"</p:animEffect>"
1834
+ )
1835
+ extra_xml = ""
1836
+ if kind == "float-up":
1837
+ id_move = next_id()
1838
+ extra_xml = (
1839
+ f'<p:anim calcmode="lin" valueType="num">'
1840
+ f'<p:cBhvr><p:cTn id="{id_move}" dur="{dur}" decel="80000" fill="hold"/>'
1841
+ f'<p:tgtEl><p:spTgt spid="{spid}"/></p:tgtEl>'
1842
+ f"<p:attrNameLst><p:attrName>ppt_y</p:attrName></p:attrNameLst>"
1843
+ f"</p:cBhvr>"
1844
+ f"<p:tavLst>"
1845
+ f'<p:tav tm="0"><p:val><p:strVal val="#ppt_y+0.024"/></p:val></p:tav>'
1846
+ f'<p:tav tm="100000"><p:val><p:strVal val="#ppt_y"/></p:val></p:tav>'
1847
+ f"</p:tavLst>"
1848
+ f"</p:anim>"
1849
+ )
1850
+ elif kind == "float-left":
1851
+ id_move = next_id()
1852
+ extra_xml = (
1853
+ f'<p:anim calcmode="lin" valueType="num">'
1854
+ f'<p:cBhvr><p:cTn id="{id_move}" dur="{dur}" decel="80000" fill="hold"/>'
1855
+ f'<p:tgtEl><p:spTgt spid="{spid}"/></p:tgtEl>'
1856
+ f"<p:attrNameLst><p:attrName>ppt_x</p:attrName></p:attrNameLst>"
1857
+ f"</p:cBhvr>"
1858
+ f"<p:tavLst>"
1859
+ f'<p:tav tm="0"><p:val><p:strVal val="#ppt_x+0.020"/></p:val></p:tav>'
1860
+ f'<p:tav tm="100000"><p:val><p:strVal val="#ppt_x"/></p:val></p:tav>'
1861
+ f"</p:tavLst>"
1862
+ f"</p:anim>"
1863
+ )
1864
+ elif kind == "scale-in":
1865
+ id_scale = next_id()
1866
+ extra_xml = (
1867
+ f"<p:animScale>"
1868
+ f'<p:cBhvr><p:cTn id="{id_scale}" dur="{dur}" decel="80000" fill="hold"/>'
1869
+ f'<p:tgtEl><p:spTgt spid="{spid}"/></p:tgtEl>'
1870
+ f"</p:cBhvr>"
1871
+ f'<p:from x="95000" y="95000"/><p:to x="100000" y="100000"/>'
1872
+ f"</p:animScale>"
1873
+ )
1874
+
1875
+ return (
1876
+ f"<p:par>"
1877
+ f'<p:cTn id="{id_outer}" presetID="{preset_id}" presetClass="entr" presetSubtype="{preset_sub}" '
1878
+ f'fill="hold" grpId="0" nodeType="{node_type}">'
1879
+ f'<p:stCondLst><p:cond delay="{delay}"/></p:stCondLst>'
1880
+ f"<p:childTnLst>{set_xml}{fx_xml}{extra_xml}</p:childTnLst>"
1881
+ f"</p:cTn>"
1882
+ f"</p:par>"
1883
+ )
1884
+
1885
+
1886
+ def _apply_slide_timing(slide: Any, anim_entries: list[dict[str, Any]], preset_cfg: dict[str, int]) -> int:
1887
+ """Inject native OOXML <p:timing> for auto-staggered and optional click-step entrance builds."""
1888
+ if not anim_entries or preset_cfg.get("enter", 0) <= 0:
1889
+ return 0
1890
+
1891
+ dedup: list[dict[str, Any]] = []
1892
+ seen_spids: set[int] = set()
1893
+ for ent in anim_entries:
1894
+ spid = int(ent["spid"])
1895
+ if spid in seen_spids:
1896
+ continue
1897
+ seen_spids.add(spid)
1898
+ dedup.append(ent)
1899
+ if not dedup:
1900
+ return 0
1901
+
1902
+ auto_items = [e for e in dedup if e.get("trigger") != "click"]
1903
+ click_items = [e for e in dedup if e.get("trigger") == "click"]
1904
+
1905
+ id_box = [2] # id=1 tmRoot, id=2 mainSeq
1906
+
1907
+ def _next_id() -> int:
1908
+ id_box[0] += 1
1909
+ return id_box[0]
1910
+
1911
+ seq_groups_xml: list[str] = []
1912
+ default_dur = preset_cfg["enter"]
1913
+ stagger_ms = preset_cfg["stagger"]
1914
+
1915
+ if auto_items:
1916
+ auto_sorted = sorted(auto_items, key=lambda e: (int(e.get("order") or 1), int(e.get("seq") or 0)))
1917
+ id_grp_outer = _next_id()
1918
+ id_grp_inner = _next_id()
1919
+ children_xml: list[str] = []
1920
+ for idx, ent in enumerate(auto_sorted):
1921
+ ord_num = max(1, int(ent.get("order") or 1))
1922
+ delay_val = ent.get("delay_ms")
1923
+ delay = int(delay_val) if delay_val is not None else (ord_num - 1) * stagger_ms
1924
+ dur_val = ent.get("dur_ms")
1925
+ dur = int(dur_val) if dur_val is not None else default_dur
1926
+ children_xml.append(
1927
+ _build_entrance_effect_xml(
1928
+ spid=int(ent["spid"]),
1929
+ anim_kind=str(ent.get("anim") or "float-up"),
1930
+ node_type="withEffect",
1931
+ delay_ms=delay,
1932
+ dur_ms=dur,
1933
+ next_id=_next_id,
1934
+ )
1935
+ )
1936
+ seq_groups_xml.append(
1937
+ f"<p:par>"
1938
+ f'<p:cTn id="{id_grp_outer}" fill="hold">'
1939
+ f'<p:stCondLst><p:cond delay="indefinite"/><p:cond evt="onBegin" delay="0"><p:tn val="2"/></p:cond></p:stCondLst>'
1940
+ f"<p:childTnLst><p:par>"
1941
+ f'<p:cTn id="{id_grp_inner}" fill="hold">'
1942
+ f'<p:stCondLst><p:cond delay="0"/></p:stCondLst>'
1943
+ f"<p:childTnLst>{''.join(children_xml)}</p:childTnLst>"
1944
+ f"</p:cTn></p:par></p:childTnLst>"
1945
+ f"</p:cTn></p:par>"
1946
+ )
1947
+
1948
+ if click_items:
1949
+ by_order: dict[int, list[dict[str, Any]]] = {}
1950
+ for idx, ent in enumerate(click_items):
1951
+ ord_key = int(ent.get("order") or (idx + 1))
1952
+ by_order.setdefault(ord_key, []).append(ent)
1953
+ for ord_key in sorted(by_order.keys()):
1954
+ grp = by_order[ord_key]
1955
+ id_grp_outer = _next_id()
1956
+ id_grp_inner = _next_id()
1957
+ children_xml = []
1958
+ for idx, ent in enumerate(grp):
1959
+ nt = "clickEffect" if idx == 0 else "withEffect"
1960
+ delay_val = ent.get("delay_ms")
1961
+ delay = int(delay_val) if delay_val is not None else min(idx * 25, 180)
1962
+ dur_val = ent.get("dur_ms")
1963
+ dur = int(dur_val) if dur_val is not None else default_dur
1964
+ children_xml.append(
1965
+ _build_entrance_effect_xml(
1966
+ spid=int(ent["spid"]),
1967
+ anim_kind=str(ent.get("anim") or "float-up"),
1968
+ node_type=nt,
1969
+ delay_ms=delay,
1970
+ dur_ms=dur,
1971
+ next_id=_next_id,
1972
+ )
1973
+ )
1974
+ seq_groups_xml.append(
1975
+ f"<p:par>"
1976
+ f'<p:cTn id="{id_grp_outer}" fill="hold">'
1977
+ f'<p:stCondLst><p:cond delay="indefinite"/></p:stCondLst>'
1978
+ f"<p:childTnLst><p:par>"
1979
+ f'<p:cTn id="{id_grp_inner}" fill="hold">'
1980
+ f'<p:stCondLst><p:cond delay="0"/></p:stCondLst>'
1981
+ f"<p:childTnLst>{''.join(children_xml)}</p:childTnLst>"
1982
+ f"</p:cTn></p:par></p:childTnLst>"
1983
+ f"</p:cTn></p:par>"
1984
+ )
1985
+
1986
+ # Per MS-OI29500, <p:bldP spid="..."/> may ONLY target text-bearing <p:sp> shapes (never <p:pic>)
1987
+ text_sp_ids: set[int] = set()
1988
+ sp_tree = slide._element.find(f".//{{{_NS_P}}}cSld/{{{_NS_P}}}spTree")
1989
+ if sp_tree is not None:
1990
+ for sp_el in sp_tree.findall(f".//{{{_NS_P}}}sp"):
1991
+ if sp_el.find(f"{{{_NS_P}}}txBody") is None:
1992
+ continue
1993
+ c_nv_pr = sp_el.find(f"{{{_NS_P}}}nvSpPr/{{{_NS_P}}}cNvPr")
1994
+ if c_nv_pr is not None and (c_nv_pr.get("id") or "").isdigit():
1995
+ text_sp_ids.add(int(c_nv_pr.get("id")))
1996
+
1997
+ bld_spids = [int(e["spid"]) for e in dedup if int(e["spid"]) in text_sp_ids]
1998
+ bld_lst_xml = (
1999
+ f"<p:bldLst>{''.join(f'<p:bldP spid=\"{sid}\" grpId=\"0\"/>' for sid in bld_spids)}</p:bldLst>"
2000
+ if bld_spids
2001
+ else ""
2002
+ )
2003
+ timing_xml = (
2004
+ f'<p:timing xmlns:p="{_NS_P}">'
2005
+ f"<p:tnLst><p:par>"
2006
+ f'<p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot">'
2007
+ f"<p:childTnLst>"
2008
+ f'<p:seq concurrent="1" nextAc="seek">'
2009
+ f'<p:cTn id="2" dur="indefinite" nodeType="mainSeq">'
2010
+ f"<p:childTnLst>{''.join(seq_groups_xml)}</p:childTnLst>"
2011
+ f"</p:cTn>"
2012
+ f'<p:prevCondLst><p:cond evt="onPrev" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>'
2013
+ f'<p:nextCondLst><p:cond evt="onNext" delay="0"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst>'
2014
+ f"</p:seq>"
2015
+ f"</p:childTnLst>"
2016
+ f"</p:cTn>"
2017
+ f"</p:par></p:tnLst>"
2018
+ f"{bld_lst_xml}"
2019
+ f"</p:timing>"
2020
+ )
2021
+ _insert_slide_motion_node(slide, parse_xml(timing_xml), "timing")
2022
+ return len(dedup)
2023
+
2024
+
2025
+ def _add_picture_fit(
2026
+ slide: Any,
2027
+ img_path: Path,
2028
+ x: float,
2029
+ y: float,
2030
+ w: float,
2031
+ h: float,
2032
+ tmp_dir: Path | None = None,
2033
+ ) -> Any:
2034
+ if not img_path.is_file() or w <= 0.2 or h <= 0.2:
2035
+ return None
2036
+ safe_path = _ensure_pptx_safe_image(img_path, tmp_dir)
2037
+ return slide.shapes.add_picture(
2038
+ str(safe_path), px_emu(x), px_emu(y), width=max(1, px_emu(w)), height=max(1, px_emu(h))
2039
+ )
2040
+
2041
+
2042
+ def _parse_item_borders(
2043
+ item: dict[str, Any],
2044
+ ) -> tuple[dict[str, tuple[float, RGBColor, float, str]], bool]:
2045
+ eff_op = float(item.get("opacity", 1.0))
2046
+ borders = item.get("borders") or {}
2047
+ border_styles = item.get("borderStyles") or {}
2048
+ parsed_edges: dict[str, tuple[float, RGBColor, float, str]] = {}
2049
+ for side in ("top", "right", "bottom", "left"):
2050
+ bw, bcol = borders.get(side, [0, ""])
2051
+ bstyle = str(border_styles.get(side) or "solid").lower()
2052
+ bw_f = float(bw or 0.0)
2053
+ if bw_f > 0.1:
2054
+ bp = parse_css_color(bcol)
2055
+ if bp and bp[1] * eff_op > 0.01:
2056
+ parsed_edges[side] = (bw_f, bp[0], bp[1] * eff_op, bstyle)
2057
+ uniform = False
2058
+ if len(parsed_edges) == 4:
2059
+ vals = list(parsed_edges.values())
2060
+ w0, c0, a0, s0 = vals[0]
2061
+ if all(
2062
+ abs(vw - w0) < 0.2 and vc == c0 and abs(va - a0) < 0.02 and vs == s0
2063
+ for vw, vc, va, vs in vals[1:]
2064
+ ):
2065
+ uniform = True
2066
+ return parsed_edges, uniform
2067
+
2068
+
2069
+ def _emit_direct_picture_with_borders(
2070
+ slide: Any,
2071
+ img_path: Path,
2072
+ item: dict[str, Any],
2073
+ x: float,
2074
+ y: float,
2075
+ w: float,
2076
+ h: float,
2077
+ tmp_dir: Path | None = None,
2078
+ ) -> Any:
2079
+ """Embed a direct local picture and preserve any visible CSS borders natively in PPTX."""
2080
+ parsed_edges, uniform = _parse_item_borders(item)
2081
+ if uniform:
2082
+ bw, b_rgb, b_alpha, b_style = parsed_edges["top"]
2083
+ # Center stroke on the CSS border-box perimeter
2084
+ inset = min(bw * 0.5, min(w, h) * 0.25)
2085
+ pic = _add_picture_fit(
2086
+ slide,
2087
+ img_path,
2088
+ x + inset,
2089
+ y + inset,
2090
+ max(0.5, w - 2.0 * inset),
2091
+ max(0.5, h - 2.0 * inset),
2092
+ tmp_dir=tmp_dir,
2093
+ )
2094
+ if pic is not None:
2095
+ pic.line.color.rgb = b_rgb
2096
+ pic.line.width = Pt(max(0.35, bw * PT_PER_PX))
2097
+ if b_style == "dashed":
2098
+ pic.line.dash_style = MSO_LINE_DASH_STYLE.DASH
2099
+ elif b_style == "dotted":
2100
+ pic.line.dash_style = MSO_LINE_DASH_STYLE.ROUND_DOT
2101
+ ln = pic._element.spPr.find(qn("a:ln"))
2102
+ if ln is not None:
2103
+ _attach_alpha(ln, b_alpha)
2104
+ _clear_shape_shadow(pic)
2105
+ return pic
2106
+
2107
+ bt = parsed_edges["top"][0] if "top" in parsed_edges else 0.0
2108
+ br = parsed_edges["right"][0] if "right" in parsed_edges else 0.0
2109
+ bb = parsed_edges["bottom"][0] if "bottom" in parsed_edges else 0.0
2110
+ bl = parsed_edges["left"][0] if "left" in parsed_edges else 0.0
2111
+ pic = _add_picture_fit(
2112
+ slide,
2113
+ img_path,
2114
+ x + bl,
2115
+ y + bt,
2116
+ max(0.5, w - bl - br),
2117
+ max(0.5, h - bt - bb),
2118
+ tmp_dir=tmp_dir,
2119
+ )
2120
+ if pic is not None and parsed_edges:
2121
+ for side, (bw_f, b_rgb, b_alpha, b_style) in parsed_edges.items():
2122
+ if b_style in ("dashed", "dotted"):
2123
+ if side == "top":
2124
+ _add_styled_line(slide, x, y + bw_f / 2.0, x + w, y + bw_f / 2.0, b_rgb, b_alpha, bw_f, b_style)
2125
+ elif side == "bottom":
2126
+ _add_styled_line(slide, x, y + h - bw_f / 2.0, x + w, y + h - bw_f / 2.0, b_rgb, b_alpha, bw_f, b_style)
2127
+ elif side == "left":
2128
+ _add_styled_line(slide, x + bw_f / 2.0, y, x + bw_f / 2.0, y + h, b_rgb, b_alpha, bw_f, b_style)
2129
+ elif side == "right":
2130
+ _add_styled_line(slide, x + w - bw_f / 2.0, y, x + w - bw_f / 2.0, y + h, b_rgb, b_alpha, bw_f, b_style)
2131
+ continue
2132
+ if side == "top":
2133
+ add_native_shape(slide, x, y, w, bw_f, fill_rgba=(b_rgb, b_alpha))
2134
+ elif side == "bottom":
2135
+ add_native_shape(slide, x, y + h - bw_f, w, bw_f, fill_rgba=(b_rgb, b_alpha))
2136
+ elif side == "left":
2137
+ add_native_shape(slide, x, y, bw_f, h, fill_rgba=(b_rgb, b_alpha))
2138
+ elif side == "right":
2139
+ add_native_shape(slide, x + w - bw_f, y, bw_f, h, fill_rgba=(b_rgb, b_alpha))
2140
+ return pic
2141
+
2142
+
2143
+ def audit_pptx_timing_xml(pptx_path: Path) -> list[str]:
2144
+ """Audit slide OOXML <p:timing> trees for PowerPoint entrance-animation defects."""
2145
+ if not Path(pptx_path).is_file():
2146
+ return [f"Missing PPTX file: {pptx_path}"]
2147
+ prs = Presentation(str(pptx_path))
2148
+ issues: list[str] = []
2149
+ for idx, slide in enumerate(prs.slides, start=1):
2150
+ sld_el = slide._element
2151
+
2152
+ # Collect slide shapes (spid -> local tag) and text-bearing <p:sp> IDs
2153
+ all_shape_tags: dict[int, str] = {}
2154
+ text_sp_ids: set[int] = set()
2155
+ sp_tree = sld_el.find(f".//{{{_NS_P}}}cSld/{{{_NS_P}}}spTree")
2156
+ if sp_tree is not None:
2157
+ for el in sp_tree.iter():
2158
+ tag = el.tag
2159
+ if not isinstance(tag, str) or not tag.startswith(f"{{{_NS_P}}}"):
2160
+ continue
2161
+ local = tag.split("}", 1)[1]
2162
+ nv_tag = {
2163
+ "sp": "nvSpPr",
2164
+ "pic": "nvPicPr",
2165
+ "graphicFrame": "nvGraphicFramePr",
2166
+ "cxnSp": "nvCxnSpPr",
2167
+ "grpSp": "nvGrpSpPr",
2168
+ }.get(local)
2169
+ if not nv_tag:
2170
+ continue
2171
+ c_nv_pr = el.find(f"{{{_NS_P}}}{nv_tag}/{{{_NS_P}}}cNvPr")
2172
+ if c_nv_pr is None:
2173
+ continue
2174
+ sid_raw = (c_nv_pr.get("id") or "").strip()
2175
+ if not sid_raw.isdigit():
2176
+ continue
2177
+ sid = int(sid_raw)
2178
+ all_shape_tags[sid] = local
2179
+ if local == "sp" and el.find(f"{{{_NS_P}}}txBody") is not None:
2180
+ text_sp_ids.add(sid)
2181
+
2182
+ # 1. Every <p:set> targeting style.visibility must have <p:to><p:strVal val="visible|hidden"/>
2183
+ for set_el in sld_el.findall(f".//{{{_NS_P}}}set"):
2184
+ attrs = [
2185
+ (a.text or "").strip()
2186
+ for a in set_el.findall(f".//{{{_NS_P}}}attrName")
2187
+ if (a.text or "").strip()
2188
+ ]
2189
+ if "style.visibility" in attrs:
2190
+ str_vals = set_el.findall(f"{{{_NS_P}}}to/{{{_NS_P}}}strVal")
2191
+ if not str_vals:
2192
+ issues.append(
2193
+ f"Slide {idx}: <p:set> targeting style.visibility is missing <p:to><p:strVal>"
2194
+ )
2195
+ else:
2196
+ for sv in str_vals:
2197
+ val = (sv.get("val") or "").strip()
2198
+ if val not in ("visible", "hidden"):
2199
+ issues.append(
2200
+ f"Slide {idx}: invalid <p:set> style.visibility value {val!r} (must be 'visible' or 'hidden')"
2201
+ )
2202
+
2203
+ # 2. Validate cTn/@id references and direct <p:par> triggers under mainSeq
2204
+ for timing_el in sld_el.findall(f".//{{{_NS_P}}}timing"):
2205
+ valid_ctn_ids = {
2206
+ c.get("id")
2207
+ for c in timing_el.findall(f".//{{{_NS_P}}}cTn")
2208
+ if c.get("id")
2209
+ }
2210
+ for tn_el in timing_el.findall(f".//{{{_NS_P}}}tn"):
2211
+ ref_id = (tn_el.get("val") or "").strip()
2212
+ if not ref_id or ref_id not in valid_ctn_ids:
2213
+ issues.append(
2214
+ f"Slide {idx}: <p:timing> <p:tn val={ref_id!r}/> references nonexistent cTn id"
2215
+ )
2216
+
2217
+ for ctn in timing_el.findall(f".//{{{_NS_P}}}cTn[@nodeType='mainSeq']"):
2218
+ child_lst = ctn.find(f"{{{_NS_P}}}childTnLst")
2219
+ if child_lst is None:
2220
+ continue
2221
+ for par in child_lst.findall(f"{{{_NS_P}}}par"):
2222
+ par_ctn = par.find(f"{{{_NS_P}}}cTn")
2223
+ if par_ctn is None:
2224
+ continue
2225
+ st_lst = par_ctn.find(f"{{{_NS_P}}}stCondLst")
2226
+ conds = st_lst.findall(f"{{{_NS_P}}}cond") if st_lst is not None else []
2227
+ if conds and all(
2228
+ c.get("delay") == "0" and not c.get("evt") and len(c) == 0
2229
+ for c in conds
2230
+ ):
2231
+ issues.append(
2232
+ f'Slide {idx}: mainSeq child <p:par> has bare <p:cond delay="0"/> without delay="indefinite" or event trigger'
2233
+ )
2234
+ has_indef = any(c.get("delay") == "indefinite" for c in conds)
2235
+ if has_indef:
2236
+ desc_node_types = {
2237
+ (c.get("nodeType") or "").strip()
2238
+ for c in par.findall(f".//{{{_NS_P}}}cTn")
2239
+ }
2240
+ has_click = "clickEffect" in desc_node_types
2241
+ has_non_click = bool(desc_node_types & {"withEffect", "afterEffect"})
2242
+ if has_non_click and not has_click:
2243
+ has_evt_tn = any(
2244
+ bool((c.get("evt") or "").strip())
2245
+ and any(
2246
+ (t.get("val") or "").strip() in valid_ctn_ids
2247
+ for t in c.findall(f"{{{_NS_P}}}tn")
2248
+ )
2249
+ for c in conds
2250
+ )
2251
+ if not has_evt_tn:
2252
+ issues.append(
2253
+ f'Slide {idx}: mainSeq auto-entrance <p:par> has delay="indefinite" without a valid sibling event <p:cond evt="..."><p:tn val="..."/></p:cond>'
2254
+ )
2255
+
2256
+ # 3. Zero <p:anim> nodes using #ppt_x or #ppt_y with additive="sum" (which doubles coordinates)
2257
+ for anim_el in sld_el.findall(f".//{{{_NS_P}}}anim"):
2258
+ cbhvr = anim_el.find(f"{{{_NS_P}}}cBhvr")
2259
+ if cbhvr is None or (cbhvr.get("additive") or "").strip().lower() != "sum":
2260
+ continue
2261
+ str_vals = [(sv.get("val") or "") for sv in anim_el.findall(f".//{{{_NS_P}}}strVal")]
2262
+ if any("#ppt_x" in v or "#ppt_y" in v for v in str_vals):
2263
+ issues.append(
2264
+ f'Slide {idx}: <p:anim> with #ppt_x/#ppt_y formula must not use additive="sum"'
2265
+ )
2266
+
2267
+ # 4. Every <p:bldP spid="..."/> must target an existing text-bearing <p:sp> (never <p:pic>)
2268
+ for bld_el in sld_el.findall(f".//{{{_NS_P}}}bldLst/{{{_NS_P}}}bldP"):
2269
+ sid_raw = (bld_el.get("spid") or "").strip()
2270
+ if not sid_raw.isdigit():
2271
+ issues.append(f"Slide {idx}: <p:bldP> has invalid spid {sid_raw!r}")
2272
+ continue
2273
+ sid = int(sid_raw)
2274
+ if sid not in all_shape_tags:
2275
+ issues.append(f"Slide {idx}: <p:bldP spid=\"{sid}\"/> references nonexistent shape")
2276
+ elif sid not in text_sp_ids:
2277
+ issues.append(
2278
+ f"Slide {idx}: <p:bldP spid=\"{sid}\"/> targets non-text-bearing <p:{all_shape_tags[sid]}> instead of text-bearing <p:sp>"
2279
+ )
2280
+
2281
+ return issues
2282
+
2283
+
2284
+ def audit_compiled_pptx(
2285
+ pptx_path: Path,
2286
+ expected_slides: int | None = None,
2287
+ expected_w_emu: int | None = None,
2288
+ expected_h_emu: int | None = None,
2289
+ ) -> dict[str, Any]:
2290
+ if not pptx_path.is_file():
2291
+ return {"ok": False, "issues": [f"Missing PPTX file: {pptx_path}"]}
2292
+ prs = Presentation(str(pptx_path))
2293
+ issues: list[str] = []
2294
+
2295
+ if expected_w_emu is not None and expected_h_emu is not None:
2296
+ if prs.slide_width != expected_w_emu or prs.slide_height != expected_h_emu:
2297
+ issues.append(
2298
+ f"Unexpected EMU dimensions: {prs.slide_width}x{prs.slide_height} (expected {expected_w_emu}x{expected_h_emu})"
2299
+ )
2300
+ else:
2301
+ valid_emus = {
2302
+ (round(w * EMU_PER_PX), round(h * EMU_PER_PX))
2303
+ for w, h in ((1920, 1080), (1080, 1440), (1080, 1920), (1440, 1440), (int(CANVAS_W_PX), int(CANVAS_H_PX)))
2304
+ } | {(int(SLIDE_W_EMU), int(SLIDE_H_EMU))}
2305
+ if (int(prs.slide_width), int(prs.slide_height)) not in valid_emus:
2306
+ issues.append(
2307
+ f"Unexpected EMU dimensions: {prs.slide_width}x{prs.slide_height} (expected {SLIDE_W_EMU}x{SLIDE_H_EMU})"
2308
+ )
2309
+ if expected_slides is not None and len(prs.slides) != expected_slides:
2310
+ issues.append(f"Slide count mismatch: expected {expected_slides}, got {len(prs.slides)}")
2311
+ if not prs.slides:
2312
+ issues.append("PPTX has 0 slides")
2313
+
2314
+ slides_info: list[dict[str, Any]] = []
2315
+ for idx, slide in enumerate(prs.slides, start=1):
2316
+ shapes_count = len(slide.shapes)
2317
+ text_boxes_count = 0
2318
+ pictures_count = 0
2319
+ auto_shapes_count = 0
2320
+ tables_count = 0
2321
+ table_text_cells = 0
2322
+ fonts: set[str] = set()
2323
+ samples: list[str] = []
2324
+
2325
+ for shape in slide.shapes:
2326
+ if shape.has_table:
2327
+ tables_count += 1
2328
+ for row in shape.table.rows:
2329
+ for cell in row.cells:
2330
+ ctxt = cell.text_frame.text.strip()
2331
+ if ctxt:
2332
+ table_text_cells += 1
2333
+ if len(samples) < 6:
2334
+ samples.append(ctxt.replace("\n", " / ")[:60])
2335
+ for para in cell.text_frame.paragraphs:
2336
+ for run in para.runs:
2337
+ if run.font and run.font.name:
2338
+ fonts.add(run.font.name)
2339
+ elif shape.has_text_frame:
2340
+ txt = shape.text_frame.text.strip()
2341
+ if txt:
2342
+ text_boxes_count += 1
2343
+ if len(samples) < 6:
2344
+ samples.append(txt.replace("\n", " / ")[:60])
2345
+ for para in shape.text_frame.paragraphs:
2346
+ for run in para.runs:
2347
+ if run.font and run.font.name:
2348
+ fonts.add(run.font.name)
2349
+ r_pr = run._r.find(qn("a:rPr"))
2350
+ if r_pr is not None:
2351
+ ea_el = r_pr.find(qn("a:ea"))
2352
+ if ea_el is not None and ea_el.get("typeface"):
2353
+ fonts.add(str(ea_el.get("typeface")))
2354
+ if shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
2355
+ pictures_count += 1
2356
+ elif shape.shape_type == MSO_SHAPE_TYPE.AUTO_SHAPE:
2357
+ auto_shapes_count += 1
2358
+
2359
+ if (text_boxes_count + table_text_cells) < 1:
2360
+ issues.append(f"Slide {idx}: only {text_boxes_count} editable text boxes and {table_text_cells} table cells (expected >= 1)")
2361
+
2362
+ sld_el = slide._element
2363
+ morph_el = sld_el.find(f".//{{{_NS_P159}}}morph")
2364
+ trans_el = sld_el.find(f".//{{{_NS_P}}}transition")
2365
+ if morph_el is not None:
2366
+ slide_trans_name = "morph"
2367
+ elif trans_el is not None:
2368
+ if trans_el.find(f"{{{_NS_P}}}push") is not None:
2369
+ slide_trans_name = "push"
2370
+ elif trans_el.find(f"{{{_NS_P}}}fade") is not None:
2371
+ slide_trans_name = "fade"
2372
+ else:
2373
+ slide_trans_name = "other"
2374
+ else:
2375
+ slide_trans_name = "none"
2376
+ morph_shapes_count = sum(1 for sh in slide.shapes if str(getattr(sh, "name", "") or "").startswith("!!"))
2377
+ animated_spids = {
2378
+ el.get("spid")
2379
+ for el in sld_el.findall(f".//{{{_NS_P}}}timing//{{{_NS_P}}}spTgt")
2380
+ if el.get("spid")
2381
+ }
2382
+
2383
+ slides_info.append(
2384
+ {
2385
+ "slide": idx,
2386
+ "shapes_count": shapes_count,
2387
+ "text_boxes_count": text_boxes_count,
2388
+ "auto_shapes_count": auto_shapes_count,
2389
+ "pictures_count": pictures_count,
2390
+ "tables_count": tables_count,
2391
+ "transition": slide_trans_name,
2392
+ "has_morph": morph_el is not None,
2393
+ "morph_shapes_count": morph_shapes_count,
2394
+ "animated_shapes_count": len(animated_spids),
2395
+ "fonts": sorted(fonts),
2396
+ "sample_texts": samples,
2397
+ }
2398
+ )
2399
+
2400
+ issues.extend(audit_pptx_timing_xml(pptx_path))
2401
+
2402
+ return {
2403
+ "ok": len(issues) == 0,
2404
+ "pptx_path": str(pptx_path),
2405
+ "emu_dimensions": [int(prs.slide_width), int(prs.slide_height)],
2406
+ "dimensions_in": [round(prs.slide_width.inches, 4), round(prs.slide_height.inches, 4)],
2407
+ "slide_count": len(prs.slides),
2408
+ "issues": issues,
2409
+ "slides": slides_info,
2410
+ }
2411
+
2412
+
2413
+ def _is_finite_num(val: Any) -> bool:
2414
+ if isinstance(val, bool) or not isinstance(val, (int, float)):
2415
+ return False
2416
+ try:
2417
+ return math.isfinite(float(val))
2418
+ except (TypeError, ValueError, OverflowError):
2419
+ return False
2420
+
2421
+
2422
+ def extract_slide_capture_requests(
2423
+ slide_data: dict[str, Any],
2424
+ canvas_w: float = CANVAS_W_PX,
2425
+ canvas_h: float = CANVAS_H_PX,
2426
+ ) -> list[dict[str, Any]]:
2427
+ explicit = slide_data.get("captureRequests")
2428
+ if isinstance(explicit, list):
2429
+ return [r for r in explicit if isinstance(r, dict) and r.get("captureId")]
2430
+
2431
+ slide_idx = int(slide_data.get("slideIdx") or 1)
2432
+ requests_out: list[dict[str, Any]] = []
2433
+ if slide_data.get("hasBackgroundImage") and not _extract_single_bg_url(slide_data.get("backgroundImageCss")):
2434
+ requests_out.append(
2435
+ {
2436
+ "captureId": f"s{slide_idx}-bg",
2437
+ "kind": "slide_bg",
2438
+ "slideIdx": slide_idx,
2439
+ "hideChildren": True,
2440
+ }
2441
+ )
2442
+
2443
+ fg_count = 0
2444
+ has_bg_pic = bool(slide_data.get("hasBackgroundImage"))
2445
+ for item in slide_data.get("items") or []:
2446
+ if not isinstance(item, dict):
2447
+ continue
2448
+ kind = item.get("kind")
2449
+ cid = item.get("captureId")
2450
+ if kind == "transformed_visual" and cid:
2451
+ req_entry: dict[str, Any] = {
2452
+ "captureId": str(cid),
2453
+ "kind": "transformed_visual",
2454
+ "slideIdx": slide_idx,
2455
+ "rect": item.get("rect"),
2456
+ "hideChildren": bool(item.get("hideChildren")),
2457
+ }
2458
+ if item.get("captureClip"):
2459
+ req_entry["captureClip"] = True
2460
+ requests_out.append(req_entry)
2461
+ fg_count += 1
2462
+ elif kind == "gradient_box" and cid:
2463
+ requests_out.append(
2464
+ {
2465
+ "captureId": str(cid),
2466
+ "kind": "gradient_box",
2467
+ "slideIdx": slide_idx,
2468
+ "rect": item.get("rect"),
2469
+ "hideChildren": bool(item.get("hasChildren")),
2470
+ }
2471
+ )
2472
+ fg_count += 1
2473
+ elif kind == "svg" and cid:
2474
+ requests_out.append(
2475
+ {
2476
+ "captureId": str(cid),
2477
+ "kind": "svg",
2478
+ "slideIdx": slide_idx,
2479
+ "rect": item.get("rect"),
2480
+ "hideChildren": False,
2481
+ }
2482
+ )
2483
+ fg_count += 1
2484
+ elif kind == "img":
2485
+ r = item.get("rect") or {}
2486
+ x = float(r.get("x", 0.0))
2487
+ y = float(r.get("y", 0.0))
2488
+ w = float(r.get("w", 0.0))
2489
+ h = float(r.get("h", 0.0))
2490
+ is_full_bleed_bottom = (
2491
+ fg_count == 0
2492
+ and x <= 2.0
2493
+ and y <= 2.0
2494
+ and w >= canvas_w - 4.0
2495
+ and h >= canvas_h - 4.0
2496
+ )
2497
+ if is_full_bleed_bottom:
2498
+ img_opacity = float(item.get("opacity", 1.0))
2499
+ if (item.get("needsCapture") or img_opacity < 0.99 or has_bg_pic) and cid:
2500
+ requests_out.append(
2501
+ {
2502
+ "captureId": str(cid),
2503
+ "kind": "slide_bg_with_bottom_img" if has_bg_pic else "img",
2504
+ "slideIdx": slide_idx,
2505
+ "rect": r,
2506
+ "hideChildren": False,
2507
+ }
2508
+ )
2509
+ has_bg_pic = True
2510
+ else:
2511
+ if item.get("needsCapture") and cid:
2512
+ requests_out.append(
2513
+ {
2514
+ "captureId": str(cid),
2515
+ "kind": "img",
2516
+ "slideIdx": slide_idx,
2517
+ "rect": r,
2518
+ "hideChildren": False,
2519
+ }
2520
+ )
2521
+ fg_count += 1
2522
+ else:
2523
+ fg_count += 1
2524
+ return requests_out
2525
+
2526
+
2527
+ def validate_slide_manifest(
2528
+ manifest: Any,
2529
+ *,
2530
+ check_sanity: bool = False,
2531
+ ) -> dict[str, Any]:
2532
+ if not isinstance(manifest, dict):
2533
+ raise ValueError("Slide manifest must be a JSON object")
2534
+
2535
+ ver = manifest.get("manifest_version")
2536
+ if isinstance(ver, bool) or not isinstance(ver, int) or ver != MANIFEST_VERSION:
2537
+ raise ValueError(
2538
+ f"Unsupported or missing manifest_version: {ver!r} (expected {MANIFEST_VERSION})"
2539
+ )
2540
+
2541
+ canvas = manifest.get("canvas")
2542
+ if not isinstance(canvas, dict):
2543
+ raise ValueError("Manifest 'canvas' must be an object with 'width' and 'height'")
2544
+ raw_w = canvas.get("width")
2545
+ raw_h = canvas.get("height")
2546
+ if not _is_finite_num(raw_w) or not _is_finite_num(raw_h):
2547
+ raise ValueError("Manifest canvas width and height must be finite numbers")
2548
+ canvas_w = int(round(float(raw_w)))
2549
+ canvas_h = int(round(float(raw_h)))
2550
+ if canvas_w < 64 or canvas_w > 10000 or canvas_h < 64 or canvas_h > 10000:
2551
+ raise ValueError(f"Manifest canvas dimensions out of valid range: {canvas_w}x{canvas_h}")
2552
+
2553
+ slides = manifest.get("slides")
2554
+ if not isinstance(slides, list) or len(slides) == 0:
2555
+ raise ValueError("Manifest 'slides' must be a non-empty list")
2556
+ if len(slides) > 200:
2557
+ raise ValueError(f"Manifest 'slides' exceeds maximum slide count (200): {len(slides)}")
2558
+
2559
+ for idx, slide in enumerate(slides, start=1):
2560
+ if not isinstance(slide, dict):
2561
+ raise ValueError(f"Slide #{idx} in manifest must be an object")
2562
+ items = slide.get("items")
2563
+ if not isinstance(items, list):
2564
+ raise ValueError(f"Slide #{idx} 'items' must be a list")
2565
+ cap_reqs = slide.get("captureRequests")
2566
+ if cap_reqs is not None and not isinstance(cap_reqs, list):
2567
+ raise ValueError(f"Slide #{idx} 'captureRequests' must be a list when present")
2568
+
2569
+ text_item_count = 0
2570
+ for item_idx, item in enumerate(items):
2571
+ if not isinstance(item, dict):
2572
+ raise ValueError(f"Slide #{idx} item #{item_idx} must be an object")
2573
+ kind = item.get("kind")
2574
+ if not isinstance(kind, str) or kind not in _VALID_MANIFEST_ITEM_KINDS:
2575
+ raise ValueError(f"Slide #{idx} item #{item_idx} has invalid kind: {kind!r}")
2576
+
2577
+ if kind == "text":
2578
+ if "blockWidth" in item and item["blockWidth"] is not None:
2579
+ bw = item["blockWidth"]
2580
+ if not _is_finite_num(bw) or float(bw) <= 0:
2581
+ raise ValueError(
2582
+ f"Slide #{idx} text item #{item_idx} has invalid 'blockWidth': {bw!r} (expected finite number > 0)"
2583
+ )
2584
+ if "direction" in item and item["direction"] is not None:
2585
+ direction = item["direction"]
2586
+ if not isinstance(direction, str) or direction not in ("ltr", "rtl"):
2587
+ raise ValueError(
2588
+ f"Slide #{idx} text item #{item_idx} has invalid 'direction': {direction!r} (expected 'ltr' or 'rtl')"
2589
+ )
2590
+ lines = item.get("lines")
2591
+ if not isinstance(lines, list) or len(lines) == 0:
2592
+ raise ValueError(f"Slide #{idx} text item #{item_idx} must have non-empty 'lines'")
2593
+ for ln in lines:
2594
+ if not isinstance(ln, dict):
2595
+ raise ValueError(f"Slide #{idx} text line must be an object")
2596
+ if "joinFromPrev" in ln and ln["joinFromPrev"] is not None:
2597
+ jfp = ln["joinFromPrev"]
2598
+ if not isinstance(jfp, str) or jfp not in ("hard", "space", "direct"):
2599
+ raise ValueError(
2600
+ f"Slide #{idx} text line has invalid 'joinFromPrev': {jfp!r} (expected 'hard', 'space', or 'direct')"
2601
+ )
2602
+ for coord in ("x", "y", "w", "h"):
2603
+ if not _is_finite_num(ln.get(coord)):
2604
+ raise ValueError(f"Slide #{idx} text line missing finite '{coord}'")
2605
+ lx, ly, lw, lh = float(ln["x"]), float(ln["y"]), float(ln["w"]), float(ln["h"])
2606
+ if lw <= 0 or lh <= 0:
2607
+ raise ValueError(f"Slide #{idx} text line has non-positive size: {lw}x{lh}")
2608
+ if check_sanity and (
2609
+ lx + lw <= 0
2610
+ or lx >= canvas_w
2611
+ or ly + lh <= 0
2612
+ or ly >= canvas_h
2613
+ or lx < -canvas_w * 0.5
2614
+ or ly < -canvas_h * 0.5
2615
+ or lx + lw > canvas_w * 1.5
2616
+ or ly + lh > canvas_h * 1.5
2617
+ ):
2618
+ raise ValueError(
2619
+ f"Sanity check failed on slide #{idx}: text line box ({lx},{ly},{lw},{lh}) outside canvas {canvas_w}x{canvas_h}"
2620
+ )
2621
+ runs = ln.get("runs")
2622
+ if not isinstance(runs, list) or len(runs) == 0:
2623
+ raise ValueError(f"Slide #{idx} text line must have non-empty 'runs'")
2624
+ if any(isinstance(r, dict) and str(r.get("text") or "").strip() for r in runs):
2625
+ text_item_count += 1
2626
+ else:
2627
+ if kind == "table":
2628
+ text_item_count += 1
2629
+ rect = item.get("rect")
2630
+ if not isinstance(rect, dict):
2631
+ raise ValueError(f"Slide #{idx} {kind} item #{item_idx} must have a 'rect' object")
2632
+ for coord in ("x", "y", "w", "h"):
2633
+ if not _is_finite_num(rect.get(coord)):
2634
+ raise ValueError(f"Slide #{idx} {kind} item #{item_idx} rect missing finite '{coord}'")
2635
+ rx, ry, rw, rh = float(rect["x"]), float(rect["y"]), float(rect["w"]), float(rect["h"])
2636
+ if rw <= 0 or rh <= 0:
2637
+ raise ValueError(f"Slide #{idx} {kind} item #{item_idx} has non-positive size: {rw}x{rh}")
2638
+ if check_sanity and (
2639
+ rx + rw <= 0
2640
+ or rx >= canvas_w
2641
+ or ry + rh <= 0
2642
+ or ry >= canvas_h
2643
+ or rx < -canvas_w * 0.5
2644
+ or ry < -canvas_h * 0.5
2645
+ or rx + rw > canvas_w * 1.5
2646
+ or ry + rh > canvas_h * 1.5
2647
+ ):
2648
+ raise ValueError(
2649
+ f"Sanity check failed on slide #{idx}: {kind} box ({rx},{ry},{rw},{rh}) outside canvas {canvas_w}x{canvas_h}"
2650
+ )
2651
+
2652
+ if check_sanity and slide.get("hasVisibleText") is True and text_item_count == 0:
2653
+ raise ValueError(
2654
+ f"Sanity check failed on slide #{idx}: slide has visible text in DOM but zero text items in manifest"
2655
+ )
2656
+
2657
+ return manifest
2658
+
2659
+
2660
+ def _normalize_asset_key_variants(raw_ref: str) -> list[str]:
2661
+ ref = str(raw_ref or "").strip()
2662
+ if not ref or ref.startswith("data:") or ref.startswith("blob:") or "\0" in ref:
2663
+ return []
2664
+ candidates: list[str] = [ref]
2665
+ parsed = urllib.parse.urlparse(ref)
2666
+ path_part = urllib.parse.unquote(parsed.path or "").replace("\\", "/").strip()
2667
+ if path_part:
2668
+ clean_path = path_part.lstrip("/")
2669
+ if clean_path and clean_path not in candidates:
2670
+ candidates.append(clean_path)
2671
+ m_api = re.match(r"^api/runs/[^/]+/assets/(.+)$", clean_path)
2672
+ if m_api:
2673
+ api_rel = m_api.group(1).lstrip("/")
2674
+ if api_rel and api_rel not in candidates:
2675
+ candidates.append(api_rel)
2676
+
2677
+ expanded: list[str] = []
2678
+ for cand in candidates:
2679
+ if cand not in expanded:
2680
+ expanded.append(cand)
2681
+ no_up = re.sub(r"^(?:\.\./|\./)+", "", cand).lstrip("/")
2682
+ if no_up and no_up not in expanded:
2683
+ expanded.append(no_up)
2684
+ if no_up.startswith("web/"):
2685
+ without_web = no_up[4:]
2686
+ if without_web and without_web not in expanded:
2687
+ expanded.append(without_web)
2688
+ elif no_up.startswith("assets/"):
2689
+ with_web = f"web/{no_up}"
2690
+ if with_web not in expanded:
2691
+ expanded.append(with_web)
2692
+ return expanded
2693
+
2694
+
2695
+ class _ManifestAssetResolver:
2696
+ """Resolves manifest asset references by URL, local path, data URI, or in-memory bytes."""
2697
+
2698
+ def __init__(
2699
+ self,
2700
+ assets: Any,
2701
+ tmp_dir: Path,
2702
+ *,
2703
+ serve_root: Path | None = None,
2704
+ port: int | None = None,
2705
+ allowed_root: Path | None = None,
2706
+ ) -> None:
2707
+ self.tmp_dir = tmp_dir
2708
+ self.serve_root = serve_root.resolve() if serve_root is not None else None
2709
+ self.port = port
2710
+ self.allowed_root = allowed_root.resolve() if allowed_root is not None else None
2711
+ self.asset_dirs: list[Path] = []
2712
+ self.entries: dict[str, Any] = {}
2713
+ self._materialized: dict[str, Path] = {}
2714
+
2715
+ if isinstance(assets, (str, Path)):
2716
+ p = Path(assets).resolve()
2717
+ if p.is_dir():
2718
+ self.asset_dirs.append(p)
2719
+ elif isinstance(assets, dict):
2720
+ for k, v in assets.items():
2721
+ self._register_entry(str(k), v)
2722
+ elif isinstance(assets, list):
2723
+ for item in assets:
2724
+ if not isinstance(item, dict):
2725
+ continue
2726
+ key = str(
2727
+ item.get("rel_path")
2728
+ or item.get("captureId")
2729
+ or item.get("name")
2730
+ or item.get("src")
2731
+ or ""
2732
+ ).strip()
2733
+ if key:
2734
+ self._register_entry(key, item)
2735
+
2736
+ for d in (self.serve_root, self.allowed_root):
2737
+ if d is not None and d not in self.asset_dirs and d.is_dir():
2738
+ self.asset_dirs.append(d)
2739
+
2740
+ def _register_entry(self, key: str, value: Any) -> None:
2741
+ self.entries[key] = value
2742
+ for variant in _normalize_asset_key_variants(key):
2743
+ self.entries.setdefault(variant, value)
2744
+ if not key.lower().endswith(".png"):
2745
+ self.entries.setdefault(f"{key}.png", value)
2746
+
2747
+ def _materialize_value(self, key_hint: str, val: Any) -> Path | None:
2748
+ if isinstance(val, Path):
2749
+ p = val.resolve()
2750
+ if self.allowed_root is not None and not _is_within_root(p, self.allowed_root) and not _is_within_root(p, self.tmp_dir.resolve()):
2751
+ return None
2752
+ return p if p.is_file() else None
2753
+
2754
+ raw_bytes: bytes | None = None
2755
+ if isinstance(val, (bytes, bytearray, memoryview)):
2756
+ raw_bytes = bytes(val)
2757
+ elif isinstance(val, dict):
2758
+ if isinstance(val.get("bytes"), (bytes, bytearray, memoryview)):
2759
+ raw_bytes = bytes(val["bytes"])
2760
+ elif isinstance(val.get("path"), (str, Path)):
2761
+ return self._materialize_value(key_hint, Path(val["path"]))
2762
+ else:
2763
+ b64 = val.get("base64") or val.get("data_base64")
2764
+ if isinstance(b64, str) and b64.strip():
2765
+ if b64.startswith("data:"):
2766
+ return self._decode_data_uri(b64)
2767
+ try:
2768
+ raw_bytes = base64.b64decode(b64)
2769
+ except Exception:
2770
+ return None
2771
+ elif isinstance(val, str):
2772
+ s = val.strip()
2773
+ if not s:
2774
+ return None
2775
+ if s.startswith("data:"):
2776
+ return self._decode_data_uri(s)
2777
+ # Check if it's an existing path on disk within allowed roots
2778
+ if "\0" not in s and len(s) < 1024:
2779
+ cand_p = Path(s)
2780
+ if cand_p.is_absolute():
2781
+ resolved = cand_p.resolve()
2782
+ if (self.allowed_root is None or _is_within_root(resolved, self.allowed_root) or _is_within_root(resolved, self.tmp_dir.resolve())) and resolved.is_file():
2783
+ return resolved
2784
+ else:
2785
+ for root in self.asset_dirs:
2786
+ boundary = self.allowed_root or root
2787
+ resolved = (root / cand_p).resolve()
2788
+ if _is_within_root(resolved, root) and _is_within_root(resolved, boundary) and resolved.is_file():
2789
+ return resolved
2790
+ try:
2791
+ raw_bytes = base64.b64decode(s, validate=True)
2792
+ except Exception:
2793
+ return None
2794
+
2795
+ if not raw_bytes:
2796
+ return None
2797
+ digest = hashlib.sha256(raw_bytes).hexdigest()[:16]
2798
+ ext = Path(key_hint.split("?")[0]).suffix.lower()
2799
+ if ext not in (".png", ".jpg", ".jpeg", ".webp", ".gif"):
2800
+ ext = ".png"
2801
+ out_p = self.tmp_dir / f"asset-{digest}{ext}"
2802
+ if not out_p.is_file():
2803
+ out_p.write_bytes(raw_bytes)
2804
+ return out_p
2805
+
2806
+ def _decode_data_uri(self, uri: str) -> Path | None:
2807
+ m = re.match(r"^data:([^;,]+)?(?:;charset=[^;,]+)?(;base64)?,(.*)$", uri, re.DOTALL | re.IGNORECASE)
2808
+ if not m:
2809
+ return None
2810
+ mime = (m.group(1) or "image/png").strip().lower()
2811
+ is_b64 = bool(m.group(2))
2812
+ payload = m.group(3) or ""
2813
+ try:
2814
+ raw = base64.b64decode(payload) if is_b64 else urllib.parse.unquote_to_bytes(payload)
2815
+ except Exception:
2816
+ return None
2817
+ if not raw:
2818
+ return None
2819
+ ext = ".png"
2820
+ if "jpeg" in mime or "jpg" in mime:
2821
+ ext = ".jpg"
2822
+ elif "webp" in mime:
2823
+ ext = ".webp"
2824
+ elif "gif" in mime:
2825
+ ext = ".gif"
2826
+ digest = hashlib.sha256(raw).hexdigest()[:16]
2827
+ out_p = self.tmp_dir / f"data-{digest}{ext}"
2828
+ if not out_p.is_file():
2829
+ out_p.write_bytes(raw)
2830
+ return out_p
2831
+
2832
+ def resolve_capture(self, capture_id: str) -> Path | None:
2833
+ if not capture_id:
2834
+ return None
2835
+ for cand in (capture_id, f"{capture_id}.png"):
2836
+ if cand in self._materialized:
2837
+ return self._materialized[cand]
2838
+ if cand in self.entries:
2839
+ p = self._materialize_value(cand, self.entries[cand])
2840
+ if p is not None:
2841
+ self._materialized[cand] = p
2842
+ return p
2843
+ for root in self.asset_dirs:
2844
+ boundary = self.allowed_root or root
2845
+ p = (root / cand).resolve()
2846
+ if _is_within_root(p, root) and _is_within_root(p, boundary) and p.is_file():
2847
+ self._materialized[cand] = p
2848
+ return p
2849
+ return None
2850
+
2851
+ def resolve(self, src: str | None) -> Path | None:
2852
+ if not src or not isinstance(src, str):
2853
+ return None
2854
+ s = src.strip()
2855
+ if not s or "\0" in s or s.startswith("blob:"):
2856
+ return None
2857
+ if s in self._materialized:
2858
+ return self._materialized[s]
2859
+ if s.startswith("data:"):
2860
+ p = self._decode_data_uri(s)
2861
+ if p is not None:
2862
+ self._materialized[s] = p
2863
+ return p
2864
+
2865
+ variants = _normalize_asset_key_variants(s)
2866
+ for v in variants:
2867
+ if v in self.entries:
2868
+ p = self._materialize_value(v, self.entries[v])
2869
+ if p is not None:
2870
+ self._materialized[s] = p
2871
+ return p
2872
+
2873
+ if self.serve_root is not None and self.port is not None:
2874
+ p = _resolve_local_img_path(s, self.serve_root, self.port, allowed_root=self.allowed_root)
2875
+ if p is not None:
2876
+ self._materialized[s] = p
2877
+ return p
2878
+
2879
+ parsed = urllib.parse.urlparse(s)
2880
+ if parsed.scheme in ("http", "https"):
2881
+ if self.port is not None:
2882
+ return None
2883
+ if parsed.hostname not in ("127.0.0.1", "localhost"):
2884
+ return None
2885
+ elif parsed.scheme:
2886
+ return None
2887
+ elif s.startswith("//"):
2888
+ return None
2889
+
2890
+ for root in self.asset_dirs:
2891
+ boundary = self.allowed_root or root
2892
+ for v in variants:
2893
+ if "://" in v or v.startswith("/"):
2894
+ continue
2895
+ parts = [pt for pt in v.replace("\\", "/").split("/") if pt]
2896
+ if not parts or any(pt in (".", "..") for pt in parts):
2897
+ continue
2898
+ cand_p = (root / Path(*parts)).resolve()
2899
+ if _is_within_root(cand_p, root) and _is_within_root(cand_p, boundary) and cand_p.is_file():
2900
+ self._materialized[s] = cand_p
2901
+ return cand_p
2902
+ return None
2903
+
2904
+
2905
+ def get_unfulfilled_capture_requests(
2906
+ manifest: dict[str, Any],
2907
+ assets: Any = None,
2908
+ *,
2909
+ allowed_root: Path | None = None,
2910
+ ) -> list[dict[str, Any]]:
2911
+ validate_slide_manifest(manifest)
2912
+ canvas = manifest["canvas"]
2913
+ canvas_w = float(canvas["width"])
2914
+ canvas_h = float(canvas["height"])
2915
+ unfulfilled: list[dict[str, Any]] = []
2916
+
2917
+ with tempfile.TemporaryDirectory(prefix="h2p-cap-check-") as tmp_str:
2918
+ resolver = _ManifestAssetResolver(assets, Path(tmp_str), allowed_root=allowed_root)
2919
+ for slide_data in manifest.get("slides") or []:
2920
+ s_idx = int(slide_data.get("slideIdx") or 1)
2921
+ has_picture_bg = False
2922
+ if slide_data.get("hasBackgroundImage"):
2923
+ single_url = _extract_single_bg_url(slide_data.get("backgroundImageCss"))
2924
+ local_bg_p = resolver.resolve(single_url) if single_url else None
2925
+ if local_bg_p is not None:
2926
+ has_picture_bg = True
2927
+ elif resolver.resolve_capture(f"s{s_idx}-bg") is not None:
2928
+ has_picture_bg = True
2929
+ else:
2930
+ unfulfilled.append(
2931
+ {
2932
+ "captureId": f"s{s_idx}-bg",
2933
+ "kind": "slide_bg",
2934
+ "slideIdx": s_idx,
2935
+ }
2936
+ )
2937
+
2938
+ fg_emitted = 0
2939
+ for item in slide_data.get("items") or []:
2940
+ kind = item.get("kind")
2941
+ cid = str(item.get("captureId") or "").strip()
2942
+ if kind in ("transformed_visual", "gradient_box", "svg"):
2943
+ if not cid or resolver.resolve_capture(cid) is None:
2944
+ unfulfilled.append(
2945
+ {
2946
+ "captureId": cid or f"s{s_idx}-{kind}",
2947
+ "kind": kind,
2948
+ "slideIdx": s_idx,
2949
+ }
2950
+ )
2951
+ fg_emitted += 1
2952
+ elif kind == "img":
2953
+ r = item.get("rect") or {}
2954
+ x, y, w, h = float(r.get("x", 0)), float(r.get("y", 0)), float(r.get("w", 0)), float(r.get("h", 0))
2955
+ is_full_bleed_bottom = (
2956
+ fg_emitted == 0
2957
+ and x <= 2.0
2958
+ and y <= 2.0
2959
+ and w >= canvas_w - 4.0
2960
+ and h >= canvas_h - 4.0
2961
+ )
2962
+ if is_full_bleed_bottom:
2963
+ img_opacity = float(item.get("opacity", 1.0))
2964
+ local_p = resolver.resolve(item.get("src", "")) if not item.get("needsCapture") else None
2965
+ can_direct_bg = (
2966
+ local_p is not None
2967
+ and img_opacity >= 0.99
2968
+ and (not has_picture_bg or not _image_has_transparency(local_p))
2969
+ )
2970
+ if can_direct_bg:
2971
+ has_picture_bg = True
2972
+ continue
2973
+ if not cid or (
2974
+ resolver.resolve_capture(f"{cid}-bg") is None
2975
+ and resolver.resolve_capture(cid) is None
2976
+ ):
2977
+ unfulfilled.append(
2978
+ {
2979
+ "captureId": cid or f"s{s_idx}-fullbleed-img",
2980
+ "kind": "slide_bg_with_bottom_img" if has_picture_bg else "img",
2981
+ "slideIdx": s_idx,
2982
+ }
2983
+ )
2984
+ has_picture_bg = True
2985
+ continue
2986
+
2987
+ if not item.get("needsCapture"):
2988
+ local_p = resolver.resolve(item.get("src", ""))
2989
+ if local_p is not None:
2990
+ fg_emitted += 1
2991
+ continue
2992
+ if not cid or resolver.resolve_capture(cid) is None:
2993
+ unfulfilled.append(
2994
+ {
2995
+ "captureId": cid or f"s{s_idx}-img",
2996
+ "kind": "img",
2997
+ "slideIdx": s_idx,
2998
+ }
2999
+ )
3000
+ fg_emitted += 1
3001
+ elif kind == "table":
3002
+ if int(item.get("nRows") or 0) >= 2 and int(item.get("nCols") or 0) >= 2:
3003
+ fg_emitted += 1
3004
+ else:
3005
+ fg_emitted += 1
3006
+ return unfulfilled
3007
+
3008
+
3009
+ def _build_slide_from_extracted(
3010
+ prs: Any,
3011
+ blank_layout: Any,
3012
+ s_idx: int,
3013
+ extracted: dict[str, Any],
3014
+ *,
3015
+ canvas_w: int,
3016
+ canvas_h: int,
3017
+ tmp_dir: Path,
3018
+ resolver: _ManifestAssetResolver,
3019
+ prev_morph_ids: set[str],
3020
+ page: Any = None,
3021
+ font_profile: str = "auto",
3022
+ wrap_mode: str = "reflow",
3023
+ ) -> tuple[dict[str, Any], set[str]]:
3024
+ slide = prs.slides.add_slide(blank_layout)
3025
+
3026
+ # 1. Slide background (solid fallback or locked native OOXML <p:bg><p:bgPr><a:blipFill>)
3027
+ bg_parsed = parse_css_color(extracted.get("backgroundColor"))
3028
+ if bg_parsed:
3029
+ set_slide_solid_bg(slide, bg_parsed[0])
3030
+ else:
3031
+ set_slide_solid_bg(slide, RGBColor(255, 255, 255))
3032
+
3033
+ has_picture_bg = False
3034
+ if extracted.get("hasBackgroundImage"):
3035
+ single_url = _extract_single_bg_url(extracted.get("backgroundImageCss"))
3036
+ local_bg_p = resolver.resolve(single_url) if single_url else None
3037
+ if local_bg_p is not None:
3038
+ set_slide_picture_bg(
3039
+ slide,
3040
+ _prepare_bg_cover_image(local_bg_p, tmp_dir, canvas_w, canvas_h),
3041
+ tmp_dir,
3042
+ )
3043
+ has_picture_bg = True
3044
+ else:
3045
+ bg_png = resolver.resolve_capture(f"s{s_idx}-bg")
3046
+ if bg_png is None and page is not None:
3047
+ cand_bg = tmp_dir / f"s{s_idx}-bg.png"
3048
+ page.evaluate(
3049
+ """(idx) => {
3050
+ const sl = document.querySelector(`.slide[data-slide="${idx}"]`) ||
3051
+ document.querySelector(`[data-slide="${idx}"]`) ||
3052
+ document.querySelector('.slide.is-active, .slide.active');
3053
+ if (!sl) return;
3054
+ sl.__h2pBgHidden = [];
3055
+ for (const ch of Array.from(sl.children)) {
3056
+ sl.__h2pBgHidden.push([ch, ch.style.visibility]);
3057
+ ch.style.visibility = 'hidden';
3058
+ }
3059
+ }""",
3060
+ s_idx,
3061
+ )
3062
+ try:
3063
+ page.screenshot(path=str(cand_bg), full_page=False, animations="disabled", timeout=15000)
3064
+ finally:
3065
+ page.evaluate(
3066
+ """(idx) => {
3067
+ const sl = document.querySelector(`.slide[data-slide="${idx}"]`) ||
3068
+ document.querySelector(`[data-slide="${idx}"]`) ||
3069
+ document.querySelector('.slide.is-active, .slide.active');
3070
+ if (!sl) return;
3071
+ for (const [ch, prev] of (sl.__h2pBgHidden || [])) {
3072
+ ch.style.visibility = prev;
3073
+ }
3074
+ delete sl.__h2pBgHidden;
3075
+ }""",
3076
+ s_idx,
3077
+ )
3078
+ if cand_bg.is_file():
3079
+ bg_png = cand_bg
3080
+ if bg_png is not None and bg_png.is_file():
3081
+ set_slide_picture_bg(slide, bg_png, tmp_dir)
3082
+ has_picture_bg = True
3083
+
3084
+ # 2. Emit all paint-ordered items and track native OOXML motion metadata
3085
+ counts = {
3086
+ "box": 0,
3087
+ "table": 0,
3088
+ "gradient_box": 0,
3089
+ "transformed": 0,
3090
+ "img": 0,
3091
+ "svg": 0,
3092
+ "text": 0,
3093
+ "picture_bg": 1 if has_picture_bg else 0,
3094
+ }
3095
+ fg_emitted = 0
3096
+ motion_preset = str(extracted.get("motionPreset") or "refined").strip().lower()
3097
+ if motion_preset not in _MOTION_DEFAULTS:
3098
+ motion_preset = "refined"
3099
+ preset_cfg = _MOTION_DEFAULTS[motion_preset]
3100
+
3101
+ curr_morph_ids: set[str] = set()
3102
+ used_morph_names: set[str] = set()
3103
+ morph_kind_counts: dict[tuple[str, str], int] = {}
3104
+ raw_anim_entries: list[dict[str, Any]] = []
3105
+ anim_seq = 0
3106
+
3107
+ def _register_item_motion(item_obj: dict[str, Any], created_shapes: list[Any]) -> None:
3108
+ nonlocal anim_seq
3109
+ if not created_shapes:
3110
+ return
3111
+ m = item_obj.get("motion")
3112
+ if not isinstance(m, dict):
3113
+ return
3114
+ mid = str(m.get("morphId") or "").strip()
3115
+ item_kind = str(item_obj.get("kind") or "shape")
3116
+ if mid:
3117
+ curr_morph_ids.add(mid)
3118
+ for sh_idx, sh in enumerate(created_shapes):
3119
+ primary_name = f"!!{mid}"
3120
+ if sh_idx == 0 and primary_name not in used_morph_names and (
3121
+ m.get("morphOwn")
3122
+ or item_kind in ("box", "img", "svg", "gradient_box", "transformed_visual", "table")
3123
+ ):
3124
+ chosen_name = primary_name
3125
+ elif sh_idx == 0 and primary_name not in used_morph_names:
3126
+ chosen_name = primary_name
3127
+ else:
3128
+ ck = (mid, item_kind)
3129
+ morph_kind_counts[ck] = morph_kind_counts.get(ck, 0) + 1
3130
+ chosen_name = f"!!{mid}__{item_kind}_{morph_kind_counts[ck]}"
3131
+ used_morph_names.add(chosen_name)
3132
+ try:
3133
+ sh.name = chosen_name
3134
+ except Exception:
3135
+ pass
3136
+
3137
+ anim_kind = str(m.get("anim") or "").strip().lower()
3138
+ if anim_kind and anim_kind != "none" and not m.get("isHeader"):
3139
+ for sh in created_shapes:
3140
+ anim_seq += 1
3141
+ raw_anim_entries.append(
3142
+ {
3143
+ "spid": int(sh.shape_id),
3144
+ "anim": anim_kind,
3145
+ "order": int(m.get("animOrder") or 1),
3146
+ "delay_ms": m.get("animDelay"),
3147
+ "dur_ms": m.get("animDur"),
3148
+ "trigger": str(m.get("animTrigger") or "auto"),
3149
+ "morph_id": mid,
3150
+ "seq": anim_seq,
3151
+ }
3152
+ )
3153
+
3154
+ for item in extracted.get("items") or []:
3155
+ kind = item.get("kind")
3156
+ before_n = len(slide.shapes)
3157
+ if kind == "box":
3158
+ _emit_box_item(slide, item)
3159
+ counts["box"] += 1
3160
+ fg_emitted += 1
3161
+ elif kind == "table":
3162
+ if _emit_table_item(slide, item, font_profile=font_profile) is not None:
3163
+ counts["table"] += 1
3164
+ fg_emitted += 1
3165
+ elif kind == "transformed_visual":
3166
+ r = item["rect"]
3167
+ cid = str(item.get("captureId") or "")
3168
+ out_png = resolver.resolve_capture(cid)
3169
+ if out_png is None and page is not None and cid:
3170
+ cand_png = tmp_dir / f"{cid}.png"
3171
+ if _capture_element_png(
3172
+ page,
3173
+ s_idx,
3174
+ cid,
3175
+ cand_png,
3176
+ hide_children=bool(item.get("hideChildren")),
3177
+ clip_rect=r if item.get("captureClip") else None,
3178
+ canvas_w=canvas_w,
3179
+ canvas_h=canvas_h,
3180
+ ):
3181
+ out_png = cand_png
3182
+ if out_png is not None and out_png.is_file():
3183
+ cx = max(0.0, float(r["x"]))
3184
+ cy = max(0.0, float(r["y"]))
3185
+ cw = min(float(canvas_w), float(r["x"]) + float(r["w"])) - cx
3186
+ ch = min(float(canvas_h), float(r["y"]) + float(r["h"])) - cy
3187
+ if cw > 0.5 and ch > 0.5:
3188
+ _add_picture_fit(slide, out_png, cx, cy, cw, ch, tmp_dir=tmp_dir)
3189
+ counts["transformed"] += 1
3190
+ fg_emitted += 1
3191
+ elif kind == "gradient_box":
3192
+ r = item["rect"]
3193
+ cid = str(item.get("captureId") or "")
3194
+ out_png = resolver.resolve_capture(cid)
3195
+ if out_png is None and page is not None and cid:
3196
+ cand_png = tmp_dir / f"{cid}.png"
3197
+ if _capture_element_png(page, s_idx, cid, cand_png, hide_children=bool(item.get("hasChildren"))):
3198
+ out_png = cand_png
3199
+ if out_png is not None and out_png.is_file():
3200
+ cx = max(0.0, float(r["x"]))
3201
+ cy = max(0.0, float(r["y"]))
3202
+ cw = min(float(canvas_w), float(r["x"]) + float(r["w"])) - cx
3203
+ ch = min(float(canvas_h), float(r["y"]) + float(r["h"])) - cy
3204
+ _add_picture_fit(slide, out_png, cx, cy, cw, ch, tmp_dir=tmp_dir)
3205
+ counts["gradient_box"] += 1
3206
+ fg_emitted += 1
3207
+ elif kind == "svg":
3208
+ r = item["rect"]
3209
+ cid = str(item.get("captureId") or "")
3210
+ out_png = resolver.resolve_capture(cid)
3211
+ if out_png is None and page is not None and cid:
3212
+ cand_png = tmp_dir / f"{cid}.png"
3213
+ if _capture_element_png(page, s_idx, cid, cand_png, hide_children=False):
3214
+ out_png = cand_png
3215
+ if out_png is not None and out_png.is_file():
3216
+ _add_picture_fit(
3217
+ slide,
3218
+ out_png,
3219
+ float(r["x"]),
3220
+ float(r["y"]),
3221
+ float(r["w"]),
3222
+ float(r["h"]),
3223
+ tmp_dir=tmp_dir,
3224
+ )
3225
+ counts["svg"] += 1
3226
+ fg_emitted += 1
3227
+ elif kind == "img":
3228
+ r = item["rect"]
3229
+ x, y, w, h = float(r["x"]), float(r["y"]), float(r["w"]), float(r["h"])
3230
+ is_full_bleed_bottom = (
3231
+ fg_emitted == 0
3232
+ and x <= 2.0
3233
+ and y <= 2.0
3234
+ and w >= canvas_w - 4.0
3235
+ and h >= canvas_h - 4.0
3236
+ )
3237
+ if is_full_bleed_bottom:
3238
+ img_opacity = float(item.get("opacity", 1.0))
3239
+ local_p = resolver.resolve(item.get("src", "")) if not item.get("needsCapture") else None
3240
+ can_direct_bg = (
3241
+ local_p is not None
3242
+ and img_opacity >= 0.99
3243
+ and (not has_picture_bg or not _image_has_transparency(local_p))
3244
+ )
3245
+ if can_direct_bg and local_p is not None:
3246
+ set_slide_picture_bg(
3247
+ slide,
3248
+ _prepare_bg_cover_image(local_p, tmp_dir, canvas_w, canvas_h),
3249
+ tmp_dir,
3250
+ )
3251
+ if not has_picture_bg:
3252
+ counts["picture_bg"] += 1
3253
+ has_picture_bg = True
3254
+ continue
3255
+ cid = str(item.get("captureId") or "")
3256
+ if cid:
3257
+ out_png = resolver.resolve_capture(f"{cid}-bg") or resolver.resolve_capture(cid)
3258
+ if out_png is None and page is not None:
3259
+ cand_png = tmp_dir / f"{cid}-bg.png"
3260
+ captured = (
3261
+ _capture_slide_bg_with_bottom_img(page, s_idx, cid, cand_png)
3262
+ if has_picture_bg
3263
+ else _capture_element_png(page, s_idx, cid, cand_png, hide_children=False)
3264
+ )
3265
+ if captured:
3266
+ out_png = cand_png
3267
+ if out_png is not None and out_png.is_file():
3268
+ set_slide_picture_bg(slide, out_png, tmp_dir)
3269
+ if not has_picture_bg:
3270
+ counts["picture_bg"] += 1
3271
+ has_picture_bg = True
3272
+ continue
3273
+
3274
+ if not item.get("needsCapture"):
3275
+ local_p = resolver.resolve(item.get("src", ""))
3276
+ if local_p is not None:
3277
+ _emit_direct_picture_with_borders(slide, local_p, item, x, y, w, h, tmp_dir=tmp_dir)
3278
+ counts["img"] += 1
3279
+ fg_emitted += 1
3280
+ _register_item_motion(item, list(slide.shapes)[before_n:])
3281
+ continue
3282
+ cid = str(item.get("captureId") or "")
3283
+ if cid:
3284
+ out_png = resolver.resolve_capture(cid)
3285
+ if out_png is None and page is not None:
3286
+ cand_png = tmp_dir / f"{cid}.png"
3287
+ if _capture_element_png(page, s_idx, cid, cand_png, hide_children=False):
3288
+ out_png = cand_png
3289
+ if out_png is not None and out_png.is_file():
3290
+ cx = max(0.0, x)
3291
+ cy = max(0.0, y)
3292
+ cw = min(float(canvas_w), x + w) - cx
3293
+ ch = min(float(canvas_h), y + h) - cy
3294
+ if cw > 1 and ch > 1:
3295
+ _add_picture_fit(slide, out_png, cx, cy, cw, ch, tmp_dir=tmp_dir)
3296
+ counts["img"] += 1
3297
+ fg_emitted += 1
3298
+ elif kind == "text":
3299
+ add_native_textbox(
3300
+ slide,
3301
+ item,
3302
+ canvas_w=float(canvas_w),
3303
+ font_profile=font_profile,
3304
+ wrap_mode=wrap_mode,
3305
+ )
3306
+ counts["text"] += 1
3307
+ fg_emitted += 1
3308
+
3309
+ created_now = list(slide.shapes)[before_n:]
3310
+ _register_item_motion(item, created_now)
3311
+
3312
+ # 3. Apply native OOXML slide transition (including p159:morph) & entrance <p:timing>
3313
+ matched_morph_ids = curr_morph_ids & prev_morph_ids
3314
+ raw_trans = str(extracted.get("transition") or "auto").strip().lower()
3315
+ custom_dur = extracted.get("transitionDur")
3316
+ applied_transition = "none"
3317
+ if motion_preset != "none" and raw_trans != "none":
3318
+ if s_idx == 1:
3319
+ if raw_trans in ("fade", "push"):
3320
+ t_dur = int(custom_dur) if custom_dur is not None else preset_cfg[raw_trans]
3321
+ applied_transition = _apply_slide_transition(slide, raw_trans, t_dur)
3322
+ else:
3323
+ if raw_trans == "morph" or (raw_trans == "auto" and bool(matched_morph_ids)):
3324
+ if matched_morph_ids or raw_trans == "morph":
3325
+ t_dur = int(custom_dur) if custom_dur is not None else preset_cfg["morph"]
3326
+ applied_transition = _apply_slide_transition(slide, "morph", t_dur)
3327
+ elif raw_trans == "push":
3328
+ t_dur = int(custom_dur) if custom_dur is not None else preset_cfg["push"]
3329
+ applied_transition = _apply_slide_transition(slide, "push", t_dur)
3330
+ else:
3331
+ t_dur = int(custom_dur) if custom_dur is not None else preset_cfg["fade"]
3332
+ applied_transition = _apply_slide_transition(slide, "fade", t_dur)
3333
+
3334
+ effective_anim_entries = [
3335
+ e
3336
+ for e in raw_anim_entries
3337
+ if not (applied_transition == "morph" and e.get("morph_id") and e["morph_id"] in matched_morph_ids)
3338
+ ]
3339
+ animated_count = (
3340
+ _apply_slide_timing(slide, effective_anim_entries, preset_cfg)
3341
+ if motion_preset != "none"
3342
+ else 0
3343
+ )
3344
+
3345
+ dropped_images = extracted.get("droppedImages") or []
3346
+ stats = {
3347
+ "slide": s_idx,
3348
+ "emitted": counts,
3349
+ "dropped_images": dropped_images,
3350
+ "transition": applied_transition,
3351
+ "morph_matched": sorted(matched_morph_ids),
3352
+ "animated_shapes": animated_count,
3353
+ }
3354
+ return stats, curr_morph_ids
3355
+
3356
+
3357
+ _EP_NS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties"
3358
+ _GENERIC_TITLES = {"", "presentation", "document", "slide deck", "untitled", "index"}
3359
+
3360
+
3361
+ def _is_valid_xml10_char(ch: str) -> bool:
3362
+ cp = ord(ch)
3363
+ return (
3364
+ cp in (0x9, 0xA, 0xD)
3365
+ or (0x20 <= cp <= 0xD7FF)
3366
+ or (0xE000 <= cp <= 0xFFFD)
3367
+ or (0x10000 <= cp <= 0x10FFFF)
3368
+ )
3369
+
3370
+
3371
+ def _strip_xml_control_chars(text: str) -> str:
3372
+ return "".join(ch for ch in text if _is_valid_xml10_char(ch))
3373
+
3374
+
3375
+ def _resolve_deck_title(prs: Any, explicit_title: str | None = None, fallback_stem: str = "") -> str:
3376
+ """Resolve a clean presentation title from HTML <title>, slide 1 largest text, or filename stem."""
3377
+ cleaned = re.sub(r"\s+", " ", _strip_xml_control_chars(str(explicit_title or ""))).strip()
3378
+ if cleaned and cleaned.lower() not in _GENERIC_TITLES:
3379
+ return cleaned[:120]
3380
+ if len(prs.slides) > 0:
3381
+ best_pt = -1.0
3382
+ best_text = ""
3383
+ for shape in prs.slides[0].shapes:
3384
+ if not shape.has_text_frame:
3385
+ continue
3386
+ txt = re.sub(r"\s+", " ", _strip_xml_control_chars(shape.text_frame.text or "")).strip()
3387
+ if not txt:
3388
+ continue
3389
+ max_pt = 0.0
3390
+ for para in shape.text_frame.paragraphs:
3391
+ if para.font and para.font.size:
3392
+ max_pt = max(max_pt, float(para.font.size.pt))
3393
+ for run in para.runs:
3394
+ if run.font and run.font.size:
3395
+ max_pt = max(max_pt, float(run.font.size.pt))
3396
+ if max_pt > best_pt:
3397
+ best_pt = max_pt
3398
+ best_text = txt
3399
+ if best_text:
3400
+ return best_text[:120]
3401
+ stem = re.sub(r"[-_]+", " ", _strip_xml_control_chars(str(fallback_stem or ""))).strip()
3402
+ return (stem or "Presentation")[:120]
3403
+
3404
+
3405
+ def _sanitize_pptx_doc_props(
3406
+ prs: Any,
3407
+ *,
3408
+ title: str | None = None,
3409
+ canvas_w: int = int(CANVAS_W_PX),
3410
+ canvas_h: int = int(CANVAS_H_PX),
3411
+ fallback_stem: str = "",
3412
+ ) -> None:
3413
+ """Replace stock python-pptx docProps/core.xml and docProps/app.xml defaults with clean, accurate metadata."""
3414
+ resolved_title = _resolve_deck_title(prs, explicit_title=title, fallback_stem=fallback_stem)
3415
+ now_utc = datetime.now(timezone.utc)
3416
+
3417
+ cp = prs.core_properties
3418
+ cp.title = resolved_title
3419
+ cp.author = "Oil Slide"
3420
+ cp.last_modified_by = "Oil Slide"
3421
+ cp.comments = ""
3422
+ cp.created = now_utc
3423
+ cp.modified = now_utc
3424
+ cp.revision = 1
3425
+
3426
+ total_slides = len(prs.slides)
3427
+ total_paragraphs = 0
3428
+ total_words = 0
3429
+ for slide in prs.slides:
3430
+ for shape in slide.shapes:
3431
+ tfs: list[Any] = []
3432
+ if shape.has_table:
3433
+ for row in shape.table.rows:
3434
+ for cell in row.cells:
3435
+ tfs.append(cell.text_frame)
3436
+ elif shape.has_text_frame:
3437
+ tfs.append(shape.text_frame)
3438
+ for tf in tfs:
3439
+ for para in tf.paragraphs:
3440
+ txt = (para.text or "").strip()
3441
+ if txt:
3442
+ total_paragraphs += 1
3443
+ total_words += len(re.findall(r"[A-Za-z0-9_]+|[\u3400-\u9fff]", txt))
3444
+
3445
+ ratio = float(canvas_w) / max(1.0, float(canvas_h))
3446
+ pres_fmt = "On-screen Show (16:9)" if abs(ratio - (16.0 / 9.0)) < 0.02 else "Custom"
3447
+
3448
+ for part in prs.part.package.iter_parts():
3449
+ if str(getattr(part, "partname", "")).lower() != "/docprops/app.xml":
3450
+ continue
3451
+ try:
3452
+ root = etree.fromstring(part.blob)
3453
+ updates = {
3454
+ "Application": "Oil Slide",
3455
+ "PresentationFormat": pres_fmt,
3456
+ "Slides": str(total_slides),
3457
+ "Paragraphs": str(total_paragraphs),
3458
+ "Words": str(total_words),
3459
+ "TotalTime": "0",
3460
+ }
3461
+ for tag, val in updates.items():
3462
+ el = root.find(f"{{{_EP_NS}}}{tag}")
3463
+ if el is None:
3464
+ el = etree.SubElement(root, f"{{{_EP_NS}}}{tag}")
3465
+ el.text = val
3466
+ for stale_tag in ("HeadingPairs", "TitlesOfParts"):
3467
+ stale_el = root.find(f"{{{_EP_NS}}}{stale_tag}")
3468
+ if stale_el is not None:
3469
+ root.remove(stale_el)
3470
+ part._blob = etree.tostring(root, xml_declaration=True, encoding="UTF-8", standalone=True)
3471
+ except Exception:
3472
+ pass
3473
+ break
3474
+
3475
+
3476
+ def build_pptx_from_manifest(
3477
+ manifest: dict[str, Any],
3478
+ assets: Any,
3479
+ out_path: Path | str,
3480
+ *,
3481
+ do_audit: bool = True,
3482
+ allowed_root: Path | None = None,
3483
+ serve_root: Path | None = None,
3484
+ port: int | None = None,
3485
+ font_profile: str = "auto",
3486
+ wrap_mode: str = "reflow",
3487
+ ) -> dict[str, Any]:
3488
+ """Build a native editable PPTX directly from a versioned slide manifest with zero Playwright/Chromium."""
3489
+ validate_slide_manifest(manifest)
3490
+
3491
+ out_abs = Path(out_path).resolve()
3492
+ out_abs.parent.mkdir(parents=True, exist_ok=True)
3493
+
3494
+ canvas = manifest["canvas"]
3495
+ canvas_w = int(round(float(canvas["width"])))
3496
+ canvas_h = int(round(float(canvas["height"])))
3497
+ slide_w_emu = round(canvas_w * EMU_PER_PX)
3498
+ slide_h_emu = round(canvas_h * EMU_PER_PX)
3499
+
3500
+ prs = Presentation()
3501
+ prs.slide_width = slide_w_emu
3502
+ prs.slide_height = slide_h_emu
3503
+ sld_sz = getattr(prs._element, "sldSz", None)
3504
+ if sld_sz is not None:
3505
+ sld_sz.set("type", "screen16x9" if (canvas_w == 1920 and canvas_h == 1080) else "custom")
3506
+ blank_layout = prs.slide_layouts[6]
3507
+
3508
+ per_slide_stats: list[dict[str, Any]] = []
3509
+ prev_morph_ids: set[str] = set()
3510
+
3511
+ with tempfile.TemporaryDirectory(prefix="manifest2pptx-") as tmp_str:
3512
+ tmp_dir = Path(tmp_str)
3513
+ resolver = _ManifestAssetResolver(
3514
+ assets,
3515
+ tmp_dir,
3516
+ serve_root=serve_root,
3517
+ port=port,
3518
+ allowed_root=allowed_root,
3519
+ )
3520
+ for idx, slide_data in enumerate(manifest["slides"], start=1):
3521
+ s_idx = int(slide_data.get("slideIdx") or idx)
3522
+ stats, prev_morph_ids = _build_slide_from_extracted(
3523
+ prs,
3524
+ blank_layout,
3525
+ s_idx,
3526
+ slide_data,
3527
+ canvas_w=canvas_w,
3528
+ canvas_h=canvas_h,
3529
+ tmp_dir=tmp_dir,
3530
+ resolver=resolver,
3531
+ prev_morph_ids=prev_morph_ids,
3532
+ page=None,
3533
+ font_profile=font_profile,
3534
+ wrap_mode=wrap_mode,
3535
+ )
3536
+ per_slide_stats.append(stats)
3537
+
3538
+ _sanitize_pptx_doc_props(
3539
+ prs,
3540
+ title=str(manifest.get("title") or "").strip() or None,
3541
+ canvas_w=canvas_w,
3542
+ canvas_h=canvas_h,
3543
+ fallback_stem=out_abs.stem,
3544
+ )
3545
+ prs.save(str(out_abs))
3546
+ result: dict[str, Any] = {
3547
+ "ok": True,
3548
+ "out": str(out_abs),
3549
+ "bytes": out_abs.stat().st_size,
3550
+ "canvas": {"width": canvas_w, "height": canvas_h},
3551
+ "slide_count": len(per_slide_stats),
3552
+ "compiled_slides": per_slide_stats,
3553
+ }
3554
+ if do_audit:
3555
+ audit = audit_compiled_pptx(
3556
+ out_abs,
3557
+ expected_slides=len(per_slide_stats),
3558
+ expected_w_emu=slide_w_emu,
3559
+ expected_h_emu=slide_h_emu,
3560
+ )
3561
+ for st in per_slide_stats:
3562
+ dropped = st.get("dropped_images") or []
3563
+ if dropped:
3564
+ srcs = [str(d.get("src") or "<empty>") for d in dropped[:4]]
3565
+ audit["issues"].append(
3566
+ f"Slide {st['slide']}: dropped {len(dropped)} unloaded <img> element(s) during PPTX export ({srcs!r})"
3567
+ )
3568
+ if audit["issues"]:
3569
+ audit["ok"] = False
3570
+ result["audit"] = audit
3571
+ result["ok"] = bool(audit.get("ok"))
3572
+ return result
3573
+
3574
+
3575
+ _BLOCKED_EXTERNAL_FONT_HOSTS = (
3576
+ "fonts.googleapis.com",
3577
+ "fonts.gstatic.com",
3578
+ "use.typekit.net",
3579
+ "p.typekit.net",
3580
+ "fonts.bunny.net",
3581
+ "fast.fonts.net",
3582
+ "fonts.loli.net",
3583
+ "fonts.font.im",
3584
+ "fonts.cat.net",
3585
+ )
3586
+
3587
+
3588
+ def _attach_external_font_guard(context: Any) -> None:
3589
+ """Abort slow/blocked external webfont requests during local Chromium capture."""
3590
+ def _block_ext_fonts(route: Any) -> None:
3591
+ req = route.request
3592
+ req_url = str(getattr(req, "url", "") or "").lower()
3593
+ is_local = req_url.startswith(
3594
+ ("http://127.0.0.1", "http://localhost", "data:", "blob:", "file:")
3595
+ )
3596
+ res_type = str(getattr(req, "resource_type", "") or "").lower()
3597
+ if not is_local and (
3598
+ res_type == "font"
3599
+ or any(h in req_url for h in _BLOCKED_EXTERNAL_FONT_HOSTS)
3600
+ ):
3601
+ route.abort("blockedbyclient")
3602
+ return
3603
+ route.continue_()
3604
+
3605
+ try:
3606
+ context.route("**/*", _block_ext_fonts)
3607
+ except Exception:
3608
+ pass
3609
+
3610
+
3611
+ _WAIT_FOR_SLIDE_READY_JS = """async (slideIdx) => {
3612
+ if (document.fonts && document.fonts.ready) {
3613
+ await Promise.race([document.fonts.ready, new Promise(r => setTimeout(r, 2500))]);
3614
+ }
3615
+ const activeSlide =
3616
+ document.querySelector(`.slide[data-slide="${slideIdx}"]`) ||
3617
+ document.querySelector(`[data-slide="${slideIdx}"]`) ||
3618
+ document.querySelector('.slide.is-active, .slide.active');
3619
+ const slideImgs = activeSlide ? Array.from(activeSlide.querySelectorAll('img')) : [];
3620
+ const docImgs = Array.from(document.images || []);
3621
+ const allImgs = Array.from(new Set([...slideImgs, ...docImgs]));
3622
+ await Promise.all(allImgs.map(async (img) => {
3623
+ try {
3624
+ if (img.loading === 'lazy' || img.getAttribute('loading') === 'lazy') {
3625
+ img.loading = 'eager';
3626
+ img.setAttribute('loading', 'eager');
3627
+ }
3628
+ img.decoding = 'sync';
3629
+ const rawSrc = img.getAttribute('src') || '';
3630
+ if (img.complete && img.naturalWidth === 0 && rawSrc) {
3631
+ img.src = img.currentSrc || rawSrc;
3632
+ }
3633
+ if (!img.complete || img.naturalWidth === 0) {
3634
+ await new Promise((res) => {
3635
+ const done = () => res();
3636
+ img.addEventListener('load', done, { once: true });
3637
+ img.addEventListener('error', done, { once: true });
3638
+ setTimeout(done, 6000);
3639
+ });
3640
+ }
3641
+ if (img.complete && img.naturalWidth > 0 && typeof img.decode === 'function') {
3642
+ await Promise.race([img.decode().catch(() => {}), new Promise(r => setTimeout(r, 3000))]);
3643
+ }
3644
+ } catch (_) {}
3645
+ }));
3646
+ await Promise.race([
3647
+ new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r))),
3648
+ new Promise(r => setTimeout(r, 500)),
3649
+ ]);
3650
+ if (typeof document.getAnimations === 'function') {
3651
+ for (const anim of document.getAnimations()) {
3652
+ try { anim.finish(); } catch (_) {}
3653
+ }
3654
+ }
3655
+ }"""
3656
+
3657
+
3658
+ def extract_manifest_from_html(
3659
+ html_path: Path,
3660
+ *,
3661
+ allowed_root: Path | None = None,
3662
+ block_external_network: bool = False,
3663
+ ratio: str | None = None,
3664
+ width: int | None = None,
3665
+ height: int | None = None,
3666
+ ) -> dict[str, Any]:
3667
+ """Extract a versioned slide manifest from an HTML deck using headless Chromium."""
3668
+ from playwright.sync_api import sync_playwright
3669
+
3670
+ html_abs = html_path.resolve()
3671
+ if not html_abs.is_file():
3672
+ raise FileNotFoundError(f"HTML file not found: {html_abs}")
3673
+
3674
+ serve_root, rel_url = _infer_serve_root(html_abs)
3675
+ boundary_root = allowed_root.resolve() if allowed_root is not None else serve_root.resolve()
3676
+ if not _is_within_root(html_abs, boundary_root):
3677
+ raise ValueError(f"HTML file escapes allowed_root: {html_abs}")
3678
+ if not _is_within_root(serve_root, boundary_root):
3679
+ serve_root = boundary_root
3680
+ rel_url = html_abs.relative_to(serve_root).as_posix()
3681
+
3682
+ canvas_w, canvas_h = _detect_html_canvas_size(html_abs, width=width, height=height, ratio=ratio)
3683
+ server, port = _start_static_server(serve_root)
3684
+ slides_out: list[dict[str, Any]] = []
3685
+
3686
+ try:
3687
+ with sync_playwright() as p:
3688
+ disable_sandbox = (os.environ.get("OIL_CHROMIUM_NO_SANDBOX") or "").strip().lower() == "true"
3689
+ chrome_args = ["--disable-gpu-sandbox", "--disable-dev-shm-usage", "--headless=new", "--hide-scrollbars"]
3690
+ browser = _launch_chromium(
3691
+ p,
3692
+ headless=True,
3693
+ chromium_sandbox=not disable_sandbox,
3694
+ args=chrome_args,
3695
+ executable_path=None,
3696
+ discover_system=True,
3697
+ )
3698
+ context_kwargs: dict[str, Any] = {
3699
+ "viewport": {"width": canvas_w, "height": canvas_h},
3700
+ "device_scale_factor": 2,
3701
+ "reduced_motion": "reduce",
3702
+ }
3703
+ if block_external_network:
3704
+ context_kwargs["service_workers"] = "block"
3705
+ context = browser.new_context(**context_kwargs)
3706
+ if block_external_network:
3707
+ local_origin = f"http://127.0.0.1:{port}/"
3708
+
3709
+ def _restrict_route(route: Any) -> None:
3710
+ req_url = str(route.request.url or "")
3711
+ if (
3712
+ req_url.startswith(local_origin)
3713
+ or req_url.startswith("data:")
3714
+ or req_url.startswith("blob:")
3715
+ ):
3716
+ route.continue_()
3717
+ else:
3718
+ route.abort()
3719
+
3720
+ context.route("**/*", _restrict_route)
3721
+ if hasattr(context, "route_web_socket"):
3722
+ context.route_web_socket("**/*", lambda ws: ws.close())
3723
+ else:
3724
+ _attach_external_font_guard(context)
3725
+ page = context.new_page()
3726
+
3727
+ base_url = f"http://127.0.0.1:{port}/{rel_url}"
3728
+ page.goto(f"{base_url}?slide=1", wait_until="domcontentloaded", timeout=20000)
3729
+ doc_title = (page.title() or "").strip()
3730
+ slide_count = int(
3731
+ page.evaluate(
3732
+ """() => {
3733
+ const byData = document.querySelectorAll('.slide[data-slide], section[data-slide]');
3734
+ if (byData.length > 0) return byData.length;
3735
+ const byClass = document.querySelectorAll('section.slide, .slide');
3736
+ return byClass.length || 1;
3737
+ }"""
3738
+ )
3739
+ )
3740
+
3741
+ for s_idx in range(1, slide_count + 1):
3742
+ if s_idx > 1:
3743
+ page.goto(f"{base_url}?slide={s_idx}", wait_until="domcontentloaded", timeout=20000)
3744
+ page.evaluate(_WAIT_FOR_SLIDE_READY_JS, s_idx)
3745
+ page.wait_for_timeout(150)
3746
+ extracted = page.evaluate(_get_extract_slide_dom_js(), [s_idx, canvas_w, canvas_h])
3747
+ slides_out.append(extracted)
3748
+
3749
+ context.close()
3750
+ browser.close()
3751
+ finally:
3752
+ server.shutdown()
3753
+ server.server_close()
3754
+
3755
+ manifest_out: dict[str, Any] = {
3756
+ "manifest_version": MANIFEST_VERSION,
3757
+ "canvas": {"width": canvas_w, "height": canvas_h},
3758
+ "slides": slides_out,
3759
+ }
3760
+ if doc_title:
3761
+ manifest_out["title"] = doc_title
3762
+ return manifest_out
3763
+
3764
+
3765
+ def compile_html_to_pptx(
3766
+ html_path: Path,
3767
+ out_path: Path,
3768
+ *,
3769
+ do_audit: bool = True,
3770
+ allowed_root: Path | None = None,
3771
+ block_external_network: bool = False,
3772
+ ratio: str | None = None,
3773
+ width: int | None = None,
3774
+ height: int | None = None,
3775
+ font_profile: str = "auto",
3776
+ wrap_mode: str = "reflow",
3777
+ ) -> dict[str, Any]:
3778
+ from playwright.sync_api import sync_playwright
3779
+
3780
+ html_abs = html_path.resolve()
3781
+ if not html_abs.is_file():
3782
+ raise FileNotFoundError(f"HTML file not found: {html_abs}")
3783
+
3784
+ out_abs = out_path.resolve()
3785
+ out_abs.parent.mkdir(parents=True, exist_ok=True)
3786
+ serve_root, rel_url = _infer_serve_root(html_abs)
3787
+ boundary_root = allowed_root.resolve() if allowed_root is not None else serve_root.resolve()
3788
+ if not _is_within_root(html_abs, boundary_root):
3789
+ raise ValueError(f"HTML file escapes allowed_root: {html_abs}")
3790
+ if not _is_within_root(serve_root, boundary_root):
3791
+ serve_root = boundary_root
3792
+ rel_url = html_abs.relative_to(serve_root).as_posix()
3793
+
3794
+ canvas_w, canvas_h = _detect_html_canvas_size(html_abs, width=width, height=height, ratio=ratio)
3795
+ slide_w_emu = round(canvas_w * EMU_PER_PX)
3796
+ slide_h_emu = round(canvas_h * EMU_PER_PX)
3797
+
3798
+ prs = Presentation()
3799
+ prs.slide_width = slide_w_emu
3800
+ prs.slide_height = slide_h_emu
3801
+ sld_sz = getattr(prs._element, "sldSz", None)
3802
+ if sld_sz is not None:
3803
+ sld_sz.set("type", "screen16x9" if (canvas_w == 1920 and canvas_h == 1080) else "custom")
3804
+ blank_layout = prs.slide_layouts[6]
3805
+
3806
+ server, port = _start_static_server(serve_root)
3807
+ per_slide_stats: list[dict[str, Any]] = []
3808
+
3809
+ try:
3810
+ with tempfile.TemporaryDirectory(prefix="html2pptx-") as tmp_str:
3811
+ tmp_dir = Path(tmp_str)
3812
+ resolver = _ManifestAssetResolver(
3813
+ None,
3814
+ tmp_dir,
3815
+ serve_root=serve_root,
3816
+ port=port,
3817
+ allowed_root=boundary_root,
3818
+ )
3819
+ with sync_playwright() as p:
3820
+ disable_sandbox = (os.environ.get("OIL_CHROMIUM_NO_SANDBOX") or "").strip().lower() == "true"
3821
+ chrome_args = ["--disable-gpu-sandbox", "--disable-dev-shm-usage", "--headless=new", "--hide-scrollbars"]
3822
+ browser = _launch_chromium(
3823
+ p,
3824
+ headless=True,
3825
+ chromium_sandbox=not disable_sandbox,
3826
+ args=chrome_args,
3827
+ executable_path=None,
3828
+ discover_system=True,
3829
+ )
3830
+ context_kwargs: dict[str, Any] = {
3831
+ "viewport": {"width": canvas_w, "height": canvas_h},
3832
+ "device_scale_factor": 2,
3833
+ "reduced_motion": "reduce",
3834
+ }
3835
+ if block_external_network:
3836
+ context_kwargs["service_workers"] = "block"
3837
+ context = browser.new_context(**context_kwargs)
3838
+ if block_external_network:
3839
+ local_origin = f"http://127.0.0.1:{port}/"
3840
+
3841
+ def _restrict_route(route: Any) -> None:
3842
+ req_url = str(route.request.url or "")
3843
+ if (
3844
+ req_url.startswith(local_origin)
3845
+ or req_url.startswith("data:")
3846
+ or req_url.startswith("blob:")
3847
+ ):
3848
+ route.continue_()
3849
+ else:
3850
+ route.abort()
3851
+
3852
+ context.route("**/*", _restrict_route)
3853
+ if hasattr(context, "route_web_socket"):
3854
+ context.route_web_socket("**/*", lambda ws: ws.close())
3855
+ else:
3856
+ _attach_external_font_guard(context)
3857
+ page = context.new_page()
3858
+
3859
+ base_url = f"http://127.0.0.1:{port}/{rel_url}"
3860
+ page.goto(f"{base_url}?slide=1", wait_until="domcontentloaded", timeout=20000)
3861
+ doc_title = (page.title() or "").strip()
3862
+ slide_count = int(
3863
+ page.evaluate(
3864
+ """() => {
3865
+ const byData = document.querySelectorAll('.slide[data-slide], section[data-slide]');
3866
+ if (byData.length > 0) return byData.length;
3867
+ const byClass = document.querySelectorAll('section.slide, .slide');
3868
+ return byClass.length || 1;
3869
+ }"""
3870
+ )
3871
+ )
3872
+
3873
+ prev_morph_ids: set[str] = set()
3874
+
3875
+ for s_idx in range(1, slide_count + 1):
3876
+ if s_idx > 1:
3877
+ page.goto(f"{base_url}?slide={s_idx}", wait_until="domcontentloaded", timeout=20000)
3878
+ page.evaluate(_WAIT_FOR_SLIDE_READY_JS, s_idx)
3879
+ page.wait_for_timeout(150)
3880
+
3881
+ extracted = page.evaluate(_get_extract_slide_dom_js(), [s_idx, canvas_w, canvas_h])
3882
+ stats, prev_morph_ids = _build_slide_from_extracted(
3883
+ prs,
3884
+ blank_layout,
3885
+ s_idx,
3886
+ extracted,
3887
+ canvas_w=canvas_w,
3888
+ canvas_h=canvas_h,
3889
+ tmp_dir=tmp_dir,
3890
+ resolver=resolver,
3891
+ prev_morph_ids=prev_morph_ids,
3892
+ page=page,
3893
+ font_profile=font_profile,
3894
+ wrap_mode=wrap_mode,
3895
+ )
3896
+ per_slide_stats.append(stats)
3897
+
3898
+ context.close()
3899
+ browser.close()
3900
+ finally:
3901
+ server.shutdown()
3902
+ server.server_close()
3903
+
3904
+ _sanitize_pptx_doc_props(
3905
+ prs,
3906
+ title=doc_title or None,
3907
+ canvas_w=canvas_w,
3908
+ canvas_h=canvas_h,
3909
+ fallback_stem=out_abs.stem,
3910
+ )
3911
+ prs.save(str(out_abs))
3912
+ result: dict[str, Any] = {
3913
+ "ok": True,
3914
+ "html": str(html_abs),
3915
+ "out": str(out_abs),
3916
+ "bytes": out_abs.stat().st_size,
3917
+ "canvas": {"width": canvas_w, "height": canvas_h},
3918
+ "slide_count": len(per_slide_stats),
3919
+ "compiled_slides": per_slide_stats,
3920
+ }
3921
+ if do_audit:
3922
+ audit = audit_compiled_pptx(
3923
+ out_abs,
3924
+ expected_slides=len(per_slide_stats),
3925
+ expected_w_emu=slide_w_emu,
3926
+ expected_h_emu=slide_h_emu,
3927
+ )
3928
+ for st in per_slide_stats:
3929
+ dropped = st.get("dropped_images") or []
3930
+ if dropped:
3931
+ srcs = [str(d.get("src") or "<empty>") for d in dropped[:4]]
3932
+ audit["issues"].append(
3933
+ f"Slide {st['slide']}: dropped {len(dropped)} unloaded <img> element(s) during PPTX export ({srcs!r})"
3934
+ )
3935
+ if audit["issues"]:
3936
+ audit["ok"] = False
3937
+ result["audit"] = audit
3938
+ result["ok"] = bool(audit.get("ok"))
3939
+ return result
3940
+
3941
+
3942
+ def main() -> int:
3943
+ _configure_utf8_stdio()
3944
+ parser = argparse.ArgumentParser(
3945
+ description="Compile any HTML slide deck (16:9, 3:4, 9:16, 1:1) or pre-extracted slide manifest to natively editable PPTX."
3946
+ )
3947
+ parser.add_argument("--html", type=Path, default=None, help="Path to multi-slide web/index.html")
3948
+ parser.add_argument(
3949
+ "--from-manifest",
3950
+ dest="from_manifest",
3951
+ type=Path,
3952
+ default=None,
3953
+ help="Path to pre-extracted slide manifest JSON (builds PPTX without launching a browser)",
3954
+ )
3955
+ parser.add_argument(
3956
+ "--assets-dir",
3957
+ dest="assets_dir",
3958
+ type=Path,
3959
+ default=None,
3960
+ help="Optional root directory for resolving relative asset paths when using --from-manifest",
3961
+ )
3962
+ parser.add_argument("--out", type=Path, required=True, help="Output .pptx file path")
3963
+ parser.add_argument(
3964
+ "--ratio",
3965
+ "--aspect-ratio",
3966
+ dest="ratio",
3967
+ type=str,
3968
+ default=None,
3969
+ help="Optional canvas aspect ratio override (16:9, 3:4, 9:16, 1:1)",
3970
+ )
3971
+ parser.add_argument("--width", type=int, default=None, help="Optional canvas width override (px)")
3972
+ parser.add_argument("--height", type=int, default=None, help="Optional canvas height override (px)")
3973
+ parser.add_argument(
3974
+ "--font-profile",
3975
+ dest="font_profile",
3976
+ choices=("auto", "windows", "macos", "cross-platform"),
3977
+ default="auto",
3978
+ help="Target font mapping profile (default: auto)",
3979
+ )
3980
+ parser.add_argument(
3981
+ "--wrap-mode",
3982
+ dest="wrap_mode",
3983
+ choices=("reflow", "exact"),
3984
+ default="reflow",
3985
+ help="Text wrapping mode: reflow merges soft-wrapped lines into editable paragraphs; exact keeps 1 paragraph per visual line (default: reflow)",
3986
+ )
3987
+ parser.add_argument("--audit", action="store_true", help="Re-open saved PPTX and audit shapes/text boxes")
3988
+ parser.add_argument("--json", action="store_true", help="Print JSON summary to stdout")
3989
+ args = parser.parse_args()
3990
+
3991
+ if args.from_manifest is None and args.html is None:
3992
+ parser.error("one of the arguments --html or --from-manifest is required")
3993
+
3994
+ if args.from_manifest is not None:
3995
+ manifest_path = args.from_manifest.resolve()
3996
+ if not manifest_path.is_file():
3997
+ raise FileNotFoundError(f"Manifest file not found: {manifest_path}")
3998
+ manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
3999
+ if args.assets_dir is not None:
4000
+ assets_root = args.assets_dir.resolve()
4001
+ elif args.html is not None and args.html.resolve().is_file():
4002
+ assets_root, _ = _infer_serve_root(args.html.resolve())
4003
+ elif isinstance(manifest.get("assets_dir"), str) and manifest["assets_dir"].strip():
4004
+ assets_root = Path(manifest["assets_dir"]).resolve()
4005
+ else:
4006
+ parent = manifest_path.parent
4007
+ if parent.name in ("web", "dist", "verify") and parent.parent != parent:
4008
+ assets_root = parent.parent
4009
+ else:
4010
+ assets_root = parent
4011
+ res = build_pptx_from_manifest(
4012
+ manifest,
4013
+ assets_root,
4014
+ args.out,
4015
+ do_audit=args.audit or True,
4016
+ font_profile=args.font_profile,
4017
+ wrap_mode=args.wrap_mode,
4018
+ )
4019
+ else:
4020
+ res = compile_html_to_pptx(
4021
+ args.html,
4022
+ args.out,
4023
+ do_audit=args.audit or True,
4024
+ ratio=args.ratio,
4025
+ width=args.width,
4026
+ height=args.height,
4027
+ font_profile=args.font_profile,
4028
+ wrap_mode=args.wrap_mode,
4029
+ )
4030
+
4031
+ if args.json:
4032
+ print(json.dumps(res, ensure_ascii=False, indent=2))
4033
+ else:
4034
+ print(f"html_to_pptx: ok={res['ok']} slides={res['slide_count']} out={res['out']} ({res['bytes']} bytes)")
4035
+ if not res["ok"]:
4036
+ for iss in (res.get("audit") or {}).get("issues", []):
4037
+ print(f" ISSUE: {iss}", file=sys.stderr)
4038
+ return 0 if res["ok"] else 1
4039
+
4040
+
4041
+ if __name__ == "__main__":
4042
+ raise SystemExit(main())