_cache_manager.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866
  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 utilities to manage the HF cache directory."""
  16. import os
  17. import shutil
  18. import time
  19. from collections import defaultdict
  20. from dataclasses import dataclass
  21. from pathlib import Path
  22. from typing import Dict, FrozenSet, List, Literal, Optional, Set, Union
  23. from huggingface_hub.errors import CacheNotFound, CorruptedCacheException
  24. from ..commands._cli_utils import tabulate
  25. from ..constants import HF_HUB_CACHE
  26. from . import logging
  27. logger = logging.get_logger(__name__)
  28. REPO_TYPE_T = Literal["model", "dataset", "space"]
  29. # List of OS-created helper files that need to be ignored
  30. FILES_TO_IGNORE = [".DS_Store"]
  31. @dataclass(frozen=True)
  32. class CachedFileInfo:
  33. """Frozen data structure holding information about a single cached file.
  34. Args:
  35. file_name (`str`):
  36. Name of the file. Example: `config.json`.
  37. file_path (`Path`):
  38. Path of the file in the `snapshots` directory. The file path is a symlink
  39. referring to a blob in the `blobs` folder.
  40. blob_path (`Path`):
  41. Path of the blob file. This is equivalent to `file_path.resolve()`.
  42. size_on_disk (`int`):
  43. Size of the blob file in bytes.
  44. blob_last_accessed (`float`):
  45. Timestamp of the last time the blob file has been accessed (from any
  46. revision).
  47. blob_last_modified (`float`):
  48. Timestamp of the last time the blob file has been modified/created.
  49. > [!WARNING]
  50. > `blob_last_accessed` and `blob_last_modified` reliability can depend on the OS you
  51. > are using. See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result)
  52. > for more details.
  53. """
  54. file_name: str
  55. file_path: Path
  56. blob_path: Path
  57. size_on_disk: int
  58. blob_last_accessed: float
  59. blob_last_modified: float
  60. @property
  61. def blob_last_accessed_str(self) -> str:
  62. """
  63. (property) Timestamp of the last time the blob file has been accessed (from any
  64. revision), returned as a human-readable string.
  65. Example: "2 weeks ago".
  66. """
  67. return _format_timesince(self.blob_last_accessed)
  68. @property
  69. def blob_last_modified_str(self) -> str:
  70. """
  71. (property) Timestamp of the last time the blob file has been modified, returned
  72. as a human-readable string.
  73. Example: "2 weeks ago".
  74. """
  75. return _format_timesince(self.blob_last_modified)
  76. @property
  77. def size_on_disk_str(self) -> str:
  78. """
  79. (property) Size of the blob file as a human-readable string.
  80. Example: "42.2K".
  81. """
  82. return _format_size(self.size_on_disk)
  83. @dataclass(frozen=True)
  84. class CachedRevisionInfo:
  85. """Frozen data structure holding information about a revision.
  86. A revision correspond to a folder in the `snapshots` folder and is populated with
  87. the exact tree structure as the repo on the Hub but contains only symlinks. A
  88. revision can be either referenced by 1 or more `refs` or be "detached" (no refs).
  89. Args:
  90. commit_hash (`str`):
  91. Hash of the revision (unique).
  92. Example: `"9338f7b671827df886678df2bdd7cc7b4f36dffd"`.
  93. snapshot_path (`Path`):
  94. Path to the revision directory in the `snapshots` folder. It contains the
  95. exact tree structure as the repo on the Hub.
  96. files: (`FrozenSet[CachedFileInfo]`):
  97. Set of [`~CachedFileInfo`] describing all files contained in the snapshot.
  98. refs (`FrozenSet[str]`):
  99. Set of `refs` pointing to this revision. If the revision has no `refs`, it
  100. is considered detached.
  101. Example: `{"main", "2.4.0"}` or `{"refs/pr/1"}`.
  102. size_on_disk (`int`):
  103. Sum of the blob file sizes that are symlink-ed by the revision.
  104. last_modified (`float`):
  105. Timestamp of the last time the revision has been created/modified.
  106. > [!WARNING]
  107. > `last_accessed` cannot be determined correctly on a single revision as blob files
  108. > are shared across revisions.
  109. > [!WARNING]
  110. > `size_on_disk` is not necessarily the sum of all file sizes because of possible
  111. > duplicated files. Besides, only blobs are taken into account, not the (negligible)
  112. > size of folders and symlinks.
  113. """
  114. commit_hash: str
  115. snapshot_path: Path
  116. size_on_disk: int
  117. files: FrozenSet[CachedFileInfo]
  118. refs: FrozenSet[str]
  119. last_modified: float
  120. @property
  121. def last_modified_str(self) -> str:
  122. """
  123. (property) Timestamp of the last time the revision has been modified, returned
  124. as a human-readable string.
  125. Example: "2 weeks ago".
  126. """
  127. return _format_timesince(self.last_modified)
  128. @property
  129. def size_on_disk_str(self) -> str:
  130. """
  131. (property) Sum of the blob file sizes as a human-readable string.
  132. Example: "42.2K".
  133. """
  134. return _format_size(self.size_on_disk)
  135. @property
  136. def nb_files(self) -> int:
  137. """
  138. (property) Total number of files in the revision.
  139. """
  140. return len(self.files)
  141. @dataclass(frozen=True)
  142. class CachedRepoInfo:
  143. """Frozen data structure holding information about a cached repository.
  144. Args:
  145. repo_id (`str`):
  146. Repo id of the repo on the Hub. Example: `"google/fleurs"`.
  147. repo_type (`Literal["dataset", "model", "space"]`):
  148. Type of the cached repo.
  149. repo_path (`Path`):
  150. Local path to the cached repo.
  151. size_on_disk (`int`):
  152. Sum of the blob file sizes in the cached repo.
  153. nb_files (`int`):
  154. Total number of blob files in the cached repo.
  155. revisions (`FrozenSet[CachedRevisionInfo]`):
  156. Set of [`~CachedRevisionInfo`] describing all revisions cached in the repo.
  157. last_accessed (`float`):
  158. Timestamp of the last time a blob file of the repo has been accessed.
  159. last_modified (`float`):
  160. Timestamp of the last time a blob file of the repo has been modified/created.
  161. > [!WARNING]
  162. > `size_on_disk` is not necessarily the sum of all revisions sizes because of
  163. > duplicated files. Besides, only blobs are taken into account, not the (negligible)
  164. > size of folders and symlinks.
  165. > [!WARNING]
  166. > `last_accessed` and `last_modified` reliability can depend on the OS you are using.
  167. > See [python documentation](https://docs.python.org/3/library/os.html#os.stat_result)
  168. > for more details.
  169. """
  170. repo_id: str
  171. repo_type: REPO_TYPE_T
  172. repo_path: Path
  173. size_on_disk: int
  174. nb_files: int
  175. revisions: FrozenSet[CachedRevisionInfo]
  176. last_accessed: float
  177. last_modified: float
  178. @property
  179. def last_accessed_str(self) -> str:
  180. """
  181. (property) Last time a blob file of the repo has been accessed, returned as a
  182. human-readable string.
  183. Example: "2 weeks ago".
  184. """
  185. return _format_timesince(self.last_accessed)
  186. @property
  187. def last_modified_str(self) -> str:
  188. """
  189. (property) Last time a blob file of the repo has been modified, returned as a
  190. human-readable string.
  191. Example: "2 weeks ago".
  192. """
  193. return _format_timesince(self.last_modified)
  194. @property
  195. def size_on_disk_str(self) -> str:
  196. """
  197. (property) Sum of the blob file sizes as a human-readable string.
  198. Example: "42.2K".
  199. """
  200. return _format_size(self.size_on_disk)
  201. @property
  202. def refs(self) -> Dict[str, CachedRevisionInfo]:
  203. """
  204. (property) Mapping between `refs` and revision data structures.
  205. """
  206. return {ref: revision for revision in self.revisions for ref in revision.refs}
  207. @dataclass(frozen=True)
  208. class DeleteCacheStrategy:
  209. """Frozen data structure holding the strategy to delete cached revisions.
  210. This object is not meant to be instantiated programmatically but to be returned by
  211. [`~utils.HFCacheInfo.delete_revisions`]. See documentation for usage example.
  212. Args:
  213. expected_freed_size (`float`):
  214. Expected freed size once strategy is executed.
  215. blobs (`FrozenSet[Path]`):
  216. Set of blob file paths to be deleted.
  217. refs (`FrozenSet[Path]`):
  218. Set of reference file paths to be deleted.
  219. repos (`FrozenSet[Path]`):
  220. Set of entire repo paths to be deleted.
  221. snapshots (`FrozenSet[Path]`):
  222. Set of snapshots to be deleted (directory of symlinks).
  223. """
  224. expected_freed_size: int
  225. blobs: FrozenSet[Path]
  226. refs: FrozenSet[Path]
  227. repos: FrozenSet[Path]
  228. snapshots: FrozenSet[Path]
  229. @property
  230. def expected_freed_size_str(self) -> str:
  231. """
  232. (property) Expected size that will be freed as a human-readable string.
  233. Example: "42.2K".
  234. """
  235. return _format_size(self.expected_freed_size)
  236. def execute(self) -> None:
  237. """Execute the defined strategy.
  238. > [!WARNING]
  239. > If this method is interrupted, the cache might get corrupted. Deletion order is
  240. > implemented so that references and symlinks are deleted before the actual blob
  241. > files.
  242. > [!WARNING]
  243. > This method is irreversible. If executed, cached files are erased and must be
  244. > downloaded again.
  245. """
  246. # Deletion order matters. Blobs are deleted in last so that the user can't end
  247. # up in a state where a `ref`` refers to a missing snapshot or a snapshot
  248. # symlink refers to a deleted blob.
  249. # Delete entire repos
  250. for path in self.repos:
  251. _try_delete_path(path, path_type="repo")
  252. # Delete snapshot directories
  253. for path in self.snapshots:
  254. _try_delete_path(path, path_type="snapshot")
  255. # Delete refs files
  256. for path in self.refs:
  257. _try_delete_path(path, path_type="ref")
  258. # Delete blob files
  259. for path in self.blobs:
  260. _try_delete_path(path, path_type="blob")
  261. logger.info(f"Cache deletion done. Saved {self.expected_freed_size_str}.")
  262. @dataclass(frozen=True)
  263. class HFCacheInfo:
  264. """Frozen data structure holding information about the entire cache-system.
  265. This data structure is returned by [`scan_cache_dir`] and is immutable.
  266. Args:
  267. size_on_disk (`int`):
  268. Sum of all valid repo sizes in the cache-system.
  269. repos (`FrozenSet[CachedRepoInfo]`):
  270. Set of [`~CachedRepoInfo`] describing all valid cached repos found on the
  271. cache-system while scanning.
  272. warnings (`List[CorruptedCacheException]`):
  273. List of [`~CorruptedCacheException`] that occurred while scanning the cache.
  274. Those exceptions are captured so that the scan can continue. Corrupted repos
  275. are skipped from the scan.
  276. > [!WARNING]
  277. > Here `size_on_disk` is equal to the sum of all repo sizes (only blobs). However if
  278. > some cached repos are corrupted, their sizes are not taken into account.
  279. """
  280. size_on_disk: int
  281. repos: FrozenSet[CachedRepoInfo]
  282. warnings: List[CorruptedCacheException]
  283. @property
  284. def size_on_disk_str(self) -> str:
  285. """
  286. (property) Sum of all valid repo sizes in the cache-system as a human-readable
  287. string.
  288. Example: "42.2K".
  289. """
  290. return _format_size(self.size_on_disk)
  291. def delete_revisions(self, *revisions: str) -> DeleteCacheStrategy:
  292. """Prepare the strategy to delete one or more revisions cached locally.
  293. Input revisions can be any revision hash. If a revision hash is not found in the
  294. local cache, a warning is thrown but no error is raised. Revisions can be from
  295. different cached repos since hashes are unique across repos,
  296. Examples:
  297. ```py
  298. >>> from huggingface_hub import scan_cache_dir
  299. >>> cache_info = scan_cache_dir()
  300. >>> delete_strategy = cache_info.delete_revisions(
  301. ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa"
  302. ... )
  303. >>> print(f"Will free {delete_strategy.expected_freed_size_str}.")
  304. Will free 7.9K.
  305. >>> delete_strategy.execute()
  306. Cache deletion done. Saved 7.9K.
  307. ```
  308. ```py
  309. >>> from huggingface_hub import scan_cache_dir
  310. >>> scan_cache_dir().delete_revisions(
  311. ... "81fd1d6e7847c99f5862c9fb81387956d99ec7aa",
  312. ... "e2983b237dccf3ab4937c97fa717319a9ca1a96d",
  313. ... "6c0e6080953db56375760c0471a8c5f2929baf11",
  314. ... ).execute()
  315. Cache deletion done. Saved 8.6G.
  316. ```
  317. > [!WARNING]
  318. > `delete_revisions` returns a [`~utils.DeleteCacheStrategy`] object that needs to
  319. > be executed. The [`~utils.DeleteCacheStrategy`] is not meant to be modified but
  320. > allows having a dry run before actually executing the deletion.
  321. """
  322. hashes_to_delete: Set[str] = set(revisions)
  323. repos_with_revisions: Dict[CachedRepoInfo, Set[CachedRevisionInfo]] = defaultdict(set)
  324. for repo in self.repos:
  325. for revision in repo.revisions:
  326. if revision.commit_hash in hashes_to_delete:
  327. repos_with_revisions[repo].add(revision)
  328. hashes_to_delete.remove(revision.commit_hash)
  329. if len(hashes_to_delete) > 0:
  330. logger.warning(f"Revision(s) not found - cannot delete them: {', '.join(hashes_to_delete)}")
  331. delete_strategy_blobs: Set[Path] = set()
  332. delete_strategy_refs: Set[Path] = set()
  333. delete_strategy_repos: Set[Path] = set()
  334. delete_strategy_snapshots: Set[Path] = set()
  335. delete_strategy_expected_freed_size = 0
  336. for affected_repo, revisions_to_delete in repos_with_revisions.items():
  337. other_revisions = affected_repo.revisions - revisions_to_delete
  338. # If no other revisions, it means all revisions are deleted
  339. # -> delete the entire cached repo
  340. if len(other_revisions) == 0:
  341. delete_strategy_repos.add(affected_repo.repo_path)
  342. delete_strategy_expected_freed_size += affected_repo.size_on_disk
  343. continue
  344. # Some revisions of the repo will be deleted but not all. We need to filter
  345. # which blob files will not be linked anymore.
  346. for revision_to_delete in revisions_to_delete:
  347. # Snapshot dir
  348. delete_strategy_snapshots.add(revision_to_delete.snapshot_path)
  349. # Refs dir
  350. for ref in revision_to_delete.refs:
  351. delete_strategy_refs.add(affected_repo.repo_path / "refs" / ref)
  352. # Blobs dir
  353. for file in revision_to_delete.files:
  354. if file.blob_path not in delete_strategy_blobs:
  355. is_file_alone = True
  356. for revision in other_revisions:
  357. for rev_file in revision.files:
  358. if file.blob_path == rev_file.blob_path:
  359. is_file_alone = False
  360. break
  361. if not is_file_alone:
  362. break
  363. # Blob file not referenced by remaining revisions -> delete
  364. if is_file_alone:
  365. delete_strategy_blobs.add(file.blob_path)
  366. delete_strategy_expected_freed_size += file.size_on_disk
  367. # Return the strategy instead of executing it.
  368. return DeleteCacheStrategy(
  369. blobs=frozenset(delete_strategy_blobs),
  370. refs=frozenset(delete_strategy_refs),
  371. repos=frozenset(delete_strategy_repos),
  372. snapshots=frozenset(delete_strategy_snapshots),
  373. expected_freed_size=delete_strategy_expected_freed_size,
  374. )
  375. def export_as_table(self, *, verbosity: int = 0) -> str:
  376. """Generate a table from the [`HFCacheInfo`] object.
  377. Pass `verbosity=0` to get a table with a single row per repo, with columns
  378. "repo_id", "repo_type", "size_on_disk", "nb_files", "last_accessed", "last_modified", "refs", "local_path".
  379. 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
  380. "repo_id", "repo_type", "revision", "size_on_disk", "nb_files", "last_modified", "refs", "local_path".
  381. Example:
  382. ```py
  383. >>> from huggingface_hub.utils import scan_cache_dir
  384. >>> hf_cache_info = scan_cache_dir()
  385. HFCacheInfo(...)
  386. >>> print(hf_cache_info.export_as_table())
  387. REPO ID REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED LAST_MODIFIED REFS LOCAL PATH
  388. --------------------------------------------------- --------- ------------ -------- ------------- ------------- ---- --------------------------------------------------------------------------------------------------
  389. roberta-base model 2.7M 5 1 day ago 1 week ago main ~/.cache/huggingface/hub/models--roberta-base
  390. suno/bark model 8.8K 1 1 week ago 1 week ago main ~/.cache/huggingface/hub/models--suno--bark
  391. t5-base model 893.8M 4 4 days ago 7 months ago main ~/.cache/huggingface/hub/models--t5-base
  392. t5-large model 3.0G 4 5 weeks ago 5 months ago main ~/.cache/huggingface/hub/models--t5-large
  393. >>> print(hf_cache_info.export_as_table(verbosity=1))
  394. REPO ID REPO TYPE REVISION SIZE ON DISK NB FILES LAST_MODIFIED REFS LOCAL PATH
  395. --------------------------------------------------- --------- ---------------------------------------- ------------ -------- ------------- ---- -----------------------------------------------------------------------------------------------------------------------------------------------------
  396. roberta-base model e2da8e2f811d1448a5b465c236feacd80ffbac7b 2.7M 5 1 week ago main ~/.cache/huggingface/hub/models--roberta-base/snapshots/e2da8e2f811d1448a5b465c236feacd80ffbac7b
  397. suno/bark model 70a8a7d34168586dc5d028fa9666aceade177992 8.8K 1 1 week ago main ~/.cache/huggingface/hub/models--suno--bark/snapshots/70a8a7d34168586dc5d028fa9666aceade177992
  398. t5-base model a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1 893.8M 4 7 months ago main ~/.cache/huggingface/hub/models--t5-base/snapshots/a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1
  399. t5-large model 150ebc2c4b72291e770f58e6057481c8d2ed331a 3.0G 4 5 months ago main ~/.cache/huggingface/hub/models--t5-large/snapshots/150ebc2c4b72291e770f58e6057481c8d2ed331a
  400. ```
  401. Args:
  402. verbosity (`int`, *optional*):
  403. The verbosity level. Defaults to 0.
  404. Returns:
  405. `str`: The table as a string.
  406. """
  407. if verbosity == 0:
  408. return tabulate(
  409. rows=[
  410. [
  411. repo.repo_id,
  412. repo.repo_type,
  413. "{:>12}".format(repo.size_on_disk_str),
  414. repo.nb_files,
  415. repo.last_accessed_str,
  416. repo.last_modified_str,
  417. ", ".join(sorted(repo.refs)),
  418. str(repo.repo_path),
  419. ]
  420. for repo in sorted(self.repos, key=lambda repo: repo.repo_path)
  421. ],
  422. headers=[
  423. "REPO ID",
  424. "REPO TYPE",
  425. "SIZE ON DISK",
  426. "NB FILES",
  427. "LAST_ACCESSED",
  428. "LAST_MODIFIED",
  429. "REFS",
  430. "LOCAL PATH",
  431. ],
  432. )
  433. else:
  434. return tabulate(
  435. rows=[
  436. [
  437. repo.repo_id,
  438. repo.repo_type,
  439. revision.commit_hash,
  440. "{:>12}".format(revision.size_on_disk_str),
  441. revision.nb_files,
  442. revision.last_modified_str,
  443. ", ".join(sorted(revision.refs)),
  444. str(revision.snapshot_path),
  445. ]
  446. for repo in sorted(self.repos, key=lambda repo: repo.repo_path)
  447. for revision in sorted(repo.revisions, key=lambda revision: revision.commit_hash)
  448. ],
  449. headers=[
  450. "REPO ID",
  451. "REPO TYPE",
  452. "REVISION",
  453. "SIZE ON DISK",
  454. "NB FILES",
  455. "LAST_MODIFIED",
  456. "REFS",
  457. "LOCAL PATH",
  458. ],
  459. )
  460. def scan_cache_dir(cache_dir: Optional[Union[str, Path]] = None) -> HFCacheInfo:
  461. """Scan the entire HF cache-system and return a [`~HFCacheInfo`] structure.
  462. Use `scan_cache_dir` in order to programmatically scan your cache-system. The cache
  463. will be scanned repo by repo. If a repo is corrupted, a [`~CorruptedCacheException`]
  464. will be thrown internally but captured and returned in the [`~HFCacheInfo`]
  465. structure. Only valid repos get a proper report.
  466. ```py
  467. >>> from huggingface_hub import scan_cache_dir
  468. >>> hf_cache_info = scan_cache_dir()
  469. HFCacheInfo(
  470. size_on_disk=3398085269,
  471. repos=frozenset({
  472. CachedRepoInfo(
  473. repo_id='t5-small',
  474. repo_type='model',
  475. repo_path=PosixPath(...),
  476. size_on_disk=970726914,
  477. nb_files=11,
  478. revisions=frozenset({
  479. CachedRevisionInfo(
  480. commit_hash='d78aea13fa7ecd06c29e3e46195d6341255065d5',
  481. size_on_disk=970726339,
  482. snapshot_path=PosixPath(...),
  483. files=frozenset({
  484. CachedFileInfo(
  485. file_name='config.json',
  486. size_on_disk=1197
  487. file_path=PosixPath(...),
  488. blob_path=PosixPath(...),
  489. ),
  490. CachedFileInfo(...),
  491. ...
  492. }),
  493. ),
  494. CachedRevisionInfo(...),
  495. ...
  496. }),
  497. ),
  498. CachedRepoInfo(...),
  499. ...
  500. }),
  501. warnings=[
  502. CorruptedCacheException("Snapshots dir doesn't exist in cached repo: ..."),
  503. CorruptedCacheException(...),
  504. ...
  505. ],
  506. )
  507. ```
  508. You can also print a detailed report directly from the `hf` command line using:
  509. ```text
  510. > hf cache scan
  511. REPO ID REPO TYPE SIZE ON DISK NB FILES REFS LOCAL PATH
  512. --------------------------- --------- ------------ -------- ------------------- -------------------------------------------------------------------------
  513. glue dataset 116.3K 15 1.17.0, main, 2.4.0 /Users/lucain/.cache/huggingface/hub/datasets--glue
  514. google/fleurs dataset 64.9M 6 main, refs/pr/1 /Users/lucain/.cache/huggingface/hub/datasets--google--fleurs
  515. Jean-Baptiste/camembert-ner model 441.0M 7 main /Users/lucain/.cache/huggingface/hub/models--Jean-Baptiste--camembert-ner
  516. bert-base-cased model 1.9G 13 main /Users/lucain/.cache/huggingface/hub/models--bert-base-cased
  517. t5-base model 10.1K 3 main /Users/lucain/.cache/huggingface/hub/models--t5-base
  518. t5-small model 970.7M 11 refs/pr/1, main /Users/lucain/.cache/huggingface/hub/models--t5-small
  519. Done in 0.0s. Scanned 6 repo(s) for a total of 3.4G.
  520. Got 1 warning(s) while scanning. Use -vvv to print details.
  521. ```
  522. Args:
  523. cache_dir (`str` or `Path`, `optional`):
  524. Cache directory to cache. Defaults to the default HF cache directory.
  525. > [!WARNING]
  526. > Raises:
  527. >
  528. > `CacheNotFound`
  529. > If the cache directory does not exist.
  530. >
  531. > [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
  532. > If the cache directory is a file, instead of a directory.
  533. Returns: a [`~HFCacheInfo`] object.
  534. """
  535. if cache_dir is None:
  536. cache_dir = HF_HUB_CACHE
  537. cache_dir = Path(cache_dir).expanduser().resolve()
  538. if not cache_dir.exists():
  539. raise CacheNotFound(
  540. f"Cache directory not found: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable.",
  541. cache_dir=cache_dir,
  542. )
  543. if cache_dir.is_file():
  544. raise ValueError(
  545. f"Scan cache expects a directory but found a file: {cache_dir}. Please use `cache_dir` argument or set `HF_HUB_CACHE` environment variable."
  546. )
  547. repos: Set[CachedRepoInfo] = set()
  548. warnings: List[CorruptedCacheException] = []
  549. for repo_path in cache_dir.iterdir():
  550. if repo_path.name == ".locks": # skip './.locks/' folder
  551. continue
  552. try:
  553. repos.add(_scan_cached_repo(repo_path))
  554. except CorruptedCacheException as e:
  555. warnings.append(e)
  556. return HFCacheInfo(
  557. repos=frozenset(repos),
  558. size_on_disk=sum(repo.size_on_disk for repo in repos),
  559. warnings=warnings,
  560. )
  561. def _scan_cached_repo(repo_path: Path) -> CachedRepoInfo:
  562. """Scan a single cache repo and return information about it.
  563. Any unexpected behavior will raise a [`~CorruptedCacheException`].
  564. """
  565. if not repo_path.is_dir():
  566. raise CorruptedCacheException(f"Repo path is not a directory: {repo_path}")
  567. if "--" not in repo_path.name:
  568. raise CorruptedCacheException(f"Repo path is not a valid HuggingFace cache directory: {repo_path}")
  569. repo_type, repo_id = repo_path.name.split("--", maxsplit=1)
  570. repo_type = repo_type[:-1] # "models" -> "model"
  571. repo_id = repo_id.replace("--", "/") # google/fleurs -> "google/fleurs"
  572. if repo_type not in {"dataset", "model", "space"}:
  573. raise CorruptedCacheException(
  574. f"Repo type must be `dataset`, `model` or `space`, found `{repo_type}` ({repo_path})."
  575. )
  576. blob_stats: Dict[Path, os.stat_result] = {} # Key is blob_path, value is blob stats
  577. snapshots_path = repo_path / "snapshots"
  578. refs_path = repo_path / "refs"
  579. if not snapshots_path.exists() or not snapshots_path.is_dir():
  580. raise CorruptedCacheException(f"Snapshots dir doesn't exist in cached repo: {snapshots_path}")
  581. # Scan over `refs` directory
  582. # key is revision hash, value is set of refs
  583. refs_by_hash: Dict[str, Set[str]] = defaultdict(set)
  584. if refs_path.exists():
  585. # Example of `refs` directory
  586. # ── refs
  587. # ├── main
  588. # └── refs
  589. # └── pr
  590. # └── 1
  591. if refs_path.is_file():
  592. raise CorruptedCacheException(f"Refs directory cannot be a file: {refs_path}")
  593. for ref_path in refs_path.glob("**/*"):
  594. # glob("**/*") iterates over all files and directories -> skip directories
  595. if ref_path.is_dir() or ref_path.name in FILES_TO_IGNORE:
  596. continue
  597. ref_name = str(ref_path.relative_to(refs_path))
  598. with ref_path.open() as f:
  599. commit_hash = f.read()
  600. refs_by_hash[commit_hash].add(ref_name)
  601. # Scan snapshots directory
  602. cached_revisions: Set[CachedRevisionInfo] = set()
  603. for revision_path in snapshots_path.iterdir():
  604. # Ignore OS-created helper files
  605. if revision_path.name in FILES_TO_IGNORE:
  606. continue
  607. if revision_path.is_file():
  608. raise CorruptedCacheException(f"Snapshots folder corrupted. Found a file: {revision_path}")
  609. cached_files = set()
  610. for file_path in revision_path.glob("**/*"):
  611. # glob("**/*") iterates over all files and directories -> skip directories
  612. if file_path.is_dir():
  613. continue
  614. blob_path = Path(file_path).resolve()
  615. if not blob_path.exists():
  616. raise CorruptedCacheException(f"Blob missing (broken symlink): {blob_path}")
  617. if blob_path not in blob_stats:
  618. blob_stats[blob_path] = blob_path.stat()
  619. cached_files.add(
  620. CachedFileInfo(
  621. file_name=file_path.name,
  622. file_path=file_path,
  623. size_on_disk=blob_stats[blob_path].st_size,
  624. blob_path=blob_path,
  625. blob_last_accessed=blob_stats[blob_path].st_atime,
  626. blob_last_modified=blob_stats[blob_path].st_mtime,
  627. )
  628. )
  629. # Last modified is either the last modified blob file or the revision folder
  630. # itself if it is empty
  631. if len(cached_files) > 0:
  632. revision_last_modified = max(blob_stats[file.blob_path].st_mtime for file in cached_files)
  633. else:
  634. revision_last_modified = revision_path.stat().st_mtime
  635. cached_revisions.add(
  636. CachedRevisionInfo(
  637. commit_hash=revision_path.name,
  638. files=frozenset(cached_files),
  639. refs=frozenset(refs_by_hash.pop(revision_path.name, set())),
  640. size_on_disk=sum(
  641. blob_stats[blob_path].st_size for blob_path in set(file.blob_path for file in cached_files)
  642. ),
  643. snapshot_path=revision_path,
  644. last_modified=revision_last_modified,
  645. )
  646. )
  647. # Check that all refs referred to an existing revision
  648. if len(refs_by_hash) > 0:
  649. raise CorruptedCacheException(
  650. f"Reference(s) refer to missing commit hashes: {dict(refs_by_hash)} ({repo_path})."
  651. )
  652. # Last modified is either the last modified blob file or the repo folder itself if
  653. # no blob files has been found. Same for last accessed.
  654. if len(blob_stats) > 0:
  655. repo_last_accessed = max(stat.st_atime for stat in blob_stats.values())
  656. repo_last_modified = max(stat.st_mtime for stat in blob_stats.values())
  657. else:
  658. repo_stats = repo_path.stat()
  659. repo_last_accessed = repo_stats.st_atime
  660. repo_last_modified = repo_stats.st_mtime
  661. # Build and return frozen structure
  662. return CachedRepoInfo(
  663. nb_files=len(blob_stats),
  664. repo_id=repo_id,
  665. repo_path=repo_path,
  666. repo_type=repo_type, # type: ignore
  667. revisions=frozenset(cached_revisions),
  668. size_on_disk=sum(stat.st_size for stat in blob_stats.values()),
  669. last_accessed=repo_last_accessed,
  670. last_modified=repo_last_modified,
  671. )
  672. def _format_size(num: int) -> str:
  673. """Format size in bytes into a human-readable string.
  674. Taken from https://stackoverflow.com/a/1094933
  675. """
  676. num_f = float(num)
  677. for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]:
  678. if abs(num_f) < 1000.0:
  679. return f"{num_f:3.1f}{unit}"
  680. num_f /= 1000.0
  681. return f"{num_f:.1f}Y"
  682. _TIMESINCE_CHUNKS = (
  683. # Label, divider, max value
  684. ("second", 1, 60),
  685. ("minute", 60, 60),
  686. ("hour", 60 * 60, 24),
  687. ("day", 60 * 60 * 24, 6),
  688. ("week", 60 * 60 * 24 * 7, 6),
  689. ("month", 60 * 60 * 24 * 30, 11),
  690. ("year", 60 * 60 * 24 * 365, None),
  691. )
  692. def _format_timesince(ts: float) -> str:
  693. """Format timestamp in seconds into a human-readable string, relative to now.
  694. Vaguely inspired by Django's `timesince` formatter.
  695. """
  696. delta = time.time() - ts
  697. if delta < 20:
  698. return "a few seconds ago"
  699. for label, divider, max_value in _TIMESINCE_CHUNKS: # noqa: B007
  700. value = round(delta / divider)
  701. if max_value is not None and value <= max_value:
  702. break
  703. return f"{value} {label}{'s' if value > 1 else ''} ago"
  704. def _try_delete_path(path: Path, path_type: str) -> None:
  705. """Try to delete a local file or folder.
  706. If the path does not exists, error is logged as a warning and then ignored.
  707. Args:
  708. path (`Path`)
  709. Path to delete. Can be a file or a folder.
  710. path_type (`str`)
  711. What path are we deleting ? Only for logging purposes. Example: "snapshot".
  712. """
  713. logger.info(f"Delete {path_type}: {path}")
  714. try:
  715. if path.is_file():
  716. os.remove(path)
  717. else:
  718. shutil.rmtree(path)
  719. except FileNotFoundError:
  720. logger.warning(f"Couldn't delete {path_type}: file not found ({path})", exc_info=True)
  721. except PermissionError:
  722. logger.warning(f"Couldn't delete {path_type}: permission denied ({path})", exc_info=True)