online_currency.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Processors for engine-type: ``online_currency``
  3. """
  4. import unicodedata
  5. import re
  6. from searx.data import CURRENCIES
  7. from .online import OnlineProcessor
  8. parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
  9. def normalize_name(name: str):
  10. name = name.strip()
  11. name = name.lower().replace('-', ' ').rstrip('s')
  12. name = re.sub(' +', ' ', name)
  13. return unicodedata.normalize('NFKD', name).lower()
  14. class OnlineCurrencyProcessor(OnlineProcessor):
  15. """Processor class used by ``online_currency`` engines."""
  16. engine_type = 'online_currency'
  17. def get_params(self, search_query, engine_category):
  18. """Returns a set of :ref:`request params <engine request online_currency>`
  19. or ``None`` if search query does not match to :py:obj:`parser_re`."""
  20. params = super().get_params(search_query, engine_category)
  21. if params is None:
  22. return None
  23. m = parser_re.match(search_query.query)
  24. if not m:
  25. return None
  26. amount_str, from_currency, to_currency = m.groups()
  27. try:
  28. amount = float(amount_str)
  29. except ValueError:
  30. return None
  31. from_currency = CURRENCIES.name_to_iso4217(normalize_name(from_currency))
  32. to_currency = CURRENCIES.name_to_iso4217(normalize_name(to_currency))
  33. params['amount'] = amount
  34. params['from'] = from_currency
  35. params['to'] = to_currency
  36. params['from_name'] = CURRENCIES.iso4217_to_name(from_currency, "en")
  37. params['to_name'] = CURRENCIES.iso4217_to_name(to_currency, "en")
  38. return params
  39. def get_default_tests(self):
  40. tests = {}
  41. tests['currency'] = {
  42. 'matrix': {'query': '1337 usd in rmb'},
  43. 'result_container': ['has_answer'],
  44. }
  45. return tests