Files
mario_scraper/translator.py
2025-04-17 13:56:40 +03:00

44 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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