results.py 10.0KB

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