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(image-pipeline): harden acquisition and export contracts

hugohe316e494603136
diff --git a/skills/ppt-master/scripts/analyze_images.py b/skills/ppt-master/scripts/analyze_images.py
index aa501b66..9a98c194 100644
--- a/skills/ppt-master/scripts/analyze_images.py
+++ b/skills/ppt-master/scripts/analyze_images.py
@@ -7,9 +7,10 @@ images in a folder. Intentionally does NOT prescribe a layout — the Strategist
decides narrative intent (hero / atmosphere / side-by-side / accent) per
references/strategist-image.md; this tool only supplies the numbers.
-When a canvas is specified, also reports the reference image/text area sizes
-that would apply *if* an image is placed side-by-side with body text. Those
-numbers are conditional on the Strategist picking the side-by-side intent.
+After resolving the canvas from the project, an explicit override, or the
+ppt169 fallback, also reports the reference image/text area sizes that would
+apply *if* an image is placed side-by-side with body text. Those numbers are
+conditional on the Strategist picking the side-by-side intent.
Usage:
python scripts/analyze_images.py <images_folder_path>
@@ -23,9 +24,11 @@ Output:
"""
import argparse
+import csv
import json
import os
import sys
+import tempfile
from pathlib import Path
from console_encoding import configure_utf8_stdio
@@ -33,7 +36,7 @@ from console_encoding import configure_utf8_stdio
configure_utf8_stdio()
try:
- from PIL import Image
+ from PIL import Image, ImageOps
except ImportError:
print("Error: PIL/Pillow not installed. Run: pip install Pillow")
sys.exit(1)
@@ -55,6 +58,8 @@ except ImportError:
},
}
+from project_utils import get_project_info, normalize_canvas_format
+
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tiff", ".tif"}
OFFICE_VECTOR_EXTENSIONS = {".emf", ".wmf"}
REPORT_WIDTH = 100
@@ -93,32 +98,6 @@ def _load_image_manifest(images_dir: str) -> dict[str, dict]:
return manifest
-def _warn_office_vectors_without_manifest(images_dir: str, manifest: dict[str, dict]) -> None:
- """Warn when EMF/WMF files cannot be reported because manifest metadata is absent."""
- if manifest:
- return
-
- vector_files = [
- path for path in Path(images_dir).iterdir()
- if path.is_file() and path.suffix.lower() in OFFICE_VECTOR_EXTENSIONS
- ]
- if not vector_files:
- return
-
- print(
- f"[WARN] Found {len(vector_files)} office vector file(s) (.emf/.wmf) "
- "but no image_manifest.json found."
- )
- print(
- " Dimensions and metadata unknown — these assets will NOT appear "
- "in the analysis report."
- )
- print(
- " To fix: ensure image_manifest.json is present in images/ "
- "(auto-generated by doc_to_md.py for DOCX sources)."
- )
-
-
def _manifest_ratio(meta: dict | None) -> float | None:
"""Return a positive display ratio from manifest metadata."""
if not meta:
@@ -197,6 +176,29 @@ def _apply_manifest_metadata(result: ImageAnalysis, meta: dict | None) -> None:
result["pptx_native_supported"] = meta.get("pptx_native_supported", True)
+def _has_transparent_pixels(image: Image.Image) -> bool:
+ """Return whether any frame contains a pixel with alpha below 255."""
+ original_frame = image.tell()
+ frame_count = int(getattr(image, "n_frames", 1))
+ try:
+ for frame_index in range(frame_count):
+ image.seek(frame_index)
+ if "A" not in image.getbands() and "transparency" not in image.info:
+ continue
+ rgba = image.convert("RGBA")
+ alpha = rgba.getchannel("A")
+ try:
+ extrema = alpha.getextrema()
+ finally:
+ alpha.close()
+ rgba.close()
+ if extrema and extrema[0] < 255:
+ return True
+ finally:
+ image.seek(original_frame)
+ return False
+
+
def _result_from_manifest(
filename: str,
filepath: str,
@@ -212,12 +214,26 @@ def _result_from_manifest(
'width': width,
'height': height,
'aspect_ratio': ratio,
- 'pixel_aspect_ratio': meta.get('pixel_ratio') or ratio,
+ 'pixel_aspect_ratio': None,
+ 'source_display_ratio': ratio,
'ratio_source': 'manifest',
+ 'format': Path(filename).suffix.lstrip('.').upper(),
+ 'has_transparent_pixels': None,
'layout_hint': classify_ratio(ratio),
'filesize_kb': os.path.getsize(filepath) / 1024,
}
_apply_manifest_metadata(result, meta)
+ suffix = Path(filename).suffix.lower()
+ is_office_vector = suffix in OFFICE_VECTOR_EXTENSIONS
+ result["asset_kind"] = meta.get(
+ "asset_kind",
+ "office_vector" if is_office_vector else "vector",
+ )
+ result["svg_renderable"] = meta.get("svg_renderable", suffix == ".svg")
+ result["pptx_native_supported"] = meta.get(
+ "pptx_native_supported",
+ is_office_vector or suffix == ".svg",
+ )
return result
@@ -311,66 +327,87 @@ def compute_layout_dimensions(
return _try_left_right_width_constrained()
-def analyze_images(images_dir: str) -> list[ImageAnalysis]:
+def _analyze_images(images_dir: str) -> tuple[list[ImageAnalysis], list[str]]:
"""Analyze all image files in a directory.
Args:
images_dir: Directory that contains image files.
Returns:
- A list of image analysis records sorted by filename.
+ Sorted image analysis records and supported files that could not be read.
"""
results: list[ImageAnalysis] = []
+ errors: list[str] = []
manifest = _load_image_manifest(images_dir)
- seen_filenames: set[str] = set()
- # Iterate through all files in the directory
for filename in sorted(os.listdir(images_dir)):
filepath = os.path.join(images_dir, filename)
+ if not os.path.isfile(filepath):
+ continue
+
+ suffix = Path(filename).suffix.lower()
meta = manifest.get(filename)
- # Check if it is an image file
- if os.path.isfile(filepath) and Path(filename).suffix.lower() in IMAGE_EXTENSIONS:
+ if suffix in IMAGE_EXTENSIONS:
try:
with Image.open(filepath) as img:
- width, height = img.size
- pixel_ratio = width / height
- aspect_ratio = _manifest_ratio(meta) or pixel_ratio
- layout_hint = classify_ratio(aspect_ratio)
+ image_format = img.format or suffix.lstrip(".").upper()
+ has_transparent_pixels = _has_transparent_pixels(img)
+ oriented = ImageOps.exif_transpose(img)
+ try:
+ width, height = oriented.size
+ finally:
+ if oriented is not img:
+ oriented.close()
+
+ aspect_ratio = width / height
result: ImageAnalysis = {
'filename': filename,
'width': width,
'height': height,
'aspect_ratio': aspect_ratio,
- 'pixel_aspect_ratio': pixel_ratio,
- 'ratio_source': 'manifest' if meta else 'pixel',
- 'layout_hint': layout_hint,
+ 'pixel_aspect_ratio': aspect_ratio,
+ 'source_display_ratio': _manifest_ratio(meta),
+ 'ratio_source': 'native',
+ 'format': image_format,
+ 'has_transparent_pixels': has_transparent_pixels,
+ 'layout_hint': classify_ratio(aspect_ratio),
'filesize_kb': os.path.getsize(filepath) / 1024
}
_apply_manifest_metadata(result, meta)
results.append(result)
- seen_filenames.add(filename)
- except Exception as e:
- print(f"[WARN] Cannot read {filename}: {e}")
- elif os.path.isfile(filepath) and meta:
+ except (
+ EOFError,
+ OSError,
+ SyntaxError,
+ ValueError,
+ ZeroDivisionError,
+ Image.DecompressionBombError,
+ ) as exc:
+ message = f"{filename}: {exc}"
+ errors.append(message)
+ print(f"[WARN] Cannot read {message}")
+ elif meta:
result = _result_from_manifest(filename, filepath, meta)
if result:
results.append(result)
- seen_filenames.add(filename)
+ else:
+ message = f"{filename}: manifest has no valid display_ratio"
+ errors.append(message)
+ print(f"[WARN] Cannot analyze {message}")
+ elif suffix in OFFICE_VECTOR_EXTENSIONS:
+ message = f"{filename}: image_manifest.json metadata is required"
+ errors.append(message)
+ print(f"[WARN] Cannot analyze {message}")
- for filename, meta in sorted(manifest.items()):
- if filename in seen_filenames:
- continue
- filepath = os.path.join(images_dir, filename)
- if not os.path.isfile(filepath):
- continue
- result = _result_from_manifest(filename, filepath, meta)
- if result:
- results.append(result)
+ return results, errors
- _warn_office_vectors_without_manifest(images_dir, manifest)
+
+def analyze_images(images_dir: str) -> list[ImageAnalysis]:
+ """Analyze readable image files while preserving the existing public API."""
+ results, _ = _analyze_images(images_dir)
return results
@@ -379,7 +416,6 @@ def enrich_with_layout(
canvas_key: str,
) -> None:
"""Add computed layout dimensions to each result in-place."""
- fmt = CANVAS_FORMATS.get(canvas_key, {})
margins = LAYOUT_MARGINS.get(canvas_key)
if not margins:
@@ -413,7 +449,7 @@ def print_results(results: list[ImageAnalysis]) -> None:
print("-" * REPORT_WIDTH)
for i, img in enumerate(results, 1):
- ratio_source = str(img.get('ratio_source', 'pixel'))
+ ratio_source = str(img.get('ratio_source', 'native'))
usage_count = int(img.get('usage_count', 1))
base = f"{i:<4} {img['width']:<7} {img['height']:<7} {img['aspect_ratio']:<7.2f} {ratio_source:<8} {usage_count:<5} {img['filesize_kb']:<10.1f}KB {img['layout_hint']:<20}"
if has_layout:
@@ -515,26 +551,115 @@ def generate_markdown(results: list[ImageAnalysis], canvas_key: str) -> None:
print("\n" + "=" * REPORT_WIDTH + "\n")
-def save_csv(results: list[ImageAnalysis], csv_path: str) -> None:
- """Save analysis results to a CSV file."""
- has_layout = 'layout_type' in results[0] if results else False
+def _format_optional_number(value: object, digits: int = 2) -> str:
+ """Format a numeric value for CSV, leaving unavailable facts blank."""
+ if not isinstance(value, (int, float)):
+ return ""
+ return f"{float(value):.{digits}f}"
- # NOTE: ImageArea_SxS / TextArea_SxS apply only if Strategist picks the
- # side-by-side intent for this image (see strategist-image.md). The tool
- # does not prescribe a layout.
- with open(csv_path, 'w', encoding='utf-8') as f:
- if has_layout:
- f.write("No,Filename,Width,Height,AspectRatio,PixelAspectRatio,RatioSource,UsageCount,DisplayRatioVariants,AssetKind,SvgRenderable,PptxNativeSupported,SizeKB,Category,ImageArea_SxS,TextArea_SxS\n")
- for i, img in enumerate(results, 1):
- f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img.get('pixel_aspect_ratio', img['aspect_ratio']):.2f},{img.get('ratio_source', 'pixel')},{img.get('usage_count', 1)},{img.get('display_ratio_variants', '')},{img.get('asset_kind', 'bitmap')},{img.get('svg_renderable', True)},{img.get('pptx_native_supported', True)},{img['filesize_kb']:.1f},{img['layout_hint']},{img['image_w']}x{img['image_h']},{img['text_w']}x{img['text_h']}\n")
- else:
- f.write("No,Filename,Width,Height,AspectRatio,PixelAspectRatio,RatioSource,UsageCount,DisplayRatioVariants,AssetKind,SvgRenderable,PptxNativeSupported,SizeKB,Category\n")
- for i, img in enumerate(results, 1):
- f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img.get('pixel_aspect_ratio', img['aspect_ratio']):.2f},{img.get('ratio_source', 'pixel')},{img.get('usage_count', 1)},{img.get('display_ratio_variants', '')},{img.get('asset_kind', 'bitmap')},{img.get('svg_renderable', True)},{img.get('pptx_native_supported', True)},{img['filesize_kb']:.1f},{img['layout_hint']}\n")
- print(f"\nCSV saved to: {csv_path}")
+def save_csv(
+ results: list[ImageAnalysis],
+ csv_path: str | Path,
+ include_layout: bool | None = None,
+) -> None:
+ """Atomically save analysis results to a standards-compliant CSV file."""
+ target = Path(csv_path)
+ target.parent.mkdir(parents=True, exist_ok=True)
+ if include_layout is None:
+ include_layout = bool(results and "layout_type" in results[0])
+ header = [
+ "No",
+ "Filename",
+ "Width",
+ "Height",
+ "AspectRatio",
+ "PixelAspectRatio",
+ "SourceDisplayRatio",
+ "RatioSource",
+ "Format",
+ "HasTransparentPixels",
+ "UsageCount",
+ "DisplayRatioVariants",
+ "AssetKind",
+ "SvgRenderable",
+ "PptxNativeSupported",
+ "SizeKB",
+ "Category",
+ ]
+ if include_layout:
+ header.extend(["ImageArea_SxS", "TextArea_SxS"])
-def main() -> None:
+ temporary_path: Path | None = None
+ try:
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ newline="",
+ prefix=f".{target.name}.",
+ suffix=".tmp",
+ dir=target.parent,
+ delete=False,
+ ) as handle:
+ temporary_path = Path(handle.name)
+ writer = csv.writer(handle, lineterminator="\n")
+ writer.writerow(header)
+ for index, image in enumerate(results, 1):
+ row = [
+ index,
+ image["filename"],
+ image["width"],
+ image["height"],
+ _format_optional_number(image["aspect_ratio"]),
+ _format_optional_number(image.get("pixel_aspect_ratio")),
+ _format_optional_number(image.get("source_display_ratio")),
+ image.get("ratio_source", "native"),
+ image.get("format", ""),
+ image.get("has_transparent_pixels", ""),
+ image.get("usage_count", 1),
+ image.get("display_ratio_variants", ""),
+ image.get("asset_kind", "bitmap"),
+ image.get("svg_renderable", True),
+ image.get("pptx_native_supported", True),
+ _format_optional_number(image["filesize_kb"], digits=1),
+ image["layout_hint"],
+ ]
+ if include_layout:
+ image_area = (
+ f"{image['image_w']}x{image['image_h']}"
+ if "image_w" in image
+ else ""
+ )
+ text_area = (
+ f"{image['text_w']}x{image['text_h']}"
+ if "text_w" in image
+ else ""
+ )
+ row.extend([image_area, text_area])
+ writer.writerow(row)
+ os.replace(temporary_path, target)
+ temporary_path = None
+ finally:
+ if temporary_path is not None:
+ temporary_path.unlink(missing_ok=True)
+
+ print(f"\nCSV saved to: {target}")
+
+
+def _resolve_canvas_key(images_dir: Path, override: str | None) -> tuple[str, str]:
+ """Resolve canvas from an explicit override, project context, or fallback."""
+ if override:
+ return normalize_canvas_format(override), "--canvas"
+
+ project_dir = images_dir.parent if images_dir.name == "images" else images_dir
+ project_info = get_project_info(str(project_dir))
+ project_canvas = normalize_canvas_format(str(project_info.get("format", "")))
+ if project_canvas in CANVAS_FORMATS:
+ return project_canvas, "project"
+ return "ppt169", "fallback"
+
+
+def main(argv: list[str] | None = None) -> int:
"""Run the CLI entry point."""
parser = argparse.ArgumentParser(
description="Analyze image sizes and compute PPT layout dimensions"
@@ -545,48 +670,59 @@ def main() -> None:
)
parser.add_argument(
"--canvas",
- default="ppt169",
- help=f"Canvas format key (default: ppt169). Available: {', '.join(sorted(CANVAS_FORMATS.keys()))}"
+ help=(
+ "Canvas format override. By default, infer it from the project "
+ f"directory and fall back to ppt169. Available: "
+ f"{', '.join(sorted(CANVAS_FORMATS.keys()))}"
+ ),
)
- args = parser.parse_args()
+ args = parser.parse_args(argv)
+ images_dir = Path(args.images_dir).resolve()
- images_dir = os.path.abspath(args.images_dir)
-
- if not os.path.exists(images_dir):
+ if not images_dir.exists():
print(f"Error: Directory not found: {images_dir}")
- sys.exit(1)
+ return 1
- if not os.path.isdir(images_dir):
+ if not images_dir.is_dir():
print(f"Error: Not a directory: {images_dir}")
- sys.exit(1)
+ return 1
- canvas_key = args.canvas
+ canvas_key, canvas_source = _resolve_canvas_key(images_dir, args.canvas)
if canvas_key not in CANVAS_FORMATS:
- print(f"Error: Unknown canvas format '{canvas_key}'. Available: {', '.join(sorted(CANVAS_FORMATS.keys()))}")
- sys.exit(1)
+ available = ", ".join(sorted(CANVAS_FORMATS.keys()))
+ print(f"Error: Unknown canvas format '{canvas_key}'. Available: {available}")
+ return 1
fmt = CANVAS_FORMATS[canvas_key]
print(f"Analyzing: {images_dir}")
- print(f"Canvas: {fmt.get('name', canvas_key)} ({fmt.get('width', '?')}x{fmt.get('height', '?')})")
+ print(
+ f"Canvas: {fmt.get('name', canvas_key)} "
+ f"({fmt.get('width', '?')}x{fmt.get('height', '?')}; {canvas_source})"
+ )
- results = analyze_images(images_dir)
+ results, errors = _analyze_images(str(images_dir))
+ enrich_with_layout(results, canvas_key)
if results:
- enrich_with_layout(results, canvas_key)
print_results(results)
generate_markdown(results, canvas_key)
-
- # Save to CSV file (saved under the project's analysis/ directory,
- # alongside the PPTX intake bundle)
- parent_dir = os.path.dirname(images_dir)
- analysis_dir = os.path.join(parent_dir, "analysis")
- os.makedirs(analysis_dir, exist_ok=True)
- csv_path = os.path.join(analysis_dir, "image_analysis.csv")
- save_csv(results, csv_path)
else:
- print("No image files found in the directory.")
+ print("No readable supported image files found in the directory.")
+
+ analysis_dir = images_dir.parent / "analysis"
+ csv_path = analysis_dir / "image_analysis.csv"
+ save_csv(results, csv_path, include_layout=canvas_key in LAYOUT_MARGINS)
+
+ if errors:
+ print(
+ f"[ERROR] {len(errors)} supported image file(s) could not be analyzed; "
+ "the current report was still written.",
+ file=sys.stderr,
+ )
+ return 1
+ return 0
if __name__ == "__main__":
- main()
+ raise SystemExit(main())
diff --git a/skills/ppt-master/scripts/image_backends/backend_common.py b/skills/ppt-master/scripts/image_backends/backend_common.py
index dcf49a1f..50bba666 100644
--- a/skills/ppt-master/scripts/image_backends/backend_common.py
+++ b/skills/ppt-master/scripts/image_backends/backend_common.py
@@ -26,7 +26,7 @@ import time
import requests
try:
- from PIL import Image as PILImage
+ from PIL import Image as PILImage, ImageOps as PILImageOps
HAS_PIL = True
except ImportError:
HAS_PIL = False
@@ -78,11 +78,6 @@ EXT_TO_PIL_FORMAT = {
def detect_image_extension(image_bytes: bytes, content_type: str = None) -> str | None:
"""Best-effort detection of the real image format."""
- if content_type:
- clean_type = content_type.split(";", 1)[0].strip().lower()
- if clean_type in CONTENT_TYPE_TO_EXT:
- return CONTENT_TYPE_TO_EXT[clean_type]
-
if image_bytes.startswith(b"\x89PNG\r\n\x1a\n"):
return ".png"
if image_bytes.startswith(b"\xff\xd8\xff"):
@@ -95,6 +90,10 @@ def detect_image_extension(image_bytes: bytes, content_type: str = None) -> str
return ".bmp"
if image_bytes.startswith((b"II*\x00", b"MM\x00*")):
return ".tiff"
+ if content_type:
+ clean_type = content_type.split(";", 1)[0].strip().lower()
+ if clean_type in CONTENT_TYPE_TO_EXT:
+ return CONTENT_TYPE_TO_EXT[clean_type]
return None
@@ -140,10 +139,35 @@ def save_image_bytes(image_bytes: bytes, path: str, content_type: str = None) ->
if not target_format:
raise ValueError(f"Unsupported output image extension: {target_ext}")
- image = PILImage.open(io.BytesIO(image_bytes))
- if target_format == "JPEG" and image.mode in ("RGBA", "LA", "P"):
- image = image.convert("RGB")
- image.save(path, format=target_format)
+ with PILImage.open(io.BytesIO(image_bytes)) as source:
+ image = PILImageOps.exif_transpose(source)
+ try:
+ if target_format == "JPEG":
+ has_alpha = (
+ image.mode in ("RGBA", "LA")
+ or "transparency" in getattr(image, "info", {})
+ )
+ if has_alpha:
+ rgba = image.convert("RGBA")
+ alpha = rgba.getchannel("A")
+ rgb = rgba.convert("RGB")
+ converted = PILImage.new("RGB", image.size, (255, 255, 255))
+ converted.paste(rgb, mask=alpha)
+ rgb.close()
+ alpha.close()
+ rgba.close()
+ if image is not source:
+ image.close()
+ image = converted
+ elif image.mode != "RGB":
+ converted = image.convert("RGB")
+ if image is not source:
+ image.close()
+ image = converted
+ image.save(path, format=target_format)
+ finally:
+ if image is not source:
+ image.close()
if actual_ext and actual_ext != target_ext:
print(f" Converted: {actual_ext} -> {target_ext}")
@@ -197,11 +221,27 @@ def normalize_image_size(image_size: str) -> str:
def is_rate_limit_error(exc: Exception) -> bool:
"""Check whether the exception appears to be rate limiting."""
err_str = str(exc).lower()
+ status_code = getattr(exc, "status_code", None)
+ error_code = getattr(exc, "code", None)
+ response = getattr(exc, "response", None)
+ error_name = type(exc).__name__.lower()
+ if (
+ status_code == 429
+ or error_code == 429
+ or getattr(response, "status_code", None) == 429
+ or error_name in {"ratelimiterror", "toomanyrequestserror"}
+ ):
+ return True
return (
"429" in err_str
- or "rate" in err_str
+ or "rate limit" in err_str
+ or "rate-limit" in err_str
+ or "rate_limit" in err_str
+ or "too many requests" in err_str
or "quota" in err_str
or "resource_exhausted" in err_str
+ or "resource exhausted" in err_str
+ or "throttl" in err_str
)
diff --git a/skills/ppt-master/scripts/image_gen.py b/skills/ppt-master/scripts/image_gen.py
index 17fe5f2f..00558d47 100644
--- a/skills/ppt-master/scripts/image_gen.py
+++ b/skills/ppt-master/scripts/image_gen.py
@@ -44,11 +44,12 @@ Usage:
python3 image_gen.py --list-backends
"""
+import argparse
import concurrent.futures
import json
import os
+import re
import sys
-import argparse
import tempfile
import threading
import time
@@ -344,32 +345,73 @@ def _resolve_backend() -> tuple[object, str]:
sys.exit(1)
-def _confirmed_image_ai_path_for_manifest(manifest_path: str) -> str | None:
- """Return confirmed image_ai_path for a project manifest, if present."""
+_AI_IMAGE_PATH_ROW_RE = re.compile(
+ r"^\s*\|\s*AI Image Acquisition Path\s*\|\s*([^|]+?)\s*\|\s*$",
+ re.MULTILINE,
+)
+VALID_AI_IMAGE_ACQUISITION_PATHS = {
+ "api",
+ "auto",
+ "host-native",
+ "manual",
+}
+
+
+def _project_design_spec_for_manifest(manifest_path: str) -> Path | None:
+ """Return a project Design Spec for an images/ manifest, when present."""
path = Path(manifest_path).resolve()
if path.parent.name != "images":
return None
- result_file = path.parent.parent / "confirm_ui" / "result.json"
- if not result_file.exists():
+ design_spec = path.parent.parent / "design_spec.md"
+ return design_spec if design_spec.is_file() else None
+
+
+def _confirmed_image_acquisition_path_for_manifest(
+ manifest_path: str,
+) -> str | None:
+ """Return the Design Spec's AI Image Acquisition Path, if present."""
+ design_spec = _project_design_spec_for_manifest(manifest_path)
+ if design_spec is None:
return None
try:
- data = json.loads(result_file.read_text(encoding="utf-8"))
- except (OSError, json.JSONDecodeError):
+ text = design_spec.read_text(encoding="utf-8")
+ except OSError:
return None
- value = data.get("image_ai_path")
- if not isinstance(value, str):
+ match = _AI_IMAGE_PATH_ROW_RE.search(text)
+ if not match:
return None
- return value.strip().lower().replace("_", "-")
+ value = match.group(1).strip().lstrip("`*_ ").strip()
+ token_match = re.match(
+ r"^(host[\s_-]*native|api|auto|manual)(?![A-Za-z0-9_-])",
+ value,
+ re.IGNORECASE,
+ )
+ selected = token_match.group(1) if token_match else value
+ return re.sub(r"[\s_]+", "-", selected.strip().lower())
def _guard_confirmed_non_api_path(manifest_path: str) -> None:
- """Prevent accidental Path A execution after host-native/manual was confirmed."""
- image_ai_path = _confirmed_image_ai_path_for_manifest(manifest_path)
- if image_ai_path not in {"host-native", "manual"}:
+ """Allow project Path A only when its Design Spec explicitly permits it."""
+ design_spec = _project_design_spec_for_manifest(manifest_path)
+ if design_spec is None:
+ return
+ acquisition_path = _confirmed_image_acquisition_path_for_manifest(manifest_path)
+ if acquisition_path not in VALID_AI_IMAGE_ACQUISITION_PATHS:
+ shown = acquisition_path or "(missing)"
+ valid = ", ".join(sorted(VALID_AI_IMAGE_ACQUISITION_PATHS))
+ print(
+ "Error: project manifest mode requires a valid "
+ "AI Image Acquisition Path in design_spec.md §I.\n"
+ f"Found: {shown!r}. Valid values: {valid}.\n"
+ "Return to Generate Step 4 recovery and record the durable "
+ "selection before running Path A."
+ )
+ sys.exit(1)
+ if acquisition_path in {"api", "auto"}:
return
- if image_ai_path == "host-native":
+ if acquisition_path == "host-native":
print(
- "Error: confirmed image_ai_path is 'host-native'.\n"
+ "Error: Design Spec confirms AI Image Acquisition Path as 'host-native'.\n"
"\n"
"Do NOT run image_gen.py --manifest for this project. That command is Path A\n"
"and may use the configured API/proxy backend. Use the host's native image\n"
@@ -379,7 +421,7 @@ def _guard_confirmed_non_api_path(manifest_path: str) -> None:
)
else:
print(
- "Error: confirmed image_ai_path is 'manual'.\n"
+ "Error: Design Spec confirms AI Image Acquisition Path as 'manual'.\n"
"\n"
"Do NOT run image_gen.py --manifest for this project. Render the Markdown\n"
"sidecar and hand images/image_prompts.md to the user for external generation:\n"
@@ -389,6 +431,7 @@ def _guard_confirmed_non_api_path(manifest_path: str) -> None:
DEFAULT_MANIFEST_CONCURRENCY = 3
+MAX_MANIFEST_RATE_LIMIT_ATTEMPTS = 3
STATUS_PENDING = "Pending"
STATUS_GENERATED = "Generated"
@@ -397,18 +440,42 @@ STATUS_NEEDS_MANUAL = "Needs-Manual"
VALID_STATUSES = {STATUS_PENDING, STATUS_GENERATED, STATUS_FAILED, STATUS_NEEDS_MANUAL}
RETRYABLE_STATUSES = {STATUS_PENDING, STATUS_FAILED}
REQUIRED_ITEM_FIELDS = ("filename", "prompt", "aspect_ratio", "status")
+VALID_PAGE_ROLES = {"local", "hero_page", "full_page"}
+VALID_TEXT_POLICIES = {"none", "embedded"}
+STRUCTURAL_IMAGE_TYPES = {
+ "infographic",
+ "flowchart",
+ "framework",
+ "matrix",
+ "cycle",
+ "funnel",
+ "pyramid",
+ "comparison",
+ "timeline",
+ "map",
+ "scene",
+}
+LEGACY_IMAGE_TYPES = {"background", "hero", "portrait", "typography"}
+EARLY_LEGACY_IMAGE_TYPES = {"illustration", "photography"}
+VALID_IMAGE_TYPES = (
+ STRUCTURAL_IMAGE_TYPES
+ | LEGACY_IMAGE_TYPES
+ | EARLY_LEGACY_IMAGE_TYPES
+)
def load_manifest(path: str) -> dict:
"""Load and validate an `image_prompts.json` manifest.
Schema (top level): {"items": [ ... ]}, optionally with
- `deck_style_anchor`, `color_scheme`, `generated_at`.
+ `deck_rendering`, `color_scheme`, `generated_at`.
Each item requires: `filename`, `prompt`, `aspect_ratio`, `status`.
Optional: `image_size`, `model`, `alt_text`, `purpose`, `type`,
- `last_error`.
+ `page_role`, `text_policy`, `slice_grid`, `slice_names`, `last_error`.
"""
+ from image_backends.backend_common import normalize_image_size
+
try:
data = json.loads(Path(path).read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
@@ -423,12 +490,51 @@ def load_manifest(path: str) -> dict:
f"got {type(data).__name__}"
)
+ for field in ("project", "generated_at", "deck_rendering"):
+ if field not in data:
+ continue
+ if not isinstance(data[field], str) or not data[field].strip():
+ raise ValueError(
+ f"{path}: field '{field}' must be a non-empty string when present"
+ )
+ if "deck_style_anchor" in data:
+ legacy_anchor = data["deck_style_anchor"]
+ if not (
+ isinstance(legacy_anchor, str)
+ and legacy_anchor.strip()
+ or isinstance(legacy_anchor, dict)
+ and legacy_anchor
+ ):
+ raise ValueError(
+ f"{path}: legacy field 'deck_style_anchor' must be a "
+ "non-empty string or object when present"
+ )
+
+ if "color_scheme" in data:
+ color_scheme = data["color_scheme"]
+ if not isinstance(color_scheme, dict) or not color_scheme:
+ raise ValueError(
+ f"{path}: field 'color_scheme' must be a non-empty object when present"
+ )
+ for key, value in color_scheme.items():
+ if (
+ not isinstance(key, str)
+ or not key.strip()
+ or not isinstance(value, str)
+ or not value.strip()
+ ):
+ raise ValueError(
+ f"{path}: color_scheme keys and values must be non-empty strings"
+ )
+
items = data.get("items")
if not isinstance(items, list) or not items:
raise ValueError(f"{path}: 'items' must be a non-empty array")
seen_filenames: set[str] = set()
seen_stems: set[str] = set()
+ missing_page_role = 0
+ missing_text_policy = 0
for i, item in enumerate(items):
prefix = f"{path}: items[{i}]"
if not isinstance(item, dict):
@@ -445,6 +551,131 @@ def load_manifest(path: str) -> dict:
f"{prefix} status '{item['status']}' is invalid. "
f"Valid: {sorted(VALID_STATUSES)}"
)
+ if item["aspect_ratio"] not in ALL_ASPECT_RATIOS:
+ raise ValueError(
+ f"{prefix} aspect_ratio '{item['aspect_ratio']}' is invalid. "
+ f"Valid: {ALL_ASPECT_RATIOS}"
+ )
+ if "image_size" in item:
+ image_size = item["image_size"]
+ if not isinstance(image_size, str) or not image_size.strip():
+ raise ValueError(
+ f"{prefix} field 'image_size' must be a non-empty string"
+ )
+ normalized_size = normalize_image_size(image_size)
+ if normalized_size not in ALL_IMAGE_SIZES:
+ raise ValueError(
+ f"{prefix} image_size '{image_size}' is invalid. "
+ f"Valid: {ALL_IMAGE_SIZES}"
+ )
+
+ page_role = item.get("page_role")
+ if page_role is None:
+ missing_page_role += 1
+ elif not isinstance(page_role, str) or page_role not in VALID_PAGE_ROLES:
+ raise ValueError(
+ f"{prefix} page_role '{page_role}' is invalid. "
+ f"Valid: {sorted(VALID_PAGE_ROLES)}"
+ )
+
+ text_policy = item.get("text_policy")
+ if text_policy is None:
+ missing_text_policy += 1
+ elif (
+ not isinstance(text_policy, str)
+ or text_policy not in VALID_TEXT_POLICIES
+ ):
+ raise ValueError(
+ f"{prefix} text_policy '{text_policy}' is invalid. "
+ f"Valid: {sorted(VALID_TEXT_POLICIES)}"
+ )
+
+ image_type = item.get("type")
+ if image_type is not None:
+ normalized_type = (
+ image_type.strip().lower()
+ if isinstance(image_type, str)
+ else ""
+ )
+ if normalized_type not in VALID_IMAGE_TYPES:
+ raise ValueError(
+ f"{prefix} type '{image_type}' is invalid. "
+ f"Valid current/legacy values: {sorted(VALID_IMAGE_TYPES)}"
+ )
+
+ for field in ("model", "alt_text", "purpose"):
+ if field in item and (
+ not isinstance(item[field], str) or not item[field].strip()
+ ):
+ raise ValueError(
+ f"{prefix} field '{field}' must be a non-empty string when present"
+ )
+ if "last_error" in item and not isinstance(item["last_error"], str):
+ raise ValueError(f"{prefix} field 'last_error' must be a string")
+ has_slice_grid = "slice_grid" in item
+ has_slice_names = "slice_names" in item
+ if has_slice_grid != has_slice_names:
+ raise ValueError(
+ f"{prefix} fields 'slice_grid' and 'slice_names' must appear together"
+ )
+ if has_slice_grid:
+ slice_grid = item["slice_grid"]
+ grid_match = (
+ re.fullmatch(r"([1-9]\d*)[xX]([1-9]\d*)", slice_grid.strip())
+ if isinstance(slice_grid, str)
+ else None
+ )
+ if grid_match is None:
+ raise ValueError(
+ f"{prefix} field 'slice_grid' must use positive RxC notation"
+ )
+ slice_names = item["slice_names"]
+ if not isinstance(slice_names, str) or not slice_names.strip():
+ raise ValueError(
+ f"{prefix} field 'slice_names' must be a non-empty string"
+ )
+ names = [name.strip() for name in slice_names.split(",")]
+ if any(not name for name in names):
+ raise ValueError(
+ f"{prefix} field 'slice_names' contains an empty name"
+ )
+ rows, cols = map(int, grid_match.groups())
+ if len(names) != rows * cols:
+ raise ValueError(
+ f"{prefix} field 'slice_names' has {len(names)} names but "
+ f"slice_grid {rows}x{cols} requires {rows * cols}"
+ )
+ normalized_outputs: set[str] = set()
+ for name in names:
+ name_path = Path(name)
+ if (
+ name in {".", ".."}
+ or ".." in name
+ or "/" in name
+ or "\\" in name
+ or ":" in name
+ or name_path.is_absolute()
+ or name_path.name != name
+ ):
+ raise ValueError(
+ f"{prefix} slice output name {name!r} must be a safe "
+ "bare filename"
+ )
+ if name_path.suffix and name_path.suffix.lower() != ".png":
+ raise ValueError(
+ f"{prefix} slice output name {name!r} must omit its "
+ "extension or use .png"
+ )
+ output_name = (
+ name if name_path.suffix else f"{name}.png"
+ ).casefold()
+ if output_name in normalized_outputs:
+ raise ValueError(
+ f"{prefix} field 'slice_names' repeats output "
+ f"{output_name!r}"
+ )
+ normalized_outputs.add(output_name)
+
fname = item["filename"]
filename_path = Path(fname)
if (
@@ -471,6 +702,22 @@ def load_manifest(path: str) -> dict:
)
seen_stems.add(stem)
+ legacy_parts = []
+ if missing_page_role:
+ legacy_parts.append(
+ f"{missing_page_role} item(s) missing page_role (resolved as local)"
+ )
+ if missing_text_policy:
+ legacy_parts.append(
+ f"{missing_text_policy} item(s) missing text_policy (resolved as none)"
+ )
+ if legacy_parts:
+ print(
+ f"Warning: {path}: legacy manifest compatibility: "
+ + "; ".join(legacy_parts),
+ file=sys.stderr,
+ )
+
return data
@@ -526,9 +773,14 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
"""Run Pending/Failed items through the backend with adaptive concurrency.
Strategy:
+ - Verify every `Generated` item's target before treating it as done;
+ missing or unreadable output returns to `Failed` for this run.
- Start at `initial_concurrency` workers per batch.
- On any rate-limit error in a batch, halve concurrency (min 1) and
- requeue the rate-limited items.
+ requeue the rate-limited items within a fixed attempt budget.
+ - A rate limit at concurrency 1 or after the budget is exhausted is
+ recorded as `status: Failed` + `last_error`; the current run then stops
+ without switching providers.
- Per-item failures are recorded as `status: Failed` + `last_error`
and not retried within this run. `Failed` remains retryable and
non-terminal; the Step 5 gate must resolve it by rerunning this
@@ -539,9 +791,32 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
Returns (ok_count, failed_count, skipped_count).
"""
- from image_backends.backend_common import is_rate_limit_error
+ from image_backends.backend_common import (
+ is_rate_limit_error,
+ validate_image_file,
+ )
items = manifest["items"]
+ repaired_generated = False
+ for item in items:
+ if item["status"] != STATUS_GENERATED:
+ continue
+ target_path = Path(output_dir) / item["filename"]
+ try:
+ validate_image_file(str(target_path))
+ except RuntimeError as exc:
+ item["status"] = STATUS_FAILED
+ item["last_error"] = (
+ f"Generated file validation failed: {exc}"
+ )[:500]
+ repaired_generated = True
+ print(
+ f" [RETRY] {item['filename']} was marked Generated but its "
+ f"target is invalid: {exc}"
+ )
+ if repaired_generated:
+ save_manifest(manifest_path, manifest)
+
pending_idx = [
i for i, it in enumerate(items) if it["status"] in RETRYABLE_STATUSES
]
@@ -565,6 +840,8 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
fail_count = 0
current = max(1, initial_concurrency)
state_lock = threading.Lock()
+ rate_limit_attempts: dict[int, int] = {}
+ stopped_for_rate_limit = False
def _one(idx: int):
item = items[idx]
@@ -609,8 +886,35 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
print(f" [OK] {item['filename']}")
elif is_rate_limit_error(exc):
rate_limited = True
- queue.append(idx)
- print(f" [RATE] {item['filename']} — requeued")
+ attempts = rate_limit_attempts.get(idx, 0) + 1
+ rate_limit_attempts[idx] = attempts
+ if (
+ current == 1
+ or attempts >= MAX_MANIFEST_RATE_LIMIT_ATTEMPTS
+ ):
+ boundary = (
+ "serial concurrency reached"
+ if current == 1
+ else "rate-limit attempt budget exhausted"
+ )
+ item["status"] = STATUS_FAILED
+ item["last_error"] = (
+ f"Rate limit persisted ({boundary}; "
+ f"attempt {attempts}): {exc}"
+ )[:500]
+ fail_count += 1
+ stopped_for_rate_limit = True
+ print(
+ f" [FAIL] {item['filename']}: {exc} "
+ f"({boundary}; status=Failed)"
+ )
+ else:
+ queue.append(idx)
+ print(
+ f" [RATE] {item['filename']} — requeued "
+ f"(attempt {attempts}/"
+ f"{MAX_MANIFEST_RATE_LIMIT_ATTEMPTS})"
+ )
else:
item["status"] = STATUS_FAILED
item["last_error"] = str(exc)[:500]
@@ -621,7 +925,13 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
)
save_manifest(manifest_path, manifest)
- if rate_limited and current > 1:
+ if stopped_for_rate_limit:
+ print(
+ "\n Persistent rate limit reached the run boundary. "
+ "Stopping without switching providers; untouched items remain retryable.\n"
+ )
+ break
+ if rate_limited and current > 1 and queue:
new_current = max(1, current // 2)
print(
f"\n ⚠ Rate-limit hit — concurrency {current} → {new_current}, "
@@ -632,9 +942,17 @@ def _run_manifest(manifest: dict, manifest_path: str, backend_module, *,
elif queue:
time.sleep(2)
+ run_state = "Stopped" if stopped_for_rate_limit else "Done"
+ remaining_note = ""
+ if stopped_for_rate_limit:
+ remaining = sum(
+ 1 for item in items if item["status"] in RETRYABLE_STATUSES
+ )
+ remaining_note = f"; {remaining} item(s) remain retryable"
print(
- f"\n[Manifest] Done: {ok_count} ok / {fail_count} failed "
- f"({skipped} pre-skipped). Manifest written to {manifest_path}"
+ f"\n[Manifest] {run_state}: {ok_count} ok / {fail_count} failed "
+ f"({skipped} pre-skipped{remaining_note}). "
+ f"Manifest written to {manifest_path}"
)
if fail_count:
print(
@@ -672,7 +990,16 @@ def render_manifest_md(manifest: dict) -> str:
project = manifest.get("project")
generated_at = manifest.get("generated_at")
color_scheme = manifest.get("color_scheme") or {}
- anchor = manifest.get("deck_style_anchor")
+ deck_rendering = manifest.get("deck_rendering")
+ if not deck_rendering:
+ legacy_anchor = manifest.get("deck_style_anchor")
+ if isinstance(legacy_anchor, dict):
+ deck_rendering = (
+ legacy_anchor.get("visual_style")
+ or json.dumps(legacy_anchor, ensure_ascii=False, sort_keys=True)
+ )
+ else:
+ deck_rendering = legacy_anchor
if project:
lines.append(f"> Project: {project}")
@@ -683,8 +1010,8 @@ def render_manifest_md(manifest: dict) -> str:
f"{k.capitalize()} {v}" for k, v in color_scheme.items()
)
lines.append(f"> Color scheme: {cs}")
- if anchor:
- lines.append(f"> Deck Style Anchor: {anchor}")
+ if deck_rendering:
+ lines.append(f"> Deck Rendering: {deck_rendering}")
lines.append("")
lines.append("---")
lines.append("")
@@ -697,11 +1024,20 @@ def render_manifest_md(manifest: dict) -> str:
for label, key in (
("Purpose", "purpose"),
("Type", "type"),
+ ("Page role", "page_role"),
+ ("Text policy", "text_policy"),
("Aspect ratio", "aspect_ratio"),
("Image size", "image_size"),
+ ("Model", "model"),
+ ("Slice grid", "slice_grid"),
+ ("Slice names", "slice_names"),
("Status", "status"),
):
value = item.get(key)
+ if not value and key == "page_role":
+ value = "local (legacy default)"
+ elif not value and key == "text_policy":
+ value = "none (legacy default)"
if value:
lines.append(f"| {label} | {value} |")
if item.get("last_error"):
diff --git a/skills/ppt-master/scripts/image_search.py b/skills/ppt-master/scripts/image_search.py
index af1da0f6..0eb7bc57 100644
--- a/skills/ppt-master/scripts/image_search.py
+++ b/skills/ppt-master/scripts/image_search.py
@@ -271,12 +271,16 @@ def _validate_downloaded_quality(path: Path) -> bool:
written to disk and rejects thumbnails / previews.
"""
try:
- from PIL import Image # type: ignore
+ from PIL import Image, ImageOps # type: ignore
except ImportError:
return True # can't check without Pillow; assume OK
try:
with Image.open(path) as im:
- w, h = im.size
+ oriented = ImageOps.exif_transpose(im)
+ oriented.load()
+ w, h = oriented.size
+ if oriented is not im:
+ oriented.close()
if w * h < _MIN_DOWNLOAD_PIXELS:
print(
f" rejected: downloaded image too small "
@@ -285,8 +289,12 @@ def _validate_downloaded_quality(path: Path) -> bool:
)
return False
return True
- except (OSError, ValueError):
- return True # unreadable image; let downstream handle it
+ except (OSError, SyntaxError, ValueError) as exc:
+ print(
+ f" rejected: downloaded file is not a readable image ({exc})",
+ file=sys.stderr,
+ )
+ return False
def _write_review_copy(
@@ -300,16 +308,20 @@ def _write_review_copy(
returns None (non-fatal) if Pillow or the source is unavailable.
"""
try:
- from PIL import Image # type: ignore
+ from PIL import Image, ImageOps # type: ignore
except ImportError:
return None
try:
dest_dir.mkdir(parents=True, exist_ok=True)
review_path = dest_dir / f"{Path(name).stem}.jpg"
with Image.open(src) as im:
- im = im.convert("RGB")
- im.thumbnail((max_side, max_side))
- im.save(review_path, "JPEG", quality=85)
+ oriented = ImageOps.exif_transpose(im)
+ review = oriented.convert("RGB")
+ review.thumbnail((max_side, max_side))
+ review.save(review_path, "JPEG", quality=85)
+ review.close()
+ if oriented is not im:
+ oriented.close()
return review_path
except (OSError, ValueError):
return None
@@ -481,6 +493,22 @@ def default_manifest_path(output_dir: str) -> Path:
return Path(output_dir) / "image_sources.json"
+def _validate_bare_filename(value: str, *, field_name: str = "filename") -> str:
+ """Require a bare filename with no absolute or parent path components."""
+ if (
+ not value.strip()
+ or value in {".", ".."}
+ or "/" in value
+ or "\\" in value
+ or ":" in value
+ or Path(value).is_absolute()
+ ):
+ raise ValueError(
+ f"{field_name} must be a bare filename without path components: {value!r}"
+ )
+ return value
+
+
def _measure_actual_image(path: Path) -> Optional[tuple[int, int]]:
"""Return ``(width, height)`` of the file actually saved at ``path``.
@@ -494,12 +522,17 @@ def _measure_actual_image(path: Path) -> Optional[tuple[int, int]]:
Returns ``None`` if Pillow is unavailable or the file is unreadable.
"""
try:
- from PIL import Image # type: ignore
+ from PIL import Image, ImageOps # type: ignore
except ImportError:
return None
try:
with Image.open(path) as im:
- return int(im.width), int(im.height)
+ oriented = ImageOps.exif_transpose(im)
+ try:
+ return int(oriented.width), int(oriented.height)
+ finally:
+ if oriented is not im:
+ oriented.close()
except (OSError, ValueError):
return None
@@ -572,20 +605,72 @@ def _read_existing_manifest(path: Path) -> dict:
if not path.exists():
return {}
try:
- return json.loads(path.read_text(encoding="utf-8"))
+ payload = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
- print(
- f" warning: existing manifest at {path} is unreadable, "
- f"starting fresh ({exc})",
- file=sys.stderr,
+ raise RuntimeError(
+ f"existing image sources manifest is unreadable: {path} ({exc}); "
+ "repair or restore it before continuing"
+ ) from exc
+ if not isinstance(payload, dict):
+ raise RuntimeError(
+ f"existing image sources manifest must be a JSON object: {path}"
)
- return {}
+ items = payload.get("items")
+ if not isinstance(items, list):
+ raise RuntimeError(
+ f"existing image sources manifest must contain an 'items' array: {path}"
+ )
+ if any(not isinstance(item, dict) for item in items):
+ raise RuntimeError(
+ f"existing image sources manifest contains a non-object item: {path}"
+ )
+ seen_filenames: set[str] = set()
+ for index, item in enumerate(items):
+ filename = item.get("filename")
+ if not isinstance(filename, str):
+ raise RuntimeError(
+ f"existing image sources manifest items[{index}].filename "
+ f"must be a non-empty bare filename: {path}"
+ )
+ try:
+ _validate_bare_filename(filename)
+ except ValueError as exc:
+ raise RuntimeError(
+ f"existing image sources manifest items[{index}]: {exc}: {path}"
+ ) from exc
+ if filename in seen_filenames:
+ raise RuntimeError(
+ f"existing image sources manifest contains duplicate filename "
+ f"{filename!r}: {path}"
+ )
+ seen_filenames.add(filename)
+ return payload
+
+
+def _write_json_atomic(path: str | Path, payload: dict) -> Path:
+ """Write JSON through a same-directory temporary file and atomic rename."""
+ target = ensure_json_parent(path)
+ fd, tmp_path = tempfile.mkstemp(
+ prefix=target.stem + ".", suffix=".tmp", dir=str(target.parent)
+ )
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ json.dump(payload, handle, ensure_ascii=False, indent=2)
+ handle.write("\n")
+ os.replace(tmp_path, target)
+ except Exception:
+ try:
+ os.unlink(tmp_path)
+ except OSError:
+ pass
+ raise
+ return target
def write_sources_manifest(path: Path, item: dict) -> Path:
"""Append ``item`` to the manifest at ``path``, replacing any prior
entry that targets the same filename."""
- manifest_path = ensure_json_parent(path)
+ manifest_path = Path(path)
payload = _read_existing_manifest(manifest_path)
items: list[dict] = list(payload.get("items") or [])
@@ -599,11 +684,7 @@ def write_sources_manifest(path: Path, item: dict) -> Path:
"provider metadata used; manual review recommended for external delivery",
)
- manifest_path.write_text(
- json.dumps(payload, indent=2, ensure_ascii=False) + "\n",
- encoding="utf-8",
- )
- return manifest_path
+ return _write_json_atomic(manifest_path, payload)
# ---------------------------------------------------------------------------
@@ -626,6 +707,19 @@ def promote_candidate(
"""
import shutil
+ target_filename = _validate_bare_filename(
+ target_filename, field_name="target filename"
+ )
+ candidate_filename = _validate_bare_filename(
+ candidate_filename, field_name="candidate filename"
+ )
+ mpath = manifest_path or default_manifest_path(str(output_dir))
+ try:
+ manifest = _read_existing_manifest(mpath)
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
stem = Path(target_filename).stem
cand_dir = output_dir / "candidates" / stem
cand_meta_path = cand_dir / "candidates.json"
@@ -660,17 +754,13 @@ def promote_candidate(
# Update candidates.json
meta["selected"] = candidate_filename
- cand_meta_path.write_text(
- json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8",
- )
+ _write_json_atomic(cand_meta_path, meta)
# Update image_sources.json
- mpath = manifest_path or default_manifest_path(str(output_dir))
actual_dim = _measure_actual_image(dst_path)
w = actual_dim[0] if actual_dim else entry.get("width", 0)
h = actual_dim[1] if actual_dim else entry.get("height", 0)
- manifest = _read_existing_manifest(mpath)
items: list[dict] = list(manifest.get("items") or [])
for item in items:
if item.get("filename") == target_filename:
@@ -707,9 +797,7 @@ def promote_candidate(
break
manifest["items"] = items
manifest["generated_at"] = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
- mpath.write_text(
- json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8",
- )
+ _write_json_atomic(mpath, manifest)
print(f" manifest updated: {mpath}", file=sys.stderr)
return 0
@@ -739,6 +827,24 @@ def fetch_url_replace(
for an arbitrary URL, so the manifest marks it ``manual`` and notes that
verifying usage rights is the user's responsibility.
"""
+ target_filename = _validate_bare_filename(
+ target_filename, field_name="target filename"
+ )
+ mpath = manifest_path or default_manifest_path(str(output_dir))
+ try:
+ existing_manifest = _read_existing_manifest(mpath)
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+ prior = next(
+ (
+ item
+ for item in existing_manifest.get("items", [])
+ if item.get("filename") == target_filename
+ ),
+ {},
+ )
+
output_dir.mkdir(parents=True, exist_ok=True)
dst_path = output_dir / target_filename
try:
@@ -756,15 +862,9 @@ def fetch_url_replace(
print(f" review copy: {review}", file=sys.stderr)
actual_dim = _measure_actual_image(dst_path)
- mpath = manifest_path or default_manifest_path(str(output_dir))
# Inherit page context (which slide / purpose / query this image serves)
# from the entry being replaced; override only source / license / size /
# status so the audit trail survives a manual swap.
- prior = next(
- (i for i in _read_existing_manifest(mpath).get("items", [])
- if i.get("filename") == target_filename),
- {},
- )
item = {
"filename": target_filename,
"slide": prior.get("slide") or slide,
@@ -848,6 +948,10 @@ def load_search_manifest(path: str) -> dict:
except ValueError as exc:
raise ValueError(f"{prefix} {exc}") from exc
fname = item["filename"]
+ try:
+ _validate_bare_filename(fname)
+ except ValueError as exc:
+ raise ValueError(f"{prefix} {exc}") from exc
if fname in seen_filenames:
raise ValueError(f"{prefix} duplicate filename '{fname}'")
seen_filenames.add(fname)
@@ -857,21 +961,7 @@ def load_search_manifest(path: str) -> dict:
def save_search_manifest(path: str, data: dict) -> None:
"""Atomically write the batch manifest back (tmp file + rename)."""
- target = Path(path)
- fd, tmp_path = tempfile.mkstemp(
- prefix=target.stem + ".", suffix=".tmp", dir=str(target.parent)
- )
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as f:
- json.dump(data, f, ensure_ascii=False, indent=2)
- f.write("\n")
- os.replace(tmp_path, target)
- except Exception:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
+ _write_json_atomic(path, data)
def _resolve_search_concurrency(cli_value: Optional[int]) -> int:
@@ -900,6 +990,7 @@ def _search_one_item(
Returns ``(manifest_item, error)``. Only the network/disk work happens
here; all manifest writes are serialized by the caller.
"""
+ filename = _validate_bare_filename(item["filename"])
orientation = item.get("orientation", "any") or "any"
strict = bool(item.get("strict_no_attribution", default_strict))
required_terms = _parse_required_terms(item.get("required_terms"))
@@ -908,7 +999,7 @@ def _search_one_item(
query=item["query"],
purpose=item.get("purpose", ""),
orientation="" if orientation == "any" else orientation,
- filename=item["filename"],
+ filename=filename,
slide=item.get("slide", ""),
min_width=int(item.get("min_width", default_min_width)),
min_height=int(item.get("min_height", default_min_height)),
@@ -917,7 +1008,7 @@ def _search_one_item(
pinned = item.get("provider") or default_provider
providers = [pinned] if pinned else _default_provider_chain()
- output_path = output_dir / item["filename"]
+ output_path = output_dir / filename
candidate, provider_name, stage = search_and_download(
providers,
@@ -932,7 +1023,7 @@ def _search_one_item(
actual_dimensions = _measure_actual_image(output_path)
item_args = argparse.Namespace(
- filename=item["filename"],
+ filename=filename,
slide=item.get("slide", ""),
purpose=item.get("purpose", ""),
query=item["query"],
@@ -971,6 +1062,7 @@ def run_search_manifest(
(terminal). Status is written back after each completion, so an interrupt
preserves finished rows. Returns ``(sourced, needs_manual, skipped)``.
"""
+ _read_existing_manifest(sources_manifest_path)
items = manifest["items"]
pending_idx = [
i for i, it in enumerate(items)
@@ -1056,7 +1148,7 @@ def build_parser() -> argparse.ArgumentParser:
"query",
nargs="?",
default=None,
- help="Search query (2-5 keywords work best). Omit in --batch mode.",
+ help="Search query (1-4 concrete keywords work best). Omit in --batch mode.",
)
parser.add_argument(
"--filename",
@@ -1212,6 +1304,16 @@ def main(argv: Optional[list[str]] = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
+ try:
+ if args.filename:
+ args.filename = _validate_bare_filename(args.filename)
+ if args.promote:
+ args.promote = _validate_bare_filename(
+ args.promote, field_name="--promote candidate filename"
+ )
+ except ValueError as exc:
+ parser.error(str(exc))
+
output_dir = Path(args.output)
# --- Promote mode ---
@@ -1276,6 +1378,9 @@ def main(argv: Optional[list[str]] = None) -> int:
except KeyboardInterrupt:
print("\n\nInterrupted by user. Partial progress preserved in manifest.")
return 130
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
# Mirror image_gen.py: a non-zero code flags rows that need manual
# attention. It is a signal, not a halt — the workflow (image-base.md
# §6) surfaces Needs-Manual rows and continues regardless.
@@ -1301,6 +1406,15 @@ def main(argv: Optional[list[str]] = None) -> int:
providers = [args.provider] if args.provider else _default_provider_chain()
+ manifest_path = (
+ Path(args.manifest) if args.manifest else default_manifest_path(args.output)
+ )
+ try:
+ _read_existing_manifest(manifest_path)
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
+
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / args.filename
@@ -1357,8 +1471,11 @@ def main(argv: Optional[list[str]] = None) -> int:
stage=stage,
actual_dimensions=actual_dimensions,
)
- manifest_path = Path(args.manifest) if args.manifest else default_manifest_path(args.output)
- write_sources_manifest(manifest_path, item)
+ try:
+ write_sources_manifest(manifest_path, item)
+ except RuntimeError as exc:
+ print(f"Error: {exc}", file=sys.stderr)
+ return 1
print(f" manifest: {manifest_path}", file=sys.stderr)
if candidate.license_tier == "attribution-required":
diff --git a/skills/ppt-master/scripts/image_sources/provider_common.py b/skills/ppt-master/scripts/image_sources/provider_common.py
index 6a438f80..90db6885 100644
--- a/skills/ppt-master/scripts/image_sources/provider_common.py
+++ b/skills/ppt-master/scripts/image_sources/provider_common.py
@@ -446,6 +446,11 @@ def score_candidate(candidate: AssetCandidate, request: ImageSearchRequest) -> f
"""
if not candidate.license_tier:
return float("-inf")
+ if (
+ candidate.license_tier == LICENSE_TIER_ATTRIBUTION_REQUIRED
+ and not candidate.author.strip()
+ ):
+ return float("-inf")
required_misses = missing_required_terms(candidate, request.required_terms)
if required_misses:
diff --git a/skills/ppt-master/scripts/project_manager.py b/skills/ppt-master/scripts/project_manager.py
index 19d2c363..231eb1d8 100644
--- a/skills/ppt-master/scripts/project_manager.py
+++ b/skills/ppt-master/scripts/project_manager.py
@@ -75,8 +75,10 @@ from _dispatcher import ( # noqa: E402
SOURCE_DIRNAME = "sources"
TEXT_SOURCE_SUFFIXES = {".md", ".markdown", ".txt"}
TABLE_TEXT_SUFFIXES = {".csv", ".tsv"}
-IMAGE_ASSET_SUFFIXES = {
+BITMAP_IMAGE_SUFFIXES = {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".tif",
+}
+IMAGE_ASSET_SUFFIXES = BITMAP_IMAGE_SUFFIXES | {
".emf", ".wmf", ".svg",
}
@@ -640,6 +642,7 @@ class ProjectManager:
"archived": [],
"markdown": [],
"assets": [],
+ "images": [],
"analysis": [],
"notes": [],
"skipped": [],
@@ -760,7 +763,18 @@ class ProjectManager:
)
summary["archived"].append(str(archived_path))
- if suffix in PDF_SUFFIXES:
+ if suffix in BITMAP_IMAGE_SUFFIXES:
+ images_dir = project_dir / "images"
+ images_dir.mkdir(parents=True, exist_ok=True)
+ image_path = self._ensure_unique_path(images_dir / archived_path.name)
+ shutil.copy2(archived_path, image_path)
+ summary["images"].append(str(image_path))
+ if image_path.name != archived_path.name:
+ summary["notes"].append(
+ f"{item}: copied runtime image as {image_path.name} "
+ "to avoid a filename collision"
+ )
+ elif suffix in PDF_SUFFIXES:
canonical_markdown_path = sources_dir / f"{archived_path.stem}.md"
if archived_path.stem in explicit_markdown_stems:
summary["notes"].append(
@@ -1050,6 +1064,10 @@ def main(argv: list[str] | None = None) -> int:
print("\nImported asset directories:")
for item in summary["assets"]:
print(f" - {item}")
+ if summary["images"]:
+ print("\nRuntime image copies:")
+ for item in summary["images"]:
+ print(f" - {item}")
if summary["analysis"]:
print("\nAnalysis artifacts:")
for item in summary["analysis"]:
diff --git a/skills/ppt-master/scripts/resource_paths.py b/skills/ppt-master/scripts/resource_paths.py
index 52061ddd..1d6f3e29 100644
--- a/skills/ppt-master/scripts/resource_paths.py
+++ b/skills/ppt-master/scripts/resource_paths.py
@@ -70,20 +70,30 @@ def external_image_reference_candidates(svg_dir: Path, href: str) -> list[Path]:
else href.split('?', 1)[0].split('#', 1)[0]
)
svg_dir = Path(svg_dir)
- project_root = project_root_for_svg_path(svg_dir)
- return [
+ project_root = project_root_for_svg_path(svg_dir).resolve()
+ candidates = [
svg_dir / decoded,
project_root / decoded,
project_root / 'images' / decoded,
project_root / 'templates' / decoded,
]
+ safe_candidates: list[Path] = []
+ for candidate in candidates:
+ resolved = candidate.resolve()
+ try:
+ resolved.relative_to(project_root)
+ except ValueError:
+ continue
+ if resolved not in safe_candidates:
+ safe_candidates.append(resolved)
+ return safe_candidates
def resolve_external_image_reference(svg_dir: Path, href: str) -> Path | None:
"""Resolve an SVG image href to an existing file, or return None."""
for candidate in external_image_reference_candidates(svg_dir, href):
- if candidate.exists():
- return candidate.resolve()
+ if candidate.is_file():
+ return candidate
return None
diff --git a/skills/ppt-master/scripts/svg_finalize/align_embed_images.py b/skills/ppt-master/scripts/svg_finalize/align_embed_images.py
index 7c0f12e0..4190251d 100644
--- a/skills/ppt-master/scripts/svg_finalize/align_embed_images.py
+++ b/skills/ppt-master/scripts/svg_finalize/align_embed_images.py
@@ -51,7 +51,6 @@ import re
import sys
from pathlib import Path
from typing import TYPE_CHECKING
-from urllib.parse import unquote
from xml.etree import ElementTree as ET
_SCRIPTS_DIR = Path(__file__).resolve().parents[1]
@@ -59,6 +58,7 @@ if str(_SCRIPTS_DIR) not in sys.path:
sys.path.insert(0, str(_SCRIPTS_DIR))
from console_encoding import configure_utf8_stdio # noqa: E402
+from resource_paths import resolve_external_image_reference # noqa: E402
configure_utf8_stdio()
@@ -119,14 +119,7 @@ def _resolve_image_path(href: str, svg_dir: Path) -> Path | None:
"""
if not href:
return None
- decoded = unquote(href)
- if decoded.startswith(('http://', 'https://', 'file://')):
- return None
- if os.path.isabs(decoded):
- candidate = Path(decoded)
- else:
- candidate = (svg_dir / decoded).resolve()
- return candidate if candidate.exists() else None
+ return resolve_external_image_reference(svg_dir, href)
def _is_svg_image(img_path: Path, raw_bytes: bytes) -> bool:
@@ -156,6 +149,29 @@ def _load_pil_image(img_path: Path) -> 'PILImage' | None:
return None
+def _prepare_raster_for_geometry(img: 'PILImage') -> 'PILImage':
+ """Apply EXIF orientation and materialize palette/tRNS transparency."""
+ from PIL import ImageOps
+
+ prepared = ImageOps.exif_transpose(img)
+ if prepared.mode == 'P':
+ prepared = prepared.convert('RGBA' if _has_alpha(prepared) else 'RGB')
+ elif (
+ 'transparency' in getattr(prepared, 'info', {})
+ and prepared.mode not in {'RGBA', 'LA'}
+ ):
+ prepared = prepared.convert('RGBA')
+ return prepared
+
+
+def _has_exif_geometry_transform(img: 'PILImage') -> bool:
+ """Return whether EXIF requires a physical mirror or rotation."""
+ try:
+ return int(img.getexif().get(274, 1)) in range(2, 9)
+ except (AttributeError, TypeError, ValueError):
+ return False
+
+
def _normalize_for_save(img: 'PILImage', mime_type: str) -> 'PILImage':
"""Coerce a PIL image into a mode that the target format can save.
@@ -166,15 +182,17 @@ def _normalize_for_save(img: 'PILImage', mime_type: str) -> 'PILImage':
if img.mode in ('RGBA', 'LA'):
from PIL import Image
background = Image.new('RGB', img.size, (255, 255, 255))
- alpha = img.getchannel('A') if img.mode == 'RGBA' else None
+ alpha = img.getchannel('A')
background.paste(img.convert('RGB'), mask=alpha)
return background
if img.mode != 'RGB':
return img.convert('RGB')
return img
- # PNG / GIF / WEBP — preserve alpha if present
+ # Lossless output — preserve alpha if present.
if img.mode == 'P':
- return img.convert('RGBA' if 'A' in img.getbands() else 'RGB')
+ return img.convert('RGBA' if _has_alpha(img) else 'RGB')
+ if img.mode not in {'1', 'L', 'LA', 'I', 'I;16', 'RGB', 'RGBA'}:
+ return img.convert('RGBA' if _has_alpha(img) else 'RGB')
return img
@@ -182,9 +200,7 @@ def _has_alpha(img: 'PILImage') -> bool:
"""Return whether a PIL image has transparency."""
if img.mode in ('RGBA', 'LA'):
return True
- if img.mode == 'P':
- return 'transparency' in getattr(img, 'info', {})
- return False
+ return 'transparency' in getattr(img, 'info', {})
def _target_size(
@@ -231,9 +247,11 @@ def _encode_pil_to_data_uri(
bytes for that path.
"""
original_mime_type = get_mime_type(src_path.name, fallback_bytes)
- mime_type = original_mime_type
- if compress and mime_type == 'image/png' and not _has_alpha(img):
- mime_type = 'image/jpeg'
+ # Match native export: only original JPEG assets stay lossy. PNG remains
+ # PNG, while BMP/TIFF and other static raster formats become lossless PNG.
+ mime_type = (
+ 'image/jpeg' if original_mime_type == 'image/jpeg' else 'image/png'
+ )
pil_format = _PIL_FORMAT_BY_MIME.get(mime_type, 'PNG')
# Encode current PIL image
@@ -251,17 +269,20 @@ def _encode_pil_to_data_uri(
except (OSError, ValueError):
return None
- # If caller passed the original bytes and they're smaller (because PIL
- # round-tripping an asset that was already well-compressed inflates it),
- # fall back to those.
- chosen = encoded_bytes
- if fallback_bytes and mime_type == original_mime_type and len(fallback_bytes) < len(encoded_bytes):
- chosen = fallback_bytes
-
- chosen = _optimize_image_bytes(
- chosen, mime_type, compress=compress, max_dimension=max_dimension,
+ optimized_bytes = _optimize_image_bytes(
+ encoded_bytes, mime_type, compress=compress, max_dimension=max_dimension,
)
+ # If the original represents the same uncropped pixels and is smaller,
+ # retain it instead of inflating an already efficient PNG/JPEG.
+ chosen = optimized_bytes
+ if (
+ fallback_bytes
+ and mime_type == original_mime_type
+ and len(fallback_bytes) < len(optimized_bytes)
+ ):
+ chosen = fallback_bytes
+
b64 = base64.b64encode(chosen).decode('ascii')
return f'data:{mime_type};base64,{b64}', len(chosen)
@@ -352,6 +373,8 @@ def _process_one_image(
print(f' [OK] {img_path.name} (animated, embedded as-is)')
return True, None
+ geometry_normalized = _has_exif_geometry_transform(img)
+ img = _prepare_raster_for_geometry(img)
box_x = _parse_float(image.get('x'))
box_y = _parse_float(image.get('y'))
box_w = _parse_float(image.get('width'))
@@ -367,7 +390,7 @@ def _process_one_image(
# ------------------------------------------------------------------
final_img: 'PILImage' = img
new_x, new_y, new_w, new_h = box_x, box_y, box_w, box_h
- transformed = False # True iff bitmap content changed (crop happened)
+ transformed = geometry_normalized
target_box_w, target_box_h = box_w, box_h
if not par_attr:
@@ -383,9 +406,10 @@ def _process_one_image(
pass
elif mode == 'slice':
x_anchor, y_anchor = get_crop_anchor(align)
- cropped = crop_image_to_size(img, int(box_w), int(box_h),
- x_anchor, y_anchor)
- final_img = cropped
+ cropped_img = crop_image_to_size(
+ img, int(box_w), int(box_h), x_anchor, y_anchor
+ )
+ final_img = cropped_img
transformed = True
else: # meet (or any other mode → treat as meet)
new_w_calc, new_h_calc, off_x, off_y = calculate_fitted_dimensions(
diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.py
index 4519078a..784d3b61 100644
--- a/skills/ppt-master/scripts/svg_quality_checker.py
+++ b/skills/ppt-master/scripts/svg_quality_checker.py
@@ -20,6 +20,7 @@ import hashlib
from pathlib import Path
from typing import List, Dict, Tuple
from collections import Counter, defaultdict
+from urllib.parse import unquote, urlsplit
from xml.etree import ElementTree as ET
from console_encoding import configure_utf8_stdio
@@ -1154,7 +1155,11 @@ class SVGQualityChecker:
self._undeclared_size_occurrences: Counter[str] = Counter()
self._undeclared_size_counts_ready = False
self._lock_seen = False # True once we locate at least one spec_lock.md
- self._source_manifest_cache: Dict[Path, Dict] = {}
+ self._source_manifest_cache: Dict[
+ Path,
+ Tuple[Dict, str | None],
+ ] = {}
+ self._source_manifest_errors_reported: set[Path] = set()
# Template-mode aggregation (populated by check_directory when
# template_mode=True). Each entry is (severity, kind, message) where
# severity is 'error' or 'warning'. Printed in print_summary.
@@ -1379,7 +1384,11 @@ class SVGQualityChecker:
# 10. Check web-sourced image attribution. Templates don't carry
# image_sources.json; skip in template mode.
if not self.template_mode:
- self._check_sourced_image_attribution(content, svg_path, result)
+ self._check_sourced_image_attribution(
+ root,
+ svg_path,
+ result,
+ )
# Determine pass/fail
result['passed'] = len(result['errors']) == 0
@@ -3019,20 +3028,17 @@ class SVGQualityChecker:
)
@staticmethod
- def _transformed_rect_bounds(
+ def _accumulated_transform_matrix(
element: ET.Element,
- bounds: Tuple[float, float, float, float],
parent_by_id: Dict[int, ET.Element],
- ) -> Tuple[float, float, float, float] | None:
- """Transform one local rectangle into root SVG coordinates."""
+ ):
+ """Return the element-to-root transform matrix when available."""
if any(helper is None for helper in (
_IDENTITY_MATRIX,
_matrix_multiply,
_parse_transform_matrix,
- _transform_point,
)):
return None
- x, y, width, height = bounds
chain: List[ET.Element] = []
current: ET.Element | None = element
while current is not None:
@@ -3047,6 +3053,25 @@ class SVGQualityChecker:
matrix,
_parse_transform_matrix(raw_transform),
)
+ except (TypeError, ValueError):
+ return None
+ return matrix
+
+ @classmethod
+ def _transformed_rect_bounds(
+ cls,
+ element: ET.Element,
+ bounds: Tuple[float, float, float, float],
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[float, float, float, float] | None:
+ """Transform one local rectangle into root SVG coordinates."""
+ if _transform_point is None:
+ return None
+ matrix = cls._accumulated_transform_matrix(element, parent_by_id)
+ if matrix is None:
+ return None
+ x, y, width, height = bounds
+ try:
corners = [
_transform_point(matrix, corner_x, corner_y)
for corner_x, corner_y in (
@@ -3062,6 +3087,38 @@ class SVGQualityChecker:
ys = [point[1] for point in corners]
return min(xs), min(ys), max(xs), max(ys)
+ @classmethod
+ def _transformed_rect_edge_lengths(
+ cls,
+ element: ET.Element,
+ bounds: Tuple[float, float, float, float],
+ parent_by_id: Dict[int, ET.Element],
+ ) -> Tuple[float, float] | None:
+ """Return frame-axis lengths after accumulated SVG transforms."""
+ if _transform_point is None:
+ return None
+ matrix = cls._accumulated_transform_matrix(element, parent_by_id)
+ if matrix is None:
+ return None
+ x, y, width, height = bounds
+ try:
+ origin = _transform_point(matrix, x, y)
+ width_end = _transform_point(matrix, x + width, y)
+ height_end = _transform_point(matrix, x, y + height)
+ except (TypeError, ValueError):
+ return None
+ rendered_w = math.hypot(
+ width_end[0] - origin[0],
+ width_end[1] - origin[1],
+ )
+ rendered_h = math.hypot(
+ height_end[0] - origin[0],
+ height_end[1] - origin[1],
+ )
+ if rendered_w <= 0 or rendered_h <= 0:
+ return None
+ return rendered_w, rendered_h
+
@staticmethod
def _resolved_root_module_bounds(
group: ET.Element,
@@ -3598,9 +3655,8 @@ class SVGQualityChecker:
return None
def _check_image_references(self, root: ET.Element, svg_path: Path, result: Dict):
- """Check image file existence and resolution vs display size."""
+ """Check image file existence and effective rendered resolution."""
svg_dir = svg_path.parent
- checked = set()
parent_by_id = {
id(child): parent
for parent in root.iter()
@@ -3622,9 +3678,6 @@ class SVGQualityChecker:
"export will still validate them."
)
return
- if href in checked:
- continue
- checked.add(href)
img_path = _resolve_external_image_reference(svg_dir, href)
if img_path is None:
@@ -3650,32 +3703,100 @@ class SVGQualityChecker:
continue
try:
- display_w = float(display_w_str)
- display_h = float(display_h_str)
+ display_x = float(display_owner.get('x') or '0')
+ display_y = float(display_owner.get('y') or '0')
+ local_display_w = float(display_w_str)
+ local_display_h = float(display_h_str)
except (ValueError, TypeError):
continue
+ if local_display_w <= 0 or local_display_h <= 0:
+ continue
+ display_w = local_display_w
+ display_h = local_display_h
+ transformed_size = self._transformed_rect_edge_lengths(
+ display_owner,
+ (display_x, display_y, local_display_w, local_display_h),
+ parent_by_id,
+ )
+ if transformed_size is not None:
+ display_w, display_h = transformed_size
+ axis_scale_x = display_w / local_display_w
+ axis_scale_y = display_h / local_display_h
try:
- from PIL import Image as PILImage
+ from PIL import Image as PILImage, ImageOps
with PILImage.open(img_path) as img:
- actual_w, actual_h = img.size
+ actual_w, actual_h = ImageOps.exif_transpose(img).size
source_bytes = img_path.stat().st_size
- if actual_w < display_w or actual_h < display_h:
+ visible_w = float(actual_w)
+ visible_h = float(actual_h)
+ fit_owner = image
+ if display_owner is not image:
+ fit_owner = display_owner
+ viewbox = (display_owner.get('viewBox') or '').split()
+ if len(viewbox) == 4:
+ try:
+ viewbox_w = float(viewbox[2])
+ viewbox_h = float(viewbox[3])
+ except ValueError:
+ pass
+ else:
+ if 0 < viewbox_w <= 1 and 0 < viewbox_h <= 1:
+ visible_w *= viewbox_w
+ visible_h *= viewbox_h
+
+ raw_aspect = fit_owner.get('preserveAspectRatio')
+ try:
+ align, mode = (
+ _parse_project_image_aspect_ratio(raw_aspect)
+ if _parse_project_image_aspect_ratio is not None
+ else ('xMidYMid', 'meet')
+ )
+ except ValueError:
+ continue
+
+ local_scale_x = local_display_w / visible_w
+ local_scale_y = local_display_h / visible_h
+ if align == 'none':
+ render_scale = max(
+ local_scale_x * axis_scale_x,
+ local_scale_y * axis_scale_y,
+ )
+ fit_label = 'none'
+ elif mode == 'slice':
+ render_scale = (
+ max(local_scale_x, local_scale_y)
+ * max(axis_scale_x, axis_scale_y)
+ )
+ fit_label = 'slice'
+ else:
+ render_scale = (
+ min(local_scale_x, local_scale_y)
+ * max(axis_scale_x, axis_scale_y)
+ )
+ fit_label = 'meet'
+
+ if render_scale > 1.0:
result['warnings'].append(
- f"Image {href} is {actual_w}x{actual_h} but displayed at "
- f"{int(display_w)}x{int(display_h)} — may appear blurry")
+ f"Image {href} is {actual_w}x{actual_h} and renders at "
+ f"{render_scale:.2f}x scale in a "
+ f"{int(display_w)}x{int(display_h)} {fit_label} frame "
+ "— may appear blurry"
+ )
elif (
- actual_w > display_w * IMAGE_DOWNSIZE_WARN_RATIO
- and actual_h > display_h * IMAGE_DOWNSIZE_WARN_RATIO
+ render_scale < 1.0 / IMAGE_DOWNSIZE_WARN_RATIO
and source_bytes >= IMAGE_DOWNSIZE_WARN_MIN_BYTES
):
source_mib = source_bytes / (1024 * 1024)
result['warnings'].append(
- f"Image {href} is {actual_w}x{actual_h} but displayed at "
- f"{int(display_w)}x{int(display_h)} and the source is "
- f"{source_mib:.1f} MiB — file-size advisory only, not an "
- f"aspect-ratio warning; consider a smaller source asset")
+ f"Image {href} is {actual_w}x{actual_h} and renders at "
+ f"{render_scale:.2f}x scale in a "
+ f"{int(display_w)}x{int(display_h)} {fit_label} frame; "
+ f"the source is {source_mib:.1f} MiB — file-size "
+ "advisory only, not an aspect-ratio warning; consider "
+ "a smaller source asset"
+ )
except ImportError:
pass # PIL not available, skip resolution check
except Exception:
@@ -5211,6 +5332,7 @@ class SVGQualityChecker:
f"{', '.join(inherited_parts)} come unchanged from mirror "
"prototype and are accepted without expanding spec_lock.md",
)
+
def _find_image_sources_manifest(self, svg_path: Path) -> Path | None:
"""Locate image_sources.json for a project SVG.
@@ -5224,57 +5346,203 @@ class SVGQualityChecker:
return candidate
return None
- def _load_image_sources_manifest(self, svg_path: Path) -> Dict:
+ def _load_image_sources_manifest(
+ self,
+ svg_path: Path,
+ ) -> Tuple[Dict, str | None, Path | None]:
manifest_path = self._find_image_sources_manifest(svg_path)
if manifest_path is None:
- return {}
+ return {}, None, None
+ payload, error = self._read_image_sources_manifest(manifest_path)
+ return payload, error, manifest_path
+
+ def _read_image_sources_manifest(
+ self,
+ manifest_path: Path,
+ ) -> Tuple[Dict, str | None]:
+ """Read one provenance manifest without accepting damaged state."""
if manifest_path in self._source_manifest_cache:
return self._source_manifest_cache[manifest_path]
try:
payload = json.loads(manifest_path.read_text(encoding='utf-8'))
- except (OSError, json.JSONDecodeError):
+ except (OSError, json.JSONDecodeError) as exc:
payload = {}
- self._source_manifest_cache[manifest_path] = payload
- return payload
+ error = f"cannot read {manifest_path}: {exc}"
+ else:
+ if not isinstance(payload, dict):
+ error = f"{manifest_path} must contain a JSON object"
+ payload = {}
+ elif not isinstance(payload.get('items'), list):
+ error = f"{manifest_path} must contain an items array"
+ payload = {}
+ elif any(not isinstance(item, dict) for item in payload['items']):
+ error = f"{manifest_path} items must contain JSON objects"
+ payload = {}
+ else:
+ seen_filenames: set[str] = set()
+ error = None
+ for index, item in enumerate(payload['items']):
+ filename = item.get('filename')
+ if (
+ not isinstance(filename, str)
+ or not filename.strip()
+ or filename in {'.', '..'}
+ or '/' in filename
+ or '\\' in filename
+ or ':' in filename
+ or Path(filename).is_absolute()
+ ):
+ error = (
+ f"{manifest_path} items[{index}].filename must be "
+ "a non-empty bare filename"
+ )
+ break
+ if filename in seen_filenames:
+ error = (
+ f"{manifest_path} contains duplicate filename "
+ f"{filename!r}"
+ )
+ break
+ seen_filenames.add(filename)
+ if error:
+ payload = {}
+ self._source_manifest_cache[manifest_path] = (payload, error)
+ return payload, error
+
+ @staticmethod
+ def _external_image_reference_basename(href: str) -> str | None:
+ """Return a decoded basename for one local external image href."""
+ if not href or href.startswith('data:'):
+ return None
+ decoded_href = html.unescape(href)
+ parsed = urlsplit(decoded_href)
+ if parsed.scheme and parsed.scheme != 'file':
+ return None
+ path_part = (
+ parsed.path
+ if parsed.scheme
+ else decoded_href.split('?', 1)[0].split('#', 1)[0]
+ )
+ return Path(unquote(path_part)).name or None
- def _check_sourced_image_attribution(self, content: str, svg_path: Path, result: Dict):
+ @classmethod
+ def _referenced_image_basenames(cls, root: ET.Element) -> set[str]:
+ """Return external image basenames referenced by one parsed SVG."""
+ filenames = set()
+ for elem in root.iter():
+ if elem.tag != f'{{{SVG_NS}}}image':
+ continue
+ href = elem.get('href') or elem.get(f'{{{XLINK_NS}}}href')
+ filename = cls._external_image_reference_basename(href or '')
+ if filename:
+ filenames.add(filename)
+ return filenames
+
+ def _check_sourced_image_attribution(
+ self,
+ root: ET.Element,
+ svg_path: Path,
+ result: Dict,
+ ):
"""Require visible credit text for attribution-required web images.
image_search.py records the legal tier in images/image_sources.json;
Executor must render compact credit text into the SVG. This check
- prevents a quality-first CC BY / CC BY-SA image from silently reaching
- export without attribution.
+ binds each credit to the referenced image's author and license instead
+ of accepting one generic deck-level CC token.
"""
- manifest = self._load_image_sources_manifest(svg_path)
+ manifest, error, manifest_path = self._load_image_sources_manifest(svg_path)
+ if error:
+ if (
+ manifest_path is not None
+ and manifest_path not in self._source_manifest_errors_reported
+ ):
+ result['errors'].append(
+ f"Invalid image source manifest: {error}"
+ )
+ self._source_manifest_errors_reported.add(manifest_path)
+ return
+
items = manifest.get('items') or []
if not items:
return
- text_content = html.unescape(re.sub(r'<[^>]+>', ' ', content))
- text_content = re.sub(r'\s+', ' ', text_content)
- svg_stem = svg_path.stem
+ credit_blocks = self._visible_svg_text_blocks(root)
+ referenced_filenames = self._referenced_image_basenames(root)
for item in items:
if not item.get('attribution_required') and item.get('license_tier') != 'attribution-required':
continue
- filename = Path(str(item.get('filename') or '')).name
- slide = str(item.get('slide') or '').strip()
- referenced = bool(filename and filename in content)
- same_slide = bool(slide and slide == svg_stem)
- if not referenced and not same_slide:
+ filename = str(item.get('filename') or '')
+ if not filename or filename not in referenced_filenames:
continue
license_name = str(item.get('license_name') or '').upper()
license_token = 'CC BY-SA' if 'BY-SA' in license_name else 'CC BY'
- has_credit = license_token in text_content.upper()
+ author = str(item.get('author') or '').strip()
+ has_credit = bool(author) and any(
+ author.casefold() in block.casefold()
+ and license_token in block.upper()
+ for block in credit_blocks
+ )
if not has_credit:
result['errors'].append(
- f"Missing inline attribution for sourced image {filename or '(unknown)'} "
- f"({license_token}). Add compact credit text per "
+ f"Missing image-specific inline attribution for sourced "
+ f"image {filename} ({author or 'unknown author'}; "
+ f"{license_token}). Add compact author + license credit per "
f"references/image-searcher.md §7."
)
+ @classmethod
+ def _visible_svg_text_blocks(cls, root: ET.Element) -> List[str]:
+ """Return rendered text blocks, excluding hidden/non-visual content."""
+ parent_by_id = {
+ id(child): parent
+ for parent in root.iter()
+ for child in list(parent)
+ }
+
+ def has_zero_opacity(element: ET.Element) -> bool:
+ current: ET.Element | None = element
+ while current is not None:
+ style_values = (
+ _parse_inline_style(current.get('style'))
+ if _parse_inline_style is not None
+ else {}
+ )
+ raw = style_values.get('opacity')
+ if raw is None:
+ raw = current.get('opacity')
+ if raw is not None:
+ value = raw.strip()
+ try:
+ opacity = (
+ float(value[:-1]) / 100
+ if value.endswith('%')
+ else float(value)
+ )
+ except ValueError:
+ pass
+ else:
+ if opacity <= 0:
+ return True
+ current = parent_by_id.get(id(current))
+ return False
+
+ blocks: List[str] = []
+ for element in root.iter(f'{{{SVG_NS}}}text'):
+ if (
+ cls._is_hidden_element(element, parent_by_id)
+ or cls._has_non_visual_ancestor(element, root, parent_by_id)
+ or has_zero_opacity(element)
+ ):
+ continue
+ text = re.sub(r'\s+', ' ', ' '.join(element.itertext())).strip()
+ if text:
+ blocks.append(text)
+ return blocks
+
@staticmethod
def _normalize_size(value: str) -> str:
"""Normalize a font-size value for drift comparison.
@@ -5952,7 +6220,7 @@ class SVGQualityChecker:
)
def _check_illustration_resource_contract(self, dir_path: Path) -> None:
- """Project-level illustration resource checks."""
+ """Project-level planned-image and illustration resource checks."""
project_path = self._resolve_project_path(dir_path)
spec_path = project_path / 'design_spec.md'
if not spec_path.exists():
@@ -5968,15 +6236,35 @@ class SVGQualityChecker:
))
return
+ current_contract = (
+ '<!-- ppt-master-schema: design-spec/v1 -->' in spec_text
+ )
rows = self._extract_image_resource_rows(spec_text)
- if not rows:
+ if not rows and not current_contract:
return
- lock_images = self._load_project_lock_images(project_path)
+ lock_entries, lock_error = self._load_project_lock_image_entries(
+ project_path
+ )
+ lock_images = set(lock_entries)
svg_texts = self._load_project_svg_texts(project_path)
- all_svg_text = "\n".join(svg_texts.values())
+ svg_references, inline_image_counts = (
+ self._load_project_svg_image_references(project_path)
+ )
+ all_svg_references = (
+ set().union(*(
+ set(references)
+ for references in svg_references.values()
+ ))
+ if svg_references
+ else set()
+ )
- sheet_rows = [row for row in rows if self._row_type(row).lower() == 'illustration sheet']
+ sheet_rows = [
+ row
+ for row in rows
+ if self._row_type(row).lower() == 'illustration sheet'
+ ]
slice_rows = [row for row in rows if self._row_acquire(row) == 'slice']
image_rows = [
row for row in rows
@@ -5995,34 +6283,55 @@ class SVGQualityChecker:
f"{filename} is an Illustration Sheet but is listed in spec_lock.md images; "
"only sliced element rows may be listed.",
))
- if filename in all_svg_text:
+ if filename in all_svg_references:
self._illustration_issues.append((
'error',
'sheet_referenced',
f"{filename} is an Illustration Sheet but is referenced by an SVG; "
"generate it only as a slice source, never place it.",
))
-
- for row in slice_rows:
- filename = self._row_filename(row)
- if not filename:
- continue
- if filename not in lock_images:
- self._illustration_issues.append((
- 'error',
- 'slice_missing_lock',
- f"{filename} is a slice row but is absent from spec_lock.md images.",
- ))
if (
self._row_status(row) == 'generated'
- and not (project_path / 'images' / filename).exists()
+ and not (project_path / 'images' / filename).is_file()
):
self._illustration_issues.append((
'error',
- 'slice_file_missing',
- f"{filename} is a Generated slice row but images/{filename} does not exist.",
+ 'sheet_file_missing',
+ f"{filename} is a Generated Illustration Sheet but "
+ f"images/{filename} does not exist.",
))
+ if current_contract:
+ self._check_planned_image_closure(
+ rows,
+ project_path,
+ lock_entries,
+ lock_error,
+ svg_references,
+ inline_image_counts,
+ )
+ else:
+ for row in slice_rows:
+ filename = self._row_filename(row)
+ if not filename:
+ continue
+ if filename not in lock_images:
+ self._illustration_issues.append((
+ 'error',
+ 'slice_missing_lock',
+ f"{filename} is a slice row but is absent from spec_lock.md images.",
+ ))
+ if (
+ self._row_status(row) == 'generated'
+ and not (project_path / 'images' / filename).exists()
+ ):
+ self._illustration_issues.append((
+ 'error',
+ 'slice_file_missing',
+ f"{filename} is a Generated slice row but "
+ f"images/{filename} does not exist.",
+ ))
+
for row in image_rows:
self._check_decorative_image_row(row, project_path, svg_texts)
@@ -6082,7 +6391,10 @@ class SVGQualityChecker:
continue
row = {header[i]: cells[i] if i < len(cells) else '' for i in range(len(header))}
filename = row.get('Filename', '').strip()
- if filename and filename.lower() != 'filename':
+ if (
+ filename.lower() != 'filename'
+ and any(value.strip() for value in row.values())
+ ):
rows.append(row)
return rows
@@ -6091,6 +6403,10 @@ class SVGQualityChecker:
def _row_filename(row: Dict[str, str]) -> str:
return Path(row.get('Filename', '').strip()).name
+ @staticmethod
+ def _row_raw_filename(row: Dict[str, str]) -> str:
+ return row.get('Filename', '').strip()
+
@staticmethod
def _row_type(row: Dict[str, str]) -> str:
return row.get('Type', '').strip()
@@ -6107,20 +6423,68 @@ class SVGQualityChecker:
def _row_layout(row: Dict[str, str]) -> str:
return row.get('Layout pattern', '').strip()
- def _load_project_lock_images(self, project_path: Path) -> set[str]:
- """Return filenames listed under spec_lock.md images."""
+ def _load_project_lock_image_entries(
+ self,
+ project_path: Path,
+ ) -> Tuple[Dict[str, List[Dict[str, str]]], str | None]:
+ """Return parsed image-lock rows keyed by basename."""
lock_path = project_path / 'spec_lock.md'
- if _parse_spec_lock is None or not lock_path.exists():
- return set()
+ if not lock_path.exists():
+ return {}, f"{lock_path} does not exist"
+ if _parse_spec_lock is None:
+ return {}, "spec_lock parser is unavailable"
try:
lock = _parse_spec_lock(lock_path)
- except Exception:
- return set()
- images = set()
- for value in lock.get('images', {}).values():
- path_part = value.split('|', 1)[0].strip()
- images.add(Path(path_part).name)
- return images
+ except Exception as exc:
+ return {}, f"cannot parse {lock_path}: {exc}"
+
+ entries: Dict[str, List[Dict[str, str]]] = defaultdict(list)
+ legacy_metadata_keys = {
+ 'image_rendering',
+ 'image_rendering_references',
+ 'image_rendering_behavior',
+ }
+ acquisition_sources = {
+ 'ai',
+ 'web',
+ 'user',
+ 'formula',
+ 'placeholder',
+ 'slice',
+ }
+ for key, value in lock.get('images', {}).items():
+ if str(key).strip().lower() in legacy_metadata_keys:
+ continue
+ parts = [part.strip() for part in value.split('|')]
+ path_part = parts[0] if parts else ''
+ if (
+ len(parts) >= 2
+ and parts[0].lower() in acquisition_sources
+ and parts[1]
+ and not urlsplit(parts[1]).scheme
+ ):
+ # Legacy key-first rows spell `<source> | <path> | ...`.
+ path_part = parts[1]
+ filename = Path(path_part).name
+ if not filename:
+ continue
+ metadata = {
+ field: raw
+ for part in parts[1:]
+ if '=' in part
+ for field, raw in [part.split('=', 1)]
+ }
+ entries[filename].append({
+ 'key': str(key),
+ 'path': path_part,
+ **metadata,
+ })
+ return dict(entries), None
+
+ def _load_project_lock_images(self, project_path: Path) -> set[str]:
+ """Return filenames listed under spec_lock.md images."""
+ entries, _error = self._load_project_lock_image_entries(project_path)
+ return set(entries)
@staticmethod
def _load_project_svg_texts(project_path: Path) -> Dict[Path, str]:
@@ -6136,6 +6500,420 @@ class SVGQualityChecker:
continue
return out
+ @classmethod
+ def _load_project_svg_image_references(
+ cls,
+ project_path: Path,
+ ) -> Tuple[Dict[Path, Dict[str, set[Path]]], Dict[Path, int]]:
+ """Parse external image paths and count inline images in generated SVGs."""
+ svg_dir = project_path / 'svg_output'
+ if not svg_dir.exists():
+ return {}, {}
+ out: Dict[Path, Dict[str, set[Path]]] = {}
+ inline_counts: Dict[Path, int] = {}
+ for svg_path in sorted(svg_dir.glob('*.svg')):
+ try:
+ root = ET.parse(svg_path).getroot()
+ except (OSError, ET.ParseError):
+ continue
+ references: Dict[str, set[Path]] = defaultdict(set)
+ inline_count = 0
+ for element in root.iter(f'{{{SVG_NS}}}image'):
+ href = (
+ element.get('href')
+ or element.get(f'{{{XLINK_NS}}}href')
+ or ''
+ )
+ if href.lstrip().lower().startswith('data:'):
+ inline_count += 1
+ continue
+ filename = cls._external_image_reference_basename(href)
+ if not filename:
+ continue
+ references.setdefault(filename, set())
+ if _resolve_external_image_reference is not None:
+ resolved = _resolve_external_image_reference(
+ svg_path.parent,
+ href,
+ )
+ if resolved is not None:
+ references[filename].add(resolved.resolve())
+ out[svg_path] = dict(references)
+ if inline_count:
+ inline_counts[svg_path] = inline_count
+ return out, inline_counts
+
+ def _check_planned_image_closure(
+ self,
+ rows: List[Dict[str, str]],
+ project_path: Path,
+ lock_entries: Dict[str, List[Dict[str, str]]],
+ lock_error: str | None,
+ svg_references: Dict[Path, Dict[str, set[Path]]],
+ inline_image_counts: Dict[Path, int],
+ ) -> None:
+ """Close Design Spec, execution lock, files, SVGs, and provenance."""
+ project_root = project_path.resolve()
+ if inline_image_counts:
+ total = sum(inline_image_counts.values())
+ shown = ', '.join(
+ f"{path.name} ({count})"
+ for path, count in sorted(inline_image_counts.items())
+ )
+ self._illustration_issues.append((
+ 'error',
+ 'svg_inline_image_untracked',
+ f"svg_output contains {total} inline data-URI image(s): "
+ f"{shown}. Current projects must keep external project-local "
+ "image hrefs so every placement closes through Design Spec "
+ "§VIII and spec_lock.md.",
+ ))
+ valid_acquisitions = {
+ 'ai',
+ 'web',
+ 'user',
+ 'formula',
+ 'placeholder',
+ 'slice',
+ }
+ valid_statuses = {
+ 'pending',
+ 'failed',
+ 'generated',
+ 'sourced',
+ 'rendered',
+ 'needs-manual',
+ 'existing',
+ 'placeholder',
+ }
+ terminal_by_acquisition = {
+ 'ai': {'generated', 'needs-manual'},
+ 'web': {'sourced', 'needs-manual'},
+ 'user': {'existing', 'needs-manual'},
+ 'formula': {'rendered', 'needs-manual'},
+ 'placeholder': {'placeholder'},
+ 'slice': {'generated', 'needs-manual'},
+ }
+ seen_filenames: set[str] = set()
+ for row in rows:
+ raw_filename = self._row_raw_filename(row)
+ filename = self._row_filename(row)
+ acquire = self._row_acquire(row)
+ status = self._row_status(row)
+ filename_is_bare = bool(filename) and (
+ filename not in {'.', '..'}
+ and '/' not in filename
+ and '\\' not in filename
+ and ':' not in filename
+ )
+ filename_is_canonical = raw_filename in {
+ filename,
+ f"images/{filename}",
+ }
+ if not filename_is_bare or not filename_is_canonical:
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_invalid_filename',
+ f"Design Spec §VIII Filename {raw_filename!r} must be "
+ "a non-empty bare filename or canonical "
+ "images/<filename> path.",
+ ))
+ elif filename in seen_filenames:
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_duplicate_filename',
+ f"Design Spec §VIII repeats Filename {filename!r}; "
+ "one resource must have one authoritative row.",
+ ))
+ else:
+ seen_filenames.add(filename)
+
+ if acquire not in valid_acquisitions:
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_invalid_acquisition',
+ f"{filename or '(missing filename)'} has invalid "
+ f"Acquire Via {row.get('Acquire Via', '').strip()!r}.",
+ ))
+ continue
+ if status not in valid_statuses:
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_invalid_status',
+ f"{filename or '(missing filename)'} has invalid "
+ f"Status {row.get('Status', '').strip()!r}.",
+ ))
+ continue
+ if status in {'pending', 'failed'}:
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_not_terminal',
+ f"{filename or '(missing filename)'} has non-terminal "
+ f"Status {row.get('Status', '').strip()!r}; finish the "
+ "owning acquisition or mark it Needs-Manual before export.",
+ ))
+ elif status not in terminal_by_acquisition[acquire]:
+ expected = ', '.join(sorted(terminal_by_acquisition[acquire]))
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_status_mismatch',
+ f"{filename or '(missing filename)'} uses Acquire Via "
+ f"{acquire!r} but Status {status!r}; terminal status must "
+ f"be one of: {expected}.",
+ ))
+
+ if lock_error:
+ self._illustration_issues.append((
+ 'error',
+ 'image_lock_unreadable',
+ lock_error,
+ ))
+ return
+
+ placed_rows = [
+ row for row in rows
+ if self._row_type(row).lower() != 'illustration sheet'
+ and self._row_acquire(row)
+ in {'ai', 'web', 'user', 'formula', 'placeholder', 'slice'}
+ ]
+ rows_by_filename = {
+ self._row_filename(row): row
+ for row in placed_rows
+ if self._row_filename(row)
+ }
+ referenced_paths: Dict[str, set[Path]] = defaultdict(set)
+ for references in svg_references.values():
+ for filename, paths in references.items():
+ referenced_paths[filename].update(paths)
+ referenced = set(referenced_paths)
+
+ for filename, row in rows_by_filename.items():
+ if filename not in lock_entries:
+ self._illustration_issues.append((
+ 'error',
+ 'planned_image_missing_lock',
+ f"{filename} is a placed Design Spec image row but is "
+ "absent from spec_lock.md images.",
+ ))
+
+ for filename in sorted(referenced - set(rows_by_filename)):
+ lock_note = (
+ ""
+ if filename in lock_entries
+ else " and is absent from spec_lock.md images"
+ )
+ self._illustration_issues.append((
+ 'error',
+ 'svg_image_missing_spec',
+ f"svg_output references {filename}, but it has no placed "
+ f"Design Spec §VIII row{lock_note}.",
+ ))
+
+ for filename, entries in lock_entries.items():
+ row = rows_by_filename.get(filename)
+ if row is None:
+ self._illustration_issues.append((
+ 'error',
+ 'locked_image_missing_spec',
+ f"{filename} is listed in spec_lock.md images but has no "
+ "placed row in Design Spec §VIII.",
+ ))
+ continue
+
+ acquire = self._row_acquire(row)
+ status = self._row_status(row)
+ candidate_paths: List[Path] = []
+ for entry in entries:
+ raw_path = entry.get('path', '')
+ if not raw_path:
+ continue
+ lock_path = Path(raw_path)
+ legacy_bare_filename = (
+ not lock_path.is_absolute()
+ and raw_path not in {'.', '..'}
+ and '/' not in raw_path
+ and '\\' not in raw_path
+ and ':' not in raw_path
+ )
+ if lock_path.is_absolute():
+ path = lock_path
+ elif legacy_bare_filename:
+ path = project_path / 'images' / raw_path
+ else:
+ path = project_path / raw_path
+ resolved_path = path.resolve()
+ try:
+ resolved_path.relative_to(project_root)
+ except ValueError:
+ self._illustration_issues.append((
+ 'error',
+ 'locked_image_path_outside_project',
+ f"{filename} lock path {entry['path']!r} resolves "
+ "outside the project workspace.",
+ ))
+ continue
+ candidate_paths.append(resolved_path)
+
+ distinct_candidate_paths = set(candidate_paths)
+ if len(distinct_candidate_paths) > 1:
+ shown = ', '.join(
+ str(path.relative_to(project_root))
+ for path in sorted(distinct_candidate_paths)
+ )
+ self._illustration_issues.append((
+ 'error',
+ 'locked_image_ambiguous_paths',
+ f"{filename} resolves to multiple locked project paths: "
+ f"{shown}. One resource must have one authoritative asset.",
+ ))
+
+ expected_paths = {
+ path
+ for path in distinct_candidate_paths
+ if path.is_file()
+ }
+ asset_exists = bool(expected_paths)
+ file_required = status in {
+ 'existing',
+ 'generated',
+ 'sourced',
+ 'rendered',
+ }
+ if not asset_exists and file_required:
+ expected = entries[0].get('path') or f"images/{filename}"
+ self._illustration_issues.append((
+ 'error',
+ 'locked_image_file_missing',
+ f"{filename} is locked and has terminal Status "
+ f"{row.get('Status', '').strip()!r}, but {expected} "
+ "does not exist.",
+ ))
+
+ actual_paths = referenced_paths.get(filename, set())
+ unexpected_paths = actual_paths - expected_paths
+ if unexpected_paths:
+ shown = ', '.join(
+ str(path.relative_to(project_root))
+ if path.is_relative_to(project_root)
+ else str(path)
+ for path in sorted(unexpected_paths)
+ )
+ self._illustration_issues.append((
+ 'error',
+ 'locked_image_reference_mismatch',
+ f"{filename} is referenced from {shown}, not exclusively "
+ "from its locked project path.",
+ ))
+
+ should_be_referenced = (
+ acquire != 'placeholder'
+ and asset_exists
+ and status
+ in {
+ 'existing',
+ 'generated',
+ 'sourced',
+ 'rendered',
+ 'needs-manual',
+ }
+ )
+ if should_be_referenced and not (actual_paths & expected_paths):
+ self._illustration_issues.append((
+ 'error',
+ 'locked_image_unreferenced',
+ f"{filename} has usable terminal content but its locked "
+ "file is not referenced by any svg_output <image> element.",
+ ))
+
+ self._check_sourced_image_provenance(
+ rows_by_filename,
+ project_path,
+ )
+
+ def _check_sourced_image_provenance(
+ self,
+ rows_by_filename: Dict[str, Dict[str, str]],
+ project_path: Path,
+ ) -> None:
+ """Require one valid provenance item for every Sourced web row."""
+ sourced = {
+ filename: row
+ for filename, row in rows_by_filename.items()
+ if self._row_acquire(row) == 'web'
+ and self._row_status(row) == 'sourced'
+ }
+ if not sourced:
+ return
+
+ manifest_path = project_path / 'images' / 'image_sources.json'
+ if not manifest_path.exists():
+ self._illustration_issues.append((
+ 'error',
+ 'image_sources_missing',
+ "Sourced web images are used, but "
+ "images/image_sources.json does not exist.",
+ ))
+ return
+
+ payload, error = self._read_image_sources_manifest(manifest_path)
+ if error:
+ if manifest_path not in self._source_manifest_errors_reported:
+ self._illustration_issues.append((
+ 'error',
+ 'image_sources_invalid',
+ error,
+ ))
+ self._source_manifest_errors_reported.add(manifest_path)
+ return
+
+ manifest_items = {
+ str(item.get('filename') or ''): item
+ for item in payload['items']
+ if item.get('filename')
+ }
+ valid_tiers = {
+ 'no-attribution',
+ 'attribution-required',
+ 'manual',
+ }
+ for filename in sourced:
+ item = manifest_items.get(filename)
+ if item is None:
+ self._illustration_issues.append((
+ 'error',
+ 'sourced_image_missing_provenance',
+ f"{filename} is Sourced but has no matching entry in "
+ "images/image_sources.json.",
+ ))
+ continue
+
+ tier = str(item.get('license_tier') or '').strip()
+ if tier not in valid_tiers:
+ self._illustration_issues.append((
+ 'error',
+ 'sourced_image_invalid_license_tier',
+ f"{filename} has invalid license_tier {tier!r} in "
+ "images/image_sources.json.",
+ ))
+ if tier != 'manual' and not str(
+ item.get('attribution_text') or ''
+ ).strip():
+ self._illustration_issues.append((
+ 'error',
+ 'sourced_image_missing_attribution_text',
+ f"{filename} has license_tier {tier!r} but no "
+ "attribution_text in images/image_sources.json.",
+ ))
+ if tier == 'attribution-required' and not str(
+ item.get('author') or ''
+ ).strip():
+ self._illustration_issues.append((
+ 'error',
+ 'sourced_image_missing_author',
+ f"{filename} requires attribution but has no author in "
+ "images/image_sources.json.",
+ ))
+
def _check_decorative_image_row(
self,
row: Dict[str, str],
@@ -6810,7 +7588,7 @@ class SVGQualityChecker:
errors = [item for item in self._illustration_issues if item[0] == 'error']
warnings = [item for item in self._illustration_issues if item[0] == 'warning']
- print("\n[ILLUSTRATION] Illustration strategy checks")
+ print("\n[IMAGES] Image resource checks")
if errors:
print(f" Errors ({len(errors)}):")
for _severity, kind, msg in errors:
diff --git a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
index 5be5109e..23832376 100644
--- a/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
+++ b/skills/ppt-master/scripts/svg_to_pptx/drawingml/elements.py
@@ -3505,12 +3505,17 @@ def _read_image_size(data: bytes) -> tuple[int | None, int | None]:
legacy stretch behaviour.
"""
try:
- from PIL import Image, UnidentifiedImageError # type: ignore
+ from PIL import Image, ImageOps, UnidentifiedImageError # type: ignore
except ImportError:
return (None, None)
try:
with Image.open(io.BytesIO(data)) as img:
- return img.size
+ oriented = ImageOps.exif_transpose(img)
+ try:
+ return oriented.size
+ finally:
+ if oriented is not img:
+ oriented.close()
except (
UnidentifiedImageError,
OSError,
@@ -3525,9 +3530,35 @@ def _image_has_alpha(img: Any) -> bool:
"""Return whether a PIL image carries useful transparency."""
if img.mode in ('RGBA', 'LA'):
return True
- if img.mode == 'P':
- return 'transparency' in getattr(img, 'info', {})
- return False
+ return 'transparency' in getattr(img, 'info', {})
+
+
+def _prepare_raster_for_geometry(img: Any) -> Any:
+ """Apply EXIF orientation and materialize palette/tRNS transparency."""
+ try:
+ from PIL import ImageOps # type: ignore
+ except ImportError:
+ return img
+
+ prepared = ImageOps.exif_transpose(img)
+ if prepared.mode == 'P':
+ prepared = prepared.convert(
+ 'RGBA' if _image_has_alpha(prepared) else 'RGB'
+ )
+ elif (
+ 'transparency' in getattr(prepared, 'info', {})
+ and prepared.mode not in {'RGBA', 'LA'}
+ ):
+ prepared = prepared.convert('RGBA')
+ return prepared
+
+
+def _has_exif_geometry_transform(img: Any) -> bool:
+ """Return whether EXIF requires a physical mirror or rotation."""
+ try:
+ return int(img.getexif().get(274, 1)) in range(2, 9)
+ except (AttributeError, TypeError, ValueError):
+ return False
def _image_target_size(
@@ -3632,6 +3663,8 @@ def _encode_optimized_image(img: Any, *, prefer_jpeg: bool, quality: int) -> tup
return buf.getvalue(), 'jpg'
if img.mode == 'P':
img = img.convert('RGBA' if _image_has_alpha(img) else 'RGB')
+ elif img.mode not in {'1', 'L', 'LA', 'I', 'I;16', 'RGB', 'RGBA'}:
+ img = img.convert('RGBA' if _image_has_alpha(img) else 'RGB')
img.save(buf, format='PNG', optimize=True)
return buf.getvalue(), 'png'
except (OSError, ValueError):
@@ -3671,6 +3704,8 @@ def _optimize_image_for_pptx(
if getattr(img, 'is_animated', False):
return img_data, img_format
+ geometry_normalized = _has_exif_geometry_transform(img)
+ img = _prepare_raster_for_geometry(img)
align, mode = parse_project_image_aspect_ratio(
elem.get('preserveAspectRatio')
)
@@ -3689,13 +3724,19 @@ def _optimize_image_for_pptx(
original_size = img.size
img = _resize_for_target(img, target_w, target_h)
resized = img.size != original_size
- prefer_jpeg = img_format.lower() in {'png', 'jpg', 'jpeg', 'bmp', 'tif', 'tiff'}
+ # Preserve source semantics: only an original JPEG stays lossy. PNG and
+ # other static raster formats use lossless PNG after any resize.
+ prefer_jpeg = img_format.lower() in {'jpg', 'jpeg'}
encoded = _encode_optimized_image(img, prefer_jpeg=prefer_jpeg, quality=ctx.image_quality)
if encoded is None:
return img_data, img_format
optimized_data, optimized_format = encoded
- if not resized and len(optimized_data) >= len(img_data):
+ if (
+ not geometry_normalized
+ and not resized
+ and len(optimized_data) >= len(img_data)
+ ):
return img_data, img_format
return optimized_data, optimized_format