search.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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 requests as requests_lib
  15. import threading
  16. import re
  17. from itertools import izip_longest, chain
  18. from operator import itemgetter
  19. from Queue import Queue
  20. from time import time
  21. from urlparse import urlparse, unquote
  22. from searx.engines import (
  23. categories, engines
  24. )
  25. from searx.languages import language_codes
  26. from searx.utils import gen_useragent
  27. from searx.query import Query
  28. from searx import logger
  29. logger = logger.getChild('search')
  30. number_of_searches = 0
  31. def search_request_wrapper(fn, url, engine_name, **kwargs):
  32. try:
  33. return fn(url, **kwargs)
  34. except:
  35. # increase errors stats
  36. engines[engine_name].stats['errors'] += 1
  37. # print engine name and specific error message
  38. logger.exception('engine crash: {0}'.format(engine_name))
  39. return
  40. def threaded_requests(requests):
  41. timeout_limit = max(r[2]['timeout'] for r in requests)
  42. search_start = time()
  43. for fn, url, request_args, engine_name in requests:
  44. request_args['timeout'] = timeout_limit
  45. th = threading.Thread(
  46. target=search_request_wrapper,
  47. args=(fn, url, engine_name),
  48. kwargs=request_args,
  49. name='search_request',
  50. )
  51. th._engine_name = engine_name
  52. th.start()
  53. for th in threading.enumerate():
  54. if th.name == 'search_request':
  55. remaining_time = max(0.0, timeout_limit - (time() - search_start))
  56. th.join(remaining_time)
  57. if th.isAlive():
  58. logger.warning('engine timeout: {0}'.format(th._engine_name))
  59. # get default reqest parameter
  60. def default_request_params():
  61. return {
  62. 'method': 'GET',
  63. 'headers': {},
  64. 'data': {},
  65. 'url': '',
  66. 'cookies': {},
  67. 'verify': True
  68. }
  69. # create a callback wrapper for the search engine results
  70. def make_callback(engine_name, results_queue, callback, params):
  71. # creating a callback wrapper for the search engine results
  72. def process_callback(response, **kwargs):
  73. response.search_params = params
  74. timeout_overhead = 0.2 # seconds
  75. search_duration = time() - params['started']
  76. timeout_limit = engines[engine_name].timeout + timeout_overhead
  77. if search_duration > timeout_limit:
  78. engines[engine_name].stats['page_load_time'] += timeout_limit
  79. engines[engine_name].stats['errors'] += 1
  80. return
  81. # callback
  82. search_results = callback(response)
  83. # add results
  84. for result in search_results:
  85. result['engine'] = engine_name
  86. results_queue.put_nowait((engine_name, search_results))
  87. # update stats with current page-load-time
  88. engines[engine_name].stats['page_load_time'] += search_duration
  89. return process_callback
  90. # return the meaningful length of the content for a result
  91. def content_result_len(content):
  92. if isinstance(content, basestring):
  93. content = re.sub('[,;:!?\./\\\\ ()-_]', '', content)
  94. return len(content)
  95. else:
  96. return 0
  97. # score results and remove duplications
  98. def score_results(results):
  99. # calculate scoring parameters
  100. flat_res = filter(
  101. None, chain.from_iterable(izip_longest(*results.values())))
  102. flat_len = len(flat_res)
  103. engines_len = len(results)
  104. results = []
  105. # pass 1: deduplication + scoring
  106. for i, res in enumerate(flat_res):
  107. res['parsed_url'] = urlparse(res['url'])
  108. res['host'] = res['parsed_url'].netloc
  109. if res['host'].startswith('www.'):
  110. res['host'] = res['host'].replace('www.', '', 1)
  111. res['engines'] = [res['engine']]
  112. weight = 1.0
  113. # strip multiple spaces and cariage returns from content
  114. if res.get('content'):
  115. res['content'] = re.sub(' +', ' ',
  116. res['content'].strip().replace('\n', ''))
  117. # get weight of this engine if possible
  118. if hasattr(engines[res['engine']], 'weight'):
  119. weight = float(engines[res['engine']].weight)
  120. # calculate score for that engine
  121. score = int((flat_len - i) / engines_len) * weight + 1
  122. # check for duplicates
  123. duplicated = False
  124. for new_res in results:
  125. # remove / from the end of the url if required
  126. p1 = res['parsed_url'].path[:-1]\
  127. if res['parsed_url'].path.endswith('/')\
  128. else res['parsed_url'].path
  129. p2 = new_res['parsed_url'].path[:-1]\
  130. if new_res['parsed_url'].path.endswith('/')\
  131. else new_res['parsed_url'].path
  132. # check if that result is a duplicate
  133. if res['host'] == new_res['host'] and\
  134. unquote(p1) == unquote(p2) and\
  135. res['parsed_url'].query == new_res['parsed_url'].query and\
  136. res.get('template') == new_res.get('template'):
  137. duplicated = new_res
  138. break
  139. # merge duplicates together
  140. if duplicated:
  141. # using content with more text
  142. if content_result_len(res.get('content', '')) >\
  143. content_result_len(duplicated.get('content', '')):
  144. duplicated['content'] = res['content']
  145. # increase result-score
  146. duplicated['score'] += score
  147. # add engine to list of result-engines
  148. duplicated['engines'].append(res['engine'])
  149. # using https if possible
  150. if duplicated['parsed_url'].scheme == 'https':
  151. continue
  152. elif res['parsed_url'].scheme == 'https':
  153. duplicated['url'] = res['parsed_url'].geturl()
  154. duplicated['parsed_url'] = res['parsed_url']
  155. # if there is no duplicate found, append result
  156. else:
  157. res['score'] = score
  158. results.append(res)
  159. results = sorted(results, key=itemgetter('score'), reverse=True)
  160. # pass 2 : group results by category and template
  161. gresults = []
  162. categoryPositions = {}
  163. for i, res in enumerate(results):
  164. # FIXME : handle more than one category per engine
  165. category = engines[res['engine']].categories[0] + ':' + ''\
  166. if 'template' not in res\
  167. else res['template']
  168. current = None if category not in categoryPositions\
  169. else categoryPositions[category]
  170. # group with previous results using the same category
  171. # if the group can accept more result and is not too far
  172. # from the current position
  173. if current is not None and (current['count'] > 0)\
  174. and (len(gresults) - current['index'] < 20):
  175. # group with the previous results using
  176. # the same category with this one
  177. index = current['index']
  178. gresults.insert(index, res)
  179. # update every index after the current one
  180. # (including the current one)
  181. for k in categoryPositions:
  182. v = categoryPositions[k]['index']
  183. if v >= index:
  184. categoryPositions[k]['index'] = v+1
  185. # update this category
  186. current['count'] -= 1
  187. else:
  188. # same category
  189. gresults.append(res)
  190. # update categoryIndex
  191. categoryPositions[category] = {'index': len(gresults), 'count': 8}
  192. # return gresults
  193. return gresults
  194. def merge_two_infoboxes(infobox1, infobox2):
  195. if 'urls' in infobox2:
  196. urls1 = infobox1.get('urls', None)
  197. if urls1 is None:
  198. urls1 = []
  199. infobox1.set('urls', urls1)
  200. urlSet = set()
  201. for url in infobox1.get('urls', []):
  202. urlSet.add(url.get('url', None))
  203. for url in infobox2.get('urls', []):
  204. if url.get('url', None) not in urlSet:
  205. urls1.append(url)
  206. if 'attributes' in infobox2:
  207. attributes1 = infobox1.get('attributes', None)
  208. if attributes1 is None:
  209. attributes1 = []
  210. infobox1.set('attributes', attributes1)
  211. attributeSet = set()
  212. for attribute in infobox1.get('attributes', []):
  213. if attribute.get('label', None) not in attributeSet:
  214. attributeSet.add(attribute.get('label', None))
  215. for attribute in infobox2.get('attributes', []):
  216. attributes1.append(attribute)
  217. if 'content' in infobox2:
  218. content1 = infobox1.get('content', None)
  219. content2 = infobox2.get('content', '')
  220. if content1 is not None:
  221. if content_result_len(content2) > content_result_len(content1):
  222. infobox1['content'] = content2
  223. else:
  224. infobox1.set('content', content2)
  225. def merge_infoboxes(infoboxes):
  226. results = []
  227. infoboxes_id = {}
  228. for infobox in infoboxes:
  229. add_infobox = True
  230. infobox_id = infobox.get('id', None)
  231. if infobox_id is not None:
  232. existingIndex = infoboxes_id.get(infobox_id, None)
  233. if existingIndex is not None:
  234. merge_two_infoboxes(results[existingIndex], infobox)
  235. add_infobox = False
  236. if add_infobox:
  237. results.append(infobox)
  238. infoboxes_id[infobox_id] = len(results)-1
  239. return results
  240. class Search(object):
  241. """Search information container"""
  242. def __init__(self, request):
  243. # init vars
  244. super(Search, self).__init__()
  245. self.query = None
  246. self.engines = []
  247. self.categories = []
  248. self.paging = False
  249. self.pageno = 1
  250. self.lang = 'all'
  251. # set blocked engines
  252. if request.cookies.get('blocked_engines'):
  253. self.blocked_engines = request.cookies['blocked_engines'].split(',') # noqa
  254. else:
  255. self.blocked_engines = []
  256. self.results = []
  257. self.suggestions = []
  258. self.answers = []
  259. self.infoboxes = []
  260. self.request_data = {}
  261. # set specific language if set
  262. if request.cookies.get('language')\
  263. and request.cookies['language'] in (x[0] for x in language_codes):
  264. self.lang = request.cookies['language']
  265. # set request method
  266. if request.method == 'POST':
  267. self.request_data = request.form
  268. else:
  269. self.request_data = request.args
  270. # TODO better exceptions
  271. if not self.request_data.get('q'):
  272. raise Exception('noquery')
  273. # set pagenumber
  274. pageno_param = self.request_data.get('pageno', '1')
  275. if not pageno_param.isdigit() or int(pageno_param) < 1:
  276. raise Exception('wrong pagenumber')
  277. self.pageno = int(pageno_param)
  278. # parse query, if tags are set, which change
  279. # the serch engine or search-language
  280. query_obj = Query(self.request_data['q'], self.blocked_engines)
  281. query_obj.parse_query()
  282. # set query
  283. self.query = query_obj.getSearchQuery()
  284. # get last selected language in query, if possible
  285. # TODO support search with multible languages
  286. if len(query_obj.languages):
  287. self.lang = query_obj.languages[-1]
  288. self.engines = query_obj.engines
  289. self.categories = []
  290. # if engines are calculated from query,
  291. # set categories by using that informations
  292. if self.engines and query_obj.specific:
  293. self.categories = list(set(engine['category']
  294. for engine in self.engines))
  295. # otherwise, using defined categories to
  296. # calculate which engines should be used
  297. else:
  298. # set used categories
  299. for pd_name, pd in self.request_data.items():
  300. if pd_name.startswith('category_'):
  301. category = pd_name[9:]
  302. # if category is not found in list, skip
  303. if category not in categories:
  304. continue
  305. if pd != 'off':
  306. # add category to list
  307. self.categories.append(category)
  308. elif category in self.categories:
  309. # remove category from list if property is set to 'off'
  310. self.categories.remove(category)
  311. # if no category is specified for this search,
  312. # using user-defined default-configuration which
  313. # (is stored in cookie)
  314. if not self.categories:
  315. cookie_categories = request.cookies.get('categories', '')
  316. cookie_categories = cookie_categories.split(',')
  317. for ccateg in cookie_categories:
  318. if ccateg in categories:
  319. self.categories.append(ccateg)
  320. # if still no category is specified, using general
  321. # as default-category
  322. if not self.categories:
  323. self.categories = ['general']
  324. # using all engines for that search, which are
  325. # declared under the specific categories
  326. for categ in self.categories:
  327. self.engines.extend({'category': categ,
  328. 'name': x.name}
  329. for x in categories[categ]
  330. if x.name not in self.blocked_engines)
  331. # do search-request
  332. def search(self, request):
  333. global number_of_searches
  334. # init vars
  335. requests = []
  336. results_queue = Queue()
  337. results = {}
  338. suggestions = set()
  339. answers = set()
  340. infoboxes = []
  341. # increase number of searches
  342. number_of_searches += 1
  343. # set default useragent
  344. # user_agent = request.headers.get('User-Agent', '')
  345. user_agent = gen_useragent()
  346. # start search-reqest for all selected engines
  347. for selected_engine in self.engines:
  348. if selected_engine['name'] not in engines:
  349. continue
  350. engine = engines[selected_engine['name']]
  351. # if paging is not supported, skip
  352. if self.pageno > 1 and not engine.paging:
  353. continue
  354. # if search-language is set and engine does not
  355. # provide language-support, skip
  356. if self.lang != 'all' and not engine.language_support:
  357. continue
  358. # set default request parameters
  359. request_params = default_request_params()
  360. request_params['headers']['User-Agent'] = user_agent
  361. request_params['category'] = selected_engine['category']
  362. request_params['started'] = time()
  363. request_params['pageno'] = self.pageno
  364. request_params['language'] = self.lang
  365. # update request parameters dependent on
  366. # search-engine (contained in engines folder)
  367. engine.request(self.query.encode('utf-8'), request_params)
  368. if request_params['url'] is None:
  369. # TODO add support of offline engines
  370. pass
  371. # create a callback wrapper for the search engine results
  372. callback = make_callback(
  373. selected_engine['name'],
  374. results_queue,
  375. engine.response,
  376. request_params)
  377. # create dictionary which contain all
  378. # informations about the request
  379. request_args = dict(
  380. headers=request_params['headers'],
  381. hooks=dict(response=callback),
  382. cookies=request_params['cookies'],
  383. timeout=engine.timeout,
  384. verify=request_params['verify']
  385. )
  386. # specific type of request (GET or POST)
  387. if request_params['method'] == 'GET':
  388. req = requests_lib.get
  389. else:
  390. req = requests_lib.post
  391. request_args['data'] = request_params['data']
  392. # ignoring empty urls
  393. if not request_params['url']:
  394. continue
  395. # append request to list
  396. requests.append((req, request_params['url'],
  397. request_args,
  398. selected_engine['name']))
  399. if not requests:
  400. return results, suggestions, answers, infoboxes
  401. # send all search-request
  402. threaded_requests(requests)
  403. while not results_queue.empty():
  404. engine_name, engine_results = results_queue.get_nowait()
  405. # TODO type checks
  406. [suggestions.add(x['suggestion'])
  407. for x in list(engine_results)
  408. if 'suggestion' in x
  409. and engine_results.remove(x) is None]
  410. [answers.add(x['answer'])
  411. for x in list(engine_results)
  412. if 'answer' in x
  413. and engine_results.remove(x) is None]
  414. infoboxes.extend(x for x in list(engine_results)
  415. if 'infobox' in x
  416. and engine_results.remove(x) is None)
  417. results[engine_name] = engine_results
  418. # update engine-specific stats
  419. for engine_name, engine_results in results.items():
  420. engines[engine_name].stats['search_count'] += 1
  421. engines[engine_name].stats['result_count'] += len(engine_results)
  422. # score results and remove duplications
  423. results = score_results(results)
  424. # merge infoboxes according to their ids
  425. infoboxes = merge_infoboxes(infoboxes)
  426. # update engine stats, using calculated score
  427. for result in results:
  428. for res_engine in result['engines']:
  429. engines[result['engine']]\
  430. .stats['score_count'] += result['score']
  431. # return results, suggestions, answers and infoboxes
  432. return results, suggestions, answers, infoboxes