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(roundtrip): keep chart formatting on edit and stop borrowing unrelated frames
hugohe30396656f4f5c
diff --git a/skills/ppt-master/scripts/docs/native-data.md b/skills/ppt-master/scripts/docs/native-data.mdindex e4016f83..ae697dad 100644--- a/skills/ppt-master/scripts/docs/native-data.md+++ b/skills/ppt-master/scripts/docs/native-data.md@@ -31,6 +31,8 @@ Cells accept `text`, `fill`, `fill_opacity`, `color`, `align` (header cells expoChart payloads carry no `schema` key: the marker's `data-pptx-replace-with` value selects the chart schema, and an invented key is rejected.+Classic charts accept root `lang`, a non-empty language tag validated by the shared language-tag helper. It preserves imported `c:lang` and takes precedence over the deck language for chart text; omission uses the deck language, then `en-US`. ChartEx rejects this field. Import projects supported plot spacing, inner manual layout, series paint/markers, axis settings and typography, and chart chrome into the same fields used for authored charts. Chart colors use RGB values: imported theme colors and their transforms are resolved against the source palette, rather than retained as theme-slot references.+- **Category charts** — `column`, `bar`, `line`, `area`, `pie`, `doughnut`, `pieOfPie`, `barOfPie`, `radar`: `categories` plus `series[].values`. Column, bar, line, and area values may be `null` for a gap (the workbook cell stays blank, the cache omits the point, `dispBlanksAs` is `gap`; at least one value per series is a number) — a fallback that breaks one line into segments is two series of the same colour with `null` outside their segment. Pie-family charts take exactly one series with per-slice colors; `hole_size` is doughnut-only, integer `10..90`, default `75`; no rotation field. Column/bar may set `series[].point_colors` (camelCase `pointColors` is read-compatible; length = values; every entry a colour — a `null` gap is line-only). Bar categories run top-down in payload order — the exporter reverses the category axis and moves the value-axis crossing so the value axis keeps its declared position; `axes.category.reverse: false` restores PowerPoint's bottom-up order (column charts stay left-to-right unless `reverse: true`). Bar/column spacing: root `gap_width` (`0..500`, the empty slot share as a percentage of one bar; PowerPoint default `150`; one category slot is the plot height (or width) divided by the category count and `bar = slot / (1 + gap_width / 100)`, so a chosen bar size converts back to `gap_width = (slot / bar - 1) × 100`) and clustered `overlap` (`-100..100`, the share of one bar the next series covers, negative for a gap); SVG-first export reads both from the fallback bars inside `plot_area` when the payload omits them, JSON-first uses the defaults.- **Line markers** — `line_style: "lineMarker"` draws a circle at every point in the series colour; `marker_size` (root or per series, SVG px diameter, `2..72` pt after `×0.75`) sizes it. `line_style` itself is a chart-root option — `series[].line_style` is rejected; inside a `combo` it sits on the plot or on a typed series. `series[].point_colors` on a line series marks single points: a colour draws that point's marker in that colour, `null` leaves it bare (with `line_style: "line"` only the coloured points carry markers), so an emphasised endpoint is `[null, …, "#C8102E"]`. Area series draw no markers; a line with markers over a fill is a `combo`. `data_labels` (column, bar, line, and area plots only, combo plots of those types included; pie-family, radar, scatter/bubble, stock, and ChartEx charts reject it — show their values through companion `notes`) is `true` or an object with `show_value`, `position`, `number_format`, `font_size`, `font_family`, `bold`, `color`, per-point `colors`, and `points` (zero-based `idx` plus optional overrides — with an explicit `show_*` flag every point keeps its label and `delete: true` hides one; without one only the listed points are labeled); positions: clustered column/bar `outside_end` / `inside_end` / `inside_base` / `center`, stacked `inside_end` / `inside_base` / `center`, line `above` / `center` / `best_fit`, area none; `series[].data_labels` takes the same object for one series, so two lines can label different points. Set `data_labels.number_format` to match the fallback (the parity gate reads `0`, `0.0`, `0.00`, `#,##0`, `#,##0.0`, their `%` forms — which scale the value by 100 — and a quoted literal prefix/suffix such as `"$"#,##0` or `0.0"%"`; other codes match only the literal value)'s rendered value labels. Rendered forms follow the en-US pattern (`.` decimal, `,` thousands); a deck written with locale separators (`1.234,5`) keeps such numbers out of the chart marker — integer ticks, no `data_labels`, the formatted figures in surrounding text or table cells.- **Combo** — shared `categories` plus `plots[]` (`type: "column" | "line" | "area"`, own `series`, optional `axis: "secondary"`, optionally own `categories` / `category_numeric` when caches genuinely differ, and `series_indices` for imported identity — same-length unique non-negative integers forming one contiguous `0..N-1` range across plots) or typed `series[]` with per-series `type` / `axis` (adjacent compatible series share a plot). Area series may set `fill_opacity` (`0..1`; `fillOpacity` read-compatible); a line plot with `area_fill: true` exports as an area chart; line/area series may set `line_width` in SVG px (`lineWidth` read-compatible); column plots take `gap_width` / `overlap`, line plots `line_style` / `marker_size`. An area series is a fill without an outline; `line_width` adds a same-colour outline around the whole region (baseline included), so a fallback that strokes only the top edge — or draws markers on it — is an area plot under a line plot with the same values. Export layers areas below columns and lines.diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex 7e9ab706..a9247717 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -255,9 +255,11 @@ as the round-trip text-capacity gate. It resolves the output roster fromfont-family, font-size, text-width, and canvas metrics only to new text orchanged source-ref objects. The gate asserts horizontal capacity: it estimatessingle-line width for each positioned line and does not model vertical-wrapping. Width beyond an explicit ancestor `data-pptx-frame` is blocking;-overflow against the nearest-rect-sibling fallback is advisory, while bounds-leaving the page canvas remain blocking. Other advisories remain non-blocking.+wrapping. Width beyond the nearest owning `data-pptx-frame` (imported) or+`data-pptx-bounds` (authored) is blocking. Without explicit bounds, only a rect+in the text's own group containing its anchor can supply an advisory frame;+page-level decorations and rectangles beside ancestor groups are excluded.+Bounds leaving the page canvas remain blocking. Other advisories remain non-blocking.Unchanged source refs, source proxies, and generated-project-only spec,template, canonical-authoring, and resource-manifest checks are excluded.diff --git a/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.pyindex a79f31cb..2adda271 100644--- a/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py+++ b/skills/ppt-master/scripts/pptx_to_svg/chart_to_svg.py@@ -425,7 +425,7 @@ def _combo_payload("series_indices": series_indices,"type": chart_type,}- for key in ("data_labels", "grouping", "line_style"):+ for key in ("data_labels", "gap_width", "grouping", "line_style", "overlap"):if plot_payload.get(key) is not None:plot_entry[key] = plot_payload[key]plots.append(plot_entry)@@ -976,7 +976,9 @@ def _chart_visual_styles(raise _UnsupportedChart("unsupported-chart-series-style")styles = _pie_visual_styles(payload, series_nodes[0], palette)else:- if any(series.find("c:dPt", C_NS) is not None for series in series_nodes):+ if chart_type not in {"bar", "column", "line"} and any(+ series.find("c:dPt", C_NS) is not None for series in series_nodes+ ):raise _UnsupportedChart("unsupported-chart-series-style")styles = []for index, series in enumerate(series_nodes):@@ -992,7 +994,8 @@ def _chart_visual_styles())colors = [- style.fill or style.stroke or style.marker_fill or _automatic_color(palette, index)+ (style.stroke if chart_type == "line" else style.fill)+ or style.fill or style.stroke or style.marker_fill or _automatic_color(palette, index)for index, style in enumerate(styles)]if colors:@@ -1196,7 +1199,8 @@ def _normalized_chart_visual_styles())colors = [- style.fill+ (style.stroke if chart_type == "line" else style.fill)+ or style.fillor style.strokeor style.marker_fillor _automatic_color(palette, index)@@ -1454,7 +1458,7 @@ def _axis_config_from_xml(_strict_axis_bool(auto, True)major_tick = _element_val(axis.find("c:majorTickMark", C_NS))minor_tick = _element_val(axis.find("c:minorTickMark", C_NS))- if major_tick not in {None, "none", "out"} or minor_tick not in {None, "none"}:+ if major_tick not in {None, "none", "out", "in", "cross"} or minor_tick not in {None, "none"}:raise _UnsupportedChart("unsupported-chart-axis-options")label_alignment = _element_val(axis.find("c:lblAlgn", C_NS))label_offset = _element_val(axis.find("c:lblOffset", C_NS))@@ -1929,20 +1933,24 @@ def _validate_chart_semantics(raise _UnsupportedChart("unsupported-chart-line-style")if chart_type in {"bar", "column"}:- _bounded_plot_integer(+ gap_width = _bounded_plot_integer(plot,"gapWidth",minimum=0,maximum=500,status="unsupported-chart-bar-options",)- _bounded_plot_integer(+ overlap = _bounded_plot_integer(plot,"overlap",minimum=-100,maximum=100,status="unsupported-chart-bar-options",)+ if gap_width is not None:+ payload["gap_width"] = gap_width+ if overlap is not None:+ payload["overlap"] = overlapif chart_type == "bubble":bubble_scale = _element_val(plot.find("c:bubbleScale", C_NS))@@ -1995,9 +2003,79 @@ def _validate_chart_semantics(second_size = _element_val(plot.find("c:secondPieSize", C_NS))if second_size not in {None, "75"}:raise _UnsupportedChart("unsupported-chart-of-pie-options")+ _apply_series_formatting(payload, plot, visual_styles, palette)return visual_styles+def _apply_series_formatting(+ payload: dict[str, Any],+ plot: ET.Element,+ visual_styles: list[SeriesVisualStyle],+ palette: ColorPalette | None,+) -> None:+ """Project the series paint and marker options the classic writer supports."""+ chart_type = payload["type"]+ if chart_type not in {"area", "bar", "column", "line"}:+ return+ for series, item, visual in zip(plot.findall("c:ser", C_NS), payload["series"], visual_styles):+ if chart_type == "area":+ item["fill_opacity"] = visual.fill_opacity+ if chart_type in {"area", "line"} and visual.stroke and visual.stroke_width > 0:+ item["line_width"] = visual.stroke_width+ if chart_type == "line" and series.find("c:marker/c:size", C_NS) is not None:+ item["marker_size"] = _round_payload_number(visual.marker_size / 0.75)++ base_color = visual.stroke if chart_type == "line" else visual.fill+ if chart_type == "line" and series.find("c:marker/c:spPr/a:solidFill", C_NS) is not None:+ base_color = visual.marker_fill or base_color+ if payload.get("line_style") == "lineMarker" and base_color != visual.stroke:+ item["point_colors"] = [base_color] * len(item["values"])+ points = series.findall("c:dPt", C_NS)+ if not points or chart_type == "area":+ continue+ colors = [base_color] * len(item["values"])+ sizes = [visual.marker_size] * len(colors)+ if chart_type == "line" and payload.get("line_style") != "lineMarker":+ colors = [None] * len(colors)+ sizes = [None] * len(colors)+ seen: set[int] = set()+ for point in points:+ raw_index = _element_val(point.find("c:idx", C_NS))+ if raw_index is None or not raw_index.isdigit():+ raise _UnsupportedChart("unsupported-chart-series-style")+ index = int(raw_index)+ if index >= len(colors) or index in seen:+ raise _UnsupportedChart("unsupported-chart-series-style")+ seen.add(index)+ if chart_type == "line":+ marker_node = point.find("c:marker", C_NS)+ marker = (+ _normalized_marker_paint(marker_node, palette)+ if palette is not None and not palette.strict+ else _resolved_marker(marker_node, palette)+ )+ if marker.symbol == "none":+ colors[index] = None+ sizes[index] = None+ elif marker.symbol == "circle":+ colors[index] = marker.shape.fill or base_color+ sizes[index] = marker.size+ else:+ shape = point.find("c:spPr", C_NS)+ paint = (+ _normalized_shape_paint(shape, palette)+ if palette is not None and not palette.strict+ else _resolved_shape_paint(shape, palette)+ )+ colors[index] = paint.fill or base_color+ if chart_type == "line" or all(colors):+ item["point_colors"] = colors+ if chart_type == "line":+ visible_sizes = {size for size in sizes if size is not None}+ if len(visible_sizes) == 1:+ item["marker_size"] = _round_payload_number(visible_sizes.pop() / 0.75)++def _apply_plot_data_labels(payload: dict[str, Any],plot: ET.Element,@@ -2091,6 +2169,11 @@ def _apply_chart_metadata(if chart is None:return+ language = _element_val(chart_root.find("c:lang", C_NS))+ if language:+ payload["lang"] = language+ _apply_chart_formatting(payload, chart_root, plot_area, palette)+title_element = chart.find("c:title", C_NS)title_entries = _canonical_title_entries(title_element)title = _chart_text(title_element)@@ -2100,7 +2183,7 @@ def _apply_chart_metadata(if len(title_entries) == 2:payload["subtitle"] = title_entries[1]else:- payload["title"] = title+ payload["title"] = _styled_chart_title(title_element, palette)legend = chart.find("c:legend", C_NS)if legend is not None:@@ -2111,30 +2194,33 @@ def _apply_chart_metadata(raise _UnsupportedChart("unsupported-chart-legend-position")payload["show_legend"] = Truepayload["legend_position"] = position+ legend_style = _source_chart_text_style(legend.find("c:txPr", C_NS), palette)+ if "font_size" in legend_style:+ payload["legend_font_size"] = legend_style["font_size"]if include_plot_labels:_apply_plot_data_labels(payload, plot, palette=palette)- axis_titles: dict[str, str] = {}+ axis_titles: dict[str, Any] = {}category_axis_nodes = (plot_area.findall("c:catAx", C_NS)+ plot_area.findall("c:dateAx", C_NS))category_titles = [- text+ axis.find("c:title", C_NS)for axis in category_axis_nodes- if (text := _chart_text(axis.find("c:title", C_NS)))+ if _chart_text(axis.find("c:title", C_NS))]value_titles = [- text+ axis.find("c:title", C_NS)for axis in plot_area.findall("c:valAx", C_NS)- if (text := _chart_text(axis.find("c:title", C_NS)))+ if _chart_text(axis.find("c:title", C_NS))]if payload["type"] == "combo":- if len(set(category_titles)) > 1:+ if len({_chart_text(title) for title in category_titles}) > 1:raise _UnsupportedChart("unsupported-chart-axis-titles")if category_titles:- axis_titles["category"] = category_titles[0]+ axis_titles["category"] = _styled_chart_title(category_titles[0], palette)for axis in plot_area.findall("c:valAx", C_NS):text = _chart_text(axis.find("c:title", C_NS))if not text:@@ -2143,35 +2229,152 @@ def _apply_chart_metadata(key = "secondary_value" if position == "r" else "value"if key in axis_titles:raise _UnsupportedChart("unsupported-chart-axis-titles")- axis_titles[key] = text+ axis_titles[key] = _styled_chart_title(axis.find("c:title", C_NS), palette)elif payload["type"] in {"scatter", "bubble"}:if category_titles:raise _UnsupportedChart("unsupported-chart-axis-titles")titled_value_axes = [(_element_val(axis.find("c:axPos", C_NS)),- _chart_text(axis.find("c:title", C_NS)),+ axis.find("c:title", C_NS),)for axis in plot_area.findall("c:valAx", C_NS)]- for position, text in titled_value_axes:- if not text:+ for position, title in titled_value_axes:+ if not _chart_text(title):continuekey = "x" if position in {"b", "t"} else "y"if key in axis_titles:raise _UnsupportedChart("unsupported-chart-axis-titles")- axis_titles[key] = text+ axis_titles[key] = _styled_chart_title(title, palette)else:if len(category_titles) > 1 or len(value_titles) > 1:raise _UnsupportedChart("unsupported-chart-axis-titles")if category_titles:- axis_titles["category"] = category_titles[0]+ axis_titles["category"] = _styled_chart_title(category_titles[0], palette)if value_titles:- axis_titles["value"] = value_titles[0]+ axis_titles["value"] = _styled_chart_title(value_titles[0], palette)if axis_titles:payload["axis_titles"] = axis_titles+def _styled_chart_title(title: ET.Element, palette: ColorPalette | None) -> str | dict[str, Any]:+ """Keep uniform title typography through the existing text-entry contract."""+ style = _source_chart_text_style(title.find("c:txPr", C_NS), palette)+ style.update(_source_chart_text_style(title.find("c:tx/c:rich", C_NS), palette))+ style.pop("bold", None)+ text = _chart_text(title)+ return {"text": text, **style} if style else text+++def _chart_fill_color(owner: ET.Element | None, palette: ColorPalette | None) -> str | None:+ """Resolve a schema-supported flat fill, including theme color transforms."""+ if owner is None:+ return None+ if owner.find("a:noFill", C_NS) is not None:+ return "none"+ color_node = find_color_elem(owner.find("a:solidFill", C_NS))+ if color_node is None:+ return None+ color, alpha = resolve_color(color_node, palette)+ return color if alpha > 0 else "none"+++def _apply_chart_formatting(+ payload: dict[str, Any],+ chart_root: ET.Element,+ plot_area: ET.Element,+ palette: ColorPalette | None,+) -> None:+ """Project only formatting with a writer in native-data.md's chart schema."""+ style = payload.setdefault("style", {})+ base_text = _source_chart_text_style(chart_root.find("c:txPr", C_NS), palette)+ for source, target in (("font_family", "font_family"), ("font_size", "font_size"),+ ("color", "text_color")):+ if source in base_text:+ style[target] = base_text[source]+ for owner, key in ((chart_root, "chart_area_fill"), (plot_area, "plot_area_fill")):+ color = _chart_fill_color(owner.find("c:spPr", C_NS), palette)+ if color is not None:+ style[key] = color++ layout = plot_area.find("c:layout/c:manualLayout", C_NS)+ if layout is not None:+ modes = {name: _element_val(layout.find(f"c:{name}", C_NS)) for name in (+ "layoutTarget", "xMode", "yMode", "wMode", "hMode",+ )}+ factors = [_axis_number(layout.find(f"c:{name}", C_NS)) for name in ("x", "y", "w", "h")]+ if (+ modes["layoutTarget"] == "inner"+ and modes["xMode"] == modes["yMode"] == "edge"+ and modes["wMode"] in {None, "factor"} and modes["hMode"] in {None, "factor"}+ and all(value is not None for value in factors)+ and factors[0] >= 0 and factors[1] >= 0 and factors[2] > 0 and factors[3] > 0+ and factors[0] + factors[2] <= 1 and factors[1] + factors[3] <= 1+ ):+ x, y, width, height = factors+ payload["plot_area"] = {+ "x": payload["x"] + x * payload["width"],+ "y": payload["y"] + y * payload["height"],+ "width": width * payload["width"], "height": height * payload["height"],+ }+ elif palette is not None:+ palette._diagnose(+ "chart-plot-layout-normalized",+ "Chart manual layout is outside the absolute inner plot-area contract",+ "keep chart data with automatic plot layout",+ )++ secondary_ids: set[str] = set()+ if payload["type"] == "combo":+ plots = [node for node in plot_area if _local_name(node.tag).endswith("Chart")]+ for plot, config in zip(plots, payload["plots"]):+ if config["axis"] == "secondary":+ secondary_ids.update(node.get("val") for node in plot.findall("c:axId", C_NS))+ for axis in plot_area:+ tag = _local_name(axis.tag)+ if tag not in {"catAx", "dateAx", "valAx"}:+ continue+ position = _element_val(axis.find("c:axPos", C_NS))+ if payload["type"] in {"scatter", "bubble"}:+ role = "x" if position in {"b", "t"} else "y"+ else:+ role = "value" if tag == "valAx" else "category"+ if _element_val(axis.find("c:axId", C_NS)) in secondary_ids:+ role = f"secondary_{role}"+ config = payload.setdefault("axes", {}).setdefault(role, {})+ if position in {"b", "t", "l", "r"}:+ config["position"] = {"b": "bottom", "t": "top", "l": "left", "r": "right"}[position]+ config["visible"] = not _strict_axis_bool(axis.find("c:delete", C_NS), False)+ config["reverse"] = _element_val(axis.find("c:scaling/c:orientation", C_NS)) == "maxMin"+ config["major_gridlines"] = axis.find("c:majorGridlines", C_NS) is not None+ for tag_name, field, aliases in (+ ("tickLblPos", "label_position", {"nextTo": "next_to", "none": "none", "low": "low", "high": "high"}),+ ("majorTickMark", "tick_marks", {value: value for value in ("none", "in", "out", "cross")}),+ ):+ value = _element_val(axis.find(f"c:{tag_name}", C_NS))+ if value in aliases:+ config[field] = aliases[value]+ if role in {"value", "secondary_value"}:+ crossing = _element_val(axis.find("c:crossBetween", C_NS))+ if crossing in {"between", "midCat"}:+ config["cross_between"] = "mid_category" if crossing == "midCat" else crossing+ number_format = axis.find("c:numFmt", C_NS)+ if number_format is not None and number_format.get("formatCode"):+ config["number_format"] = number_format.get("formatCode")+ for path, field in (("scaling/c:min", "minimum"), ("scaling/c:max", "maximum"),+ ("majorUnit", "major_unit")):+ value = _axis_number(axis.find(f"c:{path}", C_NS))+ if value is not None and (field != "major_unit" or tag == "valAx"):+ config[field] = value+ text_style = _source_chart_text_style(axis.find("c:txPr", C_NS), palette)+ config.update({key: value for key, value in text_style.items() if key != "bold"})+ for path, key in (("c:spPr/a:ln", "axis_color"), ("c:majorGridlines/c:spPr/a:ln", "grid_color")):+ color = _chart_fill_color(axis.find(path, C_NS), palette)+ if color is not None:+ style.setdefault(key, color)++def _chart_text(container: ET.Element | None) -> str:if container is None:return ""@@ -2442,16 +2645,29 @@ def _data_label_flag_payload(return config-def _source_data_label_text_style(- owner: ET.Element,+def _source_chart_text_style(+ owner: ET.Element | None,palette: ColorPalette | None,) -> dict[str, Any]:- """Read visible label run properties without requiring canonical OOXML."""- r_pr = owner.find(".//a:defRPr", C_NS)- if r_pr is None:- r_pr = owner.find(".//a:rPr", C_NS)- if r_pr is None:+ """Read uniform chart text properties without requiring canonical OOXML."""+ if owner is None:+ return {}+ properties = [owner.find(path, C_NS) for path in (+ "a:lstStyle/a:defPPr/a:defRPr", "a:lstStyle/a:lvl1pPr/a:defRPr",+ "a:p/a:pPr/a:defRPr", "a:p/a:r/a:rPr",+ )]+ if all(node is None for node in properties):return {}+ r_pr = ET.Element(f"{{{NS['a']}}}rPr")+ for node in properties:+ if node is None:+ continue+ r_pr.attrib.update(node.attrib)+ for child in node:+ previous = r_pr.find(child.tag)+ if previous is not None:+ r_pr.remove(previous)+ r_pr.append(child)style: dict[str, Any] = {}raw_size = r_pr.attrib.get("sz")@@ -2529,7 +2745,7 @@ def _point_data_label_payload(item["number_format"] = num_fmt.attrib["formatCode"]tx_pr = dlabel.find("c:txPr", C_NS)if tx_pr is not None:- item.update(_source_data_label_text_style(tx_pr, palette))+ item.update(_source_chart_text_style(tx_pr, palette))tx = dlabel.find("c:tx", C_NS)if tx is not None:@@ -2544,7 +2760,7 @@ def _point_data_label_payload(if not text:raise _UnsupportedChart("unsupported-chart-point-labels")item["text"] = text- item.update(_source_data_label_text_style(rich, palette))+ item.update(_source_chart_text_style(rich, palette))return item@@ -2613,7 +2829,7 @@ def _data_labels_payload(try:config.update(_data_label_text_style(tx_pr))except _UnsupportedChart:- config.update(_source_data_label_text_style(tx_pr, palette))+ config.update(_source_chart_text_style(tx_pr, palette))if point_nodes:assert point_count is not Nonepoints = [diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.pyindex f94f5010..c18ef9ef 100644--- a/skills/ppt-master/scripts/svg_quality/checker.py+++ b/skills/ppt-master/scripts/svg_quality/checker.py@@ -2292,8 +2292,8 @@ class SVGQualityChecker:detail = f': {frame_error}' if frame_error else ''result['warnings'].append(f'Cannot verify owning frame for edited {text_label}{detail}; '- 'keep data-pptx-frame on the logical object or place a '- 'rect frame beside the text'+ 'set data-pptx-bounds on the authored text group or group '+ 'the text with its containing rect; preserve existing imported frames')continuemetrics = self._bounds_overflow_metrics(estimated, frame)@@ -2332,8 +2332,8 @@ class SVGQualityChecker:)if frame_is_inferred:result['warnings'].append(- f'{finding}; frame inferred from nearest rect sibling; '- 'add data-pptx-frame to make this blocking'+ f'{finding}; frame inferred from a containing rect sibling; '+ 'set data-pptx-bounds on the authored text group to declare its bounds')else:result['errors'].append(finding)@@ -2348,6 +2348,8 @@ class SVGQualityChecker:while current is not None:if current.get('data-pptx-frame') is not None:return current.get('data-pptx-source-ref')+ if current.get('data-pptx-bounds') is not None:+ return Nonecurrent = parent_by_id.get(id(current))return None@@ -2411,12 +2413,16 @@ class SVGQualityChecker:str | None,bool,]:- """Resolve an explicit logical frame or the nearest rect sibling."""+ """Resolve owning bounds or a containing rect in the text's own group."""current: ET.Element | None = text_elementwhile current is not None:- raw_frame = current.get('data-pptx-frame')+ attribute = (+ 'data-pptx-frame' if current.get('data-pptx-frame') is not None+ else 'data-pptx-bounds'+ )+ raw_frame = current.get(attribute)if raw_frame is not None:- label = f'{_element_label(current)} data-pptx-frame'+ label = f'{_element_label(current)} {attribute}'try:frame = _parse_positive_bounds(raw_frame)except ValueError as exc:@@ -2438,62 +2444,54 @@ class SVGQualityChecker:if _parse_project_geometry_length is None:return None, None, 'the SVG length parser is unavailable', False- current = text_element+ parent = parent_by_id.get(id(text_element))+ if parent is None or _local_name(parent) != 'g':+ return None, None, None, False+ try:+ anchor_x = _parse_project_geometry_length(text_element.get('x') or '0', 'x')+ anchor_y = _parse_project_geometry_length(text_element.get('y') or '0', 'y')+ except (TypeError, ValueError):+ return None, None, 'the text anchor cannot be resolved', False+ anchor = cls._transformed_rect_bounds(+ text_element, (anchor_x, anchor_y, 0, 0), parent_by_id,+ )+ if anchor is None:+ return None, None, 'the text anchor has an unresolved transform', Falserect_errors: List[str] = []- while current is not None:- parent = parent_by_id.get(id(current))- if parent is None:- break- siblings = list(parent)+ siblings = list(parent)+ current_index = siblings.index(text_element)+ rects = sorted(+ (+ (abs(index - current_index), index, sibling)+ for index, sibling in enumerate(siblings)+ if _local_name(sibling) == 'rect'+ and sibling.get('data-pptx-role') not in {'decoration', 'background'}+ ),+ key=lambda item: (item[0], item[1]),+ )+ for _distance, _index, rect in rects:+ label = _element_label(rect)try:- current_index = siblings.index(current)- except ValueError:- current_index = 0- rects = sorted(- (- (abs(index - current_index), index, sibling)- for index, sibling in enumerate(siblings)- if _local_name(sibling) == 'rect'- ),- key=lambda item: (item[0], item[1]),- )- for _distance, _index, rect in rects:- label = _element_label(rect)- try:- x = _parse_project_geometry_length(- rect.get('x') or '0',- 'x',- )- y = _parse_project_geometry_length(- rect.get('y') or '0',- 'y',- )- width = _parse_project_geometry_length(- rect.get('width'),- 'width',- )- height = _parse_project_geometry_length(- rect.get('height'),- 'height',- )- if (- not all(math.isfinite(value) for value in (x, y, width, height))- or width <= 0- or height <= 0- ):- raise ValueError('must use finite positive width and height')- except (TypeError, ValueError) as exc:- rect_errors.append(f'{label} {exc}')- continue- transformed = cls._transformed_rect_bounds(- rect,- (x, y, width, height),- parent_by_id,- )- if transformed is not None:- return label, transformed, None, True+ x = _parse_project_geometry_length(rect.get('x') or '0', 'x')+ y = _parse_project_geometry_length(rect.get('y') or '0', 'y')+ width = _parse_project_geometry_length(rect.get('width'), 'width')+ height = _parse_project_geometry_length(rect.get('height'), 'height')+ if (+ not all(math.isfinite(value) for value in (x, y, width, height))+ or width <= 0 or height <= 0+ ):+ raise ValueError('must use finite positive width and height')+ except (TypeError, ValueError) as exc:+ rect_errors.append(f'{label} {exc}')+ continue+ transformed = cls._transformed_rect_bounds(rect, (x, y, width, height), parent_by_id)+ if transformed is None:rect_errors.append(f'{label} has an unresolved transform')- current = parent+ elif (+ transformed[0] <= anchor[0] <= transformed[2]+ and transformed[1] <= anchor[1] <= transformed[3]+ ):+ return label, transformed, None, Truereturn (None,None,diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.pyindex cb37a1ff..e055d375 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_data.py@@ -5,6 +5,8 @@ from __future__ import annotationsimport mathfrom typing import Any+from language_tags import LanguageTagError, normalize_language_tag+from .marker_common import (_chart_bool,_clean_hex,@@ -1628,8 +1630,19 @@ def _xy_chart_data(}+def _chart_language(payload: dict[str, Any]) -> str | None:+ if "lang" not in payload:+ return None+ try:+ return normalize_language_tag(payload["lang"])+ except LanguageTagError as exc:+ raise RuntimeError(f"Native PPTX chart lang: {exc}") from exc++def _chart_data(payload: dict[str, Any]) -> dict[str, Any]:chart_type, alias_grouping, alias_style = _chart_kind(payload)+ if _chart_language(payload) is not None and chart_type in _CHARTEX_CHART_TYPES:+ raise RuntimeError("Native PPTX chart lang is supported for classic charts only")if payload.get("hole_size") is not None and chart_type != "doughnut":raise RuntimeError("Native PPTX chart hole_size is supported for doughnut charts only"diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.pyindex ee97c6b5..c8d4462d 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/chart_xml.py@@ -18,6 +18,7 @@ from .chart_data import (_DEFAULT_CHART_COLORS,_category_axis_is_date,_category_axis_reversed,+ _chart_language,_chart_list,_chart_plot_area_layout,_data_label_position,@@ -913,6 +914,20 @@ def _axis_major_gridlines_xml(return _major_gridlines_xml(color) if enabled else ""+def _axis_tx_pr_xml(+ config: dict[str, Any],+ font_size: int,+ chart_style: dict[str, str | None],+) -> str:+ """Apply per-axis tick-label overrides to the shared chart text defaults."""+ return _chart_tx_pr_xml(+ _font_size_hpt(config["font_size"]) if config.get("font_size") else font_size,+ config.get("color") or chart_style.get("text_color"),+ font_face=config.get("font_family") or chart_style.get("font_face"),+ language=chart_style.get("primary_language"),+ )++def _axis_pair_xml(cat_ax_id: str,val_ax_id: str,@@ -951,16 +966,6 @@ def _axis_pair_xml(val_number_format = _axis_number_format_xml(value, default_value_format)axis_sp_pr = _chart_line_sp_pr_xml(chart_style.get("axis_color"))- def axis_tx_pr(config: dict[str, Any]) -> str:- # Tick-label text per axis: the payload's colour/font/size win over- # the chart-wide text style (category labels dark, value ticks grey).- return _chart_tx_pr_xml(- _font_size_hpt(config["font_size"]) if config.get("font_size") else axis_font_size,- config.get("color") or chart_style.get("text_color"),- font_face=config.get("font_family") or chart_style.get("font_face"),- language=primary_language,- )-cat_title_xml = "" if secondary else _axis_title_xml(_first_present(axis_titles.get("category"), axis_titles.get("x")),font_size=axis_title_font_size,@@ -1034,7 +1039,7 @@ def _axis_pair_xml(f"{cat_gridlines}{cat_title_xml}{cat_number_format}"f'<c:majorTickMark val="{cat_tick_marks}"/><c:minorTickMark val="none"/>'f'<c:tickLblPos val="{cat_tick_label_pos}"/>'- f"{axis_sp_pr}{axis_tx_pr(category)}"+ f"{axis_sp_pr}{_axis_tx_pr_xml(category, axis_font_size, chart_style)}"f'<c:crossAx val="{val_ax_id}"/><c:crosses val="{category_crosses}"/>{category_tail}'f"</c:{category_tag}>""<c:valAx>"@@ -1043,7 +1048,7 @@ def _axis_pair_xml(f"{val_gridlines}{val_title_xml}{val_number_format}"f'<c:majorTickMark val="{val_tick_marks}"/><c:minorTickMark val="none"/>'f'<c:tickLblPos val="{val_tick_label_pos}"/>'- f"{axis_sp_pr}{axis_tx_pr(value)}"+ f"{axis_sp_pr}{_axis_tx_pr_xml(value, axis_font_size, chart_style)}"f'<c:crossAx val="{cat_ax_id}"/><c:crosses val="{value_crosses}"/>'f"{cross_between}{major_unit}""</c:valAx>"@@ -1498,12 +1503,6 @@ def _xy_axis_xml(x_axis = normalized_axes.get("x", {})y_axis = normalized_axes.get("y", {})axis_sp_pr = _chart_line_sp_pr_xml(chart_style.get("axis_color"))- axis_tx_pr = _chart_tx_pr_xml(- axis_font_size,- chart_style.get("text_color"),- font_face=chart_style.get("font_face"),- language=primary_language,- )x_title_xml = _axis_title_xml(_first_present(axis_titles.get("x"), axis_titles.get("category")),font_size=axis_title_font_size,@@ -1546,9 +1545,9 @@ def _xy_axis_xml(f'<c:axId val="{axis_id}"/>{_axis_scaling_xml(config)}'f'<c:delete val="{delete}"/><c:axPos val="{position}"/>'f"{gridlines}{title_xml}{number_format}"- '<c:majorTickMark val="out"/><c:minorTickMark val="none"/>'+ f'<c:majorTickMark val="{config.get("tick_marks", "none")}"/><c:minorTickMark val="none"/>'f'<c:tickLblPos val="{tick_label_position}"/>'- f"{axis_sp_pr}{axis_tx_pr}"+ f"{axis_sp_pr}{_axis_tx_pr_xml(config, axis_font_size, chart_style)}"f'<c:crossAx val="{cross_axis_id}"/><c:crosses val="autoZero"/>'f'<c:crossBetween val="midCat"/>{major_unit}'"</c:valAx>"@@ -1669,6 +1668,7 @@ def _chart_xml(inherited_styles: dict[str, str] | None = None,primary_language: str | None = None,) -> bytes:+ primary_language = _chart_language(payload) or primary_languagestyle = payload.get("style") if isinstance(payload.get("style"), dict) else {}colors = ([_clean_hex(color, "#4472C4") for color in style.get("colors", [])]diff --git a/skills/ppt-master/scripts/tests/test_chart_import_formatting.py b/skills/ppt-master/scripts/tests/test_chart_import_formatting.pynew file mode 100644index 00000000..9cd67ec3--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_chart_import_formatting.py@@ -0,0 +1,345 @@+#!/usr/bin/env python3+"""PPT Master - Chart Import Formatting Regression Tests++Exercise chart data edits and owning text frames with small native fixtures.++Usage:+ python3 -m unittest tests.test_chart_import_formatting++Examples:+ Run the module from the scripts directory.++Dependencies:+ python-pptx and the local importer, converter, and checker.+"""++from __future__ import annotations++import io+import json+import tempfile+import unittest+from contextlib import redirect_stderr, redirect_stdout+from pathlib import Path+from xml.etree import ElementTree as ET+from zipfile import ZipFile++from pptx import Presentation++from pptx_to_svg.chart_to_svg import extract_native_chart_payload+from pptx_to_svg.color_resolver import ColorPalette+from pptx_to_svg.converter import ConvertOptions, convert_pptx_to_svg+from pptx_to_svg.emu_units import Xfrm+from pptx_to_svg.ooxml_loader import OoxmlPackage, PartRef+from svg_quality.checker import SVGQualityChecker+from svg_to_pptx.drawingml.converter import convert_svg_to_slide_shapes+++NS = {+ "a": "http://schemas.openxmlformats.org/drawingml/2006/main",+ "c": "http://schemas.openxmlformats.org/drawingml/2006/chart",+ "r": "http://schemas.openxmlformats.org/officeDocument/2006/relationships",+ "s": "http://www.w3.org/2000/svg",+}+++def _text_style(size: int = 1050, color: str = '<a:schemeClr val="accent1"/>') -> str:+ return (+ '<c:txPr><a:bodyPr/><a:lstStyle/><a:p><a:pPr>'+ f'<a:defRPr lang="zh-CN" sz="{size}"><a:solidFill>{color}</a:solidFill>'+ '<a:latin typeface="微软雅黑"/><a:ea typeface="微软雅黑"/>'+ '</a:defRPr></a:pPr><a:endParaRPr lang="zh-CN"/></a:p></c:txPr>'+ )+++def _source_chart() -> ET.Element:+ value_style = _text_style(1200, '<a:srgbClr val="123456"/>')+ return ET.fromstring(+ f'<c:chartSpace xmlns:c="{NS["c"]}" xmlns:a="{NS["a"]}">'+ '<c:lang val="zh-CN"/><c:chart><c:plotArea><c:layout><c:manualLayout>'+ '<c:layoutTarget val="inner"/><c:xMode val="edge"/><c:yMode val="edge"/>'+ '<c:x val="0.1"/><c:y val="0.15"/><c:w val="0.8"/><c:h val="0.65"/>'+ '</c:manualLayout></c:layout><c:barChart><c:barDir val="col"/>'+ '<c:grouping val="clustered"/><c:ser><c:idx val="0"/><c:order val="0"/>'+ '<c:tx><c:v>Budget</c:v></c:tx><c:cat><c:strLit><c:ptCount val="2"/>'+ '<c:pt idx="0"><c:v>Other</c:v></c:pt><c:pt idx="1"><c:v>Equipment</c:v></c:pt>'+ '</c:strLit></c:cat><c:val><c:numLit><c:formatCode>General</c:formatCode>'+ '<c:ptCount val="2"/><c:pt idx="0"><c:v>10</c:v></c:pt>'+ '<c:pt idx="1"><c:v>20</c:v></c:pt></c:numLit></c:val></c:ser>'+ '<c:gapWidth val="40"/><c:overlap val="-27"/><c:axId val="1"/><c:axId val="2"/>'+ '</c:barChart><c:catAx><c:axId val="1"/><c:scaling><c:orientation val="minMax"/>'+ '</c:scaling><c:axPos val="b"/><c:majorTickMark val="in"/><c:tickLblPos val="nextTo"/>'+ f'{_text_style()}<c:crossAx val="2"/><c:crosses val="autoZero"/></c:catAx>'+ '<c:valAx><c:axId val="2"/><c:scaling><c:orientation val="minMax"/></c:scaling>'+ '<c:axPos val="l"/><c:majorGridlines/><c:majorTickMark val="cross"/>'+ '<c:tickLblPos val="nextTo"/>'+ f'{value_style}'+ '<c:crossAx val="1"/><c:crosses val="autoZero"/><c:crossBetween val="between"/>'+ '</c:valAx></c:plotArea><c:legend><c:legendPos val="t"/>'+ f'{_text_style(1350)}</c:legend></c:chart>{_text_style(900)}</c:chartSpace>'+ )+++class ChartImportFormattingTests(unittest.TestCase):+ def _import(self, source: ET.Element) -> dict:+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "source.pptx"+ with ZipFile(path, "w") as archive:+ archive.writestr("ppt/charts/chart1.xml", ET.tostring(source))+ archive.writestr(+ "ppt/presentation.xml",+ '<p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main">'+ '<p:sldIdLst/></p:presentation>',+ )+ slide = PartRef("ppt/slides/slide1.xml", ET.Element("slide"), {+ "rId1": {"target": "ppt/charts/chart1.xml"},+ })+ graphic = ET.fromstring(+ f'<a:graphicData xmlns:a="{NS["a"]}" xmlns:c="{NS["c"]}" '+ f'xmlns:r="{NS["r"]}" uri="{NS["c"]}"><c:chart r:id="rId1"/></a:graphicData>'+ )+ palette = ColorPalette(None, None)+ palette.scheme["accent1"] = "347BFE"+ with OoxmlPackage(path) as package:+ result = extract_native_chart_payload(+ graphic, Xfrm(100, 80, 600, 400), slide, package, palette,+ )+ self.assertIsNone(result.native_status)+ self.assertIsNotNone(result.native_payload)+ return result.native_payload++ def _export(self, payload: dict, *, primary_language: str | None = None) -> ET.Element:+ root = ET.Element(f'{{{NS["s"]}}}svg', {"viewBox": "0 0 1280 720"})+ marker = ET.SubElement(root, f'{{{NS["s"]}}}g', {+ "id": "chart", "data-pptx-replace-with": "chart", "data-pptx-native-authority": "json",+ })+ ET.SubElement(marker, f'{{{NS["s"]}}}metadata', {"type": "application/json"}).text = json.dumps(payload)+ with tempfile.TemporaryDirectory() as temporary:+ path = Path(temporary) / "chart.svg"+ path.write_bytes(ET.tostring(root))+ _, _, _, _, parts, _ = convert_svg_to_slide_shapes(+ path, resource_root=Path(temporary), native_objects=True, primary_language=primary_language,+ )+ charts = [content for name, content in parts.items() if name.startswith("ppt/charts/chart")+ and name.endswith(".xml") and "/_rels/" not in name]+ self.assertEqual(len(charts), 1)+ return ET.fromstring(charts[0])++ def test_data_edit_preserves_spacing_layout_language_and_axis_typography(self) -> None:+ payload = self._import(_source_chart())+ self.assertEqual(payload.get("gap_width"), 40)+ self.assertEqual(payload.get("overlap"), -27)+ self.assertEqual(payload.get("plot_area"), {"x": 160, "y": 140, "width": 480, "height": 260})+ self.assertEqual(payload.get("lang"), "zh-CN")+ payload["series"][0]["values"] = [60, 140]+ payload["categories"][0] = "Reserve"+ chart = self._export(payload, primary_language="en-US")+ self.assertEqual(chart.find("c:lang", NS).get("val"), "zh-CN")+ self.assertEqual(chart.find(".//c:gapWidth", NS).get("val"), "40")+ self.assertEqual(chart.find(".//c:overlap", NS).get("val"), "-27")+ layout = chart.find(".//c:plotArea/c:layout/c:manualLayout", NS)+ self.assertIsNotNone(layout)+ for key, expected in (("x", 0.1), ("y", 0.15), ("w", 0.8), ("h", 0.65)):+ self.assertAlmostEqual(float(layout.find(f"c:{key}", NS).get("val")), expected)+ for tag, size, color, tick in (("catAx", "1050", "347BFE", "in"),+ ("valAx", "1200", "123456", "cross")):+ axis = chart.find(f".//c:{tag}", NS)+ props = axis.find("c:txPr/a:p/a:pPr/a:defRPr", NS)+ self.assertEqual(props.get("sz"), size)+ self.assertEqual(props.find("a:latin", NS).get("typeface"), "Microsoft YaHei")+ self.assertEqual(props.find("a:solidFill/a:srgbClr", NS).get("val"), color)+ self.assertEqual(axis.find("c:majorTickMark", NS).get("val"), tick)+ self.assertEqual(chart.find(".//c:legend/c:txPr//a:defRPr", NS).get("sz"), "1350")++ def test_axis_typography_is_projected_even_when_legacy_axis_gate_passes(self) -> None:+ payload = self._import(_source_chart())+ self.assertEqual(payload.get("axes", {}).get("category", {}).get("font_size"), 14)+ self.assertEqual(payload.get("axes", {}).get("value", {}).get("font_size"), 16)++ def test_chart_fill_title_and_inherited_axis_style(self) -> None:+ source = _source_chart()+ for axis in source.findall(".//c:catAx", NS) + source.findall(".//c:valAx", NS):+ axis.remove(axis.find("c:txPr", NS))+ for owner, color in ((source, "EEEEEE"), (source.find(".//c:plotArea", NS), "ABCDEF")):+ owner.append(ET.fromstring(+ f'<c:spPr xmlns:c="{NS["c"]}" xmlns:a="{NS["a"]}">'+ f'<a:solidFill><a:srgbClr val="{color}"/></a:solidFill></c:spPr>'+ ))+ title = ET.SubElement(source.find("c:chart", NS), f'{{{NS["c"]}}}title')+ title.append(ET.fromstring(+ f'<c:tx xmlns:c="{NS["c"]}" xmlns:a="{NS["a"]}"><c:rich>'+ '<a:bodyPr/><a:lstStyle/><a:p><a:r><a:rPr sz="2100">'+ '<a:solidFill><a:srgbClr val="112233"/></a:solidFill>'+ '<a:latin typeface="Arial"/></a:rPr><a:t>Budget</a:t></a:r></a:p></c:rich></c:tx>'+ ))+ chart = self._export(self._import(source))+ self.assertEqual(chart.find("c:spPr/a:solidFill/a:srgbClr", NS).get("val"), "EEEEEE")+ self.assertEqual(chart.find(".//c:plotArea/c:spPr/a:solidFill/a:srgbClr", NS).get("val"), "ABCDEF")+ self.assertEqual(chart.find(".//c:catAx/c:txPr//a:defRPr", NS).get("sz"), "900")+ props = chart.find(".//c:title//a:rPr", NS)+ self.assertEqual(props.get("sz"), "2100")+ self.assertEqual(props.find("a:solidFill/a:srgbClr", NS).get("val"), "112233")++ def test_combo_plot_spacing_and_series_formatting_survive(self) -> None:+ payload = {+ "type": "combo", "x": 100, "y": 80, "width": 600, "height": 400,+ "categories": ["A", "B"], "plots": [+ {"type": "column", "gap_width": 0, "overlap": 0, "series": [{"name": "Bars", "values": [1, 2]}]},+ {"type": "line", "line_style": "lineMarker", "series": [+ {"name": "Line", "values": [2, 3], "line_width": 4, "marker_size": 12},+ ]},+ {"type": "area", "series": [+ {"name": "Area", "values": [3, 4], "fill_opacity": 0.25, "line_width": 2},+ ]},+ ],+ }+ imported = self._import(self._export(payload))+ plots = {plot["type"]: plot for plot in imported["plots"]}+ self.assertEqual(plots["column"].get("gap_width"), 0)+ self.assertEqual(plots["column"].get("overlap"), 0)+ self.assertEqual(plots["line"]["series"][0].get("line_width"), 4)+ self.assertEqual(plots["line"]["series"][0].get("marker_size"), 12)+ self.assertEqual(plots["area"]["series"][0].get("fill_opacity"), 0.25)+ self.assertEqual(plots["area"]["series"][0].get("line_width"), 2)++ def test_equal_axis_title_text_keeps_each_axes_own_style(self) -> None:+ source = _source_chart()+ for tag, size, color in (("catAx", "1500", "123456"), ("valAx", "1800", "654321")):+ axis = source.find(f".//c:{tag}", NS)+ axis.append(ET.fromstring(+ f'<c:title xmlns:c="{NS["c"]}" xmlns:a="{NS["a"]}"><c:tx><c:rich>'+ '<a:bodyPr/><a:lstStyle/><a:p><a:pPr><a:defRPr sz="900">'+ '<a:latin typeface="Arial"/></a:defRPr></a:pPr>'+ f'<a:r><a:rPr sz="{size}"><a:solidFill><a:srgbClr val="{color}"/>'+ '</a:solidFill></a:rPr><a:t>Shared title</a:t></a:r></a:p></c:rich></c:tx></c:title>'+ ))+ chart = self._export(self._import(source))+ for tag, size, color in (("catAx", "1500", "123456"), ("valAx", "1800", "654321")):+ props = chart.find(f".//c:{tag}/c:title//a:rPr", NS)+ self.assertEqual(props.get("sz"), size)+ self.assertEqual(props.find("a:solidFill/a:srgbClr", NS).get("val"), color)+ self.assertEqual(props.find("a:latin", NS).get("typeface"), "Arial")++ def test_secondary_axis_style_stays_on_secondary_axis(self) -> None:+ payload = {+ "type": "combo", "x": 100, "y": 80, "width": 600, "height": 400,+ "categories": ["A", "B"], "plots": [+ {"type": "column", "series": [{"name": "Bars", "values": [1, 2]}]},+ {"type": "line", "axis": "secondary", "series": [{"name": "Line", "values": [3, 4]}]},+ ],+ "axes": {"secondary_value": {"font_family": "Arial", "font_size": 20, "color": "#123456"}},+ }+ imported = self._import(self._export(payload))+ self.assertEqual(imported["axes"]["secondary_value"]["font_size"], 20)+ self.assertEqual(imported["axes"]["secondary_value"]["color"], "#123456")+ imported["plots"][0]["series"][0]["values"][0] = 10+ chart = self._export(imported)+ axes = chart.findall(".//c:valAx", NS)+ right = next(axis for axis in axes if axis.find("c:axPos", NS).get("val") == "r")+ self.assertEqual(right.find("c:txPr//a:defRPr", NS).get("sz"), "1500")++ def test_point_colors_survive_for_columns_and_line_markers(self) -> None:+ for chart_type, point_colors in (("column", ["#123456", "#ABCDEF"]),+ ("line", [None, "#ABCDEF"])):+ with self.subTest(chart_type=chart_type):+ payload = {+ "type": chart_type, "x": 100, "y": 80, "width": 600, "height": 400,+ "categories": ["A", "B"], "series": [{+ "name": "S", "values": [1, 2], "point_colors": point_colors,+ }],+ }+ if chart_type == "line":+ payload["series"][0]["marker_size"] = 12+ imported = self._import(self._export(payload))+ self.assertEqual(imported["series"][0].get("point_colors"), point_colors)+ if chart_type == "line":+ self.assertEqual(imported["series"][0].get("marker_size"), 12)++ def test_scatter_axis_text_overrides_reach_writer(self) -> None:+ payload = {+ "type": "scatter", "x": 100, "y": 80, "width": 600, "height": 400,+ "series": [{"name": "S", "x": [1, 2], "y": [2, 3]}],+ "axes": {"x": {"font_family": "Arial", "font_size": 20,+ "color": "#123456", "tick_marks": "cross"}},+ }+ chart = self._export(payload)+ props = chart.find(".//c:valAx/c:txPr//a:defRPr", NS)+ self.assertEqual(props.get("sz"), "1500")+ self.assertEqual(chart.find(".//c:valAx/c:majorTickMark", NS).get("val"), "cross")+ imported = self._import(chart)+ self.assertEqual(imported["axes"]["x"].get("font_size"), 20)++ def test_language_default_and_invalid_value(self) -> None:+ payload = {"type": "column", "x": 0, "y": 0, "width": 400, "height": 300,+ "categories": ["A"], "series": [{"name": "S", "values": [1]}]}+ self.assertEqual(self._export(payload).find("c:lang", NS).get("val"), "en-US")+ self.assertEqual(self._export(payload, primary_language="fr-FR").find("c:lang", NS).get("val"), "fr-FR")+ for invalid in ("", 42, 'en-US"/><injected/>'):+ with self.subTest(invalid=invalid), self.assertRaises(RuntimeError):+ self._export({**payload, "lang": invalid})+ with self.assertRaisesRegex(RuntimeError, "classic charts only"):+ self._export({**payload, "type": "treemap", "values": [1], "levels": [["A"]], "lang": "zh-CN"})+++class RoundtripFrameInferenceTests(unittest.TestCase):+ def _check(self, body: str) -> dict:+ with tempfile.TemporaryDirectory() as temporary:+ root = Path(temporary)+ source = root / "source.pptx"+ presentation = Presentation()+ presentation.slides.add_slide(presentation.slide_layouts[6])+ presentation.save(source)+ workspace = root / "workspace"+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):+ convert_pptx_to_svg(source, workspace, ConvertOptions(inheritance_mode="both", roundtrip=True))+ page = workspace / "authoring-svg-flat/slide_01.svg"+ svg = ET.parse(page).getroot()+ additions = ET.fromstring(f'<svg xmlns="{NS["s"]}">{body}</svg>')+ svg.extend(additions)+ page.write_bytes(ET.tostring(svg))+ results = SVGQualityChecker().check_roundtrip_workspace(str(workspace))+ self.assertEqual(len(results), 1)+ return results[0]++ def test_group_bounds_prevent_unrelated_root_decoration_frame(self) -> None:+ result = self._check(+ '<rect id="accent" x="10" y="10" width="5" height="50"/>'+ '<g id="caption" data-pptx-bounds="100 100 400 66" transform="translate(20 10)">'+ '<text x="300" y="140" text-anchor="middle" font-family="Arial" font-size="24">Caption</text></g>'+ )+ findings = result["errors"] + result["warnings"]+ self.assertFalse(any("owning frame" in item for item in findings), findings)++ def test_no_frame_does_not_borrow_ancestor_decoration_or_request_metadata(self) -> None:+ result = self._check(+ '<rect id="accent" x="10" y="10" width="5" height="50"/>'+ '<g id="caption"><g><text x="300" y="140" font-family="Arial" font-size="24">Caption</text></g></g>'+ )+ findings = result["errors"] + result["warnings"]+ self.assertFalse(any("exceeds owning frame" in item for item in findings), findings)+ self.assertTrue(any("Cannot verify owning frame" in item for item in findings), findings)+ self.assertFalse(any("add data-pptx-frame" in item or "keep data-pptx-frame" in item for item in findings))++ def test_group_bounds_still_report_real_overflow(self) -> None:+ result = self._check(+ '<g id="caption" data-pptx-bounds="100 100 10 66">'+ '<text x="100" y="140" font-family="Arial" font-size="24">Long caption</text></g>'+ )+ self.assertTrue(any("exceeds owning frame" in item for item in result["errors"]), result)++ def test_direct_rect_frame_requires_text_anchor_inside(self) -> None:+ result = self._check(+ '<g id="caption"><rect id="accent" x="10" y="10" width="5" height="50"/>'+ '<rect id="frame" x="100" y="100" width="400" height="66"/>'+ '<text x="300" y="140" text-anchor="middle" font-family="Arial" font-size="24">Caption</text></g>'+ )+ self.assertFalse(any("owning frame" in item for item in result["errors"] + result["warnings"]), result)++ def test_real_sibling_frame_overflow_stays_advisory(self) -> None:+ result = self._check(+ '<g id="caption"><rect id="frame" x="100" y="100" width="80" height="66"/>'+ '<text x="110" y="140" font-family="Arial" font-size="24">Long caption text</text></g>'+ )+ self.assertFalse(result["errors"], result)+ self.assertTrue(any('exceeds owning frame <rect id="frame">' in item for item in result["warnings"]), result)+ self.assertFalse(any("add data-pptx-frame" in item for item in result["warnings"]), result)