autocomplete.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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 startpage(query, sxng_locale):
  135. """Autocomplete from Startpage. Supports Startpage's languages"""
  136. lui = engines['startpage'].traits.get_language(sxng_locale, 'english')
  137. url = 'https://startpage.com/suggestions?{query}'
  138. resp = get(url.format(query=urlencode({'q': query, 'segment': 'startpage.udog', 'lui': lui})))
  139. data = resp.json()
  140. return [e['text'] for e in data.get('suggestions', []) if 'text' in e]
  141. def swisscows(query, _lang):
  142. # swisscows autocompleter
  143. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  144. resp = json.loads(get(url.format(query=urlencode({'query': query}))).text)
  145. return resp
  146. def qwant(query, sxng_locale):
  147. """Autocomplete from Qwant. Supports Qwant's regions."""
  148. results = []
  149. locale = engines['qwant'].traits.get_region(sxng_locale, 'en_US')
  150. url = 'https://api.qwant.com/v3/suggest?{query}'
  151. resp = get(url.format(query=urlencode({'q': query, 'locale': locale, 'version': '2'})))
  152. if resp.ok:
  153. data = resp.json()
  154. if data['status'] == 'success':
  155. for item in data['data']['items']:
  156. results.append(item['value'])
  157. return results
  158. def wikipedia(query, sxng_locale):
  159. """Autocomplete from Wikipedia. Supports Wikipedia's languages (aka netloc)."""
  160. results = []
  161. eng_traits = engines['wikipedia'].traits
  162. wiki_lang = eng_traits.get_language(sxng_locale, 'en')
  163. wiki_netloc = eng_traits.custom['wiki_netloc'].get(wiki_lang, 'en.wikipedia.org') # type: ignore
  164. url = 'https://{wiki_netloc}/w/api.php?{args}'
  165. args = urlencode(
  166. {
  167. 'action': 'opensearch',
  168. 'format': 'json',
  169. 'formatversion': '2',
  170. 'search': query,
  171. 'namespace': '0',
  172. 'limit': '10',
  173. }
  174. )
  175. resp = get(url.format(args=args, wiki_netloc=wiki_netloc))
  176. if resp.ok:
  177. data = resp.json()
  178. if len(data) > 1:
  179. results = data[1]
  180. return results
  181. def yandex(query, _lang):
  182. # yandex autocompleter
  183. url = "https://suggest.yandex.com/suggest-ff.cgi?{0}"
  184. resp = json.loads(get(url.format(urlencode(dict(part=query)))).text)
  185. if len(resp) > 1:
  186. return resp[1]
  187. return []
  188. backends = {
  189. 'baidu': baidu,
  190. 'brave': brave,
  191. 'dbpedia': dbpedia,
  192. 'duckduckgo': duckduckgo,
  193. 'google': google_complete,
  194. 'mwmbl': mwmbl,
  195. 'qwant': qwant,
  196. 'seznam': seznam,
  197. 'startpage': startpage,
  198. 'stract': stract,
  199. 'swisscows': swisscows,
  200. 'wikipedia': wikipedia,
  201. 'yandex': yandex,
  202. }
  203. def search_autocomplete(backend_name, query, sxng_locale):
  204. backend = backends.get(backend_name)
  205. if backend is None:
  206. return []
  207. try:
  208. return backend(query, sxng_locale)
  209. except (HTTPError, SearxEngineResponseException):
  210. return []