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
feat(svg-to-pptx): promote majority chrome with a cover layout
hugohe3c57b68edc835
diff --git a/docs/technical-design.md b/docs/technical-design.mdindex 81b8ff95..aa0101e1 100644--- a/docs/technical-design.md+++ b/docs/technical-design.md@@ -427,7 +427,7 @@ 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 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, base-template slide layouts no generated slide references are pruned from the package, and `pageNumber`/`slideNumber` chrome whose text exactly equals the slide's display number (honoring `firstSlideNum`) becomes an auto-updating slide-number field so reordering slides in PowerPoint renumbers pages. 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: the strict-majority identical slide background (every slide must carry an explicit background, and minority slides keep their own overriding fill), 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 a strict majority of slides sharing the master; overlay chrome stays slide-local. Minority slides — covers and section pages — keep every shape slide-local and are rebound to a generated `Cover` layout with `showMasterSp="0"`, following the PowerPoint convention that page-type differences live in layouts under one master rather than in extra masters, so promoted chrome never leaks onto them. Image relationships for promoted chrome are copied to the slide master, base-template slide layouts no generated slide references are pruned from the package, and `pageNumber`/`slideNumber` chrome whose text exactly equals the slide's display number (honoring `firstSlideNum`) becomes an auto-updating slide-number field so reordering slides in PowerPoint renumbers pages. This gives ordinary decks real master/layout structure without guessing reusable layouts or placeholders from visual similarity.**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. Exporter-canonical classic charts also recover canonical solid series/slice colors and exact one- or two-paragraph title metadata. The default export still consumes fallback children as regular DrawingML shapes; only `--native-objects` activates editable PowerPoint tables/charts. Unsupported table cases — including merged cells, direct borders, non-solid fills, and mixed rich text — keep the rendered SVG table. Unsupported chart cases — including ChartEx, rotated/flipped/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. Both carry `data-pptx-native-status`; the quality checker and native-object export report them as fallback-only 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.mdindex 728e4386..07fb328f 100644--- a/docs/zh/technical-design.md+++ b/docs/zh/technical-design.md@@ -427,7 +427,7 @@ 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,基础模板中没有任何页面引用的 slide layout 也会从 package 中裁剪掉;`pageNumber`/`slideNumber` chrome 的文本若恰好等于该页应显示的页码(尊重 `firstSlideNum`),会转换为自动更新的 PowerPoint 页码字段,此后在 PowerPoint 中调整页序页码自动重算,其他编号方案保持字面文本不动。这样普通 deck 能获得真实的 master/layout 结构,同时不根据视觉相似度猜测可复用版式或占位符。+**为什么默认 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 本地。少数派页面(封面、章节页)的全部元素保持 slide-local,并被改绑到生成的 `Cover` 版式(`showMasterSp="0"`)——遵循 PowerPoint 的惯例:页型差异用同一母版下的版式表达而不是增加母版,因此被提升的母版 chrome 绝不会泄漏到这些页面上。被提升 chrome 的图片关系会复制到 slide master,基础模板中没有任何页面引用的 slide layout 也会从 package 中裁剪掉;`pageNumber`/`slideNumber` chrome 的文本若恰好等于该页应显示的页码(尊重 `firstSlideNum`),会转换为自动更新的 PowerPoint 页码字段,此后在 PowerPoint 中调整页序页码自动重算,其他编号方案保持字面文本不动。这样普通 deck 能获得真实的 master/layout 结构,同时不根据视觉相似度猜测可复用版式或占位符。**为什么原生对象重建使用 marker,而不是自动替换对象。** 独立的 `pptx_to_svg.py` 导入器会为受支持的未合并表格和保守 classic-chart cache 输出 SVG fallback,并附加 `data-pptx-native` 元数据;当现有 schema 能表达时,还会保留源表格样式继承、受支持的单元格纯色填充 / 基础文字格式,以及图表标题、图例、坐标轴标题和面积图 / 条形图 / 柱形图 / 折线图的 plot 级数据标签开关。由本 exporter 生成的规范 classic chart 还会回读规范纯色系列 / 切片,以及精确的单段或双段标题元数据。默认导出仍把 fallback 子元素当普通 DrawingML shape 处理;只有 `--native-objects` 才会启用可编辑的 PowerPoint 表格 / 图表。合并单元格、直接边框、非纯色填充、混合富文本等不支持的表格场景继续保留实际渲染的 SVG table。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.mdindex 20a30de1..c5222661 100644--- a/skills/ppt-master/SKILL.md+++ b/skills/ppt-master/SKILL.md@@ -670,21 +670,25 @@ python3 ${SKILL_DIR}/scripts/svg_to_pptx.py <project_path>> **PPTX structure mode** — native export defaults to> `--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 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+> relationship from the base deck and promotes the strict-majority identical+> native slide background into the slide master (every slide must carry an+> explicit background; minority slides keep their own, which overrides the+> master fill). 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 a strict majority of slides> 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. Baseline also prunes base-template slide layouts no generated-> slide references, so the PowerPoint new-slide picker only offers layouts that-> belong to the deck, and converts `pageNumber` / `slideNumber` chrome whose-> text exactly equals the slide's display number into an auto-updating-> PowerPoint slide-number field (other numbering schemes keep their literal-> text). Add `--pptx-structure flat` only for debugging/comparison when all-> generated backgrounds and chrome must remain slide-local.+> chrome stays slide-local. Minority slides (covers, section pages) keep every+> shape slide-local and are bound to a generated `Cover` layout with+> `showMasterSp="0"`, so promoted master chrome never appears on them. Image+> relationships for promoted chrome are copied to the master. Baseline also+> prunes base-template slide layouts no generated slide references, so the+> PowerPoint new-slide picker only offers layouts that belong to the deck, and+> converts `pageNumber` / `slideNumber` chrome whose text exactly equals the+> slide's display number into an auto-updating PowerPoint slide-number field+> (other numbering schemes keep their literal text). 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 multiplediff --git a/skills/ppt-master/scripts/README.md b/skills/ppt-master/scripts/README.mdindex b75b6cec..426203a0 100644--- a/skills/ppt-master/scripts/README.md+++ b/skills/ppt-master/scripts/README.md@@ -116,7 +116,7 @@ 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. 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. Baseline additionally prunes base-template slide layouts that no generated slide references, and swaps `pageNumber`/`slideNumber` chrome text for an auto-updating slide-number field when the text exactly equals the slide's display number. Use `--pptx-structure flat` when all generated backgrounds and chrome must remain slide-local for debugging or comparison.+Native `svg_to_pptx.py` also defaults to `--pptx-structure baseline`: the generated deck keeps a standard master/layout relationship and promotes the strict-majority identical native slide background into the slide master (minority slides keep their own overriding background). 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 on a strict majority of slides, it is not referenced by slide timing, and moving it behind slide-local content preserves z-order; image relationships are copied to the master. Minority slides such as covers keep every shape slide-local and are bound to a generated `Cover` layout (`showMasterSp="0"`) that hides the promoted master chrome. Baseline additionally prunes base-template slide layouts that no generated slide references, and swaps `pageNumber`/`slideNumber` chrome text for an auto-updating slide-number field when the text exactly equals the slide's display number. 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 tables keep their rendered SVG table; unsupported charts keep a baked preview or explicit placeholder. Both carry `data-pptx-native-status`, which `svg_quality_checker.py` and `svg_to_pptx.py --native-objects` report as a warning.diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.pyindex 672bb43b..f1e88d58 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@@ -246,6 +246,30 @@ def _put_background_on_master(master_xml: str, background_xml: str) -> str | Non)+def _dominant_variant(+ values_by_slide: dict[int, Any],+) -> tuple[Any | None, list[int]]:+ """Return the most common value and its slides, or None on a tie."""+ slides_by_value: dict[Any, list[int]] = {}+ for slide_num, value in sorted(values_by_slide.items()):+ slides_by_value.setdefault(value, []).append(slide_num)+ if not slides_by_value:+ return None, []+ best_count = max(len(slides) for slides in slides_by_value.values())+ dominant = [+ (value, slides)+ for value, slides in slides_by_value.items()+ if len(slides) == best_count+ ]+ if len(dominant) != 1:+ return None, []+ return dominant[0]+++def _is_strict_majority(subset_size: int, total: int) -> bool:+ return subset_size >= 2 and subset_size * 2 > total++def _promote_common_slide_backgrounds_to_masters(extract_dir: Path,structure: PptxStructureContext,@@ -253,7 +277,13 @@ def _promote_common_slide_backgrounds_to_masters(*,verbose: bool = False,) -> int:- """Promote identical slide backgrounds to their shared slide master."""+ """Promote the majority slide background to its shared slide master.++ Every slide in the master group must carry an explicit background —+ a slide without one would start inheriting the promoted master fill.+ Minority slides keep their own slide-level background, which always+ overrides the master fill.+ """slides_by_master: dict[str, list[int]] = {}for slide_num in range(1, slide_count + 1):master_part = structure.slide_master_part(slide_num)@@ -273,11 +303,12 @@ def _promote_common_slide_backgrounds_to_masters(if not slide_backgrounds:continue- unique_backgrounds = set(slide_backgrounds.values())- if len(unique_backgrounds) != 1:+ background_xml, dominant_slides = _dominant_variant(slide_backgrounds)+ if background_xml is None:+ continue+ if not _is_strict_majority(len(dominant_slides), len(slide_nums)):continue- background_xml = next(iter(unique_backgrounds))master_path = extract_dir / master_partmaster_xml = master_path.read_text(encoding="utf-8")promoted_master_xml = _put_background_on_master(master_xml, background_xml)@@ -285,7 +316,7 @@ def _promote_common_slide_backgrounds_to_masters(continuemaster_path.write_text(promoted_master_xml, encoding="utf-8")- for slide_num in slide_nums:+ for slide_num in dominant_slides:slide_path = extract_dir / "ppt" / "slides" / f"slide{slide_num}.xml"slide_xml = slide_path.read_text(encoding="utf-8")slide_path.write_text(@@ -425,6 +456,13 @@ def _canonical_shape_xml(# ``Image 2`` versus ``Image 8``) but do not affect rendering.if "name" in cnv.attrib:cnv.set("name", "NAME")+ for fld in clone.iter(f"{{{DML_NS}}}fld"):+ # The literal inside a slide-number field is a per-slide render+ # cache that PowerPoint recomputes from the slide position.+ if fld.attrib.get("type") == "slidenum":+ cached = fld.find(f"{{{DML_NS}}}t")+ if cached is not None:+ cached.text = ""for node in clone.iter():for attr_name, value in list(node.attrib.items()):if attr_name not in _REL_ATTRS:@@ -502,6 +540,117 @@ def _write_xml_tree(path: Path, tree: ET.ElementTree) -> None:tree.write(path, encoding="utf-8", xml_declaration=True)+COVER_LAYOUT_NAME = "Cover"+++def _next_layout_part_number(extract_dir: Path) -> int:+ layouts_dir = extract_dir / "ppt" / "slideLayouts"+ numbers = [+ int(match.group(1))+ for path in layouts_dir.glob("slideLayout*.xml")+ if (match := re.fullmatch(r"slideLayout(\d+)\.xml", path.name))+ ]+ return max(numbers, default=0) + 1+++def _next_slide_layout_id(extract_dir: Path, master_xml: str) -> int:+ """Return an unused id for a new sldLayoutId entry."""+ ids = [int(value) for value in re.findall(r'\bid="(\d{9,})"', master_xml)]+ presentation_path = extract_dir / "ppt" / "presentation.xml"+ if presentation_path.exists():+ ids.extend(+ int(value)+ for value in re.findall(+ r'\bid="(\d{9,})"', presentation_path.read_text(encoding="utf-8")+ )+ )+ return max([*ids, 2147483648]) + 1+++def _create_cover_layout(extract_dir: Path, master_part: str, base_layout_part: str) -> str:+ """Clone a layout into a Cover layout that hides master shapes.++ Returns the new layout target relative to slide parts.+ """+ base_layout_path = extract_dir / base_layout_part+ layout_xml = base_layout_path.read_text(encoding="utf-8")++ root_match = re.search(r"<p:sldLayout\b[^>]*>", layout_xml)+ if not root_match:+ raise RuntimeError(f"Slide layout has no p:sldLayout root: {base_layout_part}")+ root_tag = root_match.group(0)+ if "showMasterSp=" in root_tag:+ new_root_tag = re.sub(r'showMasterSp="[^"]*"', 'showMasterSp="0"', root_tag)+ else:+ new_root_tag = root_tag[:-1] + ' showMasterSp="0">'+ layout_xml = layout_xml.replace(root_tag, new_root_tag, 1)+ layout_xml = re.sub(+ r"(<p:cSld\b[^>]*?)\s+name=\"[^\"]*\"",+ rf'\g<1> name="{COVER_LAYOUT_NAME}"',+ layout_xml,+ count=1,+ )++ layout_num = _next_layout_part_number(extract_dir)+ new_layout_part = f"ppt/slideLayouts/slideLayout{layout_num}.xml"+ new_layout_path = extract_dir / new_layout_part+ new_layout_path.write_text(layout_xml, encoding="utf-8")++ base_rels_path = _relationships_path_for_part(extract_dir, base_layout_part)+ new_rels_path = _relationships_path_for_part(extract_dir, new_layout_part)+ new_rels_path.parent.mkdir(exist_ok=True)+ new_rels_path.write_text(+ base_rels_path.read_text(encoding="utf-8"), encoding="utf-8"+ )++ master_path = extract_dir / master_part+ master_rels_path = _relationships_path_for_part(extract_dir, master_part)+ layout_target = posixpath.relpath(+ new_layout_part, posixpath.dirname(master_part)+ )+ rel_id = _append_relationship(master_rels_path, SLIDE_LAYOUT_REL_TYPE, layout_target)++ master_xml = master_path.read_text(encoding="utf-8")+ layout_id = _next_slide_layout_id(extract_dir, master_xml)+ entry = f'<p:sldLayoutId id="{layout_id}" r:id="{rel_id}"/>'+ if "</p:sldLayoutIdLst>" not in master_xml:+ raise RuntimeError(f"Slide master has no sldLayoutIdLst: {master_part}")+ master_path.write_text(+ master_xml.replace("</p:sldLayoutIdLst>", f"{entry}</p:sldLayoutIdLst>", 1),+ encoding="utf-8",+ )++ content_types_path = extract_dir / "[Content_Types].xml"+ content_types_path.write_text(+ _add_content_type_override(+ content_types_path.read_text(encoding="utf-8"),+ new_layout_part,+ "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml",+ ),+ encoding="utf-8",+ )+ return posixpath.relpath(new_layout_part, "ppt/slides")+++def _set_slide_layout_target(rels_path: Path, target: str) -> None:+ """Point a slide's layout relationship at a different layout part."""+ content = rels_path.read_text(encoding="utf-8")+ rel_id = None+ for existing_id, attrs in _read_relationships(rels_path).items():+ if attrs.get("Type") == SLIDE_LAYOUT_REL_TYPE:+ rel_id = existing_id+ break+ if rel_id is None:+ raise RuntimeError(f"No slide layout relationship in {rels_path}")+ pattern = re.compile(+ rf'(<Relationship\b[^>]*\bId="{re.escape(rel_id)}"[^>]*\bTarget=")[^"]*(")'+ )+ new_content, replaced = pattern.subn(rf"\g<1>{target}\g<2>", content, count=1)+ if not replaced:+ raise RuntimeError(f"Could not retarget layout relationship in {rels_path}")+ rels_path.write_text(new_content, encoding="utf-8")++def _promote_common_chrome_shapes_to_masters(extract_dir: Path,structure: PptxStructureContext,@@ -547,49 +696,66 @@ def _promote_common_chrome_shapes_to_masters("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- }+ # Per token, find the strict-majority identical variant. Slides+ # outside every dominant set become cover-layout minority slides.+ candidate_sets: dict[str, dict[int, str]] = {}all_tokens = sorted({tokenfor state in slide_state.values()for token in state["tokens"]})for token in all_tokens:- shape_ids_by_slide: dict[int, str] = {}+ carriers: dict[int, str] = {}canonical_by_slide: dict[int, bytes] = {}for slide_num in slide_nums:state = slide_state[slide_num]shape_ids = state["tokens"].get(token, [])if len(shape_ids) != 1:- shape_ids_by_slide = {}- break+ continueshape_id = shape_ids[0]shape = state["shapes"].get(shape_id)if shape is None:- shape_ids_by_slide = {}- break+ continueif shape_id in state["timing_shape_ids"]:- shape_ids_by_slide = {}- break+ continueif not _shape_relationships_supported(shape, state["rels"]):- shape_ids_by_slide = {}- break- shape_ids_by_slide[slide_num] = shape_id+ continue+ carriers[slide_num] = shape_idcanonical_by_slide[slide_num] = _canonical_shape_xml(shape,state["rels"],)- if set(shape_ids_by_slide) != set(slide_nums):+ dominant_xml, dominant_slides = _dominant_variant(canonical_by_slide)+ if dominant_xml is None:continue- if len(set(canonical_by_slide.values())) != 1:+ if not _is_strict_majority(len(dominant_slides), len(slide_nums)):continue+ candidate_sets[token] = {+ slide_num: carriers[slide_num] for slide_num in dominant_slides+ }++ if not candidate_sets:+ continue+ content_slides = sorted(set.intersection(+ *(set(slides) for slides in candidate_sets.values())+ ))+ if not _is_strict_majority(len(content_slides), len(slide_nums)):+ continue++ promotions: list[tuple[str, dict[int, str]]] = []+ claimed_shape_ids: dict[int, set[str]] = {+ slide_num: set() for slide_num in content_slides+ }+ for token in sorted(candidate_sets):+ shape_ids_by_slide = {+ slide_num: candidate_sets[token][slide_num]+ for slide_num in content_slides+ }# 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+ for slide_num in content_slides):continuefor slide_num, shape_id in shape_ids_by_slide.items():@@ -607,10 +773,10 @@ def _promote_common_chrome_shapes_to_masters(shape_ids[slide_num]: tokenfor token, shape_ids in promotions}- for slide_num in slide_nums+ for slide_num in content_slides}leading_token_orders: list[list[str]] = []- for slide_num in slide_nums:+ for slide_num in content_slides:order: list[str] = []for shape_id in slide_state[slide_num]["shapes"]:token = token_by_shape_id[slide_num].get(shape_id)@@ -641,7 +807,7 @@ def _promote_common_chrome_shapes_to_masters(master_path = extract_dir / master_partmaster_rels_path = _relationships_path_for_part(extract_dir, master_part)for _token, shape_ids_by_slide in promotions:- first_slide = slide_nums[0]+ first_slide = content_slides[0]first_state = slide_state[first_slide]shape = first_state["shapes"][shape_ids_by_slide[first_slide]]master_shape = _copy_shape_relationships_to_master(@@ -660,9 +826,47 @@ def _promote_common_chrome_shapes_to_masters(sp_tree.remove(shape_to_remove)promoted += 1- for state in slide_state.values():+ for slide_num in content_slides:+ state = slide_state[slide_num]_write_xml_tree(state["path"], state["tree"])+ # Minority slides (covers, section pages) keep every shape+ # slide-local and move to a Cover layout that hides the newly+ # promoted master chrome, so their rendering never changes.+ minority_slides = [+ slide_num for slide_num in slide_nums+ if slide_num not in set(content_slides)+ ]+ if minority_slides:+ first_minority_rels = (+ extract_dir / "ppt" / "slides" / "_rels"+ / f"slide{minority_slides[0]}.xml.rels"+ )+ base_target = _find_relationship_target(+ first_minority_rels, SLIDE_LAYOUT_REL_TYPE+ )+ if not base_target:+ raise RuntimeError(+ f"Slide {minority_slides[0]} has no slide layout relationship"+ )+ base_layout_part = _resolve_package_target(+ f"ppt/slides/slide{minority_slides[0]}.xml", base_target+ )+ cover_target = _create_cover_layout(+ extract_dir, master_part, base_layout_part+ )+ for slide_num in minority_slides:+ rels_path = (+ extract_dir / "ppt" / "slides" / "_rels"+ / f"slide{slide_num}.xml.rels"+ )+ _set_slide_layout_target(rels_path, cover_target)+ if verbose:+ print(+ " Baseline cover layout: "+ f"{len(minority_slides)} slide(s) keep slide-local chrome"+ )+if verbose and promoted:print(" Baseline master chrome: "@@ -823,13 +1027,20 @@ def _prune_unused_slide_layouts(by any generated slide are always kept, and a master keeps its layoutlist untouched unless at least one referenced layout remains in it."""- referenced_layouts = {- _resolve_package_target(- f"ppt/slides/slide{slide_num}.xml",- structure.slide_layout_target(slide_num),+ # Read layout references live: earlier baseline passes may have rebound+ # minority slides to a Cover layout that the initial structure context+ # does not know about.+ referenced_layouts: set[str] = set()+ for slide_num in range(1, slide_count + 1):+ rels_path = (+ extract_dir / "ppt" / "slides" / "_rels" / f"slide{slide_num}.xml.rels"+ )+ target = _find_relationship_target(rels_path, SLIDE_LAYOUT_REL_TYPE)+ if not target:+ raise RuntimeError(f"Slide {slide_num} has no slide layout relationship")+ referenced_layouts.add(+ _resolve_package_target(f"ppt/slides/slide{slide_num}.xml", target))- for slide_num in range(1, slide_count + 1)- }pruned = 0content_types_path = extract_dir / "[Content_Types].xml"