results.py 15 KB

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