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(svg-to-pptx): preserve CSS color alpha

hugohe33a5cf0e96bf6
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 1da17327..f7f53565 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -22,7 +22,8 @@ from .utils import (
svg_length_x, svg_length_y, svg_length_size,
ctx_x, ctx_y, ctx_w, ctx_h,
rect_to_dml_xfrm,
- parse_hex_color, resolve_url_id, get_effective_filter_id,
+ 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, resolve_text_run_fonts,
matrix_multiply, parse_transform_matrix, transform_point, _xml_escape,
@@ -557,7 +558,7 @@ def convert_circle(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
# Use the stroke color/gradient as fill for the arc shape
stroke_val = _get_attr(elem, 'stroke', ctx)
- op = get_fill_opacity(elem, ctx)
+ op = get_stroke_opacity(elem, ctx)
grad_id = resolve_url_id(stroke_val) if stroke_val else None
if grad_id and grad_id in ctx.defs:
fill = build_gradient_fill(
@@ -567,9 +568,14 @@ def convert_circle(elem: ET.Element, ctx: ConvertContext) -> ShapeResult | None:
"fill",
)
elif stroke_val:
- color = parse_hex_color(stroke_val)
+ color, color_alpha = parse_svg_color(stroke_val)
fill = (
- build_solid_fill(color, op, ctx.theme_color_spec, "fill")
+ build_solid_fill(
+ color,
+ combine_opacity(op, color_alpha),
+ ctx.theme_color_spec,
+ "fill",
+ )
if color else '<a:noFill/>'
)
else:
@@ -1210,6 +1216,8 @@ def _extract_text_bullet(
bullet = {
'char': _TEXT_BULLET_MARKERS.get(marker, marker),
'fill': marker_run.get('fill'),
+ 'fill_raw': marker_run.get('fill_raw'),
+ 'opacity': marker_run.get('opacity'),
'source_prefix_width_px': _estimate_text_runs_width(prefix_runs, include_headroom=False),
'margin_px': max(
_estimate_text_runs_width(replacement_runs, include_headroom=False),
@@ -1238,10 +1246,21 @@ def _build_bullet_xml(
if not bullet:
return ''
fill = bullet.get('fill')
- if isinstance(fill, str) and re.fullmatch(r'[0-9A-Fa-f]{6}', fill):
+ fill_raw = bullet.get('fill_raw')
+ color, color_alpha = parse_svg_color(
+ fill_raw if isinstance(fill_raw, str) else ''
+ )
+ if color is None and isinstance(fill, str):
+ color = parse_hex_color(fill)
+ if color:
+ opacity = combine_opacity(bullet.get('opacity'), color_alpha)
+ alpha_xml = (
+ f'<a:alphaMod val="{int(opacity * 100000)}"/>'
+ if opacity is not None else ''
+ )
theme_spec = ctx.theme_color_spec if ctx is not None else None
color_xml = (
- f'<a:buClr>{color_node_xml(fill, theme_spec, "text")}</a:buClr>'
+ f'<a:buClr>{color_node_xml(color, theme_spec, "text", alpha_xml)}</a:buClr>'
)
else:
color_xml = '<a:buClrTx/>'
@@ -1449,8 +1468,11 @@ def _build_text_fill_xml(
"text",
)
+ parsed_color, color_alpha = parse_svg_color(fill_raw)
+ fill = parsed_color or fill
+ opacity = combine_opacity(opacity, color_alpha)
alpha_xml = ''
- if opacity is not None and opacity < 1.0:
+ if opacity is not None:
alpha_xml = f'<a:alphaMod val="{int(opacity * 100000)}"/>'
theme_spec = ctx.theme_color_spec if ctx is not None else None
return (
@@ -1469,14 +1491,14 @@ def _build_text_outline_xml(
if not stroke_raw or stroke_raw.strip().lower() in ('none', 'transparent'):
return ''
- color = parse_hex_color(stroke_raw)
+ color, color_alpha = parse_svg_color(stroke_raw)
if not color:
return ''
stroke_width = _f(str(run.get('stroke_width', 1.0)), 1.0)
- stroke_opacity = run.get('stroke_opacity')
+ stroke_opacity = combine_opacity(run.get('stroke_opacity'), color_alpha)
alpha_xml = ''
- if stroke_opacity is not None and stroke_opacity < 1.0:
+ if stroke_opacity is not None:
alpha_xml = f'<a:alphaMod val="{int(stroke_opacity * 100000)}"/>'
theme_spec = ctx.theme_color_spec if ctx is not None else None
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
index 556aa2bc..62a19adc 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/styles.py
@@ -11,7 +11,8 @@ from .theme_colors import ThemeColorSpec, color_node_xml
from .utils import (
SVG_NS, ANGLE_UNIT, DASH_PRESETS,
px_to_emu, _f, _get_attr, parse_svg_length,
- parse_hex_color, parse_inline_style, parse_stop_style, resolve_url_id,
+ combine_opacity, parse_inline_style, parse_opacity, parse_stop_style,
+ parse_svg_color, resolve_url_id,
)
@@ -58,24 +59,21 @@ def build_gradient_fill(
# Parse color from style attribute or direct attributes
style = child.get('style', '')
+ style_values = parse_inline_style(style)
color, stop_opacity = parse_stop_style(style)
if not color:
- color = parse_hex_color(child.get('stop-color', '#000000'))
+ color, color_alpha = parse_svg_color(child.get('stop-color', '#000000'))
+ stop_opacity *= color_alpha
if color is None:
color = '000000'
direct_stop_op = child.get('stop-opacity')
- if direct_stop_op is not None:
- try:
- stop_opacity = float(direct_stop_op)
- except ValueError:
- pass
+ if direct_stop_op is not None and 'stop-opacity' not in style_values:
+ stop_opacity *= parse_opacity(direct_stop_op)
alpha_xml = ''
- effective_opacity = stop_opacity
- if opacity is not None:
- effective_opacity *= opacity
- if effective_opacity < 1.0:
+ effective_opacity = combine_opacity(stop_opacity, opacity)
+ if effective_opacity is not None:
alpha_xml = f'<a:alpha val="{int(effective_opacity * 100000)}"/>'
stops_xml.append(
@@ -157,9 +155,14 @@ def build_fill_xml(
usage,
)
- color = parse_hex_color(fill)
+ color, color_alpha = parse_svg_color(fill)
if color:
- return build_solid_fill(color, opacity, ctx.theme_color_spec, usage)
+ return build_solid_fill(
+ color,
+ combine_opacity(opacity, color_alpha),
+ ctx.theme_color_spec,
+ usage,
+ )
return '<a:noFill/>'
@@ -190,20 +193,27 @@ def build_pattern_fill(
elif tag == 'path' and not fg_color:
fg_color = child.get('stroke')
- fg_hex = parse_hex_color(fg_color) if fg_color else None
- bg_hex = parse_hex_color(bg_color) if bg_color else None
+ fg_hex, fg_alpha = parse_svg_color(fg_color) if fg_color else (None, 1.0)
+ bg_hex, bg_alpha = parse_svg_color(bg_color) if bg_color else (None, 1.0)
if not fg_hex:
return ''
- alpha_xml = ''
- if opacity is not None and opacity < 1.0:
- alpha_xml = f'<a:alpha val="{int(opacity * 100000)}"/>'
+ fg_opacity = combine_opacity(opacity, fg_alpha)
+ bg_opacity = combine_opacity(opacity, bg_alpha)
+ fg_alpha_xml = (
+ f'<a:alpha val="{int(fg_opacity * 100000)}"/>'
+ if fg_opacity is not None else ''
+ )
+ bg_alpha_xml = (
+ f'<a:alpha val="{int(bg_opacity * 100000)}"/>'
+ if bg_opacity is not None else ''
+ )
- fg_xml = color_node_xml(fg_hex, theme_color_spec, usage, alpha_xml)
+ fg_xml = color_node_xml(fg_hex, theme_color_spec, usage, fg_alpha_xml)
if bg_hex:
- bg_xml = color_node_xml(bg_hex, theme_color_spec, usage)
+ bg_xml = color_node_xml(bg_hex, theme_color_spec, usage, bg_alpha_xml)
else:
- bg_xml = color_node_xml('FFFFFF', theme_color_spec, usage)
+ bg_xml = color_node_xml('FFFFFF', theme_color_spec, usage, bg_alpha_xml)
return (
f'<a:pattFill prst="{prst}">'
@@ -432,10 +442,11 @@ def build_stroke_xml(
return f'<a:ln w="{width_emu}"{cap_attr}>{grad_fill}{dash_xml}{join_xml}{line_ends}</a:ln>'
# Solid color stroke
- color = parse_hex_color(stroke)
+ color, color_alpha = parse_svg_color(stroke)
if not color:
return '<a:ln><a:noFill/></a:ln>'
+ opacity = combine_opacity(opacity, color_alpha)
alpha_xml = ''
if opacity is not None and opacity < 1.0:
alpha_xml = f'<a:alpha val="{int(opacity * 100000)}"/>'
@@ -457,12 +468,19 @@ def _parse_filter_params(
std_dev = 4.0
dx = 0.0
dy = 0.0
- opacity = 0.3
+ paint_opacity: float | None = None
+ transfer_opacity: float | None = None
+ color_alpha = 1.0
color = '000000'
has_offset = False
for child in filter_elem.iter():
tag = child.tag.replace(f'{{{SVG_NS}}}', '')
+ style_values = parse_inline_style(child.get('style'))
+
+ def effect_attr(name: str, default: str | None = None) -> str | None:
+ return style_values.get(name) or child.get(name, default)
+
if tag == 'feDropShadow':
# Shorthand element: all params in one place
std_dev = _f(child.get('stdDeviation'), 4.0)
@@ -470,10 +488,13 @@ def _parse_filter_params(
dy = _f(child.get('dy'), 0.0)
if abs(dx) > 0.01 or abs(dy) > 0.01:
has_offset = True
- opacity = _f(child.get('flood-opacity'), 0.3)
- raw_color = child.get('flood-color', '').strip().lstrip('#')
- if len(raw_color) == 6 and all(c in '0123456789abcdefABCDEF' for c in raw_color):
- color = raw_color.upper()
+ paint_opacity = parse_opacity(effect_attr('flood-opacity'), 0.3)
+ parsed_color, parsed_alpha = parse_svg_color(
+ effect_attr('flood-color', '#000000')
+ )
+ if parsed_color:
+ color = parsed_color
+ color_alpha = parsed_alpha
elif tag == 'feGaussianBlur':
std_dev = _f(child.get('stdDeviation'), 4.0)
elif tag == 'feOffset':
@@ -482,13 +503,29 @@ def _parse_filter_params(
if abs(dx) > 0.01 or abs(dy) > 0.01:
has_offset = True
elif tag == 'feFlood':
- opacity = _f(child.get('flood-opacity'), 0.3)
- raw_color = child.get('flood-color', '').strip().lstrip('#')
- if len(raw_color) == 6 and all(c in '0123456789abcdefABCDEF' for c in raw_color):
- color = raw_color.upper()
+ paint_opacity = parse_opacity(effect_attr('flood-opacity'), 0.3)
+ parsed_color, parsed_alpha = parse_svg_color(
+ effect_attr('flood-color', '#000000')
+ )
+ if parsed_color:
+ color = parsed_color
+ color_alpha = parsed_alpha
elif tag == 'feFuncA':
if child.get('type') == 'linear':
- opacity = _f(child.get('slope'), 0.3)
+ slope = max(0.0, _f(child.get('slope'), 0.3))
+ transfer_opacity = (
+ slope
+ if transfer_opacity is None
+ else transfer_opacity * slope
+ )
+
+ if paint_opacity is None:
+ opacity = transfer_opacity if transfer_opacity is not None else 0.3
+ elif transfer_opacity is None:
+ opacity = paint_opacity
+ else:
+ opacity = paint_opacity * transfer_opacity
+ opacity = max(0.0, min(1.0, opacity * color_alpha))
return {
'std_dev': std_dev, 'dx': dx, 'dy': dy,
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
index 30971a11..c7d4b0e2 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/utils.py
@@ -2,8 +2,9 @@
from __future__ import annotations
-import re
+import colorsys
import math
+import re
from xml.etree import ElementTree as ET
from .context import AffineMatrix, ConvertContext, IDENTITY_MATRIX
@@ -447,41 +448,146 @@ def parse_inline_style(style_str: str | None) -> dict[str, str]:
return styles
+def _finite_float(raw: str) -> float:
+ """Parse a finite floating-point number."""
+ value = float(raw)
+ if not math.isfinite(value):
+ raise ValueError(f'Non-finite numeric value: {raw}')
+ return value
+
+
def _parse_color_channel(raw: str) -> int:
raw = raw.strip()
if raw.endswith('%'):
- value = float(raw[:-1]) * 255.0 / 100.0
+ value = _finite_float(raw[:-1]) * 255.0 / 100.0
else:
- value = float(raw)
+ value = _finite_float(raw)
return max(0, min(255, int(round(value))))
-def parse_hex_color(color_str: str) -> str | None:
- """Parse SVG color values to 'RRGGBB'. Returns None on failure."""
+def _parse_alpha_channel(raw: str) -> float:
+ """Parse a CSS alpha channel as a clamped ``0..1`` ratio."""
+ raw = raw.strip()
+ value = (
+ _finite_float(raw[:-1]) / 100.0
+ if raw.endswith('%')
+ else _finite_float(raw)
+ )
+ return max(0.0, min(1.0, value))
+
+
+def parse_opacity(raw: str | None, default: float = 1.0) -> float:
+ """Parse a number or percentage opacity, falling back to ``default``."""
+ if raw is None:
+ return max(0.0, min(1.0, default))
+ try:
+ return _parse_alpha_channel(raw)
+ except ValueError:
+ return max(0.0, min(1.0, default))
+
+
+def _functional_color_parts(body: str) -> tuple[list[str], str | None]:
+ """Split legacy comma or modern space/slash functional color syntax."""
+ before, separator, after = body.partition('/')
+ parts = [part for part in re.split(r'[\s,]+', before.strip()) if part]
+ alpha = after.strip() if separator else None
+ if alpha is None and len(parts) > 3:
+ alpha = parts.pop()
+ return parts, alpha
+
+
+def _parse_hue_degrees(raw: str) -> float:
+ """Normalize a CSS hue angle to degrees."""
+ value = raw.strip().lower()
+ for suffix, multiplier in (
+ ('turn', 360.0),
+ ('grad', 0.9),
+ ('rad', 180.0 / math.pi),
+ ('deg', 1.0),
+ ):
+ if value.endswith(suffix):
+ return _finite_float(value[:-len(suffix)]) * multiplier
+ return _finite_float(value)
+
+
+def _parse_percentage(raw: str) -> float:
+ """Parse a CSS percentage channel as a clamped ``0..1`` ratio."""
+ value = raw.strip()
+ ratio = (
+ _finite_float(value[:-1]) / 100.0
+ if value.endswith('%')
+ else _finite_float(value) / 100.0
+ )
+ return max(0.0, min(1.0, ratio))
+
+
+def parse_svg_color(color_str: str) -> tuple[str | None, float]:
+ """Parse an SVG/CSS color into ``(RRGGBB, alpha)``."""
if not color_str:
- return None
+ return None, 1.0
color_str = color_str.strip()
named = _CSS_NAMED_COLORS.get(color_str.lower())
if named is not None or color_str.lower() in _CSS_NAMED_COLORS:
- return named
+ if color_str.lower() == 'transparent':
+ return '000000', 0.0
+ return named, 1.0
rgb_match = re.match(r'rgba?\((.+)\)$', color_str, flags=re.IGNORECASE)
if rgb_match:
- channels = re.findall(r'[-+]?(?:\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?%?', rgb_match.group(1))
- if len(channels) >= 3:
+ channels, alpha_raw = _functional_color_parts(rgb_match.group(1))
+ if len(channels) == 3:
+ try:
+ r, g, b = (_parse_color_channel(ch) for ch in channels)
+ alpha = _parse_alpha_channel(alpha_raw) if alpha_raw is not None else 1.0
+ return f'{r:02X}{g:02X}{b:02X}', alpha
+ except ValueError:
+ return None, 1.0
+
+ hsl_match = re.match(r'hsla?\((.+)\)$', color_str, flags=re.IGNORECASE)
+ if hsl_match:
+ channels, alpha_raw = _functional_color_parts(hsl_match.group(1))
+ if len(channels) == 3:
try:
- r, g, b = (_parse_color_channel(ch) for ch in channels[:3])
- return f'{r:02X}{g:02X}{b:02X}'
+ hue = (_parse_hue_degrees(channels[0]) % 360.0) / 360.0
+ saturation = _parse_percentage(channels[1])
+ lightness = _parse_percentage(channels[2])
+ red, green, blue = colorsys.hls_to_rgb(hue, lightness, saturation)
+ alpha = _parse_alpha_channel(alpha_raw) if alpha_raw is not None else 1.0
+ return (
+ f'{round(red * 255):02X}{round(green * 255):02X}{round(blue * 255):02X}',
+ alpha,
+ )
except ValueError:
- return None
+ return None, 1.0
if color_str.startswith('#'):
color_str = color_str[1:]
if len(color_str) == 3:
color_str = ''.join(c * 2 for c in color_str)
+ elif len(color_str) == 4:
+ color_str = ''.join(c * 2 for c in color_str)
+ if len(color_str) == 8 and all(c in '0123456789abcdefABCDEF' for c in color_str):
+ return color_str[:6].upper(), int(color_str[6:], 16) / 255.0
if len(color_str) == 6 and all(c in '0123456789abcdefABCDEF' for c in color_str):
- return color_str.upper()
- return None
+ return color_str.upper(), 1.0
+ return None, 1.0
+
+
+def parse_hex_color(color_str: str) -> str | None:
+ """Parse SVG color values to ``RRGGBB``, ignoring any alpha channel."""
+ if color_str and color_str.strip().lower() == 'transparent':
+ return None
+ color, _alpha = parse_svg_color(color_str)
+ return color
+
+
+def combine_opacity(*values: float | None) -> float | None:
+ """Multiply opacity components, returning ``None`` when fully opaque."""
+ combined = 1.0
+ for value in values:
+ if value is not None:
+ combined *= max(0.0, min(1.0, value))
+ return combined if combined < 1.0 else None
def parse_stop_style(style_str: str) -> tuple[str | None, float]:
@@ -494,21 +600,18 @@ def parse_stop_style(style_str: str) -> tuple[str | None, float]:
(color, opacity) tuple.
"""
color = None
- opacity = 1.0
- if not style_str:
- return color, opacity
-
- for part in style_str.split(';'):
- part = part.strip()
- if part.startswith('stop-color:'):
- color = parse_hex_color(part.split(':', 1)[1].strip())
- elif part.startswith('stop-opacity:'):
- try:
- opacity = float(part.split(':', 1)[1].strip())
- except ValueError:
- pass
-
- return color, opacity
+ color_alpha = 1.0
+ stop_opacity = 1.0
+ style_values = parse_inline_style(style_str)
+ if not style_values:
+ return color, stop_opacity
+
+ if 'stop-color' in style_values:
+ color, color_alpha = parse_svg_color(style_values['stop-color'])
+ if 'stop-opacity' in style_values:
+ stop_opacity = parse_opacity(style_values['stop-opacity'])
+
+ return color, color_alpha * stop_opacity
def resolve_url_id(url_str: str) -> str | None: