_cache_manager.py 32 KB

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