lingva.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Lingva (alternative Google Translate frontend)"""
  3. from searx.result_types import EngineResults
  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. def request(_query, params):
  16. params['url'] = f"{url}/api/v1/{params['from_lang'][1]}/{params['to_lang'][1]}/{params['query']}"
  17. return params
  18. def response(resp) -> EngineResults:
  19. results = EngineResults()
  20. result = resp.json()
  21. info = result["info"]
  22. from_to_prefix = "%s-%s " % (resp.search_params['from_lang'][1], resp.search_params['to_lang'][1])
  23. if "typo" in info:
  24. results.append({"suggestion": from_to_prefix + info["typo"]})
  25. if 'definitions' in info: # pylint: disable=too-many-nested-blocks
  26. for definition in info['definitions']:
  27. for item in definition.get('list', []):
  28. for synonym in item.get('synonyms', []):
  29. results.append({"suggestion": from_to_prefix + synonym})
  30. data = []
  31. for definition in info['definitions']:
  32. for translation in definition['list']:
  33. data.append(
  34. results.types.Translations.Item(
  35. text=result['translation'],
  36. definitions=[translation['definition']] if translation['definition'] else [],
  37. examples=[translation['example']] if translation['example'] else [],
  38. synonyms=translation['synonyms'],
  39. )
  40. )
  41. for translation in info["extraTranslations"]:
  42. for word in translation["list"]:
  43. data.append(
  44. results.types.Translations.Item(
  45. text=word['word'],
  46. definitions=word['meanings'],
  47. )
  48. )
  49. if not data and result['translation']:
  50. data.append(results.types.Translations.Item(text=result['translation']))
  51. params = resp.search_params
  52. results.add(
  53. results.types.Translations(
  54. translations=data,
  55. url=f"{url}/{params['from_lang'][1]}/{params['to_lang'][1]}/{params['query']}",
  56. )
  57. )
  58. return results