2024-12-11 15:55:27 +03:00

37 lines
1.5 KiB
Python

from openai import OpenAI
from django.core.management.base import BaseCommand
from inventory.models import CarSerie
from django.conf import settings
class Command(BaseCommand):
help = 'Translates to Arabic and saves them in arabic_name field.'
def handle(self, *args, **kwargs):
client = OpenAI(api_key=settings.OPENAI_API_KEY)
car_serie = CarSerie.objects.filter(id_car_model__car__id_car_make__is_sa_import=True)[:500]
total = car_serie.count()
print(f'Translating {total} names...')
for index, car_serie in enumerate(car_serie, start=1):
try:
completion = client.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "system",
"content": "You are a translation assistant that translates English to Arabic."
},
{
"role": "user",
"content": car_serie.name
}
],
temperature=0.3,
)
translation = completion.choices[0].message.content.strip()
car_serie.arabic_name = translation
car_serie.save()
print(f"[{index}/{total}] Translated '{car_serie.name}' to '{translation}'")
except Exception as e:
print(f"Error translating '{car_serie.name}': {e}")