online_currency.py 1.8 KB

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