results.py 15 KB

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