48 lines
2.1 KiB
Python
48 lines
2.1 KiB
Python
from openai import OpenAI
|
|
from django.core.management.base import BaseCommand
|
|
from inventory.models import CarModel
|
|
from django.conf import settings
|
|
|
|
|
|
class Command(BaseCommand):
|
|
help = (
|
|
"Translates car model names to Arabic and saves them in the arabic_name field."
|
|
)
|
|
|
|
def handle(self, *args, **kwargs):
|
|
client = OpenAI(api_key=settings.OPENAI_API_KEY)
|
|
car_models = CarModel.objects.all()
|
|
|
|
total = car_models.count()
|
|
print(f"Translating {total} names...")
|
|
|
|
for index, car_model in enumerate(car_models, start=1):
|
|
if not car_model.arabic_name or car_model.arabic_name == "-":
|
|
if isinstance(car_model.name, int):
|
|
car_model.arabic_name = car_model.name
|
|
car_model.save()
|
|
print(f"[{index}/{total}] .. Skipped GPT (Numeric)")
|
|
else:
|
|
try:
|
|
completion = client.chat.completions.create(
|
|
model="gpt-4o",
|
|
messages=[
|
|
{
|
|
"role": "system",
|
|
"content": (
|
|
"You are an assistant that translates English car names to Arabic."
|
|
"If the name is purely numeric, keep it as is."
|
|
"For mixed names like 'D9', translate them as 'دي 9'."
|
|
),
|
|
},
|
|
{"role": "user", "content": car_model.name},
|
|
],
|
|
temperature=0.2,
|
|
)
|
|
translation = completion.choices[0].message.content.strip()
|
|
car_model.arabic_name = translation
|
|
car_model.save()
|
|
print(f"[{index}/{total}] .. Done")
|
|
except Exception as e:
|
|
print(f"Error translating '{car_model.name}': {e}")
|