update_external_bangs.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. #!/usr/bin/env python
  2. # lint: pylint
  3. """
  4. Update searx/data/external_bangs.json using the duckduckgo bangs.
  5. https://duckduckgo.com/newbang loads
  6. * a javascript which provides the bang version ( https://duckduckgo.com/bv1.js )
  7. * a JSON file which contains the bangs ( https://duckduckgo.com/bang.v260.js for example )
  8. This script loads the javascript, then the bangs.
  9. The javascript URL may change in the future ( for example https://duckduckgo.com/bv2.js ),
  10. but most probably it will requires to update RE_BANG_VERSION
  11. """
  12. # pylint: disable=C0116
  13. import json
  14. import re
  15. from os.path import join
  16. import httpx
  17. from searx import searx_dir # pylint: disable=E0401 C0413
  18. # from https://duckduckgo.com/newbang
  19. URL_BV1 = 'https://duckduckgo.com/bv1.js'
  20. RE_BANG_VERSION = re.compile(r'\/bang\.v([0-9]+)\.js')
  21. HTTPS_COLON = 'https:'
  22. HTTP_COLON = 'http:'
  23. def get_bang_url():
  24. response = httpx.get(URL_BV1)
  25. response.raise_for_status()
  26. r = RE_BANG_VERSION.findall(response.text)
  27. return f'https://duckduckgo.com/bang.v{r[0]}.js', r[0]
  28. def fetch_ddg_bangs(url):
  29. response = httpx.get(url)
  30. response.raise_for_status()
  31. return json.loads(response.content.decode())
  32. def merge_when_no_leaf(node):
  33. """Minimize the number of nodes
  34. A -> B -> C
  35. B is child of A
  36. C is child of B
  37. If there are no C equals to '*', then each C are merged into A
  38. For example:
  39. d -> d -> g -> * (ddg*)
  40. -> i -> g -> * (dig*)
  41. becomes
  42. d -> dg -> *
  43. -> ig -> *
  44. """
  45. restart = False
  46. if not isinstance(node, dict):
  47. return
  48. # create a copy of the keys so node can be modified
  49. keys = list(node.keys())
  50. for key in keys:
  51. if key == '*':
  52. continue
  53. value = node[key]
  54. value_keys = list(value.keys())
  55. if '*' not in value_keys:
  56. for value_key in value_keys:
  57. node[key + value_key] = value[value_key]
  58. merge_when_no_leaf(node[key + value_key])
  59. del node[key]
  60. restart = True
  61. else:
  62. merge_when_no_leaf(value)
  63. if restart:
  64. merge_when_no_leaf(node)
  65. def optimize_leaf(parent, parent_key, node):
  66. if not isinstance(node, dict):
  67. return
  68. if len(node) == 1 and '*' in node and parent is not None:
  69. parent[parent_key] = node['*']
  70. else:
  71. for key, value in node.items():
  72. optimize_leaf(node, key, value)
  73. def parse_ddg_bangs(ddg_bangs):
  74. bang_trie = {}
  75. bang_urls = {}
  76. for bang_definition in ddg_bangs:
  77. # bang_list
  78. bang_url = bang_definition['u']
  79. if '{{{s}}}' not in bang_url:
  80. # ignore invalid bang
  81. continue
  82. bang_url = bang_url.replace('{{{s}}}', chr(2))
  83. # only for the https protocol: "https://example.com" becomes "//example.com"
  84. if bang_url.startswith(HTTPS_COLON + '//'):
  85. bang_url = bang_url[len(HTTPS_COLON):]
  86. #
  87. if bang_url.startswith(HTTP_COLON + '//') and bang_url[len(HTTP_COLON):] in bang_urls:
  88. # if the bang_url uses the http:// protocol, and the same URL exists in https://
  89. # then reuse the https:// bang definition. (written //example.com)
  90. bang_def_output = bang_urls[bang_url[len(HTTP_COLON):]]
  91. else:
  92. # normal use case : new http:// URL or https:// URL (without "https:", see above)
  93. bang_rank = str(bang_definition['r'])
  94. bang_def_output = bang_url + chr(1) + bang_rank
  95. bang_def_output = bang_urls.setdefault(bang_url, bang_def_output)
  96. bang_urls[bang_url] = bang_def_output
  97. # bang name
  98. bang = bang_definition['t']
  99. # bang_trie
  100. t = bang_trie
  101. for bang_letter in bang:
  102. t = t.setdefault(bang_letter, {})
  103. t = t.setdefault('*', bang_def_output)
  104. # optimize the trie
  105. merge_when_no_leaf(bang_trie)
  106. optimize_leaf(None, None, bang_trie)
  107. return bang_trie
  108. def get_bangs_filename():
  109. return join(join(searx_dir, "data"), "external_bangs.json")
  110. if __name__ == '__main__':
  111. bangs_url, bangs_version = get_bang_url()
  112. print(f'fetch bangs from {bangs_url}')
  113. output = {
  114. 'version': bangs_version,
  115. 'trie': parse_ddg_bangs(fetch_ddg_bangs(bangs_url))
  116. }
  117. with open(get_bangs_filename(), 'w') as fp:
  118. json.dump(output, fp, ensure_ascii=False, indent=4)