zh_translate.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import requests
  2. import json
  3. from homepagebuilder.interfaces import script, Logger
  4. from homepagebuilder.core.config import config
  5. from typing import TYPE_CHECKING
  6. if TYPE_CHECKING:
  7. from homepagebuilder.core.types import Context
  8. logger = Logger("TranslationScript")
  9. TRANSLATIONS = {}
  10. @script('name')
  11. def translate(*args, **_):
  12. if not args:
  13. return ''
  14. name = args[0]
  15. if len(args) == 2:
  16. fallback = args[1]
  17. else:
  18. fallback = name
  19. return TRANSLATIONS.get(name.lower(), fallback)
  20. def fetch_transltions():
  21. logger.info("正在加载中文翻译")
  22. try:
  23. response = requests.get('https://raw.githubusercontent.com/Light-Beacon/Minecraft-ZH-Translation-Sheet/refs/heads/main/data/translations.json',
  24. timeout=10)
  25. except ConnectionError:
  26. logger.warning("无法加载中文翻译")
  27. return {}
  28. response_content = response.content
  29. return json.loads(response_content)
  30. def init(context:'Context', *args, **kwargs):
  31. global TRANSLATIONS
  32. if config('NewsHomepage.Translation.UseReloadCache', config('NewsHomepage.Debug')):
  33. if translations_manifset_cache := context.builder.get_data('translation_manifset_cache'):
  34. TRANSLATIONS = translations_manifset_cache
  35. logger.info("从缓存中加载中文翻译数据成功, 共计 %d 条翻译", len(TRANSLATIONS))
  36. return
  37. TRANSLATIONS = fetch_transltions()
  38. logger.info("加载中文翻译数据成功, 共计 %d 条翻译", len(TRANSLATIONS))
  39. context.builder.set_data('translation_manifset_cache', TRANSLATIONS)