Skip to content

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(pptx): preserve picture geometry and harden export checks

hugohe387ce7299b30c
diff --git a/docs/technical-design.md b/docs/technical-design.md
index 8900e59d..323d9ad9 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -449,7 +449,7 @@ Several architectural decisions shape this phase:
## Image-Text Layout: Primary Structures + Modifier Layers
-The catalog of *how an image is placed on a slide* (full vocabulary in [`references/image-layout-patterns.md`](../skills/ppt-master/references/image-layout-patterns.md)) splits 81 stable-id techniques into two layers that compose freely:
+The catalog of *how an image is placed on a slide* (full vocabulary in [`references/image-layout-patterns.md`](../skills/ppt-master/references/image-layout-patterns.md)) splits 99 stable-id techniques into two layers that compose freely:
- **Primary Structures** (container layouts / image-as-canvas + native overlay / multi-image compositions) — the page's bones. One or more per page; cross-Primary combinations like *side-by-side comparison + image-as-canvas annotation* are legitimate.
- **Modifier Layers** (non-rectangular clips / overlays & masks / texture / special techniques) — finish. Any number per page, stacked on top of the Primary.
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index caab1afc..66ef6a58 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -443,7 +443,7 @@ Strategist 阶段产出两份看起来冗余但服务不同对象的产物:
## 图文版式:Primary 主结构 + Modifier 修饰层
-「图片**怎么放上幻灯片**」的词表(完整词汇在 [`references/image-layout-patterns.md`](../../skills/ppt-master/references/image-layout-patterns.md))把 81 条稳定编号技法拆成两层、自由组合:
+「图片**怎么放上幻灯片**」的词表(完整词汇在 [`references/image-layout-patterns.md`](../../skills/ppt-master/references/image-layout-patterns.md))把 99 条稳定编号技法拆成两层、自由组合:
- **Primary 主结构**(容器布局 / 图作画布 + 原生覆盖 / 多图组合)—— 页面的骨架。一页可一个也可多个;跨 Primary 的组合,如「侧边对比 + 图作画布的注解卡」,是合规的。
- **Modifier 修饰层**(非矩形裁剪 / 遮罩与叠加 / 纹理 / 特殊技法)—— 装饰层。一页可叠任意多个,附着在 Primary 之上。
diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.md
index 21e9cb62..b40e2805 100644
--- a/skills/ppt-master/scripts/docs/svg-pipeline.md
+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md
@@ -335,8 +335,9 @@ Behavior:
structured-package validation, transitions, and animations are enforced before the
builder publishes the PPTX and are reported as `enforced-at-build`, not as repeated
postflight checks.
-- `font_portability` warns only when a complete font stack contains generic CSS families
- and no concrete family name. A recommended stack such as
+- `font_portability` warns when a complete font stack has no concrete family or when
+ the converter resolves its Latin / East Asian role to a typeface that normally
+ requires a custom installation. A recommended stack such as
`"Microsoft YaHei", Arial, sans-serif` does not warn merely because it ends with a
generic fallback.
- Paragraph merging is enabled by default and trades some SVG line-layout fidelity for PowerPoint editability:
diff --git a/skills/ppt-master/scripts/image_backends/backend_common.py b/skills/ppt-master/scripts/image_backends/backend_common.py
index f34a47c9..dcf49a1f 100644
--- a/skills/ppt-master/scripts/image_backends/backend_common.py
+++ b/skills/ppt-master/scripts/image_backends/backend_common.py
@@ -152,6 +152,27 @@ def save_image_bytes(image_bytes: bytes, path: str, content_type: str = None) ->
return path
+def validate_image_file(path: str) -> str:
+ """Require an existing regular file that Pillow can read as an image."""
+ image_path = Path(path)
+ if not image_path.exists():
+ raise RuntimeError(f"Image output path does not exist: {path}")
+ if not image_path.is_file():
+ raise RuntimeError(f"Image output path is not a file: {path}")
+ if not HAS_PIL:
+ raise RuntimeError(
+ "Pillow is required to verify generated images. "
+ "Install it with: pip install Pillow"
+ )
+
+ try:
+ with PILImage.open(image_path) as image:
+ image.verify()
+ except (OSError, ValueError, SyntaxError) as exc:
+ raise RuntimeError(f"Image output is not readable: {path}: {exc}") from exc
+ return str(image_path)
+
+
def report_resolution(path: str) -> None:
"""Try to report image resolution using PIL."""
if HAS_PIL:
diff --git a/skills/ppt-master/scripts/image_gen.py b/skills/ppt-master/scripts/image_gen.py
index 3645cbf8..17fe5f2f 100644
--- a/skills/ppt-master/scripts/image_gen.py
+++ b/skills/ppt-master/scripts/image_gen.py
@@ -428,6 +428,7 @@ def load_manifest(path: str) -> dict:
raise ValueError(f"{path}: 'items' must be a non-empty array")
seen_filenames: set[str] = set()
+ seen_stems: set[str] = set()
for i, item in enumerate(items):
prefix = f"{path}: items[{i}]"
if not isinstance(item, dict):
@@ -445,9 +446,30 @@ def load_manifest(path: str) -> dict:
f"Valid: {sorted(VALID_STATUSES)}"
)
fname = item["filename"]
+ filename_path = Path(fname)
+ if (
+ filename_path.is_absolute()
+ or filename_path.name != fname
+ or "/" in fname
+ or "\\" in fname
+ or fname in {".", ".."}
+ ):
+ raise ValueError(
+ f"{prefix} field 'filename' must be one basename, got '{fname}'"
+ )
+ if not filename_path.suffix:
+ raise ValueError(
+ f"{prefix} field 'filename' must include an extension, got '{fname}'"
+ )
if fname in seen_filenames:
raise ValueError(f"{prefix} duplicate filename '{fname}'")
seen_filenames.add(fname)
+ stem = filename_path.stem
+ if stem in seen_stems:
+ raise ValueError(
+ f"{prefix} duplicate filename stem '{stem}' would reuse backend output"
+ )
+ seen_stems.add(stem)
return data
@@ -473,6 +495,29 @@ def save_manifest(path: str, data: dict) -> None:
raise
+def _materialize_manifest_image(saved_path: str, target_path: Path) -> str:
+ """Validate backend output and place it at the manifest's exact target path."""
+ from image_backends.backend_common import (
+ save_image_bytes,
+ validate_image_file,
+ )
+
+ source_path = Path(saved_path)
+ validate_image_file(str(source_path))
+
+ if source_path.resolve() != target_path.resolve():
+ try:
+ image_bytes = source_path.read_bytes()
+ except OSError as exc:
+ raise RuntimeError(
+ f"Could not read image output {source_path}: {exc}"
+ ) from exc
+ save_image_bytes(image_bytes, str(target_path))
+
+ validate_image_file(str(target_path))
+ return str(target_path)
+
+
def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
initial_concurrency: int,
image_size: str,
@@ -532,6 +577,10 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
filename=Path(item["filename"]).stem,
model=item.get("model", model),
)
+ saved_path = _materialize_manifest_image(
+ saved_path,
+ Path(output_dir) / item["filename"],
+ )
return idx, saved_path, None
except Exception as exc: # noqa: BLE001 — backend raises arbitrary types
return idx, None, exc
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.py
index 7aad5271..023a8a59 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
@@ -892,6 +892,8 @@ def _clip_blip_image(image_xml: str, geom: GeomResult | None,
"""Clip image fills to the owning shape geometry when it is not a plain rect."""
if geom is None or geom.tag == "line":
return image_xml
+ if geom.attrs.get("data-pptx-prst") == "rect":
+ return image_xml
if geom.tag == "rect" and not geom.attrs.get("rx") and not geom.attrs.get("ry"):
return image_xml
@@ -919,6 +921,8 @@ def _inject_clip_path(image_xml: str, clip_id: str) -> str:
# ---------------------------------------------------------------------------
def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
+ sp_pr = node.xml.find("p:spPr", NS)
+ geom = _resolve_geometry(node, sp_pr)
result = convert_picture(
node.xml, node.xfrm, ctx.slide_part, ctx.pkg,
media_subdir=ctx.media_subdir,
@@ -929,12 +933,13 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)
return ""
ctx.media.update(result.media)
effect_metadata = unsupported_target_effect_metadata(
- node.xml.find("p:spPr", NS),
+ sp_pr,
"picture",
)
_diagnose_unsupported_effect(ctx, effect_metadata)
+ clipped_svg = _clip_blip_image(result.svg, geom, ctx)
picture_svg = _inject_root_svg_attrs(
- result.svg,
+ clipped_svg,
{**_object_metadata(node, ctx), **effect_metadata},
)
return _wrap_shape_group(
diff --git a/skills/ppt-master/scripts/prompt_audit.py b/skills/ppt-master/scripts/prompt_audit.py
index 7ea7f2b0..7febce54 100644
--- a/skills/ppt-master/scripts/prompt_audit.py
+++ b/skills/ppt-master/scripts/prompt_audit.py
@@ -991,6 +991,21 @@ def audit_authority_graph(
return normalized, cycles, findings
+def _parse_numbered_markdown_ids(raw_ids: str) -> list[int]:
+ """Expand one numbered-Markdown heading expression into its stable ids."""
+ ids: list[int] = []
+ for part in re.split(r"\s*·\s*", raw_ids):
+ match = re.fullmatch(r"(\d+)(?:\s*[-–]\s*(\d+))?", part)
+ if match is None:
+ raise AuditError(f"Invalid numbered Markdown id expression: {raw_ids!r}")
+ start = int(match.group(1))
+ end = int(match.group(2) or start)
+ if end < start:
+ raise AuditError(f"Descending numbered Markdown id range: {raw_ids!r}")
+ ids.extend(range(start, end + 1))
+ return ids
+
+
def _registry_ids(root: Path, config: dict[str, Any]) -> tuple[set[Any], str, list[Any]]:
kind = config.get("kind")
source = config.get("source")
@@ -1005,9 +1020,15 @@ def _registry_ids(root: Path, config: dict[str, Any]) -> tuple[set[Any], str, li
regex = re.compile(pattern, re.MULTILINE)
except re.error as exc:
raise AuditError(f"Invalid registry entry_pattern: {exc}") from exc
+ id_group = "ids" if "ids" in regex.groupindex else "id"
+ if id_group not in regex.groupindex:
+ raise AuditError(
+ f"Registry {config.get('name')} entry_pattern needs an id or ids group"
+ )
matched_ids = [
- int(match.group("id"))
+ item
for match in regex.finditer(_read_utf8(root / source))
+ for item in _parse_numbered_markdown_ids(match.group(id_group))
]
duplicates = sorted(
item for item, count in Counter(matched_ids).items() if count > 1
@@ -1064,6 +1085,20 @@ def _registry_count_claims(paragraph: Paragraph, nouns: list[str]) -> list[int]:
return claims
+def _is_comprehensive_registry_reference(paragraph: Paragraph, nouns: list[str]) -> bool:
+ """Return whether a block claims complete registry coverage."""
+ scope_nouns = sorted(set(nouns + ["catalog", "registry", "file"]))
+ scope_pattern = "|".join(re.escape(noun) for noun in scope_nouns)
+ return re.search(
+ rf"\b(?:all|every|entire|full)\b(?:\W+\w+){{0,4}}\W+"
+ rf"(?:{scope_pattern})\b|"
+ rf"\b(?:{scope_pattern})\b(?:\W+\w+){{0,4}}\W+"
+ rf"\b(?:all|every|entire|full)\b|"
+ r"\bfile is split\b",
+ paragraph.normalized,
+ ) is not None
+
+
def audit_registries(
root: Path,
configs: list[dict[str, Any]],
@@ -1216,33 +1251,25 @@ def audit_registries(
)
)
- ranges = sorted(
+ ranges = [
tuple(sorted((int(match.group(1)), int(match.group(2)))))
for match in range_pattern.finditer(paragraph.text)
- )
- comprehensive = re.search(
- r"\b(all|every|entire|full|file is split)\b",
- paragraph.normalized,
- )
+ ]
+ comprehensive = _is_comprehensive_registry_reference(paragraph, nouns)
if ranges and comprehensive:
- merged: list[list[int]] = []
+ declared_ids = {
+ int(match.group(1))
+ for match in id_pattern.finditer(paragraph.text)
+ }
for start, end in ranges:
- if not merged or start > merged[-1][1] + 1:
- merged.append([start, end])
- else:
- merged[-1][1] = max(merged[-1][1], end)
- declared_count = sum(end - start + 1 for start, end in merged)
- covers_ids = all(
- any(start <= item <= end for start, end in merged)
- for item in numeric_ids
- )
- if declared_count != len(numeric_ids) or not covers_ids:
+ declared_ids.update(range(start, end + 1))
+ if declared_ids != numeric_ids:
findings.append(
Finding(
severity="error",
code="REGISTRY_RANGE_MISMATCH",
message=(
- f"{name} comprehensive ranges cover {declared_count} ids; "
+ f"{name} comprehensive ranges cover {len(declared_ids)} ids; "
f"registry contains {len(numeric_ids)}"
),
path=paragraph.path,
diff --git a/skills/ppt-master/scripts/prompt_audit_manifest.json b/skills/ppt-master/scripts/prompt_audit_manifest.json
index 82dc777c..8159881a 100644
--- a/skills/ppt-master/scripts/prompt_audit_manifest.json
+++ b/skills/ppt-master/scripts/prompt_audit_manifest.json
@@ -934,7 +934,7 @@
"name": "image-layout-patterns",
"kind": "numbered_markdown",
"source": "skills/ppt-master/references/image-layout-patterns.md",
- "entry_pattern": "^(?P<id>\\d+)\\.\\s+\\*\\*",
+ "entry_pattern": "^(?P<ids>\\d+(?:\\s*(?:[-–]|·)\\s*\\d+)*)\\.\\s+\\*\\*",
"reference_terms": [
"image-layout-patterns",
"image-text layout patterns"
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 2640eb8e..ea69708a 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -101,8 +101,6 @@ try:
matrix_multiply as _matrix_multiply,
noncanonical_stroke_dash_numbers as _noncanonical_stroke_dash_numbers,
noncanonical_transform_numbers as _noncanonical_transform_numbers,
- parse_transform_matrix as _parse_transform_matrix,
- parse_font_family as _parse_export_font_family,
parse_inline_style as _parse_inline_style,
parse_project_geometry_length as _parse_project_geometry_length,
parse_project_image_aspect_ratio as _parse_project_image_aspect_ratio,
@@ -112,6 +110,7 @@ try:
parse_project_stroke_enum as _parse_project_stroke_enum,
parse_svg_color as _parse_export_color,
parse_svg_length as _parse_export_length,
+ parse_transform_matrix as _parse_transform_matrix,
project_definition_errors as _project_definition_errors,
project_filter_errors as _project_filter_errors,
project_gradient_errors as _project_gradient_errors,
@@ -124,6 +123,7 @@ try:
project_transform_errors as _project_transform_errors,
rect_to_dml_xfrm as _rect_to_dml_xfrm,
transform_point as _transform_point,
+ unsafe_exported_font_faces as _unsafe_exported_font_faces,
validate_dml_shape_matrix as _validate_dml_shape_matrix,
)
except ImportError:
@@ -150,8 +150,6 @@ except ImportError:
_matrix_multiply = None
_noncanonical_stroke_dash_numbers = None
_noncanonical_transform_numbers = None
- _parse_transform_matrix = None
- _parse_export_font_family = None
_parse_inline_style = None
_parse_project_geometry_length = None
_parse_project_image_aspect_ratio = None
@@ -161,6 +159,7 @@ except ImportError:
_parse_project_stroke_enum = None
_parse_export_color = None
_parse_export_length = None
+ _parse_transform_matrix = None
_project_definition_errors = None
_project_filter_errors = None
_project_gradient_errors = None
@@ -173,6 +172,7 @@ except ImportError:
_project_transform_errors = None
_rect_to_dml_xfrm = None
_transform_point = None
+ _unsafe_exported_font_faces = None
_validate_dml_shape_matrix = None
try:
@@ -870,21 +870,6 @@ def _normalize_hex_rgb(value: str) -> str | None:
return color[:6].upper()
-# Fonts that survive direct PPTX typeface assignment on a typical Windows /
-# macOS viewer without requiring a custom install. Keep this aligned with
-# strategist.md §g and drawingml/utils.py FONT_FALLBACK_WIN.
-PPT_SAFE_FONTS = {
- 'microsoft yahei', 'simhei', 'simsun', 'kaiti', 'fangsong',
- 'dengxian', 'microsoft jhenghei',
- 'pingfang sc', 'heiti sc', 'songti sc', 'stsong',
- 'arial', 'arial black', 'calibri', 'segoe ui', 'verdana',
- 'helvetica', 'helvetica neue', 'tahoma', 'trebuchet ms',
- 'times new roman', 'times', 'georgia', 'cambria', 'palatino',
- 'garamond', 'book antiqua',
- 'consolas', 'courier new', 'menlo', 'monaco',
- 'impact',
-}
-
# Cheap numeric envelope for font-size role enforcement. Semantic role assignment
# is prompt-owned; Checker only verifies that a used value is close to at least
# one declared size anchor.
@@ -2454,18 +2439,16 @@ class SVGQualityChecker:
return
result['info']['fonts'] = sorted(set(font_matches))
- if _parse_export_font_family is None:
+ if _unsafe_exported_font_faces is None:
result['warnings'].append(
"Unable to import svg_to_pptx font resolver; skipped exported-font safety check"
)
return
for font_family in font_matches:
- exported = _parse_export_font_family(font_family)
unsafe = [
f"{role}={family}"
- for role, family in exported.items()
- if family.strip().lower() not in PPT_SAFE_FONTS
+ for role, family in _unsafe_exported_font_faces(font_family).items()
]
if unsafe:
result['warnings'].append(
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
index 7fed90f7..c0eb7382 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -147,6 +147,21 @@ _SERIF_LATIN = {
'Book Antiqua', 'Cambria', 'SimSun', 'Liberation Serif', 'DejaVu Serif',
}
+# Fonts that survive direct PPTX typeface assignment on a typical Windows /
+# macOS viewer without requiring a custom install. Keep this aligned with
+# strategist.md §g and FONT_FALLBACK_WIN above.
+PPT_SAFE_FONTS = frozenset({
+ 'microsoft yahei', 'simhei', 'simsun', 'kaiti', 'fangsong',
+ 'dengxian', 'microsoft jhenghei',
+ 'pingfang sc', 'heiti sc', 'songti sc', 'stsong',
+ 'arial', 'arial black', 'calibri', 'segoe ui', 'verdana',
+ 'helvetica', 'helvetica neue', 'tahoma', 'trebuchet ms',
+ 'times new roman', 'times', 'georgia', 'cambria', 'palatino',
+ 'garamond', 'book antiqua',
+ 'consolas', 'courier new', 'menlo', 'monaco',
+ 'impact',
+})
+
# Parsed SVG stroke-dasharray values -> DrawingML prstDash
DASH_PRESETS = {
(4.0, 4.0): 'dash',
@@ -2810,6 +2825,15 @@ def parse_font_family(font_family_str: str) -> dict[str, str]:
return {'latin': final_latin, 'ea': ea_font}
+def unsafe_exported_font_faces(font_family_str: str) -> dict[str, str]:
+ """Return resolved PPTX typefaces that require a custom installation."""
+ return {
+ role: family
+ for role, family in parse_font_family(font_family_str).items()
+ if family.strip().lower() not in PPT_SAFE_FONTS
+ }
+
+
def is_cjk_char(ch: str) -> bool:
"""Check if a character is CJK (Chinese/Japanese/Korean)."""
cp = ord(ch)
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.py
index b296d732..dcb1674f 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
@@ -59,6 +59,7 @@ from ..drawingml.theme_fonts import (
load_master_text_style_spec,
load_theme_font_spec,
)
+from ..drawingml.utils import unsafe_exported_font_faces
from .narration import NARRATION_EXTENSIONS, find_narration_files, probe_audio_duration
from .template_structure import (
TemplateStructureError,
@@ -211,11 +212,21 @@ def _source_resource_audit(svg_files: list[Path]) -> dict[str, object]:
for stack in font_stacks
if _font_stack_is_generic_only(stack)
})
+ unsafe_font_faces = [
+ {
+ 'stack': stack,
+ 'role': role,
+ 'typeface': typeface,
+ }
+ for stack in sorted(font_stacks)
+ for role, typeface in unsafe_exported_font_faces(stack).items()
+ ]
return {
'unresolved_template_tokens': placeholders,
'fonts': {
'stacks': sorted(font_stacks),
'generic_only_stacks': generic_only_font_stacks,
+ 'unsafe_exported_faces': unsafe_font_faces,
},
'images': {
**image_counts,
@@ -298,6 +309,7 @@ def _postflight_warning_summaries(
unresolved_token_count: int,
external_image_count: int,
generic_font_stack_count: int,
+ unsafe_font_face_count: int,
) -> tuple[str, ...]:
"""Return stable warning summaries for the terminal receipt."""
warnings: list[str] = []
@@ -311,6 +323,8 @@ def _postflight_warning_summaries(
warnings.append(f'external_images={external_image_count}')
if generic_font_stack_count:
warnings.append(f'generic_only_font_stacks={generic_font_stack_count}')
+ if unsafe_font_face_count:
+ warnings.append(f'unsafe_exported_font_faces={unsafe_font_face_count}')
return tuple(warnings)
@@ -370,12 +384,14 @@ def _write_postflight_report(
unresolved_tokens = source_audit['unresolved_template_tokens']
external_image_count = source_audit['images']['external']
generic_only_font_stacks = source_audit['fonts']['generic_only_stacks']
+ unsafe_font_faces = source_audit['fonts']['unsafe_exported_faces']
if quality_gate == 'failed':
report_status = 'failed'
elif (
not unresolved_tokens
and not external_image_count
and not generic_only_font_stacks
+ and not unsafe_font_faces
and not introduced_warning_count
and quality_gate == 'passed'
):
@@ -420,7 +436,9 @@ def _write_postflight_report(
'passed' if not external_image_count else 'warning'
),
'font_portability': (
- 'passed' if not generic_only_font_stacks else 'warning'
+ 'passed'
+ if not generic_only_font_stacks and not unsafe_font_faces
+ else 'warning'
),
},
'quality': quality,
@@ -443,6 +461,7 @@ def _write_postflight_report(
unresolved_token_count=len(unresolved_tokens),
external_image_count=external_image_count,
generic_font_stack_count=len(generic_only_font_stacks),
+ unsafe_font_face_count=len(unsafe_font_faces),
)
return _PostflightReceipt(
output_path=output_path,