results.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import re
  2. import sys
  3. from collections import defaultdict
  4. from operator import itemgetter
  5. from threading import RLock
  6. from searx.engines import engines
  7. from searx.url_utils import urlparse, unquote
  8. if sys.version_info[0] == 3:
  9. basestring = str
  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, basestring):
  15. return len(CONTENT_LEN_IGNORED_CHARS_REGEX.sub('', content))
  16. else:
  17. return 0
  18. def compare_urls(url_a, url_b):
  19. # ignore www. in comparison
  20. if url_a.netloc.startswith('www.'):
  21. host_a = url_a.netloc.replace('www.', '', 1)
  22. else:
  23. host_a = url_a.netloc
  24. if url_b.netloc.startswith('www.'):
  25. host_b = url_b.netloc.replace('www.', '', 1)
  26. else:
  27. host_b = url_b.netloc
  28. if host_a != host_b or url_a.query != url_b.query or url_a.fragment != url_b.fragment:
  29. return False
  30. # remove / from the end of the url if required
  31. path_a = url_a.path[:-1]\
  32. if url_a.path.endswith('/')\
  33. else url_a.path
  34. path_b = url_b.path[:-1]\
  35. if url_b.path.endswith('/')\
  36. else url_b.path
  37. return unquote(path_a) == unquote(path_b)
  38. def merge_two_infoboxes(infobox1, infobox2):
  39. # get engines weights
  40. if hasattr(engines[infobox1['engine']], 'weight'):
  41. weight1 = engines[infobox1['engine']].weight
  42. else:
  43. weight1 = 1
  44. if hasattr(engines[infobox2['engine']], 'weight'):
  45. weight2 = engines[infobox2['engine']].weight
  46. else:
  47. weight2 = 1
  48. if weight2 > weight1:
  49. infobox1['engine'] = infobox2['engine']
  50. if 'urls' in infobox2:
  51. urls1 = infobox1.get('urls', None)
  52. if urls1 is None:
  53. urls1 = []
  54. for url2 in infobox2.get('urls', []):
  55. unique_url = True
  56. for url1 in infobox1.get('urls', []):
  57. if compare_urls(urlparse(url1.get('url', '')), urlparse(url2.get('url', ''))):
  58. unique_url = False
  59. break
  60. if unique_url:
  61. urls1.append(url2)
  62. infobox1['urls'] = urls1
  63. if 'img_src' in infobox2:
  64. img1 = infobox1.get('img_src', None)
  65. img2 = infobox2.get('img_src')
  66. if img1 is None:
  67. infobox1['img_src'] = img2
  68. elif weight2 > weight1:
  69. infobox1['img_src'] = img2
  70. if 'attributes' in infobox2:
  71. attributes1 = infobox1.get('attributes', None)
  72. if attributes1 is None:
  73. attributes1 = []
  74. infobox1['attributes'] = attributes1
  75. attributeSet = set()
  76. for attribute in infobox1.get('attributes', []):
  77. if attribute.get('label', None) not in attributeSet:
  78. attributeSet.add(attribute.get('label', None))
  79. for attribute in infobox2.get('attributes', []):
  80. if attribute.get('label', None) not in attributeSet:
  81. attributes1.append(attribute)
  82. if 'content' in infobox2:
  83. content1 = infobox1.get('content', None)
  84. content2 = infobox2.get('content', '')
  85. if content1 is not None:
  86. if result_content_len(content2) > result_content_len(content1):
  87. infobox1['content'] = content2
  88. else:
  89. infobox1['content'] = content2
  90. def result_score(result):
  91. weight = 1.0
  92. for result_engine in result['engines']:
  93. if hasattr(engines[result_engine], 'weight'):
  94. weight *= float(engines[result_engine].weight)
  95. occurences = len(result['positions'])
  96. return sum((occurences * weight) / position for position in result['positions'])
  97. class ResultContainer(object):
  98. """docstring for ResultContainer"""
  99. def __init__(self):
  100. super(ResultContainer, self).__init__()
  101. self.results = defaultdict(list)
  102. self._merged_results = []
  103. self.infoboxes = []
  104. self.suggestions = set()
  105. self.answers = set()
  106. self.corrections = set()
  107. self._number_of_results = []
  108. self._ordered = False
  109. self.paging = False
  110. def extend(self, engine_name, results):
  111. for result in list(results):
  112. result['engine'] = engine_name
  113. if 'suggestion' in result:
  114. self.suggestions.add(result['suggestion'])
  115. results.remove(result)
  116. elif 'answer' in result:
  117. self.answers.add(result['answer'])
  118. results.remove(result)
  119. elif 'correction' in result:
  120. self.corrections.add(result['correction'])
  121. results.remove(result)
  122. elif 'infobox' in result:
  123. self._merge_infobox(result)
  124. results.remove(result)
  125. elif 'number_of_results' in result:
  126. self._number_of_results.append(result['number_of_results'])
  127. results.remove(result)
  128. if engine_name in engines:
  129. with RLock():
  130. engines[engine_name].stats['search_count'] += 1
  131. engines[engine_name].stats['result_count'] += len(results)
  132. if not results:
  133. return
  134. self.results[engine_name].extend(results)
  135. if not self.paging and engine_name in engines and engines[engine_name].paging:
  136. self.paging = True
  137. for i, result in enumerate(results):
  138. try:
  139. result['url'] = result['url'].decode('utf-8')
  140. except:
  141. pass
  142. position = i + 1
  143. self._merge_result(result, position)
  144. def _merge_infobox(self, infobox):
  145. add_infobox = True
  146. infobox_id = infobox.get('id', None)
  147. if infobox_id is not None:
  148. for existingIndex in self.infoboxes:
  149. if compare_urls(urlparse(existingIndex.get('id', '')), urlparse(infobox_id)):
  150. merge_two_infoboxes(existingIndex, infobox)
  151. add_infobox = False
  152. if add_infobox:
  153. self.infoboxes.append(infobox)
  154. def _merge_result(self, result, position):
  155. result['parsed_url'] = urlparse(result['url'])
  156. # if the result has no scheme, use http as default
  157. if not result['parsed_url'].scheme:
  158. result['parsed_url'] = result['parsed_url']._replace(scheme="http")
  159. result['url'] = result['parsed_url'].geturl()
  160. result['engines'] = [result['engine']]
  161. # strip multiple spaces and cariage returns from content
  162. if result.get('content'):
  163. result['content'] = WHITESPACE_REGEX.sub(' ', result['content'])
  164. # check for duplicates
  165. duplicated = False
  166. for merged_result in self._merged_results:
  167. if compare_urls(result['parsed_url'], merged_result['parsed_url'])\
  168. and result.get('template') == merged_result.get('template'):
  169. duplicated = merged_result
  170. break
  171. # merge duplicates together
  172. if duplicated:
  173. # using content with more text
  174. if result_content_len(result.get('content', '')) >\
  175. result_content_len(duplicated.get('content', '')):
  176. duplicated['content'] = result['content']
  177. # add the new position
  178. duplicated['positions'].append(position)
  179. # add engine to list of result-engines
  180. duplicated['engines'].append(result['engine'])
  181. # using https if possible
  182. if duplicated['parsed_url'].scheme != 'https' and result['parsed_url'].scheme == 'https':
  183. duplicated['url'] = result['parsed_url'].geturl()
  184. duplicated['parsed_url'] = result['parsed_url']
  185. # if there is no duplicate found, append result
  186. else:
  187. result['positions'] = [position]
  188. with RLock():
  189. self._merged_results.append(result)
  190. def order_results(self):
  191. for result in self._merged_results:
  192. score = result_score(result)
  193. result['score'] = score
  194. with RLock():
  195. for result_engine in result['engines']:
  196. engines[result_engine].stats['score_count'] += score
  197. results = sorted(self._merged_results, key=itemgetter('score'), reverse=True)
  198. # pass 2 : group results by category and template
  199. gresults = []
  200. categoryPositions = {}
  201. for i, res in enumerate(results):
  202. # FIXME : handle more than one category per engine
  203. res['category'] = engines[res['engine']].categories[0]
  204. # FIXME : handle more than one category per engine
  205. category = engines[res['engine']].categories[0]\
  206. + ':' + res.get('template', '')\
  207. + ':' + ('img_src' if 'img_src' in res or 'thumbnail' in res else '')
  208. current = None if category not in categoryPositions\
  209. else categoryPositions[category]
  210. # group with previous results using the same category
  211. # if the group can accept more result and is not too far
  212. # from the current position
  213. if current is not None and (current['count'] > 0)\
  214. and (len(gresults) - current['index'] < 20):
  215. # group with the previous results using
  216. # the same category with this one
  217. index = current['index']
  218. gresults.insert(index, res)
  219. # update every index after the current one
  220. # (including the current one)
  221. for k in categoryPositions:
  222. v = categoryPositions[k]['index']
  223. if v >= index:
  224. categoryPositions[k]['index'] = v + 1
  225. # update this category
  226. current['count'] -= 1
  227. else:
  228. # same category
  229. gresults.append(res)
  230. # update categoryIndex
  231. categoryPositions[category] = {'index': len(gresults), 'count': 8}
  232. # update _merged_results
  233. self._ordered = True
  234. self._merged_results = gresults
  235. def get_ordered_results(self):
  236. if not self._ordered:
  237. self.order_results()
  238. return self._merged_results
  239. def results_length(self):
  240. return len(self._merged_results)
  241. def results_number(self):
  242. resultnum_sum = sum(self._number_of_results)
  243. if not resultnum_sum or not self._number_of_results:
  244. return 0
  245. return resultnum_sum / len(self._number_of_results)