huggingface-hub 0.31.0rc0__py3-none-any.whl → 1.1.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. huggingface_hub/__init__.py +145 -46
  2. huggingface_hub/_commit_api.py +168 -119
  3. huggingface_hub/_commit_scheduler.py +15 -15
  4. huggingface_hub/_inference_endpoints.py +15 -12
  5. huggingface_hub/_jobs_api.py +301 -0
  6. huggingface_hub/_local_folder.py +18 -3
  7. huggingface_hub/_login.py +31 -63
  8. huggingface_hub/_oauth.py +460 -0
  9. huggingface_hub/_snapshot_download.py +239 -80
  10. huggingface_hub/_space_api.py +5 -5
  11. huggingface_hub/_tensorboard_logger.py +15 -19
  12. huggingface_hub/_upload_large_folder.py +172 -76
  13. huggingface_hub/_webhooks_payload.py +3 -3
  14. huggingface_hub/_webhooks_server.py +13 -25
  15. huggingface_hub/{commands → cli}/__init__.py +1 -15
  16. huggingface_hub/cli/_cli_utils.py +173 -0
  17. huggingface_hub/cli/auth.py +147 -0
  18. huggingface_hub/cli/cache.py +841 -0
  19. huggingface_hub/cli/download.py +189 -0
  20. huggingface_hub/cli/hf.py +60 -0
  21. huggingface_hub/cli/inference_endpoints.py +377 -0
  22. huggingface_hub/cli/jobs.py +772 -0
  23. huggingface_hub/cli/lfs.py +175 -0
  24. huggingface_hub/cli/repo.py +315 -0
  25. huggingface_hub/cli/repo_files.py +94 -0
  26. huggingface_hub/{commands/env.py → cli/system.py} +10 -13
  27. huggingface_hub/cli/upload.py +294 -0
  28. huggingface_hub/cli/upload_large_folder.py +117 -0
  29. huggingface_hub/community.py +20 -12
  30. huggingface_hub/constants.py +38 -53
  31. huggingface_hub/dataclasses.py +609 -0
  32. huggingface_hub/errors.py +80 -30
  33. huggingface_hub/fastai_utils.py +30 -41
  34. huggingface_hub/file_download.py +435 -351
  35. huggingface_hub/hf_api.py +2050 -1124
  36. huggingface_hub/hf_file_system.py +269 -152
  37. huggingface_hub/hub_mixin.py +43 -63
  38. huggingface_hub/inference/_client.py +347 -434
  39. huggingface_hub/inference/_common.py +133 -121
  40. huggingface_hub/inference/_generated/_async_client.py +397 -541
  41. huggingface_hub/inference/_generated/types/__init__.py +5 -1
  42. huggingface_hub/inference/_generated/types/automatic_speech_recognition.py +3 -3
  43. huggingface_hub/inference/_generated/types/base.py +10 -7
  44. huggingface_hub/inference/_generated/types/chat_completion.py +59 -23
  45. huggingface_hub/inference/_generated/types/depth_estimation.py +2 -2
  46. huggingface_hub/inference/_generated/types/document_question_answering.py +2 -2
  47. huggingface_hub/inference/_generated/types/feature_extraction.py +2 -2
  48. huggingface_hub/inference/_generated/types/fill_mask.py +2 -2
  49. huggingface_hub/inference/_generated/types/image_to_image.py +6 -2
  50. huggingface_hub/inference/_generated/types/image_to_video.py +60 -0
  51. huggingface_hub/inference/_generated/types/sentence_similarity.py +3 -3
  52. huggingface_hub/inference/_generated/types/summarization.py +2 -2
  53. huggingface_hub/inference/_generated/types/table_question_answering.py +5 -5
  54. huggingface_hub/inference/_generated/types/text2text_generation.py +2 -2
  55. huggingface_hub/inference/_generated/types/text_generation.py +10 -10
  56. huggingface_hub/inference/_generated/types/text_to_video.py +2 -2
  57. huggingface_hub/inference/_generated/types/token_classification.py +2 -2
  58. huggingface_hub/inference/_generated/types/translation.py +2 -2
  59. huggingface_hub/inference/_generated/types/zero_shot_classification.py +2 -2
  60. huggingface_hub/inference/_generated/types/zero_shot_image_classification.py +2 -2
  61. huggingface_hub/inference/_generated/types/zero_shot_object_detection.py +1 -3
  62. huggingface_hub/inference/_mcp/__init__.py +0 -0
  63. huggingface_hub/inference/_mcp/_cli_hacks.py +88 -0
  64. huggingface_hub/inference/_mcp/agent.py +100 -0
  65. huggingface_hub/inference/_mcp/cli.py +247 -0
  66. huggingface_hub/inference/_mcp/constants.py +81 -0
  67. huggingface_hub/inference/_mcp/mcp_client.py +395 -0
  68. huggingface_hub/inference/_mcp/types.py +45 -0
  69. huggingface_hub/inference/_mcp/utils.py +128 -0
  70. huggingface_hub/inference/_providers/__init__.py +82 -7
  71. huggingface_hub/inference/_providers/_common.py +129 -27
  72. huggingface_hub/inference/_providers/black_forest_labs.py +6 -6
  73. huggingface_hub/inference/_providers/cerebras.py +1 -1
  74. huggingface_hub/inference/_providers/clarifai.py +13 -0
  75. huggingface_hub/inference/_providers/cohere.py +20 -3
  76. huggingface_hub/inference/_providers/fal_ai.py +183 -56
  77. huggingface_hub/inference/_providers/featherless_ai.py +38 -0
  78. huggingface_hub/inference/_providers/fireworks_ai.py +18 -0
  79. huggingface_hub/inference/_providers/groq.py +9 -0
  80. huggingface_hub/inference/_providers/hf_inference.py +69 -30
  81. huggingface_hub/inference/_providers/hyperbolic.py +4 -4
  82. huggingface_hub/inference/_providers/nebius.py +33 -5
  83. huggingface_hub/inference/_providers/novita.py +5 -5
  84. huggingface_hub/inference/_providers/nscale.py +44 -0
  85. huggingface_hub/inference/_providers/openai.py +3 -1
  86. huggingface_hub/inference/_providers/publicai.py +6 -0
  87. huggingface_hub/inference/_providers/replicate.py +31 -13
  88. huggingface_hub/inference/_providers/sambanova.py +18 -4
  89. huggingface_hub/inference/_providers/scaleway.py +28 -0
  90. huggingface_hub/inference/_providers/together.py +20 -5
  91. huggingface_hub/inference/_providers/wavespeed.py +138 -0
  92. huggingface_hub/inference/_providers/zai_org.py +17 -0
  93. huggingface_hub/lfs.py +33 -100
  94. huggingface_hub/repocard.py +34 -38
  95. huggingface_hub/repocard_data.py +57 -57
  96. huggingface_hub/serialization/__init__.py +0 -1
  97. huggingface_hub/serialization/_base.py +12 -15
  98. huggingface_hub/serialization/_dduf.py +8 -8
  99. huggingface_hub/serialization/_torch.py +69 -69
  100. huggingface_hub/utils/__init__.py +19 -8
  101. huggingface_hub/utils/_auth.py +7 -7
  102. huggingface_hub/utils/_cache_manager.py +92 -147
  103. huggingface_hub/utils/_chunk_utils.py +2 -3
  104. huggingface_hub/utils/_deprecation.py +1 -1
  105. huggingface_hub/utils/_dotenv.py +55 -0
  106. huggingface_hub/utils/_experimental.py +7 -5
  107. huggingface_hub/utils/_fixes.py +0 -10
  108. huggingface_hub/utils/_git_credential.py +5 -5
  109. huggingface_hub/utils/_headers.py +8 -30
  110. huggingface_hub/utils/_http.py +398 -239
  111. huggingface_hub/utils/_pagination.py +4 -4
  112. huggingface_hub/utils/_parsing.py +98 -0
  113. huggingface_hub/utils/_paths.py +5 -5
  114. huggingface_hub/utils/_runtime.py +61 -24
  115. huggingface_hub/utils/_safetensors.py +21 -21
  116. huggingface_hub/utils/_subprocess.py +9 -9
  117. huggingface_hub/utils/_telemetry.py +4 -4
  118. huggingface_hub/{commands/_cli_utils.py → utils/_terminal.py} +4 -4
  119. huggingface_hub/utils/_typing.py +25 -5
  120. huggingface_hub/utils/_validators.py +55 -74
  121. huggingface_hub/utils/_verification.py +167 -0
  122. huggingface_hub/utils/_xet.py +64 -17
  123. huggingface_hub/utils/_xet_progress_reporting.py +162 -0
  124. huggingface_hub/utils/insecure_hashlib.py +3 -5
  125. huggingface_hub/utils/logging.py +8 -11
  126. huggingface_hub/utils/tqdm.py +5 -4
  127. {huggingface_hub-0.31.0rc0.dist-info → huggingface_hub-1.1.3.dist-info}/METADATA +94 -85
  128. huggingface_hub-1.1.3.dist-info/RECORD +155 -0
  129. {huggingface_hub-0.31.0rc0.dist-info → huggingface_hub-1.1.3.dist-info}/WHEEL +1 -1
  130. huggingface_hub-1.1.3.dist-info/entry_points.txt +6 -0
  131. huggingface_hub/commands/delete_cache.py +0 -474
  132. huggingface_hub/commands/download.py +0 -200
  133. huggingface_hub/commands/huggingface_cli.py +0 -61
  134. huggingface_hub/commands/lfs.py +0 -200
  135. huggingface_hub/commands/repo_files.py +0 -128
  136. huggingface_hub/commands/scan_cache.py +0 -181
  137. huggingface_hub/commands/tag.py +0 -159
  138. huggingface_hub/commands/upload.py +0 -314
  139. huggingface_hub/commands/upload_large_folder.py +0 -129
  140. huggingface_hub/commands/user.py +0 -304
  141. huggingface_hub/commands/version.py +0 -37
  142. huggingface_hub/inference_api.py +0 -217
  143. huggingface_hub/keras_mixin.py +0 -500
  144. huggingface_hub/repository.py +0 -1477
  145. huggingface_hub/serialization/_tensorflow.py +0 -95
  146. huggingface_hub/utils/_hf_folder.py +0 -68
  147. huggingface_hub-0.31.0rc0.dist-info/RECORD +0 -135
  148. huggingface_hub-0.31.0rc0.dist-info/entry_points.txt +0 -6
  149. {huggingface_hub-0.31.0rc0.dist-info → huggingface_hub-1.1.3.dist-info/licenses}/LICENSE +0 -0
  150. {huggingface_hub-0.31.0rc0.dist-info → huggingface_hub-1.1.3.dist-info}/top_level.txt +0 -0
