widgets.py 12 KB

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