71 lines
2.8 KiB
Python
71 lines
2.8 KiB
Python
import os
|
|
from django.core.management.base import BaseCommand, CommandError
|
|
from django.conf import settings
|
|
from gpt_po_translator.main import translate_po_files
|
|
|
|
class Command(BaseCommand):
|
|
help = 'Translates PO files using gpt-po-translator configured with OpenRouter.'
|
|
|
|
def add_arguments(self, parser):
|
|
parser.add_argument(
|
|
'--folder',
|
|
type=str,
|
|
default=getattr(settings, 'LOCALE_PATHS', ['locale'])[0],
|
|
help='Path to the folder containing .po files (default is the first LOCALE_PATHS entry).',
|
|
)
|
|
parser.add_argument(
|
|
'--lang',
|
|
type=str,
|
|
help='Comma-separated target language codes (e.g., de,fr,es).',
|
|
required=True,
|
|
)
|
|
parser.add_argument(
|
|
'--model',
|
|
type=str,
|
|
default='mistralai/mistral-nemo', # Example OpenRouter model
|
|
help='The OpenRouter model to use (e.g., openai/gpt-4o, mistralai/mistral-nemo).',
|
|
)
|
|
parser.add_argument(
|
|
'--bulk',
|
|
action='store_true',
|
|
help='Enable bulk translation mode for efficiency.',
|
|
)
|
|
parser.add_argument(
|
|
'--bulksize',
|
|
type=int,
|
|
default=50,
|
|
help='Entries per batch in bulk mode (default: 50).',
|
|
)
|
|
|
|
def handle(self, *args, **options):
|
|
# --- OpenRouter Configuration ---
|
|
# 1. Get API Key from environment variable
|
|
api_key = os.environ.get('OPENROUTER_API_KEY')
|
|
if not api_key:
|
|
raise CommandError("The OPENROUTER_API_KEY environment variable is not set.")
|
|
|
|
# 2. Set the base URL for OpenRouter
|
|
openrouter_base_url = "https://openrouter.ai/api/v1"
|
|
|
|
# 3. Call the core translation function, passing OpenRouter specific config
|
|
try:
|
|
self.stdout.write(self.style.NOTICE(f"Starting translation with model: {options['model']} via OpenRouter..."))
|
|
|
|
translate_po_files(
|
|
folder=options['folder'],
|
|
lang_codes=options['lang'].split(','),
|
|
provider='openai', # gpt-po-translator uses 'openai' provider for OpenAI-compatible APIs
|
|
api_key=api_key,
|
|
model_name=options['model'],
|
|
bulk=options['bulk'],
|
|
bulk_size=options['bulksize'],
|
|
# Set the base_url for the OpenAI client to point to OpenRouter
|
|
base_url=openrouter_base_url,
|
|
# OpenRouter often requires a referrer for API usage
|
|
extra_headers={"HTTP-Referer": "http://your-django-app.com"},
|
|
)
|
|
|
|
self.stdout.write(self.style.SUCCESS(f"Successfully translated PO files for languages: {options['lang']}"))
|
|
|
|
except Exception as e:
|
|
raise CommandError(f"An error occurred during translation: {e}") |