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

fix(pptx): merge leading text paragraphs

hugohe3171c8182ed1f
diff --git a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
index 43ce18f7..1561d7f2 100644
--- a/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
+++ b/skills/ppt-master/scripts/svg_finalize/flatten_tspan.py
@@ -210,16 +210,58 @@ def _tspan_has_positional_descendant(tspan: ET.Element) -> bool:
return False
+def _build_paragraph_child_view(
+ text_el: ET.Element,
+ is_svg_tag,
+) -> tuple[list[ET.Element], ET.Element | None] | None:
+ """Return direct tspan children plus an optional synthetic leading line.
+
+ The synthetic line lets paragraph classification accept common SVG
+ authoring where the first visual line is direct text under <text>. This
+ helper does not mutate the tree; _emit_mergeable_paragraph commits the
+ synthetic line only after all paragraph checks pass.
+ """
+ direct_children = list(text_el)
+ direct_tspans = [c for c in direct_children if is_svg_tag(c, "tspan")]
+ if len(direct_tspans) != len(direct_children):
+ return None
+
+ raw_lead = text_el.text or ""
+ synthetic_first: ET.Element | None = None
+ if raw_lead.strip():
+ base_x_raw = get_attr(text_el, "x")
+ if base_x_raw is None:
+ return None
+ if any((child.tail or "").strip() for child in direct_tspans):
+ return None
+ synthetic_first = ET.Element(f"{{{SVG_NS}}}tspan")
+ synthetic_first.set("x", base_x_raw)
+ synthetic_first.text = raw_lead.lstrip()
+
+ view = ([synthetic_first] if synthetic_first is not None else []) + direct_tspans
+ return view, synthetic_first
+
+
+def _get_font_size_px(elem: ET.Element) -> float | None:
+ """Read font-size from an attribute or inline style."""
+ size = parse_first_number(get_attr(elem, "font-size"))
+ if size is not None:
+ return size
+ style_size = parse_style(get_attr(elem, "style")).get("font-size")
+ return parse_first_number(style_size)
+
+
def _classify_paragraph_block(
text_el: ET.Element,
is_svg_tag,
is_new_line_tspan,
-) -> tuple[float, list[float], list[bool], list[list[ET.Element]]] | None:
+) -> tuple[float, list[float], list[bool], list[list[ET.Element]], ET.Element | None] | None:
"""Detect a mergeable paragraph block.
Returns ``(base_line_height_px, extra_space_before_px_per_line,
- is_soft_break_per_line, line_groups)`` if the children form a mergeable paragraph.
- Each list has one entry per direct-child tspan (line):
+ is_soft_break_per_line, line_groups, synthetic_first_line)`` if the children
+ form a mergeable paragraph. Each list has one entry per direct-child tspan
+ (line), including a synthetic first line when the source used leading text:
- extra_space_before_px_per_line[i]: extra px above base line-height,
used as <a:spcBef> on the downstream <a:p>. First entry is 0.
@@ -228,7 +270,8 @@ def _classify_paragraph_block(
a fresh <a:p>. First entry is always False (paragraph head).
Conditions (all must hold):
- - No leading text directly under <text>.
+ - No direct text under <text>, except simple leading text that can be
+ promoted into a synthetic first-line <tspan>.
- Every direct child is a <tspan>.
- Every logical line starts with a new-line tspan.
- Direct-child inline formatting tspans without x/y/dy are allowed only
@@ -242,15 +285,13 @@ def _classify_paragraph_block(
- No nested tspan inside any line carries x/y/dy.
"""
base_x = parse_first_number(get_attr(text_el, "x"))
- if (text_el.text or "").strip():
+ child_view = _build_paragraph_child_view(text_el, is_svg_tag)
+ if child_view is None:
return None
+ direct_tspans, synthetic_first = child_view
- direct_tspans = [c for c in list(text_el) if is_svg_tag(c, "tspan")]
- direct_children_all = [c for c in list(text_el)]
if len(direct_tspans) < 2:
return None
- if len(direct_tspans) != len(direct_children_all):
- return None
line_groups: list[list[ET.Element]] = []
for tspan in direct_tspans:
@@ -302,6 +343,9 @@ def _classify_paragraph_block(
if not positive_dys:
return None
base = min(positive_dys)
+ font_size = _get_font_size_px(text_el)
+ if font_size is not None and base > font_size * MAX_DY_MULTIPLIER + DY_TOLERANCE_PX:
+ return None
extras: list[float] = [0.0] # first line never has space-before
soft_breaks: list[bool] = [False] # first line starts a paragraph
@@ -324,7 +368,7 @@ def _classify_paragraph_block(
extras.append(0.0 if is_soft else extra)
soft_breaks.append(is_soft)
- return base, extras, soft_breaks, line_groups
+ return base, extras, soft_breaks, line_groups, synthetic_first
def _emit_mergeable_paragraph(
@@ -333,6 +377,7 @@ def _emit_mergeable_paragraph(
extras: list[float],
soft_breaks: list[bool],
line_groups: list[list[ET.Element]],
+ synthetic_first: ET.Element | None = None,
) -> None:
"""Rewrite text_el in place so it stays a single <text> with paragraph rows.
@@ -345,6 +390,9 @@ def _emit_mergeable_paragraph(
with an extra gap (omitted when 0)
"""
text_el.set(PARAGRAPH_MARK_ATTR, format_number(base_dy))
+ if synthetic_first is not None:
+ text_el.text = None
+ text_el.insert(0, synthetic_first)
# Normalize authoring variants before the downstream converter reads the
# paragraph: a line-break tspan may be followed by direct-child inline
@@ -457,8 +505,15 @@ def flatten_text_with_tspans(
if merge_paragraphs:
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 = paragraph
- _emit_mergeable_paragraph(text_el, base_dy, extras, soft_breaks, line_groups)
+ base_dy, extras, soft_breaks, line_groups, synthetic_first = paragraph
+ _emit_mergeable_paragraph(
+ text_el,
+ base_dy,
+ extras,
+ soft_breaks,
+ line_groups,
+ synthetic_first=synthetic_first,
+ )
changed = True
continue
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 8771ba2a..51b57735 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -573,6 +573,66 @@ class SVGQualityChecker:
f"Detected {len(text_matches)} potentially overly long single-line text(s) (consider using tspan for wrapping)"
)
+ self._check_unmergeable_leading_text(content, result)
+
+ def _check_unmergeable_leading_text(self, content: str, result: Dict) -> None:
+ """Warn when leading text cannot be normalized for paragraph merging."""
+ try:
+ root = ET.fromstring(content)
+ except ET.ParseError:
+ return
+
+ risky = []
+ for text_el in root.iter(f'{{{SVG_NS}}}text'):
+ if not (text_el.text or "").strip():
+ continue
+ children = list(text_el)
+ if not any(self._is_line_tspan(child) for child in children):
+ continue
+
+ reason = self._leading_text_normalizer_reject_reason(text_el)
+ if reason is not None:
+ risky.append(reason)
+
+ if risky:
+ sample = '; '.join(risky[:3])
+ suffix = '' if len(risky) <= 3 else f"; +{len(risky) - 3} more"
+ result['warnings'].append(
+ "Detected multi-line <text> with leading direct text that cannot "
+ f"be normalized for PPT paragraph merging ({sample}{suffix})"
+ )
+
+ @staticmethod
+ def _is_tspan(elem: ET.Element) -> bool:
+ return elem.tag == f'{{{SVG_NS}}}tspan'
+
+ @classmethod
+ def _is_line_tspan(cls, elem: ET.Element) -> bool:
+ if not cls._is_tspan(elem):
+ return False
+ if elem.get('x') is not None or elem.get('y') is not None:
+ return True
+ dy = elem.get('dy')
+ if dy is None:
+ return False
+ try:
+ return float(re.match(r'^[\s,]*([+-]?(?:\d+\.?\d*|\d*\.\d+))', dy).group(1)) != 0
+ except (AttributeError, ValueError):
+ return True
+
+ @classmethod
+ def _leading_text_normalizer_reject_reason(cls, text_el: ET.Element) -> str | None:
+ if text_el.get('x') is None:
+ return '<text> has no x anchor'
+
+ for child in list(text_el):
+ if not cls._is_tspan(child):
+ return '<text> has non-tspan child'
+ if (child.tail or "").strip():
+ return '<tspan> has non-empty tail text'
+
+ return None
+
def _check_image_references(self, content: str, svg_path: Path, result: Dict):
"""Check image file existence and resolution vs display size."""
# Find all <image ...> elements (capture the full tag)