Skip to content

fix(pptx): preserve template decorative elements when generating PPTX #109

Closed

Description

@larryro

Problem Statement

When generating PPTX files using a template, decorative image elements (icons, graphics, weather widgets, etc.) from the original template slides are lost in the generated output. Users expect the template to act as a visual foundation where decorative elements are preserved.

Current State

In services/crawler/app/services/pptx_service.py:

  1. New slides are created using prs.slides.add_slide(layout) - this only uses the slide layout, NOT the actual template slide content
  2. Original template slides are deleted using prs.part.drop_rel(rId), which severs relationships to embedded images
  3. Slide layouts only contain placeholder structure, not the decorative shapes that exist on the actual template slides

The code creates template_slides_by_layout but never uses it to clone slides.

Proposed Solution

Clone Template Slide + Content Replacement Approach (3-Step Flow)

  1. Analyze template → Extract slide structure (placeholders, layout type, supported content types) for AI
  2. AI generates content → AI generates matching content with slideIndex to specify which slide to clone
  3. Clone + replace → Clone the corresponding template slide based on slideIndex, then replace placeholder content

Affected Components

  • services/crawler/app/services/pptx_service.py - Add cloning methods, remove redundant manual methods, refactor generation logic
  • services/platform/convex/model/documents/generate_pptx.ts - Add slideIndex field to SlideContentData
  • services/platform/convex/agent_tools/files/pptx_tool.ts - Update slideContentSchema to add slideIndex

Acceptance Criteria

  • Template decorative elements (images, shapes, icons) are preserved in generated PPTX
  • analyze_template returns slideIndex, placeholders, and hasDecorativeElements for each slide
  • generate operation accepts slideIndex to specify which template slide to clone
  • Placeholder content (title, subtitle, body) is correctly replaced after cloning
  • Tables are still properly added to slides
  • Fallback to layout-based creation when no template or matching slide is found

🤖 Generated with Claude Code

