caiyun.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # -*- coding: utf-8 -*-
  2. import aiohttp
  3. from .common import CommonTranslator, InvalidServerResponse, MissingAPIKeyException
  4. from .keys import CAIYUN_TOKEN
  5. class CaiyunTranslator(CommonTranslator):
  6. _LANGUAGE_CODE_MAP = {
  7. 'CHS': 'zh',
  8. 'JPN': "ja",
  9. 'ENG': 'en',
  10. }
  11. _API_URL = 'https://api.interpreter.caiyunai.com/v1/translator'
  12. def __init__(self):
  13. super().__init__()
  14. if not CAIYUN_TOKEN:
  15. raise MissingAPIKeyException('Please set the CAIYUN_TOKEN environment variables before using the caiyun translator.')
  16. async def _translate(self, from_lang, to_lang, queries):
  17. data = {}
  18. if from_lang=="auto":
  19. print("[CaiyunTranlsator] from_lang was set to \"auto\", but Caiyun API doesn't support it. Trying to detect...")
  20. # detect language with stupid & simple trick
  21. queriesText = '\n'.join(queries)
  22. for char in queriesText:
  23. if 0x3000 <= ord(char) <= 0x9FFF:
  24. from_lang = "ja"
  25. break
  26. else:
  27. from_lang = "en"
  28. print(f'[CaiyunTranlsator] from_lang seems to be "{from_lang}"')
  29. data['trans_type'] = from_lang + "2" + to_lang
  30. data['source'] = queries
  31. data['request_id'] = "manga-image-translator"
  32. result = await self._do_request(data)
  33. if "target" not in result:
  34. raise InvalidServerResponse(f'Caiyun returned invalid response: {result}\nAre the API keys set correctly?')
  35. return result["target"]
  36. def _truncate(self, q):
  37. if q is None:
  38. return None
  39. size = len(q)
  40. return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]
  41. async def _do_request(self, data):
  42. headers = {
  43. "content-type": "application/json",
  44. "x-authorization": "token " + CAIYUN_TOKEN,
  45. }
  46. async with aiohttp.ClientSession() as session:
  47. async with session.post(self._API_URL, json=data, headers=headers) as resp:
  48. return await resp.json()