online_currency.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. if isinstance(currency, str):
  16. return currency
  17. return currency[0]
  18. def iso4217_to_name(iso4217, language):
  19. global CURRENCIES
  20. return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
  21. class OnlineCurrencyProcessor(OnlineProcessor):
  22. engine_type = 'online_currency'
  23. def get_params(self, search_query, engine_category):
  24. params = super().get_params(search_query, engine_category)
  25. if params is None:
  26. return None
  27. m = parser_re.match(search_query.query)
  28. if not m:
  29. return None
  30. amount_str, from_currency, to_currency = m.groups()
  31. try:
  32. amount = float(amount_str)
  33. except ValueError:
  34. return None
  35. from_currency = name_to_iso4217(from_currency.strip())
  36. to_currency = name_to_iso4217(to_currency.strip())
  37. params['amount'] = amount
  38. params['from'] = from_currency
  39. params['to'] = to_currency
  40. params['from_name'] = iso4217_to_name(from_currency, 'en')
  41. params['to_name'] = iso4217_to_name(to_currency, 'en')
  42. return params
  43. def get_default_tests(self):
  44. tests = {}
  45. tests['currency'] = {
  46. 'matrix': {'query': '1337 usd in rmb'},
  47. 'result_container': ['has_answer'],
  48. }
  49. return tests