results.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # pylint: disable=missing-module-docstring
  3. import re
  4. from collections import defaultdict
  5. from operator import itemgetter
  6. from threading import RLock
  7. from typing import List, NamedTuple, Set
  8. from urllib.parse import urlparse, unquote
  9. from searx import logger
  10. from searx import utils
  11. from searx.engines import engines
  12. from searx.metrics import histogram_observe, counter_add, count_error
  13. CONTENT_LEN_IGNORED_CHARS_REGEX = re.compile(r'[,;:!?\./\\\\ ()-_]', re.M | re.U)
  14. WHITESPACE_REGEX = re.compile('( |\t|\n)+', re.M | re.U)
  15. # return the meaningful length of the content for a result
  16. def result_content_len(content):
  17. if isinstance(content, str):
  18. return len(CONTENT_LEN_IGNORED_CHARS_REGEX.sub('', content))
  19. return 0
  20. def compare_urls(url_a, url_b):
  21. """Lazy compare between two URL.
  22. "www.example.com" and "example.com" are equals.
  23. "www.example.com/path/" and "www.example.com/path" are equals.
  24. "https://www.example.com/" and "http://www.example.com/" are equals.
  25. Args:
  26. url_a (ParseResult): first URL
  27. url_b (ParseResult): second URL
  28. Returns:
  29. bool: True if url_a and url_b are equals
  30. """
  31. # ignore www. in comparison
  32. if url_a.netloc.startswith('www.'):
  33. host_a = url_a.netloc.replace('www.', '', 1)
  34. else:
  35. host_a = url_a.netloc
  36. if url_b.netloc.startswith('www.'):
  37. host_b = url_b.netloc.replace('www.', '', 1)
  38. else:
  39. host_b = url_b.netloc
  40. if host_a != host_b or url_a.query != url_b.query or url_a.fragment != url_b.fragment:
  41. return False
  42. # remove / from the end of the url if required
  43. path_a = url_a.path[:-1] if url_a.path.endswith('/') else url_a.path
  44. path_b = url_b.path[:-1] if url_b.path.endswith('/') else url_b.path
  45. return unquote(path_a) == unquote(path_b)
  46. def merge_two_infoboxes(infobox1, infobox2): # pylint: disable=too-many-branches, too-many-statements
  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) or compare_urls(
  69. urlparse(url1.get('url', '')), parsed_url2
  70. ):
  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 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. occurrences = len(result['positions'])
  112. return sum((occurrences * weight) / position for position in result['positions'])
  113. class Timing(NamedTuple): # pylint: disable=missing-class-docstring
  114. engine: str
  115. total: float
  116. load: float
  117. class UnresponsiveEngine(NamedTuple): # pylint: disable=missing-class-docstring
  118. engine: str
  119. error_type: str
  120. suspended: bool
  121. class ResultContainer:
  122. """docstring for ResultContainer"""
  123. __slots__ = (
  124. '_merged_results',
  125. 'infoboxes',
  126. 'suggestions',
  127. 'answers',
  128. 'corrections',
  129. '_number_of_results',
  130. '_closed',
  131. 'paging',
  132. 'unresponsive_engines',
  133. 'timings',
  134. 'redirect_url',
  135. 'engine_data',
  136. 'on_result',
  137. '_lock',
  138. )
  139. def __init__(self):
  140. super().__init__()
  141. self._merged_results = []
  142. self.infoboxes = []
  143. self.suggestions = set()
  144. self.answers = {}
  145. self.corrections = set()
  146. self._number_of_results = []
  147. self.engine_data = defaultdict(dict)
  148. self._closed = False
  149. self.paging = False
  150. self.unresponsive_engines: Set[UnresponsiveEngine] = set()
  151. self.timings: List[Timing] = []
  152. self.redirect_url = None
  153. self.on_result = lambda _: True
  154. self._lock = RLock()
  155. def extend(self, engine_name, results): # pylint: disable=too-many-branches
  156. if self._closed:
  157. return
  158. standard_result_count = 0
  159. error_msgs = set()
  160. for result in list(results):
  161. result['engine'] = engine_name
  162. if 'suggestion' in result and self.on_result(result):
  163. self.suggestions.add(result['suggestion'])
  164. elif 'answer' in result and self.on_result(result):
  165. self.answers[result['answer']] = result
  166. elif 'correction' in result and self.on_result(result):
  167. self.corrections.add(result['correction'])
  168. elif 'infobox' in result and self.on_result(result):
  169. self._merge_infobox(result)
  170. elif 'number_of_results' in result and self.on_result(result):
  171. self._number_of_results.append(result['number_of_results'])
  172. elif 'engine_data' in result and self.on_result(result):
  173. self.engine_data[engine_name][result['key']] = result['engine_data']
  174. elif 'url' in result:
  175. # standard result (url, title, content)
  176. if not self._is_valid_url_result(result, error_msgs):
  177. continue
  178. # normalize the result
  179. self._normalize_url_result(result)
  180. # call on_result call searx.search.SearchWithPlugins._on_result
  181. # which calls the plugins
  182. if not self.on_result(result):
  183. continue
  184. self.__merge_url_result(result, standard_result_count + 1)
  185. standard_result_count += 1
  186. elif self.on_result(result):
  187. self.__merge_result_no_url(result, standard_result_count + 1)
  188. standard_result_count += 1
  189. if len(error_msgs) > 0:
  190. for msg in error_msgs:
  191. count_error(engine_name, 'some results are invalids: ' + msg, secondary=True)
  192. if engine_name in engines:
  193. histogram_observe(standard_result_count, 'engine', engine_name, 'result', 'count')
  194. if not self.paging and engine_name in engines and engines[engine_name].paging:
  195. self.paging = True
  196. def _merge_infobox(self, infobox):
  197. add_infobox = True
  198. infobox_id = infobox.get('id', None)
  199. infobox['engines'] = set([infobox['engine']])
  200. if infobox_id is not None:
  201. parsed_url_infobox_id = urlparse(infobox_id)
  202. with self._lock:
  203. for existingIndex in self.infoboxes:
  204. if compare_urls(urlparse(existingIndex.get('id', '')), parsed_url_infobox_id):
  205. merge_two_infoboxes(existingIndex, infobox)
  206. add_infobox = False
  207. if add_infobox:
  208. self.infoboxes.append(infobox)
  209. def _is_valid_url_result(self, result, error_msgs):
  210. if 'url' in result:
  211. if not isinstance(result['url'], str):
  212. logger.debug('result: invalid URL: %s', str(result))
  213. error_msgs.add('invalid URL')
  214. return False
  215. if 'title' in result and not isinstance(result['title'], str):
  216. logger.debug('result: invalid title: %s', str(result))
  217. error_msgs.add('invalid title')
  218. return False
  219. if 'content' in result:
  220. if not isinstance(result['content'], str):
  221. logger.debug('result: invalid content: %s', str(result))
  222. error_msgs.add('invalid content')
  223. return False
  224. return True
  225. def _normalize_url_result(self, result):
  226. """Return True if the result is valid"""
  227. result['parsed_url'] = urlparse(result['url'])
  228. # if the result has no scheme, use http as default
  229. if not result['parsed_url'].scheme:
  230. result['parsed_url'] = result['parsed_url']._replace(scheme="http")
  231. result['url'] = result['parsed_url'].geturl()
  232. # avoid duplicate content between the content and title fields
  233. if result.get('content') == result.get('title'):
  234. del result['content']
  235. # make sure there is a template
  236. if 'template' not in result:
  237. result['template'] = 'default.html'
  238. # strip multiple spaces and carriage returns from content
  239. if result.get('content'):
  240. result['content'] = WHITESPACE_REGEX.sub(' ', result['content'])
  241. def __merge_url_result(self, result, position):
  242. result['engines'] = set([result['engine']])
  243. with self._lock:
  244. duplicated = self.__find_duplicated_http_result(result)
  245. if duplicated:
  246. self.__merge_duplicated_http_result(duplicated, result, position)
  247. return
  248. # if there is no duplicate found, append result
  249. result['positions'] = [position]
  250. self._merged_results.append(result)
  251. def __find_duplicated_http_result(self, result):
  252. result_template = result.get('template')
  253. for merged_result in self._merged_results:
  254. if 'parsed_url' not in merged_result:
  255. continue
  256. if compare_urls(result['parsed_url'], merged_result['parsed_url']) and result_template == merged_result.get(
  257. 'template'
  258. ):
  259. if result_template != 'images.html':
  260. # not an image, same template, same url : it's a duplicate
  261. return merged_result
  262. # it's an image
  263. # it's a duplicate if the parsed_url, template and img_src are different
  264. if result.get('img_src', '') == merged_result.get('img_src', ''):
  265. return merged_result
  266. return None
  267. def __merge_duplicated_http_result(self, duplicated, result, position):
  268. # using content with more text
  269. if result_content_len(result.get('content', '')) > result_content_len(duplicated.get('content', '')):
  270. duplicated['content'] = result['content']
  271. # merge all result's parameters not found in duplicate
  272. for key in result.keys():
  273. if not duplicated.get(key):
  274. duplicated[key] = result.get(key)
  275. # add the new position
  276. duplicated['positions'].append(position)
  277. # add engine to list of result-engines
  278. duplicated['engines'].add(result['engine'])
  279. # using https if possible
  280. if duplicated['parsed_url'].scheme != 'https' and result['parsed_url'].scheme == 'https':
  281. duplicated['url'] = result['parsed_url'].geturl()
  282. duplicated['parsed_url'] = result['parsed_url']
  283. def __merge_result_no_url(self, result, position):
  284. result['engines'] = set([result['engine']])
  285. result['positions'] = [position]
  286. with self._lock:
  287. self._merged_results.append(result)
  288. def close(self):
  289. self._closed = True
  290. for result in self._merged_results:
  291. score = result_score(result)
  292. result['score'] = score
  293. # removing html content and whitespace duplications
  294. if result.get('content'):
  295. result['content'] = utils.html_to_text(result['content']).strip()
  296. if result.get('title'):
  297. result['title'] = ' '.join(utils.html_to_text(result['title']).strip().split())
  298. for result_engine in result['engines']:
  299. counter_add(score, 'engine', result_engine, 'score')
  300. results = sorted(self._merged_results, key=itemgetter('score'), reverse=True)
  301. # pass 2 : group results by category and template
  302. gresults = []
  303. categoryPositions = {}
  304. for res in results:
  305. # do we need to handle more than one category per engine?
  306. engine = engines[res['engine']]
  307. res['category'] = engine.categories[0] if len(engine.categories) > 0 else ''
  308. # do we need to handle more than one category per engine?
  309. category = (
  310. res['category']
  311. + ':'
  312. + res.get('template', '')
  313. + ':'
  314. + ('img_src' if 'img_src' in res or 'thumbnail' in res else '')
  315. )
  316. current = None if category not in categoryPositions else categoryPositions[category]
  317. # group with previous results using the same category
  318. # if the group can accept more result and is not too far
  319. # from the current position
  320. if current is not None and (current['count'] > 0) and (len(gresults) - current['index'] < 20):
  321. # group with the previous results using
  322. # the same category with this one
  323. index = current['index']
  324. gresults.insert(index, res)
  325. # update every index after the current one
  326. # (including the current one)
  327. for k in categoryPositions: # pylint: disable=consider-using-dict-items
  328. v = categoryPositions[k]['index']
  329. if v >= index:
  330. categoryPositions[k]['index'] = v + 1
  331. # update this category
  332. current['count'] -= 1
  333. else:
  334. # same category
  335. gresults.append(res)
  336. # update categoryIndex
  337. categoryPositions[category] = {'index': len(gresults), 'count': 8}
  338. # update _merged_results
  339. self._merged_results = gresults
  340. def get_ordered_results(self):
  341. if not self._closed:
  342. self.close()
  343. return self._merged_results
  344. def results_length(self):
  345. return len(self._merged_results)
  346. @property
  347. def number_of_results(self) -> int:
  348. """Returns the average of results number, returns zero if the average
  349. result number is smaller than the actual result count."""
  350. resultnum_sum = sum(self._number_of_results)
  351. if not resultnum_sum or not self._number_of_results:
  352. return 0
  353. average = int(resultnum_sum / len(self._number_of_results))
  354. if average < self.results_length():
  355. average = 0
  356. return average
  357. def add_unresponsive_engine(self, engine_name: str, error_type: str, suspended: bool = False):
  358. if engines[engine_name].display_error_messages:
  359. self.unresponsive_engines.add(UnresponsiveEngine(engine_name, error_type, suspended))
  360. def add_timing(self, engine_name: str, engine_time: float, page_load_time: float):
  361. self.timings.append(Timing(engine_name, total=engine_time, load=page_load_time))
  362. def get_timings(self):
  363. return self.timings