cache.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756
  1. # Copyright 2025-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 the 'hf cache' command group with cache management subcommands."""
  15. import re
  16. import time
  17. from collections import defaultdict
  18. from collections.abc import Callable, Mapping
  19. from dataclasses import dataclass
  20. from enum import Enum
  21. from typing import Annotated, Any
  22. import typer
  23. from huggingface_hub.errors import CLIError
  24. from ..utils import ANSI, CachedRepoInfo, CachedRevisionInfo, CacheNotFound, HFCacheInfo, _format_size, scan_cache_dir
  25. from ..utils._parsing import parse_duration, parse_size
  26. from ._cli_utils import FormatWithAutoOpt, RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt, get_hf_api, typer_factory
  27. from ._output import OutputFormatWithAuto, out
  28. cache_cli = typer_factory(help="Manage local cache directory.")
  29. #### Cache helper utilities
  30. @dataclass(frozen=True)
  31. class _DeletionResolution:
  32. revisions: frozenset[str]
  33. selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]]
  34. missing: tuple[str, ...]
  35. _FILTER_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)\s*(?P<op>==|!=|>=|<=|>|<|=)\s*(?P<value>.+)$")
  36. _ALLOWED_OPERATORS = {"=", "!=", ">", "<", ">=", "<="}
  37. _FILTER_KEYS = {"accessed", "modified", "refs", "size", "type"}
  38. _SORT_KEYS = {"accessed", "modified", "name", "size"}
  39. _SORT_PATTERN = re.compile(r"^(?P<key>[a-zA-Z_]+)(?::(?P<order>asc|desc))?$")
  40. _SORT_DEFAULT_ORDER = {
  41. # Default ordering: accessed/modified/size are descending (newest/biggest first), name is ascending
  42. "accessed": "desc",
  43. "modified": "desc",
  44. "size": "desc",
  45. "name": "asc",
  46. }
  47. # Dynamically generate SortOptions enum from _SORT_KEYS
  48. _sort_options_dict = {}
  49. for key in sorted(_SORT_KEYS):
  50. _sort_options_dict[key] = key
  51. _sort_options_dict[f"{key}_asc"] = f"{key}:asc"
  52. _sort_options_dict[f"{key}_desc"] = f"{key}:desc"
  53. SortOptions = Enum("SortOptions", _sort_options_dict, type=str, module=__name__) # type: ignore
  54. @dataclass(frozen=True)
  55. class CacheDeletionCounts:
  56. """Simple counters summarizing cache deletions for CLI messaging."""
  57. repo_count: int
  58. partial_revision_count: int
  59. total_revision_count: int
  60. CacheEntry = tuple[CachedRepoInfo, CachedRevisionInfo | None]
  61. RepoRefsMap = dict[CachedRepoInfo, frozenset[str]]
  62. def summarize_deletions(
  63. selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]],
  64. ) -> CacheDeletionCounts:
  65. """Summarize deletions across repositories."""
  66. repo_count = 0
  67. total_revisions = 0
  68. revisions_in_full_repos = 0
  69. for repo, revisions in selected_by_repo.items():
  70. total_revisions += len(revisions)
  71. if len(revisions) == len(repo.revisions):
  72. repo_count += 1
  73. revisions_in_full_repos += len(revisions)
  74. partial_revision_count = total_revisions - revisions_in_full_repos
  75. return CacheDeletionCounts(repo_count, partial_revision_count, total_revisions)
  76. def print_cache_selected_revisions(selected_by_repo: Mapping[CachedRepoInfo, frozenset[CachedRevisionInfo]]) -> None:
  77. """Pretty-print selected cache revisions during confirmation prompts."""
  78. for repo in sorted(selected_by_repo.keys(), key=lambda repo: (repo.repo_type, repo.repo_id.lower())):
  79. repo_key = f"{repo.repo_type}/{repo.repo_id}"
  80. revisions = sorted(selected_by_repo[repo], key=lambda rev: rev.commit_hash)
  81. if len(revisions) == len(repo.revisions):
  82. out.text(f" - {repo_key} (entire repo)")
  83. continue
  84. out.text(f" - {repo_key}:")
  85. for revision in revisions:
  86. refs = " ".join(sorted(revision.refs)) or "(detached)"
  87. out.text(f" {revision.commit_hash} [{refs}] {revision.size_on_disk_str}")
  88. def build_cache_index(
  89. hf_cache_info: HFCacheInfo,
  90. ) -> tuple[
  91. dict[str, CachedRepoInfo],
  92. dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]],
  93. ]:
  94. """Create lookup tables so CLI commands can resolve repo ids and revisions quickly."""
  95. repo_lookup: dict[str, CachedRepoInfo] = {}
  96. revision_lookup: dict[str, tuple[CachedRepoInfo, CachedRevisionInfo]] = {}
  97. for repo in hf_cache_info.repos:
  98. repo_key = repo.cache_id.lower()
  99. repo_lookup[repo_key] = repo
  100. for revision in repo.revisions:
  101. revision_lookup[revision.commit_hash.lower()] = (repo, revision)
  102. return repo_lookup, revision_lookup
  103. def collect_cache_entries(
  104. hf_cache_info: HFCacheInfo, *, include_revisions: bool
  105. ) -> tuple[list[CacheEntry], RepoRefsMap]:
  106. """Flatten cache metadata into rows consumed by `hf cache ls`."""
  107. entries: list[CacheEntry] = []
  108. repo_refs_map: RepoRefsMap = {}
  109. sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: (repo.repo_type, repo.repo_id.lower()))
  110. for repo in sorted_repos:
  111. repo_refs_map[repo] = frozenset({ref for revision in repo.revisions for ref in revision.refs})
  112. if include_revisions:
  113. for revision in sorted(repo.revisions, key=lambda rev: rev.commit_hash):
  114. entries.append((repo, revision))
  115. else:
  116. entries.append((repo, None))
  117. if include_revisions:
  118. entries.sort(
  119. key=lambda entry: (
  120. entry[0].cache_id,
  121. entry[1].commit_hash if entry[1] is not None else "",
  122. )
  123. )
  124. else:
  125. entries.sort(key=lambda entry: entry[0].cache_id)
  126. return entries, repo_refs_map
  127. def compile_cache_filter(
  128. expr: str, repo_refs_map: RepoRefsMap
  129. ) -> Callable[[CachedRepoInfo, CachedRevisionInfo | None, float], bool]:
  130. """Convert a `hf cache ls` filter expression into the yes/no test we apply to each cache entry before displaying it."""
  131. match = _FILTER_PATTERN.match(expr.strip())
  132. if not match:
  133. raise ValueError(f"Invalid filter expression: '{expr}'.")
  134. key = match.group("key").lower()
  135. op = match.group("op")
  136. value_raw = match.group("value").strip()
  137. if op not in _ALLOWED_OPERATORS:
  138. raise ValueError(f"Unsupported operator '{op}' in filter '{expr}'. Must be one of {list(_ALLOWED_OPERATORS)}.")
  139. if key not in _FILTER_KEYS:
  140. raise ValueError(f"Unsupported filter key '{key}' in '{expr}'. Must be one of {list(_FILTER_KEYS)}.")
  141. # at this point we know that key is in `_FILTER_KEYS`
  142. if key == "size":
  143. size_threshold = parse_size(value_raw)
  144. return lambda repo, revision, _: _compare_numeric(
  145. revision.size_on_disk if revision is not None else repo.size_on_disk,
  146. op,
  147. size_threshold,
  148. )
  149. if key in {"modified", "accessed"}:
  150. seconds = parse_duration(value_raw.strip())
  151. def _time_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, now: float) -> bool:
  152. timestamp = (
  153. repo.last_accessed
  154. if key == "accessed"
  155. else revision.last_modified
  156. if revision is not None
  157. else repo.last_modified
  158. )
  159. if timestamp is None:
  160. return False
  161. return _compare_numeric(now - timestamp, op, seconds)
  162. return _time_filter
  163. if key == "type":
  164. expected = value_raw.lower()
  165. if op != "=":
  166. raise ValueError(f"Only '=' is supported for 'type' filters. Got '{op}'.")
  167. def _type_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
  168. return repo.repo_type.lower() == expected
  169. return _type_filter
  170. else: # key == "refs"
  171. if op != "=":
  172. raise ValueError(f"Only '=' is supported for 'refs' filters. Got {op}.")
  173. def _refs_filter(repo: CachedRepoInfo, revision: CachedRevisionInfo | None, _: float) -> bool:
  174. refs = revision.refs if revision is not None else repo_refs_map.get(repo, frozenset())
  175. return value_raw.lower() in [ref.lower() for ref in refs]
  176. return _refs_filter
  177. def _compare_numeric(left: float | None, op: str, right: float) -> bool:
  178. """Evaluate numeric comparisons for filters."""
  179. if left is None:
  180. return False
  181. comparisons = {
  182. "=": left == right,
  183. "!=": left != right,
  184. ">": left > right,
  185. "<": left < right,
  186. ">=": left >= right,
  187. "<=": left <= right,
  188. }
  189. if op not in comparisons:
  190. raise ValueError(f"Unsupported numeric comparison operator: {op}")
  191. return comparisons[op]
  192. def compile_cache_sort(sort_expr: str) -> tuple[Callable[[CacheEntry], tuple[Any, ...]], bool]:
  193. """Convert a `hf cache ls` sort expression into a key function for sorting entries.
  194. Returns:
  195. A tuple of (key_function, reverse_flag) where reverse_flag indicates whether
  196. to sort in descending order (True) or ascending order (False).
  197. """
  198. match = _SORT_PATTERN.match(sort_expr.strip().lower())
  199. if not match:
  200. raise ValueError(f"Invalid sort expression: '{sort_expr}'. Expected format: 'key' or 'key:asc' or 'key:desc'.")
  201. key = match.group("key").lower()
  202. explicit_order = match.group("order")
  203. if key not in _SORT_KEYS:
  204. raise ValueError(f"Unsupported sort key '{key}' in '{sort_expr}'. Must be one of {list(_SORT_KEYS)}.")
  205. # Use explicit order if provided, otherwise use default for the key
  206. order = explicit_order if explicit_order else _SORT_DEFAULT_ORDER[key]
  207. reverse = order == "desc"
  208. def _sort_key(entry: CacheEntry) -> tuple[Any, ...]:
  209. repo, revision = entry
  210. if key == "name":
  211. # Sort by cache_id (repo type/id)
  212. value: Any = repo.cache_id.lower()
  213. return (value,)
  214. if key == "size":
  215. # Use revision size if available, otherwise repo size
  216. value = revision.size_on_disk if revision is not None else repo.size_on_disk
  217. return (value,)
  218. if key == "accessed":
  219. # For revisions, accessed is not available per-revision, use repo's last_accessed
  220. # For repos, use repo's last_accessed
  221. value = repo.last_accessed if repo.last_accessed is not None else 0.0
  222. return (value,)
  223. if key == "modified":
  224. # Use revision's last_modified if available, otherwise repo's last_modified
  225. if revision is not None:
  226. value = revision.last_modified if revision.last_modified is not None else 0.0
  227. else:
  228. value = repo.last_modified if repo.last_modified is not None else 0.0
  229. return (value,)
  230. # Should never reach here due to validation above
  231. raise ValueError(f"Unsupported sort key: {key}")
  232. return _sort_key, reverse
  233. def _resolve_deletion_targets(hf_cache_info: HFCacheInfo, targets: list[str]) -> _DeletionResolution:
  234. """Resolve the deletion targets into a deletion resolution."""
  235. repo_lookup, revision_lookup = build_cache_index(hf_cache_info)
  236. selected: dict[CachedRepoInfo, set[CachedRevisionInfo]] = defaultdict(set)
  237. revisions: set[str] = set()
  238. missing: list[str] = []
  239. for raw_target in targets:
  240. target = raw_target.strip()
  241. if not target:
  242. continue
  243. lowered = target.lower()
  244. if re.fullmatch(r"[0-9a-fA-F]{40}", lowered):
  245. match = revision_lookup.get(lowered)
  246. if match is None:
  247. missing.append(raw_target)
  248. continue
  249. repo, revision = match
  250. selected[repo].add(revision)
  251. revisions.add(revision.commit_hash)
  252. continue
  253. matched_repo = repo_lookup.get(lowered)
  254. if matched_repo is None:
  255. missing.append(raw_target)
  256. continue
  257. for revision in matched_repo.revisions:
  258. selected[matched_repo].add(revision)
  259. revisions.add(revision.commit_hash)
  260. frozen_selected = {repo: frozenset(revs) for repo, revs in selected.items()}
  261. return _DeletionResolution(
  262. revisions=frozenset(revisions),
  263. selected=frozen_selected,
  264. missing=tuple(missing),
  265. )
  266. #### Cache CLI commands
  267. @cache_cli.command(
  268. "list | ls",
  269. examples=[
  270. "hf cache ls",
  271. "hf cache ls --revisions",
  272. 'hf cache ls --filter "size>1GB" --limit 20',
  273. "hf cache ls --format json",
  274. ],
  275. )
  276. def ls(
  277. cache_dir: Annotated[
  278. str | None,
  279. typer.Option(
  280. help="Cache directory to scan (defaults to Hugging Face cache).",
  281. ),
  282. ] = None,
  283. revisions: Annotated[
  284. bool,
  285. typer.Option(
  286. help="Include revisions in the output instead of aggregated repositories.",
  287. ),
  288. ] = False,
  289. filter: Annotated[
  290. list[str] | None,
  291. typer.Option(
  292. "-f",
  293. "--filter",
  294. help="Filter entries (e.g. 'size>1GB', 'type=model', 'accessed>7d'). Can be used multiple times.",
  295. ),
  296. ] = None,
  297. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  298. sort: Annotated[
  299. SortOptions | None,
  300. typer.Option(
  301. help="Sort entries by key. Supported keys: 'accessed', 'modified', 'name', 'size'. "
  302. "Append ':asc' or ':desc' to explicitly set the order (e.g., 'modified:asc'). "
  303. "Defaults: 'accessed', 'modified', 'size' default to 'desc' (newest/biggest first); "
  304. "'name' defaults to 'asc' (alphabetical).",
  305. ),
  306. ] = None,
  307. limit: Annotated[
  308. int | None,
  309. typer.Option(
  310. help="Limit the number of results returned. Returns only the top N entries after sorting.",
  311. ),
  312. ] = None,
  313. ) -> None:
  314. """List cached repositories or revisions."""
  315. try:
  316. hf_cache_info = scan_cache_dir(cache_dir)
  317. except CacheNotFound as exc:
  318. raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
  319. filters = filter or []
  320. entries, repo_refs_map = collect_cache_entries(hf_cache_info, include_revisions=revisions)
  321. try:
  322. filter_fns = [compile_cache_filter(expr, repo_refs_map) for expr in filters]
  323. except ValueError as exc:
  324. raise typer.BadParameter(str(exc)) from exc
  325. now = time.time()
  326. for fn in filter_fns:
  327. entries = [entry for entry in entries if fn(entry[0], entry[1], now)]
  328. # Apply sorting if requested
  329. if sort:
  330. try:
  331. sort_key_fn, reverse = compile_cache_sort(sort.value)
  332. entries.sort(key=sort_key_fn, reverse=reverse)
  333. except ValueError as exc:
  334. raise typer.BadParameter(str(exc)) from exc
  335. # Apply limit if requested
  336. if limit is not None:
  337. if limit < 0:
  338. raise typer.BadParameter(f"Limit must be a positive integer, got {limit}.")
  339. entries = entries[:limit]
  340. if revisions:
  341. items = [
  342. {
  343. "id": repo.cache_id,
  344. "repo_id": repo.repo_id,
  345. "repo_type": repo.repo_type,
  346. "revision": revision.commit_hash,
  347. "snapshot_path": str(revision.snapshot_path),
  348. "size": revision.size_on_disk_str,
  349. "last_modified": revision.last_modified_str,
  350. "refs": sorted(revision.refs),
  351. }
  352. for repo, revision in entries
  353. if revision is not None
  354. ]
  355. out.table(
  356. items,
  357. headers=["id", "revision", "size", "last_modified", "refs"],
  358. id_key="revision",
  359. alignments={"size": "right"},
  360. )
  361. else:
  362. items = [
  363. {
  364. "id": repo.cache_id,
  365. "repo_id": repo.repo_id,
  366. "repo_type": repo.repo_type,
  367. "size": repo.size_on_disk_str,
  368. "last_accessed": repo.last_accessed_str or "",
  369. "last_modified": repo.last_modified_str,
  370. "refs": sorted(repo_refs_map.get(repo, frozenset())),
  371. }
  372. for repo, _ in entries
  373. ]
  374. out.table(
  375. items,
  376. headers=["id", "size", "last_accessed", "last_modified", "refs"],
  377. id_key="id",
  378. alignments={"size": "right"},
  379. )
  380. if entries:
  381. unique_repos = {repo for repo, _ in entries}
  382. repo_count = len(unique_repos)
  383. if revisions:
  384. revision_count = sum(1 for _, rev in entries if rev is not None)
  385. total_size = sum(rev.size_on_disk for _, rev in entries if rev is not None)
  386. else:
  387. revision_count = sum(len(repo.revisions) for repo in unique_repos)
  388. total_size = sum(repo.size_on_disk for repo in unique_repos)
  389. out.text(
  390. ANSI.bold(
  391. f"\nFound {repo_count} repo(s) for a total of {revision_count} revision(s)"
  392. f" and {_format_size(total_size)} on disk."
  393. )
  394. )
  395. @cache_cli.command(
  396. examples=[
  397. "hf cache rm model/gpt2",
  398. "hf cache rm <revision_hash>",
  399. "hf cache rm model/gpt2 --dry-run",
  400. "hf cache rm model/gpt2 --yes",
  401. ],
  402. )
  403. def rm(
  404. targets: Annotated[
  405. list[str],
  406. typer.Argument(
  407. help="One or more repo IDs (e.g. model/bert-base-uncased) or revision hashes to delete.",
  408. ),
  409. ],
  410. cache_dir: Annotated[
  411. str | None,
  412. typer.Option(
  413. help="Cache directory to scan (defaults to Hugging Face cache).",
  414. ),
  415. ] = None,
  416. yes: Annotated[
  417. bool,
  418. typer.Option(
  419. "-y",
  420. "--yes",
  421. help="Skip confirmation prompt.",
  422. ),
  423. ] = False,
  424. dry_run: Annotated[
  425. bool,
  426. typer.Option(
  427. help="Preview deletions without removing anything.",
  428. ),
  429. ] = False,
  430. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  431. ) -> None:
  432. """Remove cached repositories or revisions."""
  433. try:
  434. hf_cache_info = scan_cache_dir(cache_dir)
  435. except CacheNotFound as exc:
  436. raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
  437. resolution = _resolve_deletion_targets(hf_cache_info, targets)
  438. if resolution.missing:
  439. details = "\n".join(f" - {entry}" for entry in resolution.missing)
  440. out.warning(f"Could not find in cache:\n{details}")
  441. if len(resolution.revisions) == 0:
  442. out.text("Nothing to delete.")
  443. raise typer.Exit(code=0)
  444. strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
  445. counts = summarize_deletions(resolution.selected)
  446. summary_parts: list[str] = []
  447. if counts.repo_count:
  448. summary_parts.append(f"{counts.repo_count} repo(s)")
  449. if counts.partial_revision_count:
  450. summary_parts.append(f"{counts.partial_revision_count} revision(s)")
  451. if not summary_parts:
  452. summary_parts.append(f"{counts.total_revision_count} revision(s)")
  453. summary_text = " and ".join(summary_parts)
  454. out.text(f"About to delete {summary_text} totalling {strategy.expected_freed_size_str}.")
  455. print_cache_selected_revisions(resolution.selected)
  456. if dry_run:
  457. out.result(
  458. "Dry run: no files were deleted.",
  459. dry_run=True,
  460. repos=counts.repo_count,
  461. revisions=counts.total_revision_count,
  462. size=strategy.expected_freed_size_str,
  463. )
  464. return
  465. out.confirm("Proceed with deletion?", yes=yes)
  466. strategy.execute()
  467. counts = summarize_deletions(resolution.selected)
  468. out.result(
  469. f"Deleted {counts.repo_count} repo(s) and {counts.total_revision_count} revision(s);"
  470. f" freed {strategy.expected_freed_size_str}.",
  471. repos_deleted=counts.repo_count,
  472. revisions_deleted=counts.total_revision_count,
  473. freed=strategy.expected_freed_size_str,
  474. )
  475. @cache_cli.command(examples=["hf cache prune", "hf cache prune --dry-run"])
  476. def prune(
  477. cache_dir: Annotated[
  478. str | None,
  479. typer.Option(
  480. help="Cache directory to scan (defaults to Hugging Face cache).",
  481. ),
  482. ] = None,
  483. yes: Annotated[
  484. bool,
  485. typer.Option(
  486. "-y",
  487. "--yes",
  488. help="Skip confirmation prompt.",
  489. ),
  490. ] = False,
  491. dry_run: Annotated[
  492. bool,
  493. typer.Option(
  494. help="Preview deletions without removing anything.",
  495. ),
  496. ] = False,
  497. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  498. ) -> None:
  499. """Remove detached revisions from the cache."""
  500. try:
  501. hf_cache_info = scan_cache_dir(cache_dir)
  502. except CacheNotFound as exc:
  503. raise CLIError(f"Cache directory not found: {exc.cache_dir}") from exc
  504. selected: dict[CachedRepoInfo, frozenset[CachedRevisionInfo]] = {}
  505. revisions: set[str] = set()
  506. for repo in hf_cache_info.repos:
  507. detached = frozenset(revision for revision in repo.revisions if len(revision.refs) == 0)
  508. if not detached:
  509. continue
  510. selected[repo] = detached
  511. revisions.update(revision.commit_hash for revision in detached)
  512. if len(revisions) == 0:
  513. out.text("No unreferenced revisions found. Nothing to prune.")
  514. return
  515. resolution = _DeletionResolution(
  516. revisions=frozenset(revisions),
  517. selected=selected,
  518. missing=(),
  519. )
  520. strategy = hf_cache_info.delete_revisions(*sorted(resolution.revisions))
  521. counts = summarize_deletions(selected)
  522. out.text(
  523. f"About to delete {counts.total_revision_count} unreferenced revision(s) ({strategy.expected_freed_size_str} total)."
  524. )
  525. print_cache_selected_revisions(selected)
  526. if dry_run:
  527. out.result(
  528. "Dry run: no files were deleted.",
  529. dry_run=True,
  530. revisions=counts.total_revision_count,
  531. size=strategy.expected_freed_size_str,
  532. )
  533. return
  534. out.confirm("Proceed?", yes=yes)
  535. strategy.execute()
  536. out.result(
  537. f"Deleted {counts.total_revision_count} unreferenced revision(s); freed {strategy.expected_freed_size_str}.",
  538. revisions_deleted=counts.total_revision_count,
  539. freed=strategy.expected_freed_size_str,
  540. )
  541. @cache_cli.command(
  542. examples=[
  543. "hf cache verify gpt2",
  544. "hf cache verify gpt2 --revision refs/pr/1",
  545. "hf cache verify my-dataset --repo-type dataset",
  546. ],
  547. )
  548. def verify(
  549. repo_id: RepoIdArg,
  550. repo_type: RepoTypeOpt = RepoTypeOpt.model,
  551. revision: RevisionOpt = None,
  552. cache_dir: Annotated[
  553. str | None,
  554. typer.Option(
  555. help="Cache directory to use when verifying files from cache (defaults to Hugging Face cache).",
  556. ),
  557. ] = None,
  558. local_dir: Annotated[
  559. str | None,
  560. typer.Option(
  561. help="If set, verify files under this directory instead of the cache.",
  562. ),
  563. ] = None,
  564. fail_on_missing_files: Annotated[
  565. bool,
  566. typer.Option(
  567. "--fail-on-missing-files",
  568. help="Fail if some files exist on the remote but are missing locally.",
  569. ),
  570. ] = False,
  571. fail_on_extra_files: Annotated[
  572. bool,
  573. typer.Option(
  574. "--fail-on-extra-files",
  575. help="Fail if some files exist locally but are not present on the remote revision.",
  576. ),
  577. ] = False,
  578. token: TokenOpt = None,
  579. format: FormatWithAutoOpt = OutputFormatWithAuto.auto,
  580. ) -> None:
  581. """Verify checksums for a single repo revision from cache or a local directory.
  582. Examples:
  583. - Verify main revision in cache: `hf cache verify gpt2`
  584. - Verify specific revision: `hf cache verify gpt2 --revision refs/pr/1`
  585. - Verify dataset: `hf cache verify karpathy/fineweb-edu-100b-shuffle --repo-type dataset`
  586. - Verify local dir: `hf cache verify deepseek-ai/DeepSeek-OCR --local-dir /path/to/repo`
  587. """
  588. if local_dir is not None and cache_dir is not None:
  589. out.error("Cannot pass both --local-dir and --cache-dir. Use one or the other.")
  590. raise typer.Exit(code=2)
  591. api = get_hf_api(token=token)
  592. result = api.verify_repo_checksums(
  593. repo_id=repo_id,
  594. repo_type=repo_type.value if hasattr(repo_type, "value") else str(repo_type),
  595. revision=revision,
  596. local_dir=local_dir,
  597. cache_dir=cache_dir,
  598. token=token,
  599. )
  600. exit_code = 0
  601. if result.mismatches:
  602. details = "\n".join(
  603. f" - {m['path']}: expected {m['expected']} ({m['algorithm']}), got {m['actual']}"
  604. for m in result.mismatches
  605. )
  606. out.text(f"❌ Checksum verification failed for the following file(s):\n{details}")
  607. exit_code = 1
  608. if result.missing_paths:
  609. if fail_on_missing_files:
  610. details = "\n".join(f" - {p}" for p in result.missing_paths)
  611. out.text(f"❌ Missing files (present remotely, absent locally):\n{details}")
  612. exit_code = 1
  613. else:
  614. out.warning(
  615. f"{len(result.missing_paths)} remote file(s) are missing locally. "
  616. "Use --fail-on-missing-files for details."
  617. )
  618. if result.extra_paths:
  619. if fail_on_extra_files:
  620. details = "\n".join(f" - {p}" for p in result.extra_paths)
  621. out.text(f"❌ Extra files (present locally, absent remotely):\n{details}")
  622. exit_code = 1
  623. else:
  624. out.warning(
  625. f"{len(result.extra_paths)} local file(s) do not exist on the remote repo. "
  626. "Use --fail-on-extra-files for details."
  627. )
  628. verified_location = result.verified_path
  629. if exit_code != 0:
  630. out.error(
  631. f"Verification failed for '{repo_id}' ({repo_type.value}) in {verified_location}.\n Revision: {result.revision}"
  632. )
  633. raise typer.Exit(code=exit_code)
  634. out.result(
  635. f"Verified {result.checked_count} file(s) for {repo_type.value} '{repo_id}'. All checksums match.",
  636. repo_id=repo_id,
  637. repo_type=repo_type.value,
  638. checked=result.checked_count,
  639. path=str(verified_location),
  640. )