results.py 13 KB

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