deepl.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """Deepl translation engine"""
  4. from json import loads
  5. about = {
  6. "website": 'https://deepl.com',
  7. "wikidata_id": 'Q43968444',
  8. "official_api_documentation": 'https://www.deepl.com/docs-api',
  9. "use_official_api": True,
  10. "require_api_key": True,
  11. "results": 'JSON',
  12. }
  13. engine_type = 'online_dictionary'
  14. categories = ['general']
  15. url = 'https://api-free.deepl.com/v2/translate'
  16. api_key = None
  17. def request(_query, params):
  18. '''pre-request callback
  19. params<dict>:
  20. - ``method`` : POST/GET
  21. - ``headers``: {}
  22. - ``data``: {} # if method == POST
  23. - ``url``: ''
  24. - ``category``: 'search category'
  25. - ``pageno``: 1 # number of the requested page
  26. '''
  27. params['url'] = url
  28. params['method'] = 'POST'
  29. params['data'] = {'auth_key': api_key, 'text': params['query'], 'target_lang': params['to_lang'][1]}
  30. return params
  31. def response(resp):
  32. results = []
  33. result = loads(resp.text)
  34. translations = result['translations']
  35. infobox = "<dl>"
  36. for translation in translations:
  37. infobox += f"<dd>{translation['text']}</dd>"
  38. infobox += "</dl>"
  39. results.append(
  40. {
  41. 'infobox': 'Deepl',
  42. 'content': infobox,
  43. }
  44. )
  45. return results