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): improve imported table and chart fidelity
hugohe3b4999305eac7
diff --git a/skills/ppt-master/scripts/pptx_shapes/__init__.py b/skills/ppt-master/scripts/pptx_shapes/__init__.pyindex ce41ad40..5e724838 100644--- a/skills/ppt-master/scripts/pptx_shapes/__init__.py+++ b/skills/ppt-master/scripts/pptx_shapes/__init__.py@@ -56,7 +56,10 @@ from .registry import (get_preset_registry,)from .semantic_hash import (+ NATIVE_FALLBACK_SHA256_ATTR,resolve_preset_preview_hash,+ svg_native_fallback_fingerprint,+ svg_native_fallback_markup_fingerprint,svg_preset_preview_fingerprint,svg_text_fingerprint,)@@ -76,6 +79,7 @@ __all__ = ["OOXML_COORDINATE_MIN","OOXML_DEGREE","OOXML_LINE_WIDTH_MAX",+ "NATIVE_FALLBACK_SHA256_ATTR","SUPPORTED_OPERATORS","EvaluatedPresetGeometry","FormulaEvaluationError",@@ -95,6 +99,8 @@ __all__ = ["load_preset_shape_definitions","load_shape_type_values","resolve_preset_preview_hash",+ "svg_native_fallback_fingerprint",+ "svg_native_fallback_markup_fingerprint","svg_text_fingerprint","svg_preset_preview_fingerprint","validate_ooxml_line_width",diff --git a/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py b/skills/ppt-master/scripts/pptx_shapes/semantic_hash.pyindex 09eb8635..88cea092 100644--- a/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py+++ b/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py@@ -2,10 +2,11 @@"""PPT Master - Native Shape Semantic Fingerprints-Build stable hashes for visible SVG text and generated preset preview layers.+Build stable hashes for visible SVG text, generated preset previews, and+native chart/table fallback subtrees.Usage:- Import svg_text_fingerprint or svg_preset_preview_fingerprint.+ Import the fingerprint helper for the relevant semantic carrier.Examples:digest = svg_text_fingerprint(group_element)@@ -18,6 +19,7 @@ from __future__ import annotationsimport hashlibimport json+import refrom xml.etree import ElementTree as ET@@ -37,6 +39,18 @@ _ROOT_TEXT_STYLE_ATTRS = frozenset({"word-spacing",})+NATIVE_FALLBACK_SHA256_ATTR = "data-pptx-fallback-sha256"+_NATIVE_FALLBACK_IGNORED_TAGS = frozenset({"metadata", "title", "desc"})+_NATIVE_FALLBACK_IGNORED_ATTRS = frozenset({+ "id",+ "data-name",+ "data-ph-type",+})+_URL_ID_RE = re.compile(+ r"url\(\s*(?P<quote>['\"]?)#(?P<id>[^)'\"\s]+)(?P=quote)\s*\)",+ re.IGNORECASE,+)+def svg_text_fingerprint(root: ET.Element) -> str:"""Hash text content, structure, positioning, and visible typography.@@ -79,6 +93,84 @@ def svg_preset_preview_fingerprint(root: ET.Element) -> str:return hashlib.sha256(canonical).hexdigest()+def svg_native_fallback_fingerprint(+ root: ET.Element,+ *,+ document_root: ET.Element | None = None,+) -> str:+ """Hash one native chart/table marker's rendering-relevant SVG subtree.++ Native metadata, editor/runtime attributes, and stable element IDs are not+ fallback artwork. Reachable document-level fragment definitions are hashed+ when ``document_root`` is available. Transforms remain part of the digest+ because complete explicit native bounds are absolute and therefore do not+ consume marker transforms; changing one must make the replacement stale.+ """+ id_tokens = _native_fallback_id_tokens(root)+ dependencies = _native_fallback_external_dependencies(+ root,+ document_root,+ id_tokens,+ )+ payload = _native_fallback_subtree(+ root,+ id_tokens=id_tokens,+ )+ if dependencies:+ payload = {+ "marker": payload,+ "external_dependencies": [+ {+ "token": id_tokens[element_id],+ "node": _native_fallback_subtree(+ target,+ id_tokens=id_tokens,+ force_include=True,+ ),+ }+ for element_id, target in dependencies+ ],+ }+ canonical = json.dumps(+ payload,+ ensure_ascii=False,+ sort_keys=True,+ separators=(",", ":"),+ ).encode("utf-8")+ return hashlib.sha256(canonical).hexdigest()+++def svg_native_fallback_markup_fingerprint(+ markup: str,+ *,+ root_transform: str | None = None,+ external_markup: str | None = None,+) -> str:+ """Hash an SVG fallback fragment through the canonical marker function."""+ if external_markup:+ document_root = ET.fromstring(+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:xlink="http://www.w3.org/1999/xlink">'+ f"<defs>{external_markup}</defs><g>{markup}</g>"+ "</svg>"+ )+ wrapper = document_root[-1]+ else:+ document_root = None+ wrapper = ET.fromstring(+ '<g xmlns="http://www.w3.org/2000/svg" '+ 'xmlns:xlink="http://www.w3.org/1999/xlink">'+ f"{markup}"+ "</g>"+ )+ if root_transform:+ wrapper.set("transform", root_transform)+ return svg_native_fallback_fingerprint(+ wrapper,+ document_root=document_root,+ )++def resolve_preset_preview_hash(root: ET.Element) -> str | None:"""Resolve and cross-check a logical preset group's fingerprint contract.@@ -152,6 +244,194 @@ def _preview_subtree(}+def _native_fallback_subtree(+ element: ET.Element,+ *,+ id_tokens: dict[str, str],+ force_include: bool = False,+) -> dict | None:+ tag = _local_name(element.tag)+ if not force_include and _native_fallback_element_hidden(element):+ return None++ attrs = []+ for raw_name, raw_value in element.attrib.items():+ name = _local_name(raw_name)+ if name in _NATIVE_FALLBACK_IGNORED_ATTRS:+ continue+ if name.startswith("data-pptx-"):+ continue+ attrs.append((+ raw_name,+ _normalize_native_fallback_id_refs(name, raw_value, id_tokens),+ ))++ children = []+ for child in element:+ child_payload = _native_fallback_subtree(+ child,+ id_tokens=id_tokens,+ )+ if child_payload is None:+ continue+ entry = {"node": child_payload}+ if child.tail and (+ child.tail.strip() or tag in {"text", "tspan", "textPath"}+ ):+ entry["tail"] = child.tail+ children.append(entry)++ text = element.text or ""+ payload = {+ "tag": tag,+ "attrs": sorted(attrs),+ "children": children,+ }+ if text and (text.strip() or tag in {"text", "tspan", "textPath", "style"}):+ payload["text"] = text+ return payload+++def _native_fallback_id_tokens(+ root: ET.Element,+) -> dict[str, str]:+ tokens: dict[str, str] = {}++ def visit(+ element: ET.Element,+ *,+ is_root: bool,+ path: tuple[int, ...],+ ) -> None:+ element_id = None if is_root else element.get("id")+ if element_id and element_id not in tokens:+ tokens[element_id] = "native-node-" + "-".join(map(str, path))+ canonical_index = 0+ for child in element:+ if _native_fallback_element_hidden(child):+ continue+ visit(+ child,+ is_root=False,+ path=(*path, canonical_index),+ )+ canonical_index += 1++ visit(root, is_root=True, path=())+ return tokens+++def _native_fallback_external_dependencies(+ marker: ET.Element,+ document_root: ET.Element | None,+ id_tokens: dict[str, str],+) -> list[tuple[str, ET.Element]]:+ """Resolve the marker's reachable document-level fragment references."""+ if document_root is None or document_root is marker:+ return []++ marker_nodes = set(marker.iter())+ targets: dict[str, ET.Element] = {}+ for element in document_root.iter():+ element_id = element.get("id")+ if element_id and element_id not in targets:+ targets[element_id] = element++ dependencies: list[tuple[str, ET.Element]] = []++ def add_reference(element_id: str) -> None:+ if not element_id or element_id in id_tokens:+ return+ target = targets.get(element_id)+ if target is None or target in marker_nodes:+ return+ id_tokens[element_id] = f"native-external-{len(dependencies) + 1}"+ dependencies.append((element_id, target))+ for nested_id in _native_fallback_fragment_references(+ target,+ force_include_root=True,+ ):+ add_reference(nested_id)++ for element_id in _native_fallback_fragment_references(marker):+ add_reference(element_id)+ return dependencies+++def _native_fallback_fragment_references(+ root: ET.Element,+ *,+ force_include_root: bool = False,+) -> list[str]:+ references: list[str] = []+ seen: set[str] = set()++ def add(element_id: str) -> None:+ if element_id and element_id not in seen:+ seen.add(element_id)+ references.append(element_id)++ def visit(element: ET.Element, *, force_include: bool) -> None:+ if not force_include and _native_fallback_element_hidden(element):+ return+ for raw_name, raw_value in sorted(element.attrib.items()):+ name = _local_name(raw_name)+ if name in _NATIVE_FALLBACK_IGNORED_ATTRS:+ continue+ if name.startswith("data-pptx-"):+ continue+ for match in _URL_ID_RE.finditer(raw_value):+ add(match.group("id"))+ if name == "href" and raw_value.startswith("#"):+ add(raw_value[1:])+ for child in element:+ visit(child, force_include=False)++ visit(root, force_include=force_include_root)+ return references+++def _native_fallback_element_hidden(element: ET.Element) -> bool:+ if _local_name(element.tag) in _NATIVE_FALLBACK_IGNORED_TAGS:+ return True+ # ``display:none`` suppresses the entire descendant subtree. SVG+ # ``visibility`` is different: a descendant may explicitly restore+ # ``visibility:visible``. Keep visibility-hidden content in the digest+ # conservatively so such visible descendants cannot evade stale detection.+ return _native_fallback_style_value(element, "display") == "none"+++def _normalize_native_fallback_id_refs(+ name: str,+ value: str,+ id_tokens: dict[str, str],+) -> str:+ def replace_url(match: re.Match[str]) -> str:+ token = id_tokens.get(match.group("id"))+ return f"url(#{token})" if token is not None else match.group(0)++ normalized = _URL_ID_RE.sub(replace_url, value)+ if name in {"href", "xlink:href"} and normalized.startswith("#"):+ token = id_tokens.get(normalized[1:])+ if token is not None:+ return f"#{token}"+ return normalized+++def _native_fallback_style_value(element: ET.Element, name: str) -> str | None:+ raw = element.get(name)+ if raw is not None:+ return raw.strip().lower()+ style = element.get("style") or ""+ for declaration in style.split(";"):+ if ":" not in declaration:+ continue+ key, value = declaration.split(":", 1)+ if key.strip().lower() == name:+ return value.strip().lower()+ return None++def _element_payload(element: ET.Element) -> dict:return {"tag": _local_name(element.tag),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.pyindex 5f75add3..719e23b6 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,7 +19,9 @@ from svg_to_pptx.native_objects.chart_data import (validate_data_label_position,)+from .color_resolver import ColorPalette, find_color_elem, resolve_colorfrom .emu_units import NS, Xfrm, ooxml_bool+from .normalized_chart_svg import SeriesVisualStyle, render_normalized_chart_svgfrom .ooxml_loader import OoxmlPackage, PartRef@@ -39,6 +41,7 @@ class ChartResult:native_payload: dict[str, Any] | None = Nonenative_status: str | None = None+ normalized_svg: str | None = Noneclass _UnsupportedChart(RuntimeError):@@ -54,6 +57,7 @@ def extract_native_chart_payload(xfrm: Xfrm,slide_part: PartRef,pkg: OoxmlPackage,+ palette: ColorPalette | None = None,) -> ChartResult:"""Return native chart metadata for a supported classic chart."""if graphic_data is None:@@ -82,7 +86,11 @@ def extract_native_chart_payload(return ChartResult(native_status="unsupported-chart-part")try:- payload = _payload_from_chart_xml(chart_part.xml, xfrm)+ payload, visual_styles = _payload_from_chart_xml(+ chart_part.xml,+ xfrm,+ palette=palette,+ )validate_chart_payload(payload)except _UnsupportedChart as exc:return ChartResult(native_status=exc.status)@@ -90,10 +98,22 @@ def extract_native_chart_payload(return ChartResult(native_status="unsupported-chart-schema")except (TypeError, ValueError, AttributeError):return ChartResult(native_status="unsupported-chart-parse")- return ChartResult(native_payload=payload)+ # The visual fallback is deliberately best-effort and isolated from the+ # active native payload. A renderer defect must never downgrade a chart+ # that the native schema has already validated.+ try:+ normalized_svg = render_normalized_chart_svg(payload, visual_styles)+ except (KeyError, TypeError, ValueError, OverflowError, ArithmeticError):+ normalized_svg = None+ return ChartResult(native_payload=payload, normalized_svg=normalized_svg)-def _payload_from_chart_xml(chart_root: ET.Element, xfrm: Xfrm) -> dict[str, Any]:+def _payload_from_chart_xml(+ chart_root: ET.Element,+ xfrm: Xfrm,+ *,+ palette: ColorPalette | None = None,+) -> tuple[dict[str, Any], list[SeriesVisualStyle]]:plot_area = chart_root.find(".//c:plotArea", C_NS)if plot_area is None:raise _UnsupportedChart("unsupported-chart-plot")@@ -132,9 +152,14 @@ def _payload_from_chart_xml(chart_root: ET.Element, xfrm: Xfrm) -> dict[str, Anyelse:raise _UnsupportedChart("unsupported-chart-type")- _validate_chart_semantics(payload, plot_area, chart)+ visual_styles = _validate_chart_semantics(+ payload,+ plot_area,+ chart,+ palette=palette,+ )_apply_chart_metadata(payload, chart_root, plot_area, chart)- return payload+ return payload, visual_stylesdef _canonical_srgb_color(fill: ET.Element | None) -> str:@@ -155,98 +180,375 @@ def _canonical_srgb_color(fill: ET.Element | None) -> str:return color.upper()-def _canonical_sp_pr_color(sp_pr: ET.Element, *, line_visible: bool) -> str:- """Extract a color only from the exact series style emitted here."""- if sp_pr.attrib:+@dataclass(frozen=True)+class _LinePaint:+ color: str | None+ opacity: float+ width: float+ cap: str+ visible: bool+ automatic: bool+++@dataclass(frozen=True)+class _ShapePaint:+ fill: str | None+ fill_opacity: float+ fill_explicit: bool+ line: _LinePaint | None+++@dataclass(frozen=True)+class _MarkerPaint:+ symbol: str | None+ size: float+ shape: _ShapePaint+++_FALLBACK_CHART_COLORS = (+ "#4472C4", "#ED7D31", "#A5A5A5", "#FFC000",+ "#5B9BD5", "#70AD47", "#264478", "#9E480E",+)+_COLOR_MODIFIERS_WITH_VALUE = {+ "alpha", "alphaMod", "alphaOff", "hueMod", "hueOff", "lumMod",+ "lumOff", "satMod", "satOff", "shade", "tint",+}+_COLOR_MODIFIERS_WITHOUT_VALUE = {"comp", "gray", "inv"}+++def _resolved_solid_fill(+ fill: ET.Element,+ palette: ColorPalette | None,+) -> tuple[str, float]:+ if fill.attrib or len(fill) != 1:raise _UnsupportedChart("unsupported-chart-series-style")- children = list(sp_pr)- if [_local_name(child.tag) for child in children] != ["solidFill", "ln"]:+ color = find_color_elem(fill)+ if color is None or color is not fill[0]:raise _UnsupportedChart("unsupported-chart-series-style")- color = _canonical_srgb_color(children[0])- line = children[1]- if line.attrib or len(line) != 1:+ tag = _local_name(color.tag)+ allowed_attrs = {+ "srgbClr": {"val"},+ "schemeClr": {"val"},+ "sysClr": {"val", "lastClr"},+ "prstClr": {"val"},+ "hslClr": {"hue", "sat", "lum"},+ "scrgbClr": {"r", "g", "b"},+ }.get(tag)+ if allowed_attrs is None or not set(color.attrib).issubset(allowed_attrs):raise _UnsupportedChart("unsupported-chart-series-style")- line_child = line[0]- if line_visible:- if _local_name(line_child.tag) != "solidFill":- raise _UnsupportedChart("unsupported-chart-series-style")- if _canonical_srgb_color(line_child) != color:+ required = {+ "srgbClr": {"val"}, "schemeClr": {"val"}, "prstClr": {"val"},+ "hslClr": {"hue", "sat", "lum"}, "scrgbClr": {"r", "g", "b"},+ }.get(tag, set())+ if not required.issubset(color.attrib):+ raise _UnsupportedChart("unsupported-chart-series-style")+ for modifier in color:+ modifier_name = _local_name(modifier.tag)+ if modifier_name in _COLOR_MODIFIERS_WITH_VALUE:+ if set(modifier.attrib) != {"val"} or list(modifier):+ raise _UnsupportedChart("unsupported-chart-series-style")+ try:+ modifier_value = float(modifier.attrib["val"])+ except (TypeError, ValueError, OverflowError):+ raise _UnsupportedChart("unsupported-chart-series-style") from None+ if not math.isfinite(modifier_value):+ raise _UnsupportedChart("unsupported-chart-series-style")+ elif modifier_name in _COLOR_MODIFIERS_WITHOUT_VALUE:+ if modifier.attrib or list(modifier):+ raise _UnsupportedChart("unsupported-chart-series-style")+ else:raise _UnsupportedChart("unsupported-chart-series-style")- elif (- _local_name(line_child.tag) != "noFill"- or line_child.attrib- or list(line_child)- ):+ try:+ resolved, alpha = resolve_color(color, palette)+ except (TypeError, ValueError, OverflowError):+ raise _UnsupportedChart("unsupported-chart-series-style") from None+ if resolved is None or not math.isfinite(alpha):raise _UnsupportedChart("unsupported-chart-series-style")- return color+ return resolved.upper(), max(0.0, min(1.0, alpha))-def _canonical_chart_colors(payload: dict[str, Any], plot: ET.Element) -> list[str] | None:- """Recover colors from canonical series or pie data-point formatting."""- chart_type = payload["type"]- series_nodes = plot.findall("c:ser", C_NS)- if chart_type in {"pie", "doughnut", "of_pie"}:- if any(series.find("c:spPr", C_NS) is not None for series in series_nodes):+def _resolved_line(+ line: ET.Element,+ palette: ColorPalette | None,+) -> _LinePaint:+ if not set(line.attrib).issubset({"w", "cap"}):+ raise _UnsupportedChart("unsupported-chart-series-style")+ raw_width = line.attrib.get("w")+ if raw_width is None:+ width = 1.5+ else:+ if re.fullmatch(r"[0-9]+", raw_width) is None:raise _UnsupportedChart("unsupported-chart-series-style")- point_nodes = [- point- for series in series_nodes- for point in series.findall("c:dPt", C_NS)- ]- if not point_nodes:- return None- expected_count = len(payload["categories"]) + (1 if chart_type == "of_pie" else 0)- colors: dict[int, str] = {}- for point in point_nodes:- if point.attrib or [_local_name(child.tag) for child in point] != ["idx", "spPr"]:+ width = int(raw_width) / 9525.0+ if not 0 <= width <= 1000:+ raise _UnsupportedChart("unsupported-chart-series-style")+ cap_aliases = {None: "round", "rnd": "round", "sq": "square", "flat": "butt"}+ cap = cap_aliases.get(line.attrib.get("cap"))+ if cap is None:+ raise _UnsupportedChart("unsupported-chart-series-style")++ fill_nodes: list[ET.Element] = []+ for child in line:+ name = _local_name(child.tag)+ if name in {"solidFill", "noFill"}:+ fill_nodes.append(child)+ elif name == "prstDash":+ if child.attrib != {"val": "solid"} or list(child):raise _UnsupportedChart("unsupported-chart-series-style")- idx = point.find("c:idx", C_NS)- sp_pr = point.find("c:spPr", C_NS)- try:- point_index = int(idx.attrib.get("val", "")) if idx is not None else -1- except ValueError:- raise _UnsupportedChart("unsupported-chart-series-style") from None- if (- idx is None- or set(idx.attrib) != {"val"}- or list(idx)- or sp_pr is None- or point_index in colors- ):+ elif name in {"round", "bevel"}:+ if child.attrib or list(child):+ raise _UnsupportedChart("unsupported-chart-series-style")+ elif name == "miter":+ if not set(child.attrib).issubset({"lim"}) or list(child):+ raise _UnsupportedChart("unsupported-chart-series-style")+ raw_limit = child.attrib.get("lim")+ if raw_limit is not None and re.fullmatch(r"[0-9]+", raw_limit) is None:raise _UnsupportedChart("unsupported-chart-series-style")- colors[point_index] = _canonical_sp_pr_color(sp_pr, line_visible=True)- if set(colors) != set(range(expected_count)):+ else:+ raise _UnsupportedChart("unsupported-chart-series-style")+ if len(fill_nodes) > 1:+ raise _UnsupportedChart("unsupported-chart-series-style")+ if not fill_nodes:+ return _LinePaint(None, 1.0, width, cap, True, True)+ fill = fill_nodes[0]+ if _local_name(fill.tag) == "noFill":+ if fill.attrib or list(fill):raise _UnsupportedChart("unsupported-chart-series-style")- return [f"#{colors[index]}" for index in range(expected_count)]+ return _LinePaint(None, 1.0, width, cap, False, False)+ color, opacity = _resolved_solid_fill(fill, palette)+ return _LinePaint(color, opacity, width, cap, True, False)- if any(series.find("c:dPt", C_NS) is not None for series in series_nodes):++def _resolved_shape_paint(+ sp_pr: ET.Element | None,+ palette: ColorPalette | None,+) -> _ShapePaint:+ if sp_pr is None:+ return _ShapePaint(None, 1.0, False, None)+ if sp_pr.attrib:raise _UnsupportedChart("unsupported-chart-series-style")- sp_pr_nodes = [series.find("c:spPr", C_NS) for series in series_nodes]- if not any(sp_pr is not None for sp_pr in sp_pr_nodes):- return None- if any(sp_pr is None for sp_pr in sp_pr_nodes):+ fill_nodes: list[ET.Element] = []+ line_nodes: list[ET.Element] = []+ for child in sp_pr:+ name = _local_name(child.tag)+ if name in {"solidFill", "noFill"}:+ fill_nodes.append(child)+ elif name == "ln":+ line_nodes.append(child)+ elif name == "effectLst":+ if child.attrib or list(child):+ raise _UnsupportedChart("unsupported-chart-series-style")+ else:+ raise _UnsupportedChart("unsupported-chart-series-style")+ if len(fill_nodes) > 1 or len(line_nodes) > 1:raise _UnsupportedChart("unsupported-chart-series-style")- line_visible = not (- chart_type == "scatter"- and payload.get("scatter_style", "marker") == "marker"+ fill_color: str | None = None+ fill_opacity = 1.0+ fill_explicit = bool(fill_nodes)+ if fill_nodes:+ fill = fill_nodes[0]+ if _local_name(fill.tag) == "noFill":+ if fill.attrib or list(fill):+ raise _UnsupportedChart("unsupported-chart-series-style")+ else:+ fill_color, fill_opacity = _resolved_solid_fill(fill, palette)+ line = _resolved_line(line_nodes[0], palette) if line_nodes else None+ return _ShapePaint(fill_color, fill_opacity, fill_explicit, line)+++def _resolved_marker(+ marker: ET.Element | None,+ palette: ColorPalette | None,+) -> _MarkerPaint:+ if marker is None:+ return _MarkerPaint(None, 5.0, _resolved_shape_paint(None, palette))+ if marker.attrib:+ raise _UnsupportedChart("unsupported-chart-series-style")+ allowed = {"symbol", "size", "spPr"}+ names = [_local_name(child.tag) for child in marker]+ if any(name not in allowed for name in names) or len(names) != len(set(names)):+ raise _UnsupportedChart("unsupported-chart-series-style")+ symbol_node = marker.find("c:symbol", C_NS)+ symbol = _element_val(symbol_node)+ if symbol_node is not None and (+ set(symbol_node.attrib) != {"val"} or list(symbol_node)+ ):+ raise _UnsupportedChart("unsupported-chart-series-style")+ if symbol not in {None, "circle", "none"}:+ raise _UnsupportedChart("unsupported-chart-series-style")+ size_node = marker.find("c:size", C_NS)+ size = 5.0+ if size_node is not None:+ raw_size = size_node.attrib.get("val", "")+ if set(size_node.attrib) != {"val"} or list(size_node) or re.fullmatch(r"[0-9]+", raw_size) is None:+ raise _UnsupportedChart("unsupported-chart-series-style")+ size = float(raw_size)+ if not 2 <= size <= 72:+ raise _UnsupportedChart("unsupported-chart-series-style")+ return _MarkerPaint(+ symbol,+ size,+ _resolved_shape_paint(marker.find("c:spPr", C_NS), palette),)- return [- f"#{_canonical_sp_pr_color(sp_pr, line_visible=line_visible)}"- for sp_pr in sp_pr_nodes- if sp_pr is not None+++def _automatic_color(palette: ColorPalette | None, index: int) -> str:+ if palette is not None:+ resolved = palette.resolve_scheme(f"accent{index % 6 + 1}")+ if resolved:+ return f"#{resolved.upper()}"+ return _FALLBACK_CHART_COLORS[index % len(_FALLBACK_CHART_COLORS)]+++def _line_color(line: _LinePaint | None, default: str | None) -> str | None:+ if line is None:+ return default+ if not line.visible:+ return None+ return default if line.automatic else line.color+++def _series_visual_style(+ shape: _ShapePaint,+ marker: _MarkerPaint,+ *,+ chart_type: str,+ auto_color: str,+) -> SeriesVisualStyle:+ fill_default = auto_color if chart_type in {"area", "bar", "bubble", "column"} else None+ fill = shape.fill if shape.fill_explicit else fill_default+ if chart_type in {"line", "scatter"}:+ line_default = auto_color+ elif chart_type == "area":+ line_default = auto_color+ else:+ line_default = None+ stroke = _line_color(shape.line, line_default)+ marker_fill = marker.shape.fill if marker.shape.fill_explicit else auto_color+ marker_stroke = _line_color(marker.shape.line, auto_color)+ line = shape.line+ marker_line = marker.shape.line+ return 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.5,+ line_cap=line.cap if line is not None else "round",+ marker_fill=marker_fill,+ marker_fill_opacity=marker.shape.fill_opacity,+ marker_stroke=marker_stroke,+ marker_stroke_opacity=marker_line.opacity if marker_line is not None else 1.0,+ marker_stroke_width=marker_line.width if marker_line is not None else 1.0,+ marker_size=marker.size,+ )+++def _pie_visual_styles(+ payload: dict[str, Any],+ series: ET.Element,+ palette: ColorPalette | None,+) -> list[SeriesVisualStyle]:+ chart_type = payload["type"]+ expected_count = len(payload["categories"]) + (1 if chart_type == "of_pie" else 0)+ base_shape = _resolved_shape_paint(series.find("c:spPr", C_NS), palette)+ point_nodes = series.findall("c:dPt", C_NS)+ points: dict[int, _ShapePaint] = {}+ for point in point_nodes:+ if point.attrib:+ raise _UnsupportedChart("unsupported-chart-series-style")+ allowed = {"idx", "bubble3D", "explosion", "spPr"}+ names = [_local_name(child.tag) for child in point]+ if any(name not in allowed for name in names) or len(names) != len(set(names)):+ raise _UnsupportedChart("unsupported-chart-series-style")+ idx = point.find("c:idx", C_NS)+ if idx is None or set(idx.attrib) != {"val"} or list(idx):+ raise _UnsupportedChart("unsupported-chart-series-style")+ try:+ point_index = int(idx.attrib["val"])+ except ValueError:+ raise _UnsupportedChart("unsupported-chart-series-style") from None+ bubble_3d = point.find("c:bubble3D", C_NS)+ if bubble_3d is not None and (+ not set(bubble_3d.attrib).issubset({"val"})+ or list(bubble_3d)+ or ooxml_bool(bubble_3d.attrib.get("val"), True)+ ):+ raise _UnsupportedChart("unsupported-chart-series-style")+ if point_index < 0 or point_index >= expected_count or point_index in points:+ raise _UnsupportedChart("unsupported-chart-series-style")+ points[point_index] = _resolved_shape_paint(point.find("c:spPr", C_NS), palette)+ if points and set(points) != set(range(expected_count)):+ raise _UnsupportedChart("unsupported-chart-series-style")++ styles: list[SeriesVisualStyle] = []+ for index in range(expected_count):+ auto = _automatic_color(palette, index)+ point_shape = points.get(index, base_shape)+ fill = point_shape.fill if point_shape.fill_explicit else auto+ stroke = _line_color(point_shape.line, "#FFFFFF")+ line = point_shape.line+ styles.append(+ SeriesVisualStyle(+ fill=fill,+ fill_opacity=point_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,+ )+ )+ return styles+++def _chart_visual_styles(+ payload: dict[str, Any],+ plot: ET.Element,+ palette: ColorPalette | None,+) -> list[SeriesVisualStyle]:+ chart_type = payload["type"]+ series_nodes = plot.findall("c:ser", C_NS)+ if chart_type in {"pie", "doughnut", "of_pie"}:+ if len(series_nodes) != 1:+ raise _UnsupportedChart("unsupported-chart-series-style")+ styles = _pie_visual_styles(payload, series_nodes[0], palette)+ else:+ if any(series.find("c:dPt", C_NS) is not None for series in series_nodes):+ raise _UnsupportedChart("unsupported-chart-series-style")+ styles = []+ for index, series in enumerate(series_nodes):+ auto = _automatic_color(palette, index)+ shape = _resolved_shape_paint(series.find("c:spPr", C_NS), palette)+ marker = _resolved_marker(series.find("c:marker", C_NS), palette)+ styles.append(+ _series_visual_style(+ shape,+ marker,+ chart_type=chart_type,+ auto_color=auto,+ )+ )+ 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 stylesdef _validate_chart_semantics(payload: dict[str, Any],plot_area: ET.Element,plot: ET.Element,-) -> None:+ *,+ palette: ColorPalette | None = None,+) -> list[SeriesVisualStyle]:"""Reject valid chart features the compact marker cannot reproduce."""chart_type = payload["type"]- colors = _canonical_chart_colors(payload, plot)- if colors:- payload["style"] = {"colors": colors}+ visual_styles = _chart_visual_styles(payload, plot, palette)for tag in ("trendline", "errBars", "dropLines", "hiLowLines", "upDownBars",):@@ -330,11 +632,6 @@ def _validate_chart_semantics(marker_states: set[bool] = set()for series in plot.findall("c:ser", C_NS):marker_node = series.find("c:marker", C_NS)- if marker_node is not None and any(- child.tag.rsplit("}", 1)[-1] != "symbol"- for child in marker_node- ):- raise _UnsupportedChart("unsupported-chart-line-style")symbol = _element_val(series.find("c:marker/c:symbol", C_NS))if symbol not in {None, "circle", "none"}:raise _UnsupportedChart("unsupported-chart-line-style")@@ -389,11 +686,6 @@ def _validate_chart_semantics(marker = series.find("c:marker", C_NS)if marker is None:raise _UnsupportedChart("unsupported-chart-scatter-style")- if any(- child.tag.rsplit("}", 1)[-1] != "symbol"- for child in marker- ):- raise _UnsupportedChart("unsupported-chart-scatter-style")symbol = _element_val(marker.find("c:symbol", C_NS))if symbol != expected_marker:raise _UnsupportedChart("unsupported-chart-scatter-style")@@ -425,6 +717,7 @@ def _validate_chart_semantics(second_size = _element_val(plot.find("c:secondPieSize", C_NS))if second_size not in {None, "75"}:raise _UnsupportedChart("unsupported-chart-of-pie-options")+ return visual_stylesdef _apply_chart_metadata(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.pynew file mode 100644index 00000000..5cbb55cd--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py@@ -0,0 +1,1135 @@+"""Deterministic normalized SVG fallback for parsed classic charts.++The renderer is intentionally independent from the native-chart OOXML+emitter. It visualizes only data and semantics that ``chart_to_svg`` has+already accepted, so a rendering failure can never invalidate an otherwise+valid editable-chart payload.+"""++from __future__ import annotations++import html+import math+import re+from dataclasses import dataclass+from decimal import Decimal, ROUND_HALF_UP+from typing import Any+++_DEFAULT_COLORS = (+ "#4472C4",+ "#ED7D31",+ "#A5A5A5",+ "#FFC000",+ "#5B9BD5",+ "#70AD47",+ "#264478",+ "#9E480E",+)+++@dataclass(frozen=True)+class SeriesVisualStyle:+ """Resolved paint used only by the normalized SVG fallback."""++ fill: str | None+ fill_opacity: float = 1.0+ stroke: str | None = None+ stroke_opacity: float = 1.0+ stroke_width: float = 1.5+ line_cap: str = "round"+ marker_fill: str | None = None+ marker_fill_opacity: float = 1.0+ marker_stroke: str | None = None+ marker_stroke_opacity: float = 1.0+ marker_stroke_width: float = 1.0+ marker_size: float = 5.0+++@dataclass(frozen=True)+class _Rect:+ x: float+ y: float+ w: float+ h: float+++def render_normalized_chart_svg(+ payload: dict[str, Any],+ styles: list[SeriesVisualStyle],+) -> str | None:+ """Render a readable normalized fallback for supported classic charts."""+ chart_type = str(payload.get("type") or "")+ if chart_type not in {+ "area", "bar", "column", "doughnut", "line", "pie",+ "scatter", "bubble",+ }:+ return None++ try:+ bounds = _Rect(+ float(payload["x"]),+ float(payload["y"]),+ float(payload["width"]),+ float(payload["height"]),+ )+ except (KeyError, TypeError, ValueError, OverflowError):+ return None+ if (+ bounds.w <= 0+ or bounds.h <= 0+ or not all(math.isfinite(value) for value in vars(bounds).values())+ ):+ return None++ legend_entries = _legend_entries(payload, styles)+ content, legend_rect, title_parts = _outer_layout(+ payload,+ bounds,+ len(legend_entries),+ )+ parts = [*title_parts]+ if chart_type in {"pie", "doughnut"}:+ parts.extend(_render_pie(payload, styles, content, chart_type == "doughnut"))+ elif chart_type in {"scatter", "bubble"}:+ parts.extend(_render_xy(payload, styles, content, chart_type))+ else:+ parts.extend(_render_category(payload, styles, content, chart_type))+ if legend_rect is not None:+ parts.extend(+ _render_legend(+ legend_entries,+ legend_rect,+ str(payload.get("legend_position") or "b"),+ )+ )+ return "\n".join(part for part in parts if part)+++def _outer_layout(+ payload: dict[str, Any],+ bounds: _Rect,+ legend_count: int,+) -> tuple[_Rect, _Rect | None, list[str]]:+ pad = max(4.0, min(bounds.w, bounds.h) * 0.018)+ content = _Rect(+ bounds.x + pad,+ bounds.y + pad,+ max(1.0, bounds.w - 2 * pad),+ max(1.0, bounds.h - 2 * pad),+ )+ title_parts: list[str] = []+ title = _entry_text(payload.get("title"))+ subtitle = _entry_text(payload.get("subtitle"))+ if title:+ title_size = _font_size(+ _entry_value(payload.get("title"), "font_size"),+ min(18.0, max(10.0, bounds.h * 0.055)),+ bounds,+ )+ title_y = content.y + title_size+ title_parts.append(+ _text(+ content.x + content.w / 2,+ title_y,+ title,+ size=title_size,+ anchor="middle",+ weight="600",+ fill=_entry_color(payload.get("title"), "#333333"),+ )+ )+ used = title_size + max(4.0, title_size * 0.35)+ content = _Rect(content.x, content.y + used, content.w, max(1.0, content.h - used))+ if subtitle:+ subtitle_size = _font_size(+ _entry_value(payload.get("subtitle"), "font_size"),+ min(12.0, max(8.0, bounds.h * 0.035)),+ bounds,+ )+ title_parts.append(+ _text(+ content.x + content.w / 2,+ content.y + subtitle_size,+ subtitle,+ size=subtitle_size,+ anchor="middle",+ fill=_entry_color(payload.get("subtitle"), "#666666"),+ )+ )+ used = subtitle_size + max(3.0, subtitle_size * 0.3)+ content = _Rect(content.x, content.y + used, content.w, max(1.0, content.h - used))++ if not payload.get("show_legend") or legend_count <= 0:+ return content, None, title_parts+ position = str(payload.get("legend_position") or "b").lower()+ if position in {"l", "r", "left", "right"}:+ legend_w = min(max(86.0, content.w * 0.24), max(1.0, content.w * 0.38))+ if position in {"l", "left"}:+ legend = _Rect(content.x, content.y, legend_w, content.h)+ content = _Rect(+ content.x + legend_w,+ content.y,+ max(1.0, content.w - legend_w),+ content.h,+ )+ else:+ legend = _Rect(content.x + content.w - legend_w, content.y, legend_w, content.h)+ content = _Rect(content.x, content.y, max(1.0, content.w - legend_w), content.h)+ return content, legend, title_parts++ columns = max(1, min(4, int(content.w // 130) or 1))+ rows = math.ceil(legend_count / columns)+ legend_h = min(content.h * 0.32, max(20.0, rows * 17.0 + 4.0))+ if position in {"t", "top"}:+ legend = _Rect(content.x, content.y, content.w, legend_h)+ content = _Rect(+ content.x,+ content.y + legend_h,+ content.w,+ max(1.0, content.h - legend_h),+ )+ else:+ legend = _Rect(content.x, content.y + content.h - legend_h, content.w, legend_h)+ content = _Rect(content.x, content.y, content.w, max(1.0, content.h - legend_h))+ return content, legend, title_parts+++def _render_category(+ payload: dict[str, Any],+ styles: list[SeriesVisualStyle],+ content: _Rect,+ chart_type: str,+) -> list[str]:+ categories = [str(value) for value in payload.get("categories") or []]+ series = payload.get("series") or []+ if not categories or not series:+ return []+ styles = _complete_styles(styles, len(series))+ axis_titles = payload.get("axis_titles") if isinstance(payload.get("axis_titles"), dict) else {}+ is_bar = chart_type == "bar"+ label_size = max(6.0, min(11.0, content.h * 0.037, content.w * 0.021))+ left = max(34.0, content.w * 0.075)+ bottom = max(25.0, content.h * 0.105)+ if is_bar:+ left = min(content.w * 0.34, max(66.0, content.w * 0.18))+ bottom = max(24.0, content.h * 0.085)+ if axis_titles.get("value"):+ left += 14.0 if not is_bar else 0.0+ bottom += 14.0 if is_bar else 0.0+ if axis_titles.get("category"):+ bottom += 14.0 if not is_bar else 0.0+ left += 14.0 if is_bar else 0.0+ plot = _Rect(+ content.x + left,+ content.y + 5.0,+ max(12.0, content.w - left - 10.0),+ max(12.0, content.h - bottom - 8.0),+ )++ grouping = str(payload.get("grouping") or ("clustered" if chart_type in {"bar", "column"} else "standard"))+ segments, percent = _category_segments(series, len(categories), grouping)+ scale_values = [value for row in segments for pair in row for value in pair]+ lo, hi, ticks = _nice_scale(scale_values, include_zero=True, percent=percent)+ parts: list[str] = []+ show_value_labels = payload.get("show_value_axis_labels") is not False++ if is_bar:+ parts.extend(_horizontal_grid_and_ticks(+ plot,+ ticks,+ lo,+ hi,+ label_size,+ percent,+ show_labels=show_value_labels,+ ))+ parts.extend(_bar_category_labels(plot, categories, label_size))+ else:+ parts.extend(_vertical_grid_and_ticks(+ plot,+ ticks,+ lo,+ hi,+ label_size,+ percent,+ show_labels=show_value_labels,+ ))+ parts.extend(_column_category_labels(+ plot,+ categories,+ label_size,+ point_aligned=chart_type in {"line", "area"},+ ))+ parts.extend(_axis_titles(plot, content, axis_titles, label_size, is_bar=is_bar))++ if chart_type in {"bar", "column"}:+ parts.extend(+ _render_bars(+ payload,+ categories,+ series,+ styles,+ segments,+ plot,+ lo,+ hi,+ grouping,+ horizontal=is_bar,+ label_size=label_size,+ percent=percent,+ )+ )+ else:+ parts.extend(+ _render_lines_or_areas(+ payload,+ categories,+ series,+ styles,+ segments,+ plot,+ lo,+ hi,+ chart_type,+ label_size,+ percent,+ )+ )+ return parts+++def _category_segments(+ series: list[dict[str, Any]],+ count: int,+ grouping: str,+) -> tuple[list[list[tuple[float, float]]], bool]:+ raw = [+ [float(value) for value in item.get("values", [])[:count]]+ for item in series+ ]+ percent = grouping == "percentStacked"+ if percent:+ positive = [sum(max(row[idx], 0.0) for row in raw) for idx in range(count)]+ negative = [sum(abs(min(row[idx], 0.0)) for row in raw) for idx in range(count)]+ for row in raw:+ for idx, value in enumerate(row):+ denominator = positive[idx] if value >= 0 else negative[idx]+ row[idx] = value / denominator if denominator else 0.0+ if grouping not in {"stacked", "percentStacked"}:+ return [[(0.0, value) for value in row] for row in raw], percent++ positive_base = [0.0] * count+ negative_base = [0.0] * count+ result: list[list[tuple[float, float]]] = []+ for row in raw:+ segments: list[tuple[float, float]] = []+ for idx, value in enumerate(row):+ if value >= 0:+ start = positive_base[idx]+ positive_base[idx] += value+ end = positive_base[idx]+ else:+ start = negative_base[idx]+ negative_base[idx] += value+ end = negative_base[idx]+ segments.append((start, end))+ result.append(segments)+ return result, percent+++def _render_bars(+ payload: dict[str, Any],+ categories: list[str],+ series: list[dict[str, Any]],+ styles: list[SeriesVisualStyle],+ segments: list[list[tuple[float, float]]],+ plot: _Rect,+ lo: float,+ hi: float,+ grouping: str,+ *,+ horizontal: bool,+ label_size: float,+ percent: bool,+) -> list[str]:+ parts: list[str] = []+ stacked = grouping in {"stacked", "percentStacked"}+ category_span = (plot.h if horizontal else plot.w) / max(len(categories), 1)+ cluster = category_span * 0.72+ bar_span = cluster if stacked else cluster / max(len(series), 1)+ labels = payload.get("data_labels") if isinstance(payload.get("data_labels"), dict) else None+ for series_index, (item, style, row) in enumerate(zip(series, styles, segments)):+ fill = style.fill or "none"+ stroke = style.stroke or "none"+ for category_index, (start, end) in enumerate(row):+ offset = 0.0 if stacked else series_index * bar_span+ display_index = (+ len(categories) - 1 - category_index+ if horizontal else category_index+ )+ cluster_start = display_index * category_span + (category_span - cluster) / 2+ if horizontal:+ x1 = _map(end, lo, hi, plot.x, plot.x + plot.w)+ x0 = _map(start, lo, hi, plot.x, plot.x + plot.w)+ x = min(x0, x1)+ y = plot.y + cluster_start + offset+ w = max(abs(x1 - x0), 0.35)+ h = max(bar_span * 0.9, 0.5)+ else:+ y1 = _map(end, lo, hi, plot.y + plot.h, plot.y)+ y0 = _map(start, lo, hi, plot.y + plot.h, plot.y)+ x = plot.x + cluster_start + offset+ y = min(y0, y1)+ w = max(bar_span * 0.9, 0.5)+ h = max(abs(y1 - y0), 0.35)+ parts.append(+ f'<rect x="{_fmt(x)}" y="{_fmt(y)}" width="{_fmt(w)}" '+ f'height="{_fmt(h)}" fill="{fill}" fill-opacity="{_fmt(style.fill_opacity)}" '+ f'stroke="{stroke}" stroke-opacity="{_fmt(style.stroke_opacity)}" '+ f'stroke-width="{_fmt(max(0.4, style.stroke_width))}"/>'+ )+ if labels:+ value = float(item["values"][category_index])+ normalized_percent = end - start if percent else None+ label = _data_label(+ labels,+ str(item.get("name") or ""),+ categories[category_index],+ value,+ percent_value=normalized_percent,+ )+ if label:+ if horizontal:+ tx = x1 + (4.0 if end >= start else -4.0)+ ty = y + h / 2 + label_size * 0.32+ anchor = "start" if end >= start else "end"+ else:+ tx = x + w / 2+ ty = y1 - 4.0 if end >= start else y1 + label_size + 3.0+ anchor = "middle"+ parts.append(_text(tx, ty, label, size=max(6.0, label_size - 1), anchor=anchor))+ return parts+++def _render_lines_or_areas(+ payload: dict[str, Any],+ categories: list[str],+ series: list[dict[str, Any]],+ styles: list[SeriesVisualStyle],+ segments: list[list[tuple[float, float]]],+ plot: _Rect,+ lo: float,+ hi: float,+ chart_type: str,+ label_size: float,+ percent: bool,+) -> list[str]:+ parts: list[str] = []+ count = len(categories)+ x_positions = [+ _category_point_x(plot, idx, count)+ for idx in range(count)+ ]+ labels = payload.get("data_labels") if isinstance(payload.get("data_labels"), dict) else None+ show_markers = chart_type == "line" and payload.get("line_style") == "lineMarker"+ for series_index, (item, style, row) in enumerate(zip(series, styles, segments)):+ fill_color = style.fill or "none"+ line_color = style.stroke+ top = [+ (x_positions[idx], _map(end, lo, hi, plot.y + plot.h, plot.y))+ for idx, (_start, end) in enumerate(row)+ ]+ if chart_type == "area":+ bottom = [+ (x_positions[idx], _map(start, lo, hi, plot.y + plot.h, plot.y))+ for idx, (start, _end) in enumerate(row)+ ]+ points = top + list(reversed(bottom))+ parts.append(+ f'<polygon points="{_points(points)}" fill="{fill_color}" '+ f'fill-opacity="{_fmt(min(style.fill_opacity, 0.58))}" '+ f'stroke="{line_color or "none"}" stroke-opacity="{_fmt(style.stroke_opacity)}" '+ f'stroke-width="{_fmt(max(0.7, style.stroke_width))}" '+ 'stroke-linejoin="round"/>'+ )+ elif line_color is not None:+ parts.append(+ f'<polyline points="{_points(top)}" fill="none" stroke="{line_color}" '+ f'stroke-opacity="{_fmt(style.stroke_opacity)}" '+ f'stroke-width="{_fmt(max(1.0, style.stroke_width))}" '+ f'stroke-linecap="{style.line_cap}" stroke-linejoin="round"/>'+ )+ if show_markers:+ for x, y in top:+ radius = max(2.0, style.marker_size / 2)+ parts.append(+ f'<circle cx="{_fmt(x)}" cy="{_fmt(y)}" r="{_fmt(radius)}" '+ f'fill="{style.marker_fill or "none"}" '+ f'fill-opacity="{_fmt(style.marker_fill_opacity)}" '+ f'stroke="{style.marker_stroke or "none"}" '+ f'stroke-opacity="{_fmt(style.marker_stroke_opacity)}" '+ f'stroke-width="{_fmt(max(0.6, style.marker_stroke_width))}"/>'+ )+ if labels:+ for idx, (x, y) in enumerate(top):+ value = float(item["values"][idx])+ start, end = row[idx]+ normalized_percent = end - start if percent else None+ label = _data_label(+ labels,+ str(item.get("name") or ""),+ categories[idx],+ value,+ percent_value=normalized_percent,+ )+ if label:+ parts.append(_text(x, y - 5.0, label, size=max(6.0, label_size - 1), anchor="middle"))+ return parts+++def _render_pie(+ payload: dict[str, Any],+ styles: list[SeriesVisualStyle],+ content: _Rect,+ doughnut: bool,+) -> list[str]:+ categories = [str(value) for value in payload.get("categories") or []]+ series = payload.get("series") or []+ if not categories or len(series) != 1:+ return []+ values = [abs(float(value)) for value in series[0].get("values") or []]+ total = sum(values)+ 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)+ cx = content.x + content.w / 2+ cy = content.y + content.h / 2+ if total <= 0:+ parts = [+ f'<circle cx="{_fmt(cx)}" cy="{_fmt(cy)}" r="{_fmt(radius)}" '+ 'fill="none" stroke="#B8C0CC" stroke-width="1.2" stroke-dasharray="4 3"/>'+ ]+ if doughnut:+ parts.append(+ f'<circle cx="{_fmt(cx)}" cy="{_fmt(cy)}" r="{_fmt(radius * 0.75)}" '+ 'fill="none" stroke="#D5DAE1" stroke-width="1"/>'+ )+ parts.append(+ _text(cx, cy + label_size * 0.32, "0", size=label_size, anchor="middle")+ )+ return parts+ parts: list[str] = []+ angle = -math.pi / 2+ for idx, (category, value, style) in enumerate(zip(categories, values, styles)):+ sweep = math.tau * value / total+ end = angle + sweep+ # Pie styles are completed before rendering, so ``None`` here means+ # the source explicitly used ``noFill`` rather than an absent style.+ fill = style.fill or "none"+ 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)+ 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))}" '+ 'fill-rule="evenodd"/>'+ )+ else:+ parts.append(+ f'<circle cx="{_fmt(cx)}" cy="{_fmt(cy)}" r="{_fmt(radius)}" '+ f'fill="{fill}" fill-opacity="{_fmt(style.fill_opacity)}" '+ 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)+ parts.append(+ f'<path d="{path}" fill="{fill}" fill-opacity="{_fmt(style.fill_opacity)}" '+ f'stroke="{stroke}" stroke-opacity="{_fmt(style.stroke_opacity)}" '+ f'stroke-width="{_fmt(max(0.6, style.stroke_width))}" fill-rule="evenodd"/>'+ )+ mid = angle + sweep / 2+ label_radius = radius * (0.87 if doughnut else 0.68)+ lx = cx + math.cos(mid) * label_radius+ ly = cy + math.sin(mid) * label_radius + label_size * 0.32+ percent = value / total+ label = f"{category} {_format_percent(percent)}"+ parts.append(+ _text(+ lx,+ ly,+ label,+ size=label_size,+ anchor="middle",+ fill="#444444" if fill == "none" else _contrast_color(fill),+ )+ )+ angle = end+ return parts+++def _render_xy(+ payload: dict[str, Any],+ styles: list[SeriesVisualStyle],+ content: _Rect,+ chart_type: str,+) -> list[str]:+ series = payload.get("series") or []+ if not series:+ return []+ styles = _complete_styles(styles, len(series))+ axis_titles = payload.get("axis_titles") if isinstance(payload.get("axis_titles"), dict) else {}+ label_size = max(6.0, min(11.0, content.h * 0.037, content.w * 0.021))+ left = max(40.0, content.w * 0.09) + (14.0 if axis_titles.get("y") else 0.0)+ bottom = max(26.0, content.h * 0.1) + (14.0 if axis_titles.get("x") else 0.0)+ plot = _Rect(+ content.x + left,+ content.y + 6.0,+ max(12.0, content.w - left - 10.0),+ max(12.0, content.h - bottom - 8.0),+ )+ x_values = [float(value) for item in series for value in item.get("x") or []]+ y_values = [float(value) for item in series for value in item.get("y") or []]+ x_lo, x_hi, x_ticks = _nice_scale(x_values, include_zero=False)+ y_lo, y_hi, y_ticks = _nice_scale(y_values, include_zero=False)+ parts = _xy_grid_and_ticks(plot, x_ticks, y_ticks, x_lo, x_hi, y_lo, y_hi, label_size)+ parts.extend(_xy_axis_titles(plot, content, axis_titles, label_size))+ nonnegative_bubble_sizes = [+ float(value)+ for item in series+ for value in item.get("sizes") or []+ if float(value) >= 0+ ]+ bubble_max = max(max(nonnegative_bubble_sizes or [0.0]), 1e-12)+ scatter_style = str(payload.get("scatter_style") or "marker")+ has_line = chart_type == "scatter" and scatter_style in {"line", "lineMarker", "smooth", "smoothMarker"}+ has_marker = chart_type == "bubble" or scatter_style in {"marker", "lineMarker", "smoothMarker"}+ for idx, (item, style) in enumerate(zip(series, styles)):+ color = style.stroke or style.fill or style.marker_fill or _DEFAULT_COLORS[idx % len(_DEFAULT_COLORS)]+ points = [+ (+ _map(float(x), x_lo, x_hi, plot.x, plot.x + plot.w),+ _map(float(y), y_lo, y_hi, plot.y + plot.h, plot.y),+ )+ for x, y in zip(item.get("x") or [], item.get("y") or [])+ ]+ if has_line and style.stroke is not None and len(points) >= 2:+ parts.append(+ f'<polyline points="{_points(points)}" fill="none" stroke="{color}" '+ f'stroke-opacity="{_fmt(style.stroke_opacity)}" '+ f'stroke-width="{_fmt(max(1.0, style.stroke_width))}" '+ f'stroke-linecap="{style.line_cap}" stroke-linejoin="round"/>'+ )+ if has_marker:+ sizes = item.get("sizes") or [style.marker_size * style.marker_size] * len(points)+ for point_index, (x, y) in enumerate(points):+ if chart_type == "bubble":+ bubble_size = float(sizes[point_index])+ if bubble_size < 0:+ continue+ radius = 3.0 + 13.0 * math.sqrt(bubble_size / bubble_max)+ else:+ radius = max(2.0, style.marker_size / 2)+ fill = (+ style.fill or "none"+ if chart_type == "bubble"+ else style.marker_fill or "none"+ )+ stroke = (+ style.stroke or "none"+ if chart_type == "bubble"+ else style.marker_stroke or "none"+ )+ parts.append(+ f'<circle cx="{_fmt(x)}" cy="{_fmt(y)}" r="{_fmt(radius)}" '+ f'fill="{fill}" fill-opacity="{_fmt(style.marker_fill_opacity if chart_type == "scatter" else style.fill_opacity)}" '+ f'stroke="{stroke}" stroke-opacity="{_fmt(style.marker_stroke_opacity)}" '+ f'stroke-width="{_fmt(max(0.6, style.marker_stroke_width))}"/>'+ )+ return parts+++def _vertical_grid_and_ticks(+ plot: _Rect,+ ticks: list[float],+ lo: float,+ hi: float,+ size: float,+ percent: bool,+ *,+ show_labels: bool,+) -> list[str]:+ parts: list[str] = []+ for tick in ticks:+ y = _map(tick, lo, hi, plot.y + plot.h, plot.y)+ parts.append(+ f'<line x1="{_fmt(plot.x)}" y1="{_fmt(y)}" x2="{_fmt(plot.x + plot.w)}" '+ f'y2="{_fmt(y)}" stroke="#D9D9D9" stroke-width="0.7"/>'+ )+ if show_labels:+ label = _format_percent(tick) if percent else _format_number(tick)+ parts.append(_text(plot.x - 5.0, y + size * 0.32, label, size=size, anchor="end", fill="#666666"))+ parts.append(+ f'<line x1="{_fmt(plot.x)}" y1="{_fmt(plot.y)}" x2="{_fmt(plot.x)}" '+ f'y2="{_fmt(plot.y + plot.h)}" stroke="#808080" stroke-width="1"/>'+ )+ return parts+++def _horizontal_grid_and_ticks(+ plot: _Rect,+ ticks: list[float],+ lo: float,+ hi: float,+ size: float,+ percent: bool,+ *,+ show_labels: bool,+) -> list[str]:+ parts: list[str] = []+ for tick in ticks:+ x = _map(tick, lo, hi, plot.x, plot.x + plot.w)+ parts.append(+ f'<line x1="{_fmt(x)}" y1="{_fmt(plot.y)}" x2="{_fmt(x)}" '+ f'y2="{_fmt(plot.y + plot.h)}" stroke="#D9D9D9" stroke-width="0.7"/>'+ )+ if show_labels:+ label = _format_percent(tick) if percent else _format_number(tick)+ parts.append(_text(x, plot.y + plot.h + size + 4.0, label, size=size, anchor="middle", fill="#666666"))+ parts.append(+ f'<line x1="{_fmt(plot.x)}" y1="{_fmt(plot.y + plot.h)}" '+ f'x2="{_fmt(plot.x + plot.w)}" y2="{_fmt(plot.y + plot.h)}" '+ 'stroke="#808080" stroke-width="1"/>'+ )+ return parts+++def _column_category_labels(+ plot: _Rect,+ categories: list[str],+ size: float,+ *,+ point_aligned: bool,+) -> list[str]:+ parts: list[str] = []+ span = plot.w / max(len(categories), 1)+ rotate = len(categories) > 8 or any(len(value) > 10 for value in categories)+ for idx, category in enumerate(categories):+ if point_aligned:+ x = _category_point_x(plot, idx, len(categories))+ else:+ x = plot.x + span * (idx + 0.5)+ y = plot.y + plot.h + size + 5.0+ transform = f' transform="rotate(-35 {_fmt(x)} {_fmt(y)})"' if rotate else ""+ anchor = "end" if rotate else "middle"+ parts.append(+ f'<text x="{_fmt(x)}" y="{_fmt(y)}" text-anchor="{anchor}" '+ f'font-family="Arial" font-size="{_fmt(size)}" fill="#555555"{transform}>'+ f'{html.escape(category)}</text>'+ )+ return parts+++def _category_point_x(plot: _Rect, index: int, count: int) -> float:+ """Align line/area data points and their category labels."""+ if count <= 1:+ return plot.x + plot.w / 2+ return plot.x + plot.w * index / (count - 1)+++def _bar_category_labels(plot: _Rect, categories: list[str], size: float) -> list[str]:+ span = plot.h / max(len(categories), 1)+ return [+ _text(+ plot.x - 6.0,+ plot.y + span * (len(categories) - idx - 0.5) + size * 0.32,+ category,+ size=size,+ anchor="end",+ fill="#555555",+ )+ for idx, category in enumerate(categories)+ ]+++def _xy_grid_and_ticks(+ plot: _Rect,+ x_ticks: list[float],+ y_ticks: list[float],+ x_lo: float,+ x_hi: float,+ y_lo: float,+ y_hi: float,+ size: float,+) -> list[str]:+ parts = _vertical_grid_and_ticks(+ plot,+ y_ticks,+ y_lo,+ y_hi,+ size,+ False,+ show_labels=True,+ )+ for tick in x_ticks:+ x = _map(tick, x_lo, x_hi, plot.x, plot.x + plot.w)+ parts.append(_text(x, plot.y + plot.h + size + 4.0, _format_number(tick), size=size, anchor="middle", fill="#666666"))+ parts.append(+ f'<line x1="{_fmt(plot.x)}" y1="{_fmt(plot.y + plot.h)}" '+ f'x2="{_fmt(plot.x + plot.w)}" y2="{_fmt(plot.y + plot.h)}" '+ 'stroke="#808080" stroke-width="1"/>'+ )+ return parts+++def _axis_titles(+ plot: _Rect,+ content: _Rect,+ titles: dict[str, Any],+ size: float,+ *,+ is_bar: bool,+) -> list[str]:+ category = str(titles.get("category") or "")+ value = str(titles.get("value") or "")+ x_title = value if is_bar else category+ y_title = category if is_bar else value+ return _draw_axis_titles(plot, content, x_title, y_title, size)+++def _xy_axis_titles(+ plot: _Rect,+ content: _Rect,+ titles: dict[str, Any],+ size: float,+) -> list[str]:+ return _draw_axis_titles(+ plot,+ content,+ str(titles.get("x") or ""),+ str(titles.get("y") or ""),+ size,+ )+++def _draw_axis_titles(+ plot: _Rect,+ content: _Rect,+ x_title: str,+ y_title: str,+ size: float,+) -> list[str]:+ parts: list[str] = []+ if x_title:+ parts.append(_text(plot.x + plot.w / 2, content.y + content.h - 2.0, x_title, size=size, anchor="middle", weight="600"))+ if y_title:+ x = content.x + size+ y = plot.y + plot.h / 2+ parts.append(+ f'<text x="{_fmt(x)}" y="{_fmt(y)}" text-anchor="middle" '+ f'font-family="Arial" font-size="{_fmt(size)}" font-weight="600" '+ f'fill="#444444" transform="rotate(-90 {_fmt(x)} {_fmt(y)})">'+ f'{html.escape(y_title)}</text>'+ )+ return parts+++def _legend_entries(+ payload: dict[str, Any],+ styles: list[SeriesVisualStyle],+) -> list[tuple[str, str]]:+ chart_type = str(payload.get("type") or "")+ if chart_type in {"pie", "doughnut"}:+ labels = [str(value) for value in payload.get("categories") or []]+ 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))+ return [+ (+ label,+ style.fill or style.stroke or style.marker_fill or _DEFAULT_COLORS[idx % len(_DEFAULT_COLORS)],+ )+ for idx, (label, style) in enumerate(zip(labels, completed))+ ]+++def _render_legend(+ entries: list[tuple[str, str]],+ rect: _Rect,+ position: str,+) -> list[str]:+ if not entries:+ return []+ size = max(6.0, min(10.0, rect.h * 0.18 if position.lower() in {"l", "r", "left", "right"} else 9.0))+ parts: list[str] = []+ if position.lower() in {"l", "r", "left", "right"}:+ row_h = min(18.0, rect.h / max(len(entries), 1))+ for idx, (label, color) in enumerate(entries):+ y = rect.y + row_h * (idx + 0.5)+ parts.append(+ f'<rect x="{_fmt(rect.x + 5)}" y="{_fmt(y - 4)}" width="8" height="8" fill="{color}"/>'+ )+ parts.append(_text(rect.x + 18.0, y + size * 0.32, label, size=size, anchor="start", fill="#444444"))+ return parts++ columns = max(1, min(4, int(rect.w // 130) or 1))+ rows = math.ceil(len(entries) / columns)+ row_h = rect.h / max(rows, 1)+ col_w = rect.w / columns+ for idx, (label, color) in enumerate(entries):+ row = idx // columns+ col = idx % columns+ x = rect.x + col * col_w + 5.0+ y = rect.y + row_h * (row + 0.5)+ parts.append(+ f'<rect x="{_fmt(x)}" y="{_fmt(y - 4)}" width="8" height="8" fill="{color}"/>'+ )+ parts.append(_text(x + 13.0, y + size * 0.32, label, size=size, anchor="start", fill="#444444"))+ return parts+++def _data_label(+ config: dict[str, Any],+ series: str,+ category: str,+ value: float,+ *,+ percent_value: float | None,+) -> str:+ fields: list[str] = []+ if config.get("show_series"):+ fields.append(series)+ if config.get("show_category"):+ fields.append(category)+ if config.get("show_value"):+ fields.append(_format_data_label_value(+ value,+ config.get("number_format"),+ ))+ if config.get("show_percent"):+ if percent_value is None:+ raise ValueError(+ "normalized percent labels require percent-stacked segments"+ )+ number_format = config.get("number_format")+ normalized_format = str(number_format or "").strip()+ percent_format = (+ "0%"+ if not normalized_format or normalized_format.lower() == "general"+ else normalized_format+ )+ fields.append(_format_data_label_value(+ percent_value,+ percent_format,+ ))+ return " · ".join(field for field in fields if field)+++def _format_data_label_value(value: float, number_format: Any) -> str:+ """Render the safe numeric subset used by normalized data labels.++ Unknown Excel format programs raise so the caller falls back to the+ reconstruction-only route instead of displaying a materially wrong label.+ """+ code = str(number_format or "").strip()+ if not code or code.lower() == "general":+ return _format_number(value)+ match = re.fullmatch(+ r"(?P<prefix>[$¥¥€£]?)(?P<group>#,##)?0"+ r"(?P<decimals>\.0+)?(?P<percent>%?)",+ code,+ )+ if match is None:+ raise ValueError(f"unsupported normalized data-label format: {code!r}")+ scaled = value * 100.0 if match.group("percent") else value+ decimals = len((match.group("decimals") or "").lstrip("."))+ grouping = "," if match.group("group") else ""+ quantum = Decimal(1).scaleb(-decimals)+ rounded = Decimal(str(abs(scaled))).quantize(+ quantum,+ rounding=ROUND_HALF_UP,+ )+ absolute = format(rounded, f"{grouping}.{decimals}f")+ sign = "-" if scaled < 0 else ""+ return (+ f"{sign}{match.group('prefix')}{absolute}{match.group('percent')}"+ )+++def _nice_scale(+ values: list[float],+ *,+ include_zero: bool,+ percent: bool = False,+) -> tuple[float, float, list[float]]:+ finite = [value for value in values if math.isfinite(value)]+ if not finite:+ finite = [0.0, 1.0]+ lo = min(finite)+ hi = max(finite)+ if include_zero:+ lo = min(lo, 0.0)+ hi = max(hi, 0.0)+ if percent:+ lo = min(lo, 0.0)+ hi = max(hi, 1.0)+ if math.isclose(lo, hi):+ delta = max(abs(lo) * 0.1, 1.0)+ lo -= delta+ hi += delta+ raw_step = (hi - lo) / 5.0+ magnitude = 10 ** math.floor(math.log10(raw_step))+ normalized = raw_step / magnitude+ nice = 1.0 if normalized <= 1 else 2.0 if normalized <= 2 else 2.5 if normalized <= 2.5 else 5.0 if normalized <= 5 else 10.0+ step = nice * magnitude+ nice_lo = math.floor(lo / step) * step+ nice_hi = math.ceil(hi / step) * step+ count = max(1, int(round((nice_hi - nice_lo) / step)))+ ticks = [nice_lo + idx * step for idx in range(count + 1)]+ return nice_lo, nice_hi, ticks+++def _sector_path(+ cx: float,+ cy: float,+ outer: float,+ start: float,+ end: float,+ inner: float,+) -> str:+ x1 = cx + math.cos(start) * outer+ y1 = cy + math.sin(start) * outer+ x2 = cx + math.cos(end) * outer+ y2 = cy + math.sin(end) * outer+ large = 1 if end - start > math.pi else 0+ if inner <= 0:+ return (+ f"M {_fmt(cx)} {_fmt(cy)} L {_fmt(x1)} {_fmt(y1)} "+ f"A {_fmt(outer)} {_fmt(outer)} 0 {large} 1 {_fmt(x2)} {_fmt(y2)} Z"+ )+ ix2 = cx + math.cos(end) * inner+ iy2 = cy + math.sin(end) * inner+ ix1 = cx + math.cos(start) * inner+ iy1 = cy + math.sin(start) * inner+ return (+ f"M {_fmt(x1)} {_fmt(y1)} A {_fmt(outer)} {_fmt(outer)} 0 {large} 1 {_fmt(x2)} {_fmt(y2)} "+ f"L {_fmt(ix2)} {_fmt(iy2)} A {_fmt(inner)} {_fmt(inner)} 0 {large} 0 {_fmt(ix1)} {_fmt(iy1)} Z"+ )+++def _full_ring_path(cx: float, cy: float, outer: float, inner: float) -> str:+ return (+ f"M {_fmt(cx + outer)} {_fmt(cy)} "+ f"A {_fmt(outer)} {_fmt(outer)} 0 1 1 {_fmt(cx - outer)} {_fmt(cy)} "+ f"A {_fmt(outer)} {_fmt(outer)} 0 1 1 {_fmt(cx + outer)} {_fmt(cy)} Z "+ f"M {_fmt(cx + inner)} {_fmt(cy)} "+ f"A {_fmt(inner)} {_fmt(inner)} 0 1 0 {_fmt(cx - inner)} {_fmt(cy)} "+ f"A {_fmt(inner)} {_fmt(inner)} 0 1 0 {_fmt(cx + inner)} {_fmt(cy)} Z"+ )+++def _complete_styles(+ styles: list[SeriesVisualStyle],+ count: int,+) -> list[SeriesVisualStyle]:+ result = list(styles[:count])+ while len(result) < count:+ color = _DEFAULT_COLORS[len(result) % len(_DEFAULT_COLORS)]+ result.append(+ SeriesVisualStyle(+ fill=color,+ stroke=color,+ marker_fill=color,+ marker_stroke=color,+ )+ )+ return result+++def _entry_text(value: Any) -> str:+ if isinstance(value, dict):+ return str(value.get("text") or "")+ return str(value or "")+++def _entry_value(value: Any, key: str) -> Any:+ return value.get(key) if isinstance(value, dict) else None+++def _entry_color(value: Any, default: str) -> str:+ color = _entry_value(value, "color")+ return str(color) if isinstance(color, str) and color.startswith("#") else default+++def _font_size(value: Any, default: float, bounds: _Rect) -> float:+ try:+ size = float(value)+ except (TypeError, ValueError, OverflowError):+ size = default+ return max(6.0, min(size, max(8.0, bounds.h * 0.18)))+++def _text(+ x: float,+ y: float,+ value: str,+ *,+ size: float,+ anchor: str = "start",+ fill: str = "#444444",+ weight: str | None = None,+) -> str:+ weight_attr = f' font-weight="{weight}"' if weight else ""+ return (+ f'<text x="{_fmt(x)}" y="{_fmt(y)}" text-anchor="{anchor}" '+ f'font-family="Arial" font-size="{_fmt(size)}" fill="{fill}"{weight_attr}>'+ f'{html.escape(str(value))}</text>'+ )+++def _map(value: float, lo: float, hi: float, out_lo: float, out_hi: float) -> float:+ if math.isclose(lo, hi):+ return (out_lo + out_hi) / 2+ return out_lo + (value - lo) * (out_hi - out_lo) / (hi - lo)+++def _points(points: list[tuple[float, float]]) -> str:+ return " ".join(f"{_fmt(x)},{_fmt(y)}" for x, y in points)+++def _format_number(value: float) -> str:+ if abs(value) >= 1_000_000:+ return f"{value / 1_000_000:.1f}M".replace(".0M", "M")+ if abs(value) >= 1_000:+ return f"{value / 1_000:.1f}K".replace(".0K", "K")+ if math.isclose(value, round(value)):+ return str(int(round(value)))+ return f"{value:.2f}".rstrip("0").rstrip(".")+++def _format_percent(value: float) -> str:+ percent = value * 100.0+ return f"{percent:.1f}%".replace(".0%", "%")+++def _contrast_color(color: str) -> str:+ token = color.lstrip("#")+ try:+ r, g, b = (int(token[idx:idx + 2], 16) for idx in (0, 2, 4))+ except (ValueError, TypeError):+ return "#FFFFFF"+ luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255.0+ return "#222222" if luminance > 0.62 else "#FFFFFF"+++def _fmt(value: float) -> str:+ if not math.isfinite(float(value)):+ return "0"+ rounded = round(float(value), 3)+ if rounded == 0:+ return "0"+ if rounded.is_integer():+ return str(int(rounded))+ return f"{rounded:.3f}".rstrip("0").rstrip(".")diff --git a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.pyindex e3de69f3..4a9ae1f0 100644--- a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py+++ b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py@@ -130,6 +130,7 @@ REL_TYPES = {"slideLayout": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout","slideMaster": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster","theme": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme",+ "tableStyles": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles","image": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image","media": "http://schemas.openxmlformats.org/officeDocument/2006/relationships/media",}@@ -156,6 +157,8 @@ class OoxmlPackage:self._layouts: dict[str, PartRef] = {}self._masters: dict[str, PartRef] = {}self._themes: dict[str, PartRef] = {}+ self._table_styles: PartRef | None = None+ self._table_styles_loaded = False# ------------------- context manager -------------------@@ -311,6 +314,32 @@ class OoxmlPackage:return cachedreturn None+ def resolve_table_styles(self) -> PartRef | None:+ """Return the presentation-level table style list, when usable.++ Table style definitions are optional and some producers emit only the+ built-in style id. A missing or malformed style part must therefore+ not prevent otherwise valid slides from being converted.+ """+ if self._table_styles_loaded:+ return self._table_styles+ self._table_styles_loaded = True++ target: str | None = None+ if self.presentation is not None:+ for info in self.presentation.rels.values():+ if info.get("type") == REL_TYPES["tableStyles"]:+ target = info.get("target")+ break+ if target is None:+ target = "ppt/tableStyles.xml"++ try:+ self._table_styles = self._load_part(target)+ except RuntimeError:+ self._table_styles = None+ return self._table_styles+# ------------------- public iteration -------------------def iter_slides(self) -> Iterator[SlideRef]:diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.pyindex 575a50c7..2cbb5270 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@@ -30,7 +30,9 @@ from xml.etree import ElementTree as ETfrom pptx_shapes import (CONNECTOR_PRESET_TYPES,+ NATIVE_FALLBACK_SHA256_ATTR,has_relationship_attributes,+ svg_native_fallback_markup_fingerprint,svg_text_fingerprint,)@@ -782,8 +784,12 @@ def _render_graphic_table(tbl = graphic_data.find("a:tbl", NS)if tbl is None:return "", []+ table_styles_part = ctx.pkg.resolve_table_styles()result = convert_tbl(tbl, node.xfrm, ctx.palette,+ table_styles=(+ table_styles_part.xml if table_styles_part is not None else None+ ),theme_fonts=ctx.theme_fonts,slide_number=ctx.slide_number,id_prefix=f"tbl{ctx.shape_seq[0]}",@@ -824,6 +830,7 @@ def _render_graphic_chart(node.xfrm,ctx.slide_part,ctx.pkg,+ ctx.palette,)native_attrs: list[str] = ['data-pptx-native-source="pptx"']if result.native_payload:@@ -849,6 +856,9 @@ def _render_graphic_chart(rendered = _render_graphic_preview(node, ctx)if rendered:native_attrs.append('data-pptx-visual-status="source-preview"')+ elif result.normalized_svg:+ rendered = result.normalized_svg+ native_attrs.append('data-pptx-visual-status="normalized"')else:native_attrs.extend(['data-pptx-visual-status="placeholder"',@@ -1134,6 +1144,18 @@ def _wrap_shape_group(attrs.append(f'data-ph-type="{_xml_escape(node.placeholder.type)}"')if extra_attrs:attrs.extend(extra_attrs)+ if any(+ attribute.split("=", 1)[0] == "data-pptx-native"+ for attribute in extra_attrs+ ):+ fallback_hash = svg_native_fallback_markup_fingerprint(+ inner,+ root_transform=transform,+ external_markup="".join(ctx.defs),+ )+ attrs.append(+ f'{NATIVE_FALLBACK_SHA256_ATTR}="{fallback_hash}"'+ )if transform:attrs.append(f'transform="{transform}"')return f"<g {' '.join(attrs)}>\n{inner}\n</g>"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.pyindex 47ccbe7c..312a72e7 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@@ -36,6 +36,7 @@ Cell painting order:from __future__ import annotations+import copyfrom dataclasses import dataclassfrom typing import Anyfrom xml.etree import ElementTree as ET@@ -49,11 +50,51 @@ from .emu_units import (hundredths_pt_to_px,ooxml_bool,)-from .fill_to_svg import resolve_fill+from .fill_to_svg import FillResult, resolve_fillfrom .ln_to_svg import resolve_strokefrom .txbody_to_svg import convert_txbody+BUILTIN_MEDIUM_STYLE_2_ACCENT_1 = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"++_BUILTIN_MEDIUM_STYLE_2_ACCENT_1_XML = ET.fromstring(+ f'''<a:tblStyle xmlns:a="{NS["a"]}"+ styleId="{BUILTIN_MEDIUM_STYLE_2_ACCENT_1}">+ <a:wholeTbl>+ <a:tcTxStyle>+ <a:fontRef idx="minor"><a:prstClr val="black"/></a:fontRef>+ <a:schemeClr val="dk1"/>+ </a:tcTxStyle>+ <a:tcStyle>+ <a:tcBdr>+ <a:left><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:left>+ <a:right><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:right>+ <a:top><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:top>+ <a:bottom><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:bottom>+ <a:insideH><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:insideH>+ <a:insideV><a:ln w="12700"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:insideV>+ </a:tcBdr>+ <a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="20000"/></a:schemeClr></a:solidFill></a:fill>+ </a:tcStyle>+ </a:wholeTbl>+ <a:band1H>+ <a:tcStyle><a:fill><a:solidFill><a:schemeClr val="accent1"><a:tint val="40000"/></a:schemeClr></a:solidFill></a:fill></a:tcStyle>+ </a:band1H>+ <a:band2H><a:tcStyle/></a:band2H>+ <a:firstRow>+ <a:tcTxStyle b="on">+ <a:fontRef idx="minor"><a:prstClr val="black"/></a:fontRef>+ <a:schemeClr val="lt1"/>+ </a:tcTxStyle>+ <a:tcStyle>+ <a:tcBdr><a:bottom><a:ln w="38100"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></a:bottom></a:tcBdr>+ <a:fill><a:solidFill><a:schemeClr val="accent1"/></a:solidFill></a:fill>+ </a:tcStyle>+ </a:firstRow>+ </a:tblStyle>'''+)++@dataclassclass TableResult:"""Composite render output plus optional native table metadata."""@@ -68,6 +109,155 @@ class TableResult:self.defs = []+@dataclass(frozen=True)+class _TableStyleContext:+ """Small, best-effort view of the table style regions we render."""++ style: ET.Element | None+ table_properties: ET.Element | None++ def regions_for_row(self, row_index: int) -> tuple[tuple[str, ET.Element], ...]:+ if self.style is None:+ return ()++ names: list[str] = []+ first_row = bool(+ self.table_properties is not None+ and ooxml_bool(self.table_properties.get("firstRow"))+ )+ if first_row and row_index == 0:+ names.append("firstRow")+ elif (+ self.table_properties is not None+ and ooxml_bool(self.table_properties.get("bandRow"))+ ):+ band_index = row_index - (1 if first_row else 0)+ names.append("band1H" if band_index % 2 == 0 else "band2H")+ names.append("wholeTbl")++ regions: list[tuple[str, ET.Element]] = []+ for name in names:+ region = self.style.find(f"a:{name}", NS)+ if region is not None:+ regions.append((name, region))+ return tuple(regions)+++def _normalize_table_style_id(value: str | None) -> str:+ return (value or "").strip().strip("{}").upper()+++def _resolve_table_style(+ tbl: ET.Element,+ table_styles: ET.Element | None,+) -> _TableStyleContext:+ tbl_pr = tbl.find("a:tblPr", NS)+ style_id = (+ tbl_pr.findtext("a:tableStyleId", default="", namespaces=NS).strip()+ if tbl_pr is not None else ""+ )+ if not style_id and table_styles is not None:+ style_id = table_styles.get("def", "").strip()+ normalized_id = _normalize_table_style_id(style_id)+ supported_id = _normalize_table_style_id(BUILTIN_MEDIUM_STYLE_2_ACCENT_1)++ # P1 deliberately supports one built-in family. Consuming an arbitrary+ # custom definition here would be asymmetric: native reconstruction keeps+ # only the style id and does not copy custom tableStyles.xml definitions.+ if normalized_id != supported_id:+ return _TableStyleContext(None, tbl_pr)++ if table_styles is not None and normalized_id:+ for candidate in table_styles.findall("a:tblStyle", NS):+ if _normalize_table_style_id(candidate.get("styleId")) == normalized_id:+ return _TableStyleContext(candidate, tbl_pr)++ return _TableStyleContext(_BUILTIN_MEDIUM_STYLE_2_ACCENT_1_XML, tbl_pr)+++def _effective_cell_fill(+ tc_pr: ET.Element | None,+ table_style: _TableStyleContext,+ row_index: int,+ palette: ColorPalette | None,+ *,+ id_prefix: str,+ id_seq: list[int],+) -> FillResult:+ """Resolve direct cell fill before row-region and whole-table defaults."""+ direct = resolve_fill(+ tc_pr, palette, id_prefix=id_prefix, id_seq=id_seq,+ )+ if direct.attrs or direct.defs:+ return direct++ for _name, region in table_style.regions_for_row(row_index):+ fill_parent = region.find("a:tcStyle/a:fill", NS)+ if fill_parent is None:+ continue+ inherited = resolve_fill(+ fill_parent, palette, id_prefix=id_prefix, id_seq=id_seq,+ )+ if inherited.attrs or inherited.defs:+ return inherited+ return direct+++def _table_text_run_props(+ table_style: _TableStyleContext,+ row_index: int,+ theme_fonts: dict[str, str],+) -> tuple[ET.Element, ...]:+ """Materialize table text-style regions as lowest-priority run defaults."""+ props: list[ET.Element] = []+ for _name, region in table_style.regions_for_row(row_index):+ tx_style = region.find("a:tcTxStyle", NS)+ if tx_style is None:+ continue+ run_props = _table_tx_style_run_props(tx_style, theme_fonts)+ if run_props is not None:+ props.append(run_props)+ return tuple(props)+++def _table_tx_style_run_props(+ tx_style: ET.Element,+ theme_fonts: dict[str, str],+) -> ET.Element | None:+ run_props = ET.Element(f"{{{NS['a']}}}rPr")+ for attr in ("b", "i"):+ value = tx_style.get(attr)+ if value is not None:+ run_props.set(attr, "1" if ooxml_bool(value) else "0")++ font_ref = tx_style.find("a:fontRef", NS)+ font_role = font_ref.get("idx") if font_ref is not None else None+ if font_role in {"major", "minor"}:+ prefix = "major" if font_role == "major" else "minor"+ latin = theme_fonts.get(f"{prefix}Latin")+ east_asia = theme_fonts.get(f"{prefix}EastAsia") or latin+ complex_script = theme_fonts.get(f"{prefix}ComplexScript") or latin+ for tag, typeface in (+ ("latin", latin),+ ("ea", east_asia),+ ("cs", complex_script),+ ):+ if typeface:+ ET.SubElement(+ run_props, f"{{{NS['a']}}}{tag}",+ {"typeface": typeface},+ )++ color = find_color_elem(tx_style)+ if color is not None:+ solid_fill = ET.SubElement(run_props, f"{{{NS['a']}}}solidFill")+ solid_fill.append(copy.deepcopy(color))++ if not run_props.attrib and not list(run_props):+ return None+ return run_props++# ---------------------------------------------------------------------------# Public entry# ---------------------------------------------------------------------------@@ -77,6 +267,7 @@ def convert_tbl(xfrm: Xfrm,palette: ColorPalette | None,*,+ table_styles: ET.Element | None = None,theme_fonts: dict[str, str] | None = None,slide_number: int | None = None,id_prefix: str = "tbl",@@ -93,6 +284,7 @@ def convert_tbl(rows = tbl.findall("a:tr", NS)if not rows:return TableResult()+ table_style = _resolve_table_style(tbl, table_styles)row_heights_px = [_row_height_px(r) for r in rows]# PowerPoint's tblGrid widths and tr heights together describe the@@ -156,8 +348,8 @@ def convert_tbl(rect_w = sum(col_widths[c:c + cell.col_span])rect_h = sum(row_heights[r:r + cell.row_span])tcPr = cell.element.find("a:tcPr", NS)- fill = resolve_fill(- tcPr, palette,+ fill = _effective_cell_fill(+ tcPr, table_style, r, palette,id_prefix=f"{id_prefix}fill",id_seq=grad_seq,)@@ -186,6 +378,9 @@ def convert_tbl(cell_xfrm = Xfrm(x=cell_x, y=cell_y, w=cell_w, h=cell_h)text_result = _convert_cell_text(tx_body, tcPr, cell_xfrm, palette, theme_fonts,+ fallback_run_props=_table_text_run_props(+ table_style, r, theme_fonts or {},+ ),slide_number=slide_number,id_prefix=f"{id_prefix}txt",id_seq=grad_seq,@@ -211,7 +406,8 @@ def convert_tbl(("a:lnL", cell_x, cell_y, cell_x, cell_y + cell_h),):line_xml = _border_line(- tcPr, tag, x1, y1, x2, y2, palette,+ tcPr, table_style, r, c, len(rows), len(col_widths), tag,+ x1, y1, x2, y2, palette,id_prefix=f"{id_prefix}stk", id_seq=marker_seq, defs=defs,)if line_xml:@@ -698,6 +894,7 @@ def _convert_cell_text(palette: ColorPalette | None,theme_fonts: dict[str, str] | None,*,+ fallback_run_props: tuple[ET.Element, ...],slide_number: int | None,id_prefix: str,id_seq: list[int] | None,@@ -717,6 +914,7 @@ def _convert_cell_text(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,@@ -743,6 +941,11 @@ def _tcPr_inset_overrides(tcPr: ET.Element | None) -> dict[str, str]:def _border_line(tcPr: ET.Element | None,+ table_style: _TableStyleContext,+ row_index: int,+ col_index: int,+ row_count: int,+ col_count: int,tag: str,x1: float, y1: float, x2: float, y2: float,palette: ColorPalette | None,@@ -753,11 +956,69 @@ def _border_line() -> str:"""Emit a single border <line> for a given cell side, or empty string whenthat side is explicitly noFill / not specified."""- if tcPr is None:- return ""- ln = tcPr.find(tag, NS)- if ln is None:+ ln = tcPr.find(tag, NS) if tcPr is not None else None+ if ln is not None:+ return _line_element_to_svg(+ ln, x1, y1, x2, y2, palette,+ id_prefix=id_prefix, id_seq=id_seq, defs=defs,+ )++ # Draw inherited shared edges once, from the upper/left cell. This keeps+ # a specific firstRow bottom border from being painted over by the next+ # row's whole-table top border. A direct border above still wins because+ # it is handled before this de-duplication gate.+ if (tag == "a:lnT" and row_index > 0) or (+ tag == "a:lnL" and col_index > 0+ ):return ""++ for region_name, region in table_style.regions_for_row(row_index):+ for border_name in _table_style_border_names(+ region_name, row_index, col_index, row_count, col_count, tag,+ ):+ ln = region.find(+ f"a:tcStyle/a:tcBdr/a:{border_name}/a:ln", NS,+ )+ if ln is not None:+ return _line_element_to_svg(+ ln, x1, y1, x2, y2, palette,+ id_prefix=id_prefix, id_seq=id_seq, defs=defs,+ )+ return ""+++def _table_style_border_names(+ region_name: str,+ row_index: int,+ col_index: int,+ row_count: int,+ col_count: int,+ tag: str,+) -> tuple[str, ...]:+ side_names = {+ "a:lnT": ("top", "insideH", row_index > 0),+ "a:lnR": ("right", "insideV", col_index < col_count - 1),+ "a:lnB": ("bottom", "insideH", row_index < row_count - 1),+ "a:lnL": ("left", "insideV", col_index > 0),+ }+ side, inside, is_internal = side_names[tag]+ if region_name == "wholeTbl" and is_internal:+ return inside, side+ return side, inside+++def _line_element_to_svg(+ ln: ET.Element,+ x1: float,+ y1: float,+ x2: float,+ y2: float,+ palette: ColorPalette | None,+ *,+ id_prefix: str,+ id_seq: list[int],+ defs: list[str],+) -> str:# Skip explicit no-line.if ln.find("a:noFill", NS) is not None:return ""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.pyindex f342deef..16530e16 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@@ -107,6 +107,7 @@ def convert_txbody(default_fill: str = DEFAULT_FILL_HEX,default_font_size_px: float = DEFAULT_FONT_SIZE_PX,fallback_lst_styles: tuple[ET.Element, ...] = (),+ fallback_run_props: tuple[ET.Element, ...] = (),id_prefix: str = "txt",id_seq: list[int] | None = None,) -> TextResult:@@ -119,6 +120,7 @@ def convert_txbody(tx_body, palette, theme_fonts or {}, default_fill=default_fill,default_font_size_px=default_font_size_px,fallback_lst_styles=fallback_lst_styles,+ fallback_run_props=fallback_run_props,slide_number=slide_number, id_prefix=id_prefix, id_seq=id_seq,)if not paragraphs or not _has_visible_text(paragraphs):@@ -193,6 +195,7 @@ def convert_vertical_txbody(default_fill: str = DEFAULT_FILL_HEX,default_font_size_px: float = DEFAULT_FONT_SIZE_PX,fallback_lst_styles: tuple[ET.Element, ...] = (),+ fallback_run_props: tuple[ET.Element, ...] = (),id_prefix: str = "txt",id_seq: list[int] | None = None,) -> TextResult:@@ -210,6 +213,7 @@ def convert_vertical_txbody(tx_body, palette, theme_fonts or {}, default_fill=default_fill,default_font_size_px=default_font_size_px,fallback_lst_styles=fallback_lst_styles,+ fallback_run_props=fallback_run_props,slide_number=slide_number, id_prefix=id_prefix, id_seq=id_seq,)runs = [@@ -344,6 +348,7 @@ def _parse_paragraphs(default_fill: str = DEFAULT_FILL_HEX,default_font_size_px: float = DEFAULT_FONT_SIZE_PX,fallback_lst_styles: tuple[ET.Element, ...] = (),+ fallback_run_props: tuple[ET.Element, ...] = (),slide_number: int | None = None,id_prefix: str = "txt",id_seq: list[int] | None = None,@@ -361,6 +366,7 @@ def _parse_paragraphs(para = _parse_paragraph(p_elem, palette, theme_fonts, autonum_state,lst_styles=lst_styles,+ fallback_run_props=fallback_run_props,default_fill=default_fill,default_font_size_px=default_font_size_px,slide_number=slide_number,@@ -378,6 +384,7 @@ def _parse_paragraph(autonum_state: dict[int, int],*,lst_styles: tuple[ET.Element, ...] = (),+ fallback_run_props: tuple[ET.Element, ...] = (),default_fill: str = DEFAULT_FILL_HEX,default_font_size_px: float = DEFAULT_FONT_SIZE_PX,slide_number: int | None = None,@@ -422,6 +429,7 @@ def _parse_paragraph(text, rpr, end_rpr, palette, theme_fonts,def_rpr=def_rpr,list_def_rpr=list_def_rpr,+ fallback_run_props=fallback_run_props,default_fill=default_fill,default_font_size_px=default_font_size_px,id_prefix=id_prefix, id_seq=id_seq,@@ -449,6 +457,7 @@ def _parse_paragraph(text, rpr, end_rpr, palette, theme_fonts,def_rpr=def_rpr,list_def_rpr=list_def_rpr,+ fallback_run_props=fallback_run_props,default_fill=default_fill,default_font_size_px=default_font_size_px,id_prefix=id_prefix, id_seq=id_seq,@@ -467,13 +476,16 @@ def _build_run(*,def_rpr: ET.Element | None = None,list_def_rpr: ET.Element | None = None,+ fallback_run_props: tuple[ET.Element, ...] = (),default_fill: str = DEFAULT_FILL_HEX,default_font_size_px: float = DEFAULT_FONT_SIZE_PX,id_prefix: str = "txt",id_seq: list[int] | None = None,) -> TextRun:"""Resolve a single <a:r> run from its rPr and fallback run properties."""- style_chain = (rpr, def_rpr, list_def_rpr, end_rpr)+ style_chain = (+ rpr, def_rpr, list_def_rpr, end_rpr,+ ) + fallback_run_props# font-size: rPr > pPr/defRPr > lstStyle/lvlNpPr/defRPr > endParaRPr > defaultsz = _attr_chain(style_chain, "sz")font_size_px = hundredths_pt_to_px(sz, default_font_size_px)diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex b5cd53b7..53487425 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -1649,6 +1649,7 @@ class SVGQualityChecker:warnings = _validate_native_object_marker_with_warnings(marker,ancestors=ancestors_tuple,+ document_root=root,)except RuntimeError as exc:result['errors'].append(@@ -1673,6 +1674,7 @@ class SVGQualityChecker:for warning in _native_object_marker_warnings(marker,ancestors=ancestors_tuple,+ document_root=root,):result['warnings'].append(f"data-pptx-native marker {marker_id}: {warning}"diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex 0be8588f..1a969d47 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -45,7 +45,11 @@ from .elements import (convert_text, convert_image, convert_nested_svg,)from ..animation_config import is_chrome_id-from ..native_objects import convert_native_object, native_marker_transform+from ..native_objects import (+ convert_native_object,+ native_marker_transform,+ snapshot_native_fallback_freshness,+)from ..semantic_markers import is_static_page_frame@@ -1078,6 +1082,8 @@ def convert_svg_to_slide_shapes()_mark_unchanged_txbody_groups(root)_mark_unchanged_preset_previews(root)+ if native_objects:+ snapshot_native_fallback_freshness(root)trace_events: list[dict[str, Any]] | None = [] if trace_out is not None else Nonetrace_steps: list[dict[str, Any]] = []diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.pyindex 9d5a2a7f..c2b8f310 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/__init__.py@@ -27,6 +27,12 @@ from .chartex import (_chart_ex_style_xml,_chart_ex_xml,)+from .fallback_hash import (+ native_fallback_contract_warnings,+ require_fresh_native_fallback,+ snapshot_native_fallback_freshness,+ stamp_native_fallback_baseline,+)from .marker_common import (CHART_CONTENT_TYPE,CHARTEX_CONTENT_TYPE,@@ -60,6 +66,8 @@ __all__ = ["convert_native_object","native_object_marker_warnings","native_marker_transform",+ "snapshot_native_fallback_freshness",+ "stamp_native_fallback_baseline","validate_native_object_marker","validate_native_object_marker_with_warnings",]@@ -102,7 +110,7 @@ def _build_native_chart(elem: ET.Element, ctx: ConvertContext, payload: dict[strcolors_name,)ctx.package_files[style_part] = _chart_ex_style_xml()- ctx.package_files[colors_part] = _chart_ex_colors_xml()+ ctx.package_files[colors_part] = _chart_ex_colors_xml(payload)ctx.package_files[workbook_part] = _minimal_chart_ex_workbook(chart_data)ctx.content_type_overrides[chart_part] = CHARTEX_CONTENT_TYPEctx.content_type_overrides[style_part] = CHART_STYLE_CONTENT_TYPE@@ -171,6 +179,7 @@ def _validate_native_object_marker_payload(validate_chrome: bool = True,ctx: ConvertContext | None = None,ancestors: tuple[ET.Element, ...] = (),+ require_fresh_fallback: bool = False,) -> tuple[str, dict[str, Any], list[list[Any]] | None]:kind = (elem.get("data-pptx-native") or "").strip().lower()if not kind:@@ -183,6 +192,8 @@ def _validate_native_object_marker_payload(if _local_tag(elem) != "g":raise RuntimeError("Native PPTX table/chart markers must be <g> elements")native_marker_transform(elem.get("transform"))+ if require_fresh_fallback:+ require_fresh_native_fallback(elem, use_runtime_snapshot=True)payload = _load_payload(elem, kind)bounds_ctx = ctx or _native_marker_validation_context(elem, ancestors)@@ -222,26 +233,39 @@ def validate_native_object_marker_with_warnings(elem: ET.Element,*,ancestors: tuple[ET.Element, ...] = (),+ document_root: ET.Element | None = None,) -> list[str]:"""Validate a data-pptx-native marker and return non-fatal warnings."""kind, payload, table_rows = _validate_native_object_marker_payload(elem,ancestors=ancestors,)+ warnings = (+ native_fallback_contract_warnings(+ elem,+ document_root=document_root,+ )+ if kind else []+ )if kind == "table" and table_rows is not None:- return _native_table_warnings(elem, table_rows)- if kind == "chart":- return _native_chart_chrome_warnings(elem, payload)- return []+ warnings.extend(_native_table_warnings(elem, table_rows))+ elif kind == "chart":+ warnings.extend(_native_chart_chrome_warnings(elem, payload))+ return warningsdef native_object_marker_warnings(elem: ET.Element,*,ancestors: tuple[ET.Element, ...] = (),+ document_root: ET.Element | None = None,) -> list[str]:"""Return non-fatal warnings for a data-pptx-native marker."""- return validate_native_object_marker_with_warnings(elem, ancestors=ancestors)+ return validate_native_object_marker_with_warnings(+ elem,+ ancestors=ancestors,+ document_root=document_root,+ )def convert_native_object(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:@@ -254,11 +278,20 @@ def convert_native_object(elem: ET.Element, ctx: ConvertContext) -> ShapeResultelem,validate_chrome=False,ctx=ctx,+ require_fresh_fallback=True,)+ marker_id = elem.get("id") or "<unnamed>"+ for warning in native_fallback_contract_warnings(+ elem,+ use_runtime_snapshot=True,+ ):+ print(+ f" Warning: data-pptx-native marker {marker_id}: {warning}",+ file=sys.stderr,+ )if kind == "table":return _build_native_table(elem, ctx, payload)payload, warnings = _native_chart_export_payload(elem, payload)- marker_id = elem.get("id") or "<unnamed>"for warning in warnings:print(f" Warning: data-pptx-native marker {marker_id}: {warning}",diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chartex.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chartex.pyindex 09234c88..e0577d88 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chartex.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chartex.py@@ -10,8 +10,10 @@ from .marker_common import (CHART_COLOR_STYLE_REL_TYPE,CHART_STYLE_REL_TYPE,PACKAGE_REL_TYPE,+ _clean_hex,_compact_key,_excel_col,+ _first_present,)@@ -240,11 +242,31 @@ def _chart_ex_style_xml() -> bytes:return b'''<cs:chartStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" id="410"><cs:axisTitle><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="bg1"><a:lumMod val="65000"/></a:schemeClr></a:solidFill><a:ln w="19050"><a:solidFill><a:schemeClr val="bg1"/></a:solidFill></a:ln></cs:spPr><cs:defRPr sz="1197"/></cs:axisTitle><cs:categoryAxis><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr><cs:defRPr sz="1197"/></cs:categoryAxis><cs:chartArea mods="allowNoFillOverride allowNoLineOverride"><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="bg1"/></a:solidFill><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr><cs:defRPr sz="1330"/></cs:chartArea><cs:dataLabel><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="lt1"/></cs:fontRef><cs:defRPr sz="1197"/></cs:dataLabel><cs:dataLabelCallout><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="dk1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="lt1"/></a:solidFill><a:ln><a:solidFill><a:schemeClr val="dk1"><a:lumMod val="25000"/><a:lumOff val="75000"/></a:schemeClr></a:solidFill></a:ln></cs:spPr><cs:defRPr sz="1197"/><cs:bodyPr rot="0" spcFirstLastPara="1" vertOverflow="clip" horzOverflow="clip" vert="horz" wrap="square" lIns="36576" tIns="18288" rIns="36576" bIns="18288" anchor="ctr" anchorCtr="1"><a:spAutoFit/></cs:bodyPr></cs:dataLabelCallout><cs:dataPoint><cs:lnRef idx="0"/><cs:fillRef idx="0"><cs:styleClr val="auto"/></cs:fillRef><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:ln w="19050"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></cs:spPr></cs:dataPoint><cs:dataPoint3D><cs:lnRef idx="0"/><cs:fillRef idx="0"><cs:styleClr val="auto"/></cs:fillRef><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="phClr"/></a:solidFill></cs:spPr></cs:dataPoint3D><cs:dataPointLine><cs:lnRef idx="0"><cs:styleClr val="auto"/></cs:lnRef><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:round/></a:ln></cs:spPr></cs:dataPointLine><cs:dataPointMarker><cs:lnRef idx="0"/><cs:fillRef idx="0"><cs:styleClr val="auto"/></cs:fillRef><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:ln w="9525"><a:solidFill><a:schemeClr val="lt1"/></a:solidFill></a:ln></cs:spPr></cs:dataPointMarker><cs:dataPointMarkerLayout symbol="circle" size="5"/><cs:dataPointWireframe><cs:lnRef idx="0"><cs:styleClr val="auto"/></cs:lnRef><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:round/></a:ln></cs:spPr></cs:dataPointWireframe><cs:dataTable><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:spPr><a:ln w="9525"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill></a:ln></cs:spPr><cs:defRPr sz="1197"/></cs:dataTable><cs:downBar><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="dk1"/></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="dk1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></a:solidFill><a:ln w="9525"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></a:solidFill></a:ln></cs:spPr></cs:downBar><cs:dropLine><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="35000"/><a:lumOff val="65000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr></cs:dropLine><cs:errorBar><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr></cs:errorBar><cs:floor><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef></cs:floor><cs:gridlineMajor><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr></cs:gridlineMajor><cs:gridlineMinor><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr></cs:gridlineMinor><cs:hiLoLine><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="75000"/><a:lumOff val="25000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr></cs:hiLoLine><cs:leaderLine><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="35000"/><a:lumOff val="65000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr></cs:leaderLine><cs:legend><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:defRPr sz="1197"/></cs:legend><cs:plotArea mods="allowNoFillOverride allowNoLineOverride"><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef></cs:plotArea><cs:plotArea3D mods="allowNoFillOverride allowNoLineOverride"><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef></cs:plotArea3D><cs:seriesAxis><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill><a:round/></a:ln></cs:spPr><cs:defRPr sz="1197"/></cs:seriesAxis><cs:seriesLine><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="9525" cap="flat"><a:solidFill><a:srgbClr val="D9D9D9"/></a:solidFill><a:round/></a:ln></cs:spPr></cs:seriesLine><cs:title><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:defRPr sz="1862"/></cs:title><cs:trendline><cs:lnRef idx="0"><cs:styleClr val="auto"/></cs:lnRef><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef><cs:spPr><a:ln w="19050" cap="rnd"><a:solidFill><a:schemeClr val="phClr"/></a:solidFill><a:prstDash val="sysDash"/></a:ln></cs:spPr></cs:trendline><cs:trendlineLabel><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:defRPr sz="1197"/></cs:trendlineLabel><cs:upBar><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="dk1"/></cs:fontRef><cs:spPr><a:solidFill><a:schemeClr val="lt1"/></a:solidFill><a:ln w="9525"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="15000"/><a:lumOff val="85000"/></a:schemeClr></a:solidFill></a:ln></cs:spPr></cs:upBar><cs:valueAxis><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"><a:lumMod val="65000"/><a:lumOff val="35000"/></a:schemeClr></cs:fontRef><cs:defRPr sz="1197"/></cs:valueAxis><cs:wall><cs:lnRef idx="0"/><cs:fillRef idx="0"/><cs:effectRef idx="0"/><cs:fontRef idx="minor"><a:schemeClr val="tx1"/></cs:fontRef></cs:wall></cs:chartStyle>'''-def _chart_ex_colors_xml() -> bytes:- return b'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+def _chart_ex_colors_xml(payload: dict[str, Any]) -> bytes:+ """Return a ChartEx color style that consumes the marker palette when present."""+ style = payload.get("style") if isinstance(payload.get("style"), dict) else {}+ raw_colors = _first_present(style.get("colors"), payload.get("colors"))+ colors = (+ [_clean_hex(color, "#4472C4") for color in raw_colors]+ if isinstance(raw_colors, list)+ else []+ )+ if not colors:+ return b'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cs:colorStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle"xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"meth="cycle" id="10"><a:schemeClr val="accent1"/><a:schemeClr val="accent2"/><a:schemeClr val="accent3"/><a:schemeClr val="accent4"/><a:schemeClr val="accent5"/><a:schemeClr val="accent6"/></cs:colorStyle>'''+ color_entries = "".join(+ f'<a:srgbClr val="{color}"/>'+ for color in colors+ )+ xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>+<cs:colorStyle xmlns:cs="http://schemas.microsoft.com/office/drawing/2012/chartStyle"+ xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"+ meth="cycle" id="10">+{color_entries}+</cs:colorStyle>'''+ return xml.encode("utf-8")diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.pynew file mode 100644index 00000000..04b19251--- /dev/null+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/fallback_hash.py@@ -0,0 +1,154 @@+"""Visible-fallback fingerprint contract for native chart/table markers."""++from __future__ import annotations++import re+import secrets+from xml.etree import ElementTree as ET++from pptx_shapes import (+ NATIVE_FALLBACK_SHA256_ATTR,+ svg_native_fallback_fingerprint,+)+++NATIVE_FALLBACK_RUNTIME_ATTR = "data-pptx-runtime-fallback-unchanged"+_NATIVE_FALLBACK_RUNTIME_TOKEN_ATTR = "data-pptx-runtime-fallback-token"+_SHA256_RE = re.compile(r"^[0-9a-fA-F]{64}$")+_RUNTIME_TOKEN = secrets.token_hex(16)+++def stamp_native_fallback_baseline(+ elem: ET.Element,+ *,+ document_root: ET.Element | None = None,+) -> str:+ """Record the current canonical visible-subtree hash on one marker."""+ digest = svg_native_fallback_fingerprint(+ elem,+ document_root=document_root,+ )+ elem.set(NATIVE_FALLBACK_SHA256_ATTR, digest)+ elem.attrib.pop(NATIVE_FALLBACK_RUNTIME_ATTR, None)+ elem.attrib.pop(_NATIVE_FALLBACK_RUNTIME_TOKEN_ATTR, None)+ return digest+++def snapshot_native_fallback_freshness(root: ET.Element) -> None:+ """Snapshot raw marker freshness before exporter preprocessing mutates SVG."""+ for elem in root.iter():+ if elem.tag.rsplit("}", 1)[-1] == "metadata":+ continue+ if not (elem.get("data-pptx-native") or "").strip():+ continue+ expected, invalid = _expected_native_fallback_hash(elem)+ if invalid:+ elem.set(NATIVE_FALLBACK_RUNTIME_ATTR, "invalid")+ elem.set(_NATIVE_FALLBACK_RUNTIME_TOKEN_ATTR, _RUNTIME_TOKEN)+ elif expected is None:+ elem.attrib.pop(NATIVE_FALLBACK_RUNTIME_ATTR, None)+ elem.attrib.pop(_NATIVE_FALLBACK_RUNTIME_TOKEN_ATTR, None)+ else:+ actual = svg_native_fallback_fingerprint(+ elem,+ document_root=root,+ )+ elem.set(+ NATIVE_FALLBACK_RUNTIME_ATTR,+ "1" if actual == expected else "0",+ )+ elem.set(_NATIVE_FALLBACK_RUNTIME_TOKEN_ATTR, _RUNTIME_TOKEN)+++def native_fallback_contract_warnings(+ elem: ET.Element,+ *,+ use_runtime_snapshot: bool = False,+ document_root: ET.Element | None = None,+) -> list[str]:+ """Return non-blocking diagnostics for default/checker compatibility."""+ expected, invalid = _expected_native_fallback_hash(elem)+ if invalid:+ return [+ f"{NATIVE_FALLBACK_SHA256_ATTR} must be a 64-digit SHA-256; "+ "default SVG fallback export remains available, but "+ "--native-objects will fail"+ ]+ if expected is None:+ return [+ f"has no {NATIVE_FALLBACK_SHA256_ATTR} baseline; legacy marker "+ "remains native-compatible, but stale fallback edits cannot be detected"+ ]+ if _native_fallback_is_fresh(+ elem,+ expected,+ use_runtime_snapshot=use_runtime_snapshot,+ document_root=document_root,+ ):+ return []+ return [+ "visible SVG fallback differs from its recorded baseline; default "+ "fallback export remains available, but --native-objects will fail"+ ]+++def require_fresh_native_fallback(+ elem: ET.Element,+ *,+ use_runtime_snapshot: bool = False,+ document_root: ET.Element | None = None,+) -> None:+ """Fail the editable replacement route when a recorded fallback is stale."""+ expected, invalid = _expected_native_fallback_hash(elem)+ if invalid:+ raise RuntimeError(+ f"{NATIVE_FALLBACK_SHA256_ATTR} must be a 64-digit SHA-256"+ )+ if expected is None:+ return+ if _native_fallback_is_fresh(+ elem,+ expected,+ use_runtime_snapshot=use_runtime_snapshot,+ document_root=document_root,+ ):+ return+ raise RuntimeError(+ "Visible native-object SVG fallback was edited after its baseline was "+ "recorded; --native-objects stopped to avoid discarding the SVG edit. "+ "Use the default fallback export, or deliberately update the native "+ "metadata and baseline together"+ )+++def _expected_native_fallback_hash(+ elem: ET.Element,+) -> tuple[str | None, bool]:+ raw = elem.get(NATIVE_FALLBACK_SHA256_ATTR)+ if raw is None:+ return None, False+ if raw != raw.strip() or _SHA256_RE.fullmatch(raw) is None:+ return None, True+ return raw.lower(), False+++def _native_fallback_is_fresh(+ elem: ET.Element,+ expected: str,+ *,+ use_runtime_snapshot: bool,+ document_root: ET.Element | None,+) -> bool:+ if (+ use_runtime_snapshot+ and elem.get(_NATIVE_FALLBACK_RUNTIME_TOKEN_ATTR) == _RUNTIME_TOKEN+ ):+ snapshot = elem.get(NATIVE_FALLBACK_RUNTIME_ATTR)+ if snapshot == "1":+ return True+ if snapshot in {"0", "invalid"}:+ return False+ return svg_native_fallback_fingerprint(+ elem,+ document_root=document_root,+ ) == expecteddiff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.pyindex 0ede1c47..05dbc3ed 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_status.py@@ -5,7 +5,7 @@ from __future__ import annotationsfrom xml.etree import ElementTree as ET-VISUAL_STATUSES = frozenset({"source-preview", "placeholder"})+VISUAL_STATUSES = frozenset({"source-preview", "normalized", "placeholder"})ROUTE_STATUSES = frozenset({"reconstruction-only"})