cache.py 28 KB

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