results.py 17 KB

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