autocomplete.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This module implements functions needed for the autocompleter.
  3. """
  4. # pylint: disable=use-dict-literal
  5. import json
  6. import html
  7. from urllib.parse import urlencode, quote_plus
  8. import lxml.etree
  9. import lxml.html
  10. from httpx import HTTPError
  11. from searx.extended_types import SXNG_Response
  12. from searx import settings
  13. from searx.engines import (
  14. engines,
  15. google,
  16. )
  17. from searx.network import get as http_get, post as http_post
  18. from searx.exceptions import SearxEngineResponseException
  19. def update_kwargs(**kwargs):
  20. if 'timeout' not in kwargs:
  21. kwargs['timeout'] = settings['outgoing']['request_timeout']
  22. kwargs['raise_for_httperror'] = True
  23. def get(*args, **kwargs) -> SXNG_Response:
  24. update_kwargs(**kwargs)
  25. return http_get(*args, **kwargs)
  26. def post(*args, **kwargs) -> SXNG_Response:
  27. update_kwargs(**kwargs)
  28. return http_post(*args, **kwargs)
  29. def baidu(query, _lang):
  30. # baidu search autocompleter
  31. base_url = "https://www.baidu.com/sugrec?"
  32. response = get(base_url + urlencode({'ie': 'utf-8', 'json': 1, 'prod': 'pc', 'wd': query}))
  33. results = []
  34. if response.ok:
  35. data = response.json()
  36. if 'g' in data:
  37. for item in data['g']:
  38. results.append(item['q'])
  39. return results
  40. def brave(query, _lang):
  41. # brave search autocompleter
  42. url = 'https://search.brave.com/api/suggest?'
  43. url += urlencode({'q': query})
  44. country = 'all'
  45. # if lang in _brave:
  46. # country = lang
  47. kwargs = {'cookies': {'country': country}}
  48. resp = get(url, **kwargs)
  49. results = []
  50. if resp.ok:
  51. data = resp.json()
  52. for item in data[1]:
  53. results.append(item)
  54. return results
  55. def dbpedia(query, _lang):
  56. # dbpedia autocompleter, no HTTPS
  57. autocomplete_url = 'https://lookup.dbpedia.org/api/search.asmx/KeywordSearch?'
  58. response = get(autocomplete_url + urlencode(dict(QueryString=query)))
  59. results = []
  60. if response.ok:
  61. dom = lxml.etree.fromstring(response.content)
  62. results = dom.xpath('//Result/Label//text()')
  63. return results
  64. def duckduckgo(query, sxng_locale):
  65. """Autocomplete from DuckDuckGo. Supports DuckDuckGo's languages"""
  66. traits = engines['duckduckgo'].traits
  67. args = {
  68. 'q': query,
  69. 'kl': traits.get_region(sxng_locale, traits.all_locale),
  70. }
  71. url = 'https://duckduckgo.com/ac/?type=list&' + urlencode(args)
  72. resp = get(url)
  73. ret_val = []
  74. if resp.ok:
  75. j = resp.json()
  76. if len(j) > 1:
  77. ret_val = j[1]
  78. return ret_val
  79. def google_complete(query, sxng_locale):
  80. """Autocomplete from Google. Supports Google's languages and subdomains
  81. (:py:obj:`searx.engines.google.get_google_info`) by using the async REST
  82. API::
  83. https://{subdomain}/complete/search?{args}
  84. """
  85. google_info = google.get_google_info({'searxng_locale': sxng_locale}, engines['google'].traits)
  86. url = 'https://{subdomain}/complete/search?{args}'
  87. args = urlencode(
  88. {
  89. 'q': query,
  90. 'client': 'gws-wiz',
  91. 'hl': google_info['params']['hl'],
  92. }
  93. )
  94. results = []
  95. resp = get(url.format(subdomain=google_info['subdomain'], args=args))
  96. if resp and resp.ok:
  97. json_txt = resp.text[resp.text.find('[') : resp.text.find(']', -3) + 1]
  98. data = json.loads(json_txt)
  99. for item in data[0]:
  100. results.append(lxml.html.fromstring(item[0]).text_content())
  101. return results
  102. def mwmbl(query, _lang):
  103. """Autocomplete from Mwmbl_."""
  104. # mwmbl autocompleter
  105. url = 'https://api.mwmbl.org/search/complete?{query}'
  106. results = get(url.format(query=urlencode({'q': query}))).json()[1]
  107. # results starting with `go:` are direct urls and not useful for auto completion
  108. return [result for result in results if not result.startswith("go: ") and not result.startswith("search: ")]
  109. def seznam(query, _lang):
  110. # seznam search autocompleter
  111. url = 'https://suggest.seznam.cz/fulltext/cs?{query}'
  112. resp = get(
  113. url.format(
  114. query=urlencode(
  115. {'phrase': query, 'cursorPosition': len(query), 'format': 'json-2', 'highlight': '1', 'count': '6'}
  116. )
  117. )
  118. )
  119. if not resp.ok:
  120. return []
  121. data = resp.json()
  122. return [
  123. ''.join([part.get('text', '') for part in item.get('text', [])])
  124. for item in data.get('result', [])
  125. if item.get('itemType', None) == 'ItemType.TEXT'
  126. ]
  127. def stract(query, _lang):
  128. # stract autocompleter (beta)
  129. url = f"https://stract.com/beta/api/autosuggest?q={quote_plus(query)}"
  130. resp = post(url)
  131. if not resp.ok:
  132. return []
  133. return [html.unescape(suggestion['raw']) for suggestion in resp.json()]
  134. def swisscows(query, _lang):
  135. # swisscows autocompleter
  136. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  137. resp = json.loads(get(url.format(query=urlencode({'query': query}))).text)
  138. return resp
  139. def qwant(query, sxng_locale):
  140. """Autocomplete from Qwant. Supports Qwant's regions."""
  141. results = []
  142. locale = engines['qwant'].traits.get_region(sxng_locale, 'en_US')
  143. url = 'https://api.qwant.com/v3/suggest?{query}'
  144. resp = get(url.format(query=urlencode({'q': query, 'locale': locale, 'version': '2'})))
  145. if resp.ok:
  146. data = resp.json()
  147. if data['status'] == 'success':
  148. for item in data['data']['items']:
  149. results.append(item['value'])
  150. return results
  151. def wikipedia(query, sxng_locale):
  152. """Autocomplete from Wikipedia. Supports Wikipedia's languages (aka netloc)."""
  153. results = []
  154. eng_traits = engines['wikipedia'].traits
  155. wiki_lang = eng_traits.get_language(sxng_locale, 'en')
  156. wiki_netloc = eng_traits.custom['wiki_netloc'].get(wiki_lang, 'en.wikipedia.org') # type: ignore
  157. url = 'https://{wiki_netloc}/w/api.php?{args}'
  158. args = urlencode(
  159. {
  160. 'action': 'opensearch',
  161. 'format': 'json',
  162. 'formatversion': '2',
  163. 'search': query,
  164. 'namespace': '0',
  165. 'limit': '10',
  166. }
  167. )
  168. resp = get(url.format(args=args, wiki_netloc=wiki_netloc))
  169. if resp.ok:
  170. data = resp.json()
  171. if len(data) > 1:
  172. results = data[1]
  173. return results
  174. def yandex(query, _lang):
  175. # yandex autocompleter
  176. url = "https://suggest.yandex.com/suggest-ff.cgi?{0}"
  177. resp = json.loads(get(url.format(urlencode(dict(part=query)))).text)
  178. if len(resp) > 1:
  179. return resp[1]
  180. return []
  181. backends = {
  182. 'baidu': baidu,
  183. 'brave': brave,
  184. 'dbpedia': dbpedia,
  185. 'duckduckgo': duckduckgo,
  186. 'google': google_complete,
  187. 'mwmbl': mwmbl,
  188. 'qwant': qwant,
  189. 'seznam': seznam,
  190. 'stract': stract,
  191. 'swisscows': swisscows,
  192. 'wikipedia': wikipedia,
  193. 'yandex': yandex,
  194. }
  195. def search_autocomplete(backend_name, query, sxng_locale):
  196. backend = backends.get(backend_name)
  197. if backend is None:
  198. return []
  199. try:
  200. return backend(query, sxng_locale)
  201. except (HTTPError, SearxEngineResponseException):
  202. return []