Activity

  1. larryro commented on Jan 8, 2026

    @larryro
    ContributorAuthor

    Implementation Plan

    Step 1: Enhance Template Analysis (analyze_template)

    File: services/crawler/app/services/pptx_service.py

    Enhance _extract_slide_info() method to return more detailed slide structure for AI:

    • slideIndex for each slide (for clone matching)
    • layoutName for each slide
    • Available placeholder types (title, subtitle, body, etc.)
    • hasDecorativeElements flag (images, shapes)
    def _extract_slide_info(self, idx: int, slide) -> Dict[str, Any]:
        slide_info = {
            "slideIndex": idx,
            "slideNumber": idx + 1,
            "layoutName": slide.slide_layout.name if slide.slide_layout else "Unknown",
            "placeholders": [],
            "hasDecorativeElements": False,
            # ... existing fields
        }
    
        for shape in slide.shapes:
            if shape.is_placeholder:
                slide_info["placeholders"].append({
                    "type": shape.placeholder_format.type.name,
                    "idx": shape.placeholder_format.idx,
                })
            elif shape.shape_type == MSO_SHAPE_TYPE.PICTURE:
                slide_info["hasDecorativeElements"] = True

    Step 2: Update SlideContentData Schema

    File: services/platform/convex/model/documents/generate_pptx.ts

    Add slideIndex field to SlideContentData:

    export interface SlideContentData {
      slideIndex?: number;  // Index of template slide to clone
      layoutName?: string;  // Fallback matching
      title?: string;
      subtitle?: string;
      textContent?: string[];
      bulletPoints?: string[];
      tables?: TableData[];
    }

    File: services/platform/convex/agent_tools/files/pptx_tool.ts

    Update slideContentSchema:

    const slideContentSchema = z.object({
      slideIndex: z.number().optional().describe('Index of template slide to clone (from analyze_template)'),
      layoutName: z.string().optional().describe('Layout name as fallback matching'),
      // ... existing fields
    });

    Step 3: Add Slide Cloning Method

    File: services/crawler/app/services/pptx_service.py

    Add _clone_slide() method using deepcopy:

    from copy import deepcopy
    
    def _clone_slide(self, prs: Presentation, template_slide) -> Slide:
        """Clone a template slide including all shapes and relationships."""
        layout = template_slide.slide_layout
        new_slide = prs.slides.add_slide(layout)
    
        # Remove default shapes created by add_slide (from layout)
        for shape in list(new_slide.shapes):
            sp = shape.element
            sp.getparent().remove(sp)
    
        # Copy all shapes from template to new slide
        for shape in template_slide.shapes:
            el = deepcopy(shape.element)
            new_slide.shapes._spTree.append(el)
    
        # Copy relationships (for images, etc.)
        for rel in template_slide.part.rels.values():
            if "image" in rel.reltype.lower():
                new_slide.part.relate_to(rel._target, rel.reltype)
    
        return new_slide

    Step 4: Add Placeholder Replacement Method

    File: services/crawler/app/services/pptx_service.py

    Add _replace_placeholder_content() method:

    def _replace_placeholder_content(
        self, slide, title: str, subtitle: str,
        body_content: List, tables: List,
        title_font, body_font, title_font_size, body_font_size,
        primary_color, secondary_color
    ) -> None:
        """Replace placeholder content in a cloned slide."""
        for shape in slide.shapes:
            if not shape.is_placeholder:
                continue
    
            ph_type = shape.placeholder_format.type
    
            if ph_type == PP_PLACEHOLDER.TITLE and title:
                self._set_text_with_style(shape, title, title_font, title_font_size, primary_color)
            elif ph_type == PP_PLACEHOLDER.SUBTITLE and subtitle:
                self._set_text_with_style(shape, subtitle, body_font, body_font_size - 2, secondary_color)
            elif ph_type in (PP_PLACEHOLDER.BODY, PP_PLACEHOLDER.OBJECT):
                self._fill_body_placeholder(shape, body_content, body_font, body_font_size)

    Step 5: Modify generate_pptx_from_content() to Use Cloning

    File: services/crawler/app/services/pptx_service.py

    Modify main generation logic to use cloning:

    # Clone and replace content
    for idx, content in enumerate(slides_content):
        slide_index = content.get("slideIndex")
        layout_name = (content.get("layoutName") or "").lower()
    
        # Find template slide to clone
        template_slide = None
        if slide_index is not None and slide_index in template_slides_by_index:
            template_slide = template_slides_by_index[slide_index]
        elif layout_name and layout_name in template_slides_by_layout:
            template_slide = template_slides_by_layout[layout_name]
        elif idx < original_slide_count:
            template_slide = prs.slides[idx]
    
        if template_slide:
            # Clone the template slide (preserves all decorative elements)
            slide = self._clone_slide(prs, template_slide)
            # Replace placeholder content
            self._replace_placeholder_content(slide, ...)
        else:
            # Fallback: create from layout
            slide = self._create_slide_from_content(...)
    
    # Remove original template slides AFTER all clones are created

    Step 6: Clean Up Obsolete Code

    File: services/crawler/app/services/pptx_service.py

    Remove redundant methods after implementing cloning:

    Method Reason
    _add_title_to_slide() Cloning preserves placeholders, no need for manual textbox
    _add_subtitle_to_slide() Same
    _add_text_to_slide() Same
    _add_bullet_list_to_slide() Use placeholder filling after clone
    _create_slide_from_content() Replaced by _clone_slide() + _replace_placeholder_content()

    Keep these methods:

    Method Reason
    _add_table_to_slide() Tables may still need manual addition
    _find_layout_by_name() Needed for fallback (no template)

    Files to Modify

    File Changes
    services/crawler/app/services/pptx_service.py Add cloning methods, remove redundant methods, refactor generation
    services/platform/convex/model/documents/generate_pptx.ts Add slideIndex field
    services/platform/convex/agent_tools/files/pptx_tool.ts Update schema

    Potential Risks

    • Risk 1: Image relationships broken after clone → Mitigation: Explicitly copy relationships using relate_to()
    • Risk 2: Placeholder replacement issues → Mitigation: Test with various placeholder types
    • Risk 3: Template slide count mismatch → Mitigation: Fall back to layout-based creation
    • Risk 4: Cloned shapes overlap with layout shapes → Mitigation: Remove layout shapes before copying

    Testing Strategy

    • Unit test: Clone slide preserves all shapes including images
    • Integration test: Generate PPTX with decorative template, verify images preserved
    • Manual test: Open in PowerPoint/LibreOffice, verify visual accuracy
    • Regression test: Ensure existing functionality (placeholder filling, tables) still works

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: high

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions