add translation cache and queue

This commit is contained in:
2025-05-29 13:53:25 +03:00
parent bcee61a817
commit 5b76a0dcbd
8 changed files with 307 additions and 24 deletions

View File

@@ -1,23 +1,45 @@
from deep_translator import GoogleTranslator
from typing import Dict, Any, List
import time
from translation_cache import TranslationCache
class ProductTranslator:
def __init__(self):
self.translator = GoogleTranslator(source="pl", target="uk")
self.cache = TranslationCache() # 🧠 кеш ініціалізація
def translate_text(self, text: str) -> str:
"""Переводит текст с обработкой ошибок и задержкой"""
"""Переводит текст с кешем, обработкой ошибок и задержкой"""
if not text or not isinstance(text, str):
return text
# 🧠 Перевірка кешу
cached = self.cache.get(text)
if cached:
return cached
try:
translated = self.translator.translate(text)
time.sleep(0.5) # Задержка чтобы избежать блокировки
time.sleep(0.5) # Затримка щоб уникнути блокування
if translated and translated != text:
self.cache.add(text, translated)
self.cache.save_cache() # 💾 збереження кешу
return translated
except Exception as e:
print(f"Ошибка перевода: {e}")
error_text = str(e).lower()
print(f"[ERROR] Ошибка перевода: {e}")
if (
"too many requests" in error_text
or "you are allowed to make" in error_text
or "5 requests per second" in error_text
):
raise e
return text
def translate_list(self, items: List[str]) -> List[str]: