online_currency.py 2.1 KB

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