zh_translate.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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=5)
  25. except requests.ConnectionError:
  26. logger.warning("无法加载中文翻译:连接错误")
  27. return {}
  28. except requests.ReadTimeout as ex:
  29. logger.warning("无法加载中文翻译:访问超时")
  30. return {}
  31. response_content = response.content
  32. return json.loads(response_content)
  33. def init(context:'Context', *args, **kwargs):
  34. global TRANSLATIONS
  35. if config('NewsHomepage.Translation.UseReloadCache', config('NewsHomepage.Debug')):
  36. if translations_manifset_cache := context.builder.get_data('translation_manifset_cache'):
  37. TRANSLATIONS = translations_manifset_cache
  38. logger.info("从缓存中加载中文翻译数据成功, 共计 %d 条翻译", len(TRANSLATIONS))
  39. return
  40. TRANSLATIONS = fetch_transltions()
  41. if len(TRANSLATIONS) > 0:
  42. logger.info("加载中文翻译数据成功, 共计 %d 条翻译", len(TRANSLATIONS))
  43. context.builder.set_data('translation_manifset_cache', TRANSLATIONS)