utils.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  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. print tag
  59. self.tags.append(tag)
  60. def handle_endtag(self, tag):
  61. print tag,tag
  62. if tag != self.tags[-1]:
  63. raise Exception("invalid html")
  64. self.tags.pop()
  65. def is_valid_tag(self):
  66. return not self.tags or self.tags[-1] not in blocked_tags
  67. def handle_data(self, d):
  68. if not self.is_valid_tag():
  69. return
  70. self.result.append(d)
  71. def handle_charref(self, number):
  72. if not self.is_valid_tag():
  73. return
  74. if number[0] in (u'x', u'X'):
  75. codepoint = int(number[1:], 16)
  76. else:
  77. codepoint = int(number)
  78. self.result.append(unichr(codepoint))
  79. def handle_entityref(self, name):
  80. if not self.is_valid_tag():
  81. return
  82. # codepoint = htmlentitydefs.name2codepoint[name]
  83. # self.result.append(unichr(codepoint))
  84. self.result.append(name)
  85. def get_text(self):
  86. return u''.join(self.result)
  87. def html_to_text(html):
  88. s = HTMLTextExtractor()
  89. s.feed(html)
  90. return s.get_text()
  91. class UnicodeWriter:
  92. """
  93. A CSV writer which will write rows to CSV file "f",
  94. which is encoded in the given encoding.
  95. """
  96. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  97. # Redirect output to a queue
  98. self.queue = cStringIO.StringIO()
  99. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  100. self.stream = f
  101. self.encoder = getincrementalencoder(encoding)()
  102. def writerow(self, row):
  103. unicode_row = []
  104. for col in row:
  105. if type(col) == str or type(col) == unicode:
  106. unicode_row.append(col.encode('utf-8').strip())
  107. else:
  108. unicode_row.append(col)
  109. self.writer.writerow(unicode_row)
  110. # Fetch UTF-8 output from the queue ...
  111. data = self.queue.getvalue()
  112. data = data.decode("utf-8")
  113. # ... and reencode it into the target encoding
  114. data = self.encoder.encode(data)
  115. # write to the target stream
  116. self.stream.write(data)
  117. # empty queue
  118. self.queue.truncate(0)
  119. def writerows(self, rows):
  120. for row in rows:
  121. self.writerow(row)
  122. def get_themes(root):
  123. """Returns available themes list."""
  124. static_path = os.path.join(root, 'static')
  125. static_names = set(os.listdir(static_path))
  126. templates_path = os.path.join(root, 'templates')
  127. templates_names = set(os.listdir(templates_path))
  128. themes = []
  129. for name in static_names.intersection(templates_names):
  130. themes += [name]
  131. return static_path, templates_path, themes