autocomplete.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  13. '''
  14. import sys
  15. from lxml import etree
  16. from json import loads
  17. from searx import settings
  18. from searx.languages import language_codes
  19. from searx.engines import (
  20. categories, engines, engine_shortcuts
  21. )
  22. from searx.poolrequests import get as http_get
  23. from searx.url_utils import urlencode
  24. if sys.version_info[0] == 3:
  25. unicode = str
  26. def get(*args, **kwargs):
  27. if 'timeout' not in kwargs:
  28. kwargs['timeout'] = settings['outgoing']['request_timeout']
  29. return http_get(*args, **kwargs)
  30. def searx_bang(full_query):
  31. '''check if the searchQuery contain a bang, and create fitting autocompleter results'''
  32. # check if there is a query which can be parsed
  33. if len(full_query.getSearchQuery()) == 0:
  34. return []
  35. results = []
  36. # check if current query stats with !bang
  37. first_char = full_query.getSearchQuery()[0]
  38. if first_char == '!' or first_char == '?':
  39. if len(full_query.getSearchQuery()) == 1:
  40. # show some example queries
  41. # TODO, check if engine is not avaliable
  42. results.append(first_char + "images")
  43. results.append(first_char + "wikipedia")
  44. results.append(first_char + "osm")
  45. else:
  46. engine_query = full_query.getSearchQuery()[1:]
  47. # check if query starts with categorie name
  48. for categorie in categories:
  49. if categorie.startswith(engine_query):
  50. results.append(first_char + '{categorie}'.format(categorie=categorie))
  51. # check if query starts with engine name
  52. for engine in engines:
  53. if engine.startswith(engine_query.replace('_', ' ')):
  54. results.append(first_char + '{engine}'.format(engine=engine.replace(' ', '_')))
  55. # check if query starts with engine shortcut
  56. for engine_shortcut in engine_shortcuts:
  57. if engine_shortcut.startswith(engine_query):
  58. results.append(first_char + '{engine_shortcut}'.format(engine_shortcut=engine_shortcut))
  59. # check if current query stats with :bang
  60. elif first_char == ':':
  61. if len(full_query.getSearchQuery()) == 1:
  62. # show some example queries
  63. results.append(":en")
  64. results.append(":en_us")
  65. results.append(":english")
  66. results.append(":united_kingdom")
  67. else:
  68. engine_query = full_query.getSearchQuery()[1:]
  69. for lc in language_codes:
  70. lang_id, lang_name, country, english_name = map(unicode.lower, lc)
  71. # check if query starts with language-id
  72. if lang_id.startswith(engine_query):
  73. if len(engine_query) <= 2:
  74. results.append(u':{lang_id}'.format(lang_id=lang_id.split('-')[0]))
  75. else:
  76. results.append(u':{lang_id}'.format(lang_id=lang_id))
  77. # check if query starts with language name
  78. if lang_name.startswith(engine_query) or english_name.startswith(engine_query):
  79. results.append(u':{lang_name}'.format(lang_name=lang_name))
  80. # check if query starts with country
  81. if country.startswith(engine_query.replace('_', ' ')):
  82. results.append(u':{country}'.format(country=country.replace(' ', '_')))
  83. # remove duplicates
  84. result_set = set(results)
  85. # remove results which are already contained in the query
  86. for query_part in full_query.query_parts:
  87. if query_part in result_set:
  88. result_set.remove(query_part)
  89. # convert result_set back to list
  90. return list(result_set)
  91. def dbpedia(query, lang):
  92. # dbpedia autocompleter, no HTTPS
  93. autocomplete_url = 'http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?'
  94. response = get(autocomplete_url + urlencode(dict(QueryString=query)))
  95. results = []
  96. if response.ok:
  97. dom = etree.fromstring(response.content)
  98. results = dom.xpath('//a:Result/a:Label//text()',
  99. namespaces={'a': 'http://lookup.dbpedia.org/'})
  100. return results
  101. def duckduckgo(query, lang):
  102. # duckduckgo autocompleter
  103. url = 'https://ac.duckduckgo.com/ac/?{0}&type=list'
  104. resp = loads(get(url.format(urlencode(dict(q=query)))).text)
  105. if len(resp) > 1:
  106. return resp[1]
  107. return []
  108. def google(query, lang):
  109. # google autocompleter
  110. autocomplete_url = 'https://suggestqueries.google.com/complete/search?client=toolbar&'
  111. response = get(autocomplete_url + urlencode(dict(hl=lang, q=query)))
  112. results = []
  113. if response.ok:
  114. dom = etree.fromstring(response.text)
  115. results = dom.xpath('//suggestion/@data')
  116. return results
  117. def startpage(query, lang):
  118. # startpage autocompleter
  119. url = 'https://startpage.com/do/suggest?{query}'
  120. resp = get(url.format(query=urlencode({'query': query}))).text.split('\n')
  121. if len(resp) > 1:
  122. return resp
  123. return []
  124. def swisscows(query, lang):
  125. # swisscows autocompleter
  126. url = 'https://swisscows.ch/api/suggest?{query}&itemsCount=5'
  127. resp = loads(get(url.format(query=urlencode({'query': query}))).text)
  128. return resp
  129. def qwant(query, lang):
  130. # qwant autocompleter (additional parameter : lang=en_en&count=xxx )
  131. url = 'https://api.qwant.com/api/suggest?{query}'
  132. resp = get(url.format(query=urlencode({'q': query, 'lang': lang})))
  133. results = []
  134. if resp.ok:
  135. data = loads(resp.text)
  136. if data['status'] == 'success':
  137. for item in data['data']['items']:
  138. results.append(item['value'])
  139. return results
  140. def wikipedia(query, lang):
  141. # wikipedia autocompleter
  142. url = 'https://' + lang + '.wikipedia.org/w/api.php?action=opensearch&{0}&limit=10&namespace=0&format=json'
  143. resp = loads(get(url.format(urlencode(dict(search=query)))).text)
  144. if len(resp) > 1:
  145. return resp[1]
  146. return []
  147. backends = {'dbpedia': dbpedia,
  148. 'duckduckgo': duckduckgo,
  149. 'google': google,
  150. 'startpage': startpage,
  151. 'swisscows': swisscows,
  152. 'qwant': qwant,
  153. 'wikipedia': wikipedia
  154. }