update_external_bangs.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. #!/usr/bin/env python
  2. # lint: pylint
  3. # SPDX-License-Identifier: AGPL-3.0-or-later
  4. """Update :origin:`searx/data/external_bangs.json` using the duckduckgo bangs
  5. from :py:obj:`BANGS_URL`.
  6. - :origin:`CI Update data ... <.github/workflows/data-update.yml>`
  7. """
  8. import json
  9. import httpx
  10. from searx.external_bang import LEAF_KEY
  11. from searx.data import data_dir
  12. DATA_FILE = data_dir / 'external_bangs.json'
  13. BANGS_URL = 'https://duckduckgo.com/bang.js'
  14. """JSON file which contains the bangs."""
  15. HTTPS_COLON = 'https:'
  16. HTTP_COLON = 'http:'
  17. def main():
  18. print(f'fetch bangs from {BANGS_URL}')
  19. response = httpx.get(BANGS_URL)
  20. response.raise_for_status()
  21. ddg_bangs = json.loads(response.content.decode())
  22. trie = parse_ddg_bangs(ddg_bangs)
  23. output = {
  24. 'version': 0,
  25. 'trie': trie,
  26. }
  27. with DATA_FILE.open('w', encoding="utf8") as f:
  28. json.dump(output, f, indent=4, sort_keys=True, ensure_ascii=False)
  29. def merge_when_no_leaf(node):
  30. """Minimize the number of nodes
  31. ``A -> B -> C``
  32. - ``B`` is child of ``A``
  33. - ``C`` is child of ``B``
  34. If there are no ``C`` equals to ``<LEAF_KEY>``, then each ``C`` are merged
  35. into ``A``. For example (5 nodes)::
  36. d -> d -> g -> <LEAF_KEY> (ddg)
  37. -> i -> g -> <LEAF_KEY> (dig)
  38. becomes (3 nodes)::
  39. d -> dg -> <LEAF_KEY>
  40. -> ig -> <LEAF_KEY>
  41. """
  42. restart = False
  43. if not isinstance(node, dict):
  44. return
  45. # create a copy of the keys so node can be modified
  46. keys = list(node.keys())
  47. for key in keys:
  48. if key == LEAF_KEY:
  49. continue
  50. value = node[key]
  51. value_keys = list(value.keys())
  52. if LEAF_KEY not in value_keys:
  53. for value_key in value_keys:
  54. node[key + value_key] = value[value_key]
  55. merge_when_no_leaf(node[key + value_key])
  56. del node[key]
  57. restart = True
  58. else:
  59. merge_when_no_leaf(value)
  60. if restart:
  61. merge_when_no_leaf(node)
  62. def optimize_leaf(parent, parent_key, node):
  63. if not isinstance(node, dict):
  64. return
  65. if len(node) == 1 and LEAF_KEY in node and parent is not None:
  66. parent[parent_key] = node[LEAF_KEY]
  67. else:
  68. for key, value in node.items():
  69. optimize_leaf(node, key, value)
  70. def parse_ddg_bangs(ddg_bangs):
  71. bang_trie = {}
  72. bang_urls = {}
  73. for bang_definition in ddg_bangs:
  74. # bang_list
  75. bang_url = bang_definition['u']
  76. if '{{{s}}}' not in bang_url:
  77. # ignore invalid bang
  78. continue
  79. bang_url = bang_url.replace('{{{s}}}', chr(2))
  80. # only for the https protocol: "https://example.com" becomes "//example.com"
  81. if bang_url.startswith(HTTPS_COLON + '//'):
  82. bang_url = bang_url[len(HTTPS_COLON) :]
  83. #
  84. if bang_url.startswith(HTTP_COLON + '//') and bang_url[len(HTTP_COLON) :] in bang_urls:
  85. # if the bang_url uses the http:// protocol, and the same URL exists in https://
  86. # then reuse the https:// bang definition. (written //example.com)
  87. bang_def_output = bang_urls[bang_url[len(HTTP_COLON) :]]
  88. else:
  89. # normal use case : new http:// URL or https:// URL (without "https:", see above)
  90. bang_rank = str(bang_definition['r'])
  91. bang_def_output = bang_url + chr(1) + bang_rank
  92. bang_def_output = bang_urls.setdefault(bang_url, bang_def_output)
  93. bang_urls[bang_url] = bang_def_output
  94. # bang name
  95. bang = bang_definition['t']
  96. # bang_trie
  97. t = bang_trie
  98. for bang_letter in bang:
  99. t = t.setdefault(bang_letter, {})
  100. t = t.setdefault(LEAF_KEY, bang_def_output)
  101. # optimize the trie
  102. merge_when_no_leaf(bang_trie)
  103. optimize_leaf(None, None, bang_trie)
  104. return bang_trie
  105. if __name__ == '__main__':
  106. main()