youdao.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. import uuid
  3. import hashlib
  4. import time
  5. import aiohttp
  6. import time
  7. from .common import CommonTranslator, InvalidServerResponse, MissingAPIKeyException
  8. from .keys import YOUDAO_APP_KEY, YOUDAO_SECRET_KEY
  9. def sha256_encode(signStr):
  10. hash_algorithm = hashlib.sha256()
  11. hash_algorithm.update(signStr.encode('utf-8'))
  12. return hash_algorithm.hexdigest()
  13. class YoudaoTranslator(CommonTranslator):
  14. _LANGUAGE_CODE_MAP = {
  15. 'CHS': 'zh-CHS',
  16. 'JPN': "ja",
  17. 'ENG': 'en',
  18. 'KOR': 'ko',
  19. 'VIN': 'vi',
  20. 'CSY': 'cs',
  21. 'NLD': 'nl',
  22. 'FRA': 'fr',
  23. 'DEU': 'de',
  24. 'HUN': 'hu',
  25. 'ITA': 'it',
  26. 'PLK': 'pl',
  27. 'PTB': 'pt',
  28. 'ROM': 'ro',
  29. 'RUS': 'ru',
  30. 'ESP': 'es',
  31. 'TRK': 'tr',
  32. 'THA': 'th',
  33. 'IND': 'id'
  34. }
  35. _API_URL = 'https://openapi.youdao.com/api'
  36. def __init__(self):
  37. super().__init__()
  38. if not YOUDAO_APP_KEY or not YOUDAO_SECRET_KEY:
  39. raise MissingAPIKeyException('Please set the YOUDAO_APP_KEY and YOUDAO_SECRET_KEY environment variables before using the youdao translator.')
  40. async def _translate(self, from_lang, to_lang, queries):
  41. data = {}
  42. query_text = '\n'.join(queries)
  43. data['from'] = from_lang
  44. data['to'] = to_lang
  45. data['signType'] = 'v3'
  46. curtime = str(int(time.time()))
  47. data['curtime'] = curtime
  48. salt = str(uuid.uuid1())
  49. signStr = YOUDAO_APP_KEY + self._truncate(query_text) + salt + curtime + YOUDAO_SECRET_KEY
  50. sign = sha256_encode(signStr)
  51. data['appKey'] = YOUDAO_APP_KEY
  52. data['q'] = query_text
  53. data['salt'] = salt
  54. data['sign'] = sign
  55. #data['vocabId'] = "您的用户词表ID"
  56. result = await self._do_request(data)
  57. result_list = []
  58. if "translation" not in result:
  59. raise InvalidServerResponse(f'Youdao returned invalid response: {result}\nAre the API keys set correctly?')
  60. for ret in result["translation"]:
  61. result_list.extend(ret.split('\n'))
  62. return result_list
  63. def _truncate(self, q):
  64. if q is None:
  65. return None
  66. size = len(q)
  67. return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
  68. async def _do_request(self, data):
  69. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  70. async with aiohttp.ClientSession() as session:
  71. async with session.post(self._API_URL, data=data, headers=headers) as resp:
  72. return await resp.json()