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-import): rebuild formulas whose colors are theme tokens or translucent
hugohe3029201fe0f7a
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.mdindex eb21073a..be983de7 100644--- a/docs/powerpoint-svg-mapping.md+++ b/docs/powerpoint-svg-mapping.md@@ -214,7 +214,7 @@ The exhaustive chart/table schemas and supported family list intentionally remai| LaTeX input profile | Canonical marker sources omit outer delimiters; one complete `$...$`, `$$...$$`, `\(...\)`, or `\[...\]` pair is also accepted | Every explicitly named input in the pinned Microsoft 365 2606 / Mac 16.110 profile, plus the 2605 / 16.109 mhchem profile, compiles to editable OMML | The profile is pinned to those Microsoft documentation versions; emitted OMML retains the PowerPoint 2010+ package target. Repository verification is compiler/OMML/package-level, not complete Microsoft 365 UI certification | Explicit native normalizations are preserved; unknown or explicitly unsupported input fails closed rather than leaking as literal LaTeX || Editable block equation | One `<g data-pptx-replace-with="formula">` with explicit bounds, source LaTeX in `<metadata type="application/json">`, and visible SVG preview children | PowerPoint text shape containing `a14:m > m:oMathPara > m:oMath` | See the input-profile row | Matrices, multiline derivations, and other standalone high-structure formulas use the registered block contract || Editable inline formula | A leaf `<tspan data-pptx-inline-formula="canonical LaTeX body">preview text</tspan>` among ordinary text runs | The same DrawingML `a:p` retains surrounding runs and inserts `a14:m > m:oMath` | See the input-profile row | Direct non-empty preview text only; no child element, positional `x/y/dx/dy`, structured placeholder/Master/Layout ownership, preserved imported `txBody`, or native-replacement ancestor |-| PPTX formula reverse import | Validator-clean `m:oMathPara` becomes a block marker; validator-clean `m:oMath` remains an inline marker with surrounding runs | Re-export recompiles the canonicalized LaTeX to editable OMML | `Native-normalized` for PPT Master-owned closed OMML vocabulary | The original LaTeX spelling is not recoverable; unknown third-party OMML gets `formula-not-reconstructed`, readable text, and relationship-free opaque `txBody` retention in tolerant mode |+| PPTX formula reverse import | Color-normalized, validator-clean `m:oMathPara` becomes a block marker; corresponding `m:oMath` remains an inline marker with surrounding runs | Re-export recompiles the canonicalized LaTeX to editable OMML | `Native-normalized` for PPT Master-owned closed OMML vocabulary | Color, transparency, and diagnosed opaque-`txBody` retention follow [Native formula reverse import](../skills/ppt-master/scripts/docs/conversion.md#native-formula-reverse-import) || Browser / live preview | Ordinary SVG children inside a block marker, or the inline marker's direct text | The registered preview becomes the native-shape `mc:Fallback` beside the native math | Raw LaTeX does not render in SVG | Preview content must express the same formula; non-PowerPoint clients show it || Formula typography | Block payload style, or computed inline text-run style | Math inherits size and visible solid fill, then uses the project text language and Cambria Math; local `\color` / `\textcolor` scopes override the inherited fill on selectable runs and structural controls, while `\boldsymbol` / `\bm` also styles structural control glyphs | PowerPoint 2010+ OMML | High-structure or multiline math remains block-level || Non-PowerPoint formula playback | The same native markers | `mc:Fallback` carries the SVG preview as ordinary shapes and text; no picture branch | Keynote, WPS, LibreOffice, and other clients are outside the formula contract | The fallback is visible, not editable math; do not claim cross-client rendering or editability |@@ -226,8 +226,9 @@ PNG, media relationship, or `mc:Fallback` picture. Block JSON and inlinecontent keeps the authored page visible before export and becomes thenative-shape `mc:Fallback` after it. Import reads the `mc:Choice` branch only.`pptx_to_svg.py` performs the narrow inverse only for OMML accepted by the same-closed validator, and its output is canonical LaTeX rather than the author's-original spelling. It does not claim arbitrary Office Math conversion.+closed validator after import-only color normalization, and its output is+canonical LaTeX rather than the author's original spelling. It does not claim+arbitrary Office Math conversion.The executable closed vocabulary and pinned Microsoft source revisions live in`formula_profile.py`; Microsoft's open-ended “etc.” does not make undisclosedrelation aliases part of this contract.diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.mdindex 3489655c..80cef40e 100644--- a/docs/zh/powerpoint-svg-mapping.md+++ b/docs/zh/powerpoint-svg-mapping.md@@ -209,7 +209,7 @@ PowerPoint 原生 Chart/Table 对象是可选功能。默认导出保留 SVG fal| LaTeX 输入档位 | 规范 marker 源不写外层定界符;也接受一对完整的 `$...$`、`$$...$$`、`\(...\)` 或 `\[...\]` | 锁定的 Microsoft 365 2606 / Mac 16.110 档位中所有明确点名的输入,以及 2605 / 16.109 mhchem 档位,均编译为可编辑 OMML | 档位锁定到这些 Microsoft 文档版本;产出的 OMML 仍保持 PowerPoint 2010+ 包目标。仓库验证覆盖编译器、OMML 与包结构,不等同于完整的 Microsoft 365 UI 认证 | 保留文档明确规定的原生归一化;未知或明确不支持的输入直接失败,不把 LaTeX 字面量漏进页面 || 可编辑块级公式 | 一个带显式边界、在 `<metadata type="application/json">` 中保存源 LaTeX、并含可见 SVG 预览子元素的 `<g data-pptx-replace-with="formula">` | 含 `a14:m > m:oMathPara > m:oMath` 的 PowerPoint 文本 shape | 见输入档位行 | 矩阵、多行推导等独立高结构公式使用块级合同 || 可编辑行内公式 | 普通文本 run 中的叶子 `<tspan data-pptx-inline-formula="规范 LaTeX body">preview text</tspan>` | 同一 DrawingML `a:p` 保留前后 run,并插入 `a14:m > m:oMath` | 见输入档位行 | 只允许非空直接预览文本;禁止子元素、`x/y/dx/dy`、结构化 placeholder / Master / Layout 归属、保留的导入 `txBody` 或原生替换祖先 |-| PPTX 公式反向导入 | 通过校验的 `m:oMathPara` 变为块级 marker;通过校验的 `m:oMath` 与前后 run 一起保留为行内 marker | 再导出时把规范化 LaTeX 编译回可编辑 OMML | 对 PPT Master 自有封闭 OMML 词汇为 `Native-normalized` | 无法恢复原 LaTeX 写法;未知第三方 OMML 在 tolerant 模式下产生 `formula-not-reconstructed`、可读文本,并在无 relationship 时以不透明 `txBody` 保留 |+| PPTX 公式反向导入 | 经过颜色归一化并通过校验的 `m:oMathPara` 变为块级 marker;对应的 `m:oMath` 与前后 run 一起保留为行内 marker | 再导出时把规范化 LaTeX 编译回可编辑 OMML | 对 PPT Master 自有封闭 OMML 词汇为 `Native-normalized` | 颜色、透明度以及诊断后以不透明 `txBody` 保留的边界见[原生公式反向导入](../../skills/ppt-master/scripts/docs/conversion.md#native-formula-reverse-import) || 浏览器 / 实时预览 | 块级 marker 内的普通 SVG 子元素,或行内 marker 的直接文本 | 已登记预览转为原生公式旁的原生形状 `mc:Fallback` | 原始 LaTeX 不能直接在 SVG 中渲染 | 预览必须表达同一公式;非 PowerPoint 客户端显示它 || 公式字体 | 块级 payload 样式,或行内文本 run 的计算样式 | 公式继承字号与可见纯色填充,并使用项目文本语言和 Cambria Math;局部 `\color` / `\textcolor` 作用域会覆盖可选中文字 run 与结构控制符的继承填充,`\boldsymbol` / `\bm` 也会设置结构控制字形的样式 | PowerPoint 2010+ OMML | 高结构或多行数学内容仍使用块级形式 || 非 PowerPoint 客户端播放 | 同一类原生 marker | `mc:Fallback` 以普通形状和文字承载 SVG 预览;没有图片分支 | Keynote、WPS、LibreOffice 等客户端不在公式合同内 | 兜底只可见、不是可编辑公式;不宣称跨客户端显示或编辑能力 |@@ -219,7 +219,7 @@ PowerPoint 原生 Chart/Table 对象是可选功能。默认导出保留 SVG fal`mc:Fallback`。块级 JSON 和行内 `data-pptx-inline-formula` 的值是原生公式源;SVG 预览内容让导出前的作者页面保持可见,导出后成为原生形状 `mc:Fallback`。导入只读取 `mc:Choice` 分支。-`pptx_to_svg.py` 只对通过同一封闭校验器的 OMML 执行窄反向导入,产出的是+`pptx_to_svg.py` 先执行仅限导入端的颜色归一化,再对通过同一封闭校验器的 OMML 执行窄反向导入,产出的是规范化 LaTeX,而不是作者原始写法;它不宣称任意 Office Math 转换。可执行闭合集与锁定的 Microsoft 来源修订记录在 `formula_profile.py`;Microsoft文档中开放式的 “etc.” 不会把未披露的 relation alias 自动纳入本合同。diff --git a/skills/ppt-master/scripts/docs/conversion.md b/skills/ppt-master/scripts/docs/conversion.mdindex e175611c..ff09ec26 100644--- a/skills/ppt-master/scripts/docs/conversion.md+++ b/skills/ppt-master/scripts/docs/conversion.md@@ -376,9 +376,10 @@ replacement timing tree.### Native formula reverse import-The importer reconstructs formulas only from the closed OMML vocabulary owned-by the native formula compiler. One formula-only `a14:m > m:oMathPara` text-shape becomes a bounded `<g data-pptx-replace-with="formula">` with canonical+The importer reconstructs formulas from the native compiler's closed OMML+vocabulary after the import-only color normalization below. One formula-only+`a14:m > m:oMathPara` text shape becomes a bounded+`<g data-pptx-replace-with="formula">` with canonicalLaTeX JSON and a visible linear SVG preview when its carrier is an ungrouped,unstyled, unrotated rectangular formula shape. Carrier styling, effects,hyperlinks, or placeholder ownership force diagnosed fallback rather than@@ -388,8 +389,43 @@ Supported `a14:m > m:oMath` zones inside an ordinary paragraph become leaftheir surrounding text runs. The generated markers pass the same native-objectand inline-formula validators used by SVG-to-PPTX export.+**Color normalization** applies only to `a:solidFill` directly inside+`m:r/a:rPr` or `m:ctrlPr/a:rPr`. Each fill must contain exactly one correctly+namespaced `a:srgbClr` or `a:schemeClr`. The shared color resolver uses the+caller's effective palette and color map, never a fixed `theme1.xml`, and+strictly validates color attributes and the supported `alpha`, `alphaMod`,+and `alphaOff` modifiers even during tolerant import. The importer validates+resource limits before normalization and changes a copy of the OMML only.+Resolved RGB replaces the color node before the unchanged compiler validator+runs. The resolved marker color is the formula's base: block JSON `color` or+inline run `fill`. Serialization omits run and control colors already supplied+by that base or an enclosing local color scope. Only changes to the effective+color become LaTeX `\textcolor` scopes; nested scopes can explicitly restore+the base color when needed. Theme tokens become current RGB values and lose+their original theme-token linkage. Re-export applies the exporter's existing anchor mapping+to marker defaults; local LaTeX color scopes remain explicit RGB overrides.++**Transparency** must remain representable by the destination marker and its+existing exporter. Inline formulas retain one uniform effective alpha across+their runs and controls through the marker's `fill` / `fill-opacity` style;+surrounding runs retain their own opacity. This includes the uniform alpha+emitted by PPT Master's inline exporter with local color overrides. Alpha+must fit DrawingML's 1/100000 precision. Mixed alpha, including an opaque run+or control among translucent ones, is not reconstructed. Block markers keep+RGB in JSON `color`; their existing exporter emits opaque RGB only, so a+translucent block formula also takes the diagnosed opaque-`txBody` path.+Alpha is never discarded to make a formula pass validation.++Canonical read-back uses explicit braces for script bases and argument bodies,+`\left` / `\right` for delimiter nodes, Unicode glyphs for symbols, `\mathrm`+for upright math runs, and `\mathop` for function nodes. Insignificant source+whitespace is not recovered. Recompilation may split or join adjacent runs+with identical effective styling without changing their text or appearance.+This is normalized semantic read-back, not recovery of the author's original-LaTeX spelling and not a general Office Math converter. Every OMML root must+LaTeX spelling and not a general Office Math converter. Multiple color+children, incorrect namespaces, unresolved theme colors, unsupported modifiers,+and unknown OMML remain outside the reversible subset. Every normalized root mustpass the compiler's namespace, element, attribute, structure, size, and depthgates, and the reconstructed LaTeX must compile again under the same profile.If any formula in one text body falls outside that boundary, tolerant importdiff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex a6dcddd3..ef1fb94d 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -1038,6 +1038,13 @@ Behind [`native-formula.md`](../../references/native-formula.md) §3. The compil**Normalization**: `\dfrac` / `\tfrac`, `\dbinom` / `\tbinom`, and continued-fraction alignment normalize to the corresponding OMML structure; explicit big-delimiter grades become auto-sizing delimiters; `\mathscr` → `\mathcal`; `smallmatrix` → `matrix`; array columns become centered; style/size commands and equation tags are accepted but not stored. Color is stored in generated formula runs and structural control properties; `\boldsymbol` / `\bm` applies bold-italic to structural control glyphs.+The compiler validates its output against the closed OMML grammar before+marker-level defaults are applied.+The block and inline builders then merge marker-level run/control styles;+the inline exporter can emit theme colors and alpha in that styled OMML.+The import-only normalization and transparency boundary are owned by+[`conversion.md`, Native formula reverse import](conversion.md#native-formula-reverse-import).+**Fail-closed**: unknown commands or environments, Microsoft's explicitly unsupported commands, unsupported mhchem arrows, unescaped `%` comments, invalid macros, and resource-limit overflow block conversion — stricter than Microsoft 365's literal-text passthrough and macro-limit behavior.**Compatibility**: the package uses standard editable Office Math and keeps the PowerPoint 2010+ target; the executable profile is pinned to the documentation versions above. Repository verification covers compilation, OMML structure, and PPTX packaging, not a Microsoft 365 UI rendering/editability certification. Earlier PowerPoint versions are not the source-profile baseline; WPS, Keynote, LibreOffice, and other clients receive only the native-shape preview fallback. Reverse import is described in [`conversion.md`](conversion.md#native-formula-reverse-import).diff --git a/skills/ppt-master/scripts/pptx_to_svg/formula_import.py b/skills/ppt-master/scripts/pptx_to_svg/formula_import.pyindex 1e3ce79c..935907fe 100644--- a/skills/ppt-master/scripts/pptx_to_svg/formula_import.py+++ b/skills/ppt-master/scripts/pptx_to_svg/formula_import.py@@ -1,9 +1,10 @@"""Import PPT Master-owned Office Math into canonical SVG formula markers.-The reverse contract is deliberately narrow: accept only the closed OMML-vocabulary already validated by the native formula compiler, serialize that-structure to compiler-accepted LaTeX, and build a plain-text SVG preview.+The reverse contract is deliberately narrow: normalize supported DrawingML+colors, validate the compiler's closed OMML vocabulary, serialize that structure+to compiler-accepted LaTeX, and build a plain-text SVG preview.Unknown third-party OMML remains outside this module's reconstruction claim.+See scripts/docs/conversion.md, Native formula reverse import, for the boundary."""from __future__ import annotations@@ -22,6 +23,10 @@ from svg_to_pptx.native_objects.formula_profile import (ACCENT_COMMANDS,NARY_COMMANDS,)+from svg_to_pptx.native_objects.formula_omml import validate_omml_resource_limits++from .color_resolver import ColorPalette, resolve_color+from .emu_units import format_ooxml_alphaMATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"@@ -89,9 +94,15 @@ class FormulaImport:color: stralign: strlanguage: str+ opacity: float-def import_formula(math_zone: ET.Element, *, display: bool) -> FormulaImport:+def import_formula(+ math_zone: ET.Element,+ *,+ display: bool,+ palette: ColorPalette | None = None,+) -> FormulaImport:"""Validate and reconstruct one ``a14:m`` formula zone."""if math_zone.tag != _A14_M:raise FormulaImportError("formula carrier must be one a14:m element")@@ -107,10 +118,17 @@ def import_formula(math_zone: ET.Element, *, display: bool) -> FormulaImport:)try:- canonical = validate_omml_fragment(+ bounded = validate_omml_resource_limits(ET.tostring(root, encoding="unicode", short_empty_elements=True))+ normalized_root = ET.fromstring(bounded)+ opacity = _normalize_colors(normalized_root, palette)+ if display and opacity != 1.0:+ raise FormulaImportError("block formula metadata color cannot retain transparency")+ canonical = validate_omml_fragment(ET.tostring(normalized_root, encoding="unicode"))validated_root = ET.fromstring(canonical)+ font_size_px, color, language = _dominant_run_style(validated_root)+ _omit_inherited_colors(validated_root, color[1:])latex = _serialize_root(validated_root)if display:compile_latex_to_omml(latex)@@ -122,7 +140,6 @@ def import_formula(math_zone: ET.Element, *, display: bool) -> FormulaImport:preview = _preview_root(validated_root).strip()if not latex.strip() or not preview:raise FormulaImportError("formula reconstruction produced empty content")- font_size_px, color, language = _dominant_run_style(validated_root)return FormulaImport(latex=latex,preview=preview,@@ -130,9 +147,47 @@ def import_formula(math_zone: ET.Element, *, display: bool) -> FormulaImport:color=color,align=_formula_alignment(validated_root),language=language,+ opacity=opacity,)+def _normalize_colors(root: ET.Element, palette: ColorPalette | None) -> float:+ """Normalize only run/control fills on a copy, retaining one uniform alpha."""+ opacities: set[float] = set()+ for owner in root.iter():+ if owner.tag not in {f"{_M}r", f"{_M}ctrlPr"}:+ continue+ fills = owner.findall(f"{_A}rPr/{_A}solidFill")+ if not fills:+ opacities.add(1.0)+ for fill in fills:+ colors = list(fill)+ if (+ fill.attrib or (fill.text or "").strip()+ or len(colors) != 1+ or colors[0].tag not in {f"{_A}srgbClr", f"{_A}schemeClr"}+ or (colors[0].tail or "").strip()+ ):+ raise FormulaImportError("formula solidFill requires one a:srgbClr or a:schemeClr")+ color = colors[0]+ if any(child.tag not in {f"{_A}alpha", f"{_A}alphaMod", f"{_A}alphaOff"} for child in color):+ raise FormulaImportError("unsupported formula color modifier")+ try:+ rgb, alpha = resolve_color(color, palette, strict=True)+ except ValueError as exc:+ raise FormulaImportError(str(exc)) from exc+ if rgb is None:+ raise FormulaImportError("formula color cannot be resolved in the current palette")+ if alpha != float(format_ooxml_alpha(alpha)):+ raise FormulaImportError("formula alpha cannot be retained at DrawingML precision")+ opacities.add(alpha)+ fill.remove(color)+ ET.SubElement(fill, f"{_A}srgbClr", {"val": rgb[1:]})+ if len(opacities) > 1:+ raise FormulaImportError("mixed formula transparency cannot be represented by one marker")+ return next(iter(opacities), 1.0)++def opaque_formula_preview(math_zone: ET.Element) -> str:"""Return readable source text without claiming native reconstruction."""text = "".join(@@ -142,6 +197,23 @@ def opaque_formula_preview(math_zone: ET.Element) -> str:return text or "[unsupported formula]"+def _omit_inherited_colors(element: ET.Element, inherited_color: str) -> None:+ """Keep only color changes in the validated serialization copy."""+ if element.tag == f"{_M}r":+ properties = element.find(f"{_A}rPr")+ else:+ name = _local_name(element)+ properties = element.find(f"{_M}{name}Pr/{_M}ctrlPr/{_A}rPr")+ color = _drawing_color(properties)+ if color == inherited_color:+ properties.remove(properties.find(f"{_A}solidFill"))+ # A retained structural scope supplies its color to the whole subexpression.+ # A descendant may still need an explicit scope to restore the marker base.+ for child in element:+ if not _local_name(child).endswith(_PROPERTY_SUFFIX):+ _omit_inherited_colors(child, color or inherited_color)++def _serialize_root(root: ET.Element) -> str:if root.tag == f"{_M}oMathPara":math = root.find(f"{_M}oMath")@@ -172,6 +244,15 @@ def _serialize_argument(owner: ET.Element, name: str, *, alignment: bool = Falsedef _serialize_node(element: ET.Element, *, alignment: bool = False) -> str:+ source = _serialize_node_content(element, alignment=alignment)+ # A scoped color must cover structural glyphs as well as selectable runs.+ name = _local_name(element)+ control = element.find(f"{_M}{name}Pr/{_M}ctrlPr/{_A}rPr")+ color = _drawing_color(control)+ return f"\\textcolor{{#{color}}}{{{source}}}" if color is not None else source+++def _serialize_node_content(element: ET.Element, *, alignment: bool = False) -> str:name = _local_name(element)if name == "r":return _serialize_run(element, alignment=alignment)diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.pyindex d97411d9..a8531bc7 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@@ -604,7 +604,7 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->)if carrier_error is not None:raise FormulaImportError(carrier_error)- imported_formula = import_formula(block_formula, display=True)+ imported_formula = import_formula(block_formula, display=True, palette=ctx.palette)except FormulaImportError as exc:_diagnose_formula_fallback(ctx, exc)block_formula_failed = True@@ -1036,18 +1036,18 @@ def _prepare_inline_formula_resolver(elif not force_opaque:for zone in zones:try:- imported[id(zone)] = import_formula(zone, display=False)+ imported[id(zone)] = import_formula(zone, display=False, palette=ctx.palette)except FormulaImportError as exc:failed = True_diagnose_formula_fallback(ctx, exc)- def _resolve(zone: ET.Element) -> tuple[str | None, str]:+ def _resolve(zone: ET.Element) -> tuple[FormulaImport | None, str]:if failed:return None, opaque_formula_preview(zone)item = imported.get(id(zone))if item is None:return None, opaque_formula_preview(zone)- return item.latex, item.preview+ return item, item.previewreturn _resolvediff --git a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.pyindex 734eb9a7..1aead190 100644--- a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py@@ -37,6 +37,7 @@ from .emu_units import (hundredths_pt_to_px, ooxml_bool,)from .fill_to_svg import resolve_fill+from .formula_import import FormulaImport# ---------------------------------------------------------------------------@@ -75,7 +76,7 @@ class TextRun:HyperlinkResolver = Callable[[str, str], str | None]-InlineFormulaResolver = Callable[[ET.Element], tuple[str | None, str]]+InlineFormulaResolver = Callable[[ET.Element], tuple[FormulaImport | None, str]]TextDiagnosticSink = Callable[[str, str, str], None]@@ -782,14 +783,17 @@ def _parse_paragraph(== "{http://schemas.microsoft.com/office/drawing/2010/main}m"and inline_formula_resolver is not None):- latex, preview = inline_formula_resolver(child)+ formula, preview = inline_formula_resolver(child)if preview:formula_rpr = next(child.iter(f"{{{NS['a']}}}rPr"),None,)run = resolved_run(preview, formula_rpr)- run.formula_latex = latex+ if formula is not None:+ run.formula_latex = formula.latex+ run.fill = formula.color+ run.fill_opacity = formula.opacitypara.runs.append(run)return para@@ -1700,14 +1704,19 @@ def _emit_paragraph(else:spans.append(_run_tspan_markup(run))- base_attrs = _text_base_attrs(first_run, anchor_x, first_baseline, text_anchor)+ # Formula paragraphs carry alpha per run, so a translucent first run must+ # not make opaque formulas or surrounding text inherit that alpha.+ base_attrs = _text_base_attrs(+ first_run, anchor_x, first_baseline, text_anchor,+ inherit_opacity=not any(run.formula_latex is not None for line in visible_lines for run in line),+ )if metrics_baseline:base_attrs += ' data-pptx-text-baseline="metrics-v1"'return f"<text{base_attrs}>{''.join(spans)}</text>"def _text_base_attrs(run: TextRun | None, x: float, y: float,- text_anchor: str) -> str:+ text_anchor: str, *, inherit_opacity: bool = True) -> str:parts = [f'x="{fmt_num(x)}"',f'y="{fmt_num(y, 8)}"',@@ -1719,7 +1728,7 @@ def _text_base_attrs(run: TextRun | None, x: float, y: float,parts.append(f'font-family="{run.font_family}"')parts.append(f'font-size="{fmt_num(run.font_size_px)}"')parts.append(f'fill="{run.fill}"')- if run.fill_opacity < 1.0:+ if inherit_opacity and run.fill_opacity < 1.0:parts.append(f'fill-opacity="{format_ooxml_alpha(run.fill_opacity)}"')diff --git a/skills/ppt-master/scripts/tests/test_formula_import_colors.py b/skills/ppt-master/scripts/tests/test_formula_import_colors.pynew file mode 100644index 00000000..ca466fa8--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_formula_import_colors.py@@ -0,0 +1,345 @@+#!/usr/bin/env python3+"""+PPT Master - Native Formula Import Color Regression Tests++Exercise formula color normalization through the public import and SVG+converters, including native re-export and opaque text-body retention.++Usage:+ python3 -m unittest tests.test_formula_import_colors++Examples:+ Run the module from the scripts directory.++Dependencies:+ Standard library and the local PPT Master converters.+"""++from __future__ import annotations++import base64+import json+import sys+import tempfile+import unittest+import zipfile+from html import escape+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:+ sys.path.insert(0, str(SCRIPTS_DIR))++from pptx_to_svg.color_resolver import ColorPalette, resolve_color # noqa: E402+from pptx_to_svg.formula_import import FormulaImportError, import_formula # noqa: E402+from pptx_to_svg.ooxml_loader import OoxmlPackage # noqa: E402+from pptx_to_svg.slide_to_svg import assemble_slide # noqa: E402+from svg_to_pptx.drawingml.converter import convert_svg_to_slide_shapes # noqa: E402+from svg_to_pptx.drawingml.theme_colors import ThemeColorSpec # noqa: E402+from svg_to_pptx.native_objects.formula_compiler import ( # noqa: E402+ FormulaCompileError,+ validate_omml_fragment,+)++NS = {+ 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',+ 'a14': 'http://schemas.microsoft.com/office/drawing/2010/main',+ 'm': 'http://schemas.openxmlformats.org/officeDocument/2006/math',+ 'p': 'http://schemas.openxmlformats.org/presentationml/2006/main',+ 'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',+ 's': 'http://www.w3.org/2000/svg',+}+THEME = ThemeColorSpec(+ slots={'dk1': '173B57', 'accent2': 'C0504D'},+ roles={'text': '173B57', 'accent': 'C0504D'},+ role_slots={'text': 'dk1', 'accent': 'accent2'},+)+++class FormulaImportColorTests(unittest.TestCase):+ def setUp(self) -> None:+ temporary = tempfile.TemporaryDirectory()+ self.addCleanup(temporary.cleanup)+ self.root = Path(temporary.name)+ self.palette = ColorPalette(None, None, strict=False)+ self.palette.scheme.update(THEME.slots)++ def _export(self, svg: str, *, themed: bool = False) -> ET.Element:+ path = self.root / 'formula.svg'+ path.write_text(svg, encoding='utf-8')+ xml, *_ = convert_svg_to_slide_shapes(+ path, resource_root=self.root, theme_color_spec=THEME if themed else None,+ )+ return ET.fromstring(xml)++ def _source(+ self, latex: str = r'\frac{x}{y}+z', *, display: bool = False,+ themed: bool = False, style: str = '', prefix: str = 'before ',+ ) -> ET.Element:+ if display:+ payload = escape(json.dumps({+ 'latex': latex, 'display': 'block', 'font_size': 28,+ 'color': '#173B57', 'align': 'center',+ }))+ body = (+ '<g id="formula" data-pptx-replace-with="formula" '+ 'data-pptx-x="100" data-pptx-y="100" data-pptx-width="800" '+ 'data-pptx-height="100" data-pptx-bounds="100 100 800 100">'+ f'<metadata type="application/json">{payload}</metadata>'+ '<text x="100" y="150" font-size="28" fill="#173B57">x/y+z</text></g>'+ )+ else:+ body = (+ '<text x="100" y="150" font-size="28" fill="#173B57">'+ f'{prefix}<tspan data-pptx-inline-formula="{escape(latex, quote=True)}" '+ f'{style}>x/y+z</tspan> after</text>'+ )+ return self._export(f'<svg xmlns="{NS["s"]}" viewBox="0 0 1280 720">{body}</svg>', themed=themed)++ def _import(self, source: ET.Element, *, strict: bool = False):+ path = self.root / 'source.pptx'+ with zipfile.ZipFile(path, 'w') as archive:+ archive.writestr('ppt/presentation.xml', (+ f'<p:presentation xmlns:p="{NS["p"]}" xmlns:r="{NS["r"]}">'+ '<p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst>'+ '<p:sldSz cx="12192000" cy="6858000"/></p:presentation>'+ ))+ archive.writestr('ppt/_rels/presentation.xml.rels', (+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+ f'<Relationship Id="rId1" Type="{NS["r"]}/slide" Target="slides/slide1.xml"/>'+ '</Relationships>'+ ))+ archive.writestr('ppt/slides/slide1.xml', ET.tostring(source))+ diagnostics = []+ with OoxmlPackage(path) as package:+ svg, _ = assemble_slide(+ package, next(package.iter_slides()), self.palette,+ strict=strict, diagnostics=diagnostics,+ )+ return ET.fromstring(svg), diagnostics++ def _zone(self, slide: ET.Element) -> ET.Element:+ zones = slide.findall('.//a14:m', NS)+ self.assertEqual(len(zones), 1)+ return zones[0]++ def _colors(self, slide: ET.Element) -> list[tuple]:+ result = []+ for owner in self._zone(slide).iter():+ if owner.tag not in {f'{{{NS["m"]}}}r', f'{{{NS["m"]}}}ctrlPr'}:+ continue+ fill = owner.find('a:rPr/a:solidFill', NS)+ self.assertIsNotNone(fill)+ rgb, alpha = resolve_color(list(fill)[0], self.palette, strict=True)+ text = owner.find('m:t', NS)+ result.append((owner.tag, text.text if text is not None else '', rgb, alpha))+ return result++ def _assert_reexport(self, source: ET.Element, *, display: bool = False) -> ET.Element:+ imported, diagnostics = self._import(source)+ self.assertFalse(diagnostics)+ attribute = 'data-pptx-replace-with' if display else 'data-pptx-inline-formula'+ self.assertEqual(len([node for node in imported.iter() if node.get(attribute)]), 1)+ rebuilt = self._export(ET.tostring(imported, encoding='unicode'), themed=True)+ self.assertEqual(self._colors(source), self._colors(rebuilt))+ return imported++ def test_srgb_inline_and_block_roundtrip(self) -> None:+ for display in (False, True):+ with self.subTest(display=display):+ self._assert_reexport(self._source(display=display), display=display)++ def test_scheme_colors_include_control_properties(self) -> None:+ source = self._source(themed=True)+ self.assertIsNotNone(source.find('.//m:ctrlPr/a:rPr/a:solidFill/a:schemeClr', NS))+ self._assert_reexport(source)++ def test_block_scheme_color_uses_metadata_rgb(self) -> None:+ source = self._source(display=True)+ for color in self._zone(source).iter(f'{{{NS["a"]}}}srgbClr'):+ color.tag = f'{{{NS["a"]}}}schemeClr'+ color.set('val', 'dk1')+ imported = self._assert_reexport(source, display=True)+ metadata = imported.find('.//s:g[@data-pptx-replace-with="formula"]/s:metadata', NS)+ self.assertEqual(json.loads(metadata.text)['color'], '#173B57')++ def test_current_palette_color_map_is_honored(self) -> None:+ source = self._source(themed=True)+ self.palette.clr_map['tx1'] = 'accent2'+ for color in self._zone(source).iter(f'{{{NS["a"]}}}schemeClr'):+ color.set('val', 'tx1')+ imported = self._assert_reexport(source)+ marker = imported.find('.//s:tspan[@data-pptx-inline-formula]', NS)+ self.assertEqual(marker.get('fill'), '#C0504D')++ def test_uniform_alpha_and_surrounding_opaque_runs(self) -> None:+ for alpha in ('0', '0.43217', '1'):+ for prefix in ('before ', ''):+ with self.subTest(alpha=alpha, prefix=prefix):+ source = self._source(style=f'opacity="{alpha}"', prefix=prefix)+ imported = self._assert_reexport(source)+ marker = imported.find('.//s:tspan[@data-pptx-inline-formula]', NS)+ self.assertEqual(float(marker.get('fill-opacity', '1')), float(alpha))+ rebuilt = self._export(ET.tostring(imported, encoding='unicode'))+ for run in rebuilt.findall('.//a14:m/../a:r', NS):+ fill = run.find('a:rPr/a:solidFill', NS)+ self.assertEqual(resolve_color(list(fill)[0], self.palette)[1], 1.0)++ def test_formula_opacity_overrides_translucent_parent_text(self) -> None:+ source = self._source(prefix='<tspan opacity="0.25">before </tspan>')+ imported = self._assert_reexport(source)+ rebuilt = self._export(ET.tostring(imported, encoding='unicode'))+ runs = rebuilt.findall('.//a14:m/../a:r', NS)+ self.assertEqual(+ [resolve_color(list(run.find('a:rPr/a:solidFill', NS))[0], self.palette)[1] for run in runs],+ [0.25, 1.0],+ )++ def test_local_colors_full_partial_and_nested_controls(self) -> None:+ for latex in (+ r'\color{red}\frac{x}{y}',+ r'\textcolor{red}{x}+\frac{y}{z}',+ r'\color{red}\frac{x}{\textcolor{blue}{\sqrt{y}}}+\textcolor{green}{z}',+ ):+ for display, alpha in ((False, '1'), (False, '0.43217'), (True, '1')):+ with self.subTest(latex=latex, display=display, alpha=alpha):+ self._assert_reexport(self._source(+ latex, display=display, themed=True, style=f'fill-opacity="{alpha}"',+ ), display=display)++ def _marker_latex(self, imported: ET.Element, *, display: bool) -> str:+ if display:+ metadata = imported.find('.//s:g[@data-pptx-replace-with="formula"]/s:metadata', NS)+ return json.loads(metadata.text)['latex']+ return imported.find('.//s:tspan[@data-pptx-inline-formula]', NS).get('data-pptx-inline-formula')++ def test_default_colors_do_not_appear_in_latex(self) -> None:+ for latex in (r'\frac{x}{y}+z', r'\int_0^1 x', r'\sum_{n=1}^N \left(x_n\right)'):+ for display in (False, True):+ for themed in (False, True):+ with self.subTest(latex=latex, display=display, themed=themed):+ imported = self._assert_reexport(+ self._source(latex, display=display, themed=themed), display=display,+ )+ self.assertNotIn(r'\textcolor', self._marker_latex(imported, display=display))++ def test_partial_local_color_emits_only_one_scope(self) -> None:+ for local in ('x', r'\frac{x}{y}'):+ for display in (False, True):+ with self.subTest(local=local, display=display):+ source = self._source(+ r'a+b+c+\textcolor{red}{' + local + '}', display=display, themed=True,+ )+ imported = self._assert_reexport(source, display=display)+ latex = self._marker_latex(imported, display=display)+ self.assertEqual(latex.count(r'\textcolor'), 1)+ self.assertIn(r'\textcolor{#FF0000}{' + local + '}', latex)+ self.assertNotIn('#173B57', latex)++ def test_nested_controls_share_local_color_scope(self) -> None:+ for display in (False, True):+ with self.subTest(display=display):+ source = self._source(+ r'a+b+c+d+\textcolor{red}{\frac{x}{\sqrt{y}}}', display=display, themed=True,+ )+ imported = self._assert_reexport(source, display=display)+ latex = self._marker_latex(imported, display=display)+ self.assertEqual(latex.count(r'\textcolor'), 1)+ self.assertIn(r'\textcolor{#FF0000}{\frac{x}{\sqrt{y}}}', latex)++ def test_nested_local_scope_can_restore_base_color(self) -> None:+ for display in (False, True):+ with self.subTest(display=display):+ source = self._source(+ r'a+b+c+\textcolor{red}{\frac{x}{\textcolor{#173B57}{\sqrt{y}}}}+d',+ display=display, themed=True,+ )+ imported = self._assert_reexport(source, display=display)+ latex = self._marker_latex(imported, display=display)+ self.assertEqual(latex.count(r'\textcolor'), 2)+ self.assertIn(r'\textcolor{#173B57}{\sqrt{y}}', latex)+ self.assertTrue(latex.endswith(r'\mathrm{+}d'))++ def test_structural_color_different_from_runs_is_preserved(self) -> None:+ for display in (False, True):+ with self.subTest(display=display):+ source = self._source(display=display)+ control = self._zone(source).find('.//m:ctrlPr/a:rPr/a:solidFill/a:srgbClr', NS)+ control.set('val', 'FF0000')+ imported = self._assert_reexport(source, display=display)+ latex = self._marker_latex(imported, display=display)+ self.assertIn(+ r'\textcolor{#FF0000}{\frac{\textcolor{#173B57}{x}}{\textcolor{#173B57}{y}}}',+ latex,+ )+ self.assertTrue(latex.endswith(r'\mathrm{+}z'))++ def _assert_rejected(self, source: ET.Element, *, display: bool = False) -> None:+ before = ET.tostring(source)+ with self.assertRaises(FormulaImportError):+ import_formula(self._zone(source), display=display, palette=self.palette)+ imported, diagnostics = self._import(source)+ self.assertIn('formula-not-reconstructed', [item.code for item in diagnostics])+ self.assertFalse(any(node.get('data-pptx-inline-formula') for node in imported.iter()))+ self.assertFalse(any(node.get('data-pptx-replace-with') == 'formula' for node in imported.iter()))+ metadata = imported.find('.//s:metadata[@data-pptx-part="txbody"]', NS)+ self.assertIsNotNone(metadata)+ retained = ET.fromstring(base64.b64decode(metadata.text))+ self.assertEqual(ET.tostring(retained).strip(), ET.tostring(source.find('.//p:txBody', NS)).strip())+ self.assertEqual(ET.tostring(source), before)+ with self.assertRaisesRegex(ValueError, 'Office Math was not reconstructed'):+ self._import(source, strict=True)++ def test_reject_multiple_colors(self) -> None:+ source = self._source()+ fill = self._zone(source).find('.//a:solidFill', NS)+ ET.SubElement(fill, f'{{{NS["a"]}}}schemeClr', {'val': 'accent2'})+ self._assert_rejected(source)++ def test_reject_unresolved_theme_color(self) -> None:+ source = self._source(themed=True)+ self.palette.scheme.clear()+ self._assert_rejected(source)++ def test_reject_wrong_namespaces_unknown_math_and_bad_modifiers(self) -> None:+ for invalid in ('color-namespace', 'alpha-namespace', 'unknown-math', 'bad-alpha', 'unknown-modifier'):+ with self.subTest(invalid=invalid):+ source = self._source()+ zone = self._zone(source)+ color = zone.find('.//a:srgbClr', NS)+ if invalid == 'color-namespace':+ color.tag = '{urn:wrong}srgbClr'+ elif invalid == 'alpha-namespace':+ ET.SubElement(color, '{urn:wrong}alphaMod', {'val': '50000'})+ elif invalid == 'unknown-math':+ ET.SubElement(zone[0], f'{{{NS["m"]}}}unknown')+ elif invalid == 'bad-alpha':+ ET.SubElement(color, f'{{{NS["a"]}}}alphaMod', {'val': 'no'})+ else:+ ET.SubElement(color, f'{{{NS["a"]}}}unknown', {'val': '50000'})+ self._assert_rejected(source)++ def test_reject_mixed_run_or_control_alpha(self) -> None:+ for target in ('.//m:r/a:rPr/a:solidFill/*', './/m:ctrlPr/a:rPr/a:solidFill/*'):+ with self.subTest(target=target):+ source = self._source(style='opacity="0.5"')+ color = self._zone(source).find(target, NS)+ color[0].set('val', '25000')+ self._assert_rejected(source)++ def test_reject_block_alpha_that_metadata_cannot_reexport(self) -> None:+ source = self._source(display=True)+ for color in self._zone(source).iter(f'{{{NS["a"]}}}srgbClr'):+ ET.SubElement(color, f'{{{NS["a"]}}}alphaMod', {'val': '50000'})+ self._assert_rejected(source, display=True)++ def test_normalization_does_not_mutate_source_or_relax_compiler(self) -> None:+ for options in ({'themed': True}, {'style': 'opacity="0.5"'}):+ with self.subTest(options=options):+ zone = self._zone(self._source(**options))+ before = ET.tostring(zone)+ import_formula(zone, display=False, palette=self.palette)+ self.assertEqual(ET.tostring(zone), before)+ with self.assertRaises(FormulaCompileError):+ validate_omml_fragment(ET.tostring(zone[0], encoding='unicode'))