search.py 19 KB

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