Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

feat(pptx-objects): complete P2 chart and table reconstruction

hugohe3319f58e29f4e
diff --git a/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py
index abfacd75..05646f7d 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py
@@ -19,6 +19,7 @@ from svg_to_pptx.native_objects.chart_data import (
validate_data_label_position,
)
+from .chartex_to_svg import UnsupportedChartEx, extract_native_chartex_payload
from .color_resolver import ColorPalette, find_color_elem, resolve_color
from .emu_units import NS, Xfrm, ooxml_bool
from .normalized_chart_svg import SeriesVisualStyle, render_normalized_chart_svg
@@ -59,13 +60,25 @@ def extract_native_chart_payload(
pkg: OoxmlPackage,
palette: ColorPalette | None = None,
) -> ChartResult:
- """Return native chart metadata for a supported classic chart."""
+ """Return native chart metadata for a supported classic or ChartEx chart."""
if graphic_data is None:
return ChartResult(native_status="unsupported-chart-reference")
uri = graphic_data.attrib.get("uri", "")
if uri == CHARTEX_URI or graphic_data.find("cx:chart", C_NS) is not None:
- return ChartResult(native_status="unsupported-chartex")
+ try:
+ payload = extract_native_chartex_payload(
+ graphic_data,
+ xfrm,
+ slide_part,
+ pkg,
+ palette,
+ )
+ except UnsupportedChartEx as exc:
+ return ChartResult(native_status=exc.status)
+ except RuntimeError:
+ return ChartResult(native_status="unsupported-chartex-parse")
+ return ChartResult(native_payload=payload)
if uri != CHART_URI:
return ChartResult(native_status="unsupported-chart-uri")
if xfrm.rot or xfrm.flip_h or xfrm.flip_v:
@@ -164,20 +177,37 @@ def _payload_from_chart_xml(
raise _UnsupportedChart("unsupported-date-axis")
if chart_tag == "barChart":
payload = _category_payload(chart, _bar_chart_type(chart), xfrm)
- elif chart_tag in {"areaChart", "lineChart", "ofPieChart", "pieChart", "doughnutChart"}:
+ elif chart_tag in {
+ "areaChart",
+ "doughnutChart",
+ "lineChart",
+ "ofPieChart",
+ "pieChart",
+ "radarChart",
+ }:
chart_type = {
"areaChart": "area",
+ "doughnutChart": "doughnut",
"lineChart": "line",
"ofPieChart": "of_pie",
"pieChart": "pie",
- "doughnutChart": "doughnut",
+ "radarChart": "radar",
}[chart_tag]
+ category_kind = "date" if has_date_axis else "text"
+ if chart_tag == "radarChart" and _category_cache_is_numeric(chart):
+ category_kind = "numeric"
payload = _category_payload(
chart,
chart_type,
xfrm,
- category_kind="date" if has_date_axis else "text",
+ category_kind=category_kind,
)
+ if chart_tag == "radarChart":
+ if category_kind == "numeric":
+ payload["categories"] = [
+ str(value) for value in payload["categories"]
+ ]
+ payload["radar_style"] = _effective_radar_style(chart)
elif chart_tag == "scatterChart":
payload = _xy_payload(chart, "scatter", xfrm)
payload["axes"] = _xy_axis_contract(plot_area, chart)
@@ -1161,8 +1191,8 @@ def _axis_config_from_xml(
if cross_between != expected_cross_between:
raise _UnsupportedChart("unsupported-chart-axis-options")
auto = axis.find("c:auto", C_NS)
- if auto is not None and not _strict_axis_bool(auto, True):
- raise _UnsupportedChart("unsupported-chart-axis-options")
+ if auto is not None:
+ _strict_axis_bool(auto, True)
major_tick = _element_val(axis.find("c:majorTickMark", C_NS))
minor_tick = _element_val(axis.find("c:minorTickMark", C_NS))
if major_tick not in {None, "none", "out"} or minor_tick not in {None, "none"}:
@@ -1339,6 +1369,121 @@ def _validate_legacy_axes(payload: dict[str, Any], plot_area: ET.Element) -> Non
raise _UnsupportedChart("unsupported-chart-axis-options")
+def _validate_normalized_axis_topology(
+ payload: dict[str, Any],
+ plot_area: ET.Element,
+ plot: ET.Element,
+) -> None:
+ """Validate a category/value pair whose presentation will normalize."""
+ axes_by_id = _axis_nodes_by_id(plot_area)
+ cat_id, cat_axis, val_id, val_axis = _plot_axis_pair(plot, axes_by_id)
+ if set(axes_by_id) != {cat_id, val_id}:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+
+ plot_axis_nodes = plot.findall("c:axId", C_NS)
+ if any(set(node.attrib) != {"val"} or list(node) for node in plot_axis_nodes):
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ for axis, axis_id, cross_axis_id in (
+ (cat_axis, cat_id, val_id),
+ (val_axis, val_id, cat_id),
+ ):
+ if axis.attrib:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ id_nodes = axis.findall("c:axId", C_NS)
+ cross_nodes = axis.findall("c:crossAx", C_NS)
+ if (
+ len(id_nodes) != 1
+ or len(cross_nodes) != 1
+ or set(id_nodes[0].attrib) != {"val"}
+ or set(cross_nodes[0].attrib) != {"val"}
+ or list(id_nodes[0])
+ or list(cross_nodes[0])
+ or _element_val(id_nodes[0]) != axis_id
+ or _element_val(cross_nodes[0]) != cross_axis_id
+ ):
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+
+ position_nodes = (
+ cat_axis.findall("c:axPos", C_NS),
+ val_axis.findall("c:axPos", C_NS),
+ )
+ if any(
+ len(nodes) != 1
+ or set(nodes[0].attrib) != {"val"}
+ or list(nodes[0])
+ for nodes in position_nodes
+ ):
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+ category_position = _element_val(position_nodes[0][0])
+ value_position = _element_val(position_nodes[1][0])
+ if payload["type"] == "bar":
+ valid_positions = (
+ category_position in {"l", "r"}
+ and value_position in {"b", "t"}
+ )
+ else:
+ valid_positions = (
+ category_position in {"b", "t"}
+ and value_position in {"l", "r"}
+ )
+ if not valid_positions:
+ raise _UnsupportedChart("unsupported-chart-axis-options")
+
+
+def _validate_or_normalize_legacy_axes(
+ payload: dict[str, Any],
+ plot_area: ET.Element,
+ plot: ET.Element,
+) -> None:
+ """Keep exact legacy payloads while allowing presentation normalization."""
+ try:
+ _validate_legacy_axes(payload, plot_area)
+ except _UnsupportedChart as exc:
+ if exc.status not in {
+ "unsupported-chart-axis-number-format",
+ "unsupported-chart-axis-options",
+ }:
+ raise
+ if payload["type"] in {"area", "column", "line"}:
+ try:
+ payload["axes"] = _single_axis_contract(
+ plot_area,
+ plot,
+ category_kind="text",
+ cross_between="between",
+ )
+ return
+ except _UnsupportedChart:
+ payload.pop("axes", None)
+ _validate_normalized_axis_topology(payload, plot_area, plot)
+
+
+def _effective_radar_style(plot: ET.Element) -> str:
+ """Map Office radar marker variants to the writer's uniform style set."""
+ style_nodes = plot.findall("c:radarStyle", C_NS)
+ if len(style_nodes) > 1:
+ raise _UnsupportedChart("unsupported-chart-radar-style")
+ style_node = style_nodes[0] if style_nodes else None
+ if style_node is not None and (
+ set(style_node.attrib) != {"val"} or list(style_node)
+ ):
+ raise _UnsupportedChart("unsupported-chart-radar-style")
+ style = _element_val(style_node) if style_node is not None else "standard"
+ if style == "filled":
+ return "filled"
+ if style not in {"marker", "standard"}:
+ raise _UnsupportedChart("unsupported-chart-radar-style")
+
+ default_marker = style == "marker"
+ marker_states: list[bool] = []
+ for series in plot.findall("c:ser", C_NS):
+ symbol = _element_val(series.find("c:marker/c:symbol", C_NS))
+ marker_states.append(
+ default_marker if symbol is None else symbol != "none"
+ )
+ return "lineMarker" if any(marker_states) else "line"
+
+
def _effective_scatter_style(
plot: ET.Element,
visual_styles: list[SeriesVisualStyle],
@@ -1421,6 +1566,34 @@ def _effective_scatter_style(
return effective_styles.pop()
+def _bounded_plot_integer(
+ plot: ET.Element,
+ name: str,
+ *,
+ minimum: int,
+ maximum: int,
+ status: str,
+) -> int | None:
+ nodes = plot.findall(f"c:{name}", C_NS)
+ if len(nodes) > 1:
+ raise _UnsupportedChart(status)
+ if not nodes:
+ return None
+ node = nodes[0]
+ raw_value = node.attrib.get("val")
+ if (
+ set(node.attrib) != {"val"}
+ or list(node)
+ or raw_value is None
+ or re.fullmatch(r"-?[0-9]+", raw_value) is None
+ ):
+ raise _UnsupportedChart(status)
+ value = int(raw_value)
+ if not minimum <= value <= maximum:
+ raise _UnsupportedChart(status)
+ return value
+
+
def _validate_chart_semantics(
payload: dict[str, Any],
plot_area: ET.Element,
@@ -1440,13 +1613,20 @@ def _validate_chart_semantics(
raise _UnsupportedChart("unsupported-chart-analysis-features")
if plot_area.find("c:dTable", C_NS) is not None:
raise _UnsupportedChart("unsupported-chart-data-table")
- ser_lines = plot.find("c:serLines", C_NS)
- if ser_lines is not None and (
- chart_type != "of_pie" or ser_lines.attrib or list(ser_lines)
- ):
+ ser_line_nodes = plot.findall("c:serLines", C_NS)
+ if len(ser_line_nodes) > 1:
raise _UnsupportedChart("unsupported-chart-analysis-features")
+ if ser_line_nodes:
+ ser_lines = ser_line_nodes[0]
+ if (
+ chart_type != "of_pie"
+ or ser_lines.attrib
+ or len(ser_lines) > 1
+ or any(_local_name(child.tag) != "spPr" for child in ser_lines)
+ ):
+ raise _UnsupportedChart("unsupported-chart-analysis-features")
if validate_axes:
- _validate_legacy_axes(payload, plot_area)
+ _validate_or_normalize_legacy_axes(payload, plot_area, plot)
if chart_type == "line":
smooth_nodes = [plot.find("c:smooth", C_NS), *plot.findall("c:ser/c:smooth", C_NS)]
@@ -1471,16 +1651,20 @@ def _validate_chart_semantics(
raise _UnsupportedChart("unsupported-chart-line-style")
if chart_type in {"bar", "column"}:
- gap_width = _element_val(plot.find("c:gapWidth", C_NS))
- if gap_width not in {None, "150"}:
- raise _UnsupportedChart("unsupported-chart-bar-options")
- overlap = _element_val(plot.find("c:overlap", C_NS))
- expected_overlap = "100" if grouping in {"stacked", "percentStacked"} else "0"
- if overlap is None:
- if expected_overlap != "0":
- raise _UnsupportedChart("unsupported-chart-bar-options")
- elif overlap != expected_overlap:
- raise _UnsupportedChart("unsupported-chart-bar-options")
+ _bounded_plot_integer(
+ plot,
+ "gapWidth",
+ minimum=0,
+ maximum=500,
+ status="unsupported-chart-bar-options",
+ )
+ _bounded_plot_integer(
+ plot,
+ "overlap",
+ minimum=-100,
+ maximum=100,
+ status="unsupported-chart-bar-options",
+ )
if chart_type == "bubble":
bubble_scale = _element_val(plot.find("c:bubbleScale", C_NS))
@@ -1565,16 +1749,7 @@ def _apply_chart_metadata(
return
title_element = chart.find("c:title", C_NS)
- overlay = title_element.find("c:overlay", C_NS) if title_element is not None else None
- if overlay is not None and ooxml_bool(overlay.attrib.get("val"), True):
- raise _UnsupportedChart("unsupported-chart-title-overlay")
title_entries = _canonical_title_entries(title_element)
- if (
- title_element is not None
- and title_element.find("c:tx/c:rich", C_NS) is not None
- and title_entries is None
- ):
- raise _UnsupportedChart("unsupported-chart-title-format")
title = _chart_text(title_element)
if title:
if title_entries is not None:
@@ -1588,11 +1763,6 @@ def _apply_chart_metadata(
if legend is not None:
delete = legend.find("c:delete", C_NS)
if delete is None or not ooxml_bool(delete.attrib.get("val"), True):
- if legend.find("c:legendEntry", C_NS) is not None:
- raise _UnsupportedChart("unsupported-chart-legend-filter")
- overlay = legend.find("c:overlay", C_NS)
- if overlay is not None and ooxml_bool(overlay.attrib.get("val"), True):
- raise _UnsupportedChart("unsupported-chart-legend-overlay")
position = _element_val(legend.find("c:legendPos", C_NS)) or "r"
if position not in {"b", "l", "r", "t"}:
raise _UnsupportedChart("unsupported-chart-legend-position")
diff --git a/skills/ppt-master/scripts/pptx_to_svg/chartex_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/chartex_to_svg.py
new file mode 100644
index 00000000..4356f9a0
--- /dev/null
+++ b/skills/ppt-master/scripts/pptx_to_svg/chartex_to_svg.py
@@ -0,0 +1,421 @@
+"""Extract native ChartEx payloads from PPTX chart parts.
+
+The parser is deliberately closed around the seven ChartEx data models that
+the native writer already emits. Data topology and caches must be complete;
+unmodeled chart chrome, labels, axes, binning options, and style details are
+allowed to normalize during editable native reconstruction.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from typing import Any
+from xml.etree import ElementTree as ET
+
+from svg_to_pptx.native_objects.chart_data import validate_chart_payload
+from svg_to_pptx.native_objects.marker_common import CHART_COLOR_STYLE_REL_TYPE
+
+from .color_resolver import COLOR_TAGS, ColorPalette, resolve_color
+from .emu_units import NS, Xfrm
+from .ooxml_loader import OoxmlPackage, PartRef
+
+
+CHARTEX_URI = "http://schemas.microsoft.com/office/drawing/2014/chartex"
+
+CX_NS = {
+ **NS,
+ "cx": CHARTEX_URI,
+}
+
+_INT_TOKEN_RE = re.compile(r"[0-9]+")
+_HIERARCHY_LAYOUTS = {"sunburst", "treemap"}
+_FLAT_LAYOUTS = {"funnel", "waterfall"}
+_LEGEND_POSITIONS = {"b", "l", "r", "t"}
+
+
+class UnsupportedChartEx(RuntimeError):
+ """A ChartEx part cannot map to the current native authoring schema."""
+
+ def __init__(self, status: str) -> None:
+ super().__init__(status)
+ self.status = status
+
+
+def extract_native_chartex_payload(
+ graphic_data: ET.Element | None,
+ xfrm: Xfrm,
+ slide_part: PartRef,
+ pkg: OoxmlPackage,
+ palette: ColorPalette | None = None,
+) -> dict[str, Any]:
+ """Return a writer-valid payload for one supported ChartEx reference.
+
+ ``UnsupportedChartEx.status`` is suitable for ``data-pptx-native-status``
+ when the reference, relationship, data topology, or cache is unusable.
+ Style-part failures never reject an otherwise valid data payload.
+ """
+ if graphic_data is None:
+ raise UnsupportedChartEx("unsupported-chart-reference")
+ if xfrm.rot or xfrm.flip_h or xfrm.flip_v:
+ raise UnsupportedChartEx("unsupported-native-transform")
+
+ chart_ref = graphic_data.find("cx:chart", CX_NS)
+ if chart_ref is None:
+ raise UnsupportedChartEx("unsupported-chart-reference")
+ rid = chart_ref.attrib.get(f"{{{NS['r']}}}id")
+ if not rid:
+ raise UnsupportedChartEx("unsupported-chart-reference")
+
+ chart_path = slide_part.resolve_rel(rid)
+ if not chart_path:
+ raise UnsupportedChartEx("unsupported-chart-relationship")
+ chart_part = pkg.load_part(chart_path)
+ if chart_part is None:
+ raise UnsupportedChartEx("unsupported-chart-part")
+
+ try:
+ payload = _payload_from_chartex_xml(chart_part.xml, xfrm)
+ colors = _resolved_chart_colors(chart_part, pkg, palette)
+ if colors:
+ payload["style"] = {"colors": colors}
+ validate_chart_payload(payload)
+ except UnsupportedChartEx:
+ raise
+ except RuntimeError as exc:
+ raise UnsupportedChartEx("unsupported-chartex-schema") from exc
+ except (AttributeError, OverflowError, TypeError, ValueError) as exc:
+ raise UnsupportedChartEx("unsupported-chartex-parse") from exc
+ return payload
+
+
+def _payload_from_chartex_xml(
+ chart_root: ET.Element,
+ xfrm: Xfrm,
+) -> dict[str, Any]:
+ if chart_root.tag != f"{{{CHARTEX_URI}}}chartSpace":
+ raise UnsupportedChartEx("unsupported-chartex-part")
+
+ chart_data = _one_child(chart_root, "chartData", "unsupported-chartex-structure")
+ chart = _one_child(chart_root, "chart", "unsupported-chartex-structure")
+ plot_area = _one_child(chart, "plotArea", "unsupported-chartex-structure")
+ region = _one_child(plot_area, "plotAreaRegion", "unsupported-chartex-structure")
+
+ data_by_id = _data_parts(chart_data)
+ series_nodes = _children(region, "series")
+ if not series_nodes:
+ raise UnsupportedChartEx("unsupported-chartex-series")
+
+ chart_type = _chart_type(series_nodes)
+ payload: dict[str, Any] = {
+ **_bounds_payload(xfrm),
+ "type": chart_type,
+ }
+
+ referenced_data_ids: list[int]
+ if chart_type in _HIERARCHY_LAYOUTS:
+ data_id = _series_data_id(series_nodes[0])
+ data = _require_data(data_by_id, data_id)
+ raw_levels = _string_dimension(data, expected_levels=None)
+ values = _numeric_dimension(data, "size")
+ if not raw_levels or any(len(level) != len(values) for level in raw_levels):
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ # ChartEx serializes the innermost level first; the authoring schema
+ # and workbook writer use the natural outermost-to-innermost order.
+ payload["levels"] = list(reversed(raw_levels))
+ payload["values"] = values
+ if chart_type == "treemap":
+ parent_labels = _treemap_parent_labels(series_nodes[0])
+ if parent_labels is not None:
+ payload["parent_label_layout"] = parent_labels
+ referenced_data_ids = [data_id]
+ elif chart_type == "histogram":
+ data_id = _series_data_id(series_nodes[0])
+ data = _require_data(data_by_id, data_id)
+ _reject_dimensions(data, allowed={"numDim"})
+ payload["values"] = _numeric_dimension(data, "val")
+ referenced_data_ids = [data_id]
+ elif chart_type in {"funnel", "pareto", "waterfall"}:
+ data_id = _series_data_id(series_nodes[0])
+ data = _require_data(data_by_id, data_id)
+ categories = _string_dimension(data, expected_levels=1)[0]
+ values = _numeric_dimension(data, "val")
+ if len(categories) != len(values):
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ payload["categories"] = categories
+ payload["values"] = values
+ if chart_type == "waterfall":
+ payload["subtotals"] = _waterfall_subtotals(series_nodes[0])
+ referenced_data_ids = [data_id]
+ elif chart_type == "box_whisker":
+ items: list[dict[str, Any]] = []
+ referenced_data_ids = []
+ for index, series in enumerate(series_nodes, start=1):
+ data_id = _series_data_id(series)
+ if data_id in referenced_data_ids:
+ raise UnsupportedChartEx("unsupported-chartex-data-id")
+ data = _require_data(data_by_id, data_id)
+ categories = _string_dimension(data, expected_levels=1)[0]
+ values = _numeric_dimension(data, "val")
+ if len(categories) != len(values):
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ items.append({
+ "categories": categories,
+ "name": _series_name(series, index),
+ "values": values,
+ })
+ referenced_data_ids.append(data_id)
+ payload["series"] = items
+ else: # pragma: no cover - _chart_type is closed, keep the invariant explicit.
+ raise UnsupportedChartEx("unsupported-chartex-type")
+
+ if set(referenced_data_ids) != set(data_by_id):
+ raise UnsupportedChartEx("unsupported-chartex-data-id")
+
+ legend = chart.find("cx:legend", CX_NS)
+ if legend is not None:
+ payload["show_legend"] = True
+ position = legend.attrib.get("pos")
+ if position in _LEGEND_POSITIONS:
+ payload["legend_position"] = position
+ return payload
+
+
+def _chart_type(series_nodes: list[ET.Element]) -> str:
+ layouts = [series.attrib.get("layoutId", "") for series in series_nodes]
+ if len(series_nodes) == 1 and layouts[0] in _HIERARCHY_LAYOUTS | _FLAT_LAYOUTS:
+ return layouts[0]
+ if layouts and all(layout == "boxWhisker" for layout in layouts):
+ return "box_whisker"
+ if len(series_nodes) == 1 and layouts == ["clusteredColumn"]:
+ if series_nodes[0].find("cx:layoutPr/cx:binning", CX_NS) is None:
+ raise UnsupportedChartEx("unsupported-chartex-series")
+ return "histogram"
+ if len(series_nodes) == 2 and layouts == ["clusteredColumn", "paretoLine"]:
+ primary, line = series_nodes
+ if (
+ primary.find("cx:layoutPr/cx:aggregation", CX_NS) is None
+ or line.attrib.get("ownerIdx") != "0"
+ or line.find("cx:dataId", CX_NS) is not None
+ ):
+ raise UnsupportedChartEx("unsupported-chartex-series")
+ return "pareto"
+ raise UnsupportedChartEx("unsupported-chartex-type")
+
+
+def _data_parts(chart_data: ET.Element) -> dict[int, ET.Element]:
+ result: dict[int, ET.Element] = {}
+ for data in _children(chart_data, "data"):
+ data_id = _nonnegative_int(data.attrib.get("id"), "unsupported-chartex-data-id")
+ if data_id in result:
+ raise UnsupportedChartEx("unsupported-chartex-data-id")
+ result[data_id] = data
+ if not result:
+ raise UnsupportedChartEx("unsupported-chartex-data-id")
+ return result
+
+
+def _series_data_id(series: ET.Element) -> int:
+ data_ids = _children(series, "dataId")
+ if len(data_ids) != 1:
+ raise UnsupportedChartEx("unsupported-chartex-data-id")
+ return _nonnegative_int(
+ data_ids[0].attrib.get("val"),
+ "unsupported-chartex-data-id",
+ )
+
+
+def _require_data(data_by_id: dict[int, ET.Element], data_id: int) -> ET.Element:
+ data = data_by_id.get(data_id)
+ if data is None:
+ raise UnsupportedChartEx("unsupported-chartex-data-id")
+ return data
+
+
+def _string_dimension(
+ data: ET.Element,
+ *,
+ expected_levels: int | None,
+) -> list[list[str]]:
+ _reject_dimensions(data, allowed={"strDim", "numDim"})
+ dimensions = [
+ child
+ for child in _children(data, "strDim")
+ if child.attrib.get("type") == "cat"
+ ]
+ if len(dimensions) != 1 or len(_children(data, "strDim")) != 1:
+ raise UnsupportedChartEx("unsupported-chartex-dimension")
+ levels = _children(dimensions[0], "lvl")
+ if not levels or (expected_levels is not None and len(levels) != expected_levels):
+ raise UnsupportedChartEx("unsupported-chartex-dimension")
+ return [_level_values(level, numeric=False) for level in levels]
+
+
+def _numeric_dimension(data: ET.Element, dim_type: str) -> list[int | float]:
+ dimensions = [
+ child
+ for child in _children(data, "numDim")
+ if child.attrib.get("type") == dim_type
+ ]
+ if len(dimensions) != 1 or len(_children(data, "numDim")) != 1:
+ raise UnsupportedChartEx("unsupported-chartex-dimension")
+ levels = _children(dimensions[0], "lvl")
+ if len(levels) != 1:
+ raise UnsupportedChartEx("unsupported-chartex-dimension")
+ return _level_values(levels[0], numeric=True)
+
+
+def _reject_dimensions(data: ET.Element, *, allowed: set[str]) -> None:
+ for child in data:
+ name = _local_name(child.tag)
+ if name.endswith("Dim") and name not in allowed:
+ raise UnsupportedChartEx("unsupported-chartex-dimension")
+
+
+def _level_values(
+ level: ET.Element,
+ *,
+ numeric: bool,
+) -> list[Any]:
+ point_count = _nonnegative_int(
+ level.attrib.get("ptCount"),
+ "unsupported-chartex-cache",
+ )
+ points: dict[int, Any] = {}
+ for point in _children(level, "pt"):
+ point_index = _nonnegative_int(
+ point.attrib.get("idx"),
+ "unsupported-chartex-cache",
+ )
+ if point_index >= point_count or point_index in points or list(point):
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ raw_value = point.text or ""
+ points[point_index] = (
+ _numeric_value(raw_value)
+ if numeric
+ else raw_value
+ )
+ if (
+ len(points) != point_count
+ or any(index not in points for index in range(point_count))
+ ):
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ return [points[index] for index in range(point_count)]
+
+
+def _numeric_value(raw_value: str) -> int | float:
+ if not raw_value.strip():
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ try:
+ number = float(raw_value)
+ except (OverflowError, ValueError):
+ raise UnsupportedChartEx("unsupported-chartex-cache") from None
+ if not math.isfinite(number):
+ raise UnsupportedChartEx("unsupported-chartex-cache")
+ return int(number) if number.is_integer() else number
+
+
+def _waterfall_subtotals(series: ET.Element) -> list[int]:
+ subtotals: list[int] = []
+ for item in series.findall("cx:layoutPr/cx:subtotals/cx:idx", CX_NS):
+ subtotals.append(
+ _nonnegative_int(item.attrib.get("val"), "unsupported-chartex-cache")
+ )
+ return subtotals
+
+
+def _treemap_parent_labels(series: ET.Element) -> str | None:
+ parent = series.find("cx:layoutPr/cx:parentLabelLayout", CX_NS)
+ if parent is None:
+ return None
+ value = parent.attrib.get("val")
+ return value if value in {"banner", "none", "overlapping"} else None
+
+
+def _series_name(series: ET.Element, index: int) -> str:
+ value = series.findtext("cx:tx/cx:txData/cx:v", default="", namespaces=CX_NS)
+ return value or f"Series {index}"
+
+
+def _resolved_chart_colors(
+ chart_part: PartRef,
+ pkg: OoxmlPackage,
+ palette: ColorPalette | None,
+) -> list[str]:
+ """Resolve the base color cycle; any style failure normalizes silently."""
+ try:
+ targets = [
+ info.get("target")
+ for info in chart_part.rels.values()
+ if info.get("type") == CHART_COLOR_STYLE_REL_TYPE
+ and not info.get("external")
+ and info.get("target")
+ ]
+ if len(targets) != 1:
+ return []
+ colors_part = pkg.load_part(str(targets[0]))
+ if colors_part is None:
+ return []
+ color_nodes = [
+ child
+ for child in colors_part.xml
+ if _namespace(child.tag) == NS["a"]
+ and _local_name(child.tag) in COLOR_TAGS
+ ]
+ if not color_nodes:
+ return []
+ colors: list[str] = []
+ for color_node in color_nodes:
+ color, _alpha = resolve_color(color_node, palette)
+ if color is None:
+ return []
+ colors.append(color)
+ return colors
+ except (AttributeError, OverflowError, RuntimeError, TypeError, ValueError):
+ return []
+
+
+def _one_child(parent: ET.Element, name: str, status: str) -> ET.Element:
+ children = _children(parent, name)
+ if len(children) != 1:
+ raise UnsupportedChartEx(status)
+ return children[0]
+
+
+def _children(parent: ET.Element, name: str) -> list[ET.Element]:
+ return [
+ child
+ for child in parent
+ if child.tag == f"{{{CHARTEX_URI}}}{name}"
+ ]
+
+
+def _nonnegative_int(raw_value: str | None, status: str) -> int:
+ if raw_value is None or _INT_TOKEN_RE.fullmatch(raw_value) is None:
+ raise UnsupportedChartEx(status)
+ value = int(raw_value)
+ if value < 0:
+ raise UnsupportedChartEx(status)
+ return value
+
+
+def _bounds_payload(xfrm: Xfrm) -> dict[str, int | float]:
+ return {
+ "height": _round_payload_number(xfrm.h),
+ "width": _round_payload_number(xfrm.w),
+ "x": _round_payload_number(xfrm.x),
+ "y": _round_payload_number(xfrm.y),
+ }
+
+
+def _round_payload_number(value: float) -> int | float:
+ rounded = round(float(value), 3)
+ return int(rounded) if rounded.is_integer() else rounded
+
+
+def _namespace(tag: str) -> str:
+ return tag[1:].split("}", 1)[0] if tag.startswith("{") else ""
+
+
+def _local_name(tag: str) -> str:
+ return tag.rsplit("}", 1)[-1] if "}" in tag else tag
diff --git a/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/tbl_to_svg.py
index 21703a62..5ddedb84 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
@@ -37,6 +37,7 @@ Cell painting order:
from __future__ import annotations
import copy
+import math
from dataclasses import dataclass
from typing import Any
from xml.etree import ElementTree as ET
@@ -52,10 +53,12 @@ from .emu_units import (
)
from .fill_to_svg import FillResult, resolve_fill
from .ln_to_svg import resolve_stroke
-from .txbody_to_svg import convert_txbody
+from .txbody_to_svg import _resolve_theme_typeface, convert_txbody
BUILTIN_MEDIUM_STYLE_2_ACCENT_1 = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"
+_POWERPOINT_COORD_MIN = -(2**31)
+_POWERPOINT_COORD_MAX = 2**31 - 1
_BUILTIN_MEDIUM_STYLE_2_ACCENT_1_XML = ET.fromstring(
f'''<a:tblStyle xmlns:a="{NS["a"]}"
@@ -286,6 +289,17 @@ def convert_tbl(
return TableResult()
table_style = _resolve_table_style(tbl, table_styles)
row_heights_px = [_row_height_px(r) for r in rows]
+ grid_topology_invalid = any(
+ len(row.findall("a:tc", NS)) != len(col_widths_px)
+ for row in rows
+ )
+ source_geometry_invalid = (
+ grid_topology_invalid
+ or any(width <= 0 for width in col_widths_px)
+ or any(height <= 0 for height in row_heights_px)
+ or sum(col_widths_px) <= 0
+ or sum(row_heights_px) <= 0
+ )
# PowerPoint's tblGrid widths and tr heights together describe the
# *intrinsic* table size. The graphicFrame xfrm width/height may differ;
@@ -312,9 +326,9 @@ def convert_tbl(
native_status = merge_status
elif len(rows) > 1000 or len(col_widths) > 1000:
native_status = "unsupported-table-size"
- elif (
- any(width < 0 for width in col_widths)
- or any(height < 0 for height in row_heights)
+ elif source_geometry_invalid or (
+ any(width <= 0 for width in col_widths)
+ or any(height <= 0 for height in row_heights)
or sum(col_widths) <= 0
or sum(row_heights) <= 0
):
@@ -333,6 +347,7 @@ def convert_tbl(
row_heights,
cells,
palette,
+ theme_fonts or {},
)
)
@@ -434,11 +449,10 @@ def _column_widths_px(tbl: ET.Element) -> list[float]:
for col in grid.findall("a:gridCol", NS):
w_emu = col.attrib.get("w")
if w_emu is None:
- continue
- try:
- widths.append(emu_to_px(int(w_emu)))
- except ValueError:
widths.append(0.0)
+ continue
+ value = _safe_emu_integer(w_emu)
+ widths.append(emu_to_px(value) if value is not None else 0.0)
return widths
@@ -446,10 +460,25 @@ def _row_height_px(row: ET.Element) -> float:
h_emu = row.attrib.get("h")
if h_emu is None:
return 0.0
- try:
- return emu_to_px(int(h_emu))
- except ValueError:
- return 0.0
+ value = _safe_emu_integer(h_emu)
+ return emu_to_px(value) if value is not None else 0.0
+
+
+def _safe_emu_integer(raw_value: str) -> int | None:
+ """Return a bounded ASCII DrawingML coordinate without float overflow."""
+ token = raw_value.strip(" \t\r\n")
+ digits = token[1:] if token.startswith("-") else token
+ if (
+ not digits
+ or not digits.isascii()
+ or not digits.isdigit()
+ or len(digits) > 10
+ ):
+ return None
+ value = int(token)
+ if not _POWERPOINT_COORD_MIN <= value <= _POWERPOINT_COORD_MAX:
+ return None
+ return value
def _cumulative_starts(origin: float, sizes: list[float]) -> list[float]:
@@ -740,8 +769,14 @@ def _direct_border_payload(
ln: ET.Element,
palette: ColorPalette | None,
) -> dict[str, Any]:
- if set(ln.attrib) - {"w"}:
+ if set(ln.attrib) - {"w", "cap", "cmpd", "algn"}:
raise ValueError("unsupported border line attribute")
+ if ln.get("cap") not in {None, "flat"}:
+ raise ValueError("unsupported border cap")
+ if ln.get("cmpd") not in {None, "sng"}:
+ raise ValueError("unsupported border compound style")
+ if ln.get("algn") not in {None, "ctr"}:
+ raise ValueError("unsupported border alignment")
width_emu: int | None = None
if "w" in ln.attrib:
raw_width = ln.get("w", "")
@@ -759,11 +794,17 @@ def _direct_border_payload(
raise ValueError("invalid noFill border")
return {"style": "none"}
+ decoration_names = {"round", "headEnd", "tailEnd"}
if child_names.count("solidFill") != 1 or any(
- name not in {"solidFill", "prstDash"} for name in child_names
+ name not in {"solidFill", "prstDash", *decoration_names}
+ for name in child_names
):
raise ValueError("unsupported border paint")
- if child_names.count("prstDash") > 1 or width_emu is None:
+ if (
+ child_names.count("prstDash") > 1
+ or any(child_names.count(name) > 1 for name in decoration_names)
+ or width_emu is None
+ ):
raise ValueError("invalid solid border")
dash = next(
(child for child in children if child.tag.rsplit("}", 1)[-1] == "prstDash"),
@@ -773,6 +814,30 @@ def _direct_border_payload(
dash.attrib != {"val": "solid"} or list(dash)
):
raise ValueError("unsupported border dash")
+ line_join = next(
+ (child for child in children if child.tag.rsplit("}", 1)[-1] == "round"),
+ None,
+ )
+ if line_join is not None and (line_join.attrib or list(line_join)):
+ raise ValueError("unsupported border line join")
+ for endpoint_name in ("headEnd", "tailEnd"):
+ endpoint = next(
+ (
+ child for child in children
+ if child.tag.rsplit("}", 1)[-1] == endpoint_name
+ ),
+ None,
+ )
+ if endpoint is None:
+ continue
+ if (
+ set(endpoint.attrib) - {"type", "w", "len"}
+ or endpoint.get("type") not in {None, "none"}
+ or endpoint.get("w") not in {None, "med"}
+ or endpoint.get("len") not in {None, "med"}
+ or list(endpoint)
+ ):
+ raise ValueError("unsupported border endpoint")
solid_fill = next(
child for child in children
@@ -805,6 +870,8 @@ def _table_has_unsupported_direct_formatting(
) -> bool:
"""Reject direct cell features the compact native schema cannot retain."""
for tc in tbl.findall(".//a:tc", NS):
+ if _table_cell_has_unsupported_topology(tc):
+ return True
tc_pr = tc.find("a:tcPr", NS)
if tc_pr is not None:
allowed_attrs = {"marL", "marR", "marT", "marB", "anchor"}
@@ -814,10 +881,19 @@ def _table_has_unsupported_direct_formatting(
return True
if any(
child.tag.rsplit("}", 1)[-1]
- not in {"solidFill", *_DIRECT_BORDER_TAGS}
+ not in {"solidFill", "noFill", *_DIRECT_BORDER_TAGS}
for child in tc_pr
):
return True
+ fills = [
+ child for child in tc_pr
+ if child.tag.rsplit("}", 1)[-1] in {"solidFill", "noFill"}
+ ]
+ if len(fills) > 1:
+ return True
+ no_fill = tc_pr.find("a:noFill", NS)
+ if no_fill is not None and (no_fill.attrib or list(no_fill)):
+ return True
for border_tag in _DIRECT_BORDER_TAGS:
borders = tc_pr.findall(f"a:{border_tag}", NS)
if len(borders) > 1:
@@ -836,16 +912,119 @@ def _table_has_unsupported_direct_formatting(
tx_body = tc.find("a:txBody", NS)
if _text_body_has_unsupported_formatting(tx_body):
return True
+ return False
+
+
+def _table_cell_has_unsupported_topology(tc: ET.Element) -> bool:
+ """Accept only the closed optional txBody -> optional tcPr cell sequence."""
+ if any(
+ name not in {"gridSpan", "rowSpan", "hMerge", "vMerge"}
+ for name in tc.attrib
+ ):
+ return True
+ tx_body_tag = f"{{{NS['a']}}}txBody"
+ tc_pr_tag = f"{{{NS['a']}}}tcPr"
+ child_tags = [child.tag for child in tc]
+ child_index = 0
+ if child_tags[:1] == [tx_body_tag]:
+ child_index += 1
+ if child_tags[child_index:child_index + 1] == [tc_pr_tag]:
+ child_index += 1
+ return child_index != len(child_tags)
+
+
+def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
+ if tx_body is None:
+ return False
+ if tx_body.attrib:
+ return True
+
+ body_pr_tag = f"{{{NS['a']}}}bodyPr"
+ list_style_tag = f"{{{NS['a']}}}lstStyle"
+ paragraph_tag = f"{{{NS['a']}}}p"
+ body_tags = [child.tag for child in tx_body]
+ body_index = 0
+ if not body_tags or body_tags[0] != body_pr_tag:
+ return True
+ body_index += 1
+ if body_index < len(body_tags) and body_tags[body_index] == list_style_tag:
+ body_index += 1
+ if body_index == len(body_tags) or any(
+ tag != paragraph_tag for tag in body_tags[body_index:]
+ ):
+ return True
+
+ relationship_prefix = f"{{{NS['r']}}}"
+ forbidden_run_children = {
+ f"{{{NS['a']}}}extLst",
+ f"{{{NS['a']}}}hlinkClick",
+ f"{{{NS['a']}}}hlinkMouseOver",
+ }
+ if any(
+ node.tag in forbidden_run_children
+ or any(name.startswith(relationship_prefix) for name in node.attrib)
+ for node in tx_body.iter()
+ ):
+ return True
+
+ body_pr = tx_body.find("a:bodyPr", NS)
+ if body_pr is None or body_pr.attrib or list(body_pr):
+ return True
+ list_style = tx_body.find("a:lstStyle", NS)
+ if list_style is not None and (list_style.attrib or list(list_style)):
+ return True
+ for paragraph in tx_body.findall("a:p", NS):
+ if paragraph.attrib:
+ return True
+ p_pr_tag = f"{{{NS['a']}}}pPr"
+ run_tag = f"{{{NS['a']}}}r"
+ end_r_pr_tag = f"{{{NS['a']}}}endParaRPr"
+ direct_tags = [child.tag for child in paragraph]
+ paragraph_index = 0
+ if direct_tags[:1] == [p_pr_tag]:
+ paragraph_index += 1
+ while (
+ paragraph_index < len(direct_tags)
+ and direct_tags[paragraph_index] == run_tag
+ ):
+ paragraph_index += 1
if (
- tx_body is not None
- and tx_body.find(".//a:solidFill", NS) is not None
- and _cell_text_color(tx_body, palette) is None
+ paragraph_index < len(direct_tags)
+ and direct_tags[paragraph_index] == end_r_pr_tag
):
+ paragraph_index += 1
+ if paragraph_index != len(direct_tags):
return True
+
+ p_pr = paragraph.find("a:pPr", NS)
+ if p_pr is not None:
+ p_pr_tags = [child.tag.rsplit("}", 1)[-1] for child in p_pr]
+ if p_pr_tags.count("defRPr") > 1 or p_pr_tags.count("buNone") > 1:
+ return True
+ if any(tag.startswith("bu") and tag != "buNone" for tag in p_pr_tags):
+ return True
+
+ for run in paragraph.findall("a:r", NS):
+ if run.attrib:
+ return True
+ r_pr_tag = f"{{{NS['a']}}}rPr"
+ text_tag = f"{{{NS['a']}}}t"
+ run_tags = [child.tag for child in run]
+ if run_tags not in ([text_tag], [r_pr_tag, text_tag]):
+ return True
+ text_node = run.find("a:t", NS)
+ if text_node is None or list(text_node):
+ return True
+ allowed_text_attrs = {"{http://www.w3.org/XML/1998/namespace}space"}
+ if any(name not in allowed_text_attrs for name in text_node.attrib):
+ return True
return False
-def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
+def _legacy_text_body_has_unsupported_formatting(
+ tx_body: ET.Element | None,
+) -> bool:
+ """Return the pre-P2-T4 gate so active plain payloads stay unchanged."""
if tx_body is None:
return False
body_pr = tx_body.find("a:bodyPr", NS)
@@ -861,9 +1040,8 @@ def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
):
return True
- paragraphs = tx_body.findall("a:p", NS)
run_signatures: set[tuple[str | None, str | None, bytes | None]] = set()
- for paragraph in paragraphs:
+ for paragraph in tx_body.findall("a:p", NS):
p_pr = paragraph.find("a:pPr", NS)
alignment = p_pr.get("algn") if p_pr is not None else None
if alignment not in {None, "l", "ctr", "r"}:
@@ -878,23 +1056,29 @@ def _text_body_has_unsupported_formatting(tx_body: ET.Element | None) -> bool:
return True
default_r_pr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
- if _run_props_have_unsupported_formatting(default_r_pr):
+ if _legacy_run_props_have_unsupported_formatting(default_r_pr):
return True
for run in paragraph.findall("a:r", NS):
r_pr = run.find("a:rPr", NS)
- if _run_props_have_unsupported_formatting(r_pr):
+ if _legacy_run_props_have_unsupported_formatting(r_pr):
return True
- run_signatures.add(_effective_run_signature(r_pr, default_r_pr))
+ run_signatures.add(
+ _legacy_effective_run_signature(r_pr, default_r_pr)
+ )
end_r_pr = paragraph.find("a:endParaRPr", NS)
- if _run_props_have_unsupported_formatting(end_r_pr):
+ if _legacy_run_props_have_unsupported_formatting(end_r_pr):
return True
if not paragraph.findall("a:r", NS) and end_r_pr is not None:
- run_signatures.add(_effective_run_signature(end_r_pr, default_r_pr))
+ run_signatures.add(
+ _legacy_effective_run_signature(end_r_pr, default_r_pr)
+ )
return len(run_signatures) > 1
-def _run_props_have_unsupported_formatting(r_pr: ET.Element | None) -> bool:
+def _legacy_run_props_have_unsupported_formatting(
+ r_pr: ET.Element | None,
+) -> bool:
if r_pr is None:
return False
if ooxml_bool(r_pr.get("i")):
@@ -924,7 +1108,7 @@ def _run_props_have_unsupported_formatting(r_pr: ET.Element | None) -> bool:
)
-def _effective_run_signature(
+def _legacy_effective_run_signature(
r_pr: ET.Element | None,
default_r_pr: ET.Element | None,
) -> tuple[str | None, str | None, bytes | None]:
@@ -955,6 +1139,7 @@ def _native_table_payload(
row_heights: list[float],
cells: list[list[_CellSlot | None]],
palette: ColorPalette | None,
+ theme_fonts: dict[str, str],
) -> dict[str, Any]:
"""Build the SVG data-pptx-native payload for an unmerged table."""
tbl_pr = tbl.find("a:tblPr", NS)
@@ -987,7 +1172,11 @@ def _native_table_payload(
if slot is None or slot.is_dropped:
row_payload.append("")
continue
- cell_payload = _native_cell_payload(slot.element, palette)
+ cell_payload = _native_cell_payload(
+ slot.element,
+ palette,
+ theme_fonts,
+ )
if slot.row_span > 1:
cell_payload["row_span"] = slot.row_span
if slot.col_span > 1:
@@ -998,11 +1187,22 @@ def _native_table_payload(
return payload
-def _native_cell_payload(tc: ET.Element, palette: ColorPalette | None) -> dict[str, Any]:
+def _native_cell_payload(
+ tc: ET.Element,
+ palette: ColorPalette | None,
+ theme_fonts: dict[str, str],
+) -> dict[str, Any]:
tx_body = tc.find("a:txBody", NS)
tc_pr = tc.find("a:tcPr", NS)
paragraph_payloads = _cell_paragraph_payloads(tx_body)
- if len(paragraph_payloads) > 1:
+ rich_paragraphs = _cell_rich_paragraph_payloads(
+ tx_body,
+ palette,
+ theme_fonts,
+ )
+ if rich_paragraphs is not None:
+ cell: dict[str, Any] = {"paragraphs": rich_paragraphs}
+ elif len(paragraph_payloads) > 1:
cell: dict[str, Any] = {"paragraphs": paragraph_payloads}
else:
cell = {"text": _cell_plain_text(tx_body)}
@@ -1010,12 +1210,13 @@ def _native_cell_payload(tc: ET.Element, palette: ColorPalette | None) -> dict[s
fill = _cell_fill_hex(tc_pr, palette)
if fill:
cell["fill"] = fill
- color = _cell_text_color(tx_body, palette)
- if color:
- cell["color"] = color
- font_size = _cell_font_size_px(tx_body)
- if font_size:
- cell["font_size"] = font_size
+ if rich_paragraphs is None:
+ color = _cell_text_color(tx_body, palette)
+ if color:
+ cell["color"] = color
+ font_size = _cell_font_size_px(tx_body)
+ if font_size:
+ cell["font_size"] = font_size
if len(paragraph_payloads) <= 1:
align = _cell_align(tx_body)
if align:
@@ -1023,9 +1224,10 @@ def _native_cell_payload(tc: ET.Element, palette: ColorPalette | None) -> dict[s
valign = _cell_valign(tc_pr)
if valign:
cell["valign"] = valign
- bold = _cell_bold(tx_body)
- if bold is not None:
- cell["bold"] = bold
+ if rich_paragraphs is None:
+ bold = _cell_bold(tx_body)
+ if bold is not None:
+ cell["bold"] = bold
borders = _cell_borders_payload(tc_pr, palette)
if borders:
cell["borders"] = borders
@@ -1061,6 +1263,147 @@ def _cell_paragraph_payloads(
return payloads
+def _effective_run_attr(
+ r_pr: ET.Element | None,
+ default_r_pr: ET.Element | None,
+ name: str,
+) -> str | None:
+ if r_pr is not None and r_pr.get(name) is not None:
+ return r_pr.get(name)
+ return default_r_pr.get(name) if default_r_pr is not None else None
+
+
+def _effective_run_child(
+ r_pr: ET.Element | None,
+ default_r_pr: ET.Element | None,
+ name: str,
+) -> ET.Element | None:
+ child = r_pr.find(f"a:{name}", NS) if r_pr is not None else None
+ if child is not None:
+ return child
+ return default_r_pr.find(f"a:{name}", NS) if default_r_pr is not None else None
+
+
+def _native_run_font_family(
+ r_pr: ET.Element | None,
+ default_r_pr: ET.Element | None,
+ theme_fonts: dict[str, str],
+) -> str | None:
+ faces: list[str] = []
+ for tag in ("latin", "ea"):
+ node = _effective_run_child(r_pr, default_r_pr, tag)
+ raw_face = node.get("typeface") if node is not None else None
+ face = _resolve_theme_typeface(raw_face, theme_fonts)
+ if face and face not in faces:
+ faces.append(face)
+ if len(faces) != 1:
+ return None
+ face = faces[0].strip()
+ return face if face and "," not in face else None
+
+
+def _native_run_payload(
+ run: ET.Element,
+ default_r_pr: ET.Element | None,
+ palette: ColorPalette | None,
+ theme_fonts: dict[str, str],
+) -> dict[str, Any]:
+ r_pr = run.find("a:rPr", NS)
+ text = run.findtext("a:t", default="", namespaces=NS)
+ payload: dict[str, Any] = {"text": text}
+
+ for source, target in (("b", "bold"), ("i", "italic")):
+ raw = _effective_run_attr(r_pr, default_r_pr, source)
+ if raw is not None:
+ payload[target] = ooxml_bool(raw)
+
+ underline = _effective_run_attr(r_pr, default_r_pr, "u")
+ if underline is not None:
+ payload["underline"] = underline != "none"
+ strike = _effective_run_attr(r_pr, default_r_pr, "strike")
+ if strike is not None:
+ payload["strike"] = strike != "noStrike"
+
+ font_size = _canonical_source_font_size_px(
+ _effective_run_attr(r_pr, default_r_pr, "sz")
+ )
+ if font_size is not None:
+ payload["font_size"] = font_size
+
+ solid_fill = _effective_run_child(r_pr, default_r_pr, "solidFill")
+ if solid_fill is not None and not _solid_fill_is_unsafe(solid_fill, palette):
+ try:
+ color, _alpha = resolve_color(find_color_elem(solid_fill), palette)
+ except (AttributeError, OverflowError, TypeError, ValueError):
+ color = None
+ if color:
+ payload["color"] = color
+
+ font_family = _native_run_font_family(
+ r_pr,
+ default_r_pr,
+ theme_fonts,
+ )
+ if font_family:
+ payload["font_family"] = font_family
+
+ for source, target in (("lang", "lang"), ("altLang", "alt_lang")):
+ language = _effective_run_attr(r_pr, default_r_pr, source)
+ if language and language.strip():
+ payload[target] = language.strip()
+ return payload
+
+
+def _cell_rich_paragraph_payloads(
+ tx_body: ET.Element | None,
+ palette: ColorPalette | None,
+ theme_fonts: dict[str, str],
+) -> list[dict[str, Any]] | None:
+ """Materialize runs only when the legacy plain contract was insufficient."""
+ if tx_body is None or not _legacy_text_body_has_unsupported_formatting(tx_body):
+ return None
+
+ paragraphs: list[tuple[str | None, list[dict[str, Any]]]] = []
+ style_signatures: set[tuple[tuple[str, Any], ...]] = set()
+ needs_runs = False
+ run_only_fields = {
+ "italic", "underline", "strike", "font_family", "lang", "alt_lang",
+ }
+ for paragraph in tx_body.findall("a:p", NS):
+ p_pr = paragraph.find("a:pPr", NS)
+ align = p_pr.get("algn") if p_pr is not None else None
+ if align not in {"l", "ctr", "r"}:
+ align = None
+ default_r_pr = p_pr.find("a:defRPr", NS) if p_pr is not None else None
+ runs = [
+ _native_run_payload(run, default_r_pr, palette, theme_fonts)
+ for run in paragraph.findall("a:r", NS)
+ ]
+ paragraphs.append((align, runs))
+ for run in runs:
+ style = tuple(sorted((key, value) for key, value in run.items() if key != "text"))
+ style_signatures.add(style)
+ if run_only_fields.intersection(run):
+ needs_runs = True
+
+ if len(style_signatures) > 1:
+ needs_runs = True
+ if not needs_runs:
+ return None
+
+ payloads: list[dict[str, Any]] = []
+ for align, runs in paragraphs:
+ paragraph_payload: dict[str, Any]
+ if runs:
+ paragraph_payload = {"runs": runs}
+ else:
+ paragraph_payload = {"text": ""}
+ if align is not None:
+ paragraph_payload["align"] = align
+ payloads.append(paragraph_payload)
+ return payloads
+
+
def _cell_fill_hex(tc_pr: ET.Element | None, palette: ColorPalette | None) -> str | None:
fill = resolve_fill(tc_pr, palette)
color = fill.attrs.get("fill") if fill.attrs else None
@@ -1072,22 +1415,42 @@ def _cell_fill_hex(tc_pr: ET.Element | None, palette: ColorPalette | None) -> st
def _cell_text_color(tx_body: ET.Element | None, palette: ColorPalette | None) -> str | None:
for r_pr in _text_run_props_in_priority(tx_body):
solid_fill = r_pr.find("a:solidFill", NS)
- if solid_fill is not None:
- color, _alpha = resolve_color(find_color_elem(solid_fill), palette)
- return color
+ if solid_fill is not None and not _solid_fill_is_unsafe(solid_fill, palette):
+ try:
+ color, _alpha = resolve_color(find_color_elem(solid_fill), palette)
+ except (AttributeError, OverflowError, TypeError, ValueError):
+ continue
+ if color:
+ return color
return None
def _cell_font_size_px(tx_body: ET.Element | None) -> int | float | None:
for r_pr in _text_run_props_in_priority(tx_body):
- if not r_pr.get("sz"):
- continue
- size = hundredths_pt_to_px(r_pr.get("sz"))
- if size > 0:
- return _round_payload_number(size)
+ size = _canonical_source_font_size_px(r_pr.get("sz"))
+ if size is not None:
+ return size
return None
+def _canonical_source_font_size_px(raw_size: str | None) -> int | float | None:
+ """Return a writer-stable font size for one bounded DrawingML token."""
+ if (
+ raw_size is None
+ or not raw_size.isascii()
+ or not raw_size.isdigit()
+ or len(raw_size) > 6
+ ):
+ return None
+ size_hpt = int(raw_size)
+ if not 100 <= size_hpt <= 400000:
+ return None
+ # The writer emits sizes at 0.1pt precision; canonicalize on first import
+ # so source and native reimport payloads stay stable.
+ canonical_hpt = round(size_hpt / 10) * 10
+ return _round_payload_number(hundredths_pt_to_px(canonical_hpt))
+
+
def _cell_align(tx_body: ET.Element | None) -> str | None:
if tx_body is None:
return None
@@ -1150,7 +1513,10 @@ def _copy_cell_margins(tc_pr: ET.Element | None, cell: dict[str, Any]) -> None:
):
if source not in tc_pr.attrib:
continue
- cell[target] = _round_payload_number(emu_to_px(tc_pr.attrib[source]))
+ value = _safe_emu_integer(tc_pr.attrib[source])
+ if value is None or value < 0:
+ continue
+ cell[target] = _round_payload_number(emu_to_px(value))
# ---------------------------------------------------------------------------
@@ -1171,10 +1537,42 @@ def _convert_cell_text(
):
"""Render cell text. PowerPoint's <a:tcPr> can override txBody insets via
its own marL/marR/marT/marB attrs; convert_txbody reads from <a:bodyPr>,
- so we materialise a synthetic bodyPr by mutating the txBody in place when
- tcPr has its own insets. (We undo the mutation afterwards to keep the
- slide tree pristine for any subsequent passes.)"""
- body_pr = tx_body.find("a:bodyPr", NS)
+ so we materialise a synthetic bodyPr when tcPr has its own insets. Invalid
+ malformed source font-size and run-color values are removed from a private
+ render copy; they have already been omitted from the native payload and
+ must not crash fallback SVG generation."""
+ render_tx_body = tx_body
+ run_props = [
+ node
+ for node in tx_body.iter()
+ if node.tag in {
+ f"{{{NS['a']}}}defRPr",
+ f"{{{NS['a']}}}endParaRPr",
+ f"{{{NS['a']}}}rPr",
+ }
+ ]
+ if any(
+ _run_props_need_render_normalization(node, palette)
+ for node in run_props
+ ):
+ render_tx_body = copy.deepcopy(tx_body)
+ for node in render_tx_body.iter():
+ if node.tag not in {
+ f"{{{NS['a']}}}defRPr",
+ f"{{{NS['a']}}}endParaRPr",
+ f"{{{NS['a']}}}rPr",
+ }:
+ continue
+ if (
+ node.get("sz") is not None
+ and _canonical_source_font_size_px(node.get("sz")) is None
+ ):
+ node.attrib.pop("sz", None)
+ solid_fill = node.find("a:solidFill", NS)
+ if solid_fill is not None and _solid_fill_is_unsafe(solid_fill, palette):
+ node.remove(solid_fill)
+
+ body_pr = render_tx_body.find("a:bodyPr", NS)
overrides = _tcPr_inset_overrides(tcPr)
saved: dict[str, str | None] = {}
if overrides and body_pr is not None:
@@ -1182,13 +1580,23 @@ def _convert_cell_text(
saved[key] = body_pr.attrib.get(key)
body_pr.set(key, val)
try:
- return convert_txbody(
- tx_body, cell_xfrm, palette, theme_fonts=theme_fonts,
- fallback_run_props=fallback_run_props,
- slide_number=slide_number,
- id_prefix=id_prefix,
- id_seq=id_seq,
- )
+ try:
+ return convert_txbody(
+ render_tx_body, cell_xfrm, palette, theme_fonts=theme_fonts,
+ fallback_run_props=fallback_run_props,
+ slide_number=slide_number,
+ id_prefix=id_prefix,
+ id_seq=id_seq,
+ )
+ except (AttributeError, OverflowError, TypeError, ValueError):
+ plain_tx_body = _plain_table_text_body(render_tx_body, overrides)
+ return convert_txbody(
+ plain_tx_body, cell_xfrm, palette, theme_fonts=theme_fonts,
+ fallback_run_props=(),
+ slide_number=slide_number,
+ id_prefix=id_prefix,
+ id_seq=id_seq,
+ )
finally:
if overrides and body_pr is not None:
for key, prior in saved.items():
@@ -1198,14 +1606,99 @@ def _convert_cell_text(
body_pr.set(key, prior)
+def _run_props_need_render_normalization(
+ run_props: ET.Element,
+ palette: ColorPalette | None,
+) -> bool:
+ size = run_props.get("sz")
+ if size is not None and _canonical_source_font_size_px(size) is None:
+ return True
+ solid_fill = run_props.find("a:solidFill", NS)
+ return solid_fill is not None and _solid_fill_is_unsafe(solid_fill, palette)
+
+
+def _solid_fill_is_unsafe(
+ solid_fill: ET.Element,
+ palette: ColorPalette | None,
+) -> bool:
+ color = find_color_elem(solid_fill)
+ if color is not None and not _color_numeric_tokens_are_finite(color):
+ return True
+ try:
+ resolve_color(color, palette)
+ except (AttributeError, OverflowError, TypeError, ValueError):
+ return True
+ return False
+
+
+def _color_numeric_tokens_are_finite(color: ET.Element) -> bool:
+ """Reject non-finite numeric tokens before the resolver can clamp them."""
+ base_numeric_attrs = {
+ "hslClr": ("hue", "sat", "lum"),
+ "scrgbClr": ("r", "g", "b"),
+ }
+ modifier_tags = {
+ "alpha", "alphaMod", "alphaOff", "hueMod", "hueOff",
+ "lumMod", "lumOff", "satMod", "satOff", "shade", "tint",
+ }
+ for node in color.iter():
+ name = node.tag.rsplit("}", 1)[-1]
+ attrs = base_numeric_attrs.get(name, ())
+ if name in modifier_tags:
+ attrs = ("val",)
+ for attr in attrs:
+ raw = node.get(attr)
+ if raw is None:
+ return False
+ try:
+ value = float(raw)
+ except (OverflowError, TypeError, ValueError):
+ return False
+ if not math.isfinite(value):
+ return False
+ return True
+
+
+def _plain_table_text_body(
+ tx_body: ET.Element,
+ overrides: dict[str, str],
+) -> ET.Element:
+ """Return a text-preserving style-free fallback after malformed styling."""
+ plain = copy.deepcopy(tx_body)
+ body_pr = plain.find("a:bodyPr", NS)
+ if body_pr is None:
+ body_pr = ET.Element(f"{{{NS['a']}}}bodyPr")
+ plain.insert(0, body_pr)
+ body_pr.clear()
+ for key, value in overrides.items():
+ body_pr.set(key, value)
+ list_style = plain.find("a:lstStyle", NS)
+ if list_style is not None:
+ list_style.clear()
+ for paragraph in plain.findall("a:p", NS):
+ p_pr = paragraph.find("a:pPr", NS)
+ if p_pr is not None:
+ align = p_pr.get("algn")
+ p_pr.clear()
+ if align in {"l", "ctr", "r"}:
+ p_pr.set("algn", align)
+ for path in (".//a:rPr", ".//a:defRPr", ".//a:endParaRPr"):
+ for run_props in plain.findall(path, NS):
+ run_props.clear()
+ return plain
+
+
def _tcPr_inset_overrides(tcPr: ET.Element | None) -> dict[str, str]:
if tcPr is None:
return {}
out: dict[str, str] = {}
for src, dst in (("marL", "lIns"), ("marR", "rIns"),
("marT", "tIns"), ("marB", "bIns")):
- if src in tcPr.attrib:
- out[dst] = tcPr.attrib[src]
+ if src not in tcPr.attrib:
+ continue
+ value = _safe_emu_integer(tcPr.attrib[src])
+ if value is not None and value >= 0:
+ out[dst] = str(value)
return out
diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py
index 1359715c..78d5f4c6 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
@@ -8,7 +8,7 @@ from xml.etree import ElementTree as ET
from ..drawingml.context import ConvertContext, ShapeResult
from ..drawingml.theme_colors import ThemeColorSpec, color_node_xml
-from ..drawingml.utils import _xml_escape, detect_text_lang
+from ..drawingml.utils import _xml_escape, detect_text_lang, font_px_to_hpt
from .chart_style import _font_face_xml
from .marker_common import (
TABLE_URI,
@@ -18,6 +18,7 @@ from .marker_common import (
_compact_key,
_first_present,
_font_size_hpt,
+ _hex_or_none,
_normalized_fallback_text,
_number,
_powerpoint_emu,
@@ -35,20 +36,46 @@ def _table_text_run(
font_face: str | None,
language: str | None,
theme_color_spec: ThemeColorSpec | None,
+ italic: bool | None = None,
+ underline: bool | None = None,
+ strike: bool | None = None,
+ alt_language: str | None = None,
+ exact_font_face: bool = False,
) -> 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 ""
+ italic_attr = f' i="{_bool_attr(italic)}"' if italic is not None else ""
+ underline_attr = (
+ f' u="{"sng" if underline else "none"}"'
+ if underline is not None else ""
+ )
+ strike_attr = (
+ f' strike="{"sngStrike" if strike else "noStrike"}"'
+ if strike is not None else ""
+ )
resolved_language = language or detect_text_lang(text)
language_attr = f' lang="{_xml_escape(resolved_language)}"'
+ alt_language_attr = (
+ f' altLang="{_xml_escape(alt_language)}"' if alt_language else ""
+ )
color_xml = (
f'<a:solidFill>{color_node_xml(color, theme_color_spec, "text")}</a:solidFill>'
if color else ""
)
+ if exact_font_face and font_face:
+ escaped_face = _xml_escape(font_face)
+ font_xml = (
+ f'<a:latin typeface="{escaped_face}"/>'
+ f'<a:ea typeface="{escaped_face}"/>'
+ )
+ else:
+ font_xml = _font_face_xml(font_face)
space_attr = ' xml:space="preserve"' if text != text.strip() else ""
return (
- f'<a:r><a:rPr{language_attr}{size_attr}{bold_attr}>'
+ f'<a:r><a:rPr{language_attr}{alt_language_attr}{size_attr}{bold_attr}'
+ f'{italic_attr}{underline_attr}{strike_attr}>'
f'{color_xml}'
- f'{_font_face_xml(font_face)}'
+ f'{font_xml}'
"</a:rPr>"
f"<a:t{space_attr}>{_xml_escape(text)}</a:t></a:r>"
)
@@ -99,10 +126,25 @@ class _TableBorderSpec:
width: float | None = None
+@dataclass(frozen=True)
+class _TableRun:
+ text: str
+ bold: bool | None = None
+ italic: bool | None = None
+ underline: bool | None = None
+ strike: bool | None = None
+ color: str | None = None
+ font_size: int | None = None
+ font_family: str | None = None
+ lang: str | None = None
+ alt_lang: str | None = None
+
+
@dataclass(frozen=True)
class _TableParagraph:
text: str
align: str | None = None
+ runs: tuple[_TableRun, ...] | None = None
def _table_rows(payload: dict[str, Any]) -> list[list[Any]]:
@@ -139,28 +181,140 @@ def _table_cell_paragraphs(
if isinstance(value, str):
paragraphs.append(_TableParagraph(value))
continue
- if not isinstance(value, dict) or "text" not in value:
+ if not isinstance(value, dict):
raise RuntimeError(
- f"Native PPTX table paragraph {idx} must be a string or text object"
+ f"Native PPTX table paragraph {idx} must be a string or object"
)
- if set(value) - {"text", "align"}:
+ if set(value) - {"text", "runs", "align"}:
raise RuntimeError(
- f"Native PPTX table paragraph {idx} accepts text/align only"
+ f"Native PPTX table paragraph {idx} accepts text/runs/align only"
)
- text = value.get("text")
- if not isinstance(text, str):
+ has_text = "text" in value
+ has_runs = "runs" in value
+ if has_text == has_runs:
raise RuntimeError(
- f"Native PPTX table paragraph {idx} text must be a string"
+ f"Native PPTX table paragraph {idx} requires exactly one of text/runs"
)
align = value.get("align")
if align is not None and align not in {"l", "ctr", "r"}:
raise RuntimeError(
f"Native PPTX table paragraph {idx} align must be l, ctr, or r"
)
- paragraphs.append(_TableParagraph(text, align))
+ if has_text:
+ text = value.get("text")
+ if not isinstance(text, str):
+ raise RuntimeError(
+ f"Native PPTX table paragraph {idx} text must be a string"
+ )
+ paragraphs.append(_TableParagraph(text, align))
+ continue
+
+ raw_runs = value.get("runs")
+ if not isinstance(raw_runs, list) or not raw_runs:
+ raise RuntimeError(
+ f"Native PPTX table paragraph {idx} runs must be a non-empty list"
+ )
+ runs = tuple(
+ _table_run(run, paragraph_idx=idx, run_idx=run_idx)
+ for run_idx, run in enumerate(raw_runs, start=1)
+ )
+ paragraphs.append(
+ _TableParagraph("".join(run.text for run in runs), align, runs)
+ )
return tuple(paragraphs)
+def _table_run(
+ value: Any,
+ *,
+ paragraph_idx: int,
+ run_idx: int,
+) -> _TableRun:
+ label = f"paragraph {paragraph_idx} run {run_idx}"
+ if not isinstance(value, dict) or "text" not in value:
+ raise RuntimeError(f"Native PPTX table {label} must be a text object")
+ allowed = {
+ "text", "bold", "italic", "underline", "strike", "color",
+ "font_size", "font_family", "lang", "alt_lang",
+ }
+ unknown = set(value) - allowed
+ if unknown:
+ fields = ", ".join(sorted(unknown))
+ raise RuntimeError(
+ f"Native PPTX table {label} contains unsupported field(s): {fields}"
+ )
+ text = value.get("text")
+ if not isinstance(text, str):
+ raise RuntimeError(f"Native PPTX table {label} text must be a string")
+
+ booleans: dict[str, bool | None] = {}
+ for field in ("bold", "italic", "underline", "strike"):
+ raw = value.get(field)
+ if raw is not None and not isinstance(raw, bool):
+ raise RuntimeError(
+ f"Native PPTX table {label} {field} must be a JSON boolean"
+ )
+ booleans[field] = raw
+
+ color: str | None = None
+ if value.get("color") is not None:
+ if not isinstance(value["color"], str):
+ raise RuntimeError(f"Native PPTX table {label} color must be a string")
+ color = _hex_or_none(value["color"])
+ if color is None:
+ raise RuntimeError(f"Native PPTX table {label} color is unsupported")
+
+ font_size: int | None = None
+ if value.get("font_size") is not None:
+ font_size_px = _number(value["font_size"], f"table {label} font_size")
+ if not 100 / 75 <= font_size_px <= 400000 / 75:
+ raise RuntimeError(
+ f"Native PPTX table {label} font_size is outside DrawingML range"
+ )
+ font_size = font_px_to_hpt(font_size_px)
+ if not 100 <= font_size <= 400000:
+ raise RuntimeError(
+ f"Native PPTX table {label} font_size is outside DrawingML range"
+ )
+
+ font_family: str | None = None
+ if value.get("font_family") is not None:
+ if not isinstance(value["font_family"], str):
+ raise RuntimeError(
+ f"Native PPTX table {label} font_family must be a string"
+ )
+ font_family = value["font_family"].strip()
+ if not font_family or "," in font_family:
+ raise RuntimeError(
+ f"Native PPTX table {label} font_family must be one typeface"
+ )
+
+ languages: dict[str, str | None] = {}
+ for field in ("lang", "alt_lang"):
+ raw = value.get(field)
+ if raw is None:
+ languages[field] = None
+ continue
+ if not isinstance(raw, str) or not raw.strip():
+ raise RuntimeError(
+ f"Native PPTX table {label} {field} must be a non-empty string"
+ )
+ languages[field] = raw.strip()
+
+ return _TableRun(
+ text=text,
+ bold=booleans["bold"],
+ italic=booleans["italic"],
+ underline=booleans["underline"],
+ strike=booleans["strike"],
+ color=color,
+ font_size=font_size,
+ font_family=font_family,
+ lang=languages["lang"],
+ alt_lang=languages["alt_lang"],
+ )
+
+
def _table_span_value(
cell_data: dict[str, Any],
key: str,
@@ -819,15 +973,38 @@ def _build_native_table(elem: ET.Element, ctx: ConvertContext, payload: dict[str
if paragraph.align is not None or paragraph_align != "l"
else "<a:pPr/>"
)
- text_run_xml = _table_text_run(
- paragraph.text,
- color=color,
- bold=bold,
- font_size=cell_font_size,
- font_face=font_face,
- language=language,
- theme_color_spec=ctx.theme_color_spec,
- )
+ if paragraph.runs is None:
+ text_run_xml = _table_text_run(
+ paragraph.text,
+ color=color,
+ bold=bold,
+ font_size=cell_font_size,
+ font_face=font_face,
+ language=language,
+ theme_color_spec=ctx.theme_color_spec,
+ )
+ else:
+ text_run_xml = "".join(
+ _table_text_run(
+ run.text,
+ color=run.color or color,
+ bold=run.bold if run.bold is not None else bold,
+ font_size=(
+ run.font_size
+ if run.font_size is not None
+ else cell_font_size
+ ),
+ font_face=run.font_family or font_face,
+ language=run.lang or language,
+ theme_color_spec=ctx.theme_color_spec,
+ italic=run.italic,
+ underline=run.underline,
+ strike=run.strike,
+ alt_language=run.alt_lang,
+ exact_font_face=run.font_family is not None,
+ )
+ for run in paragraph.runs
+ )
paragraph_parts.append(
f"<a:p>{paragraph_props}{text_run_xml}</a:p>"
)