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-roundtrip): harden native structure and object reconstruction

hugohe3235ed064407b
diff --git a/docs/technical-design.md b/docs/technical-design.md
index fd810399..6ca5404c 100644
--- a/docs/technical-design.md
+++ b/docs/technical-design.md
@@ -427,9 +427,9 @@ These direct routes share some analysis primitives with the main pipeline, espec
**Why compatibility fallback belongs to the SVG snapshot path, not native shapes.** Native PPTX export translates supported SVG elements into DrawingML shapes and explicitly disables PNG+SVG compatibility mode in native-shapes mode. The PNG fallback is used only by the legacy SVG-image path (`--svg-snapshot` / `--only legacy`) when a renderer is available, because that path embeds SVG media that older Office builds may not display. Legacy compatibility is therefore an optional snapshot deliverable, not a fallback bundled inside the primary editable native deck.
-**Why the default native deck has a baseline master, not inferred templates.** `svg_to_pptx.py` keeps the actual blank slide layout relationship from the base package and defaults to `--pptx-structure baseline`. Baseline promotes only low-risk shared structure: identical slide backgrounds, plus repeated top-level SVG chrome groups whose ids clearly say `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber` and whose generated OOXML is identical across slides sharing the same master. Image relationships for promoted chrome are copied to the slide master. This gives ordinary decks real master/layout structure without guessing reusable layouts or placeholders from visual similarity.
+**Why the default native deck has a baseline master, not inferred templates.** `svg_to_pptx.py` keeps the actual blank slide layout relationship from the base package and defaults to `--pptx-structure baseline`. Baseline promotes only low-risk shared structure: identical slide backgrounds, plus a common leading prefix of repeated top-level SVG chrome whose exact id tokens say `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber`. Chrome promotion also requires identical generated OOXML, no slide-timing reference, and the same leading z-order across every slide sharing the master; overlay chrome stays slide-local. Image relationships for promoted chrome are copied to the slide master. This gives ordinary decks real master/layout structure without guessing reusable layouts or placeholders from visual similarity.
-**Why native-object round-trip uses markers, not automatic object replacement.** PPTX intake can emit visible SVG fallback plus `data-pptx-native` metadata for supported tables and classic chart cache data. The default export still consumes the fallback as regular DrawingML shapes; only `--native-objects` activates editable PowerPoint tables/charts. Unsupported cases such as merged tables, ChartEx, 3D charts, combo charts, or cache-missing charts keep the preview and carry an explicit unsupported status instead of pretending to round-trip.
+**Why native-object reconstruction uses markers, not automatic object replacement.** The standalone `pptx_to_svg.py` importer can emit SVG fallback content plus `data-pptx-native` metadata for supported unmerged tables and conservative classic-chart caches. It retains source table-style inheritance, supported solid cell fills/basic text formatting, chart title/legend/axis titles, and plot-level data-label flags for area/bar/column/line charts when the current schema can represent them. The default export still consumes fallback children as regular DrawingML shapes; only `--native-objects` activates editable PowerPoint tables/charts. Unsupported cases — including merged tables, direct cell borders/non-solid fills/mixed rich text, ChartEx, transformed/3D/combo charts, unsupported data-label scopes/types, custom axis semantics, trendlines/error bars, unsupported subtype options, sparse or non-finite caches, and date/formatted category axes — keep a baked preview when one exists (otherwise an explicit placeholder) and carry `data-pptx-native-status`. The quality checker and native-object export report those fallback-only objects as warnings. This importer/exporter pairing is a reconstruction aid, not a preservation-route substitute for `template-fill-pptx` or `native-enhance-pptx`.
---
diff --git a/docs/zh/technical-design.md b/docs/zh/technical-design.md
index 46208b28..caea29af 100644
--- a/docs/zh/technical-design.md
+++ b/docs/zh/technical-design.md
@@ -427,6 +427,10 @@ PowerPoint 的 DrawingML 是 SVG 表达力的严格子集。Executor 在一份
**为什么兼容 fallback 属于 SVG snapshot 路径,而不是 native shapes。** Native PPTX 导出会把受支持的 SVG 元素翻译成 DrawingML 形状,并在 native-shapes 模式下显式关闭 PNG+SVG 兼容模式。PNG fallback 只在 legacy SVG-image 路径(`--svg-snapshot` / `--only legacy`)且本地 renderer 可用时使用,因为那条路径嵌入的是旧版 Office 可能无法显示的 SVG media。因此,旧版兼容是一份可选 snapshot 交付物,不是捆在主 editable native deck 里的兜底层。
+**为什么默认 native deck 使用基线母版,而不推断模板。** `svg_to_pptx.py` 会保留基础 package 中空白版式的真实关系,并默认使用 `--pptx-structure baseline`。Baseline 只提升低风险共享结构:完全一致的页面背景,以及各页共同位于 shape 序列开头(视觉后层)、且 id 精确 token 为 `logo`、`footer`、`header`、`watermark`、`chrome`、`pageNumber` 或 `slideNumber` 的重复 SVG chrome。Chrome 还必须在共享同一母版的所有页面上生成完全一致的 OOXML、没有被页面动画引用,并保持相同的前置 z-order;覆盖在正文之上的 chrome 继续留在 slide 本地。被提升 chrome 的图片关系会复制到 slide master。这样普通 deck 能获得真实的 master/layout 结构,同时不根据视觉相似度猜测可复用版式或占位符。
+
+**为什么原生对象重建使用 marker,而不是自动替换对象。** 独立的 `pptx_to_svg.py` 导入器会为受支持的未合并表格和保守 classic-chart cache 输出 SVG fallback,并附加 `data-pptx-native` 元数据;当现有 schema 能表达时,还会保留源表格样式继承、受支持的单元格纯色填充 / 基础文字格式,以及图表标题、图例、坐标轴标题和面积图 / 条形图 / 柱形图 / 折线图的 plot 级数据标签开关。默认导出仍把 fallback 子元素当普通 DrawingML shape 处理;只有 `--native-objects` 才会启用可编辑的 PowerPoint 表格 / 图表。合并单元格、直接边框 / 非纯色填充 / 混合富文本、ChartEx、带变换 / 3D / 组合图表、不受支持的数据标签作用域或类型、自定义坐标轴语义、趋势线 / 误差线、不受支持的子类型参数、稀疏或非有限 cache、日期 / 格式化类别轴等不支持场景,会在有 baked preview 时保留预览,否则给出明确占位符,并写入 `data-pptx-native-status`。质量检查器和 native-object 导出会把这些 fallback-only 对象报告为 warning。这对 importer/exporter 是重建辅助能力,不能替代 `template-fill-pptx` 或 `native-enhance-pptx` 的保留型路线。
+
---
## 动画与转场模型
diff --git a/skills/ppt-master/SKILL.md b/skills/ppt-master/SKILL.md
index 69c3a8e2..59409b5f 100644
--- a/skills/ppt-master/SKILL.md
+++ b/skills/ppt-master/SKILL.md
@@ -672,13 +672,14 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> `--pptx-structure baseline`: the package keeps the real slide master/layout
> relationship from the base deck and promotes identical native slide
> backgrounds into the slide master, so ordinary decks do not repeat safe shared
-> background fills on every slide. Baseline also promotes repeated top-level SVG
-> elements whose `id` clearly marks page chrome (`logo`, `footer`, `header`,
-> `watermark`, `chrome`, `pageNumber` / `slideNumber`) when the generated OOXML
-> is identical on every slide sharing the same master; image relationships are
-> copied to the master. Add `--pptx-structure flat` only for
-> debugging/comparison when every background and chrome element must remain
-> slide-local.
+> background fills on every slide. Baseline may also promote a shared **leading**
+> prefix of top-level SVG elements whose exact id tokens mark page chrome
+> (`logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber` /
+> `slideNumber`). Promotion requires identical generated OOXML on every slide
+> sharing the master, no slide-timing reference, and z-order safety; overlay
+> chrome stays slide-local. Image relationships for promoted chrome are copied to
+> the master. Add `--pptx-structure flat` only for debugging/comparison when all
+> generated backgrounds and chrome must remain slide-local.
> **Paragraph editability vs line fidelity** — by default, mergeable dy-stacked
> paragraph blocks collapse into one editable PowerPoint text frame with multiple
@@ -695,7 +696,10 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>
> PowerPoint-editable native tables/charts and accepts that those objects may
> render differently across PowerPoint / Keynote / LibreOffice / WPS. Without
> the flag, marked groups export through their SVG fallback children like
-> ordinary SVG content.
+> ordinary SVG content. Imported objects that carry
+> `data-pptx-native-status` are fallback-only; the quality checker and
+> `--native-objects` export surface their reason as warnings rather than silently
+> claiming editability.
**Optional animation flags** (page transitions are on by default; per-element entrance is off by default — turn it on only when the user asks for it):
- `-t <effect>` — page transition. Default `fade`. Options: `fade` / `push` / `wipe` / `split` / `strips` / `cover` / `random` / `none`.
diff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.md
index a3d9fa9a..2b4a9eee 100644
--- a/skills/ppt-master/scripts/README.md
+++ b/skills/ppt-master/scripts/README.md
@@ -43,7 +43,7 @@ python3 scripts/update_repo.py
| Area | Primary scripts | Documentation |
|------|-----------------|---------------|
-| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py` | [docs/conversion.md](./docs/conversion.md) |
+| Conversion | `source_to_md.py`, `source_to_md/pdf_to_md.py`, `source_to_md/doc_to_md.py`, `source_to_md/excel_to_md.py`, `source_to_md/ppt_to_md.py`, `source_to_md/web_to_md.py`, `pptx_intake.py`, `pptx_to_svg.py` | [docs/conversion.md](./docs/conversion.md) |
| Project management | `project_manager.py`, `batch_validate.py`, `generate_examples_index.py`, `error_helper.py`, `pptx_template_import.py`, `template_fill_pptx.py`, `native_enhance_pptx.py` | [docs/project.md](./docs/project.md) |
| SVG pipeline | `finalize_svg.py`, `svg_to_pptx.py`, `total_md_split.py`, `svg_quality_checker.py`, `extract_svg_assets.py`, `animation_config.py`, `notes_to_audio.py` | [docs/svg-pipeline.md](./docs/svg-pipeline.md) |
| Spec maintenance | `update_spec.py` | [docs/update_spec.md](./docs/update_spec.md) |
@@ -62,6 +62,7 @@ python3 scripts/source_to_md/ppt_to_md.py <deck.pptx>
python3 scripts/source_to_md/doc_to_md.py <file.docx>
python3 scripts/source_to_md/excel_to_md.py <workbook.xlsx>
python3 scripts/source_to_md/web_to_md.py <url>
+python3 scripts/pptx_to_svg.py <deck.pptx> -o <output_dir> # reconstruction/reference SVG import
```
Project setup:
@@ -115,7 +116,9 @@ python3 scripts/svg_to_pptx.py <project_path>
`finalize_svg.py` optimizes raster images by default using `2x` display pixels and max `2560px`. Native `svg_to_pptx.py` defaults to `--image-sizing cap`: only oversized full source images are reduced to max `2560px`, so later PowerPoint resizing keeps more image detail. Use `svg_to_pptx.py --image-sizing display --image-scale 2` only for aggressive size reduction, or `--no-image-optimize` when the native PPTX must embed original image bytes.
-Native `svg_to_pptx.py` also defaults to `--pptx-structure baseline`: the generated deck keeps a standard master/layout relationship and promotes identical native slide backgrounds into the slide master. Repeated top-level SVG elements with chrome-oriented ids such as `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber` are also promoted when their generated OOXML is identical on every slide sharing a master; image relationships are copied to the master. Use `--pptx-structure flat` only when debugging or comparing fully slide-local output.
+Native `svg_to_pptx.py` also defaults to `--pptx-structure baseline`: the generated deck keeps a standard master/layout relationship and promotes identical native slide backgrounds into the slide master. A shared leading prefix of top-level SVG elements with exact chrome id tokens such as `logo`, `footer`, `header`, `watermark`, `chrome`, `pageNumber`, or `slideNumber` may also be promoted when its generated OOXML is identical, it is not referenced by slide timing, and moving it behind slide-local content preserves z-order; image relationships are copied to the master. Use `--pptx-structure flat` when all generated backgrounds and chrome must remain slide-local for debugging or comparison.
+
+`pptx_to_svg.py` annotates supported unmerged tables and conservative classic-chart caches with `data-pptx-native` metadata. Source table-style inheritance, supported solid cell fills/basic text formatting, chart title/legend/axis titles, and plot-level data-label flags for area/bar/column/line charts are retained when the current schema can represent them. Tables with direct borders, non-solid fills, or mixed rich-text formatting remain fallback-only, as do charts with unsupported label scopes/types, custom axis semantics, trendlines/error bars, or subtype options. Unsupported objects keep their SVG preview (or an explicit placeholder when the source has no baked preview) and carry `data-pptx-native-status`; `svg_quality_checker.py` and `svg_to_pptx.py --native-objects` report those fallback-only objects as warnings.
Image generation:
@@ -139,7 +142,7 @@ python3 scripts/update_repo.py --skip-pip
- Keep one user-facing entry point per workflow at the top level of `scripts/`
- Move provider-specific or helper internals into subdirectories
- Prefer the unified entry points `project_manager.py`, `finalize_svg.py`, and `image_gen.py`
-- Prefer `svg_final/` over `svg_output/` when exporting
+- Use `svg_output/` for native export and `svg_final/` for SVG snapshot/preview export
## Related Docs
diff --git a/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py
index 8bff867a..c0304fb5 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py
@@ -7,13 +7,14 @@ when the chart XML cache can be mapped to the current native chart schema.
from __future__ import annotations
+import math
from dataclasses import dataclass
from typing import Any
from xml.etree import ElementTree as ET
-from svg_to_pptx.native_objects.chart_data import _chart_data
+from svg_to_pptx.native_objects.chart_data import _chart_data, _data_label_position
-from .emu_units import NS, Xfrm
+from .emu_units import NS, Xfrm, ooxml_bool
from .ooxml_loader import OoxmlPackage, PartRef
@@ -58,6 +59,8 @@ def extract_native_chart_payload(
return ChartResult(native_status="unsupported-chartex")
if uri != CHART_URI:
return ChartResult(native_status="unsupported-chart-uri")
+ if xfrm.rot or xfrm.flip_h or xfrm.flip_v:
+ return ChartResult(native_status="unsupported-native-transform")
chart_ref = graphic_data.find("c:chart", C_NS)
if chart_ref is None:
@@ -99,14 +102,16 @@ def _payload_from_chart_xml(chart_root: ET.Element, xfrm: Xfrm) -> dict[str, Any
raise _UnsupportedChart("unsupported-chart-plot")
if len(chart_nodes) > 1:
raise _UnsupportedChart("unsupported-combo-chart")
+ if plot_area.find("c:dateAx", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-date-axis")
chart = chart_nodes[0]
chart_tag = _local_name(chart.tag)
if chart_tag in {"area3DChart", "bar3DChart", "line3DChart", "pie3DChart", "surface3DChart"}:
raise _UnsupportedChart("unsupported-3d-chart")
if chart_tag == "barChart":
- return _category_payload(chart, _bar_chart_type(chart), xfrm)
- if chart_tag in {"areaChart", "lineChart", "ofPieChart", "pieChart", "doughnutChart"}:
+ payload = _category_payload(chart, _bar_chart_type(chart), xfrm)
+ elif chart_tag in {"areaChart", "lineChart", "ofPieChart", "pieChart", "doughnutChart"}:
chart_type = {
"areaChart": "area",
"lineChart": "line",
@@ -114,12 +119,460 @@ def _payload_from_chart_xml(chart_root: ET.Element, xfrm: Xfrm) -> dict[str, Any
"pieChart": "pie",
"doughnutChart": "doughnut",
}[chart_tag]
- return _category_payload(chart, chart_type, xfrm)
- if chart_tag == "scatterChart":
- return _xy_payload(chart, "scatter", xfrm)
- if chart_tag == "bubbleChart":
- return _xy_payload(chart, "bubble", xfrm)
- raise _UnsupportedChart("unsupported-chart-type")
+ payload = _category_payload(chart, chart_type, xfrm)
+ elif chart_tag == "scatterChart":
+ payload = _xy_payload(chart, "scatter", xfrm)
+ elif chart_tag == "bubbleChart":
+ payload = _xy_payload(chart, "bubble", xfrm)
+ else:
+ raise _UnsupportedChart("unsupported-chart-type")
+
+ _validate_chart_semantics(payload, plot_area, chart)
+ _apply_chart_metadata(payload, chart_root, plot_area, chart)
+ return payload
+
+
+def _validate_chart_semantics(
+ payload: dict[str, Any],
+ plot_area: ET.Element,
+ plot: ET.Element,
+) -> None:
+ """Reject valid chart features the compact marker cannot reproduce."""
+ chart_type = payload["type"]
+ for tag in (
+ "trendline", "errBars", "dropLines", "hiLowLines", "upDownBars",
+ ):
+ if plot.find(f".//c:{tag}", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-analysis-features")
+ if plot_area.find("c:dTable", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-data-table")
+ ser_lines = plot.find("c:serLines", C_NS)
+ if ser_lines is not None and (
+ chart_type != "of_pie" or ser_lines.attrib or list(ser_lines)
+ ):
+ raise _UnsupportedChart("unsupported-chart-analysis-features")
+
+ grouping = payload.get("grouping")
+ axes = plot_area.findall("c:catAx", C_NS) + plot_area.findall("c:valAx", C_NS)
+ for axis in axes:
+ axis_kind = _local_name(axis.tag)
+ axis_position = _element_val(axis.find("c:axPos", C_NS))
+ delete = axis.find("c:delete", C_NS)
+ if delete is not None and ooxml_bool(delete.attrib.get("val"), True):
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ scaling = axis.find("c:scaling", C_NS)
+ if scaling is not None:
+ for tag in ("logBase", "min", "max"):
+ if scaling.find(f"c:{tag}", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ orientation = _element_val(scaling.find("c:orientation", C_NS))
+ if orientation not in {None, "minMax"}:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ for tag in (
+ "majorUnit", "minorUnit", "crossesAt", "dispUnits",
+ "tickLblSkip", "tickMarkSkip",
+ ):
+ if axis.find(f"c:{tag}", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ crosses = _element_val(axis.find("c:crosses", C_NS))
+ if crosses not in {None, "autoZero"}:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ auto = axis.find("c:auto", C_NS)
+ if auto is not None and not ooxml_bool(auto.attrib.get("val"), True):
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ num_fmt = axis.find("c:numFmt", C_NS)
+ if num_fmt is not None:
+ format_code = num_fmt.attrib.get("formatCode", "").strip()
+ allowed_formats = {"", "General"}
+ if grouping == "percentStacked":
+ allowed_formats.add("0%")
+ if format_code not in allowed_formats:
+ raise _UnsupportedChart("unsupported-chart-axis-number-format")
+ tick_label_position = _element_val(axis.find("c:tickLblPos", C_NS))
+ if payload["type"] in {"scatter", "bubble"} or axis_kind == "catAx":
+ if tick_label_position not in {None, "nextTo"}:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ elif tick_label_position == "none":
+ payload["show_value_axis_labels"] = False
+ elif tick_label_position not in {None, "nextTo"}:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+
+ has_major_gridlines = axis.find("c:majorGridlines", C_NS) is not None
+ if payload["type"] in {"scatter", "bubble"}:
+ expected_major_gridlines = axis_position in {"l", "r"}
+ else:
+ expected_major_gridlines = axis_kind == "valAx"
+ if has_major_gridlines != expected_major_gridlines:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ if axis.find("c:minorGridlines", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+
+ if chart_type == "line":
+ smooth_nodes = [plot.find("c:smooth", C_NS), *plot.findall("c:ser/c:smooth", C_NS)]
+ if any(
+ node is not None and ooxml_bool(node.attrib.get("val"), True)
+ for node in smooth_nodes
+ ):
+ raise _UnsupportedChart("unsupported-chart-line-style")
+ plot_marker = plot.find("c:marker", C_NS)
+ plot_has_markers = bool(
+ plot_marker is not None
+ and ooxml_bool(plot_marker.attrib.get("val"), True)
+ )
+ marker_states: set[bool] = set()
+ for series in plot.findall("c:ser", C_NS):
+ marker_node = series.find("c:marker", C_NS)
+ if marker_node is not None and any(
+ child.tag.rsplit("}", 1)[-1] != "symbol"
+ for child in marker_node
+ ):
+ raise _UnsupportedChart("unsupported-chart-line-style")
+ symbol = _element_val(series.find("c:marker/c:symbol", C_NS))
+ if symbol not in {None, "circle", "none"}:
+ raise _UnsupportedChart("unsupported-chart-line-style")
+ marker_states.add(plot_has_markers if symbol is None else symbol != "none")
+ if len(marker_states) > 1:
+ raise _UnsupportedChart("unsupported-chart-line-style")
+
+ if chart_type in {"bar", "column"}:
+ gap_width = _element_val(plot.find("c:gapWidth", C_NS))
+ if gap_width not in {None, "150"}:
+ raise _UnsupportedChart("unsupported-chart-bar-options")
+ overlap = _element_val(plot.find("c:overlap", C_NS))
+ expected_overlap = "100" if grouping in {"stacked", "percentStacked"} else "0"
+ if overlap is None:
+ if expected_overlap != "0":
+ raise _UnsupportedChart("unsupported-chart-bar-options")
+ elif overlap != expected_overlap:
+ raise _UnsupportedChart("unsupported-chart-bar-options")
+
+ if chart_type == "bubble":
+ bubble_scale = _element_val(plot.find("c:bubbleScale", C_NS))
+ if bubble_scale not in {None, "100"}:
+ raise _UnsupportedChart("unsupported-chart-bubble-options")
+ show_negative = plot.find("c:showNegBubbles", C_NS)
+ if show_negative is not None and ooxml_bool(
+ show_negative.attrib.get("val"),
+ True,
+ ):
+ raise _UnsupportedChart("unsupported-chart-bubble-options")
+ size_represents = _element_val(plot.find("c:sizeRepresents", C_NS))
+ if size_represents not in {None, "area"}:
+ raise _UnsupportedChart("unsupported-chart-bubble-options")
+ bubble_3d_nodes = [
+ plot.find("c:bubble3D", C_NS),
+ *plot.findall("c:ser/c:bubble3D", C_NS),
+ ]
+ if any(
+ node is not None and ooxml_bool(node.attrib.get("val"), True)
+ for node in bubble_3d_nodes
+ ):
+ raise _UnsupportedChart("unsupported-chart-bubble-options")
+
+ if chart_type == "scatter":
+ scatter_style = _element_val(plot.find("c:scatterStyle", C_NS)) or "marker"
+ expected_marker = (
+ "circle"
+ if scatter_style in {"lineMarker", "marker", "smoothMarker"}
+ else "none"
+ )
+ expected_smooth = scatter_style in {"smooth", "smoothMarker"}
+ for series in plot.findall("c:ser", C_NS):
+ marker = series.find("c:marker", C_NS)
+ if marker is None:
+ raise _UnsupportedChart("unsupported-chart-scatter-style")
+ if any(
+ child.tag.rsplit("}", 1)[-1] != "symbol"
+ for child in marker
+ ):
+ raise _UnsupportedChart("unsupported-chart-scatter-style")
+ symbol = _element_val(marker.find("c:symbol", C_NS))
+ if symbol != expected_marker:
+ raise _UnsupportedChart("unsupported-chart-scatter-style")
+ smooth = series.find("c:smooth", C_NS)
+ actual_smooth = bool(
+ smooth is not None and ooxml_bool(smooth.attrib.get("val"), True)
+ )
+ if actual_smooth != expected_smooth:
+ raise _UnsupportedChart("unsupported-chart-scatter-style")
+
+ if chart_type in {"pie", "doughnut", "of_pie"}:
+ for explosion in plot.findall(".//c:explosion", C_NS):
+ if _element_val(explosion) not in {None, "0"}:
+ raise _UnsupportedChart("unsupported-chart-pie-options")
+ first_slice = _element_val(plot.find("c:firstSliceAng", C_NS))
+ if first_slice not in {None, "0"}:
+ raise _UnsupportedChart("unsupported-chart-pie-options")
+ if chart_type == "doughnut":
+ hole_size = _element_val(plot.find("c:holeSize", C_NS))
+ if hole_size != "75":
+ raise _UnsupportedChart("unsupported-chart-doughnut-options")
+ if chart_type == "of_pie":
+ for tag in ("splitType", "splitPos", "custSplit"):
+ if plot.find(f"c:{tag}", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-of-pie-options")
+ gap_width = _element_val(plot.find("c:gapWidth", C_NS))
+ if gap_width != "100":
+ raise _UnsupportedChart("unsupported-chart-of-pie-options")
+ second_size = _element_val(plot.find("c:secondPieSize", C_NS))
+ if second_size not in {None, "75"}:
+ raise _UnsupportedChart("unsupported-chart-of-pie-options")
+
+
+def _apply_chart_metadata(
+ payload: dict[str, Any],
+ chart_root: ET.Element,
+ plot_area: ET.Element,
+ plot: ET.Element,
+) -> None:
+ """Copy visible classic-chart chrome supported by the native schema."""
+ chart = chart_root.find("c:chart", C_NS)
+ if chart is None:
+ return
+
+ title = _chart_text(chart.find("c:title", C_NS))
+ if title:
+ overlay = chart.find("c:title/c:overlay", C_NS)
+ if overlay is not None and ooxml_bool(overlay.attrib.get("val"), True):
+ raise _UnsupportedChart("unsupported-chart-title-overlay")
+ payload["title"] = title
+
+ legend = chart.find("c:legend", C_NS)
+ if legend is not None:
+ delete = legend.find("c:delete", C_NS)
+ if delete is None or not ooxml_bool(delete.attrib.get("val"), True):
+ if legend.find("c:legendEntry", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-legend-filter")
+ overlay = legend.find("c:overlay", C_NS)
+ if overlay is not None and ooxml_bool(overlay.attrib.get("val"), True):
+ raise _UnsupportedChart("unsupported-chart-legend-overlay")
+ position = _element_val(legend.find("c:legendPos", C_NS)) or "r"
+ if position not in {"b", "l", "r", "t"}:
+ raise _UnsupportedChart("unsupported-chart-legend-position")
+ payload["show_legend"] = True
+ payload["legend_position"] = position
+
+ if plot.find("c:ser/c:dLbls", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-series-data-labels")
+ data_labels = _data_labels_payload(plot.find("c:dLbls", C_NS))
+ if data_labels:
+ if payload["type"] not in {"area", "bar", "column", "line"}:
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ try:
+ _data_label_position(
+ data_labels.get("position"),
+ payload["type"],
+ payload.get("grouping"),
+ )
+ except RuntimeError:
+ raise _UnsupportedChart("unsupported-chart-data-labels") from None
+ payload["data_labels"] = data_labels
+
+ axis_titles: dict[str, str] = {}
+ category_titles = [
+ text
+ for axis in plot_area.findall("c:catAx", C_NS)
+ if (text := _chart_text(axis.find("c:title", C_NS)))
+ ]
+ value_titles = [
+ text
+ for axis in plot_area.findall("c:valAx", C_NS)
+ if (text := _chart_text(axis.find("c:title", C_NS)))
+ ]
+ if payload["type"] in {"scatter", "bubble"}:
+ if category_titles:
+ raise _UnsupportedChart("unsupported-chart-axis-titles")
+ titled_value_axes = [
+ (
+ _element_val(axis.find("c:axPos", C_NS)),
+ _chart_text(axis.find("c:title", C_NS)),
+ )
+ for axis in plot_area.findall("c:valAx", C_NS)
+ ]
+ for position, text in titled_value_axes:
+ if not text:
+ continue
+ key = "x" if position in {"b", "t"} else "y"
+ if key in axis_titles:
+ raise _UnsupportedChart("unsupported-chart-axis-titles")
+ axis_titles[key] = text
+ else:
+ if len(category_titles) > 1 or len(value_titles) > 1:
+ raise _UnsupportedChart("unsupported-chart-axis-titles")
+ if category_titles:
+ axis_titles["category"] = category_titles[0]
+ if value_titles:
+ axis_titles["value"] = value_titles[0]
+ if axis_titles:
+ payload["axis_titles"] = axis_titles
+
+
+def _chart_text(container: ET.Element | None) -> str:
+ if container is None:
+ return ""
+ paragraphs: list[str] = []
+ for paragraph in container.findall(".//a:p", C_NS):
+ text = "".join(node.text or "" for node in paragraph.findall(".//a:t", C_NS))
+ if text:
+ paragraphs.append(text)
+ if paragraphs:
+ return "\n".join(paragraphs)
+ values = [node.text or "" for node in container.findall(".//c:v", C_NS)]
+ return "".join(values)
+
+
+def _data_label_text_style(tx_pr: ET.Element) -> dict[str, Any]:
+ """Extract the subset of label text properties emitted by this exporter."""
+ body_pr = tx_pr.find("a:bodyPr", C_NS)
+ list_style = tx_pr.find("a:lstStyle", C_NS)
+ if body_pr is None or body_pr.attrib or list(body_pr):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ if list_style is None or list_style.attrib or list(list_style):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ paragraphs = tx_pr.findall("a:p", C_NS)
+ if len(paragraphs) != 1:
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ paragraph = paragraphs[0]
+ if any(
+ child.tag.rsplit("}", 1)[-1] not in {"pPr", "endParaRPr"}
+ for child in paragraph
+ ):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ p_pr = paragraph.find("a:pPr", C_NS)
+ if p_pr is None or p_pr.attrib:
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ if any(
+ child.tag.rsplit("}", 1)[-1] != "defRPr"
+ for child in p_pr
+ ):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ end_r_pr = paragraph.find("a:endParaRPr", C_NS)
+ if end_r_pr is not None and (
+ any(name not in {"lang", "altLang"} for name in end_r_pr.attrib)
+ or list(end_r_pr)
+ ):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+
+ r_pr = p_pr.find("a:defRPr", C_NS)
+ if r_pr is None:
+ return {}
+ allowed_attrs = {"sz", "b"}
+ if any(name not in allowed_attrs for name in r_pr.attrib):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ allowed_children = {"solidFill", "latin", "ea"}
+ if any(
+ child.tag.rsplit("}", 1)[-1] not in allowed_children
+ for child in r_pr
+ ):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+
+ style: dict[str, Any] = {}
+ raw_size = r_pr.attrib.get("sz")
+ if raw_size is not None:
+ try:
+ size_px = float(raw_size) / 75.0
+ except ValueError:
+ raise _UnsupportedChart("unsupported-chart-data-labels") from None
+ if size_px <= 0 or not math.isfinite(size_px):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ style["font_size"] = int(size_px) if size_px.is_integer() else round(size_px, 3)
+ if r_pr.attrib.get("b") is not None:
+ style["bold"] = ooxml_bool(r_pr.attrib.get("b"), True)
+
+ solid_fill = r_pr.find("a:solidFill", C_NS)
+ if solid_fill is not None:
+ color_children = list(solid_fill)
+ if (
+ len(color_children) != 1
+ or color_children[0].tag.rsplit("}", 1)[-1] != "srgbClr"
+ or list(color_children[0])
+ ):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ color = color_children[0].attrib.get("val", "").strip()
+ if len(color) != 6 or any(char not in "0123456789abcdefABCDEF" for char in color):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ style["color"] = f"#{color.upper()}"
+
+ latin = r_pr.find("a:latin", C_NS)
+ east_asian = r_pr.find("a:ea", C_NS)
+ latin_face = latin.attrib.get("typeface", "").strip() if latin is not None else ""
+ east_asian_face = (
+ east_asian.attrib.get("typeface", "").strip()
+ if east_asian is not None else ""
+ )
+ font_face = (
+ f"{latin_face}, {east_asian_face}"
+ if latin_face and east_asian_face and latin_face != east_asian_face
+ else latin_face or east_asian_face
+ )
+ if font_face:
+ style["font_family"] = font_face
+ return style
+
+
+def _data_labels_payload(dlabels: ET.Element | None) -> dict[str, Any] | None:
+ if dlabels is None:
+ return None
+ if dlabels.find("c:dLbl", C_NS) is not None:
+ raise _UnsupportedChart("unsupported-chart-point-labels")
+ allowed_children = {
+ "numFmt", "txPr", "dLblPos", "showLegendKey", "showVal",
+ "showCatName", "showSerName", "showPercent", "showBubbleSize",
+ "showLeaderLines",
+ }
+ if any(
+ child.tag.rsplit("}", 1)[-1] not in allowed_children
+ for child in dlabels
+ ):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ for tag in ("showLegendKey", "showBubbleSize"):
+ elem = dlabels.find(f"c:{tag}", C_NS)
+ if elem is not None and ooxml_bool(elem.attrib.get("val"), True):
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+
+ config: dict[str, Any] = {}
+ for tag, field in (
+ ("showVal", "show_value"),
+ ("showCatName", "show_category"),
+ ("showSerName", "show_series"),
+ ("showPercent", "show_percent"),
+ ):
+ elem = dlabels.find(f"c:{tag}", C_NS)
+ config[field] = (
+ ooxml_bool(elem.attrib.get("val"), True)
+ if elem is not None else False
+ )
+ if not any(config.values()):
+ return None
+
+ leader_lines = dlabels.find("c:showLeaderLines", C_NS)
+ if leader_lines is not None:
+ config["show_leader_lines"] = ooxml_bool(
+ leader_lines.attrib.get("val"),
+ True,
+ )
+
+ position = _element_val(dlabels.find("c:dLblPos", C_NS))
+ if position:
+ position_aliases = {
+ "bestFit": "best_fit",
+ "ctr": "center",
+ "inBase": "inside_base",
+ "inEnd": "inside_end",
+ "outEnd": "outside_end",
+ "t": "above",
+ }
+ normalized_position = position_aliases.get(position)
+ if normalized_position is None:
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ config["position"] = normalized_position
+ num_fmt = dlabels.find("c:numFmt", C_NS)
+ if num_fmt is not None and num_fmt.attrib.get("formatCode"):
+ config["number_format"] = num_fmt.attrib["formatCode"]
+ tx_pr = dlabels.find("c:txPr", C_NS)
+ if tx_pr is not None:
+ config.update(_data_label_text_style(tx_pr))
+ return config
def _category_payload(chart: ET.Element, chart_type: str, xfrm: Xfrm) -> dict[str, Any]:
@@ -133,6 +586,8 @@ def _category_payload(chart: ET.Element, chart_type: str, xfrm: Xfrm) -> dict[st
series: list[dict[str, Any]] = []
for idx, ser in enumerate(series_nodes, start=1):
+ if _category_values(ser.find("c:cat", C_NS)) != categories:
+ raise _UnsupportedChart("unsupported-chart-cache")
values = _numeric_values(ser.find("c:val", C_NS))
if not values or len(values) != len(categories):
raise _UnsupportedChart("unsupported-chart-cache")
@@ -197,20 +652,31 @@ def _bar_chart_type(chart: ET.Element) -> str:
def _line_style(chart: ET.Element, series_nodes: list[ET.Element]) -> str:
- if _element_val(chart.find("c:marker", C_NS)) == "1":
+ symbols = [
+ _element_val(ser.find("c:marker/c:symbol", C_NS))
+ for ser in series_nodes
+ ]
+ if symbols and all(symbol == "none" for symbol in symbols):
+ return "line"
+ if any(symbol not in {None, "none"} for symbol in symbols):
+ return "lineMarker"
+ marker = chart.find("c:marker", C_NS)
+ if marker is not None and ooxml_bool(marker.attrib.get("val"), True):
return "lineMarker"
- for ser in series_nodes:
- marker_symbol = _element_val(ser.find("c:marker/c:symbol", C_NS))
- if marker_symbol and marker_symbol != "none":
- return "lineMarker"
return "line"
def _category_values(cat: ET.Element | None) -> list[str]:
- values = _text_cache_values(cat)
- if values:
- return values
- numbers = _numeric_values(cat)
+ cache = _first_cache(cat, ("strCache", "strLit"))
+ if cache is not None:
+ return [str(value) for value in _cache_point_values(cache)]
+ cache = _first_cache(cat, ("numCache", "numLit"))
+ if cache is None:
+ return []
+ format_code = cache.findtext("c:formatCode", default="", namespaces=C_NS).strip()
+ if format_code and format_code.lower() != "general":
+ raise _UnsupportedChart("unsupported-formatted-category-cache")
+ numbers = _numeric_cache_values(cache)
return [str(value) for value in numbers]
@@ -235,9 +701,15 @@ def _numeric_values(parent: ET.Element | None) -> list[int | float]:
cache = _first_cache(parent, ("numCache", "numLit"))
if cache is None:
return []
+ return _numeric_cache_values(cache)
+
+
+def _numeric_cache_values(cache: ET.Element) -> list[int | float]:
values: list[int | float] = []
for value in _cache_point_values(cache):
number = float(value)
+ if not math.isfinite(number):
+ raise _UnsupportedChart("unsupported-chart-cache")
values.append(int(number) if number.is_integer() else number)
return values
@@ -255,16 +727,33 @@ def _first_cache(parent: ET.Element | None, names: tuple[str, ...]) -> ET.Elemen
def _cache_point_values(cache: ET.Element | None) -> list[str]:
if cache is None:
return []
- points: list[tuple[int, str]] = []
+ points: dict[int, str] = {}
for idx, point in enumerate(cache.findall("c:pt", C_NS)):
raw_idx = point.attrib.get("idx")
try:
point_idx = int(raw_idx) if raw_idx is not None else idx
except ValueError:
- point_idx = idx
+ raise _UnsupportedChart("unsupported-chart-cache")
+ if point_idx < 0 or point_idx in points:
+ raise _UnsupportedChart("unsupported-chart-cache")
value = point.findtext("c:v", default="", namespaces=C_NS)
- points.append((point_idx, value))
- return [value for _, value in sorted(points, key=lambda item: item[0])]
+ points[point_idx] = value
+
+ count_elem = cache.find("c:ptCount", C_NS)
+ if count_elem is not None:
+ try:
+ point_count = int(count_elem.attrib.get("val", ""))
+ except ValueError:
+ raise _UnsupportedChart("unsupported-chart-cache")
+ else:
+ point_count = len(points)
+ if (
+ point_count < 0
+ or point_count != len(points)
+ or any(idx not in points for idx in range(point_count))
+ ):
+ raise _UnsupportedChart("unsupported-chart-cache")
+ return [points[idx] for idx in range(point_count)]
def _element_val(elem: ET.Element | None) -> str | None:
diff --git a/skills/ppt-master/scripts/pptx_to_svg/emu_units.py b/skills/ppt-master/scripts/pptx_to_svg/emu_units.py
index dd146181..af28850f 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/emu_units.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/emu_units.py
@@ -93,6 +93,18 @@ def percent_to_ratio(val: float | int | str | None, default: float = 0.0) -> flo
return default
+def ooxml_bool(value: str | None, default: bool = False) -> bool:
+ """Parse the boolean lexical forms accepted by OOXML."""
+ if value is None:
+ return default
+ normalized = value.strip().lower()
+ if normalized in {"1", "true", "on"}:
+ return True
+ if normalized in {"0", "false", "off"}:
+ return False
+ return default
+
+
# ---------------------------------------------------------------------------
# xfrm / transform parsing
# ---------------------------------------------------------------------------
@@ -179,8 +191,8 @@ def parse_xfrm(xfrm_elem: ET.Element | None) -> Xfrm:
return Xfrm()
rot = angle_to_deg(xfrm_elem.get("rot"))
- flip_h = xfrm_elem.get("flipH") == "1"
- flip_v = xfrm_elem.get("flipV") == "1"
+ flip_h = ooxml_bool(xfrm_elem.get("flipH"))
+ flip_v = ooxml_bool(xfrm_elem.get("flipV"))
off = xfrm_elem.find("a:off", NS)
ext = xfrm_elem.find("a:ext", NS)
diff --git a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py
index 97f92de9..79600e26 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py
@@ -10,6 +10,8 @@ Handles:
- <p:grpSp> -> GROUP (recurses; resolves a:chOff/a:chExt frame)
- <p:graphicFrame> -> GRAPHIC (table / chart / SmartArt — emitted as opaque
placeholder for v1 so callers can decide a fallback)
+- <mc:AlternateContent> -> supported Choice shape with the baked Fallback
+ preview retained for graphic frames
"""
from __future__ import annotations
@@ -17,7 +19,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from xml.etree import ElementTree as ET
-from .emu_units import NS, Xfrm, parse_xfrm
+from .emu_units import NS, Xfrm, ooxml_bool, parse_xfrm
# ---------------------------------------------------------------------------
@@ -84,7 +86,7 @@ def _read_nv_sp_pr(parent: ET.Element, nv_tag: str) -> tuple[str, str, bool, Pla
if cnv is not None:
name = cnv.attrib.get("name", "")
spid = cnv.attrib.get("id", "")
- if cnv.attrib.get("hidden") == "1":
+ if ooxml_bool(cnv.attrib.get("hidden")):
hidden = True
nv_pr = container.find("p:nvPr", NS)
@@ -160,6 +162,44 @@ _KIND_MAP = {
}
+def _first_shape_child(container: ET.Element | None) -> ET.Element | None:
+ if container is None:
+ return None
+ for child in list(container):
+ if not isinstance(child.tag, str):
+ continue
+ if child.tag.split("}", 1)[-1] in _KIND_MAP:
+ return child
+ return None
+
+
+def _resolve_alternate_content(wrapper: ET.Element) -> ET.Element | None:
+ """Select an AlternateContent shape while retaining its baked preview."""
+ choice = wrapper.find("mc:Choice", NS)
+ fallback = wrapper.find("mc:Fallback", NS)
+ selected = _first_shape_child(choice)
+ selected_from_choice = selected is not None
+ if selected is None:
+ selected = _first_shape_child(fallback)
+ if selected is None:
+ return None
+
+ clone = ET.fromstring(ET.tostring(selected, encoding="utf-8"))
+ if (
+ selected_from_choice
+ and clone.tag.split("}", 1)[-1] == "graphicFrame"
+ and fallback is not None
+ ):
+ graphic_data = clone.find("a:graphic/a:graphicData", NS)
+ if graphic_data is not None:
+ preview = ET.Element(f"{{{NS['mc']}}}AlternateContent")
+ preview.append(
+ ET.fromstring(ET.tostring(fallback, encoding="utf-8"))
+ )
+ graphic_data.append(preview)
+ return clone
+
+
def _walk_container(
container: ET.Element,
parent_group_xfrm: Xfrm | None,
@@ -176,6 +216,12 @@ def _walk_container(
if not isinstance(child.tag, str):
continue
local = child.tag.split("}", 1)[-1]
+ if local == "AlternateContent":
+ resolved = _resolve_alternate_content(child)
+ if resolved is None:
+ continue
+ child = resolved
+ local = child.tag.split("}", 1)[-1]
kind_info = _KIND_MAP.get(local)
if kind_info is None:
continue
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 be904ad8..e16486b6 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
@@ -670,8 +670,11 @@ def _render_graphic_table(
ctx.defs.extend(result.defs)
native_attrs: list[str] = ['data-pptx-native-source="pptx"']
if result.native_payload:
+ if node.name and not result.native_payload.get("name"):
+ result.native_payload["name"] = node.name
payload_json = json.dumps(
result.native_payload,
+ allow_nan=False,
ensure_ascii=False,
separators=(",", ":"),
)
@@ -704,6 +707,7 @@ def _render_graphic_chart(
result.native_payload["name"] = node.name
payload_json = json.dumps(
result.native_payload,
+ allow_nan=False,
ensure_ascii=False,
separators=(",", ":"),
)
@@ -719,8 +723,6 @@ def _render_graphic_chart(
rendered = ""
if ctx.render_graphic_previews:
rendered = _render_graphic_preview(node, ctx)
- if rendered:
- rendered += "\n" + _graphic_preview_label(node, "chart preview")
return rendered, native_attrs
diff --git a/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
index 89a4d797..43f82833 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
@@ -41,7 +41,14 @@ from typing import Any
from xml.etree import ElementTree as ET
from .color_resolver import ColorPalette, find_color_elem, resolve_color
-from .emu_units import NS, Xfrm, emu_to_px, fmt_num, hundredths_pt_to_px
+from .emu_units import (
+ NS,
+ Xfrm,
+ emu_to_px,
+ fmt_num,
+ hundredths_pt_to_px,
+ ooxml_bool,
+)
from .fill_to_svg import resolve_fill
from .ln_to_svg import resolve_stroke
from .txbody_to_svg import convert_txbody
@@ -105,7 +112,16 @@ def convert_tbl(
# and dropped cells don't render anything. PowerPoint expresses merges via
# gridSpan/rowSpan on the anchor cell + hMerge/vMerge on the dropped cells.
cells = _build_cell_grid(rows, len(col_widths))
- native_status = "unsupported-merge" if _table_has_merges(rows) else None
+ if xfrm.rot or xfrm.flip_h or xfrm.flip_v:
+ native_status = "unsupported-native-transform"
+ elif _table_has_merges(rows):
+ native_status = "unsupported-merge"
+ elif _table_has_unsupported_style(tbl):
+ native_status = "unsupported-table-style"
+ elif _table_has_unsupported_direct_formatting(tbl, palette):
+ native_status = "unsupported-table-direct-formatting"
+ else:
+ native_status = None
native_payload = (
None if native_status else _native_table_payload(
tbl,
@@ -271,8 +287,8 @@ def _build_cell_grid(rows: list[ET.Element], col_count: int) -> list[list[_CellS
grid_span = _safe_int(tc.attrib.get("gridSpan"), 1)
row_span = _safe_int(tc.attrib.get("rowSpan"), 1)
- h_merge = tc.attrib.get("hMerge") == "1"
- v_merge = tc.attrib.get("vMerge") == "1"
+ h_merge = ooxml_bool(tc.attrib.get("hMerge"))
+ v_merge = ooxml_bool(tc.attrib.get("vMerge"))
if h_merge or v_merge:
# This cell is a merge slave; leave the slot tied to the anchor
@@ -317,7 +333,7 @@ def _table_has_merges(rows: list[ET.Element]) -> bool:
"""Return True when the table uses merged cells."""
for row in rows:
for tc in row.findall("a:tc", NS):
- if tc.attrib.get("hMerge") == "1" or tc.attrib.get("vMerge") == "1":
+ if ooxml_bool(tc.attrib.get("hMerge")) or ooxml_bool(tc.attrib.get("vMerge")):
return True
if _safe_int(tc.attrib.get("gridSpan"), 1) > 1:
return True
@@ -326,6 +342,166 @@ def _table_has_merges(rows: list[ET.Element]) -> bool:
return False
+def _table_has_unsupported_style(tbl: ET.Element) -> bool:
+ tbl_pr = tbl.find("a:tblPr", NS)
+ if tbl_pr is None:
+ return False
+ allowed_attrs = {
+ "firstRow", "bandRow", "firstCol", "lastCol", "lastRow",
+ "bandCol", "rtl",
+ }
+ if any(name not in allowed_attrs for name in tbl_pr.attrib):
+ return True
+ if any(
+ ooxml_bool(tbl_pr.attrib.get(name))
+ for name in ("firstCol", "lastCol", "lastRow", "bandCol", "rtl")
+ ):
+ return True
+ return any(
+ child.tag.rsplit("}", 1)[-1] != "tableStyleId"
+ for child in tbl_pr
+ )
+
+
+def _table_has_unsupported_direct_formatting(
+ tbl: ET.Element,
+ palette: ColorPalette | None,
+) -> bool:
+ """Reject direct cell features the compact native schema cannot retain."""
+ for tc in tbl.findall(".//a:tc", NS):
+ tc_pr = tc.find("a:tcPr", NS)
+ if tc_pr is not None:
+ allowed_attrs = {"marL", "marR", "marT", "marB", "anchor"}
+ if any(name not in allowed_attrs for name in tc_pr.attrib):
+ return True
+ if tc_pr.get("anchor") not in {None, "t", "ctr", "b"}:
+ return True
+ if any(
+ child.tag.rsplit("}", 1)[-1] != "solidFill"
+ for child in tc_pr
+ ):
+ return True
+ solid_fill = tc_pr.find("a:solidFill", NS)
+ if solid_fill is not None:
+ if solid_fill.find(".//a:alpha", NS) is not None:
+ return True
+ if _cell_fill_hex(tc_pr, palette) is None:
+ return True
+ tx_body = tc.find("a:txBody", NS)
+ if _text_body_has_unsupported_formatting(tx_body):
+ return True
+ if (
+ tx_body is not None
+ and tx_body.find(".//a:solidFill", NS) is not None
+ and _cell_text_color(tx_body, palette) is None
+ ):
+ return True
+ return False
+
+
+def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
+ if tx_body is None:
+ return False
+ body_pr = tx_body.find("a:bodyPr", NS)
+ if body_pr is not None and (body_pr.attrib or list(body_pr)):
+ return True
+ list_style = tx_body.find("a:lstStyle", NS)
+ if list_style is not None and (list_style.attrib or list(list_style)):
+ return True
+ if (
+ tx_body.find(".//a:br", NS) is not None
+ or tx_body.find(".//a:fld", NS) is not None
+ or tx_body.find(".//a:tab", NS) is not None
+ ):
+ return True
+
+ paragraphs = tx_body.findall("a:p", NS)
+ if len(paragraphs) > 1:
+ return True
+
+ alignments: set[str | None] = set()
+ run_signatures: set[tuple[str | None, str | None, bytes | None]] = set()
+ for paragraph in paragraphs:
+ p_pr = paragraph.find("a:pPr", NS)
+ alignment = p_pr.get("algn") if p_pr is not None else None
+ if alignment not in {None, "l", "ctr", "r"}:
+ return True
+ alignments.add(alignment)
+ if p_pr is not None:
+ if any(name != "algn" for name in p_pr.attrib):
+ return True
+ if any(
+ child.tag.rsplit("}", 1)[-1] not in {"defRPr", "buNone"}
+ for child in p_pr
+ ):
+ return True
+
+ default_r_pr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
+ if _run_props_have_unsupported_formatting(default_r_pr):
+ return True
+ for run in paragraph.findall("a:r", NS):
+ r_pr = run.find("a:rPr", NS)
+ if _run_props_have_unsupported_formatting(r_pr):
+ return True
+ run_signatures.add(_effective_run_signature(r_pr, default_r_pr))
+ end_r_pr = paragraph.find("a:endParaRPr", NS)
+ if _run_props_have_unsupported_formatting(end_r_pr):
+ return True
+ if not paragraph.findall("a:r", NS) and end_r_pr is not None:
+ run_signatures.add(_effective_run_signature(end_r_pr, default_r_pr))
+
+ return len(alignments) > 1 or len(run_signatures) > 1
+
+
+def _run_props_have_unsupported_formatting(r_pr: ET.Element | None) -> bool:
+ if r_pr is None:
+ return False
+ if ooxml_bool(r_pr.get("i")):
+ return True
+ if r_pr.get("u") not in {None, "none"}:
+ return True
+ if r_pr.get("strike") not in {None, "noStrike"}:
+ return True
+ if r_pr.get("baseline") not in {None, "0"}:
+ return True
+ if r_pr.get("cap") not in {None, "none"}:
+ return True
+ if r_pr.get("spc") not in {None, "0"}:
+ return True
+ allowed_attrs = {
+ "lang", "altLang", "sz", "b", "i", "u", "strike", "dirty",
+ "baseline", "cap", "spc",
+ }
+ if any(name not in allowed_attrs for name in r_pr.attrib):
+ return True
+ solid_fill = r_pr.find("a:solidFill", NS)
+ if solid_fill is not None and solid_fill.find(".//a:alpha", NS) is not None:
+ return True
+ return any(
+ child.tag.rsplit("}", 1)[-1] != "solidFill"
+ for child in r_pr
+ )
+
+
+def _effective_run_signature(
+ r_pr: ET.Element | None,
+ default_r_pr: ET.Element | None,
+) -> tuple[str | None, str | None, bytes | None]:
+ def attr(name: str) -> str | None:
+ if r_pr is not None and r_pr.get(name) is not None:
+ return r_pr.get(name)
+ return default_r_pr.get(name) if default_r_pr is not None else None
+
+ solid_fill = r_pr.find("a:solidFill", NS) if r_pr is not None else None
+ if solid_fill is None and default_r_pr is not None:
+ solid_fill = default_r_pr.find("a:solidFill", NS)
+ fill_xml = (
+ ET.tostring(solid_fill, encoding="utf-8")
+ if solid_fill is not None else None
+ )
+ return attr("b"), attr("sz"), fill_xml
+
+
def _round_payload_number(value: float) -> int | float:
rounded = round(float(value), 3)
return int(rounded) if rounded.is_integer() else rounded
@@ -347,13 +523,21 @@ def _native_table_payload(
"width": _round_payload_number(xfrm.w),
"height": _round_payload_number(xfrm.h),
"strict_grid": True,
- "header_rows": 1 if tbl_pr is not None and tbl_pr.get("firstRow") == "1" else 0,
+ "header_rows": (
+ 1 if tbl_pr is not None and ooxml_bool(tbl_pr.get("firstRow")) else 0
+ ),
"column_widths": [_round_payload_number(width) for width in column_widths],
"row_heights": [_round_payload_number(height) for height in row_heights],
"rows": [],
}
- if tbl_pr is not None and tbl_pr.get("bandRow") is not None:
- payload["style"] = {"band_row": tbl_pr.get("bandRow") != "0"}
+ style: dict[str, Any] = {
+ "band_row": bool(tbl_pr is not None and ooxml_bool(tbl_pr.get("bandRow"))),
+ }
+ if tbl_pr is not None:
+ table_style_id = tbl_pr.findtext("a:tableStyleId", default="", namespaces=NS).strip()
+ if table_style_id:
+ style["table_style_id"] = table_style_id
+ payload["style"] = style
rows_payload: list[list[Any]] = []
for row_cells in cells:
@@ -388,8 +572,9 @@ def _native_cell_payload(tc: ET.Element, palette: ColorPalette | None) -> dict[s
valign = _cell_valign(tc_pr)
if valign:
cell["valign"] = valign
- if _cell_bold(tx_body):
- cell["bold"] = True
+ bold = _cell_bold(tx_body)
+ if bold is not None:
+ cell["bold"] = bold
_copy_cell_margins(tc_pr, cell)
return cell
@@ -414,19 +599,22 @@ def _cell_fill_hex(tc_pr: ET.Element | None, palette: ColorPalette | None) -> st
def _cell_text_color(tx_body: ET.Element | None, palette: ColorPalette | None) -> str | None:
- r_pr = _first_text_run_props(tx_body)
- color, _alpha = resolve_color(find_color_elem(r_pr), palette)
- return color
+ for r_pr in _text_run_props_in_priority(tx_body):
+ solid_fill = r_pr.find("a:solidFill", NS)
+ if solid_fill is not None:
+ color, _alpha = resolve_color(find_color_elem(solid_fill), palette)
+ return color
+ return None
def _cell_font_size_px(tx_body: ET.Element | None) -> int | float | None:
- r_pr = _first_text_run_props(tx_body)
- if r_pr is None or not r_pr.get("sz"):
- return None
- size = hundredths_pt_to_px(r_pr.get("sz"))
- if size <= 0:
- return None
- return _round_payload_number(size)
+ for r_pr in _text_run_props_in_priority(tx_body):
+ if not r_pr.get("sz"):
+ continue
+ size = hundredths_pt_to_px(r_pr.get("sz"))
+ if size > 0:
+ return _round_payload_number(size)
+ return None
def _cell_align(tx_body: ET.Element | None) -> str | None:
@@ -448,18 +636,22 @@ def _cell_valign(tc_pr: ET.Element | None) -> str | None:
}.get(anchor)
-def _cell_bold(tx_body: ET.Element | None) -> bool:
- r_pr = _first_text_run_props(tx_body)
- return r_pr is not None and r_pr.get("b") == "1"
+def _cell_bold(tx_body: ET.Element | None) -> bool | None:
+ for r_pr in _text_run_props_in_priority(tx_body):
+ if r_pr.get("b") is not None:
+ return ooxml_bool(r_pr.get("b"))
+ return None
-def _first_text_run_props(tx_body: ET.Element | None) -> ET.Element | None:
+def _text_run_props_in_priority(tx_body: ET.Element | None) -> list[ET.Element]:
if tx_body is None:
- return None
- r_pr = tx_body.find(".//a:r/a:rPr", NS)
- if r_pr is not None:
- return r_pr
- return tx_body.find(".//a:endParaRPr", NS)
+ return []
+ props: list[ET.Element] = []
+ for path in (".//a:r/a:rPr", ".//a:pPr/a:defRPr", ".//a:endParaRPr"):
+ r_pr = tx_body.find(path, NS)
+ if r_pr is not None:
+ props.append(r_pr)
+ return props
def _copy_cell_margins(tc_pr: ET.Element | None, cell: dict[str, Any]) -> None:
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 74196dd2..342be62b 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -926,6 +926,15 @@ class SVGQualityChecker:
def _check_native_object_markers(self, root: ET.Element, result: Dict) -> None:
"""Validate opt-in native table/chart markers before PPTX export."""
+ for elem in root.iter():
+ status = elem.get('data-pptx-native-status')
+ if not status or elem.tag.rsplit('}', 1)[-1] == 'metadata':
+ continue
+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'
+ result['warnings'].append(
+ f"Native PPTX object {marker_id} is fallback-only: {status}"
+ )
+
markers = [
elem for elem in root.iter()
if elem.get('data-pptx-native') and elem.tag.rsplit('}', 1)[-1] != 'metadata'
diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
index ebb6af78..1ff5d7ba 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py
@@ -24,8 +24,8 @@ _CHROME_ID_TOKENS = frozenset({
'decoration', 'decorations', 'decor',
'header', 'footer',
'chrome', 'watermark',
- 'pagenumber', 'pagenum',
- 'page-number',
+ 'pagenumber', 'pagenum', 'slidenumber', 'slidenum',
+ 'logo', 'nav', 'rule',
})
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index 809f39d3..c52d1f09 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -25,6 +25,7 @@ from .elements import (
convert_polygon, convert_polyline,
convert_text, convert_image, convert_nested_svg,
)
+from ..animation_config import is_chrome_id
from ..native_objects import convert_native_object
@@ -32,35 +33,6 @@ class SvgNativeConversionError(RuntimeError):
"""Raised when an SVG cannot be faithfully converted to native DrawingML."""
-# ---------------------------------------------------------------------------
-# Animation anchor selection
-# ---------------------------------------------------------------------------
-
-# Tokens that mark a top-level <g id="..."> as page chrome rather than animated
-# content. When any token (after splitting id on '-' and '_') matches, the group
-# is excluded from the per-element entrance animation cascade so background,
-# header/footer, decorations etc. appear together with the slide instead of
-# requiring presenter clicks.
-_CHROME_ID_TOKENS = frozenset({
- 'background', 'bg',
- 'decoration', 'decorations', 'decor',
- 'header', 'footer',
- 'chrome', 'watermark',
- 'pagenumber', 'pagenum',
- 'nav', 'logo', 'rule',
-})
-
-
-def _is_chrome_id(elem_id: str | None) -> bool:
- if not elem_id:
- return False
- lower = elem_id.lower()
- if lower.replace('-', '').replace('_', '') in _CHROME_ID_TOKENS:
- return True
- tokens = re.split(r'[-_]', lower)
- return any(t in _CHROME_ID_TOKENS for t in tokens if t)
-
-
# ---------------------------------------------------------------------------
# Transform & layout helpers
# ---------------------------------------------------------------------------
@@ -172,7 +144,7 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
style_overrides = _extract_inheritable_styles(elem)
elem_id = elem.get('id')
- should_animate_group = ctx.depth == 0 and elem_id and not _is_chrome_id(elem_id)
+ should_animate_group = ctx.depth == 0 and elem_id and not is_chrome_id(elem_id)
visual_children = [
child for child in elem
if child.tag.replace(f'{{{SVG_NS}}}', '') not in _NON_VISUAL_TAGS
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
index 3b8ae27d..fef6e86d 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py
@@ -183,7 +183,7 @@ def _validate_native_object_marker_payload(
table_rows, _ = _validate_table_payload(payload)
else:
_chart_data(payload)
- if validate_chrome:
+ if validate_chrome and elem.get("data-pptx-native-source") != "pptx":
chrome_errors = _native_chart_chrome_errors(elem, payload)
if chrome_errors:
raise RuntimeError("; ".join(chrome_errors))
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py
index 284be141..27a43aa7 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import math
from typing import Any
from .marker_common import (
@@ -20,6 +21,8 @@ def _chart_number(value: Any) -> int | float:
number = float(value)
except (TypeError, ValueError) as exc:
raise RuntimeError(f"Native PPTX chart value is not numeric: {value}") from exc
+ if not math.isfinite(number):
+ raise RuntimeError(f"Native PPTX chart value must be finite: {value}")
return int(number) if number.is_integer() else number
@@ -42,6 +45,70 @@ def _data_labels_config(payload: dict[str, Any]) -> dict[str, Any] | None:
return raw
+def _data_label_position(value: Any, chart_type: str, grouping: str | None) -> str | None:
+ """Normalize and validate a label position for its chart plot."""
+ if chart_type == "area":
+ if value is not None:
+ raise RuntimeError("Native PPTX area data labels do not support label position")
+ return None
+ is_stacked = chart_type in {"bar", "column"} and grouping in {
+ "percentStacked", "stacked",
+ }
+ default = "ctr" if is_stacked else (
+ "outEnd" if chart_type in {"bar", "column"} else "t"
+ )
+ if value is None:
+ return default
+ aliases = {
+ "above": "t",
+ "bestfit": "bestFit",
+ "center": "ctr",
+ "inbase": "inBase",
+ "insidebase": "inBase",
+ "insideend": "inEnd",
+ "inend": "inEnd",
+ "outend": "outEnd",
+ "outsideend": "outEnd",
+ }
+ position = aliases.get(_compact_key(value))
+ if not position:
+ raise RuntimeError(
+ "Native PPTX chart data label position must be one of: "
+ "above, best_fit, center, inside_base, inside_end, outside_end"
+ )
+ if chart_type in {"bar", "column"}:
+ if position not in {"ctr", "inBase", "inEnd", "outEnd"}:
+ raise RuntimeError(
+ "Native PPTX bar/column data label position must be one of: "
+ "center, inside_base, inside_end, outside_end"
+ )
+ if is_stacked and position == "outEnd":
+ raise RuntimeError(
+ "Native PPTX stacked bar/column data labels do not support outside_end"
+ )
+ elif chart_type == "line" and position not in {"bestFit", "ctr", "t"}:
+ raise RuntimeError(
+ "Native PPTX line data label position must be one of: above, best_fit, center"
+ )
+ return position
+
+
+def _chart_data_labels(
+ payload: dict[str, Any],
+ chart_type: str,
+ grouping: str | None,
+) -> dict[str, Any] | None:
+ config = _data_labels_config(payload)
+ if config is None:
+ return None
+ if chart_type not in {"area", "bar", "column", "line"}:
+ raise RuntimeError(
+ f"Native PPTX {chart_type} chart data labels are outside current support"
+ )
+ _data_label_position(config.get("position"), chart_type, grouping)
+ return config
+
+
_CATEGORY_CHART_TYPES = {
"area",
"bar",
@@ -398,13 +465,16 @@ def _category_chart_data(
if alias_style == "exploded" or payload.get("exploded"):
raise RuntimeError("Native PPTX exploded pie/doughnut is outside current basic chart support")
+ grouping = (
+ _chart_grouping(chart_type, payload, alias_grouping)
+ if chart_type in {"bar", "column", "line", "area"}
+ else None
+ )
return {
"kind": "category",
"type": chart_type,
"categories": categories,
- "grouping": _chart_grouping(chart_type, payload, alias_grouping)
- if chart_type in {"bar", "column", "line", "area"}
- else None,
+ "grouping": grouping,
"of_pie_type": of_pie_type,
"line_style": line_style,
"radar_marker_style": radar_marker_style,
@@ -418,7 +488,7 @@ def _category_chart_data(
),
True,
),
- "data_labels": _data_labels_config(payload),
+ "data_labels": _chart_data_labels(payload, chart_type, grouping),
"series": series,
}
@@ -475,12 +545,15 @@ def _combo_plot_entry(
"Native PPTX combo line plot with series fill_opacity requires area_fill: true"
)
plot_series = fallback_series or _category_series(plot_payload, categories)
+ grouping = (
+ _chart_grouping(chart_type, plot_payload, alias_grouping)
+ if chart_type in {"area", "column", "line"}
+ else None
+ )
entry: dict[str, Any] = {
"axis": _combo_axis_name(plot_payload),
- "data_labels": _data_labels_config(plot_payload),
- "grouping": _chart_grouping(chart_type, plot_payload, alias_grouping)
- if chart_type in {"area", "column", "line"}
- else None,
+ "data_labels": _chart_data_labels(plot_payload, chart_type, grouping),
+ "grouping": grouping,
"series": plot_series,
"type": chart_type,
}
@@ -523,7 +596,11 @@ def _combo_chart_data(payload: dict[str, Any]) -> dict[str, Any]:
previous.get("line_style"),
previous.get("type"),
) if previous else None
- if previous is not None and signature == previous_signature:
+ if (
+ previous is not None
+ and signature == previous_signature
+ and plot.get("data_labels") == previous.get("data_labels")
+ ):
previous["series"].extend(plot["series"])
else:
plots.append(plot)
@@ -684,6 +761,8 @@ def _chartex_chart_data(payload: dict[str, Any], chart_type: str) -> dict[str, A
def _stock_chart_data(payload: dict[str, Any]) -> dict[str, Any]:
+ if _data_labels_config(payload) is not None:
+ raise RuntimeError("Native PPTX stock chart data labels are outside current support")
categories = [
_chart_number(item)
for item in _chart_list(payload.get("categories", payload.get("dates", [])), "categories")
@@ -725,6 +804,10 @@ def _xy_chart_data(
chart_type: str,
alias_style: str | None,
) -> dict[str, Any]:
+ if _data_labels_config(payload) is not None:
+ raise RuntimeError(
+ f"Native PPTX {chart_type} chart data labels are outside current support"
+ )
raw_series = payload.get("series", [])
if not isinstance(raw_series, list) or not raw_series:
raise RuntimeError("Native PPTX XY chart requires non-empty series")
@@ -789,6 +872,13 @@ def _xy_chart_data(
def _chart_data(payload: dict[str, Any]) -> dict[str, Any]:
chart_type, alias_grouping, alias_style = _chart_kind(payload)
+ if (
+ chart_type not in _CATEGORY_CHART_TYPES | {"combo", "stock"} | _XY_CHART_TYPES
+ and _data_labels_config(payload) is not None
+ ):
+ raise RuntimeError(
+ f"Native PPTX {chart_type} chart data labels are outside current support"
+ )
if chart_type == "combo":
return _combo_chart_data(payload)
if chart_type in _CHARTEX_CHART_TYPES:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_style.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_style.py
index 7204a0dc..686ad16e 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_style.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_style.py
@@ -476,6 +476,8 @@ def _native_chart_export_payload(
elem: ET.Element,
payload: dict[str, Any],
) -> tuple[dict[str, Any], list[str]]:
+ if elem.get("data-pptx-native-source") == "pptx":
+ return payload, []
fallback_texts = set(_visible_fallback_texts(elem))
output = payload
messages: list[str] = []
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py
index e3fa8292..a6c5f501 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py
@@ -6,7 +6,12 @@ from typing import Any
from xml.etree import ElementTree as ET
from ..drawingml.utils import detect_text_lang, px_to_emu, _xml_escape
-from .chart_data import _DEFAULT_CHART_COLORS, _chart_list, _data_labels_config
+from .chart_data import (
+ _DEFAULT_CHART_COLORS,
+ _chart_list,
+ _data_label_position,
+ _data_labels_config,
+)
from .chart_style import (
_alpha_xml,
_axis_title_xml,
@@ -82,49 +87,6 @@ def _series_color_xml(
)
-def _data_label_position(value: Any, chart_type: str, grouping: str | None) -> str | None:
- if chart_type == "area":
- if value is not None:
- raise RuntimeError("Native PPTX area data labels do not support label position")
- return None
- is_stacked = chart_type in {"bar", "column"} and grouping in {"percentStacked", "stacked"}
- default = "ctr" if is_stacked else ("outEnd" if chart_type in {"bar", "column"} else "t")
- if value is None:
- return default
- aliases = {
- "above": "t",
- "bestfit": "bestFit",
- "center": "ctr",
- "inbase": "inBase",
- "insidebase": "inBase",
- "insideend": "inEnd",
- "inend": "inEnd",
- "outend": "outEnd",
- "outsideend": "outEnd",
- }
- position = aliases.get(_compact_key(value))
- if not position:
- raise RuntimeError(
- "Native PPTX chart data label position must be one of: "
- "above, best_fit, center, inside_base, inside_end, outside_end"
- )
- if chart_type in {"bar", "column"}:
- if position not in {"ctr", "inBase", "inEnd", "outEnd"}:
- raise RuntimeError(
- "Native PPTX bar/column data label position must be one of: "
- "center, inside_base, inside_end, outside_end"
- )
- if is_stacked and position == "outEnd":
- raise RuntimeError(
- "Native PPTX stacked bar/column data labels do not support outside_end"
- )
- elif chart_type == "line" and position not in {"bestFit", "ctr", "t"}:
- raise RuntimeError(
- "Native PPTX line data label position must be one of: above, best_fit, center"
- )
- return position
-
-
def _data_label_flags_xml(config: dict[str, Any]) -> str:
show_value = _chart_bool(
_first_present(config.get("show_value"), config.get("showValue"), config.get("value")),
@@ -193,6 +155,14 @@ def _data_labels_xml(
) -> str:
if config is None:
return ""
+ show_leader_lines = _chart_bool(
+ _first_present(
+ config.get("show_leader_lines"),
+ config.get("showLeaderLines"),
+ ),
+ False,
+ )
+ leader_lines_xml = f'<c:showLeaderLines val="{_bool_attr(show_leader_lines)}"/>'
position = _data_label_position(config.get("position"), chart_type, grouping)
raw_font_size = _first_present(config.get("font_size"), config.get("fontSize"))
label_font_size = _font_size_hpt(raw_font_size, 12) if raw_font_size is not None else font_size
@@ -251,7 +221,7 @@ def _data_labels_xml(
f"{_data_label_flags_xml({**config, **item})}"
"</c:dLbl>"
)
- return f"<c:dLbls>{point_label_xml}<c:showLeaderLines val=\"0\"/></c:dLbls>"
+ return f"<c:dLbls>{point_label_xml}{leader_lines_xml}</c:dLbls>"
label_colors = [
_clean_hex(item, "#404040")
@@ -280,11 +250,21 @@ def _data_labels_xml(
f"{num_fmt_xml}{tx_pr_xml}"
f"{position_xml}"
f"{flags_xml}"
- '<c:showLeaderLines val="0"/>'
+ f'{leader_lines_xml}'
"</c:dLbls>"
)
+def _series_scoped_data_labels(config: dict[str, Any] | None) -> bool:
+ """Return whether point-level overrides require a series ``c:dLbls``."""
+ if config is None:
+ return False
+ return any(
+ bool(config.get(key))
+ for key in ("points", "colors", "label_colors", "labelColors")
+ )
+
+
def _chart_color(colors: list[str], index: int) -> str:
if index < len(colors):
return colors[index]
@@ -379,7 +359,9 @@ def _series_xml(
default_color=data_label_color,
default_font_face=data_label_font_face,
)
- if chart_type in {"area", "bar", "column", "line"} else ""
+ if _series_scoped_data_labels(data_labels)
+ and chart_type in {"area", "bar", "column", "line"}
+ else ""
)
parts.append(
"<c:ser>"
@@ -569,6 +551,7 @@ def _bar_chart_group_xml(
cat_ax_id: str,
val_ax_id: str,
vary_colors: bool = False,
+ data_labels_xml: str = "",
) -> str:
bar_dir = "bar" if chart_type == "bar" else "col"
vary_colors_xml = '<c:varyColors val="1"/>' if vary_colors else '<c:varyColors val="0"/>'
@@ -582,6 +565,7 @@ def _bar_chart_group_xml(
f'<c:barDir val="{bar_dir}"/><c:grouping val="{grouping}"/>'
f"{vary_colors_xml}"
f"{ser_xml}"
+ f"{data_labels_xml}"
'<c:gapWidth val="150"/>'
f"{overlap_xml}"
f'<c:axId val="{cat_ax_id}"/><c:axId val="{val_ax_id}"/>'
@@ -596,12 +580,14 @@ def _line_area_chart_group_xml(
*,
cat_ax_id: str,
val_ax_id: str,
+ data_labels_xml: str = "",
) -> str:
tag = "lineChart" if chart_type == "line" else "areaChart"
line_tail_xml = '<c:marker val="1"/><c:smooth val="0"/>' if chart_type == "line" else ""
return (
f'<c:{tag}><c:grouping val="{grouping}"/><c:varyColors val="0"/>'
f"{ser_xml}"
+ f"{data_labels_xml}"
f"{line_tail_xml}"
f'<c:axId val="{cat_ax_id}"/><c:axId val="{val_ax_id}"/>'
f"</c:{tag}>"
@@ -708,6 +694,20 @@ def _combo_plot_xml(
start_column=2 + start_index,
start_index=start_index,
)
+ data_labels = _data_labels_config(plot)
+ data_labels_xml = (
+ _data_labels_xml(
+ data_labels,
+ chart_type=chart_type,
+ grouping=grouping,
+ point_count=len(plot["series"][0]["values"]),
+ font_size=axis_font_size,
+ default_color=chart_style.get("text_color"),
+ default_font_face=chart_style.get("font_face"),
+ )
+ if not _series_scoped_data_labels(data_labels)
+ else ""
+ )
if chart_type == "column":
parts.append(_bar_chart_group_xml(
chart_type,
@@ -716,6 +716,7 @@ def _combo_plot_xml(
cat_ax_id=cat_ax_id,
val_ax_id=val_ax_id,
vary_colors=any(item.get("point_colors") for item in plot["series"]),
+ data_labels_xml=data_labels_xml,
))
elif chart_type in {"area", "line"}:
parts.append(_line_area_chart_group_xml(
@@ -724,6 +725,7 @@ def _combo_plot_xml(
ser_xml,
cat_ax_id=cat_ax_id,
val_ax_id=val_ax_id,
+ data_labels_xml=data_labels_xml,
))
else:
raise RuntimeError("Native PPTX combo plots support column, line, and area only")
@@ -856,6 +858,20 @@ def _chart_plot_xml(
data_label_color=chart_style.get("text_color"),
data_label_font_face=chart_style.get("font_face"),
)
+ data_labels_xml = (
+ _data_labels_xml(
+ chart_data.get("data_labels"),
+ chart_type=chart_type,
+ grouping=series_grouping,
+ point_count=len(series[0]["values"]),
+ font_size=axis_font_size,
+ default_color=chart_style.get("text_color"),
+ default_font_face=chart_style.get("font_face"),
+ )
+ if chart_type in {"area", "bar", "column", "line"}
+ and not _series_scoped_data_labels(chart_data.get("data_labels"))
+ else ""
+ )
if chart_type in {"bar", "column"}:
bar_dir = "bar" if chart_type == "bar" else "col"
@@ -886,6 +902,7 @@ def _chart_plot_xml(
f'<c:barDir val="{bar_dir}"/><c:grouping val="{grouping}"/>'
f"{vary_colors_xml}"
f"{ser_xml}"
+ f"{data_labels_xml}"
'<c:gapWidth val="150"/>'
f"{overlap_xml}"
f'<c:axId val="{cat_ax_id}"/><c:axId val="{val_ax_id}"/>'
@@ -910,6 +927,7 @@ def _chart_plot_xml(
return (
f'<c:{tag}><c:grouping val="{grouping}"/><c:varyColors val="0"/>'
f"{ser_xml}"
+ f"{data_labels_xml}"
f"{line_tail_xml}"
f'<c:axId val="{cat_ax_id}"/><c:axId val="{val_ax_id}"/>'
f"</c:{tag}>"
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
index 6640a0ff..159ea6ba 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
@@ -26,18 +26,24 @@ from .marker_common import (
def _table_text_run(
text: str,
*,
- color: str,
- bold: bool,
- font_size: int,
+ color: str | None,
+ bold: bool | None,
+ font_size: int | None,
font_face: str | None,
) -> str:
- bold_attr = ' b="1"' if bold else ""
- return (
- f'<a:r><a:rPr lang="en-US" sz="{font_size}"{bold_attr}>'
+ size_attr = f' sz="{font_size}"' if font_size is not None else ""
+ bold_attr = f' b="{_bool_attr(bold)}"' if bold is not None else ""
+ color_xml = (
f'<a:solidFill><a:srgbClr val="{color}"/></a:solidFill>'
+ if color else ""
+ )
+ space_attr = ' xml:space="preserve"' if text != text.strip() else ""
+ return (
+ f'<a:r><a:rPr lang="en-US"{size_attr}{bold_attr}>'
+ f'{color_xml}'
f'{_font_face_xml(font_face)}'
"</a:rPr>"
- f"<a:t>{_xml_escape(text)}</a:t></a:r>"
+ f"<a:t{space_attr}>{_xml_escape(text)}</a:t></a:r>"
)
@@ -304,6 +310,7 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
table_rows, col_count = _validate_table_payload(payload)
has_columns = bool(payload.get("columns") or [])
header_rows = int(payload.get("header_rows", 1 if has_columns else 0))
+ preserve_source_style = elem.get("data-pptx-native-source") == "pptx"
for row in table_rows:
row.extend([""] * (col_count - len(row)))
@@ -345,36 +352,64 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
cells_xml: list[str] = []
for cell in row:
cell_data = _cell_payload(cell)
- fill = _clean_hex(
- cell_data.get("fill"),
- header_fill if is_header else (band_fill if row_idx % 2 == 0 and row_idx else body_fill),
- )
- color = _clean_hex(cell_data.get("color"), header_text if is_header else body_text)
- align = str(cell_data.get("align") or ("ctr" if is_header else "l"))
+ if preserve_source_style:
+ fill = (
+ _clean_hex(cell_data.get("fill"), "#FFFFFF")
+ if cell_data.get("fill") is not None else None
+ )
+ color = (
+ _clean_hex(cell_data.get("color"), "#000000")
+ if cell_data.get("color") is not None else None
+ )
+ align = str(cell_data.get("align") or "l")
+ else:
+ fill = _clean_hex(
+ cell_data.get("fill"),
+ header_fill if is_header else (
+ band_fill if row_idx % 2 == 0 and row_idx else body_fill
+ ),
+ )
+ color = _clean_hex(
+ cell_data.get("color"),
+ header_text if is_header else body_text,
+ )
+ align = str(cell_data.get("align") or ("ctr" if is_header else "l"))
if align not in {"l", "ctr", "r"}:
align = "l"
text = "" if cell_data.get("text") is None else str(cell_data.get("text"))
- bold = bool(cell_data.get("bold", is_header))
- cell_font_size = (
- _font_size_hpt(cell_data.get("font_size"), 18)
- if "font_size" in cell_data
- else body_font_size
- )
- if is_header and "font_size" not in cell_data:
- cell_font_size = header_font_size
+ if preserve_source_style:
+ bold = bool(cell_data["bold"]) if "bold" in cell_data else None
+ cell_font_size = (
+ _font_size_hpt(cell_data.get("font_size"), 18)
+ if "font_size" in cell_data else None
+ )
+ else:
+ bold = bool(cell_data.get("bold", is_header))
+ cell_font_size = (
+ _font_size_hpt(cell_data.get("font_size"), 18)
+ if "font_size" in cell_data
+ else body_font_size
+ )
+ if is_header and "font_size" not in cell_data:
+ cell_font_size = header_font_size
paragraph_props = f'<a:pPr algn="{align}"/>' if align != "l" else "<a:pPr/>"
- tc_pr_attrs = (
- f' anchor="{_table_anchor(cell_data, style)}"'
- f'{_table_padding_attrs(cell_data, style)}'
- )
+ anchor_keys = {"valign", "vertical_align"}
+ anchor_attr = ""
+ if not preserve_source_style or anchor_keys.intersection(cell_data) or anchor_keys.intersection(style):
+ anchor_attr = f' anchor="{_table_anchor(cell_data, style)}"'
+ tc_pr_attrs = f'{anchor_attr}{_table_padding_attrs(cell_data, style)}'
border_xml = _table_border_xml(cell_data, style)
+ fill_xml = (
+ f'<a:solidFill><a:srgbClr val="{fill}"/></a:solidFill>'
+ if fill else ""
+ )
cells_xml.append(
"<a:tc>"
"<a:txBody><a:bodyPr/><a:lstStyle/>"
f"<a:p>{paragraph_props}"
f"{_table_text_run(text, color=color, bold=bold, font_size=cell_font_size, font_face=font_face)}"
"</a:p></a:txBody>"
- f'<a:tcPr{tc_pr_attrs}>{border_xml}<a:solidFill><a:srgbClr val="{fill}"/></a:solidFill></a:tcPr>'
+ f'<a:tcPr{tc_pr_attrs}>{border_xml}{fill_xml}</a:tcPr>'
"</a:tc>"
)
rows_xml.append(f'<a:tr h="{row_heights[row_idx]}">{"".join(cells_xml)}</a:tr>')
@@ -382,7 +417,13 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
shape_id = ctx.next_id()
first_row = _bool_attr(header_rows > 0)
band_row = _bool_attr(bool(style.get("band_row", True)))
- table_style_id = str(style.get("table_style_id") or "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}")
+ table_style_id = style.get("table_style_id")
+ if table_style_id is None and not preserve_source_style:
+ table_style_id = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"
+ table_style_xml = (
+ f'<a:tableStyleId>{_xml_escape(str(table_style_id))}</a:tableStyleId>'
+ if table_style_id else ""
+ )
name = _xml_escape(str(payload.get("name") or elem.get("id") or f"Native Table {shape_id}"))
xml = f'''<p:graphicFrame>
<p:nvGraphicFramePr>
@@ -395,7 +436,7 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
<a:graphicData uri="{TABLE_URI}">
<a:tbl>
<a:tblPr firstRow="{first_row}" bandRow="{band_row}">
-<a:tableStyleId>{_xml_escape(table_style_id)}</a:tableStyleId>
+{table_style_xml}
</a:tblPr>
<a:tblGrid>{grid_xml}</a:tblGrid>
{''.join(rows_xml)}
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.py
index c1d1af14..74d8c806 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
@@ -300,6 +300,7 @@ _CHROME_TRACE_TOKENS = (
"pagenumber",
"slidenumber",
"pagenum",
+ "slidenum",
)
_TOP_LEVEL_SHAPE_TAGS = {
f"{{{PML_NS}}}sp",
@@ -321,9 +322,11 @@ def _chrome_token_from_svg_id(svg_id: str | None) -> str | None:
return None
lower = svg_id.lower()
compact = re.sub(r"[-_\s]+", "", lower)
+ if compact in _CHROME_TRACE_TOKENS:
+ return compact
split_tokens = {token for token in re.split(r"[-_\s]+", lower) if token}
for token in _CHROME_TRACE_TOKENS:
- if token in split_tokens or token in compact:
+ if token in split_tokens:
return token
return None
@@ -341,7 +344,10 @@ def _trace_chrome_shape_ids(
token = _chrome_token_from_svg_id(event.get("id"))
shape_id = event.get("shape_id")
if token and shape_id is not None:
- result.setdefault(token, []).append(str(shape_id))
+ shape_ids = result.setdefault(token, [])
+ normalized_shape_id = str(shape_id)
+ if normalized_shape_id not in shape_ids:
+ shape_ids.append(normalized_shape_id)
return result
@@ -365,6 +371,15 @@ def _top_level_shapes_by_id(root: ET.Element) -> dict[str, ET.Element]:
return shapes
+def _timing_shape_ids(root: ET.Element) -> set[str]:
+ """Return slide-local shape ids referenced by animation timing."""
+ return {
+ elem.attrib["spid"]
+ for elem in root.findall(f".//{{{PML_NS}}}timing//{{{PML_NS}}}spTgt")
+ if elem.attrib.get("spid")
+ }
+
+
def _relationship_ids_in_shape(elem: ET.Element) -> set[str]:
rel_ids: set[str] = set()
for node in elem.iter():
@@ -398,6 +413,10 @@ def _canonical_shape_xml(
clone = ET.fromstring(ET.tostring(elem, encoding="utf-8"))
for cnv in clone.iter(f"{{{PML_NS}}}cNvPr"):
cnv.set("id", "ID")
+ # Generated names include the slide-local shape id (for example,
+ # ``Image 2`` versus ``Image 8``) but do not affect rendering.
+ if "name" in cnv.attrib:
+ cnv.set("name", "NAME")
for node in clone.iter():
for attr_name, value in list(node.attrib.items()):
if attr_name not in _REL_ATTRS:
@@ -515,11 +534,15 @@ def _promote_common_chrome_shapes_to_masters(
"rels": _read_relationships(rels_path),
"root": root,
"shapes": _top_level_shapes_by_id(root),
+ "timing_shape_ids": _timing_shape_ids(root),
"tokens": _trace_chrome_shape_ids(trace_by_slide.get(slide_num)),
"tree": tree,
}
promotions: list[tuple[str, dict[int, str]]] = []
+ claimed_shape_ids: dict[int, set[str]] = {
+ slide_num: set() for slide_num in slide_nums
+ }
all_tokens = sorted({
token
for state in slide_state.values()
@@ -539,6 +562,9 @@ def _promote_common_chrome_shapes_to_masters(
if shape is None:
shape_ids_by_slide = {}
break
+ if shape_id in state["timing_shape_ids"]:
+ shape_ids_by_slide = {}
+ break
if not _shape_relationships_supported(shape, state["rels"]):
shape_ids_by_slide = {}
break
@@ -551,8 +577,56 @@ def _promote_common_chrome_shapes_to_masters(
continue
if len(set(canonical_by_slide.values())) != 1:
continue
+ # A flattened nested chrome group can emit several semantic trace
+ # ids for the same generated DrawingML shape. Claim it once.
+ if any(
+ shape_ids_by_slide[slide_num] in claimed_shape_ids[slide_num]
+ for slide_num in slide_nums
+ ):
+ continue
+ for slide_num, shape_id in shape_ids_by_slide.items():
+ claimed_shape_ids[slide_num].add(shape_id)
promotions.append((token, shape_ids_by_slide))
+ if not promotions:
+ continue
+
+ # Master shapes always render behind slide-local shapes. Preserve the
+ # original z-order by promoting only a common leading chrome prefix;
+ # overlay headers/footers remain slide-local.
+ token_by_shape_id = {
+ slide_num: {
+ shape_ids[slide_num]: token
+ for token, shape_ids in promotions
+ }
+ for slide_num in slide_nums
+ }
+ leading_token_orders: list[list[str]] = []
+ for slide_num in slide_nums:
+ order: list[str] = []
+ for shape_id in slide_state[slide_num]["shapes"]:
+ token = token_by_shape_id[slide_num].get(shape_id)
+ if token is None:
+ break
+ order.append(token)
+ leading_token_orders.append(order)
+
+ safe_tokens = list(leading_token_orders[0])
+ for order in leading_token_orders[1:]:
+ common_length = 0
+ for expected, actual in zip(safe_tokens, order):
+ if expected != actual:
+ break
+ common_length += 1
+ safe_tokens = safe_tokens[:common_length]
+ if not safe_tokens:
+ break
+ promotion_by_token = {token: shape_ids for token, shape_ids in promotions}
+ promotions = [
+ (token, promotion_by_token[token])
+ for token in safe_tokens
+ ]
+
if not promotions:
continue
@@ -614,24 +688,6 @@ def _append_relationship(
return next_rid
-def _find_relationship_id(
- rels_path: Path,
- rel_type: str,
- target: str,
-) -> str | None:
- """Find an existing relationship id by type and target."""
- if not rels_path.exists():
- return None
- rels_content = rels_path.read_text(encoding='utf-8')
- pattern = (
- r'<Relationship\b[^>]*\bId="([^"]+)"[^>]*'
- rf'\bType="{re.escape(rel_type)}"[^>]*'
- rf'\bTarget="{re.escape(target)}"[^>]*/>'
- )
- match = re.search(pattern, rels_content)
- return match.group(1) if match else None
-
-
def _add_default_content_type(content_types: str, extension: str, content_type: str) -> str:
"""Add a Default content type if it is not already present."""
ext = extension.lstrip(".")
@@ -1159,9 +1215,9 @@ def create_pptx_with_native_svg(
image_scale: float = 2.0,
image_quality: int = 85,
native_objects: bool = False,
- pptx_structure: str = "baseline",
conversion_trace_path: Path | None = None,
doc_metadata: dict[str, Any] | None = None,
+ pptx_structure: str = "baseline",
) -> bool:
"""Create a PPTX file with native SVG.
@@ -1197,10 +1253,10 @@ def create_pptx_with_native_svg(
image_quality: JPEG quality used for opaque optimized rasters.
native_objects: Convert explicit ``data-pptx-native`` table/chart
markers to native PowerPoint objects. Default off.
- pptx_structure: PPTX structure strategy. ``baseline`` promotes safe
- shared native backgrounds to slide masters; ``flat`` leaves all
- slide backgrounds slide-local for debugging/comparison.
conversion_trace_path: Optional JSON path for native conversion diagnostics.
+ pptx_structure: PPTX structure strategy. ``baseline`` promotes safe
+ shared native backgrounds and leading chrome to slide masters;
+ ``flat`` keeps generated backgrounds/chrome slide-local.
Returns:
Whether all slides were successfully created.
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 3c72a56c..70af1e2d 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
@@ -8,6 +8,7 @@ import shutil
import argparse
from datetime import datetime
from pathlib import Path
+from xml.etree import ElementTree as ET
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
if str(_SCRIPTS_DIR) not in sys.path:
@@ -42,6 +43,23 @@ def _as_dict(value: object) -> dict:
return value if isinstance(value, dict) else {}
+def _native_object_fallbacks(svg_files: list[Path]) -> list[tuple[str, str, str]]:
+ """Return fallback-only native object statuses from SVG inputs."""
+ fallbacks: list[tuple[str, str, str]] = []
+ for svg_path in svg_files:
+ try:
+ root = ET.parse(svg_path).getroot()
+ except (OSError, ET.ParseError):
+ continue
+ for elem in root.iter():
+ status = elem.get('data-pptx-native-status')
+ if not status or elem.tag.rsplit('}', 1)[-1] == 'metadata':
+ continue
+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'
+ fallbacks.append((svg_path.name, marker_id, status))
+ return fallbacks
+
+
def _recorded_narration_on_click_slides(
ref_files: list[Path],
animation_config: dict | None,
@@ -196,8 +214,9 @@ Recorded narration:
parser.add_argument('--pptx-structure', choices=['baseline', 'flat'], default='baseline',
help='PPTX structure strategy for native export. baseline (default) '
'keeps a standard master/layout package and promotes identical '
- 'native slide backgrounds to the slide master; flat leaves '
- 'those backgrounds slide-local for debugging/comparison.')
+ 'native slide backgrounds plus a safe leading prefix of repeated '
+ 'chrome to the slide master; flat leaves generated backgrounds '
+ 'and chrome slide-local for debugging/comparison.')
parser.add_argument('--svg-snapshot', action='store_true', default=False,
help='Also emit the SVG-rendered snapshot pptx alongside '
'the native pptx in exports/ (named '
@@ -356,6 +375,19 @@ Recorded narration:
print("Error: No SVG files found")
return 1
+ if args.native_objects:
+ fallbacks = _native_object_fallbacks(native_files)
+ if fallbacks:
+ print(
+ "Warning: --native-objects found fallback-only PPTX objects; "
+ "they will export through their SVG preview instead of editable objects.",
+ file=sys.stderr,
+ )
+ for filename, marker_id, status in fallbacks[:20]:
+ print(f" {filename}: {marker_id} ({status})", file=sys.stderr)
+ if len(fallbacks) > 20:
+ print(f" ... and {len(fallbacks) - 20} more", file=sys.stderr)
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_dir: Path | None = None