44 lines
1.8 KiB
Python
44 lines
1.8 KiB
Python
from deep_translator import GoogleTranslator
|
||
from typing import Dict, Any, List
|
||
import time
|
||
|
||
class ProductTranslator:
|
||
def __init__(self):
|
||
self.translator = GoogleTranslator(source='pl', target='uk')
|
||
|
||
def translate_text(self, text: str) -> str:
|
||
"""Переводит текст с обработкой ошибок и задержкой"""
|
||
if not text or not isinstance(text, str):
|
||
return text
|
||
|
||
try:
|
||
translated = self.translator.translate(text)
|
||
time.sleep(0.5) # Задержка чтобы избежать блокировки
|
||
return translated
|
||
except Exception as e:
|
||
print(f"Ошибка перевода: {e}")
|
||
return text
|
||
|
||
def translate_list(self, items: List[str]) -> List[str]:
|
||
"""Переводит список строк"""
|
||
return [self.translate_text(item) for item in items]
|
||
|
||
def translate_product(self, product: Dict[str, Any]) -> Dict[str, Any]:
|
||
"""Переводит все текстовые поля продукта"""
|
||
translated = product.copy()
|
||
|
||
# Переводим название
|
||
translated['name'] = self.translate_text(product['name'])
|
||
|
||
# Переводим атрибуты
|
||
for attr in translated['attributes']:
|
||
attr['name'] = self.translate_text(attr['name'])
|
||
attr['value'] = self.translate_list(attr['value'])
|
||
|
||
# Переводим описание
|
||
if 'description' in translated:
|
||
for section in translated['description']:
|
||
section['title'] = self.translate_text(section['title'])
|
||
section['text'] = self.translate_text(section['text'])
|
||
|
||
return translated |