currency_convert.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import json
  2. import re
  3. import unicodedata
  4. from searx.data import CURRENCIES # NOQA
  5. categories = []
  6. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
  7. weight = 100
  8. parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
  9. https_support = True
  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. global CURRENCIES
  16. name = normalize_name(name)
  17. currency = CURRENCIES['names'].get(name, [name])
  18. return currency[0]
  19. def iso4217_to_name(iso4217, language):
  20. global CURRENCIES
  21. return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
  22. def request(query, params):
  23. m = parser_re.match(query)
  24. if not m:
  25. # wrong query
  26. return params
  27. amount, from_currency, to_currency = m.groups()
  28. amount = float(amount)
  29. from_currency = name_to_iso4217(from_currency.strip())
  30. to_currency = name_to_iso4217(to_currency.strip())
  31. params['url'] = url.format(from_currency, to_currency)
  32. params['amount'] = amount
  33. params['from'] = from_currency
  34. params['to'] = to_currency
  35. params['from_name'] = iso4217_to_name(from_currency, 'en')
  36. params['to_name'] = iso4217_to_name(to_currency, 'en')
  37. return params
  38. def response(resp):
  39. """remove first and last lines to get only json"""
  40. json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
  41. results = []
  42. try:
  43. conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
  44. except:
  45. return results
  46. answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
  47. resp.search_params['amount'],
  48. resp.search_params['from'],
  49. resp.search_params['amount'] * conversion_rate,
  50. resp.search_params['to'],
  51. conversion_rate,
  52. resp.search_params['from_name'],
  53. resp.search_params['to_name'],
  54. )
  55. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'.format(
  56. resp.search_params['from'].upper(), resp.search_params['to'])
  57. results.append({'answer': answer, 'url': url})
  58. return results