utils.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # import htmlentitydefs
  2. from codecs import getincrementalencoder
  3. from HTMLParser import HTMLParser
  4. from random import choice
  5. from searx.version import VERSION_STRING
  6. from searx import settings
  7. import cStringIO
  8. import csv
  9. import os
  10. import re
  11. ua_versions = ('29.0',
  12. '30.0',
  13. '31.0',
  14. '32.0',
  15. '33.0')
  16. ua_os = ('Windows NT 6.3; WOW64',
  17. 'X11; Linux x86_64',
  18. 'X11; Linux x86')
  19. ua = "Mozilla/5.0 ({os}) Gecko/20100101 Firefox/{version}"
  20. blocked_tags = ('script',
  21. 'style')
  22. def gen_useragent():
  23. # TODO
  24. return ua.format(os=choice(ua_os), version=choice(ua_versions))
  25. def searx_useragent():
  26. return 'searx/{searx_version} {suffix}'.format(
  27. searx_version=VERSION_STRING,
  28. suffix=settings['server'].get('useragent_suffix', ''))
  29. def highlight_content(content, query):
  30. if not content:
  31. return None
  32. # ignoring html contents
  33. # TODO better html content detection
  34. if content.find('<') != -1:
  35. return content
  36. query = query.decode('utf-8')
  37. if content.lower().find(query.lower()) > -1:
  38. query_regex = u'({0})'.format(re.escape(query))
  39. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  40. content, flags=re.I | re.U)
  41. else:
  42. regex_parts = []
  43. for chunk in query.split():
  44. if len(chunk) == 1:
  45. regex_parts.append(u'\W+{0}\W+'.format(re.escape(chunk)))
  46. else:
  47. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  48. query_regex = u'({0})'.format('|'.join(regex_parts))
  49. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  50. content, flags=re.I | re.U)
  51. return content
  52. class HTMLTextExtractor(HTMLParser):
  53. def __init__(self):
  54. HTMLParser.__init__(self)
  55. self.result = []
  56. self.tags = []
  57. def handle_starttag(self, tag, attrs):
  58. self.tags.append(tag)
  59. def handle_endtag(self, tag):
  60. if tag != self.tags[-1]:
  61. raise Exception("invalid html")
  62. self.tags.pop()
  63. def is_valid_tag(self):
  64. return not self.tags or self.tags[-1] not in blocked_tags
  65. def handle_data(self, d):
  66. if not self.is_valid_tag():
  67. return
  68. self.result.append(d)
  69. def handle_charref(self, number):
  70. if not self.is_valid_tag():
  71. return
  72. if number[0] in (u'x', u'X'):
  73. codepoint = int(number[1:], 16)
  74. else:
  75. codepoint = int(number)
  76. self.result.append(unichr(codepoint))
  77. def handle_entityref(self, name):
  78. if not self.is_valid_tag():
  79. return
  80. # codepoint = htmlentitydefs.name2codepoint[name]
  81. # self.result.append(unichr(codepoint))
  82. self.result.append(name)
  83. def get_text(self):
  84. return u''.join(self.result)
  85. def html_to_text(html):
  86. s = HTMLTextExtractor()
  87. s.feed(html)
  88. return s.get_text()
  89. class UnicodeWriter:
  90. """
  91. A CSV writer which will write rows to CSV file "f",
  92. which is encoded in the given encoding.
  93. """
  94. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  95. # Redirect output to a queue
  96. self.queue = cStringIO.StringIO()
  97. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  98. self.stream = f
  99. self.encoder = getincrementalencoder(encoding)()
  100. def writerow(self, row):
  101. unicode_row = []
  102. for col in row:
  103. if type(col) == str or type(col) == unicode:
  104. unicode_row.append(col.encode('utf-8').strip())
  105. else:
  106. unicode_row.append(col)
  107. self.writer.writerow(unicode_row)
  108. # Fetch UTF-8 output from the queue ...
  109. data = self.queue.getvalue()
  110. data = data.decode("utf-8")
  111. # ... and reencode it into the target encoding
  112. data = self.encoder.encode(data)
  113. # write to the target stream
  114. self.stream.write(data)
  115. # empty queue
  116. self.queue.truncate(0)
  117. def writerows(self, rows):
  118. for row in rows:
  119. self.writerow(row)
  120. def get_themes(root):
  121. """Returns available themes list."""
  122. static_path = os.path.join(root, 'static')
  123. templates_path = os.path.join(root, 'templates')
  124. themes = os.listdir(os.path.join(static_path, 'themes'))
  125. return static_path, templates_path, themes
  126. def get_static_files(base_path):
  127. base_path = os.path.join(base_path, 'static')
  128. static_files = set()
  129. base_path_length = len(base_path) + 1
  130. for directory, _, files in os.walk(base_path):
  131. for filename in files:
  132. f = os.path.join(directory[base_path_length:], filename)
  133. static_files.add(f)
  134. return static_files
  135. def get_result_templates(base_path):
  136. base_path = os.path.join(base_path, 'templates')
  137. result_templates = set()
  138. base_path_length = len(base_path) + 1
  139. for directory, _, files in os.walk(base_path):
  140. if directory.endswith('result_templates'):
  141. for filename in files:
  142. f = os.path.join(directory[base_path_length:], filename)
  143. result_templates.add(f)
  144. return result_templates