autocomplete.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. from searx.utils import extr
  20. def update_kwargs(**kwargs):
  21. if 'timeout' not in kwargs:
  22. kwargs['timeout'] = settings['outgoing']['request_timeout']
  23. kwargs['raise_for_httperror'] = True
  24. def get(*args, **kwargs) -> SXNG_Response:
  25. update_kwargs(**kwargs)
  26. return http_get(*args, **kwargs)
  27. def post(*args, **kwargs) -> SXNG_Response:
  28. update_kwargs(**kwargs)
  29. return http_post(*args, **kwargs)
  30. def baidu(query, _lang):
  31. # baidu search autocompleter
  32. base_url = "https://www.baidu.com/sugrec?"
  33. response = get(base_url + urlencode({'ie': 'utf-8', 'json': 1, 'prod': 'pc', 'wd': query}))
  34. results = []
  35. if response.ok:
  36. data = response.json()
  37. if 'g' in data:
  38. for item in data['g']:
  39. results.append(item['q'])
  40. return results
  41. def brave(query, _lang):
  42. # brave search autocompleter
  43. url = 'https://search.brave.com/api/suggest?'
  44. url += urlencode({'q': query})
  45. country = 'all'
  46. # if lang in _brave:
  47. # country = lang
  48. kwargs = {'cookies': {'country': country}}
  49. resp = get(url, **kwargs)
  50. results = []
  51. if resp.ok:
  52. data = resp.json()
  53. for item in data[1]:
  54. results.append(item)
  55. return results
  56. def dbpedia(query, _lang):
  57. # dbpedia autocompleter, no HTTPS
  58. autocomplete_url = 'https://lookup.dbpedia.org/api/search.asmx/KeywordSearch?'
  59. response = get(autocomplete_url + urlencode(dict(QueryString=query)))
  60. results = []
  61. if response.ok:
  62. dom = lxml.etree.fromstring(response.content)
  63. results = dom.xpath('//Result/Label//text()')
  64. return results
  65. def duckduckgo(query, sxng_locale):
  66. """Autocomplete from DuckDuckGo. Supports DuckDuckGo's languages"""
  67. traits = engines['duckduckgo'].traits
  68. args = {
  69. 'q': query,
  70. 'kl': traits.get_region(sxng_locale, traits.all_locale),
  71. }
  72. url = 'https://duckduckgo.com/ac/?type=list&' + urlencode(args)
  73. resp = get(url)
  74. ret_val = []
  75. if resp.ok:
  76. j = resp.json()
  77. if len(j) > 1:
  78. ret_val = j[1]
  79. return ret_val
  80. def google_complete(query, sxng_locale):
  81. """Autocomplete from Google. Supports Google's languages and subdomains
  82. (:py:obj:`searx.engines.google.get_google_info`) by using the async REST
  83. API::
  84. https://{subdomain}/complete/search?{args}
  85. """
  86. google_info = google.get_google_info({'searxng_locale': sxng_locale}, engines['google'].traits)
  87. url = 'https://{subdomain}/complete/search?{args}'
  88. args = urlencode(
  89. {
  90. 'q': query,
  91. 'client': 'gws-wiz',
  92. 'hl': google_info['params']['hl'],
  93. }
  94. )
  95. results = []
  96. resp = get(url.format(subdomain=google_info['subdomain'], args=args))
  97. if resp and resp.ok:
  98. json_txt = resp.text[resp.text.find('[') : resp.text.find(']', -3) + 1]
  99. data = json.loads(json_txt)
  100. for item in data[0]:
  101. results.append(lxml.html.fromstring(item[0]).text_content())
  102. return results
  103. def mwmbl(query, _lang):
  104. """Autocomplete from Mwmbl_."""
  105. # mwmbl autocompleter
  106. url = 'https://api.mwmbl.org/search/complete?{query}'
  107. results = get(url.format(query=urlencode({'q': query}))).json()[1]
  108. # results starting with `go:` are direct urls and not useful for auto completion
  109. return [result for result in results if not result.startswith("go: ") and not result.startswith("search: ")]
  110. def naver(query, _lang):
  111. # Naver search autocompleter
  112. url = f"https://ac.search.naver.com/nx/ac?{urlencode({'q': query, 'r_format': 'json', 'st': 0})}"
  113. response = get(url)
  114. results = []
  115. if response.ok:
  116. data = response.json()
  117. if data.get('items'):
  118. for item in data['items'][0]:
  119. results.append(item[0])
  120. return results
  121. def qihu360search(query, _lang):
  122. # 360Search search autocompleter
  123. url = f"https://sug.so.360.cn/suggest?{urlencode({'format': 'json', 'word': query})}"
  124. response = get(url)
  125. results = []
  126. if response.ok:
  127. data = response.json()
  128. if 'result' in data:
  129. for item in data['result']:
  130. results.append(item['word'])
  131. return results
  132. def quark(query, _lang):
  133. # Quark search autocompleter
  134. url = f"https://sugs.m.sm.cn/web?{urlencode({'q': query})}"
  135. response = get(url)
  136. results = []
  137. if response.ok:
  138. data = response.json()
  139. for item in data.get('r', []):
  140. results.append(item['w'])
  141. return results
  142. def seznam(query, _lang):
  143. # seznam search autocompleter
  144. url = 'https://suggest.seznam.cz/fulltext/cs?{query}'
  145. resp = get(
  146. url.format(
  147. query=urlencode(
  148. {'phrase': query, 'cursorPosition': len(query), 'format': 'json-2', 'highlight': '1', 'count': '6'}
  149. )
  150. )
  151. )
  152. if not resp.ok:
  153. return []
  154. data = resp.json()
  155. return [
  156. ''.join([part.get('text', '') for part in item.get('text', [])])
  157. for item in data.get('result', [])
  158. if item.get('itemType', None) == 'ItemType.TEXT'
  159. ]
  160. def sogou(query, _lang):
  161. # Sogou search autocompleter
  162. base_url = "https://sor.html5.qq.com/api/getsug?"
  163. response = get(base_url + urlencode({'m': 'searxng', 'key': query}))
  164. if response.ok:
  165. raw_json = extr(response.text, "[", "]", default="")
  166. try:
  167. data = json.loads(f"[{raw_json}]]")
  168. return data[1]
  169. except json.JSONDecodeError:
  170. return []
  171. return []
  172. def stract(query, _lang):
  173. # stract autocompleter (beta)
  174. url = f"https://stract.com/beta/api/autosuggest?q={quote_plus(query)}"
  175. resp = post(url)
  176. if not resp.ok:
  177. return []
  178. return [html.unescape(suggestion['raw']) for suggestion in resp.json()]
  179. def swisscows(query, _lang):
  180. # swisscows autocompleter
  181. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  182. resp = json.loads(get(url.format(query=urlencode({'query': query}))).text)
  183. return resp
  184. def qwant(query, sxng_locale):
  185. """Autocomplete from Qwant. Supports Qwant's regions."""
  186. results = []
  187. locale = engines['qwant'].traits.get_region(sxng_locale, 'en_US')
  188. url = 'https://api.qwant.com/v3/suggest?{query}'
  189. resp = get(url.format(query=urlencode({'q': query, 'locale': locale, 'version': '2'})))
  190. if resp.ok:
  191. data = resp.json()
  192. if data['status'] == 'success':
  193. for item in data['data']['items']:
  194. results.append(item['value'])
  195. return results
  196. def wikipedia(query, sxng_locale):
  197. """Autocomplete from Wikipedia. Supports Wikipedia's languages (aka netloc)."""
  198. results = []
  199. eng_traits = engines['wikipedia'].traits
  200. wiki_lang = eng_traits.get_language(sxng_locale, 'en')
  201. wiki_netloc = eng_traits.custom['wiki_netloc'].get(wiki_lang, 'en.wikipedia.org') # type: ignore
  202. url = 'https://{wiki_netloc}/w/api.php?{args}'
  203. args = urlencode(
  204. {
  205. 'action': 'opensearch',
  206. 'format': 'json',
  207. 'formatversion': '2',
  208. 'search': query,
  209. 'namespace': '0',
  210. 'limit': '10',
  211. }
  212. )
  213. resp = get(url.format(args=args, wiki_netloc=wiki_netloc))
  214. if resp.ok:
  215. data = resp.json()
  216. if len(data) > 1:
  217. results = data[1]
  218. return results
  219. def yandex(query, _lang):
  220. # yandex autocompleter
  221. url = "https://suggest.yandex.com/suggest-ff.cgi?{0}"
  222. resp = json.loads(get(url.format(urlencode(dict(part=query)))).text)
  223. if len(resp) > 1:
  224. return resp[1]
  225. return []
  226. backends = {
  227. '360search': qihu360search,
  228. 'baidu': baidu,
  229. 'brave': brave,
  230. 'dbpedia': dbpedia,
  231. 'duckduckgo': duckduckgo,
  232. 'google': google_complete,
  233. 'mwmbl': mwmbl,
  234. 'naver': naver,
  235. 'quark': quark,
  236. 'qwant': qwant,
  237. 'seznam': seznam,
  238. 'sogou': sogou,
  239. 'stract': stract,
  240. 'swisscows': swisscows,
  241. 'wikipedia': wikipedia,
  242. 'yandex': yandex,
  243. }
  244. def search_autocomplete(backend_name, query, sxng_locale):
  245. backend = backends.get(backend_name)
  246. if backend is None:
  247. return []
  248. try:
  249. return backend(query, sxng_locale)
  250. except (HTTPError, SearxEngineResponseException):
  251. return []