Skip to main content
Glama
daekeun-ml

PowerPoint Translator

by daekeun-ml

translate_powerpoint

Convert PowerPoint presentations to a specified language while maintaining original formatting. Supports multiple languages, optional natural language polishing, and saves output to a desired location.

Instructions

Translate a PowerPoint presentation to the specified language.

Args: input_file: Path to the input PowerPoint file (.pptx) target_language: Target language code (e.g., 'ko', 'ja', 'es', 'fr', 'de') output_file: Path to save the translated file (optional, auto-generated if not provided) model_id: AWS Bedrock model ID to use for translation enable_polishing: Enable natural language polishing for more fluent translation

Returns: Success message with translation details

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
enable_polishingNo
input_fileYes
model_idNous.anthropic.claude-3-7-sonnet-20250219-v1:0
output_fileNo
target_languageNoko

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main MCP tool handler for 'translate_powerpoint'. Validates input, instantiates PowerPointTranslator, calls translate_presentation, applies post-processing, and formats the response.
    @mcp.tool()
    def translate_powerpoint(
        input_file: str,
        target_language: str = Config.DEFAULT_TARGET_LANGUAGE,
        output_file: Optional[str] = None,
        model_id: str = Config.DEFAULT_MODEL_ID,
        enable_polishing: bool = True
    ) -> str:
        """
        Translate a PowerPoint presentation to the specified language.
        
        Args:
            input_file: Path to the input PowerPoint file (.pptx)
            target_language: Target language code (e.g., 'ko', 'ja', 'es', 'fr', 'de')
            output_file: Path to save the translated file (optional, auto-generated if not provided)
            model_id: AWS Bedrock model ID to use for translation
            enable_polishing: Enable natural language polishing for more fluent translation
        
        Returns:
            Success message with translation details
        """
        try:
            # Validate input file using helper function
            input_path, error_msg = validate_input_path(input_file)
            if error_msg:
                return error_msg
            
            # Validate target language
            if target_language not in Config.LANGUAGE_MAP:
                available_langs = ', '.join(Config.LANGUAGE_MAP.keys())
                return f"❌ Error: Unsupported language '{target_language}'. Available: {available_langs}"
            
            # Generate output filename if not provided
            if not output_file:
                output_file = str(input_path.parent / f"{input_path.stem}_translated_{target_language}{input_path.suffix}")
            
            # Create translator and translate
            logger.info(f"Starting translation: {input_path} -> {target_language}")
            translator = PowerPointTranslator(model_id, enable_polishing)
            result = translator.translate_presentation(str(input_path), output_file, target_language)
            
            # Apply post-processing if enabled
            config = Config()
            post_processing_applied = False
            if config.get_bool('ENABLE_TEXT_AUTOFIT', True):
                try:
                    verbose = config.get_bool('DEBUG', False)
                    post_processor = PowerPointPostProcessor(config, verbose=verbose)
                    # Overwrite the original output file instead of creating a new one
                    final_output = post_processor.process_presentation(output_file, output_file)
                    post_processing_applied = True
                    logger.info("Post-processing applied: Text auto-fitting enabled")
                except Exception as e:
                    logger.warning(f"Post-processing failed: {e}")
            
            # Format success message
            lang_name = Config.LANGUAGE_MAP.get(target_language, target_language)
            translation_mode = "Natural/Polished" if enable_polishing else "Literal"
            post_processing_status = "✅ Applied" if post_processing_applied else "⚠️ Skipped"
            
            return f"""✅ PowerPoint translation completed successfully!
    
    📁 Input file: {input_path}
    📁 Output file: {output_file}
    🌐 Target language: {target_language} ({lang_name})
    🎨 Translation mode: {translation_mode}
    🤖 Model: {model_id}
    📝 Translated texts: {result.translated_count}
    📋 Translated notes: {result.translated_notes_count}
    📊 Total shapes processed: {result.total_shapes}
    🔧 Post-processing: {post_processing_status}
    
    💡 Translation features used:
    • Intelligent batch processing for efficiency
    • Context-aware translation for coherence
    • Unified text frame processing
    • Formatting preservation
    • {'Natural language polishing for fluent output' if enable_polishing else 'Literal translation for accuracy'}"""
            
        except Exception as e:
            logger.error(f"Translation failed: {str(e)}")
            return f"❌ Translation failed: {str(e)}"
  • Input schema defined by function parameters and comprehensive docstring describing args, types, defaults, and return value.
    def translate_powerpoint(
        input_file: str,
        target_language: str = Config.DEFAULT_TARGET_LANGUAGE,
        output_file: Optional[str] = None,
        model_id: str = Config.DEFAULT_MODEL_ID,
        enable_polishing: bool = True
    ) -> str:
        """
        Translate a PowerPoint presentation to the specified language.
        
        Args:
            input_file: Path to the input PowerPoint file (.pptx)
            target_language: Target language code (e.g., 'ko', 'ja', 'es', 'fr', 'de')
            output_file: Path to save the translated file (optional, auto-generated if not provided)
            model_id: AWS Bedrock model ID to use for translation
            enable_polishing: Enable natural language polishing for more fluent translation
        
        Returns:
            Success message with translation details
        """
  • mcp_server.py:70-70 (registration)
    Tool registration via FastMCP @mcp.tool() decorator.
    @mcp.tool()
  • Helper function to validate and resolve input PowerPoint file path, providing detailed error messages.
    def validate_input_path(input_file: str) -> tuple[Path, str]:
        """
        Validate input file path, handling both absolute and relative paths.
        
        Args:
            input_file: Input file path (absolute or relative)
        
        Returns:
            Tuple of (validated_path, error_message). If error_message is not empty, path validation failed.
        """
        input_path = Path(input_file)
        
        # If it's a relative path, try to resolve it from current working directory
        if not input_path.is_absolute():
            # Try current working directory first
            cwd_path = Path.cwd() / input_file
            if cwd_path.exists():
                input_path = cwd_path
            else:
                # Try the script's directory as fallback
                script_dir = Path(__file__).parent
                script_path = script_dir / input_file
                if script_path.exists():
                    input_path = script_path
        
        if not input_path.exists():
            # Provide more helpful error message with current working directory info
            cwd = Path.cwd()
            script_dir = Path(__file__).parent
            error_msg = f"""❌ Error: File not found: {input_file}
    📁 Current working directory: {cwd}
    📁 Script directory: {script_dir}
    💡 Tried paths:
       • {input_file} (as provided)
       • {cwd / input_file} (from current directory)
       • {script_dir / input_file} (from script directory)
    💡 Try using absolute path or ensure file is in one of these directories"""
            return input_path, error_msg
        
        if not input_path.suffix.lower() == '.pptx':
            return input_path, f"❌ Error: File must be a PowerPoint (.pptx) file: {input_file}"
        
        return input_path, ""
  • Core translation logic in PowerPointTranslator class: loads PPTX, translates each slide using TranslationStrategy (handling complex formatting, batching, context), saves, applies post-processing.
    def translate_presentation(self, input_file: str, output_file: str, target_language: str) -> TranslationResult:
        """Translate entire PowerPoint presentation"""
        try:
            Presentation = self.deps.require('pptx')
            prs = Presentation(input_file)
            result = TranslationResult()
            
            total_slides = len(prs.slides)
            logger.info(f"🎯 Starting translation of {total_slides} slides...")
            logger.info(f"🎨 Translation mode: {'Natural/Polished' if self.enable_polishing else 'Literal'}")
            
            for slide_idx, slide in enumerate(prs.slides):
                logger.info(f"📄 Processing slide {slide_idx + 1}/{total_slides}")
                
                translated_count, notes_translated = self.strategy.translate_slide(slide, target_language)
                
                result.translated_count += translated_count
                if notes_translated:
                    result.translated_notes_count += 1
                result.total_shapes += len(slide.shapes)
                
                logger.info(f"✅ Slide {slide_idx + 1}: {translated_count} texts translated")
            
            # Save translated presentation
            prs.save(output_file)
            
            # Apply post-processing (autofit)
            post_processor = PostProcessor(config=self.config)
            post_processor.process_presentation(output_file, output_file)
            
            logger.info(f"🎉 Translation completed: {output_file}")
            logger.info(f"📊 Summary: {result.translated_count} texts, {result.translated_notes_count} notes")
            
            return result
            
        except Exception as e:
            logger.error(f"❌ Translation failed: {str(e)}")
            raise
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden but lacks critical behavioral details. It mentions 'AWS Bedrock model' and 'polishing' but doesn't disclose rate limits, authentication requirements, file size constraints, whether the original file is modified, or error handling. The return statement is vague ('Success message with translation details').

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is well-structured with clear sections (purpose, Args, Returns) and front-loaded the core function. However, the 'Returns' statement is somewhat vague, and some sentences could be more precise (e.g., 'auto-generated if not provided' is efficient).

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 5 parameters with 0% schema coverage, no annotations, and an output schema present, the description does a decent job but has gaps. It explains parameters but lacks behavioral context (e.g., side effects, limitations). The output schema existence means return values don't need explanation, but more operational guidance would help.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 0%, but the description compensates well by explaining all 5 parameters in the Args section. It clarifies 'output_file' auto-generation, provides language code examples, and explains 'enable_polishing' purpose. However, it doesn't detail 'model_id' options or 'input_file' format beyond '.pptx'.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Translate a PowerPoint presentation') and resource ('PowerPoint presentation'), distinguishing it from siblings like 'translate_specific_slides' (partial translation) and 'post_process_powerpoint' (different operation). The verb 'translate' is precise and the scope is well-defined.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description implies usage for full presentation translation but doesn't explicitly state when to use this vs. 'translate_specific_slides' (partial slides) or 'post_process_powerpoint' (non-translation processing). No guidance on prerequisites like file format compatibility or when not to use this tool is provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/daekeun-ml/ppt-translator'

If you have feedback or need assistance with the MCP directory API, please join our Discord server