1# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2# SPDX-License-Identifier: Apache-2.0
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
16import importlib.util
17import io
18import json
19import os
20import tempfile
21from collections.abc import Callable, Iterable, Iterator
22from typing import IO, Any, TypeVar
23from urllib.parse import quote
24
25from huggingface_hub import CommitOperationCopy, HfApi, get_session
26from huggingface_hub.errors import EntryNotFoundError, HfHubHTTPError, RepositoryNotFoundError, RevisionNotFoundError
27from huggingface_hub.hf_api import RepoFile, RepoFolder
28from huggingface_hub.utils import build_hf_headers, hf_raise_for_status # pyright: ignore[reportPrivateImportUsage]
29
30from ..telemetry import Telemetry
31from ..types import (
32 AWARE_DATETIME_MIN,
33 Credentials,
34 CredentialsProvider,
35 ObjectMetadata,
36 Range,
37 RetryableError,
38 SymlinkHandling,
39)
40from ..utils import safe_makedirs
41from .base import BaseStorageProvider
42
43_T = TypeVar("_T")
44
45PROVIDER = "huggingface"
46
47# The Hub refuses a paths-info request with more than 2,000 paths or a JSON body over 256,000 bytes.
48PATHS_INFO_MAX_PATHS = 2000
49PATHS_INFO_BODY_BUDGET_BYTES = 240_000
50PATHS_INFO_TIMEOUT_SECONDS = (10, 60)
51
52HF_TRANSFER_UNAVAILABLE_ERROR_MESSAGE = (
53 "Fast transfer using 'hf_transfer' is enabled (HF_HUB_ENABLE_HF_TRANSFER=1) "
54 "but 'hf_transfer' package is not available in your environment. "
55 "Either install hf_transfer with 'pip install hf_transfer' or "
56 "disable it by setting HF_HUB_ENABLE_HF_TRANSFER=0"
57)
58
59
[docs]
60class HuggingFaceCredentialsProvider(CredentialsProvider):
61 """
62 A concrete implementation of the :py:class:`multistorageclient.types.CredentialsProvider` that provides HuggingFace credentials.
63 """
64
65 def __init__(self, access_token: str):
66 """
67 Initializes the :py:class:`HuggingFaceCredentialsProvider` with the provided access token.
68
69 :param access_token: The HuggingFace access token for authentication.
70 """
71 self.token = access_token
72
[docs]
73 def get_credentials(self) -> Credentials:
74 """
75 Retrieves the current HuggingFace credentials.
76
77 :return: The current credentials used for HuggingFace authentication.
78 """
79 return Credentials(
80 access_key="",
81 secret_key="",
82 token=self.token,
83 expiration=None,
84 )
85
[docs]
86 def refresh_credentials(self) -> None:
87 """
88 Refreshes the credentials if they are expired or about to expire.
89
90 Note: HuggingFace tokens typically don't expire, so this is a no-op.
91 """
92
93
[docs]
94class HuggingFaceStorageProvider(BaseStorageProvider):
95 """
96 A concrete implementation of the :py:class:`multistorageclient.types.StorageProvider` for interacting with HuggingFace Hub repositories.
97 """
98
99 def __init__(
100 self,
101 repository_id: str,
102 repo_type: str = "model",
103 base_path: str = "",
104 repo_revision: str = "main",
105 credentials_provider: CredentialsProvider | None = None,
106 config_dict: dict[str, Any] | None = None,
107 telemetry_provider: Callable[[], Telemetry] | None = None,
108 ):
109 """
110 Initializes the :py:class:`HuggingFaceStorageProvider` with repository information and optional credentials provider.
111
112 :param repository_id: The HuggingFace repository ID (e.g., 'username/repo-name').
113 :param repo_type: The type of repository ('dataset', 'model', 'space'). Defaults to 'model'.
114 :param base_path: The root prefix path within the repository where all operations will be scoped.
115 :param repo_revision: The git revision (branch, tag, or commit) to use. Defaults to 'main'.
116 :param credentials_provider: The provider to retrieve HuggingFace credentials.
117 :param config_dict: Resolved MSC config.
118 :param telemetry_provider: A function that provides a telemetry instance.
119 """
120
121 # Validate repo_type
122 allowed_repo_types = {"dataset", "model", "space"}
123 if repo_type not in allowed_repo_types:
124 raise ValueError(f"Invalid repo_type '{repo_type}'. Must be one of: {allowed_repo_types}")
125
126 # Validate repository_id format
127 if not repository_id or "/" not in repository_id:
128 raise ValueError(f"Invalid repository_id '{repository_id}'. Expected format: 'username/repo-name'")
129
130 self._validate_hf_transfer_availability()
131
132 super().__init__(
133 base_path=base_path,
134 provider_name=PROVIDER,
135 config_dict=config_dict,
136 telemetry_provider=telemetry_provider,
137 )
138
139 self._repository_id = repository_id
140 self._repo_type = repo_type
141 self._repo_revision = repo_revision
142 self._credentials_provider = credentials_provider
143
144 self._hf_client: HfApi = self._create_hf_api_client()
145
146 def _create_hf_api_client(self) -> HfApi:
147 """
148 Creates and configures the HuggingFace API client.
149
150 Initializes the HfApi client with authentication token if credentials are provided,
151 otherwise creates an unauthenticated client for public repositories.
152
153 :return: Configured HfApi client instance.
154 """
155
156 token = None
157 if self._credentials_provider:
158 creds = self._credentials_provider.get_credentials()
159 token = creds.token
160
161 return HfApi(token=token)
162
163 def _validate_hf_transfer_availability(self) -> None:
164 """
165 Validates that hf_transfer is available if it's enabled via environment variables.
166
167 Raises:
168 ValueError: If hf_transfer is enabled but not available.
169 """
170 # Check if hf_transfer is enabled via environment variable
171 hf_transfer_enabled = os.environ.get("HF_HUB_ENABLE_HF_TRANSFER", "").lower() in ("1", "on", "true", "yes")
172
173 if hf_transfer_enabled and importlib.util.find_spec("hf_transfer") is None:
174 raise ValueError(HF_TRANSFER_UNAVAILABLE_ERROR_MESSAGE)
175
176 def _parse_rate_limit_headers(self, response) -> str:
177 """
178 Parses HuggingFace rate limit headers and returns formatted information.
179
180 HuggingFace returns rate limit information in these headers:
181 - RateLimit: "api";r=0;t=142
182 - r = requests remaining in the current window
183 - t = seconds until rate limit resets
184 - RateLimit-Policy: "fixed window";"api";q=10000;w=300
185 - q = total requests allowed per window
186 - w = window size in seconds
187
188 Reference: https://huggingface.co/docs/hub/rate-limits
189
190 :param response: The HTTP response object containing rate limit headers.
191 :return: Formatted string with rate limit information, or empty string if headers not found.
192 """
193
194 try:
195 headers = response.headers
196 except Exception:
197 return ""
198
199 rate_limit_info = []
200
201 # Note: HTTP headers are case-insensitive, but we use the canonical casing from HF docs
202 if "RateLimit" in headers:
203 rate_limit = headers["RateLimit"]
204 # Extract r (remaining) and t (time until reset)
205 remaining = None
206 reset_seconds = None
207
208 parts = rate_limit.split(";")
209 for part in parts:
210 part = part.strip()
211 if part.startswith("r="):
212 try:
213 remaining = int(part[2:])
214 except ValueError:
215 pass
216 elif part.startswith("t="):
217 try:
218 reset_seconds = int(part[2:])
219 except ValueError:
220 pass
221
222 if remaining is not None:
223 rate_limit_info.append(f"Requests remaining in current window: {remaining}")
224 if reset_seconds is not None:
225 rate_limit_info.append(f"Rate limit resets in: {reset_seconds} seconds")
226
227 if "RateLimit-Policy" in headers:
228 policy = headers["RateLimit-Policy"]
229 # Extract q (quota) and w (window size)
230 quota = None
231 window_seconds = None
232
233 parts = policy.split(";")
234 for part in parts:
235 part = part.strip()
236 if part.startswith("q="):
237 try:
238 quota = int(part[2:])
239 except ValueError:
240 pass
241 elif part.startswith("w="):
242 try:
243 window_seconds = int(part[2:])
244 except ValueError:
245 pass
246
247 if quota is not None and window_seconds is not None:
248 window_minutes = window_seconds / 60
249 rate_limit_info.append(f"Rate limit policy: {quota} requests per {window_minutes:.0f}-minute window")
250
251 if rate_limit_info:
252 return " | ".join(rate_limit_info)
253
254 return ""
255
256 def _translate_errors(
257 self,
258 func: Callable[[], _T],
259 operation: str,
260 repo_id: str,
261 path: str,
262 ) -> _T:
263 """
264 Translates HuggingFace errors into standardized exceptions with retry logic.
265
266 Parses HuggingFace rate limit headers (RateLimit and RateLimit-Policy) to provide
267 detailed information about rate limiting to users. See https://huggingface.co/docs/hub/rate-limits
268
269 :param func: The function that performs the actual HuggingFace operation.
270 :param operation: The type of operation being performed (e.g., "upload", "download", "delete").
271 :param repo_id: The HuggingFace repository ID.
272 :param path: The path of the object within the repository.
273 :return: The result of the HuggingFace operation.
274 :raises RetryableError: For transient errors that can be retried (429, 503, connection errors).
275 :raises FileNotFoundError: When the requested resource is not found.
276 :raises RuntimeError: For other non-retryable errors.
277 """
278 try:
279 return func()
280 except RepositoryNotFoundError as error:
281 raise FileNotFoundError(
282 f"Repository not found or access denied: {repo_id}. "
283 f"Verify the repository exists and you have access permissions."
284 ) from error
285 except RevisionNotFoundError as error:
286 raise FileNotFoundError(
287 f"Revision '{self._repo_revision}' not found in repository {repo_id}. "
288 f"Verify the branch, tag, or commit exists."
289 ) from error
290 except EntryNotFoundError as error:
291 raise FileNotFoundError(f"File not found in HuggingFace repository: {path}") from error
292 except FileNotFoundError:
293 raise
294 except HfHubHTTPError as error:
295 # Extract status code and parse rate limit headers
296 # Don't use hasattr() - it's unreliable with response objects
297 status_code = None
298 response = None
299
300 try:
301 response = error.response
302 if response is not None:
303 status_code = response.status_code
304 except AttributeError:
305 pass
306
307 rate_limit_info = self._parse_rate_limit_headers(response)
308 quota_suffix = f" | {rate_limit_info}" if rate_limit_info else ""
309
310 error_info = f"repo_id: {repo_id}, path: {path}, status_code: {status_code}, error: {error}"
311
312 if status_code == 404:
313 raise FileNotFoundError(f"Object {repo_id}/{path} does not exist. {error_info}") from error
314 elif status_code == 409:
315 raise RetryableError(f"Conflict Error for {repo_id}. {error_info}{quota_suffix}") from error
316 elif status_code == 429:
317 base_message = f"Rate limit exceeded when {operation} object(s) at {repo_id}/{path}. {error_info}"
318 raise RetryableError(f"{base_message}{quota_suffix}") from error
319 elif status_code == 503:
320 raise RetryableError(
321 f"Service unavailable when {operation} object(s) at {repo_id}/{path}. {error_info}{quota_suffix}"
322 ) from error
323 elif status_code in (408, 500, 502, 504):
324 raise RetryableError(
325 f"Transient error ({status_code}) when {operation} object(s) at {repo_id}/{path}. {error_info}{quota_suffix}"
326 ) from error
327 else:
328 raise RuntimeError(
329 f"HuggingFace API error during {operation} of {path}: {error}{quota_suffix}"
330 ) from error
331 except (ConnectionError, TimeoutError, OSError) as error:
332 raise RetryableError(
333 f"Connection error when {operation} object(s) at {repo_id}/{path}, error type: {type(error).__name__}"
334 ) from error
335 except Exception as error:
336 raise RuntimeError(f"Unexpected error during {operation} of {path}: {error}") from error
337
338 def _put_object(
339 self,
340 path: str,
341 body: bytes,
342 if_match: str | None = None,
343 if_none_match: str | None = None,
344 attributes: dict[str, str] | None = None,
345 ) -> int:
346 """
347 Uploads an object to the HuggingFace repository.
348
349 :param path: The path where the object will be stored in the repository.
350 :param body: The content of the object to store.
351 :param if_match: Optional ETag for conditional uploads (not supported by HuggingFace).
352 :param if_none_match: Optional ETag for conditional uploads (not supported by HuggingFace).
353 :param attributes: Optional attributes for the object (not supported by HuggingFace).
354 :return: Data size in bytes.
355 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
356 :raises ValueError: If client attempts to create a directory.
357 :raises ValueError: If conditional upload parameters are provided (not supported).
358 """
359 if not self._hf_client:
360 raise RuntimeError("HuggingFace client not initialized")
361
362 if if_match is not None or if_none_match is not None:
363 raise ValueError(
364 "HuggingFace provider does not support conditional uploads. "
365 "if_match and if_none_match parameters are not supported."
366 )
367
368 if attributes is not None:
369 raise ValueError(
370 "HuggingFace provider does not support custom object attributes. "
371 "Use commit messages or repository metadata instead."
372 )
373
374 if path.endswith("/"):
375 raise ValueError(
376 "HuggingFace Storage Provider does not support explicit directory creation. "
377 "Directories are created implicitly when files are uploaded to paths within them."
378 )
379
380 path = self._normalize_path(path)
381
382 def _invoke_api():
383 with tempfile.NamedTemporaryFile(delete=False) as temp_file:
384 temp_file.write(body)
385 temp_file_path = temp_file.name
386
387 try:
388 self._hf_client.upload_file(
389 path_or_fileobj=temp_file_path,
390 path_in_repo=path,
391 repo_id=self._repository_id,
392 repo_type=self._repo_type,
393 revision=self._repo_revision,
394 commit_message=f"Upload {path}",
395 commit_description=None,
396 create_pr=False,
397 )
398
399 return len(body)
400
401 finally:
402 os.unlink(temp_file_path)
403
404 return self._translate_errors(_invoke_api, "PUT", self._repository_id, path)
405
406 def _get_object(self, path: str, byte_range: Range | None = None) -> bytes:
407 """
408 Retrieves an object from the HuggingFace repository.
409
410 :param path: The path of the object to retrieve from the repository.
411 :param byte_range: Optional byte range for partial content (not supported by HuggingFace).
412 :return: The content of the retrieved object.
413 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
414 :raises ValueError: If a byte range is requested (HuggingFace doesn't support range reads).
415 :raises FileNotFoundError: If the file doesn't exist in the repository.
416 """
417
418 if not self._hf_client:
419 raise RuntimeError("HuggingFace client not initialized")
420
421 if byte_range is not None:
422 raise ValueError(
423 "HuggingFace provider does not support partial range reads. "
424 f"Requested range: offset={byte_range.offset}, size={byte_range.size}. "
425 "To read the entire file, call get_object() without the byte_range parameter."
426 )
427
428 path = self._normalize_path(path)
429
430 def _invoke_api():
431 with tempfile.TemporaryDirectory() as temp_dir:
432 downloaded_path = self._hf_client.hf_hub_download(
433 repo_id=self._repository_id,
434 filename=path,
435 repo_type=self._repo_type,
436 revision=self._repo_revision,
437 local_dir=temp_dir,
438 )
439
440 with open(downloaded_path, "rb") as f:
441 data = f.read()
442
443 return data
444
445 return self._translate_errors(_invoke_api, "GET", self._repository_id, path)
446
447 def _copy_object(self, src_path: str, dest_path: str) -> int:
448 """
449 Copies an object within the HuggingFace repository using server-side copy.
450
451 .. note::
452 Copy behavior is size-dependent: files ≥10MB are copied remotely via
453 metadata (LFS), while files <10MB are downloaded and re-uploaded.
454
455 :param src_path: The source path of the object to copy.
456 :param dest_path: The destination path for the copied object.
457 :return: Data size in bytes.
458 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
459 :raises FileNotFoundError: If the source file doesn't exist.
460 """
461 if not self._hf_client:
462 raise RuntimeError("HuggingFace client not initialized")
463
464 src_path = self._normalize_path(src_path)
465 dest_path = self._normalize_path(dest_path)
466
467 src_object = self._get_object_metadata(src_path)
468
469 def _invoke_api():
470 operations = [
471 CommitOperationCopy(
472 src_path_in_repo=src_path,
473 path_in_repo=dest_path,
474 )
475 ]
476
477 self._hf_client.create_commit(
478 repo_id=self._repository_id,
479 operations=operations,
480 commit_message=f"Copy {src_path} to {dest_path}",
481 repo_type=self._repo_type,
482 revision=self._repo_revision,
483 )
484
485 return src_object.content_length
486
487 return self._translate_errors(_invoke_api, "COPY", self._repository_id, f"{src_path} to {dest_path}")
488
489 def _delete_object(self, path: str, if_match: str | None = None) -> None:
490 """
491 Deletes an object from the HuggingFace repository.
492
493 :param path: The path of the object to delete from the repository.
494 :param if_match: Optional ETag for conditional deletion (not supported by HuggingFace).
495 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
496 :raises ValueError: If conditional deletion parameters are provided (not supported).
497 :raises FileNotFoundError: If the file doesn't exist in the repository.
498 """
499 if not self._hf_client:
500 raise RuntimeError("HuggingFace client not initialized")
501
502 if if_match is not None:
503 raise ValueError(
504 "HuggingFace provider does not support conditional deletion. if_match parameter is not supported."
505 )
506
507 path = self._normalize_path(path)
508
509 def _invoke_api():
510 self._hf_client.delete_file(
511 path_in_repo=path,
512 repo_id=self._repository_id,
513 repo_type=self._repo_type,
514 revision=self._repo_revision,
515 commit_message=f"Delete {path}",
516 )
517
518 self._translate_errors(_invoke_api, "DELETE", self._repository_id, path)
519
520 def _item_to_metadata(self, item: RepoFile | RepoFolder) -> ObjectMetadata:
521 """
522 Convert a RepoFile or RepoFolder into ObjectMetadata.
523
524 :param item: The RepoFile or RepoFolder item from HuggingFace API.
525 :return: ObjectMetadata representing the item.
526 """
527 # expand=True populates last_commit; fall back to the epoch sentinel when it is absent.
528 last_modified = AWARE_DATETIME_MIN
529 last_commit = getattr(item, "last_commit", None)
530 if last_commit is not None and getattr(last_commit, "date", None):
531 last_modified = last_commit.date
532
533 if isinstance(item, RepoFile):
534 etag = item.blob_id
535 return ObjectMetadata(
536 key=item.path,
537 type="file",
538 content_length=item.size,
539 last_modified=last_modified,
540 etag=etag,
541 content_type=None,
542 storage_class=None,
543 metadata=None,
544 )
545 else:
546 etag = item.tree_id
547 return ObjectMetadata(
548 key=item.path,
549 type="directory",
550 content_length=0,
551 last_modified=last_modified,
552 etag=etag,
553 content_type=None,
554 storage_class=None,
555 metadata=None,
556 )
557
558 def _make_symlink(self, path: str, target: str) -> None:
559 """
560 Not supported. HuggingFace repositories are read-only through this provider.
561
562 :raises NotImplementedError: Always.
563 """
564 raise NotImplementedError("HuggingFace provider does not support symlink creation.")
565
566 def _get_object_metadata(self, path: str, strict: bool = True) -> ObjectMetadata:
567 """
568 Retrieves metadata for an object in the HuggingFace repository.
569
570 :param path: The path of the object to get metadata for.
571 :param strict: Whether to raise an error if the object doesn't exist.
572 :return: Metadata about the object.
573 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
574 :raises FileNotFoundError: If the file doesn't exist and strict=True.
575 """
576 if not self._hf_client:
577 raise RuntimeError("HuggingFace client not initialized")
578
579 path = self._normalize_path(path)
580
581 def _invoke_api():
582 items = self._hf_client.get_paths_info(
583 repo_id=self._repository_id,
584 paths=[path],
585 repo_type=self._repo_type,
586 revision=self._repo_revision,
587 expand=True,
588 )
589
590 if not items:
591 raise FileNotFoundError(f"File not found in HuggingFace repository: {path}")
592
593 item = items[0]
594 return self._item_to_metadata(item)
595
596 try:
597 return self._translate_errors(_invoke_api, "HEAD", self._repository_id, path)
598 except FileNotFoundError:
599 if strict:
600 dir_path = path.rstrip("/") + "/"
601 if self._is_dir(dir_path):
602 return ObjectMetadata(
603 key=dir_path,
604 type="directory",
605 content_length=0,
606 last_modified=AWARE_DATETIME_MIN,
607 etag=None,
608 content_type=None,
609 storage_class=None,
610 metadata=None,
611 )
612 raise
613
614 def _list_objects(
615 self,
616 path: str,
617 start_after: str | None = None,
618 end_at: str | None = None,
619 include_directories: bool = False,
620 symlink_handling: SymlinkHandling = SymlinkHandling.FOLLOW,
621 ) -> Iterator[ObjectMetadata]:
622 """
623 Lists objects in the HuggingFace repository under the specified path.
624
625 :param path: The path to list objects under.
626 :param start_after: The key to start listing after (exclusive, used as cursor).
627 :param end_at: The key to end listing at (inclusive, used as cursor).
628 :param include_directories: Whether to include directories in the listing.
629 :return: An iterator over object metadata for objects under the specified path.
630 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
631
632 .. note::
633 The tree is listed without expanded metadata, which the Hub serves in pages of 1,000 entries.
634 As pages arrive, entries are collected into batches of up to 2,000, and the last commit of every
635 entry in a batch is fetched with a single ``paths-info`` request. Each batch is yielded as soon
636 as its metadata arrives. The ordering is directory-first, then files, with lexicographical
637 ordering within each group, so ``start_after`` and ``end_at`` are matched as exact keys.
638 """
639 if not self._hf_client:
640 raise RuntimeError("HuggingFace client not initialized")
641
642 path = self._normalize_path(path)
643
644 try:
645 metadata = self._get_object_metadata(path.rstrip("/"), strict=False)
646 if metadata and metadata.type == "file":
647 yield metadata
648 return
649 except FileNotFoundError:
650 pass
651
652 dir_path = path.rstrip("/")
653
654 # Pin one commit so the tree and paths-info requests see the same snapshot of a mutable branch or tag.
655 revision = self._translate_errors(
656 lambda: (
657 self._hf_client.repo_info(
658 repo_id=self._repository_id, repo_type=self._repo_type, revision=self._repo_revision
659 ).sha
660 ),
661 "LIST",
662 self._repository_id,
663 path,
664 )
665 if revision is None:
666 raise RuntimeError(
667 f"Repository {self._repository_id} returned no commit SHA for revision '{self._repo_revision}'."
668 )
669
670 def _listed_paths() -> Iterator[str]:
671 # Use cursor-based pagination because HuggingFace returns items with
672 # directory-first ordering (not pure lexicographical).
673 seen_start = start_after is None
674 try:
675 for item in self._hf_client.list_repo_tree(
676 repo_id=self._repository_id,
677 path_in_repo=dir_path + "/" if dir_path else None,
678 repo_type=self._repo_type,
679 revision=revision,
680 expand=False,
681 recursive=not include_directories,
682 ):
683 if not seen_start:
684 seen_start = item.path == start_after
685 continue
686 if isinstance(item, RepoFile) or (include_directories and isinstance(item, RepoFolder)):
687 yield item.path
688 if end_at is not None and item.path == end_at:
689 return
690 except EntryNotFoundError:
691 # Directory doesn't exist - return empty (matches POSIX behavior). A missing repository or
692 # revision is translated to FileNotFoundError by _translate_errors and propagates.
693 return
694
695 batches = _paths_info_batches(_listed_paths())
696
697 def _invoke_api() -> list[RepoFile | RepoFolder] | None:
698 batch = next(batches, None)
699 if batch is None:
700 return None
701 items = self._get_paths_info(batch, revision)
702 return [items[item_path] for item_path in batch if item_path in items]
703
704 while (items := self._translate_errors(_invoke_api, "LIST", self._repository_id, path)) is not None:
705 for item in items:
706 yield self._item_to_metadata(item)
707
708 def _get_paths_info(self, paths: list[str], revision: str) -> dict[str, RepoFile | RepoFolder]:
709 """
710 Fetches the metadata and last commit of up to 2,000 paths with a single ``paths-info`` request.
711
712 The request is sent as JSON, which lets each request carry up to 2,000 paths or 256 KB of data, more
713 than ``HfApi.get_paths_info`` allows.
714
715 :param paths: The paths to look up.
716 :param revision: The commit SHA to look the paths up at.
717 :return: The metadata of each path that exists, keyed by path.
718 """
719 endpoint = f"{self._hf_client.endpoint}/api/{self._repo_type}s/{self._repository_id}"
720 url = f"{endpoint}/paths-info/{quote(revision, safe='')}"
721 response = get_session().post(
722 url,
723 json={"paths": paths, "expand": True},
724 headers=build_hf_headers(token=self._hf_client.token),
725 timeout=PATHS_INFO_TIMEOUT_SECONDS,
726 )
727 hf_raise_for_status(response)
728 return {
729 entry["path"]: RepoFile(**entry) if entry["type"] == "file" else RepoFolder(**entry)
730 for entry in response.json()
731 }
732
733 def _upload_file(self, remote_path: str, f: str | IO, attributes: dict[str, str] | None = None) -> int:
734 """
735 Uploads a file to the HuggingFace repository.
736
737 :param remote_path: The remote path where the file will be stored in the repository.
738 :param f: File path or file object to upload.
739 :param attributes: Optional attributes for the file (not supported by HuggingFace).
740 :return: Data size in bytes.
741 :raises RuntimeError: If HuggingFace client is not initialized or API errors occur.
742 :raises ValueError: If client attempts to create a directory.
743 :raises ValueError: If custom attributes are provided (not supported).
744 """
745 if not self._hf_client:
746 raise RuntimeError("HuggingFace client not initialized")
747
748 if attributes is not None:
749 raise ValueError(
750 "HuggingFace provider does not support custom file attributes. "
751 "Use commit messages or repository metadata instead."
752 )
753
754 if remote_path.endswith("/"):
755 raise ValueError(
756 "HuggingFace Storage Provider does not support explicit directory creation. "
757 "Directories are created implicitly when files are uploaded to paths within them."
758 )
759
760 remote_path = self._normalize_path(remote_path)
761
762 def _invoke_api():
763 if isinstance(f, str):
764 file_size = os.path.getsize(f)
765
766 self._hf_client.upload_file(
767 path_or_fileobj=f,
768 path_in_repo=remote_path,
769 repo_id=self._repository_id,
770 repo_type=self._repo_type,
771 revision=self._repo_revision,
772 commit_message=f"Upload {remote_path}",
773 commit_description=None,
774 create_pr=False,
775 )
776
777 return file_size
778
779 else:
780 content = f.read()
781
782 if isinstance(content, str):
783 content_bytes = content.encode("utf-8")
784 else:
785 content_bytes = content
786
787 # Create temporary file since HfAPI.upload_file requires BinaryIO, not generic IO
788 with tempfile.NamedTemporaryFile(delete=False) as temp_file:
789 temp_file.write(content_bytes)
790 temp_file_path = temp_file.name
791
792 try:
793 self._hf_client.upload_file(
794 path_or_fileobj=temp_file_path,
795 path_in_repo=remote_path,
796 repo_id=self._repository_id,
797 repo_type=self._repo_type,
798 revision=self._repo_revision,
799 commit_message=f"Upload {remote_path}",
800 create_pr=False,
801 )
802
803 return len(content_bytes)
804
805 finally:
806 os.unlink(temp_file_path)
807
808 return self._translate_errors(_invoke_api, "PUT", self._repository_id, remote_path)
809
810 def _download_file(self, remote_path: str, f: str | IO, metadata: ObjectMetadata | None = None) -> int:
811 """
812 Downloads a file from the HuggingFace repository.
813
814 :param remote_path: The remote path of the file to download from the repository.
815 :param f: Local file path or file object to write to.
816 :param metadata: Optional object metadata (not used in this implementation).
817 :return: Data size in bytes.
818 """
819 if not self._hf_client:
820 raise RuntimeError("HuggingFace client not initialized")
821
822 remote_path = self._normalize_path(remote_path)
823
824 def _invoke_api():
825 if isinstance(f, str):
826 parent_dir = os.path.dirname(f)
827 if parent_dir:
828 safe_makedirs(parent_dir)
829
830 target_dir = parent_dir if parent_dir else "."
831 downloaded_path = self._hf_client.hf_hub_download(
832 repo_id=self._repository_id,
833 filename=remote_path,
834 repo_type=self._repo_type,
835 revision=self._repo_revision,
836 local_dir=target_dir,
837 )
838
839 if os.path.abspath(downloaded_path) != os.path.abspath(f):
840 os.rename(downloaded_path, f)
841
842 return os.path.getsize(f)
843
844 else:
845 with tempfile.TemporaryDirectory() as temp_dir:
846 downloaded_path = self._hf_client.hf_hub_download(
847 repo_id=self._repository_id,
848 filename=remote_path,
849 repo_type=self._repo_type,
850 revision=self._repo_revision,
851 local_dir=temp_dir,
852 )
853
854 with open(downloaded_path, "rb") as src:
855 data = src.read()
856 if isinstance(f, io.TextIOBase):
857 f.write(data.decode("utf-8"))
858 else:
859 f.write(data)
860
861 return len(data)
862
863 return self._translate_errors(_invoke_api, "GET", self._repository_id, remote_path)
864
865 def _is_dir(self, path: str) -> bool:
866 """
867 Helper method to check if a path is a directory.
868
869 :param path: The path to check.
870 :return: True if the path appears to be a directory (has files under it).
871 """
872 path = path.rstrip("/")
873 if not path:
874 # The root of the repo is always a directory
875 return True
876
877 try:
878 path_info = self._hf_client.get_paths_info(
879 repo_id=self._repository_id,
880 paths=[path],
881 repo_type=self._repo_type,
882 revision=self._repo_revision,
883 )
884
885 if not path_info:
886 return False
887
888 return isinstance(path_info[0], RepoFolder)
889
890 except RepositoryNotFoundError as e:
891 raise FileNotFoundError(
892 f"Repository not found or access denied: {self._repository_id}. "
893 f"Verify the repository exists and you have access permissions."
894 ) from e
895 except RevisionNotFoundError as e:
896 raise FileNotFoundError(
897 f"Revision '{self._repo_revision}' not found in repository {self._repository_id}. "
898 f"Verify the branch, tag, or commit exists."
899 ) from e
900 except IndexError:
901 return False
902 except Exception as e:
903 raise Exception(f"Unexpected error: {e}")
904
905 def _normalize_path(self, path: str) -> str:
906 """
907 Normalize path for HuggingFace API by removing leading slashes.
908 HuggingFace expects relative paths within repositories.
909 """
910 return path.lstrip("/")
911
912
913def _paths_info_batches(paths: Iterable[str]) -> Iterator[list[str]]:
914 """
915 Groups paths into batches that fit in a single ``paths-info`` request, yielding each one as soon as it is full.
916
917 :param paths: The paths to group, in order.
918 :return: An iterator over batches of at most 2,000 paths whose JSON body stays under the byte budget.
919 """
920 batch: list[str] = []
921 size = 0
922 for path in paths:
923 cost = len(json.dumps(path).encode()) + 2
924 if batch and size + cost > PATHS_INFO_BODY_BUDGET_BYTES:
925 yield batch
926 batch, size = [], 0
927 batch.append(path)
928 size += cost
929 if len(batch) == PATHS_INFO_MAX_PATHS:
930 yield batch
931 batch, size = [], 0
932 if batch:
933 yield batch