lingva.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Lingva (alternative Google Translate frontend)"""
  3. from json import loads
  4. about = {
  5. "website": 'https://lingva.ml',
  6. "wikidata_id": None,
  7. "official_api_documentation": 'https://github.com/thedaviddelta/lingva-translate#public-apis',
  8. "use_official_api": True,
  9. "require_api_key": False,
  10. "results": 'JSON',
  11. }
  12. engine_type = 'online_dictionary'
  13. categories = ['general', 'translate']
  14. url = "https://lingva.thedaviddelta.com"
  15. search_url = "{url}/api/v1/{from_lang}/{to_lang}/{query}"
  16. def request(_query, params):
  17. params['url'] = search_url.format(
  18. url=url, from_lang=params['from_lang'][1], to_lang=params['to_lang'][1], query=params['query']
  19. )
  20. return params
  21. def response(resp):
  22. results = []
  23. result = loads(resp.text)
  24. info = result["info"]
  25. from_to_prefix = "%s-%s " % (resp.search_params['from_lang'][1], resp.search_params['to_lang'][1])
  26. if "typo" in info:
  27. results.append({"suggestion": from_to_prefix + info["typo"]})
  28. if 'definitions' in info: # pylint: disable=too-many-nested-blocks
  29. for definition in info['definitions']:
  30. if 'list' in definition:
  31. for item in definition['list']:
  32. if 'synonyms' in item:
  33. for synonym in item['synonyms']:
  34. results.append({"suggestion": from_to_prefix + synonym})
  35. infobox = ""
  36. for translation in info["extraTranslations"]:
  37. for word in translation["list"]:
  38. infobox += f"<dl><dt>{word['word']}</dt>"
  39. for meaning in word["meanings"]:
  40. infobox += f"<dd>{meaning}</dd>"
  41. infobox += "</dl>"
  42. results.append(
  43. {
  44. 'infobox': result["translation"],
  45. 'content': infobox,
  46. }
  47. )
  48. return results