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: table parity compares runs by effective style; calculator rejects NaN and Infinity; series line_style only passes inside a combo; opaque RGBA may derive JPEG; strict-alpha haze is judged by the key-only margins
hugohe3451c68148e32
diff --git a/skills/ppt-master/scripts/docs/image.md b/skills/ppt-master/scripts/docs/image.mdindex 6db8f609..9039ac9f 100644--- a/skills/ppt-master/scripts/docs/image.md+++ b/skills/ppt-master/scripts/docs/image.md@@ -164,7 +164,9 @@ native SVG/PPT treatments. This tool does not perform semantic backgroundremoval: use `slice_images.py --alpha --bg <key> --strict-alpha` for flat-colorkeys (a pure red/green/blue key also recovers soft alpha and removes spill fromkey-dominant blends, leaving an opaque foreground of the key's hue untouched; thin-dark strokes of that hue can still fringe, so choose the key by hue absence), an+dark strokes of that hue can still fringe, so choose the key by hue absence;+strict alpha diagnoses off-key haze from the four 10% key-only margins, allowing+soft shadows and glows on a clean key), analready prepared RGBA asset or the active host image editor for a standalone cutout, and[`image-generator.md`](../../references/image-generator.md) §4.4 only forregistered subject/base layers.diff --git a/skills/ppt-master/scripts/docs/svg-pipeline.md b/skills/ppt-master/scripts/docs/svg-pipeline.mdindex f31ba990..8ad2fd0b 100644--- a/skills/ppt-master/scripts/docs/svg-pipeline.md+++ b/skills/ppt-master/scripts/docs/svg-pipeline.md@@ -1126,6 +1126,8 @@ standards rather than this pipeline overview.Analyze and review supported chart coordinates after SVG generation.+Numeric parameters and data values must be finite; NaN and either Infinity sign exit non-zero with the offending parameter or data point identified.+Use this after `svg_quality_checker.py` passes, and only for chart types supported by this script: `bar`, `pie` / `donut`, `radar`, `line` / `area` / `scatter`, and `grid`. Area charts do not have a separate calculator mode: use `calc line` for the upper boundary points, then close the filled region to the plot area's bottom baseline (`y_max`) in the SVG.### Calculate expected coordinatesdiff --git a/skills/ppt-master/scripts/image_treat.py b/skills/ppt-master/scripts/image_treat.pyindex 693132c5..0e2ec314 100644--- a/skills/ppt-master/scripts/image_treat.py+++ b/skills/ppt-master/scripts/image_treat.py@@ -321,7 +321,13 @@ def _convert_duotone_source_to_srgb(image: Image.Image) -> tuple[Image.Image, bydef _has_alpha(image: Image.Image) -> bool:- return "A" in image.getbands() or "transparency" in image.info+ if "A" in image.getbands():+ with image.getchannel("A") as alpha:+ return alpha.getextrema()[0] < 255+ if "transparency" in image.info:+ with image.convert("RGBA") as rgba:+ return rgba.getextrema()[3][0] < 255+ return Falsedef _apply_treatments(diff --git a/skills/ppt-master/scripts/slice_images.py b/skills/ppt-master/scripts/slice_images.pyindex 979b8786..95c67cef 100644--- a/skills/ppt-master/scripts/slice_images.py+++ b/skills/ppt-master/scripts/slice_images.py@@ -75,9 +75,8 @@ _KEY_DRIFT_MARGIN = 4_KEY_PURITY_OPAQUE_RATIO = 0.6# At most this many trim pixels on a touched edge count as isolated drift._EDGE_DRIFT_MAX_PIXELS = 8-# Strict-alpha haze gate: when this share of an element's trimmed box sits in-# the semi-transparent alpha band, the key field itself was recovered as soft-# alpha (the sheet ground is not the stated key), not an element edge.+# Semi-transparent coverage nominates a haze candidate; only a failed key-only+# margin can distinguish off-key ground from legitimate shadows and glows._HAZE_ALPHA_LOW = 20_HAZE_ALPHA_HIGH = 150_HAZE_MAX_SHARE = 0.15@@ -215,7 +214,10 @@ def _sample_bg(cell: Image.Image, tolerance: int) -> tuple[int, int, int]:def _sample_sheet_border(sheet: Image.Image,-) -> tuple[tuple[int, int, int], int]:+ *,+ border_ratio: float = _SHEET_DIAGNOSTIC_BORDER_RATIO,+ key: Optional[tuple[int, int, int]] = None,+) -> tuple[tuple[int, int, int], int, int]:"""Return the dominant RGB cluster, its spread, and the ring's farthest pixel.The spread describes the key field itself; the outlier distance is what a@@ -224,8 +226,8 @@ def _sample_sheet_border("""rgb = sheet.convert("RGB")width, height = rgb.size- border_x = max(1, round(width * _SHEET_DIAGNOSTIC_BORDER_RATIO))- border_y = max(1, round(height * _SHEET_DIAGNOSTIC_BORDER_RATIO))+ border_x = max(1, round(width * border_ratio))+ border_y = max(1, round(height * border_ratio))px = rgb.load()pixels: list[tuple[int, int, int]] = []@@ -262,8 +264,9 @@ def _sample_sheet_border(- min(pixel[index] for pixel in dominant_pixels)for index in range(3)]+ measured_key = dominant if key is None else keyoutlier = max(- max(abs(pixel[index] - dominant[index]) for index in range(3))+ max(abs(pixel[index] - measured_key[index]) for index in range(3))for pixel in pixels)return dominant, max(channel_spreads), outlier # type: ignore[return-value]@@ -556,14 +559,17 @@ def _haze_finding(alpha_mask: Image.Image,bbox: tuple[int, int, int, int],bg: tuple[int, int, int],+ *,+ cell: Image.Image,+ tolerance: int,) -> Optional[str]:- """Report an element box that is mostly semi-transparent haze.+ """Report semi-transparent haze only when the key-only margins are off-key.Soft-alpha recovery assumes the key field lies at the stated key; when thereal ground sits farther than the tolerance, the whole field comes back asfaint half-foreground that reads as a glowing rectangle on a dark slide.- `--strict-alpha` only inspects the outer gutter, so this gate looks at the- trimmed box itself.+ A shadow or glow can fill most of the trimmed box. Check all four margins+ at the sheet contract's 10% width before diagnosing the field itself."""box = alpha_mask.crop(bbox)total = box.width * box.height@@ -574,13 +580,21 @@ def _haze_finding(share = hazy / totalif share <= _HAZE_MAX_SHARE:return None+ dominant, spread, distance = _sample_sheet_border(+ cell, border_ratio=0.10, key=bg,+ )+ dominant_distance = max(abs(dominant[index] - bg[index]) for index in range(3))+ if max(dominant_distance, spread, distance) <= tolerance:+ return Nonehex_bg = "#{:02X}{:02X}{:02X}".format(*bg)+ measured_bg = "#{:02X}{:02X}{:02X}".format(*dominant)return (f"{label}: {share:.0%} of the trimmed element box is semi-transparent "- f"(alpha {_HAZE_ALPHA_LOW}-{_HAZE_ALPHA_HIGH}): the key field itself "- f"was recovered as soft alpha, so the sheet ground is not {hex_bg}; "- "rerun with --bg set to the measured ground colour (see the sheet "- "border line below) instead of the nearest pure key"+ f"(alpha {_HAZE_ALPHA_LOW}-{_HAZE_ALPHA_HIGH}) and its four 10% key-only "+ f"margins differ from {hex_bg} (dominant {measured_bg}; key spread "+ f"{spread}; farthest pixel {distance} from key): the ground or an effect "+ "occupies the key-only margin; regenerate with clear margins or rerun "+ "with --bg set to the measured ground colour when it is flat")@@ -822,7 +836,10 @@ def slice_sheet(notices=notices,))if strict_alpha:- haze = _haze_finding(f"cell ({r},{c})", alpha_mask, bbox, cell_bg)+ haze = _haze_finding(+ f"cell ({r},{c})", alpha_mask, bbox, cell_bg,+ cell=cell, tolerance=tolerance,+ )if haze:findings.append(haze)diff --git a/skills/ppt-master/scripts/svg_position_calculator.py b/skills/ppt-master/scripts/svg_position_calculator.pyindex 5cdb2d38..c937a3ab 100644--- a/skills/ppt-master/scripts/svg_position_calculator.py+++ b/skills/ppt-master/scripts/svg_position_calculator.py@@ -955,17 +955,45 @@ class SVGPositionValidator:# Command Line Interface# =============================================================================+class _NonFiniteNumberError(ValueError):+ """Reject a number before it can enter coordinate calculations."""+++def _finite_number(value: Any, location: str) -> float:+ number = float(value)+ if not math.isfinite(number):+ raise _NonFiniteNumberError(+ f"{location} must be finite; replace NaN or Infinity with a finite number: {value!r}"+ )+ return number+++def _validate_finite_json(value: Any, location: str) -> None:+ if isinstance(value, dict):+ for key, item in value.items():+ _validate_finite_json(item, f"{location}.{key}")+ elif isinstance(value, list):+ for index, item in enumerate(value):+ _validate_finite_json(item, f"{location}[{index}]")+ elif isinstance(value, float):+ _finite_number(value, location)++def parse_data_string(data_str: str) -> Dict[str, float]:"""Parse data string in 'label1:value1,label2:value2' format"""result = {}- for item in data_str.split(','):+ for index, item in enumerate(data_str.split(','), start=1):item = item.strip()if not item:continueif ':' in item:label, value = item.split(':', 1)try:- result[label.strip()] = float(value.strip())+ result[label.strip()] = _finite_number(+ value.strip(), f"--data point {index} ({label.strip()!r}) value"+ )+ except _NonFiniteNumberError:+ raiseexcept ValueError:print(f"[Warning] Unable to parse value: '{value.strip()}', skipped")else:@@ -983,7 +1011,8 @@ def parse_xy_data_string(data_str: str) -> List[Tuple[float, float]]:verifier that changes the point count verifies a different chart."""pairs: List[Tuple[str, float]] = []- for item in data_str.split(','):+ numeric_x = []+ for index, item in enumerate(data_str.split(','), start=1):item = item.strip()if not item:continue@@ -991,12 +1020,22 @@ def parse_xy_data_string(data_str: str) -> List[Tuple[float, float]]:raise ValueError(f"Invalid format (expected 'x:y'): '{item}'")x, y = item.rsplit(':', 1)try:- pairs.append((x.strip(), float(y.strip())))+ pairs.append((x.strip(), _finite_number(+ y.strip(), f"--data point {index} ({x.strip()!r}) y"+ )))+ except _NonFiniteNumberError:+ raiseexcept ValueError as exc:raise ValueError(f"Unable to parse value: '{item}'") from exc- try:- return [(float(x), y) for x, y in pairs]- except ValueError:+ try:+ numeric_x.append(_finite_number(x.strip(), f"--data point {index} x"))+ except _NonFiniteNumberError:+ raise+ except ValueError:+ numeric_x.append(None)+ if all(x is not None for x in numeric_x):+ return [(x, y) for x, (_label, y) in zip(numeric_x, pairs)]+ else:print(f"[Note] Category axis: {len(pairs)} labels mapped to ordinals 1..{len(pairs)} ""(pass --x-range=0.5,N+0.5 to centre them in equal slots)"@@ -1004,9 +1043,12 @@ def parse_xy_data_string(data_str: str) -> List[Tuple[float, float]]:return [(float(index), y) for index, (_label, y) in enumerate(pairs, start=1)]-def parse_tuple(s: str) -> Tuple[float, ...]:+def parse_tuple(s: str, location: str = 'tuple') -> Tuple[float, ...]:"""Parse comma-separated numeric tuple"""- return tuple(float(x.strip()) for x in s.split(','))+ return tuple(+ _finite_number(x.strip(), f"{location}[{index}]")+ for index, x in enumerate(s.split(','))+ )def extract_attr(element: str, attr_name: str) -> Optional[str]:@@ -1111,7 +1153,7 @@ def analyze_svg_file(svg_file: str) -> None:print(f"\n{'='*70}")-def interactive_mode() -> None:+def interactive_mode() -> int:"""Interactive calculation mode"""print("\n" + "="*60)print("SVG Position Calculator - Interactive Mode")@@ -1156,9 +1198,9 @@ def interactive_mode() -> None:continuecenter_str = input("Center coordinates [420,400]: ").strip() or '420,400'- radius = float(input("Radius [200]: ").strip() or '200')+ radius = _finite_number(input("Radius [200]: ").strip() or '200', 'radius')- center = parse_tuple(center_str)+ center = parse_tuple(center_str, 'center')calc = PieChartCalculator(center, radius)data = parse_data_string(data_str)slices = calc.calculate(data)@@ -1173,9 +1215,9 @@ def interactive_mode() -> None:continuecenter_str = input("Center coordinates [640,400]: ").strip() or '640,400'- radius = float(input("Radius [200]: ").strip() or '200')+ radius = _finite_number(input("Radius [200]: ").strip() or '200', 'radius')- center = parse_tuple(center_str)+ center = parse_tuple(center_str, 'center')calc = RadarChartCalculator(center, radius)data = parse_data_string(data_str)points = calc.calculate(data)@@ -1194,6 +1236,8 @@ def interactive_mode() -> None:calc = LineChartCalculator(coord)try:data = parse_xy_data_string(data_str)+ except _NonFiniteNumberError:+ raiseexcept ValueError as exc:print(f"[Error] {exc}")continue@@ -1203,8 +1247,12 @@ def interactive_mode() -> None:elif choice == '5':print("\n=== Grid Layout Calculation ===")- rows = int(input("Rows: ").strip() or '2')- cols = int(input("Columns: ").strip() or '3')+ rows_input = input("Rows: ").strip() or '2'+ _finite_number(rows_input, 'rows')+ rows = int(rows_input)+ cols_input = input("Columns: ").strip() or '3'+ _finite_number(cols_input, 'cols')+ cols = int(cols_input)canvas = input("Canvas format [ppt169]: ").strip() or 'ppt169'coord = CoordinateSystem(canvas)@@ -1217,18 +1265,18 @@ def interactive_mode() -> None:print("\n=== Custom Line Calculation ===")print("For custom formula line charts, such as price index charts")- base_x = float(input("X start value [170]: ").strip() or '170')- step_x = float(input("X step [40]: ").strip() or '40')- base_y = float(input("Y baseline [595]: ").strip() or '595')- scale_y = float(input("Y scale factor [20]: ").strip() or '20')- ref_value = float(input("Reference baseline value [100]: ").strip() or '100')+ base_x = _finite_number(input("X start value [170]: ").strip() or '170', 'base_x')+ step_x = _finite_number(input("X step [40]: ").strip() or '40', 'step_x')+ base_y = _finite_number(input("Y baseline [595]: ").strip() or '595', 'base_y')+ scale_y = _finite_number(input("Y scale factor [20]: ").strip() or '20', 'scale_y')+ ref_value = _finite_number(input("Reference baseline value [100]: ").strip() or '100', 'ref_value')print(f"\nFormula: X = {base_x} + index * {step_x}")print(f" Y = {base_y} - (value - {ref_value}) * {scale_y}")data_str = input("\nEnter data (comma-separated values): ").strip()if data_str:- values = [float(v.strip()) for v in data_str.split(',')]+ values = parse_tuple(data_str, 'data')print(f"\n{'Index':<6}{'Value':<10} {'X':<8} {'Y':<8}")print("-" * 35)for i, v in enumerate(values, 1):@@ -1251,9 +1299,14 @@ def interactive_mode() -> None:except KeyboardInterrupt:print("\nExiting interactive mode")break+ except _NonFiniteNumberError as exc:+ print(f"[Error] {exc}", file=sys.stderr)+ return 1except Exception as e:print(f"Error: {e}")+ return 0+def from_json_config(config_file: str) -> None:"""Read and calculate from JSON config file"""@@ -1266,6 +1319,7 @@ def from_json_config(config_file: str) -> None:with open(config_path, 'r', encoding='utf-8') as f:config = json.load(f)+ _validate_finite_json(config, 'config')chart_type = config.get('type', 'bar')data = config.get('data', {})@@ -1420,27 +1474,38 @@ Common commands:args = parser.parse_args(argv)+ try:+ for name, value in vars(args).items():+ if isinstance(value, float):+ _finite_number(value, f"--{name.replace('_', '-')}")+ for name in ('area', 'center', 'value_range', 'x_range', 'y_range'):+ value = getattr(args, name, None)+ if value is not None:+ setattr(args, name, parse_tuple(value, f"--{name.replace('_', '-')}"))+ if args.command == 'calc' and hasattr(args, 'data'):+ parse_data = parse_xy_data_string if args.chart_type == 'line' else parse_data_string+ args.data = parse_data(args.data)+ except ValueError as exc:+ parser.error(str(exc))+if args.command == 'calc':# Parse chart areachart_area = Noneif hasattr(args, 'area') and args.area:- parts = parse_tuple(args.area)+ parts = args.areachart_area = ChartArea(parts[0], parts[1], parts[2], parts[3])if args.chart_type == 'bar':canvas = args.canvas if hasattr(args, 'canvas') else 'ppt169'coord = CoordinateSystem(canvas, chart_area)calc = BarChartCalculator(coord)- data = parse_data_string(args.data)+ data = args.data# Parse value-range from axis tick labels (if provided)v_min, v_max = 0, Nonescale_source = 'auto (max*1.1)'if hasattr(args, 'value_range') and args.value_range:- try:- vr = parse_tuple(args.value_range)- except ValueError:- parser.error('calc bar --value-range must be numeric "min,max"')+ vr = args.value_rangeif len(vr) != 2:parser.error('calc bar --value-range must contain exactly two values: "min,max"')v_min, v_max = vr[0], vr[1]@@ -1471,18 +1536,18 @@ Common commands:print(calc.format_table(positions))elif args.chart_type == 'pie':- center = parse_tuple(args.center)+ center = args.centercalc = PieChartCalculator(center, args.radius)- data = parse_data_string(args.data)+ data = args.dataslices = calc.calculate(data, start_angle=args.start_angle, inner_radius=args.inner_radius)print(f"\n=== Pie Chart Slice Calculation ===")print(calc.format_table(slices))elif args.chart_type == 'radar':- center = parse_tuple(args.center)+ center = args.centercalc = RadarChartCalculator(center, args.radius)- data = parse_data_string(args.data)+ data = args.datapoints = calc.calculate(data, max_value=args.max_value)print(f"\n=== Radar Chart Vertex Calculation ===")@@ -1492,13 +1557,9 @@ Common commands:canvas = args.canvas if hasattr(args, 'canvas') else 'ppt169'coord = CoordinateSystem(canvas, chart_area)calc = LineChartCalculator(coord)- try:- data = parse_xy_data_string(args.data)- except ValueError as exc:- parser.error(f'calc line --data: {exc}')-- x_range = parse_tuple(args.x_range) if args.x_range else None- y_range = parse_tuple(args.y_range) if args.y_range else None+ data = args.data+ x_range = args.x_range+ y_range = args.y_rangepoints = calc.calculate(data, x_range, y_range)if getattr(args, 'slot_midpoints', False):@@ -1548,6 +1609,10 @@ Common commands:return 1with open(expected_path, 'r', encoding='utf-8') as f:expected_coords = json.load(f)+ try:+ _validate_finite_json(expected_coords, '--expected')+ except _NonFiniteNumberError as exc:+ parser.error(str(exc))results = validator.validate_from_file(args.svg_file, expected_coords)print(validator.format_results(results))else:@@ -1558,10 +1623,13 @@ Common commands:analyze_svg_file(args.svg_file)elif args.command == 'interactive':- interactive_mode()+ return interactive_mode()elif args.command == 'from-json':- from_json_config(args.config_file)+ try:+ from_json_config(args.config_file)+ except _NonFiniteNumberError as exc:+ parser.error(str(exc))else:parser.print_help()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 b64d0ce9..cb37a1ff 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@@ -879,6 +879,7 @@ def _category_series(*,chart_type: str,grouping: str | None,+ typed_combo: bool = False,) -> list[dict[str, Any]]:raw_series = payload.get("series", [])if not categories or not isinstance(raw_series, list) or not raw_series:@@ -896,7 +897,7 @@ def _category_series(raise RuntimeError("Native PPTX chart series entries must be objects")if (_first_present(item.get("line_style"), item.get("lineStyle")) is not None- and not (item.get("type") or item.get("chart_type"))+ and not typed_combo):raise RuntimeError("Native PPTX chart series[].line_style is not a series option; "@@ -1267,6 +1268,7 @@ def _combo_chart_data(payload: dict[str, Any]) -> dict[str, Any]:categories,chart_type=typed_chart_type,grouping=typed_grouping,+ typed_combo=True,)plot = _combo_plot_entry(item,diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.pyindex 0eb72564..361e3776 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/marker_common.py@@ -91,6 +91,13 @@ class _FallbackShapeRecord:fill_opacity: float | None = None+@dataclass(frozen=True)+class _FallbackTextRun:+ text: str+ fill: str | None+ bold: bool++@dataclass(frozen=True)class _FallbackTextRecord:text: str@@ -100,6 +107,7 @@ class _FallbackTextRecord:bold: boolanchor: strlabels: tuple[str, ...]+ runs: tuple[_FallbackTextRun, ...] = ()def _local_tag(elem: ET.Element) -> str:@@ -647,23 +655,37 @@ def fallback_text_inheritance(values: dict[str, str]) -> Iterator[None]:_FALLBACK_TEXT_INHERITANCE.reset(token)+def _fallback_text_bold(weight: str | None) -> bool:+ raw_weight = str(weight or "").strip().lower()+ numeric_weight = _maybe_number(raw_weight)+ return raw_weight in {"bold", "bolder"} or (+ numeric_weight is not None and numeric_weight >= 600+ )++def _dominant_text_style(elem: ET.Element,fill: str | None,weight: str | None,+ *,+ runs: list[_FallbackTextRun] | None = None,) -> tuple[str | None, str | None]:"""Return the fill and weight carried by most visible characters."""counts: dict[tuple[str | None, str | None], int] = {}+ def add_text(text: str, node_fill: str | None, node_weight: str | None) -> None:+ key = (node_fill, node_weight)+ counts[key] = counts.get(key, 0) + len("".join(text.split()))+ if text and runs is not None:+ runs.append(_FallbackTextRun(text, _hex_or_none(node_fill), _fallback_text_bold(node_weight)))+def visit(node: ET.Element, node_fill: str | None, node_weight: str | None) -> None:node_fill = _style_attr(node, "fill") or node_fillnode_weight = _style_attr(node, "font-weight") or node_weight- key = (node_fill, node_weight)- counts[key] = counts.get(key, 0) + len("".join((node.text or "").split()))+ add_text(node.text or "", node_fill, node_weight)for child in node:visit(child, node_fill, node_weight)- tail = len("".join((child.tail or "").split()))- counts[key] = counts.get(key, 0) + tail+ add_text(child.tail or "", node_fill, node_weight)visit(elem, fill, weight)return max(counts, key=counts.get) if any(counts.values()) else (fill, weight)@@ -714,25 +736,22 @@ def _fallback_text_records(# A <text> whose visible characters mostly sit in styled <tspan>s# reads in their paint and weight (a whole cell set in an emphasis# tspan is that colour, not the <text> default).- fill, weight = _dominant_text_style(elem, fill, weight)+ runs: list[_FallbackTextRun] = []+ fill, weight = _dominant_text_style(elem, fill, weight, runs=runs)x = _project_geometry_number(elem, "x") if elem.get("x") is not None else Noney = _project_geometry_number(elem, "y") if elem.get("y") is not None else Noneif x is not None and y is not None:x, y = transform_point(local_matrix, x, y)- raw_weight = str(weight or "").strip().lower()- numeric_weight = _maybe_number(raw_weight)- bold = raw_weight in {"bold", "bolder"} or (- numeric_weight is not None and numeric_weight >= 600- )return [_FallbackTextRecord(text=text,x=x,y=y,fill=_hex_or_none(fill),- bold=bold,+ bold=_fallback_text_bold(weight),anchor=str(anchor or "start").strip().lower(),labels=labels,+ runs=tuple(runs),)]diff --git a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.pyindex 97c55f92..a98a108e 100644--- a/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py+++ b/skills/ppt-master/scripts/svg_to_pptx/native_objects/table.py@@ -24,6 +24,7 @@ from ..drawingml.utils import (from .chart_style import _fallback_text_attr_values, _font_face_xml, _most_common_valuefrom .marker_common import (TABLE_URI,+ _FallbackTextRecord,_bool_attr,_bounds,_clean_hex,@@ -857,6 +858,76 @@ def _table_cell_parity_text_style(return bold, color+def _table_cell_parity_style_gaps(+ cell: Any,+ record: _FallbackTextRecord,+ default_color: str | None = None,+ occurrence: int = 0,+) -> tuple[bool, set[str]]:+ """Compare corresponding visible characters using each run's effective style."""+ cell_data = _cell_payload(cell)+ paragraphs = _table_cell_paragraphs(cell_data)+ if paragraphs is None:+ paragraphs = (_TableParagraph(str(cell_data.get("text") or "")),)+ # A fallback <text> can contain the whole cell or just one paragraph.+ joined_texts = {+ _normalized_fallback_text(separator.join(paragraph.text for paragraph in paragraphs))+ for separator in ("", " ")+ }+ if record.text not in joined_texts:+ matches = tuple(+ paragraph for paragraph in paragraphs+ if _normalized_fallback_text(paragraph.text) == record.text+ )+ paragraphs = matches[occurrence:occurrence + 1]+ cell_bold, cell_color = _table_cell_parity_text_style(cell_data)+ cell_color = cell_color or default_color+ native_styles = [+ (+ run.bold if run.bold is not None else cell_bold,+ run.color or cell_color,+ )+ for paragraph in paragraphs+ for run in (paragraph.runs or (_TableRun(paragraph.text),))+ for character in run.text+ if not character.isspace()+ ]+ fallback_styles = [+ (run.bold, run.fill)+ for run in record.runs+ for character in run.text+ if not character.isspace()+ ]+ missing_bold = False+ missing_colors: set[str] = set()+ for index, (bold, color) in enumerate(fallback_styles):+ native_bold, native_color = (+ native_styles[index] if index < len(native_styles) else (None, None)+ )+ if bold and native_bold is not True:+ missing_bold = True+ if color is not None and color != native_color:+ missing_colors.add(color)+ return missing_bold, missing_colors+++def _table_parity_style_gaps(+ table_rows: list[list[Any]],+ text_cells: list[tuple[Any, int, int]],+ default_color: str | None,+):+ """Pair repeated paragraph text with its occurrence inside the same cell."""+ occurrences: dict[tuple[int, int, str], int] = {}+ for record, row_idx, col_idx in text_cells:+ key = (row_idx, col_idx, record.text)+ occurrence = occurrences.get(key, 0)+ occurrences[key] = occurrence + 1+ bold, colors = _table_cell_parity_style_gaps(+ table_rows[row_idx][col_idx], record, default_color, occurrence+ )+ yield record, row_idx, col_idx, bold, colors++def _table_text_cells(text_records: list[Any],table_rows: list[list[Any]],@@ -931,25 +1002,15 @@ def _native_table_header_warnings():missing.append("style.header_fill")- header_colors = [record.fill for record, _, _ in header_text_cells if record.fill]- header_text_color = max(set(header_colors), key=header_colors.count) if header_colors else None- if header_text_color is not None and style.get("header_text") is None:- if not all(- _table_cell_parity_text_style(- table_rows[row_idx][col_idx]- )[1] == record.fill- for record, row_idx, col_idx in header_text_cells- if record.fill is not None- ):- missing.append("style.header_text")-- if any(- record.bold- and _table_cell_parity_text_style(- table_rows[row_idx][col_idx]- )[0] is not True- for record, row_idx, col_idx in header_text_cells- ):+ header_text = _clean_hex(+ style.get("header_text"),+ "#FFFFFF" if _hex_or_none(style.get("header_fill")) is not None+ else _clean_hex(style.get("body_text"), "#1F2937"),+ )+ header_style_gaps = list(_table_parity_style_gaps(table_rows, header_text_cells, header_text))+ if any(colors for _, _, _, _, colors in header_style_gaps):+ missing.append("style.header_text")+ if any(bold for _, _, _, bold, _ in header_style_gaps):missing.append("columns[].bold")# Header cells export centred unless the payload sets align, so a missing# align only matches a fallback whose header text is centred.@@ -1064,23 +1125,13 @@ def _native_table_body_text_warnings(body_records = [item for item in text_cells if item[1] >= header_rows]if not body_records:return []- body_colors = [- record.fill- for record, _, col_idx in body_records- if col_idx != 0 and record.fill- ]- body_color = max(set(body_colors), key=body_colors.count) if body_colors else Nonemissing_colors: set[str] = set()- for record, row_idx, col_idx in body_records:- if record.fill is None:- continue- if col_idx == 0 and record.fill != body_color:+ for record, _, col_idx, _, colors in _table_parity_style_gaps(+ table_rows, body_records, style_body_text+ ):+ if col_idx == 0:continue # first-column emphasis is reported separately- cell_color = _table_cell_parity_text_style(table_rows[row_idx][col_idx])[1]- if cell_color is None:- cell_color = style_body_text- if cell_color != record.fill:- missing_colors.add(record.fill)+ missing_colors.update(colors)if not missing_colors:return []return [@@ -1107,32 +1158,14 @@ def _native_table_first_column_warnings(first_column = [item for item in body_records if item[2] == 0]if not first_column:return []- body_colors = [- record.fill- for record, _, col_idx in body_records- if col_idx != 0 and record.fill- ]- body_color = max(set(body_colors), key=body_colors.count) if body_colors else Nonemissing: list[str] = []- if any(- record.bold- and _table_cell_parity_text_style(- table_rows[row_idx][col_idx]- )[0] is not True- for record, row_idx, col_idx in first_column- ):+ first_column_style_gaps = list(_table_parity_style_gaps(table_rows, first_column, style_body_text))+ if any(bold for _, _, _, bold, _ in first_column_style_gaps):missing.append("bold")missing_colors = sorted({- record.fill- for record, row_idx, col_idx in first_column- if (- record.fill is not None- and record.fill != body_color- and (- _table_cell_parity_text_style(table_rows[row_idx][col_idx])[1]- or style_body_text- ) != record.fill- )+ color+ for _, _, _, _, colors in first_column_style_gaps+ for color in colors})if missing_colors:missing.append("color " + "/".join(f"#{color}" for color in missing_colors))diff --git a/skills/ppt-master/scripts/tests/test_audit_r3_native_images.py b/skills/ppt-master/scripts/tests/test_audit_r3_native_images.pynew file mode 100644index 00000000..7bc06c3e--- /dev/null+++ b/skills/ppt-master/scripts/tests/test_audit_r3_native_images.py@@ -0,0 +1,515 @@+"""Regressions for round-three native object, calculator, and image findings."""++from __future__ import annotations++import contextlib+import io+import json+import math+import sys+import tempfile+import unittest+from pathlib import Path+from unittest import mock+from xml.etree import ElementTree as ET++from PIL import Image, ImageDraw++SCRIPTS_DIR = Path(__file__).resolve().parents[1]+if str(SCRIPTS_DIR) not in sys.path:+ sys.path.insert(0, str(SCRIPTS_DIR))++import image_treat # noqa: E402+import slice_images # noqa: E402+import svg_position_calculator as position_calculator # noqa: E402+from svg_to_pptx.native_objects.chart_data import _chart_data # noqa: E402+from svg_to_pptx.native_objects.chart_xml import _chart_xml # noqa: E402+++class OpaqueImageDerivativeTests(unittest.TestCase):+ def _derive(self, image: Image.Image, *, transparent: bool) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ project = Path(tmp)+ images = project / "images"+ images.mkdir()+ source = images / "source.png"+ image.save(source)+ original = source.read_bytes()+ output = images / "derived.jpg"+ stdout, stderr = io.StringIO(), io.StringIO()+ with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):+ result = image_treat.main([+ str(project), source.name, "--output", output.name, "--fit", "64x40",+ ])+ self.assertEqual(source.read_bytes(), original)+ self.assertEqual(result, 1 if transparent else 0, stderr.getvalue())+ if transparent:+ self.assertFalse(output.exists())+ self.assertIn("JPEG output cannot hold the source's transparency", stderr.getvalue())+ self.assertEqual(sorted(p.name for p in images.iterdir()), [source.name])+ else:+ with Image.open(output) as derivative:+ self.assertEqual(derivative.format, "JPEG")+ self.assertEqual(derivative.mode, "RGB")+ self.assertEqual(derivative.size, (64, 40))++ def test_rgb_and_opaque_alpha_modes_allow_jpeg(self) -> None:+ for mode, color in (("RGB", (30, 80, 120)), ("RGBA", (30, 80, 120, 255)), ("LA", (80, 255))):+ with self.subTest(mode=mode), Image.new(mode, (128, 80), color) as image:+ self._derive(image, transparent=False)++ def test_actual_alpha_pixels_refuse_jpeg_without_output(self) -> None:+ for mode, color in (("RGBA", (30, 80, 120, 255)), ("LA", (80, 255))):+ for alpha in (0, 254):+ with self.subTest(mode=mode, alpha=alpha), Image.new(mode, (128, 80), color) as image:+ image.putpixel((64, 40), (*color[:-1], alpha))+ self._derive(image, transparent=True)++ def test_palette_transparency_depends_on_used_pixels(self) -> None:+ for transparency in (1, bytes([255, 0] + [255] * 254), bytes([255, 254] + [255] * 254)):+ for used in (False, True):+ with self.subTest(transparency=repr(transparency)[:32], used=used):+ with Image.new("P", (128, 80), 0) as image:+ image.putpalette([30, 80, 120, 80, 120, 160] + [0] * 762)+ image.info["transparency"] = transparency+ if used:+ image.putpixel((64, 40), 1)+ self._derive(image, transparent=used)+++class ChartSeriesLineStyleTests(unittest.TestCase):+ def _marker_symbols(self, payload: dict) -> list[str]:+ marker = ET.fromstring('<g xmlns="http://www.w3.org/2000/svg" id="chart"/>')+ xml = _chart_xml(+ marker, payload, chart_rels_id="rId1", chart_data=_chart_data(payload),+ chart_bounds=(0, 0, 12192000, 6858000),+ )+ root = ET.fromstring(xml)+ ns = {"c": "http://schemas.openxmlformats.org/drawingml/2006/chart"}+ return [node.get("val") for node in root.findall(".//c:marker/c:symbol", ns)]++ def test_non_combo_typed_series_cannot_bypass_line_style_rejection(self) -> None:+ for type_field in (None, "type", "chart_type"):+ for style_field in ("line_style", "lineStyle"):+ with self.subTest(type_field=type_field, style_field=style_field):+ series = {"name": "S", "values": [1, 2], style_field: "lineMarker"}+ if type_field:+ series[type_field] = "line"+ with self.assertRaises(RuntimeError) as caught:+ _chart_data({"type": "line", "categories": ["A", "B"], "series": [series]})+ self.assertEqual(+ str(caught.exception),+ "Native PPTX chart series[].line_style is not a series option; "+ "set line_style on the chart root (combo: on the plot or typed series)",+ )++ def test_typed_combo_line_markers_survive_normalization_and_xml(self) -> None:+ for type_field in ("type", "chart_type"):+ for style_field in ("line_style", "lineStyle"):+ with self.subTest(type_field=type_field, style_field=style_field):+ payload = {+ "type": "combo", "categories": ["A", "B"],+ "series": [+ {type_field: "column", "name": "C", "values": [1, 2]},+ {type_field: "line", "name": "L", "values": [2, 3], style_field: "lineMarker"},+ ],+ }+ self.assertEqual(_chart_data(payload)["plots"][1]["line_style"], "lineMarker")+ symbols = self._marker_symbols(payload)+ self.assertTrue(symbols)+ self.assertNotIn("none", symbols)++ def test_root_and_combo_plot_line_markers_remain_supported(self) -> None:+ line = {+ "type": "line", "line_style": "lineMarker", "categories": ["A", "B"],+ "series": [{"name": "S", "values": [1, 2]}],+ }+ combo = {"type": "combo", "categories": ["A", "B"], "plots": [line]}+ for payload in (line, combo):+ with self.subTest(chart_type=payload["type"]):+ symbols = self._marker_symbols(payload)+ self.assertTrue(symbols)+ self.assertNotIn("none", symbols)+++class StrictAlphaMarginRegressionTests(unittest.TestCase):+ def test_a13_pure_key_soft_shadow_and_glow_preserve_partial_alpha(self) -> None:+ for key in ((255, 0, 0), (0, 255, 0), (0, 0, 255)):+ for foreground in ((0, 0, 0), (255, 255, 255)):+ with self.subTest(key=key, foreground=foreground), tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ sheet = Image.new("RGB", (120, 120), key)+ for y in range(120):+ for x in range(120):+ distance = math.hypot(x - 60, y - 60)+ alpha = 255 if distance < 9 else round(128 * max(0, 32 - distance) / 23)+ pixel = tuple(round((base * (255 - alpha) + color * alpha) / 255)+ for base, color in zip(key, foreground))+ sheet.putpixel((x, y), pixel)+ source = root / "sheet.png"+ sheet.save(source)+ expected = slice_images.slice_sheet(+ source, 1, 1, root / "normal", trim=True, alpha=True, bg=key,+ )+ actual = slice_images.slice_sheet(+ source, 1, 1, root / "strict", trim=True, alpha=True,+ strict_alpha=True, bg=key,+ )+ with Image.open(expected[0]) as normal, Image.open(actual[0]) as strict:+ self.assertEqual(strict.size, normal.size)+ self.assertEqual(strict.tobytes(), normal.tobytes())+ histogram = strict.getchannel("A").histogram()+ self.assertGreater(sum(histogram[20:151]) / (strict.width * strict.height), 0.15)+ self.assertGreater(histogram[255], 0)++ def test_a13_off_key_ground_and_inner_margin_haze_fail_without_output(self) -> None:+ for fault in ("off_key_ground", "inner_margin_noise"):+ with self.subTest(fault=fault), tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ key = (0, 0, 255)+ sheet = Image.new("RGB", (120, 120), key)+ draw = ImageDraw.Draw(sheet)+ if fault == "off_key_ground":+ draw.rectangle((0, 0, 119, 119), fill=(3, 74, 244))+ else:+ # All four outer 1% edges are pure; the required 10%+ # margins contain haze well beyond the key tolerance.+ draw.rectangle((4, 4, 115, 115), fill=(0, 0, 180))+ draw.rectangle((50, 50, 70, 70), fill=(255, 255, 255))+ source = root / "sheet.png"+ sheet.save(source)+ output = root / "output"+ stderr = io.StringIO()+ with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(stderr):+ result = slice_images.main([+ str(source), "--grid", "1x1", "--names", "element",+ "--trim", "--alpha", "--strict-alpha", "--bg", "#0000FF",+ "--tolerance", "62", "--output", str(output),+ ])+ self.assertEqual(result, 1)+ self.assertIn("four 10% key-only margins", stderr.getvalue())+ self.assertIn("measured ground colour", stderr.getvalue())+ self.assertFalse((output / "element.png").exists())+++class CalculatorFiniteInputTests(unittest.TestCase):+ def _run_calculator(self, argv):+ stdout, stderr = io.StringIO(), io.StringIO()+ with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):+ try:+ code = position_calculator.main(argv)+ except SystemExit as exc:+ code = exc.code+ return code, stdout.getvalue(), stderr.getvalue()++ def test_nonfinite_scalar_parameters_fail_before_calculation(self):+ cases = (+ ('bar', '--bar-width', ['--data', 'A:10,B:20']),+ ('bar', '--gap-width', ['--data', 'A:10,B:20']),+ ('pie', '--radius', ['--data', 'A:10,B:20']),+ ('pie', '--inner-radius', ['--data', 'A:10,B:20']),+ ('pie', '--start-angle', ['--data', 'A:10,B:20']),+ ('radar', '--radius', ['--data', 'A:10,B:20,C:30']),+ ('radar', '--max-value', ['--data', 'A:10,B:20,C:30']),+ ('grid', '--padding', ['--rows', '2', '--cols', '3']),+ ('grid', '--gap', ['--rows', '2', '--cols', '3']),+ )+ for value in ('NaN', 'Infinity', '-Infinity'):+ for chart, option, required in cases:+ with self.subTest(chart=chart, option=option, value=value):+ code, stdout, stderr = self._run_calculator(+ ['calc', chart, *required, f'{option}={value}']+ )+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn(option, stderr)+ self.assertIn('must be finite', stderr)+ with self.subTest(command='validate', value=value):+ code, stdout, stderr = self._run_calculator(+ ['validate', 'unused.svg', '--extract', f'--tolerance={value}']+ )+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn('--tolerance must be finite', stderr)++ def test_nonfinite_tuple_parameters_identify_component(self):+ cases = (+ ('bar', '--area', ['--data', 'A:10,B:20'], '0,0,{},100', 2),+ ('bar', '--value-range', ['--data', 'A:10,B:20'], '0,{}', 1),+ ('pie', '--center', ['--data', 'A:10,B:20'], '{},100', 0),+ ('radar', '--center', ['--data', 'A:10,B:20,C:30'], '100,{}', 1),+ ('line', '--area', ['--data', 'A:10,B:20'], '0,{},100,100', 1),+ ('line', '--x-range', ['--data', 'A:10,B:20'], '0,{}', 1),+ ('line', '--y-range', ['--data', 'A:10,B:20'], '0,{}', 1),+ ('grid', '--area', ['--rows', '2', '--cols', '3'], '0,0,100,{}', 3),+ )+ for value in ('NaN', 'Infinity', '-Infinity'):+ for chart, option, required, template, index in cases:+ with self.subTest(chart=chart, option=option, value=value):+ code, stdout, stderr = self._run_calculator(+ ['calc', chart, *required, f'{option}={template.format(value)}']+ )+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn(f'{option}[{index}] must be finite', stderr)++ def test_nonfinite_data_identifies_point_without_category_fallback(self):+ for value in ('NaN', 'Infinity', '-Infinity'):+ for chart in ('bar', 'pie', 'radar', 'line'):+ with self.subTest(chart=chart, value=value):+ code, stdout, stderr = self._run_calculator(+ ['calc', chart, '--data', f'A:10,B:{value},C:30']+ )+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn("--data point 2 ('B')", stderr)+ self.assertIn('must be finite', stderr)+ for data in (f'1:10,{value}:20', f'A:10,{value}:20'):+ with self.subTest(data=data):+ code, stdout, stderr = self._run_calculator(['calc', 'line', '--data', data])+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn('--data point 2 x must be finite', stderr)++ def test_finite_inputs_preserve_gap_boundaries_and_chart_modes(self):+ cases = [+ ['calc', 'bar', '--data', 'A:10,B:20', '--gap-width=0'],+ ['calc', 'bar', '--data', 'A:10,B:20', '--gap-width=150', '--horizontal'],+ ['calc', 'pie', '--data', 'A:10,B:20', '--center=100,100', '--radius=50'],+ ['calc', 'radar', '--data', 'A:10,B:20,C:30', '--max-value=40'],+ ['calc', 'line', '--data', 'A:10,B:20', '--slot-midpoints'],+ ['calc', 'line', '--data', '0:10,1:20', '--x-range=0,1', '--y-range=0,30'],+ ['calc', 'grid', '--rows=2', '--cols=3', '--padding=0', '--gap=10'],+ ]+ for argv in cases:+ with self.subTest(argv=argv):+ code, stdout, stderr = self._run_calculator(argv)+ self.assertEqual(code, 0, stderr)+ self.assertTrue(stdout)+ self.assertNotRegex(stdout.lower(), r'\b(?:nan|inf|infinity)\b')++ def test_nonfinite_json_config_and_expected_coordinates_identify_path(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp)+ config_file = root / 'config.json'+ expected_file = root / 'expected.json'+ svg_file = root / 'chart.svg'+ svg_file.write_text('<svg><rect id="bar_a" x="0" y="10"/></svg>', encoding='utf-8')+ for value in (float('nan'), float('inf'), float('-inf')):+ configs = (+ ({'type': 'bar', 'data': {'A': value}}, 'config.data.A'),+ ({'type': 'pie', 'data': {'A': 10}, 'radius': value}, 'config.radius'),+ ({'type': 'line', 'data': [[1, 10], [2, value]]}, 'config.data[1][1]'),+ ({'type': 'custom_line', 'values': [10, value]}, 'config.values[1]'),+ )+ for config, location in configs:+ with self.subTest(config=config):+ config_file.write_text(json.dumps(config), encoding='utf-8')+ code, stdout, stderr = self._run_calculator(['from-json', str(config_file)])+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn(f'{location} must be finite', stderr)+ expected_file.write_text(json.dumps({'bar_a': {'x': value}}), encoding='utf-8')+ code, stdout, stderr = self._run_calculator(+ ['validate', str(svg_file), '--expected', str(expected_file)]+ )+ self.assertNotEqual(code, 0)+ self.assertEqual(stdout, '')+ self.assertIn('--expected.bar_a.x must be finite', stderr)++ def test_interactive_nonfinite_values_exit_nonzero(self):+ for answers, location in (+ (['1', 'A:nan', ''], '--data point 1'),+ (['2', 'A:10', '', 'inf'], 'radius'),+ (['3', 'A:10,B:20,C:30', '100,-Infinity', ''], 'center[1]'),+ (['4', 'A:10,B:nan', ''], '--data point 2'),+ (['5', 'nan'], 'rows'),+ (['6', '-inf'], 'base_x'),+ ):+ with self.subTest(answers=answers), mock.patch('builtins.input', side_effect=answers):+ code, stdout, stderr = self._run_calculator(['interactive'])+ self.assertNotEqual(code, 0)+ self.assertIn(location, stderr)+ self.assertIn('must be finite', stderr)+++class NativeTableMixedRunAuditTests(unittest.TestCase):+ def _table_svg(self, red_text: str, *, mismatch: str = "", column: int = 0,+ header: bool = False, split_runs: bool = False) -> str:+ import json+ from xml.etree import ElementTree as ET++ first_run = {"text": "AAA", "color": "#000000", "bold": False}+ red_run = {"text": red_text, "color": "#FF0000", "bold": True}+ if mismatch == "bold":+ red_run["bold"] = False+ elif mismatch == "color":+ red_run["color"] = "#000000"+ elif mismatch == "swapped":+ first_run.update(color="#FF0000", bold=True)+ red_run.update(color="#000000", bold=False)+ runs = [first_run, red_run]+ if split_runs:+ runs = [{**first_run, "text": "A"}, {**first_run, "text": "AA"}, red_run]+ cell = {+ "color": "#000000", "bold": False, "align": "l",+ "paragraphs": [{"runs": runs}],+ }+ row = [cell, {"text": "OTHER", "color": "#000000", "align": "l"}]+ if column == 1:+ row.reverse()+ payload = {+ "schema": "ppt-master.semantic-table.v2",+ "x": 100, "y": 100, "width": 600, "height": 100,+ "header_rows": 1 if header else 0,+ "column_widths": [1, 1],+ "style": {"body_text": "#000000", "font_family": "Arial", "font_size": 20},+ "rows": [row],+ }+ root = ET.fromstring(+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720">'+ '<g id="table" data-pptx-replace-with="table">'+ '<metadata type="application/json"/>'+ '<rect x="100" y="100" width="600" height="100" fill="none" stroke="#000000"/>'+ '<line x1="400" y1="100" x2="400" y2="200" stroke="#000000"/>'+ f'<text x="{115 + 300 * column}" y="150" fill="#000000" font-size="20" font-family="Arial">'+ f'AAA<tspan fill="#FF0000" font-weight="bold">{red_text}</tspan></text>'+ f'<text x="{415 - 300 * column}" y="150" fill="#000000" font-size="20" '+ 'font-family="Arial">OTHER</text>'+ '</g></svg>'+ )+ root[0][0].text = json.dumps(payload)+ return ET.tostring(root, encoding="unicode")++ def _table_pipeline(self, project: Path, svg: str):+ import subprocess+ import sys++ scripts = Path(__file__).resolve().parents[1]+ output = project / "native.pptx"+ svg_dir = project / "svg_output"+ svg_dir.mkdir(parents=True)+ (svg_dir / "01.svg").write_text(svg, encoding="utf-8")+ commands = [+ ["stamp_native_fallbacks.py", str(svg_dir), "--write"],+ ["svg_quality_checker.py", str(project), "--canonical-authoring", "--stage", "final",+ "--json", "--quick-generate"],+ ["svg_to_pptx.py", str(project), "--quick-generate", "--native-charts-and-tables",+ "-o", str(output)],+ ]+ results = []+ for script, *arguments in commands:+ result = subprocess.run(+ [sys.executable, "-B", str(scripts / script), *arguments],+ capture_output=True, text=True, check=False,+ )+ results.append(result)+ for result in results[:2]:+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ return output, results[-1]++ def test_a06_mixed_runs_pass_stamp_checker_and_native_export_at_any_length(self) -> None:+ import tempfile+ import zipfile+ from xml.etree import ElementTree as ET++ ns = {"a": "http://schemas.openxmlformats.org/drawingml/2006/main"}+ with tempfile.TemporaryDirectory() as tmp:+ for length in (1, 10):+ with self.subTest(length=length):+ red_text = "B" * length+ output, result = self._table_pipeline(+ Path(tmp) / str(length), self._table_svg(red_text)+ )+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ with zipfile.ZipFile(output) as package:+ slide = ET.fromstring(package.read("ppt/slides/slide1.xml"))+ cell = slide.find(".//a:tbl/a:tr/a:tc", ns)+ self.assertIsNotNone(cell)+ actual = [+ (run.find("a:t", ns).text, run.find("a:rPr", ns).get("b"),+ run.find("a:rPr/a:solidFill/a:srgbClr", ns).get("val"))+ for run in cell.findall(".//a:r", ns)+ ]+ self.assertEqual(actual, [("AAA", "0", "000000"), (red_text, "1", "FF0000")])++ def test_a06_missing_minority_bold_or_color_still_blocks_native_export(self) -> None:+ import tempfile++ with tempfile.TemporaryDirectory() as tmp:+ for mismatch in ("bold", "color", "swapped"):+ with self.subTest(mismatch=mismatch):+ output, result = self._table_pipeline(+ Path(tmp) / mismatch, self._table_svg("B", mismatch=mismatch)+ )+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn("not projected", result.stdout + result.stderr)+ self.assertFalse(output.exists())++ def test_a06_header_and_body_run_parity_share_effective_styles(self) -> None:+ from xml.etree import ElementTree as ET+ from svg_to_pptx.native_objects import native_object_projection_warnings++ for header, column in ((True, 0), (False, 1)):+ for length in (1, 10):+ with self.subTest(header=header, column=column, length=length):+ root = ET.fromstring(self._table_svg(+ "B" * length, header=header, column=column, split_runs=True+ ))+ warnings = native_object_projection_warnings(root[0], document_root=root)+ self.assertEqual(warnings, [])+ root = ET.fromstring(self._table_svg(+ "B" * length, header=header, column=column, mismatch="color"+ ))+ warnings = native_object_projection_warnings(root[0], document_root=root)+ self.assertTrue(any("not projected" in warning for warning in warnings), warnings)++ def test_a06_repeated_paragraph_text_matches_each_style_occurrence(self) -> None:+ from xml.etree import ElementTree as ET+ from svg_to_pptx.native_objects import native_object_projection_warnings++ root = ET.fromstring(self._table_svg("B"))+ marker = root[0]+ payload = json.loads(marker[0].text)+ payload["rows"][0][0]["paragraphs"] = [+ {"runs": [{"text": "SAME", "color": "#000000", "bold": False}]},+ {"runs": [{"text": "SAME", "color": "#FF0000", "bold": True}]},+ ]+ marker[0].text = json.dumps(payload)+ first_text = marker[3]+ first_text.remove(first_text[0])+ first_text.text = "SAME"+ second_text = ET.SubElement(marker, first_text.tag, {+ **first_text.attrib, "y": "175", "fill": "#FF0000", "font-weight": "bold",+ })+ second_text.text = "SAME"+ self.assertEqual(native_object_projection_warnings(marker, document_root=root), [])+ payload["rows"][0][0]["paragraphs"][1]["runs"][0]["color"] = "#000000"+ marker[0].text = json.dumps(payload)+ warnings = native_object_projection_warnings(marker, document_root=root)+ self.assertTrue(any("color #FF0000" in warning for warning in warnings), warnings)+ payload["rows"][0][0]["paragraphs"][1]["runs"][0]["color"] = "#FF0000"+ payload["rows"][0][0]["paragraphs"][0]["runs"][0]["color"] = "#FF0000"+ marker[0].text = json.dumps(payload)+ warnings = native_object_projection_warnings(marker, document_root=root)+ self.assertTrue(any("color #000000" in warning for warning in warnings), warnings)++ def test_a06_header_text_keeps_exported_body_color_defaults(self) -> None:+ from xml.etree import ElementTree as ET+ from svg_to_pptx.native_objects import native_object_projection_warnings++ for body_color in (None, "#123456"):+ with self.subTest(body_color=body_color):+ root = ET.fromstring(self._table_svg("B", header=True))+ marker = root[0]+ payload = json.loads(marker[0].text)+ payload["rows"] = [[{"text": "AAA", "align": "l"}, {"text": "OTHER", "align": "l"}]]+ if body_color is None:+ payload["style"].pop("body_text")+ else:+ payload["style"]["body_text"] = body_color+ marker[0].text = json.dumps(payload)+ marker[3].remove(marker[3][0])+ marker[3].set("fill", body_color or "#1F2937")+ marker[4].set("fill", body_color or "#1F2937")+ self.assertEqual(native_object_projection_warnings(marker, document_root=root), [])