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

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
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