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(import): resolve theme line styles and diagnose degenerate source objects
hugohe383ac084b58f8
diff --git a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.pyindex 0cebcf0a..05b3de6f 100644--- a/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/pic_to_svg.py@@ -104,7 +104,7 @@ def convert_blip_fill("""blip = blip_fill_elem.find("a:blip", NS)if blip is None:- return PictureResult()+ return _missing_picture_result("Picture fill has no a:blip source", strict)relationship_ids = blip_embed_relationship_ids(blip)linked_rid = blip.attrib.get(f"{{{NS['r']}}}link")@@ -119,7 +119,7 @@ def convert_blip_fill(raise MediaResolutionError("Linked image relationship cannot be resolved; embed the image in PowerPoint first")- return PictureResult()+ return _missing_picture_result("Picture source has no embedded image relationship", strict)target: str | None = Noneimg_bytes: bytes | None = None@@ -154,6 +154,12 @@ def convert_blip_fill(filename, img_bytes = _normalize_office_media(filename, img_bytes)tile_source_bytes = img_bytesdiagnostics = list(_unsupported_blip_effect_diagnostics(blip))+ if xfrm.w <= 0 or xfrm.h <= 0:+ diagnostics.append(PictureDiagnostic(+ code="picture-degenerate-frame",+ message=f"Picture has a nonpositive source frame: {xfrm.w} x {xfrm.h}",+ fallback="retain the source image and exact frame; no positive frame is invented",+ ))filename, img_bytes, effect_diagnostics = _apply_blip_image_effects(filename,img_bytes,@@ -169,7 +175,17 @@ def convert_blip_fill(# srcRect: l/t/r/b in 1/100000ths (so 50000 = 50%).src_rect = blip_fill_elem.find("a:srcRect", NS)- crop = _parse_src_rect(src_rect)+ try:+ crop = _parse_src_rect(src_rect)+ except ValueError as exc:+ if strict:+ raise+ diagnostics.append(PictureDiagnostic(+ code="picture-crop-omitted",+ message=str(exc),+ fallback="retain the complete source image; the invalid crop cannot be reproduced",+ ))+ crop = None# A tile larger than its frame is visually a crop, not a stretch. Preserve# that common PowerPoint background construction through the same nested@@ -230,7 +246,7 @@ def convert_picture("""Translate <p:pic> to SVG <image> (or nested <svg>+<image> for cropping)."""blip_fill = pic_elem.find("p:blipFill", NS)if blip_fill is None:- return PictureResult()+ return _missing_picture_result("Picture has no p:blipFill source", strict)return convert_blip_fill(blip_fill, xfrm, slide_part, pkg,@@ -246,6 +262,17 @@ def convert_picture(# ---------------------------------------------------------------------------+def _missing_picture_result(message: str, strict: bool) -> PictureResult:+ """Report an unrecoverable picture source before omitting its empty preview."""+ if strict:+ raise MediaResolutionError(message)+ return PictureResult(diagnostics=(PictureDiagnostic(+ code="picture-omitted",+ message=message,+ fallback="omit the unavailable picture preview; no replacement image is invented",+ ),))++def _blip_opacity_attr(blip: ET.Element,) -> tuple[str, tuple[PictureDiagnostic, ...]]:@@ -387,10 +414,10 @@ def _parse_src_rect(elem: ET.Element | None) -> tuple[float, float, float, floatreturn Nonevb_x = lvb_y = t- vb_w = max(0.0, 1.0 - l - r)- vb_h = max(0.0, 1.0 - t - b)+ vb_w = 1.0 - l - r+ vb_h = 1.0 - t - bif vb_w <= 0 or vb_h <= 0:- return None+ raise ValueError("Picture crop has a nonpositive source rectangle")return vb_x, vb_y, vb_w, vb_h@@ -631,9 +658,12 @@ def _pct_attr(elem: ET.Element, name: str) -> float:if val is None:return 0.0try:- return float(val) / 100000.0+ value = float(val) / 100000.0except ValueError:- return 0.0+ raise ValueError(f"Invalid picture crop {name}={val!r}") from None+ if not math.isfinite(value):+ raise ValueError(f"Invalid picture crop {name}={val!r}")+ return valuedef _build_href(filename: str, img_bytes: bytes, subdir: str, embed: bool) -> str: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 25afc131..655490cf 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@@ -63,7 +63,7 @@ from .effect_to_svg import (convert_effects,unsupported_target_effect_metadata,)-from .emu_units import NS, Xfrm, fmt_num, format_canvas_px_from_emu+from .emu_units import NS, Xfrm, fmt_num, format_canvas_px_from_emu, parse_xfrmfrom .fill_to_svg import FillResult, resolve_fillfrom .formula_import import (A14_NS,@@ -124,6 +124,7 @@ class AssemblyContext:palette: ColorPalette | Nonepkg: OoxmlPackageslide_part: PartRef+ theme: PartRef | None = Noneslide_number: int | None = Nonetheme_fonts: dict[str, str] = field(default_factory=dict)media_subdir: str = "images"@@ -257,6 +258,7 @@ def assemble_slide(palette=palette,pkg=pkg,slide_part=slide.part,+ theme=pkg.resolve_theme(slide.master),slide_number=pkg.first_slide_number + slide.index - 1,theme_fonts=theme_fonts or {},media_subdir=media_subdir,@@ -375,6 +377,7 @@ def assemble_part_solo(palette=palette,pkg=pkg,slide_part=part,+ theme=pkg.resolve_theme(part if role == "master" else parent_master),theme_fonts=theme_fonts or {},media_subdir=media_subdir,embed_images=embed_images,@@ -594,9 +597,14 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->node.inherited_body_properties,)is_vertical = is_vertical_txbody(tx_body, node.xfrm)+ source_xfrm = sp_pr.find("a:xfrm", NS) if sp_pr is not None else None+ source_frame = (+ parse_xfrm(source_xfrm)+ if source_xfrm is not None and source_xfrm.find("a:ext", NS) is not None+ else node.xfrm+ )if (- is_vertical- and (node.xfrm.w <= 0 or node.xfrm.h <= 0)+ (source_frame.w <= 0 or source_frame.h <= 0)and tx_body is not Noneand any(element.text for element in tx_body.iter(f"{{{NS['a']}}}t"))and (@@ -605,13 +613,15 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->or (sp_pr is not None and sp_pr.find("a:xfrm", NS) is not None))):- # Standalone Layout/Master guides can await inherited geometry. Slide- # nodes already carry resolved inheritance, so their zero frame is real.+ # Report explicit collapsed frames even when placeholder inheritance+ # recovers their geometry. Standalone guides can await inheritance.ctx.diagnose("degenerate-text-frame",- "Vertical text has a nonpositive source frame: "- + _object_metadata(node, ctx)["data-pptx-frame"],- "honor source overflow without inventing a frame; repair it in PowerPoint",+ "Text has a nonpositive source frame: "+ + " ".join(fmt_num(value) for value in (+ source_frame.x, source_frame.y, source_frame.w, source_frame.h,+ )),+ "retain text using available placeholder geometry or source overflow",)block_formula = _block_formula_zone(tx_body)block_formula_failed = False@@ -1098,6 +1108,13 @@ def _render_block_formula(top_level: bool,) -> str:"""Emit one canonical block marker and a dependency-free SVG preview."""+ if node.xfrm.w <= 0 or node.xfrm.h <= 0:+ ctx.diagnose(+ "formula-degenerate-frame",+ "Source formula has a missing or nonpositive frame: "+ + _object_metadata(node, ctx)["data-pptx-frame"],+ "retain the formula content and exact frame; no positive frame is invented",+ )x = fmt_num(node.xfrm.x)y = fmt_num(node.xfrm.y)width = fmt_num(node.xfrm.w)@@ -1294,7 +1311,7 @@ def _build_geometry_xml(node: ShapeNode, sp_pr: ET.Element | None,fill = FillResult.none_fill()try:stroke = resolve_stroke(- sp_pr,+ _effective_shape_stroke_properties(node, ctx, sp_pr),ctx.palette,id_prefix="m",id_seq=ctx.marker_seq,@@ -1423,16 +1440,64 @@ def _resolve_shape_style_defaults(node: ShapeNode, ctx: AssemblyContext) -> dictif fill_color:defaults["fill"] = fill_color- ln_ref = style.find("a:lnRef", NS)- if ln_ref is not None and ln_ref.attrib.get("idx", "").strip() != "0":- line_color = _resolve_ref_color(ln_ref, ctx)- if line_color:- defaults["stroke"] = line_color- defaults.setdefault("stroke-width", "1")-return defaults+def _effective_shape_stroke_properties(+ node: ShapeNode,+ ctx: AssemblyContext,+ sp_pr: ET.Element | None,+) -> ET.Element | None:+ """Resolve the referenced theme line before applying local line overrides."""+ reference = node.xml.find("p:style/a:lnRef", NS)+ if reference is None or reference.get("idx") == "0":+ return sp_pr+ try:+ index = int(reference.get("idx", ""))+ except ValueError:+ raise ValueError("Invalid theme line style index") from None+ styles = (+ ctx.theme.xml.findall("a:themeElements/a:fmtScheme/a:lnStyleLst/a:ln", NS)+ if ctx.theme is not None else []+ )+ if not 1 <= index <= len(styles):+ ctx.diagnose(+ "theme-line-reference-omitted",+ f"Theme line style {index} cannot be resolved",+ "retain the local outline without inventing a theme stroke",+ )+ return sp_pr++ line = copy.deepcopy(styles[index - 1])+ reference_color = find_color_elem(reference)+ if reference_color is not None:+ for owner in line.iter():+ for child in list(owner):+ if child.tag == f"{{{NS['a']}}}schemeClr" and child.get("val") == "phClr":+ color = copy.deepcopy(reference_color)+ color.extend(copy.deepcopy(list(child)))+ owner[list(owner).index(child)] = color++ local_line = sp_pr.find("a:ln", NS) if sp_pr is not None else None+ if local_line is not None:+ line.attrib.update(local_line.attrib)+ exclusive_children = (+ {"noFill", "solidFill", "gradFill", "pattFill", "blipFill", "grpFill"},+ {"prstDash", "custDash"},+ {"round", "bevel", "miter"},+ )+ for local in local_line:+ name = local.tag.rsplit("}", 1)[-1]+ family = next((names for names in exclusive_children if name in names), {name})+ for inherited in list(line):+ if inherited.tag.rsplit("}", 1)[-1] in family:+ line.remove(inherited)+ line.append(copy.deepcopy(local))+ properties = ET.Element(f"{{{NS['p']}}}spPr")+ properties.append(line)+ return properties++def _resolve_text_style_default(node: ShapeNode, ctx: AssemblyContext) -> str:"""Resolve p:style fontRef color used by runs without explicit fill."""style = node.xml.find("p:style", NS)@@ -1687,9 +1752,9 @@ def _convert_picture(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool)"replace only this picture with a visible placeholder",)return _fallback_node_svg(node, ctx, top_level=top_level)+ _diagnose_picture_result(ctx, result)if not result.svg:return ""- _diagnose_picture_result(ctx, result)ctx.media.update(result.media)effect = convert_effects(sp_pr,@@ -1849,6 +1914,13 @@ def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,"""graphic_data = node.xml.find("a:graphic/a:graphicData", NS)uri = graphic_data.attrib.get("uri", "graphicFrame") if graphic_data is not None else "graphicFrame"+ if node.xfrm.w <= 0 or node.xfrm.h <= 0:+ ctx.diagnose(+ "graphic-degenerate-frame",+ "Source graphic has a missing or nonpositive frame: "+ + _object_metadata(node, ctx)["data-pptx-frame"],+ "retain recoverable content and the exact frame; no positive frame is invented",+ )if uri == "http://schemas.openxmlformats.org/drawingml/2006/table":rendered, replacement_attrs, payload_metadata = _render_graphic_table(@@ -1945,6 +2017,12 @@ def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,extra_attrs=[f'{_SOURCE_PROXY_ATTRIBUTE}="native-restore"'],)+ if ctx.render_graphic_previews:+ ctx.diagnose(+ "graphic-preview-unavailable",+ f"Source graphic {uri} has no recoverable visual preview",+ "retain native metadata when available and display the labelled source-frame placeholder",+ )label = uri.rsplit("/", 1)[-1]placeholder = (f'<rect x="{fmt_num(node.xfrm.x)}" y="{fmt_num(node.xfrm.y)}" '@@ -2310,9 +2388,9 @@ def _render_graphic_preview(node: ShapeNode, ctx: AssemblyContext) -> str:asset_name_map=ctx.asset_name_map,strict=ctx.strict,)+ _diagnose_picture_result(ctx, result)if not result.svg:return ""- _diagnose_picture_result(ctx, result)ctx.media.update(result.media)return result.svgdiff --git a/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.pyindex cf624aef..2ee0542b 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@@ -297,9 +297,19 @@ def convert_tbl(col_widths_px = _column_widths_px(tbl)if not col_widths_px:+ message = "Source table has no column grid; cell geometry cannot be recovered"+ if strict:+ raise ValueError(message)+ if diagnostic_sink is not None:+ diagnostic_sink("table-geometry-omitted", message, "retain the source table fallback without inventing columns")return TableResult()rows = tbl.findall("a:tr", NS)if not rows:+ message = "Source table has no rows; cell geometry cannot be recovered"+ if strict:+ raise ValueError(message)+ if diagnostic_sink is not None:+ diagnostic_sink("table-geometry-omitted", message, "retain the source table fallback without inventing rows")return TableResult()table_style = _resolve_table_style(tbl, table_styles)row_heights_px = [_row_height_px(r) for r in rows]@@ -314,6 +324,16 @@ def convert_tbl(or sum(col_widths_px) <= 0or sum(row_heights_px) <= 0)+ if source_geometry_invalid:+ message = "Source table has inconsistent cell counts or nonpositive row/column dimensions"+ if strict:+ raise ValueError(message)+ if diagnostic_sink is not None:+ diagnostic_sink(+ "table-geometry-unsupported",+ message,+ "render recoverable cells at source coordinates; cells outside the source grid cannot be placed",+ )# PowerPoint's tblGrid widths and tr heights together describe the# *intrinsic* table size. The graphicFrame xfrm width/height may differ;diff --git a/skills/ppt-master/scripts/tests/test_import_degenerate_sweep.py b/skills/ppt-master/scripts/tests/test_import_degenerate_sweep.pynew file mode 100644index 00000000..560ef8d8--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_import_degenerate_sweep.py@@ -0,0 +1,307 @@+"""Regress theme line inheritance and diagnosed degenerate source objects."""++from __future__ import annotations++import base64+import json+import tempfile+import unittest+import zipfile+from pathlib import Path+from xml.etree import ElementTree as ET++from pptx_to_svg.converter import convert_pptx_to_svg+++A = "http://schemas.openxmlformats.org/drawingml/2006/main"+P = "http://schemas.openxmlformats.org/presentationml/2006/main"+R = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+SVG = "http://www.w3.org/2000/svg"+NS = {"a": A, "p": P, "s": SVG}+PNG = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aG1cAAAAASUVORK5CYII="+)+++def _frame(width: int = 300, height: int = 100, *, graphic: bool = False) -> str:+ prefix = "p" if graphic else "a"+ return (+ f'<{prefix}:xfrm><a:off x="952500" y="952500"/>'+ f'<a:ext cx="{width * 9525}" cy="{height * 9525}"/></{prefix}:xfrm>'+ )+++def _shape(height: int, local_line: str = "") -> str:+ return (+ '<p:sp><p:nvSpPr><p:cNvPr id="2" name="Source"/>'+ '<p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:spPr>'+ + _frame(height=height)+ + '<a:prstGeom prst="rect"/><a:noFill/>' + local_line+ + '</p:spPr><p:style><a:lnRef idx="1"><a:srgbClr val="123456"/>'+ '</a:lnRef></p:style></p:sp>'+ )+++def _picture(fill: str, height: int = 100) -> str:+ return (+ '<p:pic><p:nvPicPr><p:cNvPr id="2" name="Picture"/>'+ '<p:cNvPicPr/><p:nvPr/></p:nvPicPr>' + fill+ + '<p:spPr>' + _frame(height=height)+ + '<a:prstGeom prst="rect"/></p:spPr></p:pic>'+ )+++def _graphic(content: str, *, height: int = 100, kind: str = "table") -> str:+ uri = (+ "http://schemas.openxmlformats.org/presentationml/2006/ole"+ if kind == "ole" else f"http://schemas.openxmlformats.org/drawingml/2006/{kind}"+ )+ return (+ '<p:graphicFrame><p:nvGraphicFramePr><p:cNvPr id="2" name="Graphic"/>'+ '<p:cNvGraphicFramePr/><p:nvPr/></p:nvGraphicFramePr>'+ + _frame(height=height, graphic=True)+ + f'<a:graphic><a:graphicData uri="{uri}">{content}'+ '</a:graphicData></a:graphic></p:graphicFrame>'+ )+++def _table(*, grid: str = '<a:gridCol w="2857500"/>', extra_cell: bool = False) -> str:+ cell = (+ '<a:tc><a:txBody><a:bodyPr/><a:lstStyle/><a:p>'+ '<a:r><a:rPr sz="1200"/><a:t>Kept</a:t></a:r>'+ '</a:p></a:txBody><a:tcPr/></a:tc>'+ )+ cells = cell + (cell.replace("Kept", "Outside grid") if extra_cell else "")+ return f'<a:tbl><a:tblPr/><a:tblGrid>{grid}</a:tblGrid><a:tr h="952500">{cells}</a:tr></a:tbl>'+++class ImportDegenerateSweepTests(unittest.TestCase):+ def _import(+ self, content: str, *, theme_line: str | None = None, layout_content: str = "",+ ) -> tuple[ET.Element, dict]:+ def relationships(items: list[tuple[str, str, str]]) -> str:+ return (+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'+ + ''.join(f'<Relationship Id="{key}" Type="{R}/{kind}" Target="{target}"/>'+ for key, kind, target in items)+ + '</Relationships>'+ )++ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory)+ source = root / "source.pptx"+ with zipfile.ZipFile(source, "w") as package:+ package.writestr("ppt/presentation.xml", (+ f'<p:presentation xmlns:p="{P}" xmlns:r="{R}"><p:sldIdLst>'+ '<p:sldId id="256" r:id="rId1"/></p:sldIdLst>'+ '<p:sldSz cx="12192000" cy="6858000"/></p:presentation>'+ ))+ package.writestr("ppt/_rels/presentation.xml.rels", relationships([+ ("rId1", "slide", "slides/slide1.xml"),+ ]))+ package.writestr("ppt/slides/slide1.xml", (+ f'<p:sld xmlns:p="{P}" xmlns:a="{A}" xmlns:r="{R}">'+ f'<p:cSld><p:spTree>{content}</p:spTree></p:cSld></p:sld>'+ ))+ package.writestr("ppt/slides/_rels/slide1.xml.rels", relationships([+ ("rIdLayout", "slideLayout", "../slideLayouts/slideLayout1.xml"),+ ("rIdImage", "image", "../media/source.png"),+ ]))+ package.writestr("ppt/media/source.png", PNG)+ package.writestr("ppt/slideLayouts/slideLayout1.xml", (+ f'<p:sldLayout xmlns:p="{P}" xmlns:a="{A}"><p:cSld><p:spTree>'+ f'{layout_content}</p:spTree></p:cSld></p:sldLayout>'+ ))+ package.writestr("ppt/slideLayouts/_rels/slideLayout1.xml.rels", relationships([+ ("rIdMaster", "slideMaster", "../slideMasters/slideMaster1.xml"),+ ]))+ package.writestr("ppt/slideMasters/slideMaster1.xml", (+ f'<p:sldMaster xmlns:p="{P}"><p:cSld><p:spTree/></p:cSld>'+ '<p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" '+ 'accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" '+ 'accent6="accent6" hlink="hlink" folHlink="folHlink"/></p:sldMaster>'+ ))+ if theme_line is not None:+ package.writestr("ppt/slideMasters/_rels/slideMaster1.xml.rels", relationships([+ ("rIdTheme", "theme", "../theme/theme1.xml"),+ ]))+ colors = ''.join(+ f'<a:{name}><a:srgbClr val="123456"/></a:{name}>'+ for name in ('dk1', 'lt1', 'dk2', 'lt2', 'accent1', 'accent2',+ 'accent3', 'accent4', 'accent5', 'accent6', 'hlink', 'folHlink')+ )+ package.writestr("ppt/theme/theme1.xml", (+ f'<a:theme xmlns:a="{A}"><a:themeElements><a:clrScheme name="Test">'+ f'{colors}</a:clrScheme><a:fmtScheme><a:lnStyleLst>{theme_line}'+ '</a:lnStyleLst></a:fmtScheme></a:themeElements></a:theme>'+ ))+ result = convert_pptx_to_svg(source, root / "output")+ report = json.loads((root / "output/validation/conversion-report.json").read_text())+ return ET.fromstring(result.slides[0].svg), report++ def _warning(self, report: dict, code: str) -> dict:+ found = [item for item in report["diagnostics"] if item["code"] == code]+ self.assertEqual(len(found), 1, report)+ self.assertEqual(found[0]["shape_id"], "2")+ self.assertEqual(found[0]["part_path"], "ppt/slides/slide1.xml")+ return found[0]++ def test_theme_line_paint_and_width_are_resolved_for_positive_and_zero_axes(self) -> None:+ for height in (100, 0):+ with self.subTest(height=height):+ svg, _ = self._import(_shape(height), theme_line=(+ '<a:ln w="76200"><a:solidFill><a:schemeClr val="phClr"/>'+ '</a:solidFill><a:prstDash val="dash"/></a:ln>'+ ))+ path = svg.find('.//s:path', NS)+ self.assertEqual(path.get("stroke"), "#123456")+ self.assertEqual(path.get("stroke-width"), "8")+ self.assertEqual(path.get("stroke-dasharray"), "4 4")+ self.assertEqual(path.get("data-pptx-frame"), f"100 100 300 {height}")++ def test_theme_no_fill_does_not_invent_an_outline(self) -> None:+ for height in (100, 0):+ with self.subTest(height=height):+ svg, report = self._import(_shape(height), theme_line='<a:ln w="76200"><a:noFill/></a:ln>')+ path = svg.find('.//s:path', NS)+ if height:+ self.assertEqual(path.get("stroke"), "none")+ else:+ self.assertIsNone(path)+ self.assertEqual(report["diagnostics"], [])++ def test_local_paint_overrides_theme_transparency_without_inheriting_its_alpha(self) -> None:+ local = '<a:ln w="19050"><a:solidFill><a:srgbClr val="ABCDEF"/></a:solidFill></a:ln>'+ svg, _ = self._import(_shape(100, local), theme_line=(+ '<a:ln w="76200"><a:solidFill><a:schemeClr val="phClr"><a:alpha val="0"/>'+ '</a:schemeClr></a:solidFill></a:ln>'+ ))+ path = svg.find('.//s:path', NS)+ self.assertEqual(path.get("stroke"), "#ABCDEF")+ self.assertEqual(path.get("stroke-width"), "2")+ self.assertIsNone(path.get("stroke-opacity"))++ def test_theme_gradient_stops_keep_placeholder_color(self) -> None:+ svg, _ = self._import(_shape(0), theme_line=(+ '<a:ln w="76200"><a:gradFill><a:gsLst>'+ '<a:gs pos="0"><a:schemeClr val="phClr"/></a:gs>'+ '<a:gs pos="100000"><a:srgbClr val="FFFFFF"/></a:gs>'+ '</a:gsLst><a:lin ang="0" scaled="1"/></a:gradFill></a:ln>'+ ))+ path = svg.find('.//s:path', NS)+ self.assertTrue(path.get("stroke").startswith("url(#"))+ gradient = svg.find('.//s:linearGradient', NS)+ self.assertEqual(gradient.get("gradientUnits"), "userSpaceOnUse")+ self.assertEqual([stop.get("stop-color") for stop in gradient], ["#123456", "#FFFFFF"])++ def test_inherited_cap_and_local_override_keep_source_line_ends(self) -> None:+ theme = '<a:ln w="9525" cap="flat"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></a:ln>'+ for cap in (None, "flat", "rnd"):+ with self.subTest(cap=cap):+ attributes = f' cap="{cap}"' if cap else ''+ local = (+ f'<a:ln w="19050"{attributes}><a:solidFill>'+ '<a:srgbClr val="ABCDEF"/></a:solidFill></a:ln>'+ )+ svg, _ = self._import(_shape(100, local), theme_line=theme)+ self.assertEqual(svg.find('.//s:path', NS).get("stroke-linecap"),+ {None: "butt", "flat": "butt", "rnd": "round"}[cap])++ def test_missing_picture_sources_report_omission(self) -> None:+ for fill in ('', '<p:blipFill/>', '<p:blipFill><a:blip/></p:blipFill>'):+ with self.subTest(fill=fill):+ svg, report = self._import(_picture(fill))+ self.assertIsNone(svg.find('.//s:image', NS))+ self._warning(report, "picture-omitted")++ def test_nonpositive_picture_keeps_source_frame_and_reports_it(self) -> None:+ svg, report = self._import(_picture(+ '<p:blipFill><a:blip r:embed="rIdImage"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>',+ height=0,+ ))+ image = svg.find('.//s:image', NS)+ self.assertEqual(image.get("height"), "0")+ self.assertEqual(image.get("width"), "300")+ self._warning(report, "picture-degenerate-frame")++ def test_invalid_picture_crop_reports_the_existing_full_image_fallback(self) -> None:+ for crop in ("100000", "150000", "nan", "invalid"):+ with self.subTest(crop=crop):+ svg, report = self._import(_picture(+ '<p:blipFill><a:blip r:embed="rIdImage"/>'+ f'<a:srcRect l="{crop}"/><a:stretch><a:fillRect/></a:stretch></p:blipFill>',+ ))+ self.assertIsNotNone(svg.find('.//s:image', NS))+ self._warning(report, "picture-crop-omitted")++ def test_unrecoverable_table_grid_and_truncated_cells_are_diagnosed(self) -> None:+ for table, code in (+ (_table(grid=""), "table-geometry-omitted"),+ (_table(extra_cell=True), "table-geometry-unsupported"),+ (_table(grid='<a:gridCol w="0"/>'), "table-geometry-unsupported"),+ ('<a:tbl><a:tblGrid><a:gridCol w="2857500"/></a:tblGrid></a:tbl>', "table-geometry-omitted"),+ ):+ with self.subTest(table=table):+ _, report = self._import(_graphic(table))+ self._warning(report, code)++ def test_nonpositive_graphic_frames_report_without_inventing_dimensions(self) -> None:+ for kind, content in (("table", _table()), ("chart", ""), ("ole", "")):+ with self.subTest(kind=kind):+ svg, report = self._import(_graphic(content, height=0, kind=kind))+ self._warning(report, "graphic-degenerate-frame")+ group = svg.find('s:g', NS)+ self.assertEqual(group.get("data-pptx-frame"), "100 100 300 0")++ def test_unresolved_theme_line_does_not_invent_a_stroke(self) -> None:+ svg, report = self._import(_shape(100))+ self._warning(report, "theme-line-reference-omitted")+ self.assertIsNone(svg.find('.//s:path', NS).get("stroke"))++ def test_missing_graphic_preview_is_reported(self) -> None:+ _, report = self._import(_graphic("", kind="ole"))+ self._warning(report, "graphic-preview-unavailable")++ def test_nonpositive_formula_frame_preserves_content_and_reports_it(self) -> None:+ math = (+ '<a14:m xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main" '+ 'xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math">'+ '<m:oMathPara><m:oMath><m:r><a:rPr sz="1800">'+ '<a:solidFill><a:srgbClr val="123456"/></a:solidFill></a:rPr>'+ '<m:t>x</m:t></m:r></m:oMath></m:oMathPara></a14:m>'+ )+ shape = (+ '<p:sp><p:nvSpPr><p:cNvPr id="2" name="Formula"/><p:cNvSpPr/><p:nvPr/>'+ '</p:nvSpPr><p:spPr>' + _frame(height=0)+ + '<a:prstGeom prst="rect"/><a:noFill/><a:ln><a:noFill/></a:ln></p:spPr>'+ '<p:txBody><a:bodyPr/><a:lstStyle/><a:p>' + math + '</a:p></p:txBody></p:sp>'+ )+ svg, report = self._import(shape)+ self._warning(report, "formula-degenerate-frame")+ group = svg.find('s:g', NS)+ self.assertEqual(group.get("data-pptx-frame"), "100 100 300 0")+ self.assertEqual(group.get("data-pptx-replace-with"), "formula")+ self.assertIn("x", ''.join(group.itertext()))++ def test_placeholder_inherits_omitted_and_explicit_zero_extents_with_diagnostic(self) -> None:+ shape = (+ '<p:sp><p:nvSpPr><p:cNvPr id="2" name="Placeholder"/><p:cNvSpPr/>'+ '<p:nvPr><p:ph type="body" idx="42"/></p:nvPr></p:nvSpPr><p:spPr>'+ + _frame() + '<a:prstGeom prst="rect"/><a:noFill/></p:spPr>'+ '<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>Text</a:t></a:r></a:p>'+ '</p:txBody></p:sp>'+ )+ for explicit in (False, True):+ with self.subTest(explicit=explicit):+ extent = '<a:ext cx="2857500" cy="952500"/>'+ source = shape.replace(extent, '<a:ext cx="0" cy="0"/>' if explicit else '')+ svg, report = self._import(source, layout_content=shape)+ group = svg.find('s:g', NS)+ self.assertEqual(group.get("data-pptx-frame"), "100 100 300 100")+ self.assertTrue(svg.findall('.//s:text', NS))+ if explicit:+ warning = self._warning(report, "degenerate-text-frame")+ self.assertIn("100 100 0 0", warning["message"])+ else:+ self.assertFalse(any(item["code"] == "degenerate-text-frame"+ for item in report["diagnostics"]))diff --git a/skills/ppt-master/scripts/tests/test_roundtrip_degenerate_text_frame.py b/skills/ppt-master/scripts/tests/test_roundtrip_degenerate_text_frame.pynew file mode 100644index 00000000..44082fa6--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_roundtrip_degenerate_text_frame.py@@ -0,0 +1,141 @@+#!/usr/bin/env python3+"""Keep recoverable degenerate source text editable without changing passthrough."""++from __future__ import annotations++import contextlib+import io+import tempfile+import unittest+import zipfile+from pathlib import Path+from xml.etree import ElementTree as ET++from authoring_roundtrip import materialize_flat_authoring_roundtrip+from pptx_to_svg.converter import ConvertOptions, convert_pptx_to_svg+from svg_to_pptx.drawingml.converter import SvgNativeConversionError+from svg_to_pptx.pptx_package.builder import create_pptx_with_native_svg+from svg_to_pptx.pptx_package.cli import main as export_main++SVG = "http://www.w3.org/2000/svg"+NS = {+ "p": "http://schemas.openxmlformats.org/presentationml/2006/main",+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+}+++class RoundtripDegenerateTextFrameTests(unittest.TestCase):+ def _workspace(+ self, root: Path, extent: tuple[int, int], *, stroked: bool = False,+ ) -> tuple[Path, Path]:+ root.mkdir(parents=True, exist_ok=True)+ pages = []+ for number, text in enumerate(("Text", "Control"), start=1):+ page = root / f"slide_{number:02d}.svg"+ page.write_text(+ f'<svg xmlns="{SVG}" viewBox="0 0 1280 720" lang="en-US" font-family="Arial">'+ f'<text x="100" y="140" font-size="24" fill="#123456">{text}</text></svg>',+ encoding="utf-8",+ )+ pages.append(page)+ source = root / "source.pptx"+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):+ self.assertTrue(create_pptx_with_native_svg(+ pages, source, resource_root=root, pptx_structure="flat",+ use_compat_mode=False, transition=None, workers=1, verbose=False,+ ))+ with zipfile.ZipFile(source) as package:+ files = {name: package.read(name) for name in package.namelist()}+ slide = ET.fromstring(files["ppt/slides/slide1.xml"])+ frame = slide.find(".//p:sp/p:spPr/a:xfrm/a:ext", NS)+ frame.set("cx", str(extent[0]))+ frame.set("cy", str(extent[1]))+ if stroked:+ line = slide.find(".//p:sp/p:spPr/a:ln", NS)+ line.clear()+ line.set("w", "38100")+ fill = ET.SubElement(line, f"{{{NS['a']}}}solidFill")+ ET.SubElement(fill, f"{{{NS['a']}}}srgbClr", {"val": "123456"})+ files["ppt/slides/slide1.xml"] = ET.tostring(slide, encoding="utf-8")+ with zipfile.ZipFile(source, "w", zipfile.ZIP_DEFLATED) as package:+ for name, payload in files.items():+ package.writestr(name, payload)+ workspace = root / "workspace"+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):+ convert_pptx_to_svg(+ source, workspace, ConvertOptions(roundtrip=True, inheritance_mode="both"),+ )+ return source, workspace++ def _edit(self, workspace: Path, frame: str | None = None) -> None:+ page = workspace / "authoring-svg-flat/slide_01.svg"+ root = ET.parse(page).getroot()+ source = next(node for node in root.iter() if node.get("data-pptx-source-ref", "").startswith("slide:"))+ text = next(node for node in source.iter() if node.text == "Text")+ text.text = "Edited"+ if frame is not None:+ source.set("data-pptx-frame", frame)+ page.write_bytes(ET.tostring(root))++ def test_edited_nonpositive_source_text_uses_computed_frame(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ for index, extent in enumerate(((0, 0), (2857500, 0), (0, 952500))):+ with self.subTest(extent=extent):+ _, workspace = self._workspace(Path(temporary) / str(index), extent)+ self._edit(workspace)+ result = materialize_flat_authoring_roundtrip(+ workspace, workspace / "authoring-svg-flat", workspace / "materialized",+ )+ self.assertEqual(result.report["totals"]["edited_refs"], 1)+ output = workspace / "exports/result.pptx"+ log = io.StringIO()+ with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):+ status = export_main([str(workspace), "--roundtrip", "-o", str(output)])+ self.assertEqual(status, 0, log.getvalue())+ with zipfile.ZipFile(output) as exported:+ slide = ET.fromstring(exported.read("ppt/slides/slide1.xml"))+ self.assertIn("Edited", [text.text for text in slide.findall(".//a:t", NS)])+ frame = slide.find(".//p:sp/p:spPr/a:xfrm/a:ext", NS)+ self.assertGreater(int(frame.get("cx")), 0)+ self.assertGreater(int(frame.get("cy")), 0)++ def test_explicit_positive_repair_allows_edited_source_text(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ _, workspace = self._workspace(Path(temporary), (0, 0))+ self._edit(workspace, "100 100 300 100")+ result = materialize_flat_authoring_roundtrip(+ workspace, workspace / "authoring-svg-flat", workspace / "materialized",+ )+ self.assertEqual(result.report["totals"]["edited_refs"], 1)+ self.assertIn("Edited", (workspace / "materialized/slide_01.svg").read_text())++ def test_unchanged_degenerate_source_pages_remain_byte_identical(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ source, workspace = self._workspace(Path(temporary), (0, 0))+ output = workspace / "exports/result.pptx"+ log = io.StringIO()+ with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):+ result = export_main([str(workspace), "--roundtrip", "-o", str(output)])+ self.assertEqual(result, 0, log.getvalue())+ self.assertIn("passthrough=2", log.getvalue())+ with zipfile.ZipFile(source) as original, zipfile.ZipFile(output) as exported:+ for page in ("ppt/slides/slide1.xml", "ppt/slides/slide2.xml"):+ self.assertEqual(original.read(page), exported.read(page))++ def test_stroked_zero_axis_shape_uses_existing_text_frame_validation(self) -> None:+ with tempfile.TemporaryDirectory() as temporary:+ _, workspace = self._workspace(Path(temporary), (2857500, 0), stroked=True)+ self._edit(workspace)+ materialize_flat_authoring_roundtrip(+ workspace, workspace / "authoring-svg-flat", workspace / "materialized",+ )+ materialized = ET.parse(workspace / "materialized/slide_01.svg").getroot()+ carrier = next(node for node in materialized.iter() if any(+ child.get("data-pptx-part") == "geometry" for child in node+ ))+ self.assertEqual(carrier.get("data-pptx-frame").split()[2:], ["300", "0"])+ output = workspace / "exports/result.pptx"+ log = io.StringIO()+ with contextlib.redirect_stdout(log), contextlib.redirect_stderr(log):+ with self.assertRaisesRegex(SvgNativeConversionError, "data-pptx-frame width and height must be positive"):+ export_main([str(workspace), "--roundtrip", "-o", str(output)])