tqdm.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License
  14. """Utility helpers to handle progress bars in `huggingface_hub`.
  15. Example:
  16. 1. Use `huggingface_hub.utils.tqdm` as you would use `tqdm.tqdm` or `tqdm.auto.tqdm`.
  17. 2. To disable progress bars, either use `disable_progress_bars()` helper or set the
  18. environment variable `HF_HUB_DISABLE_PROGRESS_BARS` to 1.
  19. 3. To re-enable progress bars, use `enable_progress_bars()`.
  20. 4. To check whether progress bars are disabled, use `are_progress_bars_disabled()`.
  21. NOTE: Environment variable `HF_HUB_DISABLE_PROGRESS_BARS` has the priority.
  22. Example:
  23. ```py
  24. >>> from huggingface_hub.utils import are_progress_bars_disabled, disable_progress_bars, enable_progress_bars, tqdm
  25. # Disable progress bars globally
  26. >>> disable_progress_bars()
  27. # Use as normal `tqdm`
  28. >>> for _ in tqdm(range(5)):
  29. ... pass
  30. # Still not showing progress bars, as `disable=False` is overwritten to `True`.
  31. >>> for _ in tqdm(range(5), disable=False):
  32. ... pass
  33. >>> are_progress_bars_disabled()
  34. True
  35. # Re-enable progress bars globally
  36. >>> enable_progress_bars()
  37. # Progress bar will be shown !
  38. >>> for _ in tqdm(range(5)):
  39. ... pass
  40. 100%|███████████████████████████████████████| 5/5 [00:00<00:00, 117817.53it/s]
  41. ```
  42. Group-based control:
  43. ```python
  44. # Disable progress bars for a specific group
  45. >>> disable_progress_bars("peft.foo")
  46. # Check state of different groups
  47. >>> assert not are_progress_bars_disabled("peft"))
  48. >>> assert not are_progress_bars_disabled("peft.something")
  49. >>> assert are_progress_bars_disabled("peft.foo"))
  50. >>> assert are_progress_bars_disabled("peft.foo.bar"))
  51. # Enable progress bars for a subgroup
  52. >>> enable_progress_bars("peft.foo.bar")
  53. # Check if enabling a subgroup affects the parent group
  54. >>> assert are_progress_bars_disabled("peft.foo"))
  55. >>> assert not are_progress_bars_disabled("peft.foo.bar"))
  56. # No progress bar for `name="peft.foo"`
  57. >>> for _ in tqdm(range(5), name="peft.foo"):
  58. ... pass
  59. # Progress bar will be shown for `name="peft.foo.bar"`
  60. >>> for _ in tqdm(range(5), name="peft.foo.bar"):
  61. ... pass
  62. 100%|███████████████████████████████████████| 5/5 [00:00<00:00, 117817.53it/s]
  63. ```
  64. """
  65. import io
  66. import logging
  67. import os
  68. import warnings
  69. from collections.abc import Iterator
  70. from contextlib import contextmanager, nullcontext
  71. from pathlib import Path
  72. from typing import ContextManager
  73. from tqdm.auto import tqdm as old_tqdm
  74. from ..constants import HF_HUB_DISABLE_PROGRESS_BARS
  75. # The `HF_HUB_DISABLE_PROGRESS_BARS` environment variable can be True, False, or not set (None),
  76. # allowing for control over progress bar visibility. When set, this variable takes precedence
  77. # over programmatic settings, dictating whether progress bars should be shown or hidden globally.
  78. # Essentially, the environment variable's setting overrides any code-based configurations.
  79. #
  80. # If `HF_HUB_DISABLE_PROGRESS_BARS` is not defined (None), it implies that users can manage
  81. # progress bar visibility through code. By default, progress bars are turned on.
  82. progress_bar_states: dict[str, bool] = {}
  83. def disable_progress_bars(name: str | None = None) -> None:
  84. """
  85. Disable progress bars either globally or for a specified group.
  86. This function updates the state of progress bars based on a group name.
  87. If no group name is provided, all progress bars are disabled. The operation
  88. respects the `HF_HUB_DISABLE_PROGRESS_BARS` environment variable's setting.
  89. Args:
  90. name (`str`, *optional*):
  91. The name of the group for which to disable the progress bars. If None,
  92. progress bars are disabled globally.
  93. Raises:
  94. Warning: If the environment variable precludes changes.
  95. """
  96. if HF_HUB_DISABLE_PROGRESS_BARS is False:
  97. warnings.warn(
  98. "Cannot disable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=0` is set and has priority."
  99. )
  100. return
  101. if name is None:
  102. progress_bar_states.clear()
  103. progress_bar_states["_global"] = False
  104. else:
  105. keys_to_remove = [key for key in progress_bar_states if key.startswith(f"{name}.")]
  106. for key in keys_to_remove:
  107. del progress_bar_states[key]
  108. progress_bar_states[name] = False
  109. def enable_progress_bars(name: str | None = None) -> None:
  110. """
  111. Enable progress bars either globally or for a specified group.
  112. This function sets the progress bars to enabled for the specified group or globally
  113. if no group is specified. The operation is subject to the `HF_HUB_DISABLE_PROGRESS_BARS`
  114. environment setting.
  115. Args:
  116. name (`str`, *optional*):
  117. The name of the group for which to enable the progress bars. If None,
  118. progress bars are enabled globally.
  119. Raises:
  120. Warning: If the environment variable precludes changes.
  121. """
  122. if HF_HUB_DISABLE_PROGRESS_BARS is True:
  123. warnings.warn(
  124. "Cannot enable progress bars: environment variable `HF_HUB_DISABLE_PROGRESS_BARS=1` is set and has priority."
  125. )
  126. return
  127. if name is None:
  128. progress_bar_states.clear()
  129. progress_bar_states["_global"] = True
  130. else:
  131. keys_to_remove = [key for key in progress_bar_states if key.startswith(f"{name}.")]
  132. for key in keys_to_remove:
  133. del progress_bar_states[key]
  134. progress_bar_states[name] = True
  135. def are_progress_bars_disabled(name: str | None = None) -> bool:
  136. """
  137. Check if progress bars are disabled globally or for a specific group.
  138. This function returns whether progress bars are disabled for a given group or globally.
  139. It checks the `HF_HUB_DISABLE_PROGRESS_BARS` environment variable first, then the programmatic
  140. settings.
  141. Args:
  142. name (`str`, *optional*):
  143. The group name to check; if None, checks the global setting.
  144. Returns:
  145. `bool`: True if progress bars are disabled, False otherwise.
  146. """
  147. if HF_HUB_DISABLE_PROGRESS_BARS is True:
  148. return True
  149. if name is None:
  150. return not progress_bar_states.get("_global", True)
  151. while name:
  152. if name in progress_bar_states:
  153. return not progress_bar_states[name]
  154. name = ".".join(name.split(".")[:-1])
  155. return not progress_bar_states.get("_global", True)
  156. def is_tqdm_disabled(log_level: int) -> bool | None:
  157. """
  158. Determine if tqdm progress bars should be disabled based on logging level and environment settings.
  159. see https://github.com/huggingface/huggingface_hub/pull/2000 and https://github.com/huggingface/huggingface_hub/pull/2698.
  160. """
  161. if log_level == logging.NOTSET:
  162. return True
  163. if os.getenv("TQDM_POSITION") == "-1":
  164. return False
  165. return None
  166. class tqdm(old_tqdm):
  167. """
  168. Class to override `disable` argument in case progress bars are globally disabled.
  169. Taken from https://github.com/tqdm/tqdm/issues/619#issuecomment-619639324.
  170. """
  171. def __init__(self, *args, **kwargs):
  172. name = kwargs.pop("name", None) # do not pass `name` to `tqdm`
  173. if are_progress_bars_disabled(name):
  174. kwargs["disable"] = True
  175. super().__init__(*args, **kwargs)
  176. def __delattr__(self, attr: str) -> None:
  177. """Fix for https://github.com/huggingface/huggingface_hub/issues/1603"""
  178. try:
  179. super().__delattr__(attr)
  180. except AttributeError:
  181. if attr != "_lock":
  182. raise
  183. class silent_tqdm:
  184. """Fake tqdm object that does nothing."""
  185. def __init__(self, *args, **kwargs):
  186. pass
  187. def __enter__(self):
  188. return self
  189. def __exit__(self, exc_type, exc_value, traceback):
  190. pass
  191. def update(self, n: int | float | None = 1) -> None:
  192. pass
  193. @contextmanager
  194. def tqdm_stream_file(path: Path | str) -> Iterator[io.BufferedReader]:
  195. """
  196. Open a file as binary and wrap the `read` method to display a progress bar when it's streamed.
  197. First implemented in `transformers` in 2019 but removed when switched to git-lfs. Used in `huggingface_hub` to show
  198. progress bar when uploading an LFS file to the Hub. See github.com/huggingface/transformers/pull/2078#discussion_r354739608
  199. for implementation details.
  200. Note: currently implementation handles only files stored on disk as it is the most common use case. Could be
  201. extended to stream any `BinaryIO` object but we might have to debug some corner cases.
  202. Example:
  203. ```py
  204. >>> with tqdm_stream_file("config.json") as f:
  205. >>> httpx.put(url, data=f)
  206. config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
  207. ```
  208. """
  209. if isinstance(path, str):
  210. path = Path(path)
  211. with path.open("rb") as f:
  212. total_size = path.stat().st_size
  213. pbar = tqdm(
  214. unit="B",
  215. unit_scale=True,
  216. total=total_size,
  217. initial=0,
  218. desc=path.name,
  219. )
  220. f_read = f.read
  221. def _inner_read(size: int | None = -1) -> bytes:
  222. data = f_read(size)
  223. pbar.update(len(data))
  224. return data
  225. f.read = _inner_read # type: ignore
  226. yield f
  227. pbar.close()
  228. def _create_progress_bar(*, cls: type[old_tqdm], log_level: int, name: str | None = None, **kwargs) -> old_tqdm:
  229. """Create a progress bar.
  230. For our `tqdm` subclass (or subclasses of it): respects all disable signals
  231. (`HF_HUB_DISABLE_PROGRESS_BARS`, `disable_progress_bars()`, log level) and uses
  232. `disable=None` for TTY auto-detection (see https://github.com/huggingface/huggingface_hub/pull/2000),
  233. unless `TQDM_POSITION=-1` forces bars on (https://github.com/huggingface/huggingface_hub/pull/2698).
  234. For other classes: does not inject `disable` or `name`. the custom class is fully
  235. responsible for its own behavior. Vanilla tqdm defaults to `disable=False` (bar shows).
  236. Omits `name` which vanilla tqdm rejects with `TqdmKeyError`. See https://github.com/huggingface/huggingface_hub/issues/4050.
  237. """
  238. # issubclass() crashes on non-class callables (e.g. functools.partial), guard with isinstance.
  239. if not (isinstance(cls, type) and issubclass(cls, tqdm)):
  240. return cls(**kwargs) # type: ignore[return-value]
  241. # HF subclass: keep the historical log-level / TTY behavior. Group-based
  242. # disabling is already handled in `tqdm.__init__`.
  243. disable = is_tqdm_disabled(log_level)
  244. return cls(disable=disable, name=name, **kwargs) # type: ignore[return-value]
  245. def _get_progress_bar_context(
  246. *,
  247. desc: str,
  248. log_level: int,
  249. total: int | None = None,
  250. initial: int = 0,
  251. unit: str = "B",
  252. unit_scale: bool = True,
  253. name: str | None = None,
  254. tqdm_class: type[old_tqdm] | None = None,
  255. _tqdm_bar: tqdm | None = None,
  256. ) -> ContextManager[tqdm]:
  257. if _tqdm_bar is not None:
  258. return nullcontext(_tqdm_bar)
  259. # ^ `contextlib.nullcontext` mimics a context manager that does nothing
  260. # Makes it easier to use the same code path for both cases but in the later
  261. # case, the progress bar is not closed when exiting the context manager.
  262. return _create_progress_bar( # type: ignore
  263. cls=tqdm_class or tqdm,
  264. log_level=log_level,
  265. name=name,
  266. unit=unit,
  267. unit_scale=unit_scale,
  268. total=total,
  269. initial=initial,
  270. desc=desc,
  271. )