@@ -1,200 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023-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
-
17
- Usage:
18
- huggingface-cli download --help
19
-
20
- # Download file
21
- huggingface-cli download gpt2 config.json
22
-
23
- # Download entire repo
24
- huggingface-cli download fffiloni/zeroscope --repo-type=space --revision=refs/pr/78
25
-
26
- # Download repo with filters
27
- huggingface-cli download gpt2 --include="*.safetensors"
28
-
29
- # Download with token
30
- huggingface-cli download Wauplin/private-model --token=hf_***
31
-
32
- # Download quietly (no progress bar, no warnings, only the returned path)
33
- huggingface-cli download gpt2 config.json --quiet
34
-
35
- # Download to local dir
36
- huggingface-cli download gpt2 --local-dir=./models/gpt2
37
- """
38
-
39
- import warnings
40
- from argparse import Namespace, _SubParsersAction
41
- from typing import List, Optional
42
-
43
- from huggingface_hub import logging
44
- from huggingface_hub._snapshot_download import snapshot_download
45
- from huggingface_hub.commands import BaseHuggingfaceCLICommand
46
- from huggingface_hub.file_download import hf_hub_download
47
- from huggingface_hub.utils import disable_progress_bars, enable_progress_bars
48
-
49
-
50
- logger = logging.get_logger(__name__)
51
-
52
-
53
- class DownloadCommand(BaseHuggingfaceCLICommand):
54
- @staticmethod
55
- def register_subcommand(parser: _SubParsersAction):
56
- download_parser = parser.add_parser("download", help="Download files from the Hub")
57
- download_parser.add_argument(
58
- "repo_id", type=str, help="ID of the repo to download from (e.g. `username/repo-name`)."
59
- )
60
- download_parser.add_argument(
61
- "filenames", type=str, nargs="*", help="Files to download (e.g. `config.json`, `data/metadata.jsonl`)."
62
- )
63
- download_parser.add_argument(
64
- "--repo-type",
65
- choices=["model", "dataset", "space"],
66
- default="model",
67
- help="Type of repo to download from (defaults to 'model').",
68
- )
69
- download_parser.add_argument(
70
- "--revision",
71
- type=str,
72
- help="An optional Git revision id which can be a branch name, a tag, or a commit hash.",
73
- )
74
- download_parser.add_argument(
75
- "--include", nargs="*", type=str, help="Glob patterns to match files to download."
76
- )
77
- download_parser.add_argument(
78
- "--exclude", nargs="*", type=str, help="Glob patterns to exclude from files to download."
79
- )
80
- download_parser.add_argument(
81
- "--cache-dir", type=str, help="Path to the directory where to save the downloaded files."
82
- )
83
- download_parser.add_argument(
84
- "--local-dir",
85
- type=str,
86
- help=(
87
- "If set, the downloaded file will be placed under this directory. Check out"
88
- " https://huggingface.co/docs/huggingface_hub/guides/download#download-files-to-local-folder for more"
89
- " details."
90
- ),
91
- )
92
- download_parser.add_argument(
93
- "--local-dir-use-symlinks",
94
- choices=["auto", "True", "False"],
95
- help=("Deprecated and ignored. Downloading to a local directory does not use symlinks anymore."),
96
- )
97
- download_parser.add_argument(
98
- "--force-download",
99
- action="store_true",
100
- help="If True, the files will be downloaded even if they are already cached.",
101
- )
102
- download_parser.add_argument(
103
- "--resume-download",
104
- action="store_true",
105
- help="Deprecated and ignored. Downloading a file to local dir always attempts to resume previously interrupted downloads (unless hf-transfer is enabled).",
106
- )
107
- download_parser.add_argument(
108
- "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens"
109
- )
110
- download_parser.add_argument(
111
- "--quiet",
112
- action="store_true",
113
- help="If True, progress bars are disabled and only the path to the download files is printed.",
114
- )
115
- download_parser.add_argument(
116
- "--max-workers",
117
- type=int,
118
- default=8,
119
- help="Maximum number of workers to use for downloading files. Default is 8.",
120
- )
121
- download_parser.set_defaults(func=DownloadCommand)
122
-
123
- def __init__(self, args: Namespace) -> None:
124
- self.token = args.token
125
- self.repo_id: str = args.repo_id
126
- self.filenames: List[str] = args.filenames
127
- self.repo_type: str = args.repo_type
128
- self.revision: Optional[str] = args.revision
129
- self.include: Optional[List[str]] = args.include
130
- self.exclude: Optional[List[str]] = args.exclude
131
- self.cache_dir: Optional[str] = args.cache_dir
132
- self.local_dir: Optional[str] = args.local_dir
133
- self.force_download: bool = args.force_download
134
- self.resume_download: Optional[bool] = args.resume_download or None
135
- self.quiet: bool = args.quiet
136
- self.max_workers: int = args.max_workers
137
-
138
- if args.local_dir_use_symlinks is not None:
139
- warnings.warn(
140
- "Ignoring --local-dir-use-symlinks. Downloading to a local directory does not use symlinks anymore.",
141
- FutureWarning,
142
- )
143
-
144
- def run(self) -> None:
145
- if self.quiet:
146
- disable_progress_bars()
147
- with warnings.catch_warnings():
148
- warnings.simplefilter("ignore")
149
- print(self._download()) # Print path to downloaded files
150
- enable_progress_bars()
151
- else:
152
- logging.set_verbosity_info()
153
- print(self._download()) # Print path to downloaded files
154
- logging.set_verbosity_warning()
155
-
156
- def _download(self) -> str:
157
- # Warn user if patterns are ignored
158
- if len(self.filenames) > 0:
159
- if self.include is not None and len(self.include) > 0:
160
- warnings.warn("Ignoring `--include` since filenames have being explicitly set.")
161
- if self.exclude is not None and len(self.exclude) > 0:
162
- warnings.warn("Ignoring `--exclude` since filenames have being explicitly set.")
163
-
164
- # Single file to download: use `hf_hub_download`
165
- if len(self.filenames) == 1:
166
- return hf_hub_download(
167
- repo_id=self.repo_id,
168
- repo_type=self.repo_type,
169
- revision=self.revision,
170
- filename=self.filenames[0],
171
- cache_dir=self.cache_dir,
172
- resume_download=self.resume_download,
173
- force_download=self.force_download,
174
- token=self.token,
175
- local_dir=self.local_dir,
176
- library_name="huggingface-cli",
177
- )
178
-
179
- # Otherwise: use `snapshot_download` to ensure all files comes from same revision
180
- elif len(self.filenames) == 0:
181
- allow_patterns = self.include
182
- ignore_patterns = self.exclude
183
- else:
184
- allow_patterns = self.filenames
185
- ignore_patterns = None
186
-
187
- return snapshot_download(
188
- repo_id=self.repo_id,
189
- repo_type=self.repo_type,
190
- revision=self.revision,
191
- allow_patterns=allow_patterns,
192
- ignore_patterns=ignore_patterns,
193
- resume_download=self.resume_download,
194
- force_download=self.force_download,
195
- cache_dir=self.cache_dir,
196
- token=self.token,
197
- local_dir=self.local_dir,
198
- library_name="huggingface-cli",
199
- max_workers=self.max_workers,
200
- )
@@ -1,61 +0,0 @@
1
- # Copyright 2020 The HuggingFace Team. All rights reserved.
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
-
15
- from argparse import ArgumentParser
16
-
17
- from huggingface_hub.commands.delete_cache import DeleteCacheCommand
18
- from huggingface_hub.commands.download import DownloadCommand
19
- from huggingface_hub.commands.env import EnvironmentCommand
20
- from huggingface_hub.commands.lfs import LfsCommands
21
- from huggingface_hub.commands.repo_files import RepoFilesCommand
22
- from huggingface_hub.commands.scan_cache import ScanCacheCommand
23
- from huggingface_hub.commands.tag import TagCommands
24
- from huggingface_hub.commands.upload import UploadCommand
25
- from huggingface_hub.commands.upload_large_folder import UploadLargeFolderCommand
26
- from huggingface_hub.commands.user import UserCommands
27
- from huggingface_hub.commands.version import VersionCommand
28
-
29
-
30
- def main():
31
- parser = ArgumentParser("huggingface-cli", usage="huggingface-cli <command> [<args>]")
32
- commands_parser = parser.add_subparsers(help="huggingface-cli command helpers")
33
-
34
- # Register commands
35
- DownloadCommand.register_subcommand(commands_parser)
36
- UploadCommand.register_subcommand(commands_parser)
37
- RepoFilesCommand.register_subcommand(commands_parser)
38
- EnvironmentCommand.register_subcommand(commands_parser)
39
- UserCommands.register_subcommand(commands_parser)
40
- LfsCommands.register_subcommand(commands_parser)
41
- ScanCacheCommand.register_subcommand(commands_parser)
42
- DeleteCacheCommand.register_subcommand(commands_parser)
43
- TagCommands.register_subcommand(commands_parser)
44
- VersionCommand.register_subcommand(commands_parser)
45
-
46
- # Experimental
47
- UploadLargeFolderCommand.register_subcommand(commands_parser)
48
-
49
- # Let's go
50
- args = parser.parse_args()
51
- if not hasattr(args, "func"):
52
- parser.print_help()
53
- exit(1)
54
-
55
- # Run
56
- service = args.func(args)
57
- service.run()
58
-
59
-
60
- if __name__ == "__main__":
61
- main()
@@ -1,200 +0,0 @@
1
- """
2
- Implementation of a custom transfer agent for the transfer type "multipart" for
3
- git-lfs.
4
-
5
- Inspired by:
6
- github.com/cbartz/git-lfs-swift-transfer-agent/blob/master/git_lfs_swift_transfer.py
7
-
8
- Spec is: github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
9
-
10
-
11
- To launch debugger while developing:
12
-
13
- ``` [lfs "customtransfer.multipart"]
14
- path = /path/to/huggingface_hub/.env/bin/python args = -m debugpy --listen 5678
15
- --wait-for-client
16
- /path/to/huggingface_hub/src/huggingface_hub/commands/huggingface_cli.py
17
- lfs-multipart-upload ```"""
18
-
19
- import json
20
- import os
21
- import subprocess
22
- import sys
23
- from argparse import _SubParsersAction
24
- from typing import Dict, List, Optional
25
-
26
- from huggingface_hub.commands import BaseHuggingfaceCLICommand
27
- from huggingface_hub.lfs import LFS_MULTIPART_UPLOAD_COMMAND
28
-
29
- from ..utils import get_session, hf_raise_for_status, logging
30
- from ..utils._lfs import SliceFileObj
31
-
32
-
33
- logger = logging.get_logger(__name__)
34
-
35
-
36
- class LfsCommands(BaseHuggingfaceCLICommand):
37
- """
38
- Implementation of a custom transfer agent for the transfer type "multipart"
39
- for git-lfs. This lets users upload large files >5GB 🔥. Spec for LFS custom
40
- transfer agent is:
41
- https://github.com/git-lfs/git-lfs/blob/master/docs/custom-transfers.md
42
-
43
- This introduces two commands to the CLI:
44
-
45
- 1. $ huggingface-cli lfs-enable-largefiles
46
-
47
- This should be executed once for each model repo that contains a model file
48
- >5GB. It's documented in the error message you get if you just try to git
49
- push a 5GB file without having enabled it before.
50
-
51
- 2. $ huggingface-cli lfs-multipart-upload
52
-
53
- This command is called by lfs directly and is not meant to be called by the
54
- user.
55
- """
56
-
57
- @staticmethod
58
- def register_subcommand(parser: _SubParsersAction):
59
- enable_parser = parser.add_parser(
60
- "lfs-enable-largefiles", help="Configure your repository to enable upload of files > 5GB."
61
- )
62
- enable_parser.add_argument("path", type=str, help="Local path to repository you want to configure.")
63
- enable_parser.set_defaults(func=lambda args: LfsEnableCommand(args))
64
-
65
- # Command will get called by git-lfs, do not call it directly.
66
- upload_parser = parser.add_parser(LFS_MULTIPART_UPLOAD_COMMAND, add_help=False)
67
- upload_parser.set_defaults(func=lambda args: LfsUploadCommand(args))
68
-
69
-
70
- class LfsEnableCommand:
71
- def __init__(self, args):
72
- self.args = args
73
-
74
- def run(self):
75
- local_path = os.path.abspath(self.args.path)
76
- if not os.path.isdir(local_path):
77
- print("This does not look like a valid git repo.")
78
- exit(1)
79
- subprocess.run(
80
- "git config lfs.customtransfer.multipart.path huggingface-cli".split(),
81
- check=True,
82
- cwd=local_path,
83
- )
84
- subprocess.run(
85
- f"git config lfs.customtransfer.multipart.args {LFS_MULTIPART_UPLOAD_COMMAND}".split(),
86
- check=True,
87
- cwd=local_path,
88
- )
89
- print("Local repo set up for largefiles")
90
-
91
-
92
- def write_msg(msg: Dict):
93
- """Write out the message in Line delimited JSON."""
94
- msg_str = json.dumps(msg) + "\n"
95
- sys.stdout.write(msg_str)
96
- sys.stdout.flush()
97
-
98
-
99
- def read_msg() -> Optional[Dict]:
100
- """Read Line delimited JSON from stdin."""
101
- msg = json.loads(sys.stdin.readline().strip())
102
-
103
- if "terminate" in (msg.get("type"), msg.get("event")):
104
- # terminate message received
105
- return None
106
-
107
- if msg.get("event") not in ("download", "upload"):
108
- logger.critical("Received unexpected message")
109
- sys.exit(1)
110
-
111
- return msg
112
-
113
-
114
- class LfsUploadCommand:
115
- def __init__(self, args) -> None:
116
- self.args = args
117
-
118
- def run(self) -> None:
119
- # Immediately after invoking a custom transfer process, git-lfs
120
- # sends initiation data to the process over stdin.
121
- # This tells the process useful information about the configuration.
122
- init_msg = json.loads(sys.stdin.readline().strip())
123
- if not (init_msg.get("event") == "init" and init_msg.get("operation") == "upload"):
124
- write_msg({"error": {"code": 32, "message": "Wrong lfs init operation"}})
125
- sys.exit(1)
126
-
127
- # The transfer process should use the information it needs from the
128
- # initiation structure, and also perform any one-off setup tasks it
129
- # needs to do. It should then respond on stdout with a simple empty
130
- # confirmation structure, as follows:
131
- write_msg({})
132
-
133
- # After the initiation exchange, git-lfs will send any number of
134
- # transfer requests to the stdin of the transfer process, in a serial sequence.
135
- while True:
136
- msg = read_msg()
137
- if msg is None:
138
- # When all transfers have been processed, git-lfs will send
139
- # a terminate event to the stdin of the transfer process.
140
- # On receiving this message the transfer process should
141
- # clean up and terminate. No response is expected.
142
- sys.exit(0)
143
-
144
- oid = msg["oid"]
145
- filepath = msg["path"]
146
- completion_url = msg["action"]["href"]
147
- header = msg["action"]["header"]
148
- chunk_size = int(header.pop("chunk_size"))
149
- presigned_urls: List[str] = list(header.values())
150
-
151
- # Send a "started" progress event to allow other workers to start.
152
- # Otherwise they're delayed until first "progress" event is reported,
153
- # i.e. after the first 5GB by default (!)
154
- write_msg(
155
- {
156
- "event": "progress",
157
- "oid": oid,
158
- "bytesSoFar": 1,
159
- "bytesSinceLast": 0,
160
- }
161
- )
162
-
163
- parts = []
164
- with open(filepath, "rb") as file:
165
- for i, presigned_url in enumerate(presigned_urls):
166
- with SliceFileObj(
167
- file,
168
- seek_from=i * chunk_size,
169
- read_limit=chunk_size,
170
- ) as data:
171
- r = get_session().put(presigned_url, data=data)
172
- hf_raise_for_status(r)
173
- parts.append(
174
- {
175
- "etag": r.headers.get("etag"),
176
- "partNumber": i + 1,
177
- }
178
- )
179
- # In order to support progress reporting while data is uploading / downloading,
180
- # the transfer process should post messages to stdout
181
- write_msg(
182
- {
183
- "event": "progress",
184
- "oid": oid,
185
- "bytesSoFar": (i + 1) * chunk_size,
186
- "bytesSinceLast": chunk_size,
187
- }
188
- )
189
- # Not precise but that's ok.
190
-
191
- r = get_session().post(
192
- completion_url,
193
- json={
194
- "oid": oid,
195
- "parts": parts,
196
- },
197
- )
198
- hf_raise_for_status(r)
199
-
200
- write_msg({"event": "complete", "oid": oid})
@@ -1,128 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2023-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 update or delete files in a repository using the CLI.
16
-
17
- Usage:
18
- # delete all
19
- huggingface-cli repo-files <repo_id> delete "*"
20
-
21
- # delete single file
22
- huggingface-cli repo-files <repo_id> delete file.txt
23
-
24
- # delete single folder
25
- huggingface-cli repo-files <repo_id> delete folder/
26
-
27
- # delete multiple
28
- huggingface-cli repo-files <repo_id> delete file.txt folder/ file2.txt
29
-
30
- # delete multiple patterns
31
- huggingface-cli repo-files <repo_id> delete file.txt "*.json" "folder/*.parquet"
32
-
33
- # delete from different revision / repo-type
34
- huggingface-cli repo-files <repo_id> delete file.txt --revision=refs/pr/1 --repo-type=dataset
35
- """
36
-
37
- from argparse import _SubParsersAction
38
- from typing import List, Optional
39
-
40
- from huggingface_hub import logging
41
- from huggingface_hub.commands import BaseHuggingfaceCLICommand
42
- from huggingface_hub.hf_api import HfApi
43
-
44
-
45
- logger = logging.get_logger(__name__)
46
-
47
-
48
- class DeleteFilesSubCommand:
49
- def __init__(self, args) -> None:
50
- self.args = args
51
- self.repo_id: str = args.repo_id
52
- self.repo_type: Optional[str] = args.repo_type
53
- self.revision: Optional[str] = args.revision
54
- self.api: HfApi = HfApi(token=args.token, library_name="huggingface-cli")
55
- self.patterns: List[str] = args.patterns
56
- self.commit_message: Optional[str] = args.commit_message
57
- self.commit_description: Optional[str] = args.commit_description
58
- self.create_pr: bool = args.create_pr
59
- self.token: Optional[str] = args.token
60
-
61
- def run(self) -> None:
62
- logging.set_verbosity_info()
63
- url = self.api.delete_files(
64
- delete_patterns=self.patterns,
65
- repo_id=self.repo_id,
66
- repo_type=self.repo_type,
67
- revision=self.revision,
68
- commit_message=self.commit_message,
69
- commit_description=self.commit_description,
70
- create_pr=self.create_pr,
71
- )
72
- print(f"Files correctly deleted from repo. Commit: {url}.")
73
- logging.set_verbosity_warning()
74
-
75
-
76
- class RepoFilesCommand(BaseHuggingfaceCLICommand):
77
- @staticmethod
78
- def register_subcommand(parser: _SubParsersAction):
79
- repo_files_parser = parser.add_parser("repo-files", help="Manage files in a repo on the Hub")
80
- repo_files_parser.add_argument(
81
- "repo_id", type=str, help="The ID of the repo to manage (e.g. `username/repo-name`)."
82
- )
83
- repo_files_subparsers = repo_files_parser.add_subparsers(
84
- help="Action to execute against the files.",
85
- required=True,
86
- )
87
- delete_subparser = repo_files_subparsers.add_parser(
88
- "delete",
89
- help="Delete files from a repo on the Hub",
90
- )
91
- delete_subparser.set_defaults(func=lambda args: DeleteFilesSubCommand(args))
92
- delete_subparser.add_argument(
93
- "patterns",
94
- nargs="+",
95
- type=str,
96
- help="Glob patterns to match files to delete.",
97
- )
98
- delete_subparser.add_argument(
99
- "--repo-type",
100
- choices=["model", "dataset", "space"],
101
- default="model",
102
- help="Type of the repo to upload to (e.g. `dataset`).",
103
- )
104
- delete_subparser.add_argument(
105
- "--revision",
106
- type=str,
107
- help=(
108
- "An optional Git revision to push to. It can be a branch name "
109
- "or a PR reference. If revision does not"
110
- " exist and `--create-pr` is not set, a branch will be automatically created."
111
- ),
112
- )
113
- delete_subparser.add_argument(
114
- "--commit-message", type=str, help="The summary / title / first line of the generated commit."
115
- )
116
- delete_subparser.add_argument(
117
- "--commit-description", type=str, help="The description of the generated commit."
118
- )
119
- delete_subparser.add_argument(
120
- "--create-pr", action="store_true", help="Whether to create a new Pull Request for these changes."
121
- )
122
- repo_files_parser.add_argument(
123
- "--token",
124
- type=str,
125
- help="A User Access Token generated from https://huggingface.co/settings/tokens",
126
- )
127
-
128
- repo_files_parser.set_defaults(func=RepoFilesCommand)