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): normalize tracked text runs before export
hugohe34b632e01d913
diff --git a/docs/powerpoint-svg-mapping.md b/docs/powerpoint-svg-mapping.mdindex bd4d88da..c3226c82 100644--- a/docs/powerpoint-svg-mapping.md+++ b/docs/powerpoint-svg-mapping.md@@ -121,7 +121,7 @@ preset selection and authoring behavior are documented in| Text outline | Registered stroke on text | DrawingML run outline | `Native-normalized` | Review when outline carries fine visual meaning || Text alignment | Registered `text-anchor` and paragraph semantics | Paragraph alignment plus normalized text-frame position | `Native-normalized` | Run-level anchoring and browser baseline heuristics are unsupported; exact placement belongs to [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) || Vertical text-frame alignment | No canonical generated-SVG control; generated text boxes use top anchoring | Top-anchored DrawingML text body | Imported vertical text may be normalized, but the main route does not expose a general authoring control | Do not infer vertical alignment from SVG baseline or browser layout behavior |-| Character spacing | Registered `letter-spacing` | DrawingML character spacing | `Native-normalized` | Unsupported CSS typography, out-of-range DrawingML spacing, and negative tracking that collapses a generated text frame to a non-positive extent are rejected under [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) |+| Character spacing | Registered `letter-spacing` | DrawingML character spacing | `Native-normalized` | Unsupported CSS typography, out-of-range DrawingML spacing, and negative tracking that collapses a generated run advance or text-frame extent to a non-positive value are rejected under [`shared-standards.md` §6.7](../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) || Bulleted paragraph | Recognized leading bullet form | Native DrawingML bullet | `Native-normalized` | Only the registered bullet grammar is promoted || Rotated text | Supported transform on the text object | Rotated text shape | `Native-normalized` | Skewed text and browser-only transforms are unsupported || Text shadow or glow | Supported filter/effect contract | One native outer shadow or glow | `Approximate` | One supported effect graph only; review material effects |diff --git a/docs/zh/powerpoint-svg-mapping.md b/docs/zh/powerpoint-svg-mapping.mdindex 44ec1205..7345d5cf 100644--- a/docs/zh/powerpoint-svg-mapping.md+++ b/docs/zh/powerpoint-svg-mapping.md@@ -116,7 +116,7 @@ PowerPoint 意图| 文本轮廓 | 文本上已登记 stroke | DrawingML run outline | `Native-normalized` | 轮廓承载精细视觉意义时需复核 || 文本对齐 | 已登记的 `text-anchor` 与段落语义 | 段落对齐加归一化文本框位置 | `Native-normalized` | 不支持 run 级锚定与浏览器 baseline 启发式;精确放置属于 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) || 文本框垂直对齐 | 无规范生成 SVG 控制;生成文本框使用顶部对齐 | 顶部对齐的 DrawingML text body | 导入的垂直文本可能被归一化,但主路线不公开通用创作控制 | 不得从 SVG baseline 或浏览器排版行为推断垂直对齐 |-| 字符间距 | 已登记 `letter-spacing` | DrawingML 字符间距 | `Native-normalized` | 按 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) 拒绝不受支持的 CSS 排版、超出 DrawingML 范围的间距,以及导致生成文本框 extent 非正的负字距 |+| 字符间距 | 已登记 `letter-spacing` | DrawingML 字符间距 | `Native-normalized` | 按 [`shared-standards.md` §6.7](../../skills/ppt-master/references/shared-standards.md#67-advanced-text-treatments) 拒绝不受支持的 CSS 排版、超出 DrawingML 范围的间距,以及导致生成 run advance 或文本框 extent 非正的负字距 || 项目符号段落 | 已识别的前导项目符号形式 | 原生 DrawingML bullet | `Native-normalized` | 仅提升已登记 bullet 语法 || 旋转文本 | 文本对象上受支持的 transform | 旋转文本 shape | `Native-normalized` | 倾斜文本与浏览器专属 transform 不受支持 || 文本阴影或发光 | 受支持 filter/effect 合同 | 一个原生外阴影或发光 | `Approximate` | 仅支持一个已登记效果图;实质效果需复核 |diff --git a/skills/ppt-master/references/shared-standards.md b/skills/ppt-master/references/shared-standards.mdindex 2100f89e..03074e43 100644--- a/skills/ppt-master/references/shared-standards.md+++ b/skills/ppt-master/references/shared-standards.md@@ -895,7 +895,7 @@ other value is invalid; the converter must not replace it with a default.| `font-style` | `normal` or `italic` | None | `italic` maps to `i="1"`; oblique, angle, relative, and CSS-wide values are invalid || `text-anchor` | `start`, `middle`, or `end` on `<svg>`, `<g>`, or `<text>` | None | Maps to left/center/right paragraph alignment plus normalized frame position; it is invalid on `<tspan>` because run-level anchoring has no mapping || `text-decoration` | `none`, `underline`, `line-through`, or `underline line-through` | `line-through underline` → canonical order | Maps to the single underline and strike run properties; unknown, repeated, or substring-like tokens are invalid |-| `letter-spacing` | Finite unitless ordinary decimal SVG px | The same ordinary decimal with `px`, `pt`, or `em`; normalize to unitless px | Maps to `a:rPr@spc`; the final value must fit DrawingML `-400000..400000`, and negative tracking must still leave the generated DrawingML text frame with a positive extent; keywords, percentages, exponents, leading plus signs, trailing decimal points, non-finite values, and other units are invalid |+| `letter-spacing` | Finite unitless ordinary decimal SVG px | The same ordinary decimal with `px`, `pt`, or `em`; normalize to unitless px | Maps to `a:rPr@spc`; the final value must fit DrawingML `-400000..400000`, and negative tracking must leave every generated DrawingML run with a positive estimated advance and its text frame with a positive extent; keywords, percentages, exponents, leading plus signs, trailing decimal points, non-finite values, and other units are invalid |The registered text properties follow SVG inheritance, including declarationson the root `<svg>`: inline `style` overrides the same element's direct@@ -905,13 +905,25 @@ Every declaration is validated even when a later declaration overrides it, sohidden garbage cannot bypass preflight.The DrawingML character-spacing range is necessary but not sufficient for-negative tracking. After run assembly, the generated text frame must retain a-positive horizontal and vertical extent. Checker rejects directly measurable-single-line violations, and the converter revalidates every generated text-frame before writing OOXML. It must not clamp, take the absolute value of, or-otherwise hide a non-positive extent. An unchanged imported native text body-reuses the geometry carrier's positive shape frame and attaches the preserved-`txBody` payload instead of regenerating a text frame from the SVG estimate.+negative tracking. After run assembly, each output run must retain a positive+estimated advance using the quantized `sz` and `spc` values that will actually+be written; a wider sibling run or paragraph line cannot hide a run whose+aggregate advance would reverse or collapse, which can reorder or drop+characters across PowerPoint-compatible renderers. The generated text frame+must also retain a positive horizontal and vertical extent. Checker rejects+directly measurable single-line violations, and the converter revalidates+every generated run and text frame before writing OOXML. It must not clamp,+take the absolute value of, or otherwise hide a non-positive advance or extent.+Adjacent authored runs with identical final DrawingML run properties form one+output run before sizing and validation; splitting text across equivalent+`<tspan>` nodes is not a tracking escape hatch. Tracking and width estimates+count the registered project text clusters rather than raw Unicode code points:+combining marks, variation selectors, emoji modifiers and ZWJ sequences,+paired regional indicators, and same-script virama conjuncts do not receive+internal spacing.+An unchanged imported native text body reuses the geometry carrier's positive+shape frame and attaches the preserved `txBody` payload instead of regenerating+runs or a text frame from the SVG estimate.**Hard rule — element-specific text surface**:diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex f9bd476c..f17875a0 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -60,7 +60,8 @@ try:PROJECT_OPACITY_PROPERTIES as _OPACITY_PROPERTIES,PROJECT_PAINT_PROPERTIES as _PAINT_PROPERTIES,PROJECT_PERCENTAGE_OPACITY_PROPERTIES as _PERCENTAGE_OPACITY_PROPERTIES,- estimate_text_width as _estimate_text_width,+ detect_text_lang as _detect_text_lang,+ estimate_text_cluster_widths as _estimate_text_cluster_widths,format_project_geometry_length as _format_project_geometry_length,format_project_image_aspect_ratio as _format_project_image_aspect_ratio,format_project_opacity as _format_project_opacity,@@ -98,6 +99,7 @@ try:project_stroke_style_errors as _project_stroke_style_errors,project_transform_errors as _project_transform_errors,rect_to_dml_xfrm as _rect_to_dml_xfrm,+ split_project_text_clusters as _split_project_text_clusters,transform_point as _transform_point,validate_dml_shape_matrix as _validate_dml_shape_matrix,)@@ -108,10 +110,11 @@ except ImportError:_OPACITY_PROPERTIES = None_PAINT_PROPERTIES = None_PERCENTAGE_OPACITY_PROPERTIES = None+ _detect_text_lang = None+ _estimate_text_cluster_widths = None_format_project_geometry_length = None_format_project_image_aspect_ratio = None_format_project_opacity = None- _estimate_text_width = None_font_px_to_hpt = None_is_canonical_project_geometry_length = None_is_project_opacity_default_form = None@@ -146,6 +149,7 @@ except ImportError:_project_stroke_style_errors = None_project_transform_errors = None_rect_to_dml_xfrm = None+ _split_project_text_clusters = None_transform_point = None_validate_dml_shape_matrix = None@@ -177,11 +181,13 @@ try:from svg_to_pptx.drawingml.elements import (drawingml_text_frame_width_emu as _drawingml_text_frame_width_emu,estimate_single_line_text_frame_width as _estimate_single_line_text_frame_width,+ validate_single_line_text_run_advances as _validate_single_line_text_run_advances,validate_preset_geometry_metadata as _validate_preset_geometry_metadata,)except ImportError:_drawingml_text_frame_width_emu = None_estimate_single_line_text_frame_width = None+ _validate_single_line_text_run_advances = None_validate_preset_geometry_metadata = Nonetry:@@ -2450,7 +2456,7 @@ class SVGQualityChecker:result['info']['text_elements'] = text_countresult['info']['tspan_elements'] = tspan_count- self._check_text_frame_extents(root, result)+ self._check_text_output_geometry(root, result)self._check_single_line_text_bounds(root, result)self._check_unmergeable_leading_text(root, result)@@ -2573,6 +2579,19 @@ class SVGQualityChecker:)or '')+ opacity_chain: List[str] = []+ current: ET.Element | None = owner+ while current is not None:+ style_values = (+ _parse_inline_style(current.get('style'))+ if _parse_inline_style is not None else {}+ )+ raw_opacity = style_values.get('opacity')+ if raw_opacity is None:+ raw_opacity = current.get('opacity')+ if raw_opacity is not None:+ opacity_chain.append(raw_opacity.strip())+ current = parent_by_id.get(id(current))resolved.append({'owner': owner,'text': text,@@ -2580,21 +2599,105 @@ class SVGQualityChecker:'font_weight': weight,'font_family': family,'letter_spacing': letter_spacings[id(owner)],+ 'font_style': _effective_presentation_value(+ owner,+ 'font-style',+ parent_by_id,+ ) or 'normal',+ 'text_decoration': _effective_presentation_value(+ owner,+ 'text-decoration',+ parent_by_id,+ ) or 'none',+ 'fill_raw': _effective_presentation_value(+ owner,+ 'fill',+ parent_by_id,+ ) or '#000000',+ 'fill_opacity': _effective_presentation_value(+ owner,+ 'fill-opacity',+ parent_by_id,+ ) or '1',+ 'stroke_raw': _effective_presentation_value(+ owner,+ 'stroke',+ parent_by_id,+ ) or 'none',+ 'stroke_width': _effective_presentation_value(+ owner,+ 'stroke-width',+ parent_by_id,+ ) or '1',+ 'stroke_opacity': _effective_presentation_value(+ owner,+ 'stroke-opacity',+ parent_by_id,+ ) or '1',+ 'opacity_chain': tuple(reversed(opacity_chain)),})- return resolved+ return cls._coalesce_checker_text_runs(resolved)- def _check_text_frame_extents(+ @staticmethod+ def _coalesce_checker_text_runs(runs: List[Dict]) -> List[Dict]:+ """Join only runs whose resolved source styles are provably equal."""+ if _detect_text_lang is None:+ return runs+ style_keys = (+ 'font_size',+ 'font_weight',+ 'font_family',+ 'letter_spacing',+ 'font_style',+ 'text_decoration',+ 'fill_raw',+ 'fill_opacity',+ 'stroke_raw',+ 'stroke_width',+ 'stroke_opacity',+ 'opacity_chain',+ )++ def signature(run: Dict) -> Tuple:+ return (+ _detect_text_lang(str(run.get('text', ''))),+ *(run.get(key) for key in style_keys),+ )++ merged: List[Dict] = []+ previous_signature: Tuple | None = None+ for run in runs:+ current_signature = signature(run)+ if merged and current_signature == previous_signature:+ candidate = {+ **merged[-1],+ 'text': (+ str(merged[-1].get('text', ''))+ + str(run.get('text', ''))+ ),+ }+ candidate_signature = signature(candidate)+ if candidate_signature == previous_signature:+ merged[-1] = candidate+ previous_signature = candidate_signature+ continue+ merged.append(run)+ previous_signature = current_signature+ return merged++ def _check_text_output_geometry(self,root: ET.Element,result: Dict,) -> None:- """Reject measurable generated text that would emit a non-positive cx."""+ """Reject measurable run advances or frames with non-positive geometry."""helpers = (_drawingml_text_frame_width_emu,_estimate_single_line_text_frame_width,_parse_project_font_weight,_resolve_project_font_sizes,_resolve_project_letter_spacings,+ _validate_single_line_text_run_advances,)if any(helper is None for helper in helpers):return@@ -2645,13 +2748,17 @@ class SVGQualityChecker:)except (KeyError, TypeError, ValueError):continue- if ext_cx >= 1:+ if ext_cx < 1:+ errors.append(+ f'{_element_label(text_el)} negative letter-spacing '+ 'produces a non-positive DrawingML text-frame extent '+ f'(cx={ext_cx})'+ )continue- errors.append(- f'{_element_label(text_el)} negative letter-spacing produces '- 'a non-positive DrawingML text-frame extent '- f'(cx={ext_cx})'- )+ try:+ _validate_single_line_text_run_advances(runs)+ except ValueError as exc:+ errors.append(f'{_element_label(text_el)} {exc}')result['errors'].extend(errors)def _check_single_line_text_bounds(@@ -2662,8 +2769,8 @@ class SVGQualityChecker:"""Warn only when an estimable single line exceeds the viewBox."""helpers = (_drawingml_text_frame_width_emu,+ _estimate_text_cluster_widths,_estimate_single_line_text_frame_width,- _estimate_text_width,_IDENTITY_MATRIX,_matrix_multiply,_parse_project_font_weight,@@ -2672,6 +2779,7 @@ class SVGQualityChecker:_parse_transform_matrix,_resolve_project_font_sizes,_resolve_project_letter_spacings,+ _split_project_text_clusters,_transform_point,)if any(helper is None for helper in helpers):@@ -2743,20 +2851,24 @@ class SVGQualityChecker:weight = str(run['font_weight'])font_size = float(run['font_size'])spacing = float(run['letter_spacing'])- for index, character in enumerate(text):- character_width = _estimate_text_width(- character,- font_size,- weight,- )- if not character.isspace():+ clusters = _split_project_text_clusters(text)+ cluster_widths = _estimate_text_cluster_widths(+ text,+ font_size,+ weight,+ )+ for index, (cluster, cluster_width) in enumerate(zip(+ clusters,+ cluster_widths,+ )):+ if not cluster.isspace():text_left = min(text_left, text_advance)text_right = max(text_right,- text_advance + character_width,+ text_advance + cluster_width,)- text_advance += character_width- if index < len(text) - 1:+ text_advance += cluster_width+ if index < len(clusters) - 1:text_advance += spacingexcept (KeyError, TypeError, ValueError):continuediff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.pyindex 9471d156..d1a260b4 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py@@ -45,8 +45,9 @@ from .utils import (rect_to_dml_xfrm,combine_opacity, parse_hex_color, parse_svg_color,resolve_url_id, get_effective_filter_id,- parse_inline_style, parse_font_family, is_cjk_char, estimate_text_width,- detect_text_lang, font_px_to_hpt, resolve_text_run_fonts,+ parse_inline_style, parse_font_family, is_cjk_char,+ detect_text_lang, estimate_text_cluster_widths, font_px_to_hpt,+ resolve_text_run_fonts, split_project_text_clusters,is_thick_circle_shorthand, parse_project_geometry_length,parse_project_image_aspect_ratio,parse_project_opacity,@@ -1693,15 +1694,44 @@ def _is_serif_run(run: dict[str, Any]) -> bool:def _estimate_run_text_width(run: dict[str, Any]) -> float:- """Estimate one text run's rendered width, including tracking."""+ """Estimate one run using the metrics actually emitted to DrawingML."""text = str(run.get('text', ''))- base_width = estimate_text_width(+ font_size_px = (+ font_px_to_hpt(float(run.get('font_size', 16)))+ / FONT_PX_TO_HUNDREDTHS_PT+ )+ cluster_widths = estimate_text_cluster_widths(text,- float(run.get('font_size', 16)),+ font_size_px,str(run.get('font_weight', '400')),)- letter_spacing_px = float(run.get('letter_spacing', 0.0) or 0.0)- return base_width + letter_spacing_px * max(len(text) - 1, 0)+ letter_spacing_px = (+ drawingml_letter_spacing(+ float(run.get('letter_spacing', 0.0) or 0.0)+ )+ / FONT_PX_TO_HUNDREDTHS_PT+ )+ return sum(cluster_widths) + letter_spacing_px * max(+ len(cluster_widths) - 1,+ 0,+ )+++def validate_text_run_advances(runs: list[dict[str, Any]]) -> None:+ """Reject negative tracking that reverses or collapses one output run."""+ for run in runs:+ text = str(run.get('text', ''))+ letter_spacing = float(run.get('letter_spacing', 0.0) or 0.0)+ if len(split_project_text_clusters(text)) < 2 or letter_spacing >= 0:+ continue+ advance = _estimate_run_text_width(run)+ if advance > 0:+ continue+ snippet = re.sub(r'\s+', ' ', text)+ raise ValueError(+ 'negative letter-spacing produces a non-positive DrawingML '+ f'text-run advance for {snippet!r} (advance={advance:g}px)'+ )def _uppercase_fraction(runs: list[dict[str, Any]]) -> float:@@ -1764,6 +1794,14 @@ def estimate_single_line_text_frame_width(return width+def validate_single_line_text_run_advances(+ runs: list[dict[str, Any]],+) -> None:+ """Validate the runs that remain after single-line bullet promotion."""+ content_runs, _bullet = _extract_text_bullet(runs)+ validate_text_run_advances(content_runs)++def _first_nonspace_run(runs: list[dict[str, Any]]) -> dict[str, Any] | None:for run in runs:if str(run.get('text', '')).strip():@@ -1900,8 +1938,13 @@ def _paragraph_pr_xml(return f'<a:pPr {attrs}>{body_xml}{_build_bullet_xml(bullet, ctx)}</a:pPr>'-def _estimate_bullet_line_width(runs: list[dict[str, Any]]) -> float:+def _estimate_bullet_line_width(+ runs: list[dict[str, Any]],+ default_fonts: dict[str, str],+ ctx: ConvertContext,+) -> float:line_runs, bullet = _extract_text_bullet(runs)+ line_runs = _coalesce_text_runs(line_runs, default_fonts, ctx)width = _estimate_text_runs_width(line_runs, include_headroom=False)if bullet:fs_px = float(line_runs[0].get('font_size', 16)) if line_runs else 16.0@@ -2149,14 +2192,14 @@ def _build_text_outline_xml()-def _build_run_xml(+def _build_run_properties_xml(run: dict[str, Any],default_fonts: dict[str, str],ctx: ConvertContext | None = None,effect_xml: str = '',) -> str:- """Build a single <a:r> XML from a run dict. Supports gradient fills on text."""- text = run['text']+ """Build the final ``a:rPr`` used to compare and emit one text run."""+ text = str(run['text'])fill = run.get('fill', '000000')fill_raw = run.get('fill_raw', '')fw = run.get('font_weight', '400')@@ -2192,17 +2235,66 @@ def _build_run_xml(fill_xml = _build_text_fill_xml(fill, fill_raw, opacity, ctx)outline_xml = _build_text_outline_xml(run, ctx)- space_attr = ' xml:space="preserve"' if text != text.strip() or ' ' in text else ''-- return f'''<a:r>-<a:rPr lang="{lang}" sz="{sz}"{b_attr}{i_attr}{u_attr}{strike_attr}{spc_attr} dirty="0">+ return f'''<a:rPr lang="{lang}" sz="{sz}"{b_attr}{i_attr}{u_attr}{strike_attr}{spc_attr} dirty="0">{outline_xml}{fill_xml}{effect_xml}<a:latin typeface="{_xml_escape(run_fonts['latin'])}"/><a:ea typeface="{_xml_escape(run_fonts['ea'])}"/><a:cs typeface="{_xml_escape(run_fonts['cs'])}"/>-</a:rPr>+</a:rPr>'''+++def _coalesce_text_runs(+ runs: list[dict[str, Any]],+ default_fonts: dict[str, str],+ ctx: ConvertContext | None,+) -> list[dict[str, Any]]:+ """Join adjacent runs that PowerPoint sees as one formatting run."""+ merged: list[dict[str, Any]] = []+ previous_properties: str | None = None+ for run in runs:+ text = str(run.get('text', ''))+ if not text:+ continue+ properties = _build_run_properties_xml(run, default_fonts, ctx)+ if merged and properties == previous_properties:+ candidate = {+ **merged[-1],+ 'text': str(merged[-1].get('text', '')) + text,+ }+ candidate_properties = _build_run_properties_xml(+ candidate,+ default_fonts,+ ctx,+ )+ if candidate_properties == previous_properties:+ merged[-1] = candidate+ previous_properties = candidate_properties+ continue+ merged.append({**run, 'text': text})+ previous_properties = properties+ return merged+++def _build_run_xml(+ run: dict[str, Any],+ default_fonts: dict[str, str],+ ctx: ConvertContext | None = None,+ effect_xml: str = '',+) -> str:+ """Build a single <a:r> XML from a run dict. Supports gradient fills on text."""+ text = str(run['text'])+ properties_xml = _build_run_properties_xml(+ run,+ default_fonts,+ ctx,+ effect_xml,+ )+ space_attr = ' xml:space="preserve"' if text != text.strip() or ' ' in text else ''++ return f'''<a:r>+{properties_xml}<a:t{space_attr}>{_xml_escape(text)}</a:t></a:r>'''@@ -2314,7 +2406,9 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None: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))+ visual_line_widths.append(+ _estimate_bullet_line_width(line_runs, fonts, ctx)+ )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@@ -2331,7 +2425,11 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:if prev and not prev_text.endswith(' ') \and not next_text.startswith(' ') \and not boundary_is_cjk:- prev[-1] = {**prev[-1], 'text': prev_text + ' '}+ prev.append({+ **prev[-1],+ 'text': ' ',+ 'letter_spacing': 0.0,+ })prev.extend(line_runs)else:paragraph_runs.append(line_runs)@@ -2345,7 +2443,9 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:stripped_paragraphs: list[list[dict[str, Any]]] = []for line_runs in paragraph_runs:stripped_runs, bullet = _extract_text_bullet(line_runs)- stripped_paragraphs.append(stripped_runs)+ stripped_paragraphs.append(+ _coalesce_text_runs(stripped_runs, fonts, ctx)+ )paragraph_bullets.append(bullet)paragraph_runs = stripped_paragraphs@@ -2354,6 +2454,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:else:runs = _build_text_runs(elem, parent_attrs, ctx)runs, single_bullet = _extract_text_bullet(runs)+ runs = _coalesce_text_runs(runs, fonts, ctx)full_text = ''.join(r['text'] for r in runs) if runs else ''if not full_text.strip():@@ -2529,6 +2630,7 @@ def convert_text(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:f'text-frame extent (cx={ext_cx}, cy={ext_cy})')validate_ooxml_xfrm(off_x, off_y, ext_cx, ext_cy)+ validate_text_run_advances(runs)# Paragraph mode: wrap="square" so text reflows when the user resizes,# but NO spAutoFit — otherwise PowerPoint expands the frame to fit adiff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.pyindex 6db05676..90a58237 100644--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py@@ -9,6 +9,7 @@ from __future__ import annotationsimport colorsysimport mathimport re+import unicodedatafrom collections import Counterfrom collections.abc import Iteratorfrom xml.etree import ElementTree as ET@@ -2149,6 +2150,123 @@ def detect_text_lang(text: str) -> str:return 'zh-CN' if any(is_cjk_char(ch) for ch in text) else 'en-US'+def _is_grapheme_extend(ch: str) -> bool:+ """Return whether ``ch`` extends the preceding rendered character."""+ cp = ord(ch)+ return (+ unicodedata.category(ch) in {'Mn', 'Mc', 'Me'}+ or 0xFE00 <= cp <= 0xFE0F+ or 0xE0100 <= cp <= 0xE01EF+ or 0x1F3FB <= cp <= 0x1F3FF+ or 0xE0020 <= cp <= 0xE007F+ )+++def _is_regional_indicator(ch: str) -> bool:+ return 0x1F1E6 <= ord(ch) <= 0x1F1FF+++def _is_virama(ch: str) -> bool:+ name = unicodedata.name(ch, '')+ return (+ unicodedata.combining(ch) == 9+ or 'VIRAMA' in name+ or name.endswith(' SIGN HALANT')+ )+++def _is_emoji_base(ch: str) -> bool:+ cp = ord(ch)+ return 0x2600 <= cp <= 0x27BF or 0x1F000 <= cp <= 0x1FAFF+++def _unicode_script_key(ch: str) -> str | None:+ """Return the stable Unicode-name prefix used for project script joins."""+ name = unicodedata.name(ch, '')+ if not name:+ return None+ tokens = name.split()+ boundary_tokens = {+ 'CONSONANT',+ 'LETTER',+ 'SIGN',+ 'SYLLABLE',+ 'VOWEL',+ }+ for index, token in enumerate(tokens):+ if index > 0 and token in boundary_tokens:+ return ' '.join(tokens[:index])+ if tokens[0] in {'MEETEI', 'OL', 'TAI'} and len(tokens) > 1:+ return ' '.join(tokens[:2])+ return tokens[0]+++def _virama_script_key(cluster: str, virama: str) -> str | None:+ virama_script = _unicode_script_key(virama)+ for ch in reversed(cluster):+ if not unicodedata.category(ch).startswith('L'):+ continue+ base_script = _unicode_script_key(ch)+ return base_script if base_script == virama_script else None+ return None+++def split_project_text_clusters(text: str) -> list[str]:+ """Split text into the rendered units used by project width estimates.++ This intentionally implements only the Unicode joins that affect SVG to+ DrawingML tracking: combining marks, variation selectors, emoji modifiers,+ ZWJ sequences, regional-indicator pairs, and common virama conjuncts.+ """+ clusters: list[str] = []+ virama_script: str | None = None+ emoji_join = False+ for ch in text:+ if not clusters:+ clusters.append(ch)+ continue++ cluster = clusters[-1]+ previous = cluster[-1]+ if ch == '\n' and previous == '\r':+ clusters[-1] += ch+ virama_script = None+ emoji_join = False+ elif _is_grapheme_extend(ch):+ if _is_virama(ch):+ virama_script = _virama_script_key(cluster, ch)+ clusters[-1] += ch+ elif ch == '\u200d':+ clusters[-1] += ch+ emoji_join = any(_is_emoji_base(item) for item in cluster)+ elif ch == '\u200c':+ clusters[-1] += ch+ virama_script = None+ emoji_join = False+ elif (+ virama_script is not None+ and unicodedata.category(ch).startswith('L')+ and _unicode_script_key(ch) == virama_script+ ):+ clusters[-1] += ch+ virama_script = None+ emoji_join = False+ elif emoji_join and _is_emoji_base(ch):+ clusters[-1] += ch+ emoji_join = False+ elif (+ len(cluster) == 1+ and _is_regional_indicator(cluster)+ and _is_regional_indicator(ch)+ ):+ clusters[-1] += ch+ else:+ clusters.append(ch)+ virama_script = None+ emoji_join = False+ return clusters++def resolve_text_run_fonts(text: str, fonts: dict[str, str]) -> dict[str, str]:"""Return DrawingML latin/ea/cs typefaces for one text run."""latin = fonts['latin']@@ -2159,30 +2277,56 @@ def resolve_text_run_fonts(text: str, fonts: dict[str, str]) -> dict[str, str]:return {'latin': latin, 'ea': ea, 'cs': latin}-def estimate_text_width(text: str, font_size: float, font_weight: str = '400') -> float:- """Estimate text width in SVG pixels."""- width = 0.0- for ch in text:- if is_cjk_char(ch):- width += font_size- elif ch == ' ':- width += font_size * 0.3- elif ch in 'mMwWOQ%':- width += font_size * 0.75- elif ch in 'iIlj!|':- width += font_size * 0.3- elif ch.isdigit():- # digits are tabular (uniform ~0.55em) in most UI fonts, including- # '1' — classing it with 'il|' under-sizes the box and makes- # renderers that ignore wrap="none" (LibreOffice) wrap the line- width += font_size * 0.55- else:- width += font_size * 0.55-+def _estimate_character_width(ch: str, font_size: float) -> float:+ if is_cjk_char(ch):+ return font_size+ if ch == ' ':+ return font_size * 0.3+ if ch in 'mMwWOQ%':+ return font_size * 0.75+ if ch in 'iIlj!|':+ return font_size * 0.3+ if ch.isdigit():+ # digits are tabular (uniform ~0.55em) in most UI fonts, including+ # '1' — classing it with 'il|' under-sizes the box and makes+ # renderers that ignore wrap="none" (LibreOffice) wrap the line+ return font_size * 0.55+ return font_size * 0.55+++def _estimate_grapheme_width(cluster: str, font_size: float) -> float:+ bases = [+ ch for ch in cluster+ if ch not in {'\u200c', '\u200d'} and not _is_grapheme_extend(ch)+ ]+ if not bases:+ return font_size * 0.55+ if (+ len(bases) > 1+ and all(_is_regional_indicator(ch) for ch in bases)+ ) or '\u20e3' in cluster or any(_is_emoji_base(ch) for ch in bases):+ return font_size+ return max(_estimate_character_width(ch, font_size) for ch in bases)+++def estimate_text_cluster_widths(+ text: str,+ font_size: float,+ font_weight: str = '400',+) -> list[float]:+ """Estimate each project text cluster without inserting tracking."""+ widths = [+ _estimate_grapheme_width(cluster, font_size)+ for cluster in split_project_text_clusters(text)+ ]if font_weight in ('bold', '600', '700', '800', '900'):- width *= 1.05+ widths = [width * 1.05 for width in widths]+ return widths+- return width+def estimate_text_width(text: str, font_size: float, font_weight: str = '400') -> float:+ """Estimate text width in SVG pixels."""+ return sum(estimate_text_cluster_widths(text, font_size, font_weight))def _xml_escape(text: str) -> str:diff --git a/skills/ppt-master/scripts/test_svg_quality_checker.py b/skills/ppt-master/scripts/test_svg_quality_checker.pyindex 56e2b91c..9d07cacf 100644--- a/skills/ppt-master/scripts/test_svg_quality_checker.py+++ b/skills/ppt-master/scripts/test_svg_quality_checker.py@@ -32,7 +32,11 @@ from svg_to_pptx.drawingml.converter import (SvgNativeConversionError,convert_svg_to_slide_shapes,)-from svg_to_pptx.drawingml.utils import parse_inline_style+from svg_to_pptx.drawingml.utils import (+ estimate_text_width,+ parse_inline_style,+ split_project_text_clusters,+)from svg_to_pptx.native_objects import (NativeMarkerAttributeError,native_fallback_kind,@@ -1521,8 +1525,8 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):self._assert_checker_and_exporter_reject('''<svg xmlns="http://www.w3.org/2000/svg"viewBox="0 0 640 360">- <text x="40" y="100" font-size="20"- letter-spacing="-23.4285714285714">AB</text>+ <text x="40" y="100" font-size="19.9733333333333"+ letter-spacing="-23.4266666666667">AB</text></svg>''','non-positive DrawingML text-frame extent (cx=0)',r'non-positive DrawingML text-frame extent \(cx=0',@@ -1553,6 +1557,175 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):self.assertEqual(len(extents), 2)self.assertTrue(all(value >= 1 for value in extents))+ def test_non_positive_inline_run_advance_blocks_checker_and_exporter(self):+ self._assert_checker_and_exporter_reject(+ '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="20">+ <text x="40" y="100">CONTROL PREFIX <tspan+ letter-spacing="-100">AB</tspan></text>+</svg>''',+ 'non-positive DrawingML text-run advance',+ 'non-positive DrawingML text-run advance',+ )++ def test_equivalent_inline_runs_cannot_bypass_tracking_validation(self):+ self._assert_checker_and_exporter_reject(+ '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="20">+ <text x="40" y="100">CONTROL PREFIX <tspan+ letter-spacing="-100">A</tspan><tspan+ letter-spacing="-100">B</tspan></text>+</svg>''',+ 'non-positive DrawingML text-run advance',+ 'non-positive DrawingML text-run advance',+ )++ def test_equivalent_inline_runs_are_emitted_as_one_drawingml_run(self):+ equivalent_sources = (+ 'A<tspan>B</tspan>',+ '<tspan font-family="Helvetica">A</tspan>'+ '<tspan font-family="Arial">B</tspan>',+ '<tspan font-size="20">A</tspan>'+ '<tspan font-size="20.01">B</tspan>',+ )+ for inline_text in equivalent_sources:+ with self.subTest(inline_text=inline_text):+ source = (+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 640 360">'+ '<text x="40" y="100" font-size="20" '+ f'letter-spacing="2">{inline_text}</text></svg>'+ )+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'coalesced-runs.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count('<a:r>'), 1)+ self.assertIn('<a:t>AB</a:t>', slide_xml)++ def test_distinct_output_run_properties_remain_separate(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="20" letter-spacing="-100">+ <text x="40" y="100"><tspan fill="#FF0000">A</tspan><tspan+ fill="#0000FF">B</tspan><tspan fill="#0000FF">中</tspan></text>+</svg>'''+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'distinct-runs.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count('<a:r>'), 3)+ self.assertIn('<a:rPr lang="en-US"', slide_xml)+ self.assertIn('<a:rPr lang="zh-CN"', slide_xml)++ def test_project_text_clusters_match_rendered_tracking_units(self):+ self.assertEqual(split_project_text_clusters('e\u0301'), ['e\u0301'])+ self.assertEqual(split_project_text_clusters('中\ufe00'), ['中\ufe00'])+ self.assertEqual(split_project_text_clusters('✊🏽'), ['✊🏽'])+ self.assertEqual(split_project_text_clusters('👨\u200d👩\u200d👧\u200d👦'), [+ '👨\u200d👩\u200d👧\u200d👦',+ ])+ self.assertEqual(split_project_text_clusters('🇨🇳🇺🇸🇫'), ['🇨🇳', '🇺🇸', '🇫'])+ self.assertEqual(split_project_text_clusters('क्ष'), ['क्ष'])+ self.assertEqual(split_project_text_clusters('A\u200dB'), ['A\u200d', 'B'])+ self.assertEqual(split_project_text_clusters('A्B'), ['A्', 'B'])+ self.assertEqual(split_project_text_clusters('क्A'), ['क्', 'A'])+ self.assertEqual(split_project_text_clusters('क्中'), ['क्', '中'])+ self.assertEqual(split_project_text_clusters('ᨠ᩠ᨡ'), ['ᨠ᩠ᨡ'])+ self.assertEqual(split_project_text_clusters('ᨠ᩠ꪀ'), ['ᨠ᩠', 'ꪀ'])+ self.assertEqual(+ estimate_text_width('e\u0301', 80),+ estimate_text_width('é', 80),+ )++ def test_single_graphemes_do_not_receive_internal_tracking(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="80" letter-spacing="-88">+ <text x="40" y="100">é</text>+ <text x="40" y="220">🇨🇳</text>+</svg>'''+ result = self._check(source)+ self.assertTrue(result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'single-graphemes.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count(' spc="-6600"'), 2)++ def test_virama_does_not_join_text_across_unicode_scripts(self):+ self._assert_checker_and_exporter_reject(+ '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="80" letter-spacing="-100">+ <text x="40" y="100">A्B</text>+</svg>''',+ 'non-positive DrawingML',+ 'non-positive DrawingML',+ )++ def test_soft_break_joining_space_does_not_inherit_negative_tracking(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="20" letter-spacing="-21">+ <text x="40" y="80" data-paragraph-line-height="24">+ <tspan x="40">AB</tspan>+ <tspan x="40" dy="24" data-paragraph-soft-break="1">CD</tspan>+ </text>+</svg>'''+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'soft-break.svg'+ svg_path.write_text(source, encoding='utf-8')+ slide_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertEqual(slide_xml.count('<a:p>'), 1)+ self.assertEqual(slide_xml.count('<a:r>'), 3)+ self.assertEqual(slide_xml.count(' spc="-1575"'), 2)+ self.assertIn('<a:t xml:space="preserve"> </a:t>', slide_xml)++ def test_zero_text_run_advance_is_rejected_without_narrowing_safe_tracking(self):+ invalid_metrics = (+ ('20', '-22'),+ ('20', '-21.999999'),+ ('20.01', '-22'),+ )+ for font_size, letter_spacing in invalid_metrics:+ with self.subTest(+ font_size=font_size,+ letter_spacing=letter_spacing,+ ):+ self._assert_checker_and_exporter_reject(+ '<svg xmlns="http://www.w3.org/2000/svg" '+ 'viewBox="0 0 640 360">'+ f'<text x="40" y="100" font-size="{font_size}" '+ f'letter-spacing="{letter_spacing}">AB</text></svg>',+ "non-positive DrawingML text-run advance for 'AB' "+ '(advance=0px)',+ r"non-positive DrawingML text-run advance for 'AB' "+ r"\(advance=0px\)",+ )++ safe = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360">+ <text x="40" y="100" font-size="20" letter-spacing="-21">AB</text>+</svg>'''+ safe_result = self._check(safe)+ self.assertTrue(safe_result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'positive-run-advance.svg'+ svg_path.write_text(safe, encoding='utf-8')+ safe_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertIn(' spc="-1575"', safe_xml)++ quantized_safe = safe.replace(+ 'letter-spacing="-21"',+ 'letter-spacing="-21.993"',+ )+ quantized_result = self._check(quantized_safe)+ self.assertTrue(quantized_result['passed'])+ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'quantized-positive-run-advance.svg'+ svg_path.write_text(quantized_safe, encoding='utf-8')+ quantized_xml = convert_svg_to_slide_shapes(svg_path)[0]+ self.assertIn(' spc="-1649"', quantized_xml)+def test_inherited_inline_tracking_cannot_hide_collapsed_text_frame(self):self._assert_checker_and_exporter_reject('''<svg xmlns="http://www.w3.org/2000/svg"@@ -1568,8 +1741,8 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):def test_positioned_paragraph_tracking_is_still_blocked_by_exporter(self):source = '''<svg xmlns="http://www.w3.org/2000/svg"viewBox="0 0 640 360" font-size="20" letter-spacing="-30">- <text x="40" y="80">- <tspan x="40" y="80">AB</tspan>+ <text x="40" y="80" data-paragraph-line-height="24">+ <tspan x="40">AB</tspan><tspan x="40" dy="24">AB</tspan></text></svg>'''@@ -1585,6 +1758,37 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):):convert_svg_to_slide_shapes(svg_path)+ def test_bad_paragraph_run_cannot_hide_behind_a_wider_line(self):+ source = '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="20">+ <text x="40" y="80" data-paragraph-line-height="24">+ <tspan x="40">HEALTHY PARAGRAPH LINE</tspan>+ <tspan x="40" dy="24" letter-spacing="-100">AB</tspan>+ </text>+</svg>'''+ result = self._check(source)+ self.assertTrue(result['passed'])++ with tempfile.TemporaryDirectory() as tmp_dir:+ svg_path = Path(tmp_dir) / 'mixed-paragraph-tracking.svg'+ svg_path.write_text(source, encoding='utf-8')+ with self.assertRaisesRegex(+ SvgNativeConversionError,+ 'non-positive DrawingML text-run advance',+ ):+ convert_svg_to_slide_shapes(svg_path)++ def test_bad_bullet_run_cannot_hide_behind_normal_text(self):+ self._assert_checker_and_exporter_reject(+ '''<svg xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 640 360" font-size="20">+ <text x="40" y="100">• HEALTHY PREFIX <tspan+ letter-spacing="-100">AB</tspan></text>+</svg>''',+ 'non-positive DrawingML text-run advance',+ 'non-positive DrawingML text-run advance',+ )+def test_bullet_text_uses_the_same_positive_frame_boundary(self):safe = '''<svg xmlns="http://www.w3.org/2000/svg"viewBox="0 0 640 360">@@ -1646,7 +1850,7 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):metadata.text = self._native_txbody_payload()result = {'errors': [], 'warnings': []}- SVGQualityChecker()._check_text_frame_extents(root, result)+ SVGQualityChecker()._check_text_output_geometry(root, result)self.assertEqual(result['errors'], [])@@ -1684,7 +1888,7 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):metadata.text = 'not-base64'result = {'errors': [], 'warnings': []}- SVGQualityChecker()._check_text_frame_extents(root, result)+ SVGQualityChecker()._check_text_output_geometry(root, result)self.assertIn('invalid preserved txBody metadata', '\n'.join(result['errors']))@@ -1705,7 +1909,7 @@ class SVGQualityCheckerCompatibilityTests(unittest.TestCase):metadata.text = self._native_txbody_payload()result = {'errors': [], 'warnings': []}- SVGQualityChecker()._check_text_frame_extents(root, result)+ SVGQualityChecker()._check_text_output_geometry(root, result)self.assertIn('non-positive DrawingML text-frame extent',