currency_convert.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import json
  2. import re
  3. import unicodedata
  4. from datetime import datetime
  5. from searx.data import CURRENCIES
  6. categories = []
  7. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
  8. weight = 100
  9. parser_re = re.compile('.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
  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. q = (from_currency + to_currency).upper()
  32. params['url'] = url.format(from_currency, to_currency)
  33. params['amount'] = amount
  34. params['from'] = from_currency
  35. params['to'] = to_currency
  36. params['from_name'] = iso4217_to_name(from_currency, 'en')
  37. params['to_name'] = iso4217_to_name(to_currency, 'en')
  38. return params
  39. def response(resp):
  40. """remove first and last lines to get only json"""
  41. json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
  42. results = []
  43. try:
  44. conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
  45. except:
  46. return results
  47. answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
  48. resp.search_params['amount'],
  49. resp.search_params['from'],
  50. resp.search_params['amount'] * conversion_rate,
  51. resp.search_params['to'],
  52. conversion_rate,
  53. resp.search_params['from_name'],
  54. resp.search_params['to_name'],
  55. )
  56. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'.format(
  57. resp.search_params['from'].upper(), resp.search_params['to'])
  58. results.append({'answer': answer, 'url': url})
  59. return results