progress.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702
  1. import io
  2. import sys
  3. import typing
  4. import warnings
  5. from abc import ABC, abstractmethod
  6. from collections import deque
  7. from dataclasses import dataclass, field
  8. from datetime import timedelta
  9. from io import RawIOBase, UnsupportedOperation
  10. from math import ceil
  11. from mmap import mmap
  12. from operator import length_hint
  13. from os import PathLike, stat
  14. from threading import Event, RLock, Thread
  15. from types import TracebackType
  16. from typing import (
  17. Any,
  18. BinaryIO,
  19. Callable,
  20. ContextManager,
  21. Deque,
  22. Dict,
  23. Generic,
  24. Iterable,
  25. List,
  26. NamedTuple,
  27. NewType,
  28. Optional,
  29. Sequence,
  30. TextIO,
  31. Tuple,
  32. Type,
  33. TypeVar,
  34. Union,
  35. )
  36. if sys.version_info >= (3, 8):
  37. from typing import Literal
  38. else:
  39. from pip._vendor.typing_extensions import Literal # pragma: no cover
  40. from . import filesize, get_console
  41. from .console import Console, Group, JustifyMethod, RenderableType
  42. from .highlighter import Highlighter
  43. from .jupyter import JupyterMixin
  44. from .live import Live
  45. from .progress_bar import ProgressBar
  46. from .spinner import Spinner
  47. from .style import StyleType
  48. from .table import Column, Table
  49. from .text import Text, TextType
  50. TaskID = NewType("TaskID", int)
  51. ProgressType = TypeVar("ProgressType")
  52. GetTimeCallable = Callable[[], float]
  53. _I = typing.TypeVar("_I", TextIO, BinaryIO)
  54. class _TrackThread(Thread):
  55. """A thread to periodically update progress."""
  56. def __init__(self, progress: "Progress", task_id: "TaskID", update_period: float):
  57. self.progress = progress
  58. self.task_id = task_id
  59. self.update_period = update_period
  60. self.done = Event()
  61. self.completed = 0
  62. super().__init__()
  63. def run(self) -> None:
  64. task_id = self.task_id
  65. advance = self.progress.advance
  66. update_period = self.update_period
  67. last_completed = 0
  68. wait = self.done.wait
  69. while not wait(update_period):
  70. completed = self.completed
  71. if last_completed != completed:
  72. advance(task_id, completed - last_completed)
  73. last_completed = completed
  74. self.progress.update(self.task_id, completed=self.completed, refresh=True)
  75. def __enter__(self) -> "_TrackThread":
  76. self.start()
  77. return self
  78. def __exit__(
  79. self,
  80. exc_type: Optional[Type[BaseException]],
  81. exc_val: Optional[BaseException],
  82. exc_tb: Optional[TracebackType],
  83. ) -> None:
  84. self.done.set()
  85. self.join()
  86. def track(
  87. sequence: Union[Sequence[ProgressType], Iterable[ProgressType]],
  88. description: str = "Working...",
  89. total: Optional[float] = None,
  90. auto_refresh: bool = True,
  91. console: Optional[Console] = None,
  92. transient: bool = False,
  93. get_time: Optional[Callable[[], float]] = None,
  94. refresh_per_second: float = 10,
  95. style: StyleType = "bar.back",
  96. complete_style: StyleType = "bar.complete",
  97. finished_style: StyleType = "bar.finished",
  98. pulse_style: StyleType = "bar.pulse",
  99. update_period: float = 0.1,
  100. disable: bool = False,
  101. show_speed: bool = True,
  102. ) -> Iterable[ProgressType]:
  103. """Track progress by iterating over a sequence.
  104. Args:
  105. sequence (Iterable[ProgressType]): A sequence (must support "len") you wish to iterate over.
  106. description (str, optional): Description of task show next to progress bar. Defaults to "Working".
  107. total: (float, optional): Total number of steps. Default is len(sequence).
  108. auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
  109. transient: (bool, optional): Clear the progress on exit. Defaults to False.
  110. console (Console, optional): Console to write to. Default creates internal Console instance.
  111. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
  112. style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
  113. complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
  114. finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
  115. pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
  116. update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
  117. disable (bool, optional): Disable display of progress.
  118. show_speed (bool, optional): Show speed if total isn't known. Defaults to True.
  119. Returns:
  120. Iterable[ProgressType]: An iterable of the values in the sequence.
  121. """
  122. columns: List["ProgressColumn"] = (
  123. [TextColumn("[progress.description]{task.description}")] if description else []
  124. )
  125. columns.extend(
  126. (
  127. BarColumn(
  128. style=style,
  129. complete_style=complete_style,
  130. finished_style=finished_style,
  131. pulse_style=pulse_style,
  132. ),
  133. TaskProgressColumn(show_speed=show_speed),
  134. TimeRemainingColumn(elapsed_when_finished=True),
  135. )
  136. )
  137. progress = Progress(
  138. *columns,
  139. auto_refresh=auto_refresh,
  140. console=console,
  141. transient=transient,
  142. get_time=get_time,
  143. refresh_per_second=refresh_per_second or 10,
  144. disable=disable,
  145. )
  146. with progress:
  147. yield from progress.track(
  148. sequence, total=total, description=description, update_period=update_period
  149. )
  150. class _Reader(RawIOBase, BinaryIO):
  151. """A reader that tracks progress while it's being read from."""
  152. def __init__(
  153. self,
  154. handle: BinaryIO,
  155. progress: "Progress",
  156. task: TaskID,
  157. close_handle: bool = True,
  158. ) -> None:
  159. self.handle = handle
  160. self.progress = progress
  161. self.task = task
  162. self.close_handle = close_handle
  163. self._closed = False
  164. def __enter__(self) -> "_Reader":
  165. self.handle.__enter__()
  166. return self
  167. def __exit__(
  168. self,
  169. exc_type: Optional[Type[BaseException]],
  170. exc_val: Optional[BaseException],
  171. exc_tb: Optional[TracebackType],
  172. ) -> None:
  173. self.close()
  174. def __iter__(self) -> BinaryIO:
  175. return self
  176. def __next__(self) -> bytes:
  177. line = next(self.handle)
  178. self.progress.advance(self.task, advance=len(line))
  179. return line
  180. @property
  181. def closed(self) -> bool:
  182. return self._closed
  183. def fileno(self) -> int:
  184. return self.handle.fileno()
  185. def isatty(self) -> bool:
  186. return self.handle.isatty()
  187. @property
  188. def mode(self) -> str:
  189. return self.handle.mode
  190. @property
  191. def name(self) -> str:
  192. return self.handle.name
  193. def readable(self) -> bool:
  194. return self.handle.readable()
  195. def seekable(self) -> bool:
  196. return self.handle.seekable()
  197. def writable(self) -> bool:
  198. return False
  199. def read(self, size: int = -1) -> bytes:
  200. block = self.handle.read(size)
  201. self.progress.advance(self.task, advance=len(block))
  202. return block
  203. def readinto(self, b: Union[bytearray, memoryview, mmap]): # type: ignore[no-untyped-def, override]
  204. n = self.handle.readinto(b) # type: ignore[attr-defined]
  205. self.progress.advance(self.task, advance=n)
  206. return n
  207. def readline(self, size: int = -1) -> bytes: # type: ignore[override]
  208. line = self.handle.readline(size)
  209. self.progress.advance(self.task, advance=len(line))
  210. return line
  211. def readlines(self, hint: int = -1) -> List[bytes]:
  212. lines = self.handle.readlines(hint)
  213. self.progress.advance(self.task, advance=sum(map(len, lines)))
  214. return lines
  215. def close(self) -> None:
  216. if self.close_handle:
  217. self.handle.close()
  218. self._closed = True
  219. def seek(self, offset: int, whence: int = 0) -> int:
  220. pos = self.handle.seek(offset, whence)
  221. self.progress.update(self.task, completed=pos)
  222. return pos
  223. def tell(self) -> int:
  224. return self.handle.tell()
  225. def write(self, s: Any) -> int:
  226. raise UnsupportedOperation("write")
  227. class _ReadContext(ContextManager[_I], Generic[_I]):
  228. """A utility class to handle a context for both a reader and a progress."""
  229. def __init__(self, progress: "Progress", reader: _I) -> None:
  230. self.progress = progress
  231. self.reader: _I = reader
  232. def __enter__(self) -> _I:
  233. self.progress.start()
  234. return self.reader.__enter__()
  235. def __exit__(
  236. self,
  237. exc_type: Optional[Type[BaseException]],
  238. exc_val: Optional[BaseException],
  239. exc_tb: Optional[TracebackType],
  240. ) -> None:
  241. self.progress.stop()
  242. self.reader.__exit__(exc_type, exc_val, exc_tb)
  243. def wrap_file(
  244. file: BinaryIO,
  245. total: int,
  246. *,
  247. description: str = "Reading...",
  248. auto_refresh: bool = True,
  249. console: Optional[Console] = None,
  250. transient: bool = False,
  251. get_time: Optional[Callable[[], float]] = None,
  252. refresh_per_second: float = 10,
  253. style: StyleType = "bar.back",
  254. complete_style: StyleType = "bar.complete",
  255. finished_style: StyleType = "bar.finished",
  256. pulse_style: StyleType = "bar.pulse",
  257. disable: bool = False,
  258. ) -> ContextManager[BinaryIO]:
  259. """Read bytes from a file while tracking progress.
  260. Args:
  261. file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
  262. total (int): Total number of bytes to read.
  263. description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
  264. auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
  265. transient: (bool, optional): Clear the progress on exit. Defaults to False.
  266. console (Console, optional): Console to write to. Default creates internal Console instance.
  267. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
  268. style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
  269. complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
  270. finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
  271. pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
  272. disable (bool, optional): Disable display of progress.
  273. Returns:
  274. ContextManager[BinaryIO]: A context manager yielding a progress reader.
  275. """
  276. columns: List["ProgressColumn"] = (
  277. [TextColumn("[progress.description]{task.description}")] if description else []
  278. )
  279. columns.extend(
  280. (
  281. BarColumn(
  282. style=style,
  283. complete_style=complete_style,
  284. finished_style=finished_style,
  285. pulse_style=pulse_style,
  286. ),
  287. DownloadColumn(),
  288. TimeRemainingColumn(),
  289. )
  290. )
  291. progress = Progress(
  292. *columns,
  293. auto_refresh=auto_refresh,
  294. console=console,
  295. transient=transient,
  296. get_time=get_time,
  297. refresh_per_second=refresh_per_second or 10,
  298. disable=disable,
  299. )
  300. reader = progress.wrap_file(file, total=total, description=description)
  301. return _ReadContext(progress, reader)
  302. @typing.overload
  303. def open(
  304. file: Union[str, "PathLike[str]", bytes],
  305. mode: Union[Literal["rt"], Literal["r"]],
  306. buffering: int = -1,
  307. encoding: Optional[str] = None,
  308. errors: Optional[str] = None,
  309. newline: Optional[str] = None,
  310. *,
  311. total: Optional[int] = None,
  312. description: str = "Reading...",
  313. auto_refresh: bool = True,
  314. console: Optional[Console] = None,
  315. transient: bool = False,
  316. get_time: Optional[Callable[[], float]] = None,
  317. refresh_per_second: float = 10,
  318. style: StyleType = "bar.back",
  319. complete_style: StyleType = "bar.complete",
  320. finished_style: StyleType = "bar.finished",
  321. pulse_style: StyleType = "bar.pulse",
  322. disable: bool = False,
  323. ) -> ContextManager[TextIO]:
  324. pass
  325. @typing.overload
  326. def open(
  327. file: Union[str, "PathLike[str]", bytes],
  328. mode: Literal["rb"],
  329. buffering: int = -1,
  330. encoding: Optional[str] = None,
  331. errors: Optional[str] = None,
  332. newline: Optional[str] = None,
  333. *,
  334. total: Optional[int] = None,
  335. description: str = "Reading...",
  336. auto_refresh: bool = True,
  337. console: Optional[Console] = None,
  338. transient: bool = False,
  339. get_time: Optional[Callable[[], float]] = None,
  340. refresh_per_second: float = 10,
  341. style: StyleType = "bar.back",
  342. complete_style: StyleType = "bar.complete",
  343. finished_style: StyleType = "bar.finished",
  344. pulse_style: StyleType = "bar.pulse",
  345. disable: bool = False,
  346. ) -> ContextManager[BinaryIO]:
  347. pass
  348. def open(
  349. file: Union[str, "PathLike[str]", bytes],
  350. mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
  351. buffering: int = -1,
  352. encoding: Optional[str] = None,
  353. errors: Optional[str] = None,
  354. newline: Optional[str] = None,
  355. *,
  356. total: Optional[int] = None,
  357. description: str = "Reading...",
  358. auto_refresh: bool = True,
  359. console: Optional[Console] = None,
  360. transient: bool = False,
  361. get_time: Optional[Callable[[], float]] = None,
  362. refresh_per_second: float = 10,
  363. style: StyleType = "bar.back",
  364. complete_style: StyleType = "bar.complete",
  365. finished_style: StyleType = "bar.finished",
  366. pulse_style: StyleType = "bar.pulse",
  367. disable: bool = False,
  368. ) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:
  369. """Read bytes from a file while tracking progress.
  370. Args:
  371. path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
  372. mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
  373. buffering (int): The buffering strategy to use, see :func:`io.open`.
  374. encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
  375. errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
  376. newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`
  377. total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.
  378. description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
  379. auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
  380. transient: (bool, optional): Clear the progress on exit. Defaults to False.
  381. console (Console, optional): Console to write to. Default creates internal Console instance.
  382. refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
  383. style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
  384. complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
  385. finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
  386. pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
  387. disable (bool, optional): Disable display of progress.
  388. encoding (str, optional): The encoding to use when reading in text mode.
  389. Returns:
  390. ContextManager[BinaryIO]: A context manager yielding a progress reader.
  391. """
  392. columns: List["ProgressColumn"] = (
  393. [TextColumn("[progress.description]{task.description}")] if description else []
  394. )
  395. columns.extend(
  396. (
  397. BarColumn(
  398. style=style,
  399. complete_style=complete_style,
  400. finished_style=finished_style,
  401. pulse_style=pulse_style,
  402. ),
  403. DownloadColumn(),
  404. TimeRemainingColumn(),
  405. )
  406. )
  407. progress = Progress(
  408. *columns,
  409. auto_refresh=auto_refresh,
  410. console=console,
  411. transient=transient,
  412. get_time=get_time,
  413. refresh_per_second=refresh_per_second or 10,
  414. disable=disable,
  415. )
  416. reader = progress.open(
  417. file,
  418. mode=mode,
  419. buffering=buffering,
  420. encoding=encoding,
  421. errors=errors,
  422. newline=newline,
  423. total=total,
  424. description=description,
  425. )
  426. return _ReadContext(progress, reader) # type: ignore[return-value, type-var]
  427. class ProgressColumn(ABC):
  428. """Base class for a widget to use in progress display."""
  429. max_refresh: Optional[float] = None
  430. def __init__(self, table_column: Optional[Column] = None) -> None:
  431. self._table_column = table_column
  432. self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}
  433. self._update_time: Optional[float] = None
  434. def get_table_column(self) -> Column:
  435. """Get a table column, used to build tasks table."""
  436. return self._table_column or Column()
  437. def __call__(self, task: "Task") -> RenderableType:
  438. """Called by the Progress object to return a renderable for the given task.
  439. Args:
  440. task (Task): An object containing information regarding the task.
  441. Returns:
  442. RenderableType: Anything renderable (including str).
  443. """
  444. current_time = task.get_time()
  445. if self.max_refresh is not None and not task.completed:
  446. try:
  447. timestamp, renderable = self._renderable_cache[task.id]
  448. except KeyError:
  449. pass
  450. else:
  451. if timestamp + self.max_refresh > current_time:
  452. return renderable
  453. renderable = self.render(task)
  454. self._renderable_cache[task.id] = (current_time, renderable)
  455. return renderable
  456. @abstractmethod
  457. def render(self, task: "Task") -> RenderableType:
  458. """Should return a renderable object."""
  459. class RenderableColumn(ProgressColumn):
  460. """A column to insert an arbitrary column.
  461. Args:
  462. renderable (RenderableType, optional): Any renderable. Defaults to empty string.
  463. """
  464. def __init__(
  465. self, renderable: RenderableType = "", *, table_column: Optional[Column] = None
  466. ):
  467. self.renderable = renderable
  468. super().__init__(table_column=table_column)
  469. def render(self, task: "Task") -> RenderableType:
  470. return self.renderable
  471. class SpinnerColumn(ProgressColumn):
  472. """A column with a 'spinner' animation.
  473. Args:
  474. spinner_name (str, optional): Name of spinner animation. Defaults to "dots".
  475. style (StyleType, optional): Style of spinner. Defaults to "progress.spinner".
  476. speed (float, optional): Speed factor of spinner. Defaults to 1.0.
  477. finished_text (TextType, optional): Text used when task is finished. Defaults to " ".
  478. """
  479. def __init__(
  480. self,
  481. spinner_name: str = "dots",
  482. style: Optional[StyleType] = "progress.spinner",
  483. speed: float = 1.0,
  484. finished_text: TextType = " ",
  485. table_column: Optional[Column] = None,
  486. ):
  487. self.spinner = Spinner(spinner_name, style=style, speed=speed)
  488. self.finished_text = (
  489. Text.from_markup(finished_text)
  490. if isinstance(finished_text, str)
  491. else finished_text
  492. )
  493. super().__init__(table_column=table_column)
  494. def set_spinner(
  495. self,
  496. spinner_name: str,
  497. spinner_style: Optional[StyleType] = "progress.spinner",
  498. speed: float = 1.0,
  499. ) -> None:
  500. """Set a new spinner.
  501. Args:
  502. spinner_name (str): Spinner name, see python -m rich.spinner.
  503. spinner_style (Optional[StyleType], optional): Spinner style. Defaults to "progress.spinner".
  504. speed (float, optional): Speed factor of spinner. Defaults to 1.0.
  505. """
  506. self.spinner = Spinner(spinner_name, style=spinner_style, speed=speed)
  507. def render(self, task: "Task") -> RenderableType:
  508. text = (
  509. self.finished_text
  510. if task.finished
  511. else self.spinner.render(task.get_time())
  512. )
  513. return text
  514. class TextColumn(ProgressColumn):
  515. """A column containing text."""
  516. def __init__(
  517. self,
  518. text_format: str,
  519. style: StyleType = "none",
  520. justify: JustifyMethod = "left",
  521. markup: bool = True,
  522. highlighter: Optional[Highlighter] = None,
  523. table_column: Optional[Column] = None,
  524. ) -> None:
  525. self.text_format = text_format
  526. self.justify: JustifyMethod = justify
  527. self.style = style
  528. self.markup = markup
  529. self.highlighter = highlighter
  530. super().__init__(table_column=table_column or Column(no_wrap=True))
  531. def render(self, task: "Task") -> Text:
  532. _text = self.text_format.format(task=task)
  533. if self.markup:
  534. text = Text.from_markup(_text, style=self.style, justify=self.justify)
  535. else:
  536. text = Text(_text, style=self.style, justify=self.justify)
  537. if self.highlighter:
  538. self.highlighter.highlight(text)
  539. return text
  540. class BarColumn(ProgressColumn):
  541. """Renders a visual progress bar.
  542. Args:
  543. bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.
  544. style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
  545. complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
  546. finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
  547. pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
  548. """
  549. def __init__(
  550. self,
  551. bar_width: Optional[int] = 40,
  552. style: StyleType = "bar.back",
  553. complete_style: StyleType = "bar.complete",
  554. finished_style: StyleType = "bar.finished",
  555. pulse_style: StyleType = "bar.pulse",
  556. table_column: Optional[Column] = None,
  557. ) -> None:
  558. self.bar_width = bar_width
  559. self.style = style
  560. self.complete_style = complete_style
  561. self.finished_style = finished_style
  562. self.pulse_style = pulse_style
  563. super().__init__(table_column=table_column)
  564. def render(self, task: "Task") -> ProgressBar:
  565. """Gets a progress bar widget for a task."""
  566. return ProgressBar(
  567. total=max(0, task.total) if task.total is not None else None,
  568. completed=max(0, task.completed),
  569. width=None if self.bar_width is None else max(1, self.bar_width),
  570. pulse=not task.started,
  571. animation_time=task.get_time(),
  572. style=self.style,
  573. complete_style=self.complete_style,
  574. finished_style=self.finished_style,
  575. pulse_style=self.pulse_style,
  576. )
  577. class TimeElapsedColumn(ProgressColumn):
  578. """Renders time elapsed."""
  579. def render(self, task: "Task") -> Text:
  580. """Show time elapsed."""
  581. elapsed = task.finished_time if task.finished else task.elapsed
  582. if elapsed is None:
  583. return Text("-:--:--", style="progress.elapsed")
  584. delta = timedelta(seconds=int(elapsed))
  585. return Text(str(delta), style="progress.elapsed")
  586. class TaskProgressColumn(TextColumn):
  587. """Show task progress as a percentage.
  588. Args:
  589. text_format (str, optional): Format for percentage display. Defaults to "[progress.percentage]{task.percentage:>3.0f}%".
  590. text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to "".
  591. style (StyleType, optional): Style of output. Defaults to "none".
  592. justify (JustifyMethod, optional): Text justification. Defaults to "left".
  593. markup (bool, optional): Enable markup. Defaults to True.
  594. highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.
  595. table_column (Optional[Column], optional): Table Column to use. Defaults to None.
  596. show_speed (bool, optional): Show speed if total is unknown. Defaults to False.
  597. """
  598. def __init__(
  599. self,
  600. text_format: str = "[progress.percentage]{task.percentage:>3.0f}%",
  601. text_format_no_percentage: str = "",
  602. style: StyleType = "none",
  603. justify: JustifyMethod = "left",
  604. markup: bool = True,
  605. highlighter: Optional[Highlighter] = None,
  606. table_column: Optional[Column] = None,
  607. show_speed: bool = False,
  608. ) -> None:
  609. self.text_format_no_percentage = text_format_no_percentage
  610. self.show_speed = show_speed
  611. super().__init__(
  612. text_format=text_format,
  613. style=style,
  614. justify=justify,
  615. markup=markup,
  616. highlighter=highlighter,
  617. table_column=table_column,
  618. )
  619. @classmethod
  620. def render_speed(cls, speed: Optional[float]) -> Text:
  621. """Render the speed in iterations per second.
  622. Args:
  623. task (Task): A Task object.
  624. Returns:
  625. Text: Text object containing the task speed.
  626. """
  627. if speed is None:
  628. return Text("", style="progress.percentage")
  629. unit, suffix = filesize.pick_unit_and_suffix(
  630. int(speed),
  631. ["", "×10³", "×10⁶", "×10⁹", "×10¹²"],
  632. 1000,
  633. )
  634. data_speed = speed / unit
  635. return Text(f"{data_speed:.1f}{suffix} it/s", style="progress.percentage")
  636. def render(self, task: "Task") -> Text:
  637. if task.total is None and self.show_speed:
  638. return self.render_speed(task.finished_speed or task.speed)
  639. text_format = (
  640. self.text_format_no_percentage if task.total is None else self.text_format
  641. )
  642. _text = text_format.format(task=task)
  643. if self.markup:
  644. text = Text.from_markup(_text, style=self.style, justify=self.justify)
  645. else:
  646. text = Text(_text, style=self.style, justify=self.justify)
  647. if self.highlighter:
  648. self.highlighter.highlight(text)
  649. return text
  650. class TimeRemainingColumn(ProgressColumn):
  651. """Renders estimated time remaining.
  652. Args:
  653. compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.
  654. elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.
  655. """
  656. # Only refresh twice a second to prevent jitter
  657. max_refresh = 0.5
  658. def __init__(
  659. self,
  660. compact: bool = False,
  661. elapsed_when_finished: bool = False,
  662. table_column: Optional[Column] = None,
  663. ):
  664. self.compact = compact
  665. self.elapsed_when_finished = elapsed_when_finished
  666. super().__init__(table_column=table_column)
  667. def render(self, task: "Task") -> Text:
  668. """Show time remaining."""
  669. if self.elapsed_when_finished and task.finished:
  670. task_time = task.finished_time
  671. style = "progress.elapsed"
  672. else:
  673. task_time = task.time_remaining
  674. style = "progress.remaining"
  675. if task.total is None:
  676. return Text("", style=style)
  677. if task_time is None:
  678. return Text("--:--" if self.compact else "-:--:--", style=style)
  679. # Based on https://github.com/tqdm/tqdm/blob/master/tqdm/std.py
  680. minutes, seconds = divmod(int(task_time), 60)
  681. hours, minutes = divmod(minutes, 60)
  682. if self.compact and not hours:
  683. formatted = f"{minutes:02d}:{seconds:02d}"
  684. else:
  685. formatted = f"{hours:d}:{minutes:02d}:{seconds:02d}"
  686. return Text(formatted, style=style)
  687. class FileSizeColumn(ProgressColumn):
  688. """Renders completed filesize."""
  689. def render(self, task: "Task") -> Text:
  690. """Show data completed."""
  691. data_size = filesize.decimal(int(task.completed))
  692. return Text(data_size, style="progress.filesize")
  693. class TotalFileSizeColumn(ProgressColumn):
  694. """Renders total filesize."""
  695. def render(self, task: "Task") -> Text:
  696. """Show data completed."""
  697. data_size = filesize.decimal(int(task.total)) if task.total is not None else ""
  698. return Text(data_size, style="progress.filesize.total")
  699. class MofNCompleteColumn(ProgressColumn):
  700. """Renders completed count/total, e.g. ' 10/1000'.
  701. Best for bounded tasks with int quantities.
  702. Space pads the completed count so that progress length does not change as task progresses
  703. past powers of 10.
  704. Args:
  705. separator (str, optional): Text to separate completed and total values. Defaults to "/".
  706. """
  707. def __init__(self, separator: str = "/", table_column: Optional[Column] = None):
  708. self.separator = separator
  709. super().__init__(table_column=table_column)
  710. def render(self, task: "Task") -> Text:
  711. """Show completed/total."""
  712. completed = int(task.completed)
  713. total = int(task.total) if task.total is not None else "?"
  714. total_width = len(str(total))
  715. return Text(
  716. f"{completed:{total_width}d}{self.separator}{total}",
  717. style="progress.download",
  718. )
  719. class DownloadColumn(ProgressColumn):
  720. """Renders file size downloaded and total, e.g. '0.5/2.3 GB'.
  721. Args:
  722. binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.
  723. """
  724. def __init__(
  725. self, binary_units: bool = False, table_column: Optional[Column] = None
  726. ) -> None:
  727. self.binary_units = binary_units
  728. super().__init__(table_column=table_column)
  729. def render(self, task: "Task") -> Text:
  730. """Calculate common unit for completed and total."""
  731. completed = int(task.completed)
  732. unit_and_suffix_calculation_base = (
  733. int(task.total) if task.total is not None else completed
  734. )
  735. if self.binary_units:
  736. unit, suffix = filesize.pick_unit_and_suffix(
  737. unit_and_suffix_calculation_base,
  738. ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"],
  739. 1024,
  740. )
  741. else:
  742. unit, suffix = filesize.pick_unit_and_suffix(
  743. unit_and_suffix_calculation_base,
  744. ["bytes", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
  745. 1000,
  746. )
  747. precision = 0 if unit == 1 else 1
  748. completed_ratio = completed / unit
  749. completed_str = f"{completed_ratio:,.{precision}f}"
  750. if task.total is not None:
  751. total = int(task.total)
  752. total_ratio = total / unit
  753. total_str = f"{total_ratio:,.{precision}f}"
  754. else:
  755. total_str = "?"
  756. download_status = f"{completed_str}/{total_str} {suffix}"
  757. download_text = Text(download_status, style="progress.download")
  758. return download_text
  759. class TransferSpeedColumn(ProgressColumn):
  760. """Renders human readable transfer speed."""
  761. def render(self, task: "Task") -> Text:
  762. """Show data transfer speed."""
  763. speed = task.finished_speed or task.speed
  764. if speed is None:
  765. return Text("?", style="progress.data.speed")
  766. data_speed = filesize.decimal(int(speed))
  767. return Text(f"{data_speed}/s", style="progress.data.speed")
  768. class ProgressSample(NamedTuple):
  769. """Sample of progress for a given time."""
  770. timestamp: float
  771. """Timestamp of sample."""
  772. completed: float
  773. """Number of steps completed."""
  774. @dataclass
  775. class Task:
  776. """Information regarding a progress task.
  777. This object should be considered read-only outside of the :class:`~Progress` class.
  778. """
  779. id: TaskID
  780. """Task ID associated with this task (used in Progress methods)."""
  781. description: str
  782. """str: Description of the task."""
  783. total: Optional[float]
  784. """Optional[float]: Total number of steps in this task."""
  785. completed: float
  786. """float: Number of steps completed"""
  787. _get_time: GetTimeCallable
  788. """Callable to get the current time."""
  789. finished_time: Optional[float] = None
  790. """float: Time task was finished."""
  791. visible: bool = True
  792. """bool: Indicates if this task is visible in the progress display."""
  793. fields: Dict[str, Any] = field(default_factory=dict)
  794. """dict: Arbitrary fields passed in via Progress.update."""
  795. start_time: Optional[float] = field(default=None, init=False, repr=False)
  796. """Optional[float]: Time this task was started, or None if not started."""
  797. stop_time: Optional[float] = field(default=None, init=False, repr=False)
  798. """Optional[float]: Time this task was stopped, or None if not stopped."""
  799. finished_speed: Optional[float] = None
  800. """Optional[float]: The last speed for a finished task."""
  801. _progress: Deque[ProgressSample] = field(
  802. default_factory=lambda: deque(maxlen=1000), init=False, repr=False
  803. )
  804. _lock: RLock = field(repr=False, default_factory=RLock)
  805. """Thread lock."""
  806. def get_time(self) -> float:
  807. """float: Get the current time, in seconds."""
  808. return self._get_time()
  809. @property
  810. def started(self) -> bool:
  811. """bool: Check if the task as started."""
  812. return self.start_time is not None
  813. @property
  814. def remaining(self) -> Optional[float]:
  815. """Optional[float]: Get the number of steps remaining, if a non-None total was set."""
  816. if self.total is None:
  817. return None
  818. return self.total - self.completed
  819. @property
  820. def elapsed(self) -> Optional[float]:
  821. """Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started."""
  822. if self.start_time is None:
  823. return None
  824. if self.stop_time is not None:
  825. return self.stop_time - self.start_time
  826. return self.get_time() - self.start_time
  827. @property
  828. def finished(self) -> bool:
  829. """Check if the task has finished."""
  830. return self.finished_time is not None
  831. @property
  832. def percentage(self) -> float:
  833. """float: Get progress of task as a percentage. If a None total was set, returns 0"""
  834. if not self.total:
  835. return 0.0
  836. completed = (self.completed / self.total) * 100.0
  837. completed = min(100.0, max(0.0, completed))
  838. return completed
  839. @property
  840. def speed(self) -> Optional[float]:
  841. """Optional[float]: Get the estimated speed in steps per second."""
  842. if self.start_time is None:
  843. return None
  844. with self._lock:
  845. progress = self._progress
  846. if not progress:
  847. return None
  848. total_time = progress[-1].timestamp - progress[0].timestamp
  849. if total_time == 0:
  850. return None
  851. iter_progress = iter(progress)
  852. next(iter_progress)
  853. total_completed = sum(sample.completed for sample in iter_progress)
  854. speed = total_completed / total_time
  855. return speed
  856. @property
  857. def time_remaining(self) -> Optional[float]:
  858. """Optional[float]: Get estimated time to completion, or ``None`` if no data."""
  859. if self.finished:
  860. return 0.0
  861. speed = self.speed
  862. if not speed:
  863. return None
  864. remaining = self.remaining
  865. if remaining is None:
  866. return None
  867. estimate = ceil(remaining / speed)
  868. return estimate
  869. def _reset(self) -> None:
  870. """Reset progress."""
  871. self._progress.clear()
  872. self.finished_time = None
  873. self.finished_speed = None
  874. class Progress(JupyterMixin):
  875. """Renders an auto-updating progress bar(s).
  876. Args:
  877. console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
  878. auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.
  879. refresh_per_second (Optional[float], optional): Number of times per second to refresh the progress information or None to use default (10). Defaults to None.
  880. speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.
  881. transient: (bool, optional): Clear the progress on exit. Defaults to False.
  882. redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
  883. redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.
  884. get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.
  885. disable (bool, optional): Disable progress display. Defaults to False
  886. expand (bool, optional): Expand tasks table to fit width. Defaults to False.
  887. """
  888. def __init__(
  889. self,
  890. *columns: Union[str, ProgressColumn],
  891. console: Optional[Console] = None,
  892. auto_refresh: bool = True,
  893. refresh_per_second: float = 10,
  894. speed_estimate_period: float = 30.0,
  895. transient: bool = False,
  896. redirect_stdout: bool = True,
  897. redirect_stderr: bool = True,
  898. get_time: Optional[GetTimeCallable] = None,
  899. disable: bool = False,
  900. expand: bool = False,
  901. ) -> None:
  902. assert refresh_per_second > 0, "refresh_per_second must be > 0"
  903. self._lock = RLock()
  904. self.columns = columns or self.get_default_columns()
  905. self.speed_estimate_period = speed_estimate_period
  906. self.disable = disable
  907. self.expand = expand
  908. self._tasks: Dict[TaskID, Task] = {}
  909. self._task_index: TaskID = TaskID(0)
  910. self.live = Live(
  911. console=console or get_console(),
  912. auto_refresh=auto_refresh,
  913. refresh_per_second=refresh_per_second,
  914. transient=transient,
  915. redirect_stdout=redirect_stdout,
  916. redirect_stderr=redirect_stderr,
  917. get_renderable=self.get_renderable,
  918. )
  919. self.get_time = get_time or self.console.get_time
  920. self.print = self.console.print
  921. self.log = self.console.log
  922. @classmethod
  923. def get_default_columns(cls) -> Tuple[ProgressColumn, ...]:
  924. """Get the default columns used for a new Progress instance:
  925. - a text column for the description (TextColumn)
  926. - the bar itself (BarColumn)
  927. - a text column showing completion percentage (TextColumn)
  928. - an estimated-time-remaining column (TimeRemainingColumn)
  929. If the Progress instance is created without passing a columns argument,
  930. the default columns defined here will be used.
  931. You can also create a Progress instance using custom columns before
  932. and/or after the defaults, as in this example:
  933. progress = Progress(
  934. SpinnerColumn(),
  935. *Progress.default_columns(),
  936. "Elapsed:",
  937. TimeElapsedColumn(),
  938. )
  939. This code shows the creation of a Progress display, containing
  940. a spinner to the left, the default columns, and a labeled elapsed
  941. time column.
  942. """
  943. return (
  944. TextColumn("[progress.description]{task.description}"),
  945. BarColumn(),
  946. TaskProgressColumn(),
  947. TimeRemainingColumn(),
  948. )
  949. @property
  950. def console(self) -> Console:
  951. return self.live.console
  952. @property
  953. def tasks(self) -> List[Task]:
  954. """Get a list of Task instances."""
  955. with self._lock:
  956. return list(self._tasks.values())
  957. @property
  958. def task_ids(self) -> List[TaskID]:
  959. """A list of task IDs."""
  960. with self._lock:
  961. return list(self._tasks.keys())
  962. @property
  963. def finished(self) -> bool:
  964. """Check if all tasks have been completed."""
  965. with self._lock:
  966. if not self._tasks:
  967. return True
  968. return all(task.finished for task in self._tasks.values())
  969. def start(self) -> None:
  970. """Start the progress display."""
  971. if not self.disable:
  972. self.live.start(refresh=True)
  973. def stop(self) -> None:
  974. """Stop the progress display."""
  975. self.live.stop()
  976. if not self.console.is_interactive:
  977. self.console.print()
  978. def __enter__(self) -> "Progress":
  979. self.start()
  980. return self
  981. def __exit__(
  982. self,
  983. exc_type: Optional[Type[BaseException]],
  984. exc_val: Optional[BaseException],
  985. exc_tb: Optional[TracebackType],
  986. ) -> None:
  987. self.stop()
  988. def track(
  989. self,
  990. sequence: Union[Iterable[ProgressType], Sequence[ProgressType]],
  991. total: Optional[float] = None,
  992. task_id: Optional[TaskID] = None,
  993. description: str = "Working...",
  994. update_period: float = 0.1,
  995. ) -> Iterable[ProgressType]:
  996. """Track progress by iterating over a sequence.
  997. Args:
  998. sequence (Sequence[ProgressType]): A sequence of values you want to iterate over and track progress.
  999. total: (float, optional): Total number of steps. Default is len(sequence).
  1000. task_id: (TaskID): Task to track. Default is new task.
  1001. description: (str, optional): Description of task, if new task is created.
  1002. update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
  1003. Returns:
  1004. Iterable[ProgressType]: An iterable of values taken from the provided sequence.
  1005. """
  1006. if total is None:
  1007. total = float(length_hint(sequence)) or None
  1008. if task_id is None:
  1009. task_id = self.add_task(description, total=total)
  1010. else:
  1011. self.update(task_id, total=total)
  1012. if self.live.auto_refresh:
  1013. with _TrackThread(self, task_id, update_period) as track_thread:
  1014. for value in sequence:
  1015. yield value
  1016. track_thread.completed += 1
  1017. else:
  1018. advance = self.advance
  1019. refresh = self.refresh
  1020. for value in sequence:
  1021. yield value
  1022. advance(task_id, 1)
  1023. refresh()
  1024. def wrap_file(
  1025. self,
  1026. file: BinaryIO,
  1027. total: Optional[int] = None,
  1028. *,
  1029. task_id: Optional[TaskID] = None,
  1030. description: str = "Reading...",
  1031. ) -> BinaryIO:
  1032. """Track progress file reading from a binary file.
  1033. Args:
  1034. file (BinaryIO): A file-like object opened in binary mode.
  1035. total (int, optional): Total number of bytes to read. This must be provided unless a task with a total is also given.
  1036. task_id (TaskID): Task to track. Default is new task.
  1037. description (str, optional): Description of task, if new task is created.
  1038. Returns:
  1039. BinaryIO: A readable file-like object in binary mode.
  1040. Raises:
  1041. ValueError: When no total value can be extracted from the arguments or the task.
  1042. """
  1043. # attempt to recover the total from the task
  1044. total_bytes: Optional[float] = None
  1045. if total is not None:
  1046. total_bytes = total
  1047. elif task_id is not None:
  1048. with self._lock:
  1049. total_bytes = self._tasks[task_id].total
  1050. if total_bytes is None:
  1051. raise ValueError(
  1052. f"unable to get the total number of bytes, please specify 'total'"
  1053. )
  1054. # update total of task or create new task
  1055. if task_id is None:
  1056. task_id = self.add_task(description, total=total_bytes)
  1057. else:
  1058. self.update(task_id, total=total_bytes)
  1059. return _Reader(file, self, task_id, close_handle=False)
  1060. @typing.overload
  1061. def open(
  1062. self,
  1063. file: Union[str, "PathLike[str]", bytes],
  1064. mode: Literal["rb"],
  1065. buffering: int = -1,
  1066. encoding: Optional[str] = None,
  1067. errors: Optional[str] = None,
  1068. newline: Optional[str] = None,
  1069. *,
  1070. total: Optional[int] = None,
  1071. task_id: Optional[TaskID] = None,
  1072. description: str = "Reading...",
  1073. ) -> BinaryIO:
  1074. pass
  1075. @typing.overload
  1076. def open(
  1077. self,
  1078. file: Union[str, "PathLike[str]", bytes],
  1079. mode: Union[Literal["r"], Literal["rt"]],
  1080. buffering: int = -1,
  1081. encoding: Optional[str] = None,
  1082. errors: Optional[str] = None,
  1083. newline: Optional[str] = None,
  1084. *,
  1085. total: Optional[int] = None,
  1086. task_id: Optional[TaskID] = None,
  1087. description: str = "Reading...",
  1088. ) -> TextIO:
  1089. pass
  1090. def open(
  1091. self,
  1092. file: Union[str, "PathLike[str]", bytes],
  1093. mode: Union[Literal["rb"], Literal["rt"], Literal["r"]] = "r",
  1094. buffering: int = -1,
  1095. encoding: Optional[str] = None,
  1096. errors: Optional[str] = None,
  1097. newline: Optional[str] = None,
  1098. *,
  1099. total: Optional[int] = None,
  1100. task_id: Optional[TaskID] = None,
  1101. description: str = "Reading...",
  1102. ) -> Union[BinaryIO, TextIO]:
  1103. """Track progress while reading from a binary file.
  1104. Args:
  1105. path (Union[str, PathLike[str]]): The path to the file to read.
  1106. mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
  1107. buffering (int): The buffering strategy to use, see :func:`io.open`.
  1108. encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
  1109. errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
  1110. newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`.
  1111. total (int, optional): Total number of bytes to read. If none given, os.stat(path).st_size is used.
  1112. task_id (TaskID): Task to track. Default is new task.
  1113. description (str, optional): Description of task, if new task is created.
  1114. Returns:
  1115. BinaryIO: A readable file-like object in binary mode.
  1116. Raises:
  1117. ValueError: When an invalid mode is given.
  1118. """
  1119. # normalize the mode (always rb, rt)
  1120. _mode = "".join(sorted(mode, reverse=False))
  1121. if _mode not in ("br", "rt", "r"):
  1122. raise ValueError("invalid mode {!r}".format(mode))
  1123. # patch buffering to provide the same behaviour as the builtin `open`
  1124. line_buffering = buffering == 1
  1125. if _mode == "br" and buffering == 1:
  1126. warnings.warn(
  1127. "line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used",
  1128. RuntimeWarning,
  1129. )
  1130. buffering = -1
  1131. elif _mode in ("rt", "r"):
  1132. if buffering == 0:
  1133. raise ValueError("can't have unbuffered text I/O")
  1134. elif buffering == 1:
  1135. buffering = -1
  1136. # attempt to get the total with `os.stat`
  1137. if total is None:
  1138. total = stat(file).st_size
  1139. # update total of task or create new task
  1140. if task_id is None:
  1141. task_id = self.add_task(description, total=total)
  1142. else:
  1143. self.update(task_id, total=total)
  1144. # open the file in binary mode,
  1145. handle = io.open(file, "rb", buffering=buffering)
  1146. reader = _Reader(handle, self, task_id, close_handle=True)
  1147. # wrap the reader in a `TextIOWrapper` if text mode
  1148. if mode in ("r", "rt"):
  1149. return io.TextIOWrapper(
  1150. reader,
  1151. encoding=encoding,
  1152. errors=errors,
  1153. newline=newline,
  1154. line_buffering=line_buffering,
  1155. )
  1156. return reader
  1157. def start_task(self, task_id: TaskID) -> None:
  1158. """Start a task.
  1159. Starts a task (used when calculating elapsed time). You may need to call this manually,
  1160. if you called ``add_task`` with ``start=False``.
  1161. Args:
  1162. task_id (TaskID): ID of task.
  1163. """
  1164. with self._lock:
  1165. task = self._tasks[task_id]
  1166. if task.start_time is None:
  1167. task.start_time = self.get_time()
  1168. def stop_task(self, task_id: TaskID) -> None:
  1169. """Stop a task.
  1170. This will freeze the elapsed time on the task.
  1171. Args:
  1172. task_id (TaskID): ID of task.
  1173. """
  1174. with self._lock:
  1175. task = self._tasks[task_id]
  1176. current_time = self.get_time()
  1177. if task.start_time is None:
  1178. task.start_time = current_time
  1179. task.stop_time = current_time
  1180. def update(
  1181. self,
  1182. task_id: TaskID,
  1183. *,
  1184. total: Optional[float] = None,
  1185. completed: Optional[float] = None,
  1186. advance: Optional[float] = None,
  1187. description: Optional[str] = None,
  1188. visible: Optional[bool] = None,
  1189. refresh: bool = False,
  1190. **fields: Any,
  1191. ) -> None:
  1192. """Update information associated with a task.
  1193. Args:
  1194. task_id (TaskID): Task id (returned by add_task).
  1195. total (float, optional): Updates task.total if not None.
  1196. completed (float, optional): Updates task.completed if not None.
  1197. advance (float, optional): Add a value to task.completed if not None.
  1198. description (str, optional): Change task description if not None.
  1199. visible (bool, optional): Set visible flag if not None.
  1200. refresh (bool): Force a refresh of progress information. Default is False.
  1201. **fields (Any): Additional data fields required for rendering.
  1202. """
  1203. with self._lock:
  1204. task = self._tasks[task_id]
  1205. completed_start = task.completed
  1206. if total is not None and total != task.total:
  1207. task.total = total
  1208. task._reset()
  1209. if advance is not None:
  1210. task.completed += advance
  1211. if completed is not None:
  1212. task.completed = completed
  1213. if description is not None:
  1214. task.description = description
  1215. if visible is not None:
  1216. task.visible = visible
  1217. task.fields.update(fields)
  1218. update_completed = task.completed - completed_start
  1219. current_time = self.get_time()
  1220. old_sample_time = current_time - self.speed_estimate_period
  1221. _progress = task._progress
  1222. popleft = _progress.popleft
  1223. while _progress and _progress[0].timestamp < old_sample_time:
  1224. popleft()
  1225. if update_completed > 0:
  1226. _progress.append(ProgressSample(current_time, update_completed))
  1227. if (
  1228. task.total is not None
  1229. and task.completed >= task.total
  1230. and task.finished_time is None
  1231. ):
  1232. task.finished_time = task.elapsed
  1233. if refresh:
  1234. self.refresh()
  1235. def reset(
  1236. self,
  1237. task_id: TaskID,
  1238. *,
  1239. start: bool = True,
  1240. total: Optional[float] = None,
  1241. completed: int = 0,
  1242. visible: Optional[bool] = None,
  1243. description: Optional[str] = None,
  1244. **fields: Any,
  1245. ) -> None:
  1246. """Reset a task so completed is 0 and the clock is reset.
  1247. Args:
  1248. task_id (TaskID): ID of task.
  1249. start (bool, optional): Start the task after reset. Defaults to True.
  1250. total (float, optional): New total steps in task, or None to use current total. Defaults to None.
  1251. completed (int, optional): Number of steps completed. Defaults to 0.
  1252. visible (bool, optional): Enable display of the task. Defaults to True.
  1253. description (str, optional): Change task description if not None. Defaults to None.
  1254. **fields (str): Additional data fields required for rendering.
  1255. """
  1256. current_time = self.get_time()
  1257. with self._lock:
  1258. task = self._tasks[task_id]
  1259. task._reset()
  1260. task.start_time = current_time if start else None
  1261. if total is not None:
  1262. task.total = total
  1263. task.completed = completed
  1264. if visible is not None:
  1265. task.visible = visible
  1266. if fields:
  1267. task.fields = fields
  1268. if description is not None:
  1269. task.description = description
  1270. task.finished_time = None
  1271. self.refresh()
  1272. def advance(self, task_id: TaskID, advance: float = 1) -> None:
  1273. """Advance task by a number of steps.
  1274. Args:
  1275. task_id (TaskID): ID of task.
  1276. advance (float): Number of steps to advance. Default is 1.
  1277. """
  1278. current_time = self.get_time()
  1279. with self._lock:
  1280. task = self._tasks[task_id]
  1281. completed_start = task.completed
  1282. task.completed += advance
  1283. update_completed = task.completed - completed_start
  1284. old_sample_time = current_time - self.speed_estimate_period
  1285. _progress = task._progress
  1286. popleft = _progress.popleft
  1287. while _progress and _progress[0].timestamp < old_sample_time:
  1288. popleft()
  1289. while len(_progress) > 1000:
  1290. popleft()
  1291. _progress.append(ProgressSample(current_time, update_completed))
  1292. if (
  1293. task.total is not None
  1294. and task.completed >= task.total
  1295. and task.finished_time is None
  1296. ):
  1297. task.finished_time = task.elapsed
  1298. task.finished_speed = task.speed
  1299. def refresh(self) -> None:
  1300. """Refresh (render) the progress information."""
  1301. if not self.disable and self.live.is_started:
  1302. self.live.refresh()
  1303. def get_renderable(self) -> RenderableType:
  1304. """Get a renderable for the progress display."""
  1305. renderable = Group(*self.get_renderables())
  1306. return renderable
  1307. def get_renderables(self) -> Iterable[RenderableType]:
  1308. """Get a number of renderables for the progress display."""
  1309. table = self.make_tasks_table(self.tasks)
  1310. yield table
  1311. def make_tasks_table(self, tasks: Iterable[Task]) -> Table:
  1312. """Get a table to render the Progress display.
  1313. Args:
  1314. tasks (Iterable[Task]): An iterable of Task instances, one per row of the table.
  1315. Returns:
  1316. Table: A table instance.
  1317. """
  1318. table_columns = (
  1319. (
  1320. Column(no_wrap=True)
  1321. if isinstance(_column, str)
  1322. else _column.get_table_column().copy()
  1323. )
  1324. for _column in self.columns
  1325. )
  1326. table = Table.grid(*table_columns, padding=(0, 1), expand=self.expand)
  1327. for task in tasks:
  1328. if task.visible:
  1329. table.add_row(
  1330. *(
  1331. (
  1332. column.format(task=task)
  1333. if isinstance(column, str)
  1334. else column(task)
  1335. )
  1336. for column in self.columns
  1337. )
  1338. )
  1339. return table
  1340. def __rich__(self) -> RenderableType:
  1341. """Makes the Progress class itself renderable."""
  1342. with self._lock:
  1343. return self.get_renderable()
  1344. def add_task(
  1345. self,
  1346. description: str,
  1347. start: bool = True,
  1348. total: Optional[float] = 100.0,
  1349. completed: int = 0,
  1350. visible: bool = True,
  1351. **fields: Any,
  1352. ) -> TaskID:
  1353. """Add a new 'task' to the Progress display.
  1354. Args:
  1355. description (str): A description of the task.
  1356. start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,
  1357. you will need to call `start` manually. Defaults to True.
  1358. total (float, optional): Number of total steps in the progress if known.
  1359. Set to None to render a pulsing animation. Defaults to 100.
  1360. completed (int, optional): Number of steps completed so far. Defaults to 0.
  1361. visible (bool, optional): Enable display of the task. Defaults to True.
  1362. **fields (str): Additional data fields required for rendering.
  1363. Returns:
  1364. TaskID: An ID you can use when calling `update`.
  1365. """
  1366. with self._lock:
  1367. task = Task(
  1368. self._task_index,
  1369. description,
  1370. total,
  1371. completed,
  1372. visible=visible,
  1373. fields=fields,
  1374. _get_time=self.get_time,
  1375. _lock=self._lock,
  1376. )
  1377. self._tasks[self._task_index] = task
  1378. if start:
  1379. self.start_task(self._task_index)
  1380. new_task_index = self._task_index
  1381. self._task_index = TaskID(int(self._task_index) + 1)
  1382. self.refresh()
  1383. return new_task_index
  1384. def remove_task(self, task_id: TaskID) -> None:
  1385. """Delete a task if it exists.
  1386. Args:
  1387. task_id (TaskID): A task ID.
  1388. """
  1389. with self._lock:
  1390. del self._tasks[task_id]
  1391. if __name__ == "__main__": # pragma: no coverage
  1392. import random
  1393. import time
  1394. from .panel import Panel
  1395. from .rule import Rule
  1396. from .syntax import Syntax
  1397. from .table import Table
  1398. syntax = Syntax(
  1399. '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
  1400. """Iterate and generate a tuple with a flag for last value."""
  1401. iter_values = iter(values)
  1402. try:
  1403. previous_value = next(iter_values)
  1404. except StopIteration:
  1405. return
  1406. for value in iter_values:
  1407. yield False, previous_value
  1408. previous_value = value
  1409. yield True, previous_value''',
  1410. "python",
  1411. line_numbers=True,
  1412. )
  1413. table = Table("foo", "bar", "baz")
  1414. table.add_row("1", "2", "3")
  1415. progress_renderables = [
  1416. "Text may be printed while the progress bars are rendering.",
  1417. Panel("In fact, [i]any[/i] renderable will work"),
  1418. "Such as [magenta]tables[/]...",
  1419. table,
  1420. "Pretty printed structures...",
  1421. {"type": "example", "text": "Pretty printed"},
  1422. "Syntax...",
  1423. syntax,
  1424. Rule("Give it a try!"),
  1425. ]
  1426. from itertools import cycle
  1427. examples = cycle(progress_renderables)
  1428. console = Console(record=True)
  1429. with Progress(
  1430. SpinnerColumn(),
  1431. *Progress.get_default_columns(),
  1432. TimeElapsedColumn(),
  1433. console=console,
  1434. transient=False,
  1435. ) as progress:
  1436. task1 = progress.add_task("[red]Downloading", total=1000)
  1437. task2 = progress.add_task("[green]Processing", total=1000)
  1438. task3 = progress.add_task("[yellow]Thinking", total=None)
  1439. while not progress.finished:
  1440. progress.update(task1, advance=0.5)
  1441. progress.update(task2, advance=0.3)
  1442. time.sleep(0.01)
  1443. if random.randint(0, 100) < 1:
  1444. progress.log(next(examples))