deepl.py 1.2 KB

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