Spaces:
Running
Running
import re | |
import time | |
import random | |
import os | |
from googletrans import Translator | |
from functools import lru_cache | |
TRANSLATOR_CACHE_SIZE = int(os.getenv("TRANSLATOR_CACHE_SIZE",100)) | |
class TranslatorWithCache: | |
def __init__(self, cache_size=TRANSLATOR_CACHE_SIZE): | |
self.cache_size = cache_size | |
self._init_cache() | |
def _init_cache(self): | |
self.cached_translate = lru_cache(maxsize=self.cache_size)(self._translate) | |
def has_russian_word(self, text): | |
pattern = re.compile(r'[а-яА-ЯёЁ]+') | |
return bool(pattern.search(text)) | |
def has_english_word(self, text): | |
pattern = re.compile(r'[a-zA-Z]+') | |
return bool(pattern.search(text)) | |
def _translate(self, text: str, src: str, dest: str, retries=3) -> str: | |
tr = Translator() | |
for attempt in range(retries): | |
try: | |
return tr.translate(text, src=src, dest=dest).text | |
except TypeError as e: | |
if attempt < retries - 1: | |
delay = random.uniform(1, 2) | |
print(f"Ошибка: {e}. Повторная попытка через {delay:.2f} секунд...") | |
time.sleep(delay) | |
else: | |
print(f"Ошибка: {e}. Превышено количество попыток.") | |
return text # Возвращаем оригинальный текст, если все попытки провалились. | |
def translate_ru2eng(self, text: str, src='ru', dest='en') -> str: | |
if self.has_russian_word(text): | |
return self.cached_translate(text, src, dest) | |
else: | |
return text | |
def translate_eng2ru(self, text: str, src='en', dest='ru') -> str: | |
if self.has_english_word(text): | |
return self.cached_translate(text, src, dest) | |
else: | |
return text | |
if __name__ == "__main__": | |
translator = TranslatorWithCache(cache_size=100) | |
print(translator.translate_ru2eng("Привет, как дела?")) | |
print(translator.translate_eng2ru("Hello, how are you?")) | |
print(translator.translate_ru2eng("Привет, как дела?")) # Повторный вызов для проверки кэша | |