online_currency.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 initialize(self):
  18. CURRENCIES.init()
  19. super().initialize()
  20. def get_params(self, search_query, engine_category):
  21. """Returns a set of :ref:`request params <engine request online_currency>`
  22. or ``None`` if search query does not match to :py:obj:`parser_re`."""
  23. params = super().get_params(search_query, engine_category)
  24. if params is None:
  25. return None
  26. m = parser_re.match(search_query.query)
  27. if not m:
  28. return None
  29. amount_str, from_currency, to_currency = m.groups()
  30. try:
  31. amount = float(amount_str)
  32. except ValueError:
  33. return None
  34. from_currency = CURRENCIES.name_to_iso4217(normalize_name(from_currency))
  35. to_currency = CURRENCIES.name_to_iso4217(normalize_name(to_currency))
  36. params['amount'] = amount
  37. params['from'] = from_currency
  38. params['to'] = to_currency
  39. params['from_name'] = CURRENCIES.iso4217_to_name(from_currency, "en")
  40. params['to_name'] = CURRENCIES.iso4217_to_name(to_currency, "en")
  41. return params
  42. def get_default_tests(self):
  43. tests = {}
  44. tests['currency'] = {
  45. 'matrix': {'query': '1337 usd in rmb'},
  46. 'result_container': ['has_answer'],
  47. }
  48. return tests