results.py 15 KB

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