from openai import OpenAI from django.core.management.base import BaseCommand from inventory.models import CarSerie, CarModel, CarMake, CarTrim, CarOption, CarSpecification 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) en_value = CarModel.objects.all() total = en_value.count() print(f'Translating {total} names...') for index, en_value in enumerate(en_value, start=1): if not en_value.arabic_name: try: completion = client.chat.completions.create( model="gpt-4o", messages=[ { "role": "system", "content": ( "You are an assistant that translates English to Arabic." "You are an assistant specialized in cars and automotive terms." "If the model name is a number just write it as is" "You can get the arabic names for makes, models, series, trims, options, and specifications." ) }, { "role": "user", "content": en_value.name } ], temperature=0.2, ) translation = completion.choices[0].message.content.strip() en_value.arabic_name = translation en_value.save() print(f"[{index}/{total}] .. Done") except Exception as e: print(f"Error translating '{en_value.name}': {e}")