results.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import re
  2. import sys
  3. from collections import defaultdict
  4. from operator import itemgetter
  5. from threading import RLock
  6. from searx.engines import engines
  7. from searx.url_utils import urlparse, unquote
  8. if sys.version_info[0] == 3:
  9. basestring = str
  10. CONTENT_LEN_IGNORED_CHARS_REGEX = re.compile(r'[,;:!?\./\\\\ ()-_]', re.M | re.U)
  11. WHITESPACE_REGEX = re.compile('( |\t|\n)+', re.M | re.U)
  12. # return the meaningful length of the content for a result
  13. def result_content_len(content):
  14. if isinstance(content, basestring):
  15. return len(CONTENT_LEN_IGNORED_CHARS_REGEX.sub('', content))
  16. else:
  17. return 0
  18. def compare_urls(url_a, url_b):
  19. # ignore www. in comparison
  20. if url_a.netloc.startswith('www.'):
  21. host_a = url_a.netloc.replace('www.', '', 1)
  22. else:
  23. host_a = url_a.netloc
  24. if url_b.netloc.startswith('www.'):
  25. host_b = url_b.netloc.replace('www.', '', 1)
  26. else:
  27. host_b = url_b.netloc
  28. if host_a != host_b or url_a.query != url_b.query or url_a.fragment != url_b.fragment:
  29. return False
  30. # remove / from the end of the url if required
  31. path_a = url_a.path[:-1]\
  32. if url_a.path.endswith('/')\
  33. else url_a.path
  34. path_b = url_b.path[:-1]\
  35. if url_b.path.endswith('/')\
  36. else url_b.path
  37. return unquote(path_a) == unquote(path_b)
  38. def merge_two_infoboxes(infobox1, infobox2):
  39. # get engines weights
  40. if hasattr(engines[infobox1['engine']], 'weight'):
  41. weight1 = engines[infobox1['engine']].weight
  42. else:
  43. weight1 = 1
  44. if hasattr(engines[infobox2['engine']], 'weight'):
  45. weight2 = engines[infobox2['engine']].weight
  46. else:
  47. weight2 = 1
  48. if weight2 > weight1:
  49. infobox1['engine'] = infobox2['engine']
  50. infobox1['engines'] |= infobox2['engines']
  51. if 'urls' in infobox2:
  52. urls1 = infobox1.get('urls', None)
  53. if urls1 is None:
  54. urls1 = []
  55. for url2 in infobox2.get('urls', []):
  56. unique_url = True
  57. parsed_url2 = urlparse(url2.get('url', ''))
  58. for url1 in urls1:
  59. if compare_urls(urlparse(url1.get('url', '')), parsed_url2):
  60. unique_url = False
  61. break
  62. if unique_url:
  63. urls1.append(url2)
  64. infobox1['urls'] = urls1
  65. if 'img_src' in infobox2:
  66. img1 = infobox1.get('img_src', None)
  67. img2 = infobox2.get('img_src')
  68. if img1 is None:
  69. infobox1['img_src'] = img2
  70. elif weight2 > weight1:
  71. infobox1['img_src'] = img2
  72. if 'attributes' in infobox2:
  73. attributes1 = infobox1.get('attributes', None)
  74. if attributes1 is None:
  75. attributes1 = []
  76. infobox1['attributes'] = attributes1
  77. attributeSet = set()
  78. for attribute in infobox1.get('attributes', []):
  79. if attribute.get('label', None) not in attributeSet:
  80. attributeSet.add(attribute.get('label', None))
  81. for attribute in infobox2.get('attributes', []):
  82. if attribute.get('label', None) not in attributeSet:
  83. attributes1.append(attribute)
  84. if 'content' in infobox2:
  85. content1 = infobox1.get('content', None)
  86. content2 = infobox2.get('content', '')
  87. if content1 is not None:
  88. if result_content_len(content2) > result_content_len(content1):
  89. infobox1['content'] = content2
  90. else:
  91. infobox1['content'] = content2
  92. def result_score(result):
  93. weight = 1.0
  94. for result_engine in result['engines']:
  95. if hasattr(engines[result_engine], 'weight'):
  96. weight *= float(engines[result_engine].weight)
  97. occurences = len(result['positions'])
  98. return sum((occurences * weight) / position for position in result['positions'])
  99. class ResultContainer(object):
  100. """docstring for ResultContainer"""
  101. def __init__(self):
  102. super(ResultContainer, self).__init__()
  103. self.results = defaultdict(list)
  104. self._merged_results = []
  105. self.infoboxes = []
  106. self.suggestions = set()
  107. self.answers = {}
  108. self.corrections = set()
  109. self._number_of_results = []
  110. self._ordered = False
  111. self.paging = False
  112. self.unresponsive_engines = set()
  113. self.timings = []
  114. self.redirect_url = None
  115. def extend(self, engine_name, results):
  116. for result in list(results):
  117. result['engine'] = engine_name
  118. if 'suggestion' in result:
  119. self.suggestions.add(result['suggestion'])
  120. results.remove(result)
  121. elif 'answer' in result:
  122. self.answers[result['answer']] = result
  123. results.remove(result)
  124. elif 'correction' in result:
  125. self.corrections.add(result['correction'])
  126. results.remove(result)
  127. elif 'infobox' in result:
  128. self._merge_infobox(result)
  129. results.remove(result)
  130. elif 'number_of_results' in result:
  131. self._number_of_results.append(result['number_of_results'])
  132. results.remove(result)
  133. if engine_name in engines:
  134. with RLock():
  135. engines[engine_name].stats['search_count'] += 1
  136. engines[engine_name].stats['result_count'] += len(results)
  137. if not results:
  138. return
  139. self.results[engine_name].extend(results)
  140. if not self.paging and engine_name in engines and engines[engine_name].paging:
  141. self.paging = True
  142. for i, result in enumerate(results):
  143. if 'url' in result and not isinstance(result['url'], basestring):
  144. continue
  145. try:
  146. result['url'] = result['url'].decode('utf-8')
  147. except:
  148. pass
  149. if 'title' in result and not isinstance(result['title'], basestring):
  150. continue
  151. if 'content' in result and not isinstance(result['content'], basestring):
  152. continue
  153. position = i + 1
  154. self._merge_result(result, position)
  155. def _merge_infobox(self, infobox):
  156. add_infobox = True
  157. infobox_id = infobox.get('id', None)
  158. infobox['engines'] = set([infobox['engine']])
  159. if infobox_id is not None:
  160. parsed_url_infobox_id = urlparse(infobox_id)
  161. for existingIndex in self.infoboxes:
  162. if compare_urls(urlparse(existingIndex.get('id', '')), parsed_url_infobox_id):
  163. merge_two_infoboxes(existingIndex, infobox)
  164. add_infobox = False
  165. if add_infobox:
  166. self.infoboxes.append(infobox)
  167. def _merge_result(self, result, position):
  168. if 'url' in result:
  169. self.__merge_url_result(result, position)
  170. return
  171. self.__merge_result_no_url(result, position)
  172. def __merge_url_result(self, result, position):
  173. result['parsed_url'] = urlparse(result['url'])
  174. # if the result has no scheme, use http as default
  175. if not result['parsed_url'].scheme:
  176. result['parsed_url'] = result['parsed_url']._replace(scheme="http")
  177. result['url'] = result['parsed_url'].geturl()
  178. result['engines'] = set([result['engine']])
  179. # strip multiple spaces and cariage returns from content
  180. if result.get('content'):
  181. result['content'] = WHITESPACE_REGEX.sub(' ', result['content'])
  182. duplicated = self.__find_duplicated_http_result(result)
  183. if duplicated:
  184. self.__merge_duplicated_http_result(duplicated, result, position)
  185. return
  186. # if there is no duplicate found, append result
  187. result['positions'] = [position]
  188. with RLock():
  189. self._merged_results.append(result)
  190. def __find_duplicated_http_result(self, result):
  191. result_template = result.get('template')
  192. for merged_result in self._merged_results:
  193. if 'parsed_url' not in merged_result:
  194. continue
  195. if compare_urls(result['parsed_url'], merged_result['parsed_url'])\
  196. and result_template == merged_result.get('template'):
  197. if result_template != 'images.html':
  198. # not an image, same template, same url : it's a duplicate
  199. return merged_result
  200. else:
  201. # it's an image
  202. # it's a duplicate if the parsed_url, template and img_src are differents
  203. if result.get('img_src', '') == merged_result.get('img_src', ''):
  204. return merged_result
  205. return None
  206. def __merge_duplicated_http_result(self, duplicated, result, position):
  207. # using content with more text
  208. if result_content_len(result.get('content', '')) >\
  209. result_content_len(duplicated.get('content', '')):
  210. duplicated['content'] = result['content']
  211. # merge all result's parameters not found in duplicate
  212. for key in result.keys():
  213. if not duplicated.get(key):
  214. duplicated[key] = result.get(key)
  215. # add the new position
  216. duplicated['positions'].append(position)
  217. # add engine to list of result-engines
  218. duplicated['engines'].add(result['engine'])
  219. # using https if possible
  220. if duplicated['parsed_url'].scheme != 'https' and result['parsed_url'].scheme == 'https':
  221. duplicated['url'] = result['parsed_url'].geturl()
  222. duplicated['parsed_url'] = result['parsed_url']
  223. def __merge_result_no_url(self, result, position):
  224. result['engines'] = set([result['engine']])
  225. result['positions'] = [position]
  226. with RLock():
  227. self._merged_results.append(result)
  228. def order_results(self):
  229. for result in self._merged_results:
  230. score = result_score(result)
  231. result['score'] = score
  232. with RLock():
  233. for result_engine in result['engines']:
  234. engines[result_engine].stats['score_count'] += score
  235. results = sorted(self._merged_results, key=itemgetter('score'), reverse=True)
  236. # pass 2 : group results by category and template
  237. gresults = []
  238. categoryPositions = {}
  239. for i, res in enumerate(results):
  240. # FIXME : handle more than one category per engine
  241. res['category'] = engines[res['engine']].categories[0]
  242. # FIXME : handle more than one category per engine
  243. category = engines[res['engine']].categories[0]\
  244. + ':' + res.get('template', '')\
  245. + ':' + ('img_src' if 'img_src' in res or 'thumbnail' in res else '')
  246. current = None if category not in categoryPositions\
  247. else categoryPositions[category]
  248. # group with previous results using the same category
  249. # if the group can accept more result and is not too far
  250. # from the current position
  251. if current is not None and (current['count'] > 0)\
  252. and (len(gresults) - current['index'] < 20):
  253. # group with the previous results using
  254. # the same category with this one
  255. index = current['index']
  256. gresults.insert(index, res)
  257. # update every index after the current one
  258. # (including the current one)
  259. for k in categoryPositions:
  260. v = categoryPositions[k]['index']
  261. if v >= index:
  262. categoryPositions[k]['index'] = v + 1
  263. # update this category
  264. current['count'] -= 1
  265. else:
  266. # same category
  267. gresults.append(res)
  268. # update categoryIndex
  269. categoryPositions[category] = {'index': len(gresults), 'count': 8}
  270. # update _merged_results
  271. self._ordered = True
  272. self._merged_results = gresults
  273. def get_ordered_results(self):
  274. if not self._ordered:
  275. self.order_results()
  276. return self._merged_results
  277. def results_length(self):
  278. return len(self._merged_results)
  279. def results_number(self):
  280. resultnum_sum = sum(self._number_of_results)
  281. if not resultnum_sum or not self._number_of_results:
  282. return 0
  283. return resultnum_sum / len(self._number_of_results)
  284. def add_unresponsive_engine(self, engine_name, error_type, error_message=None):
  285. if engines[engine_name].display_error_messages:
  286. self.unresponsive_engines.add((engine_name, error_type, error_message))
  287. def add_timing(self, engine_name, engine_time, page_load_time):
  288. self.timings.append({
  289. 'engine': engines[engine_name].shortcut,
  290. 'total': engine_time,
  291. 'load': page_load_time
  292. })
  293. def get_timings(self):
  294. return self.timings