widgets.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. # -*- coding: utf-8 -*-
  2. #
  3. # progressbar - Text progress bar library for Python.
  4. # Copyright (c) 2005 Nilton Volpato
  5. #
  6. # This library is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU Lesser General Public
  8. # License as published by the Free Software Foundation; either
  9. # version 2.1 of the License, or (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. # Lesser General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Lesser General Public
  17. # License along with this library; if not, write to the Free Software
  18. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  19. """Default ProgressBar widgets."""
  20. from __future__ import division
  21. import datetime
  22. import math
  23. try:
  24. from abc import ABCMeta, abstractmethod
  25. except ImportError:
  26. AbstractWidget = object
  27. abstractmethod = lambda fn: fn
  28. else:
  29. AbstractWidget = ABCMeta('AbstractWidget', (object,), {})
  30. def format_updatable(updatable, pbar):
  31. if hasattr(updatable, 'update'): return updatable.update(pbar)
  32. else: return updatable
  33. class Widget(AbstractWidget):
  34. """The base class for all widgets.
  35. The ProgressBar will call the widget's update value when the widget should
  36. be updated. The widget's size may change between calls, but the widget may
  37. display incorrectly if the size changes drastically and repeatedly.
  38. The boolean TIME_SENSITIVE informs the ProgressBar that it should be
  39. updated more often because it is time sensitive.
  40. """
  41. TIME_SENSITIVE = False
  42. __slots__ = ()
  43. @abstractmethod
  44. def update(self, pbar):
  45. """Updates the widget.
  46. pbar - a reference to the calling ProgressBar
  47. """
  48. class WidgetHFill(Widget):
  49. """The base class for all variable width widgets.
  50. This widget is much like the \\hfill command in TeX, it will expand to
  51. fill the line. You can use more than one in the same line, and they will
  52. all have the same width, and together will fill the line.
  53. """
  54. @abstractmethod
  55. def update(self, pbar, width):
  56. """Updates the widget providing the total width the widget must fill.
  57. pbar - a reference to the calling ProgressBar
  58. width - The total width the widget must fill
  59. """
  60. class Timer(Widget):
  61. """Widget which displays the elapsed seconds."""
  62. __slots__ = ('format_string',)
  63. TIME_SENSITIVE = True
  64. def __init__(self, format='Elapsed Time: %s'):
  65. self.format_string = format
  66. @staticmethod
  67. def format_time(seconds):
  68. """Formats time as the string "HH:MM:SS"."""
  69. return str(datetime.timedelta(seconds=int(seconds)))
  70. def update(self, pbar):
  71. """Updates the widget to show the elapsed time."""
  72. return self.format_string % self.format_time(pbar.seconds_elapsed)
  73. class ETA(Timer):
  74. """Widget which attempts to estimate the time of arrival."""
  75. TIME_SENSITIVE = True
  76. def update(self, pbar):
  77. """Updates the widget to show the ETA or total time when finished."""
  78. if pbar.currval == 0:
  79. return 'ETA: --:--:--'
  80. elif pbar.finished:
  81. return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
  82. else:
  83. elapsed = pbar.seconds_elapsed
  84. eta = elapsed * pbar.maxval / pbar.currval - elapsed
  85. return 'ETA: %s' % self.format_time(eta)
  86. class AdaptiveETA(Timer):
  87. """Widget which attempts to estimate the time of arrival.
  88. Uses a weighted average of two estimates:
  89. 1) ETA based on the total progress and time elapsed so far
  90. 2) ETA based on the progress as per the last 10 update reports
  91. The weight depends on the current progress so that to begin with the
  92. total progress is used and at the end only the most recent progress is
  93. used.
  94. """
  95. TIME_SENSITIVE = True
  96. NUM_SAMPLES = 10
  97. def _update_samples(self, currval, elapsed):
  98. sample = (currval, elapsed)
  99. if not hasattr(self, 'samples'):
  100. self.samples = [sample] * (self.NUM_SAMPLES + 1)
  101. else:
  102. self.samples.append(sample)
  103. return self.samples.pop(0)
  104. def _eta(self, maxval, currval, elapsed):
  105. return elapsed * maxval / float(currval) - elapsed
  106. def update(self, pbar):
  107. """Updates the widget to show the ETA or total time when finished."""
  108. if pbar.currval == 0:
  109. return 'ETA: --:--:--'
  110. elif pbar.finished:
  111. return 'Time: %s' % self.format_time(pbar.seconds_elapsed)
  112. else:
  113. elapsed = pbar.seconds_elapsed
  114. currval1, elapsed1 = self._update_samples(pbar.currval, elapsed)
  115. eta = self._eta(pbar.maxval, pbar.currval, elapsed)
  116. if pbar.currval > currval1:
  117. etasamp = self._eta(pbar.maxval - currval1,
  118. pbar.currval - currval1,
  119. elapsed - elapsed1)
  120. weight = (pbar.currval / float(pbar.maxval)) ** 0.5
  121. eta = (1 - weight) * eta + weight * etasamp
  122. return 'ETA: %s' % self.format_time(eta)
  123. class FileTransferSpeed(Widget):
  124. """Widget for showing the transfer speed (useful for file transfers)."""
  125. FORMAT = '%6.2f %s%s/s'
  126. PREFIXES = ' kMGTPEZY'
  127. __slots__ = ('unit',)
  128. def __init__(self, unit='B'):
  129. self.unit = unit
  130. def update(self, pbar):
  131. """Updates the widget with the current SI prefixed speed."""
  132. if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0
  133. scaled = power = 0
  134. else:
  135. speed = pbar.currval / pbar.seconds_elapsed
  136. power = int(math.log(speed, 1000))
  137. scaled = speed / 1000.**power
  138. return self.FORMAT % (scaled, self.PREFIXES[power], self.unit)
  139. class AnimatedMarker(Widget):
  140. """An animated marker for the progress bar which defaults to appear as if
  141. it were rotating.
  142. """
  143. __slots__ = ('markers', 'curmark')
  144. def __init__(self, markers='|/-\\'):
  145. self.markers = markers
  146. self.curmark = -1
  147. def update(self, pbar):
  148. """Updates the widget to show the next marker or the first marker when
  149. finished"""
  150. if pbar.finished: return self.markers[0]
  151. self.curmark = (self.curmark + 1) % len(self.markers)
  152. return self.markers[self.curmark]
  153. # Alias for backwards compatibility
  154. RotatingMarker = AnimatedMarker
  155. class Counter(Widget):
  156. """Displays the current count."""
  157. __slots__ = ('format_string',)
  158. def __init__(self, format='%d'):
  159. self.format_string = format
  160. def update(self, pbar):
  161. return self.format_string % pbar.currval
  162. class Percentage(Widget):
  163. """Displays the current percentage as a number with a percent sign."""
  164. def update(self, pbar):
  165. return '%3d%%' % pbar.percentage()
  166. class FormatLabel(Timer):
  167. """Displays a formatted label."""
  168. mapping = {
  169. 'elapsed': ('seconds_elapsed', Timer.format_time),
  170. 'finished': ('finished', None),
  171. 'last_update': ('last_update_time', None),
  172. 'max': ('maxval', None),
  173. 'seconds': ('seconds_elapsed', None),
  174. 'start': ('start_time', None),
  175. 'value': ('currval', None)
  176. }
  177. __slots__ = ('format_string',)
  178. def __init__(self, format):
  179. self.format_string = format
  180. def update(self, pbar):
  181. context = {}
  182. for name, (key, transform) in self.mapping.items():
  183. try:
  184. value = getattr(pbar, key)
  185. if transform is None:
  186. context[name] = value
  187. else:
  188. context[name] = transform(value)
  189. except: pass
  190. return self.format_string % context
  191. class SimpleProgress(Widget):
  192. """Returns progress as a count of the total (e.g.: "5 of 47")."""
  193. __slots__ = ('sep',)
  194. def __init__(self, sep=' of '):
  195. self.sep = sep
  196. def update(self, pbar):
  197. return '%d%s%d' % (pbar.currval, self.sep, pbar.maxval)
  198. class Bar(WidgetHFill):
  199. """A progress bar which stretches to fill the line."""
  200. __slots__ = ('marker', 'left', 'right', 'fill', 'fill_left')
  201. def __init__(self, marker='#', left='|', right='|', fill=' ',
  202. fill_left=True):
  203. """Creates a customizable progress bar.
  204. marker - string or updatable object to use as a marker
  205. left - string or updatable object to use as a left border
  206. right - string or updatable object to use as a right border
  207. fill - character to use for the empty part of the progress bar
  208. fill_left - whether to fill from the left or the right
  209. """
  210. self.marker = marker
  211. self.left = left
  212. self.right = right
  213. self.fill = fill
  214. self.fill_left = fill_left
  215. def update(self, pbar, width):
  216. """Updates the progress bar and its subcomponents."""
  217. left, marked, right = (format_updatable(i, pbar) for i in
  218. (self.left, self.marker, self.right))
  219. width -= len(left) + len(right)
  220. # Marked must *always* have length of 1
  221. if pbar.maxval:
  222. marked *= int(pbar.currval / pbar.maxval * width)
  223. else:
  224. marked = ''
  225. if self.fill_left:
  226. return '%s%s%s' % (left, marked.ljust(width, self.fill), right)
  227. else:
  228. return '%s%s%s' % (left, marked.rjust(width, self.fill), right)
  229. class ReverseBar(Bar):
  230. """A bar which has a marker which bounces from side to side."""
  231. def __init__(self, marker='#', left='|', right='|', fill=' ',
  232. fill_left=False):
  233. """Creates a customizable progress bar.
  234. marker - string or updatable object to use as a marker
  235. left - string or updatable object to use as a left border
  236. right - string or updatable object to use as a right border
  237. fill - character to use for the empty part of the progress bar
  238. fill_left - whether to fill from the left or the right
  239. """
  240. self.marker = marker
  241. self.left = left
  242. self.right = right
  243. self.fill = fill
  244. self.fill_left = fill_left
  245. class BouncingBar(Bar):
  246. def update(self, pbar, width):
  247. """Updates the progress bar and its subcomponents."""
  248. left, marker, right = (format_updatable(i, pbar) for i in
  249. (self.left, self.marker, self.right))
  250. width -= len(left) + len(right)
  251. if pbar.finished: return '%s%s%s' % (left, width * marker, right)
  252. position = int(pbar.currval % (width * 2 - 1))
  253. if position > width: position = width * 2 - position
  254. lpad = self.fill * (position - 1)
  255. rpad = self.fill * (width - len(marker) - len(lpad))
  256. # Swap if we want to bounce the other way
  257. if not self.fill_left: rpad, lpad = lpad, rpad
  258. return '%s%s%s%s%s' % (left, lpad, marker, rpad, right)