huggingface-hub 0.24.7__py3-none-any.whl → 0.25.1__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 (53) hide show
  1. huggingface_hub/__init__.py +21 -1
  2. huggingface_hub/_commit_api.py +4 -4
  3. huggingface_hub/_inference_endpoints.py +13 -1
  4. huggingface_hub/_local_folder.py +191 -4
  5. huggingface_hub/_login.py +6 -6
  6. huggingface_hub/_snapshot_download.py +8 -17
  7. huggingface_hub/_space_api.py +5 -0
  8. huggingface_hub/_tensorboard_logger.py +29 -13
  9. huggingface_hub/_upload_large_folder.py +621 -0
  10. huggingface_hub/_webhooks_server.py +1 -1
  11. huggingface_hub/commands/_cli_utils.py +5 -0
  12. huggingface_hub/commands/download.py +8 -0
  13. huggingface_hub/commands/huggingface_cli.py +6 -1
  14. huggingface_hub/commands/lfs.py +2 -1
  15. huggingface_hub/commands/repo_files.py +2 -2
  16. huggingface_hub/commands/scan_cache.py +99 -57
  17. huggingface_hub/commands/tag.py +1 -1
  18. huggingface_hub/commands/upload.py +2 -1
  19. huggingface_hub/commands/upload_large_folder.py +129 -0
  20. huggingface_hub/commands/version.py +37 -0
  21. huggingface_hub/community.py +2 -2
  22. huggingface_hub/errors.py +218 -1
  23. huggingface_hub/fastai_utils.py +2 -3
  24. huggingface_hub/file_download.py +61 -62
  25. huggingface_hub/hf_api.py +783 -314
  26. huggingface_hub/hf_file_system.py +15 -23
  27. huggingface_hub/hub_mixin.py +27 -25
  28. huggingface_hub/inference/_client.py +78 -127
  29. huggingface_hub/inference/_common.py +6 -0
  30. huggingface_hub/inference/_generated/_async_client.py +169 -144
  31. huggingface_hub/inference/_generated/types/base.py +0 -9
  32. huggingface_hub/inference/_templating.py +2 -3
  33. huggingface_hub/inference_api.py +2 -2
  34. huggingface_hub/keras_mixin.py +2 -2
  35. huggingface_hub/lfs.py +7 -98
  36. huggingface_hub/repocard.py +6 -5
  37. huggingface_hub/repository.py +5 -5
  38. huggingface_hub/serialization/_torch.py +64 -11
  39. huggingface_hub/utils/__init__.py +13 -14
  40. huggingface_hub/utils/_cache_manager.py +97 -14
  41. huggingface_hub/utils/_fixes.py +18 -2
  42. huggingface_hub/utils/_http.py +228 -2
  43. huggingface_hub/utils/_lfs.py +110 -0
  44. huggingface_hub/utils/_runtime.py +7 -1
  45. huggingface_hub/utils/_token.py +3 -2
  46. {huggingface_hub-0.24.7.dist-info → huggingface_hub-0.25.1.dist-info}/METADATA +2 -2
  47. {huggingface_hub-0.24.7.dist-info → huggingface_hub-0.25.1.dist-info}/RECORD +51 -49
  48. huggingface_hub/inference/_types.py +0 -52
  49. huggingface_hub/utils/_errors.py +0 -397
  50. {huggingface_hub-0.24.7.dist-info → huggingface_hub-0.25.1.dist-info}/LICENSE +0 -0
  51. {huggingface_hub-0.24.7.dist-info → huggingface_hub-0.25.1.dist-info}/WHEEL +0 -0
  52. {huggingface_hub-0.24.7.dist-info → huggingface_hub-0.25.1.dist-info}/entry_points.txt +0 -0
  53. {huggingface_hub-0.24.7.dist-info → huggingface_hub-0.25.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,621 @@
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
+ import enum
16
+ import logging
17
+ import os
18
+ import queue
19
+ import shutil
20
+ import sys
21
+ import threading
22
+ import time
23
+ import traceback
24
+ from datetime import datetime
25
+ from pathlib import Path
26
+ from threading import Lock
27
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
28
+
29
+ from . import constants
30
+ from ._commit_api import CommitOperationAdd, UploadInfo, _fetch_upload_modes
31
+ from ._local_folder import LocalUploadFileMetadata, LocalUploadFilePaths, get_local_upload_paths, read_upload_metadata
32
+ from .constants import DEFAULT_REVISION, REPO_TYPES
33
+ from .utils import DEFAULT_IGNORE_PATTERNS, filter_repo_objects, tqdm
34
+ from .utils._cache_manager import _format_size
35
+ from .utils.sha import sha_fileobj
36
+
37
+
38
+ if TYPE_CHECKING:
39
+ from .hf_api import HfApi
40
+
41
+ logger = logging.getLogger(__name__)
42
+
43
+ WAITING_TIME_IF_NO_TASKS = 10 # seconds
44
+ MAX_NB_REGULAR_FILES_PER_COMMIT = 75
45
+ MAX_NB_LFS_FILES_PER_COMMIT = 150
46
+
47
+
48
+ def upload_large_folder_internal(
49
+ api: "HfApi",
50
+ repo_id: str,
51
+ folder_path: Union[str, Path],
52
+ *,
53
+ repo_type: str, # Repo type is required!
54
+ revision: Optional[str] = None,
55
+ private: bool = False,
56
+ allow_patterns: Optional[Union[List[str], str]] = None,
57
+ ignore_patterns: Optional[Union[List[str], str]] = None,
58
+ num_workers: Optional[int] = None,
59
+ print_report: bool = True,
60
+ print_report_every: int = 60,
61
+ ):
62
+ """Upload a large folder to the Hub in the most resilient way possible.
63
+
64
+ See [`HfApi.upload_large_folder`] for the full documentation.
65
+ """
66
+ # 1. Check args and setup
67
+ if repo_type is None:
68
+ raise ValueError(
69
+ "For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`."
70
+ " If you are using the CLI, pass it as `--repo-type=model`."
71
+ )
72
+ if repo_type not in REPO_TYPES:
73
+ raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
74
+ if revision is None:
75
+ revision = DEFAULT_REVISION
76
+
77
+ folder_path = Path(folder_path).expanduser().resolve()
78
+ if not folder_path.is_dir():
79
+ raise ValueError(f"Provided path: '{folder_path}' is not a directory")
80
+
81
+ if ignore_patterns is None:
82
+ ignore_patterns = []
83
+ elif isinstance(ignore_patterns, str):
84
+ ignore_patterns = [ignore_patterns]
85
+ ignore_patterns += DEFAULT_IGNORE_PATTERNS
86
+
87
+ if num_workers is None:
88
+ nb_cores = os.cpu_count() or 1
89
+ num_workers = max(nb_cores - 2, 2) # Use all but 2 cores, or at least 2 cores
90
+
91
+ # 2. Create repo if missing
92
+ repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True)
93
+ logger.info(f"Repo created: {repo_url}")
94
+ repo_id = repo_url.repo_id
95
+
96
+ # 3. List files to upload
97
+ filtered_paths_list = filter_repo_objects(
98
+ (path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()),
99
+ allow_patterns=allow_patterns,
100
+ ignore_patterns=ignore_patterns,
101
+ )
102
+ paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list]
103
+ logger.info(f"Found {len(paths_list)} candidate files to upload")
104
+
105
+ # Read metadata for each file
106
+ items = [
107
+ (paths, read_upload_metadata(folder_path, paths.path_in_repo))
108
+ for paths in tqdm(paths_list, desc="Recovering from metadata files")
109
+ ]
110
+
111
+ # 4. Start workers
112
+ status = LargeUploadStatus(items)
113
+ threads = [
114
+ threading.Thread(
115
+ target=_worker_job,
116
+ kwargs={
117
+ "status": status,
118
+ "api": api,
119
+ "repo_id": repo_id,
120
+ "repo_type": repo_type,
121
+ "revision": revision,
122
+ },
123
+ )
124
+ for _ in range(num_workers)
125
+ ]
126
+
127
+ for thread in threads:
128
+ thread.start()
129
+
130
+ # 5. Print regular reports
131
+ if print_report:
132
+ print("\n\n" + status.current_report())
133
+ last_report_ts = time.time()
134
+ while True:
135
+ time.sleep(1)
136
+ if time.time() - last_report_ts >= print_report_every:
137
+ if print_report:
138
+ _print_overwrite(status.current_report())
139
+ last_report_ts = time.time()
140
+ if status.is_done():
141
+ logging.info("Is done: exiting main loop")
142
+ break
143
+
144
+ for thread in threads:
145
+ thread.join()
146
+
147
+ logger.info(status.current_report())
148
+ logging.info("Upload is complete!")
149
+
150
+
151
+ ####################
152
+ # Logic to manage workers and synchronize tasks
153
+ ####################
154
+
155
+
156
+ class WorkerJob(enum.Enum):
157
+ SHA256 = enum.auto()
158
+ GET_UPLOAD_MODE = enum.auto()
159
+ PREUPLOAD_LFS = enum.auto()
160
+ COMMIT = enum.auto()
161
+ WAIT = enum.auto() # if no tasks are available but we don't want to exit
162
+
163
+
164
+ JOB_ITEM_T = Tuple[LocalUploadFilePaths, LocalUploadFileMetadata]
165
+
166
+
167
+ class LargeUploadStatus:
168
+ """Contains information, queues and tasks for a large upload process."""
169
+
170
+ def __init__(self, items: List[JOB_ITEM_T]):
171
+ self.items = items
172
+ self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
173
+ self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
174
+ self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
175
+ self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
176
+ self.lock = Lock()
177
+
178
+ self.nb_workers_sha256: int = 0
179
+ self.nb_workers_get_upload_mode: int = 0
180
+ self.nb_workers_preupload_lfs: int = 0
181
+ self.nb_workers_commit: int = 0
182
+ self.nb_workers_waiting: int = 0
183
+ self.last_commit_attempt: Optional[float] = None
184
+
185
+ self._started_at = datetime.now()
186
+
187
+ # Setup queues
188
+ for item in self.items:
189
+ paths, metadata = item
190
+ if metadata.sha256 is None:
191
+ self.queue_sha256.put(item)
192
+ elif metadata.upload_mode is None:
193
+ self.queue_get_upload_mode.put(item)
194
+ elif metadata.upload_mode == "lfs" and not metadata.is_uploaded:
195
+ self.queue_preupload_lfs.put(item)
196
+ elif not metadata.is_committed:
197
+ self.queue_commit.put(item)
198
+ else:
199
+ logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)")
200
+
201
+ def current_report(self) -> str:
202
+ """Generate a report of the current status of the large upload."""
203
+ nb_hashed = 0
204
+ size_hashed = 0
205
+ nb_preuploaded = 0
206
+ nb_lfs = 0
207
+ nb_lfs_unsure = 0
208
+ size_preuploaded = 0
209
+ nb_committed = 0
210
+ size_committed = 0
211
+ total_size = 0
212
+ ignored_files = 0
213
+ total_files = 0
214
+
215
+ with self.lock:
216
+ for _, metadata in self.items:
217
+ if metadata.should_ignore:
218
+ ignored_files += 1
219
+ continue
220
+ total_size += metadata.size
221
+ total_files += 1
222
+ if metadata.sha256 is not None:
223
+ nb_hashed += 1
224
+ size_hashed += metadata.size
225
+ if metadata.upload_mode == "lfs":
226
+ nb_lfs += 1
227
+ if metadata.upload_mode is None:
228
+ nb_lfs_unsure += 1
229
+ if metadata.is_uploaded:
230
+ nb_preuploaded += 1
231
+ size_preuploaded += metadata.size
232
+ if metadata.is_committed:
233
+ nb_committed += 1
234
+ size_committed += metadata.size
235
+ total_size_str = _format_size(total_size)
236
+
237
+ now = datetime.now()
238
+ now_str = now.strftime("%Y-%m-%d %H:%M:%S")
239
+ elapsed = now - self._started_at
240
+ elapsed_str = str(elapsed).split(".")[0] # remove milliseconds
241
+
242
+ message = "\n" + "-" * 10
243
+ message += f" {now_str} ({elapsed_str}) "
244
+ message += "-" * 10 + "\n"
245
+
246
+ message += "Files: "
247
+ message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | "
248
+ message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})"
249
+ if nb_lfs_unsure > 0:
250
+ message += f" (+{nb_lfs_unsure} unsure)"
251
+ message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})"
252
+ message += f" | ignored: {ignored_files}\n"
253
+
254
+ message += "Workers: "
255
+ message += f"hashing: {self.nb_workers_sha256} | "
256
+ message += f"get upload mode: {self.nb_workers_get_upload_mode} | "
257
+ message += f"pre-uploading: {self.nb_workers_preupload_lfs} | "
258
+ message += f"committing: {self.nb_workers_commit} | "
259
+ message += f"waiting: {self.nb_workers_waiting}\n"
260
+ message += "-" * 51
261
+
262
+ return message
263
+
264
+ def is_done(self) -> bool:
265
+ with self.lock:
266
+ return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items)
267
+
268
+
269
+ def _worker_job(
270
+ status: LargeUploadStatus,
271
+ api: "HfApi",
272
+ repo_id: str,
273
+ repo_type: str,
274
+ revision: str,
275
+ ):
276
+ """
277
+ Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded
278
+ and committed. If no tasks are available, the worker will wait for 10 seconds before checking again.
279
+
280
+ If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up.
281
+
282
+ Read `upload_large_folder` docstring for more information on how tasks are prioritized.
283
+ """
284
+ while True:
285
+ next_job: Optional[Tuple[WorkerJob, List[JOB_ITEM_T]]] = None
286
+
287
+ # Determine next task
288
+ next_job = _determine_next_job(status)
289
+ if next_job is None:
290
+ return
291
+ job, items = next_job
292
+
293
+ # Perform task
294
+ if job == WorkerJob.SHA256:
295
+ item = items[0] # single item
296
+ try:
297
+ _compute_sha256(item)
298
+ status.queue_get_upload_mode.put(item)
299
+ except KeyboardInterrupt:
300
+ raise
301
+ except Exception as e:
302
+ logger.error(f"Failed to compute sha256: {e}")
303
+ traceback.format_exc()
304
+ status.queue_sha256.put(item)
305
+
306
+ with status.lock:
307
+ status.nb_workers_sha256 -= 1
308
+
309
+ elif job == WorkerJob.GET_UPLOAD_MODE:
310
+ try:
311
+ _get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
312
+ except KeyboardInterrupt:
313
+ raise
314
+ except Exception as e:
315
+ logger.error(f"Failed to get upload mode: {e}")
316
+ traceback.format_exc()
317
+
318
+ # Items are either:
319
+ # - dropped (if should_ignore)
320
+ # - put in LFS queue (if LFS)
321
+ # - put in commit queue (if regular)
322
+ # - or put back (if error occurred).
323
+ for item in items:
324
+ _, metadata = item
325
+ if metadata.should_ignore:
326
+ continue
327
+ if metadata.upload_mode == "lfs":
328
+ status.queue_preupload_lfs.put(item)
329
+ elif metadata.upload_mode == "regular":
330
+ status.queue_commit.put(item)
331
+ else:
332
+ status.queue_get_upload_mode.put(item)
333
+
334
+ with status.lock:
335
+ status.nb_workers_get_upload_mode -= 1
336
+
337
+ elif job == WorkerJob.PREUPLOAD_LFS:
338
+ item = items[0] # single item
339
+ try:
340
+ _preupload_lfs(item, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
341
+ status.queue_commit.put(item)
342
+ except KeyboardInterrupt:
343
+ raise
344
+ except Exception as e:
345
+ logger.error(f"Failed to preupload LFS: {e}")
346
+ traceback.format_exc()
347
+ status.queue_preupload_lfs.put(item)
348
+
349
+ with status.lock:
350
+ status.nb_workers_preupload_lfs -= 1
351
+
352
+ elif job == WorkerJob.COMMIT:
353
+ try:
354
+ _commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
355
+ except KeyboardInterrupt:
356
+ raise
357
+ except Exception as e:
358
+ logger.error(f"Failed to commit: {e}")
359
+ traceback.format_exc()
360
+ for item in items:
361
+ status.queue_commit.put(item)
362
+ with status.lock:
363
+ status.last_commit_attempt = time.time()
364
+ status.nb_workers_commit -= 1
365
+
366
+ elif job == WorkerJob.WAIT:
367
+ time.sleep(WAITING_TIME_IF_NO_TASKS)
368
+ with status.lock:
369
+ status.nb_workers_waiting -= 1
370
+
371
+
372
+ def _determine_next_job(status: LargeUploadStatus) -> Optional[Tuple[WorkerJob, List[JOB_ITEM_T]]]:
373
+ with status.lock:
374
+ # 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file)
375
+ if (
376
+ status.nb_workers_commit == 0
377
+ and status.queue_commit.qsize() > 0
378
+ and status.last_commit_attempt is not None
379
+ and time.time() - status.last_commit_attempt > 5 * 60
380
+ ):
381
+ status.nb_workers_commit += 1
382
+ logger.debug("Job: commit (more than 5 minutes since last commit attempt)")
383
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
384
+
385
+ # 2. Commit if at least 100 files are ready to commit
386
+ elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150:
387
+ status.nb_workers_commit += 1
388
+ logger.debug("Job: commit (>100 files ready)")
389
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
390
+
391
+ # 3. Get upload mode if at least 10 files
392
+ elif status.queue_get_upload_mode.qsize() >= 10:
393
+ status.nb_workers_get_upload_mode += 1
394
+ logger.debug("Job: get upload mode (>10 files ready)")
395
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, 50))
396
+
397
+ # 4. Preupload LFS file if at least 1 file and no worker is preuploading LFS
398
+ elif status.queue_preupload_lfs.qsize() > 0 and status.nb_workers_preupload_lfs == 0:
399
+ status.nb_workers_preupload_lfs += 1
400
+ logger.debug("Job: preupload LFS (no other worker preuploading LFS)")
401
+ return (WorkerJob.PREUPLOAD_LFS, _get_one(status.queue_preupload_lfs))
402
+
403
+ # 5. Compute sha256 if at least 1 file and no worker is computing sha256
404
+ elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0:
405
+ status.nb_workers_sha256 += 1
406
+ logger.debug("Job: sha256 (no other worker computing sha256)")
407
+ return (WorkerJob.SHA256, _get_one(status.queue_sha256))
408
+
409
+ # 6. Get upload mode if at least 1 file and no worker is getting upload mode
410
+ elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0:
411
+ status.nb_workers_get_upload_mode += 1
412
+ logger.debug("Job: get upload mode (no other worker getting upload mode)")
413
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, 50))
414
+
415
+ # 7. Preupload LFS file if at least 1 file
416
+ # Skip if hf_transfer is enabled and there is already a worker preuploading LFS
417
+ elif status.queue_preupload_lfs.qsize() > 0 and (
418
+ status.nb_workers_preupload_lfs == 0 or not constants.HF_HUB_ENABLE_HF_TRANSFER
419
+ ):
420
+ status.nb_workers_preupload_lfs += 1
421
+ logger.debug("Job: preupload LFS")
422
+ return (WorkerJob.PREUPLOAD_LFS, _get_one(status.queue_preupload_lfs))
423
+
424
+ # 8. Compute sha256 if at least 1 file
425
+ elif status.queue_sha256.qsize() > 0:
426
+ status.nb_workers_sha256 += 1
427
+ logger.debug("Job: sha256")
428
+ return (WorkerJob.SHA256, _get_one(status.queue_sha256))
429
+
430
+ # 9. Get upload mode if at least 1 file
431
+ elif status.queue_get_upload_mode.qsize() > 0:
432
+ status.nb_workers_get_upload_mode += 1
433
+ logger.debug("Job: get upload mode")
434
+ return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, 50))
435
+
436
+ # 10. Commit if at least 1 file and 1 min since last commit attempt
437
+ elif (
438
+ status.nb_workers_commit == 0
439
+ and status.queue_commit.qsize() > 0
440
+ and status.last_commit_attempt is not None
441
+ and time.time() - status.last_commit_attempt > 1 * 60
442
+ ):
443
+ status.nb_workers_commit += 1
444
+ logger.debug("Job: commit (1 min since last commit attempt)")
445
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
446
+
447
+ # 11. Commit if at least 1 file all other queues are empty and all workers are waiting
448
+ # e.g. when it's the last commit
449
+ elif (
450
+ status.nb_workers_commit == 0
451
+ and status.queue_commit.qsize() > 0
452
+ and status.queue_sha256.qsize() == 0
453
+ and status.queue_get_upload_mode.qsize() == 0
454
+ and status.queue_preupload_lfs.qsize() == 0
455
+ and status.nb_workers_sha256 == 0
456
+ and status.nb_workers_get_upload_mode == 0
457
+ and status.nb_workers_preupload_lfs == 0
458
+ ):
459
+ status.nb_workers_commit += 1
460
+ logger.debug("Job: commit")
461
+ return (WorkerJob.COMMIT, _get_items_to_commit(status.queue_commit))
462
+
463
+ # 12. If all queues are empty, exit
464
+ elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items):
465
+ logger.info("All files have been processed! Exiting worker.")
466
+ return None
467
+
468
+ # 13. If no task is available, wait
469
+ else:
470
+ status.nb_workers_waiting += 1
471
+ logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)")
472
+ return (WorkerJob.WAIT, [])
473
+
474
+
475
+ ####################
476
+ # Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit)
477
+ ####################
478
+
479
+
480
+ def _compute_sha256(item: JOB_ITEM_T) -> None:
481
+ """Compute sha256 of a file and save it in metadata."""
482
+ paths, metadata = item
483
+ if metadata.sha256 is None:
484
+ with paths.file_path.open("rb") as f:
485
+ metadata.sha256 = sha_fileobj(f).hex()
486
+ metadata.save(paths)
487
+
488
+
489
+ def _get_upload_mode(items: List[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
490
+ """Get upload mode for each file and update metadata.
491
+
492
+ Also receive info if the file should be ignored.
493
+ """
494
+ additions = [_build_hacky_operation(item) for item in items]
495
+ _fetch_upload_modes(
496
+ additions=additions,
497
+ repo_type=repo_type,
498
+ repo_id=repo_id,
499
+ headers=api._build_hf_headers(),
500
+ revision=revision,
501
+ )
502
+ for item, addition in zip(items, additions):
503
+ paths, metadata = item
504
+ metadata.upload_mode = addition._upload_mode
505
+ metadata.should_ignore = addition._should_ignore
506
+ metadata.save(paths)
507
+
508
+
509
+ def _preupload_lfs(item: JOB_ITEM_T, api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
510
+ """Preupload LFS file and update metadata."""
511
+ paths, metadata = item
512
+ addition = _build_hacky_operation(item)
513
+ api.preupload_lfs_files(
514
+ repo_id=repo_id,
515
+ repo_type=repo_type,
516
+ revision=revision,
517
+ additions=[addition],
518
+ )
519
+
520
+ metadata.is_uploaded = True
521
+ metadata.save(paths)
522
+
523
+
524
+ def _commit(items: List[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
525
+ """Commit files to the repo."""
526
+ additions = [_build_hacky_operation(item) for item in items]
527
+ api.create_commit(
528
+ repo_id=repo_id,
529
+ repo_type=repo_type,
530
+ revision=revision,
531
+ operations=additions,
532
+ commit_message="Add files using upload-large-folder tool",
533
+ )
534
+ for paths, metadata in items:
535
+ metadata.is_committed = True
536
+ metadata.save(paths)
537
+
538
+
539
+ ####################
540
+ # Hacks with CommitOperationAdd to bypass checks/sha256 calculation
541
+ ####################
542
+
543
+
544
+ class HackyCommitOperationAdd(CommitOperationAdd):
545
+ def __post_init__(self) -> None:
546
+ if isinstance(self.path_or_fileobj, Path):
547
+ self.path_or_fileobj = str(self.path_or_fileobj)
548
+
549
+
550
+ def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd:
551
+ paths, metadata = item
552
+ operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path)
553
+ with paths.file_path.open("rb") as file:
554
+ sample = file.peek(512)[:512]
555
+ if metadata.sha256 is None:
556
+ raise ValueError("sha256 must have been computed by now!")
557
+ operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample)
558
+ return operation
559
+
560
+
561
+ ####################
562
+ # Misc helpers
563
+ ####################
564
+
565
+
566
+ def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> List[JOB_ITEM_T]:
567
+ return [queue.get()]
568
+
569
+
570
+ def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> List[JOB_ITEM_T]:
571
+ return [queue.get() for _ in range(min(queue.qsize(), n))]
572
+
573
+
574
+ def _get_items_to_commit(queue: "queue.Queue[JOB_ITEM_T]") -> List[JOB_ITEM_T]:
575
+ """Special case for commit job: the number of items to commit depends on the type of files."""
576
+ # Can take at most 50 regular files and/or 100 LFS files in a single commit
577
+ items: List[JOB_ITEM_T] = []
578
+ nb_lfs, nb_regular = 0, 0
579
+ while True:
580
+ # If empty queue => commit everything
581
+ if queue.qsize() == 0:
582
+ return items
583
+
584
+ # If we have enough items => commit them
585
+ if nb_lfs >= MAX_NB_LFS_FILES_PER_COMMIT or nb_regular >= MAX_NB_REGULAR_FILES_PER_COMMIT:
586
+ return items
587
+
588
+ # Else, get a new item and increase counter
589
+ item = queue.get()
590
+ items.append(item)
591
+ _, metadata = item
592
+ if metadata.upload_mode == "lfs":
593
+ nb_lfs += 1
594
+ else:
595
+ nb_regular += 1
596
+
597
+
598
+ def _print_overwrite(report: str) -> None:
599
+ """Print a report, overwriting the previous lines.
600
+
601
+ Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout`
602
+ to print the report.
603
+
604
+ Note: works well only if no other process is writing to `sys.stdout`!
605
+ """
606
+ report += "\n"
607
+ # Get terminal width
608
+ terminal_width = shutil.get_terminal_size().columns
609
+
610
+ # Count number of lines that should be cleared
611
+ nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines())
612
+
613
+ # Clear previous lines based on the number of lines in the report
614
+ for _ in range(nb_lines):
615
+ sys.stdout.write("\r\033[K") # Clear line
616
+ sys.stdout.write("\033[F") # Move cursor up one line
617
+
618
+ # Print the new report, filling remaining space with whitespace
619
+ sys.stdout.write(report)
620
+ sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1])))
621
+ sys.stdout.flush()
@@ -36,7 +36,7 @@ else:
36
36
 
37
37
 
38
38
  _global_app: Optional["WebhooksServer"] = None
39
- _is_local = os.getenv("SYSTEM") != "spaces"
39
+ _is_local = os.environ.get("SPACE_ID") is None
40
40
 
41
41
 
42
42
  @experimental
@@ -26,6 +26,7 @@ class ANSI:
26
26
  _gray = "\u001b[90m"
27
27
  _red = "\u001b[31m"
28
28
  _reset = "\u001b[0m"
29
+ _yellow = "\u001b[33m"
29
30
 
30
31
  @classmethod
31
32
  def bold(cls, s: str) -> str:
@@ -39,6 +40,10 @@ class ANSI:
39
40
  def red(cls, s: str) -> str:
40
41
  return cls._format(s, cls._bold + cls._red)
41
42
 
43
+ @classmethod
44
+ def yellow(cls, s: str) -> str:
45
+ return cls._format(s, cls._yellow)
46
+
42
47
  @classmethod
43
48
  def _format(cls, s: str, code: str) -> str:
44
49
  if os.environ.get("NO_COLOR"):
@@ -112,6 +112,12 @@ class DownloadCommand(BaseHuggingfaceCLICommand):
112
112
  action="store_true",
113
113
  help="If True, progress bars are disabled and only the path to the download files is printed.",
114
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
+ )
115
121
  download_parser.set_defaults(func=DownloadCommand)
116
122
 
117
123
  def __init__(self, args: Namespace) -> None:
@@ -127,6 +133,7 @@ class DownloadCommand(BaseHuggingfaceCLICommand):
127
133
  self.force_download: bool = args.force_download
128
134
  self.resume_download: Optional[bool] = args.resume_download or None
129
135
  self.quiet: bool = args.quiet
136
+ self.max_workers: int = args.max_workers
130
137
 
131
138
  if args.local_dir_use_symlinks is not None:
132
139
  warnings.warn(
@@ -189,4 +196,5 @@ class DownloadCommand(BaseHuggingfaceCLICommand):
189
196
  token=self.token,
190
197
  local_dir=self.local_dir,
191
198
  library_name="huggingface-cli",
199
+ max_workers=self.max_workers,
192
200
  )
@@ -22,7 +22,9 @@ from huggingface_hub.commands.repo_files import RepoFilesCommand
22
22
  from huggingface_hub.commands.scan_cache import ScanCacheCommand
23
23
  from huggingface_hub.commands.tag import TagCommands
24
24
  from huggingface_hub.commands.upload import UploadCommand
25
+ from huggingface_hub.commands.upload_large_folder import UploadLargeFolderCommand
25
26
  from huggingface_hub.commands.user import UserCommands
27
+ from huggingface_hub.commands.version import VersionCommand
26
28
 
27
29
 
28
30
  def main():
@@ -39,10 +41,13 @@ def main():
39
41
  ScanCacheCommand.register_subcommand(commands_parser)
40
42
  DeleteCacheCommand.register_subcommand(commands_parser)
41
43
  TagCommands.register_subcommand(commands_parser)
44
+ VersionCommand.register_subcommand(commands_parser)
45
+
46
+ # Experimental
47
+ UploadLargeFolderCommand.register_subcommand(commands_parser)
42
48
 
43
49
  # Let's go
44
50
  args = parser.parse_args()
45
-
46
51
  if not hasattr(args, "func"):
47
52
  parser.print_help()
48
53
  exit(1)