delete_cache.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. # coding=utf-8
  2. # Copyright 2022-present, the HuggingFace Inc. team.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Contains command to delete some revisions from the HF cache directory.
  16. Usage:
  17. huggingface-cli delete-cache
  18. huggingface-cli delete-cache --disable-tui
  19. huggingface-cli delete-cache --dir ~/.cache/huggingface/hub
  20. huggingface-cli delete-cache --sort=size
  21. NOTE:
  22. This command is based on `InquirerPy` to build the multiselect menu in the terminal.
  23. This dependency has to be installed with `pip install "huggingface_hub[cli]"`. Since
  24. we want to avoid as much as possible cross-platform issues, I chose a library that
  25. is built on top of `python-prompt-toolkit` which seems to be a reference in terminal
  26. GUI (actively maintained on both Unix and Windows, 7.9k stars).
  27. For the moment, the TUI feature is in beta.
  28. See:
  29. - https://github.com/kazhala/InquirerPy
  30. - https://inquirerpy.readthedocs.io/en/latest/
  31. - https://github.com/prompt-toolkit/python-prompt-toolkit
  32. Other solutions could have been:
  33. - `simple_term_menu`: would be good as well for our use case but some issues suggest
  34. that Windows is less supported.
  35. See: https://github.com/IngoMeyer441/simple-term-menu
  36. - `PyInquirer`: very similar to `InquirerPy` but older and not maintained anymore.
  37. In particular, no support of Python3.10.
  38. See: https://github.com/CITGuru/PyInquirer
  39. - `pick` (or `pickpack`): easy to use and flexible but built on top of Python's
  40. standard library `curses` that is specific to Unix (not implemented on Windows).
  41. See https://github.com/wong2/pick and https://github.com/anafvana/pickpack.
  42. - `inquirer`: lot of traction (700 stars) but explicitly states "experimental
  43. support of Windows". Not built on top of `python-prompt-toolkit`.
  44. See https://github.com/magmax/python-inquirer
  45. TODO: add support for `huggingface-cli delete-cache aaaaaa bbbbbb cccccc (...)` ?
  46. TODO: add "--keep-last" arg to delete revisions that are not on `main` ref
  47. TODO: add "--filter" arg to filter repositories by name ?
  48. TODO: add "--limit" arg to limit to X repos ?
  49. TODO: add "-y" arg for immediate deletion ?
  50. See discussions in https://github.com/huggingface/huggingface_hub/issues/1025.
  51. """
  52. import os
  53. from argparse import Namespace, _SubParsersAction
  54. from functools import wraps
  55. from tempfile import mkstemp
  56. from typing import Any, Callable, Iterable, List, Literal, Optional, Union
  57. from ..utils import CachedRepoInfo, CachedRevisionInfo, HFCacheInfo, scan_cache_dir
  58. from . import BaseHuggingfaceCLICommand
  59. from ._cli_utils import ANSI, show_deprecation_warning
  60. try:
  61. from InquirerPy import inquirer
  62. from InquirerPy.base.control import Choice
  63. from InquirerPy.separator import Separator
  64. _inquirer_py_available = True
  65. except ImportError:
  66. _inquirer_py_available = False
  67. SortingOption_T = Literal["alphabetical", "lastUpdated", "lastUsed", "size"]
  68. def require_inquirer_py(fn: Callable) -> Callable:
  69. """Decorator to flag methods that require `InquirerPy`."""
  70. # TODO: refactor this + imports in a unified pattern across codebase
  71. @wraps(fn)
  72. def _inner(*args, **kwargs):
  73. if not _inquirer_py_available:
  74. raise ImportError(
  75. "The `delete-cache` command requires extra dependencies to work with"
  76. ' the TUI.\nPlease run `pip install "huggingface_hub[cli]"` to install'
  77. " them.\nOtherwise, disable TUI using the `--disable-tui` flag."
  78. )
  79. return fn(*args, **kwargs)
  80. return _inner
  81. # Possibility for the user to cancel deletion
  82. _CANCEL_DELETION_STR = "CANCEL_DELETION"
  83. class DeleteCacheCommand(BaseHuggingfaceCLICommand):
  84. @staticmethod
  85. def register_subcommand(parser: _SubParsersAction):
  86. delete_cache_parser = parser.add_parser("delete-cache", help="Delete revisions from the cache directory.")
  87. delete_cache_parser.add_argument(
  88. "--dir",
  89. type=str,
  90. default=None,
  91. help="cache directory (optional). Default to the default HuggingFace cache.",
  92. )
  93. delete_cache_parser.add_argument(
  94. "--disable-tui",
  95. action="store_true",
  96. help=(
  97. "Disable Terminal User Interface (TUI) mode. Useful if your"
  98. " platform/terminal doesn't support the multiselect menu."
  99. ),
  100. )
  101. delete_cache_parser.add_argument(
  102. "--sort",
  103. nargs="?",
  104. choices=["alphabetical", "lastUpdated", "lastUsed", "size"],
  105. help=(
  106. "Sort repositories by the specified criteria. Options: "
  107. "'alphabetical' (A-Z), "
  108. "'lastUpdated' (newest first), "
  109. "'lastUsed' (most recent first), "
  110. "'size' (largest first)."
  111. ),
  112. )
  113. delete_cache_parser.set_defaults(func=DeleteCacheCommand)
  114. def __init__(self, args: Namespace) -> None:
  115. self.cache_dir: Optional[str] = args.dir
  116. self.disable_tui: bool = args.disable_tui
  117. self.sort_by: Optional[SortingOption_T] = args.sort
  118. def run(self):
  119. """Run `delete-cache` command with or without TUI."""
  120. show_deprecation_warning("huggingface-cli delete-cache", "hf cache delete")
  121. # Scan cache directory
  122. hf_cache_info = scan_cache_dir(self.cache_dir)
  123. # Manual review from the user
  124. if self.disable_tui:
  125. selected_hashes = _manual_review_no_tui(hf_cache_info, preselected=[], sort_by=self.sort_by)
  126. else:
  127. selected_hashes = _manual_review_tui(hf_cache_info, preselected=[], sort_by=self.sort_by)
  128. # If deletion is not cancelled
  129. if len(selected_hashes) > 0 and _CANCEL_DELETION_STR not in selected_hashes:
  130. confirm_message = _get_expectations_str(hf_cache_info, selected_hashes) + " Confirm deletion ?"
  131. # Confirm deletion
  132. if self.disable_tui:
  133. confirmed = _ask_for_confirmation_no_tui(confirm_message)
  134. else:
  135. confirmed = _ask_for_confirmation_tui(confirm_message)
  136. # Deletion is confirmed
  137. if confirmed:
  138. strategy = hf_cache_info.delete_revisions(*selected_hashes)
  139. print("Start deletion.")
  140. strategy.execute()
  141. print(
  142. f"Done. Deleted {len(strategy.repos)} repo(s) and"
  143. f" {len(strategy.snapshots)} revision(s) for a total of"
  144. f" {strategy.expected_freed_size_str}."
  145. )
  146. return
  147. # Deletion is cancelled
  148. print("Deletion is cancelled. Do nothing.")
  149. def _get_repo_sorting_key(repo: CachedRepoInfo, sort_by: Optional[SortingOption_T] = None):
  150. if sort_by == "alphabetical":
  151. return (repo.repo_type, repo.repo_id.lower()) # by type then name
  152. elif sort_by == "lastUpdated":
  153. return -max(rev.last_modified for rev in repo.revisions) # newest first
  154. elif sort_by == "lastUsed":
  155. return -repo.last_accessed # most recently used first
  156. elif sort_by == "size":
  157. return -repo.size_on_disk # largest first
  158. else:
  159. return (repo.repo_type, repo.repo_id) # default stable order
  160. @require_inquirer_py
  161. def _manual_review_tui(
  162. hf_cache_info: HFCacheInfo,
  163. preselected: List[str],
  164. sort_by: Optional[SortingOption_T] = None,
  165. ) -> List[str]:
  166. """Ask the user for a manual review of the revisions to delete.
  167. Displays a multi-select menu in the terminal (TUI).
  168. """
  169. # Define multiselect list
  170. choices = _get_tui_choices_from_scan(
  171. repos=hf_cache_info.repos,
  172. preselected=preselected,
  173. sort_by=sort_by,
  174. )
  175. checkbox = inquirer.checkbox(
  176. message="Select revisions to delete:",
  177. choices=choices, # List of revisions with some pre-selection
  178. cycle=False, # No loop between top and bottom
  179. height=100, # Large list if possible
  180. # We use the instruction to display to the user the expected effect of the
  181. # deletion.
  182. instruction=_get_expectations_str(
  183. hf_cache_info,
  184. selected_hashes=[c.value for c in choices if isinstance(c, Choice) and c.enabled],
  185. ),
  186. # We use the long instruction to should keybindings instructions to the user
  187. long_instruction="Press <space> to select, <enter> to validate and <ctrl+c> to quit without modification.",
  188. # Message that is displayed once the user validates its selection.
  189. transformer=lambda result: f"{len(result)} revision(s) selected.",
  190. )
  191. # Add a callback to update the information line when a revision is
  192. # selected/unselected
  193. def _update_expectations(_) -> None:
  194. # Hacky way to dynamically set an instruction message to the checkbox when
  195. # a revision hash is selected/unselected.
  196. checkbox._instruction = _get_expectations_str(
  197. hf_cache_info,
  198. selected_hashes=[choice["value"] for choice in checkbox.content_control.choices if choice["enabled"]],
  199. )
  200. checkbox.kb_func_lookup["toggle"].append({"func": _update_expectations})
  201. # Finally display the form to the user.
  202. try:
  203. return checkbox.execute()
  204. except KeyboardInterrupt:
  205. return [] # Quit without deletion
  206. @require_inquirer_py
  207. def _ask_for_confirmation_tui(message: str, default: bool = True) -> bool:
  208. """Ask for confirmation using Inquirer."""
  209. return inquirer.confirm(message, default=default).execute()
  210. def _get_tui_choices_from_scan(
  211. repos: Iterable[CachedRepoInfo],
  212. preselected: List[str],
  213. sort_by: Optional[SortingOption_T] = None,
  214. ) -> List:
  215. """Build a list of choices from the scanned repos.
  216. Args:
  217. repos (*Iterable[`CachedRepoInfo`]*):
  218. List of scanned repos on which we want to delete revisions.
  219. preselected (*List[`str`]*):
  220. List of revision hashes that will be preselected.
  221. sort_by (*Optional[SortingOption_T]*):
  222. Sorting direction. Choices: "alphabetical", "lastUpdated", "lastUsed", "size".
  223. Return:
  224. The list of choices to pass to `inquirer.checkbox`.
  225. """
  226. choices: List[Union[Choice, Separator]] = []
  227. # First choice is to cancel the deletion
  228. choices.append(
  229. Choice(
  230. _CANCEL_DELETION_STR,
  231. name="None of the following (if selected, nothing will be deleted).",
  232. enabled=False,
  233. )
  234. )
  235. # Sort repos based on specified criteria
  236. sorted_repos = sorted(repos, key=lambda repo: _get_repo_sorting_key(repo, sort_by))
  237. for repo in sorted_repos:
  238. # Repo as separator
  239. choices.append(
  240. Separator(
  241. f"\n{repo.repo_type.capitalize()} {repo.repo_id} ({repo.size_on_disk_str},"
  242. f" used {repo.last_accessed_str})"
  243. )
  244. )
  245. for revision in sorted(repo.revisions, key=_revision_sorting_order):
  246. # Revision as choice
  247. choices.append(
  248. Choice(
  249. revision.commit_hash,
  250. name=(
  251. f"{revision.commit_hash[:8]}:"
  252. f" {', '.join(sorted(revision.refs)) or '(detached)'} #"
  253. f" modified {revision.last_modified_str}"
  254. ),
  255. enabled=revision.commit_hash in preselected,
  256. )
  257. )
  258. # Return choices
  259. return choices
  260. def _manual_review_no_tui(
  261. hf_cache_info: HFCacheInfo,
  262. preselected: List[str],
  263. sort_by: Optional[SortingOption_T] = None,
  264. ) -> List[str]:
  265. """Ask the user for a manual review of the revisions to delete.
  266. Used when TUI is disabled. Manual review happens in a separate tmp file that the
  267. user can manually edit.
  268. """
  269. # 1. Generate temporary file with delete commands.
  270. fd, tmp_path = mkstemp(suffix=".txt") # suffix to make it easier to find by editors
  271. os.close(fd)
  272. lines = []
  273. sorted_repos = sorted(hf_cache_info.repos, key=lambda repo: _get_repo_sorting_key(repo, sort_by))
  274. for repo in sorted_repos:
  275. lines.append(
  276. f"\n# {repo.repo_type.capitalize()} {repo.repo_id} ({repo.size_on_disk_str},"
  277. f" used {repo.last_accessed_str})"
  278. )
  279. for revision in sorted(repo.revisions, key=_revision_sorting_order):
  280. lines.append(
  281. # Deselect by prepending a '#'
  282. f"{'' if revision.commit_hash in preselected else '#'} "
  283. f" {revision.commit_hash} # Refs:"
  284. # Print `refs` as comment on same line
  285. f" {', '.join(sorted(revision.refs)) or '(detached)'} # modified"
  286. # Print `last_modified` as comment on same line
  287. f" {revision.last_modified_str}"
  288. )
  289. with open(tmp_path, "w") as f:
  290. f.write(_MANUAL_REVIEW_NO_TUI_INSTRUCTIONS)
  291. f.write("\n".join(lines))
  292. # 2. Prompt instructions to user.
  293. instructions = f"""
  294. TUI is disabled. In order to select which revisions you want to delete, please edit
  295. the following file using the text editor of your choice. Instructions for manual
  296. editing are located at the beginning of the file. Edit the file, save it and confirm
  297. to continue.
  298. File to edit: {ANSI.bold(tmp_path)}
  299. """
  300. print("\n".join(line.strip() for line in instructions.strip().split("\n")))
  301. # 3. Wait for user confirmation.
  302. while True:
  303. selected_hashes = _read_manual_review_tmp_file(tmp_path)
  304. if _ask_for_confirmation_no_tui(
  305. _get_expectations_str(hf_cache_info, selected_hashes) + " Continue ?",
  306. default=False,
  307. ):
  308. break
  309. # 4. Return selected_hashes sorted to maintain stable order
  310. os.remove(tmp_path)
  311. return sorted(selected_hashes) # Sort to maintain stable order
  312. def _ask_for_confirmation_no_tui(message: str, default: bool = True) -> bool:
  313. """Ask for confirmation using pure-python."""
  314. YES = ("y", "yes", "1")
  315. NO = ("n", "no", "0")
  316. DEFAULT = ""
  317. ALL = YES + NO + (DEFAULT,)
  318. full_message = message + (" (Y/n) " if default else " (y/N) ")
  319. while True:
  320. answer = input(full_message).lower()
  321. if answer == DEFAULT:
  322. return default
  323. if answer in YES:
  324. return True
  325. if answer in NO:
  326. return False
  327. print(f"Invalid input. Must be one of {ALL}")
  328. def _get_expectations_str(hf_cache_info: HFCacheInfo, selected_hashes: List[str]) -> str:
  329. """Format a string to display to the user how much space would be saved.
  330. Example:
  331. ```
  332. >>> _get_expectations_str(hf_cache_info, selected_hashes)
  333. '7 revisions selected counting for 4.3G.'
  334. ```
  335. """
  336. if _CANCEL_DELETION_STR in selected_hashes:
  337. return "Nothing will be deleted."
  338. strategy = hf_cache_info.delete_revisions(*selected_hashes)
  339. return f"{len(selected_hashes)} revisions selected counting for {strategy.expected_freed_size_str}."
  340. def _read_manual_review_tmp_file(tmp_path: str) -> List[str]:
  341. """Read the manually reviewed instruction file and return a list of revision hash.
  342. Example:
  343. ```txt
  344. # This is the tmp file content
  345. ###
  346. # Commented out line
  347. 123456789 # revision hash
  348. # Something else
  349. # a_newer_hash # 2 days ago
  350. an_older_hash # 3 days ago
  351. ```
  352. ```py
  353. >>> _read_manual_review_tmp_file(tmp_path)
  354. ['123456789', 'an_older_hash']
  355. ```
  356. """
  357. with open(tmp_path) as f:
  358. content = f.read()
  359. # Split lines
  360. lines = [line.strip() for line in content.split("\n")]
  361. # Filter commented lines
  362. selected_lines = [line for line in lines if not line.startswith("#")]
  363. # Select only before comment
  364. selected_hashes = [line.split("#")[0].strip() for line in selected_lines]
  365. # Return revision hashes
  366. return [hash for hash in selected_hashes if len(hash) > 0]
  367. _MANUAL_REVIEW_NO_TUI_INSTRUCTIONS = f"""
  368. # INSTRUCTIONS
  369. # ------------
  370. # This is a temporary file created by running `huggingface-cli delete-cache` with the
  371. # `--disable-tui` option. It contains a set of revisions that can be deleted from your
  372. # local cache directory.
  373. #
  374. # Please manually review the revisions you want to delete:
  375. # - Revision hashes can be commented out with '#'.
  376. # - Only non-commented revisions in this file will be deleted.
  377. # - Revision hashes that are removed from this file are ignored as well.
  378. # - If `{_CANCEL_DELETION_STR}` line is uncommented, the all cache deletion is cancelled and
  379. # no changes will be applied.
  380. #
  381. # Once you've manually reviewed this file, please confirm deletion in the terminal. This
  382. # file will be automatically removed once done.
  383. # ------------
  384. # KILL SWITCH
  385. # ------------
  386. # Un-comment following line to completely cancel the deletion process
  387. # {_CANCEL_DELETION_STR}
  388. # ------------
  389. # REVISIONS
  390. # ------------
  391. """.strip()
  392. def _revision_sorting_order(revision: CachedRevisionInfo) -> Any:
  393. # Sort by last modified (oldest first)
  394. return revision.last_modified