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(hyperlinks): add native link round-trip support
hugohe309839bd8ca31
diff --git a/skills/ppt-master/scripts/hyperlink_contract.py b/skills/ppt-master/scripts/hyperlink_contract.pynew file mode 100644index 00000000..07f67bc0--- /dev/null+++ b/skills/ppt-master/scripts/hyperlink_contract.py@@ -0,0 +1,399 @@+#!/usr/bin/env python3+"""+PPT Master - Hyperlink Contract++Parse and validate the shared SVG hyperlink surface used by quality checks,+SVG-to-PPTX export, and PPTX-to-SVG round-trip conversion.++Usage:+ from hyperlink_contract import parse_hyperlink_target++Examples:+ parse_hyperlink_target("https://example.com")+ parse_hyperlink_target("#slide-3", slide_count=8)++Dependencies:+ None (standard library only).+"""++from __future__ import annotations++import re+from dataclasses import dataclass+from xml.etree import ElementTree as ET+++SVG_NS = "http://www.w3.org/2000/svg"+XLINK_NS = "http://www.w3.org/1999/xlink"+HYPERLINK_REL_TYPE = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/"+ "hyperlink"+)+SLIDE_REL_TYPE = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide"+)+SLIDE_JUMP_ACTION = "ppaction://hlinksldjump"+SHAPE_HYPERLINK_ATTR = "data-pptx-shape-hyperlink"++_SLIDE_TARGET_RE = re.compile(r"#slide-([1-9][0-9]*)")+_URI_SCHEME_RE = re.compile(r"([A-Za-z][A-Za-z0-9+.-]*):")+_FORBIDDEN_EXTERNAL_SCHEMES = frozenset({+ "data",+ "file",+ "javascript",+ "vbscript",+})+_NON_OUTPUT_ANCESTORS = frozenset({+ "defs",+ "desc",+ "metadata",+ "style",+ "symbol",+ "title",+})+_INLINE_CONTAINER_TAGS = frozenset({"text", "tspan"})+_INLINE_CONTENT_TAGS = frozenset({"tspan"})+_UNSUPPORTED_LINK_BEHAVIOR_ATTRIBUTES = frozenset({+ "download",+ "hreflang",+ "ping",+ "referrerpolicy",+ "rel",+ "target",+ "type",+})+++class HyperlinkContractError(ValueError):+ """Raised when one hyperlink cannot be represented faithfully in PPTX."""+++@dataclass(frozen=True)+class HyperlinkTarget:+ """One normalized hyperlink destination."""++ raw: str+ kind: str+ slide_number: int | None = None+++def _local_name(elem: ET.Element) -> str:+ if not isinstance(elem.tag, str):+ return str(elem.tag)+ return elem.tag.rsplit("}", 1)[-1]+++def parse_hyperlink_target(+ raw: str,+ *,+ slide_count: int | None = None,+) -> HyperlinkTarget:+ """Parse one canonical SVG hyperlink target.++ Same-deck jumps use ``#slide-N``. External destinations must be absolute+ URIs with an explicit scheme. Local files, script/data URLs, relative+ paths, arbitrary SVG fragments, whitespace, and control characters fail+ closed instead of being silently dropped during export.+ """+ if not isinstance(raw, str):+ raise HyperlinkContractError("hyperlink target must be a string")+ if not raw:+ raise HyperlinkContractError("hyperlink target must not be empty")+ if raw != raw.strip():+ raise HyperlinkContractError(+ "hyperlink target must not contain leading or trailing whitespace"+ )+ if any(ord(char) < 0x21 or ord(char) == 0x7F for char in raw):+ raise HyperlinkContractError(+ "hyperlink target must not contain whitespace or control characters; "+ "percent-encode URI spaces"+ )+ if "\\" in raw:+ raise HyperlinkContractError(+ "hyperlink target must use URI syntax, not a filesystem path"+ )++ slide_match = _SLIDE_TARGET_RE.fullmatch(raw)+ if slide_match is not None:+ slide_number = int(slide_match.group(1))+ if slide_count is not None and slide_number > slide_count:+ raise HyperlinkContractError(+ f"slide jump {raw!r} exceeds the {slide_count}-slide deck"+ )+ return HyperlinkTarget(+ raw=f"#slide-{slide_number}",+ kind="slide",+ slide_number=slide_number,+ )++ if raw.startswith("#"):+ raise HyperlinkContractError(+ "same-deck hyperlinks must use the exact #slide-N form"+ )+ scheme_match = _URI_SCHEME_RE.match(raw)+ if scheme_match is None:+ raise HyperlinkContractError(+ "external hyperlinks must be absolute URIs with an explicit scheme"+ )+ scheme = scheme_match.group(1).lower()+ if scheme in _FORBIDDEN_EXTERNAL_SCHEMES:+ raise HyperlinkContractError(+ f"external hyperlink scheme {scheme!r} is not allowed"+ )+ return HyperlinkTarget(raw=raw, kind="external")+++def svg_hyperlink_href(elem: ET.Element) -> str:+ """Return the sole href value from one SVG ``<a>`` element."""+ if _local_name(elem) != "a" or elem.tag != f"{{{SVG_NS}}}a":+ raise HyperlinkContractError("hyperlink carrier must be an SVG <a>")+ href = elem.get("href")+ xlink_href = elem.get(f"{{{XLINK_NS}}}href")+ if href is not None and xlink_href is not None:+ raise HyperlinkContractError(+ "SVG <a> must not declare both href and xlink:href"+ )+ value = href if href is not None else xlink_href+ if value is None:+ raise HyperlinkContractError("SVG <a> must declare href")+ return value+++def project_hyperlink_errors(+ root: ET.Element,+ *,+ slide_count: int | None = None,+) -> list[str]:+ """Return fail-closed diagnostics for every SVG hyperlink carrier."""+ errors: list[str] = []+ parent_by_id = {+ id(child): parent+ for parent in root.iter()+ for child in list(parent)+ }+ anchors = [+ elem for elem in root.iter()+ if _local_name(elem) == "a"+ ]+ for index, anchor in enumerate(anchors, 1):+ label = anchor.get("id") or f"anchor {index}"+ if anchor.tag != f"{{{SVG_NS}}}a":+ errors.append(f"{label}: hyperlink carrier must be an SVG <a>")+ continue+ try:+ href = svg_hyperlink_href(anchor)+ parse_hyperlink_target(href, slide_count=slide_count)+ except HyperlinkContractError as exc:+ errors.append(f"{label}: {exc}")++ unsupported_attrs = sorted(+ name+ for name in anchor.attrib+ if name.rsplit("}", 1)[-1].lower()+ in _UNSUPPORTED_LINK_BEHAVIOR_ATTRIBUTES+ )+ if unsupported_attrs:+ errors.append(+ f"{label}: unsupported link behavior attribute(s): "+ + ", ".join(unsupported_attrs)+ )++ ancestors: list[ET.Element] = []+ current = parent_by_id.get(id(anchor))+ while current is not None:+ ancestors.append(current)+ current = parent_by_id.get(id(current))+ ancestor_tags = [_local_name(elem) for elem in ancestors]+ if "a" in ancestor_tags:+ errors.append(f"{label}: nested SVG <a> elements are not supported")+ hidden_ancestor = next(+ (tag for tag in ancestor_tags if tag in _NON_OUTPUT_ANCESTORS),+ None,+ )+ if hidden_ancestor is not None:+ errors.append(+ f"{label}: hyperlink cannot appear inside non-output "+ f"<{hidden_ancestor}> content"+ )+ replacement_ancestor = next(+ (+ elem+ for elem in ancestors+ if elem.get("data-pptx-replace-with") is not None+ or elem.get("data-pptx-part") == "geometry-detail"+ ),+ None,+ )+ if replacement_ancestor is not None:+ errors.append(+ f"{label}: hyperlink cannot appear inside content replaced "+ "or skipped during native export"+ )++ inline = any(tag in _INLINE_CONTAINER_TAGS for tag in ancestor_tags)+ children = [+ child for child in list(anchor)+ if _local_name(child) not in _NON_OUTPUT_ANCESTORS+ ]+ if inline:+ if any(_local_name(child) not in _INLINE_CONTENT_TAGS for child in children):+ errors.append(+ f"{label}: inline hyperlink content may contain only <tspan>"+ )+ positioned = [+ elem+ for elem in anchor.iter()+ if any(elem.get(name) is not None for name in ("x", "y", "dx", "dy"))+ ]+ if positioned:+ errors.append(+ f"{label}: inline hyperlink cannot own x/y/dx/dy; "+ "put line positioning on an enclosing <tspan>"+ )+ direct_parent = parent_by_id.get(id(anchor))+ if (+ direct_parent is not None+ and _local_name(direct_parent) == "text"+ and (+ direct_parent.get("data-paragraph-line-height") is not None+ or any(+ _local_name(sibling) == "tspan"+ and any(+ sibling.get(name) is not None+ for name in ("x", "y", "dx", "dy")+ )+ for sibling in list(direct_parent)+ )+ )+ ):+ errors.append(+ f"{label}: multi-line hyperlinks must be nested inside "+ "the owning line <tspan>"+ )+ visible_text = "".join(anchor.itertext())+ if not visible_text.strip():+ errors.append(f"{label}: inline hyperlink must contain visible text")+ else:+ if anchor.text and anchor.text.strip():+ errors.append(+ f"{label}: shape hyperlink cannot contain direct text; "+ "wrap text in <text>"+ )+ visible_children = [+ child for child in children+ if child.get("data-pptx-part") != "geometry-detail"+ ]+ if not visible_children:+ errors.append(+ f"{label}: shape hyperlink must wrap at least one visual element"+ )+ if any(_local_name(child) == "tspan" for child in children):+ errors.append(+ f"{label}: shape hyperlink cannot contain a bare <tspan>; "+ "wrap inline runs in <text>"+ )++ for index, carrier in enumerate(+ (+ elem+ for elem in root.iter()+ if elem.get(SHAPE_HYPERLINK_ATTR) is not None+ ),+ 1,+ ):+ label = carrier.get("id") or f"shape hyperlink transport {index}"+ raw_target = carrier.get(SHAPE_HYPERLINK_ATTR) or ""+ try:+ parse_hyperlink_target(raw_target, slide_count=slide_count)+ except HyperlinkContractError as exc:+ errors.append(f"{label}: {exc}")+ if _local_name(carrier) != "g":+ errors.append(+ f"{label}: {SHAPE_HYPERLINK_ATTR} is allowed only on <g>"+ )+ ancestors: list[ET.Element] = []+ current = parent_by_id.get(id(carrier))+ while current is not None:+ ancestors.append(current)+ current = parent_by_id.get(id(current))+ if any(_local_name(elem) == "a" for elem in ancestors):+ errors.append(+ f"{label}: {SHAPE_HYPERLINK_ATTR} cannot be nested in <a>"+ )+ inline_anchors = [+ elem+ for elem in carrier.iter(f"{{{SVG_NS}}}a")+ if any(+ _local_name(ancestor) in _INLINE_CONTAINER_TAGS+ for ancestor in _ancestors_of(elem, parent_by_id)+ )+ ]+ if not inline_anchors:+ errors.append(+ f"{label}: {SHAPE_HYPERLINK_ATTR} is reserved for PPTX "+ "round-trip groups that also contain inline hyperlinks"+ )+ return errors+++def _ancestors_of(+ elem: ET.Element,+ parent_by_id: dict[int, ET.Element],+) -> list[ET.Element]:+ """Return ancestors from nearest parent to the SVG root."""+ ancestors: list[ET.Element] = []+ current = parent_by_id.get(id(elem))+ while current is not None:+ ancestors.append(current)+ current = parent_by_id.get(id(current))+ return ancestors+++def trigger_shape_hyperlink_errors(+ root: ET.Element,+ trigger_group_ids: set[str] | frozenset[str],+) -> list[str]:+ """Reject navigation links on click-trigger animation groups."""+ if not trigger_group_ids:+ return []+ parent_by_id = {+ id(child): parent+ for parent in root.iter()+ for child in list(parent)+ }+ errors: list[str] = []+ for elem in root.iter():+ group_id = elem.get("id")+ if _local_name(elem) != "g" or group_id not in trigger_group_ids:+ continue+ has_link = elem.get(SHAPE_HYPERLINK_ATTR) is not None or any(+ _local_name(descendant) == "a"+ or descendant.get(SHAPE_HYPERLINK_ATTR) is not None+ for descendant in elem.iter()+ )+ if not has_link:+ has_link = any(+ _local_name(ancestor) == "a"+ or ancestor.get(SHAPE_HYPERLINK_ATTR) is not None+ for ancestor in _ancestors_of(elem, parent_by_id)+ )+ if has_link:+ errors.append(+ f"animation trigger group {group_id!r} cannot also carry a "+ "hyperlink; use an ordinary animation or a separate trigger"+ )+ return errors+++__all__ = [+ "HYPERLINK_REL_TYPE",+ "HyperlinkContractError",+ "HyperlinkTarget",+ "SHAPE_HYPERLINK_ATTR",+ "SLIDE_JUMP_ACTION",+ "SLIDE_REL_TYPE",+ "parse_hyperlink_target",+ "project_hyperlink_errors",+ "svg_hyperlink_href",+ "trigger_shape_hyperlink_errors",+]diff --git a/skills/ppt-master/scripts/pptx_opc_validation.py b/skills/ppt-master/scripts/pptx_opc_validation.pyindex 5d159ba9..1f2e5a86 100644--- a/skills/ppt-master/scripts/pptx_opc_validation.py+++ b/skills/ppt-master/scripts/pptx_opc_validation.py@@ -9,12 +9,27 @@ from pathlib import Pathfrom urllib.parse import urlsplitfrom xml.etree import ElementTree as ET+from hyperlink_contract import (+ HYPERLINK_REL_TYPE,+ SLIDE_JUMP_ACTION,+ SLIDE_REL_TYPE,+)+PACKAGE_REL_NS = ("http://schemas.openxmlformats.org/package/2006/relationships")_RELATIONSHIPS_TAG = f"{{{PACKAGE_REL_NS}}}Relationships"_RELATIONSHIP_TAG = f"{{{PACKAGE_REL_NS}}}Relationship"+_DRAWINGML_NS = (+ "http://schemas.openxmlformats.org/drawingml/2006/main"+)+_PRESENTATIONML_NS = (+ "http://schemas.openxmlformats.org/presentationml/2006/main"+)+_OFFICE_REL_NS = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+)_OPC_UNRESERVED = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")@@ -127,6 +142,126 @@ def resolve_internal_opc_target(return canonical_opc_part_path(resolved)+def _relationships_path_for_part(part_path: Path) -> Path:+ return part_path.parent / "_rels" / f"{part_path.name}.rels"+++def _relationship_attrs_by_id(rels_path: Path) -> dict[str, dict[str, str]]:+ if not rels_path.is_file():+ return {}+ root = ET.parse(rels_path).getroot()+ return {+ elem.attrib["Id"]: dict(elem.attrib)+ for elem in root.findall(_RELATIONSHIP_TAG)+ if elem.attrib.get("Id")+ }+++def _presentation_slide_roster(extract_dir: Path) -> set[str]:+ """Return canonical slide parts reachable from ``p:sldIdLst``."""+ presentation = extract_dir / "ppt" / "presentation.xml"+ presentation_rels = _relationships_path_for_part(presentation)+ if not presentation.is_file() or not presentation_rels.is_file():+ return set()+ rels = _relationship_attrs_by_id(presentation_rels)+ root = ET.parse(presentation).getroot()+ roster: set[str] = set()+ rels_rel = presentation_rels.relative_to(extract_dir).as_posix()+ for slide_id in root.findall(+ f"{{{_PRESENTATIONML_NS}}}sldIdLst/"+ f"{{{_PRESENTATIONML_NS}}}sldId"+ ):+ relationship_id = slide_id.attrib.get(f"{{{_OFFICE_REL_NS}}}id")+ relationship = rels.get(relationship_id or "")+ if relationship is None or relationship.get("Type") != SLIDE_REL_TYPE:+ continue+ target = relationship.get("Target", "")+ resolved = resolve_internal_opc_target(rels_rel, target)+ if resolved is not None:+ roster.add(resolved)+ return roster+++def verify_hyperlink_relationships(extract_dir: Path) -> list[str]:+ """Return hyperlink/action mismatches and slide jumps outside the roster."""+ roster = _presentation_slide_roster(extract_dir)+ problems: list[str] = []+ source_patterns = (+ "ppt/slides/slide*.xml",+ "ppt/slideLayouts/slideLayout*.xml",+ "ppt/slideMasters/slideMaster*.xml",+ )+ for pattern in source_patterns:+ for part_path in sorted(extract_dir.glob(pattern)):+ rels_path = _relationships_path_for_part(part_path)+ rels = _relationship_attrs_by_id(rels_path)+ part_rel = part_path.relative_to(extract_dir).as_posix()+ rels_rel = rels_path.relative_to(extract_dir).as_posix()+ try:+ root = ET.parse(part_path).getroot()+ except ET.ParseError:+ continue+ for link in root.iter(f"{{{_DRAWINGML_NS}}}hlinkClick"):+ action = (link.attrib.get("action") or "").strip()+ if action == "ppaction://media":+ continue+ relationship_id = (+ link.attrib.get(f"{{{_OFFICE_REL_NS}}}id") or ""+ ).strip()+ if not relationship_id:+ if action == SLIDE_JUMP_ACTION:+ problems.append(+ f"{part_rel} -> <slide jump without relationship id>"+ )+ continue+ relationship = rels.get(relationship_id)+ if relationship is None:+ problems.append(+ f"{part_rel} -> <missing hyperlink relationship "+ f"{relationship_id!r}>"+ )+ continue+ rel_type = relationship.get("Type", "")+ target_mode = relationship.get("TargetMode", "")+ target = relationship.get("Target", "")+ if rel_type == HYPERLINK_REL_TYPE:+ if target_mode.lower() != "external":+ problems.append(+ f"{part_rel} -> <hyperlink relationship "+ f"{relationship_id!r} is not External>"+ )+ if action == SLIDE_JUMP_ACTION:+ problems.append(+ f"{part_rel} -> <slide jump {relationship_id!r} "+ "uses an external hyperlink relationship>"+ )+ continue+ if rel_type == SLIDE_REL_TYPE:+ if target_mode:+ problems.append(+ f"{part_rel} -> <slide relationship "+ f"{relationship_id!r} cannot be External>"+ )+ if action != SLIDE_JUMP_ACTION:+ problems.append(+ f"{part_rel} -> <slide relationship "+ f"{relationship_id!r} lacks hlinksldjump action>"+ )+ resolved = resolve_internal_opc_target(rels_rel, target)+ if resolved is not None and resolved not in roster:+ problems.append(+ f"{part_rel} -> <slide jump {relationship_id!r} "+ f"targets non-roster part {resolved}>"+ )+ continue+ if action == SLIDE_JUMP_ACTION:+ problems.append(+ f"{part_rel} -> <slide jump {relationship_id!r} uses "+ f"relationship type {rel_type!r}>"+ )+ return problems++def verify_internal_relationships(extract_dir: Path) -> list[str]:"""Return invalid or dangling internal relationships in an OPC package."""package_parts: set[str] = set()@@ -207,4 +342,5 @@ def verify_internal_relationships(extract_dir: Path) -> list[str]:)elif resolved not in package_parts:problems.append(f"{rels_rel} -> {resolved}")+ problems.extend(verify_hyperlink_relationships(extract_dir))return problemsdiff --git a/skills/ppt-master/scripts/pptx_to_svg/hyperlinks.py b/skills/ppt-master/scripts/pptx_to_svg/hyperlinks.pynew file mode 100644index 00000000..5aae61a5--- /dev/null+++ b/skills/ppt-master/scripts/pptx_to_svg/hyperlinks.py@@ -0,0 +1,93 @@+#!/usr/bin/env python3+"""+PPT Master - PPTX Hyperlink Resolver++Resolve native DrawingML click actions into the canonical SVG ``href`` form+used by the authoring and round-trip pipelines.++Usage:+ from .hyperlinks import resolve_click_hyperlink++Examples:+ result = resolve_click_hyperlink(rels, "rId3", "", slide_index_by_part=roster)++Dependencies:+ PPT Master hyperlink contract.+"""++from __future__ import annotations++from dataclasses import dataclass++from hyperlink_contract import (+ HYPERLINK_REL_TYPE,+ HyperlinkContractError,+ SLIDE_JUMP_ACTION,+ SLIDE_REL_TYPE,+ parse_hyperlink_target,+)+++@dataclass(frozen=True)+class HyperlinkResolution:+ """Resolved SVG target or one actionable source-package diagnostic."""++ href: str | None = None+ error: str | None = None+++def resolve_click_hyperlink(+ relationships: dict[str, dict[str, str]],+ relationship_id: str,+ action: str,+ *,+ slide_index_by_part: dict[str, int],+) -> HyperlinkResolution:+ """Resolve a click hyperlink relationship from one OOXML source part."""+ if action == "ppaction://media":+ return HyperlinkResolution()+ if not relationship_id:+ return HyperlinkResolution(error="click hyperlink has no relationship id")+ relationship = relationships.get(relationship_id)+ if relationship is None:+ return HyperlinkResolution(+ error=f"click hyperlink relationship {relationship_id!r} is missing"+ )+ rel_type = relationship.get("type", "")+ target = relationship.get("target", "")+ external = relationship.get("external") == "1"++ if action == SLIDE_JUMP_ACTION:+ if external or rel_type != SLIDE_REL_TYPE:+ return HyperlinkResolution(+ error="hlinksldjump does not reference an internal slide"+ )+ slide_index = slide_index_by_part.get(target)+ if slide_index is None:+ return HyperlinkResolution(+ error=f"slide jump target {target!r} is not in the presentation roster"+ )+ return HyperlinkResolution(href=f"#slide-{slide_index}")++ if action.startswith("ppaction://") and action not in {+ "ppaction://hlinkurl",+ }:+ return HyperlinkResolution(+ error=f"unsupported PowerPoint click action {action!r}"+ )+ if not external or rel_type != HYPERLINK_REL_TYPE:+ return HyperlinkResolution(+ error="click hyperlink does not reference an external hyperlink"+ )+ try:+ parsed = parse_hyperlink_target(target)+ except HyperlinkContractError as exc:+ return HyperlinkResolution(error=str(exc))+ if parsed.kind != "external":+ return HyperlinkResolution(+ error="external hyperlink relationship resolved to a slide target"+ )+ return HyperlinkResolution(href=parsed.raw)+++__all__ = ["HyperlinkResolution", "resolve_click_hyperlink"]diff --git a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.pyindex 47ae6cd4..9e8716c9 100644--- a/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py+++ b/skills/ppt-master/scripts/pptx_to_svg/ooxml_loader.py@@ -424,6 +424,11 @@ class OoxmlPackage:return self._slides[index - 1]return None+ @property+ def slide_index_by_part(self) -> dict[str, int]:+ """Return final presentation-order indices keyed by slide part path."""+ return {slide.part.path: slide.index for slide in self._slides}+def iter_all_masters(self) -> Iterator[PartRef]:"""Yield every slideMaster declared in presentation.xml, regardless ofwhether any slide currently uses it.diff --git a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.pyindex 945e80bb..398b000e 100644--- a/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py+++ b/skills/ppt-master/scripts/pptx_to_svg/shape_walker.py@@ -71,6 +71,8 @@ class ShapeNode:name: str = ""spid: str = ""hidden: bool = False+ hyperlink_rid: str = ""+ hyperlink_action: str = ""placeholder: PlaceholderInfo | None = Noneinherited_lst_styles: tuple[ET.Element, ...] = ()inherited_body_properties: tuple[ET.Element, ...] = ()@@ -85,7 +87,10 @@ class ShapeNode:# Walker# ----------------------------------------------------------------------------def _read_nv_sp_pr(parent: ET.Element, nv_tag: str) -> tuple[str, str, bool, PlaceholderInfo | None]:+def _read_nv_sp_pr(+ parent: ET.Element,+ nv_tag: str,+) -> tuple[str, str, bool, PlaceholderInfo | None, str, str]:"""Extract name/id/hidden/placeholder from an nvXXXPr container.nv_tag is one of nvSpPr / nvPicPr / nvCxnSpPr / nvGrpSpPr / nvGraphicFramePr.@@ -95,8 +100,10 @@ def _read_nv_sp_pr(parent: ET.Element, nv_tag: str) -> tuple[str, str, bool, Plaspid = ""hidden = Falseph: PlaceholderInfo | None = None+ hyperlink_rid = ""+ hyperlink_action = ""if container is None:- return name, spid, hidden, ph+ return name, spid, hidden, ph, hyperlink_rid, hyperlink_actioncnv = container.find("p:cNvPr", NS)if cnv is not None:@@ -104,6 +111,10 @@ def _read_nv_sp_pr(parent: ET.Element, nv_tag: str) -> tuple[str, str, bool, Plaspid = cnv.attrib.get("id", "")if ooxml_bool(cnv.attrib.get("hidden")):hidden = True+ hyperlink = cnv.find("a:hlinkClick", NS)+ if hyperlink is not None:+ hyperlink_rid = hyperlink.attrib.get(f"{{{NS['r']}}}id", "")+ hyperlink_action = hyperlink.attrib.get("action", "")nv_pr = container.find("p:nvPr", NS)if nv_pr is not None:@@ -116,7 +127,7 @@ def _read_nv_sp_pr(parent: ET.Element, nv_tag: str) -> tuple[str, str, bool, Plaorient=ph_elem.attrib.get("orient"),)- return name, spid, hidden, ph+ return name, spid, hidden, ph, hyperlink_rid, hyperlink_actiondef _resolve_xfrm(shape: ET.Element, kind: str) -> ET.Element | None:@@ -248,7 +259,14 @@ def _walk_container(continuekind, nv_tag = kind_info- name, spid, hidden, ph = _read_nv_sp_pr(child, nv_tag)+ (+ name,+ spid,+ hidden,+ ph,+ hyperlink_rid,+ hyperlink_action,+ ) = _read_nv_sp_pr(child, nv_tag)xfrm = parse_xfrm(_resolve_xfrm(child, kind))effective_rotation = (ancestor_rotation + xfrm.rot) % 360.0@@ -288,6 +306,8 @@ def _walk_container(node = ShapeNode(kind=kind, xml=child, xfrm=xfrm,name=name, spid=spid, hidden=hidden, placeholder=ph,+ hyperlink_rid=hyperlink_rid,+ hyperlink_action=hyperlink_action,inherited_lst_styles=inherited_lst_styles,inherited_body_properties=inherited_body_properties,effective_rotation=effective_rotation,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 8fb881e8..7517f771 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@@ -42,6 +42,7 @@ from pptx_effects import (txbody_has_run_effects,unsupported_effect_metadata,)+from hyperlink_contract import SHAPE_HYPERLINK_ATTRfrom .color_resolver import ColorPalette, find_color_elem, resolve_colorfrom .chart_to_svg import CHART_URI, CHARTEX_URI, extract_native_chart_payload@@ -57,6 +58,7 @@ from .import_diagnostics import (ImportDiagnostic,append_diagnostic,)+from .hyperlinks import resolve_click_hyperlinkfrom .ln_to_svg import StrokeResult, resolve_strokefrom .ooxml_loader import (OoxmlPackage,@@ -169,6 +171,30 @@ def _diagnose_picture_result()+def _resolve_svg_hyperlink(+ ctx: AssemblyContext,+ relationship_id: str,+ action: str,+) -> str | None:+ """Resolve one source-part click link or record its explicit loss."""+ resolution = resolve_click_hyperlink(+ ctx.slide_part.rels,+ relationship_id,+ action,+ slide_index_by_part=ctx.pkg.slide_index_by_part,+ )+ if resolution.error is None:+ return resolution.href+ if ctx.strict:+ raise ValueError(resolution.error)+ ctx.diagnose(+ "hyperlink-omitted",+ resolution.error,+ "retain the object and omit only its unsupported click link",+ )+ return None++# ---------------------------------------------------------------------------# Public entry# ---------------------------------------------------------------------------@@ -532,6 +558,11 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->fallback_lst_styles=node.inherited_lst_styles,id_prefix=f"{ctx.group_id_prefix}txt",id_seq=ctx.grad_seq,+ hyperlink_resolver=lambda rid, action: _resolve_svg_hyperlink(+ ctx,+ rid,+ action,+ ),)else:text_result = convert_txbody(@@ -543,6 +574,11 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->fallback_lst_styles=node.inherited_lst_styles,id_prefix=f"{ctx.group_id_prefix}txt",id_seq=ctx.grad_seq,+ hyperlink_resolver=lambda rid, action: _resolve_svg_hyperlink(+ ctx,+ rid,+ action,+ ),) if tx_body is not None else TextResult()except ValueError as exc:if ctx.strict:@@ -1222,6 +1258,11 @@ def _render_graphic_table(id_prefix=f"tbl{ctx.shape_seq[0]}",grad_seq=ctx.grad_seq,marker_seq=ctx.marker_seq,+ hyperlink_resolver=lambda rid, action: _resolve_svg_hyperlink(+ ctx,+ rid,+ action,+ ),)if result.defs:ctx.defs.extend(result.defs)@@ -1573,7 +1614,21 @@ def _wrap_shape_group()if transform:attrs.append(f'transform="{transform}"')- return f"<g {' '.join(attrs)}>\n{inner}\n</g>"+ group_xml = f"<g {' '.join(attrs)}>\n{inner}\n</g>"+ if node.hyperlink_rid or node.hyperlink_action:+ href = _resolve_svg_hyperlink(+ ctx,+ node.hyperlink_rid,+ node.hyperlink_action,+ )+ if href is not None and '<a href=' in inner:+ attrs.append(+ f'{SHAPE_HYPERLINK_ATTR}="{_xml_escape(href)}"'+ )+ return f"<g {' '.join(attrs)}>\n{inner}\n</g>"+ if href is not None:+ return f'<a href="{_xml_escape(href)}">{group_xml}</a>'+ return group_xmldef _attrs_to_xml(attrs: dict[str, str]) -> str: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 1f1ce210..8cff3da6 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@@ -56,6 +56,7 @@ from .emu_units import (from .fill_to_svg import FillResult, resolve_fillfrom .ln_to_svg import resolve_strokefrom .txbody_to_svg import _resolve_theme_typeface, convert_txbody+from .txbody_to_svg import HyperlinkResolverBUILTIN_MEDIUM_STYLE_2_ACCENT_1 = "{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}"@@ -279,6 +280,7 @@ def convert_tbl(id_prefix: str = "tbl",grad_seq: list[int] | None = None,marker_seq: list[int] | None = None,+ hyperlink_resolver: HyperlinkResolver | None = None,) -> TableResult:"""Render an <a:tbl> at the given absolute xfrm into SVG markup."""grad_seq = grad_seq if grad_seq is not None else [0]@@ -414,6 +416,7 @@ def convert_tbl(slide_number=slide_number,id_prefix=f"{id_prefix}txt",id_seq=grad_seq,+ hyperlink_resolver=hyperlink_resolver,)defs.extend(text_result.defs)if text_result.svg:@@ -1549,6 +1552,7 @@ def _convert_cell_text(slide_number: int | None,id_prefix: str,id_seq: list[int] | None,+ hyperlink_resolver: HyperlinkResolver | None,):"""Render cell text. PowerPoint's <a:tcPr> can override txBody insets viaits own marL/marR/marT/marB attrs; convert_txbody reads from <a:bodyPr>,@@ -1602,6 +1606,7 @@ def _convert_cell_text(slide_number=slide_number,id_prefix=id_prefix,id_seq=id_seq,+ hyperlink_resolver=hyperlink_resolver,)except (AttributeError, OverflowError, TypeError, ValueError):plain_tx_body = _plain_table_text_body(render_tx_body, overrides)@@ -1611,6 +1616,7 @@ def _convert_cell_text(slide_number=slide_number,id_prefix=id_prefix,id_seq=id_seq,+ hyperlink_resolver=hyperlink_resolver,)finally:if overrides and body_pr is not None: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 b3240f1e..1550a35d 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@@ -23,6 +23,7 @@ back to paragraph/list defaults, endParaRPr, or spec-default values.from __future__ import annotationsfrom dataclasses import dataclass, field+from typing import Callablefrom xml.etree import ElementTree as ETfrom svg_to_pptx.drawingml.utils import detect_text_lang, is_cjk_char@@ -64,6 +65,10 @@ class TextRun:strikethrough: bool = Falseletter_spacing_px: float = 0.0is_break: bool = False # marks an a:br within a paragraph+ hyperlink_href: str | None = None+++HyperlinkResolver = Callable[[str, str], str | None]@dataclass@@ -114,6 +119,7 @@ def convert_txbody(fallback_run_props: tuple[ET.Element, ...] = (),id_prefix: str = "txt",id_seq: list[int] | None = None,+ hyperlink_resolver: HyperlinkResolver | None = None,) -> TextResult:"""Convert <p:txBody> under the given shape geometry to SVG <text>(s)."""if tx_body is None:@@ -126,6 +132,7 @@ def convert_txbody(fallback_lst_styles=fallback_lst_styles,fallback_run_props=fallback_run_props,slide_number=slide_number, id_prefix=id_prefix, id_seq=id_seq,+ hyperlink_resolver=hyperlink_resolver,)if not paragraphs or not _has_visible_text(paragraphs):return TextResult()@@ -224,6 +231,7 @@ def convert_vertical_txbody(fallback_run_props: tuple[ET.Element, ...] = (),id_prefix: str = "txt",id_seq: list[int] | None = None,+ hyperlink_resolver: HyperlinkResolver | None = None,) -> TextResult:"""Render East Asian vertical text as upright stacked glyphs.@@ -241,6 +249,7 @@ def convert_vertical_txbody(fallback_lst_styles=fallback_lst_styles,fallback_run_props=fallback_run_props,slide_number=slide_number, id_prefix=id_prefix, id_seq=id_seq,+ hyperlink_resolver=hyperlink_resolver,)runs = [run@@ -280,12 +289,15 @@ def convert_vertical_txbody(if first_run is None:first_run = runfirst_baseline = baseline_y- spans.append(f"<tspan{tspan_attrs}>{_xml_escape(char)}</tspan>")+ run_span = f"<tspan{tspan_attrs}>{_xml_escape(char)}</tspan>"+ spans.append(_wrap_run_hyperlink(run_span, run))else:dy = baseline_y - (previous_baseline or baseline_y)+ run_span = f"<tspan{tspan_attrs}>{_xml_escape(char)}</tspan>"+ linked_span = _wrap_run_hyperlink(run_span, run)spans.append(- f'<tspan x="{fmt_num(center_x)}" dy="{fmt_num(dy)}"'- f"{tspan_attrs}>{_xml_escape(char)}</tspan>"+ f'<tspan x="{fmt_num(center_x)}" dy="{fmt_num(dy)}">'+ f"{linked_span}</tspan>")previous_baseline = baseline_ycursor_y += advance@@ -374,6 +386,7 @@ def _parse_paragraphs(slide_number: int | None = None,id_prefix: str = "txt",id_seq: list[int] | None = None,+ hyperlink_resolver: HyperlinkResolver | None = None,) -> list[TextParagraph]:"""Walk <a:p> children producing TextParagraph objects."""paragraphs: list[TextParagraph] = []@@ -393,6 +406,7 @@ def _parse_paragraphs(default_font_size_px=default_font_size_px,slide_number=slide_number,id_prefix=id_prefix, id_seq=id_seq,+ hyperlink_resolver=hyperlink_resolver,)paragraphs.append(para)@@ -412,6 +426,7 @@ def _parse_paragraph(slide_number: int | None = None,id_prefix: str = "txt",id_seq: list[int] | None = None,+ hyperlink_resolver: HyperlinkResolver | None = None,) -> TextParagraph:para = TextParagraph()@@ -452,6 +467,7 @@ def _parse_paragraph(default_fill=default_fill,default_font_size_px=default_font_size_px,id_prefix=id_prefix, id_seq=id_seq,+ hyperlink_resolver=hyperlink_resolver,)for child in list(p_elem):@@ -517,6 +533,7 @@ def _build_run(default_font_size_px: float = DEFAULT_FONT_SIZE_PX,id_prefix: str = "txt",id_seq: list[int] | None = None,+ hyperlink_resolver: HyperlinkResolver | None = None,) -> TextRun:"""Resolve a single <a:r> run from its rPr and fallback run properties."""style_chain = (@@ -605,6 +622,14 @@ def _build_run()font_family = _build_font_stack(latin_face, ea_face, cs_face)+ hyperlink_href: str | None = None+ if rpr is not None and hyperlink_resolver is not None:+ hyperlink = rpr.find("a:hlinkClick", NS)+ if hyperlink is not None:+ hyperlink_href = hyperlink_resolver(+ hyperlink.attrib.get(f"{{{NS['r']}}}id", ""),+ hyperlink.attrib.get("action", ""),+ )return TextRun(text=text,@@ -618,6 +643,7 @@ def _build_run(underline=underline,strikethrough=strikethrough,letter_spacing_px=letter_spacing_px,+ hyperlink_href=hyperlink_href,)@@ -1125,6 +1151,7 @@ def _copy_run(run: TextRun, *, text: str) -> TextRun:underline=run.underline,strikethrough=run.strikethrough,letter_spacing_px=run.letter_spacing_px,+ hyperlink_href=run.hyperlink_href,)@@ -1238,6 +1265,23 @@ def _emit_paragraph(f'dy="{fmt_num(line_advance)}"></tspan>')continue+ line_has_hyperlink = any(run.hyperlink_href for run in line)+ if line_has_hyperlink:+ run_spans = ''.join(+ _wrap_run_hyperlink(+ f'<tspan{_run_tspan_attrs(run)}>'+ f'{_xml_escape(run.text)}</tspan>',+ run,+ )+ for run in line+ )+ position_attrs = (+ f' x="{fmt_num(anchor_x)}" dy="{fmt_num(line_advance)}"'+ if line_advance is not None+ else ''+ )+ spans.append(f'<tspan{position_attrs}>{run_spans}</tspan>')+ continuefor run_idx, run in enumerate(line):attrs = _run_tspan_attrs(run)if run_idx == 0 and line_advance is not None:@@ -1318,6 +1362,13 @@ def _run_tspan_attrs(run: TextRun) -> str:return " " + " ".join(parts)+def _wrap_run_hyperlink(markup: str, run: TextRun) -> str:+ """Wrap one visible SVG run in the canonical hyperlink carrier."""+ if not run.hyperlink_href:+ return markup+ return f'<a href="{_xml_escape(run.hyperlink_href)}">{markup}</a>'++def _xml_escape(text: str) -> str:return (text.replace("&", "&").replace("<", "<")diff --git a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py b/skills/ppt-master/scripts/source_to_md/ppt_to_md.pyindex 9e2a8d85..3a6d0c7e 100644--- a/skills/ppt-master/scripts/source_to_md/ppt_to_md.py+++ b/skills/ppt-master/scripts/source_to_md/ppt_to_md.py@@ -217,8 +217,11 @@ def _encode_md_url(url: str) -> str:return quote(url, safe="/:?=&%#@!$'*+,;")-def _resolve_internal_jump(run: object, shape: object) -> str | None:- """Return ``#slide-N`` for a run carrying a slide-internal jump, else None.+def _resolve_internal_jump(+ run: object,+ shape: object,+) -> tuple[bool, str | None]:+ """Return whether a run is an internal jump and its resolved target.Reads ``run._r`` (private python-pptx API) because the public``run.hyperlink.address`` cannot tell an internal jump apart from an@@ -228,26 +231,26 @@ def _resolve_internal_jump(run: object, shape: object) -> str | None:try:rpr = run._r.find(qn("a:rPr"))if rpr is None:- return None+ return False, Nonehlink = rpr.find(qn("a:hlinkClick"))if hlink is None or "hlinksldjump" not in (hlink.get("action", "") or ""):- return None+ return False, Noner_id = hlink.get(qn("r:id"), "")if not r_id:- return None+ return True, Nonetarget_slide = shape.part.related_part(r_id).slideprs = shape.part.slide.part.package.presentation_part.presentation- return f"#slide-{list(prs.slides).index(target_slide) + 1}"+ return True, f"#slide-{list(prs.slides).index(target_slide) + 1}"except (KeyError, ValueError, AttributeError):print(f"[WARN] ppt_to_md: could not resolve slide jump rId={r_id}", file=sys.stderr)- return None+ return True, Nonedef _run_url(run: object, shape: object) -> str | None:"""Resolve a run's hyperlink target to a markdown-ready URL, or None."""if shape is not None:- internal = _resolve_internal_jump(run, shape)- if internal:+ is_internal, internal = _resolve_internal_jump(run, shape)+ if is_internal:return internaltry:addr = run.hyperlink.address@@ -258,7 +261,12 @@ def _run_url(run: object, shape: object) -> str | None:return None-def _paragraph_to_markdown(paragraph: object, shape: object) -> str:+def _paragraph_to_markdown(+ paragraph: object,+ shape: object,+ *,+ use_shape_click_action: bool = True,+) -> str:"""Render one paragraph, merging consecutive runs that share a URL.Run text is concatenated verbatim — including the spaces between runs — and@@ -298,28 +306,40 @@ def _paragraph_to_markdown(paragraph: object, shape: object) -> str:text = normalize_text("".join(parts))# Shape-level click_action only matters when no run carried its own link.- if not has_run_hyperlink and shape is not None:+ if (+ use_shape_click_action+ and not has_run_hyperlink+ and shape is not None+ ):text = _apply_shape_click_action(text, shape)return textdef _apply_shape_click_action(text: str, shape: object) -> str:"""Wrap paragraph text in a link from the shape's click_action, if any."""+ target = _shape_click_target(shape)+ if target is None:+ return text+ return f"[{_escape_md_link_text(text)}]({target})"+++def _shape_click_target(shape: object) -> str | None:+ """Return one Markdown-ready whole-shape click target, if supported."""try:action = shape.click_actionif action.action == PP_ACTION.HYPERLINK:url = action.hyperlink.address or ""if _is_supported_url(url):- return f"[{_escape_md_link_text(text)}]({_encode_md_url(url)})"+ return _encode_md_url(url)elif action.action == PP_ACTION.NAMED_SLIDE:target = action.target_slideif target is not None:prs = shape.part.slide.part.package.presentation_part.presentationidx = list(prs.slides).index(target) + 1- return f"[{_escape_md_link_text(text)}](#slide-{idx})"+ return f"#slide-{idx}"except (AttributeError, ValueError):print("[WARN] ppt_to_md: could not process shape click_action", file=sys.stderr)- return text+ return Nonedef _paragraph_has_hyperlink(paragraph: object) -> bool:@@ -339,7 +359,12 @@ def _paragraph_has_hyperlink(paragraph: object) -> bool:return False-def text_frame_to_markdown(text_frame: object, shape: object = None) -> str:+def text_frame_to_markdown(+ text_frame: object,+ shape: object = None,+ *,+ use_shape_click_action: bool = True,+) -> str:"""Convert a PowerPoint text frame into Markdown, preserving hyperlinks.Run-level external URLs and slide-internal jumps are emitted as@@ -362,7 +387,11 @@ def text_frame_to_markdown(text_frame: object, shape: object = None) -> str:paragraphs = []for paragraph in visible_paragraphs:text = _escape_readback_control_lines(- _paragraph_to_markdown(paragraph, shape)+ _paragraph_to_markdown(+ paragraph,+ shape,+ use_shape_click_action=use_shape_click_action,+ ))if not text:continue@@ -377,11 +406,20 @@ def text_frame_to_markdown(text_frame: object, shape: object = None) -> str:return "\n\n".join(paragraphs)-def table_to_markdown(table: object) -> str:+def table_to_markdown(table: object, shape: object = None) -> str:"""Convert a PowerPoint table to a Markdown table."""rows = []for row in table.rows:- cells = [escape_table_cell(cell.text) for cell in row.cells]+ cells = [+ escape_table_cell(+ text_frame_to_markdown(+ cell.text_frame,+ shape,+ use_shape_click_action=False,+ )+ )+ for cell in row.cells+ ]rows.append(cells)if not rows:@@ -1098,7 +1136,7 @@ def convert_presentation_to_markdown(shape = item.shapeif getattr(shape, "has_table", False):- table_md = table_to_markdown(shape.table)+ table_md = table_to_markdown(shape.table, shape)if table_md:blocks.append(table_md)continue@@ -1136,10 +1174,14 @@ def convert_presentation_to_markdown(image_count = next_image_indeximage_manifest.append(saved_picture.manifest_entry)asset_dir_used = True- blocks.append(+ image_markdown = (f"![Slide {slide_index} Image {image_ref_count}]"f"({asset_dir.name}/{saved_picture.filename})")+ image_link = _shape_click_target(shape)+ if image_link is not None:+ image_markdown = f"[{image_markdown}]({image_link})"+ blocks.append(image_markdown)if is_picture_shape:continuediff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.pyindex 232f5914..775e2af4 100644--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py@@ -677,22 +677,25 @@ def flatten_text_with_tspans(def _has_tspan_children(elem: ET.Element) -> bool:- """Return True if elem contains any nested <tspan> children (inline runs)."""- return any(c.tag == f"{{{SVG_NS}}}tspan" for c in list(elem))-+ """Return True when one inline subtree has nested runs or hyperlinks."""+ return any(+ c.tag in {+ f"{{{SVG_NS}}}a",+ f"{{{SVG_NS}}}tspan",+ }+ for c in list(elem)+ )-def _copy_inline_tspan(src: ET.Element, strip_line_attrs: bool) -> ET.Element:- """Deep-copy a tspan as an inline run, preserving nested tspan structure, head text, and tail text.- When strip_line_attrs is True, x/y/dy are dropped because the enclosing- <text> owns the resolved line position. Drop dx only from a positioned- line starter, where compute_line_positions already consumed it; preserve- dx on later inline runs.- Nested tspans are copied recursively without stripping (they are already inline-only).- """- new = ET.Element(f"{{{SVG_NS}}}tspan")+def _copy_inline_element(src: ET.Element, strip_line_attrs: bool) -> ET.Element:+ """Deep-copy one supported inline ``tspan`` or hyperlink subtree."""+ local = src.tag.rsplit("}", 1)[-1]+ if local not in {"a", "tspan"}:+ raise ValueError(f"Unsupported inline text child <{local}>")+ new = ET.Element(f"{{{SVG_NS}}}{local}")consumed_dx = (- strip_line_attrs+ local == "tspan"+ and strip_line_attrsand _positional_tspan_attribute(src) is not None)for k, v in src.attrib.items():@@ -703,12 +706,27 @@ def _copy_inline_tspan(src: ET.Element, strip_line_attrs: bool) -> ET.Element:new.set(k, v)new.text = src.textfor child in list(src):- if child.tag == f"{{{SVG_NS}}}tspan":- new.append(_copy_inline_tspan(child, strip_line_attrs=False))+ if child.tag in {+ f"{{{SVG_NS}}}a",+ f"{{{SVG_NS}}}tspan",+ }:+ new.append(_copy_inline_element(child, strip_line_attrs=False))new.tail = src.tailreturn new+def _copy_inline_tspan(src: ET.Element, strip_line_attrs: bool) -> ET.Element:+ """Deep-copy a tspan as an inline run, preserving nested tspan structure, head text, and tail text.++ When strip_line_attrs is True, x/y/dy are dropped because the enclosing+ <text> owns the resolved line position. Drop dx only from a positioned+ line starter, where compute_line_positions already consumed it; preserve+ dx on later inline runs.+ Nested tspans are copied recursively without stripping (they are already inline-only).+ """+ return _copy_inline_element(src, strip_line_attrs)++def _create_text_element_from_line(text_el: ET.Element,lead_text: str | None,diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.pyindex e95fa1d7..30cd95fb 100644--- a/skills/ppt-master/scripts/svg_quality/checker.py+++ b/skills/ppt-master/scripts/svg_quality/checker.py@@ -119,6 +119,15 @@ except ImportError:_unsafe_exported_font_faces = None_validate_dml_shape_matrix = None+try:+ from hyperlink_contract import (+ SHAPE_HYPERLINK_ATTR as _SHAPE_HYPERLINK_ATTR,+ project_hyperlink_errors as _project_hyperlink_errors,+ )+except ImportError:+ _SHAPE_HYPERLINK_ATTR = 'data-pptx-shape-hyperlink'+ _project_hyperlink_errors = None+try:from svg_to_pptx.drawingml.converter import (SvgNativeConversionError as _SvgNativeConversionError,@@ -1058,6 +1067,7 @@ class SVGQualityChecker:self._communication_trace_issues: List[Tuple[str, str]] = []self._pptx_structure_issues: List[Tuple[str, str]] = []self._has_incomplete_page_roster = False+ self._active_slide_count: int | None = Noneself._prototype_by_output: Dict[Path, Path] = {}self._active_prototype_path: Path | None = Noneself._active_template_reuse_scope: str | None = None@@ -1223,6 +1233,9 @@ class SVGQualityChecker:# 5. Check text wrapping methodsself._check_text_elements(content, root, result)+ # 5b. Validate native hyperlink targets and carrier structure.+ self._check_hyperlinks(root, result)+# 6. Check image references (file existence and resolution)self._check_image_references(root, svg_path, result)@@ -1498,6 +1511,32 @@ class SVGQualityChecker:self._check_unmergeable_leading_text(root, result)self._check_nested_positional_tspans(root, result)+ def _check_hyperlinks(self, root: ET.Element, result: Dict) -> None:+ """Validate the standard SVG anchor surface shared with export."""+ anchors = [+ elem for elem in root.iter()+ if _local_name(elem) == 'a'+ ]+ transports = [+ elem for elem in root.iter()+ if elem.get(_SHAPE_HYPERLINK_ATTR) is not None+ ]+ if not anchors and not transports:+ return+ result['info']['hyperlinks'] = len(anchors) + len(transports)+ if _project_hyperlink_errors is None:+ result['errors'].append(+ 'Unable to import hyperlink validator; cannot verify SVG links'+ )+ return+ result['errors'].extend(+ f'Invalid SVG hyperlink: {error}'+ for error in _project_hyperlink_errors(+ root,+ slide_count=self._active_slide_count,+ )+ )+def _check_nested_positional_tspans(self,root: ET.Element,@@ -5046,6 +5085,8 @@ class SVGQualityChecker:self.issue_types['Input issues'] += 1return []+ self._active_slide_count = len(svg_files)+self._configure_prototype_context(dir_path, svg_files)if not self.template_mode:self._prepare_undeclared_size_occurrences(svg_files)diff --git a/skills/ppt-master/scripts/svg_quality/svg_contracts.py b/skills/ppt-master/scripts/svg_quality/svg_contracts.pyindex b135061a..fd8c0ad4 100644--- a/skills/ppt-master/scripts/svg_quality/svg_contracts.py+++ b/skills/ppt-master/scripts/svg_quality/svg_contracts.py@@ -387,7 +387,7 @@ def check_reference_spelling(root: ET.Element, result: Dict) -> None:labels = []xlink_href = f'{{{XLINK_NS}}}href'for elem in root.iter():- if _local_name(elem).lower() not in {'image', 'use'}:+ if _local_name(elem).lower() not in {'a', 'image', 'use'}:continueif elem.get(xlink_href) is not None:labels.append(_element_label(elem))diff --git a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py b/skills/ppt-master/scripts/svg_to_pptx/animation_config.pyindex 2b95c09e..bc0d8476 100644--- a/skills/ppt-master/scripts/svg_to_pptx/animation_config.py+++ b/skills/ppt-master/scripts/svg_to_pptx/animation_config.py@@ -10,6 +10,8 @@ from pathlib import Path, PureWindowsPathfrom typing import Anyfrom xml.etree import ElementTree as ET+from hyperlink_contract import SHAPE_HYPERLINK_ATTR+from pptx_animations import (ANIMATIONS,ANIMATION_AFTER_EFFECTS,@@ -77,6 +79,7 @@ class GroupTarget:order: intchrome: bool = Falsestructurally_static: bool = False+ has_hyperlink: bool = False@dataclass(frozen=True)@@ -156,6 +159,11 @@ def scan_svg_targets(svg_path: Path) -> tuple[list[GroupTarget], list[str]]:order=visual_index,chrome=chrome,structurally_static=structurally_static,+ has_hyperlink=any(+ _tag_name(descendant) == 'a'+ or descendant.get(SHAPE_HYPERLINK_ATTR) is not None+ for descendant in child.iter()+ ),))@@ -1492,6 +1500,12 @@ def validate_animation_config(f'references non-triggerable structural group 'f'{trigger_shape!r}')+ elif trigger_target.has_hyperlink:+ warnings.append(+ f'animations.json {effect_path}.trigger_shape '+ f'references hyperlink-bearing group {trigger_shape!r}; '+ 'use an ordinary animation or a separate trigger'+ )morph_pairs, morph_errors = _resolve_morph_pairs(list(targets_by_slide),diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.pyindex 5181a1d7..62fc9b82 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py@@ -69,6 +69,8 @@ class ConvertContext:claimed_shape_ids: set[int] = field(default_factory=set)referenced_shape_ids: set[int] = field(default_factory=set)slide_num: int = 1+ # Public presentation roster size, used to fail closed on #slide-N links.+ slide_count: int | None = Nonetranslate_x: float = 0.0translate_y: float = 0.0scale_x: float = 1.0@@ -245,6 +247,7 @@ class ConvertContext:claimed_shape_ids=self.claimed_shape_ids,referenced_shape_ids=self.referenced_shape_ids,slide_num=self.slide_num,+ slide_count=self.slide_count,translate_x=self.translate_x + dx,translate_y=self.translate_y + dy,scale_x=self.scale_x * sx,diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex f140645d..039e5a1e 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -12,6 +12,11 @@ from typing import Anyfrom xml.etree import ElementTree as ETfrom native_payloads import NativePayloadError, hydrate_native_payload_refs+from hyperlink_contract import (+ SHAPE_HYPERLINK_ATTR,+ project_hyperlink_errors,+ svg_hyperlink_href,+)from pptx_shapes import (has_relationship_attributes,resolve_preset_preview_hash,@@ -33,6 +38,7 @@ from .context import (ShapeResult,resolve_text_flow,)+from .hyperlinks import apply_shape_hyperlinkfrom .paths import (project_freeform_geometry_errors,project_gradient_geometry_errors,@@ -170,6 +176,23 @@ def _require_inline_formula_markers()+def _require_project_hyperlinks(+ root: ET.Element,+ svg_path: Path | str,+ *,+ slide_count: int | None,+) -> None:+ """Reject hyperlinks that cannot be represented faithfully in PPTX."""+ errors = project_hyperlink_errors(root, slide_count=slide_count)+ if not errors:+ return+ preview = '; '.join(errors[:8])+ suffix = '' if len(errors) <= 8 else f'; +{len(errors) - 8} more'+ raise SvgNativeConversionError(+ f'{Path(svg_path).name}: invalid SVG hyperlink(s): {preview}{suffix}'+ )++def _native_replacement_enabled(elem: ET.Element, ctx: ConvertContext) -> bool:"""Return whether this marker is active under the current export policy."""kind = native_replacement_kind(elem)@@ -1011,6 +1034,14 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:</p:grpSp>''', bounds_emu=(group_x, group_y, group_x + group_w, group_y + group_h))+def convert_a(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:+ """Convert one standard SVG anchor into a clickable DrawingML object."""+ result = convert_g(elem, ctx)+ if result is None:+ return None+ return apply_shape_hyperlink(result, ctx, svg_hyperlink_href(elem))++# ---------------------------------------------------------------------------# Defs collection & element dispatch# ---------------------------------------------------------------------------@@ -1028,6 +1059,7 @@ _CONVERTERS = {'text': convert_text,'image': convert_image,'g': convert_g,+ 'a': convert_a,'svg': convert_nested_svg,}@@ -1337,6 +1369,9 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | Noneif converter:try:result = converter(elem, ctx)+ shape_hyperlink = elem.get(SHAPE_HYPERLINK_ATTR)+ if result is not None and shape_hyperlink is not None:+ result = apply_shape_hyperlink(result, ctx, shape_hyperlink)except Exception as e:trace('error', error=str(e))raise SvgNativeConversionError(f'Failed to convert <{tag}>: {e}') from e@@ -1390,7 +1425,7 @@ def collect_unsupported_visuals(returnis_supported_visual_child = (tag in _SUPPORTED_VISUAL_CHILD_TAGS- and parent_tag in {'text', 'tspan'}+ and parent_tag in {'text', 'tspan', 'a'})is_data_icon_placeholder = (allow_data_icon_use@@ -1418,6 +1453,7 @@ def collect_unsupported_visuals(def convert_svg_to_slide_shapes(svg_path: str | Path,slide_num: int = 1,+ slide_count: int | None = None,verbose: bool = False,merge_paragraphs: bool | None = None,image_optimize: bool = True,@@ -1446,6 +1482,7 @@ def convert_svg_to_slide_shapes(Args:svg_path: Path to the SVG file.slide_num: Slide number (for naming).+ slide_count: Public deck size used to validate ``#slide-N`` targets.verbose: Print progress info.merge_paragraphs: Legacy compatibility option. True selects reflow;False selects split. Do not combine with ``text_flow``.@@ -1504,6 +1541,11 @@ def convert_svg_to_slide_shapes(raise SvgNativeConversionError(str(exc)) from exc_require_native_marker_attributes(root, svg_path)_require_inline_formula_markers(root, svg_path)+ _require_project_hyperlinks(+ root,+ svg_path,+ slide_count=slide_count,+ )_require_project_nested_svg_crops(root, svg_path)_require_project_clip_paths(root, svg_path)authored_errors = validate_authored_preset_tree(root)@@ -1646,6 +1688,11 @@ def convert_svg_to_slide_shapes(print(f' Expanded {expanded_local} local <use href="#..."/> instance(s)')_require_inline_formula_markers(root, svg_path)+ _require_project_hyperlinks(+ root,+ svg_path,+ slide_count=slide_count,+ )# Recheck compiler-injected icon/use wrappers and cloned definition trees._require_project_nested_svg_crops(root, svg_path)@@ -1675,6 +1722,13 @@ def convert_svg_to_slide_shapes(1 for elem in root.iter()if elem.get(INLINE_FORMULA_ATTR) is not None)+ hyperlink_count_before_text_lowering = sum(+ 1 for elem in root.iter()+ if (+ elem.tag == f'{{{SVG_NS}}}a'+ or elem.get(SHAPE_HYPERLINK_ATTR) is not None+ )+ )# Flatten positional <tspan> (those with x/y/non-zero dy) into independent# <text> elements. DrawingML runs cannot reposition mid-paragraph, so a@@ -1705,6 +1759,13 @@ def convert_svg_to_slide_shapes(1 for elem in root.iter()if elem.get(INLINE_FORMULA_ATTR) is not None)+ hyperlink_count_after_text_lowering = sum(+ 1 for elem in root.iter()+ if (+ elem.tag == f'{{{SVG_NS}}}a'+ or elem.get(SHAPE_HYPERLINK_ATTR) is not None+ )+ )if (inline_formula_count_after_text_lowering!= inline_formula_count_before_text_lowering@@ -1714,7 +1775,18 @@ def convert_svg_to_slide_shapes(f'marker count from {inline_formula_count_before_text_lowering} 'f'to {inline_formula_count_after_text_lowering}')+ if hyperlink_count_after_text_lowering != hyperlink_count_before_text_lowering:+ raise SvgNativeConversionError(+ f'{svg_path.name}: positional text lowering changed hyperlink '+ f'count from {hyperlink_count_before_text_lowering} '+ f'to {hyperlink_count_after_text_lowering}'+ )_require_inline_formula_markers(root, svg_path)+ _require_project_hyperlinks(+ root,+ svg_path,+ slide_count=slide_count,+ )_require_project_text_properties(root, svg_path)try:@@ -1743,6 +1815,7 @@ def convert_svg_to_slide_shapes(reserved_shape_ids=frozenset(source_shape_id_map.values()),source_shape_id_map=source_shape_id_map,slide_num=slide_num,+ slide_count=slide_count,viewport_width=viewport_width,viewport_height=viewport_height,svg_dir=Path(svg_path).parent,diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.pyindex 1c155129..7266c07f 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py@@ -24,6 +24,7 @@ from pptx_shapes import (validate_ooxml_xfrm,)from pptx_effects import EFFECT_REASON_ATTR, EFFECT_STATUS_ATTR+from hyperlink_contract import svg_hyperlink_hreffrom pptx_to_svg.preset_authoring import AUTHORING_ATTR, AUTHORING_VALUEfrom resource_paths import (resolve_external_image_reference,@@ -36,6 +37,12 @@ from .context import (ConvertContext,ShapeResult,)+from .hyperlinks import (+ HYPERLINK_ACTION_KEY,+ HYPERLINK_RID_KEY,+ hyperlink_click_xml,+ hyperlink_run_metadata,+)from .theme_colors import color_node_xmlfrom .theme_fonts import theme_font_tokensfrom .text_properties import (@@ -2175,7 +2182,10 @@ def _extract_text_bullet() -> tuple[list[dict[str, Any]], dict[str, Any] | None]:"""Convert a leading text bullet marker into paragraph metadata."""first_nonspace = _first_nonspace_run(runs)- if first_nonspace and first_nonspace.get(_INLINE_FORMULA_KEY) is not None:+ if first_nonspace and (+ first_nonspace.get(_INLINE_FORMULA_KEY) is not None+ or first_nonspace.get(HYPERLINK_RID_KEY) is not None+ ):return runs, Nonefull_text = ''.join(str(run.get('text', '')) for run in runs)match = _TEXT_BULLET_RE.match(full_text)@@ -2390,37 +2400,68 @@ def _collect_tspan_runs(ctx: ConvertContext,inherited_xml_space: str = 'default',) -> list[dict[str, Any]]:- """Recursively turn a tspan subtree into runs, propagating styling through nested tspans.+ """Recursively turn one inline SVG subtree into DrawingML text runs."""+ return _collect_inline_runs(+ tspan,+ inherited_attrs,+ ctx,+ inherited_xml_space,+ )- Order: tspan.text → (each nested child tspan's runs → that child's tail under THIS tspan's attrs).- """++def _collect_inline_runs(+ container: ET.Element,+ inherited_attrs: dict[str, Any],+ ctx: ConvertContext,+ inherited_xml_space: str = 'default',+ inherited_hyperlink: dict[str, str] | None = None,+) -> list[dict[str, Any]]:+ """Collect nested ``tspan``/``a`` content with style and link inheritance."""runs: list[dict[str, Any]] = []- own_attrs = _override_run_attrs(inherited_attrs, tspan, ctx)- own_xml_space = resolve_project_xml_space(tspan, inherited_xml_space)+ own_attrs = _override_run_attrs(inherited_attrs, container, ctx)+ own_xml_space = resolve_project_xml_space(container, inherited_xml_space)+ container_tag = container.tag.replace(f'{{{SVG_NS}}}', '')+ own_hyperlink = inherited_hyperlink+ if container_tag == 'a':+ own_hyperlink = hyperlink_run_metadata(+ ctx,+ svg_hyperlink_href(container),+ )- if tspan.text:+ if container.text:run = {**own_attrs,- 'text': tspan.text,+ 'text': container.text,'_xml_space': own_xml_space,}- inline_formula = tspan.get(_INLINE_FORMULA_ATTR)+ if own_hyperlink is not None:+ run.update(own_hyperlink)+ inline_formula = container.get(_INLINE_FORMULA_ATTR)if inline_formula is not None:run[_INLINE_FORMULA_KEY] = inline_formularuns.append(run)- for child in tspan:+ for child in container:child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')- if child_tag == 'tspan':+ if child_tag in {'tspan', 'a'}:runs.extend(- _collect_tspan_runs(child, own_attrs, ctx, own_xml_space)+ _collect_inline_runs(+ child,+ own_attrs,+ ctx,+ own_xml_space,+ own_hyperlink,+ ))if child.tail:- runs.append({+ tail_run = {**own_attrs,'text': child.tail,'_xml_space': own_xml_space,- })+ }+ if own_hyperlink is not None:+ tail_run.update(own_hyperlink)+ runs.append(tail_run)return runs@@ -2448,10 +2489,13 @@ def _build_text_runs(for child in elem:child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')- if child_tag == 'tspan':- runs.extend(- _collect_tspan_runs(child, parent_attrs, ctx, xml_space)- )+ if child_tag in {'tspan', 'a'}:+ runs.extend(_collect_inline_runs(+ child,+ parent_attrs,+ ctx,+ xml_space,+ ))if child.tail:runs.append({**parent_attrs,@@ -2603,6 +2647,17 @@ def _build_run_properties_xml(fill_xml = _build_text_fill_xml(fill, fill_raw, opacity, ctx)outline_xml = _build_text_outline_xml(run, ctx)+ relationship_id = run.get(HYPERLINK_RID_KEY)+ hyperlink_xml = (+ hyperlink_click_xml(+ str(relationship_id),+ str(run.get(HYPERLINK_ACTION_KEY))+ if run.get(HYPERLINK_ACTION_KEY) is not None+ else None,+ )+ if relationship_id is not None+ else ''+ )return f'''<a:rPr lang="{lang}" sz="{sz}"{b_attr}{i_attr}{u_attr}{strike_attr}{spc_attr} dirty="0">{outline_xml}@@ -2610,7 +2665,8 @@ def _build_run_properties_xml({effect_xml}<a:latin typeface="{_xml_escape(run_fonts['latin'])}"/><a:ea typeface="{_xml_escape(run_fonts['ea'])}"/>-<a:cs typeface="{_xml_escape(run_fonts['cs'])}"/>{rtl_xml}+<a:cs typeface="{_xml_escape(run_fonts['cs'])}"/>+{hyperlink_xml}{rtl_xml}</a:rPr>'''@@ -2638,6 +2694,8 @@ def _coalesce_text_runs(if (mergedand merged[-1].get(_INLINE_FORMULA_KEY) is None+ and merged[-1].get(HYPERLINK_RID_KEY) == run.get(HYPERLINK_RID_KEY)+ and merged[-1].get(HYPERLINK_ACTION_KEY) == run.get(HYPERLINK_ACTION_KEY)and properties == previous_properties):candidate = {@@ -2865,6 +2923,8 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:'letter_spacing': 0.0,}joining_space.pop(_INLINE_FORMULA_KEY, None)+ joining_space.pop(HYPERLINK_RID_KEY, None)+ joining_space.pop(HYPERLINK_ACTION_KEY, None)prev.append(joining_space)prev.extend(line_runs)else:diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/hyperlinks.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/hyperlinks.pynew file mode 100644index 00000000..a1123973--- /dev/null+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/hyperlinks.py@@ -0,0 +1,162 @@+#!/usr/bin/env python3+"""+PPT Master - DrawingML Hyperlink Lowering++Register native PowerPoint hyperlink relationships and attach click actions to+text runs or clickable leaf shapes produced by the SVG converter.++Usage:+ from .hyperlinks import apply_shape_hyperlink, hyperlink_run_metadata++Examples:+ metadata = hyperlink_run_metadata(ctx, "https://example.com")+ linked = apply_shape_hyperlink(result, ctx, "#slide-2")++Dependencies:+ PPT Master hyperlink contract and DrawingML conversion context.+"""++from __future__ import annotations++import re++from hyperlink_contract import (+ HYPERLINK_REL_TYPE,+ SLIDE_JUMP_ACTION,+ SLIDE_REL_TYPE,+ parse_hyperlink_target,+)++from .context import ConvertContext, ShapeResult+++HYPERLINK_RID_KEY = "_hyperlink_rid"+HYPERLINK_ACTION_KEY = "_hyperlink_action"++_CNVPR_RE = re.compile(+ r"<p:cNvPr\b[^<>]*(?:/>|>.*?</p:cNvPr>)",+ re.DOTALL,+)+_GROUP_NONVISUAL_RE = re.compile(+ r"<p:nvGrpSpPr>.*?</p:nvGrpSpPr>",+ re.DOTALL,+)+++def register_hyperlink(+ ctx: ConvertContext,+ raw_target: str,+) -> tuple[str, str | None]:+ """Register one slide relationship and return ``(rId, action)``."""+ target = parse_hyperlink_target(+ raw_target,+ slide_count=ctx.slide_count,+ )+ if target.kind == "slide":+ relationship_type = SLIDE_REL_TYPE+ relationship_target = f"slide{target.slide_number}.xml"+ target_mode = None+ action = SLIDE_JUMP_ACTION+ else:+ relationship_type = HYPERLINK_REL_TYPE+ relationship_target = target.raw+ target_mode = "External"+ action = None++ for relationship in ctx.rel_entries:+ if (+ relationship.get("type") == relationship_type+ and relationship.get("target") == relationship_target+ and relationship.get("target_mode") == target_mode+ ):+ return relationship["id"], action++ relationship_id = ctx.next_rel_id()+ relationship = {+ "id": relationship_id,+ "type": relationship_type,+ "target": relationship_target,+ }+ if target_mode is not None:+ relationship["target_mode"] = target_mode+ ctx.rel_entries.append(relationship)+ return relationship_id, action+++def hyperlink_click_xml(+ relationship_id: str,+ action: str | None = None,+) -> str:+ """Build one DrawingML click hyperlink child."""+ action_attr = f' action="{action}"' if action else ""+ return f'<a:hlinkClick r:id="{relationship_id}"{action_attr}/>'+++def hyperlink_run_metadata(+ ctx: ConvertContext,+ raw_target: str,+) -> dict[str, str]:+ """Return the internal run fields for one SVG inline anchor."""+ relationship_id, action = register_hyperlink(ctx, raw_target)+ metadata = {HYPERLINK_RID_KEY: relationship_id}+ if action is not None:+ metadata[HYPERLINK_ACTION_KEY] = action+ return metadata+++def apply_shape_hyperlink(+ result: ShapeResult,+ ctx: ConvertContext,+ raw_target: str,+) -> ShapeResult:+ """Attach one click hyperlink to every clickable leaf object.++ DrawingML group containers are selection/animation structures, not a+ reliable click-action carrier across PowerPoint APIs. A multi-object SVG+ anchor therefore shares one relationship across each leaf ``p:cNvPr``.+ Authors use an explicit background shape when the whole rectangular button+ area, including gaps between descendants, must be clickable.+ """+ relationship_id, action = register_hyperlink(ctx, raw_target)+ hlink_xml = hyperlink_click_xml(relationship_id, action)+ group_ranges = [+ (match.start(), match.end())+ for match in _GROUP_NONVISUAL_RE.finditer(result.xml)+ ]+ replacements: list[tuple[int, int, str]] = []+ for match in _CNVPR_RE.finditer(result.xml):+ if any(start <= match.start() < end for start, end in group_ranges):+ continue+ original = match.group(0)+ if "<a:hlinkClick" in original:+ raise ValueError(+ "hyperlink carrier already contains a click hyperlink"+ )+ if original.endswith("/>"):+ replacement = f"{original[:-2]}>{hlink_xml}</p:cNvPr>"+ else:+ replacement = original.replace(+ "</p:cNvPr>",+ f"{hlink_xml}</p:cNvPr>",+ 1,+ )+ replacements.append((match.start(), match.end(), replacement))++ if not replacements:+ raise ValueError(+ "hyperlink carrier did not produce a clickable DrawingML leaf"+ )+ linked_xml = result.xml+ for start, end, replacement in reversed(replacements):+ linked_xml = linked_xml[:start] + replacement + linked_xml[end:]+ return ShapeResult(xml=linked_xml, bounds_emu=result.bounds_emu)+++__all__ = [+ "HYPERLINK_ACTION_KEY",+ "HYPERLINK_RID_KEY",+ "apply_shape_hyperlink",+ "hyperlink_click_xml",+ "hyperlink_run_metadata",+ "register_hyperlink",+]diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.pyindex 60618452..cb2d28d4 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/inline_formula.py@@ -28,12 +28,16 @@ from .formula_compiler import (SVG_NS = "http://www.w3.org/2000/svg"DML_NS = "http://schemas.openxmlformats.org/drawingml/2006/main"+OFFICE_REL_NS = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships"+)MATH_NS = "http://schemas.openxmlformats.org/officeDocument/2006/math"A14_NS = "http://schemas.microsoft.com/office/drawing/2010/main"MC_NS = "http://schemas.openxmlformats.org/markup-compatibility/2006"INLINE_FORMULA_ATTR = "data-pptx-inline-formula"_SVG_TEXT = f"{{{SVG_NS}}}text"_SVG_TSPAN = f"{{{SVG_NS}}}tspan"+_SVG_A = f"{{{SVG_NS}}}a"_MATH_RUN = f"{{{MATH_NS}}}r"_MATH_RUN_PROPERTIES = f"{{{MATH_NS}}}rPr"_DML_RUN_PROPERTIES = f"{{{DML_NS}}}rPr"@@ -165,7 +169,7 @@ def inline_formula_marker_errors(root: ET.Element) -> list[str]:text_owner = parentelif (text_owner is None- and parent.tag != _SVG_TSPAN+ and parent.tag not in {_SVG_A, _SVG_TSPAN}and invalid_inline_container is None):invalid_inline_container = parent_tag@@ -202,7 +206,7 @@ def inline_formula_marker_errors(root: ET.Element) -> list[str]:errors.append(f"{label} must be inside an SVG <text> element")elif invalid_inline_container is not None:errors.append(- f"{label} can only be nested through <tspan> elements before "+ f"{label} can only be nested through <tspan>/<a> elements before "f"its owning <text>, found <{invalid_inline_container}>")if non_output_ancestor is not None:@@ -246,7 +250,8 @@ def _apply_run_properties(omml: str, run_properties_xml: str) -> str:try:root = ET.fromstring(omml)wrapper = ET.fromstring(- f'<root xmlns:a="{DML_NS}">{run_properties_xml}</root>'+ f'<root xmlns:a="{DML_NS}" xmlns:r="{OFFICE_REL_NS}">'+ f"{run_properties_xml}</root>")except (ET.ParseError, RecursionError) as exc:raise RuntimeError(f"Invalid inline formula XML: {exc}") from excdiff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.pyindex 700da803..ec8dd186 100644--- a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py@@ -19,10 +19,10 @@ import zipfilefrom concurrent.futures import ProcessPoolExecutor, as_completedfrom dataclasses import asdict, dataclassfrom datetime import datetime, timezone-from pathlib import Path, PureWindowsPath+from pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Anyfrom xml.etree import ElementTree as ET-from xml.sax.saxutils import escape+from xml.sax.saxutils import escape, quoteattrfrom pptx import Presentationfrom pptx.util import Emu@@ -55,6 +55,10 @@ from pptx_opc_validation import (verify_internal_relationships,)from language_tags import normalize_language_tag+from hyperlink_contract import (+ HYPERLINK_REL_TYPE,+ trigger_shape_hyperlink_errors,+)from ..animation_config import (MorphPair,@@ -251,10 +255,15 @@ def _find_relationship_id(rels_path: Path,rel_type: str,target: str,+ target_mode: str | None = None,) -> str | None:"""Find an existing relationship by type and target."""for rel_id, attrs in _read_relationships(rels_path).items():- if attrs.get("Type") == rel_type and attrs.get("Target") == target:+ if (+ attrs.get("Type") == rel_type+ and attrs.get("Target") == target+ and attrs.get("TargetMode") == target_mode+ ):return rel_idreturn None@@ -653,15 +662,20 @@ def _shape_relationships_supported(elem: ET.Element,rels: dict[str, dict[str, str]],) -> bool:- """Only image relationships are safe to copy into a slide master here."""+ """Return whether every shape relation can move to Master/Layout parts."""for rel_id in _relationship_ids_in_shape(elem):attrs = rels.get(rel_id)if not attrs:return False- if attrs.get("TargetMode"):- return False- if attrs.get("Type") != IMAGE_REL_TYPE:- return False+ rel_type = attrs.get("Type")+ target_mode = attrs.get("TargetMode")+ if rel_type == IMAGE_REL_TYPE and not target_mode:+ continue+ if rel_type == HYPERLINK_REL_TYPE and target_mode == "External":+ continue+ if rel_type == SLIDE_REL_TYPE and not target_mode:+ continue+ return Falsereturn True@@ -691,7 +705,8 @@ def _canonical_shape_xml(attrs = rels.get(value, {})node.set(attr_name,- f"{attrs.get('Type', '')}|{attrs.get('Target', '')}",+ f"{attrs.get('Type', '')}|{attrs.get('Target', '')}|"+ f"{attrs.get('TargetMode', '')}",)return ET.tostring(clone, encoding="utf-8")@@ -700,11 +715,37 @@ def _ensure_relationship(rels_path: Path,rel_type: str,target: str,+ target_mode: str | None = None,) -> str:- existing = _find_relationship_id(rels_path, rel_type, target)+ existing = _find_relationship_id(+ rels_path,+ rel_type,+ target,+ target_mode,+ )if existing:return existing- return _append_relationship(rels_path, rel_type, target)+ return _append_relationship(+ rels_path,+ rel_type,+ target,+ target_mode=target_mode,+ )+++def _part_name_for_relationships_path(rels_path: Path) -> str:+ """Recover one ``ppt/...`` package part from its relationship sidecar."""+ if rels_path.parent.name != "_rels" or not rels_path.name.endswith(".rels"):+ raise RuntimeError(f"Invalid PPTX relationship path: {rels_path}")+ part_path = rels_path.parent.parent / rels_path.name.removesuffix(".rels")+ parts = part_path.parts+ try:+ ppt_index = len(parts) - 1 - tuple(reversed(parts)).index("ppt")+ except ValueError as exc:+ raise RuntimeError(+ f"Relationship path is not under a ppt package: {rels_path}"+ ) from exc+ return PurePosixPath(*parts[ppt_index:]).as_posix()def _copy_shape_relationships_to_part(@@ -714,6 +755,7 @@ def _copy_shape_relationships_to_part() -> ET.Element:"""Clone a shape and retarget supported relationship ids to another part."""clone = ET.fromstring(ET.tostring(elem, encoding="utf-8"))+ target_part = _part_name_for_relationships_path(target_rels_path)for node in clone.iter():for attr_name, value in list(node.attrib.items()):if attr_name not in _REL_ATTRS:@@ -721,10 +763,22 @@ def _copy_shape_relationships_to_part(rel = slide_rels.get(value)if not rel:raise RuntimeError(f"Missing slide relationship for {value}")+ target_mode = rel.get("TargetMode")+ relationship_target = rel["Target"]+ if target_mode != "External":+ resolved_target = _resolve_package_target(+ "ppt/slides/source.xml",+ relationship_target,+ )+ relationship_target = posixpath.relpath(+ resolved_target,+ posixpath.dirname(target_part),+ )new_rid = _ensure_relationship(target_rels_path,rel["Type"],- rel["Target"],+ relationship_target,+ target_mode,)node.set(attr_name, new_rid)return clone@@ -2144,7 +2198,7 @@ def _move_template_static_shape(if not _shape_relationships_supported(shape, state.rels):raise TemplateStructureError(f"{state.spec.svg_path.name}: structure element {item.element_id!r} "- "uses a non-image or external relationship"+ "uses a relationship that cannot move to a template part")prototype_state = states[0]@@ -3776,6 +3830,8 @@ def _append_relationship(rels_path: Path,rel_type: str,target: str,+ *,+ target_mode: str | None = None,) -> str:"""Append a relationship entry with the next available rId."""with open(rels_path, 'r', encoding='utf-8') as f:@@ -3783,9 +3839,14 @@ def _append_relationship(rid_numbers = [int(match) for match in re.findall(r'Id="rId(\d+)"', rels_content)]next_rid = f'rId{max(rid_numbers, default=0) + 1}'+ mode_attr = (+ f" TargetMode={quoteattr(target_mode)}"+ if target_mode is not None+ else ""+ )rel_xml = (- f' <Relationship Id="{next_rid}" '- f'Type="{rel_type}" Target="{target}"/>'+ f" <Relationship Id={quoteattr(next_rid)} "+ f"Type={quoteattr(rel_type)} Target={quoteattr(target)}{mode_attr}/>")rels_content = rels_content.replace('</Relationships>', rel_xml + '\n</Relationships>',@@ -5341,6 +5402,13 @@ def create_pptx_with_native_svg(explicit_animation_groups = frozenset(explicit_group_ids | trigger_group_ids)+ if trigger_group_ids:+ hyperlink_trigger_errors = trigger_shape_hyperlink_errors(+ ET.parse(svg_path).getroot(),+ trigger_group_ids,+ )+ if hyperlink_trigger_errors:+ raise ValueError('; '.join(hyperlink_trigger_errors))converter_group_overrides = (explicit_animation_groups| frozenset(@@ -5359,7 +5427,9 @@ def create_pptx_with_native_svg(content_type_overrides,) = (convert_svg_to_slide_shapes(- svg_path, slide_num=slide_num, verbose=verbose,+ svg_path, slide_num=slide_num,+ slide_count=public_slide_count,+ verbose=verbose,text_flow=text_flow,image_optimize=image_optimize,image_max_dimension=image_max_dimension,@@ -5544,9 +5614,16 @@ def create_pptx_with_native_svg(extra_rels = ''for rel in rel_entries:+ target_mode = rel.get('target_mode')+ mode_attr = (+ f" TargetMode={quoteattr(target_mode)}"+ if target_mode is not None+ else ''+ )extra_rels += (- f'\n <Relationship Id="{rel["id"]}" '- f'Type="{rel["type"]}" Target="{rel["target"]}"/>'+ f"\n <Relationship Id={quoteattr(rel['id'])} "+ f"Type={quoteattr(rel['type'])} "+ f"Target={quoteattr(rel['target'])}{mode_attr}/>")rels_xml = f'''<?xml version="1.0" encoding="UTF-8" standalone="yes"?>diff --git a/skills/ppt-master/scripts/template_fill_pptx/applier.py b/skills/ppt-master/scripts/template_fill_pptx/applier.pyindex 7285f506..f97718f9 100644--- a/skills/ppt-master/scripts/template_fill_pptx/applier.py+++ b/skills/ppt-master/scripts/template_fill_pptx/applier.py@@ -8,10 +8,12 @@ from __future__ import annotationsimport tempfileimport zipfile+from dataclasses import dataclassfrom pathlib import Pathfrom typing import Anyfrom xml.etree import ElementTree as ET+from hyperlink_contract import SLIDE_JUMP_ACTIONfrom pptx_animations import (object_animation_fingerprint,validate_pptx_animation_package,@@ -30,7 +32,17 @@ from .chart_fill import ()from .clone import _make_part_allocator, deep_clone_slide_private_partsfrom .notes import _find_notes_master_target, _slide_rels_with_notes-from .ooxml import NS, REL_NS, SLIDE_REL_TYPE, _parse_slide_refs, _qn, _xml_bytes+from .ooxml import (+ NS,+ REL_NS,+ SLIDE_REL_TYPE,+ SlideRef,+ _normalize_part,+ _parse_slide_refs,+ _qn,+ _rels_name_for_part,+ _xml_bytes,+)from .package import (_add_notes_override,_add_slide_override,@@ -40,6 +52,7 @@ from .package import (_max_slide_id,_max_slide_part_number,_prune_unreferenced_parts,+ _relative_target,)from .table_fill import _apply_table_edits_to_slidefrom .text_fill import _apply_replacements_to_slide@@ -51,6 +64,201 @@ from .transitions import ()+@dataclass(frozen=True)+class _PlannedSlideClone:+ """One output slide resolved before any source relationship is rewritten."""++ offset: int+ item: dict[str, Any]+ source_slide: int+ source_ref: SlideRef+ slide_number: int+ part_name: str+ rels_name: str+ presentation_rid: str+++def _build_clone_roster(+ plan_slides: list[Any],+ slide_refs: dict[int, SlideRef],+ *,+ next_slide_number: int,+ next_rel_number: int,+) -> list[_PlannedSlideClone]:+ """Resolve every planned output slide before cloning begins."""+ roster: list[_PlannedSlideClone] = []+ for offset, raw_item in enumerate(plan_slides):+ if not isinstance(raw_item, dict):+ raise RuntimeError(f"Plan slide {offset + 1} must be an object")+ source_slide = int(raw_item.get("source_slide", 0))+ if source_slide not in slide_refs:+ raise RuntimeError(f"Plan references a missing source slide: {source_slide}")+ slide_number = next_slide_number + offset+ roster.append(+ _PlannedSlideClone(+ offset=offset,+ item=raw_item,+ source_slide=source_slide,+ source_ref=slide_refs[source_slide],+ slide_number=slide_number,+ part_name=f"ppt/slides/slide{slide_number}.xml",+ rels_name=f"ppt/slides/_rels/slide{slide_number}.xml.rels",+ presentation_rid=f"rId{next_rel_number + offset}",+ )+ )+ return roster+++_SLIDE_LAYOUT_REL_TYPE = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"+)+_SLIDE_MASTER_REL_TYPE = (+ "http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster"+)+++def _slide_jump_relationship_ids(part_root: ET.Element) -> set[str]:+ """Return relationship ids used by actual same-deck click actions."""+ relationship_attr = _qn(NS["r"], "id")+ return {+ relationship_id+ for link in part_root.iter(_qn(NS["a"], "hlinkClick"))+ if (link.attrib.get("action") or "").strip() == SLIDE_JUMP_ACTION+ if (relationship_id := (link.attrib.get(relationship_attr) or "").strip())+ }+++def _remap_slide_jump_relationships(+ part_root: ET.Element,+ relationships_root: ET.Element,+ *,+ source_owner_part: str,+ output_owner_part: str,+ owner_label: str,+ outputs_by_source_part: dict[str, list[str]],+ source_ref_by_part: dict[str, SlideRef],+ self_source_part: str | None = None,+ self_output_part: str | None = None,+) -> bool:+ """Point referenced slide-jump relationships at final output slides.++ Unreferenced ``/slide`` relationships are left untouched. A cloned slide's+ self-link follows that clone; shared layout/master links require one unique+ output for the referenced source slide.+ """+ relationship_ids = _slide_jump_relationship_ids(part_root)+ relationships = {+ rel.attrib.get("Id", ""): rel+ for rel in relationships_root.findall(_qn(REL_NS, "Relationship"))+ }+ changed = False+ for relationship_id in sorted(relationship_ids):+ rel = relationships.get(relationship_id)+ if rel is None:+ raise RuntimeError(+ f"{owner_label} has a slide jump with missing relationship "+ f"{relationship_id!r}"+ )+ if rel.attrib.get("Type") != SLIDE_REL_TYPE:+ raise RuntimeError(+ f"{owner_label} slide jump {relationship_id!r} does not use "+ "a slide relationship"+ )+ if rel.attrib.get("TargetMode") == "External":+ raise RuntimeError(+ f"{owner_label} has an external slide relationship"+ )+ target = rel.attrib.get("Target")+ if not target:+ raise RuntimeError(+ f"{owner_label} has a slide relationship without a target"+ )+ source_target_part = _normalize_part(target, source_owner_part)+ if (+ self_source_part is not None+ and self_output_part is not None+ and source_target_part == self_source_part+ ):+ output_target_part = self_output_part+ else:+ output_targets = outputs_by_source_part.get(source_target_part, [])+ source_target_ref = source_ref_by_part.get(source_target_part)+ target_label = (+ f"source slide {source_target_ref.index}"+ if source_target_ref is not None+ else source_target_part+ )+ if not output_targets:+ raise RuntimeError(+ f"{owner_label} links to omitted {target_label}; "+ "include the target exactly once or remove the link"+ )+ if len(output_targets) > 1:+ raise RuntimeError(+ f"{owner_label} links to repeated {target_label}; "+ "the output target is ambiguous"+ )+ output_target_part = output_targets[0]+ output_target = _relative_target(output_owner_part, output_target_part)+ if rel.attrib.get("Target") != output_target:+ rel.set("Target", output_target)+ changed = True+ return changed+++def _remap_reachable_shared_layer_slide_jumps(+ entries: dict[str, bytes],+ clone_roster: list[_PlannedSlideClone],+ *,+ outputs_by_source_part: dict[str, list[str]],+ source_ref_by_part: dict[str, SlideRef],+) -> None:+ """Remap links inherited from layouts and masters used by output slides."""+ pending: list[str] = []+ for clone in clone_roster:+ rels_data = entries.get(clone.rels_name)+ if not rels_data:+ continue+ rels_root = ET.fromstring(rels_data)+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("Type") != _SLIDE_LAYOUT_REL_TYPE:+ continue+ target = rel.attrib.get("Target")+ if target:+ pending.append(_normalize_part(target, clone.part_name))++ visited: set[str] = set()+ while pending:+ part_name = pending.pop()+ if part_name in visited:+ continue+ visited.add(part_name)+ part_data = entries.get(part_name)+ rels_name = _rels_name_for_part(part_name)+ rels_data = entries.get(rels_name)+ if not part_data or not rels_data:+ continue+ part_root = ET.fromstring(part_data)+ rels_root = ET.fromstring(rels_data)+ changed = _remap_slide_jump_relationships(+ part_root,+ rels_root,+ source_owner_part=part_name,+ output_owner_part=part_name,+ owner_label=part_name,+ outputs_by_source_part=outputs_by_source_part,+ source_ref_by_part=source_ref_by_part,+ )+ if changed:+ entries[rels_name] = _xml_bytes(rels_root)+ for rel in rels_root.findall(_qn(REL_NS, "Relationship")):+ if rel.attrib.get("Type") != _SLIDE_MASTER_REL_TYPE:+ continue+ target = rel.attrib.get("Target")+ if target:+ pending.append(_normalize_part(target, part_name))++def apply_plan(pptx_path: Path,plan: dict[str, Any],@@ -90,15 +298,25 @@ def apply_plan(allocate_part = _make_part_allocator(entries)wrote_auto_advance = False- for offset, item in enumerate(plan_slides):- source_slide = int(item.get("source_slide", 0))- if source_slide not in slide_refs:- raise RuntimeError(f"Plan references a missing source slide: {source_slide}")- source_ref = slide_refs[source_slide]- new_slide_number = next_slide_number + offset- new_part = f"ppt/slides/slide{new_slide_number}.xml"- new_rels = f"ppt/slides/_rels/slide{new_slide_number}.xml.rels"- new_rid = f"rId{next_rel_number + offset}"+ clone_roster = _build_clone_roster(+ plan_slides,+ slide_refs,+ next_slide_number=next_slide_number,+ next_rel_number=next_rel_number,+ )+ source_ref_by_part = {ref.part_name: ref for ref in slide_refs.values()}+ outputs_by_source_part: dict[str, list[str]] = {}+ for clone in clone_roster:+ outputs_by_source_part.setdefault(clone.source_ref.part_name, []).append(clone.part_name)++ for clone in clone_roster:+ item = clone.item+ source_slide = clone.source_slide+ source_ref = clone.source_ref+ new_slide_number = clone.slide_number+ new_part = clone.part_name+ new_rels = clone.rels_name+ new_rid = clone.presentation_ridsource_slide_xml = entries[source_ref.part_name]source_animation_fingerprint = object_animation_fingerprint(@@ -143,6 +361,17 @@ def apply_plan(source_rels = entries.get(source_ref.rels_name)slide_rels_root = ET.fromstring(source_rels) if source_rels else _empty_relationships_root()+ _remap_slide_jump_relationships(+ slide_root,+ slide_rels_root,+ source_owner_part=source_ref.part_name,+ output_owner_part=new_part,+ owner_label=f"Source slide {source_slide}",+ outputs_by_source_part=outputs_by_source_part,+ source_ref_by_part=source_ref_by_part,+ self_source_part=source_ref.part_name,+ self_output_part=new_part,+ )deep_clone_slide_private_parts(slide_rels_root,new_slide_part=new_part,@@ -203,9 +432,19 @@ def apply_plan(ET.SubElement(sld_id_lst,_qn(NS["p"], "sldId"),- {"id": str(next_slide_id + offset), _qn(NS["r"], "id"): new_rid},+ {+ "id": str(next_slide_id + clone.offset),+ _qn(NS["r"], "id"): new_rid,+ },)+ _remap_reachable_shared_layer_slide_jumps(+ entries,+ clone_roster,+ outputs_by_source_part=outputs_by_source_part,+ source_ref_by_part=source_ref_by_part,+ )+entries["ppt/presentation.xml"] = _xml_bytes(pres_root)entries["ppt/_rels/presentation.xml.rels"] = _xml_bytes(pres_rels_root)_prune_unreferenced_parts(entries, content_root)