translated.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """MyMemory Translated
  3. """
  4. import urllib.parse
  5. from searx.result_types import EngineResults
  6. # about
  7. about = {
  8. "website": 'https://mymemory.translated.net/',
  9. "wikidata_id": None,
  10. "official_api_documentation": 'https://mymemory.translated.net/doc/spec.php',
  11. "use_official_api": True,
  12. "require_api_key": False,
  13. "results": 'JSON',
  14. }
  15. engine_type = 'online_dictionary'
  16. categories = ['general', 'translate']
  17. api_url = "https://api.mymemory.translated.net"
  18. web_url = "https://mymemory.translated.net"
  19. weight = 100
  20. https_support = True
  21. api_key = ''
  22. def request(query, params): # pylint: disable=unused-argument
  23. args = {"q": params["query"], "langpair": f"{params['from_lang'][1]}|{params['to_lang'][1]}"}
  24. if api_key:
  25. args["key"] = api_key
  26. params['url'] = f"{api_url}/get?{urllib.parse.urlencode(args)}"
  27. return params
  28. def response(resp) -> EngineResults:
  29. results = EngineResults()
  30. data = resp.json()
  31. args = {
  32. "q": resp.search_params["query"],
  33. "lang": resp.search_params.get("searxng_locale", "en"), # ui language
  34. "sl": resp.search_params['from_lang'][1],
  35. "tl": resp.search_params['to_lang'][1],
  36. }
  37. link = f"{web_url}/search.php?{urllib.parse.urlencode(args)}"
  38. text = data['responseData']['translatedText']
  39. examples = [f"{m['segment']} : {m['translation']}" for m in data['matches'] if m['translation'] != text]
  40. item = results.types.Translations.Item(text=text, examples=examples)
  41. results.add(results.types.Translations(translations=[item], url=link))
  42. return results