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

40
translation_cache.py Normal file
View File

@@ -0,0 +1,40 @@
import json
import os
import hashlib
CACHE_FILE = "product_translation_cache.json"
MAX_CACHE_ENTRIES = 200_000 # максимум записів у кеші
class TranslationCache:
def __init__(self):
self.cache = {}
self.load_cache()
def get_hash(self, text: str) -> str:
return hashlib.md5(text.strip().encode("utf-8")).hexdigest()
def load_cache(self):
if os.path.exists(CACHE_FILE):
try:
with open(CACHE_FILE, "r", encoding="utf-8") as f:
self.cache = json.load(f)
except Exception as e:
print(f"[CACHE] Помилка завантаження кешу: {e}")
def save_cache(self):
# якщо занадто великий кеш — залишаємо тільки останні MAX_CACHE_ENTRIES
if len(self.cache) > MAX_CACHE_ENTRIES:
# зберігаємо найновіші — останні додані (у Python 3.7+ dict зберігає порядок)
trimmed = dict(list(self.cache.items())[-MAX_CACHE_ENTRIES:])
self.cache = trimmed
with open(CACHE_FILE, "w", encoding="utf-8") as f:
json.dump(self.cache, f, ensure_ascii=False, indent=2)
def get(self, text: str) -> str | None:
key = self.get_hash(text)
return self.cache.get(key)
def add(self, text: str, translated: str):
key = self.get_hash(text)
self.cache[key] = translated