utils.py 4.0KB

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