online_currency.py 2.0 KB

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