results.py 13 KB

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