選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

baidu_translate.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. # -*- coding: utf-8 -*-
  2. import random
  3. from hashlib import md5
  4. import requests
  5. from config import conf
  6. from translate.translator import Translator
  7. class BaiduTranslator(Translator):
  8. def __init__(self) -> None:
  9. super().__init__()
  10. endpoint = "http://api.fanyi.baidu.com"
  11. path = "/api/trans/vip/translate"
  12. self.url = endpoint + path
  13. self.appid = conf().get("baidu_translate_app_id")
  14. self.appkey = conf().get("baidu_translate_app_key")
  15. if not self.appid or not self.appkey:
  16. raise Exception("baidu translate appid or appkey not set")
  17. # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`, need to convert to ISO 639-1 codes
  18. def translate(self, query: str, from_lang: str = "", to_lang: str = "en") -> str:
  19. if not from_lang:
  20. from_lang = "auto" # baidu suppport auto detect
  21. salt = random.randint(32768, 65536)
  22. sign = self.make_md5("{}{}{}{}".format(self.appid, query, salt, self.appkey))
  23. headers = {"Content-Type": "application/x-www-form-urlencoded"}
  24. payload = {"appid": self.appid, "q": query, "from": from_lang, "to": to_lang, "salt": salt, "sign": sign}
  25. retry_cnt = 3
  26. while retry_cnt:
  27. r = requests.post(self.url, params=payload, headers=headers)
  28. result = r.json()
  29. errcode = result.get("error_code", "52000")
  30. if errcode != "52000":
  31. if errcode == "52001" or errcode == "52002":
  32. retry_cnt -= 1
  33. continue
  34. else:
  35. raise Exception(result["error_msg"])
  36. else:
  37. break
  38. text = "\n".join([item["dst"] for item in result["trans_result"]])
  39. return text
  40. def make_md5(self, s, encoding="utf-8"):
  41. return md5(s.encode(encoding)).hexdigest()