results.py 13 KB

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