update_external_bangs.py 3.8 KB

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