Skip to content

Instantly share code, notes, and snippets.

@Cresdy
Created January 15, 2026 02:39
Show Gist options
  • Select an option

  • Save Cresdy/25dbf9eb93902afa34a380af0e3cd88d to your computer and use it in GitHub Desktop.

Select an option

Save Cresdy/25dbf9eb93902afa34a380af0e3cd88d to your computer and use it in GitHub Desktop.
gist123
"""
智能翻译插件 - 核心翻译器
"""
import json
import re
import hashlib
import logging
from typing import Optional, Dict, Any, List
logger = logging.getLogger(__name__)
class Translator:
def __init__(self):
from .dictionary import DictionaryManager
from .cache import TranslationCache
from .fallback import FallbackTranslator
self.dictionary = DictionaryManager()
self.cache = TranslationCache()
self.fallback = FallbackTranslator()
self.stats = {'total': 0, 'cache_hits': 0, 'dict_hits': 0}
logger.info("翻译器初始化完成")
def translate(self, chinese_text: str, category: str = "attraction",
context: Optional[Dict] = None) -> str:
if not chinese_text:
return ""
self.stats['total'] += 1
text = chinese_text.strip()
# 1. 检查缓存
cache_key = self._make_key(text, category, context)
if cached := self.cache.get(cache_key):
self.stats['cache_hits'] += 1
return cached
# 2. 检查词典
if dict_result := self.dictionary.lookup(text, category, context):
self.stats['dict_hits'] += 1
self.cache.set(cache_key, dict_result)
return dict_result
# 3. 规则翻译
if rule_result := self.fallback.translate_with_rules(text, category, context):
self.cache.set(cache_key, rule_result)
return rule_result
# 4. 标记需要翻译
result = f"[需翻译] {text}"
self.cache.set(cache_key, result)
return result
def _make_key(self, text, category, context):
key = f"{text}:{category}"
if context:
key += f":{json.dumps(context, sort_keys=True)}"
return hashlib.md5(key.encode()).hexdigest()
# 便捷函数
_translator = None
def get_translator():
global _translator
if _translator is None:
_translator = Translator()
return _translator
def translate(text, category="attraction", context=None):
return get_translator().translate(text, category, context)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment