autocomplete.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 qihu360search(query, _lang):
  111. # 360Search search autocompleter
  112. url = f"https://sug.so.360.cn/suggest?{urlencode({'format': 'json', 'word': query})}"
  113. response = get(url)
  114. results = []
  115. if response.ok:
  116. data = response.json()
  117. if 'result' in data:
  118. for item in data['result']:
  119. results.append(item['word'])
  120. return results
  121. def quark(query, _lang):
  122. # Quark search autocompleter
  123. url = f"https://sugs.m.sm.cn/web?{urlencode({'q': query})}"
  124. response = get(url)
  125. results = []
  126. if response.ok:
  127. data = response.json()
  128. for item in data.get('r', []):
  129. results.append(item['w'])
  130. return results
  131. def seznam(query, _lang):
  132. # seznam search autocompleter
  133. url = 'https://suggest.seznam.cz/fulltext/cs?{query}'
  134. resp = get(
  135. url.format(
  136. query=urlencode(
  137. {'phrase': query, 'cursorPosition': len(query), 'format': 'json-2', 'highlight': '1', 'count': '6'}
  138. )
  139. )
  140. )
  141. if not resp.ok:
  142. return []
  143. data = resp.json()
  144. return [
  145. ''.join([part.get('text', '') for part in item.get('text', [])])
  146. for item in data.get('result', [])
  147. if item.get('itemType', None) == 'ItemType.TEXT'
  148. ]
  149. def sogou(query, _lang):
  150. # Sogou search autocompleter
  151. base_url = "https://sor.html5.qq.com/api/getsug?"
  152. response = get(base_url + urlencode({'m': 'searxng', 'key': query}))
  153. if response.ok:
  154. raw_json = extr(response.text, "[", "]", default="")
  155. try:
  156. data = json.loads(f"[{raw_json}]]")
  157. return data[1]
  158. except json.JSONDecodeError:
  159. return []
  160. return []
  161. def stract(query, _lang):
  162. # stract autocompleter (beta)
  163. url = f"https://stract.com/beta/api/autosuggest?q={quote_plus(query)}"
  164. resp = post(url)
  165. if not resp.ok:
  166. return []
  167. return [html.unescape(suggestion['raw']) for suggestion in resp.json()]
  168. def swisscows(query, _lang):
  169. # swisscows autocompleter
  170. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  171. resp = json.loads(get(url.format(query=urlencode({'query': query}))).text)
  172. return resp
  173. def qwant(query, sxng_locale):
  174. """Autocomplete from Qwant. Supports Qwant's regions."""
  175. results = []
  176. locale = engines['qwant'].traits.get_region(sxng_locale, 'en_US')
  177. url = 'https://api.qwant.com/v3/suggest?{query}'
  178. resp = get(url.format(query=urlencode({'q': query, 'locale': locale, 'version': '2'})))
  179. if resp.ok:
  180. data = resp.json()
  181. if data['status'] == 'success':
  182. for item in data['data']['items']:
  183. results.append(item['value'])
  184. return results
  185. def wikipedia(query, sxng_locale):
  186. """Autocomplete from Wikipedia. Supports Wikipedia's languages (aka netloc)."""
  187. results = []
  188. eng_traits = engines['wikipedia'].traits
  189. wiki_lang = eng_traits.get_language(sxng_locale, 'en')
  190. wiki_netloc = eng_traits.custom['wiki_netloc'].get(wiki_lang, 'en.wikipedia.org') # type: ignore
  191. url = 'https://{wiki_netloc}/w/api.php?{args}'
  192. args = urlencode(
  193. {
  194. 'action': 'opensearch',
  195. 'format': 'json',
  196. 'formatversion': '2',
  197. 'search': query,
  198. 'namespace': '0',
  199. 'limit': '10',
  200. }
  201. )
  202. resp = get(url.format(args=args, wiki_netloc=wiki_netloc))
  203. if resp.ok:
  204. data = resp.json()
  205. if len(data) > 1:
  206. results = data[1]
  207. return results
  208. def yandex(query, _lang):
  209. # yandex autocompleter
  210. url = "https://suggest.yandex.com/suggest-ff.cgi?{0}"
  211. resp = json.loads(get(url.format(urlencode(dict(part=query)))).text)
  212. if len(resp) > 1:
  213. return resp[1]
  214. return []
  215. backends = {
  216. '360search': qihu360search,
  217. 'baidu': baidu,
  218. 'brave': brave,
  219. 'dbpedia': dbpedia,
  220. 'duckduckgo': duckduckgo,
  221. 'google': google_complete,
  222. 'mwmbl': mwmbl,
  223. 'quark': quark,
  224. 'qwant': qwant,
  225. 'seznam': seznam,
  226. 'sogou': sogou,
  227. 'stract': stract,
  228. 'swisscows': swisscows,
  229. 'wikipedia': wikipedia,
  230. 'yandex': yandex,
  231. }
  232. def search_autocomplete(backend_name, query, sxng_locale):
  233. backend = backends.get(backend_name)
  234. if backend is None:
  235. return []
  236. try:
  237. return backend(query, sxng_locale)
  238. except (HTTPError, SearxEngineResponseException):
  239. return []