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: preset atoms keep their paint through style compaction; beautify intake ranks sizes by text carried

hugohe36881d370d45f
diff --git a/skills/ppt-master/scripts/beautify_identity.py b/skills/ppt-master/scripts/beautify_identity.py
index 20dd54b4..6192874e 100644
--- a/skills/ppt-master/scripts/beautify_identity.py
+++ b/skills/ppt-master/scripts/beautify_identity.py
@@ -148,40 +148,64 @@ def _layout_text_sizes(pkg: "OoxmlPackage") -> list[dict]:
return _rank(sizes, 10)
-def _sample_observed(pkg: "OoxmlPackage") -> dict:
+def _theme_font_refs(fonts: dict) -> dict[str, str]:
+ """Map `+mj-lt` / `+mn-ea` style theme references to their declared faces."""
+ refs: dict[str, str] = {}
+ for prefix, role in (("+mj", "title"), ("+mn", "body")):
+ pair = fonts.get(role) or {}
+ for suffix, slot in (("lt", "latin"), ("ea", "ea"), ("cs", "cs")):
+ face = pair.get(slot)
+ if face:
+ refs[f"{prefix}-{suffix}"] = face
+ return refs
+
+
+def _sample_observed(pkg: "OoxmlPackage", font_refs: dict[str, str]) -> dict:
"""Aggregate run-level fonts, explicit point sizes, and explicit fill colors.
Theme extraction reports the *declared* identity; a hand-edited deck often
overrides it per shape / run. This is a frequency sample of run-level usage
(not a full style resolution — it misses schemeClr + master/layout
inheritance, and counts chart/gradient fills), enough for the workflow to
- recommend theme vs observed. `sizes_pt` only counts runs that set an explicit
- `sz`; runs inheriting the placeholder size are not seen here (use
- `theme.sizes` for those), so a small sample is a hint, not the full picture.
+ recommend theme vs observed. Theme font references (`+mn-ea`) count as the
+ face they resolve to. `sizes_pt` only counts runs that set an explicit `sz`
+ and ranks by the characters those runs carry, so a size split across many
+ short runs does not outrank the size that sets most of the text; runs
+ inheriting the placeholder size are not seen here (use `theme.sizes` for
+ those), so a small sample is a hint, not the full picture.
"""
latin: dict[str, int] = {}
ea: dict[str, int] = {}
- sizes: dict[float, int] = {}
+ size_runs: dict[float, int] = {}
+ size_chars: dict[float, int] = {}
colors: dict[str, int] = {}
for slide in pkg.iter_slides():
root = slide.part.xml
for tag, bucket in (("a:latin", latin), ("a:ea", ea)):
for elem in root.iterfind(f".//{tag}", NS):
face = (elem.attrib.get("typeface") or "").strip()
- if face and not face.startswith("+"): # skip +mj-*/+mn-* theme refs
+ if face.startswith("+"):
+ face = font_refs.get(face, "")
+ if face:
bucket[face] = bucket.get(face, 0) + 1
- for elem in root.iterfind(".//a:rPr", NS):
- sz = (elem.attrib.get("sz") or "").strip()
+ for run in root.iterfind(".//a:r", NS):
+ rpr = run.find("a:rPr", NS)
+ sz = (rpr.attrib.get("sz") or "").strip() if rpr is not None else ""
if sz.isdigit():
pt = int(sz) / 100
- sizes[pt] = sizes.get(pt, 0) + 1
+ size_runs[pt] = size_runs.get(pt, 0) + 1
+ size_chars[pt] = size_chars.get(pt, 0) + len(run.findtext("a:t", "", NS))
for elem in root.iterfind(".//a:srgbClr", NS):
val = (elem.attrib.get("val") or "").strip().upper()
if val:
colors[f"#{val}"] = colors.get(f"#{val}", 0) + 1
+ ranked_sizes = sorted(size_chars, key=lambda pt: (-size_chars[pt], -size_runs[pt], pt))
return {
"fonts": {"latin": _rank(latin, 5), "ea": _rank(ea, 5)},
- "sizes_pt": _rank(sizes, 8),
+ "sizes_pt": [
+ {"value": pt, "count": size_runs[pt], "chars": size_chars[pt]}
+ for pt in ranked_sizes[:8]
+ ],
"colors": _rank(colors, 8),
}
@@ -233,7 +257,7 @@ def extract_identity(pptx_path: Path) -> dict:
"slide_count": pkg.slide_count,
"canvas": canvas,
"theme": {"palette": palette, "fonts": fonts, "sizes": sizes},
- "observed": _sample_observed(pkg),
+ "observed": _sample_observed(pkg, _theme_font_refs(fonts)),
"layout_sizes_pt": _layout_text_sizes(pkg),
}
diff --git a/skills/ppt-master/scripts/compact_svg_styles.py b/skills/ppt-master/scripts/compact_svg_styles.py
index 57629105..ca8d447b 100644
--- a/skills/ppt-master/scripts/compact_svg_styles.py
+++ b/skills/ppt-master/scripts/compact_svg_styles.py
@@ -33,6 +33,7 @@ from typing import Optional
from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
+from pptx_to_svg.preset_authoring import authored_preset_encoding
from svg_to_pptx.drawingml.utils import INHERITABLE_ATTRS
configure_utf8_stdio()
@@ -339,7 +340,10 @@ def _promote_common_group_defaults(
stats: StyleCompactionStats,
) -> None:
"""Factor proven direct-child repetition into an existing SVG group."""
- if _local_name(element.tag) in _DEFINITION_SUBTREES:
+ if (
+ _local_name(element.tag) in _DEFINITION_SUBTREES
+ or authored_preset_encoding(element)
+ ):
return
for child in element:
_promote_common_group_defaults(child, stats)
@@ -357,6 +361,10 @@ def _promote_common_group_defaults(
]
if len(children) < 2:
return
+ # Helper-owned preset atoms keep their paint local; the preset contract
+ # rejects paint that only arrives from an ancestor group.
+ if any(authored_preset_encoding(child) for child in children):
+ return
element_styles = _style_declarations(element.get("style"))
if element_styles is None:
@@ -404,7 +412,10 @@ def _remove_redundant_inherited_styles(
inherited: dict[str, str],
stats: StyleCompactionStats,
) -> None:
- if _local_name(element.tag) in _DEFINITION_SUBTREES:
+ if (
+ _local_name(element.tag) in _DEFINITION_SUBTREES
+ or authored_preset_encoding(element)
+ ):
return
declarations = _style_declarations(element.get("style"))
if declarations is None:
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index ff50ff27..3f16062f 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -407,7 +407,7 @@ def finalize_project(
safe_print("[OK] Done!")
print()
print("Next steps:")
- print(f" python scripts/svg_to_pptx.py \"{project_dir}\"")
+ print(f" python3 scripts/svg_to_pptx.py \"{project_dir}\"")
return True
diff --git a/skills/ppt-master/scripts/pptx_ooxml/analyzer.py b/skills/ppt-master/scripts/pptx_ooxml/analyzer.py
index d87ce30b..776e4b41 100644
--- a/skills/ppt-master/scripts/pptx_ooxml/analyzer.py
+++ b/skills/ppt-master/scripts/pptx_ooxml/analyzer.py
@@ -183,7 +183,8 @@ def _classify_page_type(index: int, total: int, text: str, slots: list[dict[str,
return "ending_candidate"
if any(keyword in normalized for keyword in TOC_KEYWORDS):
return "toc_candidate"
- if any(keyword in normalized for keyword in CHAPTER_KEYWORDS):
+ # Body prose mentions "部分"/"part" too; only a short page reads as a divider.
+ if len(text) <= 120 and any(keyword in normalized for keyword in CHAPTER_KEYWORDS):
return "chapter_candidate"
if len(slots) <= 2 and len(text) <= 80:
return "chapter_candidate"
diff --git a/skills/ppt-master/scripts/tests/test_dogfood_leaves_fixes.py b/skills/ppt-master/scripts/tests/test_dogfood_leaves_fixes.py
index 144e7918..8001dc82 100644
--- a/skills/ppt-master/scripts/tests/test_dogfood_leaves_fixes.py
+++ b/skills/ppt-master/scripts/tests/test_dogfood_leaves_fixes.py
@@ -30,6 +30,10 @@ from svg_to_pptx.pptx_package.builder import _slide_size_type # noqa: E402
from project_management.cli import _is_project_tree, PROJECTS_ROOT # noqa: E402
from narration_sync import _project_input_path # noqa: E402
from tts_backends import backend_edge # noqa: E402
+from compact_svg_styles import compact_svg_style_tree # noqa: E402
+from pptx_to_svg.preset_authoring import validate_authored_preset_tree # noqa: E402
+from pptx_ooxml.analyzer import _classify_page_type # noqa: E402
+from beautify_identity import _theme_font_refs # noqa: E402
PDF_URL = "https://www.example.gov/content/pkg/report/pdf/report.pdf"
@@ -193,6 +197,54 @@ class PolygonFilterTests(unittest.TestCase):
self.assertIn("Polygon", xml)
+class PresetPaintCompactionTests(unittest.TestCase):
+ SVG = (
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">'
+ '<g id="rail-field" data-pptx-role="decoration" data-pptx-bounds="0 0 380 720">'
+ '<rect x="0" y="0" width="300" height="720" fill="#004B20"/>'
+ '<g id="p08-rail-edge" data-pptx-authoring="preset" data-pptx-object="shape" '
+ 'data-pptx-prst="rtTriangle" data-pptx-frame="300 0 80 720" fill="#004B20" '
+ 'stroke="none" transform="matrix(1 0 0 -1 0 720)">'
+ '<path d="M 300 720 L 300 0 L 380 720 Z"/></g>'
+ '</g></svg>'
+ )
+
+ def test_preset_keeps_local_paint(self) -> None:
+ root = ET.fromstring(self.SVG)
+ stats = compact_svg_style_tree(root)
+ self.assertEqual(stats.changed_declarations, 0)
+ self.assertEqual(validate_authored_preset_tree(root), [])
+
+ def test_parent_paint_is_not_stripped_from_preset(self) -> None:
+ root = ET.fromstring(self.SVG.replace(
+ 'data-pptx-bounds="0 0 380 720">',
+ 'data-pptx-bounds="0 0 380 720" fill="#004B20">',
+ ))
+ compact_svg_style_tree(root)
+ preset = root.find('.//*[@id="p08-rail-edge"]')
+ self.assertEqual(preset.get("fill"), "#004B20")
+ self.assertEqual(validate_authored_preset_tree(root), [])
+
+
+class BeautifyIntakeTests(unittest.TestCase):
+ def test_prose_mentioning_part_stays_content(self) -> None:
+ text = "涉及的主要扶持措施" + "对新增部分的场地按实际租金给予补贴。" * 10
+ slots = [{}, {}]
+ self.assertEqual(_classify_page_type(8, 16, text, slots), "content_candidate")
+ self.assertEqual(
+ _classify_page_type(3, 16, "第一部分 政府采购基本概念 PART ONE", slots),
+ "chapter_candidate",
+ )
+
+ def test_theme_font_refs_resolve(self) -> None:
+ refs = _theme_font_refs({
+ "title": {"latin": "Verdana", "ea": "微软雅黑"},
+ "body": {"latin": "Verdana", "ea": "微软雅黑"},
+ })
+ self.assertEqual(refs["+mn-ea"], "微软雅黑")
+ self.assertEqual(refs["+mj-lt"], "Verdana")
+
+
class SlideSizeTypeTests(unittest.TestCase):
def test_standard_ratios_keep_their_token(self) -> None:
self.assertEqual(_slide_size_type(12192000, 6858000), "screen16x9")
diff --git a/skills/ppt-master/workflows/profiles/beautify-pptx.md b/skills/ppt-master/workflows/profiles/beautify-pptx.md
index 1ac4a000..20a445c6 100644
--- a/skills/ppt-master/workflows/profiles/beautify-pptx.md
+++ b/skills/ppt-master/workflows/profiles/beautify-pptx.md
@@ -46,7 +46,7 @@ python3 ${SKILL_DIR}/scripts/project_manager.py import-sources <project_path> <s
`import-sources` already wrote the standard PPTX intake bundle under `analysis/` (for an older project, `pptx_intake.py <project_path>/sources/<source.pptx> -o <project_path>/analysis` once) and ran `ppt_to_md`, so the **frozen content contract** is `sources/<stem>.md` (one source slide per block, in order) and extracted pictures are in `images/` with per-slide binding in `images/image_manifest.json` (`occurrences[].slide_index`); never re-run `ppt_to_md`.
-**Visual identity** — read `analysis/<stem>.identity.json`: `theme.palette.background` / `text` / `primary` / `accent1..6` and `theme.fonts.title` / `body` (`latin` / `ea` / `cs`, with `scripts` mapping `Hans` / `Hant` / `Jpan` / `Hang` supplemental faces — use the matching script when `ea` is empty) are what the deck declares; `theme.sizes.title` / `body` (pt) are the master placeholder defaults, `body` being the coarse level-1 value that commonly over-reads, with `theme.sizes.body_levels` as the full ramp for reference; `observed.colors` / `observed.fonts` / `observed.sizes_pt` are frequency-ranked samples of run-level overrides (not a complete style resolution — they miss `schemeClr` and inheritance and count chart/gradient fills); `layout_sizes_pt` is a reference fact only; `canvas.aspect` drove Step 3. A hand-edited deck can diverge from `theme`; Step 5 resolves which to use.
+**Visual identity** — read `analysis/<stem>.identity.json`: `theme.palette.background` / `text` / `primary` / `accent1..6` and `theme.fonts.title` / `body` (`latin` / `ea` / `cs`, with `scripts` mapping `Hans` / `Hant` / `Jpan` / `Hang` supplemental faces — use the matching script when `ea` is empty) are what the deck declares; `theme.sizes.title` / `body` (pt) are the master placeholder defaults, `body` being the coarse level-1 value that commonly over-reads, with `theme.sizes.body_levels` as the full ramp for reference; `observed.colors` / `observed.fonts` / `observed.sizes_pt` are frequency-ranked samples of run-level overrides (`sizes_pt` by characters carried) (not a complete style resolution — they miss `schemeClr` and inheritance and count chart/gradient fills); `layout_sizes_pt` is a reference fact only; `canvas.aspect` drove Step 3. A hand-edited deck can diverge from `theme`; Step 5 resolves which to use.
**Hard rule — regenerate visuals, do not carry them over**: charts / tables / images are rebuilt from their data in the effective style, never spliced byte-for-byte; data values are frozen, only rendering is the deck's own; pictures are reused but re-laid-out. A user who wants an original element verbatim copies it across themselves.
@@ -65,7 +65,7 @@ Use the cleaned `svg-flat/slide_*.svg` pages and `svg-flat_vector_asset_inventor
python3 ${SKILL_DIR}/scripts/beautify_inventory.py <project_path>/analysis/<stem>.slide_library.json --images <project_path>/images/image_manifest.json -o <project_path>/analysis/beautify_inventory.json
```
-Omit `--images` when no pictures were extracted. It joins `text_blocks`, `tables`, `charts`, `diagrams` (SmartArt nodes + hierarchy + source layout), and `images` (bound through `image_manifest` `occurrences[].slide_index`, with geometry and `usage_count`) per slide with frozen values inlined, and emits empty `ignored` and `needs_confirmation` arrays to fill with judgment: `ignored` — hidden slides/shapes, master-only text, image crop/opacity/rotation/mask; `needs_confirmation` — unreadable SmartArt, combo / dual-axis / waterfall charts, merged-cell or multi-header tables, density outliers (overcrowded or near-empty). SmartArt keeps its wording and relationships and is redrawn as ordinary editable shapes, never regenerated natively.
+Omit `--images` when no pictures were extracted. It joins `text_blocks`, `tables`, `charts`, `diagrams` (SmartArt nodes + hierarchy + source layout), and `images` (bound through `image_manifest` `occurrences[].slide_index`, with geometry and `usage_count`) per slide with frozen values inlined, and emits empty `ignored` and `needs_confirmation` arrays to fill with judgment: `ignored` — hidden slides/shapes, master-only text, full-slide template-skin or fully covered pictures, image crop/opacity/rotation/mask; `needs_confirmation` — unreadable SmartArt, combo / dual-axis / waterfall charts, merged-cell or multi-header tables, density outliers (overcrowded or near-empty). SmartArt keeps its wording and relationships and is redrawn as ordinary editable shapes, never regenerated natively.
**Mandatory — bounded inventory reads**: the complete inventory is the validation ledger, not the authoring prompt. Read `beautify_inventory.py <inventory> --summary`, then `--page <N>`, adding `--with-geometry` only for structural ambiguity; never bulk-read either complete file during authoring.
@@ -116,7 +116,7 @@ Do not run the Default confirmation flow. Apply the same inventory interpretatio
"design_directions": {"selected": 0, "candidates": [
{"id": "source-replica", "name_en": "Source replica (recommended)", "mode": "custom", "mode_behavior_zh": "briefing 基底;逐页结构、顺序与文字 1:1 逐字不变。", "visual_style": "custom", "visual_style_behavior_zh": "复刻源 PPT 视觉身份与版式。", "icons": "…",
"color": {"palette": {"background": "#...", "secondary_bg": "#...", "primary": "#...", "accent": "#...", "secondary_accent": "#...", "body_text": "#..."}},
- "typography": {"heading": {"primary": "…"}, "body": {"primary": "…"}, "body_size": "<dominant observed.sizes_pt × 4/3, as px>"},
+ "typography": {"heading": {"primary": "…"}, "body": {"primary": "…"}, "body_size": "<dominant observed.sizes_pt × 4/3 × canvas scale, as px>"},
"image_strategy": {"rendering": "custom", "behavior_zh": "…"}},
{"id": "alternative-a", "...": "same shape; body_size = canvas-appropriate baseline"},
{"id": "alternative-b", "...": "same shape"}
@@ -126,7 +126,7 @@ Do not run the Default confirmation flow. Apply the same inventory interpretatio
- **Recommend keep, allow override**: pre-fill the communication contract from the source's apparent audience and purpose (composite purposes in prose; examples are hints, never a `primary_job` selector) and canvas / mode / visual style / icons / image strategy with the source-faithful default (mode `briefing`, `image_usage` `provided`). The only true non-choices are frozen text and strict 1:1 page count; `content_divergence` is seeded verbatim with `locked: true` (the UI renders it read-only and restores it on every submit). A request to reshape wording or structure routes to the main pipeline.
- **The pre-selected default is the source replica** (`selected: 0`): the candidate that best replicates the source's `theme` / `observed` style. Author the other candidates with the same content-driven judgment the Strategist uses from scratch (color §e, typography §g) — palette and font pairing chosen for this deck's content, ≥3 meaningful candidates, no manufactured pairings to fill a quota; `primary` follows the source language, `english` only when that language is not English.
-- **`body_size` is load-bearing and the replica follows the source's own size**: seed it from the dominant `observed.sizes_pt` value converted to px (`× 4/3` — a 20pt body becomes `26.67`; seeding bare `20` shrinks it ~25%, the pt-as-px trap); the confirm page writes that px to `result.json` and the chat branch retains it, with no second conversion and no `body_size_pt`. The most-frequent-size proxy counts titles, captions, and chart labels too, so cross-check it against the page's actual body blocks and prefer the size body paragraphs visibly render at. Seed chain: `observed` → `theme.sizes.body` (a level-1 default that over-reads; treat as an upper-ish guess) → the consumption-mode baseline (`text` 20 / `balanced` 24 / `presentation` 32 px); `body_levels` and `layout_sizes_pt` are reference context for judging a saner value, never auto-seeds. The canvas hint is a sanity range, not the seed — when the source size lands far outside it, surface that to the user rather than snapping. Alternatives may use the consumption-mode baseline.
+- **`body_size` is load-bearing and the replica follows the source's own size**: seed it from the dominant `observed.sizes_pt` value converted to px (`× 4/3` — a 20pt body becomes `26.67`; seeding bare `20` shrinks it ~25%, the pt-as-px trap), then scaled by Step 3's canvas width ÷ `canvas.width_px` when they differ (a 960px-wide source on `ppt169` multiplies by 4/3 again); the confirm page writes that px to `result.json` and the chat branch retains it, with no second conversion and no `body_size_pt`. The most-frequent-size proxy counts titles, captions, and chart labels too, so cross-check it against the page's actual body blocks and prefer the size body paragraphs visibly render at. Seed chain: `observed` → `theme.sizes.body` (a level-1 default that over-reads; treat as an upper-ish guess) → the consumption-mode baseline (`text` 20 / `balanced` 24 / `presentation` 32 px); `body_levels` and `layout_sizes_pt` are reference context for judging a saner value, never auto-seeds. The canvas hint is a sanity range, not the seed — when the source size lands far outside it, surface that to the user rather than snapping. Alternatives may use the consumption-mode baseline.
Run Step 4's confirmation orchestration unchanged. In the UI branch read `confirm_ui/result.json` exactly once after the final wait and run `--shutdown` before Step 6; in the chat branch retain the visible final summary. Then enter Step 4 as Strategist with the plan pre-resolved under the two invariants — the content-faithful clause ([`strategist.md`](../../references/strategist.md) §d Layer 1) and page count = source slide count — writing the confirmed state completely into `design_spec.md` (mode, canvas, visual style, color + typography incl. `body_size`; skip both recommendation flows). §VII holds only `Page | Family | Template | Usage` rows for selected `chart` / `table` references projected into `spec_lock.md page_visualizations`; qualitative relationships stay in §IX; §VIII holds source pictures for re-layout.
@@ -144,7 +144,7 @@ Run Step 4's confirmation orchestration unchanged. In the UI branch read `confir
## 7. Validate Output
-`python3 ${SKILL_DIR}/scripts/source_to_md/ppt_to_md.py <project_path>/exports/<output.pptx>` — every source text string appears unaltered; chart categories / series / table cells match exactly; slide count equals the source; charts/tables are native SVG in the effective palette; text and shapes use the effective colors and fonts; paste-back elements retain palette and font declarations (alignment and font availability not guaranteed).
+`python3 ${SKILL_DIR}/scripts/source_to_md/ppt_to_md.py <project_path>/exports/<output.pptx>` — every source text string appears unaltered (read-back orders text by position and splits at authored line breaks, so compare each page as whitespace-stripped containment, not sequence); chart categories / series / table cells match exactly; slide count equals the source; charts/tables are native SVG in the effective palette; text and shapes use the effective colors and fonts; paste-back elements retain palette and font declarations (alignment and font availability not guaranteed).
```markdown
## ✅ Beautify Complete