Laravel AI Translator

repository·master·Indexed 42 days ago

https://github.com/kargnas/laravel-ai-translator

An AI-powered tool for automating the translation of Laravel language files (PHP and JSON) using frontier models from OpenRouter, OpenAI, Anthropic, and Gemini. Features include context-aware translation, structure preservation for variables and HTML, parallel translation, and a cleanup utility to find and remove unused translation keys. Supports Consensus mode for multi-translator validation and custom locale-specific styling rules. Requires PHP 8.3+ and Laravel 12.0+.

Tokens
6.4K
Snippets
23
Records
29
Agent score
53%

What's inside Laravel AI Translator

  1. Overview of Laravel AI Translator features

    master

    Laravel AI Translator automates the localization of Laravel language files using frontier AI models.

    Core Capabilities:

    • Automatic Detection: Scans your lang directory for language folders.
    • Context-Awareness: Analyzes keys to understand if they are buttons, descriptions, or UI elements.
    • Structure Preservation: Maintains variables, HTML tags, pluralization codes, and nested structures.
    • Cost Efficiency: Uses chunking to process multiple strings in a single AI request.
    • Validation: Automatically checks AI translations to catch errors.
    • Style Consistency: Maintains a consistent tone across translations, which can be customized via configuration.
  2. Use Consensus mode for multi-translator validation

    master

    Consensus mode allows you to use multiple translators and a 'judge' to ensure high-quality translations. You configure multiple entries in the translators array and one judge entry. The judge evaluates the candidates produced by the translators and selects the best one for each key.

    'consensus' => [
        'translators' => [
            ['provider' => 'anthropic', 'model' => 'claude-sonnet-4-20250514', 'api_key' => env('ANTHROPIC_API_KEY')],
            ['provider' => 'openrouter', 'model' => 'anthropic/claude-sonnet-4.5', 'api_key' => env('OPENROUTER_API_KEY')],
        ],
        'judge' => [
            'provider' => 'openrouter',
            'model' => 'anthropic/claude-sonnet-4.5',
            'api_key' => env('OPENROUTER_API_KEY),
        ],
    ],
  3. Create Custom Language Styles

    master

    You can tailor translations to specific audiences or platforms by defining custom styles in the config/ai-translator.php configuration file. This is done by adding entries to two keys:

    1. locale_names: Maps a locale code to a human-readable name.
    2. additional_rules: Defines an array of instructions (prompts) that the AI should follow for that specific locale.

    Example of creating a 'Reddit English' style:

    'locale_names' => [
        'en_reddit' => 'English (Reddit)',
    ],
    'additional_rules' => [
        'en_reddit' => [
            "- Incorporate sarcasm and exaggeration",
            "- Use popular internet slang and meme references",
            "- Add humorous calls for sources on obvious statements",
        ],
    ],
  4. Publish the AI Translator configuration

    master

    To customize settings like AI providers, models, or custom translation rules, publish the package configuration file to your Laravel application using the following command:

    php artisan vendor:publish --provider="Kargnas\LaravelAiTranslator\ServiceProvider"
  5. Install Laravel AI Translator

    master

    To use Laravel AI Translator in your project, follow these steps:

    1. Install the package via Composer.
    2. Configure your OpenRouter API key in your .env file. You can obtain a key from OpenRouter.
    3. (Optional) Publish the configuration file to customize settings.
    4. (Optional) Specify a custom AI model in the configuration file.
    # 1. Install the package
    composer require kargnas/laravel-ai-translator
    
    # 2. Add your OpenRouter API key to .env
    # OPENROUTER_API_KEY=your-openrouter-api-key-here
    
    # 3. Publish the configuration file (optional)
    php artisan vendor:publish --provider="Kargnas\LaravelAiTranslator\ServiceProvider"
  6. Translate PHP and JSON language files

    master

    The package supports both Laravel's PHP array-based language files and JSON-based files.

    PHP Files

    Located in subdirectories like lang/en/, lang/ko/, etc. Use these commands:

    • php artisan ai-translator:translate (Standard translation)
    • php artisan ai-translator:translate-parallel (Parallel translation)

    JSON Files

    Located at the root of the lang directory like lang/en.json. Use this command:

    • php artisan ai-translator:translate-json
    # For PHP files
    php artisan ai-translator:translate
    
    # For JSON files
    php artisan ai-translator:translate-json
  7. Run an OpenRouter smoke test

    master

    This smoke test allows you to verify the package's functionality using OpenRouter in a disposable Laravel environment. The script creates a temporary Laravel project and installs the package from your current local checkout.

    Warning: Do not run these tests against production language files.

    export OPENROUTER_API_KEY='your-openrouter-api-key'
    ./scripts/test-setup.sh laravel-ai-translator-openrouter-smoke
    cd laravel-ai-translator-openrouter-smoke
    
    # Update configuration to use OpenRouter instead of Anthropic
    perl -0pi -e "s/'provider' => 'anthropic'/'provider' => 'openrouter'/; s/'model' => 'claude-3-5-sonnet-latest'/'model' => 'anthropic\/claude-sonnet-4.5'/; s/env\('ANTHROPIC_API_KEY'\)/env('OPENROUTER_API_KEY')/" config/ai-translator.php
    
    # Execute the translation test
    php artisan ai-translator:test en ko --text='Hello from OpenRouter'
  8. Add custom translation rules and locale context

    master

    You can improve translation quality and style using two configuration keys:

    1. locale_names: Maps locale codes to full language names (e.g., 'ko' => 'Korean'). This provides context to the AI.
    2. additional_rules: Provides custom instructions to the AI prompt. You can set a default rule for all languages or language-specific rules (e.g., for 'ko').
    'locale_names' => [
        'en' => 'English',
        'ko' => 'Korean',
    ],
    
    'additional_rules' => [
        'default' => [
            "Use a friendly and intuitive tone of voice.",
        ],
        'ko' => [
            "한국의 인터넷 서비스 '토스'의 서비스 말투 처럼...",
        ],
    ],
  9. Configure AI providers and models

    master

    The config/ai-translator.php file allows you to define your AI provider, model, and API key. OpenRouter is the default provider.

    Supported providers include:

    • openrouter (default)
    • openai
    • anthropic
    • gemini

    Ensure you add the corresponding API key to your .env file (e.g., OPENROUTER_API_KEY, OPENAI_API_KEY, etc.) before configuring the provider in the config file.

    'ai' => [
        'provider' => 'openrouter',
        'model' => 'vendor/model-id',
        'api_key' => env('OPENROUTER_API_KEY'),
    ],
  10. How change detection works in JSON translation

    master

    To save costs and time, the translator uses a ChangeDetector to avoid re-translating strings that haven't changed in the source file.

    • Default Behavior: The command compares the current source strings against a saved state. It only translates strings that are either new (untranslated) or have changed since the last run.
    • Bypassing Detection: If you want to re-translate an entire file regardless of changes, use the --force-retranslate flag.
    • Large Files: If a file has more than 500 strings to translate, the command will prompt for confirmation before proceeding to prevent unexpected costs, unless --force-big-files is used.