PHPackages                             kargnas/laravel-ai-translator - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Localization &amp; i18n](/categories/localization)
4. /
5. kargnas/laravel-ai-translator

ActiveLibrary[Localization &amp; i18n](/categories/localization)

kargnas/laravel-ai-translator
=============================

AI-powered translation tool for Laravel language files

1.7.21(9mo ago)24838.8k—6.3%34[2 PRs](https://github.com/kargnas/laravel-ai-translator/pulls)1MITPHPPHP ^8.1CI passing

Since Jun 30Pushed 5mo ago5 watchersCompare

[ Source](https://github.com/kargnas/laravel-ai-translator)[ Packagist](https://packagist.org/packages/kargnas/laravel-ai-translator)[ Docs](https://kargn.as/projects/laravel-ai-translator)[ RSS](/packages/kargnas-laravel-ai-translator/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (14)Versions (63)Used By (1)

Laravel AI Translator by kargnas
================================

[](#laravel-ai-translator-by-kargnas)

AI-powered translation tool for Laravel language files

[![Build Status](https://github.com/kargnas/laravel-ai-translator/actions/workflows/tests.yml/badge.svg)](https://github.com/kargnas/laravel-ai-translator/actions)[![Total Downloads](https://camo.githubusercontent.com/0f770ef2d67adb8458d3afe05fd48e1c9eecf35039d81719745e8f3bcfdc7726/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6b6172676e61732f6c61726176656c2d61692d7472616e736c61746f72)](https://packagist.org/packages/kargnas/laravel-ai-translator)[![Latest Stable Version](https://camo.githubusercontent.com/0090addc3adb1b2ea65a7074ab76136207d9e051e30d4469f46d974650d3417c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6b6172676e61732f6c61726176656c2d61692d7472616e736c61746f72)](https://packagist.org/packages/kargnas/laravel-ai-translator)[![License](https://camo.githubusercontent.com/7f9cc69c91aadff9507d45a89a75b71135423bdf7b81ef747708dea09cb5bf8e/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6b6172676e61732f6c61726176656c2d61692d7472616e736c61746f72)](https://packagist.org/packages/kargnas/laravel-ai-translator)

[Official Website](https://kargn.as/projects/laravel-ai-translator)

🔄 Recent Updates
----------------

[](#-recent-updates)

- 🔍 **Find &amp; Remove Unused Translations**: New `ai-translator:find-unused` command to detect and optionally remove unused translation keys
    - Scans your codebase for actual translation usage
    - Supports file type-specific comment detection (PHP, JS, JSX, Vue, Blade)
    - Automatic backup before deletion
    - Removes keys from both source and target languages
    - Progress bars for better UX
- 🧹 **Enhanced Clean Command**: Improved pattern matching and backup handling
    - More precise file pattern matching (no more subdirectory confusion)
    - Better handling of backup directories
    - Strict path matching to prevent unintended deletions
- 🔁 **Parallel Translation**: Translate multiple locales concurrently with the `translate-parallel` command
- **New Provider**: Added Google Gemini support (including the 2.5 models)
- **AI Enhancement**: Added support for Claude 3.7's Extended Thinking capabilities
    - Extended context window up to 200K tokens, output tokens up to 64K tokens
    - Enhanced reasoning for complex translations
    - Improved context understanding with extended thinking mode
- **Visual Logging Improvements**: Completely redesigned logging system
    - 🎨 Beautiful color-coded console output
    - 📊 Real-time progress indicators
    - 🔍 Detailed token usage tracking with visual stats
    - 💫 Animated status indicators for long-running processes
- **Performance Improvements**: Enhanced translation processing efficiency and reduced API calls
- **Better Error Handling**: Improved error handling and recovery mechanisms
- **Code Refactoring**: Major code restructuring for better maintainability
    - Separated services into dedicated classes
    - Improved token usage tracking and reporting
    - Enhanced console output formatting
- **Testing Improvements**: Added comprehensive test suite using Pest
    - XML parsing validation tests
    - Line break handling in CDATA
    - XML comment tag support
    - Multiple translation items processing
- **XML Processing**: Enhanced XML and AI response parsing system for more reliable translations

Overview
--------

[](#overview)

[![Laravel AI Translator Example](docs/example.webp)](docs/example.webp)

Laravel AI Translator is a powerful tool designed to streamline the localization process in Laravel projects. It automates the tedious task of translating strings across multiple languages, leveraging advanced AI models to provide high-quality, context-aware translations.

Key benefits:

- Time-saving: Translate all your language files with one simple command
- AI-powered: Utilizes state-of-the-art language models (GPT-4, GPT-4o, GPT-3.5, Claude, Gemini) for superior translation quality
- Smart context understanding: Accurately captures nuances, technical terms, and Laravel-specific expressions
- Seamless integration: Works within your existing Laravel project structure, preserving complex language file structures

Whether you're working on a personal project or a large-scale application, Laravel AI Translator simplifies the internationalization process, allowing you to focus on building great features instead of wrestling with translations.

Key Features
------------

[](#key-features)

- Automatically detects all language folders in your `lang` directory
- Translates PHP language files from a source language (default: English) to all other languages
- Supports multiple AI providers for intelligent, context-aware translations
- Preserves variables, HTML tags, pluralization codes, and nested structures
- Maintains consistent tone and style across translations
- Supports custom translation rules for enhanced quality and project-specific requirements
- Efficiently processes large language files, saving time and effort
- Respects Laravel's localization system, ensuring compatibility with your existing setup
- Chunking functionality for cost-effective translations: Processes multiple strings in a single AI request, significantly reducing API costs and improving efficiency
- String validation to ensure translation accuracy: Automatically checks and validates AI translations to catch and correct any errors or mistranslations

Also, this tool is designed to translate your language files intelligently:

- Contextual Understanding: Analyzes keys to determine if they represent buttons, descriptions, or other UI elements.
- Linguistic Precision: Preserves word forms, tenses, and punctuation in translations.
- Variable Handling: Respects and maintains your language file variables during translation.
- Smart Length Adaptation: Adjusts translation length to fit UI constraints where possible.
- Tone Consistency: Maintains a consistent tone across translations, customizable via configuration.

Do you want to know how this works? See the prompt in `src/AI`.

Custom Language Styles
----------------------

[](#custom-language-styles)

In addition to standard language translations, this package now supports custom language styles, allowing for unique and creative localizations.

### Built-in Styles

[](#built-in-styles)

The package includes several built-in language styles:

- `ko_kp`: North Korean style Korean
- Various regional dialects and language variants

These are automatically available and don't require additional configuration.

### Custom Style Example: Reddit English

[](#custom-style-example-reddit-english)

As an demonstration of custom styling capabilities, we've implemented a "Reddit style" English:

This style mimics the casual, often humorous language found on Reddit, featuring:

- Liberal use of sarcasm
- Internet slang and meme references
- Playful skepticism

Example configuration:

```
'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",
    ],
],
```

### Creating Custom Styles

[](#creating-custom-styles)

You can create your own custom language styles by adding new entries to the `locale_names` and `additional_rules` in the configuration. This allows you to tailor translations to specific audiences or platforms.

These custom styles offer creative ways to customize your translations, adding a unique flair to your localized content. Use responsibly to enhance user engagement while maintaining clarity and appropriateness for your audience.

Prerequisites
-------------

[](#prerequisites)

- PHP 8.0 or higher
- Laravel 8.0 or higher

Installation
------------

[](#installation)

1. Install the package via composer:

    ```
    composer require kargnas/laravel-ai-translator
    ```
2. Add the Claude API key to your `.env` file:

    ```
    ANTHROPIC_API_KEY=your-anthropic-api-key-here

    ```

    You can obtain an API key from the [Anthropic Console](https://console.anthropic.com/settings/keys).

(If you want to use OpenAI's GPT or Google's Gemini instead, see step 4 below for configuration instructions.)

3. (Optional) Publish the configuration file:

    ```
    php artisan vendor:publish --provider="Kargnas\LaravelAiTranslator\ServiceProvider"
    ```

    This step is optional but recommended if you want to customize the package's behavior. It will create a `config/ai-translator.php` file where you can modify various settings.
4. (Optional) The package is configured to use Claude by default. If you want to use OpenAI's GPT or Google's Gemini instead, update the `config/ai-translator.php` file:

    For OpenAI GPT:

    ```
    'ai' => [
        'provider' => 'openai',
        'model' => 'gpt-4o',
        'api_key' => env('OPENAI_API_KEY'),
    ],
    ```

    Or for Gemini:

    ```
    'ai' => [
        'provider' => 'gemini',
        'model' => 'gemini-2.5-pro-preview-05-06',
        'api_key' => env('GEMINI_API_KEY'),
    ],
    ```

    Then, add the OpenAI or Gemini API key to your `.env` file:

    ```
    OPENAI_API_KEY=your-openai-api-key-here
    GEMINI_API_KEY=your-gemini-api-key-here

    ```

    You can obtain API keys from:

    - OpenAI: [OpenAI Platform](https://platform.openai.com/account/api-keys)
    - Gemini: [Google AI Studio](https://aistudio.google.com/app/apikey)

    **We strongly recommend using Claude for the best translation quality and accuracy.**
5. You're now ready to use the Laravel AI Translator!

Usage
-----

[](#usage)

To translate your language files, run the following command:

```
php artisan ai-translator:translate
```

To speed up translating multiple locales, you can run them in parallel:

```
php artisan ai-translator:translate-parallel
```

Specify target locales separated by commas using the `--locale` option. For example:

```
php artisan ai-translator:translate-parallel --locale=ko,ja
```

If you omit the `--locale` option, the command automatically translates all available locales.

This command will:

1. Recognize all language folders in your `lang` directory
2. Use AI to translate the contents of the string files in the source language, English. (You can change the source language in the config file)

### Finding and Removing Unused Translations

[](#finding-and-removing-unused-translations)

To find translation keys that are no longer used in your codebase:

```
php artisan ai-translator:find-unused [options]
```

This command scans your source code to identify unused translation keys and optionally removes them.

#### Features

[](#features)

- **Smart Code Scanning**: Analyzes PHP, JavaScript, Vue, and Blade files
- **Comment Awareness**: Ignores translation keys in comments (file type specific)
- **Dynamic Key Detection**: Recognizes template literal patterns like `${variable}`
- **Automatic Cleanup**: Optionally removes unused keys from all language files
- **Backup Protection**: Creates automatic backups before deletion
- **Source Language Support**: Removes keys from source language as well

#### Options

[](#options)

- `--source=LOCALE`: Source language to analyze (default: from config)
- `--scan-path=PATH`: Directories to scan (default: app, resources/views)
- `--format=FORMAT`: Output format (table, json, summary)
- `--show-files`: Show which files contain unused translations
- `-f|--force`: Automatically delete without confirmation

#### Examples

[](#examples)

```
# Find unused translations (interactive deletion prompt)
php artisan ai-translator:find-unused

# Scan specific directories
php artisan ai-translator:find-unused --scan-path=app --scan-path=resources

# Auto-delete without confirmation
php artisan ai-translator:find-unused --force

# Show detailed file information
php artisan ai-translator:find-unused --show-files

# Output as JSON
php artisan ai-translator:find-unused --format=json
```

The command automatically:

- Creates timestamped backups in `lang/backup-before-unused/` before deletion
- Detects translation usage patterns in all major file types
- Removes commented-out code to avoid false positives
- Shows progress bars during deletion for better UX

### Cleaning Translations

[](#cleaning-translations)

To remove translated strings and prepare for re-translation, use the clean command:

```
php artisan ai-translator:clean [pattern] [options]
```

This command removes translations from locale files while preserving your source language, allowing you to regenerate translations with updated AI models or rules.

#### Arguments

[](#arguments)

- `pattern`: Optional pattern to match files or keys
    - `enums` - matches `lang/{locale}/enums.php` files only (not subdirectories)
    - `foo/bar` - matches exact path `lang/{locale}/foo/bar.php`
    - `enums.heroes` - matches specific keys within files

#### Options

[](#options-1)

- `-s|--source=LOCALE`: Source locale to exclude from cleaning (default: from config)
- `-f|--force`: Skip confirmation prompt
- `--no-backup`: Skip creating backup files
- `--dry-run`: Preview changes without deletion

#### Examples

[](#examples-1)

```
# Remove all translations from all target locales (interactive confirmation)
php artisan ai-translator:clean

# Remove translations from specific file (direct matches only)
php artisan ai-translator:clean enums

# Remove translations from exact subdirectory path
php artisan ai-translator:clean auth/login

# Remove specific key translations
php artisan ai-translator:clean enums.heroes

# Specify different source locale
php artisan ai-translator:clean --source=es

# Skip confirmation and backup
php artisan ai-translator:clean enums --force --no-backup

# Preview what would be deleted
php artisan ai-translator:clean enums --dry-run
```

The command automatically:

- Creates backups in `lang/backup/` before deletion (unless `--no-backup` is used)
- Uses strict pattern matching (no wildcards in subdirectories)
- Excludes backup directories from being treated as locales
- Shows detailed statistics before performing deletions
- Prevents accidental overwrites by checking for existing backup directories

### Example

[](#example)

Given an English language file:

```
