autocomplete.py 7.0 KB

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