logo

searx

My custom branche(s) on searx, a meta-search engine git clone https://hacktivis.me/git/searx.git

currency_convert.py (2549B)


  1. import json
  2. import re
  3. import os
  4. import sys
  5. import unicodedata
  6. from io import open
  7. from datetime import datetime
  8. if sys.version_info[0] == 3:
  9. unicode = str
  10. categories = []
  11. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'
  12. weight = 100
  13. parser_re = re.compile(b'.*?(\\d+(?:\\.\\d+)?) ([^.0-9]+) (?:in|to) ([^.0-9]+)', re.I)
  14. db = 1
  15. def normalize_name(name):
  16. name = name.decode('utf-8').lower().replace('-', ' ').rstrip('s')
  17. name = re.sub(' +', ' ', name)
  18. return unicodedata.normalize('NFKD', name).lower()
  19. def name_to_iso4217(name):
  20. global db
  21. name = normalize_name(name)
  22. currencies = db['names'].get(name, [name])
  23. return currencies[0]
  24. def iso4217_to_name(iso4217, language):
  25. global db
  26. return db['iso4217'].get(iso4217, {}).get(language, iso4217)
  27. def request(query, params):
  28. m = parser_re.match(query)
  29. if not m:
  30. # wrong query
  31. return params
  32. amount, from_currency, to_currency = m.groups()
  33. amount = float(amount)
  34. from_currency = name_to_iso4217(from_currency.strip())
  35. to_currency = name_to_iso4217(to_currency.strip())
  36. q = (from_currency + to_currency).upper()
  37. params['url'] = url.format(from_currency, to_currency)
  38. params['amount'] = amount
  39. params['from'] = from_currency
  40. params['to'] = to_currency
  41. params['from_name'] = iso4217_to_name(from_currency, 'en')
  42. params['to_name'] = iso4217_to_name(to_currency, 'en')
  43. return params
  44. def response(resp):
  45. """remove first and last lines to get only json"""
  46. json_resp = resp.text[resp.text.find('\n') + 1:resp.text.rfind('\n') - 2]
  47. results = []
  48. try:
  49. conversion_rate = float(json.loads(json_resp)['conversion']['converted-amount'])
  50. except:
  51. return results
  52. answer = '{0} {1} = {2} {3}, 1 {1} ({5}) = {4} {3} ({6})'.format(
  53. resp.search_params['amount'],
  54. resp.search_params['from'],
  55. resp.search_params['amount'] * conversion_rate,
  56. resp.search_params['to'],
  57. conversion_rate,
  58. resp.search_params['from_name'],
  59. resp.search_params['to_name'],
  60. )
  61. url = 'https://duckduckgo.com/js/spice/currency/1/{0}/{1}'.format(
  62. resp.search_params['from'].upper(), resp.search_params['to'])
  63. results.append({'answer': answer, 'url': url})
  64. return results
  65. def load():
  66. global db
  67. current_dir = os.path.dirname(os.path.realpath(__file__))
  68. json_data = open(current_dir + "/../data/currencies.json", 'r', encoding='utf-8').read()
  69. db = json.loads(json_data)
  70. load()