currency_convert.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. def normalize_name(name):
  10. name = name.lower().replace('-', ' ').rstrip('s')
  11. name = re.sub(' +', ' ', name)
  12. return unicodedata.normalize('NFKD', name).lower()
  13. def name_to_iso4217(name):
  14. global CURRENCIES
  15. name = normalize_name(name)
  16. currency = CURRENCIES['names'].get(name, [name])
  17. return currency[0]
  18. def iso4217_to_name(iso4217, language):
  19. global CURRENCIES
  20. return CURRENCIES['iso4217'].get(iso4217, {}).get(language, iso4217)
  21. def request(query, params):
  22. m = parser_re.match(query)
  23. if not m:
  24. # wrong query
  25. return params
  26. amount, from_currency, to_currency = m.groups()
  27. amount = float(amount)
  28. from_currency = name_to_iso4217(from_currency.strip())
  29. to_currency = name_to_iso4217(to_currency.strip())
  30. q = (from_currency + to_currency).upper()
  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