utils.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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. def gen_useragent():
  21. # TODO
  22. return ua.format(os=choice(ua_os), version=choice(ua_versions))
  23. def searx_useragent():
  24. return 'searx/{searx_version} {suffix}'.format(
  25. searx_version=VERSION_STRING,
  26. suffix=settings['server'].get('useragent_suffix', ''))
  27. def highlight_content(content, query):
  28. if not content:
  29. return None
  30. # ignoring html contents
  31. # TODO better html content detection
  32. if content.find('<') != -1:
  33. return content
  34. query = query.decode('utf-8')
  35. if content.lower().find(query.lower()) > -1:
  36. query_regex = u'({0})'.format(re.escape(query))
  37. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  38. content, flags=re.I | re.U)
  39. else:
  40. regex_parts = []
  41. for chunk in query.split():
  42. if len(chunk) == 1:
  43. regex_parts.append(u'\W+{0}\W+'.format(re.escape(chunk)))
  44. else:
  45. regex_parts.append(u'{0}'.format(re.escape(chunk)))
  46. query_regex = u'({0})'.format('|'.join(regex_parts))
  47. content = re.sub(query_regex, '<span class="highlight">\\1</span>',
  48. content, flags=re.I | re.U)
  49. return content
  50. class HTMLTextExtractor(HTMLParser):
  51. def __init__(self):
  52. HTMLParser.__init__(self)
  53. self.result = []
  54. def handle_data(self, d):
  55. self.result.append(d)
  56. def handle_charref(self, number):
  57. if number[0] in (u'x', u'X'):
  58. codepoint = int(number[1:], 16)
  59. else:
  60. codepoint = int(number)
  61. self.result.append(unichr(codepoint))
  62. def handle_entityref(self, name):
  63. # codepoint = htmlentitydefs.name2codepoint[name]
  64. # self.result.append(unichr(codepoint))
  65. self.result.append(name)
  66. def get_text(self):
  67. return u''.join(self.result)
  68. def html_to_text(html):
  69. s = HTMLTextExtractor()
  70. s.feed(html)
  71. return s.get_text()
  72. class UnicodeWriter:
  73. """
  74. A CSV writer which will write rows to CSV file "f",
  75. which is encoded in the given encoding.
  76. """
  77. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  78. # Redirect output to a queue
  79. self.queue = cStringIO.StringIO()
  80. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  81. self.stream = f
  82. self.encoder = getincrementalencoder(encoding)()
  83. def writerow(self, row):
  84. unicode_row = []
  85. for col in row:
  86. if type(col) == str or type(col) == unicode:
  87. unicode_row.append(col.encode('utf-8').strip())
  88. else:
  89. unicode_row.append(col)
  90. self.writer.writerow(unicode_row)
  91. # Fetch UTF-8 output from the queue ...
  92. data = self.queue.getvalue()
  93. data = data.decode("utf-8")
  94. # ... and reencode it into the target encoding
  95. data = self.encoder.encode(data)
  96. # write to the target stream
  97. self.stream.write(data)
  98. # empty queue
  99. self.queue.truncate(0)
  100. def writerows(self, rows):
  101. for row in rows:
  102. self.writerow(row)
  103. def get_themes(root):
  104. """Returns available themes list."""
  105. static_path = os.path.join(root, 'static')
  106. static_names = set(os.listdir(static_path))
  107. templates_path = os.path.join(root, 'templates')
  108. templates_names = set(os.listdir(templates_path))
  109. themes = []
  110. for name in static_names.intersection(templates_names):
  111. themes += [name]
  112. return static_path, templates_path, themes