utils.py 3.9 KB

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