search.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. 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. self.blocked_engines = get_blocked_engines(engines, request.cookies)
  253. self.results = []
  254. self.suggestions = []
  255. self.answers = []
  256. self.infoboxes = []
  257. self.request_data = {}
  258. # set specific language if set
  259. if request.cookies.get('language')\
  260. and request.cookies['language'] in (x[0] for x in language_codes):
  261. self.lang = request.cookies['language']
  262. # set request method
  263. if request.method == 'POST':
  264. self.request_data = request.form
  265. else:
  266. self.request_data = request.args
  267. # TODO better exceptions
  268. if not self.request_data.get('q'):
  269. raise Exception('noquery')
  270. # set pagenumber
  271. pageno_param = self.request_data.get('pageno', '1')
  272. if not pageno_param.isdigit() or int(pageno_param) < 1:
  273. raise Exception('wrong pagenumber')
  274. self.pageno = int(pageno_param)
  275. # parse query, if tags are set, which change
  276. # the serch engine or search-language
  277. query_obj = Query(self.request_data['q'], self.blocked_engines)
  278. query_obj.parse_query()
  279. # set query
  280. self.query = query_obj.getSearchQuery()
  281. # get last selected language in query, if possible
  282. # TODO support search with multible languages
  283. if len(query_obj.languages):
  284. self.lang = query_obj.languages[-1]
  285. self.engines = query_obj.engines
  286. self.categories = []
  287. # if engines are calculated from query,
  288. # set categories by using that informations
  289. if self.engines and query_obj.specific:
  290. self.categories = list(set(engine['category']
  291. for engine in self.engines))
  292. # otherwise, using defined categories to
  293. # calculate which engines should be used
  294. else:
  295. # set used categories
  296. for pd_name, pd in self.request_data.items():
  297. if pd_name.startswith('category_'):
  298. category = pd_name[9:]
  299. # if category is not found in list, skip
  300. if category not in categories:
  301. continue
  302. if pd != 'off':
  303. # add category to list
  304. self.categories.append(category)
  305. elif category in self.categories:
  306. # remove category from list if property is set to 'off'
  307. self.categories.remove(category)
  308. # if no category is specified for this search,
  309. # using user-defined default-configuration which
  310. # (is stored in cookie)
  311. if not self.categories:
  312. cookie_categories = request.cookies.get('categories', '')
  313. cookie_categories = cookie_categories.split(',')
  314. for ccateg in cookie_categories:
  315. if ccateg in categories:
  316. self.categories.append(ccateg)
  317. # if still no category is specified, using general
  318. # as default-category
  319. if not self.categories:
  320. self.categories = ['general']
  321. # using all engines for that search, which are
  322. # declared under the specific categories
  323. for categ in self.categories:
  324. self.engines.extend({'category': categ,
  325. 'name': engine.name}
  326. for engine in categories[categ]
  327. if (engine.name, categ) not in self.blocked_engines)
  328. # do search-request
  329. def search(self, request):
  330. global number_of_searches
  331. # init vars
  332. requests = []
  333. results_queue = Queue()
  334. results = {}
  335. suggestions = set()
  336. answers = set()
  337. infoboxes = []
  338. # increase number of searches
  339. number_of_searches += 1
  340. # set default useragent
  341. # user_agent = request.headers.get('User-Agent', '')
  342. user_agent = gen_useragent()
  343. # start search-reqest for all selected engines
  344. for selected_engine in self.engines:
  345. if selected_engine['name'] not in engines:
  346. continue
  347. engine = engines[selected_engine['name']]
  348. # if paging is not supported, skip
  349. if self.pageno > 1 and not engine.paging:
  350. continue
  351. # if search-language is set and engine does not
  352. # provide language-support, skip
  353. if self.lang != 'all' and not engine.language_support:
  354. continue
  355. # set default request parameters
  356. request_params = default_request_params()
  357. request_params['headers']['User-Agent'] = user_agent
  358. request_params['category'] = selected_engine['category']
  359. request_params['started'] = time()
  360. request_params['pageno'] = self.pageno
  361. request_params['language'] = self.lang
  362. try:
  363. # 0 = None, 1 = Moderate, 2 = Strict
  364. request_params['safesearch'] = int(request.cookies.get('safesearch', 1))
  365. except ValueError:
  366. request_params['safesearch'] = 1
  367. # update request parameters dependent on
  368. # search-engine (contained in engines folder)
  369. engine.request(self.query.encode('utf-8'), request_params)
  370. if request_params['url'] is None:
  371. # TODO add support of offline engines
  372. pass
  373. # create a callback wrapper for the search engine results
  374. callback = make_callback(
  375. selected_engine['name'],
  376. results_queue,
  377. engine.response,
  378. request_params)
  379. # create dictionary which contain all
  380. # informations about the request
  381. request_args = dict(
  382. headers=request_params['headers'],
  383. hooks=dict(response=callback),
  384. cookies=request_params['cookies'],
  385. timeout=engine.timeout,
  386. verify=request_params['verify']
  387. )
  388. # specific type of request (GET or POST)
  389. if request_params['method'] == 'GET':
  390. req = requests_lib.get
  391. else:
  392. req = requests_lib.post
  393. request_args['data'] = request_params['data']
  394. # ignoring empty urls
  395. if not request_params['url']:
  396. continue
  397. # append request to list
  398. requests.append((req, request_params['url'],
  399. request_args,
  400. selected_engine['name']))
  401. if not requests:
  402. return results, suggestions, answers, infoboxes
  403. # send all search-request
  404. threaded_requests(requests)
  405. while not results_queue.empty():
  406. engine_name, engine_results = results_queue.get_nowait()
  407. # TODO type checks
  408. [suggestions.add(x['suggestion'])
  409. for x in list(engine_results)
  410. if 'suggestion' in x
  411. and engine_results.remove(x) is None]
  412. [answers.add(x['answer'])
  413. for x in list(engine_results)
  414. if 'answer' in x
  415. and engine_results.remove(x) is None]
  416. infoboxes.extend(x for x in list(engine_results)
  417. if 'infobox' in x
  418. and engine_results.remove(x) is None)
  419. results[engine_name] = engine_results
  420. # update engine-specific stats
  421. for engine_name, engine_results in results.items():
  422. engines[engine_name].stats['search_count'] += 1
  423. engines[engine_name].stats['result_count'] += len(engine_results)
  424. # score results and remove duplications
  425. results = score_results(results)
  426. # merge infoboxes according to their ids
  427. infoboxes = merge_infoboxes(infoboxes)
  428. # update engine stats, using calculated score
  429. for result in results:
  430. for res_engine in result['engines']:
  431. engines[result['engine']]\
  432. .stats['score_count'] += result['score']
  433. # return results, suggestions, answers and infoboxes
  434. return results, suggestions, answers, infoboxes