Skip to content

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

fix(pptx-to-svg): preserve complex deck semantics in SVG imports

hugohe38c86685977de
diff --git a/skills/ppt-master/scripts/extract_svg_assets.py b/skills/ppt-master/scripts/extract_svg_assets.py
index 00221568..f5e6fc20 100644
--- a/skills/ppt-master/scripts/extract_svg_assets.py
+++ b/skills/ppt-master/scripts/extract_svg_assets.py
@@ -38,10 +38,12 @@ import argparse
import copy
import hashlib
import json
+import os
import re
import sys
from pathlib import Path
from typing import Optional
+from urllib.parse import urlsplit, urlunsplit
from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
@@ -55,6 +57,7 @@ configure_utf8_stdio()
SVG_NS = "http://www.w3.org/2000/svg"
DRAWABLE = {"path", "polygon", "polyline", "rect", "circle", "ellipse", "line"}
SEMANTIC_CONTENT = {"text", "tspan", "foreignObject"}
+DEFINITION_CONTAINERS = {"defs"}
DEFAULT_MIN_DRAWABLES = 20
DEFAULT_MIN_BYTES = 3000
DEFAULT_MIN_DECORATION_BYTES = 3000
@@ -99,7 +102,12 @@ def _has_icon_placeholder(elem: ET.Element) -> bool:
def _is_extractable_subtree(elem: ET.Element) -> bool:
"""Pure vector subtrees can be moved; semantic content must stay inline."""
- if _has_icon_placeholder(elem) or _is_chart_group(elem) or _has_semantic_content(elem):
+ if (
+ _local(elem.tag) in DEFINITION_CONTAINERS
+ or _has_icon_placeholder(elem)
+ or _is_chart_group(elem)
+ or _has_semantic_content(elem)
+ ):
return False
return _drawable_count(elem) > 0
@@ -189,16 +197,48 @@ def _collect_id_mapping(asset_id: str, group: ET.Element, dependencies: list[ET.
def _rewrite_references(elem: ET.Element, id_mapping: dict[str, str]) -> None:
- def rewrite_url(match: re.Match[str]) -> str:
- quote, ref_id = match.group(1), match.group(2)
- new_id = id_mapping.get(ref_id, ref_id)
- return f"url({quote}#{new_id}{quote})"
+ _rewrite_reference_values(elem, id_mapping)
for item in elem.iter():
elem_id = item.get("id")
if elem_id in id_mapping:
item.set("id", id_mapping[elem_id])
+
+def _rebase_external_hrefs(
+ elem: ET.Element,
+ source_dir: Path,
+ target_dir: Path,
+) -> int:
+ """Keep relative image/use references valid after moving a subtree."""
+ rewritten_count = 0
+ for item in elem.iter():
+ for attr_name, value in list(item.attrib.items()):
+ if _local(attr_name) != "href" or value.startswith(("#", "/")):
+ continue
+ parsed = urlsplit(value)
+ if parsed.scheme or parsed.netloc or not parsed.path:
+ continue
+ source_target = (source_dir / parsed.path).resolve()
+ relative = Path(os.path.relpath(source_target, target_dir)).as_posix()
+ rewritten = urlunsplit(("", "", relative, parsed.query, parsed.fragment))
+ if rewritten != value:
+ item.set(attr_name, rewritten)
+ rewritten_count += 1
+ return rewritten_count
+
+
+def _rewrite_reference_values(
+ elem: ET.Element,
+ id_mapping: dict[str, str],
+) -> None:
+ """Rewrite local URL/href references without renaming definition ids."""
+ def rewrite_url(match: re.Match[str]) -> str:
+ quote, ref_id = match.group(1), match.group(2)
+ new_id = id_mapping.get(ref_id, ref_id)
+ return f"url({quote}#{new_id}{quote})"
+
+ for item in elem.iter():
for attr_name, value in list(item.attrib.items()):
rewritten = URL_REF_RE.sub(rewrite_url, value)
if _local(attr_name) == "href" and value.startswith("#") and value[1:] in id_mapping:
@@ -207,11 +247,92 @@ def _rewrite_references(elem: ET.Element, id_mapping: dict[str, str]) -> None:
item.set(attr_name, rewritten)
+def _definition_signature(elem: ET.Element) -> bytes:
+ """Return definition semantics without its document-local id."""
+ normalized = copy.deepcopy(elem)
+ normalized.attrib.pop("id", None)
+ return ET.tostring(normalized, encoding="utf-8")
+
+
+def _optimize_definitions(root: ET.Element) -> tuple[int, int]:
+ """Deduplicate equivalent defs and remove definitions with no live refs."""
+ deduplicated = 0
+ pruned = 0
+ definition_containers = [
+ child for child in root
+ if _local(child.tag) in DEFINITION_CONTAINERS
+ ]
+
+ for definitions in definition_containers:
+ canonical_by_signature: dict[bytes, str] = {}
+ duplicate_ids: dict[str, str] = {}
+ duplicate_elements: list[ET.Element] = []
+ for definition in list(definitions):
+ definition_id = definition.get("id")
+ if not definition_id:
+ continue
+ signature = _definition_signature(definition)
+ canonical_id = canonical_by_signature.get(signature)
+ if canonical_id is None:
+ canonical_by_signature[signature] = definition_id
+ continue
+ duplicate_ids[definition_id] = canonical_id
+ duplicate_elements.append(definition)
+
+ if duplicate_ids:
+ _rewrite_reference_values(root, duplicate_ids)
+ for definition in duplicate_elements:
+ definitions.remove(definition)
+ deduplicated += len(duplicate_elements)
+
+ owner_by_id: dict[str, ET.Element] = {}
+ for definition in definitions:
+ for item in definition.iter():
+ if item_id := item.get("id"):
+ owner_by_id[item_id] = definition
+
+ live_refs: set[str] = set()
+ for attr_name, value in root.attrib.items():
+ live_refs.update(match.group(2) for match in URL_REF_RE.finditer(value))
+ if _local(attr_name) == "href" and value.startswith("#"):
+ live_refs.add(value[1:])
+ for child in root:
+ if child is definitions:
+ continue
+ live_refs.update(_referenced_ids(child))
+
+ reachable: set[ET.Element] = set()
+ pending = sorted(live_refs)
+ while pending:
+ ref_id = pending.pop(0)
+ owner = owner_by_id.get(ref_id)
+ if owner is None or owner in reachable:
+ continue
+ reachable.add(owner)
+ for nested_ref in sorted(_referenced_ids(owner)):
+ if nested_ref not in live_refs:
+ live_refs.add(nested_ref)
+ pending.append(nested_ref)
+
+ for definition in list(definitions):
+ has_id = any(item.get("id") for item in definition.iter())
+ if has_id and definition not in reachable:
+ definitions.remove(definition)
+ pruned += 1
+
+ if not list(definitions):
+ root.remove(definitions)
+
+ return deduplicated, pruned
+
+
def _find_extractable(root: ET.Element, min_drawables: int, min_bytes: int) -> list[ET.Element]:
"""Outermost <g> groups whose drawable count clears the threshold (no nesting)."""
found: list[ET.Element] = []
def walk(elem: ET.Element) -> None:
+ if _local(elem.tag) in DEFINITION_CONTAINERS:
+ return
for child in list(elem):
if _local(child.tag) != "g":
walk(child)
@@ -254,6 +375,8 @@ def _find_extractable_runs(
found.append((parent, list(run)))
def walk(elem: ET.Element) -> None:
+ if _local(elem.tag) in DEFINITION_CONTAINERS:
+ return
run: list[ET.Element] = []
for child in list(elem):
if _is_extractable_subtree(child):
@@ -548,12 +671,13 @@ def extract_file(
view_box = root.get("viewBox")
width = root.get("width")
height = root.get("height")
+ definitions_changed = any(_optimize_definitions(root))
# A namespaced projection is an all-at-once readability pass. Once it owns
# an asset reference, reruns inventory the existing placeholders instead of
# progressively factoring their remaining parent/sibling geometry.
if _has_namespace_placeholder(root, icon_namespace):
- if not inplace:
+ if definitions_changed or not inplace:
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
@@ -587,7 +711,7 @@ def extract_file(
targets.append((parent, run))
if not targets:
- if not inplace:
+ if definitions_changed or not inplace:
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
@@ -648,8 +772,20 @@ def extract_file(
_rewrite_references(dependency, id_mapping)
# Asset keeps the group in original page coordinates and carries its defs.
+ asset_path = icons_dir / asset
+ external_hrefs_rewritten = _rebase_external_hrefs(
+ group,
+ svg_path.parent,
+ asset_path.parent,
+ )
+ for dependency in dependencies:
+ external_hrefs_rewritten += _rebase_external_hrefs(
+ dependency,
+ svg_path.parent,
+ asset_path.parent,
+ )
asset_bytes = _asset_svg(group, dependencies, view_box, width, height)
- (icons_dir / asset).write_bytes(asset_bytes)
+ asset_path.write_bytes(asset_bytes)
placeholder = ET.Element(f"{{{SVG_NS}}}use")
placeholder.set("data-icon", icon_reference)
@@ -670,9 +806,11 @@ def extract_file(
"byte_count": _xml_size(group),
"source_refs": source_refs,
"dependencies": [id_mapping.get(elem_id, elem_id) for elem_id in dependency_source_ids],
+ "external_hrefs_rewritten": external_hrefs_rewritten,
"elements": _tag_histogram(group),
})
+ _optimize_definitions(root)
rewritten = _rewritten_path(svg_path, rewritten_dir, inplace)
rewritten.parent.mkdir(parents=True, exist_ok=True)
tree.write(rewritten, encoding="utf-8", xml_declaration=True)
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 e2568b1f..e7ef0395 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
@@ -249,7 +249,13 @@ def _payload_from_chart_xml(
has_date_axis or chart_tag in {"bubbleChart", "scatterChart"}
),
)
- _apply_chart_metadata(payload, chart_root, plot_area, chart)
+ _apply_chart_metadata(
+ payload,
+ chart_root,
+ plot_area,
+ chart,
+ palette=palette,
+ )
return payload, visual_styles
@@ -261,16 +267,46 @@ def _combo_payload(
*,
palette: ColorPalette | None,
) -> tuple[dict[str, Any], list[SeriesVisualStyle]]:
- series_indices_by_plot = [
- _plot_series_indices(chart, "unsupported-combo-series-order")
+ series_identifiers_by_plot = [
+ _plot_series_identifiers(chart, "unsupported-combo-series-order")
for chart in chart_nodes
]
- flat_series_indices = [
+ source_indices_by_plot = [
+ identifiers[0] for identifiers in series_identifiers_by_plot
+ ]
+ source_orders_by_plot = [
+ identifiers[1] for identifiers in series_identifiers_by_plot
+ ]
+ flat_source_indices = [
index
- for series_indices in series_indices_by_plot
- for index in series_indices
+ for indices in source_indices_by_plot
+ for index in indices
+ ]
+ flat_source_orders = [
+ order
+ for orders in source_orders_by_plot
+ for order in orders
]
- if sorted(flat_series_indices) != list(range(len(flat_series_indices))):
+ expected_series_order = list(range(len(flat_source_orders)))
+ canonical_indices = (
+ flat_source_indices == flat_source_orders
+ and sorted(flat_source_indices) == expected_series_order
+ )
+ normalizable_indices = (
+ len(set(flat_source_indices)) == len(flat_source_indices)
+ and sorted(flat_source_orders) == expected_series_order
+ )
+ if canonical_indices:
+ series_indices_by_plot = source_indices_by_plot
+ elif normalizable_indices and palette is not None and not palette.strict:
+ palette._diagnose(
+ "combo-series-indices-normalized",
+ "Combo chart series idx values do not match their contiguous "
+ "display order",
+ "reindex series by their unique contiguous order values",
+ )
+ series_indices_by_plot = source_orders_by_plot
+ else:
raise _UnsupportedChart("unsupported-combo-series-order")
axes_by_id = _axis_nodes_by_id(plot_area)
if not axes_by_id:
@@ -378,7 +414,7 @@ def _combo_payload(
str(color)
for color in plot_payload.get("style", {}).get("colors", [])
)
- _apply_plot_data_labels(plot_payload, chart)
+ _apply_plot_data_labels(plot_payload, chart, palette=palette)
plot_entry: dict[str, Any] = {
"axis": axis_name,
"categories": list(plot_payload["categories"]),
@@ -424,6 +460,7 @@ def _combo_payload(
chart_root,
plot_area,
chart_nodes[0],
+ palette=palette,
include_plot_labels=False,
)
return payload, visual_styles
@@ -574,7 +611,13 @@ def _stock_payload(
"type": "stock",
}
visual_styles = _chart_visual_styles(payload, chart, palette)
- _apply_chart_metadata(payload, chart_root, plot_area, chart)
+ _apply_chart_metadata(
+ payload,
+ chart_root,
+ plot_area,
+ chart,
+ palette=palette,
+ )
return payload, visual_styles
@@ -955,6 +998,213 @@ def _chart_visual_styles(
return styles
+def _representative_gradient_color(
+ gradient: ET.Element,
+ palette: ColorPalette | None,
+) -> tuple[str, float] | None:
+ """Collapse a chart gradient to one representative tolerant-mode color."""
+ resolved: list[tuple[str, float]] = []
+ for stop in gradient.findall("a:gsLst/a:gs", C_NS):
+ try:
+ color, opacity = resolve_color(
+ find_color_elem(stop),
+ palette,
+ strict=False,
+ )
+ except (TypeError, ValueError, OverflowError):
+ continue
+ if color is not None:
+ resolved.append((color, opacity))
+ if not resolved:
+ return None
+ channels = [
+ tuple(int(color[offset:offset + 2], 16) for offset in (1, 3, 5))
+ for color, _opacity in resolved
+ ]
+ averaged = tuple(
+ round(sum(channel[index] for channel in channels) / len(channels))
+ for index in range(3)
+ )
+ color = "#" + "".join(f"{value:02X}" for value in averaged)
+ opacity = sum(value for _color, value in resolved) / len(resolved)
+ return color, max(0.0, min(1.0, opacity))
+
+
+def _representative_fill(
+ container: ET.Element | None,
+ palette: ColorPalette | None,
+) -> tuple[str | None, float, bool]:
+ """Return a flat color approximation for one chart fill container."""
+ if container is None:
+ return None, 1.0, False
+ if container.find("a:noFill", C_NS) is not None:
+ return None, 1.0, True
+ solid = container.find("a:solidFill", C_NS)
+ if solid is not None:
+ try:
+ color, opacity = resolve_color(
+ find_color_elem(solid),
+ palette,
+ strict=False,
+ )
+ except (TypeError, ValueError, OverflowError):
+ color = None
+ opacity = 1.0
+ if color is not None:
+ return color.upper(), max(0.0, min(1.0, opacity)), True
+ gradient = container.find("a:gradFill", C_NS)
+ if gradient is not None:
+ representative = _representative_gradient_color(gradient, palette)
+ if representative is not None:
+ return representative[0].upper(), representative[1], True
+ return None, 1.0, False
+
+
+def _normalized_line_paint(
+ line: ET.Element | None,
+ palette: ColorPalette | None,
+) -> _LinePaint | None:
+ if line is None:
+ return None
+ color, opacity, explicit = _representative_fill(line, palette)
+ raw_width = line.attrib.get("w", "")
+ width = int(raw_width) / 9525.0 if raw_width.isdigit() else 1.5
+ width = max(0.0, min(1000.0, width))
+ cap = {
+ "rnd": "round",
+ "sq": "square",
+ "flat": "butt",
+ }.get(line.attrib.get("cap"), "round")
+ return _LinePaint(
+ color,
+ opacity,
+ width,
+ cap,
+ not (explicit and color is None),
+ not explicit,
+ )
+
+
+def _normalized_shape_paint(
+ sp_pr: ET.Element | None,
+ palette: ColorPalette | None,
+) -> _ShapePaint:
+ fill, opacity, explicit = _representative_fill(sp_pr, palette)
+ line = (
+ _normalized_line_paint(sp_pr.find("a:ln", C_NS), palette)
+ if sp_pr is not None
+ else None
+ )
+ return _ShapePaint(fill, opacity, explicit, line)
+
+
+def _normalized_marker_paint(
+ marker: ET.Element | None,
+ palette: ColorPalette | None,
+) -> _MarkerPaint:
+ if marker is None:
+ return _MarkerPaint(None, 5.0, _normalized_shape_paint(None, palette))
+ symbol = _element_val(marker.find("c:symbol", C_NS))
+ if symbol not in {None, "circle", "none"}:
+ symbol = "circle"
+ raw_size = _element_val(marker.find("c:size", C_NS))
+ try:
+ size = float(raw_size) if raw_size is not None else 5.0
+ except (TypeError, ValueError, OverflowError):
+ size = 5.0
+ return _MarkerPaint(
+ symbol,
+ max(2.0, min(72.0, size)),
+ _normalized_shape_paint(marker.find("c:spPr", C_NS), palette),
+ )
+
+
+def _normalized_chart_visual_styles(
+ payload: dict[str, Any],
+ plot: ET.Element,
+ palette: ColorPalette | None,
+) -> list[SeriesVisualStyle]:
+ """Keep chart data visible when source-only styling is not portable."""
+ chart_type = payload["type"]
+ series_nodes = plot.findall("c:ser", C_NS)
+ styles: list[SeriesVisualStyle] = []
+ if chart_type in {"pie", "doughnut", "of_pie"} and series_nodes:
+ expected_count = len(payload["categories"])
+ if chart_type == "of_pie":
+ expected_count += 1
+ series = series_nodes[0]
+ base_shape = _normalized_shape_paint(
+ series.find("c:spPr", C_NS),
+ palette,
+ )
+ points: dict[int, _ShapePaint] = {}
+ for point in series.findall("c:dPt", C_NS):
+ raw_index = _element_val(point.find("c:idx", C_NS))
+ if raw_index is None or not raw_index.isdigit():
+ continue
+ point_index = int(raw_index)
+ if 0 <= point_index < expected_count:
+ points[point_index] = _normalized_shape_paint(
+ point.find("c:spPr", C_NS),
+ palette,
+ )
+ for index in range(expected_count):
+ auto = _automatic_color(palette, index)
+ shape = points.get(index, base_shape)
+ fill = shape.fill if shape.fill_explicit else auto
+ line = shape.line
+ stroke = _line_color(line, "#FFFFFF")
+ styles.append(
+ SeriesVisualStyle(
+ fill=fill,
+ fill_opacity=shape.fill_opacity,
+ stroke=stroke,
+ stroke_opacity=line.opacity if line is not None else 1.0,
+ stroke_width=line.width if line is not None else 1.0,
+ line_cap=line.cap if line is not None else "round",
+ marker_fill=fill,
+ marker_stroke=stroke,
+ )
+ )
+ else:
+ for index, series in enumerate(series_nodes):
+ shape = _normalized_shape_paint(
+ series.find("c:spPr", C_NS),
+ palette,
+ )
+ if not shape.fill_explicit:
+ first_point = series.find("c:dPt/c:spPr", C_NS)
+ point_shape = _normalized_shape_paint(first_point, palette)
+ if point_shape.fill_explicit:
+ shape = _ShapePaint(
+ point_shape.fill,
+ point_shape.fill_opacity,
+ True,
+ shape.line,
+ )
+ styles.append(
+ _series_visual_style(
+ shape,
+ _normalized_marker_paint(
+ series.find("c:marker", C_NS),
+ palette,
+ ),
+ chart_type=chart_type,
+ auto_color=_automatic_color(palette, index),
+ )
+ )
+ colors = [
+ style.fill
+ or style.stroke
+ or style.marker_fill
+ or _automatic_color(palette, index)
+ for index, style in enumerate(styles)
+ ]
+ if colors:
+ payload["style"] = {"colors": colors}
+ return styles
+
+
def _strict_axis_bool(elem: ET.Element | None, default: bool) -> bool:
if elem is None:
return default
@@ -989,8 +1239,12 @@ def _validate_canonical_series_order(
expected_index += 1
-def _plot_series_indices(plot: ET.Element, status: str) -> list[int]:
+def _plot_series_identifiers(
+ plot: ET.Element,
+ status: str,
+) -> tuple[list[int], list[int]]:
indices: list[int] = []
+ orders: list[int] = []
for series in plot.findall("c:ser", C_NS):
values: list[int] = []
for child_name in ("idx", "order"):
@@ -1005,12 +1259,15 @@ def _plot_series_indices(plot: ET.Element, status: str) -> list[int]:
):
raise _UnsupportedChart(status)
values.append(int(raw_value))
- if values[0] != values[1]:
- raise _UnsupportedChart(status)
indices.append(values[0])
- if not indices or len(set(indices)) != len(indices):
+ orders.append(values[1])
+ if (
+ not indices
+ or len(set(indices)) != len(indices)
+ or len(set(orders)) != len(orders)
+ ):
raise _UnsupportedChart(status)
- return indices
+ return indices, orders
def _axis_number(elem: ET.Element | None) -> int | float | None:
@@ -1605,7 +1862,26 @@ def _validate_chart_semantics(
"""Reject valid chart features the compact marker cannot reproduce."""
chart_type = payload["type"]
grouping = payload.get("grouping")
- visual_styles = _chart_visual_styles(payload, plot, palette)
+ try:
+ visual_styles = _chart_visual_styles(payload, plot, palette)
+ except _UnsupportedChart as exc:
+ if (
+ exc.status != "unsupported-chart-series-style"
+ or palette is None
+ or palette.strict
+ ):
+ raise
+ palette._diagnose(
+ "chart-series-style-normalized",
+ "Chart series styling uses DrawingML features outside the native "
+ "flat-color chart contract",
+ "preserve chart data and use representative flat series colors",
+ )
+ visual_styles = _normalized_chart_visual_styles(
+ payload,
+ plot,
+ palette,
+ )
for tag in (
"trendline", "errBars", "dropLines", "hiLowLines", "upDownBars",
):
@@ -1700,9 +1976,13 @@ def _validate_chart_semantics(
if first_slice not in {None, "0"}:
raise _UnsupportedChart("unsupported-chart-pie-options")
if chart_type == "doughnut":
- hole_size = _element_val(plot.find("c:holeSize", C_NS))
- if hole_size != "75":
+ raw_hole_size = _element_val(plot.find("c:holeSize", C_NS))
+ if raw_hole_size is None or not raw_hole_size.isdigit():
raise _UnsupportedChart("unsupported-chart-doughnut-options")
+ hole_size = int(raw_hole_size)
+ if not 10 <= hole_size <= 90:
+ raise _UnsupportedChart("unsupported-chart-doughnut-options")
+ payload["hole_size"] = hole_size
if chart_type == "of_pie":
for tag in ("splitType", "splitPos", "custSplit"):
if plot.find(f"c:{tag}", C_NS) is not None:
@@ -1716,14 +1996,34 @@ def _validate_chart_semantics(
return visual_styles
-def _apply_plot_data_labels(payload: dict[str, Any], plot: ET.Element) -> None:
+def _apply_plot_data_labels(
+ payload: dict[str, Any],
+ plot: ET.Element,
+ *,
+ palette: ColorPalette | None = None,
+) -> None:
if plot.find("c:ser/c:dLbls", C_NS) is not None:
- raise _UnsupportedChart("unsupported-chart-series-data-labels")
+ if palette is None or palette.strict:
+ raise _UnsupportedChart("unsupported-chart-series-data-labels")
+ palette._diagnose(
+ "chart-series-data-labels-omitted",
+ "Per-series or per-point chart data-label placement is outside "
+ "the native chart contract",
+ "keep the chart data and any supported plot-level labels",
+ )
data_labels = _data_labels_payload(plot.find("c:dLbls", C_NS))
if not data_labels:
return
if payload["type"] not in {"area", "bar", "column", "line"}:
- raise _UnsupportedChart("unsupported-chart-data-labels")
+ if palette is None or palette.strict:
+ raise _UnsupportedChart("unsupported-chart-data-labels")
+ palette._diagnose(
+ "chart-data-labels-normalized",
+ "Source data-label options are outside the native contract for "
+ f'{payload["type"]} charts',
+ "use the normalized SVG chart label layout",
+ )
+ return
try:
validate_data_label_position(
data_labels.get("position"),
@@ -1741,6 +2041,7 @@ def _apply_chart_metadata(
plot_area: ET.Element,
plot: ET.Element,
*,
+ palette: ColorPalette | None = None,
include_plot_labels: bool = True,
) -> None:
"""Copy visible classic-chart chrome supported by the native schema."""
@@ -1770,7 +2071,7 @@ def _apply_chart_metadata(
payload["legend_position"] = position
if include_plot_labels:
- _apply_plot_data_labels(payload, plot)
+ _apply_plot_data_labels(payload, plot, palette=palette)
axis_titles: dict[str, str] = {}
category_axis_nodes = (
diff --git a/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.py
index 760af4a4..76c821da 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/fill_to_svg.py
@@ -81,6 +81,7 @@ def resolve_fill(
id_prefix: str = "g",
id_seq: list[int] | None = None,
placeholder_hex: str | None = None,
+ group_fill: FillResult | None = None,
) -> FillResult:
"""Inspect <p:spPr>'s fill children and emit an SVG fill descriptor.
@@ -124,7 +125,11 @@ def resolve_fill(
fill_elem, fill_name = fill_children[0]
if fill_name == "grpFill":
- raise ValueError("Unsupported DrawingML fill: grpFill")
+ if group_fill is None:
+ raise ValueError(
+ "DrawingML grpFill requires a resolved ancestor group fill"
+ )
+ return FillResult(attrs=dict(group_fill.attrs))
return handlers[fill_name](
fill_elem,
palette,
@@ -179,7 +184,7 @@ def _resolve_grad_fill(elem: ET.Element, palette: ColorPalette | None,
_validate_gradient_attributes(elem)
_validate_gradient_rotation(elem)
_validate_gradient_flip(elem)
- _validate_gradient_tile_rect(elem)
+ _validate_or_normalize_gradient_tile_rect(elem, palette)
if seq is None:
seq = [0]
seq[0] += 1
@@ -248,7 +253,7 @@ def _resolve_grad_fill(elem: ET.Element, palette: ColorPalette | None,
# ang is 1/60000 deg. 0° = horizontal left-to-right.
_validate_linear_gradient_structure(lin)
angle = _linear_gradient_angle(lin)
- _validate_linear_gradient_scaling(lin, angle)
+ _validate_or_normalize_linear_gradient_scaling(lin, angle, palette)
angle_deg = angle / ANGLE_UNIT
x1, y1, x2, y2 = _angle_to_unit_endpoints(angle_deg)
defs_xml = (
@@ -399,11 +404,12 @@ def _validate_linear_gradient_structure(lin: ET.Element) -> None:
)
-def _validate_linear_gradient_scaling(
+def _validate_or_normalize_linear_gradient_scaling(
lin: ET.Element,
angle: int,
+ palette: ColorPalette | None,
) -> None:
- """Require a scaling mode representable by unit-box SVG geometry."""
+ """Normalize unscaled oblique gradients only in tolerant import mode."""
scaled = _parse_ooxml_boolean(
lin.get("scaled"),
default=False,
@@ -411,10 +417,18 @@ def _validate_linear_gradient_scaling(
)
quarter_turn = 90 * ANGLE_UNIT
if not scaled and angle % quarter_turn:
- raise ValueError(
+ message = (
"Unscaled non-cardinal DrawingML linear gradients are not "
"representable by the normalized SVG mapping"
)
+ if palette is None or palette.strict:
+ raise ValueError(message)
+ palette._diagnose(
+ "gradient-scaling-normalized",
+ message,
+ "map the angle to the normalized SVG unit box while preserving "
+ "its stops",
+ )
def _validate_gradient_rotation(gradient: ET.Element) -> None:
@@ -474,8 +488,11 @@ def _validate_gradient_flip(gradient: ET.Element) -> None:
raise ValueError(f"Unsupported DrawingML gradient flip: {flip!r}")
-def _validate_gradient_tile_rect(gradient: ET.Element) -> None:
- """Accept only the full-area gradient tile rectangle."""
+def _validate_or_normalize_gradient_tile_rect(
+ gradient: ET.Element,
+ palette: ColorPalette | None,
+) -> None:
+ """Ignore a cropped gradient tile only in tolerant import mode."""
tile_rects = gradient.findall("a:tileRect", NS)
if len(tile_rects) > 1:
raise ValueError(
@@ -489,10 +506,19 @@ def _validate_gradient_tile_rect(gradient: ET.Element) -> None:
)
for value in values.values():
if value != 0:
- raise ValueError(
+ message = (
"Non-zero DrawingML gradient tileRect is not representable "
"by the project SVG gradient mapping"
)
+ if palette is None or palette.strict:
+ raise ValueError(message)
+ palette._diagnose(
+ "gradient-tile-rect-normalized",
+ message,
+ "use the full object bounding box while preserving the "
+ "gradient stops and direction",
+ )
+ return
def _validate_path_gradient_focus(
diff --git a/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.py
index 7e613616..351cb75a 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/ln_to_svg.py
@@ -237,7 +237,7 @@ def resolve_stroke(
if set(join.attrib) - {"lim"}:
raise ValueError("Invalid DrawingML line join structure")
limit = join.attrib.get("lim")
- if limit != "800000":
+ if limit not in {None, "800000"}:
raise ValueError(
f"Unsupported DrawingML miter limit: {limit!r}"
)
diff --git a/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py b/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py
index f4065dbc..6bcac955 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py
@@ -63,7 +63,7 @@ def render_normalized_chart_svg(
chart_type = str(payload.get("type") or "")
if chart_type not in {
"area", "bar", "column", "doughnut", "line", "pie",
- "scatter", "bubble",
+ "scatter", "bubble", "combo",
}:
return None
@@ -92,6 +92,8 @@ def render_normalized_chart_svg(
parts = [*title_parts]
if chart_type in {"pie", "doughnut"}:
parts.extend(_render_pie(payload, styles, content, chart_type == "doughnut"))
+ elif chart_type == "combo":
+ parts.extend(_render_combo(payload, styles, content))
elif chart_type in {"scatter", "bubble"}:
parts.extend(_render_xy(payload, styles, content, chart_type))
else:
@@ -300,6 +302,134 @@ def _render_category(
return parts
+def _render_combo(
+ payload: dict[str, Any],
+ styles: list[SeriesVisualStyle],
+ content: _Rect,
+) -> list[str]:
+ """Render supported category combo plots against one shared value scale."""
+ categories = [str(value) for value in payload.get("categories") or []]
+ plots = payload.get("plots") or []
+ if not categories or not isinstance(plots, list) or not plots:
+ return []
+ all_series = [
+ series
+ for plot_payload in plots
+ if isinstance(plot_payload, dict)
+ for series in plot_payload.get("series") or []
+ if isinstance(series, dict)
+ ]
+ values = [
+ float(value)
+ for series in all_series
+ for value in series.get("values") or []
+ ]
+ if not all_series or not values:
+ return []
+
+ label_size = max(6.0, min(11.0, content.h * 0.037, content.w * 0.021))
+ axes = payload.get("axes") if isinstance(payload.get("axes"), dict) else {}
+ value_axis = axes.get("value") if isinstance(axes.get("value"), dict) else {}
+ show_value_labels = value_axis.get("visible") is not False
+ show_gridlines = value_axis.get("major_gridlines") is not False
+ left = max(12.0, content.w * 0.035)
+ if show_value_labels:
+ left = max(34.0, content.w * 0.075)
+ bottom = max(25.0, content.h * 0.105)
+ plot_rect = _Rect(
+ content.x + left,
+ content.y + 5.0,
+ max(12.0, content.w - left - 10.0),
+ max(12.0, content.h - bottom - 8.0),
+ )
+ lo, hi, ticks = _nice_scale(values, include_zero=True)
+ parts = _vertical_grid_and_ticks(
+ plot_rect,
+ ticks,
+ lo,
+ hi,
+ label_size,
+ False,
+ show_labels=show_value_labels,
+ show_gridlines=show_gridlines,
+ )
+ parts.extend(
+ _column_category_labels(
+ plot_rect,
+ categories,
+ label_size,
+ point_aligned=False,
+ )
+ )
+
+ style_offset = 0
+ for plot_payload in plots:
+ if not isinstance(plot_payload, dict):
+ continue
+ plot_type = str(plot_payload.get("type") or "")
+ plot_series = plot_payload.get("series") or []
+ if not isinstance(plot_series, list) or not plot_series:
+ continue
+ plot_styles = _complete_styles(
+ styles[style_offset:style_offset + len(plot_series)],
+ len(plot_series),
+ )
+ style_offset += len(plot_series)
+ grouping = str(plot_payload.get("grouping") or "standard")
+ segments, percent = _category_segments(
+ plot_series,
+ len(categories),
+ grouping,
+ )
+ normalized_plot = {
+ **payload,
+ **plot_payload,
+ "categories": categories,
+ "series": plot_series,
+ }
+ if plot_type == "column":
+ parts.extend(
+ _render_bars(
+ normalized_plot,
+ categories,
+ plot_series,
+ plot_styles,
+ segments,
+ plot_rect,
+ lo,
+ hi,
+ grouping,
+ horizontal=False,
+ label_size=label_size,
+ percent=percent,
+ )
+ )
+ elif plot_type in {"line", "area"}:
+ category_span = plot_rect.w / max(len(categories), 1)
+ point_plot = _Rect(
+ plot_rect.x + category_span / 2.0,
+ plot_rect.y,
+ max(1.0, plot_rect.w - category_span),
+ plot_rect.h,
+ )
+ parts.extend(
+ _render_lines_or_areas(
+ normalized_plot,
+ categories,
+ plot_series,
+ plot_styles,
+ segments,
+ point_plot,
+ lo,
+ hi,
+ plot_type,
+ label_size,
+ percent,
+ )
+ )
+ return parts
+
+
def _category_labels(payload: dict[str, Any]) -> list[str] | None:
raw_categories = payload.get("categories") or []
axes = payload.get("axes")
@@ -550,6 +680,11 @@ def _render_pie(
styles = _complete_styles(styles, len(categories))
label_size = max(6.0, min(10.0, content.h * 0.035, content.w * 0.018))
radius = max(5.0, min(content.w, content.h) * 0.34)
+ inner_radius = radius * (
+ float(payload.get("hole_size", 75)) / 100.0
+ if doughnut
+ else 0.0
+ )
cx = content.x + content.w / 2
cy = content.y + content.h / 2
if total <= 0:
@@ -559,7 +694,7 @@ def _render_pie(
]
if doughnut:
parts.append(
- f'<circle cx="{_fmt(cx)}" cy="{_fmt(cy)}" r="{_fmt(radius * 0.75)}" '
+ f'<circle cx="{_fmt(cx)}" cy="{_fmt(cy)}" r="{_fmt(inner_radius)}" '
'fill="none" stroke="#D5DAE1" stroke-width="1"/>'
)
parts.append(
@@ -577,8 +712,7 @@ def _render_pie(
stroke = style.stroke or "none"
if sweep >= math.tau - 1e-9:
if doughnut:
- inner = radius * 0.75
- path = _full_ring_path(cx, cy, radius, inner)
+ path = _full_ring_path(cx, cy, radius, inner_radius)
parts.append(
f'<path d="{path}" fill="{fill}" fill-opacity="{_fmt(style.fill_opacity)}" '
f'stroke="{stroke}" stroke-width="{_fmt(max(0.6, style.stroke_width))}" '
@@ -591,7 +725,14 @@ def _render_pie(
f'stroke="{stroke}" stroke-width="{_fmt(max(0.6, style.stroke_width))}"/>'
)
else:
- path = _sector_path(cx, cy, radius, angle, end, radius * 0.75 if doughnut else 0.0)
+ path = _sector_path(
+ cx,
+ cy,
+ radius,
+ angle,
+ end,
+ inner_radius,
+ )
parts.append(
f'<path d="{path}" fill="{fill}" fill-opacity="{_fmt(style.fill_opacity)}" '
f'stroke="{stroke}" stroke-opacity="{_fmt(style.stroke_opacity)}" '
@@ -925,6 +1066,17 @@ def _legend_entries(
chart_type = str(payload.get("type") or "")
if chart_type in {"pie", "doughnut"}:
labels = [str(value) for value in payload.get("categories") or []]
+ elif chart_type == "combo":
+ labels = [
+ str(series.get("name") or f"Series {index + 1}")
+ for index, series in enumerate(
+ series
+ for plot_payload in payload.get("plots") or []
+ if isinstance(plot_payload, dict)
+ for series in plot_payload.get("series") or []
+ if isinstance(series, dict)
+ )
+ ]
else:
labels = [str(item.get("name") or f"Series {idx + 1}") for idx, item in enumerate(payload.get("series") or [])]
completed = _complete_styles(styles, len(labels))
diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
index 23be583f..d731f9f6 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
@@ -43,6 +43,14 @@ from pptx_effects import (
unsupported_effect_metadata,
)
from hyperlink_contract import SHAPE_HYPERLINK_ATTR
+from svg_to_pptx.drawingml.paths import (
+ PathCommand,
+ normalize_path_commands,
+ parse_svg_path,
+ parse_svg_points,
+ svg_path_to_absolute,
+ transform_path_commands,
+)
from .color_resolver import ColorPalette, find_color_elem, resolve_color
from .chart_to_svg import CHART_URI, CHARTEX_URI, extract_native_chart_payload
@@ -129,6 +137,7 @@ class AssemblyContext:
# Accumulated outputs
defs: list[str] = field(default_factory=list)
media: dict[str, bytes] = field(default_factory=dict)
+ group_fills: list[FillResult | None] = field(default_factory=list)
def bind_palette(self) -> None:
"""Route tolerant color diagnostics through the current object context."""
@@ -1027,6 +1036,7 @@ def _build_geometry_xml(node: ShapeNode, sp_pr: ET.Element | None,
ctx.palette,
id_prefix="g",
id_seq=ctx.grad_seq,
+ group_fill=ctx.group_fills[-1] if ctx.group_fills else None,
)
except ValueError as exc:
if ctx.strict:
@@ -1133,15 +1143,17 @@ def _resolve_shape_style_defaults(node: ShapeNode, ctx: AssemblyContext) -> dict
defaults: dict[str, str] = {}
fill_ref = style.find("a:fillRef", NS)
- fill_color = _resolve_ref_color(fill_ref, ctx)
- if fill_color:
- defaults["fill"] = fill_color
+ if fill_ref is not None and fill_ref.attrib.get("idx", "").strip() != "0":
+ fill_color = _resolve_ref_color(fill_ref, ctx)
+ if fill_color:
+ defaults["fill"] = fill_color
ln_ref = style.find("a:lnRef", NS)
- line_color = _resolve_ref_color(ln_ref, ctx)
- if line_color:
- defaults["stroke"] = line_color
- defaults.setdefault("stroke-width", "1")
+ if ln_ref is not None and ln_ref.attrib.get("idx", "").strip() != "0":
+ line_color = _resolve_ref_color(ln_ref, ctx)
+ if line_color:
+ defaults["stroke"] = line_color
+ defaults.setdefault("stroke-width", "1")
return defaults
@@ -1206,9 +1218,40 @@ def _clip_blip_image(image_xml: str, geom: GeomResult | None,
if geom.tag == "rect" and not geom.attrs.get("rx") and not geom.attrs.get("ry"):
return image_xml
+ clip_geom = geom
+ if image_xml.startswith("<svg"):
+ flattened = None
+ if (
+ not ctx.strict
+ and geom.attrs.get("data-pptx-geometry-kind") == "custom"
+ ):
+ flattened = _flatten_vector_custom_crop(image_xml)
+ if flattened is not None:
+ image_xml = flattened
+ ctx.diagnose(
+ "vector-custom-geometry-crop-normalized",
+ "SVG-only picture combines srcRect with custom geometry; "
+ "Office renders the complete vector as the custom-shape fill",
+ "ignore srcRect and clip the complete vector to the custom geometry",
+ )
+ else:
+ try:
+ clip_geom = _project_clip_into_nested_crop(geom, image_xml)
+ except ValueError as exc:
+ if ctx.strict:
+ raise ValueError(
+ f"Cannot project picture geometry into its crop viewBox: {exc}"
+ ) from exc
+ ctx.diagnose(
+ "nested-crop-shape-clip-omitted",
+ f"Cannot project picture geometry into its crop viewBox: {exc}",
+ "source image crop retained without the additional shape clip",
+ )
+ return image_xml
+
ctx.clip_seq[0] += 1
clip_id = f"{ctx.group_id_prefix}clip{ctx.clip_seq[0]}"
- clip_shape = _geom_to_svg(geom, "")
+ clip_shape = _geom_to_svg(clip_geom, "")
ctx.defs.append(
f'<clipPath id="{clip_id}" clipPathUnits="userSpaceOnUse">'
f'{clip_shape}</clipPath>'
@@ -1216,15 +1259,121 @@ def _clip_blip_image(image_xml: str, geom: GeomResult | None,
return _inject_clip_path(image_xml, clip_id)
+def _flatten_vector_custom_crop(image_xml: str) -> str | None:
+ """Normalize an SVG-only custom-shape crop to a plain full-vector image."""
+ wrapper = ET.fromstring(image_xml)
+ if wrapper.tag != "svg" or len(wrapper) != 1 or wrapper[0].tag != "image":
+ return None
+ image = wrapper[0]
+ href = image.attrib.get("href", "")
+ href_path = href.split("#", 1)[0].split("?", 1)[0].casefold()
+ if not (
+ href_path.endswith(".svg")
+ or href_path.startswith("data:image/svg+xml")
+ ):
+ return None
+
+ attrs = {
+ key: value
+ for key, value in image.attrib.items()
+ if key not in {"x", "y", "width", "height", "preserveAspectRatio"}
+ }
+ for key in ("x", "y", "width", "height"):
+ value = wrapper.attrib.get(key)
+ if value is None:
+ return None
+ attrs[key] = value
+ attrs["preserveAspectRatio"] = "none"
+ return f"<image{_attrs_to_xml(attrs)}/>"
+
+
def _inject_clip_path(image_xml: str, clip_id: str) -> str:
clip_attr = f' clip-path="url(#{clip_id})"'
if image_xml.startswith("<image"):
return image_xml.replace("<image", f"<image{clip_attr}", 1)
if image_xml.startswith("<svg"):
- return image_xml.replace("<svg", f'<svg data-pptx-crop="1"{clip_attr}', 1)
+ marked = image_xml.replace("<svg", '<svg data-pptx-crop="1"', 1)
+ return marked.replace("<image", f"<image{clip_attr}", 1)
return image_xml
+def _project_clip_into_nested_crop(
+ geom: GeomResult,
+ image_xml: str,
+) -> GeomResult:
+ """Map absolute slide geometry into one nested crop's viewBox space."""
+ wrapper = ET.fromstring(image_xml)
+ if wrapper.tag != "svg":
+ raise ValueError("expected a nested <svg> crop wrapper")
+
+ try:
+ frame_x = float(wrapper.attrib["x"])
+ frame_y = float(wrapper.attrib["y"])
+ frame_w = float(wrapper.attrib["width"])
+ frame_h = float(wrapper.attrib["height"])
+ view_box = [float(token) for token in wrapper.attrib["viewBox"].split()]
+ except (KeyError, ValueError) as exc:
+ raise ValueError("crop wrapper has incomplete numeric geometry") from exc
+ if frame_w <= 0 or frame_h <= 0 or len(view_box) != 4:
+ raise ValueError(
+ "crop wrapper requires positive dimensions and four viewBox values"
+ )
+ vb_x, vb_y, vb_w, vb_h = view_box
+ if vb_w <= 0 or vb_h <= 0:
+ raise ValueError("crop viewBox dimensions must be positive")
+
+ scale_x = vb_w / frame_w
+ scale_y = vb_h / frame_h
+ matrix = (
+ scale_x,
+ 0.0,
+ 0.0,
+ scale_y,
+ vb_x - frame_x * scale_x,
+ vb_y - frame_y * scale_y,
+ )
+
+ if geom.tag == "path" and geom.path_d:
+ commands = normalize_path_commands(
+ svg_path_to_absolute(parse_svg_path(geom.path_d))
+ )
+ transformed = transform_path_commands(commands, matrix)
+ return GeomResult(
+ tag="path",
+ path_d=_serialize_clip_path(transformed),
+ )
+ if geom.tag in {"polygon", "polyline"} and geom.points:
+ points = parse_svg_points(
+ geom.points,
+ min_points=3 if geom.tag == "polygon" else 2,
+ )
+ transformed = [
+ (
+ x * scale_x + matrix[4],
+ y * scale_y + matrix[5],
+ )
+ for x, y in points
+ ]
+ return GeomResult(
+ tag=geom.tag,
+ points=" ".join(
+ f"{fmt_num(x, 5)},{fmt_num(y, 5)}"
+ for x, y in transformed
+ ),
+ )
+ raise ValueError(f"unsupported clip geometry <{geom.tag}>")
+
+
+def _serialize_clip_path(commands: list[PathCommand]) -> str:
+ """Serialize normalized M/L/C/Z commands with crop-safe precision."""
+ parts: list[str] = []
+ for command in commands:
+ parts.append(command.cmd)
+ if command.args:
+ parts.append(" ".join(fmt_num(value, 5) for value in command.args))
+ return " ".join(parts)
+
+
# ---------------------------------------------------------------------------
# Picture (<p:pic>)
# ---------------------------------------------------------------------------
@@ -1323,11 +1472,42 @@ def _convert_connector(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool
def _convert_group(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
"""Render group contents flat (children already remapped to slide space)."""
+ parent_fill = ctx.group_fills[-1] if ctx.group_fills else None
+ group_properties = node.xml.find("p:grpSpPr", NS)
+ try:
+ resolved_fill = resolve_fill(
+ group_properties,
+ ctx.palette,
+ id_prefix="g",
+ id_seq=ctx.grad_seq,
+ group_fill=parent_fill,
+ )
+ except ValueError as exc:
+ if ctx.strict:
+ raise
+ ctx.diagnose(
+ "group-fill-omitted",
+ str(exc),
+ "inherit the nearest resolved ancestor group fill when available",
+ )
+ group_fill = parent_fill
+ else:
+ ctx.defs.extend(resolved_fill.defs)
+ group_fill = (
+ FillResult(attrs=dict(resolved_fill.attrs))
+ if resolved_fill.attrs
+ else parent_fill
+ )
+
inner_parts: list[str] = []
- for child in node.children:
- chunk = _convert_node(child, ctx, top_level=False)
- if chunk:
- inner_parts.append(chunk)
+ ctx.group_fills.append(group_fill)
+ try:
+ for child in node.children:
+ chunk = _convert_node(child, ctx, top_level=False)
+ if chunk:
+ inner_parts.append(chunk)
+ finally:
+ ctx.group_fills.pop()
if not inner_parts:
return ""
inner = "\n".join(inner_parts)
diff --git a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py
index d3d55c0d..274c3b3d 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/txbody_to_svg.py
@@ -24,6 +24,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from typing import Callable
+from unicodedata import east_asian_width
from xml.etree import ElementTree as ET
from svg_to_pptx.drawingml.utils import detect_text_lang, is_cjk_char
@@ -92,6 +93,8 @@ class TextParagraph:
space_after_px: float = 0.0
empty_line_font_size_px: float = DEFAULT_FONT_SIZE_PX
bullet_prefix: str = "" # rendered prefix like '• ' or '1. '
+ bullet_fill: str | None = None
+ bullet_fill_opacity: float = 1.0
@dataclass
@@ -265,6 +268,7 @@ def convert_vertical_txbody(
if tx_body is None:
return TextResult()
+ body_pr = tx_body.find("a:bodyPr", NS)
paragraphs = _parse_paragraphs(
tx_body, palette, theme_fonts or {}, default_fill=default_fill,
default_font_size_px=default_font_size_px,
@@ -276,6 +280,13 @@ def convert_vertical_txbody(
strict=strict,
diagnostic_sink=diagnostic_sink,
)
+ if body_pr is not None and body_pr.attrib.get("vert") == "eaVert":
+ return _convert_east_asian_vertical(
+ paragraphs,
+ xfrm,
+ body_pr,
+ )
+
runs = [
run
for para in paragraphs
@@ -338,6 +349,183 @@ def convert_vertical_txbody(
)
+def _convert_east_asian_vertical(
+ paragraphs: list[TextParagraph],
+ xfrm: Xfrm,
+ body_pr: ET.Element,
+) -> TextResult:
+ """Render eaVert columns with upright CJK and sideways Latin runs."""
+ columns: list[list[tuple[bool, str, TextRun]]] = []
+ for paragraph in paragraphs:
+ column: list[tuple[bool, str, TextRun]] = []
+ for run in paragraph.runs:
+ if run.is_break:
+ if column:
+ columns.append(column)
+ column = []
+ continue
+ start = 0
+ while start < len(run.text):
+ upright = _is_east_asian_vertical_upright(run.text[start])
+ end = start + 1
+ while (
+ end < len(run.text)
+ and _is_east_asian_vertical_upright(run.text[end]) == upright
+ ):
+ end += 1
+ column.append((upright, run.text[start:end], run))
+ start = end
+ if column:
+ columns.append(column)
+
+ if not columns:
+ return TextResult()
+
+ box_x, box_y, box_w, box_h = _rotated_bbox(xfrm)
+ lins = _read_emu_attr(body_pr, "lIns", DEFAULT_INSETS_EMU["l"])
+ tins = _read_emu_attr(body_pr, "tIns", DEFAULT_INSETS_EMU["t"])
+ rins = _read_emu_attr(body_pr, "rIns", DEFAULT_INSETS_EMU["r"])
+ bins = _read_emu_attr(body_pr, "bIns", DEFAULT_INSETS_EMU["b"])
+ inner_x = box_x + lins
+ inner_y = box_y + tins
+ inner_w = max(box_w - lins - rins, 1.0)
+ inner_h = max(box_h - tins - bins, 1.0)
+
+ column_widths = [
+ max(run.font_size_px * 1.05 for _upright, _text, run in column)
+ for column in columns
+ ]
+ total_width = sum(column_widths)
+ right_x = inner_x + min(inner_w, (inner_w + total_width) / 2.0)
+ column_centers: list[float] = []
+ for width in column_widths:
+ column_centers.append(right_x - width / 2.0)
+ right_x -= width
+
+ anchor = body_pr.attrib.get("anchor", "t")
+ bottom_y = inner_y + inner_h
+ text_blocks: list[str] = []
+ for column, center_x in zip(columns, column_centers):
+ content_height = sum(
+ _east_asian_vertical_segment_height(upright, text, run)
+ for upright, text, run in column
+ )
+ if anchor == "ctr":
+ cursor_y = inner_y + max(0.0, (inner_h - content_height) / 2.0)
+ elif anchor == "b":
+ cursor_y = inner_y + max(0.0, inner_h - content_height)
+ else:
+ cursor_y = inner_y
+
+ for upright, text, run in column:
+ available = bottom_y - cursor_y
+ if available <= 0:
+ break
+ if upright:
+ advance = run.font_size_px * 1.05
+ visible_count = min(len(text), int(available // advance))
+ visible = text[:visible_count]
+ if not visible:
+ break
+ text_blocks.append(
+ _emit_upright_vertical_segment(
+ visible,
+ run,
+ center_x,
+ cursor_y,
+ advance,
+ )
+ )
+ cursor_y += advance * visible_count
+ if visible_count < len(text):
+ break
+ continue
+
+ visible = _fit_sideways_vertical_text(text, run, available)
+ if not visible:
+ break
+ text_blocks.append(
+ _emit_sideways_vertical_segment(
+ visible,
+ run,
+ center_x,
+ cursor_y,
+ )
+ )
+ cursor_y += _estimate_run_width(visible, run)
+ if len(visible) < len(text):
+ break
+
+ return TextResult(
+ svg="\n".join(text_blocks),
+ defs=_collect_text_defs(paragraphs),
+ contains_inline_formula=False,
+ )
+
+
+def _is_east_asian_vertical_upright(char: str) -> bool:
+ """Keep East Asian wide/full-width glyphs upright in eaVert text."""
+ return _is_cjk(char) or east_asian_width(char) in {"W", "F"}
+
+
+def _east_asian_vertical_segment_height(
+ upright: bool,
+ text: str,
+ run: TextRun,
+) -> float:
+ if upright:
+ return len(text) * run.font_size_px * 1.05
+ return _estimate_run_width(text, run)
+
+
+def _fit_sideways_vertical_text(
+ text: str,
+ run: TextRun,
+ available: float,
+) -> str:
+ end = 0
+ for index in range(1, len(text) + 1):
+ if _estimate_run_width(text[:index], run) > available:
+ break
+ end = index
+ return text[:end]
+
+
+def _emit_upright_vertical_segment(
+ text: str,
+ run: TextRun,
+ center_x: float,
+ top_y: float,
+ advance: float,
+) -> str:
+ first_baseline = top_y + run.font_size_px * 0.85
+ attrs = _text_base_attrs(run, center_x, first_baseline, "middle")
+ spans = [_xml_escape(text[0])]
+ for char in text[1:]:
+ spans.append(
+ f'<tspan x="{fmt_num(center_x)}" dy="{fmt_num(advance)}">'
+ f"{_xml_escape(char)}</tspan>"
+ )
+ markup = f"<text{attrs}>{''.join(spans)}</text>"
+ return _wrap_run_hyperlink(markup, run)
+
+
+def _emit_sideways_vertical_segment(
+ text: str,
+ run: TextRun,
+ center_x: float,
+ top_y: float,
+) -> str:
+ baseline_x = center_x - run.font_size_px * 0.3
+ start_y = top_y + run.font_size_px * 0.1
+ attrs = _text_base_attrs(run, baseline_x, start_y, "start")
+ transform = (
+ f' transform="rotate(90 {fmt_num(baseline_x)} {fmt_num(start_y)})"'
+ )
+ markup = f"<text{attrs}{transform}>{_xml_escape(text)}</text>"
+ return _wrap_run_hyperlink(markup, run)
+
+
def _rotated_bbox(xfrm: Xfrm) -> tuple[float, float, float, float]:
rot = round(xfrm.rot) % 360
cx = xfrm.x + xfrm.w / 2.0
@@ -482,6 +670,9 @@ def _parse_paragraph(
para.bullet_prefix = _resolve_bullet_prefix(
para_style_chain, para.level, autonum_state,
)
+ para.bullet_fill, para.bullet_fill_opacity = _resolve_bullet_fill(
+ para_style_chain, palette,
+ )
# Default endParaRPr style (applies if a run has no rPr)
end_rpr = p_elem.find("a:endParaRPr", NS)
@@ -940,6 +1131,10 @@ def _resolve_bullet_prefix(
bu_char = _child_chain(sources, "a:buChar")
if bu_char is not None:
ch = bu_char.attrib.get("char", "•")
+ bu_font = _child_chain(sources, "a:buFont")
+ typeface = bu_font.attrib.get("typeface", "") if bu_font is not None else ""
+ if typeface.casefold() == "wingdings" and ch == "l":
+ ch = "●"
return f"{ch} "
bu_auto = _child_chain(sources, "a:buAutoNum")
if bu_auto is not None:
@@ -958,6 +1153,19 @@ def _resolve_bullet_prefix(
return ""
+def _resolve_bullet_fill(
+ sources: tuple[ET.Element | None, ...],
+ palette: ColorPalette | None,
+) -> tuple[str | None, float]:
+ """Resolve an explicit DrawingML bullet color independently of text."""
+ bu_clr = _child_chain(sources, "a:buClr")
+ if bu_clr is None:
+ return None, 1.0
+ color_elem = find_color_elem(bu_clr)
+ color, opacity = resolve_color(color_elem, palette)
+ return color, opacity
+
+
def _format_auto_number(value: int, kind: str) -> str:
lower = kind.lower()
if "alphalc" in lower:
@@ -1132,8 +1340,19 @@ def _wrap_paragraph_into_lines(
first_run = next((r for r in para.runs if not r.is_break), None)
if first_run is not None:
bullet_run = _copy_run(first_run, text=para.bullet_prefix)
+ if para.bullet_fill is not None:
+ bullet_run.fill = para.bullet_fill
+ bullet_run.fill_opacity = para.bullet_fill_opacity
+ hanging_width = max(-para.indent_px, 0.0)
+ measured_width = _estimate_run_width(para.bullet_prefix, bullet_run)
+ if hanging_width > measured_width:
+ space_width = _estimate_run_width(" ", bullet_run)
+ extra_spaces = round(
+ (hanging_width - measured_width) / space_width
+ )
+ bullet_run.text += " " * max(extra_spaces, 0)
lines[-1].append(bullet_run)
- cur_w = _estimate_run_width(para.bullet_prefix, bullet_run)
+ cur_w = _estimate_run_width(bullet_run.text, bullet_run)
for run in para.runs:
if run.is_break:
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index ffce4221..6e8021d7 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -165,6 +165,7 @@ def _normalize_preview_hrefs(root: ET.Element) -> None:
def _inline_icons(
content: str,
icons_dir: Path,
+ target_dir: Path,
fallback_dir: Optional[Path] = None,
) -> tuple[str, list[dict]]:
"""Replace <use data-icon="..."/> with rendered <g> for browser preview.
@@ -190,7 +191,11 @@ def _inline_icons(
continue
icon_path, _ = resolve_icon_path(icon_name, icons_dir, fallback_dir)
color = str(attrs.get('fill', '#000000'))
- elements, style, base_size = extract_paths_from_icon(icon_path, color)
+ elements, style, base_size = extract_paths_from_icon(
+ icon_path,
+ color,
+ target_dir=target_dir,
+ )
except Exception as exc:
warnings.append({'icon': icon_name, 'reason': f'{type(exc).__name__}: {exc}'})
logger.warning('icon inline failed: name=%r reason=%s', icon_name, exc)
@@ -713,6 +718,7 @@ def create_app(
content, warnings = _inline_icons(
content,
icons_dir,
+ svg_file.parent,
icons_fallback_dir,
)
if not pending_edits:
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_icons.py b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
index 0b4638dd..3c216d29 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_icons.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_icons.py
@@ -49,6 +49,7 @@ import re
import sys
import argparse
from pathlib import Path
+from urllib.parse import urlsplit, urlunsplit
from xml.etree import ElementTree as ET
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
@@ -258,7 +259,41 @@ def resolve_icon_path(icon_name: str, icons_dir: Path, fallback_dir: Path | None
return icon_path, base_size
-def extract_paths_from_icon(icon_path: Path, target_color: str = '#000000') -> tuple[list[str], str, BaseGeometry]:
+def _rebase_preserve_asset_hrefs(
+ content: str,
+ source_dir: Path,
+ target_dir: Path,
+) -> str:
+ """Rebase relative hrefs when a preserve-color asset is inlined."""
+ pattern = re.compile(
+ r'(\b(?:xlink:)?href\s*=\s*)(["\'])(.*?)\2',
+ re.IGNORECASE | re.DOTALL,
+ )
+
+ def replace(match: re.Match[str]) -> str:
+ value = match.group(3)
+ if value.startswith(("#", "/")):
+ return match.group(0)
+ parsed = urlsplit(value)
+ if parsed.scheme or parsed.netloc or not parsed.path:
+ return match.group(0)
+ source_target = (source_dir / parsed.path).resolve()
+ try:
+ relative = Path(os.path.relpath(source_target, target_dir)).as_posix()
+ except ValueError:
+ return match.group(0)
+ rewritten = urlunsplit(("", "", relative, parsed.query, parsed.fragment))
+ return f'{match.group(1)}{match.group(2)}{rewritten}{match.group(2)}'
+
+ return pattern.sub(replace, content)
+
+
+def extract_paths_from_icon(
+ icon_path: Path,
+ target_color: str = '#000000',
+ *,
+ target_dir: Path | None = None,
+) -> tuple[list[str], str, BaseGeometry]:
"""
Extract drawable elements from an icon SVG file.
@@ -274,6 +309,15 @@ def extract_paths_from_icon(icon_path: Path, target_color: str = '#000000') -> t
if _is_preserve_color_asset(content):
geometry = _get_viewbox_geometry(content) or (0.0, 0.0, DEFAULT_ICON_BASE_SIZE, DEFAULT_ICON_BASE_SIZE)
elements = _extract_svg_body(content)
+ if target_dir is not None:
+ elements = [
+ _rebase_preserve_asset_hrefs(
+ element,
+ icon_path.parent,
+ target_dir,
+ )
+ for element in elements
+ ]
return elements, 'preserve', geometry
style = _detect_icon_style(content)
@@ -483,7 +527,10 @@ def process_svg_file(svg_path: Path, icons_dir: Path, dry_run: bool = False, ver
)
continue
- elements, style, base_size = extract_paths_from_icon(icon_path)
+ elements, style, base_size = extract_paths_from_icon(
+ icon_path,
+ target_dir=svg_path.parent,
+ )
color = resolve_icon_color(attrs, style)
if not elements:
print(