results.py 14 KB

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