Download the PHP package kargnas/laravel-ai-translator without Composer
On this page you can find all versions of the php package kargnas/laravel-ai-translator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download kargnas/laravel-ai-translator
More information about kargnas/laravel-ai-translator
Files in kargnas/laravel-ai-translator
Package laravel-ai-translator
Short Description AI-powered translation tool for Laravel language files
License MIT
Homepage https://kargn.as/projects/laravel-ai-translator
Informations about the package laravel-ai-translator
Laravel AI Translator by kargnas
AI-powered translation tool for Laravel language files
๐ Recent Updates
- ๐ Find & 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
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
- 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
In addition to standard language translations, this package now supports custom language styles, allowing for unique and creative localizations.
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
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:
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
- PHP 8.0 or higher
- Laravel 8.0 or higher
Installation
-
Install the package via composer:
-
Add the Claude API key to your
.env
file:You can obtain an API key from the Anthropic Console.
(If you want to use OpenAI's GPT or Google's Gemini instead, see step 4 below for configuration instructions.)
-
(Optional) Publish the configuration file:
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. -
(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:
Or for Gemini:
Then, add the OpenAI or Gemini API key to your
.env
file:You can obtain API keys from:
- OpenAI: OpenAI Platform
- Gemini: Google AI Studio
We strongly recommend using Claude for the best translation quality and accuracy.
- You're now ready to use the Laravel AI Translator!
Usage
To translate your language files, run the following command:
To speed up translating multiple locales, you can run them in parallel:
Specify target locales separated by commas using the --locale
option. For example:
If you omit the --locale
option, the command automatically translates all available locales.
This command will:
- Recognize all language folders in your
lang
directory - 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
To find translation keys that are no longer used in your codebase:
This command scans your source code to identify unused translation keys and optionally removes them.
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
--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
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
To remove translated strings and prepare for re-translation, use the clean command:
This command removes translations from locale files while preserving your source language, allowing you to regenerate translations with updated AI models or rules.
Arguments
pattern
: Optional pattern to match files or keysenums
- matcheslang/{locale}/enums.php
files only (not subdirectories)foo/bar
- matches exact pathlang/{locale}/foo/bar.php
enums.heroes
- matches specific keys within files
Options
-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
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
Given an English language file:
The package will generate translations like these:
-
Korean:
-
Simplified Chinese:
-
Thai:
-
Japanese:
-
๐คฃ Simplified Chinese (Dongbei Dialect):
-
๐คฃ Korean (North Korea):
-
๐คฃ Korean (Busan Dialect):
- ๐คฃ English (Reddit):
Configuration
If you want to customize the settings, you can publish the configuration file:
This will create a config/ai-translator.php
file where you can modify the following settings:
-
source_directory
: If you use a different directory for language files instead of the defaultlang
directory, you can specify it here. -
ai
: Configure the AI provider and model:This package supports Anthropic's Claude, Google's Gemini, and OpenAI's GPT models for translations. Here are the tested and verified models:
Provider Model Extended Thinking Context Window Max Tokens anthropic
claude-sonnet-4-20250514
โ 200K 8K/64K* anthropic
claude-3-7-sonnet-latest
โ 200K 8K/64K* anthropic
claude-3-7-sonnet-latest
โ 200K 8K anthropic
claude-3-haiku-20240307
โ 200K 8K openai
gpt-4o
โ 128K 4K openai
gpt-4o-mini
โ 128K 4K gemini
gemini-2.5-pro-preview-05-06
โ 1000K 64K gemini
gemini-2.5-flash-preview-04-17
โ 1000K 64K * 8K tokens for normal mode, 64K tokens when extended thinking is enabled
For available models:
- Anthropic: See Anthropic Models Documentation
- OpenAI: See OpenAI Models Documentation
โญ๏ธ Strong Recommendation: We highly recommend using Anthropic's Claude models, particularly
claude-sonnet-4-20250514
orclaude-3-7-sonnet-latest
. Here's why:- More accurate and natural translations
- Better understanding of context and nuances
- More consistent output quality
- More cost-effective for the quality provided
- Claude 4.0 offers even better reasoning and translation quality
While OpenAI integration is available, we strongly advise against using it for translations. Our extensive testing has shown that Claude models consistently produce superior results for localization tasks.
Provider Setup
-
Get your API key:
- Anthropic: Console API Keys
- OpenAI: API Keys
- Gemini: Google AI Studio
-
Add to your
.env
file: - Configure in
config/ai-translator.php
:
-
locale_names
: This mapping of locale codes to language names enhances translation quality by providing context to the AI. -
additional_rules
: Add custom rules to the translation prompt. This is useful for customizing the style of the messages or creating entirely new language styles. disable_plural
: Disable pluralization. Use ":count apples" instead of ":count apple|:count apples"
Example configuration:
Make sure to set your chosen AI provider's API key in your .env
file.
Supported File Types
This package supports both PHP and JSON language files used by Laravel:
PHP Language Files
These commands translate PHP language files located in subdirectories like lang/en/
, lang/ko/
, etc.
JSON Language Files
This command translates root-level JSON language files like lang/en.json
, lang/ko.json
, etc.
All translation commands support the same powerful features:
- Interactive language selection: Choose source and target languages interactively
- Reference language support: Use high-quality translations as reference for better results
- Chunking: Process multiple strings in batches for cost-effective API usage
- Progress tracking: Real-time progress indicators with colorful console output
- Token usage monitoring: Track and display API token consumption and costs
- Context awareness: Maintain translation consistency across files
Command Options
All translation commands support these options:
--source=LOCALE
: Source language (e.g.,--source=en
)--locale=LOCALE1,LOCALE2
: Target locales (e.g.,--locale=ko,ja
)--reference=LOCALE1,LOCALE2
: Reference languages for guidance (e.g.,--reference=fr,es
)--chunk=SIZE
: Chunk size for batch processing (default: 100)--max-context=COUNT
: Maximum context items (default: 1000)--force-big-files
: Force translation of files with 500+ strings--show-prompt
: Display AI prompts during translation--non-interactive
: Run without interactive prompts
File Structure Examples
PHP Files:
JSON Files:
Why Support Both Formats?
PHP Files Benefits:
- Nested array structure for better organization
- Support for comments and context
- Slightly better performance
- More flexibility for complex translations
JSON Files Benefits:
- Simpler flat structure
- Easier to edit manually
- Better for frontend JavaScript integration
- Widely supported format
Choose the format that best fits your project's needs - this package handles both seamlessly!
TODO List
We're constantly working to improve Laravel AI Translator. Here are some features and improvements we're planning:
- [ ] Implement strict validation for translations:
- Verify that variables are correctly preserved in translated strings
- Check for consistency in pluralization rules across translations
- [ ] Expand support for other LLMs (such as Gemini)
- [ ] Replace regex-based XML parser with proper XML parsing:
- Better handle edge cases and malformed XML
If you'd like to contribute to any of these tasks, please feel free to submit a pull request!
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
The MIT License (MIT). Please see License File for more information.
Credits
- Created by Sangrak Choi
- Inspired by Mandarin Study
Read my articles about language
- Hong Kong vs Taiwan Chinese - Essential UI Localization Guide
- Setting non-English as the Default Language in a Global Service? Are you crazy?
- Introducing a Service for Learning Mandarin Chinese Based on Etymology
- Tired of manual translations? I've created an AI translator that actually works.
- Laravel AI Translator v1.1: Smarter, Faster, and More Cost-Effective
All versions of laravel-ai-translator with dependencies
crowdin/crowdin-api-client Version ^1.14
google-gemini-php/client Version ^1.0|^2.0
guzzlehttp/guzzle Version ^6.0|^7.0
guzzlehttp/promises Version ^1.0|^2.0
illuminate/support Version >=8.0
openai-php/client Version >=0.2 <1.0
symfony/process Version ^5.0|^6.0|^7.0