AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He
fix(svg-to-pptx): enforce complete freeform geometry grammar
hugohe3f99722f40927
diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.mdindex 4ceeb003..8926a61e 100644--- a/skills/ppt-master/references/shared-standards.md+++ b/skills/ppt-master/references/shared-standards.md@@ -869,6 +869,25 @@ instance graph.| `A` | Cubic segments of at most 90° | `Approximate` || `Z`; polygon/polyline | Closed/open freeform | `Native-normalized` |+**Hard rule — complete freeform grammar**: Generated `path@d` and+`polygon` / `polyline@points` use finite unitless ordinary decimals and only+the commands registered above. Native export consumes the complete attribute;+it never extracts recognizable fragments while ignoring other characters.+Finite scientific notation, a leading plus sign, and a trailing decimal point+remain read-compatible and receive recommendation warnings; generated SVG does+not write them. Unknown commands or characters, misplaced/repeated commas,+non-finite numbers, missing attributes, incomplete command groups, and odd+point counts are invalid. A path starts with `M` / `m`; `A` radii are+non-negative and both arc flags are exactly `0` or `1`. Each registered path+command accepts its uppercase absolute and lowercase relative form. Legal+separator-free arc flag sequences remain valid and are parsed as individual+flag tokens. A polygon has at least three coordinate pairs and a polyline at+least two.++**Validation**: Checker and native export consume the same parser in+[`paths.py`](../scripts/svg_to_pptx/drawingml/paths.py); native-object fallback+bounds reuse its normalized commands rather than a second path grammar.+Command identity, relative coordinates, shorthand, arc parameters, and originalhandles are not retained. Geometry needs non-zero bounds. Use a closed cubicpath for organic silhouettes, polygon/closed path for ribbons/facets, open pathdiff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 8646b6d9..ea974484 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -89,6 +89,17 @@ except ImportError:_rect_to_dml_xfrm = None_validate_dml_shape_matrix = None+try:+ from svg_to_pptx.drawingml.paths import (+ iter_project_freeform_geometry as _iter_project_freeform_geometry,+ noncanonical_path_numbers as _noncanonical_path_numbers,+ noncanonical_points_numbers as _noncanonical_points_numbers,+ )+except ImportError:+ _iter_project_freeform_geometry = None+ _noncanonical_path_numbers = None+ _noncanonical_points_numbers = None+try:from svg_to_pptx.drawingml.converter import (collect_unsupported_visuals as _collect_unsupported_visuals,@@ -1067,7 +1078,10 @@ class SVGQualityChecker:# 2a. Validate direct geometry lengths and stroke widths.self._check_geometry_length_values(root, result)- # 2b. Validate the closed authoring-property surface and+ # 2b. Validate complete path-data and point-list grammar.+ self._check_freeform_geometry_values(root, result)++ # 2c. Validate the closed authoring-property surface and# conditional definition interfaces before export.self._check_authoring_property_contract(root, result)self._check_paint_compatibility(root, result)@@ -2152,6 +2166,64 @@ class SVGQualityChecker:f'{attribute}="{normalized}". No change is required for export.')+ def _check_freeform_geometry_values(+ self,+ root: ET.Element,+ result: Dict,+ ) -> None:+ """Reject malformed path/points syntax and advise decimal spelling."""+ helpers = (+ _format_project_geometry_length,+ _iter_project_freeform_geometry,+ _noncanonical_path_numbers,+ _noncanonical_points_numbers,+ )+ if any(helper is None for helper in helpers):+ result['warnings'].append(+ "Unable to import svg_to_pptx freeform geometry validators; "+ "native export will still validate path and points syntax."+ )+ return++ errors: set[str] = set()+ recommendations: Counter[tuple[str, str, str]] = Counter()+ examples: Dict[tuple[str, str, str], List[str]] = defaultdict(list)++ for elem, attribute, raw, min_points in _iter_project_freeform_geometry(root):+ label = _element_label(elem)+ try:+ if raw is None:+ tag = _local_name(elem)+ raise ValueError(f'<{tag}> requires {attribute}')+ if attribute == 'd':+ compatible_numbers = _noncanonical_path_numbers(raw)+ else:+ required_points = min_points or 2+ compatible_numbers = _noncanonical_points_numbers(+ raw,+ min_points=required_points,+ )+ except ValueError as exc:+ errors.add(f'{label} {attribute}: {exc}')+ continue++ for number in compatible_numbers:+ normalized = _format_project_geometry_length(float(number))+ key = (attribute, number, normalized)+ recommendations[key] += 1+ if label not in examples[key] and len(examples[key]) < 3:+ examples[key].append(label)++ result['errors'].extend(sorted(errors))+ for (attribute, raw, normalized), count in sorted(recommendations.items()):+ shown_examples = ', '.join(examples[(attribute, raw, normalized)])+ result['warnings'].append(+ f"Recommendation: freeform geometry {attribute} numeric token "+ f"{raw!r} is converter-compatible in {count} occurrence(s) "+ f"({shown_examples}); generated SVG should prefer the ordinary "+ f"decimal spelling {normalized!r}. No change is required for export."+ )+def _check_font_size_values(self, content: str, result: Dict):"""Keep supported font-size units compatible and recommend unitless px."""canonical_re = re.compile(r'^(?:\d+(?:\.\d+)?|\.\d+)$')diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.pyindex 22891748..efe94345 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/converter.py@@ -27,6 +27,7 @@ from pptx_to_svg.preset_authoring import (from resource_paths import icon_search_dirs_for_svgfrom .context import ConvertContext, ShapeResult+from .paths import project_freeform_geometry_errorsfrom .theme_colors import ThemeColorSpecfrom .theme_fonts import ThemeFontSpecfrom .utils import (@@ -62,6 +63,22 @@ class SvgNativeConversionError(RuntimeError):"""Raised when an SVG cannot be faithfully converted to native DrawingML."""+def _require_project_freeform_geometry(+ root: ET.Element,+ svg_path: Path | str,+) -> None:+ """Reject malformed path and points values with one aggregated error."""+ errors = project_freeform_geometry_errors(root)+ if not errors:+ return+ preview = '; '.join(errors[:8])+ suffix = '' if len(errors) <= 8 else f'; +{len(errors) - 8} more'+ raise SvgNativeConversionError(+ f'{Path(svg_path).name}: invalid project freeform geometry: '+ f'{preview}{suffix}'+ )++# ---------------------------------------------------------------------------# Transform & layout helpers# ---------------------------------------------------------------------------@@ -1138,6 +1155,8 @@ def convert_svg_to_slide_shapes(f'{preview}{suffix}')+ _require_project_freeform_geometry(root, svg_path)+viewport_width, viewport_height = _root_viewport_size(root)# Expand project icon placeholders and static same-document <use>@@ -1155,6 +1174,8 @@ def convert_svg_to_slide_shapes(trace_steps.append({'action': 'expand-use-data-icons', 'count': expanded})if verbose and expanded:print(f' Expanded {expanded} <use data-icon="..."/> placeholder(s)')+ if expanded:+ _require_project_freeform_geometry(root, svg_path)try:injected_geometry_count = materialize_inline_geometry_properties(root)diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.pyindex 82d4fd44..0aaf1553 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py@@ -46,7 +46,7 @@ from .styles import (get_element_opacity, get_fill_opacity, get_stroke_opacity,)from .paths import (- PathCommand, parse_svg_path, svg_path_to_absolute,+ PathCommand, parse_svg_path, parse_svg_points, svg_path_to_absolute,normalize_path_commands, path_commands_to_drawingml,)@@ -1442,22 +1442,10 @@ def convert_path(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:# polygon / polyline# ----------------------------------------------------------------------------def _parse_points(points_str: str) -> list[tuple[float, float]]:- """Parse SVG points attribute into a list of (x, y) tuples."""- nums = re.findall(r'[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?', points_str)- if len(nums) < 4:- return []- return [(float(nums[i]), float(nums[i + 1])) for i in range(0, len(nums) - 1, 2)]--def convert_polygon(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:"""Convert SVG <polygon> to DrawingML custom geometry shape."""preset_geom = _build_preset_geom_from_meta(elem)- points = _parse_points(elem.get('points', ''))- if not points:- if preset_geom is not None:- raise ValueError('Preset-bearing <polygon> requires valid points')- return None+ points = parse_svg_points(elem.get('points', ''), min_points=3)commands = [PathCommand('M', [points[0][0], points[0][1]])]for px_, py_ in points[1:]:@@ -1526,11 +1514,7 @@ def convert_polygon(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | Nonedef convert_polyline(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:"""Convert SVG <polyline> to DrawingML custom geometry shape."""preset_geom = _build_preset_geom_from_meta(elem)- points = _parse_points(elem.get('points', ''))- if not points:- if preset_geom is not None:- raise ValueError('Preset-bearing <polyline> requires valid points')- return None+ points = parse_svg_points(elem.get('points', ''), min_points=2)commands = [PathCommand('M', [points[0][0], points[0][1]])]for px_, py_ in points[1:]:@@ -2670,9 +2654,7 @@ def _resolve_clip_geometry(# --- Polygon → custGeom ---if shape_tag == 'polygon':- pts = _parse_points(shape.get('points', ''))- if not pts:- return DEFAULT+ pts = parse_svg_points(shape.get('points', ''), min_points=3)commands = [PathCommand('M', [pts[0][0], pts[0][1]])]for px_, py_ in pts[1:]:commands.append(PathCommand('L', [px_, py_]))diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.pyindex 04b115e3..8b0f5436 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/paths.py@@ -1,12 +1,18 @@-"""SVG path parsing, normalization, and DrawingML path command generation."""+"""SVG path parsing, normalization, and DrawingML path command generation.++See references/shared-standards.md §6.9 for the project freeform grammar.+"""from __future__ import annotationsimport mathimport re+from collections import deque+from collections.abc import Iteratorfrom dataclasses import dataclass, field+from xml.etree import ElementTree as ET-from .utils import px_to_emu+from .utils import SVG_NS, px_to_emu@dataclass@@ -25,55 +31,301 @@ _ARG_COUNTS = {'A': 7, 'a': 7, 'Z': 0, 'z': 0,}+_PATH_COMMAND_CHARS = 'MmLlHhVvCcSsQqTtAaZz'+_PATH_NUMBER_PATTERN = (+ r'[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?'+)+_PATH_TOKEN_RE = re.compile(+ rf'(?P<command>[{_PATH_COMMAND_CHARS}])|(?P<number>{_PATH_NUMBER_PATTERN})'+)+_POINT_TOKEN_RE = re.compile(_PATH_NUMBER_PATTERN)+_TOKEN_SEPARATOR_RE = re.compile(r'[ \t\r\n]*(?:,[ \t\r\n]*)?')+_TRAILING_WHITESPACE_RE = re.compile(r'[ \t\r\n]*')+_CANONICAL_FREEFORM_NUMBER_RE = re.compile(+ r'-?(?:\d+(?:\.\d+)?|\.\d+)$'+)+++@dataclass(frozen=True)+class _GeometryToken:+ kind: str+ raw: str+ offset: int+++def _tokenize_path_data(d: str) -> list[_GeometryToken]:+ """Tokenize one complete path-data value without skipping input."""+ if not d or not d.strip():+ raise ValueError('path d must not be empty')++ tokens: list[_GeometryToken] = []+ cursor = 0+ previous_kind: str | None = None+ for match in _PATH_TOKEN_RE.finditer(d):+ kind = 'command' if match.lastgroup == 'command' else 'number'+ gap = d[cursor:match.start()]+ if _TOKEN_SEPARATOR_RE.fullmatch(gap) is None:+ raise ValueError(+ f'path d contains unsupported syntax at offset {cursor}: {gap!r}'+ )+ if ',' in gap and (+ previous_kind is None+ or previous_kind == 'command'+ or kind == 'command'+ ):+ raise ValueError(+ f'path d has a misplaced comma at offset {cursor}'+ )+ tokens.append(_GeometryToken(kind, match.group(), match.start()))+ previous_kind = kind+ cursor = match.end()++ trailing = d[cursor:]+ if _TRAILING_WHITESPACE_RE.fullmatch(trailing) is None:+ raise ValueError(+ f'path d contains unsupported trailing syntax at offset '+ f'{cursor}: {trailing!r}'+ )+ if not tokens:+ raise ValueError('path d must contain a supported command')+ return tokens+++def _finite_token_value(token: _GeometryToken, context: str) -> float:+ value = float(token.raw)+ if not math.isfinite(value):+ raise ValueError(+ f'{context} contains a non-finite number {token.raw!r} at '+ f'offset {token.offset}'+ )+ return value+++def _expand_arc_argument_tokens(+ argument_tokens: list[_GeometryToken],+ command_token: _GeometryToken,+) -> list[_GeometryToken]:+ """Split compact SVG arc flags without weakening the numeric grammar."""+ pending = deque(argument_tokens)+ expanded: list[_GeometryToken] = []+ argument_index = 0+ while pending:+ token = pending.popleft()+ position = argument_index % _ARG_COUNTS[command_token.raw]+ if position in {3, 4}:+ if not token.raw or token.raw[0] not in {'0', '1'}:+ raise ValueError(+ f'path arc flag at offset {token.offset} must be exactly '+ f'0 or 1; got {token.raw!r}'+ )+ expanded.append(+ _GeometryToken('number', token.raw[0], token.offset)+ )+ remainder = token.raw[1:]+ if remainder:+ next_position = (position + 1) % _ARG_COUNTS[command_token.raw]+ if (+ next_position in {3, 4}+ and remainder[0] not in {'0', '1'}+ ) or (+ next_position not in {3, 4}+ and re.fullmatch(_PATH_NUMBER_PATTERN, remainder) is None+ ):+ raise ValueError(+ f'path arc flag at offset {token.offset} must be '+ f'exactly 0 or 1; got {token.raw!r}'+ )+ pending.appendleft(+ _GeometryToken('number', remainder, token.offset + 1)+ )+ else:+ expanded.append(token)+ argument_index += 1++ return expanded-def parse_svg_path(d: str) -> list[PathCommand]:- """Parse SVG path d attribute into a list of PathCommands."""- if not d:- return []++def _tokenize_points(points: str) -> list[_GeometryToken]:+ """Tokenize one complete polygon/polyline points value."""+ if not points or not points.strip():+ raise ValueError('points must not be empty')++ tokens: list[_GeometryToken] = []+ cursor = 0+ for match in _POINT_TOKEN_RE.finditer(points):+ gap = points[cursor:match.start()]+ if _TOKEN_SEPARATOR_RE.fullmatch(gap) is None:+ raise ValueError(+ f'points contains unsupported syntax at offset {cursor}: {gap!r}'+ )+ if not tokens and ',' in gap:+ raise ValueError('points cannot start with a comma')+ tokens.append(_GeometryToken('number', match.group(), match.start()))+ cursor = match.end()++ trailing = points[cursor:]+ if _TRAILING_WHITESPACE_RE.fullmatch(trailing) is None:+ raise ValueError(+ f'points contains unsupported trailing syntax at offset '+ f'{cursor}: {trailing!r}'+ )+ if not tokens:+ raise ValueError('points must contain coordinate pairs')+ return tokens+++def _parse_svg_path_tokens(+ d: str,+) -> tuple[list[PathCommand], list[_GeometryToken]]:+ """Parse path data and retain its semantic numeric tokens."""+ tokens = _tokenize_path_data(d)+ if tokens[0].kind != 'command' or tokens[0].raw not in {'M', 'm'}:+ raise ValueError('path d must begin with M or m')commands: list[PathCommand] = []- tokens = re.findall(- r'[MmLlHhVvCcSsQqTtAaZz]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?', d- )+ number_tokens: list[_GeometryToken] = []+ token_index = 0+ while token_index < len(tokens):+ command_token = tokens[token_index]+ if command_token.kind != 'command':+ raise ValueError(+ f'path d requires a command at offset {command_token.offset}'+ )+ command = command_token.raw+ token_index += 1+ if command in {'Z', 'z'}:+ commands.append(PathCommand(command, []))+ continue++ argument_tokens: list[_GeometryToken] = []+ while token_index < len(tokens) and tokens[token_index].kind == 'number':+ argument_tokens.append(tokens[token_index])+ token_index += 1++ argument_count = _ARG_COUNTS[command]+ if command in {'A', 'a'}:+ argument_tokens = _expand_arc_argument_tokens(+ argument_tokens,+ command_token,+ )+ if not argument_tokens:+ raise ValueError(+ f'path command {command!r} at offset {command_token.offset} '+ f'requires {argument_count} argument(s)'+ )+ if len(argument_tokens) % argument_count:+ raise ValueError(+ f'path command {command!r} at offset {command_token.offset} '+ f'has {len(argument_tokens)} argument(s); expected a multiple '+ f'of {argument_count}'+ )++ for group_index in range(0, len(argument_tokens), argument_count):+ group = argument_tokens[group_index:group_index + argument_count]+ values = [_finite_token_value(token, 'path d') for token in group]+ if command in {'A', 'a'}:+ if values[0] < 0 or values[1] < 0:+ raise ValueError('path arc radii must be non-negative')++ emitted_command = command+ if command == 'M' and group_index > 0:+ emitted_command = 'L'+ elif command == 'm' and group_index > 0:+ emitted_command = 'l'+ commands.append(PathCommand(emitted_command, values))+ number_tokens.extend(group)+ return commands, number_tokens- current_cmd: str | None = None- current_args: list[float] = []-- def flush() -> None:- nonlocal current_cmd, current_args- if current_cmd is None:- return-- n = _ARG_COUNTS.get(current_cmd, 0)- if n == 0:- commands.append(PathCommand(current_cmd, []))- elif n > 0 and len(current_args) >= n:- i = 0- while i + n <= len(current_args):- commands.append(PathCommand(current_cmd, current_args[i:i + n]))- # After first M, implicit commands become L- if current_cmd == 'M':- current_cmd = 'L'- elif current_cmd == 'm':- current_cmd = 'l'- i += n- current_args = []-- for token in tokens:- if token in 'MmLlHhVvCcSsQqTtAaZz':- flush()- current_cmd = token- current_args = []- else:- try:- current_args.append(float(token))- except ValueError:- pass- flush()+def parse_svg_path(d: str) -> list[PathCommand]:+ """Parse one complete supported SVG path value or fail closed."""+ commands, _ = _parse_svg_path_tokens(d)return commands+def parse_svg_points(+ points: str,+ *,+ min_points: int = 2,+) -> list[tuple[float, float]]:+ """Parse complete polygon/polyline points into finite coordinate pairs."""+ tokens = _tokenize_points(points)+ if len(tokens) % 2:+ raise ValueError(+ f'points has {len(tokens)} numeric value(s); expected coordinate pairs'+ )+ point_count = len(tokens) // 2+ if point_count < min_points:+ raise ValueError(+ f'points requires at least {min_points} coordinate pair(s); '+ f'found {point_count}'+ )+ values = [_finite_token_value(token, 'points') for token in tokens]+ return [+ (values[index], values[index + 1])+ for index in range(0, len(values), 2)+ ]+++def noncanonical_path_numbers(d: str) -> tuple[str, ...]:+ """Return compatible path numbers that generated SVG should normalize."""+ _, number_tokens = _parse_svg_path_tokens(d)+ return tuple(+ token.raw+ for token in number_tokens+ if _CANONICAL_FREEFORM_NUMBER_RE.fullmatch(token.raw) is None+ )+++def noncanonical_points_numbers(points: str, *, min_points: int) -> tuple[str, ...]:+ """Return compatible point numbers that generated SVG should normalize."""+ parse_svg_points(points, min_points=min_points)+ return tuple(+ token.raw+ for token in _tokenize_points(points)+ if _CANONICAL_FREEFORM_NUMBER_RE.fullmatch(token.raw) is None+ )+++def iter_project_freeform_geometry(+ root: ET.Element,+) -> Iterator[tuple[ET.Element, str, str | None, int | None]]:+ """Yield path/points values and their minimum point-count contract."""+ for elem in root.iter():+ raw_tag = str(elem.tag)+ if raw_tag.startswith('{'):+ namespace, tag = raw_tag[1:].split('}', 1)+ if namespace != SVG_NS:+ continue+ else:+ tag = raw_tag+ if tag == 'path':+ yield elem, 'd', elem.get('d'), None+ elif tag == 'polygon':+ yield elem, 'points', elem.get('points'), 3+ elif tag == 'polyline':+ yield elem, 'points', elem.get('points'), 2+++def project_freeform_geometry_errors(root: ET.Element) -> list[str]:+ """Return blocking path/points grammar errors for converter preflight."""+ errors: list[str] = []+ for elem, attribute, raw, min_points in iter_project_freeform_geometry(root):+ tag = elem.tag.rsplit('}', 1)[-1] if '}' in str(elem.tag) else str(elem.tag)+ elem_id = elem.get('id')+ label = f'<{tag} id={elem_id!r}>' if elem_id else f'<{tag}>'+ try:+ if raw is None:+ raise ValueError(f'<{tag}> requires {attribute}')+ if attribute == 'd':+ parse_svg_path(raw)+ else:+ parse_svg_points(raw, min_points=min_points or 2)+ except ValueError as exc:+ errors.append(f'{label} {attribute}: {exc}')+ return errors++def svg_path_to_absolute(commands: list[PathCommand]) -> list[PathCommand]:"""Convert all relative path commands to absolute."""result: list[PathCommand] = []diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.pyindex add4d5d6..173f87ef 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.py@@ -10,6 +10,11 @@ from typing import Anyfrom xml.etree import ElementTree as ETfrom ..drawingml.context import ConvertContext, IDENTITY_MATRIX+from ..drawingml.paths import (+ parse_svg_path,+ parse_svg_points,+ svg_path_to_absolute,+)from ..drawingml.utils import (EMU_PER_PX,ctx_h,@@ -51,7 +56,6 @@ _NATIVE_TRANSFORM_ARGS_RE = re.compile()_HEX_RE = re.compile(r"^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$")_RGB_RE = re.compile(r"^rgba?\(([^)]+)\)$", re.IGNORECASE)-_POINT_RE = re.compile(r"[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?")_CSS_NAMED_COLORS = {"aliceblue": "F0F8FF","black": "000000",@@ -363,118 +367,49 @@ def _apply_matrix_bbox(return result-def _points_attr_bbox(value: str | None) -> tuple[float, float, float, float] | None:- numbers = [float(item) for item in _POINT_RE.findall(value or "")]- points = [- (numbers[idx], numbers[idx + 1])- for idx in range(0, len(numbers) - 1, 2)- ]+def _points_attr_bbox(+ value: str | None,+ *,+ min_points: int,+) -> tuple[float, float, float, float] | None:+ try:+ points = parse_svg_points(value or "", min_points=min_points)+ except ValueError as exc:+ raise RuntimeError(f"Invalid native fallback points: {exc}") from excreturn _bbox_from_points(points)def _path_bbox(value: str | None) -> tuple[float, float, float, float] | None:- tokens = re.findall(r"[AaCcHhLlMmQqSsTtVvZz]|[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?", value or "")+ try:+ commands = svg_path_to_absolute(parse_svg_path(value or ""))+ except ValueError as exc:+ raise RuntimeError(f"Invalid native fallback path d: {exc}") from exc+points: list[tuple[float, float]] = []- index = 0- command = ""- current_x = 0.0- current_y = 0.0subpath_x = 0.0subpath_y = 0.0- def read_number() -> float | None:- nonlocal index- if index >= len(tokens) or re.fullmatch(r"[A-Za-z]", tokens[index]):- return None- number = float(tokens[index])- index += 1- return number-- def add_point(x_value: float, y_value: float, *, relative: bool) -> tuple[float, float]:- x = current_x + x_value if relative else x_value- y = current_y + y_value if relative else y_value- points.append((x, y))- return x, y-- while index < len(tokens):- token = tokens[index]- if re.fullmatch(r"[A-Za-z]", token):- command = token- index += 1- if not command:- break-- relative = command.islower()- op = command.upper()- if op == "Z":- current_x, current_y = subpath_x, subpath_y- points.append((current_x, current_y))- command = ""- continue-- if op in {"M", "L", "T"}:- x_raw = read_number()- y_raw = read_number()- if x_raw is None or y_raw is None:- break- current_x, current_y = add_point(x_raw, y_raw, relative=relative)- if op == "M":- subpath_x, subpath_y = current_x, current_y- command = "l" if relative else "L"- continue-- if op == "H":- x_raw = read_number()- if x_raw is None:- break- current_x = current_x + x_raw if relative else x_raw- points.append((current_x, current_y))- continue-- if op == "V":- y_raw = read_number()- if y_raw is None:- break- current_y = current_y + y_raw if relative else y_raw- points.append((current_x, current_y))- continue-- if op == "C":- values = [read_number() for _ in range(6)]- if any(item is None for item in values):- break- for point_idx in range(0, 6, 2):- current_x, current_y = add_point(- values[point_idx], # type: ignore[arg-type]- values[point_idx + 1], # type: ignore[arg-type]- relative=relative,- )- continue-- if op in {"S", "Q"}:- values = [read_number() for _ in range(4)]- if any(item is None for item in values):- break- for point_idx in range(0, 4, 2):- current_x, current_y = add_point(- values[point_idx], # type: ignore[arg-type]- values[point_idx + 1], # type: ignore[arg-type]- relative=relative,- )- continue-- if op == "A":- values = [read_number() for _ in range(7)]- if any(item is None for item in values):- break- current_x, current_y = add_point(- values[5], # type: ignore[arg-type]- values[6], # type: ignore[arg-type]- relative=relative,+ for command in commands:+ values = command.args+ if command.cmd == "M":+ subpath_x, subpath_y = values+ points.append((subpath_x, subpath_y))+ elif command.cmd in {"L", "T"}:+ points.append((values[0], values[1]))+ elif command.cmd == "C":+ points.extend(+ (values[index], values[index + 1])+ for index in range(0, 6, 2))- continue-- break+ elif command.cmd in {"S", "Q"}:+ points.extend(+ (values[index], values[index + 1])+ for index in range(0, 4, 2)+ )+ elif command.cmd == "A":+ points.append((values[5], values[6]))+ elif command.cmd == "Z":+ points.append((subpath_x, subpath_y))return _bbox_from_points(points)@@ -534,7 +469,10 @@ def _element_local_bbox(elem: ET.Element) -> tuple[float, float, float, float] |return _bbox_from_points(points)if tag in {"polygon", "polyline"}:- return _points_attr_bbox(elem.get("points"))+ return _points_attr_bbox(+ elem.get("points"),+ min_points=3 if tag == "polygon" else 2,+ )if tag == "path":# This intentionally approximates path geometry from command endpoints.