update_external_bangs.py 3.9 KB

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