scan_cache.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # coding=utf-8
  2. # Copyright 2022-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains command to scan the HF cache directory.
  16. Usage:
  17. huggingface-cli scan-cache
  18. huggingface-cli scan-cache -v
  19. huggingface-cli scan-cache -vvv
  20. huggingface-cli scan-cache --dir ~/.cache/huggingface/hub
  21. """
  22. import time
  23. from argparse import Namespace, _SubParsersAction
  24. from typing import Optional
  25. from ..utils import CacheNotFound, HFCacheInfo, scan_cache_dir
  26. from . import BaseHuggingfaceCLICommand
  27. from ._cli_utils import ANSI, show_deprecation_warning, tabulate
  28. class ScanCacheCommand(BaseHuggingfaceCLICommand):
  29. @staticmethod
  30. def register_subcommand(parser: _SubParsersAction):
  31. scan_cache_parser = parser.add_parser("scan-cache", help="Scan cache directory.")
  32. scan_cache_parser.add_argument(
  33. "--dir",
  34. type=str,
  35. default=None,
  36. help="cache directory to scan (optional). Default to the default HuggingFace cache.",
  37. )
  38. scan_cache_parser.add_argument(
  39. "-v",
  40. "--verbose",
  41. action="count",
  42. default=0,
  43. help="show a more verbose output",
  44. )
  45. scan_cache_parser.set_defaults(func=ScanCacheCommand)
  46. def __init__(self, args: Namespace) -> None:
  47. self.verbosity: int = args.verbose
  48. self.cache_dir: Optional[str] = args.dir
  49. def run(self):
  50. show_deprecation_warning("huggingface-cli scan-cache", "hf cache scan")
  51. try:
  52. t0 = time.time()
  53. hf_cache_info = scan_cache_dir(self.cache_dir)
  54. t1 = time.time()
  55. except CacheNotFound as exc:
  56. cache_dir = exc.cache_dir
  57. print(f"Cache directory not found: {cache_dir}")
  58. return
  59. self._print_hf_cache_info_as_table(hf_cache_info)
  60. print(
  61. f"\nDone in {round(t1 - t0, 1)}s. Scanned {len(hf_cache_info.repos)} repo(s)"
  62. f" for a total of {ANSI.red(hf_cache_info.size_on_disk_str)}."
  63. )
  64. if len(hf_cache_info.warnings) > 0:
  65. message = f"Got {len(hf_cache_info.warnings)} warning(s) while scanning."
  66. if self.verbosity >= 3:
  67. print(ANSI.gray(message))
  68. for warning in hf_cache_info.warnings:
  69. print(ANSI.gray(str(warning)))
  70. else:
  71. print(ANSI.gray(message + " Use -vvv to print details."))
  72. def _print_hf_cache_info_as_table(self, hf_cache_info: HFCacheInfo) -> None:
  73. print(get_table(hf_cache_info, verbosity=self.verbosity))
  74. def get_table(hf_cache_info: HFCacheInfo, *, verbosity: int = 0) -> str:
  75. """Generate a table from the [`HFCacheInfo`] object.
  76. Pass `verbosity=0` to get a table with a single row per repo, with columns
  77. "repo_id", "repo_type", "size_on_disk", "nb_files", "last_accessed", "last_modified", "refs", "local_path".
  78. Pass `verbosity=1` to get a table with a row per repo and revision (thus multiple rows can appear for a single repo), with columns
  79. "repo_id", "repo_type", "revision", "size_on_disk", "nb_files", "last_modified", "refs", "local_path".
  80. Example:
  81. ```py
  82. >>> from huggingface_hub.utils import scan_cache_dir
  83. >>> from huggingface_hub.commands.scan_cache import get_table
  84. >>> hf_cache_info = scan_cache_dir()
  85. HFCacheInfo(...)
  86. >>> print(get_table(hf_cache_info, verbosity=0))
  87. REPO ID REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED LAST_MODIFIED REFS LOCAL PATH
  88. --------------------------------------------------- --------- ------------ -------- ------------- ------------- ---- --------------------------------------------------------------------------------------------------
  89. roberta-base model 2.7M 5 1 day ago 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--roberta-base
  90. suno/bark model 8.8K 1 1 week ago 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--suno--bark
  91. t5-base model 893.8M 4 4 days ago 7 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-base
  92. t5-large model 3.0G 4 5 weeks ago 5 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-large
  93. >>> print(get_table(hf_cache_info, verbosity=1))
  94. REPO ID REPO TYPE REVISION SIZE ON DISK NB FILES LAST_MODIFIED REFS LOCAL PATH
  95. --------------------------------------------------- --------- ---------------------------------------- ------------ -------- ------------- ---- -----------------------------------------------------------------------------------------------------------------------------------------------------
  96. roberta-base model e2da8e2f811d1448a5b465c236feacd80ffbac7b 2.7M 5 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--roberta-base\\snapshots\\e2da8e2f811d1448a5b465c236feacd80ffbac7b
  97. suno/bark model 70a8a7d34168586dc5d028fa9666aceade177992 8.8K 1 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--suno--bark\\snapshots\\70a8a7d34168586dc5d028fa9666aceade177992
  98. t5-base model a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1 893.8M 4 7 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-base\\snapshots\\a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1
  99. t5-large model 150ebc2c4b72291e770f58e6057481c8d2ed331a 3.0G 4 5 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-large\\snapshots\\150ebc2c4b72291e770f58e6057481c8d2ed331a ```
  100. ```
  101. Args:
  102. hf_cache_info ([`HFCacheInfo`]):
  103. The HFCacheInfo object to print.
  104. verbosity (`int`, *optional*):
  105. The verbosity level. Defaults to 0.
  106. Returns:
  107. `str`: The table as a string.
  108. """
  109. if verbosity == 0:
  110. return tabulate(
  111. rows=[
  112. [
  113. repo.repo_id,
  114. repo.repo_type,
  115. "{:>12}".format(repo.size_on_disk_str),
  116. repo.nb_files,
  117. repo.last_accessed_str,
  118. repo.last_modified_str,
  119. ", ".join(sorted(repo.refs)),
  120. str(repo.repo_path),
  121. ]
  122. for repo in sorted(hf_cache_info.repos, key=lambda repo: repo.repo_path)
  123. ],
  124. headers=[
  125. "REPO ID",
  126. "REPO TYPE",
  127. "SIZE ON DISK",
  128. "NB FILES",
  129. "LAST_ACCESSED",
  130. "LAST_MODIFIED",
  131. "REFS",
  132. "LOCAL PATH",
  133. ],
  134. )
  135. else:
  136. return tabulate(
  137. rows=[
  138. [
  139. repo.repo_id,
  140. repo.repo_type,
  141. revision.commit_hash,
  142. "{:>12}".format(revision.size_on_disk_str),
  143. revision.nb_files,
  144. revision.last_modified_str,
  145. ", ".join(sorted(revision.refs)),
  146. str(revision.snapshot_path),
  147. ]
  148. for repo in sorted(hf_cache_info.repos, key=lambda repo: repo.repo_path)
  149. for revision in sorted(repo.revisions, key=lambda revision: revision.commit_hash)
  150. ],
  151. headers=[
  152. "REPO ID",
  153. "REPO TYPE",
  154. "REVISION",
  155. "SIZE ON DISK",
  156. "NB FILES",
  157. "LAST_MODIFIED",
  158. "REFS",
  159. "LOCAL PATH",
  160. ],
  161. )