No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

47 líneas
1.7KB

  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. if errcode := result.get("error_code", "52000") != "52000":
  28. if errcode == "52001" or errcode == "52002":
  29. retry_cnt -= 1
  30. continue
  31. else:
  32. raise Exception(result["error_msg"])
  33. else:
  34. break
  35. text = "\n".join([item["dst"] for item in result["trans_result"]])
  36. return text
  37. def make_md5(self, s, encoding="utf-8"):
  38. return md5(s.encode(encoding)).hexdigest()