Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

1716 řádky
59 KiB

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