download.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. # coding=utf-8
  2. # Copyright 202-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 download files from the Hub with the CLI.
  16. Usage:
  17. hf download --help
  18. # Download file
  19. hf download gpt2 config.json
  20. # Download entire repo
  21. hf download fffiloni/zeroscope --repo-type=space --revision=refs/pr/78
  22. # Download repo with filters
  23. hf download gpt2 --include="*.safetensors"
  24. # Download with token
  25. hf download Wauplin/private-model --token=hf_***
  26. # Download quietly (no progress bar, no warnings, only the returned path)
  27. hf download gpt2 config.json --quiet
  28. # Download to local dir
  29. hf download gpt2 --local-dir=./models/gpt2
  30. """
  31. import warnings
  32. from typing import Annotated, Optional, Union
  33. import typer
  34. from huggingface_hub import logging
  35. from huggingface_hub._snapshot_download import snapshot_download
  36. from huggingface_hub.file_download import DryRunFileInfo, hf_hub_download
  37. from huggingface_hub.utils import _format_size, disable_progress_bars, enable_progress_bars, tabulate
  38. from ._cli_utils import RepoIdArg, RepoTypeOpt, RevisionOpt, TokenOpt
  39. logger = logging.get_logger(__name__)
  40. def download(
  41. repo_id: RepoIdArg,
  42. filenames: Annotated[
  43. Optional[list[str]],
  44. typer.Argument(
  45. help="Files to download (e.g. `config.json`, `data/metadata.jsonl`).",
  46. ),
  47. ] = None,
  48. repo_type: RepoTypeOpt = RepoTypeOpt.model,
  49. revision: RevisionOpt = None,
  50. include: Annotated[
  51. Optional[list[str]],
  52. typer.Option(
  53. help="Glob patterns to include from files to download. eg: *.json",
  54. ),
  55. ] = None,
  56. exclude: Annotated[
  57. Optional[list[str]],
  58. typer.Option(
  59. help="Glob patterns to exclude from files to download.",
  60. ),
  61. ] = None,
  62. cache_dir: Annotated[
  63. Optional[str],
  64. typer.Option(
  65. help="Directory where to save files.",
  66. ),
  67. ] = None,
  68. local_dir: Annotated[
  69. Optional[str],
  70. typer.Option(
  71. help="If set, the downloaded file will be placed under this directory. Check out https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-a-local-folder for more details.",
  72. ),
  73. ] = None,
  74. force_download: Annotated[
  75. bool,
  76. typer.Option(
  77. help="If True, the files will be downloaded even if they are already cached.",
  78. ),
  79. ] = False,
  80. dry_run: Annotated[
  81. bool,
  82. typer.Option(
  83. help="If True, perform a dry run without actually downloading the file.",
  84. ),
  85. ] = False,
  86. token: TokenOpt = None,
  87. quiet: Annotated[
  88. bool,
  89. typer.Option(
  90. help="If True, progress bars are disabled and only the path to the download files is printed.",
  91. ),
  92. ] = False,
  93. max_workers: Annotated[
  94. int,
  95. typer.Option(
  96. help="Maximum number of workers to use for downloading files. Default is 8.",
  97. ),
  98. ] = 8,
  99. ) -> None:
  100. """Download files from the Hub."""
  101. def run_download() -> Union[str, DryRunFileInfo, list[DryRunFileInfo]]:
  102. filenames_list = filenames if filenames is not None else []
  103. # Warn user if patterns are ignored
  104. if len(filenames_list) > 0:
  105. if include is not None and len(include) > 0:
  106. warnings.warn("Ignoring `--include` since filenames have being explicitly set.")
  107. if exclude is not None and len(exclude) > 0:
  108. warnings.warn("Ignoring `--exclude` since filenames have being explicitly set.")
  109. # Single file to download: use `hf_hub_download`
  110. if len(filenames_list) == 1:
  111. return hf_hub_download(
  112. repo_id=repo_id,
  113. repo_type=repo_type.value,
  114. revision=revision,
  115. filename=filenames_list[0],
  116. cache_dir=cache_dir,
  117. force_download=force_download,
  118. token=token,
  119. local_dir=local_dir,
  120. library_name="huggingface-cli",
  121. dry_run=dry_run,
  122. )
  123. # Otherwise: use `snapshot_download` to ensure all files comes from same revision
  124. if len(filenames_list) == 0:
  125. allow_patterns = include
  126. ignore_patterns = exclude
  127. else:
  128. allow_patterns = filenames_list
  129. ignore_patterns = None
  130. return snapshot_download(
  131. repo_id=repo_id,
  132. repo_type=repo_type.value,
  133. revision=revision,
  134. allow_patterns=allow_patterns,
  135. ignore_patterns=ignore_patterns,
  136. force_download=force_download,
  137. cache_dir=cache_dir,
  138. token=token,
  139. local_dir=local_dir,
  140. library_name="huggingface-cli",
  141. max_workers=max_workers,
  142. dry_run=dry_run,
  143. )
  144. def _print_result(result: Union[str, DryRunFileInfo, list[DryRunFileInfo]]) -> None:
  145. if isinstance(result, str):
  146. print(result)
  147. return
  148. # Print dry run info
  149. if isinstance(result, DryRunFileInfo):
  150. result = [result]
  151. print(
  152. f"[dry-run] Will download {len([r for r in result if r.will_download])} files (out of {len(result)}) totalling {_format_size(sum(r.file_size for r in result if r.will_download))}."
  153. )
  154. columns = ["File", "Bytes to download"]
  155. items: list[list[Union[str, int]]] = []
  156. for info in sorted(result, key=lambda x: x.filename):
  157. items.append([info.filename, _format_size(info.file_size) if info.will_download else "-"])
  158. print(tabulate(items, headers=columns))
  159. if quiet:
  160. disable_progress_bars()
  161. with warnings.catch_warnings():
  162. warnings.simplefilter("ignore")
  163. _print_result(run_download())
  164. enable_progress_bars()
  165. else:
  166. _print_result(run_download())
  167. logging.set_verbosity_warning()