Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(scripts): re-stamp native baselines after update_spec, judge merged-cell blanks as authored, and add width arithmetic to text-overflow diagnostics

hugohe33e2002d0baf1
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
index 5c633800..fcce0ec5 100644
--- a/skills/ppt-master/scripts/image_search.py
+++ b/skills/ppt-master/scripts/image_search.py
@@ -441,6 +441,7 @@ def _stage_and_validate_image(
min_width: int,
min_height: int,
enforce_thumbnail_floor: bool = True,
+ metadata_dimensions: Optional[tuple[int, int]] = None,
) -> tuple[Path, tuple[int, int]]:
"""Materialize and validate beside the target without changing the canonical."""
output_path.parent.mkdir(parents=True, exist_ok=True)
@@ -460,8 +461,28 @@ def _stage_and_validate_image(
min_height=min_height,
enforce_thumbnail_floor=enforce_thumbnail_floor,
):
+ actual_dimensions = _measure_actual_image(temp_path)
+ if actual_dimensions is None:
+ measured = "measured dimensions unavailable (file unreadable)"
+ else:
+ measured = (
+ f"measured {actual_dimensions[0]}x{actual_dimensions[1]}"
+ )
+ details = [
+ measured,
+ f"required minimum {min_width}x{min_height}",
+ ]
+ if (
+ metadata_dimensions is not None
+ and metadata_dimensions != actual_dimensions
+ ):
+ details.append(
+ "metadata claimed "
+ f"{metadata_dimensions[0]}x{metadata_dimensions[1]}"
+ )
raise DownloadQualityError(
- "downloaded image did not satisfy the requested dimensions/readability"
+ "downloaded image did not satisfy the requested "
+ f"dimensions/readability: {'; '.join(details)}"
)
actual_dimensions = _measure_actual_image(temp_path)
if actual_dimensions is None:
@@ -485,6 +506,7 @@ def _stage_validated_image(
min_width: int,
min_height: int,
enforce_thumbnail_floor: bool = True,
+ metadata_dimensions: Optional[tuple[int, int]] = None,
) -> tuple[Path, tuple[int, int]]:
"""Download and validate beside the target without changing the canonical."""
return _stage_and_validate_image(
@@ -497,6 +519,7 @@ def _stage_validated_image(
min_width=min_width,
min_height=min_height,
enforce_thumbnail_floor=enforce_thumbnail_floor,
+ metadata_dimensions=metadata_dimensions,
)
@@ -507,6 +530,7 @@ def _stage_validated_candidate_copy(
min_width: int,
min_height: int,
enforce_thumbnail_floor: bool = True,
+ metadata_dimensions: Optional[tuple[int, int]] = None,
) -> tuple[Path, tuple[int, int]]:
"""Stage a saved pool candidate, preserving target-extension correctness."""
return _stage_and_validate_image(
@@ -518,6 +542,7 @@ def _stage_validated_candidate_copy(
min_width=min_width,
min_height=min_height,
enforce_thumbnail_floor=enforce_thumbnail_floor,
+ metadata_dimensions=metadata_dimensions,
)
@@ -1389,6 +1414,12 @@ def promote_candidate(
)
return 1
+ metadata_dimensions = (
+ (selected_candidate.width, selected_candidate.height)
+ if selected_candidate.width > 0 and selected_candidate.height > 0
+ else None
+ )
+
staged_path: Optional[Path] = None
try:
legacy_src_path = cand_dir / candidate_filename
@@ -1401,6 +1432,7 @@ def promote_candidate(
dst_path,
min_width=min_width,
min_height=min_height,
+ metadata_dimensions=metadata_dimensions,
)
else:
staged_path, actual_dimensions = _stage_validated_image(
@@ -1408,6 +1440,7 @@ def promote_candidate(
dst_path,
min_width=min_width,
min_height=min_height,
+ metadata_dimensions=metadata_dimensions,
)
item_args = argparse.Namespace(
diff --git a/skills/ppt-master/scripts/stamp_native_fallbacks.py b/skills/ppt-master/scripts/stamp_native_fallbacks.py
index de07068e..39249a7f 100644
--- a/skills/ppt-master/scripts/stamp_native_fallbacks.py
+++ b/skills/ppt-master/scripts/stamp_native_fallbacks.py
@@ -146,7 +146,7 @@ def _patch_document(
source: bytes,
root: ET.Element,
digests: dict[ET.Element, str],
-) -> bytes:
+) -> tuple[bytes, int]:
elements = list(root.iter())
spans = _start_tag_spans(source)
if len(elements) != len(spans):
@@ -171,7 +171,7 @@ def _patch_document(
patched = source
for start, end, replacement in reversed(patches):
patched = patched[:start] + replacement + patched[end:]
- return patched
+ return patched, len(patches)
def _validated_svg_first_digests(
@@ -246,16 +246,25 @@ def _atomic_write(path: Path, payload: bytes) -> None:
temporary_path.unlink()
-def _prepare_file(path: Path) -> tuple[bytes, int, int, bool]:
- source = path.read_bytes()
+def prepare_native_fallback_baselines(
+ source: bytes,
+ path: Path,
+) -> tuple[bytes, int, int, int]:
+ """Validate and plan fallback baselines for one in-memory SVG document."""
try:
root = ET.fromstring(source)
except ET.ParseError as exc:
raise NativeFallbackStampError(f"{path.name}: invalid SVG XML: {exc}") from exc
digests, json_authoritative = _validated_svg_first_digests(root, path)
- patched = _patch_document(source, root, digests)
- changed = patched != source
- return patched, len(digests), json_authoritative, changed
+ patched, restamped = _patch_document(source, root, digests)
+ return patched, len(digests), json_authoritative, restamped
+
+
+def _prepare_file(path: Path) -> tuple[bytes, int, int, bool]:
+ patched, svg_first, json_authoritative, restamped = (
+ prepare_native_fallback_baselines(path.read_bytes(), path)
+ )
+ return patched, svg_first, json_authoritative, restamped > 0
def stamp_file(path: Path, *, write: bool) -> tuple[int, int, bool]:
diff --git a/skills/ppt-master/scripts/svg_quality/checker.py b/skills/ppt-master/scripts/svg_quality/checker.py
index 54d94f0b..923f68d5 100644
--- a/skills/ppt-master/scripts/svg_quality/checker.py
+++ b/skills/ppt-master/scripts/svg_quality/checker.py
@@ -93,6 +93,7 @@ try:
PROJECT_PAINT_PROPERTIES as _PAINT_PROPERTIES,
PROJECT_TEXT_IMAGE_FILL_ATTR as _TEXT_IMAGE_FILL_ATTR,
detect_text_lang as _detect_text_lang,
+ is_cjk_char as _is_cjk_char,
matrix_multiply as _matrix_multiply,
parse_inline_style as _parse_inline_style,
parse_project_geometry_length as _parse_project_geometry_length,
@@ -102,6 +103,7 @@ try:
parse_transform_matrix as _parse_transform_matrix,
project_mask_errors as _project_mask_errors,
rect_to_dml_xfrm as _rect_to_dml_xfrm,
+ split_project_text_clusters as _split_project_text_clusters,
transform_point as _transform_point,
unsafe_exported_font_faces as _unsafe_exported_font_faces,
validate_dml_shape_matrix as _validate_dml_shape_matrix,
@@ -111,6 +113,7 @@ except ImportError:
_PAINT_PROPERTIES = None
_TEXT_IMAGE_FILL_ATTR = 'data-pptx-text-image-fill'
_detect_text_lang = None
+ _is_cjk_char = None
_matrix_multiply = None
_parse_inline_style = None
_parse_project_geometry_length = None
@@ -120,6 +123,7 @@ except ImportError:
_parse_transform_matrix = None
_project_mask_errors = None
_rect_to_dml_xfrm = None
+ _split_project_text_clusters = None
_transform_point = None
_unsafe_exported_font_faces = None
_validate_dml_shape_matrix = None
@@ -3279,16 +3283,14 @@ class SVGQualityChecker:
)
@classmethod
- def _estimated_text_bounds(
+ def _resolved_text_lines(
cls,
text_el: ET.Element,
parent_by_id: Dict[int, ET.Element],
font_sizes: Dict[int, float],
letter_spacings: Dict[int, float],
- *,
- include_headroom: bool = True,
- ) -> Tuple[float, float, float, float] | None:
- """Estimate one single- or multi-line text carrier's visual bounds."""
+ ) -> List[Tuple[ET.Element, float, float, List[Dict], float]] | None:
+ """Resolve one text carrier into the lines used by width estimation."""
lines: List[Tuple[ET.Element, float, float, List[Dict], float]] | None
try:
runs = cls._resolved_single_line_text_runs(
@@ -3317,7 +3319,26 @@ class SVGQualityChecker:
font_sizes,
letter_spacings,
)
- if not lines:
+ return lines or None
+
+ @classmethod
+ def _estimated_text_bounds(
+ cls,
+ text_el: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ font_sizes: Dict[int, float],
+ letter_spacings: Dict[int, float],
+ *,
+ include_headroom: bool = True,
+ ) -> Tuple[float, float, float, float] | None:
+ """Estimate one single- or multi-line text carrier's visual bounds."""
+ lines = cls._resolved_text_lines(
+ text_el,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ if lines is None:
return None
bounds = [
@@ -3434,6 +3455,114 @@ class SVGQualityChecker:
return None
return rendered_w, rendered_h
+ @classmethod
+ def _text_width_diagnostic(
+ cls,
+ text_element: ET.Element,
+ parent_by_id: Dict[int, ET.Element],
+ font_sizes: Dict[int, float],
+ letter_spacings: Dict[int, float],
+ *,
+ container_width: float,
+ include_headroom: bool,
+ ) -> str | None:
+ """Summarize the overflowing line's effective per-cluster width."""
+ if (
+ _estimate_single_line_text_frame_width is None
+ or _is_cjk_char is None
+ or _split_project_text_clusters is None
+ or not math.isfinite(container_width)
+ or container_width <= 0
+ ):
+ return None
+ lines = cls._resolved_text_lines(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ )
+ if lines is None:
+ return None
+
+ widest: Tuple[float, List[str], float] | None = None
+ for line_element, _x, _y, runs, _font_size in lines:
+ clusters: List[str] = []
+ weighted_font_size = 0.0
+ try:
+ for run in runs:
+ run_clusters = [
+ cluster
+ for cluster in _split_project_text_clusters(
+ str(run.get('text', ''))
+ )
+ if not cluster.isspace()
+ ]
+ run_font_size = float(run['font_size'])
+ clusters.extend(run_clusters)
+ weighted_font_size += run_font_size * len(run_clusters)
+ raw_width = float(_estimate_single_line_text_frame_width(
+ runs,
+ include_headroom=include_headroom,
+ ))
+ except (KeyError, TypeError, ValueError):
+ continue
+ if not clusters or not math.isfinite(raw_width) or raw_width <= 0:
+ continue
+ transformed = cls._transformed_rect_edge_lengths(
+ line_element,
+ (0.0, 0.0, raw_width, 1.0),
+ parent_by_id,
+ )
+ rendered_width = transformed[0] if transformed is not None else raw_width
+ if not math.isfinite(rendered_width) or rendered_width <= 0:
+ continue
+ rendered_font_size = (
+ weighted_font_size
+ / len(clusters)
+ * rendered_width
+ / raw_width
+ )
+ if widest is None or rendered_width > widest[0]:
+ widest = rendered_width, clusters, rendered_font_size
+
+ if widest is None:
+ return None
+ rendered_width, clusters, rendered_font_size = widest
+ per_cluster = rendered_width / len(clusters)
+ if not math.isfinite(per_cluster) or per_cluster <= 0:
+ return None
+
+ cjk_clusters = [
+ any(_is_cjk_char(ch) for ch in cluster)
+ for cluster in clusters
+ ]
+ if all(cjk_clusters):
+ cluster_label = 'CJK char'
+ elif not any(cjk_clusters) and all(
+ all(ord(ch) < 128 for ch in cluster)
+ for cluster in clusters
+ ):
+ cluster_label = 'Latin char'
+ else:
+ cluster_label = 'mixed char'
+
+ font_size = (
+ f'{rendered_font_size:.0f}'
+ if math.isclose(rendered_font_size, round(rendered_font_size), abs_tol=0.05)
+ else f'{rendered_font_size:.1f}'
+ )
+ width = (
+ f'{container_width:.0f}'
+ if math.isclose(container_width, round(container_width), abs_tol=0.05)
+ else f'{container_width:.1f}'
+ )
+ headroom = 'incl. headroom' if include_headroom else 'without headroom'
+ fits = max(0, math.floor(container_width / per_cluster))
+ return (
+ f'≈{per_cluster:.1f} px per {cluster_label} at {font_size}px '
+ f'{headroom}; ≈{fits} chars fit in {width} px'
+ )
+
@staticmethod
def _resolved_root_module_bounds(
group: ET.Element,
@@ -3565,6 +3694,7 @@ class SVGQualityChecker:
container: str,
outer: Tuple[float, float, float, float],
repair: str,
+ width_diagnostic: str | None = None,
) -> None:
"""Record a warning through 5% overflow and an error above it."""
metrics = cls._bounds_overflow_metrics(inner, outer)
@@ -3588,6 +3718,11 @@ class SVGQualityChecker:
)
left, top, right, bottom = inner
outer_left, outer_top, outer_right, outer_bottom = outer
+ width_suffix = (
+ f'; {width_diagnostic}'
+ if horizontal_ratio > 0 and width_diagnostic
+ else ''
+ )
bucket.append(
f'{subject} exceeds {container} on the {axes} axis: '
f'content ({left:.1f}, {top:.1f})-({right:.1f}, '
@@ -3595,7 +3730,7 @@ class SVGQualityChecker:
f'{outer_top:.1f})-({outer_right:.1f}, '
f'{outer_bottom:.1f}), overflow horizontal '
f'{horizontal_ratio:.1%}, vertical {vertical_ratio:.1%}; '
- f'{repair}'
+ f'{repair}{width_suffix}'
)
@classmethod
@@ -3606,6 +3741,7 @@ class SVGQualityChecker:
subject: str,
inner: Tuple[float, float, float, float],
canvas: Tuple[float, float, float, float],
+ width_diagnostic: str | None = None,
) -> bool:
"""Record one page-boundary error and return whether it overflowed."""
metrics = cls._bounds_overflow_metrics(inner, canvas)
@@ -3614,6 +3750,11 @@ class SVGQualityChecker:
axes, horizontal_ratio, vertical_ratio = metrics
left, top, right, bottom = inner
canvas_left, canvas_top, canvas_right, canvas_bottom = canvas
+ width_suffix = (
+ f'; {width_diagnostic}'
+ if horizontal_ratio > 0 and width_diagnostic
+ else ''
+ )
result['errors'].append(
f'{subject} exceeds the root viewBox on the {axes} axis: '
f'content ({left:.1f}, {top:.1f})-({right:.1f}, '
@@ -3622,6 +3763,7 @@ class SVGQualityChecker:
f'{canvas_bottom:.1f}), overflow horizontal '
f'{horizontal_ratio:.1%}, vertical {vertical_ratio:.1%}; '
'move or reflow the text until its estimated bounds stay on-page'
+ f'{width_suffix}'
)
return True
@@ -4070,6 +4212,14 @@ class SVGQualityChecker:
subject=self._text_diagnostic_label(text_element),
inner=page_estimated,
canvas=canvas,
+ width_diagnostic=self._text_width_diagnostic(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ container_width=canvas[2] - canvas[0],
+ include_headroom=False,
+ ),
)
):
page_overflow_text_ids.add(id(text_element))
@@ -4117,6 +4267,14 @@ class SVGQualityChecker:
'expand the root module bounds into available '
'non-overlapping space; otherwise reflow the text'
),
+ width_diagnostic=self._text_width_diagnostic(
+ text_element,
+ parent_by_id,
+ font_sizes,
+ letter_spacings,
+ container_width=boundary[2] - boundary[0],
+ include_headroom=True,
+ ),
)
def _check_unmergeable_leading_text(self, root: ET.Element, result: Dict) -> None:
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.py
index 6aaf62c2..bfa7a84f 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
@@ -439,36 +439,14 @@ def _merge_covered_cell_is_blank(value: Any) -> bool:
return True
if not isinstance(value, dict):
return False
- if value.get("merge_continuation") is not True:
- if any(key != "text" for key in value):
- return False
- text = value.get("text")
- if text not in {None, ""}:
+ if set(value) - {"merge_continuation", "text"}:
return False
- paragraphs = value.get("paragraphs")
- if paragraphs is None:
- return True
- if not isinstance(paragraphs, list):
+ if (
+ "merge_continuation" in value
+ and value["merge_continuation"] is not True
+ ):
return False
- for paragraph in paragraphs:
- if isinstance(paragraph, str):
- if paragraph:
- return False
- continue
- if not isinstance(paragraph, dict):
- return False
- if paragraph.get("text") not in {None, ""}:
- return False
- runs = paragraph.get("runs")
- if runs is not None and (
- not isinstance(runs, list)
- or any(
- not isinstance(run, dict) or run.get("text") not in {None, ""}
- for run in runs
- )
- ):
- return False
- return True
+ return value.get("text") in {None, ""}
def _resolve_table_merge_layout(
@@ -648,12 +626,20 @@ def _validate_table_payload(
int,
dict[tuple[int, int], _TableMergeRegion],
]:
+ authored_payload = payload
+ authored_rows = _table_rows(authored_payload)
payload = expand_semantic_table_payload(payload)
table_rows = _table_rows(payload)
col_count = _validate_table_lengths(payload, table_rows)
for row in table_rows:
row.extend([""] * (col_count - len(row)))
- merge_layout = _resolve_table_merge_layout(payload, table_rows, col_count)
+ for row in authored_rows:
+ row.extend([""] * (col_count - len(row)))
+ merge_layout = _resolve_table_merge_layout(
+ authored_payload,
+ authored_rows,
+ col_count,
+ )
_table_header_rows(payload, len(table_rows))
_validate_table_cell_formatting(payload, table_rows)
return payload, table_rows, col_count, merge_layout
diff --git a/skills/ppt-master/scripts/tests/test_image_search.py b/skills/ppt-master/scripts/tests/test_image_search.py
new file mode 100644
index 00000000..933f8be9
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_image_search.py
@@ -0,0 +1,93 @@
+#!/usr/bin/env python3
+"""Regression tests for image-search candidate promotion."""
+
+from __future__ import annotations
+
+import io
+import json
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stderr
+from pathlib import Path
+from unittest.mock import patch
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+import image_search # noqa: E402
+
+
+class ImageSearchPromotionTests(unittest.TestCase):
+ def test_quality_failure_reports_actual_required_and_metadata_dimensions(
+ self,
+ ) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ output_dir = Path(temp_dir) / "images"
+ candidate_dir = output_dir / "candidates" / "hero"
+ candidate_dir.mkdir(parents=True)
+ candidates_path = candidate_dir / "candidates.json"
+ candidates_path.write_text(
+ json.dumps({
+ "candidate_storage": "thumbnail-only",
+ "target_filename": "hero.jpg",
+ "request": {
+ "min_width": 1200,
+ "min_height": 800,
+ },
+ "candidates": [{
+ "filename": "candidate_01.jpg",
+ "provider": "pixabay",
+ "width": 4836,
+ "height": 2915,
+ "download_url": "https://example.invalid/original.jpg",
+ }],
+ }),
+ encoding="utf-8",
+ )
+
+ def fake_download(_url: str, destination: str, **_kwargs) -> None:
+ Path(destination).write_bytes(b"fake downloaded image")
+
+ stderr = io.StringIO()
+ with (
+ patch.object(
+ image_search,
+ "download_image",
+ side_effect=fake_download,
+ ),
+ patch.object(
+ image_search,
+ "_validate_downloaded_quality",
+ return_value=False,
+ ),
+ patch.object(
+ image_search,
+ "_measure_actual_image",
+ return_value=(1280, 772),
+ ),
+ redirect_stderr(stderr),
+ ):
+ result = image_search.promote_candidate(
+ output_dir,
+ "hero.jpg",
+ "candidate_01.jpg",
+ )
+
+ self.assertEqual(result, 1)
+ message = stderr.getvalue()
+ self.assertIn("candidate promotion failed", message)
+ self.assertIn("measured 1280x772", message)
+ self.assertIn("required minimum 1200x800", message)
+ self.assertIn("metadata claimed 4836x2915", message)
+ self.assertFalse((output_dir / "hero.jpg").exists())
+ self.assertNotIn(
+ "selected",
+ json.loads(candidates_path.read_text(encoding="utf-8")),
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py b/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py
index bc93c6a2..632abc47 100644
--- a/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py
+++ b/skills/ppt-master/scripts/tests/test_native_chart_table_parity.py
@@ -23,6 +23,7 @@ from svg_to_pptx.native_objects import ( # noqa: E402
from svg_to_pptx.native_objects.table import ( # noqa: E402
_table_border_specs,
_table_border_xml,
+ _validate_table_payload,
)
from svg_to_pptx.pptx_package.cli import ( # noqa: E402
_native_object_projection_findings,
@@ -84,6 +85,48 @@ class NativeTableBorderTests(unittest.TestCase):
self.assertIn("lnBlToTr", border_xml)
+class NativeTableMergeTests(unittest.TestCase):
+ @staticmethod
+ def _payload(covered_cell: dict) -> dict:
+ return {
+ "schema": "ppt-master.semantic-table.v2",
+ "defaults": {
+ "cell": {
+ "color": "#1F2937",
+ "fill": "#FFFFFF",
+ "padding": {"left": 8, "right": 8},
+ "valign": "middle",
+ },
+ },
+ "rows": [[
+ {"text": "Owner", "col_span": 2},
+ covered_cell,
+ ]],
+ }
+
+ def test_merge_blankness_uses_authored_cells_before_defaults(self) -> None:
+ for covered_cell in (
+ {},
+ {"text": ""},
+ {"merge_continuation": True},
+ ):
+ with self.subTest(covered_cell=covered_cell):
+ _payload, rows, col_count, merge_layout = (
+ _validate_table_payload(self._payload(covered_cell))
+ )
+ self.assertEqual((len(rows), col_count), (1, 2))
+ self.assertIn((0, 1), merge_layout)
+
+ for covered_cell in (
+ {"text": "authored"},
+ {"paragraphs": [{"text": ""}]},
+ {"fill": "#F1F4F8"},
+ ):
+ with self.subTest(covered_cell=covered_cell):
+ with self.assertRaisesRegex(RuntimeError, "must be blank"):
+ _validate_table_payload(self._payload(covered_cell))
+
+
class NativeChartExTests(unittest.TestCase):
@staticmethod
def _chart_data(chart_type: str) -> dict:
diff --git a/skills/ppt-master/scripts/tests/test_svg_quality_checker.py b/skills/ppt-master/scripts/tests/test_svg_quality_checker.py
index 7e2f34be..006c3782 100644
--- a/skills/ppt-master/scripts/tests/test_svg_quality_checker.py
+++ b/skills/ppt-master/scripts/tests/test_svg_quality_checker.py
@@ -21,9 +21,13 @@ from svg_quality.checker import SVGQualityChecker # noqa: E402
SVG_NS = 'http://www.w3.org/2000/svg'
-def _parse_svg(body: str, root_attributes: str = '') -> ET.Element:
+def _parse_svg(
+ body: str,
+ root_attributes: str = '',
+ view_box: str = '0 0 1000 1000',
+) -> ET.Element:
return ET.fromstring(
- f'<svg xmlns="{SVG_NS}" viewBox="0 0 1000 1000" '
+ f'<svg xmlns="{SVG_NS}" viewBox="{view_box}" '
f'{root_attributes}>{body}</svg>'
)
@@ -160,6 +164,51 @@ class SVGQualityCheckerBoundsTests(unittest.TestCase):
any('root viewBox' in error for error in result['errors'])
)
+ def test_horizontal_overflow_reports_per_cluster_width_and_capacity(
+ self,
+ ) -> None:
+ cjk_text = '天地玄黄宇宙洪荒日月盈昃辰宿列张寒来暑往秋收冬藏'
+ module_root = _parse_svg(
+ '<g id="module" data-pptx-bounds="0 0 540 100">'
+ f'<text x="0" y="30" font-size="24">{cjk_text}</text>'
+ '</g>'
+ )
+ module_result = _empty_result()
+ SVGQualityChecker()._check_text_bounds(module_root, module_result)
+ module_error = next(
+ error
+ for error in module_result['errors']
+ if 'data-pptx-bounds on the horizontal axis' in error
+ )
+ self.assertTrue(
+ module_error.endswith(
+ '≈25.4 px per CJK char at 24px incl. headroom; '
+ '≈21 chars fit in 540 px'
+ ),
+ module_error,
+ )
+
+ page_root = _parse_svg(
+ '<g id="module" data-pptx-bounds="0 0 1000 100">'
+ f'<text x="0" y="30" font-size="24">{cjk_text}</text>'
+ '</g>',
+ view_box='0 0 540 100',
+ )
+ page_result = _empty_result()
+ SVGQualityChecker()._check_text_bounds(page_root, page_result)
+ page_error = next(
+ error
+ for error in page_result['errors']
+ if 'exceeds the root viewBox on the horizontal axis' in error
+ )
+ self.assertTrue(
+ page_error.endswith(
+ '≈24.0 px per CJK char at 24px without headroom; '
+ '≈22 chars fit in 540 px'
+ ),
+ page_error,
+ )
+
def test_root_module_overlap_is_error_with_minimal_exemptions(self) -> None:
cases = (
(
diff --git a/skills/ppt-master/scripts/tests/test_update_spec.py b/skills/ppt-master/scripts/tests/test_update_spec.py
new file mode 100644
index 00000000..38d73c07
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_update_spec.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python3
+"""End-to-end regression tests for synchronized spec and SVG updates."""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+import sys
+import tempfile
+import unittest
+from pathlib import Path
+
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+
+from stamp_native_fallbacks import stamp_file # noqa: E402
+
+
+UPDATE_SPEC = SCRIPTS_DIR / "update_spec.py"
+SVG_CHECKER = SCRIPTS_DIR / "svg_quality_checker.py"
+FALLBACK_HASH_RE = re.compile(r'data-pptx-fallback-sha256="([0-9a-f]{64})"')
+
+
+class UpdateSpecNativeFallbackTests(unittest.TestCase):
+ def _copy_minimal_project(self, root: Path) -> Path:
+ fixture = root / "fixture"
+ svg_dir = fixture / "svg_output"
+ svg_dir.mkdir(parents=True)
+ (fixture / "spec_lock.md").write_text(
+ """<!-- ppt-master-schema: spec-lock/v1 -->
+# Execution Lock
+
+## canvas
+- viewBox: 0 0 1280 720
+- format: PPT 16:9
+
+## colors
+- background: #FFFFFF
+- accent: #B23A2A
+- body_text: #1F2937
+
+## typography
+- font_family: Microsoft YaHei
+- body: 24
+- title: 36
+
+## pptx_structure
+- mode: flat
+""",
+ encoding="utf-8",
+ )
+ svg_path = svg_dir / "01_native_table.svg"
+ svg_path.write_text(
+ """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720"
+ data-pptx-page-role="content" font-family="Microsoft YaHei">
+ <rect id="background" data-pptx-role="background" x="0" y="0" width="1280" height="720" fill="#FFFFFF"/>
+ <g id="accent-table" data-pptx-replace-with="table" data-pptx-bounds="100 100 300 80">
+ <metadata type="application/json">{
+ "schema": "ppt-master.semantic-table.v2",
+ "name": "accent-table",
+ "x": 100, "y": 100, "width": 300, "height": 80,
+ "header_rows": 0,
+ "column_widths": [300],
+ "row_heights": [80],
+ "style": {
+ "font_family": "Microsoft YaHei",
+ "font_size": 24,
+ "band_row": false,
+ "border_color": "#B23A2A",
+ "border_width": 1
+ },
+ "rows": [[{"text": "Accent", "color": "#B23A2A"}]]
+ }</metadata>
+ <rect x="100" y="100" width="300" height="80" fill="#FFFFFF" stroke="#B23A2A"/>
+ <text x="120" y="150" font-size="24" fill="#B23A2A">Accent</text>
+ </g>
+</svg>
+""",
+ encoding="utf-8",
+ )
+ svg_first, json_first, changed = stamp_file(svg_path, write=True)
+ self.assertEqual((svg_first, json_first, changed), (1, 0, True))
+
+ project = root / "project"
+ shutil.copytree(fixture, project)
+ return project
+
+ def test_update_restamps_touched_native_fallback_and_checker_passes(
+ self,
+ ) -> None:
+ with tempfile.TemporaryDirectory() as temp_dir:
+ project = self._copy_minimal_project(Path(temp_dir))
+ lock_path = project / "spec_lock.md"
+ svg_path = project / "svg_output" / "01_native_table.svg"
+ original_lock = lock_path.read_bytes()
+ original_svg = svg_path.read_bytes()
+ original_hash = FALLBACK_HASH_RE.search(
+ original_svg.decode("utf-8")
+ )
+ self.assertIsNotNone(original_hash)
+
+ dry_run = subprocess.run(
+ [
+ sys.executable,
+ str(UPDATE_SPEC),
+ str(project),
+ "colors.accent=#8C2F1F",
+ "--dry-run",
+ ],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(dry_run.returncode, 0, dry_run.stderr)
+ self.assertIn(
+ "[dry-run] native fallbacks: 1 marker(s) would be re-stamped",
+ dry_run.stdout,
+ )
+ self.assertEqual(lock_path.read_bytes(), original_lock)
+ self.assertEqual(svg_path.read_bytes(), original_svg)
+
+ update = subprocess.run(
+ [
+ sys.executable,
+ str(UPDATE_SPEC),
+ str(project),
+ "colors.accent=#8C2F1F",
+ ],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(update.returncode, 0, update.stderr)
+ self.assertIn(
+ "native fallbacks: 1 marker(s) re-stamped",
+ update.stdout,
+ )
+ updated_svg = svg_path.read_text(encoding="utf-8")
+ self.assertNotIn("#B23A2A", updated_svg)
+ self.assertIn("#8C2F1F", updated_svg)
+ updated_hash = FALLBACK_HASH_RE.search(updated_svg)
+ self.assertIsNotNone(updated_hash)
+ self.assertNotEqual(original_hash.group(1), updated_hash.group(1))
+
+ checker = subprocess.run(
+ [
+ sys.executable,
+ str(SVG_CHECKER),
+ str(svg_path),
+ "--canonical-authoring",
+ "--stage",
+ "final",
+ ],
+ check=False,
+ capture_output=True,
+ text=True,
+ )
+ self.assertEqual(
+ checker.returncode,
+ 0,
+ checker.stdout + checker.stderr,
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/ppt-master/scripts/update_spec.py b/skills/ppt-master/scripts/update_spec.py
index ac73c903..5dc5b147 100755
--- a/skills/ppt-master/scripts/update_spec.py
+++ b/skills/ppt-master/scripts/update_spec.py
@@ -34,6 +34,10 @@ from pathlib import Path
from console_encoding import configure_utf8_stdio
from project_management.project_specs import parse_spec_lock as parse_lock
+from stamp_native_fallbacks import (
+ NativeFallbackStampError,
+ prepare_native_fallback_baselines,
+)
configure_utf8_stdio()
@@ -127,6 +131,21 @@ def _plan_font_family_updates(
return planned
+def _plan_native_fallback_updates(
+ planned: list[tuple[Path, str, int]],
+) -> tuple[list[tuple[Path, str, int]], int]:
+ """Re-stamp changed SVG text in memory before the joint publish."""
+ stamped: list[tuple[Path, str, int]] = []
+ restamped_markers = 0
+ for path, text, replacement_count in planned:
+ payload, _svg_first, _json_first, restamped = (
+ prepare_native_fallback_baselines(text.encode("utf-8"), path)
+ )
+ stamped.append((path, payload.decode("utf-8"), replacement_count))
+ restamped_markers += restamped
+ return stamped, restamped_markers
+
+
def _publish_text_updates(updates: list[tuple[Path, str]]) -> None:
"""Publish existing text files as one rollback unit."""
if not updates:
@@ -315,23 +334,7 @@ def main() -> int:
print(f"error: {exc}", file=sys.stderr)
return 2
planned_svg = _plan_color_updates(svg_dir, old_value, new_value)
- changed = [
- (path, count)
- for path, _text, count in planned_svg
- ]
lock_changes = [(key, old_value, new_value)]
- if not args.dry_run:
- try:
- _publish_text_updates([
- *(
- (path, new_text)
- for path, new_text, _count in planned_svg
- ),
- (lock, planned_lock),
- ])
- except (OSError, RuntimeError, ValueError) as exc:
- print(f"error: update was not published: {exc}", file=sys.stderr)
- return 2
elif section == "typography" and key == "font_family":
family_keys = [
name
@@ -353,25 +356,9 @@ def main() -> int:
{name: new_value for name in family_keys},
)
planned_svg = _plan_font_family_updates(svg_dir, new_value)
- changed = [
- (path, count)
- for path, _text, count in planned_svg
- ]
except (KeyError, ValueError) as e:
print(f"error: {e}", file=sys.stderr)
return 2
- if not args.dry_run:
- try:
- _publish_text_updates([
- *(
- (path, new_text)
- for path, new_text, _count in planned_svg
- ),
- (lock, planned_lock),
- ])
- except (OSError, RuntimeError, ValueError) as exc:
- print(f"error: update was not published: {exc}", file=sys.stderr)
- return 2
else:
print(
f"error: {section}.{key} is not supported by update_spec.py.\n"
@@ -381,6 +368,29 @@ def main() -> int:
)
return 2
+ try:
+ planned_svg, restamped_markers = _plan_native_fallback_updates(planned_svg)
+ except (NativeFallbackStampError, UnicodeError) as exc:
+ print(f"error: native fallback baselines could not be prepared: {exc}", file=sys.stderr)
+ return 2
+
+ changed = [
+ (path, count)
+ for path, _text, count in planned_svg
+ ]
+ if not args.dry_run:
+ try:
+ _publish_text_updates([
+ *(
+ (path, new_text)
+ for path, new_text, _count in planned_svg
+ ),
+ (lock, planned_lock),
+ ])
+ except (OSError, RuntimeError, ValueError) as exc:
+ print(f"error: update was not published: {exc}", file=sys.stderr)
+ return 2
+
if args.dry_run:
for lock_key, previous, replacement in lock_changes:
print(
@@ -388,12 +398,17 @@ def main() -> int:
f"{section}.{lock_key} {previous} → {replacement}"
)
print(f"[dry-run] svg_output/: {len(changed)} file(s) would be updated")
+ print(
+ f"[dry-run] native fallbacks: {restamped_markers} marker(s) "
+ "would be re-stamped"
+ )
else:
for lock_key, previous, replacement in lock_changes:
print(
f"spec_lock.md: {section}.{lock_key} {previous} → {replacement}"
)
print(f"svg_output/: {len(changed)} file(s) updated")
+ print(f"native fallbacks: {restamped_markers} marker(s) re-stamped")
for p, n in changed:
suffix = "replacement" if n == 1 else "replacements"
print(f" - {p.name} ({n} {suffix})")