Files
chatgpt-on-wechat/translate/factory.py
Zmjjeff7 6a553886da feat(translate): add Youdao as a new translation provider
The translate module previously only supported Baidu translation, and the
factory raised a bare RuntimeError for any other type. This change adds
Youdao Translation as a second provider and improves the factory's error
message.

Implementation details:
- New YoudaoTranslator class in translate/youdao/youdao_translate.py
- Implements Youdao's v3 SHA-256 signature scheme, including the
  truncate-input rule for queries longer than 20 characters
- Maps ISO 639-1 language codes to Youdao-specific codes
  (zh -> zh-CHS, zh-TW -> zh-CHT, others pass through)
- Differentiates network errors, API error codes, and empty translations
- factory.create_translator now lists the supported types in its
  RuntimeError message instead of failing silently
- Default config exposes youdao_translate_app_key and
  youdao_translate_app_secret

Adds 17 unit tests covering signature correctness, language code mapping,
input truncation edge cases, the full request/response flow, and factory
dispatch. All tests pass under Python 3.11.
2026-05-05 23:58:32 +08:00

18 lines
532 B
Python

SUPPORTED_TRANSLATORS = ("baidu", "youdao")
def create_translator(translator_type):
if translator_type == "baidu":
from translate.baidu.baidu_translate import BaiduTranslator
return BaiduTranslator()
if translator_type == "youdao":
from translate.youdao.youdao_translate import YoudaoTranslator
return YoudaoTranslator()
raise RuntimeError(
"unsupported translator type: {}, supported: {}".format(
translator_type, ", ".join(SUPPORTED_TRANSLATORS)
)
)