online_currency.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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):
  10. name = name.lower().replace('-', ' ').rstrip('s')
  11. name = re.sub(' +', ' ', name)
  12. return unicodedata.normalize('NFKD', name).lower()
  13. def name_to_iso4217(name):
  14. name = normalize_name(name)
  15. currency = CURRENCIES['names'].get(name, [name])
  16. if isinstance(currency, str):
  17. return currency
  18. return currency[-1]
  19. def iso4217_to_name(iso4217, language):
  20. return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
  21. class OnlineCurrencyProcessor(OnlineProcessor):
  22. """Processor class used by ``online_currency`` engines."""
  23. engine_type = 'online_currency'
  24. def get_params(self, search_query, engine_category):
  25. """Returns a set of :ref:`request params <engine request online_currency>`
  26. or ``None`` if search query does not match to :py:obj:`parser_re`."""
  27. params = super().get_params(search_query, engine_category)
  28. if params is None:
  29. return None
  30. m = parser_re.match(search_query.query)
  31. if not m:
  32. return None
  33. amount_str, from_currency, to_currency = m.groups()
  34. try:
  35. amount = float(amount_str)
  36. except ValueError:
  37. return None
  38. from_currency = name_to_iso4217(from_currency.strip())
  39. to_currency = name_to_iso4217(to_currency.strip())
  40. params['amount'] = amount
  41. params['from'] = from_currency
  42. params['to'] = to_currency
  43. params['from_name'] = iso4217_to_name(from_currency, 'en')
  44. params['to_name'] = iso4217_to_name(to_currency, 'en')
  45. return params
  46. def get_default_tests(self):
  47. tests = {}
  48. tests['currency'] = {
  49. 'matrix': {'query': '1337 usd in rmb'},
  50. 'result_container': ['has_answer'],
  51. }
  52. return tests