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-objects): preserve editable chart and table compatibility
hugohe36de844abdab4
diff --git a/skills/ppt-master/scripts/pptx_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg.pyindex b1db79cf..54f84144 100644--- a/skills/ppt-master/scripts/pptx_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg.py@@ -26,6 +26,7 @@ from __future__ import annotationsimport argparseimport sysfrom pathlib import Path+from xml.etree import ElementTree as ET# Allow running this script from anywheresys.path.insert(0, str(Path(__file__).resolve().parent))@@ -37,6 +38,23 @@ from pptx_to_svg.converter import ConvertOptionsconfigure_utf8_stdio()+def _reconstruction_only_graphics(result: object) -> list[tuple[int, str]]:+ """Return slide/object labels for generated placeholders."""+ artifacts = getattr(result, "flat_slides", None) or getattr(result, "slides", [])+ diagnostics: list[tuple[int, str]] = []+ for artifact in artifacts:+ try:+ root = ET.fromstring(artifact.svg)+ except ET.ParseError:+ continue+ for elem in root.iter():+ if elem.get("data-pptx-route-status") != "reconstruction-only":+ continue+ marker_id = elem.get("id") or elem.get("data-name") or "<unnamed>"+ diagnostics.append((artifact.index, marker_id))+ return diagnostics++def parse_args() -> argparse.Namespace:parser = argparse.ArgumentParser(description="Convert .pptx to per-slide SVG by reading OOXML directly.",@@ -110,6 +128,21 @@ def main() -> int:fonts = ", ".join(f"{k}={v}" for k, v in result.theme_fonts.items())print(f"Theme fonts: {fonts}")print(f"Slides converted: {len(result.slides)}")+ reconstruction_only = _reconstruction_only_graphics(result)+ if reconstruction_only:+ print(+ "Warning: chart placeholder(s) without a baked preview are "+ "reconstruction-only. Default export keeps the placeholder; "+ "--native-objects may reconstruct entries with a valid active marker:",+ file=sys.stderr,+ )+ for slide_index, marker_id in reconstruction_only[:20]:+ print(f" slide {slide_index}: {marker_id}", file=sys.stderr)+ if len(reconstruction_only) > 20:+ print(+ f" ... and {len(reconstruction_only) - 20} more",+ file=sys.stderr,+ )print(f"Output: {output_dir}")return 0diff --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 0d6b9b49..575a50c7 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@@ -847,6 +847,13 @@ def _render_graphic_chart(rendered = ""if ctx.render_graphic_previews:rendered = _render_graphic_preview(node, ctx)+ if rendered:+ native_attrs.append('data-pptx-visual-status="source-preview"')+ else:+ native_attrs.extend([+ 'data-pptx-visual-status="placeholder"',+ 'data-pptx-route-status="reconstruction-only"',+ ])return rendered, native_attrsdiff --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 1bfa5636..47ccbe7c 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@@ -288,11 +288,21 @@ def _build_cell_grid(rows: list[ET.Element], col_count: int) -> list[list[_CellSgrid: list[list[_CellSlot | None]] = [[None] * col_count for _ in rows]for r, row in enumerate(rows):+ row_cells = row.findall("a:tc", NS)+ # PowerPoint writes one physical <a:tc> for every grid column, including+ # explicit hMerge/vMerge continuation cells. In that canonical form the+ # physical index is the grid column; advancing by gridSpan would consume+ # the continuation cell twice and shift every following cell left.+ explicit_grid = len(row_cells) >= col_countc = 0- for tc in row.findall("a:tc", NS):- # Skip already-occupied slots from a row above's rowSpan anchor.- while c < col_count and grid[r][c] is not None:- c += 1+ for physical_col, tc in enumerate(row_cells):+ if explicit_grid:+ c = physical_col+ else:+ # Retain best-effort support for compact/non-canonical rows that+ # omit explicit merge continuation cells.+ while c < col_count and grid[r][c] is not None:+ c += 1if c >= col_count:break@@ -302,10 +312,8 @@ def _build_cell_grid(rows: list[ET.Element], col_count: int) -> list[list[_CellSv_merge = ooxml_bool(tc.attrib.get("vMerge"))if h_merge or v_merge:- # This cell is a merge slave; leave the slot tied to the anchor- # if one was already placed there, else mark as dropped placeholder.- if grid[r][c] is None:- grid[r][c] = _CellSlot(element=tc, is_dropped=True)+ # Merge slaves are physical cells but have no independent paint.+ grid[r][c] = _CellSlot(element=tc, is_dropped=True)c += 1continue@@ -326,7 +334,7 @@ def _build_cell_grid(rows: list[ET.Element], col_count: int) -> list[list[_CellSgrid[rr][cc] = _CellSlot(element=tc, is_dropped=True,)- c += slot.col_span+ c += 1 if explicit_grid else slot.col_spanreturn griddiff --git a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py b/skills/ppt-master/scripts/source_to_md/ppt_to_md.pyindex 50b174fd..b1931aa2 100644--- a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py+++ b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py@@ -17,8 +17,10 @@ Dependency:API stability note:Detecting slide-internal jumps (``ppaction://hlinksldjump``) reads``run._r`` (the CT_TextRun lxml element) because python-pptx exposes no- public API to distinguish an internal jump from an external URL. This- access pattern is stable across python-pptx 0.6.x; pin python-pptx<0.7.+ public API to distinguish an internal jump from an external URL. XY chart+ extraction likewise reads ``series._element`` for X values and bubble sizes,+ which the public chart API does not expose. Keep these private accesses+ localized here and covered by conversion smoke tests."""from __future__ import annotations@@ -57,6 +59,10 @@ configure_utf8_stdio()EMU_PER_INCH = 914400+DRAWINGML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"+PRESENTATIONML_NS = "http://schemas.openxmlformats.org/presentationml/2006/main"+RELATIONSHIP_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+CHARTEX_URI = "http://schemas.microsoft.com/office/drawing/2014/chartex"OFFICE_VECTOR_EXTENSIONS = {"emf", "wmf"}IMAGE_EXT_BY_CONTENT_TYPE = {"image/bmp": "bmp",@@ -133,7 +139,10 @@ def sanitize_filename(value: str) -> str:def escape_table_cell(value: str) -> str:"""Escape Markdown table syntax inside a cell."""- return normalize_text(value).replace("|", r"\|") or " "+ normalized = value.replace("\r\n", "\n").replace("\r", "\n")+ lines = [re.sub(r"\s+", " ", line).strip() for line in normalized.split("\n")]+ with_breaks = "<br>".join(lines)+ return with_breaks.replace("|", r"\|") or " "def _safe_position(shape: object, attr: str) -> int:@@ -384,55 +393,260 @@ def _format_chart_value(value: object) -> str:return str(value)-def chart_to_markdown(chart: object, name: str) -> str:- """Render a chart's data as a Markdown table so the numbers survive conversion.-- A native PowerPoint chart stores its data in embedded XML, not in any text- frame — emitting only a `[Chart]` placeholder drops every value. The markdown- is the content contract for downstream generation, so transcribe categories ×- series here. `scripts/pptx_intake.py` writes the same data in structured JSON- form for tooling; this is the human- and content-readable mirror.- """+def _chart_header(chart: object, name: str) -> tuple[str, str]:+ """Return the Markdown chart header and its best-effort type label."""try:chart_type = str(chart.chart_type)- except (ValueError, AttributeError):+ except (ValueError, AttributeError, KeyError):chart_type = ""+ raw_name = "" if name is None else str(name)+ chart_name = normalize_text(raw_name).replace("\n", " ") or "Chart"+ header = f"> [Chart] {chart_name}" + (f" — {chart_type}" if chart_type else "")+ return header, chart_type+++def _chart_warning_lines(warnings: list[str]) -> list[str]:+ """Return stable, de-duplicated Markdown warning blocks."""+ lines: list[str] = []+ seen: set[str] = set()+ for warning in warnings:+ normalized = normalize_text(warning).replace("\n", " ") or "unknown warning"+ if normalized in seen:+ continue+ seen.add(normalized)+ lines.append(f"> [Chart data warning: {normalized}]")+ return lines+++def _chart_data_unavailable(+ header: str,+ reason: str,+ *,+ warnings: list[str] | None = None,+) -> str:+ """Attach an explicit data-read failure to a chart heading."""+ normalized_reason = normalize_text(reason).replace("\n", " ") or "unknown reason"+ lines = [header]+ lines.extend(_chart_warning_lines(warnings or []))+ lines.append(f"> [Chart data unavailable: {normalized_reason}]")+ return "\n".join(lines)+++def _chart_value_cell(value: object) -> str:+ """Return one chart table cell while keeping missing values visibly empty."""+ rendered = _format_chart_value(value)+ return escape_table_cell(rendered) if rendered else ""+++def _chart_series_element(series: object) -> object | None:+ """Return python-pptx's series XML carrier when its public API is insufficient."""+ element = getattr(series, "_element", None)+ if element is not None:+ return element+ return getattr(series, "_ser", None)+++def _chart_series_name(series: object, index: int) -> str:+ """Return a stable, Markdown-safe series name."""+ try:+ raw_name = series.name+ except (ValueError, AttributeError, KeyError):+ raw_name = None+ label = str(raw_name) if raw_name not in (None, "") else f"Series {index}"+ return escape_table_cell(label)+++def _chart_numeric_cache_values(+ parent: object | None,+) -> tuple[list[object | None] | None, str | None]:+ """Read one XY display cache through python-pptx's OOXML value helpers."""+ if parent is None:+ return None, "missing numeric value container"+ try:+ point_count = int(parent.ptCount_val)+ values = [parent.pt_v(index) for index in range(point_count)]+ except (AttributeError, IndexError, TypeError, ValueError):+ return None, "invalid or unavailable numeric display cache"+ if point_count <= 0 or all(value is None for value in values):+ return None, "numeric display cache contains no values"+ return values, None+++def _chart_family(chart_type: str, series: list[object]) -> str:+ """Classify category, scatter, and bubble charts without misreading XY as category."""+ type_key = chart_type.upper()+ if "BUBBLE" in type_key:+ return "bubble"+ if "SCATTER" in type_key:+ return "scatter"+ for item in series:+ element = _chart_series_element(item)+ if element is None:+ continue+ if element.find(qn("c:bubbleSize")) is not None:+ return "bubble"+ if element.find(qn("c:xVal")) is not None or element.find(qn("c:yVal")) is not None:+ return "scatter"+ return "category"+++def _xy_chart_to_markdown(+ series: list[object],+ *,+ family: str,+ header: str,+) -> str:+ """Render scatter/bubble series as typed per-point X/Y[/size] rows."""+ table_header = ["Series", "Point", "X", "Y"]+ if family == "bubble":+ table_header.append("Size")+ rows: list[list[str]] = []+ warnings: list[str] = []++ for series_index, item in enumerate(series, start=1):+ series_name = _chart_series_name(item, series_index)+ element = _chart_series_element(item)+ if element is None:+ x_values = None+ warnings.append(f"{series_name}: series XML is unavailable for X data")+ else:+ x_values, x_error = _chart_numeric_cache_values(+ element.find(qn("c:xVal"))+ )+ if x_error:+ warnings.append(f"{series_name}: X data {x_error}")+ try:+ y_values = list(item.values)+ except (ValueError, TypeError, AttributeError, KeyError):+ y_values = []+ warnings.append(f"{series_name}: Y values are unavailable")++ size_values: list[object | None] | None = None+ if family == "bubble":+ if element is None:+ size_error = "missing series XML"+ else:+ size_values, size_error = _chart_numeric_cache_values(+ element.find(qn("c:bubbleSize"))+ )+ if size_error:+ warnings.append(f"{series_name}: bubble sizes {size_error}")++ x_values = x_values or []+ point_count = max(+ len(x_values),+ len(y_values),+ len(size_values or []),+ )+ if point_count == 0:+ warnings.append(f"{series_name}: no readable points")+ continue+ point_counts = {len(x_values), len(y_values)}+ if family == "bubble":+ point_counts.add(len(size_values or []))+ if len(point_counts) > 1:+ dimensions = "X/Y/size" if family == "bubble" else "X/Y"+ warnings.append(+ f"{series_name}: {dimensions} point counts differ; "+ "missing cells are blank"+ )++ for point_index in range(point_count):+ x_value = x_values[point_index] if point_index < len(x_values) else None+ y_value = y_values[point_index] if point_index < len(y_values) else None+ row = [+ series_name,+ str(point_index + 1),+ _chart_value_cell(x_value),+ _chart_value_cell(y_value),+ ]+ if family == "bubble":+ size_value = (+ size_values[point_index]+ if size_values is not None and point_index < len(size_values)+ else None+ )+ row.append(_chart_value_cell(size_value))+ rows.append(row)++ if not rows:+ return _chart_data_unavailable(+ header,+ "chart has no readable XY points",+ warnings=warnings,+ )+ lines = [header]+ lines.extend(_chart_warning_lines(warnings))+ lines.extend([+ "",+ "| " + " | ".join(table_header) + " |",+ "| " + " | ".join(["---"] * len(table_header)) + " |",+ ])+ lines.extend("| " + " | ".join(row) + " |" for row in rows)+ return "\n".join(lines)+++def _category_chart_to_markdown(chart: object, series: list[object], header: str) -> str:+ """Render a conventional category chart through python-pptx's public API."""categories: list[str] = []+ warnings: list[str] = []+ has_category_xml = any(+ (element := _chart_series_element(item)) is not None+ and element.find(qn("c:cat")) is not None+ for item in series+ )try:plots = list(chart.plots)if plots:categories = [- escape_table_cell(str(cat)) if cat is not None else ""- for cat in plots[0].categories+ escape_table_cell(str(category)) if category is not None else ""+ for category in plots[0].categories]- except (ValueError, IndexError, AttributeError):- categories = []+ except (ValueError, TypeError, IndexError, AttributeError, KeyError):+ if has_category_xml:+ warnings.append("chart categories are unavailable; using point numbers")+ if not has_category_xml and not categories:+ warnings.append("chart categories are missing; using point numbers")+ elif has_category_xml and not categories:+ warnings.append("chart categories are empty; using point numbers")series_data: list[tuple[str, list[object]]] = []- try:- for index, series in enumerate(chart.series, start=1):- try:- values = list(series.values)- except (ValueError, TypeError, AttributeError):- values = []- label = str(series.name) if getattr(series, "name", None) else f"Series {index}"- series_data.append((escape_table_cell(label), values))- except (ValueError, AttributeError):- series_data = []-- header = f"> [Chart] {name}" + (f" — {chart_type}" if chart_type else "")- row_count = len(categories) if categories else max((len(v) for _, v in series_data), default=0)- if not series_data or row_count == 0:- return header+ for index, item in enumerate(series, start=1):+ series_name = _chart_series_name(item, index)+ try:+ values = list(item.values)+ except (ValueError, TypeError, AttributeError, KeyError):+ warnings.append(f"{series_name}: series values are unavailable")+ continue+ series_data.append((series_name, values))- table_header = (["Category"] if categories else ["#"]) + [sname for sname, _ in series_data]- lines = [- header,+ row_count = max(+ len(categories),+ max((len(values) for _, values in series_data), default=0),+ )+ if not series_data or row_count == 0:+ return _chart_data_unavailable(+ header,+ "chart has no readable category-series data",+ warnings=warnings,+ )+ point_counts = {len(values) for _, values in series_data}+ if categories:+ point_counts.add(len(categories))+ if len(point_counts) > 1:+ warnings.append("category/series point counts differ; missing cells are blank")++ table_header = (["Category"] if categories else ["#"]) + [+ series_name for series_name, _ in series_data+ ]+ lines = [header]+ lines.extend(_chart_warning_lines(warnings))+ lines.extend(["","| " + " | ".join(table_header) + " |","| " + " | ".join(["---"] * len(table_header)) + " |",- ]+ ])for row_index in range(row_count):if categories:label = categories[row_index] if row_index < len(categories) else ""@@ -440,11 +654,85 @@ def chart_to_markdown(chart: object, name: str) -> str:label = str(row_index + 1)cells = [label]for _, values in series_data:- cells.append(_format_chart_value(values[row_index]) if row_index < len(values) else "")+ value = values[row_index] if row_index < len(values) else None+ cells.append(_chart_value_cell(value))lines.append("| " + " | ".join(cells) + " |")return "\n".join(lines)+def chart_to_markdown(chart: object, name: str) -> str:+ """Render category, scatter, and bubble data without flattening chart semantics.++ A native PowerPoint chart stores its data in embedded XML, not in any text+ frame. Public python-pptx APIs cover category values and scatter/bubble Y+ values, but not XY X coordinates or bubble sizes. Read only those missing+ display caches from the series XML. Preserve every readable value and emit+ explicit warnings for missing dimensions or series rather than discarding+ the chart's remaining content.+ """+ header, chart_type = _chart_header(chart, name)+ try:+ series = list(chart.series)+ except (ValueError, TypeError, AttributeError, KeyError):+ return _chart_data_unavailable(header, "chart series are unavailable")+ if not series:+ return _chart_data_unavailable(header, "chart has no readable series")++ family = _chart_family(chart_type, series)+ if family in {"scatter", "bubble"}:+ return _xy_chart_to_markdown(series, family=family, header=header)+ return _category_chart_to_markdown(chart, series, header)+++def _chart_reference_id(element: object) -> str | None:+ """Return the first chart relationship id carried by an OOXML shape subtree."""+ for descendant in element.iter():+ if descendant.tag.rsplit("}", 1)[-1] != "chart":+ continue+ relationship_id = descendant.get(f"{{{RELATIONSHIP_NS}}}id")+ if relationship_id:+ return relationship_id+ return None+++def _unexposed_chartex_markdown(+ slide: object,+ emitted_relationship_ids: set[str],+) -> list[str]:+ """Report ChartEx objects omitted from ``slide.shapes`` by python-pptx."""+ blocks: list[str] = []+ seen_relationship_ids: set[str] = set()+ slide_element = getattr(slide, "element", None)+ if slide_element is None:+ slide_element = getattr(slide, "_element", None)+ if slide_element is None:+ return blocks+ for graphic_data in slide_element.iter(f"{{{DRAWINGML_NS}}}graphicData"):+ if graphic_data.get("uri") != CHARTEX_URI:+ continue+ relationship_id = _chart_reference_id(graphic_data)+ if relationship_id and (+ relationship_id in emitted_relationship_ids+ or relationship_id in seen_relationship_ids+ ):+ continue+ if relationship_id:+ seen_relationship_ids.add(relationship_id)++ name = "ChartEx chart"+ current = graphic_data+ while current is not None:+ name_element = current.find(f".//{{{PRESENTATIONML_NS}}}cNvPr")+ if name_element is not None and name_element.get("name"):+ name = name_element.get("name")+ break+ current = current.getparent() if hasattr(current, "getparent") else None+ chart_name = normalize_text(str(name)).replace("\n", " ") or "ChartEx chart"+ header = f"> [Chart] {chart_name} — ChartEx"+ blocks.append(_chart_data_unavailable(header, "unsupported ChartEx data model"))+ return blocks++def _image_part_for_shape(shape: object) -> object | None:"""Return the first embedded image part referenced by a shape."""element = getattr(shape, "element", None)@@ -787,6 +1075,7 @@ def convert_presentation_to_markdown(if diagram.get("shape_id") is not None}emitted_diagram_ids: set[str] = set()+ emitted_chart_relationship_ids: set[str] = set()for item in iter_leaf_shapes(slide.shapes):shape = item.shape@@ -843,10 +1132,31 @@ def convert_presentation_to_markdown(continueif getattr(shape, "has_chart", False):+ shape_element = getattr(shape, "element", None)+ if shape_element is None:+ shape_element = getattr(shape, "_element", None)+ relationship_id = (+ _chart_reference_id(shape_element)+ if shape_element is not None+ else None+ )+ if relationship_id:+ emitted_chart_relationship_ids.add(relationship_id)try:blocks.append(chart_to_markdown(shape.chart, getattr(shape, "name", "Chart")))- except (ValueError, AttributeError, KeyError):- blocks.append(f"> [Chart] {getattr(shape, 'name', 'Chart')}")+ except (ValueError, TypeError, AttributeError, KeyError) as exc:+ raw_name = getattr(shape, "name", "Chart")+ name = normalize_text("" if raw_name is None else str(raw_name)) or "Chart"+ blocks.append(+ _chart_data_unavailable(+ f"> [Chart] {name}",+ f"chart read failed ({type(exc).__name__})",+ )+ )++ blocks.extend(+ _unexposed_chartex_markdown(slide, emitted_chart_relationship_ids)+ )for diagram in slide_diagrams:if str(diagram.get("diagram_id")) in emitted_diagram_ids:diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex fbf2163c..b5cd53b7 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -127,6 +127,15 @@ try:except ImportError:_native_object_marker_warnings = None+try:+ from svg_to_pptx.native_objects.marker_status import (+ native_marker_release_block_reason as _native_marker_release_block_reason,+ native_marker_status_errors as _native_marker_status_errors,+ )+except ImportError:+ _native_marker_release_block_reason = None+ _native_marker_status_errors = None+try:from svg_to_pptx.semantic_markers import (SEMANTIC_ATTRS as _SEMANTIC_ATTRS,@@ -904,7 +913,8 @@ class SVGQualityChecker:f"<{tag} opacity> must be a numeric value from 0 to 1, got {raw_opacity!r}")if tag == 'g' and opacity < 1.0 and any(- descendant.get('data-pptx-native')+ descendant.tag.rsplit('}', 1)[-1] != 'metadata'+ and descendant.get('data-pptx-native')for descendant in elem.iter()):result['warnings'].append(@@ -1548,10 +1558,55 @@ class SVGQualityChecker:def _check_native_object_markers(self, root: ET.Element, result: Dict) -> None:"""Validate opt-in native table/chart markers before PPTX export."""+ invalid_status_elements: set[ET.Element] = set()+ for elem in root.iter():+ if elem.tag.rsplit('}', 1)[-1] == 'metadata':+ continue+ has_status = any(+ elem.get(name) is not None+ for name in (+ 'data-pptx-visual-status',+ 'data-pptx-route-status',+ 'data-pptx-native-status',+ )+ )+ if not has_status:+ continue+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'+ if (+ _native_marker_status_errors is None+ or _native_marker_release_block_reason is None+ ):+ result['errors'].append(+ "Unable to import native-object status validator; "+ f"cannot verify PPTX graphic {marker_id}"+ )+ continue+ status_errors = _native_marker_status_errors(elem)+ for error in status_errors:+ result['errors'].append(+ f"PPTX graphic {marker_id} has invalid status metadata: {error}"+ )+ if status_errors:+ invalid_status_elements.add(elem)+ continue+ if elem.get('data-pptx-route-status') == 'reconstruction-only':+ route = (+ "--native-objects may reconstruct its active native marker"+ if (elem.get('data-pptx-native') or '').strip()+ else "default export keeps the visible placeholder"+ )+ result['warnings'].append(+ f"PPTX graphic {marker_id} is a reconstruction-only placeholder; "+ f"it has no baked preview and {route}"+ )+for elem in root.iter():status = elem.get('data-pptx-native-status')if not status or elem.tag.rsplit('}', 1)[-1] == 'metadata':continue+ if elem.get('data-pptx-native'):+ continuemarker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'result['warnings'].append(f"Native PPTX object {marker_id} is fallback-only: {status}"@@ -1559,7 +1614,11 @@ class SVGQualityChecker:markers = [elem for elem in root.iter()- if elem.get('data-pptx-native') and elem.tag.rsplit('}', 1)[-1] != 'metadata'+ if (+ elem.get('data-pptx-native')+ and elem.tag.rsplit('}', 1)[-1] != 'metadata'+ and elem not in invalid_status_elements+ )]if not markers:returndiff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.pyindex 2d202a88..9d5a2a7f 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py@@ -44,6 +44,7 @@ from .marker_common import (_validate_bounds_inputs,native_marker_transform,)+from .marker_status import native_marker_status_errorsfrom .table import (_build_native_table,_native_table_warnings,@@ -174,6 +175,9 @@ def _validate_native_object_marker_payload(kind = (elem.get("data-pptx-native") or "").strip().lower()if not kind:return "", {}, None+ status_errors = native_marker_status_errors(elem)+ if status_errors:+ raise RuntimeError("; ".join(status_errors))if kind not in _NATIVE_KINDS:raise RuntimeError(f"Unsupported data-pptx-native value: {kind}")if _local_tag(elem) != "g":diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.pynew file mode 100644index 00000000..0ede1c47--- /dev/null+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.py@@ -0,0 +1,60 @@+"""Validate native-object fallback and release-route status attributes."""++from __future__ import annotations++from xml.etree import ElementTree as ET+++VISUAL_STATUSES = frozenset({"source-preview", "placeholder"})+ROUTE_STATUSES = frozenset({"reconstruction-only"})+++def native_marker_status_errors(elem: ET.Element) -> list[str]:+ """Return invalid or contradictory native-object status declarations."""+ errors: list[str] = []+ visual_raw = elem.get("data-pptx-visual-status")+ route_raw = elem.get("data-pptx-route-status")+ native_raw = elem.get("data-pptx-native")+ fallback_raw = elem.get("data-pptx-native-status")++ visual = visual_raw.strip() if visual_raw is not None else None+ route = route_raw.strip() if route_raw is not None else None+ native = native_raw.strip() if native_raw is not None else ""+ fallback = fallback_raw.strip() if fallback_raw is not None else ""++ if visual_raw is not None and visual_raw != visual:+ errors.append("data-pptx-visual-status must not contain surrounding whitespace")+ if route_raw is not None and route_raw != route:+ errors.append("data-pptx-route-status must not contain surrounding whitespace")+ if visual is not None and visual not in VISUAL_STATUSES:+ errors.append(f"unsupported data-pptx-visual-status value: {visual!r}")+ if route is not None and route not in ROUTE_STATUSES:+ errors.append(f"unsupported data-pptx-route-status value: {route!r}")+ if visual == "placeholder" and route != "reconstruction-only":+ errors.append(+ "data-pptx-visual-status='placeholder' requires "+ "data-pptx-route-status='reconstruction-only'"+ )+ if route == "reconstruction-only" and visual != "placeholder":+ errors.append(+ "data-pptx-route-status='reconstruction-only' requires "+ "data-pptx-visual-status='placeholder'"+ )+ if native and fallback:+ errors.append(+ "data-pptx-native and data-pptx-native-status are mutually exclusive"+ )+ return errors+++def native_marker_release_block_reason(elem: ET.Element) -> str | None:+ """Return invalid status metadata that must block an export.++ A valid ``reconstruction-only`` declaration is diagnostic rather than a+ release block: default export keeps its visible placeholder, while an+ active native marker may still reconstruct the editable object.+ """+ errors = native_marker_status_errors(elem)+ if errors:+ return f"invalid-status: {errors[0]}"+ return Nonediff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.pyindex f655fb35..5c5b02b8 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py@@ -7,7 +7,7 @@ from xml.etree import ElementTree as ETfrom ..drawingml.context import ConvertContext, ShapeResultfrom ..drawingml.theme_colors import ThemeColorSpec, color_node_xml-from ..drawingml.utils import _xml_escape+from ..drawingml.utils import _xml_escape, detect_text_langfrom .chart_style import _font_face_xmlfrom .marker_common import (TABLE_URI,@@ -32,17 +32,20 @@ def _table_text_run(bold: bool | None,font_size: int | None,font_face: str | None,+ language: str | None,theme_color_spec: ThemeColorSpec | None,) -> str:size_attr = f' sz="{font_size}"' if font_size is not None else ""bold_attr = f' b="{_bool_attr(bold)}"' if bold is not None else ""+ resolved_language = language or detect_text_lang(text)+ language_attr = f' lang="{_xml_escape(resolved_language)}"'color_xml = (f'<a:solidFill>{color_node_xml(color, theme_color_spec, "text")}</a:solidFill>'if color else "")space_attr = ' xml:space="preserve"' if text != text.strip() else ""return (- f'<a:r><a:rPr lang="en-US"{size_attr}{bold_attr}>'+ f'<a:r><a:rPr{language_attr}{size_attr}{bold_attr}>'f'{color_xml}'f'{_font_face_xml(font_face)}'"</a:rPr>"@@ -397,6 +400,11 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[strband_fill = _clean_hex(style.get("band_fill"), "#F3F6FA")font_face = str(style["font_family"]) if style.get("font_family") else Nonebody_font_size = _font_size_hpt(style.get("font_size"), 18)+ band_rows_enabled = _table_bool(+ style.get("band_row"),+ "style.band_row",+ default=True,+ )header_font_size = _font_size_hpt(style.get("header_font_size", style.get("font_size")),18,@@ -440,7 +448,9 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[strfill = _clean_hex(cell_data.get("fill"),header_fill if is_header else (- band_fill if row_idx % 2 == 0 and row_idx else body_fill+ band_fill+ if band_rows_enabled and row_idx % 2 == 0 and row_idx+ else body_fill),)color = _clean_hex(@@ -492,6 +502,10 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[strbold=bold,font_size=cell_font_size,font_face=font_face,+ language=(+ str(cell_data.get("lang") or style.get("lang") or "").strip()+ or None+ ),theme_color_spec=ctx.theme_color_spec,)cells_xml.append(@@ -507,7 +521,7 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[strshape_id = ctx.next_id()first_row = _bool_attr(header_rows > 0)- band_row = _bool_attr(_table_bool(style.get("band_row"), "style.band_row", default=True))+ band_row = _bool_attr(band_rows_enabled)table_style_id = style.get("table_style_id")if table_style_id is None and not preserve_source_style:table_style_id = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.pyindex 59328e44..844c084e 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/cli.py@@ -37,6 +37,7 @@ if __package__ in {None, ''}:from .dimensions import CANVAS_FORMATS, get_project_info, get_viewbox_dimensionsfrom .discovery import find_svg_files, find_notes_filesfrom .builder import create_pptx_with_native_svg+from ..native_objects.marker_status import native_marker_release_block_reasonfrom ..drawingml.theme_colors import ThemeColorError, load_theme_color_specfrom ..drawingml.theme_fonts import (ThemeFontError,@@ -83,6 +84,50 @@ def _native_object_fallbacks(svg_files: list[Path]) -> list[tuple[str, str, str]return fallbacks+def _release_blocked_graphics(+ svg_files: list[Path],+) -> list[tuple[str, str, str]]:+ """Return graphics whose status metadata is invalid."""+ blocked: list[tuple[str, str, str]] = []+ for svg_path in svg_files:+ try:+ root = ET.parse(svg_path).getroot()+ except (OSError, ET.ParseError):+ continue+ for elem in root.iter():+ if elem.tag.rsplit('}', 1)[-1] == 'metadata':+ continue+ reason = native_marker_release_block_reason(elem)+ if reason is None:+ continue+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'+ blocked.append((svg_path.name, marker_id, reason))+ return blocked+++def _reconstruction_only_graphics(+ svg_files: list[Path],+) -> list[tuple[str, str, bool]]:+ """Return valid placeholder routes for non-blocking diagnostics."""+ diagnostics: list[tuple[str, str, bool]] = []+ for svg_path in svg_files:+ try:+ root = ET.parse(svg_path).getroot()+ except (OSError, ET.ParseError):+ continue+ for elem in root.iter():+ if elem.tag.rsplit('}', 1)[-1] == 'metadata':+ continue+ if elem.get('data-pptx-route-status') != 'reconstruction-only':+ continue+ if native_marker_release_block_reason(elem) is not None:+ continue+ marker_id = elem.get('id') or elem.get('data-name') or '<unnamed>'+ active_native = bool((elem.get('data-pptx-native') or '').strip())+ diagnostics.append((svg_path.name, marker_id, active_native))+ return diagnostics++def _recorded_narration_on_click_slides(ref_files: list[Path],animation_config: dict | None,@@ -214,8 +259,10 @@ Recorded narration:'conversion decisions for debugging.')parser.add_argument('--native-objects', action='store_true', default=False,help='Opt in to converting explicit data-pptx-native table/chart '- 'markers into native PowerPoint objects. Default off: marked '- 'groups export through their SVG fallback children. When set, '+ 'markers into editable PowerPoint objects. This editable-first '+ 'replacement may normalize styling or omit unmodeled marker-local '+ 'visuals. Default off: marked groups export through their SVG '+ 'fallback children. When set, ''the default-flow export is named <project>_<ts>_native_charts.pptx ''to tell it apart from a plain shape export.')parser.add_argument(@@ -428,7 +475,47 @@ Recorded narration:print(f" {message}", file=sys.stderr)return 1+ release_blocked = _release_blocked_graphics(native_files)+ if release_blocked:+ print(+ "Error: invalid PPTX graphic status metadata cannot enter an export. "+ "Correct the reported visual/route/native status attributes first.",+ file=sys.stderr,+ )+ for filename, marker_id, status in release_blocked[:20]:+ print(f" {filename}: {marker_id} ({status})", file=sys.stderr)+ if len(release_blocked) > 20:+ print(+ f" ... and {len(release_blocked) - 20} more",+ file=sys.stderr,+ )+ return 1++ reconstruction_only = _reconstruction_only_graphics(native_files)+ if reconstruction_only:+ print(+ "Warning: reconstruction-only PPTX chart placeholder(s) have no baked "+ "preview. Default export keeps the placeholder; --native-objects "+ "reconstructs entries that carry a valid active native marker.",+ file=sys.stderr,+ )+ for filename, marker_id, active_native in reconstruction_only[:20]:+ route = "active native reconstruction" if active_native else "placeholder fallback"+ print(f" {filename}: {marker_id} ({route})", file=sys.stderr)+ if len(reconstruction_only) > 20:+ print(+ f" ... and {len(reconstruction_only) - 20} more",+ file=sys.stderr,+ )+if args.native_objects:+ print(+ "Warning: --native-objects is an editable-first replacement route. "+ "Native charts/tables may normalize styling or omit SVG details that "+ "are not represented by marker metadata; use the default export when "+ "exact fallback artwork is required.",+ file=sys.stderr,+ )fallbacks = _native_object_fallbacks(native_files)if fallbacks:print(diff --git a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py b/skills/ppt-master/scripts/template_fill_pptx/analyzer.pyindex 14165185..9d8860d2 100644--- a/skills/ppt-master/scripts/template_fill_pptx/analyzer.py+++ b/skills/ppt-master/scripts/template_fill_pptx/analyzer.py@@ -9,18 +9,24 @@ from xml.etree import ElementTree as ETfrom .chart_read import empty_chart_data, read_chart_datafrom .diagram_read import read_smartart_diagrams+from .edit_safety import (+ _chart_edit_capability,+ _chart_frames,+ _chart_reference,+ _table_cell_merge_info,+ _table_merge_topology,+ _unsupported_chart_capability,+)from .ooxml import (CHART_REL_TYPE,NS,SlideRef,- _chart_containers,_container_geometry,_emu_to_px,_normalize_part,_paragraph_texts,_parse_slide_refs,_read_xml,- _qn,_shape_identity,_slide_relationships,_table_containers,@@ -36,16 +42,37 @@ def _analyze_tables(slide_root: ET.Element, source_slide: int) -> list[dict[str,tables: list[dict[str, Any]] = []for order, container in enumerate(_table_containers(slide_root), start=1):shape_id, _shape_name = _shape_identity(container, order)+ table = container.find(".//a:tbl", NS)+ if table is None:+ continue+ merge_topology = _table_merge_topology(table)+ merge_anchors = {+ (int(item["row"]), int(item["col"])): item.get("anchor")+ for item in merge_topology["slave_cells"]+ }rows: list[dict[str, Any]] = []max_columns = 0- for row_index, row in enumerate(container.findall(".//a:tbl/a:tr", NS)):+ for row_index, row in enumerate(table.findall("a:tr", NS)):cells: list[dict[str, Any]] = []for col_index, cell in enumerate(row.findall("a:tc", NS)):+ merge_info = _table_cell_merge_info(cell)+ merge_anchor = merge_anchors.get((row_index, col_index))+ if merge_anchor is not None:+ merge_info["merge_anchor"] = merge_anchor+ merge_info["anchor_row"] = merge_anchor["row"]+ merge_info["anchor_col"] = merge_anchor["col"]+ elif merge_info["is_merge_slave"]:+ merge_info["anchor_row"] = None+ merge_info["anchor_col"] = None+ else:+ merge_info["anchor_row"] = row_index+ merge_info["anchor_col"] = col_indexcells.append({"row": row_index,"col": col_index,"text": "\n".join(_paragraph_texts(cell)),+ **merge_info,})max_columns = max(max_columns, len(cells))@@ -56,6 +83,7 @@ def _analyze_tables(slide_root: ET.Element, source_slide: int) -> list[dict[str,"row_count": len(rows),"column_count": max_columns,"rows": rows,+ "merge_topology": merge_topology,})return tables@@ -64,19 +92,47 @@ def _analyze_tables(slide_root: ET.Element, source_slide: int) -> list[dict[str,def _analyze_charts(zf: zipfile.ZipFile, slide_root: ET.Element, slide_ref: SlideRef) -> list[dict[str, Any]]:charts: list[dict[str, Any]] = []relationships = _slide_relationships(zf, slide_ref.rels_name)- for order, container in enumerate(_chart_containers(slide_root), start=1):+ for order, container in enumerate(_chart_frames(slide_root), start=1):shape_id, _shape_name = _shape_identity(container, order)- chart = container.find(".//c:chart", NS)- rel_id = chart.attrib.get(_qn(NS["r"], "id")) if chart is not None else ""+ chart_kind, rel_id = _chart_reference(container)payload: dict[str, Any] = {"chart_id": f"s{slide_ref.index:02d}_ch{shape_id}"}payload.update(empty_chart_data())+ payload["chart_kind"] = chart_kind+ if chart_kind == "chartex":+ payload["chart_type"] = "chartEx"+ payload["plot_types"] = ["chartEx"]+ payload["edit_capability"] = _unsupported_chart_capability(+ "chart_edit_chartex_unsupported",+ "template-fill chart edits do not support ChartEx",+ )+ charts.append(payload)+ continue+ if chart_kind != "classic":+ payload["edit_capability"] = _unsupported_chart_capability(+ "chart_edit_plot_type_unsupported",+ "template-fill chart edits require a classic DrawingML chart reference",+ )+ charts.append(payload)+ continue+rel = relationships.get(rel_id)if rel and rel.get("type") == CHART_REL_TYPE:chart_part = _normalize_part(rel["target"], slide_ref.part_name)try:- payload.update(read_chart_data(_read_xml(zf, chart_part)))+ chart_root = _read_xml(zf, chart_part)+ payload.update(read_chart_data(chart_root))+ payload["edit_capability"] = _chart_edit_capability(chart_root)except RuntimeError:payload.update(empty_chart_data())+ payload["edit_capability"] = _unsupported_chart_capability(+ "chart_edit_part_unavailable",+ "template-fill could not read the classic chart part",+ )+ else:+ payload["edit_capability"] = _unsupported_chart_capability(+ "chart_edit_relationship_unsupported",+ "template-fill chart edits require a classic chart relationship",+ )charts.append(payload)return chartsdiff --git a/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py b/skills/ppt-master/scripts/template_fill_pptx/chart_fill.pyindex 9748391d..d3c33257 100644--- a/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py+++ b/skills/ppt-master/scripts/template_fill_pptx/chart_fill.py@@ -10,10 +10,16 @@ from __future__ import annotationsimport ioimport re+import sysimport zipfilefrom typing import Anyfrom xml.etree import ElementTree as ET+from .edit_safety import (+ _chart_frames,+ _chart_reference,+ _require_supported_chart_edit,+)from .ooxml import (CHART_CONTENT_TYPE,CHART_REL_TYPE,@@ -21,7 +27,6 @@ from .ooxml import (PACKAGE_REL_TYPE,REL_NS,XLSX_CONTENT_TYPE,- _chart_containers,_normalize_part,_qn,_rels_name_for_part,@@ -34,11 +39,15 @@ from .selectors import _chart_selectorsdef _chart_key_maps(slide_root: ET.Element, source_slide: int) -> dict[str, dict[str, str]]:maps: dict[str, dict[str, str]] = {}- for order, container in enumerate(_chart_containers(slide_root), start=1):+ for order, container in enumerate(_chart_frames(slide_root), start=1):shape_id, shape_name = _shape_identity(container, order)- chart = container.find(".//c:chart", NS)- rel_id = chart.attrib.get(_qn(NS["r"], "id")) if chart is not None else ""- info = {"shape_id": shape_id, "shape_name": shape_name, "rel_id": rel_id or ""}+ chart_kind, rel_id = _chart_reference(container)+ info = {+ "shape_id": shape_id,+ "shape_name": shape_name,+ "rel_id": rel_id,+ "chart_kind": chart_kind,+ }maps[f"chart_id:s{source_slide:02d}_ch{shape_id}"] = infomaps[f"shape_id:{shape_id}"] = infoif shape_name:@@ -168,6 +177,13 @@ def _set_value_cache(series: ET.Element, values: list[Any], column_index: int) -def _apply_chart_edit_to_chart_xml(chart_root: ET.Element, chart_edit: dict[str, Any]) -> None:+ capability = _require_supported_chart_edit(chart_root)+ for warning in capability.get("warnings", []):+ if not isinstance(warning, dict):+ continue+ code = warning.get("code") or "chart_edit_category_flattened"+ message = warning.get("message") or "chart categories will be flattened"+ print(f" Warning: {message} [{code}]", file=sys.stderr)categories = [str(item) for item in chart_edit.get("categories", [])]series_payload = chart_edit.get("series", [])if not categories or not isinstance(series_payload, list) or not series_payload:@@ -346,6 +362,17 @@ def _apply_chart_edits_to_slide_package(continueerrors.append(", ".join(selectors) or "<missing selector>")continue+ chart_kind = chart_info.get("chart_kind", "")+ if chart_kind != "classic":+ code = (+ "chart_edit_chartex_unsupported"+ if chart_kind == "chartex"+ else "chart_edit_plot_type_unsupported"+ )+ raise RuntimeError(+ "template-fill chart edits require a supported classic chart "+ f"[{code}]"+ )rel_id = chart_info.get("rel_id", "")rel = _find_relationship(rels_root, rel_id)if rel is None:diff --git a/skills/ppt-master/scripts/template_fill_pptx/checker.py b/skills/ppt-master/scripts/template_fill_pptx/checker.pyindex 5488485f..8213f361 100644--- a/skills/ppt-master/scripts/template_fill_pptx/checker.py+++ b/skills/ppt-master/scripts/template_fill_pptx/checker.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport unicodedatafrom typing import Any+from .edit_safety import _is_verified_category_capabilityfrom .selectors import (_chart_selectors,_replacement_selectors,@@ -55,6 +56,78 @@ def _chart_lookup(library: dict[str, Any]) -> dict[tuple[int, str], dict[str, Anreturn lookup+def _table_cell_lookup(table: dict[str, Any]) -> dict[tuple[int, int], dict[str, Any]]:+ lookup: dict[tuple[int, int], dict[str, Any]] = {}+ for row in table.get("rows", []):+ for cell in row.get("cells", []):+ if not isinstance(cell, dict):+ continue+ try:+ key = (int(cell.get("row", -1)), int(cell.get("col", -1)))+ except (TypeError, ValueError):+ continue+ lookup[key] = cell+ return lookup+++def _table_merge_slave_lookup(+ table: dict[str, Any],+) -> dict[tuple[int, int], dict[str, int] | None]:+ lookup: dict[tuple[int, int], dict[str, int] | None] = {}+ topology = table.get("merge_topology")+ if isinstance(topology, dict):+ for slave in topology.get("slave_cells", []):+ if not isinstance(slave, dict):+ continue+ try:+ key = (int(slave.get("row", -1)), int(slave.get("col", -1)))+ except (TypeError, ValueError):+ continue+ anchor = slave.get("anchor")+ lookup[key] = anchor if isinstance(anchor, dict) else None++ for key, cell in _table_cell_lookup(table).items():+ if cell.get("is_merge_slave") is True or cell.get("merge_role") == "slave":+ anchor = cell.get("merge_anchor")+ lookup.setdefault(key, anchor if isinstance(anchor, dict) else None)+ return lookup+++def _chart_edit_capability_review(+ chart: dict[str, Any],+) -> tuple[tuple[str, str] | None, list[tuple[str, str]]]:+ capability = chart.get("edit_capability")+ if not isinstance(capability, dict):+ return None, [+ (+ "chart_edit_capability_unknown",+ "chart edit capability is missing; runtime will inspect the actual "+ "chart XML before mutation, and re-running template analysis is recommended",+ )+ ]+ if capability.get("supported") is not True:+ return (+ str(capability.get("code") or "chart_edit_capability_unknown"),+ str(capability.get("message") or "chart edit capability is unsupported"),+ ), []+ if not _is_verified_category_capability(capability):+ return (+ "chart_edit_capability_unknown",+ "chart edit capability is not the verified single-plot c:cat/c:val model",+ ), []++ capability_warnings: list[tuple[str, str]] = []+ raw_warnings = capability.get("warnings")+ if isinstance(raw_warnings, list):+ for item in raw_warnings:+ if not isinstance(item, dict):+ continue+ code = str(item.get("code") or "chart_edit_category_flattened")+ message = str(item.get("message") or "chart categories will be flattened")+ capability_warnings.append((code, message))+ return None, capability_warnings++def _visual_width(text: str) -> float:"""Estimate rendered text width in Latin-character units.@@ -339,10 +412,18 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:continuerow_count = int(table.get("row_count") or 0)column_count = int(table.get("column_count") or 0)+ table_cells = _table_cell_lookup(table)+ merge_slaves = _table_merge_slave_lookup(table)for cell in cells:row = int(cell.get("row", -1))col = int(cell.get("col", -1))- if row < 0 or col < 0 or row >= row_count or col >= column_count:+ if (+ row < 0+ or col < 0+ or row >= row_count+ or col >= column_count+ or (table_cells and (row, col) not in table_cells)+ ):results.append({"status": "ERROR",@@ -355,6 +436,32 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:)summary["error"] += 1continue+ if (row, col) in merge_slaves:+ anchor = merge_slaves[(row, col)]+ anchor_hint = ""+ if anchor is not None:+ anchor_hint = (+ f"; edit merge anchor row={anchor.get('row')} "+ f"col={anchor.get('col')} instead"+ )+ results.append(+ {+ "status": "ERROR",+ "code": "table_cell_is_merge_slave",+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "table_id": table.get("table_id"),+ "row": row,+ "col": col,+ "message": (+ f"table cell row={row} col={col} is a merged-cell slave"+ f"{anchor_hint}"+ ),+ }+ )+ summary["error"] += 1+ continuesummary["ok"] += 1results.append({@@ -397,23 +504,35 @@ def check_plan(library: dict[str, Any], plan: dict[str, Any]) -> dict[str, Any]:)summary["error"] += 1continue- if len(chart.get("plot_types") or []) > 1:+ capability_error, capability_warnings = _chart_edit_capability_review(chart)+ if capability_error is not None:+ error_code, error_message = capability_errorresults.append({"status": "ERROR",- "code": "chart_combo_unsupported",+ "code": error_code,"plan_slide": slide_index,"source_slide": source_slide,"selector": selectors[0] if selectors else "","chart_id": chart.get("chart_id"),- "message": (- "template-fill chart edits do not support multi-plot / combination charts; "- "use beautify/main pipeline to redraw the chart, or leave the native chart untouched"- ),+ "message": error_message,})summary["error"] += 1continue+ for warning_code, warning_message in capability_warnings:+ results.append(+ {+ "status": "WARN",+ "code": warning_code,+ "plan_slide": slide_index,+ "source_slide": source_slide,+ "selector": selectors[0] if selectors else "",+ "chart_id": chart.get("chart_id"),+ "message": warning_message,+ }+ )+ summary["warn"] += 1categories = chart_edit.get("categories", [])series = chart_edit.get("series", [])if not isinstance(categories, list) or not isinstance(series, list) or not series:diff --git a/skills/ppt-master/scripts/template_fill_pptx/edit_safety.py b/skills/ppt-master/scripts/template_fill_pptx/edit_safety.pynew file mode 100644index 00000000..e3146910--- /dev/null+++ b/skills/ppt-master/scripts/template_fill_pptx/edit_safety.py@@ -0,0 +1,294 @@+"""Classify template-fill chart and table edits before package mutation."""++from __future__ import annotations++from typing import Any+from xml.etree import ElementTree as ET++from .ooxml import NS, _qn++_XY_PLOTS = frozenset({"bubbleChart", "scatterChart"})+++def _local_name(tag: str) -> str:+ return tag.rsplit("}", 1)[-1]+++def _tag_namespace(tag: str) -> str:+ if not tag.startswith("{") or "}" not in tag:+ return ""+ return tag[1:].split("}", 1)[0]+++def _chart_reference(frame: ET.Element) -> tuple[str, str]:+ """Return ``(classic|chartex|unknown, relationship id)`` for a chart frame."""+ graphic_data = frame.find(".//a:graphicData", NS)+ if graphic_data is None:+ return "", ""++ for node in graphic_data.iter():+ if _local_name(node.tag) != "chart":+ continue+ namespace = _tag_namespace(node.tag)+ rel_id = node.attrib.get(_qn(NS["r"], "id"), "")+ if namespace == NS["c"]:+ return "classic", rel_id+ if "chartex" in namespace.lower():+ return "chartex", rel_id+ return "unknown", rel_id++ uri = graphic_data.attrib.get("uri", "").lower()+ if "chartex" in uri:+ return "chartex", ""+ if "chart" in uri:+ return "unknown", ""+ return "", ""+++def _chart_frames(slide_root: ET.Element) -> list[ET.Element]:+ """Return classic, ChartEx, and unknown chart graphic frames."""+ return [+ frame+ for frame in slide_root.findall(".//p:graphicFrame", NS)+ if _chart_reference(frame)[0]+ ]+++def _unsupported_chart_capability(+ code: str,+ message: str,+ *,+ plot_type: str | None = None,+ plot_count: int = 0,+ data_model: str = "unknown",+) -> dict[str, Any]:+ return {+ "supported": False,+ "code": code,+ "message": message,+ "plot_type": plot_type,+ "plot_count": plot_count,+ "data_model": data_model,+ }+++def _chart_edit_capability(chart_root: ET.Element) -> dict[str, Any]:+ """Classify whether the category cache writer can safely edit a chart part."""+ root_namespace = _tag_namespace(chart_root.tag)+ if "chartex" in root_namespace.lower():+ return _unsupported_chart_capability(+ "chart_edit_chartex_unsupported",+ "template-fill chart edits do not support ChartEx",+ )+ if root_namespace != NS["c"]:+ return _unsupported_chart_capability(+ "chart_edit_plot_type_unsupported",+ "template-fill chart edits require a classic DrawingML chart part",+ )++ plot_area = chart_root.find(".//c:plotArea", NS)+ if plot_area is None:+ return _unsupported_chart_capability(+ "chart_edit_plot_type_unsupported",+ "template-fill chart edits require a classic chart plotArea",+ )++ plot_nodes = [+ child+ for child in list(plot_area)+ if _tag_namespace(child.tag) == NS["c"] and _local_name(child.tag).endswith("Chart")+ ]+ if len(plot_nodes) > 1:+ return _unsupported_chart_capability(+ "chart_edit_multi_plot_unsupported",+ "template-fill chart edits do not support multi-plot or combination charts",+ plot_count=len(plot_nodes),+ )+ if not plot_nodes:+ return _unsupported_chart_capability(+ "chart_edit_plot_type_unsupported",+ "template-fill chart edits require exactly one recognized chart plot",+ )++ plot = plot_nodes[0]+ plot_type = _local_name(plot.tag)+ if plot_type == "scatterChart":+ return _unsupported_chart_capability(+ "chart_edit_scatter_unsupported",+ "template-fill chart edits do not support scatter xVal/yVal data",+ plot_type=plot_type,+ plot_count=1,+ data_model="xy",+ )+ if plot_type == "bubbleChart":+ return _unsupported_chart_capability(+ "chart_edit_bubble_unsupported",+ "template-fill chart edits do not support bubble xVal/yVal/bubbleSize data",+ plot_type=plot_type,+ plot_count=1,+ data_model="bubble",+ )+ series_nodes = plot.findall("c:ser", NS)+ if not series_nodes:+ return _unsupported_chart_capability(+ "chart_edit_no_series",+ "template-fill chart edits require at least one editable series",+ plot_type=plot_type,+ plot_count=1,+ data_model="category",+ )+ for series in series_nodes:+ if any(+ series.find(f"c:{tag}", NS) is not None+ for tag in ("xVal", "yVal", "bubbleSize")+ ):+ return _unsupported_chart_capability(+ "chart_edit_data_model_unsupported",+ "template-fill chart edits require c:cat/c:val series",+ plot_type=plot_type,+ plot_count=1,+ )+ category = series.find("c:cat", NS)+ values = series.find("c:val", NS)+ if category is None or values is None:+ return _unsupported_chart_capability(+ "chart_edit_data_model_unsupported",+ "template-fill chart edits require c:cat/c:val on every series",+ plot_type=plot_type,+ plot_count=1,+ )+ capability_warnings: list[dict[str, str]] = []+ if plot_area.find("c:dateAx", NS) is not None:+ capability_warnings.append(+ {+ "code": "chart_edit_date_axis_flattened",+ "message": (+ "template-fill will flatten date-axis categories to the "+ "replacement single-level category cache"+ ),+ }+ )+ if any(+ series.find("c:cat/c:multiLvlStrRef", NS) is not None+ for series in series_nodes+ ):+ capability_warnings.append(+ {+ "code": "chart_edit_multilevel_categories_flattened",+ "message": (+ "template-fill will flatten multi-level categories to the "+ "replacement single-level category cache"+ ),+ }+ )++ return {+ "supported": True,+ "code": "chart_edit_category_single_plot",+ "message": "single classic plot uses c:cat/c:val series",+ "plot_type": plot_type,+ "plot_count": 1,+ "data_model": "category",+ "warnings": capability_warnings,+ }+++def _is_verified_category_capability(capability: Any) -> bool:+ """Return whether an analyzer capability matches the runtime structural gate."""+ return bool(+ isinstance(capability, dict)+ and capability.get("supported") is True+ and capability.get("code") == "chart_edit_category_single_plot"+ and capability.get("data_model") == "category"+ and capability.get("plot_count") == 1+ and isinstance(capability.get("plot_type"), str)+ and bool(capability.get("plot_type"))+ and capability.get("plot_type") not in _XY_PLOTS+ )+++def _require_supported_chart_edit(chart_root: ET.Element) -> dict[str, Any]:+ """Raise before mutation unless ``chart_root`` uses the verified category model."""+ capability = _chart_edit_capability(chart_root)+ if not _is_verified_category_capability(capability):+ code = capability.get("code") or "chart_edit_capability_unknown"+ message = capability.get("message") or "chart edit capability is unknown"+ raise RuntimeError(f"{message} [{code}]")+ return capability+++def _ooxml_bool(value: str | None) -> bool:+ return str(value or "").strip().lower() in {"1", "on", "true"}+++def _positive_span(value: str | None) -> int:+ try:+ return max(int(value or "1"), 1)+ except ValueError:+ return 1+++def _table_cell_merge_info(cell: ET.Element) -> dict[str, Any]:+ """Return the merge role encoded directly on one physical ``a:tc`` cell."""+ h_merge = _ooxml_bool(cell.attrib.get("hMerge"))+ v_merge = _ooxml_bool(cell.attrib.get("vMerge"))+ row_span = _positive_span(cell.attrib.get("rowSpan"))+ col_span = _positive_span(cell.attrib.get("gridSpan"))+ is_merge_slave = h_merge or v_merge+ is_merge_anchor = not is_merge_slave and (row_span > 1 or col_span > 1)+ merge_role = "slave" if is_merge_slave else "anchor" if is_merge_anchor else "none"+ return {+ "merge_role": merge_role,+ "is_merge_anchor": is_merge_anchor,+ "is_merge_slave": is_merge_slave,+ "row_span": row_span,+ "col_span": col_span,+ "h_merge": h_merge,+ "v_merge": v_merge,+ }+++def _table_merge_topology(table: ET.Element) -> dict[str, Any]:+ """Describe merge anchors and physical slave cells in a DrawingML table."""+ cell_states: list[tuple[int, int, dict[str, Any]]] = []+ anchors: list[dict[str, int]] = []+ for row_index, row in enumerate(table.findall("a:tr", NS)):+ for col_index, cell in enumerate(row.findall("a:tc", NS)):+ info = _table_cell_merge_info(cell)+ cell_states.append((row_index, col_index, info))+ if info["is_merge_anchor"]:+ anchors.append(+ {+ "row": row_index,+ "col": col_index,+ "row_span": info["row_span"],+ "col_span": info["col_span"],+ }+ )++ covered_by: dict[tuple[int, int], dict[str, int]] = {}+ for anchor in anchors:+ for row_index in range(anchor["row"], anchor["row"] + anchor["row_span"]):+ for col_index in range(anchor["col"], anchor["col"] + anchor["col_span"]):+ if (row_index, col_index) == (anchor["row"], anchor["col"]):+ continue+ covered_by.setdefault(+ (row_index, col_index),+ {"row": anchor["row"], "col": anchor["col"]},+ )++ slave_cells: list[dict[str, Any]] = []+ for row_index, col_index, info in cell_states:+ if not info["is_merge_slave"]:+ continue+ slave: dict[str, Any] = {"row": row_index, "col": col_index}+ anchor = covered_by.get((row_index, col_index))+ if anchor is not None:+ slave["anchor"] = anchor+ slave_cells.append(slave)++ return {+ "has_merges": bool(anchors or slave_cells),+ "anchors": anchors,+ "slave_cells": slave_cells,+ }diff --git a/skills/ppt-master/scripts/template_fill_pptx/ooxml.py b/skills/ppt-master/scripts/template_fill_pptx/ooxml.pyindex 4cb2812e..5dbdc6ec 100644--- a/skills/ppt-master/scripts/template_fill_pptx/ooxml.py+++ b/skills/ppt-master/scripts/template_fill_pptx/ooxml.py@@ -75,6 +75,13 @@ def _read_xml(zf: zipfile.ZipFile, name: str) -> ET.Element:def _xml_bytes(root: ET.Element) -> bytes:+ root_namespace = root.tag[1:].split("}", 1)[0] if root.tag.startswith("{") else ""+ if root_namespace in {REL_NS, CT_NS}:+ # OPC relationship/content-type roots conventionally use the default+ # namespace. ElementTree's global prefix registry can be changed while+ # parsing source parts; restore the package-root form before writing so+ # strict consumers such as LibreOffice accept the generated package.+ ET.register_namespace("", root_namespace)return ET.tostring(root, encoding="utf-8", xml_declaration=True)diff --git a/skills/ppt-master/scripts/template_fill_pptx/table_fill.py b/skills/ppt-master/scripts/template_fill_pptx/table_fill.pyindex 5b51110e..7d43605c 100644--- a/skills/ppt-master/scripts/template_fill_pptx/table_fill.py+++ b/skills/ppt-master/scripts/template_fill_pptx/table_fill.py@@ -8,6 +8,7 @@ from __future__ import annotationsfrom typing import Anyfrom xml.etree import ElementTree as ET+from .edit_safety import _table_cell_merge_infofrom .ooxml import NS, _shape_identity, _table_containersfrom .selectors import _table_cell_text, _table_selectorsfrom .text_fill import _set_container_text@@ -32,6 +33,7 @@ def _apply_table_edits_to_slide() -> None:maps = _table_key_maps(slide_root, source_slide)errors: list[str] = []+ pending_edits: list[tuple[ET.Element, str]] = []for table_edit in table_edits:selectors = _table_selectors(table_edit)table_frame = next((maps[key] for key in selectors if key in maps), None)@@ -54,6 +56,16 @@ def _apply_table_edits_to_slide(if col_index < 0 or col_index >= len(row_cells):errors.append(f"{selectors[0] if selectors else '<table>'} row={row_index} col={col_index}")continue- _set_container_text(row_cells[col_index], _table_cell_text(cell_edit))+ target_cell = row_cells[col_index]+ if _table_cell_merge_info(target_cell)["is_merge_slave"]:+ target = selectors[0] if selectors else "<table>"+ errors.append(+ f"{target} row={row_index} col={col_index} is a merged-cell slave "+ "[table_cell_is_merge_slave]; edit the merge anchor instead"+ )+ continue+ pending_edits.append((target_cell, _table_cell_text(cell_edit)))if errors:raise RuntimeError(f"Invalid table edit target(s) on slide {source_slide}: {'; '.join(errors)}")+ for target_cell, text in pending_edits:+ _set_container_text(target_cell, text)