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

baidu_translate.py 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`, need to convert to ISO 639-1 codes
  16. def translate(self, query: str, from_lang: str = "", to_lang: str = "en") -> str:
  17. if not from_lang:
  18. from_lang = "auto" # baidu suppport auto detect
  19. salt = random.randint(32768, 65536)
  20. sign = self.make_md5(self.appid + query + str(salt) + self.appkey)
  21. headers = {"Content-Type": "application/x-www-form-urlencoded"}
  22. payload = {"appid": self.appid, "q": query, "from": from_lang, "to": to_lang, "salt": salt, "sign": sign}
  23. retry_cnt = 3
  24. while retry_cnt:
  25. r = requests.post(self.url, params=payload, headers=headers)
  26. result = r.json()
  27. errcode = result.get("error_code", "52000")
  28. if errcode != "52000":
  29. if errcode == "52001" or errcode == "52002":
  30. retry_cnt -= 1
  31. continue
  32. else:
  33. raise Exception(result["error_msg"])
  34. else:
  35. break
  36. text = "\n".join([item["dst"] for item in result["trans_result"]])
  37. return text
  38. def make_md5(self, s, encoding="utf-8"):
  39. return md5(s.encode(encoding)).hexdigest()