Files
mario_scraper/translation_cache.py

41 lines
1.5 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.
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