AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
fix(svg-canvas): enforce the locked root viewBox contract
hugohe3f9a6e598b61c
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.mdindex 6d4692f1..b51947da 100644--- a/docs/powerpoint-svg-mapping.md+++ b/docs/powerpoint-svg-mapping.md@@ -38,7 +38,7 @@ Each row owns one PowerPoint capability. The mapping cardinality is not always o| PowerPoint feature | Project representation | PPTX result | Import and fidelity | Validation boundary ||---|---|---|---|---|-| Presentation slide size | Root SVG `viewBox`, selected through the project canvas contract | Presentation width and height; `1 SVG px = 9,525 EMU` at 96 DPI | `Native-stable`; imported coordinates are projected onto the SVG canvas | Every page must use the selected canvas; a root transform is forbidden |+| Presentation slide size | Root SVG `viewBox="0 0 W H"`, selected through the project canvas contract | Presentation width and height; `1 SVG px = 9,525 EMU` at 96 DPI | `Native-stable`; imported custom PPTX sizes may use compatible fractional dimensions | Values must be finite with a zero origin and positive supported dimensions; every public page/internal Layout prototype must match the lock; a root transform is forbidden || Slide | One complete `svg_output/<slide>.svg` page | One `p:sld` with its relationships | Reconstructed as one complete SVG page | SVG is the visible page authority; notes and package behavior are separate || Object position and size | Absolute SVG coordinates and element bounds | `a:xfrm` offsets and extents | `Native-normalized` through coordinate conversion | Values must be finite and use the registered coordinate grammar || Z-order | SVG source order, back to front | PowerPoint shape-tree order | Reconstructed in shape-tree order | Do not rely on browser-only stacking behavior |@@ -46,7 +46,7 @@ Each row owns one PowerPoint capability. The mapping cardinality is not always o| Theme colors and fonts | Roles locked in `spec_lock.md`; canonical SVG uses the resolved values | Theme-aware tokens where an exact locked role can be retained; otherwise direct DrawingML values | `Native-stable` for registered roles | New pages must not invent unlocked colors, fonts, or text sizes || PowerPoint-only package identity | `spec_lock.md` structure declarations and the package builder | Presentation, Master, Layout, relationship, and content-type registrations | Read back from package structure, not inferred from page appearance | Final-package read-back must match the declared roster |-See [`canvas-formats.md`](../skills/ppt-master/references/canvas-formats.md) for supported canvases and the normative standards for the exact unit grammar.+See [`canvas-formats.md`](../skills/ppt-master/references/canvas-formats.md) for supported canvases and [`shared-standards.md`](../skills/ppt-master/references/shared-standards.md) §4.1 for the normative root-`viewBox` contract.## 2. Master, Layout, background, and placeholder featuresdiff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.mdindex 2997fafd..f3278345 100644--- a/docs/zh/powerpoint-svg-mapping.md+++ b/docs/zh/powerpoint-svg-mapping.md@@ -38,7 +38,7 @@ PowerPoint 意图| PowerPoint 功能 | 项目表达 | PPTX 结果 | 回导与保真度 | 校验边界 ||---|---|---|---|---|-| 演示文稿页面尺寸 | 根 SVG `viewBox`,通过项目画布合同选择 | 演示文稿宽高;96 DPI 下 `1 SVG px = 9,525 EMU` | `Native-stable`;导入坐标投影到 SVG 画布 | 每页必须使用已选画布;禁止根 transform |+| 演示文稿页面尺寸 | 根 SVG `viewBox="0 0 W H"`,通过项目画布合同选择 | 演示文稿宽高;96 DPI 下 `1 SVG px = 9,525 EMU` | `Native-stable`;回导的自定义 PPTX 尺寸可使用兼容的正小数 | 数值必须有限、原点为零且尺寸为受支持的正值;所有公开页和内部 Layout 原型必须匹配锁;禁止根 transform || 幻灯片 | 一个完整的 `svg_output/<slide>.svg` 页面 | 一个 `p:sld` 及其 relationships | 重建为一张完整 SVG 页面 | SVG 是可见页面权威;备注和包行为单独承载 || 对象位置与尺寸 | SVG 绝对坐标与元素边界 | `a:xfrm` 偏移和范围 | 经坐标换算后为 `Native-normalized` | 数值必须有限,并使用已登记坐标语法 || Z 顺序 | SVG 源码顺序,由后到前 | PowerPoint shape tree 顺序 | 按 shape tree 顺序重建 | 不得依赖浏览器专属堆叠行为 |@@ -46,7 +46,7 @@ PowerPoint 意图| 主题颜色与字体 | `spec_lock.md` 锁定的角色;规范 SVG 使用解析后的值 | 当精确匹配锁定角色时保留 theme token,否则写直接 DrawingML 值 | 已登记角色为 `Native-stable` | 新页面不得自行发明未锁定颜色、字体或字号 || PowerPoint 包身份 | `spec_lock.md` 结构声明与打包器 | Presentation、Master、Layout、relationship 与 content type 注册 | 从包结构读回,不从页面外观推断 | 最终包读回必须与声明的 roster 一致 |-受支持的画布见 [`canvas-formats.md`](../../skills/ppt-master/references/canvas-formats.md),精确单位语法以规范为准。+受支持的画布见 [`canvas-formats.md`](../../skills/ppt-master/references/canvas-formats.md),根 `viewBox` 的规范合同见 [`shared-standards.md`](../../skills/ppt-master/references/shared-standards.md) §4.1。## 2. Master、Layout、背景与占位符功能diff --git a/skills/ppt-master/references/canvas-formats.md b/skills/ppt-master/references/canvas-formats.mdindex 0be72bf4..318a25ea 100644--- a/skills/ppt-master/references/canvas-formats.md+++ b/skills/ppt-master/references/canvas-formats.md@@ -1,6 +1,7 @@# Canvas Format Specification-> See shared-standards.md for SVG basic rules.+> See [`shared-standards.md`](shared-standards.md) §4.1 for the normative root+> `viewBox` grammar, compatibility spellings, and fail-closed validation rules.## Format Quick Reference@@ -15,6 +16,13 @@| `banner` | Landscape Banner | `1920x1080` | `0 0 1920 1080` | 16:9 | Web banners, digital screens || `a4` | A4 Print | `1240x1754` | `0 0 1240 1754` | 1:sqrt(2) | Print posters, flyers |+The table lists canonical root spellings. New custom canvases likewise use+`0 0 W H` with positive integer pixels. A fractional positive canvas is accepted+only as compatible input for an imported custom PowerPoint slide size; it is not+the default authoring form. All pages and internal Layout prototypes in one+export use the same numeric canvas and stay within PowerPoint's supported slide+range (914,400–51,206,400 EMU per side, approximately 96–5,376 SVG px).+`ppt169` is the canonical PPT wide-screen canvas in this repo: `1280x720`, not any arbitrary 16:9 size. Same-ratio canvases such as `banner` (`1920x1080`) must be treated as different coordinate systems.## Format Selection Decision Treediff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.mdindex c029b44d..36a08c6a 100644--- a/skills/ppt-master/references/shared-standards.md+++ b/skills/ppt-master/references/shared-standards.md@@ -520,9 +520,22 @@ continue without modification.Semantic markers are minimal compiler hints orthogonal to native SVG semantics. Free-design and brand-only pages use flat export, declare one canonical root `data-pptx-page-role` (`cover` / `toc` / `section` / `content` / `ending`), and omit Master/Layout/layer/placeholder markers. On deck/layout template routes, root Master/Layout identity, atomic layer elements, grouped slots, and native-object metadata are authoritative and read first; each page carries its final structured contract from the start of SVG authoring and omits `data-pptx-page-role`. Add `data-pptx-role` only when no specialized marker expresses the required page-frame behavior; the element also uses a stable unique `id`. Do not classify ordinary page content or move visible facts out of SVG attributes/text into metadata. See [`semantic-svg.md`](semantic-svg.md) for the canonical vocabulary and examples.-- **Canvas authority**: `viewBox` MUST match the selected canvas dimensions.- Root `width` and `height` are optional and do not override it. Root `<svg>`- `transform` is forbidden; apply transforms to child elements or groups.+- **Canvas authority**: New authoring writes the root canvas exactly as+ `viewBox="0 0 W H"`, using single spaces and positive ordinary-decimal integer+ pixels from the selected project/template lock. Numerically identical SVG+ spellings (integral decimals, exponent or leading-plus notation, and comma+ separators) are compatible input and receive a normalization warning.+ Positive fractional dimensions are also read-compatible for custom slide+ sizes reconstructed from PPTX; export quantizes them once at+ `1 SVG px = 9,525 EMU`. Missing/malformed/non-finite values, a non-zero+ origin, non-positive dimensions, or dimensions outside PowerPoint's supported+ slide-size range are errors. Every public page and internal Layout prototype+ in one build MUST use the same numeric canvas and match `spec_lock.md`+ `canvas.viewBox`; standalone templates match `design_spec.md`+ `canvas_viewbox`. Root `width` and `height` are optional and do not override+ the `viewBox`. Root `<svg>` `transform` is forbidden; apply transforms to+ child elements or groups. This root-page rule does not replace the separate+ nested-crop and `<symbol viewBox>` contracts.- **Font portability**: font families used by the deck must resolve to installedexport faces. `@font-face` remains forbidden; the typography contract lives in[`strategist.md §g`](strategist.md).diff --git a/skills/ppt-master/scripts/pptx_to_svg/emu_units.py b/skills/ppt-master/scripts/pptx_to_svg/emu_units.pyindex 9ebb09c4..f45036c9 100644--- a/skills/ppt-master/scripts/pptx_to_svg/emu_units.py+++ b/skills/ppt-master/scripts/pptx_to_svg/emu_units.py@@ -12,6 +12,7 @@ DrawingML unit conventions:from __future__ import annotations+from decimal import Decimal, ROUND_HALF_UP, localcontextfrom xml.etree import ElementTree as ETEMU_PER_INCH = 914400@@ -235,3 +236,13 @@ def _fmt(val: float, ndigits: int = 2) -> str:fmt_num = _fmt+++def format_canvas_px_from_emu(emu: int) -> str:+ """Format a slide-size coordinate with enough precision to recover EMU."""+ with localcontext() as context:+ context.prec = 32+ value = Decimal(emu) / Decimal(EMU_PER_PX)+ rounded = value.quantize(Decimal("0.00001"), rounding=ROUND_HALF_UP)+ token = format(rounded, "f").rstrip("0").rstrip(".")+ return token or "0"diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.pyindex 76ba03be..587f4922 100644--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py@@ -40,7 +40,7 @@ from .color_resolver import ColorPalette, find_color_elem, resolve_colorfrom .chart_to_svg import CHART_URI, CHARTEX_URI, extract_native_chart_payloadfrom .custgeom_to_svg import convert_custom_geomfrom .effect_to_svg import convert_effects-from .emu_units import NS, Xfrm, fmt_num+from .emu_units import NS, Xfrm, fmt_num, format_canvas_px_from_emufrom .fill_to_svg import resolve_fillfrom .ln_to_svg import resolve_strokefrom .ooxml_loader import OoxmlPackage, PartRef, SlideRef@@ -134,6 +134,9 @@ def assemble_slide()canvas_w, canvas_h = pkg.slide_size_px+ canvas_w_token, canvas_h_token = (+ format_canvas_px_from_emu(value) for value in pkg.slide_size_emu+ )# Background (cSld/bg) — emit as the first body element.body_parts: list[str] = []@@ -176,8 +179,8 @@ def assemble_slide(svg = (f'<svg xmlns="http://www.w3.org/2000/svg" 'f'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" '- f'width="{fmt_num(canvas_w)}" height="{fmt_num(canvas_h)}" '- f'viewBox="0 0 {fmt_num(canvas_w)} {fmt_num(canvas_h)}">'+ f'width="{canvas_w_token}" height="{canvas_h_token}" '+ f'viewBox="0 0 {canvas_w_token} {canvas_h_token}">'f"{defs_block}"+ "\n".join(body_parts)+ "</svg>"@@ -232,6 +235,9 @@ def assemble_part_solo()canvas_w, canvas_h = pkg.slide_size_px+ canvas_w_token, canvas_h_token = (+ format_canvas_px_from_emu(value) for value in pkg.slide_size_emu+ )body_parts: list[str] = []@@ -272,8 +278,8 @@ def assemble_part_solo(svg = (f'<svg xmlns="http://www.w3.org/2000/svg" 'f'xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" '- f'width="{fmt_num(canvas_w)}" height="{fmt_num(canvas_h)}" '- f'viewBox="0 0 {fmt_num(canvas_w)} {fmt_num(canvas_h)}">'+ f'width="{canvas_w_token}" height="{canvas_h_token}" '+ f'viewBox="0 0 {canvas_w_token} {canvas_h_token}">'f"{defs_block}"+ "\n".join(body_parts)+ "</svg>"diff --git a/skills/ppt-master/scripts/project_utils.py b/skills/ppt-master/scripts/project_utils.pyindex 98cfcc21..3870f081 100644--- a/skills/ppt-master/scripts/project_utils.py+++ b/skills/ppt-master/scripts/project_utils.py@@ -11,9 +11,13 @@ import refrom pathlib import Pathfrom datetime import datetimefrom typing import Dict, List, Optional, Tuple-from xml.etree import ElementTree as ETfrom console_encoding import configure_utf8_stdio+from svg_to_pptx.canvas_contract import (+ CanvasContractError,+ parse_project_viewbox,+ read_project_viewbox,+)configure_utf8_stdio()@@ -324,36 +328,38 @@ def validate_svg_viewbox(svg_files: List[Path], expected_format: Optional[str] =List of warnings"""warnings = []- viewboxes = set()+ viewboxes = {}# Determine expected viewBoxexpected_viewbox = Noneif expected_format and expected_format in CANVAS_FORMATS:- expected_viewbox = CANVAS_FORMATS[expected_format]['viewbox']+ expected_viewbox = parse_project_viewbox(+ CANVAS_FORMATS[expected_format]['viewbox'],+ context=f"canvas format {expected_format!r}",+ )- for svg_file in svg_files[:10]: # Check first 10 files+ for svg_file in svg_files:try:- viewbox = ET.parse(svg_file).getroot().get('viewBox')- if viewbox:- viewboxes.add(viewbox)-- # If expected format is specified, check for match- if expected_viewbox and viewbox != expected_viewbox:- warnings.append(- f"{svg_file.name}: root viewBox '{viewbox}' differs from recorded "- f"project format '{expected_format}' ({expected_viewbox}); export uses "- f"the SVG viewBox as the canvas size"- )- else:- warnings.append(f"{svg_file.name}: root viewBox attribute not found")- except Exception as e:- warnings.append(f"{svg_file.name}: Failed to read - {e}")+ viewbox = read_project_viewbox(svg_file)+ except CanvasContractError as exc:+ warnings.append(str(exc))+ continue+ viewboxes[svg_file.name] = viewbox+ if expected_viewbox and viewbox != expected_viewbox:+ warnings.append(+ f"{svg_file.name}: root viewBox '{viewbox.canonical}' must match "+ f"project format '{expected_format}' ({expected_viewbox.canonical})"+ )# Check for multiple different viewBoxes- if len(viewboxes) > 1:+ distinct = {viewbox for viewbox in viewboxes.values()}+ if len(distinct) > 1:+ details = ", ".join(+ f"{name}={viewbox.canonical}"+ for name, viewbox in sorted(viewboxes.items())+ )warnings.append(- f"Multiple different root viewBox settings detected: {viewboxes}; "- "confirm this mixed-canvas project is intentional"+ "All project SVG root viewBoxes must match; found " + details)return warningsdiff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 2ed76fdb..559c652b 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -31,6 +31,12 @@ except ImportError:print("Warning: Unable to import project_utils")CANVAS_FORMATS = {}+from svg_to_pptx.canvas_contract import (+ CanvasContractError,+ parse_project_svg_root,+ parse_project_viewbox,+)+try:from update_spec import parse_lock as _parse_spec_lockexcept ImportError:@@ -901,6 +907,27 @@ def _declared_template_structure_mode(target_path: Path) -> str | None:return match.group(1).lower() if match else None+def _declared_template_canvas_viewbox(target_path: Path) -> str | None:+ """Return a template design spec's locked root-canvas value."""+ directory = target_path.parent if target_path.is_file() else target_path+ spec_path = directory / 'design_spec.md'+ try:+ text = spec_path.read_text(encoding='utf-8')+ except OSError:+ return None+ if not text.startswith('---\n'):+ return None+ end = text.find('\n---\n', 4)+ if end == -1:+ return None+ match = re.search(+ r'^canvas_viewbox:\s*["\']?([^"\'\r\n]+?)["\']?\s*$',+ text[4:end],+ re.MULTILINE,+ )+ return match.group(1).strip() if match else None++def _template_structure_checks_enabled(target_path: Path) -> bool:"""Return whether positive structure checks apply to this template."""return _declared_template_structure_mode(target_path) == 'structured'@@ -977,16 +1004,11 @@ def _effective_presentation_value(def _parse_viewbox_values(viewbox: str) -> Tuple[float, float, float, float] | None:"""Parse a root viewBox into four numeric values."""- parts = re.split(r'[\s,]+', viewbox.strip())- if len(parts) != 4:- return Nonetry:- values = tuple(float(part) for part in parts)- except ValueError:- return None- if values[2] <= 0 or values[3] <= 0:+ parsed = parse_project_viewbox(viewbox)+ except CanvasContractError:return None- return values+ return 0.0, 0.0, float(parsed.width), float(parsed.height)def _parse_placeholders_fallback(block: str) -> Dict[str, Tuple[str, ...]]:@@ -1127,7 +1149,14 @@ class SVGQualityChecker:self._pptx_structure_issues: List[Tuple[str, str]] = []self._aggregate_counts_applied = False- def check_file(self, svg_file: str, expected_format: str = None) -> Dict:+ def check_file(+ self,+ svg_file: str,+ expected_format: str = None,+ *,+ expected_viewbox: str | None = None,+ expected_viewbox_label: str = "expected canvas",+ ) -> Dict:"""Check a single SVG file@@ -1169,7 +1198,14 @@ class SVGQualityChecker:root = self._parse_xml_root(content, result)if root is not None:# 1. Check viewBox- self._check_viewbox(root, result, expected_format)+ self._check_viewbox(+ root,+ svg_path,+ result,+ expected_format,+ expected_viewbox=expected_viewbox,+ expected_viewbox_label=expected_viewbox_label,+ )# 1a. Validate exact importer transport before compatible# inline geometry is materialized on the shared tree.@@ -1320,44 +1356,80 @@ class SVGQualityChecker:)return None- def _check_viewbox(self, root: ET.Element, result: Dict, expected_format: str = None):- """Check viewBox attribute"""+ def _check_viewbox(+ self,+ root: ET.Element,+ svg_path: Path,+ result: Dict,+ expected_format: str = None,+ *,+ expected_viewbox: str | None = None,+ expected_viewbox_label: str = "expected canvas",+ ):+ """Validate the root page canvas and its project-level locks."""viewbox = root.get('viewBox')- if not viewbox:- result['errors'].append("Missing viewBox attribute")- return-- result['info']['viewbox'] = viewbox-- parts = re.split(r'[\s,]+', viewbox.strip())- if len(parts) != 4:- result['errors'].append(- f"viewBox must contain exactly four numeric values; got: {viewbox}"- )- returntry:- values = tuple(float(part) for part in parts)- except ValueError:- result['errors'].append(- f"viewBox must contain exactly four numeric values; got: {viewbox}"+ parsed = parse_project_svg_root(+ root,+ context=svg_path.name,)+ except CanvasContractError as exc:+ result['errors'].append(str(exc))return- if values[2] <= 0 or values[3] <= 0:- result['errors'].append(- f"viewBox width/height must be positive; got: {viewbox}"+ assert viewbox is not None+ result['info']['viewbox'] = viewbox+ if viewbox != parsed.canonical or not parsed.has_integer_dimensions:+ if parsed.has_integer_dimensions:+ recommendation = f'write viewBox="{parsed.canonical}"'+ else:+ recommendation = (+ "fractional dimensions are reserved for compatible imported "+ "custom slide sizes; new authoring uses integer pixels"+ )+ result['warnings'].append(+ f"Compatible non-canonical root viewBox {viewbox!r}; {recommendation}.")- return- if values[0] != 0 or values[1] != 0 or any(not part.isdigit() for part in parts):- result['warnings'].append(f"Unusual viewBox format: {viewbox}")+ contracts: list[tuple[str, str]] = []+ if expected_viewbox is not None:+ contracts.append((expected_viewbox_label, expected_viewbox))+ elif not self.template_mode:+ lock = self._get_spec_lock(svg_path)+ if lock is not None and 'canvas' in lock:+ locked_viewbox = lock.get('canvas', {}).get('viewBox')+ if not locked_viewbox:+ result['errors'].append(+ "spec_lock.md canvas section must declare viewBox"+ )+ else:+ contracts.append(("spec_lock canvas", locked_viewbox))- # Check if it matches expected formatif expected_format and expected_format in CANVAS_FORMATS:- expected_viewbox = CANVAS_FORMATS[expected_format]['viewbox']- expected_values = _parse_viewbox_values(expected_viewbox)- if expected_values and values != expected_values:+ contracts.append((+ f"canvas format {expected_format!r}",+ CANVAS_FORMATS[expected_format]['viewbox'],+ ))+ elif expected_format:+ result['errors'].append(f"Unsupported canvas format: {expected_format}")++ seen_contracts: set[tuple[str, str]] = set()+ for label, raw_expected in contracts:+ contract_key = (label, raw_expected)+ if contract_key in seen_contracts:+ continue+ seen_contracts.add(contract_key)+ try:+ expected = parse_project_viewbox(+ raw_expected,+ context=f"{label} viewBox",+ )+ except CanvasContractError as exc:+ result['errors'].append(str(exc))+ continue+ if parsed != expected:result['errors'].append(- f"viewBox mismatch: expected '{expected_viewbox}', got '{viewbox}'"+ f"viewBox mismatch: {label} requires '{expected.canonical}', "+ f"got '{parsed.canonical}'")def _check_forbidden_elements(self, content: str, root: ET.Element, result: Dict):@@ -4323,10 +4395,59 @@ class SVGQualityChecker:self.issue_types['Input issues'] += 1return []+ directory_expected_viewbox: str | None = None+ directory_expected_label = "the first SVG canvas"+ directory_lock_has_canvas = False+ if self.template_mode:+ template_viewbox = _declared_template_canvas_viewbox(dir_path)+ if template_viewbox:+ directory_expected_viewbox = template_viewbox+ directory_expected_label = "design_spec canvas_viewbox"+ else:+ directory_expected_viewbox = ""+ directory_expected_label = "design_spec canvas_viewbox"+ if expected_format is None and directory_expected_viewbox is None:+ lock = (+ None+ if self.template_mode+ else self._get_spec_lock(svg_files[0])+ )+ if lock is not None:+ if 'canvas' in lock:+ directory_lock_has_canvas = True+ locked_viewbox = lock.get('canvas', {}).get('viewBox')+ if locked_viewbox:+ directory_expected_viewbox = locked_viewbox+ directory_expected_label = "spec_lock canvas"+ else:+ directory_expected_viewbox = ""+ directory_expected_label = "spec_lock canvas"+ if (+ directory_expected_viewbox is None+ and not directory_lock_has_canvas+ ):+ for svg_file in svg_files:+ try:+ root = ET.parse(svg_file).getroot()+ first_canvas = parse_project_viewbox(+ root.get('viewBox'),+ context=f"{svg_file.name} root viewBox",+ )+ except (OSError, ET.ParseError, CanvasContractError):+ continue+ directory_expected_viewbox = first_canvas.canonical+ directory_expected_label = f"first SVG {svg_file.name}"+ break+print(f"\n[SCAN] Checking {len(svg_files)} SVG file(s)...\n")for svg_file in svg_files:- result = self.check_file(str(svg_file), expected_format)+ result = self.check_file(+ str(svg_file),+ expected_format,+ expected_viewbox=directory_expected_viewbox,+ expected_viewbox_label=directory_expected_label,+ )self._print_result(result)if self.template_mode:diff --git a/skills/ppt-master/scripts/svg_to_pptx/__init__.py b/skills/ppt-master/scripts/svg_to_pptx/__init__.pyindex 5ae582f0..f8a1e412 100644--- a/skills/ppt-master/scripts/svg_to_pptx/__init__.py+++ b/skills/ppt-master/scripts/svg_to_pptx/__init__.py@@ -6,12 +6,32 @@ Public API:- create_pptx_with_native_svg(): Build PPTX from SVG files"""-from .pptx_package.cli import main-from .drawingml.converter import convert_svg_to_slide_shapes-from .pptx_package.builder import create_pptx_with_native_svg+from __future__ import annotations++from typing import Any__all__ = ['main','convert_svg_to_slide_shapes','create_pptx_with_native_svg',]+++def __getattr__(name: str) -> Any:+ """Load public entry points lazily to keep low-level imports acyclic."""+ if name == 'main':+ from .pptx_package.cli import main++ value = main+ elif name == 'convert_svg_to_slide_shapes':+ from .drawingml.converter import convert_svg_to_slide_shapes++ value = convert_svg_to_slide_shapes+ elif name == 'create_pptx_with_native_svg':+ from .pptx_package.builder import create_pptx_with_native_svg++ value = create_pptx_with_native_svg+ else:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")+ globals()[name] = value+ return valuediff --git a/skills/ppt-master/scripts/svg_to_pptx/canvas_contract.py b/skills/ppt-master/scripts/svg_to_pptx/canvas_contract.pynew file mode 100644index 00000000..f8e2f5ae--- /dev/null+++ b/skills/ppt-master/scripts/svg_to_pptx/canvas_contract.py@@ -0,0 +1,226 @@+"""Project root-SVG canvas parsing and cross-file validation."""++from __future__ import annotations++import re+from dataclasses import dataclass+from decimal import Decimal, InvalidOperation, ROUND_HALF_UP, localcontext+from pathlib import Path+from typing import Iterable+from xml.etree import ElementTree as ET+++class CanvasContractError(ValueError):+ """Raised when a root SVG canvas cannot map faithfully to one slide."""+++PPTX_SLIDE_EMU_MIN = 914400+PPTX_SLIDE_EMU_MAX = 51206400+++_SVG_NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"+_VIEWBOX_RE = re.compile(+ rf"^\s*({_SVG_NUMBER})(?:\s*,\s*|\s+)"+ rf"({_SVG_NUMBER})(?:\s*,\s*|\s+)"+ rf"({_SVG_NUMBER})(?:\s*,\s*|\s+)"+ rf"({_SVG_NUMBER})\s*$"+)+++@dataclass(frozen=True)+class ProjectViewBox:+ """One validated zero-origin project canvas."""++ width: Decimal+ height: Decimal++ @property+ def values(self) -> tuple[Decimal, Decimal, Decimal, Decimal]:+ return Decimal(0), Decimal(0), self.width, self.height++ @property+ def pixel_dimensions(self) -> tuple[float, float]:+ return float(self.width), float(self.height)++ @property+ def emu_dimensions(self) -> tuple[int, int]:+ """Quantize the SVG canvas to DrawingML's integer EMU dimensions."""+ width_emu, height_emu = self._scaled_emu_values()+ width = int(width_emu.to_integral_value(ROUND_HALF_UP))+ height = int(height_emu.to_integral_value(ROUND_HALF_UP))+ return width, height++ def _scaled_emu_values(self) -> tuple[Decimal, Decimal]:+ precision = max(+ 28,+ len(self.width.as_tuple().digits) + 8,+ len(self.height.as_tuple().digits) + 8,+ )+ with localcontext() as context:+ context.prec = precision+ return self.width * Decimal(9525), self.height * Decimal(9525)++ @property+ def canonical(self) -> str:+ return f"0 0 {_format_decimal(self.width)} {_format_decimal(self.height)}"++ @property+ def has_integer_dimensions(self) -> bool:+ return (+ self.width == self.width.to_integral_value()+ and self.height == self.height.to_integral_value()+ )+++def _format_decimal(value: Decimal) -> str:+ token = format(value, "f")+ if "." in token:+ token = token.rstrip("0").rstrip(".")+ return token or "0"+++def parse_project_viewbox(+ raw: str | None,+ *,+ context: str = "root viewBox",+) -> ProjectViewBox:+ """Parse the registered project root-viewBox subset.++ Equivalent SVG numeric spellings are accepted so callers can distinguish+ compatible input from canonical authoring. Semantic values stay closed:+ the origin is exactly zero and dimensions map to positive DrawingML sizes.+ Fractional dimensions remain read-compatible because imported custom PPTX+ slide sizes are not necessarily whole CSS pixels.+ """+ if raw is None or not raw.strip():+ raise CanvasContractError(f"{context} is required")++ match = _VIEWBOX_RE.fullmatch(raw)+ if match is None:+ raise CanvasContractError(+ f"{context} must contain exactly four SVG numbers; got {raw!r}"+ )++ try:+ values = tuple(Decimal(token) for token in match.groups())+ except InvalidOperation as exc:+ raise CanvasContractError(+ f"{context} contains an invalid numeric value; got {raw!r}"+ ) from exc+ if not all(value.is_finite() for value in values):+ raise CanvasContractError(+ f"{context} values must be finite; got {raw!r}"+ )++ x, y, width, height = values+ if x != 0 or y != 0:+ raise CanvasContractError(+ f'{context} origin must be "0 0"; got {raw!r}'+ )+ if width <= 0 or height <= 0:+ raise CanvasContractError(+ f"{context} width and height must be positive; got {raw!r}"+ )+ viewbox = ProjectViewBox(width=width, height=height)+ require_powerpoint_slide_size(viewbox, context=context)+ return viewbox+++def read_project_viewbox(svg_path: str | Path) -> ProjectViewBox:+ """Read and validate one file's root SVG viewBox."""+ path = Path(svg_path)+ try:+ root = ET.parse(path).getroot()+ except (OSError, ET.ParseError) as exc:+ raise CanvasContractError(f"{path.name}: unable to parse root SVG: {exc}") from exc+ return parse_project_svg_root(+ root,+ context=path.name,+ )+++def parse_project_svg_root(+ root: ET.Element,+ *,+ context: str = "document",+) -> ProjectViewBox:+ """Validate one page root element and its project viewBox."""+ if root.tag.rsplit("}", 1)[-1] != "svg":+ raise CanvasContractError(f"{context}: root element must be <svg>")+ return parse_project_viewbox(+ root.get("viewBox"),+ context=f"{context} root viewBox",+ )+++def require_powerpoint_slide_size(+ viewbox: ProjectViewBox,+ *,+ context: str = "SVG canvas",+) -> tuple[int, int]:+ """Return EMU dimensions or reject values outside PowerPoint's range."""+ # Reject before converting to int so an adversarial exponent cannot force+ # construction of an enormous Python integer or fixed-point string.+ values = viewbox.width, viewbox.height+ outside_coarse_bound = any(+ value > Decimal(PPTX_SLIDE_EMU_MAX) for value in values+ )+ scaled = () if outside_coarse_bound else viewbox._scaled_emu_values()+ outside_emu_bound = outside_coarse_bound or not all(+ Decimal(PPTX_SLIDE_EMU_MIN) - Decimal("0.5")+ <= value+ < Decimal(PPTX_SLIDE_EMU_MAX) + Decimal("0.5")+ for value in scaled+ )+ if outside_emu_bound:+ dimensions = f"{viewbox.width} x {viewbox.height} px"+ raise CanvasContractError(+ f"{context} must map to PowerPoint's supported slide range "+ f"({PPTX_SLIDE_EMU_MIN}..{PPTX_SLIDE_EMU_MAX} EMU per side); "+ f"got {dimensions}"+ )+ return viewbox.emu_dimensions+++def require_consistent_project_viewboxes(+ svg_paths: Iterable[str | Path],+ *,+ expected_viewbox: str | None = None,+ expected_label: str = "expected canvas",+) -> ProjectViewBox:+ """Validate every public/internal SVG and return their shared canvas."""+ paths = [Path(path) for path in svg_paths]+ if not paths:+ raise CanvasContractError("at least one SVG is required to resolve the canvas")++ errors: list[str] = []+ parsed: list[tuple[Path, ProjectViewBox]] = []+ for path in paths:+ try:+ parsed.append((path, read_project_viewbox(path)))+ except CanvasContractError as exc:+ errors.append(str(exc))+ if errors:+ details = "\n".join(f" - {error}" for error in errors)+ raise CanvasContractError("SVG canvas validation failed:\n" + details)++ if expected_viewbox is not None:+ reference = parse_project_viewbox(+ expected_viewbox,+ context=f"{expected_label} viewBox",+ )+ else:+ reference = parsed[0][1]++ mismatches = [+ f"{path.name}: expected {reference.canonical}, got {viewbox.canonical}"+ for path, viewbox in parsed+ if viewbox != reference+ ]+ if mismatches:+ details = "\n".join(f" - {message}" for message in mismatches)+ raise CanvasContractError(+ f"SVG canvases must all match {expected_label} "+ f"({reference.canonical}):\n{details}"+ )+ return referencediff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex 691b9a3b..fd828e79 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -74,6 +74,11 @@ from .elements import (project_nested_svg_crop_errors,)from ..animation_config import is_chrome_id, usable_animation_group_id+from ..canvas_contract import (+ CanvasContractError,+ parse_project_svg_root,+ parse_project_viewbox,+)from ..native_objects import (NativeMarkerAttributeError,convert_native_object,@@ -399,20 +404,8 @@ def parse_transform(transform_str: str) -> tuple[float, float, float, float, flo# compensate for the offset between those two centres.def _root_viewport_size(root: ET.Element) -> tuple[float, float]:"""Return the SVG root viewport size in user units."""- view_box = root.get('viewBox')- if view_box:- raw_parts = re.split(r'[\s,]+', view_box.strip())- if len(raw_parts) == 4:- try:- parts = [float(n) for n in raw_parts]- except ValueError:- parts = []- if parts and parts[2] > 0 and parts[3] > 0:- return parts[2], parts[3]-- width = parse_svg_length(root.get('width'), 1280.0)- height = parse_svg_length(root.get('height'), 720.0)- return max(width, 1.0), max(height, 1.0)+ viewbox = parse_project_viewbox(root.get('viewBox'))+ return float(viewbox.width), float(viewbox.height)def _extract_rotate_pivot(transform_str: str) -> tuple[float, float] | None:@@ -907,21 +900,8 @@ _SUPPORTED_VISUAL_CHILD_TAGS = frozenset(('tspan',))def _parse_svg_canvas(root: ET.Element) -> tuple[float, float, float, float]:"""Return the SVG canvas as (x, y, width, height) in SVG units."""- view_box = root.get('viewBox', '')- parts = re.split(r'[\s,]+', view_box.strip()) if view_box else []- if len(parts) == 4:- try:- x, y, w, h = (float(part) for part in parts)- if w > 0 and h > 0:- return x, y, w, h- except ValueError:- pass- return (- 0.0,- 0.0,- parse_svg_length(root.get('width'), 0.0),- parse_svg_length(root.get('height'), 0.0),- )+ viewbox = parse_project_viewbox(root.get('viewBox'))+ return 0.0, 0.0, float(viewbox.width), float(viewbox.height)def _is_full_canvas_rect(@@ -1359,6 +1339,13 @@ def convert_svg_to_slide_shapes(svg_path = Path(svg_path)tree = ET.parse(str(svg_path))root = tree.getroot()+ try:+ parse_project_svg_root(+ root,+ context=svg_path.name,+ )+ except CanvasContractError as exc:+ raise SvgNativeConversionError(str(exc)) from exc_require_chart_table_marker_attributes(root, svg_path)_require_project_nested_svg_crops(root, svg_path)_require_project_clip_paths(root, svg_path)diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.pyindex 87f9bc73..f22fc873 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py@@ -66,8 +66,7 @@ from ..semantic_markers import ()from .dimensions import (CANVAS_FORMATS,- get_slide_dimensions, get_pixel_dimensions,- get_viewbox_dimensions, detect_format_from_svg,+ resolve_svg_canvas,)from .media import (PNG_RENDERER,@@ -4460,6 +4459,7 @@ def create_pptx_with_native_svg(structured_baseline: bool = False,baseline_layout_specs: list[TemplateSlideSpec] | None = None,layout_definition_files: list[Path] | None = None,+ expected_viewbox: str | None = None,) -> bool:"""Create a PPTX file with native DrawingML shapes.@@ -4470,6 +4470,8 @@ def create_pptx_with_native_svg(that no generated page uses. They are converted on internal carrierslides, registered, and removed before the package is published.canvas_format: Canvas format key.+ expected_viewbox: Optional project/template-lock canvas contract. Every+ public page and internal Layout definition must match it.verbose: Whether to output detailed information.transition: Transition effect name.transition_duration: Transition duration in seconds.@@ -4563,6 +4565,14 @@ def create_pptx_with_native_svg(use_compat_mode = Falseif pptx_structure not in {"baseline", "structured", "preserve", "flat"}:raise ValueError(f"Unsupported pptx_structure: {pptx_structure}")+ requested_canvas_format = canvas_format+ canvas, detected_canvas_format = resolve_svg_canvas(+ svg_files,+ canvas_format=canvas_format,+ expected_viewbox=expected_viewbox,+ )+ if canvas_format is None:+ canvas_format = detected_canvas_formatif pptx_structure == "flat":flat_errors = flat_structure_metadata_errors(public_svg_files)if flat_errors:@@ -4634,29 +4644,24 @@ def create_pptx_with_native_svg(print(" Will use pure SVG mode (may not display in Office LTSC 2021 and similar versions)")use_compat_mode = False- # Auto-detect canvas format or get dimensions from viewBox- custom_pixels: tuple[int, int] | None = None- if canvas_format is None:- canvas_format = detect_format_from_svg(svg_files[0])- if canvas_format and verbose:+ width_emu, height_emu = canvas.emu_dimensions+ pixel_width, pixel_height = canvas.pixel_dimensions+ pixel_width_label, pixel_height_label = canvas.canonical.split()[2:]+ if verbose and requested_canvas_format is None:+ if canvas_format:format_name = CANVAS_FORMATS.get(canvas_format, {}).get('name', canvas_format)print(f" Detected canvas format: {format_name}")-- if canvas_format is None:- custom_pixels = get_viewbox_dimensions(svg_files[0])- if custom_pixels and verbose:- print(f" Using SVG viewBox dimensions: {custom_pixels[0]} x {custom_pixels[1]} px")-- if canvas_format is None and custom_pixels is None:- canvas_format = 'ppt169'- if verbose:- print(f" Using default format: PPT 16:9")-- width_emu, height_emu = get_slide_dimensions(canvas_format or 'ppt169', custom_pixels)- pixel_width, pixel_height = get_pixel_dimensions(canvas_format or 'ppt169', custom_pixels)+ else:+ print(+ " Using SVG viewBox dimensions: "+ f"{canvas.canonical.removeprefix('0 0 ')} px"+ )if verbose:- print(f" Slide dimensions: {pixel_width} x {pixel_height} px")+ print(+ f" Slide dimensions: {pixel_width_label} x "+ f"{pixel_height_label} px"+ )print(f" SVG file count: {public_slide_count}")if definition_svg_files:print(diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.pyindex 3b483106..53d79861 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py@@ -35,7 +35,7 @@ if __package__ in {None, ''}:sys.modules.setdefault('svg_to_pptx', package)__package__ = 'svg_to_pptx'-from .dimensions import CANVAS_FORMATS, get_project_info, get_viewbox_dimensions+from .dimensions import CANVAS_FORMATS, get_project_infofrom .discovery import find_svg_files, find_notes_filesfrom .builder import create_pptx_with_native_svgfrom ..native_objects import (@@ -101,6 +101,20 @@ def _declared_pptx_structure_mode(project_path: Path) -> str | None:return mode_match.group(1).strip().lower() if mode_match else None+def _declared_canvas_viewbox(project_path: Path) -> str | None:+ """Return the project-lock root canvas without inferring from its name."""+ lock_path = project_path / 'spec_lock.md'+ try:+ from update_spec import parse_lock++ lock = parse_lock(lock_path)+ except (OSError, ValueError):+ return None+ canvas = lock.get('canvas', {})+ value = canvas.get('viewBox')+ return value.strip() if isinstance(value, str) and value.strip() else None++def _print_structure_migration_error(mode: str | None) -> None:"""Explain how a legacy or absent SVG structure contract is restored."""label = repr(mode) if mode else 'missing (legacy implicit baseline)'@@ -293,7 +307,7 @@ Recorded narration:'Pass output/final/<name> only for diagnostics.')parser.add_argument('-f', '--format', type=str,choices=list(CANVAS_FORMATS.keys()), default=None,- help='Specify canvas format')+ help='Require SVG canvases to match this registered format')parser.add_argument('-q', '--quiet', action='store_true', help='Quiet mode')merge_group = parser.add_mutually_exclusive_group()@@ -510,14 +524,17 @@ Recorded narration:try:project_info = get_project_info(str(project_path))project_name = project_info.get('name', project_path.name)- detected_format = project_info.get('format')except Exception:project_name = project_path.name- detected_format = Nonecanvas_format = args.format- if canvas_format is None and detected_format and detected_format != 'unknown':- canvas_format = detected_format+ expected_viewbox = _declared_canvas_viewbox(project_path)+ if expected_viewbox is None:+ print(+ "Error: spec_lock.md must contain canvas.viewBox for release export",+ file=sys.stderr,+ )+ return 1# Native DrawingML is the only PPTX product. ``-s`` remains an explicit# diagnostic source override; standard export always reads svg_output/.@@ -649,28 +666,6 @@ Recorded narration:verbose = not args.quiet- # Honor the actual SVG pixels over a stale project-recorded format. The- # canvas_format read from project init can disagree with what the Executor- # actually drew — e.g. a mirror template imported at 2560×1440 while the- # project was initialized as ppt169 (1280×720). When the first SVG's real- # viewBox doesn't match the recorded format's dimensions, drop the format- # so the builder sizes the slide by pixels (custom_pixels path). Standard- # decks match exactly, so this only changes behavior on the conflict case.- # An explicit --format always wins and is never second-guessed.- if args.format is None and canvas_format:- fmt_info = CANVAS_FORMATS.get(canvas_format)- actual_dims = get_viewbox_dimensions(ref_files[0])- if fmt_info and actual_dims:- fmt_dims = (fmt_info.get('width'), fmt_info.get('height'))- if fmt_dims != actual_dims:- if verbose:- print(- f" Recorded format '{canvas_format}' "- f"({fmt_dims[0]}×{fmt_dims[1]}) differs from SVG viewBox "- f"({actual_dims[0]}×{actual_dims[1]}); exporting by SVG pixels"- )- canvas_format = None-enable_notes = not args.no_notesnotes: dict[str, str] = {}if enable_notes:@@ -914,6 +909,7 @@ Recorded narration:shared_kwargs = dict(canvas_format=canvas_format,+ expected_viewbox=expected_viewbox,doc_metadata=doc_metadata,structure_name=structure_name,verbose=verbose,diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/dimensions.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/dimensions.pyindex cb82e040..7a1446b6 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/dimensions.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/dimensions.py@@ -7,6 +7,14 @@ import sysfrom pathlib import Pathfrom xml.etree import ElementTree as ET+from ..canvas_contract import (+ CanvasContractError,+ ProjectViewBox,+ parse_project_viewbox,+ read_project_viewbox,+ require_consistent_project_viewboxes,+)+# Import project utility modulessys.path.insert(0, str(Path(__file__).resolve().parent.parent))try:@@ -93,44 +101,19 @@ def get_pixel_dimensions(return 1280, 720-def _root_viewbox(svg_path: Path) -> str | None:- """Return the root SVG viewBox, ignoring nested sprite/crop viewBoxes."""- try:- root = ET.parse(svg_path).getroot()- except (ET.ParseError, OSError):- return None- return root.get('viewBox')---def _parse_viewbox_values(viewbox: str) -> tuple[float, float, float, float] | None:- parts = re.split(r'[\s,]+', viewbox.strip())- if len(parts) != 4:- return None- try:- values = tuple(float(part) for part in parts)- except ValueError:- return None- if values[2] <= 0 or values[3] <= 0:- return None- return values---def get_viewbox_dimensions(svg_path: Path) -> tuple[int, int] | None:+def get_viewbox_dimensions(svg_path: Path) -> tuple[float, float]:"""Extract pixel dimensions from SVG viewBox.Args:svg_path: Path to the SVG file.Returns:- (width, height) as integers, or None if not found.+ (width, height) in SVG pixels.++ Raises:+ CanvasContractError: The root canvas is missing or invalid."""- viewbox = _root_viewbox(svg_path)- if not viewbox:- return None- values = _parse_viewbox_values(viewbox)- if values is None:- return None- return int(round(values[2])), int(round(values[3]))+ return read_project_viewbox(svg_path).pixel_dimensionsdef detect_format_from_svg(svg_path: Path) -> str | None:@@ -142,14 +125,65 @@ def detect_format_from_svg(svg_path: Path) -> str | None:Returns:Canvas format key (e.g. 'ppt169'), or None if not detected."""- viewbox = _root_viewbox(svg_path)- if not viewbox:- return None- values = _parse_viewbox_values(viewbox)- if values is None:- return None+ viewbox = read_project_viewbox(svg_path)for fmt_key, fmt_info in CANVAS_FORMATS.items():- expected = _parse_viewbox_values(fmt_info['viewbox'])- if expected and values == expected:+ expected = parse_project_viewbox(+ fmt_info['viewbox'],+ context=f"registered canvas {fmt_key!r}",+ )+ if viewbox == expected:return fmt_keyreturn None+++def resolve_svg_canvas(+ svg_files: list[Path],+ *,+ canvas_format: str | None = None,+ expected_viewbox: str | None = None,+) -> tuple[ProjectViewBox, str | None]:+ """Resolve one fail-closed canvas for every public/internal SVG."""+ format_viewbox: str | None = None+ if canvas_format is not None:+ if canvas_format not in CANVAS_FORMATS:+ raise CanvasContractError(f"Unsupported canvas format: {canvas_format}")+ format_viewbox = CANVAS_FORMATS[canvas_format]['viewbox']++ if expected_viewbox is not None and format_viewbox is not None:+ locked = parse_project_viewbox(+ expected_viewbox,+ context="locked canvas viewBox",+ )+ selected = parse_project_viewbox(+ format_viewbox,+ context=f"canvas format {canvas_format!r}",+ )+ if locked != selected:+ raise CanvasContractError(+ f"canvas format {canvas_format!r} ({selected.canonical}) conflicts "+ f"with the locked canvas ({locked.canonical})"+ )++ required = expected_viewbox if expected_viewbox is not None else format_viewbox+ if expected_viewbox is not None:+ expected_label = "the locked canvas"+ elif canvas_format is not None:+ expected_label = f"canvas format {canvas_format!r}"+ else:+ expected_label = "the first SVG canvas"+ viewbox = require_consistent_project_viewboxes(+ svg_files,+ expected_viewbox=required,+ expected_label=expected_label,+ )+ detected_format = canvas_format+ if detected_format is None:+ for fmt_key, fmt_info in CANVAS_FORMATS.items():+ registered = parse_project_viewbox(+ fmt_info['viewbox'],+ context=f"registered canvas {fmt_key!r}",+ )+ if viewbox == registered:+ detected_format = fmt_key+ break+ return viewbox, detected_formatdiff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.pyindex f5f51d81..b26a1b96 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/template_structure.py@@ -35,6 +35,7 @@ from ..drawingml.utils import (parse_project_geometry_length,project_geometry_length_errors,)+from ..canvas_contract import CanvasContractError, parse_project_viewboxfrom ..geometry_properties import (GeometryStyleError,materialize_inline_geometry_properties,@@ -396,17 +397,8 @@ def _is_authored_preset_atom(elem: ET.Element) -> bool:def _svg_canvas(root: ET.Element) -> tuple[float, float, float, float]:- raw_viewbox = (root.get("viewBox") or "").strip()- values = [part for part in re.split(r"[\s,]+", raw_viewbox) if part]- if len(values) != 4:- return 0.0, 0.0, 0.0, 0.0- try:- x, y, width, height = (float(value) for value in values)- except ValueError:- return 0.0, 0.0, 0.0, 0.0- if not all(math.isfinite(value) for value in (x, y, width, height)):- return 0.0, 0.0, 0.0, 0.0- return x, y, width, height+ viewbox = parse_project_viewbox(root.get("viewBox"))+ return 0.0, 0.0, float(viewbox.width), float(viewbox.height)def _is_full_canvas_solid_rect(@@ -1220,6 +1212,13 @@ def parse_template_slide(if _local_tag(root) != "svg":raise TemplateStructureError(f"{svg_path.name}: root element must be <svg>")+ try:+ parse_project_viewbox(+ root.get("viewBox"),+ context=f"{svg_path.name} root viewBox",+ )+ except CanvasContractError as exc:+ raise TemplateStructureError(str(exc)) from excgeometry_errors = project_geometry_length_errors(root)if geometry_errors:@@ -2869,7 +2868,12 @@ def _placement_lint_errors(svg_path: Path) -> list[str]:f"{svg_path.name}: {element_id} uses template metadata below the SVG ""root; only a direct slot child may declare its carrier marker")- canvas = _svg_canvas(root)+ try:+ canvas = _svg_canvas(root)+ except CanvasContractError:+ # Root-canvas validation is owned by parse_template_slide and the+ # page Checker; placement lint should not duplicate that diagnosis.+ return errorslast_order_rank = -1for elem in root:tag = _local_tag(elem)diff --git a/skills/ppt-master/scripts/template_preview_pptx.py b/skills/ppt-master/scripts/template_preview_pptx.pyindex 58ca103e..79853334 100644--- a/skills/ppt-master/scripts/template_preview_pptx.py+++ b/skills/ppt-master/scripts/template_preview_pptx.py@@ -50,6 +50,10 @@ _REPLICATION_MODE_RE = re.compile(r"^replication_mode\s*:\s*(standard|fidelity|mirror)\s*$",re.MULTILINE,)+_CANVAS_VIEWBOX_RE = re.compile(+ r"^canvas_viewbox\s*:\s*[\"']?([^\"'\r\n]+?)[\"']?\s*$",+ re.MULTILINE,+)_FONT_SIZE_RE = re.compile(r"^([0-9]+(?:\.[0-9]+)?)(?:px)?$")_FILENAME_UNSAFE_RE = re.compile(r"[\\/:*?\"<>|\x00-\x1f]+")_TITLE_PLACEHOLDERS = frozenset({"title", "subtitle"})@@ -98,6 +102,18 @@ def _replication_mode(spec_path: Path) -> str:return match.group(1) if match else "standard"+def _canvas_viewbox(spec_path: Path) -> str | None:+ """Read the template's locked root canvas when declared."""+ text = spec_path.read_text(encoding="utf-8")+ if not text.startswith("---\n"):+ return None+ end = text.find("\n---\n", 4)+ if end == -1:+ return None+ match = _CANVAS_VIEWBOX_RE.search(text[4:end])+ return match.group(1).strip() if match else None++def _style_property(style: str, name: str) -> str | None:"""Return one inline CSS declaration value."""for declaration in style.split(";"):@@ -266,6 +282,11 @@ def main(argv: list[str] | None = None) -> int:spec_path = template_dir / "design_spec.md"template_id = _template_id(spec_path, workspace)replication_mode = _replication_mode(spec_path)+ locked_canvas = _canvas_viewbox(spec_path)+ if locked_canvas is None and not args.visual_only:+ raise ValueError(+ "design_spec.md frontmatter must declare canvas_viewbox"+ )use_full_placeholder_frames = (not args.visual_only and replication_mode != "mirror")@@ -302,6 +323,7 @@ def main(argv: list[str] | None = None) -> int:svg_files=svg_files,output_path=output_path,canvas_format=None,+ expected_viewbox=locked_canvas,verbose=True,transition=None,enable_notes=False,diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.pyindex 965771b6..0b3bdb13 100644--- a/skills/ppt-master/scripts/test_svg_quality_checker.py+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py@@ -2,6 +2,7 @@"""Regression tests for SVG checker compatibility severity."""import base64+import contextlibimport ioimport jsonimport math@@ -9,10 +10,14 @@ import reimport sysimport tempfileimport unittest+import zipfilefrom pathlib import Pathfrom unittest.mock import patchfrom xml.etree import ElementTree as ET+from pptx import Presentation+from pptx.util import Emu+SCRIPT_DIR = Path(__file__).resolve().parentif str(SCRIPT_DIR) not in sys.path:sys.path.insert(0, str(SCRIPT_DIR))@@ -30,16 +35,26 @@ from pptx_to_svg.preset_authoring import (validate_authored_preset_tree,)from pptx_to_svg.emu_units import Xfrm+from pptx_to_svg.converter import ConvertOptions, convert_pptx_to_svgfrom pptx_to_svg.txbody_to_svg import convert_txbody, convert_vertical_txbodyfrom svg_to_pptx.animation_config import (build_group_listing,build_scaffold,validate_animation_config,)+from svg_to_pptx.canvas_contract import (+ CanvasContractError,+ parse_project_viewbox,+)from svg_to_pptx.drawingml.converter import (SvgNativeConversionError,convert_svg_to_slide_shapes,)+from svg_to_pptx.pptx_package.builder import create_pptx_with_native_svg+from svg_to_pptx.pptx_package.dimensions import (+ CANVAS_FORMATS as PACKAGE_CANVAS_FORMATS,+ resolve_svg_canvas,+)from svg_to_pptx.drawingml.elements import parse_project_nested_svg_cropfrom svg_to_pptx.drawingml.utils import (estimate_text_width,@@ -60,6 +75,7 @@ from svg_to_pptx.pptx_package.template_structure import (parse_template_slide,)from svg_to_pptx.use_expander import UseExpansionError, expand_local_use_references+from template_preview_pptx import _canvas_viewbox as preview_canvas_viewboxclass SVGQualityCheckerCompatibilityTests(unittest.TestCase):@@ -167,6 +183,303 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):):convert_svg_to_slide_shapes(svg_path)+ def test_root_viewbox_uses_one_closed_checker_and_exporter_contract(self):+ canonical = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 1280 720">'+ '<rect x="0" y="0" width="1280" height="720" fill="#FFFFFF"/>'+ '</svg>'+ )+ canonical_result = self._check(canonical)+ self.assertFalse(any(+ 'non-canonical root viewBox' in warning+ for warning in canonical_result['warnings']+ ))++ compatible = canonical.replace(+ 'viewBox="0 0 1280 720"',+ 'viewBox="0.0,0,+1.28e3,720.0"',+ )+ compatible_result = self._check(compatible)+ self.assertTrue(compatible_result['passed'])+ self.assertTrue(any(+ 'Compatible non-canonical root viewBox' in warning+ for warning in compatible_result['warnings']+ ))++ with tempfile.TemporaryDirectory() as tmp_dir:+ canonical_path = Path(tmp_dir) / 'canonical.svg'+ compatible_path = Path(tmp_dir) / 'compatible.svg'+ canonical_path.write_text(canonical, encoding='utf-8')+ compatible_path.write_text(compatible, encoding='utf-8')+ self.assertEqual(+ convert_svg_to_slide_shapes(canonical_path)[0],+ convert_svg_to_slide_shapes(compatible_path)[0],+ )++ fractional = canonical.replace('1280 720', '1280.25 720.01')+ fractional_result = self._check(fractional)+ self.assertTrue(fractional_result['passed'])+ self.assertTrue(any(+ 'fractional dimensions are reserved' in warning+ for warning in fractional_result['warnings']+ ))++ invalid_cases = {+ 'missing': (+ canonical.replace(' viewBox="0 0 1280 720"', ''),+ 'root viewBox is required',+ ),+ 'non-finite': (+ canonical.replace('0 0 1280 720', '0 0 NaN 720'),+ 'must contain exactly four SVG numbers',+ ),+ 'nonzero origin': (+ canonical.replace('0 0 1280 720', '10 0 1280 720'),+ 'origin must be "0 0"',+ ),+ 'zero width': (+ canonical.replace('0 0 1280 720', '0 0 0 720'),+ 'width and height must be positive',+ ),+ 'below PowerPoint range': (+ canonical.replace('0 0 1280 720', '0 0 0.4 0.4'),+ "PowerPoint's supported slide range",+ ),+ 'oversized exponent': (+ canonical.replace('0 0 1280 720', '0 0 1e999999 720'),+ "PowerPoint's supported slide range",+ ),+ 'non-SVG root': (+ '<g xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 1280 720"/>',+ 'root element must be <svg>',+ ),+ }+ for name, (content, message) in invalid_cases.items():+ with self.subTest(name=name):+ self._assert_checker_and_exporter_reject(+ content,+ message,+ re.escape(message),+ )++ def test_root_viewbox_matches_spec_lock_and_all_project_pages(self):+ content = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 1280 720"/>'+ )+ mismatched = self._check_with_spec_lock(+ content,+ '## canvas\n- viewBox: 0 0 1024 768\n',+ )+ self.assertTrue(any(+ "spec_lock canvas requires '0 0 1024 768'" in error+ for error in mismatched['errors']+ ))++ invalid_lock = self._check_with_spec_lock(+ content,+ '## canvas\n- viewBox: 0 0 NaN 720\n',+ )+ self.assertTrue(any(+ 'spec_lock canvas viewBox must contain exactly four SVG numbers'+ in error+ for error in invalid_lock['errors']+ ))++ partial_lock = self._check_with_spec_lock(+ content,+ '## colors\n- primary: #000000\n',+ )+ self.assertFalse(any(+ 'canvas section' in error or 'viewBox mismatch' in error+ for error in partial_lock['errors']+ ))++ with tempfile.TemporaryDirectory() as tmp_dir:+ project = Path(tmp_dir)+ output_dir = project / 'svg_output'+ output_dir.mkdir()+ (project / 'spec_lock.md').write_text(+ '## canvas\n- format: PPT 16:9\n',+ encoding='utf-8',+ )+ (output_dir / '01.svg').write_text(content, encoding='utf-8')+ checker = SVGQualityChecker()+ with contextlib.redirect_stdout(io.StringIO()):+ missing_project_lock = checker.check_directory(str(project))+ self.assertTrue(any(+ 'spec_lock.md canvas section must declare viewBox' in error+ for result in missing_project_lock+ for error in result['errors']+ ))++ (project / 'spec_lock.md').write_text(+ '## colors\n- primary: #000000\n',+ encoding='utf-8',+ )+ checker = SVGQualityChecker()+ with contextlib.redirect_stdout(io.StringIO()):+ missing_canvas_section = checker.check_directory(str(project))+ self.assertTrue(any(+ 'spec_lock canvas viewBox is required' in error+ for result in missing_canvas_section+ for error in result['errors']+ ))++ with tempfile.TemporaryDirectory() as tmp_dir:+ output_dir = Path(tmp_dir) / 'svg_output'+ output_dir.mkdir()+ (output_dir / '01.svg').write_text(content, encoding='utf-8')+ (output_dir / '02.svg').write_text(+ content.replace('1280 720', '1280.0 720.0'),+ encoding='utf-8',+ )+ checker = SVGQualityChecker()+ with contextlib.redirect_stdout(io.StringIO()):+ equivalent = checker.check_directory(str(output_dir))+ self.assertFalse(any(+ 'viewBox mismatch' in error+ for result in equivalent+ for error in result['errors']+ ))++ (output_dir / '02.svg').write_text(+ content.replace('1280 720', '1024 768'),+ encoding='utf-8',+ )+ checker = SVGQualityChecker()+ with contextlib.redirect_stdout(io.StringIO()):+ mixed = checker.check_directory(str(output_dir))+ self.assertTrue(any(+ "first SVG 01.svg requires '0 0 1280 720'" in error+ for result in mixed+ for error in result['errors']+ ))++ with tempfile.TemporaryDirectory() as tmp_dir:+ template_dir = Path(tmp_dir)+ (template_dir / 'design_spec.md').write_text(+ '---\nkind: layout\n---\n# Test\n',+ encoding='utf-8',+ )+ (template_dir / '01.svg').write_text(content, encoding='utf-8')+ checker = SVGQualityChecker(template_mode=True)+ with contextlib.redirect_stdout(io.StringIO()):+ missing_template_lock = checker.check_directory(str(template_dir))+ self.assertTrue(any(+ 'design_spec canvas_viewbox viewBox is required' in error+ for result in missing_template_lock+ for error in result['errors']+ ))++ def test_builder_canvas_guard_covers_public_and_internal_svgs(self):+ self.assertIn('ppt43', PACKAGE_CANVAS_FORMATS)+ svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {dims}"/>'+ with tempfile.TemporaryDirectory() as tmp_dir:+ root = Path(tmp_dir)+ public = root / 'public.svg'+ other = root / 'other.svg'+ public.write_text(svg.format(dims='1280 720'), encoding='utf-8')+ other.write_text(svg.format(dims='1024 768'), encoding='utf-8')++ with self.assertRaisesRegex(CanvasContractError, 'other.svg'):+ create_pptx_with_native_svg(+ [public, other],+ root / 'mixed-public.pptx',+ pptx_structure='flat',+ verbose=False,+ )+ with self.assertRaisesRegex(CanvasContractError, 'other.svg'):+ create_pptx_with_native_svg(+ [public],+ root / 'mixed-internal.pptx',+ pptx_structure='structured',+ layout_definition_files=[other],+ verbose=False,+ )+ with self.assertRaisesRegex(CanvasContractError, 'canvas format'):+ resolve_svg_canvas([other], canvas_format='ppt169')++ too_small = root / 'too-small.svg'+ too_small.write_text(svg.format(dims='100 80'), encoding='utf-8')+ with self.assertRaisesRegex(+ CanvasContractError,+ "PowerPoint's supported slide range",+ ):+ resolve_svg_canvas([too_small])++ def test_template_preview_canvas_lock_only_reads_frontmatter(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ spec_path = Path(tmp_dir) / 'design_spec.md'+ spec_path.write_text(+ '---\nkind: layout\n---\n\n```yaml\n'+ 'canvas_viewbox: "0 0 1280 720"\n```\n',+ encoding='utf-8',+ )+ self.assertIsNone(preview_canvas_viewbox(spec_path))++ spec_path.write_text(+ '---\nkind: layout\ncanvas_viewbox: "0 0 1280 720"\n---\n',+ encoding='utf-8',+ )+ self.assertEqual(+ preview_canvas_viewbox(spec_path),+ '0 0 1280 720',+ )++ def test_imported_fractional_root_canvas_round_trips_exact_slide_emu(self):+ with tempfile.TemporaryDirectory() as tmp_dir:+ root = Path(tmp_dir)+ source_path = root / 'source.pptx'+ svg_path = root / 'fractional.svg'+ output_path = root / 'fractional.pptx'+ source_width = 12192001+ source_height = 6858001+ presentation = Presentation()+ presentation.slide_width = Emu(source_width)+ presentation.slide_height = Emu(source_height)+ presentation.slides.add_slide(presentation.slide_layouts[6])+ presentation.save(source_path)++ imported = convert_pptx_to_svg(+ source_path,+ options=ConvertOptions(inheritance_mode='flat'),+ )+ imported_svg = imported.slides[0].svg+ svg_path.write_text(imported_svg, encoding='utf-8')+ imported_root = ET.fromstring(imported_svg)+ imported_viewbox = parse_project_viewbox(+ imported_root.get('viewBox')+ )+ self.assertEqual(+ imported_viewbox.emu_dimensions,+ (source_width, source_height),+ )++ # Keep the historical first four positional arguments covered;+ # new optional contracts must be appended to the public API.+ self.assertTrue(create_pptx_with_native_svg(+ [svg_path],+ output_path,+ None,+ False,+ pptx_structure='flat',+ transition=None,+ enable_notes=False,+ ))+ with zipfile.ZipFile(output_path) as package:+ presentation = ET.fromstring(package.read('ppt/presentation.xml'))+ size = presentation.find(+ '{http://schemas.openxmlformats.org/presentationml/2006/main}sldSz'+ )+ self.assertIsNotNone(size)+ self.assertEqual(+ (int(size.get('cx')), int(size.get('cy'))),+ (source_width, source_height),+ )+def test_top_level_group_ids_are_unique_animation_anchors(self):duplicate = '''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><g id="card"><rect x="10" y="10" width="20" height="20" fill="#000000"/></g>diff --git a/skills/ppt-master/templates/spec_lock_reference.md b/skills/ppt-master/templates/spec_lock_reference.mdindex a78e8f76..c1acac7a 100644--- a/skills/ppt-master/templates/spec_lock_reference.md+++ b/skills/ppt-master/templates/spec_lock_reference.md@@ -4,13 +4,13 @@>> Machine-readable execution contract. Executor MUST `read_file` this before every SVG page. Values not listed here must NOT appear in SVGs. For design narrative (rationale, audience, style), see `design_spec.md`.>-> After SVG generation begins, this is the canonical source for color / font / icon / image values. Modifications should go through `scripts/update_spec.py` to keep this file and generated SVGs in sync.+> After SVG generation begins, this is the canonical source for color / font / icon / image values. Supported color/font modifications should go through `scripts/update_spec.py` to keep this file and generated SVGs in sync. Canvas changes are intentionally not bulk-rewritten by that tool.## canvas- viewBox: 0 0 1280 720- format: PPT 16:9-> Strategist: fill viewBox and format for the chosen canvas. Common values: `0 0 1280 720` (PPT 16:9), `0 0 1024 768` (PPT 4:3), `0 0 1242 1660` (Xiaohongshu), `0 0 1080 1080` (WeChat Moments), `0 0 1080 1920` (Story).+> Strategist: fill viewBox and format for the chosen canvas. New authoring uses the canonical `0 0 W H` spelling with positive integer pixels. Every generated page and internal Layout prototype must match this numeric canvas. Common values: `0 0 1280 720` (PPT 16:9), `0 0 1024 768` (PPT 4:3), `0 0 1242 1660` (Xiaohongshu), `0 0 1080 1080` (WeChat Moments), `0 0 1080 1920` (Story). Changing the canvas after authoring starts requires re-authoring and re-validating affected SVGs; `update_spec.py` does not propagate canvas changes.## mode- mode: pyramid