Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Gpt Translate Laravel Package

edeoliv/gpt-translate

Laravel package to generate and translate JSON language files using OpenAI ChatGPT. Scans PHP/JS/TS/Vue for __(), @lang(), trans(), etc., builds a base locale, then translates to other languages with optional context, exclusions, and model selection.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require edeoliv/gpt-translate
    php artisan vendor:publish --provider="Edeoliv\GptTranslate\TranslateProvider" --tag="config"
    

    This publishes the openai.php config file to config/openai.php.

  2. Configure OpenAI API Key Add your OpenAI API key to .env:

    OPEN_AI_KEY=your-api-key-here
    

    Update config/openai.php with your preferred model (e.g., gpt-3.5-turbo) and other settings.

  3. Generate Base Translation File Scan your app for translation strings and generate a base en.json file:

    php artisan gpt-translate:generate
    

    Run this in your project root where translation strings (e.g., __('key'), @lang('key')) are used.

  4. First Translation Translate the base file to another language (e.g., Spanish):

    php artisan gpt-translate:translate es
    

    This creates es.json in resources/lang/es/.


First Use Case: Quick Translation Workflow

  1. Add a new translation string in a Blade file:
    <h1>{{ __('welcome.message') }}</h1>
    
  2. Generate the base file (if not already done):
    php artisan gpt-translate:generate
    
    This adds "welcome.message": "Welcome!" to en.json.
  3. Translate to French:
    php artisan gpt-translate:translate fr
    
    The package sends the en.json content to ChatGPT and returns translations for fr.json.

Implementation Patterns

Workflow: Localization Pipeline

  1. Develop in Base Language Use __() or @lang() in Blade, JS, or Vue files. Example:

    // resources/js/app.js
    console.log($t('validation.required', { attribute: 'name' }));
    
    <!-- resources/js/components/Example.vue -->
    <template>
      <p>{{ $t('greeting') }}</p>
    </template>
    
  2. Generate Base File Run php artisan gpt-translate:generate to extract all strings into en.json. Customize the scan paths in config/gpt-translate.php:

    'scan_paths' => [
        'resources/lang/en',
        'resources/views',
        'resources/js',
        'resources/js/components',
    ],
    
  3. Translate to Target Languages Batch-translate all languages:

    php artisan gpt-translate:translate es fr de
    

    Or translate incrementally as needed.

  4. Override Auto-Translations Manually edit generated files (e.g., es.json) for context-specific tweaks.


Integration Tips

  • Dynamic Context Pass context to ChatGPT for better translations via config/gpt-translate.php:

    'translation_context' => [
        'app_name' => 'My Awesome App',
        'domain' => 'e-commerce',
    ],
    

    The package appends this to prompts (e.g., "Translate 'Welcome!' to Spanish for an e-commerce app named 'My Awesome App'.").

  • Exclude Strings Skip specific keys (e.g., API endpoints) by adding them to config/gpt-translate.php:

    'exclude_keys' => [
        'api.*',
        'auth.password',
    ],
    
  • Model Flexibility Use higher-tier models (e.g., gpt-4) for complex translations:

    'model' => env('GPT_MODEL', 'gpt-4'),
    
  • Testing Mock translations in tests by overriding the GptTranslate facade or using Laravel’s trans() helper directly.


Gotchas and Tips

Pitfalls

  1. API Rate Limits

    • ChatGPT has token limits (~4000 tokens for gpt-3.5-turbo). Large en.json files may fail.
    • Fix: Split translations into smaller chunks or use gpt-4 (higher limit).
    • Tip: Monitor usage via OpenAI’s dashboard and set OPEN_AI_MAX_TOKENS in .env.
  2. Context Overrides

    • ChatGPT may misinterpret generic strings (e.g., "Submit" could be a button or form term).
    • Fix: Use translation_context or pre-translate ambiguous terms manually.
  3. File Overwrites

    • Running php artisan gpt-translate:translate without --force skips existing files.
    • Tip: Use --force to re-translate or back up files before running.
  4. Scan Paths Missed

    • Custom paths (e.g., app/Locale) aren’t scanned by default.
    • Fix: Extend the scanPaths method in GptTranslateServiceProvider or update config/gpt-translate.php.

Debugging

  1. Enable Logging Add to .env:

    GPT_TRANSLATE_LOG=true
    

    Logs appear in storage/logs/gpt-translate.log.

  2. Check API Responses Enable verbose output:

    php artisan gpt-translate:translate es --verbose
    

    Shows raw ChatGPT responses for debugging mis-translations.

  3. Validate JSON If translations fail silently, validate the generated files:

    php artisan gpt-translate:validate
    

Extension Points

  1. Custom Prompt Templates Override the default prompt in app/Providers/GptTranslateServiceProvider.php:

    $this->app->singleton(GptTranslateService::class, function ($app) {
        $service = new GptTranslateService($app['config']['gpt-translate']);
        $service->setPromptTemplate("Translate the following keys and values to {lang} for a {domain} app: {keys}");
        return $service;
    });
    
  2. Post-Translation Hooks Add logic after translation via an event listener:

    // Event: GptTranslate\Events\TranslationCompleted
    public function handle(TranslationCompleted $event) {
        // Example: Log translations or push to a CMS
    }
    
  3. Support Additional Languages Extend the supportedLanguages array in config/gpt-translate.php:

    'supported_languages' => [
        'en', 'es', 'fr', 'de', 'it', 'pt', 'ja', // Add 'ja' for Japanese
    ],
    

    Note: ChatGPT’s accuracy varies by language.

  4. Batch Processing For large projects, chunk translations by file:

    // In a custom command
    $translator = app(GptTranslateService::class);
    $translator->translateChunk('en.json', 'es', 50); // Translate 50 keys at a time
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor
spatie/laravel-javascript-views