results.py 14 KB

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