online_currency.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. params = super().get_params(search_query, engine_category)
  27. if params is None:
  28. return None
  29. m = parser_re.match(search_query.query)
  30. if not m:
  31. return None
  32. amount_str, from_currency, to_currency = m.groups()
  33. try:
  34. amount = float(amount_str)
  35. except ValueError:
  36. return None
  37. from_currency = name_to_iso4217(from_currency.strip())
  38. to_currency = name_to_iso4217(to_currency.strip())
  39. params['amount'] = amount
  40. params['from'] = from_currency
  41. params['to'] = to_currency
  42. params['from_name'] = iso4217_to_name(from_currency, 'en')
  43. params['to_name'] = iso4217_to_name(to_currency, 'en')
  44. return params
  45. def get_default_tests(self):
  46. tests = {}
  47. tests['currency'] = {
  48. 'matrix': {'query': '1337 usd in rmb'},
  49. 'result_container': ['has_answer'],
  50. }
  51. return tests