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
feat(image): improve layout calculation, prompt guidance, and pipeline validation
hugohe32bd28d5e3107
diff --git a/skills/ppt-master/references/image-generator.md b/skills/ppt-master/references/image-generator.mdindex a2659158..5285cfec 100644--- a/skills/ppt-master/references/image-generator.md+++ b/skills/ppt-master/references/image-generator.md@@ -83,6 +83,12 @@ Every image must be output in the following format:| General Versatile | Modern illustration, flat design | `modern`, `flat design`, `gradient`, `vibrant colors` || General Consulting | Clean professional, corporate | `professional`, `clean`, `corporate`, `minimalist` || Top Consulting | Premium minimal, abstract geometric | `premium`, `sophisticated`, `geometric`, `abstract`, `elegant` |+| Technology / SaaS | Futuristic, digital | `futuristic`, `digital`, `tech grid`, `circuit pattern`, `neon accents`, `dark background` |+| Education / Training | Friendly, instructional | `friendly`, `instructional`, `whiteboard style`, `pastel colors`, `simple shapes` |+| Marketing / Branding | Bold, energetic | `bold`, `energetic`, `dynamic composition`, `vivid colors`, `action-oriented` |+| Healthcare / Medical | Clean, reassuring | `clean`, `clinical`, `soft blue-green palette`, `organic curves`, `reassuring` |+| Finance / Banking | Conservative, trustworthy | `conservative`, `trustworthy`, `blue-gray palette`, `structured`, `precise` |+| Creative / Design | Artistic, experimental | `artistic`, `experimental`, `asymmetric`, `textured`, `hand-crafted feel` |### 2.4 Color Integration Method@@ -108,6 +114,26 @@ Full directive: "color palette: deep navy blue (#1E3A5F), light gray (#F8F9FA),> Supported aspect ratios: `1:1`, `2:3`, `3:2`, `3:4`, `4:3`, `4:5`, `5:4`, `9:16`, `16:9`, `21:9` (Gemini also supports `1:4`, `1:8`, `4:1`, `8:1`)+### 2.6 Multi-Image Coherence Strategy++When generating multiple images for a single deck, visual coherence is critical. Use a **Deck Style Anchor** — a shared prefix of 15-25 words prepended to every image prompt.++**Construction**: Combine style keywords (Section 2.3) + color directive (Section 2.4) + quality directive into one reusable prefix.++**Example**:+```+Deck Style Anchor:+"modern flat design illustration, color palette: deep navy (#1E3A5F), light gray (#F8F9FA), gold accent (#D4AF37), clean minimalist, high quality, 4K"++Image 1 prompt: [Deck Style Anchor], abstract technology network showing connected nodes...+Image 2 prompt: [Deck Style Anchor], team of professionals collaborating at a desk...+Image 3 prompt: [Deck Style Anchor], growth chart with upward trending line...+```++**Exception**: Background images may replace style keywords with `background`, `backdrop`, `negative space for text overlay` while keeping the same color directive. This ensures color consistency without compromising background functionality.++**Rule**: Define the Deck Style Anchor once in the prompt document header (Section 5), then reference it in every individual prompt.+---## 3. Image Type Classification & Handling@@ -380,7 +406,21 @@ Abstract futuristic background with flowing digital waves...### When Images Are Unsatisfactory-Provide prompt variants for user selection: Variant A (more abstract), Variant B (more concrete), Variant C (different color tone).+Diagnose the problem category and apply a targeted prompt fix:++| Problem | Diagnosis | Prompt Adjustment |+|---------|-----------|-------------------|+| Wrong style | Image looks photorealistic when flat design was intended | Change style directive: replace `photography` with `flat design illustration` |+| Wrong colors | Colors don't match the design spec palette | Strengthen color directive: add explicit HEX codes, repeat color names |+| Wrong composition | Subject is off-center or layout doesn't fit the slide | Adjust composition directive: add `centered composition`, `rule of thirds`, or `wide negative space on left` |+| Wrong subject | Image depicts something different from what was described | Rewrite subject description with more specificity and concrete details |+| Low quality | Image is blurry, has artifacts, or lacks detail | Add `highly detailed, sharp focus, professional quality, 8K resolution` |++**Variant workflow**:+1. Keep the original prompt as "Variant A" in `image_prompts.md`+2. Create modified prompt as "Variant B" with targeted fixes from the table above+3. If needed, create "Variant C" with a different stylistic approach+4. Label all variants clearly so the user can compare results---diff --git a/skills/ppt-master/references/image-layout-spec.md b/skills/ppt-master/references/image-layout-spec.mdindex a61ddf69..4a2658ce 100644--- a/skills/ppt-master/references/image-layout-spec.md+++ b/skills/ppt-master/references/image-layout-spec.md@@ -38,14 +38,18 @@ Layout rules for pages containing images. Both the Strategist planning phase and## Dimension Calculation Formulas-### PPT 16:9 (1280x720) Canvas Parameters+### Canvas Parameters (All Formats)-```-Canvas: 1280 x 720 px-Content area: 1160 x 640 px (left/right margin 60px, top/bottom margin 40px)-Title area height: 60 px-Content start: y = 80 px (title + spacing)-```+| Format | Canvas | Margins (L/R, T/B) | Content Area (W x H) | Title Height | Content Start Y |+|--------|--------|--------------------|-----------------------|-------------|----------------|+| PPT 16:9 | 1280x720 | 60, 60 | 1160 x 600 | 60px | 80px |+| PPT 4:3 | 1024x768 | 50, 50 | 924 x 608 | 60px | 70px |+| Xiaohongshu | 1242x1660 | 60, 80 | 1122 x 1500 | 80px | 100px |+| WeChat Moments | 1080x1080 | 60, 60 | 960 x 960 | 60px | 80px |+| Story | 1080x1920 | 60, 120/180 | 960 x 1620 | 80px | 140px |+| WeChat Article | 900x383 | 40, 40 | 820 x 303 | 40px | 50px |++> In the formulas below, **W** = content area width, **H** = content area height (already excludes title). The PPT 16:9 example uses W=1160, H=600.### Top-Bottom Layout Calculation@@ -104,6 +108,63 @@ Switch to left-right: image 780x446 (left), text area 360x600 (right) → 7:3 le---+## Portrait Canvas Override++The default layout type selection table assumes a **landscape or square canvas**. For portrait canvases (height > width), the rules change because left-right splits make both columns too narrow.++| Canvas Orientation | Image Ratio | Recommended Layout | Reason |+|-------------------|-------------|-------------------|--------|+| Portrait (Xiaohongshu, Story) | > 1.5 (wide) | Top-bottom | Same as landscape canvas |+| Portrait (Xiaohongshu, Story) | 1.2-1.5 (standard) | Top-bottom | Left-right too narrow on tall canvas |+| Portrait (Xiaohongshu, Story) | 0.8-1.2 (square) | Top-bottom | Image fits well in top half |+| Portrait (Xiaohongshu, Story) | 0.5-0.8 (portrait) | Left-right | Portrait image on tall canvas works |+| Portrait (Xiaohongshu, Story) | < 0.5 (extreme portrait) | Left-right | Image takes one side, text the other |++> On square canvases (WeChat Moments 1:1), use the standard landscape canvas rules.++---++## Multi-Image Layout++When a slide contains multiple images, use these formulas to divide the content area evenly.++### Grid Formulas++```+columns = number of columns+rows = number of rows+gap = 20px (PPT formats) or 30px (social formats)++cell_width = (W - (columns - 1) * gap) / columns+cell_height = (H - (rows - 1) * gap) / rows+```++### Common Patterns++| Image Count | Layout | Grid | Description |+|-------------|--------|------|-------------|+| 2 (both landscape) | Side-by-side | 2x1 | Two equal columns |+| 2 (both portrait) | Stacked | 1x2 | Two equal rows |+| 2 (mixed) | 1 large + 1 small | Custom | Landscape top (full-width), portrait right-bottom |+| 3 | 1 large + 2 small | 1+2 | Left large (50% width), right column with 2 stacked |+| 4 | Grid | 2x2 | Equal-sized cells |++### Example: 2x2 Grid on PPT 16:9++```+W=1160, H=600, gap=20+cell_width = (1160 - 20) / 2 = 570+cell_height = (600 - 20) / 2 = 290++Image positions:+ (60, 80) 570x290 (650, 80) 570x290+ (60, 390) 570x290 (650, 390) 570x290+```++> For multi-image slides, use `preserveAspectRatio="xMidYMid meet"` on all images to maintain consistent display within cells.++---+## Prohibited Practices| Prohibited | Correct Approach |@@ -159,10 +220,12 @@ In the Design Specification & Content Outline, the image resource list must incl## Automation Tool```bash-python3 scripts/analyze_images.py <project_path>/images+python3 scripts/analyze_images.py <project_path>/images # Default: PPT 16:9+python3 scripts/analyze_images.py <project_path>/images --canvas ppt43 # PPT 4:3+python3 scripts/analyze_images.py <project_path>/images --canvas xiaohongshu # Xiaohongshu```-Output includes dimensions, ratios, and layout recommendations (Markdown table), which can be directly used to populate the image resource list.+The `--canvas` parameter selects the target canvas format (default `ppt169`). The tool computes layout type (top-bottom / left-right), image display area, and text area dimensions based on the formulas in this spec. Output includes a Markdown table that can be directly pasted into the image resource list.---diff --git a/skills/ppt-master/references/strategist.md b/skills/ppt-master/references/strategist.mdindex c7d3aea7..dd598ddf 100644--- a/skills/ppt-master/references/strategist.md+++ b/skills/ppt-master/references/strategist.md@@ -184,6 +184,17 @@ Selection principle: Font size is based on **content density**, not design style| Status | Pending generation / Existing / Placeholder || Generation description | Fill in detailed description for AI generation |+**Generation description quality guide** — the description is the seed for Image_Generator's prompt, so specificity matters:++| Quality | Example | Why |+|---------|---------|-----|+| Bad | "team photo" | Too vague — style, setting, lighting, composition all unknown |+| Good | "Professional team of 4 diverse people collaborating at a modern office desk, natural lighting, laptop visible" | Specifies subject count, setting, lighting, and props |+| Bad | "tech background" | No color, style, or composition guidance |+| Good | "Abstract flowing digital waves in deep navy (#1E3A5F) to midnight blue gradient, subtle particle effects, clean center area for text overlay" | Specifies subject, colors with HEX, effects, and text area needs |+| Bad | "chart" | Image_Generator cannot know what type of chart or data |+| Good | "Clean flowchart showing 4 sequential steps connected by arrows, flat design, light gray background, blue accent nodes" | Specifies diagram type, count, style, colors |+**Image type descriptions**:| Type | Suitable Scenarios |@@ -206,6 +217,10 @@ Selection principle: Font size is based on **content density**, not design styleCore logic: The layout container's aspect ratio must closely match the image's original ratio. Never force a wide image into a square container or a portrait image into a narrow horizontal strip.+> **Portrait canvases** (Xiaohongshu, Story): Layout rules differ — top-bottom is preferred for most ratios since left-right columns become too narrow. See "Portrait Canvas Override" in `references/image-layout-spec.md`.++> **Multi-image slides**: When multiple images appear on one page, use the grid formulas in the "Multi-Image Layout" section of `references/image-layout-spec.md`.+> **Pipeline handoff**: When C) AI generation is selected, after outputting the design spec, prompt the user to invoke Image_Generator. Once images are collected in `images/`, proceed to Executor.### Visualization Reference (Non-blocking — Strategist recommends, no user confirmation needed)diff --git a/skills/ppt-master/scripts/analyze_images.py b/skills/ppt-master/scripts/analyze_images.pyindex 0ffa941e..27ce71e4 100644--- a/skills/ppt-master/scripts/analyze_images.py+++ b/skills/ppt-master/scripts/analyze_images.py@@ -3,17 +3,19 @@Image Size Analysis Tool========================Analyzes width, height, and aspect ratio of all images in a specified folder,-and outputs PPT layout recommendations.+and outputs PPT layout recommendations with computed dimensions.Usage:python scripts/analyze_images.py <images_folder_path>python scripts/analyze_images.py projects/xxx/images+ python scripts/analyze_images.py projects/xxx/images --canvas ppt43Output:- Analysis report displayed in console- Generates image_analysis.csv in the parent directory of the images folder"""+import argparseimport osimport sysfrom pathlib import Path@@ -24,17 +26,127 @@ except ImportError:print("Error: PIL/Pillow not installed. Run: pip install Pillow")sys.exit(1)+try:+ from config import CANVAS_FORMATS, LAYOUT_MARGINS+except ImportError:+ CANVAS_FORMATS = {+ 'ppt169': {+ 'name': 'PPT 16:9',+ 'width': 1280,+ 'height': 720,+ },+ }+ LAYOUT_MARGINS = {+ 'ppt169': {+ 'top': 60, 'right': 60, 'bottom': 60, 'left': 60,+ 'content_width': 1160, 'content_height': 600+ },+ }+IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp", ".tiff", ".tif"}REPORT_WIDTH = 100CATEGORY_WIDTH = 50-PPT_WIDTH = 1280-PPT_HEIGHT = 720-FULL_SCREEN_MIN_RATIO = 1.5-FULL_SCREEN_MAX_RATIO = 2.0++# Title area height and gap between image/text areas (px)+TITLE_HEIGHT = 60+LAYOUT_GAP = 20+# Minimum text area dimensions (px)+MIN_TEXT_HEIGHT = 150+MIN_TEXT_WIDTH = 280ImageAnalysis = dict[str, str | float | int]+def classify_ratio(aspect_ratio: float) -> str:+ """Classify image aspect ratio into layout category.++ Thresholds aligned with image-layout-spec.md:+ >2.0 ultra-wide, 1.5-2.0 wide, 1.2-1.5 standard landscape,+ 0.8-1.2 square, <0.8 portrait.+ """+ if aspect_ratio > 2.0:+ return "Ultra-wide"+ elif aspect_ratio > 1.5:+ return "Wide landscape"+ elif aspect_ratio > 1.2:+ return "Standard landscape"+ elif aspect_ratio > 0.8:+ return "Near square"+ else:+ return "Portrait"+++def compute_layout_dimensions(+ ratio: float,+ content_w: int,+ content_h: int,+ gap: int = LAYOUT_GAP,+) -> dict:+ """Compute image and text area dimensions following image-layout-spec.md.++ Returns dict with layout_type, image_w, image_h, text_w, text_h.+ """+ # Effective content height (below title)+ H = content_h+ W = content_w++ def _try_top_bottom() -> dict | None:+ img_w = W+ img_h = int(round(W / ratio))+ text_h = H - img_h - gap+ if text_h >= MIN_TEXT_HEIGHT:+ return {+ 'layout_type': 'top-bottom',+ 'image_w': img_w,+ 'image_h': img_h,+ 'text_w': W,+ 'text_h': text_h,+ }+ return None++ def _try_left_right_height_first() -> dict | None:+ img_h = H+ img_w = int(round(H * ratio))+ text_w = W - img_w - gap+ if text_w >= MIN_TEXT_WIDTH:+ return {+ 'layout_type': 'left-right',+ 'image_w': img_w,+ 'image_h': img_h,+ 'text_w': text_w,+ 'text_h': H,+ }+ return None++ def _try_left_right_width_constrained() -> dict:+ img_w = int(round(W * 0.7))+ img_h = int(round(img_w / ratio))+ text_w = W - img_w - gap+ return {+ 'layout_type': 'left-right',+ 'image_w': img_w,+ 'image_h': min(img_h, H),+ 'text_w': max(text_w, MIN_TEXT_WIDTH),+ 'text_h': H,+ }++ # Decision tree per image-layout-spec.md+ if ratio > 1.5:+ # Ultra-wide or wide → try top-bottom first+ result = _try_top_bottom()+ if result:+ return result+ # Fallback to left-right (wide-constrained)+ return _try_left_right_width_constrained()+ else:+ # Standard landscape, square, portrait → try left-right (height-first)+ result = _try_left_right_height_first()+ if result:+ return result+ # Fallback to left-right (width-constrained)+ return _try_left_right_width_constrained()++def analyze_images(images_dir: str) -> list[ImageAnalysis]:"""Analyze all image files in a directory.@@ -57,18 +169,7 @@ def analyze_images(images_dir: str) -> list[ImageAnalysis]:with Image.open(filepath) as img:width, height = img.sizeaspect_ratio = width / height-- # Determine PPT layout recommendation- if aspect_ratio > FULL_SCREEN_MIN_RATIO:- layout_hint = "Wide landscape"- elif aspect_ratio > 1.2:- layout_hint = "Standard landscape"- elif aspect_ratio > 0.8:- layout_hint = "Near square"- elif aspect_ratio > 0.6:- layout_hint = "Standard portrait"- else:- layout_hint = "Narrow portrait"+ layout_hint = classify_ratio(aspect_ratio)results.append({'filename': filename,@@ -84,132 +185,162 @@ def analyze_images(images_dir: str) -> list[ImageAnalysis]:return results-def print_results(results: list[ImageAnalysis]) -> None:- """Print the analysis report to stdout.+def enrich_with_layout(+ results: list[ImageAnalysis],+ 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)- Args:- results: Image analysis records returned by `analyze_images`.- """+ if not margins:+ print(f"[WARN] No layout margins for canvas '{canvas_key}', skipping dimension calculation")+ return++ content_w = margins['content_width']+ content_h = margins['content_height']++ for img in results:+ dims = compute_layout_dimensions(img['aspect_ratio'], content_w, content_h)+ img.update(dims)+++def print_results(results: list[ImageAnalysis]) -> None:+ """Print the analysis report to stdout."""print("\n" + "=" * REPORT_WIDTH)print("Image Size Analysis Report")print("=" * REPORT_WIDTH)- # Table header- print(f"\n{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Size':<10} {'Layout':<15} {'Filename'}")+ has_layout = 'layout_type' in results[0] if results else False++ if has_layout:+ print(f"\n{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Size':<10} {'Category':<20} {'Layout':<12} {'ImgArea':<14} {'Filename'}")+ else:+ print(f"\n{'No.':<4} {'Width':<7} {'Height':<7} {'Ratio':<7} {'Size':<10} {'Category':<20} {'Filename'}")print("-" * REPORT_WIDTH)for i, img in enumerate(results, 1):- print(f"{i:<4} {img['width']:<7} {img['height']:<7} {img['aspect_ratio']:<7.2f} {img['filesize_kb']:<10.1f}KB {img['layout_hint']:<15} {img['filename'][:40]}")+ base = f"{i:<4} {img['width']:<7} {img['height']:<7} {img['aspect_ratio']:<7.2f} {img['filesize_kb']:<10.1f}KB {img['layout_hint']:<20}"+ if has_layout:+ img_area = f"{img['image_w']}x{img['image_h']}"+ print(f"{base} {img['layout_type']:<12} {img_area:<14} {img['filename'][:35]}")+ else:+ print(f"{base} {img['filename'][:40]}")print("-" * REPORT_WIDTH)print(f"Total: {len(results)} images\n")- # Group statistics by aspect ratio+ # Group statistics by aspect ratio (aligned with image-layout-spec.md thresholds)print("\nGroup by Aspect Ratio:")print("-" * CATEGORY_WIDTH)categories = {- "Wide (>1.5)": [],+ "Ultra-wide (>2.0)": [],+ "Wide (1.5-2.0)": [],"Standard (1.2-1.5)": [],"Square (0.8-1.2)": [],- "Portrait (0.6-0.8)": [],- "Narrow (<0.6)": []+ "Portrait (<0.8)": [],}for img in results:ar = img['aspect_ratio']- if ar > 1.5:- categories["Wide (>1.5)"].append(img)+ if ar > 2.0:+ categories["Ultra-wide (>2.0)"].append(img)+ elif ar > 1.5:+ categories["Wide (1.5-2.0)"].append(img)elif ar > 1.2:categories["Standard (1.2-1.5)"].append(img)elif ar > 0.8:categories["Square (0.8-1.2)"].append(img)- elif ar > 0.6:- categories["Portrait (0.6-0.8)"].append(img)else:- categories["Narrow (<0.6)"].append(img)+ categories["Portrait (<0.8)"].append(img)for cat, imgs in categories.items():if imgs:- print(f"\\n{cat}: {len(imgs)} images")+ print(f"\n{cat}: {len(imgs)} images")for img in imgs[:5]: # Show only the first 5print(f" - {img['width']}x{img['height']} (ratio {img['aspect_ratio']:.2f}) - {img['filename'][:35]}...")if len(imgs) > 5:print(f" ... and {len(imgs) - 5} more")- # PPT layout recommendations- print("\\n" + "=" * REPORT_WIDTH)- print("PPT Fit Suggestions (16:9 = 1280x720)")- print("=" * REPORT_WIDTH)- ppt_width, ppt_height = PPT_WIDTH, PPT_HEIGHT- ppt_ratio = ppt_width / ppt_height-- print(f"\\nStandard PPT canvas: {ppt_width}x{ppt_height} (ratio {ppt_ratio:.2f})")-- fit_count = 0- for img in results:- if FULL_SCREEN_MIN_RATIO <= img["aspect_ratio"] <= FULL_SCREEN_MAX_RATIO:- fit_count += 1-- print(f"\\nImages suitable for full-screen display: {fit_count}")+def generate_markdown(results: list[ImageAnalysis], canvas_key: str) -> None:+ """Print a Markdown-ready image inventory section."""+ print("\n" + "=" * REPORT_WIDTH)+ print("Markdown Snippet for Strategist (Copy & Paste)")+ print("=" * REPORT_WIDTH)+ has_layout = 'layout_type' in results[0] if results else False+ fmt_name = CANVAS_FORMATS.get(canvas_key, {}).get('name', canvas_key)-def generate_markdown(results: list[ImageAnalysis]) -> None:- """Print a Markdown-ready image inventory section.+ print(f"\n## Image Resource Inventory (Auto-scan Results — {fmt_name})\n")- Args:- results: Image analysis records returned by `analyze_images`.- """- print("\\n" + "=" * REPORT_WIDTH)- print("Markdown Snippet for Strategist (Copy & Paste)")- print("=" * REPORT_WIDTH)- print("\\n## Image Resource Inventory (Auto-scan Results)\\n")- print("| Filename | Size | Ratio | Layout Suggestion | Usage | Status | Generation Description |")- print("|----------|------|-------|-------------------|-------|--------|-----------------------|")+ if has_layout:+ print("| Filename | Size | Ratio | Layout | Image Area | Text Area | Usage | Type | Status | Generation Description |")+ print("|----------|------|-------|--------|------------|-----------|-------|------|--------|-----------------------|")+ else:+ print("| Filename | Size | Ratio | Layout Suggestion | Usage | Type | Status | Generation Description |")+ print("|----------|------|-------|-------------------|-------|------|--------|-----------------------|")for img in results:- # Simplify layout suggestion description to match Strategist conventions- layout_desc = img['layout_hint']- if img['aspect_ratio'] > 2.0:- layout_desc += " (suitable for full-width/split)"- elif img['aspect_ratio'] > 1.2:- layout_desc += " (suitable for full-screen/illustration)"- elif img['aspect_ratio'] < 0.8:- layout_desc += " (suitable for side-by-side columns)"+ ratio_str = f"{img['aspect_ratio']:.2f}"- # Usage and generation description to be filled in by the strategist; placeholders used here- print(f"| {img['filename']} | {img['width']}x{img['height']} | {img['aspect_ratio']:.2f} | {layout_desc} | (to be filled) | Existing | - |")- print("\\n" + "=" * REPORT_WIDTH + "\\n")+ if has_layout:+ img_area = f"{img['image_w']}x{img['image_h']}"+ text_area = f"{img['text_w']}x{img['text_h']}"+ print(f"| {img['filename']} | {img['width']}x{img['height']} | {ratio_str} | {img['layout_type']} | {img_area} | {text_area} | (to be filled) | | Existing | - |")+ else:+ layout_desc = img['layout_hint']+ if img['aspect_ratio'] > 2.0:+ layout_desc += " (top-bottom, full-width)"+ elif img['aspect_ratio'] > 1.5:+ layout_desc += " (top-bottom)"+ elif img['aspect_ratio'] > 1.2:+ layout_desc += " (left-right split)"+ elif img['aspect_ratio'] > 0.8:+ layout_desc += " (left-right split)"+ else:+ layout_desc += " (left-right, image on left)"+ print(f"| {img['filename']} | {img['width']}x{img['height']} | {ratio_str} | {layout_desc} | (to be filled) | | Existing | - |")++ print("\n" + "=" * REPORT_WIDTH + "\n")def save_csv(results: list[ImageAnalysis], csv_path: str) -> None:- """Save analysis results to a CSV file.+ """Save analysis results to a CSV file."""+ has_layout = 'layout_type' in results[0] if results else False- Args:- results: Image analysis records returned by `analyze_images`.- csv_path: Destination CSV path.- """with open(csv_path, 'w', encoding='utf-8') as f:- f.write("No,Filename,Width,Height,AspectRatio,SizeKB,Layout\n")- for i, img in enumerate(results, 1):- f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img['filesize_kb']:.1f},{img['layout_hint']}\n")+ if has_layout:+ f.write("No,Filename,Width,Height,AspectRatio,SizeKB,Category,LayoutType,ImageArea,TextArea\n")+ for i, img in enumerate(results, 1):+ f.write(f"{i},{img['filename']},{img['width']},{img['height']},{img['aspect_ratio']:.2f},{img['filesize_kb']:.1f},{img['layout_hint']},{img['layout_type']},{img['image_w']}x{img['image_h']},{img['text_w']}x{img['text_h']}\n")+ else:+ f.write("No,Filename,Width,Height,AspectRatio,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['filesize_kb']:.1f},{img['layout_hint']}\n")print(f"\nCSV saved to: {csv_path}")def main() -> None:"""Run the CLI entry point."""- if len(sys.argv) < 2:- print("Usage: python analyze_images.py <images_folder_path>")- print("Example: python analyze_images.py projects/myproject/images")- print(" python analyze_images.py C:/path/to/images")- sys.exit(1)-- images_dir = sys.argv[1]-- # Convert to absolute path- images_dir = os.path.abspath(images_dir)+ parser = argparse.ArgumentParser(+ description="Analyze image sizes and compute PPT layout dimensions"+ )+ parser.add_argument(+ "images_dir",+ help="Path to the images directory"+ )+ parser.add_argument(+ "--canvas",+ default="ppt169",+ help=f"Canvas format key (default: ppt169). Available: {', '.join(sorted(CANVAS_FORMATS.keys()))}"+ )++ args = parser.parse_args()++ images_dir = os.path.abspath(args.images_dir)if not os.path.exists(images_dir):print(f"Error: Directory not found: {images_dir}")@@ -219,13 +350,21 @@ def main() -> None:print(f"Error: Not a directory: {images_dir}")sys.exit(1)+ canvas_key = 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)++ 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', '?')})")results = analyze_images(images_dir)if results:+ enrich_with_layout(results, canvas_key)print_results(results)- generate_markdown(results)+ generate_markdown(results, canvas_key)# Save to CSV file (saved in the parent directory of the images folder)parent_dir = os.path.dirname(images_dir)diff --git a/skills/ppt-master/scripts/config.py b/skills/ppt-master/scripts/config.pyindex fe70835c..3797de32 100644--- a/skills/ppt-master/scripts/config.py+++ b/skills/ppt-master/scripts/config.py@@ -323,6 +323,14 @@ LAYOUT_MARGINS = {'content_width': 1160,'content_height': 600},+ 'ppt43': {+ 'top': 50,+ 'right': 50,+ 'bottom': 50,+ 'left': 50,+ 'content_width': 924,+ 'content_height': 608+ },'xiaohongshu': {'top': 80,'right': 60,@@ -338,7 +346,23 @@ LAYOUT_MARGINS = {'left': 60,'content_width': 960,'content_height': 960- }+ },+ 'story': {+ 'top': 120,+ 'right': 60,+ 'bottom': 180,+ 'left': 60,+ 'content_width': 960,+ 'content_height': 1620+ },+ 'wechat': {+ 'top': 40,+ 'right': 40,+ 'bottom': 40,+ 'left': 40,+ 'content_width': 820,+ 'content_height': 303+ },}diff --git a/skills/ppt-master/scripts/finalize_svg.py b/skills/ppt-master/scripts/finalize_svg.pyindex ae40a916..c96dc24a 100644--- a/skills/ppt-master/scripts/finalize_svg.py+++ b/skills/ppt-master/scripts/finalize_svg.py@@ -106,6 +106,8 @@ def finalize_project(options: dict[str, bool],dry_run: bool = False,quiet: bool = False,+ compress: bool = False,+ max_dimension: int | None = None,) -> bool:"""Finalize SVG files in the project@@ -115,6 +117,8 @@ def finalize_project(options: Processing options dictionarydry_run: Preview only, do not executequiet: Quiet mode, reduce output+ compress: Compress images before embedding+ max_dimension: Downscale images exceeding this dimension"""svg_output = project_dir / 'svg_output'svg_final = project_dir / 'svg_final'@@ -198,7 +202,9 @@ def finalize_project(safe_print("[4/6] Embedding images...")images_count = 0for svg_file in svg_final.glob('*.svg'):- count, _ = embed_images_in_svg(str(svg_file), dry_run=False)+ count, _ = embed_images_in_svg(str(svg_file), dry_run=False,+ compress=compress,+ max_dimension=max_dimension)images_count += countif not quiet:if images_count > 0:@@ -274,6 +280,10 @@ Processing options (for --only):help='Preview only, do not execute')parser.add_argument('--quiet', '-q', action='store_true',help='Quiet mode, reduce output')+ parser.add_argument('--compress', action='store_true',+ help='Compress images before embedding (JPEG quality=85, PNG optimize)')+ parser.add_argument('--max-dimension', type=int, default=None,+ help='Downscale images exceeding this dimension on either axis (e.g., 2560)')args = parser.parse_args()@@ -303,7 +313,9 @@ Processing options (for --only):'fix_rounded': True,}- success = finalize_project(args.project_dir, options, args.dry_run, args.quiet)+ success = finalize_project(args.project_dir, options, args.dry_run, args.quiet,+ compress=args.compress,+ max_dimension=args.max_dimension)sys.exit(0 if success else 1)diff --git a/skills/ppt-master/scripts/svg_finalize/embed_images.py b/skills/ppt-master/scripts/svg_finalize/embed_images.pyindex 26d54e1e..3c6d8aeb 100644--- a/skills/ppt-master/scripts/svg_finalize/embed_images.py+++ b/skills/ppt-master/scripts/svg_finalize/embed_images.py@@ -53,13 +53,72 @@ def get_file_size_str(size_bytes: int) -> str:else:return f"{size_bytes / (1024 * 1024):.1f} MB"-def embed_images_in_svg(svg_path: str, dry_run: bool = False) -> tuple[int, int]:+def _optimize_image_bytes(img_bytes: bytes, mime_type: str,+ compress: bool = False,+ max_dimension: int | None = None) -> bytes:+ """Optionally compress and/or downscale image bytes.++ Returns the (possibly optimized) image bytes. Falls back to the+ original bytes if PIL is not available or optimization fails.+ """+ if not compress and not max_dimension:+ return img_bytes++ try:+ from PIL import Image as PILImage+ import io+ except ImportError:+ return img_bytes++ try:+ img = PILImage.open(io.BytesIO(img_bytes))+ except Exception:+ return img_bytes++ changed = False++ # Downscale if exceeding max_dimension+ if max_dimension:+ w, h = img.size+ if w > max_dimension or h > max_dimension:+ ratio = min(max_dimension / w, max_dimension / h)+ new_w, new_h = int(w * ratio), int(h * ratio)+ img = img.resize((new_w, new_h), PILImage.LANCZOS)+ changed = True++ # Compress+ if compress or changed:+ buf = io.BytesIO()+ if mime_type == 'image/jpeg':+ if img.mode in ('RGBA', 'P'):+ img = img.convert('RGB')+ img.save(buf, format='JPEG', quality=85, optimize=True)+ elif mime_type == 'image/png':+ img.save(buf, format='PNG', optimize=True)+ else:+ # For other formats, just re-save+ fmt = img.format or 'PNG'+ img.save(buf, format=fmt)++ optimized = buf.getvalue()+ # Only use optimized version if it's actually smaller+ if len(optimized) < len(img_bytes):+ return optimized++ return img_bytes+++def embed_images_in_svg(svg_path: str, dry_run: bool = False,+ compress: bool = False,+ max_dimension: int | None = None) -> tuple[int, int]:"""Convert externally referenced images in an SVG file to Base64 inline format.Args:svg_path: SVG file pathdry_run: If True, only show which images would be processed without modifying the file+ compress: If True, compress images before embedding (JPEG quality=85, PNG optimize)+ max_dimension: If set, downscale images exceeding this dimension on either axisReturns:tuple: (number of images processed, file size after embedding)@@ -93,23 +152,32 @@ def embed_images_in_svg(svg_path: str, dry_run: bool = False) -> tuple[int, int]if not os.path.exists(full_path):print(f" [WARN] Image not found: {img_path}")- images_found.append((img_path, "NOT FOUND", 0))+ images_found.append((img_path, "NOT FOUND", 0, None))return match.group(0)-+img_size = os.path.getsize(full_path)-+if dry_run:- images_found.append((img_path, "WILL EMBED", img_size))+ images_found.append((img_path, "WILL EMBED", img_size, None))return match.group(0)with open(full_path, 'rb') as img_file:img_bytes = img_file.read()- b64_data = base64.b64encode(img_bytes).decode('utf-8')mime_type = get_mime_type(img_path, img_bytes)+ optimized_bytes = _optimize_image_bytes(+ img_bytes, mime_type, compress=compress, max_dimension=max_dimension)+ b64_data = base64.b64encode(optimized_bytes).decode('utf-8')+images_embedded += 1- images_found.append((img_path, "EMBEDDED", img_size))-+ saved = len(img_bytes) - len(optimized_bytes)+ if saved > 0 and (compress or max_dimension):+ pct = saved / len(img_bytes) * 100+ images_found.append((img_path, "EMBEDDED", img_size,+ f"{get_file_size_str(len(img_bytes))} → {get_file_size_str(len(optimized_bytes))}, saved {pct:.0f}%"))+ else:+ images_found.append((img_path, "EMBEDDED", img_size, None))+return f'href="data:{mime_type};base64,{b64_data}"'new_content = re.sub(pattern, replace_with_base64, content)@@ -119,10 +187,13 @@ def embed_images_in_svg(svg_path: str, dry_run: bool = False) -> tuple[int, int]# Print processed imagesif images_found:print(f"\n[FILE] {os.path.basename(svg_path)}")- for img_path, status, size in images_found:+ for img_path, status, size, opt_info in images_found:size_str = get_file_size_str(size) if size > 0 else ""if status == "EMBEDDED":- print(f" [OK] {img_path} ({size_str})")+ if opt_info:+ print(f" [OK] {img_path} ({opt_info})")+ else:+ print(f" [OK] {img_path} ({size_str})")elif status == "WILL EMBED":print(f" [PREVIEW] {img_path} ({size_str}) [dry-run]")else:@@ -151,11 +222,19 @@ Examples:parser.add_argument('files', nargs='+', help='SVG files to process')parser.add_argument('--dry-run', '-n', action='store_true',help='Only show which images would be processed, without modifying files')-+ parser.add_argument('--compress', action='store_true',+ help='Compress images before embedding (JPEG quality=85, PNG optimize)')+ parser.add_argument('--max-dimension', type=int, default=None,+ help='Downscale images exceeding this dimension on either axis (e.g., 2560)')+args = parser.parse_args()-+if args.dry_run:print("[INFO] Dry-run mode: only preview, no modification\n")+ if args.compress:+ print("[INFO] Compression enabled: JPEG quality=85, PNG optimize")+ if args.max_dimension:+ print(f"[INFO] Max dimension: {args.max_dimension}px")total_images = 0total_files = 0@@ -169,7 +248,9 @@ Examples:print(f"[SKIP] Skipping non-SVG file: {svg_file}")continue- images, _ = embed_images_in_svg(svg_file, dry_run=args.dry_run)+ images, _ = embed_images_in_svg(svg_file, dry_run=args.dry_run,+ compress=args.compress,+ max_dimension=args.max_dimension)if images > 0:total_images += imagestotal_files += 1diff --git a/skills/ppt-master/scripts/svg_quality_checker.py b/skills/ppt-master/scripts/svg_quality_checker.pyindex 09198ed4..791b04e1 100644--- a/skills/ppt-master/scripts/svg_quality_checker.py+++ b/skills/ppt-master/scripts/svg_quality_checker.py@@ -89,6 +89,9 @@ class SVGQualityChecker:# 5. Check text wrapping methodsself._check_text_elements(content, result)+ # 6. Check image references (file existence and resolution)+ self._check_image_references(content, svg_path, result)+# Determine pass/failresult['passed'] = len(result['errors']) == 0@@ -288,6 +291,71 @@ class SVGQualityChecker:f"Detected {len(text_matches)} potentially overly long single-line text(s) (consider using tspan for wrapping)")+ def _check_image_references(self, content: str, svg_path: Path, result: Dict):+ """Check image file existence and resolution vs display size."""+ # Find all <image ...> elements (capture the full tag)+ img_tag_pattern = re.compile(r'<image\b([^>]*)/?>', re.IGNORECASE)++ svg_dir = svg_path.parent+ checked = set()++ for tag_match in img_tag_pattern.finditer(content):+ attrs = tag_match.group(1)++ # Extract href (prefer href over xlink:href)+ href_match = (+ re.search(r'\bhref="(?!data:)([^"]+)"', attrs) or+ re.search(r'\bxlink:href="(?!data:)([^"]+)"', attrs)+ )+ if not href_match:+ continue++ href = href_match.group(1)+ if href in checked:+ continue+ checked.add(href)++ # Resolve path relative to SVG file directory+ img_path = (svg_dir / href).resolve()++ if not img_path.exists():+ result['errors'].append(+ f"Image file not found: {href} (resolved to {img_path})")+ continue++ # Check resolution vs display size+ w_match = re.search(r'\bwidth="([^"]+)"', attrs)+ h_match = re.search(r'\bheight="([^"]+)"', attrs)+ display_w_str = w_match.group(1) if w_match else None+ display_h_str = h_match.group(1) if h_match else None+ if not display_w_str or not display_h_str:+ continue++ try:+ display_w = float(display_w_str)+ display_h = float(display_h_str)+ except (ValueError, TypeError):+ continue++ try:+ from PIL import Image as PILImage+ with PILImage.open(img_path) as img:+ actual_w, actual_h = img.size++ if actual_w < display_w or actual_h < display_h:+ 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")+ elif actual_w > display_w * 4 and actual_h > display_h * 4:+ result['warnings'].append(+ f"Image {href} is {actual_w}x{actual_h} but displayed at "+ f"{int(display_w)}x{int(display_h)} — consider downsizing "+ f"to reduce file size")+ except ImportError:+ pass # PIL not available, skip resolution check+ except Exception:+ pass # Image unreadable, skip resolution check+def _categorize_issue(self, error_msg: str) -> str:"""Categorize issue type"""if 'viewBox' in error_msg: