huggingface-hub 1.0.0rc1__py3-none-any.whl → 1.0.0rc3__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.

Potentially problematic release.


This version of huggingface-hub might be problematic. Click here for more details.

Files changed (59) hide show
  1. huggingface_hub/__init__.py +4 -7
  2. huggingface_hub/_commit_api.py +126 -66
  3. huggingface_hub/_commit_scheduler.py +4 -7
  4. huggingface_hub/_login.py +10 -16
  5. huggingface_hub/_snapshot_download.py +119 -21
  6. huggingface_hub/_tensorboard_logger.py +2 -5
  7. huggingface_hub/_upload_large_folder.py +1 -2
  8. huggingface_hub/_webhooks_server.py +8 -20
  9. huggingface_hub/cli/_cli_utils.py +12 -6
  10. huggingface_hub/cli/download.py +32 -7
  11. huggingface_hub/cli/repo.py +137 -5
  12. huggingface_hub/dataclasses.py +122 -2
  13. huggingface_hub/errors.py +4 -0
  14. huggingface_hub/fastai_utils.py +22 -32
  15. huggingface_hub/file_download.py +234 -38
  16. huggingface_hub/hf_api.py +385 -424
  17. huggingface_hub/hf_file_system.py +55 -65
  18. huggingface_hub/inference/_client.py +27 -48
  19. huggingface_hub/inference/_generated/_async_client.py +27 -48
  20. huggingface_hub/inference/_generated/types/image_to_image.py +6 -2
  21. huggingface_hub/inference/_mcp/agent.py +2 -5
  22. huggingface_hub/inference/_mcp/mcp_client.py +6 -8
  23. huggingface_hub/inference/_providers/__init__.py +16 -0
  24. huggingface_hub/inference/_providers/_common.py +2 -0
  25. huggingface_hub/inference/_providers/fal_ai.py +2 -0
  26. huggingface_hub/inference/_providers/publicai.py +6 -0
  27. huggingface_hub/inference/_providers/scaleway.py +28 -0
  28. huggingface_hub/inference/_providers/zai_org.py +17 -0
  29. huggingface_hub/lfs.py +14 -8
  30. huggingface_hub/repocard.py +12 -16
  31. huggingface_hub/serialization/_base.py +3 -6
  32. huggingface_hub/serialization/_torch.py +16 -34
  33. huggingface_hub/utils/__init__.py +1 -2
  34. huggingface_hub/utils/_cache_manager.py +42 -72
  35. huggingface_hub/utils/_chunk_utils.py +2 -3
  36. huggingface_hub/utils/_http.py +37 -68
  37. huggingface_hub/utils/_validators.py +2 -2
  38. huggingface_hub/utils/logging.py +8 -11
  39. {huggingface_hub-1.0.0rc1.dist-info → huggingface_hub-1.0.0rc3.dist-info}/METADATA +2 -2
  40. {huggingface_hub-1.0.0rc1.dist-info → huggingface_hub-1.0.0rc3.dist-info}/RECORD +44 -56
  41. {huggingface_hub-1.0.0rc1.dist-info → huggingface_hub-1.0.0rc3.dist-info}/entry_points.txt +0 -1
  42. huggingface_hub/commands/__init__.py +0 -27
  43. huggingface_hub/commands/_cli_utils.py +0 -74
  44. huggingface_hub/commands/delete_cache.py +0 -476
  45. huggingface_hub/commands/download.py +0 -195
  46. huggingface_hub/commands/env.py +0 -39
  47. huggingface_hub/commands/huggingface_cli.py +0 -65
  48. huggingface_hub/commands/lfs.py +0 -200
  49. huggingface_hub/commands/repo.py +0 -151
  50. huggingface_hub/commands/repo_files.py +0 -132
  51. huggingface_hub/commands/scan_cache.py +0 -183
  52. huggingface_hub/commands/tag.py +0 -159
  53. huggingface_hub/commands/upload.py +0 -318
  54. huggingface_hub/commands/upload_large_folder.py +0 -131
  55. huggingface_hub/commands/user.py +0 -207
  56. huggingface_hub/commands/version.py +0 -40
  57. {huggingface_hub-1.0.0rc1.dist-info → huggingface_hub-1.0.0rc3.dist-info}/LICENSE +0 -0
  58. {huggingface_hub-1.0.0rc1.dist-info → huggingface_hub-1.0.0rc3.dist-info}/WHEEL +0 -0
  59. {huggingface_hub-1.0.0rc1.dist-info → huggingface_hub-1.0.0rc3.dist-info}/top_level.txt +0 -0
@@ -1,183 +0,0 @@
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 scan the HF cache directory.
16
-
17
- Usage:
18
- huggingface-cli scan-cache
19
- huggingface-cli scan-cache -v
20
- huggingface-cli scan-cache -vvv
21
- huggingface-cli scan-cache --dir ~/.cache/huggingface/hub
22
- """
23
-
24
- import time
25
- from argparse import Namespace, _SubParsersAction
26
- from typing import Optional
27
-
28
- from ..utils import CacheNotFound, HFCacheInfo, scan_cache_dir
29
- from . import BaseHuggingfaceCLICommand
30
- from ._cli_utils import ANSI, show_deprecation_warning, tabulate
31
-
32
-
33
- class ScanCacheCommand(BaseHuggingfaceCLICommand):
34
- @staticmethod
35
- def register_subcommand(parser: _SubParsersAction):
36
- scan_cache_parser = parser.add_parser("scan-cache", help="Scan cache directory.")
37
-
38
- scan_cache_parser.add_argument(
39
- "--dir",
40
- type=str,
41
- default=None,
42
- help="cache directory to scan (optional). Default to the default HuggingFace cache.",
43
- )
44
- scan_cache_parser.add_argument(
45
- "-v",
46
- "--verbose",
47
- action="count",
48
- default=0,
49
- help="show a more verbose output",
50
- )
51
- scan_cache_parser.set_defaults(func=ScanCacheCommand)
52
-
53
- def __init__(self, args: Namespace) -> None:
54
- self.verbosity: int = args.verbose
55
- self.cache_dir: Optional[str] = args.dir
56
-
57
- def run(self):
58
- show_deprecation_warning("huggingface-cli scan-cache", "hf cache scan")
59
-
60
- try:
61
- t0 = time.time()
62
- hf_cache_info = scan_cache_dir(self.cache_dir)
63
- t1 = time.time()
64
- except CacheNotFound as exc:
65
- cache_dir = exc.cache_dir
66
- print(f"Cache directory not found: {cache_dir}")
67
- return
68
-
69
- self._print_hf_cache_info_as_table(hf_cache_info)
70
-
71
- print(
72
- f"\nDone in {round(t1 - t0, 1)}s. Scanned {len(hf_cache_info.repos)} repo(s)"
73
- f" for a total of {ANSI.red(hf_cache_info.size_on_disk_str)}."
74
- )
75
- if len(hf_cache_info.warnings) > 0:
76
- message = f"Got {len(hf_cache_info.warnings)} warning(s) while scanning."
77
- if self.verbosity >= 3:
78
- print(ANSI.gray(message))
79
- for warning in hf_cache_info.warnings:
80
- print(ANSI.gray(str(warning)))
81
- else:
82
- print(ANSI.gray(message + " Use -vvv to print details."))
83
-
84
- def _print_hf_cache_info_as_table(self, hf_cache_info: HFCacheInfo) -> None:
85
- print(get_table(hf_cache_info, verbosity=self.verbosity))
86
-
87
-
88
- def get_table(hf_cache_info: HFCacheInfo, *, verbosity: int = 0) -> str:
89
- """Generate a table from the [`HFCacheInfo`] object.
90
-
91
- Pass `verbosity=0` to get a table with a single row per repo, with columns
92
- "repo_id", "repo_type", "size_on_disk", "nb_files", "last_accessed", "last_modified", "refs", "local_path".
93
-
94
- Pass `verbosity=1` to get a table with a row per repo and revision (thus multiple rows can appear for a single repo), with columns
95
- "repo_id", "repo_type", "revision", "size_on_disk", "nb_files", "last_modified", "refs", "local_path".
96
-
97
- Example:
98
- ```py
99
- >>> from huggingface_hub.utils import scan_cache_dir
100
- >>> from huggingface_hub.commands.scan_cache import get_table
101
-
102
- >>> hf_cache_info = scan_cache_dir()
103
- HFCacheInfo(...)
104
-
105
- >>> print(get_table(hf_cache_info, verbosity=0))
106
- REPO ID REPO TYPE SIZE ON DISK NB FILES LAST_ACCESSED LAST_MODIFIED REFS LOCAL PATH
107
- --------------------------------------------------- --------- ------------ -------- ------------- ------------- ---- --------------------------------------------------------------------------------------------------
108
- roberta-base model 2.7M 5 1 day ago 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--roberta-base
109
- suno/bark model 8.8K 1 1 week ago 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--suno--bark
110
- t5-base model 893.8M 4 4 days ago 7 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-base
111
- t5-large model 3.0G 4 5 weeks ago 5 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-large
112
-
113
- >>> print(get_table(hf_cache_info, verbosity=1))
114
- REPO ID REPO TYPE REVISION SIZE ON DISK NB FILES LAST_MODIFIED REFS LOCAL PATH
115
- --------------------------------------------------- --------- ---------------------------------------- ------------ -------- ------------- ---- -----------------------------------------------------------------------------------------------------------------------------------------------------
116
- roberta-base model e2da8e2f811d1448a5b465c236feacd80ffbac7b 2.7M 5 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--roberta-base\\snapshots\\e2da8e2f811d1448a5b465c236feacd80ffbac7b
117
- suno/bark model 70a8a7d34168586dc5d028fa9666aceade177992 8.8K 1 1 week ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--suno--bark\\snapshots\\70a8a7d34168586dc5d028fa9666aceade177992
118
- t5-base model a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1 893.8M 4 7 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-base\\snapshots\\a9723ea7f1b39c1eae772870f3b547bf6ef7e6c1
119
- t5-large model 150ebc2c4b72291e770f58e6057481c8d2ed331a 3.0G 4 5 months ago main C:\\Users\\admin\\.cache\\huggingface\\hub\\models--t5-large\\snapshots\\150ebc2c4b72291e770f58e6057481c8d2ed331a ```
120
- ```
121
-
122
- Args:
123
- hf_cache_info ([`HFCacheInfo`]):
124
- The HFCacheInfo object to print.
125
- verbosity (`int`, *optional*):
126
- The verbosity level. Defaults to 0.
127
-
128
- Returns:
129
- `str`: The table as a string.
130
- """
131
- if verbosity == 0:
132
- return tabulate(
133
- rows=[
134
- [
135
- repo.repo_id,
136
- repo.repo_type,
137
- "{:>12}".format(repo.size_on_disk_str),
138
- repo.nb_files,
139
- repo.last_accessed_str,
140
- repo.last_modified_str,
141
- ", ".join(sorted(repo.refs)),
142
- str(repo.repo_path),
143
- ]
144
- for repo in sorted(hf_cache_info.repos, key=lambda repo: repo.repo_path)
145
- ],
146
- headers=[
147
- "REPO ID",
148
- "REPO TYPE",
149
- "SIZE ON DISK",
150
- "NB FILES",
151
- "LAST_ACCESSED",
152
- "LAST_MODIFIED",
153
- "REFS",
154
- "LOCAL PATH",
155
- ],
156
- )
157
- else:
158
- return tabulate(
159
- rows=[
160
- [
161
- repo.repo_id,
162
- repo.repo_type,
163
- revision.commit_hash,
164
- "{:>12}".format(revision.size_on_disk_str),
165
- revision.nb_files,
166
- revision.last_modified_str,
167
- ", ".join(sorted(revision.refs)),
168
- str(revision.snapshot_path),
169
- ]
170
- for repo in sorted(hf_cache_info.repos, key=lambda repo: repo.repo_path)
171
- for revision in sorted(repo.revisions, key=lambda revision: revision.commit_hash)
172
- ],
173
- headers=[
174
- "REPO ID",
175
- "REPO TYPE",
176
- "REVISION",
177
- "SIZE ON DISK",
178
- "NB FILES",
179
- "LAST_MODIFIED",
180
- "REFS",
181
- "LOCAL PATH",
182
- ],
183
- )
@@ -1,159 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2024-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
-
16
- """Contains commands to perform tag management with the CLI.
17
-
18
- Usage Examples:
19
- - Create a tag:
20
- $ huggingface-cli tag user/my-model 1.0 --message "First release"
21
- $ huggingface-cli tag user/my-model 1.0 -m "First release" --revision develop
22
- $ huggingface-cli tag user/my-dataset 1.0 -m "First release" --repo-type dataset
23
- $ huggingface-cli tag user/my-space 1.0
24
- - List all tags:
25
- $ huggingface-cli tag -l user/my-model
26
- $ huggingface-cli tag --list user/my-dataset --repo-type dataset
27
- - Delete a tag:
28
- $ huggingface-cli tag -d user/my-model 1.0
29
- $ huggingface-cli tag --delete user/my-dataset 1.0 --repo-type dataset
30
- $ huggingface-cli tag -d user/my-space 1.0 -y
31
- """
32
-
33
- from argparse import Namespace, _SubParsersAction
34
-
35
- from huggingface_hub.commands import BaseHuggingfaceCLICommand
36
- from huggingface_hub.constants import (
37
- REPO_TYPES,
38
- )
39
- from huggingface_hub.hf_api import HfApi
40
-
41
- from ..errors import HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundError
42
- from ._cli_utils import ANSI, show_deprecation_warning
43
-
44
-
45
- class TagCommands(BaseHuggingfaceCLICommand):
46
- @staticmethod
47
- def register_subcommand(parser: _SubParsersAction):
48
- tag_parser = parser.add_parser("tag", help="(create, list, delete) tags for a repo in the hub")
49
-
50
- tag_parser.add_argument("repo_id", type=str, help="The ID of the repo to tag (e.g. `username/repo-name`).")
51
- tag_parser.add_argument("tag", nargs="?", type=str, help="The name of the tag for creation or deletion.")
52
- tag_parser.add_argument("-m", "--message", type=str, help="The description of the tag to create.")
53
- tag_parser.add_argument("--revision", type=str, help="The git revision to tag.")
54
- tag_parser.add_argument(
55
- "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens."
56
- )
57
- tag_parser.add_argument(
58
- "--repo-type",
59
- choices=["model", "dataset", "space"],
60
- default="model",
61
- help="Set the type of repository (model, dataset, or space).",
62
- )
63
- tag_parser.add_argument("-y", "--yes", action="store_true", help="Answer Yes to prompts automatically.")
64
-
65
- tag_parser.add_argument("-l", "--list", action="store_true", help="List tags for a repository.")
66
- tag_parser.add_argument("-d", "--delete", action="store_true", help="Delete a tag for a repository.")
67
-
68
- tag_parser.set_defaults(func=lambda args: handle_commands(args))
69
-
70
-
71
- def handle_commands(args: Namespace):
72
- show_deprecation_warning("huggingface-cli tag", "hf repo tag")
73
-
74
- if args.list:
75
- return TagListCommand(args)
76
- elif args.delete:
77
- return TagDeleteCommand(args)
78
- else:
79
- return TagCreateCommand(args)
80
-
81
-
82
- class TagCommand:
83
- def __init__(self, args: Namespace):
84
- self.args = args
85
- self.api = HfApi(token=self.args.token)
86
- self.repo_id = self.args.repo_id
87
- self.repo_type = self.args.repo_type
88
- if self.repo_type not in REPO_TYPES:
89
- print("Invalid repo --repo-type")
90
- exit(1)
91
-
92
-
93
- class TagCreateCommand(TagCommand):
94
- def run(self):
95
- print(f"You are about to create tag {ANSI.bold(self.args.tag)} on {self.repo_type} {ANSI.bold(self.repo_id)}")
96
-
97
- try:
98
- self.api.create_tag(
99
- repo_id=self.repo_id,
100
- tag=self.args.tag,
101
- tag_message=self.args.message,
102
- revision=self.args.revision,
103
- repo_type=self.repo_type,
104
- )
105
- except RepositoryNotFoundError:
106
- print(f"{self.repo_type.capitalize()} {ANSI.bold(self.repo_id)} not found.")
107
- exit(1)
108
- except RevisionNotFoundError:
109
- print(f"Revision {ANSI.bold(self.args.revision)} not found.")
110
- exit(1)
111
- except HfHubHTTPError as e:
112
- if e.response.status_code == 409:
113
- print(f"Tag {ANSI.bold(self.args.tag)} already exists on {ANSI.bold(self.repo_id)}")
114
- exit(1)
115
- raise e
116
-
117
- print(f"Tag {ANSI.bold(self.args.tag)} created on {ANSI.bold(self.repo_id)}")
118
-
119
-
120
- class TagListCommand(TagCommand):
121
- def run(self):
122
- try:
123
- refs = self.api.list_repo_refs(
124
- repo_id=self.repo_id,
125
- repo_type=self.repo_type,
126
- )
127
- except RepositoryNotFoundError:
128
- print(f"{self.repo_type.capitalize()} {ANSI.bold(self.repo_id)} not found.")
129
- exit(1)
130
- except HfHubHTTPError as e:
131
- print(e)
132
- print(ANSI.red(e.response.text))
133
- exit(1)
134
- if len(refs.tags) == 0:
135
- print("No tags found")
136
- exit(0)
137
- print(f"Tags for {self.repo_type} {ANSI.bold(self.repo_id)}:")
138
- for tag in refs.tags:
139
- print(tag.name)
140
-
141
-
142
- class TagDeleteCommand(TagCommand):
143
- def run(self):
144
- print(f"You are about to delete tag {ANSI.bold(self.args.tag)} on {self.repo_type} {ANSI.bold(self.repo_id)}")
145
-
146
- if not self.args.yes:
147
- choice = input("Proceed? [Y/n] ").lower()
148
- if choice not in ("", "y", "yes"):
149
- print("Abort")
150
- exit()
151
- try:
152
- self.api.delete_tag(repo_id=self.repo_id, tag=self.args.tag, repo_type=self.repo_type)
153
- except RepositoryNotFoundError:
154
- print(f"{self.repo_type.capitalize()} {ANSI.bold(self.repo_id)} not found.")
155
- exit(1)
156
- except RevisionNotFoundError:
157
- print(f"Tag {ANSI.bold(self.args.tag)} not found on {ANSI.bold(self.repo_id)}")
158
- exit(1)
159
- print(f"Tag {ANSI.bold(self.args.tag)} deleted on {ANSI.bold(self.repo_id)}")
@@ -1,318 +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 upload a repo or file with the CLI.
16
-
17
- Usage:
18
- # Upload file (implicit)
19
- huggingface-cli upload my-cool-model ./my-cool-model.safetensors
20
-
21
- # Upload file (explicit)
22
- huggingface-cli upload my-cool-model ./my-cool-model.safetensors model.safetensors
23
-
24
- # Upload directory (implicit). If `my-cool-model/` is a directory it will be uploaded, otherwise an exception is raised.
25
- huggingface-cli upload my-cool-model
26
-
27
- # Upload directory (explicit)
28
- huggingface-cli upload my-cool-model ./models/my-cool-model .
29
-
30
- # Upload filtered directory (example: tensorboard logs except for the last run)
31
- huggingface-cli upload my-cool-model ./model/training /logs --include "*.tfevents.*" --exclude "*20230905*"
32
-
33
- # Upload with wildcard
34
- huggingface-cli upload my-cool-model "./model/training/*.safetensors"
35
-
36
- # Upload private dataset
37
- huggingface-cli upload Wauplin/my-cool-dataset ./data . --repo-type=dataset --private
38
-
39
- # Upload with token
40
- huggingface-cli upload Wauplin/my-cool-model --token=hf_****
41
-
42
- # Sync local Space with Hub (upload new files, delete removed files)
43
- huggingface-cli upload Wauplin/space-example --repo-type=space --exclude="/logs/*" --delete="*" --commit-message="Sync local Space with Hub"
44
-
45
- # Schedule commits every 30 minutes
46
- huggingface-cli upload Wauplin/my-cool-model --every=30
47
- """
48
-
49
- import os
50
- import time
51
- import warnings
52
- from argparse import Namespace, _SubParsersAction
53
- from typing import Optional
54
-
55
- from huggingface_hub import logging
56
- from huggingface_hub._commit_scheduler import CommitScheduler
57
- from huggingface_hub.commands import BaseHuggingfaceCLICommand
58
- from huggingface_hub.constants import HF_HUB_ENABLE_HF_TRANSFER
59
- from huggingface_hub.errors import RevisionNotFoundError
60
- from huggingface_hub.hf_api import HfApi
61
- from huggingface_hub.utils import disable_progress_bars, enable_progress_bars
62
- from huggingface_hub.utils._runtime import is_xet_available
63
-
64
- from ._cli_utils import show_deprecation_warning
65
-
66
-
67
- logger = logging.get_logger(__name__)
68
-
69
-
70
- class UploadCommand(BaseHuggingfaceCLICommand):
71
- @staticmethod
72
- def register_subcommand(parser: _SubParsersAction):
73
- upload_parser = parser.add_parser("upload", help="Upload a file or a folder to a repo on the Hub")
74
- upload_parser.add_argument(
75
- "repo_id", type=str, help="The ID of the repo to upload to (e.g. `username/repo-name`)."
76
- )
77
- upload_parser.add_argument(
78
- "local_path",
79
- nargs="?",
80
- help="Local path to the file or folder to upload. Wildcard patterns are supported. Defaults to current directory.",
81
- )
82
- upload_parser.add_argument(
83
- "path_in_repo",
84
- nargs="?",
85
- help="Path of the file or folder in the repo. Defaults to the relative path of the file or folder.",
86
- )
87
- upload_parser.add_argument(
88
- "--repo-type",
89
- choices=["model", "dataset", "space"],
90
- default="model",
91
- help="Type of the repo to upload to (e.g. `dataset`).",
92
- )
93
- upload_parser.add_argument(
94
- "--revision",
95
- type=str,
96
- help=(
97
- "An optional Git revision to push to. It can be a branch name or a PR reference. If revision does not"
98
- " exist and `--create-pr` is not set, a branch will be automatically created."
99
- ),
100
- )
101
- upload_parser.add_argument(
102
- "--private",
103
- action="store_true",
104
- help=(
105
- "Whether to create a private repo if repo doesn't exist on the Hub. Ignored if the repo already"
106
- " exists."
107
- ),
108
- )
109
- upload_parser.add_argument("--include", nargs="*", type=str, help="Glob patterns to match files to upload.")
110
- upload_parser.add_argument(
111
- "--exclude", nargs="*", type=str, help="Glob patterns to exclude from files to upload."
112
- )
113
- upload_parser.add_argument(
114
- "--delete",
115
- nargs="*",
116
- type=str,
117
- help="Glob patterns for file to be deleted from the repo while committing.",
118
- )
119
- upload_parser.add_argument(
120
- "--commit-message", type=str, help="The summary / title / first line of the generated commit."
121
- )
122
- upload_parser.add_argument("--commit-description", type=str, help="The description of the generated commit.")
123
- upload_parser.add_argument(
124
- "--create-pr", action="store_true", help="Whether to upload content as a new Pull Request."
125
- )
126
- upload_parser.add_argument(
127
- "--every",
128
- type=float,
129
- help="If set, a background job is scheduled to create commits every `every` minutes.",
130
- )
131
- upload_parser.add_argument(
132
- "--token", type=str, help="A User Access Token generated from https://huggingface.co/settings/tokens"
133
- )
134
- upload_parser.add_argument(
135
- "--quiet",
136
- action="store_true",
137
- help="If True, progress bars are disabled and only the path to the uploaded files is printed.",
138
- )
139
- upload_parser.set_defaults(func=UploadCommand)
140
-
141
- def __init__(self, args: Namespace) -> None:
142
- self.repo_id: str = args.repo_id
143
- self.repo_type: Optional[str] = args.repo_type
144
- self.revision: Optional[str] = args.revision
145
- self.private: bool = args.private
146
-
147
- self.include: Optional[list[str]] = args.include
148
- self.exclude: Optional[list[str]] = args.exclude
149
- self.delete: Optional[list[str]] = args.delete
150
-
151
- self.commit_message: Optional[str] = args.commit_message
152
- self.commit_description: Optional[str] = args.commit_description
153
- self.create_pr: bool = args.create_pr
154
- self.api: HfApi = HfApi(token=args.token, library_name="huggingface-cli")
155
- self.quiet: bool = args.quiet # disable warnings and progress bars
156
-
157
- # Check `--every` is valid
158
- if args.every is not None and args.every <= 0:
159
- raise ValueError(f"`every` must be a positive value (got '{args.every}')")
160
- self.every: Optional[float] = args.every
161
-
162
- # Resolve `local_path` and `path_in_repo`
163
- repo_name: str = args.repo_id.split("/")[-1] # e.g. "Wauplin/my-cool-model" => "my-cool-model"
164
- self.local_path: str
165
- self.path_in_repo: str
166
-
167
- if args.local_path is not None and any(c in args.local_path for c in ["*", "?", "["]):
168
- if args.include is not None:
169
- raise ValueError("Cannot set `--include` when passing a `local_path` containing a wildcard.")
170
- if args.path_in_repo is not None and args.path_in_repo != ".":
171
- raise ValueError("Cannot set `path_in_repo` when passing a `local_path` containing a wildcard.")
172
- self.local_path = "."
173
- self.include = args.local_path
174
- self.path_in_repo = "."
175
- elif args.local_path is None and os.path.isfile(repo_name):
176
- # Implicit case 1: user provided only a repo_id which happen to be a local file as well => upload it with same name
177
- self.local_path = repo_name
178
- self.path_in_repo = repo_name
179
- elif args.local_path is None and os.path.isdir(repo_name):
180
- # Implicit case 2: user provided only a repo_id which happen to be a local folder as well => upload it at root
181
- self.local_path = repo_name
182
- self.path_in_repo = "."
183
- elif args.local_path is None:
184
- # Implicit case 3: user provided only a repo_id that does not match a local file or folder
185
- # => the user must explicitly provide a local_path => raise exception
186
- raise ValueError(f"'{repo_name}' is not a local file or folder. Please set `local_path` explicitly.")
187
- elif args.path_in_repo is None and os.path.isfile(args.local_path):
188
- # Explicit local path to file, no path in repo => upload it at root with same name
189
- self.local_path = args.local_path
190
- self.path_in_repo = os.path.basename(args.local_path)
191
- elif args.path_in_repo is None:
192
- # Explicit local path to folder, no path in repo => upload at root
193
- self.local_path = args.local_path
194
- self.path_in_repo = "."
195
- else:
196
- # Finally, if both paths are explicit
197
- self.local_path = args.local_path
198
- self.path_in_repo = args.path_in_repo
199
-
200
- def run(self) -> None:
201
- show_deprecation_warning("huggingface-cli upload", "hf upload")
202
-
203
- if self.quiet:
204
- disable_progress_bars()
205
- with warnings.catch_warnings():
206
- warnings.simplefilter("ignore")
207
- print(self._upload())
208
- enable_progress_bars()
209
- else:
210
- logging.set_verbosity_info()
211
- print(self._upload())
212
- logging.set_verbosity_warning()
213
-
214
- def _upload(self) -> str:
215
- if os.path.isfile(self.local_path):
216
- if self.include is not None and len(self.include) > 0:
217
- warnings.warn("Ignoring `--include` since a single file is uploaded.")
218
- if self.exclude is not None and len(self.exclude) > 0:
219
- warnings.warn("Ignoring `--exclude` since a single file is uploaded.")
220
- if self.delete is not None and len(self.delete) > 0:
221
- warnings.warn("Ignoring `--delete` since a single file is uploaded.")
222
-
223
- if not is_xet_available() and not HF_HUB_ENABLE_HF_TRANSFER:
224
- logger.info(
225
- "Consider using `hf_transfer` for faster uploads. This solution comes with some limitations. See"
226
- " https://huggingface.co/docs/huggingface_hub/hf_transfer for more details."
227
- )
228
-
229
- # Schedule commits if `every` is set
230
- if self.every is not None:
231
- if os.path.isfile(self.local_path):
232
- # If file => watch entire folder + use allow_patterns
233
- folder_path = os.path.dirname(self.local_path)
234
- path_in_repo = (
235
- self.path_in_repo[: -len(self.local_path)] # remove filename from path_in_repo
236
- if self.path_in_repo.endswith(self.local_path)
237
- else self.path_in_repo
238
- )
239
- allow_patterns = [self.local_path]
240
- ignore_patterns = []
241
- else:
242
- folder_path = self.local_path
243
- path_in_repo = self.path_in_repo
244
- allow_patterns = self.include or []
245
- ignore_patterns = self.exclude or []
246
- if self.delete is not None and len(self.delete) > 0:
247
- warnings.warn("Ignoring `--delete` when uploading with scheduled commits.")
248
-
249
- scheduler = CommitScheduler(
250
- folder_path=folder_path,
251
- repo_id=self.repo_id,
252
- repo_type=self.repo_type,
253
- revision=self.revision,
254
- allow_patterns=allow_patterns,
255
- ignore_patterns=ignore_patterns,
256
- path_in_repo=path_in_repo,
257
- private=self.private,
258
- every=self.every,
259
- hf_api=self.api,
260
- )
261
- print(f"Scheduling commits every {self.every} minutes to {scheduler.repo_id}.")
262
- try: # Block main thread until KeyboardInterrupt
263
- while True:
264
- time.sleep(100)
265
- except KeyboardInterrupt:
266
- scheduler.stop()
267
- return "Stopped scheduled commits."
268
-
269
- # Otherwise, create repo and proceed with the upload
270
- if not os.path.isfile(self.local_path) and not os.path.isdir(self.local_path):
271
- raise FileNotFoundError(f"No such file or directory: '{self.local_path}'.")
272
- repo_id = self.api.create_repo(
273
- repo_id=self.repo_id,
274
- repo_type=self.repo_type,
275
- exist_ok=True,
276
- private=self.private,
277
- space_sdk="gradio" if self.repo_type == "space" else None,
278
- # ^ We don't want it to fail when uploading to a Space => let's set Gradio by default.
279
- # ^ I'd rather not add CLI args to set it explicitly as we already have `huggingface-cli repo create` for that.
280
- ).repo_id
281
-
282
- # Check if branch already exists and if not, create it
283
- if self.revision is not None and not self.create_pr:
284
- try:
285
- self.api.repo_info(repo_id=repo_id, repo_type=self.repo_type, revision=self.revision)
286
- except RevisionNotFoundError:
287
- logger.info(f"Branch '{self.revision}' not found. Creating it...")
288
- self.api.create_branch(repo_id=repo_id, repo_type=self.repo_type, branch=self.revision, exist_ok=True)
289
- # ^ `exist_ok=True` to avoid race concurrency issues
290
-
291
- # File-based upload
292
- if os.path.isfile(self.local_path):
293
- return self.api.upload_file(
294
- path_or_fileobj=self.local_path,
295
- path_in_repo=self.path_in_repo,
296
- repo_id=repo_id,
297
- repo_type=self.repo_type,
298
- revision=self.revision,
299
- commit_message=self.commit_message,
300
- commit_description=self.commit_description,
301
- create_pr=self.create_pr,
302
- )
303
-
304
- # Folder-based upload
305
- else:
306
- return self.api.upload_folder(
307
- folder_path=self.local_path,
308
- path_in_repo=self.path_in_repo,
309
- repo_id=repo_id,
310
- repo_type=self.repo_type,
311
- revision=self.revision,
312
- commit_message=self.commit_message,
313
- commit_description=self.commit_description,
314
- create_pr=self.create_pr,
315
- allow_patterns=self.include,
316
- ignore_patterns=self.exclude,
317
- delete_patterns=self.delete,
318
- )