results.py 13 KB

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