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): image tools honour EXIF orientation, rotate_images reports failures, sparse chart caches import as gaps

hugohe31f61f5b32e36
diff --git a/skills/ppt-master/scripts/gemini_watermark_remover.py b/skills/ppt-master/scripts/gemini_watermark_remover.py
index fe9ef094..c1bc72b0 100644
--- a/skills/ppt-master/scripts/gemini_watermark_remover.py
+++ b/skills/ppt-master/scripts/gemini_watermark_remover.py
@@ -34,7 +34,7 @@ from console_encoding import configure_utf8_stdio
configure_utf8_stdio()
import numpy as np
-from PIL import Image
+from PIL import Image, ImageOps
# Algorithm parameters
ALPHA_THRESHOLD = 0.002 # Alpha threshold; values below this are not processed
@@ -156,7 +156,8 @@ def process_image(input_path: Path, output_path: Path | None = None, verbose: bo
Returns:
Output file path
"""
- image = Image.open(input_path)
+ with Image.open(input_path) as source:
+ image = ImageOps.exif_transpose(source)
width, height = image.size
config = detect_watermark_config(width, height)
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
index 51d0ecf2..c7cb1d03 100644
--- a/skills/ppt-master/scripts/image_search.py
+++ b/skills/ppt-master/scripts/image_search.py
@@ -446,7 +446,7 @@ def _normalize_multi_frame_jpeg(path: Path) -> bool:
if path.suffix.lower() not in {".jpg", ".jpeg"}:
return False
try:
- from PIL import Image # type: ignore
+ from PIL import Image, ImageOps # type: ignore
except ImportError:
return False
try:
@@ -458,10 +458,10 @@ def _normalize_multi_frame_jpeg(path: Path) -> bool:
if not multi_frame:
return False
source.seek(0)
- frame = source.convert("RGB")
+ frame = ImageOps.exif_transpose(source).convert("RGB")
save_kwargs: dict[str, object] = {"quality": 95}
for key in ("exif", "icc_profile"):
- value = source.info.get(key)
+ value = frame.info.get(key)
if value:
save_kwargs[key] = value
except (OSError, ValueError, SyntaxError):
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.py
index 9f8ec91b..a79f31cb 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
@@ -2740,7 +2740,7 @@ def _line_style(chart: ET.Element, series_nodes: list[ET.Element]) -> str:
def _category_values(cat: ET.Element | None) -> list[str]:
cache = _first_cache(cat, ("strCache", "strLit"))
if cache is not None:
- return [str(value) for value in _cache_point_values(cache)]
+ return [str(value) if value is not None else "" for value in _cache_point_values(cache)]
cache = _first_cache(cat, ("numCache", "numLit"))
if cache is None:
return []
@@ -2748,7 +2748,7 @@ def _category_values(cat: ET.Element | None) -> list[str]:
if format_code and format_code.lower() != "general":
raise _UnsupportedChart("unsupported-formatted-category-cache")
numbers = _numeric_cache_values(cache)
- return [str(value) for value in numbers]
+ return [str(value) if value is not None else "" for value in numbers]
def _category_cache_is_numeric(chart: ET.Element) -> bool:
@@ -2804,21 +2804,24 @@ def _series_name(ser: ET.Element, index: int) -> str:
def _text_cache_values(parent: ET.Element | None) -> list[str]:
cache = _first_cache(parent, ("strCache", "strLit"))
if cache is not None:
- return [str(value) for value in _cache_point_values(cache)]
+ return [str(value) if value is not None else "" for value in _cache_point_values(cache)]
cache = _first_cache(parent, ("numCache", "numLit"))
- return [str(value) for value in _cache_point_values(cache)]
+ return [str(value) if value is not None else "" for value in _cache_point_values(cache)]
-def _numeric_values(parent: ET.Element | None) -> list[int | float]:
+def _numeric_values(parent: ET.Element | None) -> list[int | float | None]:
cache = _first_cache(parent, ("numCache", "numLit"))
if cache is None:
return []
return _numeric_cache_values(cache)
-def _numeric_cache_values(cache: ET.Element) -> list[int | float]:
- values: list[int | float] = []
+def _numeric_cache_values(cache: ET.Element) -> list[int | float | None]:
+ values: list[int | float | None] = []
for value in _cache_point_values(cache):
+ if value is None:
+ values.append(None)
+ continue
number = float(value)
if not math.isfinite(number):
raise _UnsupportedChart("unsupported-chart-cache")
@@ -2836,7 +2839,7 @@ def _first_cache(parent: ET.Element | None, names: tuple[str, ...]) -> ET.Elemen
return None
-def _cache_point_values(cache: ET.Element | None) -> list[str]:
+def _cache_point_values(cache: ET.Element | None) -> list[str | None]:
if cache is None:
return []
points: dict[int, str] = {}
@@ -2861,11 +2864,10 @@ def _cache_point_values(cache: ET.Element | None) -> list[str]:
point_count = len(points)
if (
point_count < 0
- or point_count != len(points)
- or any(idx not in points for idx in range(point_count))
+ or any(idx >= point_count for idx in points)
):
raise _UnsupportedChart("unsupported-chart-cache")
- return [points[idx] for idx in range(point_count)]
+ return [points.get(idx) for idx in range(point_count)]
def _element_val(elem: ET.Element | None) -> str | None:
diff --git a/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py b/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py
index ac12be95..ce184f09 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/normalized_chart_svg.py
@@ -323,6 +323,7 @@ def _render_combo(
float(value)
for series in all_series
for value in series.get("values") or []
+ if value is not None
]
if not all_series or not values:
return []
@@ -482,7 +483,7 @@ def _category_segments(
grouping: str,
) -> tuple[list[list[tuple[float, float]]], bool]:
raw = [
- [float(value) for value in item.get("values", [])[:count]]
+ [float(value) if value is not None else 0.0 for value in item.get("values", [])[:count]]
for item in series
]
percent = grouping == "percentStacked"
@@ -539,6 +540,8 @@ def _render_bars(
fill = style.fill or "none"
stroke = style.stroke or "none"
for category_index, (start, end) in enumerate(row):
+ if item["values"][category_index] is None:
+ continue
offset = 0.0 if stacked else series_index * bar_span
display_index = (
len(categories) - 1 - category_index
@@ -625,28 +628,41 @@ def _render_lines_or_areas(
(x_positions[idx], _map(end, lo, hi, plot.y + plot.h, plot.y))
for idx, (_start, end) in enumerate(row)
]
- if chart_type == "area":
- bottom = [
- (x_positions[idx], _map(start, lo, hi, plot.y + plot.h, plot.y))
- for idx, (start, _end) in enumerate(row)
- ]
- points = top + list(reversed(bottom))
- parts.append(
- f'<polygon points="{_points(points)}" fill="{fill_color}" '
- f'fill-opacity="{_fmt(min(style.fill_opacity, 0.58))}" '
- f'stroke="{line_color or "none"}" stroke-opacity="{_fmt(style.stroke_opacity)}" '
- f'stroke-width="{_fmt(max(0.7, style.stroke_width))}" '
- 'stroke-linejoin="round"/>'
- )
- elif line_color is not None:
- parts.append(
- f'<polyline points="{_points(top)}" fill="none" stroke="{line_color}" '
- f'stroke-opacity="{_fmt(style.stroke_opacity)}" '
- f'stroke-width="{_fmt(max(1.0, style.stroke_width))}" '
- f'stroke-linecap="{style.line_cap}" stroke-linejoin="round"/>'
- )
+ runs: list[list[int]] = [[]]
+ for idx, value in enumerate(item["values"][:count]):
+ if value is None:
+ if runs[-1]:
+ runs.append([])
+ else:
+ runs[-1].append(idx)
+ for indices in runs:
+ if not indices:
+ continue
+ points = [top[idx] for idx in indices]
+ if chart_type == "area":
+ bottom = [
+ (x_positions[idx], _map(row[idx][0], lo, hi, plot.y + plot.h, plot.y))
+ for idx in indices
+ ]
+ points += list(reversed(bottom))
+ parts.append(
+ f'<polygon points="{_points(points)}" fill="{fill_color}" '
+ f'fill-opacity="{_fmt(min(style.fill_opacity, 0.58))}" '
+ f'stroke="{line_color or "none"}" stroke-opacity="{_fmt(style.stroke_opacity)}" '
+ f'stroke-width="{_fmt(max(0.7, style.stroke_width))}" '
+ 'stroke-linejoin="round"/>'
+ )
+ elif line_color is not None:
+ parts.append(
+ f'<polyline points="{_points(points)}" fill="none" stroke="{line_color}" '
+ f'stroke-opacity="{_fmt(style.stroke_opacity)}" '
+ f'stroke-width="{_fmt(max(1.0, style.stroke_width))}" '
+ f'stroke-linecap="{style.line_cap}" stroke-linejoin="round"/>'
+ )
if show_markers:
- for x, y in top:
+ for idx, (x, y) in enumerate(top):
+ if item["values"][idx] is None:
+ continue
radius = max(2.0, style.marker_size / 2)
parts.append(
f'<circle cx="{_fmt(x)}" cy="{_fmt(y)}" r="{_fmt(radius)}" '
@@ -657,6 +673,8 @@ def _render_lines_or_areas(
f'stroke-width="{_fmt(max(0.6, style.marker_stroke_width))}"/>'
)
for idx, (x, y) in enumerate(top):
+ if item["values"][idx] is None:
+ continue
labels = _point_data_labels(payload, item, idx)
if labels:
value = float(item["values"][idx])
diff --git a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
index 6ac3e3bf..28d9ef2b 100644
--- a/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
+++ b/skills/ppt-master/scripts/pptx_to_svg/slide_to_svg.py
@@ -1876,7 +1876,7 @@ def _convert_graphic_fallback(node: ShapeNode, ctx: AssemblyContext,
f'fill="none" stroke="#999999" stroke-dasharray="4 4"/>'
f'<text x="{fmt_num(node.xfrm.x + node.xfrm.w / 2)}" '
f'y="{fmt_num(node.xfrm.y + node.xfrm.h / 2)}" '
- f'text-anchor="middle" font-size="14" fill="#999999">'
+ f'text-anchor="middle" font-family="Arial" font-size="14" fill="#999999">'
f"[{_xml_escape(label)}]</text>"
)
if chart_payload_metadata:
@@ -1896,7 +1896,7 @@ def _graphic_preview_label(node: ShapeNode, label: str) -> str:
f'width="{fmt_num(node.xfrm.w)}" height="22" '
f'fill="#FFFFFF" fill-opacity="0.82" stroke="#999999" stroke-width="0.5"/>'
f'<text x="{fmt_num(node.xfrm.x + 6)}" y="{fmt_num(node.xfrm.y + 15)}" '
- f'font-size="11" fill="#666666">[{_xml_escape(label)}]</text>'
+ f'font-family="Arial" font-size="11" fill="#666666">[{_xml_escape(label)}]</text>'
)
diff --git a/skills/ppt-master/scripts/rotate_images.py b/skills/ppt-master/scripts/rotate_images.py
index 86a0b994..3159fbc9 100644
--- a/skills/ppt-master/scripts/rotate_images.py
+++ b/skills/ppt-master/scripts/rotate_images.py
@@ -109,25 +109,32 @@ class ImageRotator:
Number of images fixed
"""
target_path = Path(target_dir)
- if not target_path.exists():
- return 0
+ if not target_path.is_dir():
+ raise FileNotFoundError(f"Directory not found: {target_path}")
print(f"[AUTO] Checking EXIF orientation information...")
fixed_count = 0
+ failed_count = 0
valid_exts = {'.jpg', '.jpeg', '.webp'} # PNG typically does not carry rotation EXIF
# Pre-collect file list to avoid issues caused by modifying during iteration
files = [f for f in target_path.iterdir() if f.is_file() and f.suffix.lower() in valid_exts]
for f in files:
- if self._fix_single_exif(f):
- fixed_count += 1
+ try:
+ if self._fix_single_exif(f):
+ fixed_count += 1
+ except RuntimeError as e:
+ print(f" [WARN] {e}")
+ failed_count += 1
if fixed_count > 0:
print(f"[OK] Auto-fixed EXIF orientation for {fixed_count} image(s)")
- else:
+ elif not failed_count:
print(f"[INFO] No images requiring EXIF correction found")
+ if failed_count:
+ raise RuntimeError(f"EXIF correction failed for {failed_count} of {len(files)} image(s)")
return fixed_count
def generate_contact_sheet(
@@ -356,10 +363,15 @@ class ImageRotator:
raise ValueError("Invalid input: not a file path nor a valid JSON string")
elif isinstance(json_source, list):
tasks = json_source
+ else:
+ raise ValueError("Rotation tasks must be a JSON array")
+
+ if not isinstance(tasks, list):
+ raise ValueError("Rotation tasks must be a JSON array")
gif_paths = []
for task in tasks:
- if not isinstance(task, dict):
+ if not isinstance(task, dict) or not isinstance(task.get('path'), str):
continue
task_path = self._normalize_task_path(task.get('path', ''))
if Path(task_path).suffix.lower() == '.gif':
@@ -375,13 +387,19 @@ class ImageRotator:
cwd = Path(os.getcwd())
repo_root = self._repo_root()
- stats = {'total': len(tasks), 'success': 0}
+ stats = {'total': len(tasks), 'success': 0, 'failed': 0}
for task in tasks:
+ if not isinstance(task, dict) or not isinstance(task.get('path'), str):
+ print(f"[ERROR] Invalid rotation task: {task!r}")
+ stats['failed'] += 1
+ continue
rel_path = self._normalize_task_path(task.get('path', ''))
rotation = task.get('rotation')
if not rel_path or rotation is None:
+ print(f"[ERROR] Rotation task requires path and rotation: {task!r}")
+ stats['failed'] += 1
continue
# Absolute paths should stay absolute; repo-relative paths should resolve from repo root.
@@ -405,6 +423,7 @@ class ImageRotator:
if not target_file.exists():
print(f"[SKIP] File not found: {rel_path}")
+ stats['failed'] += 1
continue
try:
@@ -413,6 +432,7 @@ class ImageRotator:
stats['success'] += 1
except Exception as e:
print(f"[ERROR] {target_file.name}: {e}")
+ stats['failed'] += 1
return stats
@@ -458,8 +478,7 @@ class ImageRotator:
)
return True
except Exception as e:
- print(f" [WARN] Failed to read EXIF for {file_path.name}: {e}")
- return False
+ raise RuntimeError(f"Failed to fix EXIF for {file_path.name}: {e}") from e
def _get_exif_orientation(self, img: Image.Image) -> Optional[int]:
"""Get the Orientation value"""
@@ -500,14 +519,15 @@ class ImageRotator:
if ccw_angle == 0:
return
+ prepared = ImageOps.exif_transpose(img)
if ccw_angle == 90:
- rotated = img.transpose(T.ROTATE_90)
+ rotated = prepared.transpose(T.ROTATE_90)
elif ccw_angle == 180:
- rotated = img.transpose(T.ROTATE_180)
+ rotated = prepared.transpose(T.ROTATE_180)
elif ccw_angle == 270:
- rotated = img.transpose(T.ROTATE_270)
+ rotated = prepared.transpose(T.ROTATE_270)
else:
- rotated = img.rotate(ccw_angle, expand=True)
+ rotated = prepared.rotate(ccw_angle, expand=True)
rotated.load()
@@ -766,7 +786,7 @@ def main(argv: list[str] | None = None) -> int:
except Exception as e:
print(f"[ERROR] Execution failed: {e}")
return 1
- return 0
+ return 1 if stats['failed'] else 0
if args.command == 'auto':
target_dir = args.images_directory
diff --git a/skills/ppt-master/scripts/slice_images.py b/skills/ppt-master/scripts/slice_images.py
index 532e34d6..4d269f0d 100644
--- a/skills/ppt-master/scripts/slice_images.py
+++ b/skills/ppt-master/scripts/slice_images.py
@@ -53,6 +53,7 @@ from PIL import (
ImageChops,
ImageFilter,
ImageMath,
+ ImageOps,
)
_GRID_RE = re.compile(r"^\s*(\d+)\s*[xX×]\s*(\d+)\s*$")
@@ -663,7 +664,8 @@ def slice_sheet(
if suffix and suffix != ".png":
raise ValueError(f"--alpha requires .png output names, got {name!r}")
- sheet = Image.open(sheet_path).convert("RGBA")
+ with Image.open(sheet_path) as source:
+ sheet = ImageOps.exif_transpose(source).convert("RGBA")
sw, sh = sheet.size
output_dir.mkdir(parents=True, exist_ok=True)
diff --git a/skills/ppt-master/scripts/source_to_md/web_to_md.py b/skills/ppt-master/scripts/source_to_md/web_to_md.py
index bd423e91..200aa477 100644
--- a/skills/ppt-master/scripts/source_to_md/web_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/web_to_md.py
@@ -174,7 +174,7 @@ def _decode_response_text(response) -> str:
return raw.decode("utf-8", errors="replace")
try:
- from PIL import Image
+ from PIL import Image, ImageOps
PILLOW_AVAILABLE = True
except ImportError:
PILLOW_AVAILABLE = False
@@ -383,7 +383,8 @@ def download_and_rewrite_images(
# Convert webp to png (optimized)
try:
img_data = io.BytesIO(resp.content)
- pil_image = Image.open(img_data)
+ with Image.open(img_data) as source:
+ pil_image = ImageOps.exif_transpose(source)
# Update filename to .png
converted_from = filename
diff --git a/skills/ppt-master/scripts/svg_finalize/crop_images.py b/skills/ppt-master/scripts/svg_finalize/crop_images.py
index 028bc319..ef7f1ad3 100644
--- a/skills/ppt-master/scripts/svg_finalize/crop_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/crop_images.py
@@ -33,7 +33,7 @@ from console_encoding import configure_utf8_stdio # noqa: E402
configure_utf8_stdio()
try:
- from PIL import Image
+ from PIL import Image, ImageOps
except ImportError:
print("Error: PIL (Pillow) is required. Run: pip install Pillow")
exit(1)
@@ -243,7 +243,8 @@ def process_svg_images(
try:
# Open and process image
- img = Image.open(img_path)
+ with Image.open(img_path) as source:
+ img = ImageOps.exif_transpose(source)
output_is_png = img_path.suffix.lower() == '.png'
# Preserve alpha for PNG assets such as translucent overlays.
diff --git a/skills/ppt-master/scripts/svg_finalize/embed_images.py b/skills/ppt-master/scripts/svg_finalize/embed_images.py
index 0a64fc87..39912efb 100644
--- a/skills/ppt-master/scripts/svg_finalize/embed_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/embed_images.py
@@ -87,6 +87,7 @@ def _optimize_image_bytes(img_bytes: bytes, mime_type: str,
try:
from PIL import Image as PILImage
+ from PIL import ImageOps
import io
except ImportError:
return img_bytes
@@ -109,6 +110,8 @@ def _optimize_image_bytes(img_bytes: bytes, mime_type: str,
f"exempt from size limits")
return img_bytes
+ source_format = img.format
+ img = ImageOps.exif_transpose(img)
changed = False
# Downscale if exceeding max_dimension
@@ -131,7 +134,7 @@ def _optimize_image_bytes(img_bytes: bytes, mime_type: str,
img.save(buf, format='PNG', optimize=True)
else:
# For other formats, just re-save
- fmt = img.format or 'PNG'
+ fmt = source_format or 'PNG'
img.save(buf, format=fmt)
optimized = buf.getvalue()
diff --git a/skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py b/skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py
index 1e47a6ce..f0b9dc11 100644
--- a/skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py
+++ b/skills/ppt-master/scripts/svg_finalize/fix_image_aspect.py
@@ -42,7 +42,7 @@ configure_utf8_stdio()
# Try to import PIL for getting image dimensions
try:
- from PIL import Image
+ from PIL import Image, ImageOps
HAS_PIL = True
except ImportError:
HAS_PIL = False
@@ -54,7 +54,7 @@ def get_image_dimensions_pil(image_path: str) -> tuple[int | None, int | None]:
"""Get image dimensions using PIL."""
try:
with Image.open(image_path) as img:
- return img.width, img.height
+ return ImageOps.exif_transpose(img).size
except Exception as e:
print(f" [WARN] Cannot read image with PIL: {e}")
return None, None
@@ -121,7 +121,7 @@ def get_image_dimensions_from_base64(data_uri: str) -> tuple[int | None, int | N
if HAS_PIL:
with Image.open(io.BytesIO(img_bytes)) as img:
- return img.width, img.height
+ return ImageOps.exif_transpose(img).size
else:
# Use basic method
if img_bytes[:8] == b'\x89PNG\r\n\x1a\n':
diff --git a/skills/ppt-master/scripts/tests/test_image_search.py b/skills/ppt-master/scripts/tests/test_image_search.py
index b0ece320..f98111d3 100644
--- a/skills/ppt-master/scripts/tests/test_image_search.py
+++ b/skills/ppt-master/scripts/tests/test_image_search.py
@@ -182,3 +182,19 @@ class CandidatePoolContinuationTests(unittest.TestCase):
self.assertEqual(getattr(image, "n_frames", 1), 1)
self.assertGreater(image.getpixel((3, 3))[0], 150)
self.assertFalse(image_search._normalize_multi_frame_jpeg(path))
+
+ def test_multi_frame_camera_jpeg_bakes_exif_orientation(self) -> None:
+ from PIL import Image
+
+ with tempfile.TemporaryDirectory() as temp_dir:
+ path = Path(temp_dir) / "camera.jpg"
+ first = Image.new("RGB", (64, 48), "red")
+ exif = first.getexif()
+ exif[274] = 6
+ first.save(path, format="MPO", save_all=True, exif=exif,
+ append_images=[Image.new("RGB", (64, 48), "blue")])
+ self.assertTrue(image_search._normalize_multi_frame_jpeg(path))
+ with Image.open(path) as image:
+ self.assertEqual(image.format, "JPEG")
+ self.assertEqual(image.size, (48, 64))
+ self.assertNotIn(274, image.getexif())
diff --git a/skills/ppt-master/scripts/tests/test_native_chart_fidelity.py b/skills/ppt-master/scripts/tests/test_native_chart_fidelity.py
index b9e35a82..53e0eb12 100644
--- a/skills/ppt-master/scripts/tests/test_native_chart_fidelity.py
+++ b/skills/ppt-master/scripts/tests/test_native_chart_fidelity.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import sys
+import tempfile
import unittest
from pathlib import Path
from xml.etree import ElementTree as ET
@@ -19,6 +20,18 @@ from svg_to_pptx.native_objects.chart_style import ( # noqa: E402
_native_chart_chrome_warnings,
)
from svg_to_pptx.native_objects.chart_xml import _chart_xml # noqa: E402
+from pptx_to_svg.chart_to_svg import ( # noqa: E402
+ _UnsupportedChart,
+ _cache_point_values,
+ _category_payload,
+ _numeric_cache_values,
+)
+from pptx_to_svg.emu_units import NS, Xfrm # noqa: E402
+from pptx_to_svg.ooxml_loader import PartRef # noqa: E402
+from pptx_to_svg.normalized_chart_svg import render_normalized_chart_svg # noqa: E402
+from pptx_to_svg.shape_walker import GRAPHIC, ShapeNode # noqa: E402
+from pptx_to_svg.slide_to_svg import AssemblyContext, _convert_graphic_fallback # noqa: E402
+from svg_authoring_view import _render_projection # noqa: E402
SVG_NS = "http://www.w3.org/2000/svg"
@@ -54,6 +67,91 @@ def _bar_payload(**extra: object) -> dict:
return payload
+class ChartImportTests(unittest.TestCase):
+ def test_sparse_cache_preserves_missing_indices(self) -> None:
+ cache = ET.fromstring(
+ '<c:numCache xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart">'
+ '<c:ptCount val="5"/><c:pt idx="3"><c:v>2.5</c:v></c:pt>'
+ '<c:pt idx="1"><c:v>1</c:v></c:pt></c:numCache>'
+ )
+ self.assertEqual(_cache_point_values(cache), [None, "1", None, "2.5", None])
+ self.assertEqual(_numeric_cache_values(cache), [None, 1, None, 2.5, None])
+
+ def test_exported_line_gaps_survive_category_import(self) -> None:
+ payload = {
+ "type": "line", "categories": ["A", "B", "C", "D"],
+ "series": [{"name": "S", "values": [1, None, 3, None]}],
+ }
+ chart = ET.fromstring(_render(payload)).find(
+ ".//{http://schemas.openxmlformats.org/drawingml/2006/chart}lineChart"
+ )
+ imported = _category_payload(chart, "line", Xfrm(0, 0, 400, 200))
+ self.assertEqual(imported["categories"], payload["categories"])
+ self.assertEqual(imported["series"], payload["series"])
+
+ def test_invalid_cache_indices_and_counts_remain_rejected(self) -> None:
+ for contents in (
+ '<c:ptCount val="1"/><c:pt idx="1"><c:v>2</c:v></c:pt>',
+ '<c:ptCount val="2"/><c:pt idx="0"/><c:pt idx="0"/>',
+ '<c:ptCount val="2"/><c:pt idx="-1"/>',
+ '<c:ptCount val="-1"/>',
+ '<c:ptCount val="bad"/>',
+ ):
+ with self.subTest(contents=contents):
+ cache = ET.fromstring(
+ '<c:numCache xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart">'
+ f'{contents}</c:numCache>'
+ )
+ with self.assertRaises(_UnsupportedChart):
+ _cache_point_values(cache)
+
+ def test_normalized_chart_preview_keeps_gaps(self) -> None:
+ payload = {
+ "type": "line", "x": 0, "y": 0, "width": 400, "height": 200,
+ "categories": ["A", "B", "C", "D", "E", "F"],
+ "series": [{"name": "S", "values": [None, 1, 2, None, 4, None]}],
+ "line_style": "lineMarker",
+ }
+ rendered = render_normalized_chart_svg(payload, [])
+ self.assertIsNotNone(rendered)
+ root = ET.fromstring(f'<svg xmlns="{SVG_NS}">{rendered}</svg>')
+ lines = root.findall(f'.//{{{SVG_NS}}}polyline')
+ self.assertEqual([len(line.get("points").split()) for line in lines], [2, 1])
+ self.assertEqual(len(root.findall(f'.//{{{SVG_NS}}}circle')), 3)
+ for chart_type in ("area", "bar", "column"):
+ with self.subTest(type=chart_type):
+ self.assertIsNotNone(render_normalized_chart_svg({**payload, "type": chart_type}, []))
+ combo = {**payload, "type": "combo", "plots": [{"type": "line", "series": payload["series"]}]}
+ self.assertIsNotNone(render_normalized_chart_svg(combo, []))
+
+ def test_unsupported_graphic_placeholder_can_publish_authoring_projection(self) -> None:
+ xml = ET.fromstring(
+ f'<p:graphicFrame xmlns:p="{NS["p"]}" xmlns:a="{NS["a"]}">'
+ '<a:graphic><a:graphicData '
+ 'uri="http://schemas.openxmlformats.org/drawingml/2006/chart"/>'
+ '</a:graphic></p:graphicFrame>'
+ )
+ node = ShapeNode(GRAPHIC, xml, Xfrm(20, 20, 200, 100), name="unsupported", spid="2")
+ ctx = AssemblyContext(
+ palette=None, pkg=None,
+ slide_part=PartRef("ppt/slides/slide1.xml", ET.Element("slide")),
+ render_graphic_previews=False,
+ )
+ fallback = _convert_graphic_fallback(node, ctx, top_level=True)
+ self.assertIn("unsupported-chart-reference", fallback)
+ self.assertIn("[chart]", fallback)
+ with tempfile.TemporaryDirectory() as tmp:
+ source = Path(tmp) / "slide.svg"
+ source.write_text(
+ f'<svg xmlns="{SVG_NS}" viewBox="0 0 400 200">{fallback}</svg>',
+ encoding="utf-8",
+ )
+ _, rendered, _ = _render_projection(source, Path(tmp) / "authoring.svg")
+ root = ET.fromstring(rendered)
+ self.assertTrue(root.get("font-family"))
+ self.assertIn("[chart]", "".join(root.itertext()))
+
+
class CategoryOrderTests(unittest.TestCase):
def test_bar_categories_read_top_down_with_value_axis_at_bottom(self) -> None:
xml = _render(_bar_payload())
diff --git a/skills/ppt-master/scripts/tests/test_rotate_images.py b/skills/ppt-master/scripts/tests/test_rotate_images.py
new file mode 100644
index 00000000..ab02a437
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_rotate_images.py
@@ -0,0 +1,115 @@
+#!/usr/bin/env python3
+"""Regression tests for image rotation task outcomes and EXIF handling."""
+
+from __future__ import annotations
+
+import io
+import json
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from pathlib import Path
+
+from PIL import Image
+
+from rotate_images import ImageRotator, main
+
+
+class ImageRotationTests(unittest.TestCase):
+ def test_fix_exit_status_tracks_failed_and_invalid_tasks(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ source = root / "image.png"
+ fixes = root / "fixes.json"
+ cases = (
+ ([{"path": str(root / "missing.png"), "rotation": 90}], 1),
+ ([{"path": str(source), "rotation": "bad"}], 1),
+ ([{"path": str(source)}], 1),
+ ([{"rotation": 90}], 1),
+ ([None, {"path": 42, "rotation": 90}], 1),
+ ([{"path": str(source), "rotation": 90}], 0),
+ ([{"path": str(source), "rotation": 0}], 0),
+ ([], 0),
+ ({"path": str(source), "rotation": 90}, 1),
+ )
+ for tasks, expected in cases:
+ with self.subTest(tasks=tasks):
+ Image.new("RGB", (80, 40), "red").save(source)
+ fixes.write_text(json.dumps(tasks), encoding="utf-8")
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main(["fix", str(fixes)]), expected)
+
+ def test_fix_continues_after_failures_and_reports_success_count(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ source = Path(tmp) / "image.png"
+ Image.new("RGB", (80, 40), "red").save(source)
+ tasks = [None, {}, {"path": str(source), "rotation": "bad"},
+ {"path": str(source), "rotation": 90}]
+ with redirect_stdout(io.StringIO()):
+ stats = ImageRotator().apply_fixes(tasks)
+ self.assertEqual(stats, {"total": 4, "success": 1, "failed": 3})
+ with Image.open(source) as result:
+ self.assertEqual(result.size, (40, 80))
+
+ def test_manual_rotation_follows_exif_display_orientation(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ source = Path(tmp) / "image.jpg"
+ image = Image.new("RGB", (80, 40), "red")
+ image.paste("blue", (40, 0, 80, 40))
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(source, exif=exif)
+ with redirect_stdout(io.StringIO()):
+ stats = ImageRotator().apply_fixes([{"path": str(source), "rotation": 90}])
+ self.assertEqual(stats["success"], 1)
+ with Image.open(source) as result:
+ self.assertEqual(result.size, (80, 40))
+ self.assertEqual(result.getexif().get(274, 1), 1)
+ self.assertGreater(result.getpixel((10, 10))[2], 200)
+
+ def test_auto_and_gen_fail_on_unreadable_images_and_missing_directories(self) -> None:
+ for command in ("auto", "gen"):
+ with self.subTest(command=command), tempfile.TemporaryDirectory() as tmp:
+ images = Path(tmp) / "images"
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main([command, str(images)]), 1)
+ images.mkdir()
+ (images / "bad.jpg").write_bytes(b"not an image")
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main([command, str(images)]), 1)
+ self.assertFalse((Path(tmp) / "image_orientation_tool.html").exists())
+
+ def test_auto_and_gen_accept_valid_images(self) -> None:
+ for command in ("auto", "gen"):
+ with self.subTest(command=command), tempfile.TemporaryDirectory() as tmp:
+ images = Path(tmp) / "images"
+ images.mkdir()
+ source = images / "image.jpg"
+ image = Image.new("RGB", (80, 40), "red")
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(source, exif=exif)
+ with redirect_stdout(io.StringIO()):
+ self.assertEqual(main([command, str(images)]), 0)
+ self.assertEqual(main([command, str(images)]), 0)
+ with Image.open(source) as result:
+ self.assertEqual(result.size, (40, 80))
+ self.assertEqual(result.getexif().get(274, 1), 1)
+
+ def test_auto_continues_after_failed_images(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ (root / "bad.jpg").write_bytes(b"not an image")
+ image = Image.new("RGB", (80, 40), "red")
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(root / "good.jpg", exif=exif)
+ with redirect_stdout(io.StringIO()) as stdout:
+ self.assertEqual(main(["auto", str(root)]), 1)
+ self.assertIn("Auto-fixed EXIF orientation for 1 image(s)", stdout.getvalue())
+ with Image.open(root / "good.jpg") as result:
+ self.assertEqual(result.size, (40, 80))
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/skills/ppt-master/scripts/tests/test_slice_images.py b/skills/ppt-master/scripts/tests/test_slice_images.py
index 77a5937a..1ca4ec12 100644
--- a/skills/ppt-master/scripts/tests/test_slice_images.py
+++ b/skills/ppt-master/scripts/tests/test_slice_images.py
@@ -3,20 +3,70 @@
from __future__ import annotations
+import base64
+import io
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
+from xml.etree import ElementTree as ET
from PIL import Image, ImageDraw
+from slice_images import slice_sheet
+from svg_finalize.crop_images import process_svg_images
+from svg_finalize.embed_images import _optimize_image_bytes
+from svg_finalize.fix_image_aspect import (
+ get_image_dimensions_from_base64,
+ get_image_dimensions_pil,
+)
+from pptx_to_svg.pic_to_svg import _apply_blip_image_effects, _image_size_at_96_dpi
+
SCRIPTS_DIR = Path(__file__).resolve().parents[1]
SCRIPT = SCRIPTS_DIR / "slice_images.py"
class SliceImagesDiagnosticsTests(unittest.TestCase):
+ def test_sheet_orientation_is_applied_before_slicing(self) -> None:
+ for orientation, expected_size in ((6, (40, 80)), (None, (80, 40))):
+ with self.subTest(orientation=orientation), tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ source = root / "sheet.jpg"
+ image = Image.new("RGB", (80, 40), "red")
+ image.paste("blue", (40, 0, 80, 40))
+ exif = image.getexif()
+ if orientation is not None:
+ exif[274] = orientation
+ image.save(source, exif=exif)
+
+ paths = slice_sheet(source, 1, 1, root / "output")
+
+ with Image.open(paths[0]) as result:
+ self.assertEqual(result.size, expected_size)
+ self.assertNotIn(274, result.getexif())
+ self.assertGreater(result.getpixel((10, 10))[0], 200)
+ blue_point = (10, 60) if orientation == 6 else (60, 10)
+ self.assertGreater(result.getpixel(blue_point)[2], 200)
+
+ def test_grid_uses_oriented_dimensions(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ source = root / "sheet.jpg"
+ image = Image.new("RGB", (80, 40), "red")
+ image.paste("blue", (40, 0, 80, 40))
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(source, exif=exif)
+
+ paths = slice_sheet(source, 2, 1, root / "output")
+
+ for path, channel in zip(paths, (0, 2)):
+ with Image.open(path) as result:
+ self.assertEqual(result.size, (40, 40))
+ self.assertGreater(result.getpixel((20, 20))[channel], 200)
+
def test_strict_alpha_reports_measured_sheet_border_and_exact_rerun(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -56,5 +106,85 @@ class SliceImagesDiagnosticsTests(unittest.TestCase):
self.assertFalse((output_dir / "element.png").exists())
+class ImageOrientationProcessingTests(unittest.TestCase):
+ def test_compression_applies_orientation_and_preserves_image_format(self) -> None:
+ for fmt, mime in (("JPEG", "image/jpeg"), ("PNG", "image/png"), ("WEBP", "image/webp")):
+ for orientation in (None, 6):
+ with self.subTest(format=fmt, orientation=orientation):
+ image = Image.new("RGB", (80, 40), "red")
+ image.paste("blue", (40, 0, 80, 40))
+ exif = image.getexif()
+ if orientation is not None:
+ exif[274] = orientation
+ source = io.BytesIO()
+ image.save(source, format=fmt, exif=exif)
+ result = _optimize_image_bytes(source.getvalue(), mime, compress=True, max_dimension=20)
+ self.assertLess(len(result), len(source.getvalue()))
+ with Image.open(io.BytesIO(result)) as optimized:
+ self.assertEqual(optimized.format, fmt)
+ self.assertEqual(optimized.size, (10, 20) if orientation == 6 else (20, 10))
+ self.assertNotIn(274, optimized.getexif())
+
+ def test_animated_images_are_not_reencoded(self) -> None:
+ source = io.BytesIO()
+ Image.new("RGB", (80, 40), "red").save(
+ source, format="GIF", save_all=True,
+ append_images=[Image.new("RGB", (80, 40), "blue")],
+ )
+ original = source.getvalue()
+ self.assertEqual(_optimize_image_bytes(original, "image/gif", compress=True), original)
+
+ def test_svg_dimensions_and_crop_use_display_orientation_while_import_keeps_stored_pixels(self) -> None:
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ source = root / "photo.jpg"
+ image = Image.new("RGB", (80, 40), "red")
+ image.paste("blue", (40, 0, 80, 40))
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(source, exif=exif, dpi=(96, 96))
+ data = source.read_bytes()
+ uri = "data:image/jpeg;base64," + base64.b64encode(data).decode("ascii")
+ self.assertEqual(get_image_dimensions_pil(str(source)), (40, 80))
+ self.assertEqual(get_image_dimensions_from_base64(uri), (40, 80))
+ # PPTX import keeps the stored pixel orientation: PowerPoint renders
+ # an embedded picture without applying its EXIF orientation tag.
+ self.assertEqual(_image_size_at_96_dpi(data, ET.Element("blipFill")), (80, 40))
+
+ svg = root / "slide.svg"
+ svg.write_text(
+ '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 80">'
+ '<image href="photo.jpg" width="40" height="80" '
+ 'preserveAspectRatio="xMidYMid slice"/></svg>',
+ encoding="utf-8",
+ )
+ self.assertEqual(process_svg_images(str(svg), root / "cropped", verbose=False), (1, 0))
+ with Image.open(root / "cropped" / "photo.jpg") as cropped:
+ self.assertEqual(cropped.size, (40, 80))
+ self.assertGreater(cropped.getpixel((10, 60))[2], 200)
+
+ blip = ET.fromstring(
+ '<a:blip xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">'
+ '<a:lum bright="10000"/></a:blip>'
+ )
+ _, adjusted, diagnostics = _apply_blip_image_effects("photo.jpg", data, blip)
+ self.assertEqual(diagnostics, ())
+ with Image.open(io.BytesIO(adjusted)) as result:
+ self.assertEqual(result.size, (80, 40))
+
+ def test_watermark_processing_applies_orientation(self) -> None:
+ from gemini_watermark_remover import process_image
+
+ with tempfile.TemporaryDirectory() as tmp:
+ source = Path(tmp) / "image.jpg"
+ image = Image.new("RGB", (256, 160), "red")
+ exif = image.getexif()
+ exif[274] = 6
+ image.save(source, exif=exif)
+ output = process_image(source, Path(tmp) / "processed.png", verbose=False)
+ with Image.open(output) as result:
+ self.assertEqual(result.size, (160, 256))
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/skills/ppt-master/scripts/tests/test_source_to_md_cli.py b/skills/ppt-master/scripts/tests/test_source_to_md_cli.py
index b2192eef..4d1a4723 100644
--- a/skills/ppt-master/scripts/tests/test_source_to_md_cli.py
+++ b/skills/ppt-master/scripts/tests/test_source_to_md_cli.py
@@ -65,6 +65,24 @@ class OutputNamingTests(unittest.TestCase):
class ImageFlagRoutingTests(unittest.TestCase):
+ def test_downloaded_webp_is_oriented_before_png_conversion(self) -> None:
+ from PIL import Image
+
+ image = Image.new("RGB", (80, 40), "red")
+ exif = image.getexif()
+ exif[274] = 6
+ encoded = io.BytesIO()
+ image.save(encoded, format="WEBP", exif=exif)
+ response = Mock(content=encoded.getvalue(), headers={"Content-Type": "image/webp"})
+ content = web_to_md.BeautifulSoup('<p><img src="photo.webp"/></p>', "html.parser")
+ with tempfile.TemporaryDirectory() as tmp:
+ with patch.object(web_to_md, "_http_get", return_value=response), redirect_stdout(io.StringIO()):
+ count = web_to_md.download_and_rewrite_images(content, "https://example.com/", tmp, "images")
+ self.assertEqual(count, 1)
+ with Image.open(next(Path(tmp).glob("*.png"))) as converted:
+ self.assertEqual(converted.size, (40, 80))
+ self.assertNotIn(274, converted.getexif())
+
def test_no_images_is_accepted_for_web_and_pdf(self) -> None:
self.assertTrue(
source_to_md._validate_pdf_image_flags(