Skip to content

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

feat(text-layout): add explicit paragraph break contracts

hugohe3edb9358b9fcf
diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.py
index 05781a47..947afc57 100644
--- a/skills/ppt-master/scripts/finalize_svg.py
+++ b/skills/ppt-master/scripts/finalize_svg.py
@@ -57,6 +57,7 @@ from svg_to_pptx.geometry_properties import (
GeometryStyleError,
materialize_inline_geometry_in_file,
)
+from svg_to_pptx.text_contract import RUNTIME_ATTRS, TextContractError
from svg_to_pptx.use_expander import (
UseExpansionError,
expand_local_use_references_in_file,
@@ -89,13 +90,22 @@ def process_flatten_text(svg_file: Path, verbose: bool = False) -> bool:
from xml.etree import ElementTree as ET
tree = ET.parse(str(svg_file))
- changed = flatten_text_with_tspans(tree)
+ changed = flatten_text_with_tspans(
+ tree,
+ enforce_native_carrier=False,
+ source_name=svg_file.name,
+ )
if changed:
+ for element in tree.getroot().iter():
+ for attribute in RUNTIME_ATTRS:
+ element.attrib.pop(attribute, None)
tree.write(str(svg_file), encoding='unicode', xml_declaration=False)
if verbose:
safe_print(f" [OK] {svg_file.name}: text flattened")
return changed
+ except TextContractError:
+ raise
except Exception as e:
if verbose:
safe_print(f" [ERROR] {svg_file.name}: {e}")
@@ -361,10 +371,19 @@ Aliases (still accepted):
safe_print("[ERROR] --image-scale must be >= 1")
sys.exit(1)
- success = finalize_project(args.project_dir, options, args.dry_run, args.quiet,
- compress=args.compress,
- max_dimension=args.max_dimension,
- image_scale=args.image_scale)
+ try:
+ success = finalize_project(
+ args.project_dir,
+ options,
+ args.dry_run,
+ args.quiet,
+ compress=args.compress,
+ max_dimension=args.max_dimension,
+ image_scale=args.image_scale,
+ )
+ except TextContractError as exc:
+ safe_print(f"[ERROR] {exc.format()}")
+ sys.exit(1)
sys.exit(0 if success else 1)
diff --git a/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py b/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py
index 88cea092..52471f82 100644
--- a/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py
+++ b/skills/ppt-master/scripts/pptx_shapes/semantic_hash.py
@@ -39,6 +39,13 @@ _ROOT_TEXT_STYLE_ATTRS = frozenset({
"word-spacing",
})
+_TEXT_CONTRACT_ATTRS = frozenset({
+ "data-pptx-text-mode",
+ "data-pptx-text-bounds",
+ "data-pptx-break",
+ "data-pptx-join",
+})
+
NATIVE_FALLBACK_SHA256_ATTR = "data-pptx-fallback-sha256"
_NATIVE_FALLBACK_IGNORED_TAGS = frozenset({"metadata", "title", "desc"})
_NATIVE_FALLBACK_IGNORED_ATTRS = frozenset({
@@ -239,6 +246,7 @@ def _preview_subtree(
if name != "id"
and name != "data-pptx-preview-sha256"
and not name.startswith("data-pptx-runtime-")
+ and name not in _TEXT_CONTRACT_ATTRS
),
"children": children,
}
@@ -438,7 +446,11 @@ def _element_payload(element: ET.Element) -> dict:
"attrs": sorted(
(name, value)
for name, value in element.attrib.items()
- if not name.startswith("data-pptx-") and name != "id"
+ if name != "id"
+ and (
+ not name.startswith("data-pptx-")
+ or name in _TEXT_CONTRACT_ATTRS
+ )
),
"text": element.text or "",
"children": [
diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
index 2cbb5270..01468011 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
@@ -40,7 +40,7 @@ from .color_resolver import ColorPalette, find_color_elem, resolve_color
from .chart_to_svg import CHART_URI, CHARTEX_URI, extract_native_chart_payload
from .custgeom_to_svg import convert_custom_geom
from .effect_to_svg import convert_effects
-from .emu_units import NS, Xfrm, fmt_num
+from .emu_units import NS, Xfrm, fmt_num, ooxml_bool
from .fill_to_svg import resolve_fill
from .ln_to_svg import resolve_stroke
from .ooxml_loader import OoxmlPackage, PartRef, SlideRef
@@ -61,6 +61,9 @@ from .txbody_to_svg import (
)
+_TEXT_CARRIER_VERSION = "1"
+
+
# ---------------------------------------------------------------------------
# AssemblyContext
# ---------------------------------------------------------------------------
@@ -285,17 +288,33 @@ def assemble_part_solo(
# Per-node dispatch
# ---------------------------------------------------------------------------
-def _convert_node(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
+def _convert_node(
+ node: ShapeNode,
+ ctx: AssemblyContext,
+ *,
+ top_level: bool,
+ transformed_ancestor: bool = False,
+) -> str:
if node.hidden and not ctx.keep_hidden:
return ""
if node.kind == SHAPE:
- return _convert_shape(node, ctx, top_level=top_level)
+ return _convert_shape(
+ node,
+ ctx,
+ top_level=top_level,
+ transformed_ancestor=transformed_ancestor,
+ )
if node.kind == PICTURE:
return _convert_picture(node, ctx, top_level=top_level)
if node.kind == CONNECTOR:
return _convert_connector(node, ctx, top_level=top_level)
if node.kind == GROUP:
- return _convert_group(node, ctx, top_level=top_level)
+ return _convert_group(
+ node,
+ ctx,
+ top_level=top_level,
+ transformed_ancestor=transformed_ancestor,
+ )
if node.kind == GRAPHIC:
return _convert_graphic_fallback(node, ctx, top_level=top_level)
return ""
@@ -305,7 +324,13 @@ def _convert_node(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->
# Shape (<p:sp>)
# ---------------------------------------------------------------------------
-def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
+def _convert_shape(
+ node: ShapeNode,
+ ctx: AssemblyContext,
+ *,
+ top_level: bool,
+ transformed_ancestor: bool,
+) -> str:
sp_pr = node.xml.find("p:spPr", NS)
# Check for blipFill (image-filled shape, e.g. Canva exports where images
@@ -389,6 +414,16 @@ def _convert_shape(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) ->
text_result.svg,
)
)
+ inner_parts.append(
+ _text_carrier_metadata(
+ node,
+ sp_pr,
+ tx_body,
+ is_vertical=is_vertical,
+ has_blip_fill=blip_fill_elem is not None,
+ transformed_ancestor=transformed_ancestor,
+ )
+ )
if text_result.svg:
inner_parts.append(text_result.svg)
inner = "\n".join(inner_parts) if inner_parts else ""
@@ -422,6 +457,148 @@ def _txbody_metadata(
)
+def _style_ref_is_visible(node: ShapeNode, ref_name: str) -> bool:
+ """Return whether a shape-style reference selects a visible style entry."""
+ style = node.xml.find("p:style", NS)
+ ref = style.find(f"a:{ref_name}", NS) if style is not None else None
+ if ref is None:
+ return False
+ raw_idx = ref.get("idx")
+ if raw_idx is None:
+ return True
+ try:
+ return int(raw_idx) > 0
+ except ValueError:
+ return True
+
+
+def _has_visible_shape_fill(node: ShapeNode, sp_pr: ET.Element | None) -> bool:
+ """Return whether the source shape owns a visible non-image fill."""
+ if sp_pr is not None:
+ if sp_pr.find("a:noFill", NS) is not None:
+ return False
+ if any(
+ sp_pr.find(f"a:{tag}", NS) is not None
+ for tag in ("solidFill", "gradFill", "pattFill", "grpFill")
+ ):
+ return True
+ return _style_ref_is_visible(node, "fillRef")
+
+
+def _has_visible_shape_line(node: ShapeNode, sp_pr: ET.Element | None) -> bool:
+ """Return whether the source shape owns a visible outline."""
+ line = sp_pr.find("a:ln", NS) if sp_pr is not None else None
+ if line is not None:
+ return line.find("a:noFill", NS) is None
+ return _style_ref_is_visible(node, "lnRef")
+
+
+def _has_visible_shape_effect(node: ShapeNode, sp_pr: ET.Element | None) -> bool:
+ """Return whether the source shape owns a visible effect or 3D treatment."""
+ if sp_pr is not None:
+ for tag in ("effectLst", "effectDag"):
+ effect = sp_pr.find(f"a:{tag}", NS)
+ if effect is not None and len(effect):
+ return True
+ if any(
+ sp_pr.find(f"a:{tag}", NS) is not None
+ for tag in ("scene3d", "sp3d")
+ ):
+ return True
+ return _style_ref_is_visible(node, "effectRef")
+
+
+def _text_carrier_ineligibility_reasons(
+ node: ShapeNode,
+ sp_pr: ET.Element | None,
+ tx_body: ET.Element,
+ nv_sp_pr: ET.Element | None,
+ *,
+ is_vertical: bool,
+ has_blip_fill: bool,
+ transformed_ancestor: bool,
+) -> list[str]:
+ """Return stable reasons why a native text carrier is unsafe to rewrite."""
+ reasons: list[str] = []
+ c_nv_sp_pr = (
+ nv_sp_pr.find("p:cNvSpPr", NS)
+ if nv_sp_pr is not None
+ else None
+ )
+ owns_text_frame = (
+ node.placeholder is not None
+ or (
+ c_nv_sp_pr is not None
+ and ooxml_bool(c_nv_sp_pr.get("txBox"))
+ )
+ )
+
+ if is_vertical:
+ reasons.append("vertical-text")
+ if (
+ transformed_ancestor
+ or abs(node.xfrm.rot) > 1e-9
+ or node.xfrm.flip_h
+ or node.xfrm.flip_v
+ ):
+ reasons.append("rotated-or-flipped")
+ if not owns_text_frame:
+ reasons.append("missing-frame-owner")
+ if has_blip_fill:
+ reasons.append("blip-fill")
+ if _has_visible_shape_fill(node, sp_pr):
+ reasons.append("visible-fill")
+ if _has_visible_shape_line(node, sp_pr):
+ reasons.append("visible-line")
+ if _has_visible_shape_effect(node, sp_pr):
+ reasons.append("visible-effect")
+ if has_relationship_attributes(tx_body):
+ reasons.append("txbody-relationships")
+ if nv_sp_pr is None:
+ reasons.append("missing-nvsppr")
+ elif has_relationship_attributes(nv_sp_pr):
+ reasons.append("nvsppr-relationships")
+ return reasons
+
+
+def _text_carrier_metadata(
+ node: ShapeNode,
+ sp_pr: ET.Element | None,
+ tx_body: ET.Element,
+ *,
+ is_vertical: bool,
+ has_blip_fill: bool,
+ transformed_ancestor: bool,
+) -> str:
+ """Describe whether a native text frame can accept a rebuilt txBody."""
+ nv_sp_pr = node.xml.find("p:nvSpPr", NS)
+ reasons = _text_carrier_ineligibility_reasons(
+ node,
+ sp_pr,
+ tx_body,
+ nv_sp_pr,
+ is_vertical=is_vertical,
+ has_blip_fill=has_blip_fill,
+ transformed_ancestor=transformed_ancestor,
+ )
+ eligible = not reasons
+ reason = ",".join(reasons) if reasons else "eligible"
+ attrs = [
+ 'data-pptx-part="text-carrier"',
+ f'data-pptx-text-carrier-version="{_TEXT_CARRIER_VERSION}"',
+ f'data-pptx-text-carrier-eligible="{1 if eligible else 0}"',
+ f'data-pptx-text-carrier-reason="{reason}"',
+ ]
+
+ if nv_sp_pr is None or has_relationship_attributes(nv_sp_pr):
+ return f'<metadata {" ".join(attrs)}/>'
+
+ raw = ET.tostring(nv_sp_pr, encoding="utf-8")
+ encoded = base64.b64encode(raw).decode("ascii")
+ attrs.append('data-pptx-encoding="base64"')
+ return f'<metadata {" ".join(attrs)}>{encoded}</metadata>'
+
+
def _resolve_geometry(node: ShapeNode, sp_pr: ET.Element | None) -> GeomResult | None:
"""Resolve a DrawingML shape geometry into an absolute SVG geometry model."""
prst_geom = sp_pr.find("a:prstGeom", NS) if sp_pr is not None else None
@@ -680,11 +857,28 @@ def _convert_connector(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool
# Group (<p:grpSp>)
# ---------------------------------------------------------------------------
-def _convert_group(node: ShapeNode, ctx: AssemblyContext, *, top_level: bool) -> str:
+def _convert_group(
+ node: ShapeNode,
+ ctx: AssemblyContext,
+ *,
+ top_level: bool,
+ transformed_ancestor: bool,
+) -> str:
"""Render group contents flat (children already remapped to slide space)."""
inner_parts: list[str] = []
+ child_has_transformed_ancestor = (
+ transformed_ancestor
+ or abs(node.xfrm.rot) > 1e-9
+ or node.xfrm.flip_h
+ or node.xfrm.flip_v
+ )
for child in node.children:
- chunk = _convert_node(child, ctx, top_level=False)
+ chunk = _convert_node(
+ child,
+ ctx,
+ top_level=False,
+ transformed_ancestor=child_has_transformed_ancestor,
+ )
if chunk:
inner_parts.append(chunk)
if not inner_parts:
diff --git a/skills/ppt-master/scripts/svg_editor/annotations.py b/skills/ppt-master/scripts/svg_editor/annotations.py
index 7a02353c..e43ea892 100644
--- a/skills/ppt-master/scripts/svg_editor/annotations.py
+++ b/skills/ppt-master/scripts/svg_editor/annotations.py
@@ -158,6 +158,8 @@ def promote_tspan_to_text(
return False, 'not-found'
if _local_name(target) != 'tspan' or _local_name(text_el) != 'text':
return False, 'not-tspan'
+ if text_el.get('data-pptx-text-mode') == 'paragraph':
+ return False, 'explicit-paragraph-line-move'
grandparent: Optional[ET.Element] = None
for candidate in root.iter():
diff --git a/skills/ppt-master/scripts/svg_editor/server.py b/skills/ppt-master/scripts/svg_editor/server.py
index a595880b..e960265f 100644
--- a/skills/ppt-master/scripts/svg_editor/server.py
+++ b/skills/ppt-master/scripts/svg_editor/server.py
@@ -242,6 +242,10 @@ _UNSAFE_COLOR_RE = re.compile(r'[;:@\\]|url\s*\(', re.IGNORECASE)
_SAFE_ATTR_NAME_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_.:-]*$')
_MAX_ATTR_VALUE_LEN = 256
_MAX_EDIT_TEXT_LEN = 5000
+_PURE_TRANSLATE_RE = re.compile(
+ r'^\s*(?:translate\(\s*[-+]?\d+(?:\.\d+)?'
+ r'(?:(?:\s*,\s*|\s+)[-+]?\d+(?:\.\d+)?)?\s*\)\s*)+$'
+)
_ADDABLE_BATCH_ATTRS = frozenset({
'fill', 'stroke', 'opacity',
'font-size', 'font-family', 'font-weight', 'text-anchor',
@@ -314,6 +318,42 @@ def _find_by_id(root: ET.Element, element_id: str) -> Optional[ET.Element]:
return None
+def _explicit_paragraph_owner(
+ root: ET.Element,
+ target: ET.Element,
+) -> Optional[ET.Element]:
+ """Return the explicit paragraph <text> owning target, if any."""
+ for candidate in root.iter():
+ tag = candidate.tag.split('}', 1)[-1]
+ if tag != 'text' or candidate.get('data-pptx-text-mode') != 'paragraph':
+ continue
+ if candidate is target or target in candidate.iter():
+ return candidate
+ return None
+
+
+def _validate_explicit_paragraph_edit(
+ root: ET.Element,
+ target: ET.Element,
+ attrs: dict,
+) -> Optional[str]:
+ """Protect paragraph frame/visual-line ownership in Live Preview."""
+ owner = _explicit_paragraph_owner(root, target)
+ if owner is None:
+ return None
+ if target is not owner and {'x', 'y', 'dy', 'transform'} & attrs.keys():
+ return 'explicit paragraph lines cannot be moved independently; switch to lines mode'
+ if target is owner and {'x', 'y'} & attrs.keys():
+ return 'move an explicit paragraph with a pure translate, not parent x/y'
+ if target is owner and 'data-pptx-text-bounds' in attrs:
+ return 'explicit paragraph bounds require a dedicated frame edit operation'
+ if target is owner and 'transform' in attrs:
+ transform = attrs.get('transform')
+ if transform is not None and not _PURE_TRANSLATE_RE.fullmatch(transform):
+ return 'explicit paragraphs only support pure translate transforms'
+ return None
+
+
def _apply_edit_record(root: ET.Element, record: dict) -> tuple[bool, Optional[str]]:
element_id = record.get('element_id')
if not isinstance(element_id, str):
@@ -339,6 +379,9 @@ def _apply_edit_record(root: ET.Element, record: dict) -> tuple[bool, Optional[s
target = _find_by_id(root, element_id)
if target is None:
return False, 'not-found'
+ paragraph_error = _validate_explicit_paragraph_edit(root, target, attrs)
+ if paragraph_error:
+ return False, paragraph_error
_strip_edited_inline_geometry(target, attrs.keys())
ok, reason = set_attributes(root, element_id, attrs)
if not ok:
@@ -788,6 +831,9 @@ def create_app(
attr_err = _validate_edit_attrs(attrs, set(target.attrib.keys()))
if attr_err:
return jsonify({'error': attr_err}), 400
+ paragraph_error = _validate_explicit_paragraph_edit(root, target, attrs)
+ if paragraph_error:
+ return jsonify({'error': paragraph_error}), 400
changes = []
staged: dict = {'element_id': element_id}
diff --git a/skills/ppt-master/scripts/svg_editor/static/app.js b/skills/ppt-master/scripts/svg_editor/static/app.js
index 6327536e..0bf04c88 100644
--- a/skills/ppt-master/scripts/svg_editor/static/app.js
+++ b/skills/ppt-master/scripts/svg_editor/static/app.js
@@ -1886,6 +1886,10 @@
function renderEditableProps(el) {
var tag = localName(el);
var isGroup = tag === "g";
+ var isExplicitParagraph = tag === "text" &&
+ el.getAttribute("data-pptx-text-mode") === "paragraph";
+ var paragraphOwner = explicitParagraphOwner(el);
+ var isExplicitParagraphLine = paragraphOwner && paragraphOwner !== el;
var html = '<div class="prop-caption">' +
escapeHtml(isGroup ? t("label_group_edit") : t("label_direct_edit")) + '</div>';
@@ -1897,22 +1901,26 @@
'</button></td></tr></table>';
}
- html += '<div class="prop-section">' + escapeHtml(t("section_geometry")) + '</div>';
- html += '<table class="prop-table">';
- // Geometry: position + size in render coords — editable, folded into
- // the element's transform matrix on commit (works for any element type).
- try {
- var rb = computeRenderBox(el);
- html += '<tr><td class="prop-key">position</td><td class="prop-val geo-cell">' +
- '<input type="number" class="prop-edit prop-edit-geo" data-geo="x" value="' + Math.round(rb.x) + '">' +
- '<input type="number" class="prop-edit prop-edit-geo" data-geo="y" value="' + Math.round(rb.y) + '">' +
- '</td></tr>';
- html += '<tr><td class="prop-key">size</td><td class="prop-val geo-cell">' +
- '<input type="number" class="prop-edit prop-edit-geo" data-geo="w" min="1" value="' + Math.round(rb.w) + '">' +
- '<input type="number" class="prop-edit prop-edit-geo" data-geo="h" min="1" value="' + Math.round(rb.h) + '">' +
- '</td></tr>';
- } catch (e) { /* no geometry */ }
- html += '</table>';
+ if (!isExplicitParagraphLine) {
+ html += '<div class="prop-section">' + escapeHtml(t("section_geometry")) + '</div>';
+ html += '<table class="prop-table">';
+ // Geometry: position + size in render coords — editable, folded into
+ // the element's transform matrix on commit (works for any element type).
+ try {
+ var rb = computeRenderBox(el);
+ html += '<tr><td class="prop-key">position</td><td class="prop-val geo-cell">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="x" value="' + Math.round(rb.x) + '">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="y" value="' + Math.round(rb.y) + '">' +
+ '</td></tr>';
+ if (!isExplicitParagraph) {
+ html += '<tr><td class="prop-key">size</td><td class="prop-val geo-cell">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="w" min="1" value="' + Math.round(rb.w) + '">' +
+ '<input type="number" class="prop-edit prop-edit-geo" data-geo="h" min="1" value="' + Math.round(rb.h) + '">' +
+ '</td></tr>';
+ }
+ } catch (e) { /* no geometry */ }
+ html += '</table>';
+ }
var textStyleTargets = textStyleTargetsForSelection(el);
@@ -1966,13 +1974,22 @@
function ownAttributeSpecs(el) {
var specs = [];
+ var paragraphOwner = explicitParagraphOwner(el);
Array.from(el.attributes).forEach(function (attr) {
var key = attr.name;
if (key === "class" || key === "data-edit-target" || key === "data-edit-annotation") return;
+ var paragraphLocked = paragraphOwner && (
+ (paragraphOwner === el && [
+ "x", "y", "transform", "data-pptx-text-bounds"
+ ].indexOf(key) !== -1) ||
+ (paragraphOwner !== el && [
+ "x", "y", "dy", "transform"
+ ].indexOf(key) !== -1)
+ );
specs.push({
key: key,
value: attr.value,
- editable: isEditableAttributeName(key)
+ editable: isEditableAttributeName(key) && !paragraphLocked
});
});
return specs;
@@ -2372,6 +2389,23 @@
}
function rawMoveAttrs(el, dx, dy) {
+ var paragraphOwner = explicitParagraphOwner(el);
+ if (paragraphOwner) {
+ if (paragraphOwner !== el) return null;
+ var paragraphOwn = ownMatrix(el);
+ var paragraphClose = function (a, b) { return Math.abs(a - b) < 1e-6; };
+ if (!paragraphClose(paragraphOwn.a, 1) || !paragraphClose(paragraphOwn.b, 0) ||
+ !paragraphClose(paragraphOwn.c, 0) || !paragraphClose(paragraphOwn.d, 1)) {
+ return null;
+ }
+ var paragraphDelta = parentDelta(dx, dy, el);
+ if (!paragraphDelta) return null;
+ var tx = paragraphOwn.e + paragraphDelta.x;
+ var ty = paragraphOwn.f + paragraphDelta.y;
+ return {
+ transform: "translate(" + formatCoord(tx) + " " + formatCoord(ty) + ")"
+ };
+ }
if (localName(el) === "g" && el.hasAttribute("data-icon") &&
el.hasAttribute("data-use-x") && el.hasAttribute("data-use-y")) {
var iconOwn = ownMatrix(el);
@@ -2462,6 +2496,8 @@
}
function attrsForMove(el, dx, dy) {
+ var paragraphOwner = explicitParagraphOwner(el);
+ if (paragraphOwner && paragraphOwner !== el) return null;
var attrs = rawMoveAttrs(el, dx, dy);
if (attrs) return attrs;
var rb = computeRenderBox(el);
@@ -2470,6 +2506,18 @@
return tstr ? { transform: tstr } : null;
}
+ function explicitParagraphOwner(el) {
+ var candidate = el;
+ while (candidate && candidate !== svgContent) {
+ if (localName(candidate) === "text" &&
+ candidate.getAttribute("data-pptx-text-mode") === "paragraph") {
+ return candidate;
+ }
+ candidate = candidate.parentElement;
+ }
+ return null;
+ }
+
function computeElementsBox(elements) {
var minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
elements.forEach(function (el) {
diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index 1a09efc1..f2007922 100644
--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -2,6 +2,7 @@ import os
import sys
import re
import argparse
+import weakref
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -10,6 +11,21 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from svg_to_pptx.text_contract import ( # noqa: E402
+ RUNTIME_CONTRACT_ATTR,
+ RUNTIME_EFFECTIVE_MODE_ATTR,
+ RUNTIME_LINE_COUNT_ATTR,
+ RUNTIME_LINE_INDEX_ATTR,
+ RUNTIME_MODE_REASON_ATTR,
+ RUNTIME_REQUESTED_MODE_ATTR,
+ RUNTIME_SOURCE_ID_ATTR,
+ TEXT_BOUNDS_ATTR,
+ TEXT_BREAK_ATTR,
+ TEXT_JOIN_ATTR,
+ TEXT_MODE_ATTR,
+ TextBlockContract,
+ validate_text_contracts,
+)
configure_utf8_stdio()
@@ -20,6 +36,8 @@ NSMAP = {"svg": SVG_NS}
# Ensure pretty element names without ns0 prefix on write
ET.register_namespace("", SVG_NS)
+_NORMALIZED_ROOTS: weakref.WeakSet[ET.Element] = weakref.WeakSet()
+
TEXT_STYLE_ATTRS = {
# common text styling
@@ -184,6 +202,7 @@ def copy_text_attrs(
PARAGRAPH_MARK_ATTR = "data-paragraph-line-height"
PARAGRAPH_SPACE_BEFORE_ATTR = "data-paragraph-space-before"
+PARAGRAPH_TOP_INSET_ATTR = "data-paragraph-top-inset"
# Marks a line-break tspan as a SOFT break inside the current paragraph
# (SVG used dy to simulate text wrapping; the downstream converter should
# merge its runs into the previous <a:p> rather than start a new one).
@@ -382,7 +401,7 @@ def _classify_paragraph_block(
def _emit_mergeable_paragraph(
text_el: ET.Element,
- base_dy: float,
+ base_dy: float | None,
extras: list[float],
soft_breaks: list[bool],
line_groups: list[list[ET.Element]],
@@ -398,7 +417,10 @@ def _emit_mergeable_paragraph(
- PARAGRAPH_SPACE_BEFORE_ATTR on tspans that open a new paragraph
with an extra gap (omitted when 0)
"""
- text_el.set(PARAGRAPH_MARK_ATTR, format_number(base_dy))
+ if base_dy is not None:
+ text_el.set(PARAGRAPH_MARK_ATTR, format_number(base_dy))
+ else:
+ text_el.attrib.pop(PARAGRAPH_MARK_ATTR, None)
if synthetic_first is not None:
text_el.text = None
text_el.insert(0, synthetic_first)
@@ -442,9 +464,101 @@ def _emit_mergeable_paragraph(
tspan.set(PARAGRAPH_SPACE_BEFORE_ATTR, format_number(extra))
+def _set_runtime_contract_attrs(
+ elem: ET.Element,
+ contract: TextBlockContract,
+ *,
+ effective_mode: str,
+ reason: str,
+ line_index: int | None = None,
+ line_count: int | None = None,
+) -> None:
+ """Attach rendering-neutral runtime provenance to a normalized text node."""
+ if contract.preserve_space:
+ elem.set("{http://www.w3.org/XML/1998/namespace}space", "preserve")
+ elem.set(RUNTIME_CONTRACT_ATTR, "1")
+ elem.set(RUNTIME_SOURCE_ID_ATTR, contract.element_id)
+ elem.set(RUNTIME_REQUESTED_MODE_ATTR, contract.requested_mode)
+ elem.set(RUNTIME_EFFECTIVE_MODE_ATTR, effective_mode)
+ elem.set(RUNTIME_MODE_REASON_ATTR, reason)
+ if line_index is not None:
+ elem.set(RUNTIME_LINE_INDEX_ATTR, str(line_index))
+ if line_count is not None:
+ elem.set(RUNTIME_LINE_COUNT_ATTR, str(line_count))
+
+
+def _strip_public_contract_from_split_line(elem: ET.Element) -> None:
+ """Remove block/break author metadata after a block becomes line frames."""
+ elem.attrib.pop(TEXT_MODE_ATTR, None)
+ elem.attrib.pop(TEXT_BOUNDS_ATTR, None)
+ for descendant in elem.iter():
+ descendant.attrib.pop(TEXT_BREAK_ATTR, None)
+ descendant.attrib.pop(TEXT_JOIN_ATTR, None)
+
+
+def _mark_split_lines(
+ new_texts: list[ET.Element],
+ contract: TextBlockContract,
+ *,
+ reason: str,
+) -> None:
+ """Record one explicit source block on every independent runtime line."""
+ line_count = len(new_texts)
+ for line_index, line in enumerate(new_texts, start=1):
+ _strip_public_contract_from_split_line(line)
+ _set_runtime_contract_attrs(
+ line,
+ contract,
+ effective_mode="lines",
+ reason=reason,
+ line_index=line_index,
+ line_count=line_count,
+ )
+
+
+def _emit_explicit_paragraph(
+ text_el: ET.Element,
+ contract: TextBlockContract,
+) -> None:
+ """Normalize a validated explicit paragraph into the existing internal IR."""
+ if text_el.get("x") is None and contract.anchor_x is not None:
+ text_el.set("x", format_number(contract.anchor_x))
+ if text_el.get("y") is None and contract.anchor_y is not None:
+ text_el.set("y", format_number(contract.anchor_y))
+
+ line_groups = [list(line.elements) for line in contract.visual_lines]
+ extras = [line.space_before for line in contract.visual_lines]
+ soft_breaks = [line.break_kind == "soft" for line in contract.visual_lines]
+ _emit_mergeable_paragraph(
+ text_el,
+ contract.base_line_height,
+ extras,
+ soft_breaks,
+ line_groups,
+ )
+
+ if contract.top_inset is not None:
+ text_el.set(PARAGRAPH_TOP_INSET_ATTR, format_number(contract.top_inset))
+ _set_runtime_contract_attrs(
+ text_el,
+ contract,
+ effective_mode="paragraph",
+ reason="explicit-paragraph",
+ line_count=len(contract.visual_lines),
+ )
+ for line_index, line in enumerate(list(text_el), start=1):
+ if line.tag != f"{{{SVG_NS}}}tspan":
+ continue
+ line.set(RUNTIME_LINE_INDEX_ATTR, str(line_index))
+ line.set(RUNTIME_LINE_COUNT_ATTR, str(len(contract.visual_lines)))
+
+
def flatten_text_with_tspans(
tree: ET.ElementTree,
merge_paragraphs: bool = False,
+ *,
+ enforce_native_carrier: bool = True,
+ source_name: str | None = None,
) -> bool:
"""Flatten multi-line tspan text into independent text nodes when needed.
@@ -453,9 +567,18 @@ def flatten_text_with_tspans(
so downstream conversion emits one editable PowerPoint text frame
with multiple <a:p>. Default False preserves the original behavior:
every line-break tspan becomes its own <text>, matching the SVG's
- pixel-fidelity contract.
+ pixel-fidelity contract. ``enforce_native_carrier=False`` is reserved for
+ that on-disk visual preview; PPTX export keeps the native carrier guard.
"""
root = tree.getroot()
+ if root in _NORMALIZED_ROOTS:
+ return False
+ contracts = validate_text_contracts(
+ root,
+ merge_paragraphs=merge_paragraphs,
+ enforce_native_carrier=enforce_native_carrier,
+ source_name=source_name,
+ )
parent_map = {c: p for p in root.iter() for c in p}
changed = False
@@ -483,13 +606,23 @@ def flatten_text_with_tspans(
for el in root.iter():
if is_svg_tag(el, "text"):
has_tspan_child = any(is_svg_tag(c, "tspan") for c in list(el))
- if has_tspan_child:
+ if has_tspan_child or el in contracts:
candidates.append(el)
for text_el in candidates:
parent = parent_map.get(text_el)
if parent is None:
continue
+ contract = contracts.get(text_el)
+
+ if (
+ contract is not None
+ and contract.requested_mode == "paragraph"
+ and merge_paragraphs
+ ):
+ _emit_explicit_paragraph(text_el, contract)
+ changed = True
+ continue
# First check whether any tspan needs flattening (dy != 0 or has its own y attribute)
needs_flatten = False
@@ -502,6 +635,23 @@ def flatten_text_with_tspans(
# If no tspan needs a line break, skip the entire text element
if not needs_flatten:
+ if contract is not None:
+ reason = (
+ "cli-no-merge"
+ if not merge_paragraphs
+ else "explicit-lines"
+ if contract.requested_mode == "lines"
+ else "legacy-auto-single-line"
+ )
+ _set_runtime_contract_attrs(
+ text_el,
+ contract,
+ effective_mode="lines",
+ reason=reason,
+ line_index=1,
+ line_count=1,
+ )
+ changed = True
continue
# Paragraph fast-path (opt-in via merge_paragraphs=True): if the
@@ -511,7 +661,10 @@ def flatten_text_with_tspans(
# converter emit multiple <a:p> runs. When disabled, every tspan
# gets its own independent <text> so the SVG's exact line layout
# is preserved in PowerPoint.
- if merge_paragraphs:
+ if (
+ merge_paragraphs
+ and (contract is None or contract.requested_mode == "auto")
+ ):
paragraph = _classify_paragraph_block(text_el, is_svg_tag, is_new_line_tspan)
if paragraph is not None:
base_dy, extras, soft_breaks, line_groups, synthetic_first = paragraph
@@ -523,6 +676,18 @@ def flatten_text_with_tspans(
line_groups,
synthetic_first=synthetic_first,
)
+ if contract is not None:
+ _set_runtime_contract_attrs(
+ text_el,
+ contract,
+ effective_mode="paragraph",
+ reason="legacy-auto-merge",
+ line_count=len(line_groups),
+ )
+ for line_index, line in enumerate(list(text_el), start=1):
+ if is_svg_tag(line, "tspan"):
+ line.set(RUNTIME_LINE_INDEX_ATTR, str(line_index))
+ line.set(RUNTIME_LINE_COUNT_ATTR, str(len(line_groups)))
changed = True
continue
@@ -574,6 +739,15 @@ def flatten_text_with_tspans(
new_texts.append(ne)
if new_texts:
+ if contract is not None:
+ if not merge_paragraphs:
+ reason = "cli-no-merge"
+ elif contract.requested_mode == "lines":
+ reason = "explicit-lines"
+ else:
+ reason = "legacy-auto-split"
+ _mark_split_lines(new_texts, contract, reason=reason)
+
# Replace original <text> with the list of new <text> nodes
try:
idx = list(parent).index(text_el)
@@ -591,6 +765,8 @@ def flatten_text_with_tspans(
parent.remove(text_el)
changed = True
+ if changed:
+ _NORMALIZED_ROOTS.add(root)
return changed
@@ -649,6 +825,12 @@ def _create_text_element_from_line(
tspan = tspans[0]
content = collect_text_content(tspan)
+ if text_el.get(TEXT_MODE_ATTR) is not None:
+ xml_space_attr = "{http://www.w3.org/XML/1998/namespace}space"
+ child_xml_space = tspan.get(xml_space_attr) or tspan.get("xml:space")
+ if child_xml_space is not None:
+ ne.set(xml_space_attr, child_xml_space)
+
# Merge style
merged_style = merge_styles(text_el.get("style"), tspan.get("style"))
if merged_style:
@@ -691,7 +873,11 @@ def process_svg_file(
print(f"[WARN] Failed to parse {src_path}: {e}")
return False
- changed = flatten_text_with_tspans(tree, merge_paragraphs=merge_paragraphs)
+ changed = flatten_text_with_tspans(
+ tree,
+ merge_paragraphs=merge_paragraphs,
+ source_name=Path(src_path).name,
+ )
# Ensure destination directory exists
os.makedirs(os.path.dirname(dst_path), exist_ok=True)
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 53487425..fff29a0a 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -21,6 +21,7 @@ from collections import Counter, defaultdict
from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
+from svg_to_pptx.text_contract import TextContractError, validate_text_contracts
configure_utf8_stdio()
@@ -1108,6 +1109,17 @@ class SVGQualityChecker:
def _check_text_elements(self, content: str, root: ET.Element, result: Dict):
"""Check text elements and wrapping methods"""
+ try:
+ validate_text_contracts(
+ root,
+ merge_paragraphs=True,
+ source_name=result.get('file'),
+ )
+ except TextContractError as exc:
+ result['errors'].extend(
+ diagnostic.format() for diagnostic in exc.diagnostics
+ )
+
# Count text and tspan elements
text_count = content.count('<text')
tspan_count = content.count('<tspan')
@@ -2075,6 +2087,8 @@ class SVGQualityChecker:
def _categorize_issue(self, error_msg: str) -> str:
"""Categorize issue type"""
+ if error_msg.startswith('[TEXT_'):
+ return 'Text contract'
if 'Invalid XML' in error_msg:
return 'XML well-formedness'
elif 'viewBox' in error_msg:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
index 4d677e87..5744655b 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/context.py
@@ -21,6 +21,7 @@ class ShapeResult:
xml: str
bounds_emu: tuple[int, int, int, int] | None = None
+ trace_metadata: dict[str, Any] = field(default_factory=dict)
@dataclass
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
index 1a969d47..82b5e8c5 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import base64
import binascii
import hashlib
+import json
import math
import re
from pathlib import Path
@@ -158,6 +159,117 @@ def _txbody_metadata(elem: ET.Element) -> ET.Element | None:
return None
+def _text_carrier_metadata(elem: ET.Element) -> ET.Element | None:
+ for child in elem:
+ if (
+ child.tag.replace(f'{{{SVG_NS}}}', '') == 'metadata'
+ and child.get('data-pptx-part') == 'text-carrier'
+ ):
+ return child
+ return None
+
+
+def _decode_text_carrier_nvsppr(metadata: ET.Element) -> ET.Element:
+ """Decode the versioned native carrier identity metadata."""
+ if metadata.get('data-pptx-text-carrier-version') != '1':
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_VERSION] Unsupported text-carrier metadata version'
+ )
+ if metadata.get('data-pptx-text-carrier-eligible') != '1':
+ reason = metadata.get('data-pptx-text-carrier-reason') or 'unknown'
+ raise SvgNativeConversionError(
+ f'[TEXT_NATIVE_CARRIER_INELIGIBLE] Native text carrier is not eligible: {reason}'
+ )
+ if metadata.get('data-pptx-encoding') != 'base64':
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_ENCODING] Eligible text carrier requires base64 nvSpPr'
+ )
+ try:
+ raw = base64.b64decode((metadata.text or '').strip(), validate=True)
+ nv_sp_pr = ET.fromstring(raw)
+ except (ValueError, binascii.Error, ET.ParseError) as exc:
+ raise SvgNativeConversionError(
+ f'[TEXT_NATIVE_CARRIER_XML] Invalid text-carrier nvSpPr: {exc}'
+ ) from exc
+ p_ns = 'http://schemas.openxmlformats.org/presentationml/2006/main'
+ if nv_sp_pr.tag != f'{{{p_ns}}}nvSpPr':
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_XML] text-carrier payload must be p:nvSpPr'
+ )
+ if has_relationship_attributes(nv_sp_pr):
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_REL] text-carrier nvSpPr contains relationships'
+ )
+ return nv_sp_pr
+
+
+def _replace_native_text_carrier(
+ geometry: ShapeResult,
+ compiled_text: ShapeResult,
+ carrier_metadata: ET.Element,
+) -> ShapeResult:
+ """Attach a rebuilt paragraph txBody to its original native p:sp."""
+ shape_match = re.search(r'<p:cNvPr id="(\d+)"', geometry.xml)
+ if shape_match is None:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_SHAPE] Native geometry has no output shape id'
+ )
+ output_shape_id = int(shape_match.group(1))
+ nv_sp_pr = _decode_text_carrier_nvsppr(carrier_metadata)
+ p_ns = 'http://schemas.openxmlformats.org/presentationml/2006/main'
+ a_ns = 'http://schemas.openxmlformats.org/drawingml/2006/main'
+ c_nv_pr = nv_sp_pr.find(f'{{{p_ns}}}cNvPr')
+ if c_nv_pr is None:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_XML] text-carrier nvSpPr has no p:cNvPr'
+ )
+ c_nv_pr.set('id', str(output_shape_id))
+ ET.register_namespace('p', p_ns)
+ ET.register_namespace('a', a_ns)
+ nv_sp_pr_xml = ET.tostring(nv_sp_pr, encoding='unicode')
+
+ txbody_match = re.search(r'<p:txBody>.*?</p:txBody>', compiled_text.xml, re.DOTALL)
+ xfrm_match = re.search(r'<a:xfrm(?:\s[^>]*)?>.*?</a:xfrm>', compiled_text.xml, re.DOTALL)
+ if txbody_match is None or xfrm_match is None:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_COMPILE] Rebuilt paragraph lacks txBody or xfrm'
+ )
+ combined_xml, nv_count = re.subn(
+ r'<p:nvSpPr>.*?</p:nvSpPr>',
+ lambda _match: nv_sp_pr_xml,
+ geometry.xml,
+ count=1,
+ flags=re.DOTALL,
+ )
+ if nv_count != 1:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_SHAPE] Native geometry has no replaceable p:nvSpPr'
+ )
+ combined_xml, xfrm_count = re.subn(
+ r'<a:xfrm(?:\s[^>]*)?>.*?</a:xfrm>',
+ lambda _match: xfrm_match.group(0),
+ combined_xml,
+ count=1,
+ flags=re.DOTALL,
+ )
+ if xfrm_count != 1:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_SHAPE] Native geometry has no replaceable a:xfrm'
+ )
+ metadata = {
+ **compiled_text.trace_metadata,
+ 'txbody_restore': 'rebuilt-same-shape',
+ }
+ return _append_shape_text(
+ ShapeResult(
+ xml=combined_xml,
+ bounds_emu=compiled_text.bounds_emu,
+ trace_metadata=metadata,
+ ),
+ txbody_match.group(0),
+ )
+
+
_TXBODY_UNCHANGED_ATTR = 'data-pptx-runtime-txbody-unchanged'
_PREVIEW_UNCHANGED_ATTR = 'data-pptx-runtime-preview-unchanged'
@@ -264,6 +376,7 @@ def _append_shape_text(
+ shape.xml[closing:]
),
bounds_emu=shape.bounds_emu,
+ trace_metadata=shape.trace_metadata,
)
@@ -417,6 +530,74 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
and child.get('data-pptx-part') not in allowed_parts
for child in elem
)
+ visible_texts = [
+ descendant
+ for descendant in elem.iter()
+ if descendant.tag.replace(f'{{{SVG_NS}}}', '') == 'text'
+ and ''.join(descendant.itertext()).strip()
+ ]
+ contracted_texts = [
+ text
+ for text in visible_texts
+ if text.get('data-pptx-runtime-text-contract') == '1'
+ ]
+ if contracted_texts:
+ if len(contracted_texts) != 1 or len(visible_texts) != 1:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_TEXT_COUNT] Native carrier requires exactly one '
+ 'non-empty explicit text block'
+ )
+ contract_text = contracted_texts[0]
+ requested_mode = contract_text.get('data-pptx-runtime-requested-mode')
+ effective_mode = contract_text.get('data-pptx-runtime-effective-mode')
+ if requested_mode in {'auto', 'lines'} or effective_mode != 'paragraph':
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_MODE_UNSUPPORTED] Native text carriers only '
+ 'support explicit paragraph mode'
+ )
+ carrier_meta = _text_carrier_metadata(elem)
+ if carrier_meta is None:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_METADATA_REQUIRED] Re-import the source '
+ 'PPTX to obtain versioned text-carrier metadata'
+ )
+ if len(carrier_children) != 1 or has_foreign_visual:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_STRUCTURE] Native text carrier has '
+ 'unsupported visible geometry children'
+ )
+ geometry_ctx = child_ctx
+ if transform and not native_subtree_active:
+ geometry_ctx = ctx.child(
+ 0, 0, 1.0, 1.0,
+ transform_matrix=parse_transform_matrix(transform),
+ filter_id=filter_id,
+ style_overrides=style_overrides,
+ opacity_multiplier=local_opacity,
+ )
+ geometry_result = convert_element(carrier_children[0], geometry_ctx)
+ ctx.sync_from_child(geometry_ctx)
+ if geometry_result is None:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_SHAPE] Native carrier has no geometry shape'
+ )
+ compiled_text = convert_text(contract_text, child_ctx)
+ ctx.sync_from_child(child_ctx)
+ if compiled_text is None:
+ raise SvgNativeConversionError(
+ '[TEXT_NATIVE_CARRIER_COMPILE] Explicit paragraph compiled empty'
+ )
+ restored = _replace_native_text_carrier(
+ geometry_result,
+ compiled_text,
+ carrier_meta,
+ )
+ if should_animate_group and elem_id:
+ shape_match = re.search(r'<p:cNvPr id="(\d+)"', restored.xml)
+ if shape_match:
+ ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
+ return restored
+
native_text = _decode_unchanged_txbody(elem, txbody_meta)
if len(carrier_children) == 1 and not has_foreign_visual and native_text is not None:
geometry_ctx = child_ctx
@@ -477,7 +658,11 @@ def convert_g(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
shape_match = re.search(r'<p:cNvPr id="(\d+)"', child_results[0].xml)
if shape_match:
ctx.anim_targets.append((int(shape_match.group(1)), elem_id))
- return child_results[0]
+ child_result = child_results[0]
+ return ShapeResult(
+ xml=child_result.xml,
+ bounds_emu=child_result.bounds_emu,
+ )
# Multiple children, or a top-level semantic one-child group: wrap in
# <p:grpSp> so PowerPoint can animate the group as one unit.
@@ -879,6 +1064,72 @@ def _geometry_trace_metadata(elem: ET.Element, result: ShapeResult) -> dict[str,
return {'output_geometry': 'unknown', 'fidelity': 'visual-only'}
+def _aggregate_text_contract_trace(
+ events: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """Aggregate per-shape text events into stable source-block mappings."""
+ grouped: dict[str, list[dict[str, Any]]] = {}
+ for event in events:
+ if not event.get('text_contract'):
+ continue
+ source_id = event.get('source_text_id')
+ if not isinstance(source_id, str) or not source_id:
+ continue
+ grouped.setdefault(source_id, []).append(event)
+
+ blocks: list[dict[str, Any]] = []
+ for source_id, source_events in grouped.items():
+ ordered = sorted(
+ source_events,
+ key=lambda event: int(event.get('line_index') or 1),
+ )
+ shape_ids = [
+ int(event['shape_id'])
+ for event in ordered
+ if event.get('shape_id') is not None
+ ]
+ bounds = [
+ event['bounds_emu']
+ for event in ordered
+ if isinstance(event.get('bounds_emu'), list)
+ and len(event['bounds_emu']) == 4
+ ]
+ union_bounds = None
+ if bounds:
+ union_bounds = [
+ min(value[0] for value in bounds),
+ min(value[1] for value in bounds),
+ max(value[2] for value in bounds),
+ max(value[3] for value in bounds),
+ ]
+ content_hashes = [
+ str(event.get('content_sha256'))
+ for event in ordered
+ if event.get('content_sha256')
+ ]
+ if len(content_hashes) == 1:
+ content_sha256 = content_hashes[0]
+ else:
+ payload = json.dumps(content_hashes, separators=(',', ':'))
+ content_sha256 = hashlib.sha256(payload.encode('utf-8')).hexdigest()
+ blocks.append({
+ 'source': {'element_id': source_id},
+ 'requested_mode': ordered[0].get('requested_mode'),
+ 'effective_mode': ordered[0].get('effective_mode'),
+ 'resolution_reason': ordered[0].get('resolution_reason'),
+ 'visual_line_count': ordered[0].get('visual_line_count'),
+ 'output_shape_ids': shape_ids,
+ 'output_shape_count': len(shape_ids),
+ 'paragraph_count': sum(int(event.get('paragraph_count') or 0) for event in ordered),
+ 'break_count': sum(int(event.get('break_count') or 0) for event in ordered),
+ 'slide_bounds_emu': union_bounds,
+ 'content_sha256': content_sha256,
+ 'txbody_restore': ordered[0].get('txbody_restore', 'not-applicable'),
+ 'readback': {'status': 'passed'},
+ })
+ return blocks
+
+
def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"""Dispatch an SVG element to the appropriate converter."""
tag = elem.tag.replace(f'{{{SVG_NS}}}', '')
@@ -939,6 +1190,7 @@ def convert_element(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None
if result.bounds_emu is not None:
metadata['bounds_emu'] = list(result.bounds_emu)
metadata.update(_geometry_trace_metadata(elem, result))
+ metadata.update(result.trace_metadata)
trace('native', **metadata)
else:
trace('skip', reason='empty-or-non-rendering')
@@ -1171,7 +1423,11 @@ def convert_svg_to_slide_shapes(
# merge_paragraphs additionally folds mergeable paragraph blocks into a
# single annotated <text> for downstream multi-<a:p> conversion.
from ..tspan_flattener import flatten_positional_tspans
- flattened = flatten_positional_tspans(tree, merge_paragraphs=merge_paragraphs)
+ flattened = flatten_positional_tspans(
+ tree,
+ merge_paragraphs=merge_paragraphs,
+ source_name=svg_path.name,
+ )
if flattened:
trace_steps.append({
'action': 'flatten-positional-tspans',
@@ -1316,6 +1572,7 @@ def convert_svg_to_slide_shapes(
},
'preprocess': trace_steps,
'events': trace_events or [],
+ 'text_blocks': _aggregate_text_contract_trace(trace_events or []),
})
shapes_xml = '\n'.join(shapes)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index a6a94801..62ee3561 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -6,8 +6,10 @@ import base64
import binascii
import hashlib
import io
+import json
import math
import re
+from decimal import Decimal, ROUND_HALF_EVEN
from pathlib import Path
from typing import Any
from urllib.parse import unquote_to_bytes
@@ -1790,6 +1792,9 @@ def _strip_leading_chars_from_runs(
stripped: list[dict[str, Any]] = []
remaining = char_count
for run in runs:
+ if run.get('_break'):
+ stripped.append(run)
+ continue
text = str(run.get('text', ''))
if remaining >= len(text):
remaining -= len(text)
@@ -2024,7 +2029,11 @@ def _collect_tspan_runs(
if tspan.text:
t = _normalize_text(tspan.text, preserve_space=child_preserve_space)
if t:
- runs.append({**own_attrs, 'text': t})
+ runs.append({
+ **own_attrs,
+ '_preserve_space': child_preserve_space,
+ 'text': t,
+ })
for child in tspan:
child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
@@ -2033,7 +2042,11 @@ def _collect_tspan_runs(
if child.tail:
t = _normalize_text(child.tail, preserve_space=child_preserve_space)
if t:
- runs.append({**own_attrs, 'text': t})
+ runs.append({
+ **own_attrs,
+ '_preserve_space': child_preserve_space,
+ 'text': t,
+ })
return runs
@@ -2041,6 +2054,8 @@ def _collect_tspan_runs(
def _build_text_runs(
elem: ET.Element,
parent_attrs: dict[str, Any],
+ *,
+ respect_preserved_edges: bool = False,
) -> list[dict[str, Any]]:
"""Build a list of text runs from a <text> element, handling <tspan> children.
@@ -2054,7 +2069,11 @@ def _build_text_runs(
if elem.text:
t = _normalize_text(elem.text, preserve_space=preserve_space)
if t:
- runs.append({**parent_attrs, 'text': t})
+ runs.append({
+ **parent_attrs,
+ '_preserve_space': preserve_space,
+ 'text': t,
+ })
for child in elem:
child_tag = child.tag.replace(f'{{{SVG_NS}}}', '')
@@ -2063,13 +2082,19 @@ def _build_text_runs(
if child.tail:
t = _normalize_text(child.tail, preserve_space=preserve_space)
if t:
- runs.append({**parent_attrs, 'text': t})
+ runs.append({
+ **parent_attrs,
+ '_preserve_space': preserve_space,
+ 'text': t,
+ })
# Strip the paragraph's overall leading / trailing whitespace once unless
# xml:space="preserve" asks us to keep source indentation.
if runs and not preserve_space:
- runs[0]['text'] = runs[0]['text'].lstrip(' ')
- runs[-1]['text'] = runs[-1]['text'].rstrip(' ')
+ if not respect_preserved_edges or not runs[0].get('_preserve_space'):
+ runs[0]['text'] = runs[0]['text'].lstrip(' ')
+ if not respect_preserved_edges or not runs[-1].get('_preserve_space'):
+ runs[-1]['text'] = runs[-1]['text'].rstrip(' ')
runs = [r for r in runs if r['text']]
return runs
@@ -2192,6 +2217,151 @@ def _build_run_xml(
</a:r>'''
+_TEXT_CONTRACT_MARK_ATTR = 'data-pptx-runtime-text-contract'
+_TEXT_CONTRACT_SOURCE_ATTR = 'data-pptx-runtime-source-text-id'
+_TEXT_CONTRACT_REQUESTED_ATTR = 'data-pptx-runtime-requested-mode'
+_TEXT_CONTRACT_EFFECTIVE_ATTR = 'data-pptx-runtime-effective-mode'
+_TEXT_CONTRACT_LINE_INDEX_ATTR = 'data-pptx-runtime-line-index'
+_TEXT_CONTRACT_LINE_COUNT_ATTR = 'data-pptx-runtime-line-count'
+_TEXT_CONTRACT_REASON_ATTR = 'data-pptx-runtime-mode-reason'
+_TEXT_CONTRACT_TOP_INSET_ATTR = 'data-paragraph-top-inset'
+
+
+def _contract_round(
+ value: float,
+ multiplier: int,
+ *factors: float,
+) -> int:
+ """Apply decimal ties-to-even rounding for explicit contract metrics."""
+ scaled = Decimal(str(value)) * Decimal(multiplier)
+ for factor in factors:
+ scaled *= Decimal(str(factor))
+ return int(scaled.to_integral_value(rounding=ROUND_HALF_EVEN))
+
+
+def _trim_explicit_paragraph_edges(
+ paragraphs: list[list[dict[str, Any]]],
+) -> None:
+ """Trim only the block's outer whitespace, preserving join boundaries."""
+ text_runs = [
+ run
+ for paragraph in paragraphs
+ for run in paragraph
+ if not run.get('_break') and run.get('text')
+ ]
+ if not text_runs:
+ return
+ if not text_runs[0].get('_preserve_space'):
+ text_runs[0]['text'] = str(text_runs[0]['text']).lstrip(' ')
+ if not text_runs[-1].get('_preserve_space'):
+ text_runs[-1]['text'] = str(text_runs[-1]['text']).rstrip(' ')
+ for paragraph in paragraphs:
+ paragraph[:] = [
+ run for run in paragraph
+ if run.get('_break') or run.get('text')
+ ]
+
+
+def _append_explicit_soft_join(
+ paragraph: list[dict[str, Any]],
+ next_runs: list[dict[str, Any]],
+ join_kind: str,
+) -> None:
+ """Append an explicit soft-wrapped line using the declared join policy."""
+ if join_kind == 'space' and paragraph and next_runs:
+ previous_text = str(paragraph[-1].get('text', ''))
+ next_text = str(next_runs[0].get('text', ''))
+ if (
+ previous_text
+ and next_text
+ and not previous_text[-1].isspace()
+ and not next_text[0].isspace()
+ ):
+ paragraph[-1] = {**paragraph[-1], 'text': previous_text + ' '}
+ paragraph.extend(next_runs)
+
+
+def _paragraph_content_sha256(
+ paragraphs: list[list[dict[str, Any]]],
+ bullets: list[dict[str, Any] | None] | None = None,
+) -> str:
+ """Hash paragraph/run/break structure without copying text into traces."""
+ tokens: list[list[dict[str, str]]] = []
+ paragraph_bullets = bullets or [None] * len(paragraphs)
+ for paragraph, bullet in zip(paragraphs, paragraph_bullets):
+ paragraph_tokens: list[dict[str, str]] = []
+ if bullet:
+ paragraph_tokens.append({
+ 'kind': 'bullet',
+ 'text': str(bullet.get('char', '•')),
+ })
+ for item in paragraph:
+ if item.get('_break'):
+ paragraph_tokens.append({'kind': 'break'})
+ else:
+ paragraph_tokens.append({
+ 'kind': 'run',
+ 'text': str(item.get('text', '')),
+ })
+ tokens.append(paragraph_tokens)
+ payload = json.dumps(tokens, ensure_ascii=False, separators=(',', ':'))
+ return hashlib.sha256(payload.encode('utf-8')).hexdigest()
+
+
+def _validate_compiled_text_shape(
+ shape_xml: str,
+ *,
+ expected_paragraphs: int,
+ expected_breaks: int,
+ expected_bounds: tuple[int, int, int, int],
+) -> None:
+ """Reparse the generated shape and verify contract-owned structure."""
+ wrapper = (
+ '<root '
+ 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" '
+ 'xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">'
+ + shape_xml
+ + '</root>'
+ )
+ try:
+ root = ET.fromstring(wrapper)
+ except ET.ParseError as exc:
+ raise ValueError(f'[TEXT_READBACK_XML] Invalid generated text XML: {exc}') from exc
+ ns = {
+ 'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
+ 'p': 'http://schemas.openxmlformats.org/presentationml/2006/main',
+ }
+ shape = root.find('p:sp', ns)
+ if shape is None:
+ raise ValueError('[TEXT_READBACK_SHAPE] Generated text is not one p:sp')
+ paragraphs = shape.findall('./p:txBody/a:p', ns)
+ breaks = shape.findall('.//a:br', ns)
+ if len(paragraphs) != expected_paragraphs:
+ raise ValueError(
+ '[TEXT_READBACK_PARAGRAPHS] Generated paragraph count '
+ f'{len(paragraphs)} != {expected_paragraphs}'
+ )
+ if len(breaks) != expected_breaks:
+ raise ValueError(
+ '[TEXT_READBACK_BREAKS] Generated line-break count '
+ f'{len(breaks)} != {expected_breaks}'
+ )
+ off = shape.find('./p:spPr/a:xfrm/a:off', ns)
+ ext = shape.find('./p:spPr/a:xfrm/a:ext', ns)
+ if off is None or ext is None:
+ raise ValueError('[TEXT_READBACK_BOUNDS] Generated text has no complete a:xfrm')
+ actual = (
+ int(off.get('x', '0')),
+ int(off.get('y', '0')),
+ int(off.get('x', '0')) + int(ext.get('cx', '0')),
+ int(off.get('y', '0')) + int(ext.get('cy', '0')),
+ )
+ if actual != expected_bounds:
+ raise ValueError(
+ f'[TEXT_READBACK_BOUNDS] Generated bounds {actual} != {expected_bounds}'
+ )
+
+
def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"""Convert SVG <text> to DrawingML text shape with multi-run support."""
x = ctx_x(svg_length_x(elem.get('x'), ctx), ctx)
@@ -2242,38 +2412,63 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
'stroke_opacity': stroke_opacity,
}
- # Paragraph mode: flatten_tspan marks <text> with data-paragraph-line-height
- # when its direct-child tspans form a mergeable paragraph (same x, dy
- # clustered around one base line-height). Each direct tspan becomes one
- # <a:p> so the paragraph survives as a single editable text frame.
- # Per-line data-paragraph-space-before encodes paragraph gaps (extra dy
- # above the base line-height) for the corresponding <a:p>.
- # Paragraph mode is controlled by ctx.merge_paragraphs. When off, ignore
- # any data-paragraph-* markers and fall through to the original
- # one-text-per-tspan path so the SVG's pixel layout is preserved.
+ # Legacy paragraphs continue to use the internal data-paragraph-* IR.
+ # Explicit contracts additionally preserve author-declared break/join
+ # semantics and may remain a paragraph even when they contain one line.
+ explicit_contract = elem.get(_TEXT_CONTRACT_MARK_ATTR) == '1'
+ requested_mode = elem.get(_TEXT_CONTRACT_REQUESTED_ATTR)
+ effective_mode = elem.get(_TEXT_CONTRACT_EFFECTIVE_ATTR)
+ explicit_paragraph = (
+ explicit_contract
+ and requested_mode == 'paragraph'
+ and effective_mode == 'paragraph'
+ )
line_height_attr = elem.get('data-paragraph-line-height') if ctx.merge_paragraphs else None
line_height_px = _f(line_height_attr) if line_height_attr is not None else None
paragraph_runs: list[list[dict[str, Any]]] | None = None
paragraph_space_before: list[float] = []
paragraph_bullets: list[dict[str, Any] | None] = []
+ single_bullet: dict[str, Any] | None = None
# Per-tspan widths (visual lines as the deck author drew them) regardless
# of how many merge into one <a:p>; used to size the textbox so PowerPoint
# has room to wrap text to the SVG's original line widths.
visual_line_widths: list[float] = []
- if line_height_px is not None and line_height_px > 0:
+ if explicit_paragraph or (line_height_px is not None and line_height_px > 0):
preserve_space = _preserves_space(elem)
paragraph_runs = []
for child in elem:
if child.tag != f'{{{SVG_NS}}}tspan':
continue
line_runs = _collect_tspan_runs(child, parent_attrs, preserve_space)
- if line_runs and not preserve_space:
+ if line_runs and not preserve_space and not explicit_paragraph:
line_runs[0]['text'] = line_runs[0]['text'].lstrip(' ')
line_runs[-1]['text'] = line_runs[-1]['text'].rstrip(' ')
line_runs = [r for r in line_runs if r['text']]
if not line_runs:
continue
visual_line_widths.append(_estimate_bullet_line_width(line_runs))
+ if explicit_paragraph:
+ break_kind = child.get('data-pptx-break')
+ if not paragraph_runs:
+ paragraph_runs.append(line_runs)
+ paragraph_space_before.append(0.0)
+ continue
+ if break_kind == 'soft':
+ _append_explicit_soft_join(
+ paragraph_runs[-1],
+ line_runs,
+ child.get('data-pptx-join') or 'none',
+ )
+ continue
+ if break_kind == 'line':
+ paragraph_runs[-1].append({'_break': True})
+ paragraph_runs[-1].extend(line_runs)
+ continue
+ paragraph_runs.append(line_runs)
+ sb_attr = child.get('data-paragraph-space-before')
+ paragraph_space_before.append(_f(sb_attr) if sb_attr else 0.0)
+ continue
+
soft_break = child.get('data-paragraph-soft-break') == '1'
if soft_break and paragraph_runs:
# Append to the previous paragraph. A Latin line-wrap needs a
@@ -2296,6 +2491,8 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
paragraph_runs.append(line_runs)
sb_attr = child.get('data-paragraph-space-before')
paragraph_space_before.append(_f(sb_attr) if sb_attr else 0.0)
+ if explicit_paragraph and paragraph_runs and not preserve_space:
+ _trim_explicit_paragraph_edges(paragraph_runs)
if not paragraph_runs:
paragraph_runs = None
paragraph_space_before = []
@@ -2309,9 +2506,18 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
paragraph_runs = stripped_paragraphs
if paragraph_runs is not None:
- runs = [r for line in paragraph_runs for r in line]
+ runs = [
+ run
+ for paragraph in paragraph_runs
+ for run in paragraph
+ if not run.get('_break')
+ ]
else:
- runs = _build_text_runs(elem, parent_attrs)
+ runs = _build_text_runs(
+ elem,
+ parent_attrs,
+ respect_preserved_edges=explicit_contract,
+ )
runs, single_bullet = _extract_text_bullet(runs)
if not runs:
@@ -2331,8 +2537,9 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
# Total height assumes the visual line count from the SVG source;
# if PowerPoint wraps to more or fewer lines after the user resizes,
# the user resizes the height accordingly.
+ effective_line_height = line_height_px or 0.0
text_height = (
- line_height_px * (len(visual_line_widths) - 1)
+ effective_line_height * (len(visual_line_widths) - 1)
+ sum(paragraph_space_before)
+ font_size * 1.5
)
@@ -2342,19 +2549,38 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
fs_px = float(runs[0].get('font_size', font_size)) if runs else font_size
text_width += _bullet_margin_px(single_bullet, fs_px)
text_height = font_size * 1.5
- padding = _textbox_padding(font_size)
-
- # Adjust position based on text-anchor
- if text_anchor == 'middle':
- box_x = x - text_width / 2 - padding
- elif text_anchor == 'end':
- box_x = x - text_width - padding
+ explicit_bounds: tuple[float, float, float, float] | None = None
+ if explicit_paragraph:
+ bounds_raw = elem.get('data-pptx-text-bounds')
+ try:
+ values = [float(value) for value in re.split(r'[\s,]+', bounds_raw or '') if value]
+ except ValueError as exc:
+ raise ValueError('[TEXT_BOUNDS_FORMAT] Invalid explicit text bounds') from exc
+ if len(values) != 4:
+ raise ValueError('[TEXT_BOUNDS_FORMAT] Explicit text bounds require x y width height')
+ explicit_bounds = (values[0], values[1], values[2], values[3])
+
+ if explicit_bounds is not None:
+ raw_box_x, raw_box_y, raw_box_w, raw_box_h = explicit_bounds
+ box_x = ctx_x(raw_box_x, ctx)
+ box_y = ctx_y(raw_box_y, ctx)
+ box_w = ctx_w(raw_box_w, ctx)
+ box_h = ctx_h(raw_box_h, ctx)
+ padding = 0.0
else:
- box_x = x - padding
+ padding = _textbox_padding(font_size)
+
+ # Adjust position based on text-anchor
+ if text_anchor == 'middle':
+ box_x = x - text_width / 2 - padding
+ elif text_anchor == 'end':
+ box_x = x - text_width - padding
+ else:
+ box_x = x - padding
- box_y = y - font_size * 0.85
- box_w = text_width + padding * 2
- box_h = text_height + padding
+ box_y = y - font_size * 0.85
+ box_w = text_width + padding * 2
+ box_h = text_height + padding
text_transform = elem.get('transform', '')
if text_transform and 'rotate' not in text_transform and not ctx.use_transform_matrix:
@@ -2432,18 +2658,53 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
if paragraph_runs is not None:
# SVG dy(px) -> hundredths-of-a-point: dy_pt = dy_px * 0.75, then x100.
- line_spc_val = round(line_height_px * FONT_PX_TO_HUNDREDTHS_PT)
- ln_spc_xml = f'<a:lnSpc><a:spcPts val="{line_spc_val}"/></a:lnSpc>'
+ metric_scale = ctx.scale_y if explicit_paragraph else 1.0
+ if line_height_px is not None and line_height_px > 0:
+ if explicit_paragraph:
+ line_spc_val = _contract_round(
+ line_height_px,
+ FONT_PX_TO_HUNDREDTHS_PT,
+ metric_scale,
+ )
+ else:
+ line_spc_val = round(
+ line_height_px * FONT_PX_TO_HUNDREDTHS_PT
+ )
+ ln_spc_xml = f'<a:lnSpc><a:spcPts val="{line_spc_val}"/></a:lnSpc>'
+ else:
+ ln_spc_xml = ''
paragraph_xml_chunks = []
- for line, extra_px, bullet in zip(paragraph_runs, paragraph_space_before, paragraph_bullets):
+ for line, extra_px, bullet in zip(
+ paragraph_runs,
+ paragraph_space_before,
+ paragraph_bullets,
+ ):
spc_bef_xml = ''
if extra_px > 0:
- spc_bef_val = round(extra_px * FONT_PX_TO_HUNDREDTHS_PT)
+ if explicit_paragraph:
+ spc_bef_val = _contract_round(
+ extra_px,
+ FONT_PX_TO_HUNDREDTHS_PT,
+ metric_scale,
+ )
+ else:
+ spc_bef_val = round(
+ extra_px * FONT_PX_TO_HUNDREDTHS_PT
+ )
spc_bef_xml = f'<a:spcBef><a:spcPts val="{spc_bef_val}"/></a:spcBef>'
- runs_inner = '\n'.join(_build_run_xml(r, fonts, ctx, text_effect_xml) for r in line)
+ runs_inner = '\n'.join(
+ '<a:br/>'
+ if item.get('_break')
+ else _build_run_xml(item, fonts, ctx, text_effect_xml)
+ for item in line
+ )
+ first_run = next((item for item in line if not item.get('_break')), None)
p_pr_xml = _paragraph_pr_xml(
algn=algn,
- font_size=float(line[0].get('font_size', font_size)) if line else font_size,
+ font_size=(
+ float(first_run.get('font_size', font_size))
+ if first_run is not None else font_size
+ ),
body_xml=f'{ln_spc_xml}{spc_bef_xml}',
bullet=bullet,
ctx=ctx,
@@ -2462,10 +2723,16 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
)
paragraphs_xml = f'<a:p>\n{p_pr_xml}\n{runs_xml}\n</a:p>'
- off_x = px_to_emu(box_x)
- off_y = px_to_emu(box_y)
- ext_cx = px_to_emu(box_w)
- ext_cy = px_to_emu(box_h)
+ if explicit_bounds is not None:
+ off_x = _contract_round(box_x, 9525)
+ off_y = _contract_round(box_y, 9525)
+ ext_cx = _contract_round(box_w, 9525)
+ ext_cy = _contract_round(box_h, 9525)
+ else:
+ off_x = px_to_emu(box_x)
+ off_y = px_to_emu(box_y)
+ ext_cx = px_to_emu(box_w)
+ ext_cy = px_to_emu(box_h)
# Paragraph mode: wrap="square" so text reflows when the user resizes,
# but NO spAutoFit — otherwise PowerPoint expands the frame to fit a
@@ -2474,8 +2741,12 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
# headroom; PowerPoint wraps long paragraphs inside this design width.
# Single-line text keeps wrap="none" + spAutoFit for tight fidelity.
if paragraph_runs is not None:
+ top_inset = 0
+ if explicit_paragraph:
+ top_inset_px = _f(elem.get(_TEXT_CONTRACT_TOP_INSET_ATTR))
+ top_inset = _contract_round(top_inset_px, 9525, ctx.scale_y)
body_pr_xml = (
- '<a:bodyPr wrap="square" lIns="0" tIns="0" rIns="0" bIns="0" '
+ f'<a:bodyPr wrap="square" lIns="0" tIns="{top_inset}" rIns="0" bIns="0" '
'anchor="t" anchorCtr="0"/>'
)
else:
@@ -2484,7 +2755,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
'anchor="t" anchorCtr="0">\n<a:spAutoFit/>\n</a:bodyPr>'
)
- return ShapeResult(xml=f'''<p:sp>
+ shape_xml = f'''<p:sp>
<p:nvSpPr>
<p:cNvPr id="{shape_id}" name="TextBox {shape_id}"/>
<p:cNvSpPr txBox="1"/><p:nvPr/>
@@ -2502,7 +2773,57 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
<a:lstStyle/>
{paragraphs_xml}
</p:txBody>
-</p:sp>''', bounds_emu=(off_x, off_y, off_x + ext_cx, off_y + ext_cy))
+</p:sp>'''
+ bounds_emu = (off_x, off_y, off_x + ext_cx, off_y + ext_cy)
+ paragraph_count = len(paragraph_runs) if paragraph_runs is not None else 1
+ break_count = (
+ sum(
+ 1
+ for paragraph in paragraph_runs
+ for item in paragraph
+ if item.get('_break')
+ )
+ if paragraph_runs is not None else 0
+ )
+ trace_metadata: dict[str, Any] = {}
+ if explicit_contract:
+ effective_paragraphs = (
+ paragraph_runs
+ if paragraph_runs is not None
+ else [runs]
+ )
+ effective_bullets = (
+ paragraph_bullets
+ if paragraph_runs is not None
+ else [single_bullet]
+ )
+ trace_metadata = {
+ 'text_contract': True,
+ 'source_text_id': elem.get(_TEXT_CONTRACT_SOURCE_ATTR),
+ 'requested_mode': requested_mode,
+ 'effective_mode': effective_mode,
+ 'resolution_reason': elem.get(_TEXT_CONTRACT_REASON_ATTR),
+ 'visual_line_count': int(elem.get(_TEXT_CONTRACT_LINE_COUNT_ATTR) or '1'),
+ 'line_index': int(elem.get(_TEXT_CONTRACT_LINE_INDEX_ATTR) or '1'),
+ 'paragraph_count': paragraph_count,
+ 'break_count': break_count,
+ 'content_sha256': _paragraph_content_sha256(
+ effective_paragraphs,
+ effective_bullets,
+ ),
+ 'readback': {'status': 'passed'},
+ }
+ _validate_compiled_text_shape(
+ shape_xml,
+ expected_paragraphs=paragraph_count,
+ expected_breaks=break_count,
+ expected_bounds=bounds_emu,
+ )
+ return ShapeResult(
+ xml=shape_xml,
+ bounds_emu=bounds_emu,
+ trace_metadata=trace_metadata,
+ )
# ---------------------------------------------------------------------------
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/builder.py
index 34404ce9..ee805592 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
@@ -107,6 +107,7 @@ from .template_structure import (
template_placeholder_bindings,
)
from .template_validation import validate_pptx_template_package
+from .text_validation import validate_pptx_text_contracts
SLIDE_LAYOUT_REL_TYPE = (
"http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout"
@@ -3638,9 +3639,12 @@ def create_pptx_with_native_svg(
separators=(',', ':'),
)
animation_rng = random.Random(animation_seed)
- conversion_trace: list[dict[str, Any]] | None = [] if conversion_trace_path else None
+ runtime_trace: list[dict[str, Any]] | None = [] if use_native_shapes else None
+ conversion_trace: list[dict[str, Any]] | None = (
+ runtime_trace if conversion_trace_path else None
+ )
structure_trace: list[dict[str, Any]] | None = (
- []
+ runtime_trace
if use_native_shapes and pptx_structure in {"baseline", "template", "preserve"}
else None
)
@@ -3720,9 +3724,7 @@ def create_pptx_with_native_svg(
animation_group_overrides=explicit_animation_groups,
theme_font_spec=active_theme_font_spec,
theme_color_spec=active_theme_color_spec,
- trace_out=conversion_trace
- if conversion_trace is not None
- else structure_trace,
+ trace_out=runtime_trace,
)
)
# Order matters: OOXML schema requires <p:transition>
@@ -4287,6 +4289,12 @@ def create_pptx_with_native_svg(
raise RuntimeError(
f'PPTX animation package validation failed: {exc}'
) from exc
+ try:
+ validate_pptx_text_contracts(temp_output_path, runtime_trace)
+ except ValueError as exc:
+ raise RuntimeError(
+ f'PPTX text contract validation failed: {exc}'
+ ) from exc
shutil.move(str(temp_output_path), str(output_path))
permission_warnings = _relax_output_permissions(output_path)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/pptx_package/text_validation.py b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/text_validation.py
new file mode 100644
index 00000000..03a43f4b
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/pptx_package/text_validation.py
@@ -0,0 +1,176 @@
+"""Post-package validation for explicit SVG text-layout contracts."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import zipfile
+from pathlib import Path
+from typing import Any
+from xml.etree import ElementTree as ET
+
+
+P_NS = 'http://schemas.openxmlformats.org/presentationml/2006/main'
+A_NS = 'http://schemas.openxmlformats.org/drawingml/2006/main'
+NS = {'p': P_NS, 'a': A_NS}
+
+
+def _shape_id(shape: ET.Element) -> int | None:
+ c_nv_pr = shape.find('./p:nvSpPr/p:cNvPr', NS)
+ if c_nv_pr is None:
+ c_nv_pr = shape.find('./p:nvGrpSpPr/p:cNvPr', NS)
+ if c_nv_pr is None:
+ return None
+ try:
+ return int(c_nv_pr.get('id', ''))
+ except ValueError:
+ return None
+
+
+def _shape_map(root: ET.Element) -> dict[int, ET.Element]:
+ shapes: dict[int, ET.Element] = {}
+ for element in root.iter():
+ if element.tag not in {
+ f'{{{P_NS}}}sp',
+ f'{{{P_NS}}}grpSp',
+ }:
+ continue
+ shape_id = _shape_id(element)
+ if shape_id is not None:
+ shapes[shape_id] = element
+ return shapes
+
+
+def _shape_bounds(shape: ET.Element) -> list[int]:
+ off = shape.find('./p:spPr/a:xfrm/a:off', NS)
+ ext = shape.find('./p:spPr/a:xfrm/a:ext', NS)
+ if off is None or ext is None:
+ raise ValueError('[TEXT_PACKAGE_BOUNDS] Text shape has no complete a:xfrm')
+ x = int(off.get('x', '0'))
+ y = int(off.get('y', '0'))
+ return [x, y, x + int(ext.get('cx', '0')), y + int(ext.get('cy', '0'))]
+
+
+def _content_sha256(shape: ET.Element) -> str:
+ txbody = shape.find('./p:txBody', NS)
+ if txbody is None:
+ raise ValueError('[TEXT_PACKAGE_TXBODY] Contract output has no direct p:txBody')
+ paragraphs: list[list[dict[str, str]]] = []
+ for paragraph in txbody.findall('./a:p', NS):
+ tokens: list[dict[str, str]] = []
+ bullet = paragraph.find('./a:pPr/a:buChar', NS)
+ if bullet is not None:
+ tokens.append({
+ 'kind': 'bullet',
+ 'text': bullet.get('char', '•'),
+ })
+ for child in paragraph:
+ if child.tag == f'{{{A_NS}}}br':
+ tokens.append({'kind': 'break'})
+ continue
+ if child.tag not in {f'{{{A_NS}}}r', f'{{{A_NS}}}fld'}:
+ continue
+ text = child.find('./a:t', NS)
+ text_value = text.text if text is not None and text.text is not None else ''
+ tokens.append({'kind': 'run', 'text': text_value})
+ paragraphs.append(tokens)
+ payload = json.dumps(paragraphs, ensure_ascii=False, separators=(',', ':'))
+ return hashlib.sha256(payload.encode('utf-8')).hexdigest()
+
+
+def _combined_content_sha256(shapes: list[ET.Element]) -> str:
+ hashes = [_content_sha256(shape) for shape in shapes]
+ if len(hashes) == 1:
+ return hashes[0]
+ payload = json.dumps(hashes, separators=(',', ':'))
+ return hashlib.sha256(payload.encode('utf-8')).hexdigest()
+
+
+def _union_bounds(shapes: list[ET.Element]) -> list[int]:
+ bounds = [_shape_bounds(shape) for shape in shapes]
+ return [
+ min(value[0] for value in bounds),
+ min(value[1] for value in bounds),
+ max(value[2] for value in bounds),
+ max(value[3] for value in bounds),
+ ]
+
+
+def _validate_block(
+ block: dict[str, Any],
+ shapes_by_id: dict[int, ET.Element],
+) -> None:
+ source = block.get('source') or {}
+ source_id = source.get('element_id') or '<unknown>'
+ shape_ids = [int(value) for value in block.get('output_shape_ids') or []]
+ missing = [shape_id for shape_id in shape_ids if shape_id not in shapes_by_id]
+ if missing:
+ raise ValueError(
+ f'[TEXT_PACKAGE_SHAPE_MAP] {source_id}: missing output shape id(s) {missing}'
+ )
+ shapes = [shapes_by_id[shape_id] for shape_id in shape_ids]
+ effective_mode = block.get('effective_mode')
+ expected_shape_count = (
+ 1
+ if effective_mode == 'paragraph'
+ else int(block.get('visual_line_count') or 0)
+ )
+ if len(shapes) != expected_shape_count:
+ raise ValueError(
+ f'[TEXT_PACKAGE_SHAPE_COUNT] {source_id}: '
+ f'{len(shapes)} != {expected_shape_count}'
+ )
+ paragraph_count = sum(
+ len(shape.findall('./p:txBody/a:p', NS))
+ for shape in shapes
+ )
+ break_count = sum(
+ len(shape.findall('./p:txBody/a:p/a:br', NS))
+ for shape in shapes
+ )
+ if paragraph_count != int(block.get('paragraph_count') or 0):
+ raise ValueError(
+ f'[TEXT_PACKAGE_PARAGRAPHS] {source_id}: '
+ f'{paragraph_count} != {block.get("paragraph_count")}'
+ )
+ if break_count != int(block.get('break_count') or 0):
+ raise ValueError(
+ f'[TEXT_PACKAGE_BREAKS] {source_id}: '
+ f'{break_count} != {block.get("break_count")}'
+ )
+ expected_bounds = block.get('slide_bounds_emu')
+ if expected_bounds is not None and _union_bounds(shapes) != expected_bounds:
+ raise ValueError(
+ f'[TEXT_PACKAGE_BOUNDS] {source_id}: final package bounds changed'
+ )
+ actual_hash = _combined_content_sha256(shapes)
+ if actual_hash != block.get('content_sha256'):
+ raise ValueError(
+ f'[TEXT_PACKAGE_CONTENT] {source_id}: final text content hash changed'
+ )
+ block['readback'] = {'status': 'passed'}
+
+
+def validate_pptx_text_contracts(
+ pptx_path: Path,
+ conversion_traces: list[dict[str, Any]] | None,
+) -> None:
+ """Validate explicit text blocks in a temporary PPTX before publication."""
+ if not conversion_traces:
+ return
+ with zipfile.ZipFile(pptx_path) as package:
+ for slide_trace in conversion_traces:
+ blocks = slide_trace.get('text_blocks') or []
+ if not blocks:
+ continue
+ slide_num = int(slide_trace['slide_num'])
+ slide_path = f'ppt/slides/slide{slide_num}.xml'
+ try:
+ root = ET.fromstring(package.read(slide_path))
+ except KeyError as exc:
+ raise ValueError(
+ f'[TEXT_PACKAGE_SLIDE] Missing {slide_path}'
+ ) from exc
+ shapes_by_id = _shape_map(root)
+ for block in blocks:
+ _validate_block(block, shapes_by_id)
diff --git a/skills/ppt-master/scripts/svg_to_pptx/text_contract.py b/skills/ppt-master/scripts/svg_to_pptx/text_contract.py
new file mode 100644
index 00000000..6ef5330f
--- /dev/null
+++ b/skills/ppt-master/scripts/svg_to_pptx/text_contract.py
@@ -0,0 +1,1322 @@
+#!/usr/bin/env python3
+"""
+PPT Master - SVG Text Layout Contract
+
+Parse and validate explicit SVG paragraph/line semantics before any tspan
+normalization mutates the author source tree.
+
+Usage:
+ Import ``validate_text_contracts`` from the SVG quality/export pipeline.
+
+Examples:
+ contracts = validate_text_contracts(svg_root, merge_paragraphs=True)
+
+Dependencies:
+ None (only uses the Python standard library)
+"""
+
+from __future__ import annotations
+
+import math
+import re
+from dataclasses import dataclass
+from xml.etree import ElementTree as ET
+
+
+SVG_NS = "http://www.w3.org/2000/svg"
+XML_SPACE_ATTR = "{http://www.w3.org/XML/1998/namespace}space"
+
+TEXT_MODE_ATTR = "data-pptx-text-mode"
+TEXT_BOUNDS_ATTR = "data-pptx-text-bounds"
+TEXT_BREAK_ATTR = "data-pptx-break"
+TEXT_JOIN_ATTR = "data-pptx-join"
+
+RUNTIME_CONTRACT_ATTR = "data-pptx-runtime-text-contract"
+RUNTIME_SOURCE_ID_ATTR = "data-pptx-runtime-source-text-id"
+RUNTIME_REQUESTED_MODE_ATTR = "data-pptx-runtime-requested-mode"
+RUNTIME_EFFECTIVE_MODE_ATTR = "data-pptx-runtime-effective-mode"
+RUNTIME_LINE_INDEX_ATTR = "data-pptx-runtime-line-index"
+RUNTIME_LINE_COUNT_ATTR = "data-pptx-runtime-line-count"
+RUNTIME_MODE_REASON_ATTR = "data-pptx-runtime-mode-reason"
+RUNTIME_ATTRS = frozenset(
+ {
+ RUNTIME_CONTRACT_ATTR,
+ RUNTIME_SOURCE_ID_ATTR,
+ RUNTIME_REQUESTED_MODE_ATTR,
+ RUNTIME_EFFECTIVE_MODE_ATTR,
+ RUNTIME_LINE_INDEX_ATTR,
+ RUNTIME_LINE_COUNT_ATTR,
+ RUNTIME_MODE_REASON_ATTR,
+ }
+)
+
+TEXT_MODES = frozenset({"auto", "paragraph", "lines"})
+BREAK_KINDS = frozenset({"soft", "line", "paragraph"})
+JOIN_KINDS = frozenset({"space", "none"})
+
+DY_TOLERANCE_PX = 0.5
+MAX_DY_MULTIPLIER = 3.0
+
+_NUMBER = r"[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?"
+_COORDINATE_RE = re.compile(rf"^({_NUMBER})(?:px)?$")
+_FOUR_NUMBERS_RE = re.compile(
+ rf"^\s*({_NUMBER})(?:\s*,\s*|\s+)"
+ rf"({_NUMBER})(?:\s*,\s*|\s+)"
+ rf"({_NUMBER})(?:\s*,\s*|\s+)"
+ rf"({_NUMBER})\s*$"
+)
+_TRANSLATE_RE = re.compile(
+ rf"translate\(\s*({_NUMBER})(?:(?:\s*,\s*|\s+)({_NUMBER}))?\s*\)"
+)
+
+
+@dataclass
+class TextContractDiagnostic:
+ """Describe one stable, actionable text-contract violation."""
+
+ code: str
+ message: str
+ source_name: str | None = None
+ element_id: str | None = None
+ element_tag: str = "text"
+ attribute: str | None = None
+ hint: str | None = None
+
+ def format(self) -> str:
+ """Format the diagnostic for checker/exporter user-facing output."""
+ location = f"<{self.element_tag}>"
+ if self.element_id:
+ location = f"<{self.element_tag} id={self.element_id!r}>"
+ if self.source_name:
+ location = f"{self.source_name} {location}"
+ attribute = f" {self.attribute}:" if self.attribute else ":"
+ rendered = f"[{self.code}] {location}{attribute} {self.message}"
+ if self.hint:
+ rendered += f"; fix: {self.hint}"
+ return rendered
+
+
+class TextContractError(ValueError):
+ """Aggregate explicit text-contract diagnostics without partial mutation."""
+
+ def __init__(
+ self,
+ diagnostics: list[TextContractDiagnostic] | tuple[TextContractDiagnostic, ...],
+ ):
+ self.diagnostics = tuple(diagnostics)
+ super().__init__(self.format())
+
+ def format(self) -> str:
+ """Format every diagnostic in deterministic discovery order."""
+ return "\n".join(diagnostic.format() for diagnostic in self.diagnostics)
+
+
+@dataclass
+class TextVisualLine:
+ """Normalized author-source view of one explicit paragraph visual line."""
+
+ starter: ET.Element
+ inline_tspans: tuple[ET.Element, ...]
+ break_kind: str | None
+ join_kind: str | None
+ dy: float
+ space_before: float = 0.0
+
+ @property
+ def elements(self) -> tuple[ET.Element, ...]:
+ """Return the line starter followed by direct-child inline runs."""
+ return (self.starter, *self.inline_tspans)
+
+
+@dataclass
+class TextBlockContract:
+ """Validated explicit contract attached to one SVG ``<text>`` block."""
+
+ element: ET.Element
+ element_id: str
+ requested_mode: str
+ effective_mode: str
+ mode_reason: str
+ bounds: tuple[float, float, float, float] | None = None
+ anchor_x: float | None = None
+ anchor_y: float | None = None
+ block_font_size: float | None = None
+ base_line_height: float | None = None
+ top_inset: float | None = None
+ preserve_space: bool = False
+ visual_lines: tuple[TextVisualLine, ...] = ()
+
+
+def _local_name(elem: ET.Element) -> str:
+ return elem.tag.rsplit("}", 1)[-1]
+
+
+def _style_map(elem: ET.Element) -> dict[str, str]:
+ parsed: dict[str, str] = {}
+ for declaration in (elem.get("style") or "").split(";"):
+ if ":" not in declaration:
+ continue
+ name, value = declaration.split(":", 1)
+ parsed[name.strip()] = value.strip()
+ return parsed
+
+
+def _element_chain(
+ elem: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+) -> list[ET.Element]:
+ chain = [elem]
+ while chain[-1] in parent_map:
+ chain.append(parent_map[chain[-1]])
+ chain.reverse()
+ return chain
+
+
+def _effective_property(
+ elem: ET.Element,
+ name: str,
+ parent_map: dict[ET.Element, ET.Element],
+) -> str | None:
+ value: str | None = None
+ for node in _element_chain(elem, parent_map):
+ if node.get(name) is not None:
+ value = node.get(name)
+ style_value = _style_map(node).get(name)
+ if style_value is not None:
+ value = style_value
+ return value
+
+
+def _preserves_space(
+ elem: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+) -> bool:
+ preserve = False
+ for node in _element_chain(elem, parent_map):
+ value = node.get(XML_SPACE_ATTR) or node.get("xml:space")
+ if value == "preserve":
+ preserve = True
+ elif value == "default":
+ preserve = False
+ return preserve
+
+
+def _parse_coordinate(value: str | None) -> float | None:
+ if value is None:
+ return None
+ match = _COORDINATE_RE.fullmatch(value.strip())
+ if not match:
+ return None
+ parsed = float(match.group(1))
+ return parsed if math.isfinite(parsed) else None
+
+
+def _parse_bounds(value: str | None) -> tuple[float, float, float, float] | None:
+ if value is None:
+ return None
+ match = _FOUR_NUMBERS_RE.fullmatch(value)
+ if not match:
+ return None
+ parsed = tuple(float(part) for part in match.groups())
+ if not all(math.isfinite(part) for part in parsed):
+ return None
+ return parsed # type: ignore[return-value]
+
+
+def _parse_length_px(value: str | None, inherited: float = 16.0) -> float | None:
+ if value is None:
+ return inherited
+ raw = value.strip().lower()
+ match = re.fullmatch(rf"({_NUMBER})(px|pt|em|rem)?", raw)
+ if not match:
+ return None
+ amount = float(match.group(1))
+ if not math.isfinite(amount):
+ return None
+ unit = match.group(2) or "px"
+ if unit == "pt":
+ return amount * 4.0 / 3.0
+ if unit in {"em", "rem"}:
+ return amount * inherited
+ return amount
+
+
+def _effective_font_size(
+ elem: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+) -> float | None:
+ size = 16.0
+ for node in _element_chain(elem, parent_map):
+ raw = node.get("font-size")
+ style_raw = _style_map(node).get("font-size")
+ if style_raw is not None:
+ raw = style_raw
+ if raw is None:
+ continue
+ parsed = _parse_length_px(raw, size)
+ if parsed is None or parsed <= 0:
+ return None
+ size = parsed
+ return size
+
+
+def _translate_only(value: str) -> bool:
+ position = 0
+ matched = False
+ while position < len(value):
+ separator = re.match(r"[\s,]*", value[position:])
+ position += separator.end() if separator else 0
+ if position >= len(value):
+ break
+ match = _TRANSLATE_RE.match(value, position)
+ if not match:
+ return False
+ matched = True
+ position = match.end()
+ return matched
+
+
+def _has_visible_direct_text(value: str | None, preserve_space: bool) -> bool:
+ if not value:
+ return False
+ return bool(value) if preserve_space else bool(value.strip())
+
+
+def _nearest_text(
+ elem: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+) -> ET.Element | None:
+ current = parent_map.get(elem)
+ while current is not None:
+ if _local_name(current) == "text":
+ return current
+ current = parent_map.get(current)
+ return None
+
+
+def _direct_metadata(elem: ET.Element, part: str) -> ET.Element | None:
+ for child in elem:
+ if (
+ _local_name(child) == "metadata"
+ and child.get("data-pptx-part") == part
+ ):
+ return child
+ return None
+
+
+def _native_text_carrier(
+ text: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+) -> ET.Element | None:
+ current = parent_map.get(text)
+ while current is not None:
+ if _direct_metadata(current, "txbody") is not None:
+ return current
+ current = parent_map.get(current)
+ return None
+
+
+def _validate_native_carrier_contract(
+ text: ET.Element,
+ mode: str,
+ merge_paragraphs: bool,
+ parent_map: dict[ET.Element, ET.Element],
+ diagnostics: list[TextContractDiagnostic],
+) -> None:
+ """Fail closed when an imported one-shape text carrier cannot be rebuilt."""
+ carrier = _native_text_carrier(text, parent_map)
+ if carrier is None:
+ return
+
+ if mode in {"auto", "lines"} or not merge_paragraphs:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_NATIVE_MODE_UNSUPPORTED",
+ text,
+ "native text carriers only support effective paragraph mode",
+ attribute=TEXT_MODE_ATTR,
+ hint="use paragraph mode without --no-merge, or remove the native carrier metadata",
+ )
+ return
+
+ visible_texts = [
+ descendant
+ for descendant in carrier.iter()
+ if _local_name(descendant) == "text"
+ and "".join(descendant.itertext()).strip()
+ ]
+ if len(visible_texts) != 1:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_NATIVE_TEXT_COUNT",
+ text,
+ "native text carriers require exactly one non-empty text block",
+ hint="keep one non-empty explicit paragraph inside the imported carrier",
+ )
+
+ carrier_metadata = _direct_metadata(carrier, "text-carrier")
+ if (
+ carrier_metadata is None
+ or carrier_metadata.get("data-pptx-text-carrier-version") != "1"
+ ):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_NATIVE_CARRIER_METADATA_REQUIRED",
+ text,
+ "native paragraph recompilation requires version-1 text-carrier metadata",
+ hint="re-import the source PPTX with the current pptx_to_svg converter",
+ )
+ return
+ if carrier_metadata.get("data-pptx-text-carrier-eligible") != "1":
+ reason = carrier_metadata.get("data-pptx-text-carrier-reason") or "unknown"
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_NATIVE_CARRIER_INELIGIBLE",
+ text,
+ f"the imported native text carrier is ineligible: {reason}",
+ hint="use ordinary SVG text or remove the unsupported carrier feature",
+ )
+
+
+def _line_has_positional_descendant(starter: ET.Element) -> bool:
+ for descendant in starter.iter():
+ if descendant is starter or _local_name(descendant) != "tspan":
+ continue
+ if any(descendant.get(name) is not None for name in ("x", "y", "dy")):
+ return True
+ return False
+
+
+def _add_diagnostic(
+ diagnostics: list[TextContractDiagnostic],
+ code: str,
+ elem: ET.Element,
+ message: str,
+ *,
+ attribute: str | None = None,
+ hint: str | None = None,
+ owner: ET.Element | None = None,
+) -> None:
+ identity = owner or elem
+ diagnostics.append(
+ TextContractDiagnostic(
+ code=code,
+ message=message,
+ element_id=identity.get("id"),
+ element_tag=_local_name(elem),
+ attribute=attribute,
+ hint=hint,
+ )
+ )
+
+
+def _validate_transforms_and_baseline(
+ text: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+ diagnostics: list[TextContractDiagnostic],
+) -> None:
+ for node in _element_chain(text, parent_map):
+ style_transform = _style_map(node).get("transform")
+ if style_transform is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_TRANSFORM_UNSUPPORTED",
+ node,
+ "CSS style transforms are unsupported for explicit paragraph bounds",
+ attribute="style/transform",
+ hint="move a pure translate into the SVG transform attribute",
+ owner=text,
+ )
+ continue
+ transform = node.get("transform")
+ if transform and not _translate_only(transform):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_TRANSFORM_UNSUPPORTED",
+ node,
+ "explicit paragraph bounds only support pure translate transforms",
+ attribute="transform",
+ hint="materialize the transform into coordinates or use mode='lines'",
+ owner=text,
+ )
+
+ effective_dominant = _effective_property(text, "dominant-baseline", parent_map)
+ effective_alignment = _effective_property(text, "alignment-baseline", parent_map)
+ effective_shift = _effective_property(text, "baseline-shift", parent_map)
+ if effective_dominant not in {None, "auto", "alphabetic"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BASELINE_UNSUPPORTED",
+ text,
+ f"unsupported inherited dominant-baseline {effective_dominant!r}",
+ attribute="dominant-baseline",
+ hint="use the default alphabetic baseline",
+ )
+ if effective_alignment not in {None, "auto", "baseline", "alphabetic"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BASELINE_UNSUPPORTED",
+ text,
+ f"unsupported inherited alignment-baseline {effective_alignment!r}",
+ attribute="alignment-baseline",
+ hint="use the default alphabetic baseline",
+ )
+ if effective_shift not in {
+ None,
+ "baseline",
+ "0",
+ "0px",
+ "+0",
+ "+0px",
+ "-0",
+ "-0px",
+ }:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BASELINE_UNSUPPORTED",
+ text,
+ f"unsupported inherited baseline-shift {effective_shift!r}",
+ attribute="baseline-shift",
+ hint="remove baseline-shift from explicit paragraph text",
+ )
+
+ for node in text.iter():
+ if node is text:
+ continue
+ if node is not text:
+ transform = _style_map(node).get("transform") or node.get("transform")
+ if transform:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_TRANSFORM_UNSUPPORTED",
+ node,
+ "tspan transforms are unsupported in explicit paragraph mode",
+ attribute="transform",
+ hint="remove the tspan transform and express line positions with x/dy",
+ owner=text,
+ )
+
+ styles = _style_map(node)
+ dominant = styles.get("dominant-baseline") or node.get("dominant-baseline")
+ alignment = styles.get("alignment-baseline") or node.get("alignment-baseline")
+ shift = styles.get("baseline-shift") or node.get("baseline-shift")
+ if dominant not in {None, "auto", "alphabetic"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BASELINE_UNSUPPORTED",
+ node,
+ f"unsupported dominant-baseline {dominant!r}",
+ attribute="dominant-baseline",
+ hint="use the default alphabetic baseline",
+ owner=text,
+ )
+ if alignment not in {None, "auto", "baseline", "alphabetic"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BASELINE_UNSUPPORTED",
+ node,
+ f"unsupported alignment-baseline {alignment!r}",
+ attribute="alignment-baseline",
+ hint="use the default alphabetic baseline",
+ owner=text,
+ )
+ if shift not in {None, "baseline", "0", "0px", "+0", "+0px", "-0", "-0px"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BASELINE_UNSUPPORTED",
+ node,
+ f"unsupported baseline-shift {shift!r}",
+ attribute="baseline-shift",
+ hint="remove baseline-shift from explicit paragraph text",
+ owner=text,
+ )
+
+
+def _validate_unsupported_text_features(
+ text: ET.Element,
+ parent_map: dict[ET.Element, ET.Element],
+ diagnostics: list[TextContractDiagnostic],
+) -> None:
+ """Reject SVG text features that have no deterministic DrawingML mapping."""
+ for attribute in ("dx", "dy", "rotate"):
+ if text.get(attribute) is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BLOCK_OFFSET_UNSUPPORTED",
+ text,
+ f"block-level {attribute} is unsupported in explicit paragraph mode",
+ attribute=attribute,
+ hint="fold the offset into x/y or use a pure translate",
+ )
+
+ for node in text.iter():
+ for attribute in ("textLength", "lengthAdjust"):
+ if node.get(attribute) is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LENGTH_ADJUST_UNSUPPORTED",
+ node,
+ "SVG text-length adjustment has no native paragraph mapping",
+ attribute=attribute,
+ hint="remove textLength/lengthAdjust and use normal font metrics",
+ owner=text,
+ )
+ if node is not text and node.get("rotate") is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BLOCK_OFFSET_UNSUPPORTED",
+ node,
+ "per-character tspan rotation is unsupported in paragraph mode",
+ attribute="rotate",
+ hint="remove the rotate attribute or use mode='lines'",
+ owner=text,
+ )
+ if node is text:
+ continue
+ styles = _style_map(node)
+ if node.get("dx") is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_INLINE_OFFSET_UNSUPPORTED",
+ node,
+ "tspan dx offsets have no deterministic paragraph-run mapping",
+ attribute="dx",
+ hint="fold the offset into line x or remove it",
+ owner=text,
+ )
+ local_writing = styles.get("writing-mode") or node.get("writing-mode")
+ local_direction = styles.get("direction") or node.get("direction")
+ local_bidi = styles.get("unicode-bidi") or node.get("unicode-bidi")
+ if local_writing not in {None, "horizontal-tb"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_WRITING_MODE_UNSUPPORTED",
+ node,
+ f"unsupported tspan writing-mode {local_writing!r}",
+ attribute="writing-mode",
+ hint="remove the run-level writing mode",
+ owner=text,
+ )
+ if local_direction not in {None, "ltr"} or local_bidi not in {None, "normal"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_DIRECTION_UNSUPPORTED",
+ node,
+ "run-level bidirectional controls are unsupported in v1",
+ attribute="direction/unicode-bidi",
+ hint="remove the run-level bidi controls",
+ owner=text,
+ )
+
+ writing_mode = _effective_property(text, "writing-mode", parent_map)
+ if writing_mode not in {None, "horizontal-tb"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_WRITING_MODE_UNSUPPORTED",
+ text,
+ f"unsupported writing-mode {writing_mode!r}",
+ attribute="writing-mode",
+ hint="use horizontal-tb text or mode='lines'",
+ )
+ direction = _effective_property(text, "direction", parent_map)
+ unicode_bidi = _effective_property(text, "unicode-bidi", parent_map)
+ if direction not in {None, "ltr"} or unicode_bidi not in {None, "normal"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_DIRECTION_UNSUPPORTED",
+ text,
+ "bidirectional paragraph controls are unsupported in v1",
+ attribute="direction/unicode-bidi",
+ hint="use default left-to-right text or mode='lines'",
+ )
+
+
+def _parse_paragraph_contract(
+ text: ET.Element,
+ element_id: str,
+ parent_map: dict[ET.Element, ET.Element],
+ merge_paragraphs: bool,
+ diagnostics: list[TextContractDiagnostic],
+) -> TextBlockContract | None:
+ bounds_raw = text.get(TEXT_BOUNDS_ATTR)
+ bounds = _parse_bounds(bounds_raw)
+ if bounds_raw is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_REQUIRED",
+ text,
+ "paragraph mode requires four explicit text-frame bounds",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="add data-pptx-text-bounds='x y width height'",
+ )
+ elif bounds is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_INVALID",
+ text,
+ "bounds must contain exactly four finite unitless numbers",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="use data-pptx-text-bounds='x y width height'",
+ )
+ elif bounds[2] <= 0 or bounds[3] <= 0:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_NONPOSITIVE",
+ text,
+ "text-frame width and height must both be positive",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="provide positive width and height values",
+ )
+
+ _validate_transforms_and_baseline(text, parent_map, diagnostics)
+ _validate_unsupported_text_features(text, parent_map, diagnostics)
+
+ effective_font_size_raw = _effective_property(text, "font-size", parent_map)
+ if (
+ effective_font_size_raw is not None
+ and re.fullmatch(rf"{_NUMBER}(?:em|rem)", effective_font_size_raw.strip().lower())
+ ):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_FONT_SIZE_RELATIVE",
+ text,
+ "relative block font sizes are unsupported in explicit paragraph mode",
+ attribute="font-size",
+ hint="resolve the block font size to unitless px or pt",
+ )
+
+ font_size = _effective_font_size(text, parent_map)
+ if font_size is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_FONT_SIZE_INVALID",
+ text,
+ "the inherited block font-size must resolve to a positive px value",
+ attribute="font-size",
+ hint="use a positive unitless, px, or pt font-size",
+ )
+
+ preserve_space = _preserves_space(text, parent_map)
+ if _has_visible_direct_text(text.text, preserve_space):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_PARAGRAPH_DIRECT_TEXT",
+ text,
+ "paragraph content must start inside a direct child tspan",
+ hint="move the direct text into the first line tspan",
+ )
+
+ direct_children = list(text)
+ for child in direct_children:
+ if _local_name(child) != "tspan":
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_PARAGRAPH_CHILD_INVALID",
+ child,
+ "paragraph mode only accepts direct child tspan elements",
+ hint="remove the non-tspan child or move it outside the text block",
+ owner=text,
+ )
+ if _has_visible_direct_text(child.tail, preserve_space):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_PARAGRAPH_DIRECT_TEXT",
+ child,
+ "direct tspan tail text is ambiguous paragraph content",
+ hint="move the tail into the preceding or following line tspan",
+ owner=text,
+ )
+
+ tspan_children = [child for child in direct_children if _local_name(child) == "tspan"]
+ line_groups: list[list[ET.Element]] = []
+ for tspan in tspan_children:
+ positional = any(tspan.get(name) is not None for name in ("x", "y", "dy"))
+ if positional:
+ line_groups.append([tspan])
+ elif not line_groups:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_START_REQUIRED",
+ tspan,
+ "an inline tspan appears before the first positioned visual line",
+ hint="give the first line tspan the required x/y or x/dy anchor",
+ owner=text,
+ )
+ else:
+ line_groups[-1].append(tspan)
+
+ if not line_groups:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_START_REQUIRED",
+ text,
+ "paragraph mode requires at least one positioned direct child tspan",
+ hint="wrap the first visual line in a positioned tspan",
+ )
+ return None
+
+ for group in line_groups:
+ for line_part in group:
+ if _line_has_positional_descendant(line_part):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_POSITIONAL_NESTED",
+ line_part,
+ "nested positional tspans are unsupported in paragraph mode",
+ hint="keep x/y/dy only on direct visual-line starters",
+ owner=text,
+ )
+ content = "".join("".join(part.itertext()) for part in group)
+ if not content.strip():
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_EMPTY",
+ group[0],
+ "empty or whitespace-only visual lines are unsupported in v1",
+ hint="remove the empty line and express spacing on the next paragraph dy",
+ owner=text,
+ )
+
+ parent_x_raw = text.get("x")
+ parent_y_raw = text.get("y")
+ first = line_groups[0][0]
+ anchor_x: float | None = None
+ anchor_y: float | None = None
+ parent_anchor = parent_x_raw is not None or parent_y_raw is not None
+ if parent_anchor and (parent_x_raw is None or parent_y_raw is None):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BLOCK_ANCHOR_INVALID",
+ text,
+ "parent text must provide both x and y, or neither",
+ attribute="x/y",
+ hint="use <text x y> with first <tspan x dy='0'>, or put x/y on the first tspan",
+ )
+ elif parent_anchor:
+ anchor_x = _parse_coordinate(parent_x_raw)
+ anchor_y = _parse_coordinate(parent_y_raw)
+ first_x = _parse_coordinate(first.get("x"))
+ first_dy = _parse_coordinate(first.get("dy"))
+ if anchor_x is None or anchor_y is None or first_x is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BLOCK_ANCHOR_INVALID",
+ first,
+ "parent and first-line anchors must be finite unitless or px coordinates",
+ attribute="x/y/dy",
+ hint="use numeric parent x/y and repeat parent x on the first tspan",
+ owner=text,
+ )
+ if first.get("y") is not None or first.get("dy") is None or first_dy != 0:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_FIRST_LINE_GEOMETRY",
+ first,
+ "with parent x/y, the first line must use x and dy='0' without y",
+ attribute="x/y/dy",
+ hint="repeat the parent x and set dy='0' on the first tspan",
+ owner=text,
+ )
+ if anchor_x is not None and first_x is not None and abs(anchor_x - first_x) > 1e-6:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_X_MISMATCH",
+ first,
+ "first-line x does not repeat the block anchor",
+ attribute="x",
+ hint="set the first-line x equal to the parent text x",
+ owner=text,
+ )
+ else:
+ anchor_x = _parse_coordinate(first.get("x"))
+ anchor_y = _parse_coordinate(first.get("y"))
+ if anchor_x is None or anchor_y is None or first.get("dy") is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_FIRST_LINE_GEOMETRY",
+ first,
+ "without parent x/y, the first line must provide finite x/y and no dy",
+ attribute="x/y/dy",
+ hint="put x and y on the first tspan, or use the parent-anchor form",
+ owner=text,
+ )
+
+ if first.get(TEXT_BREAK_ATTR) is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BREAK_FIRST",
+ first,
+ "the first visual line cannot declare a preceding break",
+ attribute=TEXT_BREAK_ATTR,
+ hint="remove data-pptx-break from the first line",
+ owner=text,
+ )
+ if first.get(TEXT_JOIN_ATTR) is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_JOIN_FORBIDDEN",
+ first,
+ "the first visual line cannot declare a join",
+ attribute=TEXT_JOIN_ATTR,
+ hint="remove data-pptx-join from the first line",
+ owner=text,
+ )
+
+ raw_lines: list[tuple[ET.Element, tuple[ET.Element, ...], str | None, str | None, float]] = [
+ (first, tuple(line_groups[0][1:]), None, None, 0.0)
+ ]
+ for group in line_groups[1:]:
+ starter = group[0]
+ line_x = _parse_coordinate(starter.get("x"))
+ line_dy = _parse_coordinate(starter.get("dy"))
+ if starter.get("y") is not None or starter.get("x") is None or line_x is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_GEOMETRY_INVALID",
+ starter,
+ "later visual lines require a finite x and must not set y",
+ attribute="x/y",
+ hint="repeat the block anchor x and use a positive relative dy",
+ owner=text,
+ )
+ if anchor_x is not None and line_x is not None and abs(anchor_x - line_x) > 1e-6:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_X_MISMATCH",
+ starter,
+ "visual-line x does not repeat the block anchor",
+ attribute="x",
+ hint="set every line starter x equal to the block anchor",
+ owner=text,
+ )
+ if line_dy is None or line_dy <= 0:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_DY_INVALID",
+ starter,
+ "later visual lines require a positive relative dy",
+ attribute="dy",
+ hint="set dy to the positive distance from the preceding baseline",
+ owner=text,
+ )
+ line_dy = 0.0
+ break_kind = starter.get(TEXT_BREAK_ATTR)
+ join_kind = starter.get(TEXT_JOIN_ATTR)
+ if break_kind is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BREAK_REQUIRED",
+ starter,
+ "every visual line after the first must declare its break semantics",
+ attribute=TEXT_BREAK_ATTR,
+ hint="set data-pptx-break to soft, line, or paragraph",
+ owner=text,
+ )
+ elif break_kind not in BREAK_KINDS:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BREAK_INVALID",
+ starter,
+ f"unknown break kind {break_kind!r}",
+ attribute=TEXT_BREAK_ATTR,
+ hint="use exactly soft, line, or paragraph",
+ owner=text,
+ )
+ if break_kind == "soft":
+ if join_kind is None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_JOIN_REQUIRED",
+ starter,
+ "soft visual breaks require an explicit join policy",
+ attribute=TEXT_JOIN_ATTR,
+ hint="set data-pptx-join to space or none",
+ owner=text,
+ )
+ elif join_kind not in JOIN_KINDS:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_JOIN_INVALID",
+ starter,
+ f"unknown join kind {join_kind!r}",
+ attribute=TEXT_JOIN_ATTR,
+ hint="use exactly space or none",
+ owner=text,
+ )
+ elif join_kind is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_JOIN_FORBIDDEN",
+ starter,
+ "join is only valid with data-pptx-break='soft'",
+ attribute=TEXT_JOIN_ATTR,
+ hint="remove data-pptx-join or change the break to soft",
+ owner=text,
+ )
+ raw_lines.append((starter, tuple(group[1:]), break_kind, join_kind, line_dy))
+
+ for group in line_groups:
+ for inline in group[1:]:
+ for attribute in (TEXT_BREAK_ATTR, TEXT_JOIN_ATTR):
+ if inline.get(attribute) is not None:
+ _add_diagnostic(
+ diagnostics,
+ (
+ "TEXT_BREAK_PLACEMENT"
+ if attribute == TEXT_BREAK_ATTR
+ else "TEXT_JOIN_PLACEMENT"
+ ),
+ inline,
+ "break/join metadata is only valid on a direct visual-line starter",
+ attribute=attribute,
+ hint="move the attribute to the positioned line-start tspan",
+ owner=text,
+ )
+
+ base_line_height: float | None = None
+ if len(raw_lines) > 1:
+ positive_dys = [line[4] for line in raw_lines[1:] if line[4] > 0]
+ if positive_dys:
+ base_line_height = min(positive_dys)
+ if font_size is not None and (
+ base_line_height > font_size * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX
+ ):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_HEIGHT_INVALID",
+ text,
+ "base line height exceeds three times the block font size",
+ attribute="dy",
+ hint="reduce line dy or split the content into separate text blocks",
+ )
+ for starter, _, break_kind, _, line_dy in raw_lines[1:]:
+ if line_dy > base_line_height * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_LINE_HEIGHT_INVALID",
+ starter,
+ "line dy exceeds three times the normalized base line height",
+ attribute="dy",
+ hint="reduce the gap or use a separate text block",
+ owner=text,
+ )
+ if break_kind in {"soft", "line"} and (
+ abs(line_dy - base_line_height) > DY_TOLERANCE_PX
+ ):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BREAK_SPACING_INVALID",
+ starter,
+ "soft and line breaks cannot carry paragraph spacing",
+ attribute="dy",
+ hint="use the base line height, or declare a paragraph break",
+ owner=text,
+ )
+
+ visual_lines: list[TextVisualLine] = []
+ for starter, inline, break_kind, join_kind, line_dy in raw_lines:
+ space_before = 0.0
+ if break_kind == "paragraph" and base_line_height is not None:
+ space_before = max(0.0, line_dy - base_line_height)
+ visual_lines.append(
+ TextVisualLine(
+ starter=starter,
+ inline_tspans=inline,
+ break_kind=break_kind,
+ join_kind=join_kind,
+ dy=line_dy,
+ space_before=space_before,
+ )
+ )
+
+ top_inset: float | None = None
+ if bounds is not None and bounds[2] > 0 and bounds[3] > 0:
+ text_anchor = _effective_property(text, "text-anchor", parent_map) or "start"
+ if text_anchor not in {"start", "middle", "end"}:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_ANCHOR_INVALID",
+ text,
+ f"unsupported text-anchor {text_anchor!r}",
+ attribute="text-anchor",
+ hint="use start, middle, or end",
+ )
+ if anchor_x is not None:
+ expected_x = {
+ "start": bounds[0],
+ "middle": bounds[0] + bounds[2] / 2.0,
+ "end": bounds[0] + bounds[2],
+ }.get(text_anchor)
+ if expected_x is not None and abs(anchor_x - expected_x) > DY_TOLERANCE_PX:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_ANCHOR_MISMATCH",
+ text,
+ "block anchor x does not match the declared text frame and text-anchor",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="align line x with the frame left, center, or right anchor",
+ )
+ if anchor_y is not None:
+ final_baseline = anchor_y + sum(line[4] for line in raw_lines[1:])
+ bounds_bottom = bounds[1] + bounds[3]
+ if (
+ anchor_y < bounds[1] - DY_TOLERANCE_PX
+ or anchor_y > bounds_bottom + DY_TOLERANCE_PX
+ or final_baseline < bounds[1] - DY_TOLERANCE_PX
+ or final_baseline > bounds_bottom + DY_TOLERANCE_PX
+ ):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_BASELINE_OUTSIDE",
+ text,
+ "first or final visual baseline falls outside the declared text frame",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="increase frame height or correct the line baselines",
+ )
+ if font_size is not None:
+ top_inset = anchor_y - bounds[1] - 0.85 * font_size
+ if top_inset < -1e-9:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_TOP_INSET_NEGATIVE",
+ text,
+ "the baseline-to-frame offset produces a negative top inset",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="move bounds.y upward or move the first baseline downward",
+ )
+ else:
+ top_inset = max(0.0, top_inset)
+
+ effective_mode = "paragraph" if merge_paragraphs else "lines"
+ mode_reason = "explicit-paragraph" if merge_paragraphs else "cli-no-merge"
+ return TextBlockContract(
+ element=text,
+ element_id=element_id,
+ requested_mode="paragraph",
+ effective_mode=effective_mode,
+ mode_reason=mode_reason,
+ bounds=bounds,
+ anchor_x=anchor_x,
+ anchor_y=anchor_y,
+ block_font_size=font_size,
+ base_line_height=base_line_height,
+ top_inset=top_inset,
+ preserve_space=preserve_space,
+ visual_lines=tuple(visual_lines),
+ )
+
+
+def validate_text_contracts(
+ root: ET.Element,
+ merge_paragraphs: bool = True,
+ *,
+ enforce_native_carrier: bool = True,
+ source_name: str | None = None,
+) -> dict[ET.Element, TextBlockContract]:
+ """Validate every explicit text contract and return contracts by element.
+
+ Validation is all-or-nothing. Every discoverable violation is collected and
+ raised as one ``TextContractError`` before callers mutate the SVG tree.
+ Unmarked legacy text is intentionally omitted from the result. Disable
+ ``enforce_native_carrier`` only for strict visual-preview generation;
+ formal PPTX export must keep it enabled.
+ """
+ diagnostics: list[TextContractDiagnostic] = []
+ parent_map = {child: parent for parent in root.iter() for child in parent}
+ id_counts: dict[str, int] = {}
+ for elem in root.iter():
+ elem_id = elem.get("id")
+ if elem_id:
+ id_counts[elem_id] = id_counts.get(elem_id, 0) + 1
+
+ for elem in root.iter():
+ tag = _local_name(elem)
+ for attribute in elem.attrib:
+ if attribute.startswith("data-paragraph-"):
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_INTERNAL_ATTR_FORBIDDEN",
+ elem,
+ "data-paragraph-* attributes are compiler-internal and cannot be authored",
+ attribute=attribute,
+ hint="remove the internal attribute and use the public text contract",
+ owner=_nearest_text(elem, parent_map),
+ )
+ elif attribute in RUNTIME_ATTRS:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_RUNTIME_ATTR_FORBIDDEN",
+ elem,
+ "data-pptx-runtime-* attributes are compiler-internal and cannot be authored",
+ attribute=attribute,
+ hint="remove the runtime attribute from svg_output",
+ owner=_nearest_text(elem, parent_map),
+ )
+ if elem.get(TEXT_MODE_ATTR) is not None and tag != "text":
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_MODE_PLACEMENT",
+ elem,
+ "text mode is only valid on an SVG text element",
+ attribute=TEXT_MODE_ATTR,
+ hint="move data-pptx-text-mode to the owning text element",
+ owner=_nearest_text(elem, parent_map),
+ )
+ if elem.get(TEXT_BOUNDS_ATTR) is not None and tag != "text":
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_PLACEMENT",
+ elem,
+ "text bounds are only valid on an SVG text element",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="move data-pptx-text-bounds to the owning text element",
+ owner=_nearest_text(elem, parent_map),
+ )
+ for attribute, code in (
+ (TEXT_BREAK_ATTR, "TEXT_BREAK_PLACEMENT"),
+ (TEXT_JOIN_ATTR, "TEXT_JOIN_PLACEMENT"),
+ ):
+ if elem.get(attribute) is None:
+ continue
+ owner = _nearest_text(elem, parent_map)
+ if tag != "tspan" or owner is None or parent_map.get(elem) is not owner:
+ _add_diagnostic(
+ diagnostics,
+ code,
+ elem,
+ "break/join metadata is only valid on a direct visual-line tspan",
+ attribute=attribute,
+ hint="move the attribute to a direct line-start tspan in paragraph mode",
+ owner=owner,
+ )
+ elif owner.get(TEXT_MODE_ATTR) != "paragraph":
+ _add_diagnostic(
+ diagnostics,
+ code,
+ elem,
+ "break/join metadata requires data-pptx-text-mode='paragraph'",
+ attribute=attribute,
+ hint="remove the attribute or opt the owning text into paragraph mode",
+ owner=owner,
+ )
+
+ contracts: dict[ET.Element, TextBlockContract] = {}
+ for text in root.iter(f"{{{SVG_NS}}}text"):
+ mode = text.get(TEXT_MODE_ATTR)
+ if mode is None:
+ if text.get(TEXT_BOUNDS_ATTR) is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_MODE",
+ text,
+ "text bounds do not implicitly enable paragraph mode",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="add data-pptx-text-mode='paragraph' or remove bounds",
+ )
+ continue
+ if mode not in TEXT_MODES:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_MODE_INVALID",
+ text,
+ f"unknown text mode {mode!r}",
+ attribute=TEXT_MODE_ATTR,
+ hint="use exactly auto, paragraph, or lines without surrounding whitespace",
+ )
+ continue
+
+ element_id = text.get("id") or ""
+ if not element_id:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_ID_REQUIRED",
+ text,
+ "an explicit text contract requires a non-empty stable id",
+ attribute="id",
+ hint="add a unique id to the text element",
+ )
+ elif id_counts.get(element_id, 0) != 1:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_ID_DUPLICATE",
+ text,
+ f"explicit text id {element_id!r} is not unique in this SVG",
+ attribute="id",
+ hint="rename the text element so its id is unique",
+ )
+
+ if mode != "paragraph" and text.get(TEXT_BOUNDS_ATTR) is not None:
+ _add_diagnostic(
+ diagnostics,
+ "TEXT_BOUNDS_FORBIDDEN",
+ text,
+ f"text bounds are not valid in {mode!r} mode",
+ attribute=TEXT_BOUNDS_ATTR,
+ hint="remove bounds or use paragraph mode",
+ )
+
+ if enforce_native_carrier:
+ _validate_native_carrier_contract(
+ text,
+ mode,
+ merge_paragraphs,
+ parent_map,
+ diagnostics,
+ )
+
+ if mode == "paragraph":
+ contract = _parse_paragraph_contract(
+ text,
+ element_id,
+ parent_map,
+ merge_paragraphs,
+ diagnostics,
+ )
+ if contract is not None:
+ contracts[text] = contract
+ else:
+ effective_mode = "lines" if not merge_paragraphs or mode == "lines" else "auto"
+ if not merge_paragraphs:
+ reason = "cli-no-merge"
+ elif mode == "lines":
+ reason = "explicit-lines"
+ else:
+ reason = "legacy-auto"
+ contracts[text] = TextBlockContract(
+ element=text,
+ element_id=element_id,
+ requested_mode=mode,
+ effective_mode=effective_mode,
+ mode_reason=reason,
+ preserve_space=_preserves_space(text, parent_map),
+ )
+
+ if diagnostics:
+ if source_name:
+ for diagnostic in diagnostics:
+ diagnostic.source_name = source_name
+ raise TextContractError(diagnostics)
+ return contracts
+
+
+__all__ = [
+ "BREAK_KINDS",
+ "JOIN_KINDS",
+ "RUNTIME_CONTRACT_ATTR",
+ "RUNTIME_ATTRS",
+ "RUNTIME_EFFECTIVE_MODE_ATTR",
+ "RUNTIME_LINE_COUNT_ATTR",
+ "RUNTIME_LINE_INDEX_ATTR",
+ "RUNTIME_MODE_REASON_ATTR",
+ "RUNTIME_REQUESTED_MODE_ATTR",
+ "RUNTIME_SOURCE_ID_ATTR",
+ "TEXT_BOUNDS_ATTR",
+ "TEXT_BREAK_ATTR",
+ "TEXT_JOIN_ATTR",
+ "TEXT_MODE_ATTR",
+ "TextBlockContract",
+ "TextContractDiagnostic",
+ "TextContractError",
+ "TextVisualLine",
+ "validate_text_contracts",
+]
diff --git a/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py b/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py
index 45b6d1f5..c782304c 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/tspan_flattener.py
@@ -31,6 +31,8 @@ from xml.etree import ElementTree as ET
def flatten_positional_tspans(
tree: ET.ElementTree,
merge_paragraphs: bool = False,
+ *,
+ source_name: str | None = None,
) -> bool:
"""Flatten positional ``<tspan>`` elements into independent ``<text>``.
@@ -45,4 +47,8 @@ def flatten_positional_tspans(
if str(scripts_dir) not in sys.path:
sys.path.insert(0, str(scripts_dir))
from svg_finalize.flatten_tspan import flatten_text_with_tspans # type: ignore
- return flatten_text_with_tspans(tree, merge_paragraphs=merge_paragraphs)
+ return flatten_text_with_tspans(
+ tree,
+ merge_paragraphs=merge_paragraphs,
+ source_name=source_name,
+ )