Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/__about__.py +17 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/__init__.py +13 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/exceptions.py +52 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/fernet.py +224 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/py.typed +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/utils.py +138 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/INSTALLER +1 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/METADATA +215 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/RECORD +269 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/REQUESTED +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/WHEEL +5 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/top_level.txt +1 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/__init__.py +1690 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_buckets.py +1177 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_commit_api.py +975 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_commit_scheduler.py +353 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_dataset_viewer.py +173 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_eval_results.py +211 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_jobs_api.py +399 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_local_folder.py +451 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_login.py +495 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_oauth.py +460 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_snapshot_download.py +466 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_space_api.py +184 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_tensorboard_logger.py +190 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_upload_large_folder.py +765 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_webhooks_payload.py +137 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_webhooks_server.py +376 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/community.py +363 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/constants.py +283 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/dataclasses.py +667 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/fastai_utils.py +414 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/hf_api.py +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/hf_file_system.py +1454 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/hub_mixin.py +831 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/lfs.py +395 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/py.typed +0 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/repocard.py +826 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/repocard_data.py +770 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/INSTALLER +1 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/METADATA +121 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/RECORD +105 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/WHEEL +4 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/INSTALLER +1 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/METADATA +115 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/RECORD +360 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/WHEEL +5 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/entry_points.txt +3 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/top_level.txt +1 -0
- data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython_pygments_lexers-1.1.1.dist-info/INSTALLER +1 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/__about__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
__all__ = [
|
| 8 |
+
"__author__",
|
| 9 |
+
"__copyright__",
|
| 10 |
+
"__version__",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
__version__ = "46.0.5"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__author__ = "The Python Cryptographic Authority and individual contributors"
|
| 17 |
+
__copyright__ = f"Copyright 2013-2025 {__author__}"
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/__init__.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
from cryptography.__about__ import __author__, __copyright__, __version__
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"__author__",
|
| 11 |
+
"__copyright__",
|
| 12 |
+
"__version__",
|
| 13 |
+
]
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/exceptions.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import typing
|
| 8 |
+
|
| 9 |
+
from cryptography.hazmat.bindings._rust import exceptions as rust_exceptions
|
| 10 |
+
|
| 11 |
+
if typing.TYPE_CHECKING:
|
| 12 |
+
from cryptography.hazmat.bindings._rust import openssl as rust_openssl
|
| 13 |
+
|
| 14 |
+
_Reasons = rust_exceptions._Reasons
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class UnsupportedAlgorithm(Exception):
|
| 18 |
+
def __init__(self, message: str, reason: _Reasons | None = None) -> None:
|
| 19 |
+
super().__init__(message)
|
| 20 |
+
self._reason = reason
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class AlreadyFinalized(Exception):
|
| 24 |
+
pass
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class AlreadyUpdated(Exception):
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class NotYetFinalized(Exception):
|
| 32 |
+
pass
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class InvalidTag(Exception):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class InvalidSignature(Exception):
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class InternalError(Exception):
|
| 44 |
+
def __init__(
|
| 45 |
+
self, msg: str, err_code: list[rust_openssl.OpenSSLError]
|
| 46 |
+
) -> None:
|
| 47 |
+
super().__init__(msg)
|
| 48 |
+
self.err_code = err_code
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class InvalidKey(Exception):
|
| 52 |
+
pass
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/fernet.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import base64
|
| 8 |
+
import binascii
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
import typing
|
| 12 |
+
from collections.abc import Iterable
|
| 13 |
+
|
| 14 |
+
from cryptography import utils
|
| 15 |
+
from cryptography.exceptions import InvalidSignature
|
| 16 |
+
from cryptography.hazmat.primitives import hashes, padding
|
| 17 |
+
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
| 18 |
+
from cryptography.hazmat.primitives.hmac import HMAC
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class InvalidToken(Exception):
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
_MAX_CLOCK_SKEW = 60
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class Fernet:
|
| 29 |
+
def __init__(
|
| 30 |
+
self,
|
| 31 |
+
key: bytes | str,
|
| 32 |
+
backend: typing.Any = None,
|
| 33 |
+
) -> None:
|
| 34 |
+
try:
|
| 35 |
+
key = base64.urlsafe_b64decode(key)
|
| 36 |
+
except binascii.Error as exc:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
"Fernet key must be 32 url-safe base64-encoded bytes."
|
| 39 |
+
) from exc
|
| 40 |
+
if len(key) != 32:
|
| 41 |
+
raise ValueError(
|
| 42 |
+
"Fernet key must be 32 url-safe base64-encoded bytes."
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
self._signing_key = key[:16]
|
| 46 |
+
self._encryption_key = key[16:]
|
| 47 |
+
|
| 48 |
+
@classmethod
|
| 49 |
+
def generate_key(cls) -> bytes:
|
| 50 |
+
return base64.urlsafe_b64encode(os.urandom(32))
|
| 51 |
+
|
| 52 |
+
def encrypt(self, data: bytes) -> bytes:
|
| 53 |
+
return self.encrypt_at_time(data, int(time.time()))
|
| 54 |
+
|
| 55 |
+
def encrypt_at_time(self, data: bytes, current_time: int) -> bytes:
|
| 56 |
+
iv = os.urandom(16)
|
| 57 |
+
return self._encrypt_from_parts(data, current_time, iv)
|
| 58 |
+
|
| 59 |
+
def _encrypt_from_parts(
|
| 60 |
+
self, data: bytes, current_time: int, iv: bytes
|
| 61 |
+
) -> bytes:
|
| 62 |
+
utils._check_bytes("data", data)
|
| 63 |
+
|
| 64 |
+
padder = padding.PKCS7(algorithms.AES.block_size).padder()
|
| 65 |
+
padded_data = padder.update(data) + padder.finalize()
|
| 66 |
+
encryptor = Cipher(
|
| 67 |
+
algorithms.AES(self._encryption_key),
|
| 68 |
+
modes.CBC(iv),
|
| 69 |
+
).encryptor()
|
| 70 |
+
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
|
| 71 |
+
|
| 72 |
+
basic_parts = (
|
| 73 |
+
b"\x80"
|
| 74 |
+
+ current_time.to_bytes(length=8, byteorder="big")
|
| 75 |
+
+ iv
|
| 76 |
+
+ ciphertext
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
h = HMAC(self._signing_key, hashes.SHA256())
|
| 80 |
+
h.update(basic_parts)
|
| 81 |
+
hmac = h.finalize()
|
| 82 |
+
return base64.urlsafe_b64encode(basic_parts + hmac)
|
| 83 |
+
|
| 84 |
+
def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:
|
| 85 |
+
timestamp, data = Fernet._get_unverified_token_data(token)
|
| 86 |
+
if ttl is None:
|
| 87 |
+
time_info = None
|
| 88 |
+
else:
|
| 89 |
+
time_info = (ttl, int(time.time()))
|
| 90 |
+
return self._decrypt_data(data, timestamp, time_info)
|
| 91 |
+
|
| 92 |
+
def decrypt_at_time(
|
| 93 |
+
self, token: bytes | str, ttl: int, current_time: int
|
| 94 |
+
) -> bytes:
|
| 95 |
+
if ttl is None:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"decrypt_at_time() can only be used with a non-None ttl"
|
| 98 |
+
)
|
| 99 |
+
timestamp, data = Fernet._get_unverified_token_data(token)
|
| 100 |
+
return self._decrypt_data(data, timestamp, (ttl, current_time))
|
| 101 |
+
|
| 102 |
+
def extract_timestamp(self, token: bytes | str) -> int:
|
| 103 |
+
timestamp, data = Fernet._get_unverified_token_data(token)
|
| 104 |
+
# Verify the token was not tampered with.
|
| 105 |
+
self._verify_signature(data)
|
| 106 |
+
return timestamp
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]:
|
| 110 |
+
if not isinstance(token, (str, bytes)):
|
| 111 |
+
raise TypeError("token must be bytes or str")
|
| 112 |
+
|
| 113 |
+
try:
|
| 114 |
+
data = base64.urlsafe_b64decode(token)
|
| 115 |
+
except (TypeError, binascii.Error):
|
| 116 |
+
raise InvalidToken
|
| 117 |
+
|
| 118 |
+
if not data or data[0] != 0x80:
|
| 119 |
+
raise InvalidToken
|
| 120 |
+
|
| 121 |
+
if len(data) < 9:
|
| 122 |
+
raise InvalidToken
|
| 123 |
+
|
| 124 |
+
timestamp = int.from_bytes(data[1:9], byteorder="big")
|
| 125 |
+
return timestamp, data
|
| 126 |
+
|
| 127 |
+
def _verify_signature(self, data: bytes) -> None:
|
| 128 |
+
h = HMAC(self._signing_key, hashes.SHA256())
|
| 129 |
+
h.update(data[:-32])
|
| 130 |
+
try:
|
| 131 |
+
h.verify(data[-32:])
|
| 132 |
+
except InvalidSignature:
|
| 133 |
+
raise InvalidToken
|
| 134 |
+
|
| 135 |
+
def _decrypt_data(
|
| 136 |
+
self,
|
| 137 |
+
data: bytes,
|
| 138 |
+
timestamp: int,
|
| 139 |
+
time_info: tuple[int, int] | None,
|
| 140 |
+
) -> bytes:
|
| 141 |
+
if time_info is not None:
|
| 142 |
+
ttl, current_time = time_info
|
| 143 |
+
if timestamp + ttl < current_time:
|
| 144 |
+
raise InvalidToken
|
| 145 |
+
|
| 146 |
+
if current_time + _MAX_CLOCK_SKEW < timestamp:
|
| 147 |
+
raise InvalidToken
|
| 148 |
+
|
| 149 |
+
self._verify_signature(data)
|
| 150 |
+
|
| 151 |
+
iv = data[9:25]
|
| 152 |
+
ciphertext = data[25:-32]
|
| 153 |
+
decryptor = Cipher(
|
| 154 |
+
algorithms.AES(self._encryption_key), modes.CBC(iv)
|
| 155 |
+
).decryptor()
|
| 156 |
+
plaintext_padded = decryptor.update(ciphertext)
|
| 157 |
+
try:
|
| 158 |
+
plaintext_padded += decryptor.finalize()
|
| 159 |
+
except ValueError:
|
| 160 |
+
raise InvalidToken
|
| 161 |
+
unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
|
| 162 |
+
|
| 163 |
+
unpadded = unpadder.update(plaintext_padded)
|
| 164 |
+
try:
|
| 165 |
+
unpadded += unpadder.finalize()
|
| 166 |
+
except ValueError:
|
| 167 |
+
raise InvalidToken
|
| 168 |
+
return unpadded
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class MultiFernet:
|
| 172 |
+
def __init__(self, fernets: Iterable[Fernet]):
|
| 173 |
+
fernets = list(fernets)
|
| 174 |
+
if not fernets:
|
| 175 |
+
raise ValueError(
|
| 176 |
+
"MultiFernet requires at least one Fernet instance"
|
| 177 |
+
)
|
| 178 |
+
self._fernets = fernets
|
| 179 |
+
|
| 180 |
+
def encrypt(self, msg: bytes) -> bytes:
|
| 181 |
+
return self.encrypt_at_time(msg, int(time.time()))
|
| 182 |
+
|
| 183 |
+
def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes:
|
| 184 |
+
return self._fernets[0].encrypt_at_time(msg, current_time)
|
| 185 |
+
|
| 186 |
+
def rotate(self, msg: bytes | str) -> bytes:
|
| 187 |
+
timestamp, data = Fernet._get_unverified_token_data(msg)
|
| 188 |
+
for f in self._fernets:
|
| 189 |
+
try:
|
| 190 |
+
p = f._decrypt_data(data, timestamp, None)
|
| 191 |
+
break
|
| 192 |
+
except InvalidToken:
|
| 193 |
+
pass
|
| 194 |
+
else:
|
| 195 |
+
raise InvalidToken
|
| 196 |
+
|
| 197 |
+
iv = os.urandom(16)
|
| 198 |
+
return self._fernets[0]._encrypt_from_parts(p, timestamp, iv)
|
| 199 |
+
|
| 200 |
+
def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
|
| 201 |
+
for f in self._fernets:
|
| 202 |
+
try:
|
| 203 |
+
return f.decrypt(msg, ttl)
|
| 204 |
+
except InvalidToken:
|
| 205 |
+
pass
|
| 206 |
+
raise InvalidToken
|
| 207 |
+
|
| 208 |
+
def decrypt_at_time(
|
| 209 |
+
self, msg: bytes | str, ttl: int, current_time: int
|
| 210 |
+
) -> bytes:
|
| 211 |
+
for f in self._fernets:
|
| 212 |
+
try:
|
| 213 |
+
return f.decrypt_at_time(msg, ttl, current_time)
|
| 214 |
+
except InvalidToken:
|
| 215 |
+
pass
|
| 216 |
+
raise InvalidToken
|
| 217 |
+
|
| 218 |
+
def extract_timestamp(self, msg: bytes | str) -> int:
|
| 219 |
+
for f in self._fernets:
|
| 220 |
+
try:
|
| 221 |
+
return f.extract_timestamp(msg)
|
| 222 |
+
except InvalidToken:
|
| 223 |
+
pass
|
| 224 |
+
raise InvalidToken
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/py.typed
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/cryptography/utils.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file is dual licensed under the terms of the Apache License, Version
|
| 2 |
+
# 2.0, and the BSD License. See the LICENSE file in the root of this repository
|
| 3 |
+
# for complete details.
|
| 4 |
+
|
| 5 |
+
from __future__ import annotations
|
| 6 |
+
|
| 7 |
+
import enum
|
| 8 |
+
import sys
|
| 9 |
+
import types
|
| 10 |
+
import typing
|
| 11 |
+
import warnings
|
| 12 |
+
from collections.abc import Callable, Sequence
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# We use a UserWarning subclass, instead of DeprecationWarning, because CPython
|
| 16 |
+
# decided deprecation warnings should be invisible by default.
|
| 17 |
+
class CryptographyDeprecationWarning(UserWarning):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# Several APIs were deprecated with no specific end-of-life date because of the
|
| 22 |
+
# ubiquity of their use. They should not be removed until we agree on when that
|
| 23 |
+
# cycle ends.
|
| 24 |
+
DeprecatedIn36 = CryptographyDeprecationWarning
|
| 25 |
+
DeprecatedIn40 = CryptographyDeprecationWarning
|
| 26 |
+
DeprecatedIn41 = CryptographyDeprecationWarning
|
| 27 |
+
DeprecatedIn42 = CryptographyDeprecationWarning
|
| 28 |
+
DeprecatedIn43 = CryptographyDeprecationWarning
|
| 29 |
+
DeprecatedIn46 = CryptographyDeprecationWarning
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
# If you're wondering why we don't use `Buffer`, it's because `Buffer` would
|
| 33 |
+
# be more accurately named: Bufferable. It means something which has an
|
| 34 |
+
# `__buffer__`. Which means you can't actually treat the result as a buffer
|
| 35 |
+
# (and do things like take a `len()`).
|
| 36 |
+
if sys.version_info >= (3, 9):
|
| 37 |
+
Buffer = typing.Union[bytes, bytearray, memoryview]
|
| 38 |
+
else:
|
| 39 |
+
Buffer = typing.ByteString
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _check_bytes(name: str, value: bytes) -> None:
|
| 43 |
+
if not isinstance(value, bytes):
|
| 44 |
+
raise TypeError(f"{name} must be bytes")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _check_byteslike(name: str, value: Buffer) -> None:
|
| 48 |
+
try:
|
| 49 |
+
memoryview(value)
|
| 50 |
+
except TypeError:
|
| 51 |
+
raise TypeError(f"{name} must be bytes-like")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def int_to_bytes(integer: int, length: int | None = None) -> bytes:
|
| 55 |
+
if length == 0:
|
| 56 |
+
raise ValueError("length argument can't be 0")
|
| 57 |
+
return integer.to_bytes(
|
| 58 |
+
length or (integer.bit_length() + 7) // 8 or 1, "big"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class InterfaceNotImplemented(Exception):
|
| 63 |
+
pass
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class _DeprecatedValue:
|
| 67 |
+
def __init__(self, value: object, message: str, warning_class):
|
| 68 |
+
self.value = value
|
| 69 |
+
self.message = message
|
| 70 |
+
self.warning_class = warning_class
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class _ModuleWithDeprecations(types.ModuleType):
|
| 74 |
+
def __init__(self, module: types.ModuleType):
|
| 75 |
+
super().__init__(module.__name__)
|
| 76 |
+
self.__dict__["_module"] = module
|
| 77 |
+
|
| 78 |
+
def __getattr__(self, attr: str) -> object:
|
| 79 |
+
obj = getattr(self._module, attr)
|
| 80 |
+
if isinstance(obj, _DeprecatedValue):
|
| 81 |
+
warnings.warn(obj.message, obj.warning_class, stacklevel=2)
|
| 82 |
+
obj = obj.value
|
| 83 |
+
return obj
|
| 84 |
+
|
| 85 |
+
def __setattr__(self, attr: str, value: object) -> None:
|
| 86 |
+
setattr(self._module, attr, value)
|
| 87 |
+
|
| 88 |
+
def __delattr__(self, attr: str) -> None:
|
| 89 |
+
obj = getattr(self._module, attr)
|
| 90 |
+
if isinstance(obj, _DeprecatedValue):
|
| 91 |
+
warnings.warn(obj.message, obj.warning_class, stacklevel=2)
|
| 92 |
+
|
| 93 |
+
delattr(self._module, attr)
|
| 94 |
+
|
| 95 |
+
def __dir__(self) -> Sequence[str]:
|
| 96 |
+
return ["_module", *dir(self._module)]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def deprecated(
|
| 100 |
+
value: object,
|
| 101 |
+
module_name: str,
|
| 102 |
+
message: str,
|
| 103 |
+
warning_class: type[Warning],
|
| 104 |
+
name: str | None = None,
|
| 105 |
+
) -> _DeprecatedValue:
|
| 106 |
+
module = sys.modules[module_name]
|
| 107 |
+
if not isinstance(module, _ModuleWithDeprecations):
|
| 108 |
+
sys.modules[module_name] = module = _ModuleWithDeprecations(module)
|
| 109 |
+
dv = _DeprecatedValue(value, message, warning_class)
|
| 110 |
+
# Maintain backwards compatibility with `name is None` for pyOpenSSL.
|
| 111 |
+
if name is not None:
|
| 112 |
+
setattr(module, name, dv)
|
| 113 |
+
return dv
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def cached_property(func: Callable) -> property:
|
| 117 |
+
cached_name = f"_cached_{func}"
|
| 118 |
+
sentinel = object()
|
| 119 |
+
|
| 120 |
+
def inner(instance: object):
|
| 121 |
+
cache = getattr(instance, cached_name, sentinel)
|
| 122 |
+
if cache is not sentinel:
|
| 123 |
+
return cache
|
| 124 |
+
result = func(instance)
|
| 125 |
+
setattr(instance, cached_name, result)
|
| 126 |
+
return result
|
| 127 |
+
|
| 128 |
+
return property(inner)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# Python 3.10 changed representation of enums. We use well-defined object
|
| 132 |
+
# representation and string representation from Python 3.9.
|
| 133 |
+
class Enum(enum.Enum):
|
| 134 |
+
def __repr__(self) -> str:
|
| 135 |
+
return f"<{self.__class__.__name__}.{self._name_}: {self._value_!r}>"
|
| 136 |
+
|
| 137 |
+
def __str__(self) -> str:
|
| 138 |
+
return f"{self.__class__.__name__}.{self._name_}"
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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-Version: 2.4
|
| 2 |
+
Name: googleapis-common-protos
|
| 3 |
+
Version: 1.75.0
|
| 4 |
+
Summary: Common protobufs used in Google APIs
|
| 5 |
+
Author-email: Google LLC <googleapis-packages@google.com>
|
| 6 |
+
License: Apache 2.0
|
| 7 |
+
Project-URL: Repository, https://github.com/googleapis/google-cloud-python/tree/main/packages/googleapis-common-protos
|
| 8 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 9 |
+
Classifier: Intended Audience :: Developers
|
| 10 |
+
Classifier: License :: OSI Approved :: Apache Software License
|
| 11 |
+
Classifier: Programming Language :: Python
|
| 12 |
+
Classifier: Programming Language :: Python :: 3
|
| 13 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 14 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 15 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 16 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 17 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.14
|
| 19 |
+
Classifier: Operating System :: OS Independent
|
| 20 |
+
Classifier: Topic :: Internet
|
| 21 |
+
Requires-Python: >=3.9
|
| 22 |
+
Description-Content-Type: text/x-rst
|
| 23 |
+
License-File: LICENSE
|
| 24 |
+
Requires-Dist: protobuf<8.0.0,>=4.25.8
|
| 25 |
+
Provides-Extra: grpc
|
| 26 |
+
Requires-Dist: grpcio<2.0.0,>=1.44.0; extra == "grpc"
|
| 27 |
+
Dynamic: license-file
|
| 28 |
+
|
| 29 |
+
Python Client for Service Config
|
| 30 |
+
================================
|
| 31 |
+
|
| 32 |
+
|stable| |pypi| |versions|
|
| 33 |
+
|
| 34 |
+
- `Client Library Documentation`_
|
| 35 |
+
|
| 36 |
+
.. |stable| image:: https://img.shields.io/badge/support-stable-gold.svg
|
| 37 |
+
:target: https://github.com/googleapis/google-cloud-python/blob/main/README.rst#stability-levels
|
| 38 |
+
.. |pypi| image:: https://img.shields.io/pypi/v/googleapis-common-protos.svg
|
| 39 |
+
:target: https://pypi.org/project/googleapis-common-protos/
|
| 40 |
+
.. |versions| image:: https://img.shields.io/pypi/pyversions/googleapis-common-protos.svg
|
| 41 |
+
:target: https://pypi.org/project/googleapis-common-protos/
|
| 42 |
+
.. _Client Library Documentation: https://github.com/googleapis/google-cloud-python/tree/main/packages/googleapis-common-protos/summary_overview
|
| 43 |
+
|
| 44 |
+
Quick Start
|
| 45 |
+
-----------
|
| 46 |
+
|
| 47 |
+
In order to use this library, you first need to go through the following steps:
|
| 48 |
+
|
| 49 |
+
1. `Select or create a Cloud Platform project.`_
|
| 50 |
+
2. `Enable billing for your project.`_
|
| 51 |
+
3. `Set up Authentication.`_
|
| 52 |
+
|
| 53 |
+
.. _Select or create a Cloud Platform project.: https://console.cloud.google.com/project
|
| 54 |
+
.. _Enable billing for your project.: https://cloud.google.com/billing/docs/how-to/modify-project#enable_billing_for_a_project
|
| 55 |
+
.. _Set up Authentication.: https://googleapis.dev/python/google-api-core/latest/auth.html
|
| 56 |
+
|
| 57 |
+
Installation
|
| 58 |
+
~~~~~~~~~~~~
|
| 59 |
+
|
| 60 |
+
Install this library in a virtual environment using `venv`_. `venv`_ is a tool that
|
| 61 |
+
creates isolated Python environments. These isolated environments can have separate
|
| 62 |
+
versions of Python packages, which allows you to isolate one project's dependencies
|
| 63 |
+
from the dependencies of other projects.
|
| 64 |
+
|
| 65 |
+
With `venv`_, it's possible to install this library without needing system
|
| 66 |
+
install permissions, and without clashing with the installed system
|
| 67 |
+
dependencies.
|
| 68 |
+
|
| 69 |
+
.. _`venv`: https://docs.python.org/3/library/venv.html
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
Code samples and snippets
|
| 73 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 74 |
+
|
| 75 |
+
Code samples and snippets live in the `samples/`_ folder.
|
| 76 |
+
|
| 77 |
+
.. _samples/: https://github.com/googleapis/google-cloud-python/tree/main/packages/googleapis-common-protos/samples
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
Supported Python Versions
|
| 81 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 82 |
+
Our client libraries are compatible with all current `active`_ and `maintenance`_ versions of
|
| 83 |
+
Python.
|
| 84 |
+
|
| 85 |
+
Python >= 3.9, including 3.14
|
| 86 |
+
|
| 87 |
+
.. _active: https://devguide.python.org/devcycle/#in-development-main-branch
|
| 88 |
+
.. _maintenance: https://devguide.python.org/devcycle/#maintenance-branches
|
| 89 |
+
|
| 90 |
+
Unsupported Python Versions
|
| 91 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 92 |
+
Python <= 3.8
|
| 93 |
+
|
| 94 |
+
If you are using an `end-of-life`_
|
| 95 |
+
version of Python, we recommend that you update as soon as possible to an actively supported version.
|
| 96 |
+
|
| 97 |
+
.. _end-of-life: https://devguide.python.org/devcycle/#end-of-life-branches
|
| 98 |
+
|
| 99 |
+
Mac/Linux
|
| 100 |
+
^^^^^^^^^
|
| 101 |
+
|
| 102 |
+
.. code-block:: console
|
| 103 |
+
|
| 104 |
+
python3 -m venv <your-env>
|
| 105 |
+
source <your-env>/bin/activate
|
| 106 |
+
pip install googleapis-common-protos
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
Windows
|
| 110 |
+
^^^^^^^
|
| 111 |
+
|
| 112 |
+
.. code-block:: console
|
| 113 |
+
|
| 114 |
+
py -m venv <your-env>
|
| 115 |
+
.\<your-env>\Scripts\activate
|
| 116 |
+
pip install googleapis-common-protos
|
| 117 |
+
|
| 118 |
+
Next Steps
|
| 119 |
+
~~~~~~~~~~
|
| 120 |
+
|
| 121 |
+
- Read the `Client Library Documentation`_ for Service Config
|
| 122 |
+
to see other available methods on the client.
|
| 123 |
+
- View this `README`_ to see the full list of Cloud
|
| 124 |
+
APIs that we cover.
|
| 125 |
+
|
| 126 |
+
.. _README: https://github.com/googleapis/google-cloud-python/blob/main/README.rst
|
| 127 |
+
|
| 128 |
+
Logging
|
| 129 |
+
-------
|
| 130 |
+
|
| 131 |
+
This library uses the standard Python :code:`logging` functionality to log some RPC events that could be of interest for debugging and monitoring purposes.
|
| 132 |
+
Note the following:
|
| 133 |
+
|
| 134 |
+
#. Logs may contain sensitive information. Take care to **restrict access to the logs** if they are saved, whether it be on local storage or on Google Cloud Logging.
|
| 135 |
+
#. Google may refine the occurrence, level, and content of various log messages in this library without flagging such changes as breaking. **Do not depend on immutability of the logging events**.
|
| 136 |
+
#. By default, the logging events from this library are not handled. You must **explicitly configure log handling** using one of the mechanisms below.
|
| 137 |
+
|
| 138 |
+
Simple, environment-based configuration
|
| 139 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 140 |
+
|
| 141 |
+
To enable logging for this library without any changes in your code, set the :code:`GOOGLE_SDK_PYTHON_LOGGING_SCOPE` environment variable to a valid Google
|
| 142 |
+
logging scope. This configures handling of logging events (at level :code:`logging.DEBUG` or higher) from this library in a default manner, emitting the logged
|
| 143 |
+
messages in a structured format. It does not currently allow customizing the logging levels captured nor the handlers, formatters, etc. used for any logging
|
| 144 |
+
event.
|
| 145 |
+
|
| 146 |
+
A logging scope is a period-separated namespace that begins with :code:`google`, identifying the Python module or package to log.
|
| 147 |
+
|
| 148 |
+
- Valid logging scopes: :code:`google`, :code:`google.cloud.asset.v1`, :code:`google.api`, :code:`google.auth`, etc.
|
| 149 |
+
- Invalid logging scopes: :code:`foo`, :code:`123`, etc.
|
| 150 |
+
|
| 151 |
+
**NOTE**: If the logging scope is invalid, the library does not set up any logging handlers.
|
| 152 |
+
|
| 153 |
+
Environment-Based Examples
|
| 154 |
+
^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| 155 |
+
|
| 156 |
+
- Enabling the default handler for all Google-based loggers
|
| 157 |
+
|
| 158 |
+
.. code-block:: console
|
| 159 |
+
|
| 160 |
+
export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google
|
| 161 |
+
|
| 162 |
+
- Enabling the default handler for a specific Google module (for a client library called :code:`library_v1`):
|
| 163 |
+
|
| 164 |
+
.. code-block:: console
|
| 165 |
+
|
| 166 |
+
export GOOGLE_SDK_PYTHON_LOGGING_SCOPE=google.cloud.library_v1
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
Advanced, code-based configuration
|
| 170 |
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
| 171 |
+
|
| 172 |
+
You can also configure a valid logging scope using Python's standard `logging` mechanism.
|
| 173 |
+
|
| 174 |
+
Code-Based Examples
|
| 175 |
+
^^^^^^^^^^^^^^^^^^^
|
| 176 |
+
|
| 177 |
+
- Configuring a handler for all Google-based loggers
|
| 178 |
+
|
| 179 |
+
.. code-block:: python
|
| 180 |
+
|
| 181 |
+
import logging
|
| 182 |
+
|
| 183 |
+
from google.cloud import library_v1
|
| 184 |
+
|
| 185 |
+
base_logger = logging.getLogger("google")
|
| 186 |
+
base_logger.addHandler(logging.StreamHandler())
|
| 187 |
+
base_logger.setLevel(logging.DEBUG)
|
| 188 |
+
|
| 189 |
+
- Configuring a handler for a specific Google module (for a client library called :code:`library_v1`):
|
| 190 |
+
|
| 191 |
+
.. code-block:: python
|
| 192 |
+
|
| 193 |
+
import logging
|
| 194 |
+
|
| 195 |
+
from google.cloud import library_v1
|
| 196 |
+
|
| 197 |
+
base_logger = logging.getLogger("google.cloud.library_v1")
|
| 198 |
+
base_logger.addHandler(logging.StreamHandler())
|
| 199 |
+
base_logger.setLevel(logging.DEBUG)
|
| 200 |
+
|
| 201 |
+
Logging details
|
| 202 |
+
~~~~~~~~~~~~~~~
|
| 203 |
+
|
| 204 |
+
#. Regardless of which of the mechanisms above you use to configure logging for this library, by default logging events are not propagated up to the root
|
| 205 |
+
logger from the `google`-level logger. If you need the events to be propagated to the root logger, you must explicitly set
|
| 206 |
+
:code:`logging.getLogger("google").propagate = True` in your code.
|
| 207 |
+
#. You can mix the different logging configurations above for different Google modules. For example, you may want use a code-based logging configuration for
|
| 208 |
+
one library, but decide you need to also set up environment-based logging configuration for another library.
|
| 209 |
+
|
| 210 |
+
#. If you attempt to use both code-based and environment-based configuration for the same module, the environment-based configuration will be ineffectual
|
| 211 |
+
if the code -based configuration gets applied first.
|
| 212 |
+
|
| 213 |
+
#. The Google-specific logging configurations (default handlers for environment-based configuration; not propagating logging events to the root logger) get
|
| 214 |
+
executed the first time *any* client library is instantiated in your application, and only if the affected loggers have not been previously configured.
|
| 215 |
+
(This is the reason for 2.i. above.)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 4 |
+
google/api/__pycache__/billing_pb2.cpython-311.pyc,,
|
| 5 |
+
google/api/__pycache__/client_pb2.cpython-311.pyc,,
|
| 6 |
+
google/api/__pycache__/config_change_pb2.cpython-311.pyc,,
|
| 7 |
+
google/api/__pycache__/consumer_pb2.cpython-311.pyc,,
|
| 8 |
+
google/api/__pycache__/context_pb2.cpython-311.pyc,,
|
| 9 |
+
google/api/__pycache__/control_pb2.cpython-311.pyc,,
|
| 10 |
+
google/api/__pycache__/distribution_pb2.cpython-311.pyc,,
|
| 11 |
+
google/api/__pycache__/documentation_pb2.cpython-311.pyc,,
|
| 12 |
+
google/api/__pycache__/endpoint_pb2.cpython-311.pyc,,
|
| 13 |
+
google/api/__pycache__/error_reason_pb2.cpython-311.pyc,,
|
| 14 |
+
google/api/__pycache__/field_behavior_pb2.cpython-311.pyc,,
|
| 15 |
+
google/api/__pycache__/field_info_pb2.cpython-311.pyc,,
|
| 16 |
+
google/api/__pycache__/http_pb2.cpython-311.pyc,,
|
| 17 |
+
google/api/__pycache__/httpbody_pb2.cpython-311.pyc,,
|
| 18 |
+
google/api/__pycache__/label_pb2.cpython-311.pyc,,
|
| 19 |
+
google/api/__pycache__/launch_stage_pb2.cpython-311.pyc,,
|
| 20 |
+
google/api/__pycache__/log_pb2.cpython-311.pyc,,
|
| 21 |
+
google/api/__pycache__/logging_pb2.cpython-311.pyc,,
|
| 22 |
+
google/api/__pycache__/metric_pb2.cpython-311.pyc,,
|
| 23 |
+
google/api/__pycache__/monitored_resource_pb2.cpython-311.pyc,,
|
| 24 |
+
google/api/__pycache__/monitoring_pb2.cpython-311.pyc,,
|
| 25 |
+
google/api/__pycache__/policy_pb2.cpython-311.pyc,,
|
| 26 |
+
google/api/__pycache__/quota_pb2.cpython-311.pyc,,
|
| 27 |
+
google/api/__pycache__/resource_pb2.cpython-311.pyc,,
|
| 28 |
+
google/api/__pycache__/routing_pb2.cpython-311.pyc,,
|
| 29 |
+
google/api/__pycache__/service_pb2.cpython-311.pyc,,
|
| 30 |
+
google/api/__pycache__/source_info_pb2.cpython-311.pyc,,
|
| 31 |
+
google/api/__pycache__/system_parameter_pb2.cpython-311.pyc,,
|
| 32 |
+
google/api/__pycache__/usage_pb2.cpython-311.pyc,,
|
| 33 |
+
google/api/__pycache__/visibility_pb2.cpython-311.pyc,,
|
| 34 |
+
google/api/annotations.proto,sha256=556nQctgWmXnjKMiF0dkpK-f3hliwWMeErhMSTS6mmw,1045
|
| 35 |
+
google/api/annotations_pb2.py,sha256=ftDIJchQHj08Jh-RquF7tPNvPviWUBjJ_UR8qXl21kI,2183
|
| 36 |
+
google/api/annotations_pb2.pyi,sha256=yAsaRnQFljG5TZeFT1y3gcvYhelrdgf0CBVQ7FymxEg,887
|
| 37 |
+
google/api/auth.proto,sha256=ASZOTluO4gOI3DUAZnBMrTgWv1FDC1gPLM29urNqwzY,9262
|
| 38 |
+
google/api/auth_pb2.py,sha256=T38Ps0n-q17FnH9AUrBIz_PVq2HksEpaMZvtEqwJJDg,3602
|
| 39 |
+
google/api/auth_pb2.pyi,sha256=jvybOkHuFGQQufvANL2hqhmsAnKrQk5L8AFUkWO-fgQ,4324
|
| 40 |
+
google/api/backend.proto,sha256=jVY4DMkKfL6Hdm5TuyKLr5BTkFhCGnikh7getvvFpcw,7609
|
| 41 |
+
google/api/backend_pb2.py,sha256=KP0oZzkd5Yh-nWI719fxR8OxfEm-AdfGf2yJA5rOiWs,3826
|
| 42 |
+
google/api/backend_pb2.pyi,sha256=EjRBRdYLE0PoKHiyNyMoyBxFPCLSLxuEYbpsxf021aQ,4027
|
| 43 |
+
google/api/billing.proto,sha256=CeStm0L5GBYLyC8U3oCrk2AxWGACRuTNWqiMe_cVbyY,3062
|
| 44 |
+
google/api/billing_pb2.py,sha256=IXKyMW4TePtZgkfVyudp3HmaC9cuVackkAfhZEnfkJc,2315
|
| 45 |
+
google/api/billing_pb2.pyi,sha256=jZ_rAtvdJSst4OmP-_7hUKyBg2i0ZnufnuVZc2O1EQo,1871
|
| 46 |
+
google/api/client.proto,sha256=Xp_BFykP59NHJ5FUPJeb7Hz0SX8_5v-vnemumcxPGAQ,21460
|
| 47 |
+
google/api/client_pb2.py,sha256=4Lz0BBiIjUuss1NhkEvEBQtdcRe9llzAxumLGP8yIWw,12835
|
| 48 |
+
google/api/client_pb2.pyi,sha256=W5Y7E7oNTmOJjXmUkesw97Omsr9hFd7oujVuNI2zsNo,19753
|
| 49 |
+
google/api/config_change.proto,sha256=Vp4BOt2QggBfBspllzjPKcBrhqA9avts2VRJYDvFotU,3166
|
| 50 |
+
google/api/config_change_pb2.py,sha256=K3LteW8ju84EZrZi85zWvKUAuiU-7heuUlOgiwyTC-c,2694
|
| 51 |
+
google/api/config_change_pb2.pyi,sha256=ww6_F3S0QX06FRdhEJXEZ23vM_YNO5TGqCSP_jpzWIg,2384
|
| 52 |
+
google/api/consumer.proto,sha256=mZrLMRYo2cKUHQz9qr3xgEe-LuBh3aLZVD15qm3v7IQ,2717
|
| 53 |
+
google/api/consumer_pb2.py,sha256=KPshuZnxt3In3szFQDeOCPEjJBn9t3AAk1AblL5JxQ8,2575
|
| 54 |
+
google/api/consumer_pb2.pyi,sha256=yrxukHRfFHWffcA_fBW-8EkP3KxbAYUshl_QjXY2DlU,2349
|
| 55 |
+
google/api/context.proto,sha256=mmb7KqO6Rt834703e6i4QgJaRBivePOL65mK9ar5cYU,3229
|
| 56 |
+
google/api/context_pb2.py,sha256=kLrlSNkJaMuRPAC9OsfuSctP4MaCsjRPC77LRafdreg,2377
|
| 57 |
+
google/api/context_pb2.pyi,sha256=nsrPLW7YXomSXEQ7M0raTPX4xHXukgrjgZn8P9rUzzg,2339
|
| 58 |
+
google/api/control.proto,sha256=WB77VK6jSnzRLMBuDdLjFVpxNkUmns7yFWKXIzOJZf4,1438
|
| 59 |
+
google/api/control_pb2.py,sha256=IEJrMt_JB0qtsW_alxq7qYZTwAvjjB1LtMm4G9MILVg,2178
|
| 60 |
+
google/api/control_pb2.pyi,sha256=A_7VMDxGo-3rxWiCnF_ZxdnpBQqwoR06E80EQp5CMAQ,1546
|
| 61 |
+
google/api/distribution.proto,sha256=lL0aF9viC8-5rRThYGR7PrLgmpXtq6NDe4OxnRGPwoY,8660
|
| 62 |
+
google/api/distribution_pb2.py,sha256=qrwrLvSB_-C4APNdlxPk6x2-wKKCEoCqqeFYjrc2mCc,4485
|
| 63 |
+
google/api/distribution_pb2.pyi,sha256=731eKpsS9ApKO16aWZayhny9WrGPinFraKIpDXVxBn4,5768
|
| 64 |
+
google/api/documentation.proto,sha256=pjKEaypqBt5Ks4gNhC8xQqOFEFVToX_8n_43GLjFh0c,6925
|
| 65 |
+
google/api/documentation_pb2.py,sha256=15hZGj3DaTvy5OHnMSltlJbr-3zkC34IDfiaqoiqvc0,2844
|
| 66 |
+
google/api/documentation_pb2.pyi,sha256=SeGxZ44uoF0owOlV2x7902jwd_Qa_QoMebkntxme588,3062
|
| 67 |
+
google/api/endpoint.proto,sha256=pXxcRg9sjsPcoZXGvQSiS-pnrqN5rJWssAlz3maNw40,2891
|
| 68 |
+
google/api/endpoint_pb2.py,sha256=fuvSOmBXuyKCRhCYlREp5dDfsf3czi7FKtE_rIC1ZKM,2109
|
| 69 |
+
google/api/endpoint_pb2.pyi,sha256=O6_2RdBfzfiS1Hx0-_XCDmEPiI7XNZ2177Q11SbCnYA,1479
|
| 70 |
+
google/api/error_reason.proto,sha256=xp28eBE118qUSF7GdOgszpRYsBrnBpBqW3PrJ1y1Ew4,30153
|
| 71 |
+
google/api/error_reason_pb2.py,sha256=m6_PwUbGFFer-zDmkcxSVVVQ4fnk5-qiaiJ4LY5YISg,4000
|
| 72 |
+
google/api/error_reason_pb2.pyi,sha256=bY7ceN6hELYkOkaSvub28Iy0Zwq8eMF4jf77ZMESRF0,4813
|
| 73 |
+
google/api/field_behavior.proto,sha256=u37XdyXJX3UewsR82SNZ0BN8OTg7imKu9BureqdHjaU,4306
|
| 74 |
+
google/api/field_behavior_pb2.py,sha256=sNpZt35NZvShp4grKa-SLSfmFB72CK4bSM0zz7JUO5s,2681
|
| 75 |
+
google/api/field_behavior_pb2.pyi,sha256=HKVTIpHfvh2KJaaJnyqqzVBgmN_8oyputJVIcil5nSA,1680
|
| 76 |
+
google/api/field_info.proto,sha256=U7sKZzZCtO__LLSPbrnbsGk7GYrIN9poSuVPdR6M854,4456
|
| 77 |
+
google/api/field_info_pb2.py,sha256=G7KZqUiIPj7jWqO1ATnEZ5EvyHB-uSa06oGBLCQRL-A,2818
|
| 78 |
+
google/api/field_info_pb2.pyi,sha256=KXrS4aT8FDlrGAuqsbI18rHMTKeURN2p89Y6LmkAAj4,2368
|
| 79 |
+
google/api/http.proto,sha256=6tmRKaoV3V9iM5QgMMcu7DO8DXscfCYNwUMpPvZsW3g,15059
|
| 80 |
+
google/api/http_pb2.py,sha256=ept8doWslX_1NrjiffpqL3K7kL2F_Vb8GhDbyVaZ4iI,2870
|
| 81 |
+
google/api/http_pb2.pyi,sha256=ZatZQGFKlxDoLD56bgoFlzyxwKicySxa7gHqefPh6aA,3147
|
| 82 |
+
google/api/httpbody.proto,sha256=RUpRAjluAw7bDa5cCQVsiVMEGif2ZeSx48EigPbtJCE,2661
|
| 83 |
+
google/api/httpbody_pb2.py,sha256=JYkw3Nh37k-4FYiokP9XeyOfaullNwDHILXehtp3g0U,2191
|
| 84 |
+
google/api/httpbody_pb2.pyi,sha256=pu0vnjKqz3IYCvnBGtKAPmoBOWtHoFh3c5hTMTiyKbI,1569
|
| 85 |
+
google/api/label.proto,sha256=2t_ebV7M42t-MjLiQ5oNWsgzV1AHMqK3dg6JzGYRGAY,1357
|
| 86 |
+
google/api/label_pb2.py,sha256=joaFwkEe9R67fyL0_dM-CSEoRl3ZV0_Btn-Y5CX0EI0,2327
|
| 87 |
+
google/api/label_pb2.pyi,sha256=e9xbiTc7WWwXo9nudkr_YgpyiNuZeOCXTjWWhkWzReQ,1778
|
| 88 |
+
google/api/launch_stage.proto,sha256=aOIsmCEie06ExwKVafzhBVwh5syrmR4Jhrx18S703YI,3083
|
| 89 |
+
google/api/launch_stage_pb2.py,sha256=tczWsud1ySWYToKQXvM1WiW5IFFHp1PQEwbJ_p5O49M,2212
|
| 90 |
+
google/api/launch_stage_pb2.pyi,sha256=EtU16uO1pQYSj4cm1CJAzgA-NTBFLnd2q2YC1otGpfc,1381
|
| 91 |
+
google/api/log.proto,sha256=SYnp8Z9tunTeauKRWgRvu-yPeqYbVVUvRTF996yP7Cc,2043
|
| 92 |
+
google/api/log_pb2.py,sha256=yvoU1AEy-akyCZWDFjvSVeoZWMoc2Q1HWu2n2L1vqOU,2238
|
| 93 |
+
google/api/log_pb2.pyi,sha256=HxEOSCZAjaZCqs6I3Q4oX23qjH3INyZKEbdS1YanSAU,1728
|
| 94 |
+
google/api/logging.proto,sha256=gDlYNjtkEu12Xsrk4qqymGtBFjfFy0kVgZZXXmH561g,3174
|
| 95 |
+
google/api/logging_pb2.py,sha256=FZuSohoIkAOmZvvx4MXDsbvS7FlDAx92GfPsBuQy5aU,2396
|
| 96 |
+
google/api/logging_pb2.pyi,sha256=-Cg_5x5tPXB7O-wBf0RH_Xy6sseKBaUsqLcGFnYnhPw,2178
|
| 97 |
+
google/api/metric.proto,sha256=Ah8O9VDbI9mPi6-3SspBib7RZZEciJC_h2mtBSx61s0,11166
|
| 98 |
+
google/api/metric_pb2.py,sha256=qyXiu7am9d7R0Fpef3VYZkc2Pj7zfRBoomDIOv44RYk,5468
|
| 99 |
+
google/api/metric_pb2.pyi,sha256=MSZarEVxq2qnAjsawwI_Hpoh9ZR_-MEBUCocg7DMhjQ,7825
|
| 100 |
+
google/api/monitored_resource.proto,sha256=z31kMz9bYoetsOuL2-VSvDiBOoXOgTTDnL4cVr5-nNI,5888
|
| 101 |
+
google/api/monitored_resource_pb2.py,sha256=E9yM4N8C4css3Q1ihTymg7PcyDCffD3SeJdSVeJN7vA,4147
|
| 102 |
+
google/api/monitored_resource_pb2.pyi,sha256=wCBRjCKwNIOdYnKHaMhOQjoTi5l6sTeJTOipUMIoQ6U,3644
|
| 103 |
+
google/api/monitoring.proto,sha256=BlY9xUnnVtxVm6cxNsp8XpSuUvmoj0T9M9XZnoP8zs8,4457
|
| 104 |
+
google/api/monitoring_pb2.py,sha256=I65b90zZlGPOLAcc73Hc3xlvP_tWseWOlOSbVEyU2e4,2451
|
| 105 |
+
google/api/monitoring_pb2.pyi,sha256=voVGgqhqmKtIGjskaJnj5iuvwduVHcqWSquIbX0DE08,2220
|
| 106 |
+
google/api/policy.proto,sha256=aVzA-bYS5DyVha7GjHD-enQQJq3oKrKIzXv7OQXHloo,3110
|
| 107 |
+
google/api/policy_pb2.py,sha256=c01rgUhd9wKwu8KWFqJbeOa3QgPfPt_ghBPE5qid_ek,2686
|
| 108 |
+
google/api/policy_pb2.pyi,sha256=N9FSJUBlyqQrSVFubEtnJxxT2LMPeXp-jVJtVKPaO2M,2169
|
| 109 |
+
google/api/quota.proto,sha256=rV6KUwN_0YC_ZGiU9ONnBayYTyBNwtXZjY_pne23JdM,7180
|
| 110 |
+
google/api/quota_pb2.py,sha256=Bm-kKrUCjPK-2w6Idmum307cr-fTruTqTA_CctlvdyI,3613
|
| 111 |
+
google/api/quota_pb2.pyi,sha256=dcFO42Pazb7jKttUp3EnFPUDKic7Hkg4k93Qanw7Fp0,3876
|
| 112 |
+
google/api/resource.proto,sha256=gV1R6tpDQb8BZytHS17Aq76hkOjfn0qiagyW29rSmTs,8994
|
| 113 |
+
google/api/resource_pb2.py,sha256=7Ii8Wo9zyT6EbMw3oqYUl-iJqMvzrawDWHL4FHKbBHk,3535
|
| 114 |
+
google/api/resource_pb2.pyi,sha256=a1Ovn3QT3oqBPaE7A_f6u_aJ0QMaxo8W_K4yYUeboNQ,3588
|
| 115 |
+
google/api/routing.proto,sha256=8xy0PD7-B6gM2BTu3lh_Gji02siAUwadz-qshnAFEb4,15193
|
| 116 |
+
google/api/routing_pb2.py,sha256=ZKjkgtGMn5bURZHEABNCScT89VnpleA_DI2kBHJOYtk,2489
|
| 117 |
+
google/api/routing_pb2.pyi,sha256=z7nFx78IfmaruAPgltVWo21QSa6g75rAVoAA4T89mIE,1821
|
| 118 |
+
google/api/service.proto,sha256=kcRxkGafszlDfwn5EdLqQwfG6Z9dZqtQTEjRo9InTaM,6698
|
| 119 |
+
google/api/service_pb2.py,sha256=Gluq1Te2mq7tpDnJmThRTDAIexJSecKcBEzBWQDtI5E,5858
|
| 120 |
+
google/api/service_pb2.pyi,sha256=Ipz86MPZ3FXYyNqDq2X6P5GeJf5ePF7c2HnOX9kZo_E,7164
|
| 121 |
+
google/api/source_info.proto,sha256=hpjvyJjXFLIG7cyK8Ly8-A1Tjn3QBf4gbSuSLDFLq2M,1091
|
| 122 |
+
google/api/source_info_pb2.py,sha256=q1RNK5AbU6RSSZYAp5qxIrp9AXEAMN2TubJ5Ic9uFGM,2155
|
| 123 |
+
google/api/source_info_pb2.pyi,sha256=65e7q_WYVA6Db1a1srDBkMTxErD6gp_Vq-oOIfGoJzc,1343
|
| 124 |
+
google/api/system_parameter.proto,sha256=tFFRmHZ3rCeJkSvIu7JwcJtPZKhTODxloTMBPgl095M,3475
|
| 125 |
+
google/api/system_parameter_pb2.py,sha256=wjrmlXW3GZmoUyPi_WUPxT1Y-llBszGby10MuBrLNyI,2611
|
| 126 |
+
google/api/system_parameter_pb2.pyi,sha256=_kZoYlhbvOzWBha-Xok9Yb4kQu-BOSXF7G5GW8tW-PY,2217
|
| 127 |
+
google/api/usage.proto,sha256=JsOCA34-fGyuum0YMpttfd83wWMuxbzVfFhU1b4Ae60,3198
|
| 128 |
+
google/api/usage_pb2.py,sha256=yRT5UuPJtfWdSC_2OoR19S0dsTRs0mLDhkJde748RyU,2354
|
| 129 |
+
google/api/usage_pb2.pyi,sha256=pe0wm3i9Zyg0E1Xr9h_MhRXVS8gtkfjW4KTG_UH5iik,2175
|
| 130 |
+
google/api/visibility.proto,sha256=gPC1xRdPDHM4Dg6R6GXhQhM5MMXzWzwHwqUuxmEKGBA,3767
|
| 131 |
+
google/api/visibility_pb2.py,sha256=6TOOsD0dBuuH8VsHt22lk5I1VX4gBr5C-lQSZNpjCHQ,3114
|
| 132 |
+
google/api/visibility_pb2.pyi,sha256=A_h87gi4Z60MvmeZfO7KWO3e7ijb2D5iRigIWIncMHI,2213
|
| 133 |
+
google/cloud/__pycache__/common_resources_pb2.cpython-311.pyc,,
|
| 134 |
+
google/cloud/__pycache__/extended_operations_pb2.cpython-311.pyc,,
|
| 135 |
+
google/cloud/common_resources.proto,sha256=rTSsmDKoThiospOtRHLZX27W7cBPCEJS5rpVK1bP9Y0,1578
|
| 136 |
+
google/cloud/common_resources_pb2.py,sha256=VZB8FjsN0p-B-zZY4Dpr-PeRjGJL8Pw-7phLDO4VuCo,2594
|
| 137 |
+
google/cloud/common_resources_pb2.pyi,sha256=auOAyE8-AWvsY9qu5xhX0TcaGWfP9vPOUcvEWkkngBc,765
|
| 138 |
+
google/cloud/extended_operations.proto,sha256=gI4lL58QZw4JOL01_j5Rirk5A00f6MG0P0m5eX9ytSM,6307
|
| 139 |
+
google/cloud/extended_operations_pb2.py,sha256=yQ4PP6xqIfg9hP7IA9GPuihVdUPLUFY1iIJhvUwj2Rc,2816
|
| 140 |
+
google/cloud/extended_operations_pb2.pyi,sha256=7OLGIjrs7vyd0YZRbbF1bml4JF9hSdolMCEnR3XSE90,1889
|
| 141 |
+
google/cloud/location/__pycache__/locations_pb2.cpython-311.pyc,,
|
| 142 |
+
google/cloud/location/locations.proto,sha256=QPoDwHP-htlXfOl9mtm2XzWOmXMHzbxX1fYIvfAeAs4,3604
|
| 143 |
+
google/cloud/location/locations_pb2.py,sha256=LVOFFuPb_iGB4Pq1vmkwKTXfuXiJtL14VLofIQrIs5g,5077
|
| 144 |
+
google/cloud/location/locations_pb2.pyi,sha256=h1M_ojWa47nyQQC7c2QDmNcxwYDPBlp146sS2HLohdU,3392
|
| 145 |
+
google/gapic/metadata/__pycache__/gapic_metadata_pb2.cpython-311.pyc,,
|
| 146 |
+
google/gapic/metadata/gapic_metadata.proto,sha256=_VxjjqKXoL4XYFOBBQCwIbIQ724gD6SOR-AJBTwPk4Y,3805
|
| 147 |
+
google/gapic/metadata/gapic_metadata_pb2.py,sha256=5tWBkOIiFLPrUyAvIyoRfmhZ3bpC-rVRdk-97sCl_0M,4836
|
| 148 |
+
google/gapic/metadata/gapic_metadata_pb2.pyi,sha256=XpWHLh90cI0tcohiaKj1gAh-FwfnYHhFPNghwuGAsTU,4501
|
| 149 |
+
google/logging/type/__pycache__/http_request_pb2.cpython-311.pyc,,
|
| 150 |
+
google/logging/type/__pycache__/log_severity_pb2.cpython-311.pyc,,
|
| 151 |
+
google/logging/type/http_request.proto,sha256=zxYFInPIcyFDrWQYwN4FmqSaOy9AL2Lmp8Y0kUNsxGU,3601
|
| 152 |
+
google/logging/type/http_request_pb2.py,sha256=2msckjGr_DP79cGeFqNUbAXcUUUzIQigDaUWT_FzFK4,3023
|
| 153 |
+
google/logging/type/http_request_pb2.pyi,sha256=Ar76mTRYKUJwcp22VO6BqwRBQ_AtejqK6kP2dpMwdVg,3102
|
| 154 |
+
google/logging/type/log_severity.proto,sha256=zqnBXSkSV3PGG0sBjdvJs9fwiKL3N9anTjjxtgfdpR4,2555
|
| 155 |
+
google/logging/type/log_severity_pb2.py,sha256=MYW_HWzMFEuoJ_bD0DUC0Hu9S5zhIZjEm40tXQ-XWoQ,2568
|
| 156 |
+
google/logging/type/log_severity_pb2.pyi,sha256=47i081SvX-t7hqlZzmzy8NZj7OK3myeoNeupVCHWi_0,1378
|
| 157 |
+
google/longrunning/__pycache__/operations_grpc.cpython-311.pyc,,
|
| 158 |
+
google/longrunning/__pycache__/operations_grpc_pb2.cpython-311.pyc,,
|
| 159 |
+
google/longrunning/__pycache__/operations_pb2.cpython-311.pyc,,
|
| 160 |
+
google/longrunning/__pycache__/operations_pb2_grpc.cpython-311.pyc,,
|
| 161 |
+
google/longrunning/__pycache__/operations_proto.cpython-311.pyc,,
|
| 162 |
+
google/longrunning/__pycache__/operations_proto_pb2.cpython-311.pyc,,
|
| 163 |
+
google/longrunning/operations_grpc.py,sha256=ZtTe_7HJsDWG4OZol8Qi0qoV7HkK4BAxt8Vh0Vh_-xs,818
|
| 164 |
+
google/longrunning/operations_grpc_pb2.py,sha256=iglg37RTLIXqkyQofLiC4yJrzywRhXlPE0apvd0jTKM,531
|
| 165 |
+
google/longrunning/operations_pb2.py,sha256=IREpzTVW90oSeGiWq0sRogtXgiBzEL8kMuwL8XC0Cqc,1569
|
| 166 |
+
google/longrunning/operations_pb2_grpc.py,sha256=DFQ7x25xPEr9VFT9zSVcZ2gqPsvG-5xhQGfLm4mRu3s,14464
|
| 167 |
+
google/longrunning/operations_proto.proto,sha256=_PVg87i50b3agoAwJqyMqmFrDuGdD1VOjrnvey8gH8I,10041
|
| 168 |
+
google/longrunning/operations_proto.py,sha256=vIe7RoVZfjsS7MSZB487GGMIB_5_7--sT_cyt8coGCk,243
|
| 169 |
+
google/longrunning/operations_proto_pb2.py,sha256=8WTwiP_Ml96srgHb3kRb8GiqhdBa23diTCx79Yl49jg,7232
|
| 170 |
+
google/longrunning/operations_proto_pb2.pyi,sha256=5_V9vvbdpSXXdEyn1ZoBNpPjWa0bFX3CV6wtGeVD3u8,4490
|
| 171 |
+
google/rpc/__pycache__/code_pb2.cpython-311.pyc,,
|
| 172 |
+
google/rpc/__pycache__/error_details_pb2.cpython-311.pyc,,
|
| 173 |
+
google/rpc/__pycache__/http_pb2.cpython-311.pyc,,
|
| 174 |
+
google/rpc/__pycache__/status_pb2.cpython-311.pyc,,
|
| 175 |
+
google/rpc/code.proto,sha256=g6Yxhbg89zMhlvxerQ7JG5OsIH--kbPVvD1y9GGwuzE,7138
|
| 176 |
+
google/rpc/code_pb2.py,sha256=Ml0fMQsB0rRiIc-IaZr9mL-dsshI2FAh-q8y8zDVOZU,2480
|
| 177 |
+
google/rpc/code_pb2.pyi,sha256=S0tVsFZr7_QXpLUhRkRCqDj3EoaNAO0Rn5FV7SXIaqs,1771
|
| 178 |
+
google/rpc/context/__pycache__/attribute_context_pb2.cpython-311.pyc,,
|
| 179 |
+
google/rpc/context/__pycache__/audit_context_pb2.cpython-311.pyc,,
|
| 180 |
+
google/rpc/context/attribute_context.proto,sha256=iqPw_p9Icr4KMqGtT2IDsYpnt6S7afwApGUlULRVqT4,15115
|
| 181 |
+
google/rpc/context/attribute_context_pb2.py,sha256=5GWLlWiU_8Ih8VjC4I0OvALBUnbFrspdolSK2lPmkY8,8486
|
| 182 |
+
google/rpc/context/attribute_context_pb2.pyi,sha256=o83zMSgOtfU0bGhGxoYdBbycIA-lMMVYFpyPHxAdRIk,11595
|
| 183 |
+
google/rpc/context/audit_context.proto,sha256=zRpTxlPL1iautgoibxmRO8l1J3FT4bXbrlo7pDvaBF4,1829
|
| 184 |
+
google/rpc/context/audit_context_pb2.py,sha256=YN20-Ylpwif0pkiZ6qbSkWrJCBsRb8qOLpkWRrHsd20,2417
|
| 185 |
+
google/rpc/context/audit_context_pb2.pyi,sha256=G3mCF1BRTuDkWmskAJlS2mtNWvkwgCbkI5MAlF4winA,1922
|
| 186 |
+
google/rpc/error_details.proto,sha256=XBjULmkk9EdiJTS0t824tTwGBsjOcpuRLuXt-I0cVSA,14599
|
| 187 |
+
google/rpc/error_details_pb2.py,sha256=VOCmCBVtWGJQBlIOVJmoIg9hr-24NInTSJ6STc2sOos,6458
|
| 188 |
+
google/rpc/error_details_pb2.pyi,sha256=-EfcgKWO3z5CPvno0avW4vbZI543aklSNcmC3taRCVo,8436
|
| 189 |
+
google/rpc/http.proto,sha256=-SSZX6rlLrksCdfqJdmyF_6aZilUwGOY511ctOWsA4Y,1940
|
| 190 |
+
google/rpc/http_pb2.py,sha256=vdwAfgWQO8tRKRZ0LmtNNzF9PAKl1BvPBnl8ivtd1hE,2569
|
| 191 |
+
google/rpc/http_pb2.pyi,sha256=XakmiDuqsd36SU1F1F-83EPLYVrjTdBeYX0-iNXhfdc,2467
|
| 192 |
+
google/rpc/status.proto,sha256=9b_SYuZwXHrnPzLgrY7iDOjAoleN-MT3br92tXLyle0,1902
|
| 193 |
+
google/rpc/status_pb2.py,sha256=THsaoBimY8TJojCNdUAITWgZkn9TRSESrmkAs0hj1kc,2163
|
| 194 |
+
google/rpc/status_pb2.pyi,sha256=t6HXKXT0R6KoNoDacgCv1JNZqT6U2XCvr4J3QejgZsU,1531
|
| 195 |
+
google/type/__pycache__/calendar_period_pb2.cpython-311.pyc,,
|
| 196 |
+
google/type/__pycache__/color_pb2.cpython-311.pyc,,
|
| 197 |
+
google/type/__pycache__/date_pb2.cpython-311.pyc,,
|
| 198 |
+
google/type/__pycache__/datetime_pb2.cpython-311.pyc,,
|
| 199 |
+
google/type/__pycache__/dayofweek_pb2.cpython-311.pyc,,
|
| 200 |
+
google/type/__pycache__/decimal_pb2.cpython-311.pyc,,
|
| 201 |
+
google/type/__pycache__/expr_pb2.cpython-311.pyc,,
|
| 202 |
+
google/type/__pycache__/fraction_pb2.cpython-311.pyc,,
|
| 203 |
+
google/type/__pycache__/interval_pb2.cpython-311.pyc,,
|
| 204 |
+
google/type/__pycache__/latlng_pb2.cpython-311.pyc,,
|
| 205 |
+
google/type/__pycache__/localized_text_pb2.cpython-311.pyc,,
|
| 206 |
+
google/type/__pycache__/money_pb2.cpython-311.pyc,,
|
| 207 |
+
google/type/__pycache__/month_pb2.cpython-311.pyc,,
|
| 208 |
+
google/type/__pycache__/phone_number_pb2.cpython-311.pyc,,
|
| 209 |
+
google/type/__pycache__/postal_address_pb2.cpython-311.pyc,,
|
| 210 |
+
google/type/__pycache__/quaternion_pb2.cpython-311.pyc,,
|
| 211 |
+
google/type/__pycache__/timeofday_pb2.cpython-311.pyc,,
|
| 212 |
+
google/type/calendar_period.proto,sha256=9yF5iMSypeW2F5wgg_UhvZxnCedksCG-qLeFRRa47sM,1762
|
| 213 |
+
google/type/calendar_period_pb2.py,sha256=XOyXbtenesUOlDEnJm3gZBoCXgwVEpWK6oVmExyteJE,2286
|
| 214 |
+
google/type/calendar_period_pb2.pyi,sha256=sVo812wLSg28VeC_oZHNSNbvxWgbbw-FWyWDA1IK_xg,1400
|
| 215 |
+
google/type/color.proto,sha256=VudYYPezFTiqaZcdWXAe8EJiTX8aW5x44B5k3VJJ1oE,6355
|
| 216 |
+
google/type/color_pb2.py,sha256=cqxyFJGOmF3I9m5voOmYS0GpsqBr8FSQufryjXUZGLk,2210
|
| 217 |
+
google/type/color_pb2.pyi,sha256=40iw29SFgBeB0OlAnvTkr9c_2ODa73BAiokAmzpGZOo,1492
|
| 218 |
+
google/type/date.proto,sha256=llrtlNwElkcRdr1gf33JQThU8HyBJTkz2gdd7iZpqdo,2010
|
| 219 |
+
google/type/date_pb2.py,sha256=MKIMd153XIvEG3yGQ5iSkOI4L1MVEpayKgn66TijoUo,2013
|
| 220 |
+
google/type/date_pb2.pyi,sha256=bhco_u3qTskpSxPthxrNYoafvupno3P7D0PDOfiw8KU,1187
|
| 221 |
+
google/type/datetime.proto,sha256=jT6duaGNV58LGFd0RsbrifYnL_jSl-nhZCyDVFNLZJ8,4051
|
| 222 |
+
google/type/datetime_pb2.py,sha256=TW3u8EBqTpK4UPmS_vAaf-tn2TI3L_CZ8hxp12OVLPU,2689
|
| 223 |
+
google/type/datetime_pb2.pyi,sha256=lpcUmSY0MQjnrj8f3wrjBdvrVNUXoAy6nilNaas6Msk,2420
|
| 224 |
+
google/type/dayofweek.proto,sha256=ymgfkFAq2BggcQXwflDA9eJnbArwqH_u-gcbKZxDIFs,1204
|
| 225 |
+
google/type/dayofweek_pb2.py,sha256=f9FxF0aUyTOUNoU2pLSK0n7q7CNkFtmJHeRdRhjXPzA,2225
|
| 226 |
+
google/type/dayofweek_pb2.pyi,sha256=RbF1ibri8xloSPPHR25zNuzBTzpwbzn6u_FGsT_P4iE,1335
|
| 227 |
+
google/type/decimal.proto,sha256=B7G4uISyUOxdeiR7A2EFQmXvm0toahP8vW6TZ54tdmA,4225
|
| 228 |
+
google/type/decimal_pb2.py,sha256=_5XGyWkq9iG8nqRZjAnmxOh45AQR-dkIKlGC0yIsDvY,1986
|
| 229 |
+
google/type/decimal_pb2.pyi,sha256=ETMNgbDSMkwbwVzF1dy1iYv5F1vfSZVrZTacBiqw4MQ,980
|
| 230 |
+
google/type/expr.proto,sha256=0dPcT7ZAFuoY0h1S7Zf_Z-ZVbWm__JT_SwL22A-9CmM,2730
|
| 231 |
+
google/type/expr_pb2.py,sha256=bsjT5uZsgPXvZXwL8v9qtIA1Efqom7zpl39sTYQ3tjo,2052
|
| 232 |
+
google/type/expr_pb2.pyi,sha256=8pRxBNy6-l60abONgar3wsRFxhNO17AXXXbZkv1-aHc,1355
|
| 233 |
+
google/type/fraction.proto,sha256=kmiYI3Uq-eiUFnd1fcroK8q8K02nArLn16IDNU8Ojp4,1156
|
| 234 |
+
google/type/fraction_pb2.py,sha256=ipZOlS6ImN931TCYJuUH3oOWh4ctr9Zueyd2c7VttSw,2043
|
| 235 |
+
google/type/fraction_pb2.pyi,sha256=xxowlWmKi9jiqpTxJPJVuUW4-OqpmT_7Jp-D1liGaSY,1126
|
| 236 |
+
google/type/interval.proto,sha256=Ka64BsFKpTgvG8vZW9cyNd6h7K42DVdXulyeG_FuZmo,1635
|
| 237 |
+
google/type/interval_pb2.py,sha256=S-n2knvS6f11-0b3VZ6TqqrHWenkIZQ6aoRL-Gcxbs0,2216
|
| 238 |
+
google/type/interval_pb2.pyi,sha256=madlH1_IMGBMoFfLY5RWpIyFVVzKuofwxngaHcEzOf4,1389
|
| 239 |
+
google/type/latlng.proto,sha256=OWZlYbbCy0XUiKVq2Qm47JtaCGzPYuKMZiBZFw89HL0,1433
|
| 240 |
+
google/type/latlng_pb2.py,sha256=6VA7OraCRufnwOXAWJCoFbTy9YJw5OS8qGU2hAv9TIM,2002
|
| 241 |
+
google/type/latlng_pb2.pyi,sha256=H1_dd3GUfw-M3Cro2VoyUQTN44XDXKTWaYrp_Kt_nek,1120
|
| 242 |
+
google/type/localized_text.proto,sha256=QiVYjqGjTBNBZjb__yoIyEmy-rS4LLwt4QXUJKvxcQY,1317
|
| 243 |
+
google/type/localized_text_pb2.py,sha256=5MUXOU8IRnbsksVcshuOon7hLMYQ1vpjMykH8sxu1AE,2088
|
| 244 |
+
google/type/localized_text_pb2.pyi,sha256=lHUdsojwSWDYMNBDzSy4_9OKyflCBdA91wZ0TAR5d-A,1119
|
| 245 |
+
google/type/money.proto,sha256=ShOe9R4kNSVmisHd0FkSJUUtiWM--w7UJjfoe3wY80k,1571
|
| 246 |
+
google/type/money_pb2.py,sha256=W_d-ZElqX0hI8BZLVY7ivHfTItjF3mIy6QG7QEiikzI,2019
|
| 247 |
+
google/type/money_pb2.pyi,sha256=dTUleurCYBGl3UsFgEL-AIGerrPd6-HUAX02kLmXZ4Y,1232
|
| 248 |
+
google/type/month.proto,sha256=fbmvxTp3igZAnEqGxF0ec_8YkxtkNE6OcGNjBYvEmXQ,1479
|
| 249 |
+
google/type/month_pb2.py,sha256=8PgUJGd159TLBpU5iqcLOSQQylNKWxnWwSVmgmwuOi4,2305
|
| 250 |
+
google/type/month_pb2.pyi,sha256=CP_EBA3rCkhfHRqOQDQMKl8sv3gvQjpW69kQ7T5Mdss,1458
|
| 251 |
+
google/type/phone_number.proto,sha256=wVm4OCBqdU11zLn2h84CE1G1bb3-722o_sXHyKINSG0,4784
|
| 252 |
+
google/type/phone_number_pb2.py,sha256=_P8mMd7IvPKZIBilyZaQQuyStUPT2N7WSa6LtYQX2T4,2417
|
| 253 |
+
google/type/phone_number_pb2.pyi,sha256=WvSMlpfqLgGCKjsgmeSAY3QpOm6b011ZIoWNzWUh4cM,1745
|
| 254 |
+
google/type/postal_address.proto,sha256=ZCChFjQ75f3xr8Vx7Z0qfzlycj1m4NJjOKDKsDqAA_o,6322
|
| 255 |
+
google/type/postal_address_pb2.py,sha256=cdiZ7Ya1ZjqUkEWeOrvssSGbQ8Fl-XtItdWUtYx1bpE,2472
|
| 256 |
+
google/type/postal_address_pb2.pyi,sha256=STB5j1C7kWT4arbDBmhG2gEA0fdOKcRol-QAd3JMv6U,2605
|
| 257 |
+
google/type/quaternion.proto,sha256=4zvM4Lkl5UcCREiip9gyFn9rKMaschknkdsjY7Q4o3U,3826
|
| 258 |
+
google/type/quaternion_pb2.py,sha256=F8fZrRgteK1P8-fl6PDKS5uRFBrVfYUYdWqkgrb_2KE,2100
|
| 259 |
+
google/type/quaternion_pb2.pyi,sha256=78kj_z0GXrulbyoCcbon2tzlWsYHwwoTPVnWOWl1aOk,1257
|
| 260 |
+
google/type/timeofday.proto,sha256=leDlsFSJ88fhexFf-Nuf5ba59RYugzgeNNggjPZZco4,1840
|
| 261 |
+
google/type/timeofday_pb2.py,sha256=z3upmrX1MYdlj7zqOV_jKvOVE-3LQHHqcqaHw-HqXxM,2112
|
| 262 |
+
google/type/timeofday_pb2.pyi,sha256=B9mzMCS_LEgqUGrvb_0fNDY0AnKcduAuN5mJe7xjn1s,1320
|
| 263 |
+
googleapis_common_protos-1.75.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 264 |
+
googleapis_common_protos-1.75.0.dist-info/METADATA,sha256=sTe2otO4piAEGuYPAOdWQi5qegrJsNMMOmNn5lH4j38,8559
|
| 265 |
+
googleapis_common_protos-1.75.0.dist-info/RECORD,,
|
| 266 |
+
googleapis_common_protos-1.75.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 267 |
+
googleapis_common_protos-1.75.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
| 268 |
+
googleapis_common_protos-1.75.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
| 269 |
+
googleapis_common_protos-1.75.0.dist-info/top_level.txt,sha256=_1QvSJIhFAGfxb79D6DhB7SUw2X6T4rwnz_LLrbcD3c,7
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/REQUESTED
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (82.0.1)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/googleapis_common_protos-1.75.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
google
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/__init__.py
ADDED
|
@@ -0,0 +1,1690 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# ***********
|
| 16 |
+
# `huggingface_hub` init has 2 modes:
|
| 17 |
+
# - Normal usage:
|
| 18 |
+
# If imported to use it, all modules and functions are lazy-loaded. This means
|
| 19 |
+
# they exist at top level in module but are imported only the first time they are
|
| 20 |
+
# used. This way, `from huggingface_hub import something` will import `something`
|
| 21 |
+
# quickly without the hassle of importing all the features from `huggingface_hub`.
|
| 22 |
+
# - Static check:
|
| 23 |
+
# If statically analyzed, all modules and functions are loaded normally. This way
|
| 24 |
+
# static typing check works properly as well as autocomplete in text editors and
|
| 25 |
+
# IDEs.
|
| 26 |
+
#
|
| 27 |
+
# The static model imports are done inside the `if TYPE_CHECKING:` statement at
|
| 28 |
+
# the bottom of this file. Since module/functions imports are duplicated, it is
|
| 29 |
+
# mandatory to make sure to add them twice when adding one. This is checked in the
|
| 30 |
+
# `make quality` command.
|
| 31 |
+
#
|
| 32 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 33 |
+
# ```
|
| 34 |
+
# # Use script
|
| 35 |
+
# python utils/check_static_imports.py --update-file
|
| 36 |
+
#
|
| 37 |
+
# # Or run style on codebase
|
| 38 |
+
# make style
|
| 39 |
+
# ```
|
| 40 |
+
#
|
| 41 |
+
# ***********
|
| 42 |
+
# Lazy loader vendored from https://github.com/scientific-python/lazy_loader
|
| 43 |
+
import importlib
|
| 44 |
+
import os
|
| 45 |
+
import sys
|
| 46 |
+
from typing import TYPE_CHECKING
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
__version__ = "1.7.1"
|
| 50 |
+
|
| 51 |
+
# Alphabetical order of definitions is ensured in tests
|
| 52 |
+
# WARNING: any comment added in this dictionary definition will be lost when
|
| 53 |
+
# re-generating the file !
|
| 54 |
+
_SUBMOD_ATTRS = {
|
| 55 |
+
"_buckets": [
|
| 56 |
+
"BucketFile",
|
| 57 |
+
"BucketFileMetadata",
|
| 58 |
+
"BucketFolder",
|
| 59 |
+
"BucketInfo",
|
| 60 |
+
"BucketUrl",
|
| 61 |
+
"SyncOperation",
|
| 62 |
+
"SyncPlan",
|
| 63 |
+
],
|
| 64 |
+
"_commit_scheduler": [
|
| 65 |
+
"CommitScheduler",
|
| 66 |
+
],
|
| 67 |
+
"_eval_results": [
|
| 68 |
+
"EvalResultEntry",
|
| 69 |
+
"eval_result_entries_to_yaml",
|
| 70 |
+
"parse_eval_result_entries",
|
| 71 |
+
],
|
| 72 |
+
"_inference_endpoints": [
|
| 73 |
+
"InferenceEndpoint",
|
| 74 |
+
"InferenceEndpointError",
|
| 75 |
+
"InferenceEndpointStatus",
|
| 76 |
+
"InferenceEndpointTimeoutError",
|
| 77 |
+
"InferenceEndpointType",
|
| 78 |
+
],
|
| 79 |
+
"_jobs_api": [
|
| 80 |
+
"JobAccelerator",
|
| 81 |
+
"JobHardware",
|
| 82 |
+
"JobInfo",
|
| 83 |
+
"JobOwner",
|
| 84 |
+
"JobStage",
|
| 85 |
+
"JobStatus",
|
| 86 |
+
],
|
| 87 |
+
"_login": [
|
| 88 |
+
"auth_list",
|
| 89 |
+
"auth_switch",
|
| 90 |
+
"interpreter_login",
|
| 91 |
+
"login",
|
| 92 |
+
"logout",
|
| 93 |
+
"notebook_login",
|
| 94 |
+
],
|
| 95 |
+
"_oauth": [
|
| 96 |
+
"OAuthInfo",
|
| 97 |
+
"OAuthOrgInfo",
|
| 98 |
+
"OAuthUserInfo",
|
| 99 |
+
"attach_huggingface_oauth",
|
| 100 |
+
"parse_huggingface_oauth",
|
| 101 |
+
],
|
| 102 |
+
"_snapshot_download": [
|
| 103 |
+
"snapshot_download",
|
| 104 |
+
],
|
| 105 |
+
"_space_api": [
|
| 106 |
+
"SpaceHardware",
|
| 107 |
+
"SpaceRuntime",
|
| 108 |
+
"SpaceStage",
|
| 109 |
+
"SpaceStorage",
|
| 110 |
+
"SpaceVariable",
|
| 111 |
+
],
|
| 112 |
+
"_tensorboard_logger": [
|
| 113 |
+
"HFSummaryWriter",
|
| 114 |
+
],
|
| 115 |
+
"_webhooks_payload": [
|
| 116 |
+
"WebhookPayload",
|
| 117 |
+
"WebhookPayloadComment",
|
| 118 |
+
"WebhookPayloadDiscussion",
|
| 119 |
+
"WebhookPayloadDiscussionChanges",
|
| 120 |
+
"WebhookPayloadEvent",
|
| 121 |
+
"WebhookPayloadMovedTo",
|
| 122 |
+
"WebhookPayloadRepo",
|
| 123 |
+
"WebhookPayloadUrl",
|
| 124 |
+
"WebhookPayloadWebhook",
|
| 125 |
+
],
|
| 126 |
+
"_webhooks_server": [
|
| 127 |
+
"WebhooksServer",
|
| 128 |
+
"webhook_endpoint",
|
| 129 |
+
],
|
| 130 |
+
"cli._cli_utils": [
|
| 131 |
+
"check_cli_update",
|
| 132 |
+
"typer_factory",
|
| 133 |
+
],
|
| 134 |
+
"community": [
|
| 135 |
+
"Discussion",
|
| 136 |
+
"DiscussionComment",
|
| 137 |
+
"DiscussionCommit",
|
| 138 |
+
"DiscussionEvent",
|
| 139 |
+
"DiscussionStatusChange",
|
| 140 |
+
"DiscussionTitleChange",
|
| 141 |
+
"DiscussionWithDetails",
|
| 142 |
+
],
|
| 143 |
+
"constants": [
|
| 144 |
+
"CONFIG_NAME",
|
| 145 |
+
"FLAX_WEIGHTS_NAME",
|
| 146 |
+
"HUGGINGFACE_CO_URL_HOME",
|
| 147 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
| 148 |
+
"PYTORCH_WEIGHTS_NAME",
|
| 149 |
+
"REPO_TYPE_DATASET",
|
| 150 |
+
"REPO_TYPE_MODEL",
|
| 151 |
+
"REPO_TYPE_SPACE",
|
| 152 |
+
"TF2_WEIGHTS_NAME",
|
| 153 |
+
"TF_WEIGHTS_NAME",
|
| 154 |
+
"is_offline_mode",
|
| 155 |
+
],
|
| 156 |
+
"fastai_utils": [
|
| 157 |
+
"_save_pretrained_fastai",
|
| 158 |
+
"from_pretrained_fastai",
|
| 159 |
+
"push_to_hub_fastai",
|
| 160 |
+
],
|
| 161 |
+
"file_download": [
|
| 162 |
+
"DryRunFileInfo",
|
| 163 |
+
"HfFileMetadata",
|
| 164 |
+
"_CACHED_NO_EXIST",
|
| 165 |
+
"get_hf_file_metadata",
|
| 166 |
+
"hf_hub_download",
|
| 167 |
+
"hf_hub_url",
|
| 168 |
+
"try_to_load_from_cache",
|
| 169 |
+
],
|
| 170 |
+
"hf_api": [
|
| 171 |
+
"Collection",
|
| 172 |
+
"CollectionItem",
|
| 173 |
+
"CommitInfo",
|
| 174 |
+
"CommitOperation",
|
| 175 |
+
"CommitOperationAdd",
|
| 176 |
+
"CommitOperationCopy",
|
| 177 |
+
"CommitOperationDelete",
|
| 178 |
+
"DatasetInfo",
|
| 179 |
+
"GitCommitInfo",
|
| 180 |
+
"GitRefInfo",
|
| 181 |
+
"GitRefs",
|
| 182 |
+
"HfApi",
|
| 183 |
+
"ModelInfo",
|
| 184 |
+
"Organization",
|
| 185 |
+
"RepoFile",
|
| 186 |
+
"RepoFolder",
|
| 187 |
+
"RepoUrl",
|
| 188 |
+
"SpaceInfo",
|
| 189 |
+
"User",
|
| 190 |
+
"UserLikes",
|
| 191 |
+
"WebhookInfo",
|
| 192 |
+
"WebhookWatchedItem",
|
| 193 |
+
"accept_access_request",
|
| 194 |
+
"add_collection_item",
|
| 195 |
+
"add_space_secret",
|
| 196 |
+
"add_space_variable",
|
| 197 |
+
"auth_check",
|
| 198 |
+
"batch_bucket_files",
|
| 199 |
+
"bucket_info",
|
| 200 |
+
"cancel_access_request",
|
| 201 |
+
"cancel_job",
|
| 202 |
+
"change_discussion_status",
|
| 203 |
+
"comment_discussion",
|
| 204 |
+
"create_branch",
|
| 205 |
+
"create_bucket",
|
| 206 |
+
"create_collection",
|
| 207 |
+
"create_commit",
|
| 208 |
+
"create_discussion",
|
| 209 |
+
"create_inference_endpoint",
|
| 210 |
+
"create_inference_endpoint_from_catalog",
|
| 211 |
+
"create_pull_request",
|
| 212 |
+
"create_repo",
|
| 213 |
+
"create_scheduled_job",
|
| 214 |
+
"create_scheduled_uv_job",
|
| 215 |
+
"create_tag",
|
| 216 |
+
"create_webhook",
|
| 217 |
+
"dataset_info",
|
| 218 |
+
"delete_branch",
|
| 219 |
+
"delete_bucket",
|
| 220 |
+
"delete_collection",
|
| 221 |
+
"delete_collection_item",
|
| 222 |
+
"delete_file",
|
| 223 |
+
"delete_folder",
|
| 224 |
+
"delete_inference_endpoint",
|
| 225 |
+
"delete_repo",
|
| 226 |
+
"delete_scheduled_job",
|
| 227 |
+
"delete_space_secret",
|
| 228 |
+
"delete_space_storage",
|
| 229 |
+
"delete_space_variable",
|
| 230 |
+
"delete_tag",
|
| 231 |
+
"delete_webhook",
|
| 232 |
+
"disable_space_dev_mode",
|
| 233 |
+
"disable_webhook",
|
| 234 |
+
"download_bucket_files",
|
| 235 |
+
"duplicate_repo",
|
| 236 |
+
"duplicate_space",
|
| 237 |
+
"edit_discussion_comment",
|
| 238 |
+
"enable_space_dev_mode",
|
| 239 |
+
"enable_webhook",
|
| 240 |
+
"fetch_job_logs",
|
| 241 |
+
"fetch_job_metrics",
|
| 242 |
+
"file_exists",
|
| 243 |
+
"get_bucket_file_metadata",
|
| 244 |
+
"get_bucket_paths_info",
|
| 245 |
+
"get_collection",
|
| 246 |
+
"get_dataset_tags",
|
| 247 |
+
"get_discussion_details",
|
| 248 |
+
"get_full_repo_name",
|
| 249 |
+
"get_inference_endpoint",
|
| 250 |
+
"get_local_safetensors_metadata",
|
| 251 |
+
"get_model_tags",
|
| 252 |
+
"get_organization_overview",
|
| 253 |
+
"get_paths_info",
|
| 254 |
+
"get_repo_discussions",
|
| 255 |
+
"get_safetensors_metadata",
|
| 256 |
+
"get_space_runtime",
|
| 257 |
+
"get_space_variables",
|
| 258 |
+
"get_user_overview",
|
| 259 |
+
"get_webhook",
|
| 260 |
+
"grant_access",
|
| 261 |
+
"inspect_job",
|
| 262 |
+
"inspect_scheduled_job",
|
| 263 |
+
"list_accepted_access_requests",
|
| 264 |
+
"list_bucket_tree",
|
| 265 |
+
"list_buckets",
|
| 266 |
+
"list_collections",
|
| 267 |
+
"list_daily_papers",
|
| 268 |
+
"list_dataset_parquet_files",
|
| 269 |
+
"list_datasets",
|
| 270 |
+
"list_inference_catalog",
|
| 271 |
+
"list_inference_endpoints",
|
| 272 |
+
"list_jobs",
|
| 273 |
+
"list_jobs_hardware",
|
| 274 |
+
"list_lfs_files",
|
| 275 |
+
"list_liked_repos",
|
| 276 |
+
"list_models",
|
| 277 |
+
"list_organization_followers",
|
| 278 |
+
"list_organization_members",
|
| 279 |
+
"list_papers",
|
| 280 |
+
"list_pending_access_requests",
|
| 281 |
+
"list_rejected_access_requests",
|
| 282 |
+
"list_repo_commits",
|
| 283 |
+
"list_repo_files",
|
| 284 |
+
"list_repo_likers",
|
| 285 |
+
"list_repo_refs",
|
| 286 |
+
"list_repo_tree",
|
| 287 |
+
"list_spaces",
|
| 288 |
+
"list_user_followers",
|
| 289 |
+
"list_user_following",
|
| 290 |
+
"list_webhooks",
|
| 291 |
+
"merge_pull_request",
|
| 292 |
+
"model_info",
|
| 293 |
+
"move_bucket",
|
| 294 |
+
"move_repo",
|
| 295 |
+
"paper_info",
|
| 296 |
+
"parse_local_safetensors_file_metadata",
|
| 297 |
+
"parse_safetensors_file_metadata",
|
| 298 |
+
"pause_inference_endpoint",
|
| 299 |
+
"pause_space",
|
| 300 |
+
"permanently_delete_lfs_files",
|
| 301 |
+
"preupload_lfs_files",
|
| 302 |
+
"reject_access_request",
|
| 303 |
+
"rename_discussion",
|
| 304 |
+
"repo_exists",
|
| 305 |
+
"repo_info",
|
| 306 |
+
"repo_type_and_id_from_hf_id",
|
| 307 |
+
"request_space_hardware",
|
| 308 |
+
"request_space_storage",
|
| 309 |
+
"restart_space",
|
| 310 |
+
"resume_inference_endpoint",
|
| 311 |
+
"resume_scheduled_job",
|
| 312 |
+
"revision_exists",
|
| 313 |
+
"run_as_future",
|
| 314 |
+
"run_job",
|
| 315 |
+
"run_uv_job",
|
| 316 |
+
"scale_to_zero_inference_endpoint",
|
| 317 |
+
"set_space_sleep_time",
|
| 318 |
+
"space_info",
|
| 319 |
+
"super_squash_history",
|
| 320 |
+
"suspend_scheduled_job",
|
| 321 |
+
"sync_bucket",
|
| 322 |
+
"unlike",
|
| 323 |
+
"update_collection_item",
|
| 324 |
+
"update_collection_metadata",
|
| 325 |
+
"update_inference_endpoint",
|
| 326 |
+
"update_repo_settings",
|
| 327 |
+
"update_webhook",
|
| 328 |
+
"upload_file",
|
| 329 |
+
"upload_folder",
|
| 330 |
+
"upload_large_folder",
|
| 331 |
+
"verify_repo_checksums",
|
| 332 |
+
"whoami",
|
| 333 |
+
],
|
| 334 |
+
"hf_file_system": [
|
| 335 |
+
"HfFileSystem",
|
| 336 |
+
"HfFileSystemFile",
|
| 337 |
+
"HfFileSystemResolvedPath",
|
| 338 |
+
"HfFileSystemStreamFile",
|
| 339 |
+
"hffs",
|
| 340 |
+
],
|
| 341 |
+
"hub_mixin": [
|
| 342 |
+
"ModelHubMixin",
|
| 343 |
+
"PyTorchModelHubMixin",
|
| 344 |
+
],
|
| 345 |
+
"inference._client": [
|
| 346 |
+
"InferenceClient",
|
| 347 |
+
"InferenceTimeoutError",
|
| 348 |
+
],
|
| 349 |
+
"inference._generated._async_client": [
|
| 350 |
+
"AsyncInferenceClient",
|
| 351 |
+
],
|
| 352 |
+
"inference._generated.types": [
|
| 353 |
+
"AudioClassificationInput",
|
| 354 |
+
"AudioClassificationOutputElement",
|
| 355 |
+
"AudioClassificationOutputTransform",
|
| 356 |
+
"AudioClassificationParameters",
|
| 357 |
+
"AudioToAudioInput",
|
| 358 |
+
"AudioToAudioOutputElement",
|
| 359 |
+
"AutomaticSpeechRecognitionEarlyStoppingEnum",
|
| 360 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
| 361 |
+
"AutomaticSpeechRecognitionInput",
|
| 362 |
+
"AutomaticSpeechRecognitionOutput",
|
| 363 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
| 364 |
+
"AutomaticSpeechRecognitionParameters",
|
| 365 |
+
"ChatCompletionInput",
|
| 366 |
+
"ChatCompletionInputFunctionDefinition",
|
| 367 |
+
"ChatCompletionInputFunctionName",
|
| 368 |
+
"ChatCompletionInputGrammarType",
|
| 369 |
+
"ChatCompletionInputJSONSchema",
|
| 370 |
+
"ChatCompletionInputMessage",
|
| 371 |
+
"ChatCompletionInputMessageChunk",
|
| 372 |
+
"ChatCompletionInputMessageChunkType",
|
| 373 |
+
"ChatCompletionInputResponseFormatJSONObject",
|
| 374 |
+
"ChatCompletionInputResponseFormatJSONSchema",
|
| 375 |
+
"ChatCompletionInputResponseFormatText",
|
| 376 |
+
"ChatCompletionInputStreamOptions",
|
| 377 |
+
"ChatCompletionInputTool",
|
| 378 |
+
"ChatCompletionInputToolCall",
|
| 379 |
+
"ChatCompletionInputToolChoiceClass",
|
| 380 |
+
"ChatCompletionInputToolChoiceEnum",
|
| 381 |
+
"ChatCompletionInputURL",
|
| 382 |
+
"ChatCompletionOutput",
|
| 383 |
+
"ChatCompletionOutputComplete",
|
| 384 |
+
"ChatCompletionOutputFunctionDefinition",
|
| 385 |
+
"ChatCompletionOutputLogprob",
|
| 386 |
+
"ChatCompletionOutputLogprobs",
|
| 387 |
+
"ChatCompletionOutputMessage",
|
| 388 |
+
"ChatCompletionOutputToolCall",
|
| 389 |
+
"ChatCompletionOutputTopLogprob",
|
| 390 |
+
"ChatCompletionOutputUsage",
|
| 391 |
+
"ChatCompletionStreamOutput",
|
| 392 |
+
"ChatCompletionStreamOutputChoice",
|
| 393 |
+
"ChatCompletionStreamOutputDelta",
|
| 394 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
| 395 |
+
"ChatCompletionStreamOutputFunction",
|
| 396 |
+
"ChatCompletionStreamOutputLogprob",
|
| 397 |
+
"ChatCompletionStreamOutputLogprobs",
|
| 398 |
+
"ChatCompletionStreamOutputTopLogprob",
|
| 399 |
+
"ChatCompletionStreamOutputUsage",
|
| 400 |
+
"DepthEstimationInput",
|
| 401 |
+
"DepthEstimationOutput",
|
| 402 |
+
"DocumentQuestionAnsweringInput",
|
| 403 |
+
"DocumentQuestionAnsweringInputData",
|
| 404 |
+
"DocumentQuestionAnsweringOutputElement",
|
| 405 |
+
"DocumentQuestionAnsweringParameters",
|
| 406 |
+
"FeatureExtractionInput",
|
| 407 |
+
"FeatureExtractionInputTruncationDirection",
|
| 408 |
+
"FillMaskInput",
|
| 409 |
+
"FillMaskOutputElement",
|
| 410 |
+
"FillMaskParameters",
|
| 411 |
+
"ImageClassificationInput",
|
| 412 |
+
"ImageClassificationOutputElement",
|
| 413 |
+
"ImageClassificationOutputTransform",
|
| 414 |
+
"ImageClassificationParameters",
|
| 415 |
+
"ImageSegmentationInput",
|
| 416 |
+
"ImageSegmentationOutputElement",
|
| 417 |
+
"ImageSegmentationParameters",
|
| 418 |
+
"ImageSegmentationSubtask",
|
| 419 |
+
"ImageTextToImageInput",
|
| 420 |
+
"ImageTextToImageOutput",
|
| 421 |
+
"ImageTextToImageParameters",
|
| 422 |
+
"ImageTextToImageTargetSize",
|
| 423 |
+
"ImageTextToVideoInput",
|
| 424 |
+
"ImageTextToVideoOutput",
|
| 425 |
+
"ImageTextToVideoParameters",
|
| 426 |
+
"ImageTextToVideoTargetSize",
|
| 427 |
+
"ImageToImageInput",
|
| 428 |
+
"ImageToImageOutput",
|
| 429 |
+
"ImageToImageParameters",
|
| 430 |
+
"ImageToImageTargetSize",
|
| 431 |
+
"ImageToTextEarlyStoppingEnum",
|
| 432 |
+
"ImageToTextGenerationParameters",
|
| 433 |
+
"ImageToTextInput",
|
| 434 |
+
"ImageToTextOutput",
|
| 435 |
+
"ImageToTextParameters",
|
| 436 |
+
"ImageToVideoInput",
|
| 437 |
+
"ImageToVideoOutput",
|
| 438 |
+
"ImageToVideoParameters",
|
| 439 |
+
"ImageToVideoTargetSize",
|
| 440 |
+
"ObjectDetectionBoundingBox",
|
| 441 |
+
"ObjectDetectionInput",
|
| 442 |
+
"ObjectDetectionOutputElement",
|
| 443 |
+
"ObjectDetectionParameters",
|
| 444 |
+
"Padding",
|
| 445 |
+
"QuestionAnsweringInput",
|
| 446 |
+
"QuestionAnsweringInputData",
|
| 447 |
+
"QuestionAnsweringOutputElement",
|
| 448 |
+
"QuestionAnsweringParameters",
|
| 449 |
+
"SentenceSimilarityInput",
|
| 450 |
+
"SentenceSimilarityInputData",
|
| 451 |
+
"SummarizationInput",
|
| 452 |
+
"SummarizationOutput",
|
| 453 |
+
"SummarizationParameters",
|
| 454 |
+
"SummarizationTruncationStrategy",
|
| 455 |
+
"TableQuestionAnsweringInput",
|
| 456 |
+
"TableQuestionAnsweringInputData",
|
| 457 |
+
"TableQuestionAnsweringOutputElement",
|
| 458 |
+
"TableQuestionAnsweringParameters",
|
| 459 |
+
"Text2TextGenerationInput",
|
| 460 |
+
"Text2TextGenerationOutput",
|
| 461 |
+
"Text2TextGenerationParameters",
|
| 462 |
+
"Text2TextGenerationTruncationStrategy",
|
| 463 |
+
"TextClassificationInput",
|
| 464 |
+
"TextClassificationOutputElement",
|
| 465 |
+
"TextClassificationOutputTransform",
|
| 466 |
+
"TextClassificationParameters",
|
| 467 |
+
"TextGenerationInput",
|
| 468 |
+
"TextGenerationInputGenerateParameters",
|
| 469 |
+
"TextGenerationInputGrammarType",
|
| 470 |
+
"TextGenerationOutput",
|
| 471 |
+
"TextGenerationOutputBestOfSequence",
|
| 472 |
+
"TextGenerationOutputDetails",
|
| 473 |
+
"TextGenerationOutputFinishReason",
|
| 474 |
+
"TextGenerationOutputPrefillToken",
|
| 475 |
+
"TextGenerationOutputToken",
|
| 476 |
+
"TextGenerationStreamOutput",
|
| 477 |
+
"TextGenerationStreamOutputStreamDetails",
|
| 478 |
+
"TextGenerationStreamOutputToken",
|
| 479 |
+
"TextToAudioEarlyStoppingEnum",
|
| 480 |
+
"TextToAudioGenerationParameters",
|
| 481 |
+
"TextToAudioInput",
|
| 482 |
+
"TextToAudioOutput",
|
| 483 |
+
"TextToAudioParameters",
|
| 484 |
+
"TextToImageInput",
|
| 485 |
+
"TextToImageOutput",
|
| 486 |
+
"TextToImageParameters",
|
| 487 |
+
"TextToSpeechEarlyStoppingEnum",
|
| 488 |
+
"TextToSpeechGenerationParameters",
|
| 489 |
+
"TextToSpeechInput",
|
| 490 |
+
"TextToSpeechOutput",
|
| 491 |
+
"TextToSpeechParameters",
|
| 492 |
+
"TextToVideoInput",
|
| 493 |
+
"TextToVideoOutput",
|
| 494 |
+
"TextToVideoParameters",
|
| 495 |
+
"TokenClassificationAggregationStrategy",
|
| 496 |
+
"TokenClassificationInput",
|
| 497 |
+
"TokenClassificationOutputElement",
|
| 498 |
+
"TokenClassificationParameters",
|
| 499 |
+
"TranslationInput",
|
| 500 |
+
"TranslationOutput",
|
| 501 |
+
"TranslationParameters",
|
| 502 |
+
"TranslationTruncationStrategy",
|
| 503 |
+
"TypeEnum",
|
| 504 |
+
"VideoClassificationInput",
|
| 505 |
+
"VideoClassificationOutputElement",
|
| 506 |
+
"VideoClassificationOutputTransform",
|
| 507 |
+
"VideoClassificationParameters",
|
| 508 |
+
"VisualQuestionAnsweringInput",
|
| 509 |
+
"VisualQuestionAnsweringInputData",
|
| 510 |
+
"VisualQuestionAnsweringOutputElement",
|
| 511 |
+
"VisualQuestionAnsweringParameters",
|
| 512 |
+
"ZeroShotClassificationInput",
|
| 513 |
+
"ZeroShotClassificationOutputElement",
|
| 514 |
+
"ZeroShotClassificationParameters",
|
| 515 |
+
"ZeroShotImageClassificationInput",
|
| 516 |
+
"ZeroShotImageClassificationOutputElement",
|
| 517 |
+
"ZeroShotImageClassificationParameters",
|
| 518 |
+
"ZeroShotObjectDetectionBoundingBox",
|
| 519 |
+
"ZeroShotObjectDetectionInput",
|
| 520 |
+
"ZeroShotObjectDetectionOutputElement",
|
| 521 |
+
"ZeroShotObjectDetectionParameters",
|
| 522 |
+
],
|
| 523 |
+
"inference._mcp.agent": [
|
| 524 |
+
"Agent",
|
| 525 |
+
],
|
| 526 |
+
"inference._mcp.mcp_client": [
|
| 527 |
+
"MCPClient",
|
| 528 |
+
],
|
| 529 |
+
"repocard": [
|
| 530 |
+
"DatasetCard",
|
| 531 |
+
"ModelCard",
|
| 532 |
+
"RepoCard",
|
| 533 |
+
"SpaceCard",
|
| 534 |
+
"metadata_eval_result",
|
| 535 |
+
"metadata_load",
|
| 536 |
+
"metadata_save",
|
| 537 |
+
"metadata_update",
|
| 538 |
+
],
|
| 539 |
+
"repocard_data": [
|
| 540 |
+
"CardData",
|
| 541 |
+
"DatasetCardData",
|
| 542 |
+
"EvalResult",
|
| 543 |
+
"ModelCardData",
|
| 544 |
+
"SpaceCardData",
|
| 545 |
+
],
|
| 546 |
+
"serialization": [
|
| 547 |
+
"StateDictSplit",
|
| 548 |
+
"get_torch_storage_id",
|
| 549 |
+
"get_torch_storage_size",
|
| 550 |
+
"load_state_dict_from_file",
|
| 551 |
+
"load_torch_model",
|
| 552 |
+
"save_torch_model",
|
| 553 |
+
"save_torch_state_dict",
|
| 554 |
+
"split_state_dict_into_shards_factory",
|
| 555 |
+
"split_torch_state_dict_into_shards",
|
| 556 |
+
],
|
| 557 |
+
"serialization._dduf": [
|
| 558 |
+
"DDUFEntry",
|
| 559 |
+
"export_entries_as_dduf",
|
| 560 |
+
"export_folder_as_dduf",
|
| 561 |
+
"read_dduf_file",
|
| 562 |
+
],
|
| 563 |
+
"utils": [
|
| 564 |
+
"ASYNC_CLIENT_FACTORY_T",
|
| 565 |
+
"CLIENT_FACTORY_T",
|
| 566 |
+
"CacheNotFound",
|
| 567 |
+
"CachedFileInfo",
|
| 568 |
+
"CachedRepoInfo",
|
| 569 |
+
"CachedRevisionInfo",
|
| 570 |
+
"CorruptedCacheException",
|
| 571 |
+
"DeleteCacheStrategy",
|
| 572 |
+
"HFCacheInfo",
|
| 573 |
+
"cached_assets_path",
|
| 574 |
+
"close_session",
|
| 575 |
+
"dump_environment_info",
|
| 576 |
+
"get_async_session",
|
| 577 |
+
"get_session",
|
| 578 |
+
"get_token",
|
| 579 |
+
"hf_raise_for_status",
|
| 580 |
+
"logging",
|
| 581 |
+
"scan_cache_dir",
|
| 582 |
+
"set_async_client_factory",
|
| 583 |
+
"set_client_factory",
|
| 584 |
+
],
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
# WARNING: __all__ is generated automatically, Any manual edit will be lost when re-generating this file !
|
| 588 |
+
#
|
| 589 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 590 |
+
# ```
|
| 591 |
+
# # Use script
|
| 592 |
+
# python utils/check_all_variable.py --update
|
| 593 |
+
#
|
| 594 |
+
# # Or run style on codebase
|
| 595 |
+
# make style
|
| 596 |
+
# ```
|
| 597 |
+
|
| 598 |
+
__all__ = [
|
| 599 |
+
"ASYNC_CLIENT_FACTORY_T",
|
| 600 |
+
"Agent",
|
| 601 |
+
"AsyncInferenceClient",
|
| 602 |
+
"AudioClassificationInput",
|
| 603 |
+
"AudioClassificationOutputElement",
|
| 604 |
+
"AudioClassificationOutputTransform",
|
| 605 |
+
"AudioClassificationParameters",
|
| 606 |
+
"AudioToAudioInput",
|
| 607 |
+
"AudioToAudioOutputElement",
|
| 608 |
+
"AutomaticSpeechRecognitionEarlyStoppingEnum",
|
| 609 |
+
"AutomaticSpeechRecognitionGenerationParameters",
|
| 610 |
+
"AutomaticSpeechRecognitionInput",
|
| 611 |
+
"AutomaticSpeechRecognitionOutput",
|
| 612 |
+
"AutomaticSpeechRecognitionOutputChunk",
|
| 613 |
+
"AutomaticSpeechRecognitionParameters",
|
| 614 |
+
"BucketFile",
|
| 615 |
+
"BucketFileMetadata",
|
| 616 |
+
"BucketFolder",
|
| 617 |
+
"BucketInfo",
|
| 618 |
+
"BucketUrl",
|
| 619 |
+
"CLIENT_FACTORY_T",
|
| 620 |
+
"CONFIG_NAME",
|
| 621 |
+
"CacheNotFound",
|
| 622 |
+
"CachedFileInfo",
|
| 623 |
+
"CachedRepoInfo",
|
| 624 |
+
"CachedRevisionInfo",
|
| 625 |
+
"CardData",
|
| 626 |
+
"ChatCompletionInput",
|
| 627 |
+
"ChatCompletionInputFunctionDefinition",
|
| 628 |
+
"ChatCompletionInputFunctionName",
|
| 629 |
+
"ChatCompletionInputGrammarType",
|
| 630 |
+
"ChatCompletionInputJSONSchema",
|
| 631 |
+
"ChatCompletionInputMessage",
|
| 632 |
+
"ChatCompletionInputMessageChunk",
|
| 633 |
+
"ChatCompletionInputMessageChunkType",
|
| 634 |
+
"ChatCompletionInputResponseFormatJSONObject",
|
| 635 |
+
"ChatCompletionInputResponseFormatJSONSchema",
|
| 636 |
+
"ChatCompletionInputResponseFormatText",
|
| 637 |
+
"ChatCompletionInputStreamOptions",
|
| 638 |
+
"ChatCompletionInputTool",
|
| 639 |
+
"ChatCompletionInputToolCall",
|
| 640 |
+
"ChatCompletionInputToolChoiceClass",
|
| 641 |
+
"ChatCompletionInputToolChoiceEnum",
|
| 642 |
+
"ChatCompletionInputURL",
|
| 643 |
+
"ChatCompletionOutput",
|
| 644 |
+
"ChatCompletionOutputComplete",
|
| 645 |
+
"ChatCompletionOutputFunctionDefinition",
|
| 646 |
+
"ChatCompletionOutputLogprob",
|
| 647 |
+
"ChatCompletionOutputLogprobs",
|
| 648 |
+
"ChatCompletionOutputMessage",
|
| 649 |
+
"ChatCompletionOutputToolCall",
|
| 650 |
+
"ChatCompletionOutputTopLogprob",
|
| 651 |
+
"ChatCompletionOutputUsage",
|
| 652 |
+
"ChatCompletionStreamOutput",
|
| 653 |
+
"ChatCompletionStreamOutputChoice",
|
| 654 |
+
"ChatCompletionStreamOutputDelta",
|
| 655 |
+
"ChatCompletionStreamOutputDeltaToolCall",
|
| 656 |
+
"ChatCompletionStreamOutputFunction",
|
| 657 |
+
"ChatCompletionStreamOutputLogprob",
|
| 658 |
+
"ChatCompletionStreamOutputLogprobs",
|
| 659 |
+
"ChatCompletionStreamOutputTopLogprob",
|
| 660 |
+
"ChatCompletionStreamOutputUsage",
|
| 661 |
+
"Collection",
|
| 662 |
+
"CollectionItem",
|
| 663 |
+
"CommitInfo",
|
| 664 |
+
"CommitOperation",
|
| 665 |
+
"CommitOperationAdd",
|
| 666 |
+
"CommitOperationCopy",
|
| 667 |
+
"CommitOperationDelete",
|
| 668 |
+
"CommitScheduler",
|
| 669 |
+
"CorruptedCacheException",
|
| 670 |
+
"DDUFEntry",
|
| 671 |
+
"DatasetCard",
|
| 672 |
+
"DatasetCardData",
|
| 673 |
+
"DatasetInfo",
|
| 674 |
+
"DeleteCacheStrategy",
|
| 675 |
+
"DepthEstimationInput",
|
| 676 |
+
"DepthEstimationOutput",
|
| 677 |
+
"Discussion",
|
| 678 |
+
"DiscussionComment",
|
| 679 |
+
"DiscussionCommit",
|
| 680 |
+
"DiscussionEvent",
|
| 681 |
+
"DiscussionStatusChange",
|
| 682 |
+
"DiscussionTitleChange",
|
| 683 |
+
"DiscussionWithDetails",
|
| 684 |
+
"DocumentQuestionAnsweringInput",
|
| 685 |
+
"DocumentQuestionAnsweringInputData",
|
| 686 |
+
"DocumentQuestionAnsweringOutputElement",
|
| 687 |
+
"DocumentQuestionAnsweringParameters",
|
| 688 |
+
"DryRunFileInfo",
|
| 689 |
+
"EvalResult",
|
| 690 |
+
"EvalResultEntry",
|
| 691 |
+
"FLAX_WEIGHTS_NAME",
|
| 692 |
+
"FeatureExtractionInput",
|
| 693 |
+
"FeatureExtractionInputTruncationDirection",
|
| 694 |
+
"FillMaskInput",
|
| 695 |
+
"FillMaskOutputElement",
|
| 696 |
+
"FillMaskParameters",
|
| 697 |
+
"GitCommitInfo",
|
| 698 |
+
"GitRefInfo",
|
| 699 |
+
"GitRefs",
|
| 700 |
+
"HFCacheInfo",
|
| 701 |
+
"HFSummaryWriter",
|
| 702 |
+
"HUGGINGFACE_CO_URL_HOME",
|
| 703 |
+
"HUGGINGFACE_CO_URL_TEMPLATE",
|
| 704 |
+
"HfApi",
|
| 705 |
+
"HfFileMetadata",
|
| 706 |
+
"HfFileSystem",
|
| 707 |
+
"HfFileSystemFile",
|
| 708 |
+
"HfFileSystemResolvedPath",
|
| 709 |
+
"HfFileSystemStreamFile",
|
| 710 |
+
"ImageClassificationInput",
|
| 711 |
+
"ImageClassificationOutputElement",
|
| 712 |
+
"ImageClassificationOutputTransform",
|
| 713 |
+
"ImageClassificationParameters",
|
| 714 |
+
"ImageSegmentationInput",
|
| 715 |
+
"ImageSegmentationOutputElement",
|
| 716 |
+
"ImageSegmentationParameters",
|
| 717 |
+
"ImageSegmentationSubtask",
|
| 718 |
+
"ImageTextToImageInput",
|
| 719 |
+
"ImageTextToImageOutput",
|
| 720 |
+
"ImageTextToImageParameters",
|
| 721 |
+
"ImageTextToImageTargetSize",
|
| 722 |
+
"ImageTextToVideoInput",
|
| 723 |
+
"ImageTextToVideoOutput",
|
| 724 |
+
"ImageTextToVideoParameters",
|
| 725 |
+
"ImageTextToVideoTargetSize",
|
| 726 |
+
"ImageToImageInput",
|
| 727 |
+
"ImageToImageOutput",
|
| 728 |
+
"ImageToImageParameters",
|
| 729 |
+
"ImageToImageTargetSize",
|
| 730 |
+
"ImageToTextEarlyStoppingEnum",
|
| 731 |
+
"ImageToTextGenerationParameters",
|
| 732 |
+
"ImageToTextInput",
|
| 733 |
+
"ImageToTextOutput",
|
| 734 |
+
"ImageToTextParameters",
|
| 735 |
+
"ImageToVideoInput",
|
| 736 |
+
"ImageToVideoOutput",
|
| 737 |
+
"ImageToVideoParameters",
|
| 738 |
+
"ImageToVideoTargetSize",
|
| 739 |
+
"InferenceClient",
|
| 740 |
+
"InferenceEndpoint",
|
| 741 |
+
"InferenceEndpointError",
|
| 742 |
+
"InferenceEndpointStatus",
|
| 743 |
+
"InferenceEndpointTimeoutError",
|
| 744 |
+
"InferenceEndpointType",
|
| 745 |
+
"InferenceTimeoutError",
|
| 746 |
+
"JobAccelerator",
|
| 747 |
+
"JobHardware",
|
| 748 |
+
"JobInfo",
|
| 749 |
+
"JobOwner",
|
| 750 |
+
"JobStage",
|
| 751 |
+
"JobStatus",
|
| 752 |
+
"MCPClient",
|
| 753 |
+
"ModelCard",
|
| 754 |
+
"ModelCardData",
|
| 755 |
+
"ModelHubMixin",
|
| 756 |
+
"ModelInfo",
|
| 757 |
+
"OAuthInfo",
|
| 758 |
+
"OAuthOrgInfo",
|
| 759 |
+
"OAuthUserInfo",
|
| 760 |
+
"ObjectDetectionBoundingBox",
|
| 761 |
+
"ObjectDetectionInput",
|
| 762 |
+
"ObjectDetectionOutputElement",
|
| 763 |
+
"ObjectDetectionParameters",
|
| 764 |
+
"Organization",
|
| 765 |
+
"PYTORCH_WEIGHTS_NAME",
|
| 766 |
+
"Padding",
|
| 767 |
+
"PyTorchModelHubMixin",
|
| 768 |
+
"QuestionAnsweringInput",
|
| 769 |
+
"QuestionAnsweringInputData",
|
| 770 |
+
"QuestionAnsweringOutputElement",
|
| 771 |
+
"QuestionAnsweringParameters",
|
| 772 |
+
"REPO_TYPE_DATASET",
|
| 773 |
+
"REPO_TYPE_MODEL",
|
| 774 |
+
"REPO_TYPE_SPACE",
|
| 775 |
+
"RepoCard",
|
| 776 |
+
"RepoFile",
|
| 777 |
+
"RepoFolder",
|
| 778 |
+
"RepoUrl",
|
| 779 |
+
"SentenceSimilarityInput",
|
| 780 |
+
"SentenceSimilarityInputData",
|
| 781 |
+
"SpaceCard",
|
| 782 |
+
"SpaceCardData",
|
| 783 |
+
"SpaceHardware",
|
| 784 |
+
"SpaceInfo",
|
| 785 |
+
"SpaceRuntime",
|
| 786 |
+
"SpaceStage",
|
| 787 |
+
"SpaceStorage",
|
| 788 |
+
"SpaceVariable",
|
| 789 |
+
"StateDictSplit",
|
| 790 |
+
"SummarizationInput",
|
| 791 |
+
"SummarizationOutput",
|
| 792 |
+
"SummarizationParameters",
|
| 793 |
+
"SummarizationTruncationStrategy",
|
| 794 |
+
"SyncOperation",
|
| 795 |
+
"SyncPlan",
|
| 796 |
+
"TF2_WEIGHTS_NAME",
|
| 797 |
+
"TF_WEIGHTS_NAME",
|
| 798 |
+
"TableQuestionAnsweringInput",
|
| 799 |
+
"TableQuestionAnsweringInputData",
|
| 800 |
+
"TableQuestionAnsweringOutputElement",
|
| 801 |
+
"TableQuestionAnsweringParameters",
|
| 802 |
+
"Text2TextGenerationInput",
|
| 803 |
+
"Text2TextGenerationOutput",
|
| 804 |
+
"Text2TextGenerationParameters",
|
| 805 |
+
"Text2TextGenerationTruncationStrategy",
|
| 806 |
+
"TextClassificationInput",
|
| 807 |
+
"TextClassificationOutputElement",
|
| 808 |
+
"TextClassificationOutputTransform",
|
| 809 |
+
"TextClassificationParameters",
|
| 810 |
+
"TextGenerationInput",
|
| 811 |
+
"TextGenerationInputGenerateParameters",
|
| 812 |
+
"TextGenerationInputGrammarType",
|
| 813 |
+
"TextGenerationOutput",
|
| 814 |
+
"TextGenerationOutputBestOfSequence",
|
| 815 |
+
"TextGenerationOutputDetails",
|
| 816 |
+
"TextGenerationOutputFinishReason",
|
| 817 |
+
"TextGenerationOutputPrefillToken",
|
| 818 |
+
"TextGenerationOutputToken",
|
| 819 |
+
"TextGenerationStreamOutput",
|
| 820 |
+
"TextGenerationStreamOutputStreamDetails",
|
| 821 |
+
"TextGenerationStreamOutputToken",
|
| 822 |
+
"TextToAudioEarlyStoppingEnum",
|
| 823 |
+
"TextToAudioGenerationParameters",
|
| 824 |
+
"TextToAudioInput",
|
| 825 |
+
"TextToAudioOutput",
|
| 826 |
+
"TextToAudioParameters",
|
| 827 |
+
"TextToImageInput",
|
| 828 |
+
"TextToImageOutput",
|
| 829 |
+
"TextToImageParameters",
|
| 830 |
+
"TextToSpeechEarlyStoppingEnum",
|
| 831 |
+
"TextToSpeechGenerationParameters",
|
| 832 |
+
"TextToSpeechInput",
|
| 833 |
+
"TextToSpeechOutput",
|
| 834 |
+
"TextToSpeechParameters",
|
| 835 |
+
"TextToVideoInput",
|
| 836 |
+
"TextToVideoOutput",
|
| 837 |
+
"TextToVideoParameters",
|
| 838 |
+
"TokenClassificationAggregationStrategy",
|
| 839 |
+
"TokenClassificationInput",
|
| 840 |
+
"TokenClassificationOutputElement",
|
| 841 |
+
"TokenClassificationParameters",
|
| 842 |
+
"TranslationInput",
|
| 843 |
+
"TranslationOutput",
|
| 844 |
+
"TranslationParameters",
|
| 845 |
+
"TranslationTruncationStrategy",
|
| 846 |
+
"TypeEnum",
|
| 847 |
+
"User",
|
| 848 |
+
"UserLikes",
|
| 849 |
+
"VideoClassificationInput",
|
| 850 |
+
"VideoClassificationOutputElement",
|
| 851 |
+
"VideoClassificationOutputTransform",
|
| 852 |
+
"VideoClassificationParameters",
|
| 853 |
+
"VisualQuestionAnsweringInput",
|
| 854 |
+
"VisualQuestionAnsweringInputData",
|
| 855 |
+
"VisualQuestionAnsweringOutputElement",
|
| 856 |
+
"VisualQuestionAnsweringParameters",
|
| 857 |
+
"WebhookInfo",
|
| 858 |
+
"WebhookPayload",
|
| 859 |
+
"WebhookPayloadComment",
|
| 860 |
+
"WebhookPayloadDiscussion",
|
| 861 |
+
"WebhookPayloadDiscussionChanges",
|
| 862 |
+
"WebhookPayloadEvent",
|
| 863 |
+
"WebhookPayloadMovedTo",
|
| 864 |
+
"WebhookPayloadRepo",
|
| 865 |
+
"WebhookPayloadUrl",
|
| 866 |
+
"WebhookPayloadWebhook",
|
| 867 |
+
"WebhookWatchedItem",
|
| 868 |
+
"WebhooksServer",
|
| 869 |
+
"ZeroShotClassificationInput",
|
| 870 |
+
"ZeroShotClassificationOutputElement",
|
| 871 |
+
"ZeroShotClassificationParameters",
|
| 872 |
+
"ZeroShotImageClassificationInput",
|
| 873 |
+
"ZeroShotImageClassificationOutputElement",
|
| 874 |
+
"ZeroShotImageClassificationParameters",
|
| 875 |
+
"ZeroShotObjectDetectionBoundingBox",
|
| 876 |
+
"ZeroShotObjectDetectionInput",
|
| 877 |
+
"ZeroShotObjectDetectionOutputElement",
|
| 878 |
+
"ZeroShotObjectDetectionParameters",
|
| 879 |
+
"_CACHED_NO_EXIST",
|
| 880 |
+
"_save_pretrained_fastai",
|
| 881 |
+
"accept_access_request",
|
| 882 |
+
"add_collection_item",
|
| 883 |
+
"add_space_secret",
|
| 884 |
+
"add_space_variable",
|
| 885 |
+
"attach_huggingface_oauth",
|
| 886 |
+
"auth_check",
|
| 887 |
+
"auth_list",
|
| 888 |
+
"auth_switch",
|
| 889 |
+
"batch_bucket_files",
|
| 890 |
+
"bucket_info",
|
| 891 |
+
"cached_assets_path",
|
| 892 |
+
"cancel_access_request",
|
| 893 |
+
"cancel_job",
|
| 894 |
+
"change_discussion_status",
|
| 895 |
+
"check_cli_update",
|
| 896 |
+
"close_session",
|
| 897 |
+
"comment_discussion",
|
| 898 |
+
"create_branch",
|
| 899 |
+
"create_bucket",
|
| 900 |
+
"create_collection",
|
| 901 |
+
"create_commit",
|
| 902 |
+
"create_discussion",
|
| 903 |
+
"create_inference_endpoint",
|
| 904 |
+
"create_inference_endpoint_from_catalog",
|
| 905 |
+
"create_pull_request",
|
| 906 |
+
"create_repo",
|
| 907 |
+
"create_scheduled_job",
|
| 908 |
+
"create_scheduled_uv_job",
|
| 909 |
+
"create_tag",
|
| 910 |
+
"create_webhook",
|
| 911 |
+
"dataset_info",
|
| 912 |
+
"delete_branch",
|
| 913 |
+
"delete_bucket",
|
| 914 |
+
"delete_collection",
|
| 915 |
+
"delete_collection_item",
|
| 916 |
+
"delete_file",
|
| 917 |
+
"delete_folder",
|
| 918 |
+
"delete_inference_endpoint",
|
| 919 |
+
"delete_repo",
|
| 920 |
+
"delete_scheduled_job",
|
| 921 |
+
"delete_space_secret",
|
| 922 |
+
"delete_space_storage",
|
| 923 |
+
"delete_space_variable",
|
| 924 |
+
"delete_tag",
|
| 925 |
+
"delete_webhook",
|
| 926 |
+
"disable_space_dev_mode",
|
| 927 |
+
"disable_webhook",
|
| 928 |
+
"download_bucket_files",
|
| 929 |
+
"dump_environment_info",
|
| 930 |
+
"duplicate_repo",
|
| 931 |
+
"duplicate_space",
|
| 932 |
+
"edit_discussion_comment",
|
| 933 |
+
"enable_space_dev_mode",
|
| 934 |
+
"enable_webhook",
|
| 935 |
+
"eval_result_entries_to_yaml",
|
| 936 |
+
"export_entries_as_dduf",
|
| 937 |
+
"export_folder_as_dduf",
|
| 938 |
+
"fetch_job_logs",
|
| 939 |
+
"fetch_job_metrics",
|
| 940 |
+
"file_exists",
|
| 941 |
+
"from_pretrained_fastai",
|
| 942 |
+
"get_async_session",
|
| 943 |
+
"get_bucket_file_metadata",
|
| 944 |
+
"get_bucket_paths_info",
|
| 945 |
+
"get_collection",
|
| 946 |
+
"get_dataset_tags",
|
| 947 |
+
"get_discussion_details",
|
| 948 |
+
"get_full_repo_name",
|
| 949 |
+
"get_hf_file_metadata",
|
| 950 |
+
"get_inference_endpoint",
|
| 951 |
+
"get_local_safetensors_metadata",
|
| 952 |
+
"get_model_tags",
|
| 953 |
+
"get_organization_overview",
|
| 954 |
+
"get_paths_info",
|
| 955 |
+
"get_repo_discussions",
|
| 956 |
+
"get_safetensors_metadata",
|
| 957 |
+
"get_session",
|
| 958 |
+
"get_space_runtime",
|
| 959 |
+
"get_space_variables",
|
| 960 |
+
"get_token",
|
| 961 |
+
"get_torch_storage_id",
|
| 962 |
+
"get_torch_storage_size",
|
| 963 |
+
"get_user_overview",
|
| 964 |
+
"get_webhook",
|
| 965 |
+
"grant_access",
|
| 966 |
+
"hf_hub_download",
|
| 967 |
+
"hf_hub_url",
|
| 968 |
+
"hf_raise_for_status",
|
| 969 |
+
"hffs",
|
| 970 |
+
"inspect_job",
|
| 971 |
+
"inspect_scheduled_job",
|
| 972 |
+
"interpreter_login",
|
| 973 |
+
"is_offline_mode",
|
| 974 |
+
"list_accepted_access_requests",
|
| 975 |
+
"list_bucket_tree",
|
| 976 |
+
"list_buckets",
|
| 977 |
+
"list_collections",
|
| 978 |
+
"list_daily_papers",
|
| 979 |
+
"list_dataset_parquet_files",
|
| 980 |
+
"list_datasets",
|
| 981 |
+
"list_inference_catalog",
|
| 982 |
+
"list_inference_endpoints",
|
| 983 |
+
"list_jobs",
|
| 984 |
+
"list_jobs_hardware",
|
| 985 |
+
"list_lfs_files",
|
| 986 |
+
"list_liked_repos",
|
| 987 |
+
"list_models",
|
| 988 |
+
"list_organization_followers",
|
| 989 |
+
"list_organization_members",
|
| 990 |
+
"list_papers",
|
| 991 |
+
"list_pending_access_requests",
|
| 992 |
+
"list_rejected_access_requests",
|
| 993 |
+
"list_repo_commits",
|
| 994 |
+
"list_repo_files",
|
| 995 |
+
"list_repo_likers",
|
| 996 |
+
"list_repo_refs",
|
| 997 |
+
"list_repo_tree",
|
| 998 |
+
"list_spaces",
|
| 999 |
+
"list_user_followers",
|
| 1000 |
+
"list_user_following",
|
| 1001 |
+
"list_webhooks",
|
| 1002 |
+
"load_state_dict_from_file",
|
| 1003 |
+
"load_torch_model",
|
| 1004 |
+
"logging",
|
| 1005 |
+
"login",
|
| 1006 |
+
"logout",
|
| 1007 |
+
"merge_pull_request",
|
| 1008 |
+
"metadata_eval_result",
|
| 1009 |
+
"metadata_load",
|
| 1010 |
+
"metadata_save",
|
| 1011 |
+
"metadata_update",
|
| 1012 |
+
"model_info",
|
| 1013 |
+
"move_bucket",
|
| 1014 |
+
"move_repo",
|
| 1015 |
+
"notebook_login",
|
| 1016 |
+
"paper_info",
|
| 1017 |
+
"parse_eval_result_entries",
|
| 1018 |
+
"parse_huggingface_oauth",
|
| 1019 |
+
"parse_local_safetensors_file_metadata",
|
| 1020 |
+
"parse_safetensors_file_metadata",
|
| 1021 |
+
"pause_inference_endpoint",
|
| 1022 |
+
"pause_space",
|
| 1023 |
+
"permanently_delete_lfs_files",
|
| 1024 |
+
"preupload_lfs_files",
|
| 1025 |
+
"push_to_hub_fastai",
|
| 1026 |
+
"read_dduf_file",
|
| 1027 |
+
"reject_access_request",
|
| 1028 |
+
"rename_discussion",
|
| 1029 |
+
"repo_exists",
|
| 1030 |
+
"repo_info",
|
| 1031 |
+
"repo_type_and_id_from_hf_id",
|
| 1032 |
+
"request_space_hardware",
|
| 1033 |
+
"request_space_storage",
|
| 1034 |
+
"restart_space",
|
| 1035 |
+
"resume_inference_endpoint",
|
| 1036 |
+
"resume_scheduled_job",
|
| 1037 |
+
"revision_exists",
|
| 1038 |
+
"run_as_future",
|
| 1039 |
+
"run_job",
|
| 1040 |
+
"run_uv_job",
|
| 1041 |
+
"save_torch_model",
|
| 1042 |
+
"save_torch_state_dict",
|
| 1043 |
+
"scale_to_zero_inference_endpoint",
|
| 1044 |
+
"scan_cache_dir",
|
| 1045 |
+
"set_async_client_factory",
|
| 1046 |
+
"set_client_factory",
|
| 1047 |
+
"set_space_sleep_time",
|
| 1048 |
+
"snapshot_download",
|
| 1049 |
+
"space_info",
|
| 1050 |
+
"split_state_dict_into_shards_factory",
|
| 1051 |
+
"split_torch_state_dict_into_shards",
|
| 1052 |
+
"super_squash_history",
|
| 1053 |
+
"suspend_scheduled_job",
|
| 1054 |
+
"sync_bucket",
|
| 1055 |
+
"try_to_load_from_cache",
|
| 1056 |
+
"typer_factory",
|
| 1057 |
+
"unlike",
|
| 1058 |
+
"update_collection_item",
|
| 1059 |
+
"update_collection_metadata",
|
| 1060 |
+
"update_inference_endpoint",
|
| 1061 |
+
"update_repo_settings",
|
| 1062 |
+
"update_webhook",
|
| 1063 |
+
"upload_file",
|
| 1064 |
+
"upload_folder",
|
| 1065 |
+
"upload_large_folder",
|
| 1066 |
+
"verify_repo_checksums",
|
| 1067 |
+
"webhook_endpoint",
|
| 1068 |
+
"whoami",
|
| 1069 |
+
]
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
def _attach(package_name, submodules=None, submod_attrs=None):
|
| 1073 |
+
"""Attach lazily loaded submodules, functions, or other attributes.
|
| 1074 |
+
|
| 1075 |
+
Typically, modules import submodules and attributes as follows:
|
| 1076 |
+
|
| 1077 |
+
```py
|
| 1078 |
+
import mysubmodule
|
| 1079 |
+
import anothersubmodule
|
| 1080 |
+
|
| 1081 |
+
from .foo import someattr
|
| 1082 |
+
```
|
| 1083 |
+
|
| 1084 |
+
The idea is to replace a package's `__getattr__`, `__dir__`, such that all imports
|
| 1085 |
+
work exactly the way they would with normal imports, except that the import occurs
|
| 1086 |
+
upon first use.
|
| 1087 |
+
|
| 1088 |
+
The typical way to call this function, replacing the above imports, is:
|
| 1089 |
+
|
| 1090 |
+
```python
|
| 1091 |
+
__getattr__, __dir__ = lazy.attach(
|
| 1092 |
+
__name__,
|
| 1093 |
+
['mysubmodule', 'anothersubmodule'],
|
| 1094 |
+
{'foo': ['someattr']}
|
| 1095 |
+
)
|
| 1096 |
+
```
|
| 1097 |
+
This functionality requires Python 3.7 or higher.
|
| 1098 |
+
|
| 1099 |
+
Args:
|
| 1100 |
+
package_name (`str`):
|
| 1101 |
+
Typically use `__name__`.
|
| 1102 |
+
submodules (`set`):
|
| 1103 |
+
List of submodules to attach.
|
| 1104 |
+
submod_attrs (`dict`):
|
| 1105 |
+
Dictionary of submodule -> list of attributes / functions.
|
| 1106 |
+
These attributes are imported as they are used.
|
| 1107 |
+
|
| 1108 |
+
Returns:
|
| 1109 |
+
__getattr__, __dir__, __all__
|
| 1110 |
+
|
| 1111 |
+
"""
|
| 1112 |
+
if submod_attrs is None:
|
| 1113 |
+
submod_attrs = {}
|
| 1114 |
+
|
| 1115 |
+
if submodules is None:
|
| 1116 |
+
submodules = set()
|
| 1117 |
+
else:
|
| 1118 |
+
submodules = set(submodules)
|
| 1119 |
+
|
| 1120 |
+
attr_to_modules = {attr: mod for mod, attrs in submod_attrs.items() for attr in attrs}
|
| 1121 |
+
|
| 1122 |
+
def __getattr__(name):
|
| 1123 |
+
if name in submodules:
|
| 1124 |
+
try:
|
| 1125 |
+
return importlib.import_module(f"{package_name}.{name}")
|
| 1126 |
+
except Exception as e:
|
| 1127 |
+
print(f"Error importing {package_name}.{name}: {e}")
|
| 1128 |
+
raise
|
| 1129 |
+
elif name in attr_to_modules:
|
| 1130 |
+
submod_path = f"{package_name}.{attr_to_modules[name]}"
|
| 1131 |
+
try:
|
| 1132 |
+
submod = importlib.import_module(submod_path)
|
| 1133 |
+
except Exception as e:
|
| 1134 |
+
print(f"Error importing {submod_path}: {e}")
|
| 1135 |
+
raise
|
| 1136 |
+
attr = getattr(submod, name)
|
| 1137 |
+
|
| 1138 |
+
# If the attribute lives in a file (module) with the same
|
| 1139 |
+
# name as the attribute, ensure that the attribute and *not*
|
| 1140 |
+
# the module is accessible on the package.
|
| 1141 |
+
if name == attr_to_modules[name]:
|
| 1142 |
+
pkg = sys.modules[package_name]
|
| 1143 |
+
pkg.__dict__[name] = attr
|
| 1144 |
+
|
| 1145 |
+
return attr
|
| 1146 |
+
else:
|
| 1147 |
+
raise AttributeError(f"No {package_name} attribute {name}")
|
| 1148 |
+
|
| 1149 |
+
def __dir__():
|
| 1150 |
+
return __all__
|
| 1151 |
+
|
| 1152 |
+
return __getattr__, __dir__
|
| 1153 |
+
|
| 1154 |
+
|
| 1155 |
+
__getattr__, __dir__ = _attach(__name__, submodules=[], submod_attrs=_SUBMOD_ATTRS)
|
| 1156 |
+
|
| 1157 |
+
if os.environ.get("EAGER_IMPORT", ""):
|
| 1158 |
+
for attr in __all__:
|
| 1159 |
+
__getattr__(attr)
|
| 1160 |
+
|
| 1161 |
+
# WARNING: any content below this statement is generated automatically. Any manual edit
|
| 1162 |
+
# will be lost when re-generating this file !
|
| 1163 |
+
#
|
| 1164 |
+
# To update the static imports, please run the following command and commit the changes.
|
| 1165 |
+
# ```
|
| 1166 |
+
# # Use script
|
| 1167 |
+
# python utils/check_static_imports.py --update
|
| 1168 |
+
#
|
| 1169 |
+
# # Or run style on codebase
|
| 1170 |
+
# make style
|
| 1171 |
+
# ```
|
| 1172 |
+
if TYPE_CHECKING: # pragma: no cover
|
| 1173 |
+
from ._buckets import (
|
| 1174 |
+
BucketFile, # noqa: F401
|
| 1175 |
+
BucketFileMetadata, # noqa: F401
|
| 1176 |
+
BucketFolder, # noqa: F401
|
| 1177 |
+
BucketInfo, # noqa: F401
|
| 1178 |
+
BucketUrl, # noqa: F401
|
| 1179 |
+
SyncOperation, # noqa: F401
|
| 1180 |
+
SyncPlan, # noqa: F401
|
| 1181 |
+
)
|
| 1182 |
+
from ._commit_scheduler import CommitScheduler # noqa: F401
|
| 1183 |
+
from ._eval_results import (
|
| 1184 |
+
EvalResultEntry, # noqa: F401
|
| 1185 |
+
eval_result_entries_to_yaml, # noqa: F401
|
| 1186 |
+
parse_eval_result_entries, # noqa: F401
|
| 1187 |
+
)
|
| 1188 |
+
from ._inference_endpoints import (
|
| 1189 |
+
InferenceEndpoint, # noqa: F401
|
| 1190 |
+
InferenceEndpointError, # noqa: F401
|
| 1191 |
+
InferenceEndpointStatus, # noqa: F401
|
| 1192 |
+
InferenceEndpointTimeoutError, # noqa: F401
|
| 1193 |
+
InferenceEndpointType, # noqa: F401
|
| 1194 |
+
)
|
| 1195 |
+
from ._jobs_api import (
|
| 1196 |
+
JobAccelerator, # noqa: F401
|
| 1197 |
+
JobHardware, # noqa: F401
|
| 1198 |
+
JobInfo, # noqa: F401
|
| 1199 |
+
JobOwner, # noqa: F401
|
| 1200 |
+
JobStage, # noqa: F401
|
| 1201 |
+
JobStatus, # noqa: F401
|
| 1202 |
+
)
|
| 1203 |
+
from ._login import (
|
| 1204 |
+
auth_list, # noqa: F401
|
| 1205 |
+
auth_switch, # noqa: F401
|
| 1206 |
+
interpreter_login, # noqa: F401
|
| 1207 |
+
login, # noqa: F401
|
| 1208 |
+
logout, # noqa: F401
|
| 1209 |
+
notebook_login, # noqa: F401
|
| 1210 |
+
)
|
| 1211 |
+
from ._oauth import (
|
| 1212 |
+
OAuthInfo, # noqa: F401
|
| 1213 |
+
OAuthOrgInfo, # noqa: F401
|
| 1214 |
+
OAuthUserInfo, # noqa: F401
|
| 1215 |
+
attach_huggingface_oauth, # noqa: F401
|
| 1216 |
+
parse_huggingface_oauth, # noqa: F401
|
| 1217 |
+
)
|
| 1218 |
+
from ._snapshot_download import snapshot_download # noqa: F401
|
| 1219 |
+
from ._space_api import (
|
| 1220 |
+
SpaceHardware, # noqa: F401
|
| 1221 |
+
SpaceRuntime, # noqa: F401
|
| 1222 |
+
SpaceStage, # noqa: F401
|
| 1223 |
+
SpaceStorage, # noqa: F401
|
| 1224 |
+
SpaceVariable, # noqa: F401
|
| 1225 |
+
)
|
| 1226 |
+
from ._tensorboard_logger import HFSummaryWriter # noqa: F401
|
| 1227 |
+
from ._webhooks_payload import (
|
| 1228 |
+
WebhookPayload, # noqa: F401
|
| 1229 |
+
WebhookPayloadComment, # noqa: F401
|
| 1230 |
+
WebhookPayloadDiscussion, # noqa: F401
|
| 1231 |
+
WebhookPayloadDiscussionChanges, # noqa: F401
|
| 1232 |
+
WebhookPayloadEvent, # noqa: F401
|
| 1233 |
+
WebhookPayloadMovedTo, # noqa: F401
|
| 1234 |
+
WebhookPayloadRepo, # noqa: F401
|
| 1235 |
+
WebhookPayloadUrl, # noqa: F401
|
| 1236 |
+
WebhookPayloadWebhook, # noqa: F401
|
| 1237 |
+
)
|
| 1238 |
+
from ._webhooks_server import (
|
| 1239 |
+
WebhooksServer, # noqa: F401
|
| 1240 |
+
webhook_endpoint, # noqa: F401
|
| 1241 |
+
)
|
| 1242 |
+
from .cli._cli_utils import (
|
| 1243 |
+
check_cli_update, # noqa: F401
|
| 1244 |
+
typer_factory, # noqa: F401
|
| 1245 |
+
)
|
| 1246 |
+
from .community import (
|
| 1247 |
+
Discussion, # noqa: F401
|
| 1248 |
+
DiscussionComment, # noqa: F401
|
| 1249 |
+
DiscussionCommit, # noqa: F401
|
| 1250 |
+
DiscussionEvent, # noqa: F401
|
| 1251 |
+
DiscussionStatusChange, # noqa: F401
|
| 1252 |
+
DiscussionTitleChange, # noqa: F401
|
| 1253 |
+
DiscussionWithDetails, # noqa: F401
|
| 1254 |
+
)
|
| 1255 |
+
from .constants import (
|
| 1256 |
+
CONFIG_NAME, # noqa: F401
|
| 1257 |
+
FLAX_WEIGHTS_NAME, # noqa: F401
|
| 1258 |
+
HUGGINGFACE_CO_URL_HOME, # noqa: F401
|
| 1259 |
+
HUGGINGFACE_CO_URL_TEMPLATE, # noqa: F401
|
| 1260 |
+
PYTORCH_WEIGHTS_NAME, # noqa: F401
|
| 1261 |
+
REPO_TYPE_DATASET, # noqa: F401
|
| 1262 |
+
REPO_TYPE_MODEL, # noqa: F401
|
| 1263 |
+
REPO_TYPE_SPACE, # noqa: F401
|
| 1264 |
+
TF2_WEIGHTS_NAME, # noqa: F401
|
| 1265 |
+
TF_WEIGHTS_NAME, # noqa: F401
|
| 1266 |
+
is_offline_mode, # noqa: F401
|
| 1267 |
+
)
|
| 1268 |
+
from .fastai_utils import (
|
| 1269 |
+
_save_pretrained_fastai, # noqa: F401
|
| 1270 |
+
from_pretrained_fastai, # noqa: F401
|
| 1271 |
+
push_to_hub_fastai, # noqa: F401
|
| 1272 |
+
)
|
| 1273 |
+
from .file_download import (
|
| 1274 |
+
_CACHED_NO_EXIST, # noqa: F401
|
| 1275 |
+
DryRunFileInfo, # noqa: F401
|
| 1276 |
+
HfFileMetadata, # noqa: F401
|
| 1277 |
+
get_hf_file_metadata, # noqa: F401
|
| 1278 |
+
hf_hub_download, # noqa: F401
|
| 1279 |
+
hf_hub_url, # noqa: F401
|
| 1280 |
+
try_to_load_from_cache, # noqa: F401
|
| 1281 |
+
)
|
| 1282 |
+
from .hf_api import (
|
| 1283 |
+
Collection, # noqa: F401
|
| 1284 |
+
CollectionItem, # noqa: F401
|
| 1285 |
+
CommitInfo, # noqa: F401
|
| 1286 |
+
CommitOperation, # noqa: F401
|
| 1287 |
+
CommitOperationAdd, # noqa: F401
|
| 1288 |
+
CommitOperationCopy, # noqa: F401
|
| 1289 |
+
CommitOperationDelete, # noqa: F401
|
| 1290 |
+
DatasetInfo, # noqa: F401
|
| 1291 |
+
GitCommitInfo, # noqa: F401
|
| 1292 |
+
GitRefInfo, # noqa: F401
|
| 1293 |
+
GitRefs, # noqa: F401
|
| 1294 |
+
HfApi, # noqa: F401
|
| 1295 |
+
ModelInfo, # noqa: F401
|
| 1296 |
+
Organization, # noqa: F401
|
| 1297 |
+
RepoFile, # noqa: F401
|
| 1298 |
+
RepoFolder, # noqa: F401
|
| 1299 |
+
RepoUrl, # noqa: F401
|
| 1300 |
+
SpaceInfo, # noqa: F401
|
| 1301 |
+
User, # noqa: F401
|
| 1302 |
+
UserLikes, # noqa: F401
|
| 1303 |
+
WebhookInfo, # noqa: F401
|
| 1304 |
+
WebhookWatchedItem, # noqa: F401
|
| 1305 |
+
accept_access_request, # noqa: F401
|
| 1306 |
+
add_collection_item, # noqa: F401
|
| 1307 |
+
add_space_secret, # noqa: F401
|
| 1308 |
+
add_space_variable, # noqa: F401
|
| 1309 |
+
auth_check, # noqa: F401
|
| 1310 |
+
batch_bucket_files, # noqa: F401
|
| 1311 |
+
bucket_info, # noqa: F401
|
| 1312 |
+
cancel_access_request, # noqa: F401
|
| 1313 |
+
cancel_job, # noqa: F401
|
| 1314 |
+
change_discussion_status, # noqa: F401
|
| 1315 |
+
comment_discussion, # noqa: F401
|
| 1316 |
+
create_branch, # noqa: F401
|
| 1317 |
+
create_bucket, # noqa: F401
|
| 1318 |
+
create_collection, # noqa: F401
|
| 1319 |
+
create_commit, # noqa: F401
|
| 1320 |
+
create_discussion, # noqa: F401
|
| 1321 |
+
create_inference_endpoint, # noqa: F401
|
| 1322 |
+
create_inference_endpoint_from_catalog, # noqa: F401
|
| 1323 |
+
create_pull_request, # noqa: F401
|
| 1324 |
+
create_repo, # noqa: F401
|
| 1325 |
+
create_scheduled_job, # noqa: F401
|
| 1326 |
+
create_scheduled_uv_job, # noqa: F401
|
| 1327 |
+
create_tag, # noqa: F401
|
| 1328 |
+
create_webhook, # noqa: F401
|
| 1329 |
+
dataset_info, # noqa: F401
|
| 1330 |
+
delete_branch, # noqa: F401
|
| 1331 |
+
delete_bucket, # noqa: F401
|
| 1332 |
+
delete_collection, # noqa: F401
|
| 1333 |
+
delete_collection_item, # noqa: F401
|
| 1334 |
+
delete_file, # noqa: F401
|
| 1335 |
+
delete_folder, # noqa: F401
|
| 1336 |
+
delete_inference_endpoint, # noqa: F401
|
| 1337 |
+
delete_repo, # noqa: F401
|
| 1338 |
+
delete_scheduled_job, # noqa: F401
|
| 1339 |
+
delete_space_secret, # noqa: F401
|
| 1340 |
+
delete_space_storage, # noqa: F401
|
| 1341 |
+
delete_space_variable, # noqa: F401
|
| 1342 |
+
delete_tag, # noqa: F401
|
| 1343 |
+
delete_webhook, # noqa: F401
|
| 1344 |
+
disable_space_dev_mode, # noqa: F401
|
| 1345 |
+
disable_webhook, # noqa: F401
|
| 1346 |
+
download_bucket_files, # noqa: F401
|
| 1347 |
+
duplicate_repo, # noqa: F401
|
| 1348 |
+
duplicate_space, # noqa: F401
|
| 1349 |
+
edit_discussion_comment, # noqa: F401
|
| 1350 |
+
enable_space_dev_mode, # noqa: F401
|
| 1351 |
+
enable_webhook, # noqa: F401
|
| 1352 |
+
fetch_job_logs, # noqa: F401
|
| 1353 |
+
fetch_job_metrics, # noqa: F401
|
| 1354 |
+
file_exists, # noqa: F401
|
| 1355 |
+
get_bucket_file_metadata, # noqa: F401
|
| 1356 |
+
get_bucket_paths_info, # noqa: F401
|
| 1357 |
+
get_collection, # noqa: F401
|
| 1358 |
+
get_dataset_tags, # noqa: F401
|
| 1359 |
+
get_discussion_details, # noqa: F401
|
| 1360 |
+
get_full_repo_name, # noqa: F401
|
| 1361 |
+
get_inference_endpoint, # noqa: F401
|
| 1362 |
+
get_local_safetensors_metadata, # noqa: F401
|
| 1363 |
+
get_model_tags, # noqa: F401
|
| 1364 |
+
get_organization_overview, # noqa: F401
|
| 1365 |
+
get_paths_info, # noqa: F401
|
| 1366 |
+
get_repo_discussions, # noqa: F401
|
| 1367 |
+
get_safetensors_metadata, # noqa: F401
|
| 1368 |
+
get_space_runtime, # noqa: F401
|
| 1369 |
+
get_space_variables, # noqa: F401
|
| 1370 |
+
get_user_overview, # noqa: F401
|
| 1371 |
+
get_webhook, # noqa: F401
|
| 1372 |
+
grant_access, # noqa: F401
|
| 1373 |
+
inspect_job, # noqa: F401
|
| 1374 |
+
inspect_scheduled_job, # noqa: F401
|
| 1375 |
+
list_accepted_access_requests, # noqa: F401
|
| 1376 |
+
list_bucket_tree, # noqa: F401
|
| 1377 |
+
list_buckets, # noqa: F401
|
| 1378 |
+
list_collections, # noqa: F401
|
| 1379 |
+
list_daily_papers, # noqa: F401
|
| 1380 |
+
list_dataset_parquet_files, # noqa: F401
|
| 1381 |
+
list_datasets, # noqa: F401
|
| 1382 |
+
list_inference_catalog, # noqa: F401
|
| 1383 |
+
list_inference_endpoints, # noqa: F401
|
| 1384 |
+
list_jobs, # noqa: F401
|
| 1385 |
+
list_jobs_hardware, # noqa: F401
|
| 1386 |
+
list_lfs_files, # noqa: F401
|
| 1387 |
+
list_liked_repos, # noqa: F401
|
| 1388 |
+
list_models, # noqa: F401
|
| 1389 |
+
list_organization_followers, # noqa: F401
|
| 1390 |
+
list_organization_members, # noqa: F401
|
| 1391 |
+
list_papers, # noqa: F401
|
| 1392 |
+
list_pending_access_requests, # noqa: F401
|
| 1393 |
+
list_rejected_access_requests, # noqa: F401
|
| 1394 |
+
list_repo_commits, # noqa: F401
|
| 1395 |
+
list_repo_files, # noqa: F401
|
| 1396 |
+
list_repo_likers, # noqa: F401
|
| 1397 |
+
list_repo_refs, # noqa: F401
|
| 1398 |
+
list_repo_tree, # noqa: F401
|
| 1399 |
+
list_spaces, # noqa: F401
|
| 1400 |
+
list_user_followers, # noqa: F401
|
| 1401 |
+
list_user_following, # noqa: F401
|
| 1402 |
+
list_webhooks, # noqa: F401
|
| 1403 |
+
merge_pull_request, # noqa: F401
|
| 1404 |
+
model_info, # noqa: F401
|
| 1405 |
+
move_bucket, # noqa: F401
|
| 1406 |
+
move_repo, # noqa: F401
|
| 1407 |
+
paper_info, # noqa: F401
|
| 1408 |
+
parse_local_safetensors_file_metadata, # noqa: F401
|
| 1409 |
+
parse_safetensors_file_metadata, # noqa: F401
|
| 1410 |
+
pause_inference_endpoint, # noqa: F401
|
| 1411 |
+
pause_space, # noqa: F401
|
| 1412 |
+
permanently_delete_lfs_files, # noqa: F401
|
| 1413 |
+
preupload_lfs_files, # noqa: F401
|
| 1414 |
+
reject_access_request, # noqa: F401
|
| 1415 |
+
rename_discussion, # noqa: F401
|
| 1416 |
+
repo_exists, # noqa: F401
|
| 1417 |
+
repo_info, # noqa: F401
|
| 1418 |
+
repo_type_and_id_from_hf_id, # noqa: F401
|
| 1419 |
+
request_space_hardware, # noqa: F401
|
| 1420 |
+
request_space_storage, # noqa: F401
|
| 1421 |
+
restart_space, # noqa: F401
|
| 1422 |
+
resume_inference_endpoint, # noqa: F401
|
| 1423 |
+
resume_scheduled_job, # noqa: F401
|
| 1424 |
+
revision_exists, # noqa: F401
|
| 1425 |
+
run_as_future, # noqa: F401
|
| 1426 |
+
run_job, # noqa: F401
|
| 1427 |
+
run_uv_job, # noqa: F401
|
| 1428 |
+
scale_to_zero_inference_endpoint, # noqa: F401
|
| 1429 |
+
set_space_sleep_time, # noqa: F401
|
| 1430 |
+
space_info, # noqa: F401
|
| 1431 |
+
super_squash_history, # noqa: F401
|
| 1432 |
+
suspend_scheduled_job, # noqa: F401
|
| 1433 |
+
sync_bucket, # noqa: F401
|
| 1434 |
+
unlike, # noqa: F401
|
| 1435 |
+
update_collection_item, # noqa: F401
|
| 1436 |
+
update_collection_metadata, # noqa: F401
|
| 1437 |
+
update_inference_endpoint, # noqa: F401
|
| 1438 |
+
update_repo_settings, # noqa: F401
|
| 1439 |
+
update_webhook, # noqa: F401
|
| 1440 |
+
upload_file, # noqa: F401
|
| 1441 |
+
upload_folder, # noqa: F401
|
| 1442 |
+
upload_large_folder, # noqa: F401
|
| 1443 |
+
verify_repo_checksums, # noqa: F401
|
| 1444 |
+
whoami, # noqa: F401
|
| 1445 |
+
)
|
| 1446 |
+
from .hf_file_system import (
|
| 1447 |
+
HfFileSystem, # noqa: F401
|
| 1448 |
+
HfFileSystemFile, # noqa: F401
|
| 1449 |
+
HfFileSystemResolvedPath, # noqa: F401
|
| 1450 |
+
HfFileSystemStreamFile, # noqa: F401
|
| 1451 |
+
hffs, # noqa: F401
|
| 1452 |
+
)
|
| 1453 |
+
from .hub_mixin import (
|
| 1454 |
+
ModelHubMixin, # noqa: F401
|
| 1455 |
+
PyTorchModelHubMixin, # noqa: F401
|
| 1456 |
+
)
|
| 1457 |
+
from .inference._client import (
|
| 1458 |
+
InferenceClient, # noqa: F401
|
| 1459 |
+
InferenceTimeoutError, # noqa: F401
|
| 1460 |
+
)
|
| 1461 |
+
from .inference._generated._async_client import AsyncInferenceClient # noqa: F401
|
| 1462 |
+
from .inference._generated.types import (
|
| 1463 |
+
AudioClassificationInput, # noqa: F401
|
| 1464 |
+
AudioClassificationOutputElement, # noqa: F401
|
| 1465 |
+
AudioClassificationOutputTransform, # noqa: F401
|
| 1466 |
+
AudioClassificationParameters, # noqa: F401
|
| 1467 |
+
AudioToAudioInput, # noqa: F401
|
| 1468 |
+
AudioToAudioOutputElement, # noqa: F401
|
| 1469 |
+
AutomaticSpeechRecognitionEarlyStoppingEnum, # noqa: F401
|
| 1470 |
+
AutomaticSpeechRecognitionGenerationParameters, # noqa: F401
|
| 1471 |
+
AutomaticSpeechRecognitionInput, # noqa: F401
|
| 1472 |
+
AutomaticSpeechRecognitionOutput, # noqa: F401
|
| 1473 |
+
AutomaticSpeechRecognitionOutputChunk, # noqa: F401
|
| 1474 |
+
AutomaticSpeechRecognitionParameters, # noqa: F401
|
| 1475 |
+
ChatCompletionInput, # noqa: F401
|
| 1476 |
+
ChatCompletionInputFunctionDefinition, # noqa: F401
|
| 1477 |
+
ChatCompletionInputFunctionName, # noqa: F401
|
| 1478 |
+
ChatCompletionInputGrammarType, # noqa: F401
|
| 1479 |
+
ChatCompletionInputJSONSchema, # noqa: F401
|
| 1480 |
+
ChatCompletionInputMessage, # noqa: F401
|
| 1481 |
+
ChatCompletionInputMessageChunk, # noqa: F401
|
| 1482 |
+
ChatCompletionInputMessageChunkType, # noqa: F401
|
| 1483 |
+
ChatCompletionInputResponseFormatJSONObject, # noqa: F401
|
| 1484 |
+
ChatCompletionInputResponseFormatJSONSchema, # noqa: F401
|
| 1485 |
+
ChatCompletionInputResponseFormatText, # noqa: F401
|
| 1486 |
+
ChatCompletionInputStreamOptions, # noqa: F401
|
| 1487 |
+
ChatCompletionInputTool, # noqa: F401
|
| 1488 |
+
ChatCompletionInputToolCall, # noqa: F401
|
| 1489 |
+
ChatCompletionInputToolChoiceClass, # noqa: F401
|
| 1490 |
+
ChatCompletionInputToolChoiceEnum, # noqa: F401
|
| 1491 |
+
ChatCompletionInputURL, # noqa: F401
|
| 1492 |
+
ChatCompletionOutput, # noqa: F401
|
| 1493 |
+
ChatCompletionOutputComplete, # noqa: F401
|
| 1494 |
+
ChatCompletionOutputFunctionDefinition, # noqa: F401
|
| 1495 |
+
ChatCompletionOutputLogprob, # noqa: F401
|
| 1496 |
+
ChatCompletionOutputLogprobs, # noqa: F401
|
| 1497 |
+
ChatCompletionOutputMessage, # noqa: F401
|
| 1498 |
+
ChatCompletionOutputToolCall, # noqa: F401
|
| 1499 |
+
ChatCompletionOutputTopLogprob, # noqa: F401
|
| 1500 |
+
ChatCompletionOutputUsage, # noqa: F401
|
| 1501 |
+
ChatCompletionStreamOutput, # noqa: F401
|
| 1502 |
+
ChatCompletionStreamOutputChoice, # noqa: F401
|
| 1503 |
+
ChatCompletionStreamOutputDelta, # noqa: F401
|
| 1504 |
+
ChatCompletionStreamOutputDeltaToolCall, # noqa: F401
|
| 1505 |
+
ChatCompletionStreamOutputFunction, # noqa: F401
|
| 1506 |
+
ChatCompletionStreamOutputLogprob, # noqa: F401
|
| 1507 |
+
ChatCompletionStreamOutputLogprobs, # noqa: F401
|
| 1508 |
+
ChatCompletionStreamOutputTopLogprob, # noqa: F401
|
| 1509 |
+
ChatCompletionStreamOutputUsage, # noqa: F401
|
| 1510 |
+
DepthEstimationInput, # noqa: F401
|
| 1511 |
+
DepthEstimationOutput, # noqa: F401
|
| 1512 |
+
DocumentQuestionAnsweringInput, # noqa: F401
|
| 1513 |
+
DocumentQuestionAnsweringInputData, # noqa: F401
|
| 1514 |
+
DocumentQuestionAnsweringOutputElement, # noqa: F401
|
| 1515 |
+
DocumentQuestionAnsweringParameters, # noqa: F401
|
| 1516 |
+
FeatureExtractionInput, # noqa: F401
|
| 1517 |
+
FeatureExtractionInputTruncationDirection, # noqa: F401
|
| 1518 |
+
FillMaskInput, # noqa: F401
|
| 1519 |
+
FillMaskOutputElement, # noqa: F401
|
| 1520 |
+
FillMaskParameters, # noqa: F401
|
| 1521 |
+
ImageClassificationInput, # noqa: F401
|
| 1522 |
+
ImageClassificationOutputElement, # noqa: F401
|
| 1523 |
+
ImageClassificationOutputTransform, # noqa: F401
|
| 1524 |
+
ImageClassificationParameters, # noqa: F401
|
| 1525 |
+
ImageSegmentationInput, # noqa: F401
|
| 1526 |
+
ImageSegmentationOutputElement, # noqa: F401
|
| 1527 |
+
ImageSegmentationParameters, # noqa: F401
|
| 1528 |
+
ImageSegmentationSubtask, # noqa: F401
|
| 1529 |
+
ImageTextToImageInput, # noqa: F401
|
| 1530 |
+
ImageTextToImageOutput, # noqa: F401
|
| 1531 |
+
ImageTextToImageParameters, # noqa: F401
|
| 1532 |
+
ImageTextToImageTargetSize, # noqa: F401
|
| 1533 |
+
ImageTextToVideoInput, # noqa: F401
|
| 1534 |
+
ImageTextToVideoOutput, # noqa: F401
|
| 1535 |
+
ImageTextToVideoParameters, # noqa: F401
|
| 1536 |
+
ImageTextToVideoTargetSize, # noqa: F401
|
| 1537 |
+
ImageToImageInput, # noqa: F401
|
| 1538 |
+
ImageToImageOutput, # noqa: F401
|
| 1539 |
+
ImageToImageParameters, # noqa: F401
|
| 1540 |
+
ImageToImageTargetSize, # noqa: F401
|
| 1541 |
+
ImageToTextEarlyStoppingEnum, # noqa: F401
|
| 1542 |
+
ImageToTextGenerationParameters, # noqa: F401
|
| 1543 |
+
ImageToTextInput, # noqa: F401
|
| 1544 |
+
ImageToTextOutput, # noqa: F401
|
| 1545 |
+
ImageToTextParameters, # noqa: F401
|
| 1546 |
+
ImageToVideoInput, # noqa: F401
|
| 1547 |
+
ImageToVideoOutput, # noqa: F401
|
| 1548 |
+
ImageToVideoParameters, # noqa: F401
|
| 1549 |
+
ImageToVideoTargetSize, # noqa: F401
|
| 1550 |
+
ObjectDetectionBoundingBox, # noqa: F401
|
| 1551 |
+
ObjectDetectionInput, # noqa: F401
|
| 1552 |
+
ObjectDetectionOutputElement, # noqa: F401
|
| 1553 |
+
ObjectDetectionParameters, # noqa: F401
|
| 1554 |
+
Padding, # noqa: F401
|
| 1555 |
+
QuestionAnsweringInput, # noqa: F401
|
| 1556 |
+
QuestionAnsweringInputData, # noqa: F401
|
| 1557 |
+
QuestionAnsweringOutputElement, # noqa: F401
|
| 1558 |
+
QuestionAnsweringParameters, # noqa: F401
|
| 1559 |
+
SentenceSimilarityInput, # noqa: F401
|
| 1560 |
+
SentenceSimilarityInputData, # noqa: F401
|
| 1561 |
+
SummarizationInput, # noqa: F401
|
| 1562 |
+
SummarizationOutput, # noqa: F401
|
| 1563 |
+
SummarizationParameters, # noqa: F401
|
| 1564 |
+
SummarizationTruncationStrategy, # noqa: F401
|
| 1565 |
+
TableQuestionAnsweringInput, # noqa: F401
|
| 1566 |
+
TableQuestionAnsweringInputData, # noqa: F401
|
| 1567 |
+
TableQuestionAnsweringOutputElement, # noqa: F401
|
| 1568 |
+
TableQuestionAnsweringParameters, # noqa: F401
|
| 1569 |
+
Text2TextGenerationInput, # noqa: F401
|
| 1570 |
+
Text2TextGenerationOutput, # noqa: F401
|
| 1571 |
+
Text2TextGenerationParameters, # noqa: F401
|
| 1572 |
+
Text2TextGenerationTruncationStrategy, # noqa: F401
|
| 1573 |
+
TextClassificationInput, # noqa: F401
|
| 1574 |
+
TextClassificationOutputElement, # noqa: F401
|
| 1575 |
+
TextClassificationOutputTransform, # noqa: F401
|
| 1576 |
+
TextClassificationParameters, # noqa: F401
|
| 1577 |
+
TextGenerationInput, # noqa: F401
|
| 1578 |
+
TextGenerationInputGenerateParameters, # noqa: F401
|
| 1579 |
+
TextGenerationInputGrammarType, # noqa: F401
|
| 1580 |
+
TextGenerationOutput, # noqa: F401
|
| 1581 |
+
TextGenerationOutputBestOfSequence, # noqa: F401
|
| 1582 |
+
TextGenerationOutputDetails, # noqa: F401
|
| 1583 |
+
TextGenerationOutputFinishReason, # noqa: F401
|
| 1584 |
+
TextGenerationOutputPrefillToken, # noqa: F401
|
| 1585 |
+
TextGenerationOutputToken, # noqa: F401
|
| 1586 |
+
TextGenerationStreamOutput, # noqa: F401
|
| 1587 |
+
TextGenerationStreamOutputStreamDetails, # noqa: F401
|
| 1588 |
+
TextGenerationStreamOutputToken, # noqa: F401
|
| 1589 |
+
TextToAudioEarlyStoppingEnum, # noqa: F401
|
| 1590 |
+
TextToAudioGenerationParameters, # noqa: F401
|
| 1591 |
+
TextToAudioInput, # noqa: F401
|
| 1592 |
+
TextToAudioOutput, # noqa: F401
|
| 1593 |
+
TextToAudioParameters, # noqa: F401
|
| 1594 |
+
TextToImageInput, # noqa: F401
|
| 1595 |
+
TextToImageOutput, # noqa: F401
|
| 1596 |
+
TextToImageParameters, # noqa: F401
|
| 1597 |
+
TextToSpeechEarlyStoppingEnum, # noqa: F401
|
| 1598 |
+
TextToSpeechGenerationParameters, # noqa: F401
|
| 1599 |
+
TextToSpeechInput, # noqa: F401
|
| 1600 |
+
TextToSpeechOutput, # noqa: F401
|
| 1601 |
+
TextToSpeechParameters, # noqa: F401
|
| 1602 |
+
TextToVideoInput, # noqa: F401
|
| 1603 |
+
TextToVideoOutput, # noqa: F401
|
| 1604 |
+
TextToVideoParameters, # noqa: F401
|
| 1605 |
+
TokenClassificationAggregationStrategy, # noqa: F401
|
| 1606 |
+
TokenClassificationInput, # noqa: F401
|
| 1607 |
+
TokenClassificationOutputElement, # noqa: F401
|
| 1608 |
+
TokenClassificationParameters, # noqa: F401
|
| 1609 |
+
TranslationInput, # noqa: F401
|
| 1610 |
+
TranslationOutput, # noqa: F401
|
| 1611 |
+
TranslationParameters, # noqa: F401
|
| 1612 |
+
TranslationTruncationStrategy, # noqa: F401
|
| 1613 |
+
TypeEnum, # noqa: F401
|
| 1614 |
+
VideoClassificationInput, # noqa: F401
|
| 1615 |
+
VideoClassificationOutputElement, # noqa: F401
|
| 1616 |
+
VideoClassificationOutputTransform, # noqa: F401
|
| 1617 |
+
VideoClassificationParameters, # noqa: F401
|
| 1618 |
+
VisualQuestionAnsweringInput, # noqa: F401
|
| 1619 |
+
VisualQuestionAnsweringInputData, # noqa: F401
|
| 1620 |
+
VisualQuestionAnsweringOutputElement, # noqa: F401
|
| 1621 |
+
VisualQuestionAnsweringParameters, # noqa: F401
|
| 1622 |
+
ZeroShotClassificationInput, # noqa: F401
|
| 1623 |
+
ZeroShotClassificationOutputElement, # noqa: F401
|
| 1624 |
+
ZeroShotClassificationParameters, # noqa: F401
|
| 1625 |
+
ZeroShotImageClassificationInput, # noqa: F401
|
| 1626 |
+
ZeroShotImageClassificationOutputElement, # noqa: F401
|
| 1627 |
+
ZeroShotImageClassificationParameters, # noqa: F401
|
| 1628 |
+
ZeroShotObjectDetectionBoundingBox, # noqa: F401
|
| 1629 |
+
ZeroShotObjectDetectionInput, # noqa: F401
|
| 1630 |
+
ZeroShotObjectDetectionOutputElement, # noqa: F401
|
| 1631 |
+
ZeroShotObjectDetectionParameters, # noqa: F401
|
| 1632 |
+
)
|
| 1633 |
+
from .inference._mcp.agent import Agent # noqa: F401
|
| 1634 |
+
from .inference._mcp.mcp_client import MCPClient # noqa: F401
|
| 1635 |
+
from .repocard import (
|
| 1636 |
+
DatasetCard, # noqa: F401
|
| 1637 |
+
ModelCard, # noqa: F401
|
| 1638 |
+
RepoCard, # noqa: F401
|
| 1639 |
+
SpaceCard, # noqa: F401
|
| 1640 |
+
metadata_eval_result, # noqa: F401
|
| 1641 |
+
metadata_load, # noqa: F401
|
| 1642 |
+
metadata_save, # noqa: F401
|
| 1643 |
+
metadata_update, # noqa: F401
|
| 1644 |
+
)
|
| 1645 |
+
from .repocard_data import (
|
| 1646 |
+
CardData, # noqa: F401
|
| 1647 |
+
DatasetCardData, # noqa: F401
|
| 1648 |
+
EvalResult, # noqa: F401
|
| 1649 |
+
ModelCardData, # noqa: F401
|
| 1650 |
+
SpaceCardData, # noqa: F401
|
| 1651 |
+
)
|
| 1652 |
+
from .serialization import (
|
| 1653 |
+
StateDictSplit, # noqa: F401
|
| 1654 |
+
get_torch_storage_id, # noqa: F401
|
| 1655 |
+
get_torch_storage_size, # noqa: F401
|
| 1656 |
+
load_state_dict_from_file, # noqa: F401
|
| 1657 |
+
load_torch_model, # noqa: F401
|
| 1658 |
+
save_torch_model, # noqa: F401
|
| 1659 |
+
save_torch_state_dict, # noqa: F401
|
| 1660 |
+
split_state_dict_into_shards_factory, # noqa: F401
|
| 1661 |
+
split_torch_state_dict_into_shards, # noqa: F401
|
| 1662 |
+
)
|
| 1663 |
+
from .serialization._dduf import (
|
| 1664 |
+
DDUFEntry, # noqa: F401
|
| 1665 |
+
export_entries_as_dduf, # noqa: F401
|
| 1666 |
+
export_folder_as_dduf, # noqa: F401
|
| 1667 |
+
read_dduf_file, # noqa: F401
|
| 1668 |
+
)
|
| 1669 |
+
from .utils import (
|
| 1670 |
+
ASYNC_CLIENT_FACTORY_T, # noqa: F401
|
| 1671 |
+
CLIENT_FACTORY_T, # noqa: F401
|
| 1672 |
+
CachedFileInfo, # noqa: F401
|
| 1673 |
+
CachedRepoInfo, # noqa: F401
|
| 1674 |
+
CachedRevisionInfo, # noqa: F401
|
| 1675 |
+
CacheNotFound, # noqa: F401
|
| 1676 |
+
CorruptedCacheException, # noqa: F401
|
| 1677 |
+
DeleteCacheStrategy, # noqa: F401
|
| 1678 |
+
HFCacheInfo, # noqa: F401
|
| 1679 |
+
cached_assets_path, # noqa: F401
|
| 1680 |
+
close_session, # noqa: F401
|
| 1681 |
+
dump_environment_info, # noqa: F401
|
| 1682 |
+
get_async_session, # noqa: F401
|
| 1683 |
+
get_session, # noqa: F401
|
| 1684 |
+
get_token, # noqa: F401
|
| 1685 |
+
hf_raise_for_status, # noqa: F401
|
| 1686 |
+
logging, # noqa: F401
|
| 1687 |
+
scan_cache_dir, # noqa: F401
|
| 1688 |
+
set_async_client_factory, # noqa: F401
|
| 1689 |
+
set_client_factory, # noqa: F401
|
| 1690 |
+
)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_buckets.py
ADDED
|
@@ -0,0 +1,1177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2026-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 |
+
"""Shared logic for bucket operations.
|
| 16 |
+
|
| 17 |
+
This module contains the core buckets logic used by both the CLI and the Python API.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import fnmatch
|
| 21 |
+
import json
|
| 22 |
+
import mimetypes
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from dataclasses import dataclass, field
|
| 27 |
+
from datetime import datetime, timezone
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import TYPE_CHECKING, Any, Iterator, Literal, Optional, Union
|
| 30 |
+
|
| 31 |
+
from . import constants, logging
|
| 32 |
+
from .errors import BucketNotFoundError
|
| 33 |
+
from .utils import XetFileData, disable_progress_bars, enable_progress_bars, parse_datetime
|
| 34 |
+
from .utils._terminal import StatusLine
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
if TYPE_CHECKING:
|
| 38 |
+
from .hf_api import HfApi
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
logger = logging.get_logger(__name__)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
BUCKET_PREFIX = "hf://buckets/"
|
| 45 |
+
_SYNC_TIME_WINDOW_MS = 1000 # 1s safety-window for file modification time comparisons
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# =============================================================================
|
| 49 |
+
# Bucket data structures
|
| 50 |
+
# =============================================================================
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _split_bucket_id_and_prefix(path: str) -> tuple[str, str]:
|
| 54 |
+
"""Split 'namespace/name(/optional/prefix)' into ('namespace/name', 'prefix').
|
| 55 |
+
|
| 56 |
+
Returns (bucket_id, prefix) where prefix may be empty string.
|
| 57 |
+
Raises ValueError if path doesn't contain at least namespace/name.
|
| 58 |
+
"""
|
| 59 |
+
parts = path.split("/", 2)
|
| 60 |
+
if len(parts) < 2 or not parts[0] or not parts[1]:
|
| 61 |
+
raise ValueError(f"Invalid bucket path: '{path}'. Expected format: namespace/bucket_name")
|
| 62 |
+
bucket_id = f"{parts[0]}/{parts[1]}"
|
| 63 |
+
prefix = parts[2] if len(parts) > 2 else ""
|
| 64 |
+
return bucket_id, prefix
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class BucketInfo:
|
| 69 |
+
"""
|
| 70 |
+
Contains information about a bucket on the Hub. This object is returned by [`bucket_info`] and [`list_buckets`].
|
| 71 |
+
|
| 72 |
+
Attributes:
|
| 73 |
+
id (`str`):
|
| 74 |
+
ID of the bucket.
|
| 75 |
+
private (`bool`):
|
| 76 |
+
Is the bucket private.
|
| 77 |
+
created_at (`datetime`):
|
| 78 |
+
Date of creation of the bucket on the Hub.
|
| 79 |
+
size (`int`):
|
| 80 |
+
Size of the bucket in bytes.
|
| 81 |
+
total_files (`int`):
|
| 82 |
+
Total number of files in the bucket.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
id: str
|
| 86 |
+
private: bool
|
| 87 |
+
created_at: datetime
|
| 88 |
+
size: int
|
| 89 |
+
total_files: int
|
| 90 |
+
|
| 91 |
+
def __init__(self, **kwargs):
|
| 92 |
+
self.id = kwargs.pop("id")
|
| 93 |
+
self.private = kwargs.pop("private")
|
| 94 |
+
self.created_at = parse_datetime(kwargs.pop("createdAt"))
|
| 95 |
+
self.size = kwargs.pop("size")
|
| 96 |
+
self.total_files = kwargs.pop("totalFiles")
|
| 97 |
+
self.__dict__.update(**kwargs)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@dataclass
|
| 101 |
+
class _BucketAddFile:
|
| 102 |
+
source: Union[str, Path, bytes]
|
| 103 |
+
destination: str
|
| 104 |
+
|
| 105 |
+
xet_hash: Optional[str] = field(default=None)
|
| 106 |
+
size: Optional[int] = field(default=None)
|
| 107 |
+
mtime: int = field(init=False)
|
| 108 |
+
content_type: Optional[str] = field(init=False)
|
| 109 |
+
|
| 110 |
+
def __post_init__(self) -> None:
|
| 111 |
+
self.content_type = None
|
| 112 |
+
if isinstance(self.source, (str, Path)): # guess content type from source path
|
| 113 |
+
self.content_type = mimetypes.guess_type(self.source)[0]
|
| 114 |
+
if self.content_type is None: # or default to destination path content type
|
| 115 |
+
self.content_type = mimetypes.guess_type(self.destination)[0]
|
| 116 |
+
|
| 117 |
+
self.mtime = int(
|
| 118 |
+
os.path.getmtime(self.source) * 1000 if not isinstance(self.source, bytes) else time.time() * 1000
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class _BucketDeleteFile:
|
| 124 |
+
path: str
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
@dataclass(frozen=True)
|
| 128 |
+
class BucketFileMetadata:
|
| 129 |
+
"""Data structure containing information about a file in a bucket.
|
| 130 |
+
|
| 131 |
+
Returned by [`get_bucket_file_metadata`].
|
| 132 |
+
|
| 133 |
+
Args:
|
| 134 |
+
size (`int`):
|
| 135 |
+
Size of the file in bytes.
|
| 136 |
+
xet_file_data (`XetFileData`):
|
| 137 |
+
Xet information for the file (hash and refresh route).
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
size: int
|
| 141 |
+
xet_file_data: XetFileData
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@dataclass
|
| 145 |
+
class BucketUrl:
|
| 146 |
+
"""Describes a bucket URL on the Hub.
|
| 147 |
+
|
| 148 |
+
`BucketUrl` is returned by [`create_bucket`]. At initialization, the URL is parsed to populate properties:
|
| 149 |
+
- endpoint (`str`)
|
| 150 |
+
- namespace (`str`)
|
| 151 |
+
- bucket_id (`str`)
|
| 152 |
+
- url (`str`)
|
| 153 |
+
- handle (`str`)
|
| 154 |
+
|
| 155 |
+
Args:
|
| 156 |
+
url (`str`):
|
| 157 |
+
String value of the bucket url.
|
| 158 |
+
endpoint (`str`, *optional*):
|
| 159 |
+
Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| 160 |
+
"""
|
| 161 |
+
|
| 162 |
+
url: str
|
| 163 |
+
endpoint: str = ""
|
| 164 |
+
namespace: str = field(init=False)
|
| 165 |
+
bucket_id: str = field(init=False)
|
| 166 |
+
handle: str = field(init=False)
|
| 167 |
+
|
| 168 |
+
def __post_init__(self) -> None:
|
| 169 |
+
self.endpoint = self.endpoint or constants.ENDPOINT
|
| 170 |
+
|
| 171 |
+
# Parse URL: expected format is `{endpoint}/buckets/{namespace}/{bucket_name}`
|
| 172 |
+
url_path = self.url.replace(self.endpoint, "").strip("/")
|
| 173 |
+
# Remove leading "buckets/" prefix
|
| 174 |
+
if url_path.startswith("buckets/"):
|
| 175 |
+
url_path = url_path[len("buckets/") :]
|
| 176 |
+
bucket_id, prefix = _split_bucket_id_and_prefix(url_path)
|
| 177 |
+
if prefix:
|
| 178 |
+
raise ValueError(f"Unable to parse bucket URL: {self.url}")
|
| 179 |
+
self.namespace = bucket_id.split("/")[0]
|
| 180 |
+
self.bucket_id = bucket_id
|
| 181 |
+
|
| 182 |
+
self.handle = f"hf://buckets/{self.bucket_id}"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
@dataclass
|
| 186 |
+
class BucketFile:
|
| 187 |
+
"""
|
| 188 |
+
Contains information about a file in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| 189 |
+
|
| 190 |
+
Similar to [`RepoFile`] but for files in buckets.
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
type: Literal["file"]
|
| 194 |
+
path: str
|
| 195 |
+
size: int
|
| 196 |
+
xet_hash: str
|
| 197 |
+
mtime: Optional[datetime]
|
| 198 |
+
uploaded_at: Optional[datetime]
|
| 199 |
+
|
| 200 |
+
def __init__(self, **kwargs):
|
| 201 |
+
self.type = kwargs.pop("type")
|
| 202 |
+
self.path = kwargs.pop("path")
|
| 203 |
+
self.size = kwargs.pop("size")
|
| 204 |
+
self.xet_hash = kwargs.pop("xetHash")
|
| 205 |
+
mtime = kwargs.pop("mtime", None)
|
| 206 |
+
self.mtime = parse_datetime(mtime) if mtime else None
|
| 207 |
+
uploaded_at = kwargs.pop("uploadedAt", None)
|
| 208 |
+
self.uploaded_at = parse_datetime(uploaded_at) if uploaded_at else None
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
@dataclass
|
| 212 |
+
class BucketFolder:
|
| 213 |
+
"""
|
| 214 |
+
Contains information about a directory in a bucket on the Hub. This object is returned by [`list_bucket_tree`].
|
| 215 |
+
|
| 216 |
+
Similar to [`RepoFolder`] but for directories in buckets.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
type: Literal["directory"]
|
| 220 |
+
path: str
|
| 221 |
+
uploaded_at: Optional[datetime]
|
| 222 |
+
|
| 223 |
+
def __init__(self, **kwargs):
|
| 224 |
+
self.type = kwargs.pop("type")
|
| 225 |
+
self.path = kwargs.pop("path")
|
| 226 |
+
uploaded_at = kwargs.pop("uploadedAt", None) or kwargs.pop("uploaded_at", None)
|
| 227 |
+
self.uploaded_at = (
|
| 228 |
+
(uploaded_at if isinstance(uploaded_at, datetime) else parse_datetime(uploaded_at))
|
| 229 |
+
if uploaded_at
|
| 230 |
+
else None
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# =============================================================================
|
| 235 |
+
# Bucket path parsing
|
| 236 |
+
# =============================================================================
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _parse_bucket_path(path: str) -> tuple[str, str]:
|
| 240 |
+
"""Parse a bucket path like hf://buckets/namespace/bucket_name/prefix into (bucket_id, prefix).
|
| 241 |
+
|
| 242 |
+
Returns:
|
| 243 |
+
tuple: (bucket_id, prefix) where bucket_id is "namespace/bucket_name" and prefix may be empty string.
|
| 244 |
+
"""
|
| 245 |
+
if not path.startswith(BUCKET_PREFIX):
|
| 246 |
+
raise ValueError(f"Invalid bucket path: {path}. Must start with {BUCKET_PREFIX}")
|
| 247 |
+
return _split_bucket_id_and_prefix(path.removeprefix(BUCKET_PREFIX))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _is_bucket_path(path: str) -> bool:
|
| 251 |
+
"""Check if a path is a bucket path."""
|
| 252 |
+
return path.startswith(BUCKET_PREFIX)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# =============================================================================
|
| 256 |
+
# Sync data structures
|
| 257 |
+
# =============================================================================
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@dataclass
|
| 261 |
+
class SyncOperation:
|
| 262 |
+
"""Represents a sync operation to be performed."""
|
| 263 |
+
|
| 264 |
+
action: Literal["upload", "download", "delete", "skip"]
|
| 265 |
+
path: str
|
| 266 |
+
size: Optional[int] = None
|
| 267 |
+
reason: str = ""
|
| 268 |
+
local_mtime: Optional[str] = None
|
| 269 |
+
remote_mtime: Optional[str] = None
|
| 270 |
+
bucket_file: Optional[BucketFile] = None # BucketFile when available (not serialized to plan file)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
@dataclass
|
| 274 |
+
class SyncPlan:
|
| 275 |
+
"""Represents a complete sync plan."""
|
| 276 |
+
|
| 277 |
+
source: str
|
| 278 |
+
dest: str
|
| 279 |
+
timestamp: str
|
| 280 |
+
operations: list[SyncOperation] = field(default_factory=list)
|
| 281 |
+
|
| 282 |
+
def summary(self) -> dict[str, Union[int, str]]:
|
| 283 |
+
uploads = sum(1 for op in self.operations if op.action == "upload")
|
| 284 |
+
downloads = sum(1 for op in self.operations if op.action == "download")
|
| 285 |
+
deletes = sum(1 for op in self.operations if op.action == "delete")
|
| 286 |
+
skips = sum(1 for op in self.operations if op.action == "skip")
|
| 287 |
+
total_size = sum(op.size or 0 for op in self.operations if op.action in ("upload", "download"))
|
| 288 |
+
return {
|
| 289 |
+
"uploads": uploads,
|
| 290 |
+
"downloads": downloads,
|
| 291 |
+
"deletes": deletes,
|
| 292 |
+
"skips": skips,
|
| 293 |
+
"total_size": total_size,
|
| 294 |
+
}
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
# =============================================================================
|
| 298 |
+
# Filter matching
|
| 299 |
+
# =============================================================================
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
class FilterMatcher:
|
| 303 |
+
"""Matches file paths against include/exclude patterns."""
|
| 304 |
+
|
| 305 |
+
def __init__(
|
| 306 |
+
self,
|
| 307 |
+
include_patterns: Optional[list[str]] = None,
|
| 308 |
+
exclude_patterns: Optional[list[str]] = None,
|
| 309 |
+
filter_rules: Optional[list[tuple[str, str]]] = None,
|
| 310 |
+
):
|
| 311 |
+
"""Initialize the filter matcher.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
include_patterns: Patterns to include (from --include)
|
| 315 |
+
exclude_patterns: Patterns to exclude (from --exclude)
|
| 316 |
+
filter_rules: Rules from filter file as list of ("+"/"-", pattern) tuples
|
| 317 |
+
"""
|
| 318 |
+
self.include_patterns = include_patterns or []
|
| 319 |
+
self.exclude_patterns = exclude_patterns or []
|
| 320 |
+
self.filter_rules = filter_rules or []
|
| 321 |
+
|
| 322 |
+
def matches(self, path: str) -> bool:
|
| 323 |
+
"""Check if a path should be included based on the filter rules.
|
| 324 |
+
|
| 325 |
+
Filtering rules:
|
| 326 |
+
- Filters are evaluated in order, first matching rule decides
|
| 327 |
+
- If no rules match, include by default (unless include patterns are specified)
|
| 328 |
+
"""
|
| 329 |
+
# First check filter rules from file (in order)
|
| 330 |
+
for sign, pattern in self.filter_rules:
|
| 331 |
+
if fnmatch.fnmatch(path, pattern):
|
| 332 |
+
return sign == "+"
|
| 333 |
+
|
| 334 |
+
# Then check CLI patterns
|
| 335 |
+
for pattern in self.exclude_patterns:
|
| 336 |
+
if fnmatch.fnmatch(path, pattern):
|
| 337 |
+
return False
|
| 338 |
+
|
| 339 |
+
for pattern in self.include_patterns:
|
| 340 |
+
if fnmatch.fnmatch(path, pattern):
|
| 341 |
+
return True
|
| 342 |
+
|
| 343 |
+
# If include patterns were specified but none matched, exclude
|
| 344 |
+
if self.include_patterns:
|
| 345 |
+
return False
|
| 346 |
+
|
| 347 |
+
# Default: include
|
| 348 |
+
return True
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _parse_filter_file(filter_file: str) -> list[tuple[str, str]]:
|
| 352 |
+
"""Parse a filter file and return a list of (sign, pattern) tuples.
|
| 353 |
+
|
| 354 |
+
Filter file format:
|
| 355 |
+
- Lines starting with "+" are include patterns
|
| 356 |
+
- Lines starting with "-" are exclude patterns
|
| 357 |
+
- Empty lines and lines starting with "#" are ignored
|
| 358 |
+
"""
|
| 359 |
+
rules = []
|
| 360 |
+
with open(filter_file) as f:
|
| 361 |
+
for line in f:
|
| 362 |
+
line = line.strip()
|
| 363 |
+
if not line or line.startswith("#"):
|
| 364 |
+
continue
|
| 365 |
+
if line.startswith("+"):
|
| 366 |
+
rules.append(("+", line[1:].strip()))
|
| 367 |
+
elif line.startswith("-"):
|
| 368 |
+
rules.append(("-", line[1:].strip()))
|
| 369 |
+
else:
|
| 370 |
+
# Default to include if no prefix
|
| 371 |
+
rules.append(("+", line))
|
| 372 |
+
return rules
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
# =============================================================================
|
| 376 |
+
# File listing
|
| 377 |
+
# =============================================================================
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _list_local_files(local_path: str) -> Iterator[tuple[str, int, float]]:
|
| 381 |
+
"""List all files in a local directory.
|
| 382 |
+
|
| 383 |
+
Yields:
|
| 384 |
+
tuple: (relative_path, size, mtime_ms) for each file
|
| 385 |
+
"""
|
| 386 |
+
local_path = os.path.abspath(local_path)
|
| 387 |
+
if not os.path.isdir(local_path):
|
| 388 |
+
raise ValueError(f"Local path must be a directory: {local_path}")
|
| 389 |
+
|
| 390 |
+
for root, _, files in os.walk(local_path):
|
| 391 |
+
for filename in files:
|
| 392 |
+
full_path = os.path.join(root, filename)
|
| 393 |
+
rel_path = os.path.relpath(full_path, local_path)
|
| 394 |
+
# Normalize to forward slashes for consistency
|
| 395 |
+
rel_path = rel_path.replace(os.sep, "/")
|
| 396 |
+
size = os.path.getsize(full_path)
|
| 397 |
+
mtime_ms = os.path.getmtime(full_path) * 1000
|
| 398 |
+
yield rel_path, size, mtime_ms
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def _list_remote_files(api: "HfApi", bucket_id: str, prefix: str) -> Iterator[tuple[str, int, float, Any]]:
|
| 402 |
+
"""List all files in a bucket with a given prefix.
|
| 403 |
+
|
| 404 |
+
Yields:
|
| 405 |
+
tuple: (relative_path, size, mtime_ms, bucket_file) for each file.
|
| 406 |
+
bucket_file is the BucketFile object from list_bucket_tree.
|
| 407 |
+
"""
|
| 408 |
+
for item in api.list_bucket_tree(bucket_id, prefix=prefix or None, recursive=True):
|
| 409 |
+
if isinstance(item, BucketFolder):
|
| 410 |
+
continue
|
| 411 |
+
path = item.path
|
| 412 |
+
# Remove prefix from path to get relative path
|
| 413 |
+
# Only strip prefix if it's followed by "/" (directory boundary) or is exact match
|
| 414 |
+
if prefix:
|
| 415 |
+
if path.startswith(prefix + "/"):
|
| 416 |
+
rel_path = path[len(prefix) + 1 :]
|
| 417 |
+
elif path == prefix:
|
| 418 |
+
# Exact match: the file IS the prefix (e.g., single file download)
|
| 419 |
+
rel_path = path.rsplit("/", 1)[-1] if "/" in path else path
|
| 420 |
+
else:
|
| 421 |
+
# Path doesn't match prefix pattern (e.g., "submarine.txt" for prefix "sub")
|
| 422 |
+
# Skip this file - it was returned by the API but doesn't belong to this prefix
|
| 423 |
+
continue
|
| 424 |
+
else:
|
| 425 |
+
rel_path = path
|
| 426 |
+
mtime_ms = item.mtime.timestamp() * 1000 if item.mtime else 0
|
| 427 |
+
yield rel_path, item.size, mtime_ms, item
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
# =============================================================================
|
| 431 |
+
# Sync plan computation
|
| 432 |
+
# =============================================================================
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _mtime_to_iso(mtime_ms: float) -> str:
|
| 436 |
+
"""Convert mtime in milliseconds to ISO format string."""
|
| 437 |
+
return datetime.fromtimestamp(mtime_ms / 1000, tz=timezone.utc).isoformat()
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def _compare_files_for_sync(
|
| 441 |
+
*,
|
| 442 |
+
path: str,
|
| 443 |
+
action: Literal["upload", "download"],
|
| 444 |
+
source_size: int,
|
| 445 |
+
source_mtime: float,
|
| 446 |
+
dest_size: int,
|
| 447 |
+
dest_mtime: float,
|
| 448 |
+
source_newer_label: str,
|
| 449 |
+
dest_newer_label: str,
|
| 450 |
+
ignore_sizes: bool,
|
| 451 |
+
ignore_times: bool,
|
| 452 |
+
ignore_existing: bool,
|
| 453 |
+
bucket_file: Optional[Any] = None,
|
| 454 |
+
) -> SyncOperation:
|
| 455 |
+
"""Compare source and dest files and return the appropriate sync operation.
|
| 456 |
+
|
| 457 |
+
This is a unified helper for both upload and download directions.
|
| 458 |
+
|
| 459 |
+
Args:
|
| 460 |
+
path: Relative file path
|
| 461 |
+
action: "upload" or "download"
|
| 462 |
+
source_size: Size of the source file (bytes)
|
| 463 |
+
source_mtime: Mtime of the source file (milliseconds)
|
| 464 |
+
dest_size: Size of the destination file (bytes)
|
| 465 |
+
dest_mtime: Mtime of the destination file (milliseconds)
|
| 466 |
+
source_newer_label: Label when source is newer (e.g., "local newer" or "remote newer")
|
| 467 |
+
dest_newer_label: Label when dest is newer (e.g., "remote newer" or "local newer")
|
| 468 |
+
ignore_sizes: Only compare mtime
|
| 469 |
+
ignore_times: Only compare size
|
| 470 |
+
ignore_existing: Skip files that exist on receiver
|
| 471 |
+
bucket_file: BucketFile object (for downloads only)
|
| 472 |
+
|
| 473 |
+
Returns:
|
| 474 |
+
SyncOperation describing the action to take
|
| 475 |
+
"""
|
| 476 |
+
local_mtime_iso = _mtime_to_iso(source_mtime if action == "upload" else dest_mtime)
|
| 477 |
+
remote_mtime_iso = _mtime_to_iso(dest_mtime if action == "upload" else source_mtime)
|
| 478 |
+
|
| 479 |
+
base_kwargs: dict[str, Any] = {
|
| 480 |
+
"path": path,
|
| 481 |
+
"size": source_size,
|
| 482 |
+
"local_mtime": local_mtime_iso,
|
| 483 |
+
"remote_mtime": remote_mtime_iso,
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
if ignore_existing:
|
| 487 |
+
return SyncOperation(action="skip", reason="exists on receiver (--ignore-existing)", **base_kwargs)
|
| 488 |
+
|
| 489 |
+
size_differs = source_size != dest_size
|
| 490 |
+
source_newer = (source_mtime - dest_mtime) > _SYNC_TIME_WINDOW_MS
|
| 491 |
+
|
| 492 |
+
if ignore_sizes:
|
| 493 |
+
if source_newer:
|
| 494 |
+
return SyncOperation(action=action, reason=source_newer_label, bucket_file=bucket_file, **base_kwargs)
|
| 495 |
+
else:
|
| 496 |
+
dest_newer = (dest_mtime - source_mtime) > _SYNC_TIME_WINDOW_MS
|
| 497 |
+
skip_reason = dest_newer_label if dest_newer else "same mtime"
|
| 498 |
+
return SyncOperation(action="skip", reason=skip_reason, **base_kwargs)
|
| 499 |
+
elif ignore_times:
|
| 500 |
+
if size_differs:
|
| 501 |
+
return SyncOperation(action=action, reason="size differs", bucket_file=bucket_file, **base_kwargs)
|
| 502 |
+
else:
|
| 503 |
+
return SyncOperation(action="skip", reason="same size", **base_kwargs)
|
| 504 |
+
else:
|
| 505 |
+
if size_differs or source_newer:
|
| 506 |
+
reason = "size differs" if size_differs else source_newer_label
|
| 507 |
+
return SyncOperation(action=action, reason=reason, bucket_file=bucket_file, **base_kwargs)
|
| 508 |
+
else:
|
| 509 |
+
return SyncOperation(action="skip", reason="identical", **base_kwargs)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _compute_sync_plan(
|
| 513 |
+
source: str,
|
| 514 |
+
dest: str,
|
| 515 |
+
api: "HfApi",
|
| 516 |
+
delete: bool = False,
|
| 517 |
+
ignore_times: bool = False,
|
| 518 |
+
ignore_sizes: bool = False,
|
| 519 |
+
existing: bool = False,
|
| 520 |
+
ignore_existing: bool = False,
|
| 521 |
+
filter_matcher: Optional[FilterMatcher] = None,
|
| 522 |
+
status: Optional[Any] = None,
|
| 523 |
+
) -> SyncPlan:
|
| 524 |
+
"""Compute the sync plan by comparing source and destination.
|
| 525 |
+
|
| 526 |
+
Returns:
|
| 527 |
+
SyncPlan with all operations to be performed
|
| 528 |
+
"""
|
| 529 |
+
filter_matcher = filter_matcher or FilterMatcher()
|
| 530 |
+
is_upload = not _is_bucket_path(source) and _is_bucket_path(dest)
|
| 531 |
+
is_download = _is_bucket_path(source) and not _is_bucket_path(dest)
|
| 532 |
+
|
| 533 |
+
if not is_upload and not is_download:
|
| 534 |
+
raise ValueError("One of source or dest must be a bucket path (hf://buckets/...) and the other must be local.")
|
| 535 |
+
|
| 536 |
+
plan = SyncPlan(
|
| 537 |
+
source=source,
|
| 538 |
+
dest=dest,
|
| 539 |
+
timestamp=datetime.now(timezone.utc).isoformat(),
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
remote_total: Optional[int] = None
|
| 543 |
+
if is_upload:
|
| 544 |
+
# Local -> Remote
|
| 545 |
+
local_path = os.path.abspath(source)
|
| 546 |
+
bucket_id, prefix = _parse_bucket_path(dest)
|
| 547 |
+
|
| 548 |
+
if not os.path.isdir(local_path):
|
| 549 |
+
raise ValueError(f"Source must be a directory: {local_path}")
|
| 550 |
+
|
| 551 |
+
# Get local and remote file lists
|
| 552 |
+
local_files = {}
|
| 553 |
+
for rel_path, size, mtime_ms in _list_local_files(local_path):
|
| 554 |
+
if filter_matcher.matches(rel_path):
|
| 555 |
+
local_files[rel_path] = (size, mtime_ms)
|
| 556 |
+
if status:
|
| 557 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 558 |
+
if status:
|
| 559 |
+
status.done(f"Scanning local directory ({len(local_files)} files)")
|
| 560 |
+
|
| 561 |
+
remote_files = {}
|
| 562 |
+
if status:
|
| 563 |
+
try:
|
| 564 |
+
remote_total = api.bucket_info(bucket_id).total_files
|
| 565 |
+
except Exception:
|
| 566 |
+
pass
|
| 567 |
+
try:
|
| 568 |
+
for rel_path, size, mtime_ms, _ in _list_remote_files(api, bucket_id, prefix):
|
| 569 |
+
if filter_matcher.matches(rel_path):
|
| 570 |
+
remote_files[rel_path] = (size, mtime_ms)
|
| 571 |
+
if status:
|
| 572 |
+
total_str = f"/{remote_total}" if remote_total is not None else ""
|
| 573 |
+
status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
|
| 574 |
+
except BucketNotFoundError:
|
| 575 |
+
# Bucket doesn't exist yet - this is expected for new uploads
|
| 576 |
+
logger.debug(f"Bucket '{bucket_id}' not found, treating as empty.")
|
| 577 |
+
if status:
|
| 578 |
+
status.done(f"Scanning remote bucket ({len(remote_files)} files)")
|
| 579 |
+
|
| 580 |
+
# Compare files
|
| 581 |
+
all_paths = set(local_files.keys()) | set(remote_files.keys())
|
| 582 |
+
if status:
|
| 583 |
+
status.done(f"Comparing files ({len(all_paths)} paths)")
|
| 584 |
+
for path in sorted(all_paths):
|
| 585 |
+
local_info = local_files.get(path)
|
| 586 |
+
remote_info = remote_files.get(path)
|
| 587 |
+
|
| 588 |
+
if local_info and not remote_info:
|
| 589 |
+
# New file
|
| 590 |
+
if existing:
|
| 591 |
+
# --existing: skip new files
|
| 592 |
+
plan.operations.append(
|
| 593 |
+
SyncOperation(
|
| 594 |
+
action="skip",
|
| 595 |
+
path=path,
|
| 596 |
+
size=local_info[0],
|
| 597 |
+
reason="new file (--existing)",
|
| 598 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 599 |
+
)
|
| 600 |
+
)
|
| 601 |
+
else:
|
| 602 |
+
plan.operations.append(
|
| 603 |
+
SyncOperation(
|
| 604 |
+
action="upload",
|
| 605 |
+
path=path,
|
| 606 |
+
size=local_info[0],
|
| 607 |
+
reason="new file",
|
| 608 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 609 |
+
)
|
| 610 |
+
)
|
| 611 |
+
elif local_info and remote_info:
|
| 612 |
+
# File exists in both - use helper to determine action
|
| 613 |
+
local_size, local_mtime = local_info
|
| 614 |
+
remote_size, remote_mtime = remote_info
|
| 615 |
+
plan.operations.append(
|
| 616 |
+
_compare_files_for_sync(
|
| 617 |
+
path=path,
|
| 618 |
+
action="upload",
|
| 619 |
+
source_size=local_size,
|
| 620 |
+
source_mtime=local_mtime,
|
| 621 |
+
dest_size=remote_size,
|
| 622 |
+
dest_mtime=remote_mtime,
|
| 623 |
+
source_newer_label="local newer",
|
| 624 |
+
dest_newer_label="remote newer",
|
| 625 |
+
ignore_sizes=ignore_sizes,
|
| 626 |
+
ignore_times=ignore_times,
|
| 627 |
+
ignore_existing=ignore_existing,
|
| 628 |
+
)
|
| 629 |
+
)
|
| 630 |
+
elif not local_info and remote_info and delete:
|
| 631 |
+
# File only in remote and --delete mode
|
| 632 |
+
plan.operations.append(
|
| 633 |
+
SyncOperation(
|
| 634 |
+
action="delete",
|
| 635 |
+
path=path,
|
| 636 |
+
size=remote_info[0],
|
| 637 |
+
reason="not in source (--delete)",
|
| 638 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 639 |
+
)
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
else:
|
| 643 |
+
# Remote -> Local (download)
|
| 644 |
+
bucket_id, prefix = _parse_bucket_path(source)
|
| 645 |
+
local_path = os.path.abspath(dest)
|
| 646 |
+
|
| 647 |
+
# Get remote and local file lists
|
| 648 |
+
remote_files = {}
|
| 649 |
+
bucket_file_map: dict[str, Any] = {}
|
| 650 |
+
if status:
|
| 651 |
+
try:
|
| 652 |
+
remote_total = api.bucket_info(bucket_id).total_files
|
| 653 |
+
except Exception:
|
| 654 |
+
pass
|
| 655 |
+
for rel_path, size, mtime_ms, bucket_file in _list_remote_files(api, bucket_id, prefix):
|
| 656 |
+
if filter_matcher.matches(rel_path):
|
| 657 |
+
remote_files[rel_path] = (size, mtime_ms)
|
| 658 |
+
bucket_file_map[rel_path] = bucket_file
|
| 659 |
+
if status:
|
| 660 |
+
total_str = f"/{remote_total}" if remote_total is not None else ""
|
| 661 |
+
status.update(f"Scanning remote bucket ({len(remote_files)}{total_str} files)")
|
| 662 |
+
if status:
|
| 663 |
+
status.done(f"Scanning remote bucket ({len(remote_files)} files)")
|
| 664 |
+
|
| 665 |
+
local_files = {}
|
| 666 |
+
if os.path.isdir(local_path):
|
| 667 |
+
for rel_path, size, mtime_ms in _list_local_files(local_path):
|
| 668 |
+
if filter_matcher.matches(rel_path):
|
| 669 |
+
local_files[rel_path] = (size, mtime_ms)
|
| 670 |
+
if status:
|
| 671 |
+
status.update(f"Scanning local directory ({len(local_files)} files)")
|
| 672 |
+
if status:
|
| 673 |
+
status.done(f"Scanning local directory ({len(local_files)} files)")
|
| 674 |
+
|
| 675 |
+
# Compare files
|
| 676 |
+
all_paths = set(remote_files.keys()) | set(local_files.keys())
|
| 677 |
+
if status:
|
| 678 |
+
status.done(f"Comparing files ({len(all_paths)} paths)")
|
| 679 |
+
for path in sorted(all_paths):
|
| 680 |
+
remote_info = remote_files.get(path)
|
| 681 |
+
local_info = local_files.get(path)
|
| 682 |
+
|
| 683 |
+
if remote_info and not local_info:
|
| 684 |
+
# New file
|
| 685 |
+
if existing:
|
| 686 |
+
# --existing: skip new files
|
| 687 |
+
plan.operations.append(
|
| 688 |
+
SyncOperation(
|
| 689 |
+
action="skip",
|
| 690 |
+
path=path,
|
| 691 |
+
size=remote_info[0],
|
| 692 |
+
reason="new file (--existing)",
|
| 693 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 694 |
+
)
|
| 695 |
+
)
|
| 696 |
+
else:
|
| 697 |
+
plan.operations.append(
|
| 698 |
+
SyncOperation(
|
| 699 |
+
action="download",
|
| 700 |
+
path=path,
|
| 701 |
+
size=remote_info[0],
|
| 702 |
+
reason="new file",
|
| 703 |
+
remote_mtime=_mtime_to_iso(remote_info[1]),
|
| 704 |
+
bucket_file=bucket_file_map.get(path),
|
| 705 |
+
)
|
| 706 |
+
)
|
| 707 |
+
elif remote_info and local_info:
|
| 708 |
+
# File exists in both - use helper to determine action
|
| 709 |
+
remote_size, remote_mtime = remote_info
|
| 710 |
+
local_size, local_mtime = local_info
|
| 711 |
+
plan.operations.append(
|
| 712 |
+
_compare_files_for_sync(
|
| 713 |
+
path=path,
|
| 714 |
+
action="download",
|
| 715 |
+
source_size=remote_size,
|
| 716 |
+
source_mtime=remote_mtime,
|
| 717 |
+
dest_size=local_size,
|
| 718 |
+
dest_mtime=local_mtime,
|
| 719 |
+
source_newer_label="remote newer",
|
| 720 |
+
dest_newer_label="local newer",
|
| 721 |
+
ignore_sizes=ignore_sizes,
|
| 722 |
+
ignore_times=ignore_times,
|
| 723 |
+
ignore_existing=ignore_existing,
|
| 724 |
+
bucket_file=bucket_file_map.get(path),
|
| 725 |
+
)
|
| 726 |
+
)
|
| 727 |
+
elif not remote_info and local_info and delete:
|
| 728 |
+
# File only in local and --delete mode
|
| 729 |
+
plan.operations.append(
|
| 730 |
+
SyncOperation(
|
| 731 |
+
action="delete",
|
| 732 |
+
path=path,
|
| 733 |
+
size=local_info[0],
|
| 734 |
+
reason="not in source (--delete)",
|
| 735 |
+
local_mtime=_mtime_to_iso(local_info[1]),
|
| 736 |
+
)
|
| 737 |
+
)
|
| 738 |
+
|
| 739 |
+
return plan
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
# =============================================================================
|
| 743 |
+
# Plan serialization
|
| 744 |
+
# =============================================================================
|
| 745 |
+
|
| 746 |
+
|
| 747 |
+
def _write_plan(plan: SyncPlan, f) -> None:
|
| 748 |
+
"""Write a sync plan as JSONL to a file-like object."""
|
| 749 |
+
# Write header
|
| 750 |
+
header = {
|
| 751 |
+
"type": "header",
|
| 752 |
+
"source": plan.source,
|
| 753 |
+
"dest": plan.dest,
|
| 754 |
+
"timestamp": plan.timestamp,
|
| 755 |
+
"summary": plan.summary(),
|
| 756 |
+
}
|
| 757 |
+
f.write(json.dumps(header) + "\n")
|
| 758 |
+
|
| 759 |
+
# Write operations
|
| 760 |
+
for op in plan.operations:
|
| 761 |
+
op_dict: dict[str, Any] = {
|
| 762 |
+
"type": "operation",
|
| 763 |
+
"action": op.action,
|
| 764 |
+
"path": op.path,
|
| 765 |
+
"reason": op.reason,
|
| 766 |
+
}
|
| 767 |
+
if op.size is not None:
|
| 768 |
+
op_dict["size"] = op.size
|
| 769 |
+
if op.local_mtime is not None:
|
| 770 |
+
op_dict["local_mtime"] = op.local_mtime
|
| 771 |
+
if op.remote_mtime is not None:
|
| 772 |
+
op_dict["remote_mtime"] = op.remote_mtime
|
| 773 |
+
f.write(json.dumps(op_dict) + "\n")
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
def _save_plan(plan: SyncPlan, plan_file: str) -> None:
|
| 777 |
+
"""Save a sync plan to a JSONL file."""
|
| 778 |
+
with open(plan_file, "w") as f:
|
| 779 |
+
_write_plan(plan, f)
|
| 780 |
+
|
| 781 |
+
|
| 782 |
+
def _load_plan(plan_file: str) -> SyncPlan:
|
| 783 |
+
"""Load a sync plan from a JSONL file."""
|
| 784 |
+
with open(plan_file) as f:
|
| 785 |
+
lines = f.readlines()
|
| 786 |
+
|
| 787 |
+
if not lines:
|
| 788 |
+
raise ValueError(f"Empty plan file: {plan_file}")
|
| 789 |
+
|
| 790 |
+
# Parse header
|
| 791 |
+
header = json.loads(lines[0])
|
| 792 |
+
if header.get("type") != "header":
|
| 793 |
+
raise ValueError("Invalid plan file: expected header as first line")
|
| 794 |
+
|
| 795 |
+
plan = SyncPlan(
|
| 796 |
+
source=header["source"],
|
| 797 |
+
dest=header["dest"],
|
| 798 |
+
timestamp=header["timestamp"],
|
| 799 |
+
)
|
| 800 |
+
|
| 801 |
+
# Parse operations
|
| 802 |
+
for line in lines[1:]:
|
| 803 |
+
op_dict = json.loads(line)
|
| 804 |
+
if op_dict.get("type") != "operation":
|
| 805 |
+
continue
|
| 806 |
+
plan.operations.append(
|
| 807 |
+
SyncOperation(
|
| 808 |
+
action=op_dict["action"],
|
| 809 |
+
path=op_dict["path"],
|
| 810 |
+
size=op_dict.get("size"),
|
| 811 |
+
reason=op_dict.get("reason", ""),
|
| 812 |
+
local_mtime=op_dict.get("local_mtime"),
|
| 813 |
+
remote_mtime=op_dict.get("remote_mtime"),
|
| 814 |
+
)
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
return plan
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
# =============================================================================
|
| 821 |
+
# Plan execution
|
| 822 |
+
# =============================================================================
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
def _execute_plan(plan: SyncPlan, api: "HfApi", verbose: bool = False, status: Optional[Any] = None) -> None:
|
| 826 |
+
"""Execute a sync plan."""
|
| 827 |
+
is_upload = not _is_bucket_path(plan.source) and _is_bucket_path(plan.dest)
|
| 828 |
+
is_download = _is_bucket_path(plan.source) and not _is_bucket_path(plan.dest)
|
| 829 |
+
|
| 830 |
+
if is_upload:
|
| 831 |
+
local_path = os.path.abspath(plan.source)
|
| 832 |
+
bucket_id, prefix = _parse_bucket_path(plan.dest)
|
| 833 |
+
prefix = prefix.rstrip("/") # Avoid double slashes in remote paths
|
| 834 |
+
|
| 835 |
+
# Collect operations
|
| 836 |
+
add_files: list[tuple[Union[str, Path, bytes], str]] = []
|
| 837 |
+
delete_paths: list[str] = []
|
| 838 |
+
|
| 839 |
+
for op in plan.operations:
|
| 840 |
+
if op.action == "upload":
|
| 841 |
+
local_file = os.path.join(local_path, op.path)
|
| 842 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 843 |
+
if verbose:
|
| 844 |
+
print(f" Uploading: {op.path} ({op.reason})")
|
| 845 |
+
add_files.append((local_file, remote_path))
|
| 846 |
+
elif op.action == "delete":
|
| 847 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 848 |
+
if verbose:
|
| 849 |
+
print(f" Deleting: {op.path} ({op.reason})")
|
| 850 |
+
delete_paths.append(remote_path)
|
| 851 |
+
elif op.action == "skip" and verbose:
|
| 852 |
+
print(f" Skipping: {op.path} ({op.reason})")
|
| 853 |
+
|
| 854 |
+
# Execute batch operations
|
| 855 |
+
if add_files or delete_paths:
|
| 856 |
+
if status:
|
| 857 |
+
parts = []
|
| 858 |
+
if add_files:
|
| 859 |
+
parts.append(f"uploading {len(add_files)} files")
|
| 860 |
+
if delete_paths:
|
| 861 |
+
parts.append(f"deleting {len(delete_paths)} files")
|
| 862 |
+
status.done(", ".join(parts).capitalize())
|
| 863 |
+
api.batch_bucket_files(
|
| 864 |
+
bucket_id,
|
| 865 |
+
add=add_files or None,
|
| 866 |
+
delete=delete_paths or None,
|
| 867 |
+
)
|
| 868 |
+
|
| 869 |
+
elif is_download:
|
| 870 |
+
bucket_id, prefix = _parse_bucket_path(plan.source)
|
| 871 |
+
prefix = prefix.rstrip("/") # Avoid double slashes in remote paths
|
| 872 |
+
local_path = os.path.abspath(plan.dest)
|
| 873 |
+
|
| 874 |
+
# Ensure local directory exists
|
| 875 |
+
os.makedirs(local_path, exist_ok=True)
|
| 876 |
+
|
| 877 |
+
# Collect download operations
|
| 878 |
+
download_files: list[tuple[Union[str, BucketFile], Union[str, Path]]] = []
|
| 879 |
+
delete_files: list[str] = []
|
| 880 |
+
|
| 881 |
+
for op in plan.operations:
|
| 882 |
+
if op.action == "download":
|
| 883 |
+
local_file = os.path.join(local_path, op.path)
|
| 884 |
+
# Ensure parent directory exists
|
| 885 |
+
os.makedirs(os.path.dirname(local_file), exist_ok=True)
|
| 886 |
+
if verbose:
|
| 887 |
+
print(f" Downloading: {op.path} ({op.reason})")
|
| 888 |
+
# Use BucketFile when available (avoids extra metadata fetch per file)
|
| 889 |
+
if op.bucket_file is not None:
|
| 890 |
+
download_files.append((op.bucket_file, local_file))
|
| 891 |
+
else:
|
| 892 |
+
remote_path = f"{prefix}/{op.path}" if prefix else op.path
|
| 893 |
+
download_files.append((remote_path, local_file))
|
| 894 |
+
elif op.action == "delete":
|
| 895 |
+
local_file = os.path.join(local_path, op.path)
|
| 896 |
+
if verbose:
|
| 897 |
+
print(f" Deleting: {op.path} ({op.reason})")
|
| 898 |
+
delete_files.append(local_file)
|
| 899 |
+
elif op.action == "skip" and verbose:
|
| 900 |
+
print(f" Skipping: {op.path} ({op.reason})")
|
| 901 |
+
|
| 902 |
+
# Execute downloads
|
| 903 |
+
if len(download_files) > 0:
|
| 904 |
+
if status:
|
| 905 |
+
status.done(f"Downloading {len(download_files)} files")
|
| 906 |
+
api.download_bucket_files(bucket_id, download_files)
|
| 907 |
+
|
| 908 |
+
# Execute deletes
|
| 909 |
+
if status and delete_files:
|
| 910 |
+
status.done(f"Deleting {len(delete_files)} local files")
|
| 911 |
+
for file_path in delete_files:
|
| 912 |
+
if os.path.exists(file_path):
|
| 913 |
+
os.remove(file_path)
|
| 914 |
+
# Remove empty parent directories
|
| 915 |
+
parent = os.path.dirname(file_path)
|
| 916 |
+
while parent != local_path:
|
| 917 |
+
try:
|
| 918 |
+
os.rmdir(parent)
|
| 919 |
+
parent = os.path.dirname(parent)
|
| 920 |
+
except OSError:
|
| 921 |
+
break
|
| 922 |
+
|
| 923 |
+
|
| 924 |
+
def _print_plan_summary(plan: SyncPlan) -> None:
|
| 925 |
+
"""Print a summary of the sync plan."""
|
| 926 |
+
summary = plan.summary()
|
| 927 |
+
print(f"Sync plan: {plan.source} -> {plan.dest}")
|
| 928 |
+
print(f" Uploads: {summary['uploads']}")
|
| 929 |
+
print(f" Downloads: {summary['downloads']}")
|
| 930 |
+
print(f" Deletes: {summary['deletes']}")
|
| 931 |
+
print(f" Skips: {summary['skips']}")
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
# =============================================================================
|
| 935 |
+
# Public sync function (Python API)
|
| 936 |
+
# =============================================================================
|
| 937 |
+
|
| 938 |
+
|
| 939 |
+
def sync_bucket_internal(
|
| 940 |
+
source: Optional[str] = None,
|
| 941 |
+
dest: Optional[str] = None,
|
| 942 |
+
*,
|
| 943 |
+
api: "HfApi",
|
| 944 |
+
delete: bool = False,
|
| 945 |
+
ignore_times: bool = False,
|
| 946 |
+
ignore_sizes: bool = False,
|
| 947 |
+
existing: bool = False,
|
| 948 |
+
ignore_existing: bool = False,
|
| 949 |
+
include: Optional[list[str]] = None,
|
| 950 |
+
exclude: Optional[list[str]] = None,
|
| 951 |
+
filter_from: Optional[str] = None,
|
| 952 |
+
plan: Optional[str] = None,
|
| 953 |
+
apply: Optional[str] = None,
|
| 954 |
+
dry_run: bool = False,
|
| 955 |
+
verbose: bool = False,
|
| 956 |
+
quiet: bool = False,
|
| 957 |
+
token: Union[bool, str, None] = None,
|
| 958 |
+
) -> SyncPlan:
|
| 959 |
+
"""Sync files between a local directory and a bucket.
|
| 960 |
+
|
| 961 |
+
This is equivalent to the ``hf buckets sync`` CLI command. One of ``source`` or ``dest`` must be a bucket path
|
| 962 |
+
(``hf://buckets/...``) and the other must be a local directory path.
|
| 963 |
+
|
| 964 |
+
Args:
|
| 965 |
+
source (`str`, *optional*):
|
| 966 |
+
Source path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
|
| 967 |
+
Required unless using ``apply``.
|
| 968 |
+
dest (`str`, *optional*):
|
| 969 |
+
Destination path: local directory or ``hf://buckets/namespace/bucket_name(/prefix)``.
|
| 970 |
+
Required unless using ``apply``.
|
| 971 |
+
api ([`HfApi`]):
|
| 972 |
+
The HfApi instance to use for API calls.
|
| 973 |
+
delete (`bool`, *optional*, defaults to `False`):
|
| 974 |
+
Delete destination files not present in source.
|
| 975 |
+
ignore_times (`bool`, *optional*, defaults to `False`):
|
| 976 |
+
Skip files only based on size, ignoring modification times.
|
| 977 |
+
ignore_sizes (`bool`, *optional*, defaults to `False`):
|
| 978 |
+
Skip files only based on modification times, ignoring sizes.
|
| 979 |
+
existing (`bool`, *optional*, defaults to `False`):
|
| 980 |
+
Skip creating new files on receiver (only update existing files).
|
| 981 |
+
ignore_existing (`bool`, *optional*, defaults to `False`):
|
| 982 |
+
Skip updating files that exist on receiver (only create new files).
|
| 983 |
+
include (`list[str]`, *optional*):
|
| 984 |
+
Include files matching patterns (fnmatch-style).
|
| 985 |
+
exclude (`list[str]`, *optional*):
|
| 986 |
+
Exclude files matching patterns (fnmatch-style).
|
| 987 |
+
filter_from (`str`, *optional*):
|
| 988 |
+
Path to a filter file with include/exclude rules.
|
| 989 |
+
plan (`str`, *optional*):
|
| 990 |
+
Save sync plan to this JSONL file instead of executing.
|
| 991 |
+
apply (`str`, *optional*):
|
| 992 |
+
Apply a previously saved plan file. When set, ``source`` and ``dest`` are not needed.
|
| 993 |
+
dry_run (`bool`, *optional*, defaults to `False`):
|
| 994 |
+
Print sync plan to stdout as JSONL without executing.
|
| 995 |
+
verbose (`bool`, *optional*, defaults to `False`):
|
| 996 |
+
Show detailed per-file operations.
|
| 997 |
+
quiet (`bool`, *optional*, defaults to `False`):
|
| 998 |
+
Suppress all output and progress bars.
|
| 999 |
+
token (Union[bool, str, None], optional):
|
| 1000 |
+
A valid user access token. If not provided, the locally saved token will be used.
|
| 1001 |
+
|
| 1002 |
+
Returns:
|
| 1003 |
+
[`SyncPlan`]: The computed (or loaded) sync plan.
|
| 1004 |
+
|
| 1005 |
+
Raises:
|
| 1006 |
+
`ValueError`: If arguments are invalid (e.g., both paths are remote, conflicting options).
|
| 1007 |
+
|
| 1008 |
+
Example:
|
| 1009 |
+
```python
|
| 1010 |
+
>>> from huggingface_hub import HfApi
|
| 1011 |
+
>>> api = HfApi()
|
| 1012 |
+
|
| 1013 |
+
# Upload local directory to bucket
|
| 1014 |
+
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket")
|
| 1015 |
+
|
| 1016 |
+
# Download bucket to local directory
|
| 1017 |
+
>>> api.sync_bucket("hf://buckets/username/my-bucket", "./data")
|
| 1018 |
+
|
| 1019 |
+
# Sync with delete and filtering
|
| 1020 |
+
>>> api.sync_bucket(
|
| 1021 |
+
... "./data",
|
| 1022 |
+
... "hf://buckets/username/my-bucket",
|
| 1023 |
+
... delete=True,
|
| 1024 |
+
... include=["*.safetensors"],
|
| 1025 |
+
... )
|
| 1026 |
+
|
| 1027 |
+
# Dry run: preview what would be synced
|
| 1028 |
+
>>> plan = api.sync_bucket("./data", "hf://buckets/username/my-bucket", dry_run=True)
|
| 1029 |
+
>>> plan.summary()
|
| 1030 |
+
{'uploads': 3, 'downloads': 0, 'deletes': 0, 'skips': 1, 'total_size': 4096}
|
| 1031 |
+
|
| 1032 |
+
# Save plan for review, then apply
|
| 1033 |
+
>>> api.sync_bucket("./data", "hf://buckets/username/my-bucket", plan="sync-plan.jsonl")
|
| 1034 |
+
>>> api.sync_bucket(apply="sync-plan.jsonl")
|
| 1035 |
+
```
|
| 1036 |
+
"""
|
| 1037 |
+
# Build API with token if needed
|
| 1038 |
+
if token is not None:
|
| 1039 |
+
from .hf_api import HfApi
|
| 1040 |
+
|
| 1041 |
+
api = HfApi(token=token)
|
| 1042 |
+
# --- Apply mode ---
|
| 1043 |
+
if apply:
|
| 1044 |
+
if source or dest:
|
| 1045 |
+
raise ValueError("Cannot specify source/dest when using apply.")
|
| 1046 |
+
if plan is not None:
|
| 1047 |
+
raise ValueError("Cannot specify both plan and apply.")
|
| 1048 |
+
if delete:
|
| 1049 |
+
raise ValueError("Cannot specify delete when using apply.")
|
| 1050 |
+
if ignore_times:
|
| 1051 |
+
raise ValueError("Cannot specify ignore_times when using apply.")
|
| 1052 |
+
if ignore_sizes:
|
| 1053 |
+
raise ValueError("Cannot specify ignore_sizes when using apply.")
|
| 1054 |
+
if include:
|
| 1055 |
+
raise ValueError("Cannot specify include when using apply.")
|
| 1056 |
+
if exclude:
|
| 1057 |
+
raise ValueError("Cannot specify exclude when using apply.")
|
| 1058 |
+
if filter_from:
|
| 1059 |
+
raise ValueError("Cannot specify filter_from when using apply.")
|
| 1060 |
+
if existing:
|
| 1061 |
+
raise ValueError("Cannot specify existing when using apply.")
|
| 1062 |
+
if ignore_existing:
|
| 1063 |
+
raise ValueError("Cannot specify ignore_existing when using apply.")
|
| 1064 |
+
if dry_run:
|
| 1065 |
+
raise ValueError("Cannot specify dry_run when using apply.")
|
| 1066 |
+
|
| 1067 |
+
sync_plan = _load_plan(apply)
|
| 1068 |
+
status = StatusLine(enabled=not quiet)
|
| 1069 |
+
if not quiet:
|
| 1070 |
+
_print_plan_summary(sync_plan)
|
| 1071 |
+
print("Executing plan...")
|
| 1072 |
+
|
| 1073 |
+
if quiet:
|
| 1074 |
+
disable_progress_bars()
|
| 1075 |
+
try:
|
| 1076 |
+
_execute_plan(sync_plan, api, verbose=verbose, status=status)
|
| 1077 |
+
finally:
|
| 1078 |
+
if quiet:
|
| 1079 |
+
enable_progress_bars()
|
| 1080 |
+
|
| 1081 |
+
if not quiet:
|
| 1082 |
+
print("Sync completed.")
|
| 1083 |
+
|
| 1084 |
+
return sync_plan
|
| 1085 |
+
|
| 1086 |
+
# --- Normal mode ---
|
| 1087 |
+
if not source or not dest:
|
| 1088 |
+
raise ValueError("Both source and dest are required (unless using apply).")
|
| 1089 |
+
|
| 1090 |
+
source_is_bucket = _is_bucket_path(source)
|
| 1091 |
+
dest_is_bucket = _is_bucket_path(dest)
|
| 1092 |
+
|
| 1093 |
+
if source_is_bucket and dest_is_bucket:
|
| 1094 |
+
raise ValueError("Remote to remote sync is not supported. One path must be local.")
|
| 1095 |
+
|
| 1096 |
+
if not source_is_bucket and not dest_is_bucket:
|
| 1097 |
+
raise ValueError("One of source or dest must be a bucket path (hf://buckets/...).")
|
| 1098 |
+
|
| 1099 |
+
if ignore_times and ignore_sizes:
|
| 1100 |
+
raise ValueError("Cannot specify both ignore_times and ignore_sizes.")
|
| 1101 |
+
|
| 1102 |
+
if existing and ignore_existing:
|
| 1103 |
+
raise ValueError("Cannot specify both existing and ignore_existing.")
|
| 1104 |
+
|
| 1105 |
+
if dry_run and plan:
|
| 1106 |
+
raise ValueError("Cannot specify both dry_run and plan.")
|
| 1107 |
+
|
| 1108 |
+
# Validate local path
|
| 1109 |
+
if source_is_bucket:
|
| 1110 |
+
if os.path.exists(dest) and not os.path.isdir(dest):
|
| 1111 |
+
raise ValueError(f"Destination must be a directory: {dest}")
|
| 1112 |
+
else:
|
| 1113 |
+
if not os.path.isdir(source):
|
| 1114 |
+
raise ValueError(f"Source must be an existing directory: {source}")
|
| 1115 |
+
|
| 1116 |
+
# Build filter matcher
|
| 1117 |
+
filter_rules = None
|
| 1118 |
+
if filter_from:
|
| 1119 |
+
filter_rules = _parse_filter_file(filter_from)
|
| 1120 |
+
|
| 1121 |
+
filter_matcher = FilterMatcher(
|
| 1122 |
+
include_patterns=include,
|
| 1123 |
+
exclude_patterns=exclude,
|
| 1124 |
+
filter_rules=filter_rules,
|
| 1125 |
+
)
|
| 1126 |
+
|
| 1127 |
+
# Compute sync plan
|
| 1128 |
+
status = StatusLine(enabled=not quiet and not dry_run)
|
| 1129 |
+
sync_plan = _compute_sync_plan(
|
| 1130 |
+
source=source,
|
| 1131 |
+
dest=dest,
|
| 1132 |
+
api=api,
|
| 1133 |
+
delete=delete,
|
| 1134 |
+
ignore_times=ignore_times,
|
| 1135 |
+
ignore_sizes=ignore_sizes,
|
| 1136 |
+
existing=existing,
|
| 1137 |
+
ignore_existing=ignore_existing,
|
| 1138 |
+
filter_matcher=filter_matcher,
|
| 1139 |
+
status=status,
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
if dry_run:
|
| 1143 |
+
_write_plan(sync_plan, sys.stdout)
|
| 1144 |
+
return sync_plan
|
| 1145 |
+
|
| 1146 |
+
if plan:
|
| 1147 |
+
_save_plan(sync_plan, plan)
|
| 1148 |
+
if not quiet:
|
| 1149 |
+
_print_plan_summary(sync_plan)
|
| 1150 |
+
print(f"Plan saved to: {plan}")
|
| 1151 |
+
return sync_plan
|
| 1152 |
+
|
| 1153 |
+
# Execute plan
|
| 1154 |
+
if not quiet:
|
| 1155 |
+
_print_plan_summary(sync_plan)
|
| 1156 |
+
|
| 1157 |
+
summary = sync_plan.summary()
|
| 1158 |
+
if summary["uploads"] == 0 and summary["downloads"] == 0 and summary["deletes"] == 0:
|
| 1159 |
+
if not quiet:
|
| 1160 |
+
print("Nothing to sync.")
|
| 1161 |
+
return sync_plan
|
| 1162 |
+
|
| 1163 |
+
if not quiet:
|
| 1164 |
+
print("Syncing...")
|
| 1165 |
+
|
| 1166 |
+
if quiet:
|
| 1167 |
+
disable_progress_bars()
|
| 1168 |
+
try:
|
| 1169 |
+
_execute_plan(sync_plan, api, verbose=verbose, status=status)
|
| 1170 |
+
finally:
|
| 1171 |
+
if quiet:
|
| 1172 |
+
enable_progress_bars()
|
| 1173 |
+
|
| 1174 |
+
if not quiet:
|
| 1175 |
+
print("Sync completed.")
|
| 1176 |
+
|
| 1177 |
+
return sync_plan
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_commit_api.py
ADDED
|
@@ -0,0 +1,975 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Type definitions and utilities for the `create_commit` API
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
import os
|
| 8 |
+
import warnings
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from contextlib import contextmanager
|
| 11 |
+
from dataclasses import dataclass, field
|
| 12 |
+
from itertools import groupby
|
| 13 |
+
from pathlib import Path, PurePosixPath
|
| 14 |
+
from typing import TYPE_CHECKING, Any, BinaryIO, Iterable, Iterator, Literal, Optional, Union
|
| 15 |
+
|
| 16 |
+
from tqdm.contrib.concurrent import thread_map
|
| 17 |
+
|
| 18 |
+
from . import constants
|
| 19 |
+
from .errors import EntryNotFoundError, HfHubHTTPError, XetAuthorizationError, XetRefreshTokenError
|
| 20 |
+
from .file_download import hf_hub_url
|
| 21 |
+
from .lfs import UploadInfo, lfs_upload, post_lfs_batch_info
|
| 22 |
+
from .utils import (
|
| 23 |
+
FORBIDDEN_FOLDERS,
|
| 24 |
+
XetTokenType,
|
| 25 |
+
are_progress_bars_disabled,
|
| 26 |
+
chunk_iterable,
|
| 27 |
+
fetch_xet_connection_info_from_repo_info,
|
| 28 |
+
get_session,
|
| 29 |
+
hf_raise_for_status,
|
| 30 |
+
http_backoff,
|
| 31 |
+
logging,
|
| 32 |
+
sha,
|
| 33 |
+
tqdm_stream_file,
|
| 34 |
+
validate_hf_hub_args,
|
| 35 |
+
)
|
| 36 |
+
from .utils import tqdm as hf_tqdm
|
| 37 |
+
from .utils._runtime import is_xet_available
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if TYPE_CHECKING:
|
| 41 |
+
from .hf_api import RepoFile
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
logger = logging.get_logger(__name__)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
UploadMode = Literal["lfs", "regular"]
|
| 48 |
+
|
| 49 |
+
# Max is 1,000 per request on the Hub for HfApi.get_paths_info
|
| 50 |
+
# Otherwise we get:
|
| 51 |
+
# HfHubHTTPError: 413 Client Error: Payload Too Large for url: https://huggingface.co/api/datasets/xxx (Request ID: xxx)\n\ntoo many parameters
|
| 52 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1503
|
| 53 |
+
FETCH_LFS_BATCH_SIZE = 500
|
| 54 |
+
|
| 55 |
+
UPLOAD_BATCH_MAX_NUM_FILES = 256
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class CommitOperationDelete:
|
| 60 |
+
"""
|
| 61 |
+
Data structure holding necessary info to delete a file or a folder from a repository
|
| 62 |
+
on the Hub.
|
| 63 |
+
|
| 64 |
+
Args:
|
| 65 |
+
path_in_repo (`str`):
|
| 66 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
| 67 |
+
for a file or `"checkpoints/1fec34a/"` for a folder.
|
| 68 |
+
is_folder (`bool` or `Literal["auto"]`, *optional*)
|
| 69 |
+
Whether the Delete Operation applies to a folder or not. If "auto", the path
|
| 70 |
+
type (file or folder) is guessed automatically by looking if path ends with
|
| 71 |
+
a "/" (folder) or not (file). To explicitly set the path type, you can set
|
| 72 |
+
`is_folder=True` or `is_folder=False`.
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
path_in_repo: str
|
| 76 |
+
is_folder: Union[bool, Literal["auto"]] = "auto"
|
| 77 |
+
|
| 78 |
+
def __post_init__(self):
|
| 79 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 80 |
+
|
| 81 |
+
if self.is_folder == "auto":
|
| 82 |
+
self.is_folder = self.path_in_repo.endswith("/")
|
| 83 |
+
if not isinstance(self.is_folder, bool):
|
| 84 |
+
raise ValueError(
|
| 85 |
+
f"Wrong value for `is_folder`. Must be one of [`True`, `False`, `'auto'`]. Got '{self.is_folder}'."
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
@dataclass
|
| 90 |
+
class CommitOperationCopy:
|
| 91 |
+
"""
|
| 92 |
+
Data structure holding necessary info to copy a file in a repository on the Hub.
|
| 93 |
+
|
| 94 |
+
Limitations:
|
| 95 |
+
- Only LFS files can be copied. To copy a regular file, you need to download it locally and re-upload it
|
| 96 |
+
- Cross-repository copies are not supported.
|
| 97 |
+
|
| 98 |
+
Note: you can combine a [`CommitOperationCopy`] and a [`CommitOperationDelete`] to rename an LFS file on the Hub.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
src_path_in_repo (`str`):
|
| 102 |
+
Relative filepath in the repo of the file to be copied, e.g. `"checkpoints/1fec34a/weights.bin"`.
|
| 103 |
+
path_in_repo (`str`):
|
| 104 |
+
Relative filepath in the repo where to copy the file, e.g. `"checkpoints/1fec34a/weights_copy.bin"`.
|
| 105 |
+
src_revision (`str`, *optional*):
|
| 106 |
+
The git revision of the file to be copied. Can be any valid git revision.
|
| 107 |
+
Default to the target commit revision.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
src_path_in_repo: str
|
| 111 |
+
path_in_repo: str
|
| 112 |
+
src_revision: Optional[str] = None
|
| 113 |
+
# set to the OID of the file to be copied if it has already been uploaded
|
| 114 |
+
# useful to determine if a commit will be empty or not.
|
| 115 |
+
_src_oid: Optional[str] = None
|
| 116 |
+
# set to the OID of the file to copy to if it has already been uploaded
|
| 117 |
+
# useful to determine if a commit will be empty or not.
|
| 118 |
+
_dest_oid: Optional[str] = None
|
| 119 |
+
|
| 120 |
+
def __post_init__(self):
|
| 121 |
+
self.src_path_in_repo = _validate_path_in_repo(self.src_path_in_repo)
|
| 122 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@dataclass
|
| 126 |
+
class CommitOperationAdd:
|
| 127 |
+
"""
|
| 128 |
+
Data structure holding necessary info to upload a file to a repository on the Hub.
|
| 129 |
+
|
| 130 |
+
Args:
|
| 131 |
+
path_in_repo (`str`):
|
| 132 |
+
Relative filepath in the repo, for example: `"checkpoints/1fec34a/weights.bin"`
|
| 133 |
+
path_or_fileobj (`str`, `Path`, `bytes`, or `BinaryIO`):
|
| 134 |
+
Either:
|
| 135 |
+
- a path to a local file (as `str` or `pathlib.Path`) to upload
|
| 136 |
+
- a buffer of bytes (`bytes`) holding the content of the file to upload
|
| 137 |
+
- a "file object" (subclass of `io.BufferedIOBase`), typically obtained
|
| 138 |
+
with `open(path, "rb")`. It must support `seek()` and `tell()` methods.
|
| 139 |
+
|
| 140 |
+
Raises:
|
| 141 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 142 |
+
If `path_or_fileobj` is not one of `str`, `Path`, `bytes` or `io.BufferedIOBase`.
|
| 143 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 144 |
+
If `path_or_fileobj` is a `str` or `Path` but not a path to an existing file.
|
| 145 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 146 |
+
If `path_or_fileobj` is a `io.BufferedIOBase` but it doesn't support both
|
| 147 |
+
`seek()` and `tell()`.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
path_in_repo: str
|
| 151 |
+
path_or_fileobj: Union[str, Path, bytes, BinaryIO]
|
| 152 |
+
upload_info: UploadInfo = field(init=False, repr=False)
|
| 153 |
+
|
| 154 |
+
# Internal attributes
|
| 155 |
+
|
| 156 |
+
# set to "lfs" or "regular" once known
|
| 157 |
+
_upload_mode: Optional[UploadMode] = field(init=False, repr=False, default=None)
|
| 158 |
+
|
| 159 |
+
# set to True if .gitignore rules prevent the file from being uploaded as LFS
|
| 160 |
+
# (server-side check)
|
| 161 |
+
_should_ignore: Optional[bool] = field(init=False, repr=False, default=None)
|
| 162 |
+
|
| 163 |
+
# set to the remote OID of the file if it has already been uploaded
|
| 164 |
+
# useful to determine if a commit will be empty or not
|
| 165 |
+
_remote_oid: Optional[str] = field(init=False, repr=False, default=None)
|
| 166 |
+
|
| 167 |
+
# set to True once the file has been uploaded as LFS
|
| 168 |
+
_is_uploaded: bool = field(init=False, repr=False, default=False)
|
| 169 |
+
|
| 170 |
+
# set to True once the file has been committed
|
| 171 |
+
_is_committed: bool = field(init=False, repr=False, default=False)
|
| 172 |
+
|
| 173 |
+
def __post_init__(self) -> None:
|
| 174 |
+
"""Validates `path_or_fileobj` and compute `upload_info`."""
|
| 175 |
+
self.path_in_repo = _validate_path_in_repo(self.path_in_repo)
|
| 176 |
+
|
| 177 |
+
# Validate `path_or_fileobj` value
|
| 178 |
+
if isinstance(self.path_or_fileobj, Path):
|
| 179 |
+
self.path_or_fileobj = str(self.path_or_fileobj)
|
| 180 |
+
if isinstance(self.path_or_fileobj, str):
|
| 181 |
+
path_or_fileobj = os.path.normpath(os.path.expanduser(self.path_or_fileobj))
|
| 182 |
+
if not os.path.isfile(path_or_fileobj):
|
| 183 |
+
raise ValueError(f"Provided path: '{path_or_fileobj}' is not a file on the local file system")
|
| 184 |
+
elif not isinstance(self.path_or_fileobj, (io.BufferedIOBase, bytes)):
|
| 185 |
+
# ^^ Inspired from: https://stackoverflow.com/questions/44584829/how-to-determine-if-file-is-opened-in-binary-or-text-mode
|
| 186 |
+
raise ValueError(
|
| 187 |
+
"path_or_fileobj must be either an instance of str, bytes or"
|
| 188 |
+
" io.BufferedIOBase. If you passed a file-like object, make sure it is"
|
| 189 |
+
" in binary mode."
|
| 190 |
+
)
|
| 191 |
+
if isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
| 192 |
+
try:
|
| 193 |
+
self.path_or_fileobj.tell()
|
| 194 |
+
self.path_or_fileobj.seek(0, os.SEEK_CUR)
|
| 195 |
+
except (OSError, AttributeError) as exc:
|
| 196 |
+
raise ValueError(
|
| 197 |
+
"path_or_fileobj is a file-like object but does not implement seek() and tell()"
|
| 198 |
+
) from exc
|
| 199 |
+
|
| 200 |
+
# Compute "upload_info" attribute
|
| 201 |
+
if isinstance(self.path_or_fileobj, str):
|
| 202 |
+
self.upload_info = UploadInfo.from_path(self.path_or_fileobj)
|
| 203 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
| 204 |
+
self.upload_info = UploadInfo.from_bytes(self.path_or_fileobj)
|
| 205 |
+
else:
|
| 206 |
+
self.upload_info = UploadInfo.from_fileobj(self.path_or_fileobj)
|
| 207 |
+
|
| 208 |
+
@contextmanager
|
| 209 |
+
def as_file(self, with_tqdm: bool = False) -> Iterator[BinaryIO]:
|
| 210 |
+
"""
|
| 211 |
+
A context manager that yields a file-like object allowing to read the underlying
|
| 212 |
+
data behind `path_or_fileobj`.
|
| 213 |
+
|
| 214 |
+
Args:
|
| 215 |
+
with_tqdm (`bool`, *optional*, defaults to `False`):
|
| 216 |
+
If True, iterating over the file object will display a progress bar. Only
|
| 217 |
+
works if the file-like object is a path to a file. Pure bytes and buffers
|
| 218 |
+
are not supported.
|
| 219 |
+
|
| 220 |
+
Example:
|
| 221 |
+
|
| 222 |
+
```python
|
| 223 |
+
>>> operation = CommitOperationAdd(
|
| 224 |
+
... path_in_repo="remote/dir/weights.h5",
|
| 225 |
+
... path_or_fileobj="./local/weights.h5",
|
| 226 |
+
... )
|
| 227 |
+
CommitOperationAdd(path_in_repo='remote/dir/weights.h5', path_or_fileobj='./local/weights.h5')
|
| 228 |
+
|
| 229 |
+
>>> with operation.as_file() as file:
|
| 230 |
+
... content = file.read()
|
| 231 |
+
|
| 232 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
| 233 |
+
... while True:
|
| 234 |
+
... data = file.read(1024)
|
| 235 |
+
... if not data:
|
| 236 |
+
... break
|
| 237 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| 238 |
+
|
| 239 |
+
>>> with operation.as_file(with_tqdm=True) as file:
|
| 240 |
+
... httpx.put(..., data=file)
|
| 241 |
+
config.json: 100%|█████████████████████████| 8.19k/8.19k [00:02<00:00, 3.72kB/s]
|
| 242 |
+
```
|
| 243 |
+
"""
|
| 244 |
+
if isinstance(self.path_or_fileobj, str) or isinstance(self.path_or_fileobj, Path):
|
| 245 |
+
if with_tqdm:
|
| 246 |
+
with tqdm_stream_file(self.path_or_fileobj) as file:
|
| 247 |
+
yield file
|
| 248 |
+
else:
|
| 249 |
+
with open(self.path_or_fileobj, "rb") as file:
|
| 250 |
+
yield file
|
| 251 |
+
elif isinstance(self.path_or_fileobj, bytes):
|
| 252 |
+
yield io.BytesIO(self.path_or_fileobj)
|
| 253 |
+
elif isinstance(self.path_or_fileobj, io.BufferedIOBase):
|
| 254 |
+
prev_pos = self.path_or_fileobj.tell()
|
| 255 |
+
yield self.path_or_fileobj
|
| 256 |
+
self.path_or_fileobj.seek(prev_pos, io.SEEK_SET)
|
| 257 |
+
|
| 258 |
+
def b64content(self) -> bytes:
|
| 259 |
+
"""
|
| 260 |
+
The base64-encoded content of `path_or_fileobj`
|
| 261 |
+
|
| 262 |
+
Returns: `bytes`
|
| 263 |
+
"""
|
| 264 |
+
with self.as_file() as file:
|
| 265 |
+
return base64.b64encode(file.read())
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def _local_oid(self) -> Optional[str]:
|
| 269 |
+
"""Return the OID of the local file.
|
| 270 |
+
|
| 271 |
+
This OID is then compared to `self._remote_oid` to check if the file has changed compared to the remote one.
|
| 272 |
+
If the file did not change, we won't upload it again to prevent empty commits.
|
| 273 |
+
|
| 274 |
+
For LFS files, the OID corresponds to the SHA256 of the file content (used a LFS ref).
|
| 275 |
+
For regular files, the OID corresponds to the SHA1 of the file content.
|
| 276 |
+
Note: this is slightly different to git OID computation since the oid of an LFS file is usually the git-SHA1 of the
|
| 277 |
+
pointer file content (not the actual file content). However, using the SHA256 is enough to detect changes
|
| 278 |
+
and more convenient client-side.
|
| 279 |
+
"""
|
| 280 |
+
if self._upload_mode is None:
|
| 281 |
+
return None
|
| 282 |
+
elif self._upload_mode == "lfs":
|
| 283 |
+
return self.upload_info.sha256.hex()
|
| 284 |
+
else:
|
| 285 |
+
# Regular file => compute sha1
|
| 286 |
+
# => no need to read by chunk since the file is guaranteed to be <=5MB.
|
| 287 |
+
with self.as_file() as file:
|
| 288 |
+
return sha.git_hash(file.read())
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _validate_path_in_repo(path_in_repo: str) -> str:
|
| 292 |
+
# Validate `path_in_repo` value to prevent a server-side issue
|
| 293 |
+
if path_in_repo.startswith("/"):
|
| 294 |
+
path_in_repo = path_in_repo[1:]
|
| 295 |
+
if path_in_repo == "." or path_in_repo == ".." or path_in_repo.startswith("../"):
|
| 296 |
+
raise ValueError(f"Invalid `path_in_repo` in CommitOperation: '{path_in_repo}'")
|
| 297 |
+
if path_in_repo.startswith("./"):
|
| 298 |
+
path_in_repo = path_in_repo[2:]
|
| 299 |
+
for forbidden in FORBIDDEN_FOLDERS:
|
| 300 |
+
if any(part == forbidden for part in path_in_repo.split("/")):
|
| 301 |
+
raise ValueError(
|
| 302 |
+
f"Invalid `path_in_repo` in CommitOperation: cannot update files under a '{forbidden}/' folder (path:"
|
| 303 |
+
f" '{path_in_repo}')."
|
| 304 |
+
)
|
| 305 |
+
return path_in_repo
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
CommitOperation = Union[CommitOperationAdd, CommitOperationCopy, CommitOperationDelete]
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _warn_on_overwriting_operations(operations: list[CommitOperation]) -> None:
|
| 312 |
+
"""
|
| 313 |
+
Warn user when a list of operations is expected to overwrite itself in a single
|
| 314 |
+
commit.
|
| 315 |
+
|
| 316 |
+
Rules:
|
| 317 |
+
- If a filepath is updated by multiple `CommitOperationAdd` operations, a warning
|
| 318 |
+
message is triggered.
|
| 319 |
+
- If a filepath is updated at least once by a `CommitOperationAdd` and then deleted
|
| 320 |
+
by a `CommitOperationDelete`, a warning is triggered.
|
| 321 |
+
- If a `CommitOperationDelete` deletes a filepath that is then updated by a
|
| 322 |
+
`CommitOperationAdd`, no warning is triggered. This is usually useless (no need to
|
| 323 |
+
delete before upload) but can happen if a user deletes an entire folder and then
|
| 324 |
+
add new files to it.
|
| 325 |
+
"""
|
| 326 |
+
nb_additions_per_path: dict[str, int] = defaultdict(int)
|
| 327 |
+
for operation in operations:
|
| 328 |
+
path_in_repo = operation.path_in_repo
|
| 329 |
+
if isinstance(operation, CommitOperationAdd):
|
| 330 |
+
if nb_additions_per_path[path_in_repo] > 0:
|
| 331 |
+
warnings.warn(
|
| 332 |
+
"About to update multiple times the same file in the same commit:"
|
| 333 |
+
f" '{path_in_repo}'. This can cause undesired inconsistencies in"
|
| 334 |
+
" your repo."
|
| 335 |
+
)
|
| 336 |
+
nb_additions_per_path[path_in_repo] += 1
|
| 337 |
+
for parent in PurePosixPath(path_in_repo).parents:
|
| 338 |
+
# Also keep track of number of updated files per folder
|
| 339 |
+
# => warns if deleting a folder overwrite some contained files
|
| 340 |
+
nb_additions_per_path[str(parent)] += 1
|
| 341 |
+
if isinstance(operation, CommitOperationDelete):
|
| 342 |
+
if nb_additions_per_path[str(PurePosixPath(path_in_repo))] > 0:
|
| 343 |
+
if operation.is_folder:
|
| 344 |
+
warnings.warn(
|
| 345 |
+
"About to delete a folder containing files that have just been"
|
| 346 |
+
f" updated within the same commit: '{path_in_repo}'. This can"
|
| 347 |
+
" cause undesired inconsistencies in your repo."
|
| 348 |
+
)
|
| 349 |
+
else:
|
| 350 |
+
warnings.warn(
|
| 351 |
+
"About to delete a file that have just been updated within the"
|
| 352 |
+
f" same commit: '{path_in_repo}'. This can cause undesired"
|
| 353 |
+
" inconsistencies in your repo."
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
@validate_hf_hub_args
|
| 358 |
+
def _upload_files(
|
| 359 |
+
*,
|
| 360 |
+
additions: list[CommitOperationAdd],
|
| 361 |
+
repo_type: str,
|
| 362 |
+
repo_id: str,
|
| 363 |
+
headers: dict[str, str],
|
| 364 |
+
endpoint: Optional[str] = None,
|
| 365 |
+
num_threads: int = 5,
|
| 366 |
+
revision: Optional[str] = None,
|
| 367 |
+
create_pr: Optional[bool] = None,
|
| 368 |
+
):
|
| 369 |
+
"""
|
| 370 |
+
Negotiates per-file transfer (LFS vs Xet) and uploads in batches.
|
| 371 |
+
"""
|
| 372 |
+
xet_additions: list[CommitOperationAdd] = []
|
| 373 |
+
lfs_actions: list[dict[str, Any]] = []
|
| 374 |
+
lfs_oid2addop: dict[str, CommitOperationAdd] = {}
|
| 375 |
+
|
| 376 |
+
for chunk in chunk_iterable(additions, chunk_size=UPLOAD_BATCH_MAX_NUM_FILES):
|
| 377 |
+
chunk_list = [op for op in chunk]
|
| 378 |
+
|
| 379 |
+
transfers: list[str] = ["basic", "multipart"]
|
| 380 |
+
has_buffered_io_data = any(isinstance(op.path_or_fileobj, io.BufferedIOBase) for op in chunk_list)
|
| 381 |
+
if is_xet_available():
|
| 382 |
+
if not has_buffered_io_data:
|
| 383 |
+
transfers.append("xet")
|
| 384 |
+
else:
|
| 385 |
+
logger.warning(
|
| 386 |
+
"Uploading files as a binary IO buffer is not supported by Xet Storage. "
|
| 387 |
+
"Falling back to HTTP upload."
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
actions_chunk, errors_chunk, chosen_transfer = post_lfs_batch_info(
|
| 391 |
+
upload_infos=[op.upload_info for op in chunk_list],
|
| 392 |
+
repo_id=repo_id,
|
| 393 |
+
repo_type=repo_type,
|
| 394 |
+
revision=revision,
|
| 395 |
+
endpoint=endpoint,
|
| 396 |
+
headers=headers,
|
| 397 |
+
token=None, # already passed in 'headers'
|
| 398 |
+
transfers=transfers,
|
| 399 |
+
)
|
| 400 |
+
if errors_chunk:
|
| 401 |
+
message = "\n".join(
|
| 402 |
+
[
|
| 403 |
+
f"Encountered error for file with OID {err.get('oid')}: `{err.get('error', {}).get('message')}"
|
| 404 |
+
for err in errors_chunk
|
| 405 |
+
]
|
| 406 |
+
)
|
| 407 |
+
raise ValueError(f"LFS batch API returned errors:\n{message}")
|
| 408 |
+
|
| 409 |
+
# If server returns a transfer we didn't offer (e.g "xet" while uploading from BytesIO),
|
| 410 |
+
# fall back to LFS for this chunk.
|
| 411 |
+
if chosen_transfer == "xet" and ("xet" in transfers):
|
| 412 |
+
xet_additions.extend(chunk_list)
|
| 413 |
+
else:
|
| 414 |
+
lfs_actions.extend(actions_chunk)
|
| 415 |
+
for op in chunk_list:
|
| 416 |
+
lfs_oid2addop[op.upload_info.sha256.hex()] = op
|
| 417 |
+
|
| 418 |
+
if len(lfs_actions) > 0:
|
| 419 |
+
_upload_lfs_files(
|
| 420 |
+
actions=lfs_actions,
|
| 421 |
+
oid2addop=lfs_oid2addop,
|
| 422 |
+
headers=headers,
|
| 423 |
+
endpoint=endpoint,
|
| 424 |
+
num_threads=num_threads,
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
if len(xet_additions) > 0:
|
| 428 |
+
_upload_xet_files(
|
| 429 |
+
additions=xet_additions,
|
| 430 |
+
repo_type=repo_type,
|
| 431 |
+
repo_id=repo_id,
|
| 432 |
+
headers=headers,
|
| 433 |
+
endpoint=endpoint,
|
| 434 |
+
revision=revision,
|
| 435 |
+
create_pr=create_pr,
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
@validate_hf_hub_args
|
| 440 |
+
def _upload_lfs_files(
|
| 441 |
+
*,
|
| 442 |
+
actions: list[dict[str, Any]],
|
| 443 |
+
oid2addop: dict[str, CommitOperationAdd],
|
| 444 |
+
headers: dict[str, str],
|
| 445 |
+
endpoint: Optional[str] = None,
|
| 446 |
+
num_threads: int = 5,
|
| 447 |
+
):
|
| 448 |
+
"""
|
| 449 |
+
Uploads the content of `additions` to the Hub using the large file storage protocol.
|
| 450 |
+
|
| 451 |
+
Relevant external documentation:
|
| 452 |
+
- LFS Batch API: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
|
| 453 |
+
|
| 454 |
+
Args:
|
| 455 |
+
actions (`list[dict[str, Any]]`):
|
| 456 |
+
LFS batch actions returned by the server.
|
| 457 |
+
oid2addop (`dict[str, CommitOperationAdd]`):
|
| 458 |
+
A dictionary mapping the OID of the file to the corresponding `CommitOperationAdd` object.
|
| 459 |
+
headers (`dict[str, str]`):
|
| 460 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 461 |
+
endpoint (`str`, *optional*):
|
| 462 |
+
The endpoint to use for the request. Defaults to `constants.ENDPOINT`.
|
| 463 |
+
num_threads (`int`, *optional*):
|
| 464 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
| 465 |
+
|
| 466 |
+
Raises:
|
| 467 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 468 |
+
If an upload failed for any reason
|
| 469 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 470 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 471 |
+
repo_id (`str`):
|
| 472 |
+
A namespace (user or an organization) and a repo name separated
|
| 473 |
+
by a `/`.
|
| 474 |
+
headers (`dict[str, str]`):
|
| 475 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 476 |
+
num_threads (`int`, *optional*):
|
| 477 |
+
The number of concurrent threads to use when uploading. Defaults to 5.
|
| 478 |
+
revision (`str`, *optional*):
|
| 479 |
+
The git revision to upload to.
|
| 480 |
+
|
| 481 |
+
Raises:
|
| 482 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 483 |
+
If an upload failed for any reason
|
| 484 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 485 |
+
If the server returns malformed responses
|
| 486 |
+
[`HfHubHTTPError`]
|
| 487 |
+
If the LFS batch endpoint returned an HTTP error.
|
| 488 |
+
"""
|
| 489 |
+
# Filter out files already present upstream
|
| 490 |
+
filtered_actions = []
|
| 491 |
+
for action in actions:
|
| 492 |
+
if action.get("actions") is None:
|
| 493 |
+
logger.debug(
|
| 494 |
+
f"Content of file {oid2addop[action['oid']].path_in_repo} is already present upstream - skipping upload."
|
| 495 |
+
)
|
| 496 |
+
else:
|
| 497 |
+
filtered_actions.append(action)
|
| 498 |
+
|
| 499 |
+
# Upload according to server-provided actions
|
| 500 |
+
def _wrapped_lfs_upload(batch_action) -> None:
|
| 501 |
+
try:
|
| 502 |
+
operation = oid2addop[batch_action["oid"]]
|
| 503 |
+
lfs_upload(operation=operation, lfs_batch_action=batch_action, headers=headers, endpoint=endpoint)
|
| 504 |
+
except Exception as exc:
|
| 505 |
+
raise RuntimeError(f"Error while uploading '{operation.path_in_repo}' to the Hub.") from exc
|
| 506 |
+
|
| 507 |
+
if len(filtered_actions) == 1:
|
| 508 |
+
logger.debug("Uploading 1 LFS file to the Hub")
|
| 509 |
+
_wrapped_lfs_upload(filtered_actions[0])
|
| 510 |
+
else:
|
| 511 |
+
logger.debug(
|
| 512 |
+
f"Uploading {len(filtered_actions)} LFS files to the Hub using up to {num_threads} threads concurrently"
|
| 513 |
+
)
|
| 514 |
+
thread_map(
|
| 515 |
+
_wrapped_lfs_upload,
|
| 516 |
+
filtered_actions,
|
| 517 |
+
desc=f"Upload {len(filtered_actions)} LFS files",
|
| 518 |
+
max_workers=num_threads,
|
| 519 |
+
tqdm_class=hf_tqdm,
|
| 520 |
+
)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
@validate_hf_hub_args
|
| 524 |
+
def _upload_xet_files(
|
| 525 |
+
*,
|
| 526 |
+
additions: list[CommitOperationAdd],
|
| 527 |
+
repo_type: str,
|
| 528 |
+
repo_id: str,
|
| 529 |
+
headers: dict[str, str],
|
| 530 |
+
endpoint: Optional[str] = None,
|
| 531 |
+
revision: Optional[str] = None,
|
| 532 |
+
create_pr: Optional[bool] = None,
|
| 533 |
+
):
|
| 534 |
+
"""
|
| 535 |
+
Uploads the content of `additions` to the Hub using the xet storage protocol.
|
| 536 |
+
This chunks the files and deduplicates the chunks before uploading them to xetcas storage.
|
| 537 |
+
|
| 538 |
+
Args:
|
| 539 |
+
additions (`` of `CommitOperationAdd`):
|
| 540 |
+
The files to be uploaded.
|
| 541 |
+
repo_type (`str`):
|
| 542 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 543 |
+
repo_id (`str`):
|
| 544 |
+
A namespace (user or an organization) and a repo name separated
|
| 545 |
+
by a `/`.
|
| 546 |
+
headers (`dict[str, str]`):
|
| 547 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 548 |
+
endpoint: (`str`, *optional*):
|
| 549 |
+
The endpoint to use for the xetcas service. Defaults to `constants.ENDPOINT`.
|
| 550 |
+
revision (`str`, *optional*):
|
| 551 |
+
The git revision to upload to.
|
| 552 |
+
create_pr (`bool`, *optional*):
|
| 553 |
+
Whether or not to create a Pull Request with that commit.
|
| 554 |
+
|
| 555 |
+
Raises:
|
| 556 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 557 |
+
If an upload failed for any reason.
|
| 558 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 559 |
+
If the server returns malformed responses or if the user is unauthorized to upload to xet storage.
|
| 560 |
+
[`HfHubHTTPError`]
|
| 561 |
+
If the LFS batch endpoint returned an HTTP error.
|
| 562 |
+
|
| 563 |
+
**How it works:**
|
| 564 |
+
The file download system uses Xet storage, which is a content-addressable storage system that breaks files into chunks
|
| 565 |
+
for efficient storage and transfer.
|
| 566 |
+
|
| 567 |
+
`hf_xet.upload_files` manages uploading files by:
|
| 568 |
+
- Taking a list of file paths to upload
|
| 569 |
+
- Breaking files into smaller chunks for efficient storage
|
| 570 |
+
- Avoiding duplicate storage by recognizing identical chunks across files
|
| 571 |
+
- Connecting to a storage server (CAS server) that manages these chunks
|
| 572 |
+
|
| 573 |
+
The upload process works like this:
|
| 574 |
+
1. Create a local folder at ~/.cache/huggingface/xet/chunk-cache to store file chunks for reuse.
|
| 575 |
+
2. Process files in parallel (up to 8 files at once):
|
| 576 |
+
2.1. Read the file content.
|
| 577 |
+
2.2. Split the file content into smaller chunks based on content patterns: each chunk gets a unique ID based on what's in it.
|
| 578 |
+
2.3. For each chunk:
|
| 579 |
+
- Check if it already exists in storage.
|
| 580 |
+
- Skip uploading chunks that already exist.
|
| 581 |
+
2.4. Group chunks into larger blocks for efficient transfer.
|
| 582 |
+
2.5. Upload these blocks to the storage server.
|
| 583 |
+
2.6. Create and upload information about how the file is structured.
|
| 584 |
+
3. Return reference files that contain information about the uploaded files, which can be used later to download them.
|
| 585 |
+
"""
|
| 586 |
+
if len(additions) == 0:
|
| 587 |
+
return
|
| 588 |
+
|
| 589 |
+
# at this point, we know that hf_xet is installed
|
| 590 |
+
from hf_xet import upload_bytes, upload_files
|
| 591 |
+
|
| 592 |
+
from .utils._xet_progress_reporting import XetProgressReporter
|
| 593 |
+
|
| 594 |
+
try:
|
| 595 |
+
xet_connection_info = fetch_xet_connection_info_from_repo_info(
|
| 596 |
+
token_type=XetTokenType.WRITE,
|
| 597 |
+
repo_id=repo_id,
|
| 598 |
+
repo_type=repo_type,
|
| 599 |
+
revision=revision,
|
| 600 |
+
headers=headers,
|
| 601 |
+
endpoint=endpoint,
|
| 602 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 603 |
+
)
|
| 604 |
+
except HfHubHTTPError as e:
|
| 605 |
+
if e.response.status_code == 401:
|
| 606 |
+
raise XetAuthorizationError(
|
| 607 |
+
f"You are unauthorized to upload to xet storage for {repo_type}/{repo_id}. "
|
| 608 |
+
f"Please check that you have configured your access token with write access to the repo."
|
| 609 |
+
) from e
|
| 610 |
+
raise
|
| 611 |
+
|
| 612 |
+
xet_endpoint = xet_connection_info.endpoint
|
| 613 |
+
access_token_info = (xet_connection_info.access_token, xet_connection_info.expiration_unix_epoch)
|
| 614 |
+
|
| 615 |
+
def token_refresher() -> tuple[str, int]:
|
| 616 |
+
new_xet_connection = fetch_xet_connection_info_from_repo_info(
|
| 617 |
+
token_type=XetTokenType.WRITE,
|
| 618 |
+
repo_id=repo_id,
|
| 619 |
+
repo_type=repo_type,
|
| 620 |
+
revision=revision,
|
| 621 |
+
headers=headers,
|
| 622 |
+
endpoint=endpoint,
|
| 623 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 624 |
+
)
|
| 625 |
+
if new_xet_connection is None:
|
| 626 |
+
raise XetRefreshTokenError("Failed to refresh xet token")
|
| 627 |
+
return new_xet_connection.access_token, new_xet_connection.expiration_unix_epoch
|
| 628 |
+
|
| 629 |
+
if not are_progress_bars_disabled():
|
| 630 |
+
progress = XetProgressReporter()
|
| 631 |
+
progress_callback = progress.update_progress
|
| 632 |
+
else:
|
| 633 |
+
progress, progress_callback = None, None
|
| 634 |
+
|
| 635 |
+
try:
|
| 636 |
+
all_bytes_ops = [op for op in additions if isinstance(op.path_or_fileobj, bytes)]
|
| 637 |
+
all_paths_ops = [op for op in additions if isinstance(op.path_or_fileobj, (str, Path))]
|
| 638 |
+
|
| 639 |
+
xet_headers = headers.copy()
|
| 640 |
+
xet_headers.pop("authorization", None)
|
| 641 |
+
|
| 642 |
+
if len(all_paths_ops) > 0:
|
| 643 |
+
all_paths = [str(op.path_or_fileobj) for op in all_paths_ops]
|
| 644 |
+
all_sha256s = [op.upload_info.sha256.hex() for op in all_paths_ops]
|
| 645 |
+
upload_files(
|
| 646 |
+
all_paths,
|
| 647 |
+
xet_endpoint,
|
| 648 |
+
access_token_info,
|
| 649 |
+
token_refresher,
|
| 650 |
+
progress_callback,
|
| 651 |
+
repo_type,
|
| 652 |
+
request_headers=xet_headers,
|
| 653 |
+
sha256s=all_sha256s,
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
if len(all_bytes_ops) > 0:
|
| 657 |
+
all_bytes = [op.path_or_fileobj for op in all_bytes_ops]
|
| 658 |
+
all_sha256s = [op.upload_info.sha256.hex() for op in all_bytes_ops]
|
| 659 |
+
upload_bytes(
|
| 660 |
+
all_bytes,
|
| 661 |
+
xet_endpoint,
|
| 662 |
+
access_token_info,
|
| 663 |
+
token_refresher,
|
| 664 |
+
progress_callback,
|
| 665 |
+
repo_type,
|
| 666 |
+
request_headers=xet_headers,
|
| 667 |
+
sha256s=all_sha256s,
|
| 668 |
+
)
|
| 669 |
+
|
| 670 |
+
finally:
|
| 671 |
+
if progress is not None:
|
| 672 |
+
progress.close(False)
|
| 673 |
+
|
| 674 |
+
return
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def _validate_preupload_info(preupload_info: dict):
|
| 678 |
+
files = preupload_info.get("files")
|
| 679 |
+
if not isinstance(files, list):
|
| 680 |
+
raise ValueError("preupload_info is improperly formatted")
|
| 681 |
+
for file_info in files:
|
| 682 |
+
if not (
|
| 683 |
+
isinstance(file_info, dict)
|
| 684 |
+
and isinstance(file_info.get("path"), str)
|
| 685 |
+
and isinstance(file_info.get("uploadMode"), str)
|
| 686 |
+
and (file_info["uploadMode"] in ("lfs", "regular"))
|
| 687 |
+
):
|
| 688 |
+
raise ValueError("preupload_info is improperly formatted:")
|
| 689 |
+
return preupload_info
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
@validate_hf_hub_args
|
| 693 |
+
def _fetch_upload_modes(
|
| 694 |
+
additions: Iterable[CommitOperationAdd],
|
| 695 |
+
repo_type: str,
|
| 696 |
+
repo_id: str,
|
| 697 |
+
headers: dict[str, str],
|
| 698 |
+
revision: str,
|
| 699 |
+
endpoint: Optional[str] = None,
|
| 700 |
+
create_pr: bool = False,
|
| 701 |
+
gitignore_content: Optional[str] = None,
|
| 702 |
+
) -> None:
|
| 703 |
+
"""
|
| 704 |
+
Requests the Hub "preupload" endpoint to determine whether each input file should be uploaded as a regular git blob,
|
| 705 |
+
as a git LFS blob, or as a XET file. Input `additions` are mutated in-place with the upload mode.
|
| 706 |
+
|
| 707 |
+
Args:
|
| 708 |
+
additions (`Iterable` of :class:`CommitOperationAdd`):
|
| 709 |
+
Iterable of :class:`CommitOperationAdd` describing the files to
|
| 710 |
+
upload to the Hub.
|
| 711 |
+
repo_type (`str`):
|
| 712 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 713 |
+
repo_id (`str`):
|
| 714 |
+
A namespace (user or an organization) and a repo name separated
|
| 715 |
+
by a `/`.
|
| 716 |
+
headers (`dict[str, str]`):
|
| 717 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 718 |
+
revision (`str`):
|
| 719 |
+
The git revision to upload the files to. Can be any valid git revision.
|
| 720 |
+
gitignore_content (`str`, *optional*):
|
| 721 |
+
The content of the `.gitignore` file to know which files should be ignored. The order of priority
|
| 722 |
+
is to first check if `gitignore_content` is passed, then check if the `.gitignore` file is present
|
| 723 |
+
in the list of files to commit and finally default to the `.gitignore` file already hosted on the Hub
|
| 724 |
+
(if any).
|
| 725 |
+
Raises:
|
| 726 |
+
[`~utils.HfHubHTTPError`]
|
| 727 |
+
If the Hub API returned an error.
|
| 728 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 729 |
+
If the Hub API response is improperly formatted.
|
| 730 |
+
"""
|
| 731 |
+
endpoint = endpoint if endpoint is not None else constants.ENDPOINT
|
| 732 |
+
|
| 733 |
+
# Fetch upload mode (LFS or regular) chunk by chunk.
|
| 734 |
+
upload_modes: dict[str, UploadMode] = {}
|
| 735 |
+
should_ignore_info: dict[str, bool] = {}
|
| 736 |
+
oid_info: dict[str, Optional[str]] = {}
|
| 737 |
+
|
| 738 |
+
for chunk in chunk_iterable(additions, 256):
|
| 739 |
+
payload: dict = {
|
| 740 |
+
"files": [
|
| 741 |
+
{
|
| 742 |
+
"path": op.path_in_repo,
|
| 743 |
+
"sample": base64.b64encode(op.upload_info.sample).decode("ascii"),
|
| 744 |
+
"size": op.upload_info.size,
|
| 745 |
+
}
|
| 746 |
+
for op in chunk
|
| 747 |
+
]
|
| 748 |
+
}
|
| 749 |
+
if gitignore_content is not None:
|
| 750 |
+
payload["gitIgnore"] = gitignore_content
|
| 751 |
+
|
| 752 |
+
resp = http_backoff(
|
| 753 |
+
"POST",
|
| 754 |
+
f"{endpoint}/api/{repo_type}s/{repo_id}/preupload/{revision}",
|
| 755 |
+
json=payload,
|
| 756 |
+
headers=headers,
|
| 757 |
+
params={"create_pr": "1"} if create_pr else None,
|
| 758 |
+
)
|
| 759 |
+
hf_raise_for_status(resp)
|
| 760 |
+
preupload_info = _validate_preupload_info(resp.json())
|
| 761 |
+
upload_modes.update(**{file["path"]: file["uploadMode"] for file in preupload_info["files"]})
|
| 762 |
+
should_ignore_info.update(**{file["path"]: file["shouldIgnore"] for file in preupload_info["files"]})
|
| 763 |
+
oid_info.update(**{file["path"]: file.get("oid") for file in preupload_info["files"]})
|
| 764 |
+
|
| 765 |
+
# Set upload mode for each addition operation
|
| 766 |
+
for addition in additions:
|
| 767 |
+
addition._upload_mode = upload_modes[addition.path_in_repo]
|
| 768 |
+
addition._should_ignore = should_ignore_info[addition.path_in_repo]
|
| 769 |
+
addition._remote_oid = oid_info[addition.path_in_repo]
|
| 770 |
+
|
| 771 |
+
# Empty files cannot be uploaded as LFS (S3 would fail with a 501 Not Implemented)
|
| 772 |
+
# => empty files are uploaded as "regular" to still allow users to commit them.
|
| 773 |
+
for addition in additions:
|
| 774 |
+
if addition.upload_info.size == 0:
|
| 775 |
+
addition._upload_mode = "regular"
|
| 776 |
+
|
| 777 |
+
|
| 778 |
+
@validate_hf_hub_args
|
| 779 |
+
def _fetch_files_to_copy(
|
| 780 |
+
copies: Iterable[CommitOperationCopy],
|
| 781 |
+
repo_type: str,
|
| 782 |
+
repo_id: str,
|
| 783 |
+
headers: dict[str, str],
|
| 784 |
+
revision: str,
|
| 785 |
+
endpoint: Optional[str] = None,
|
| 786 |
+
) -> dict[tuple[str, Optional[str]], Union["RepoFile", bytes]]:
|
| 787 |
+
"""
|
| 788 |
+
Fetch information about the files to copy.
|
| 789 |
+
|
| 790 |
+
For LFS files, we only need their metadata (file size and sha256) while for regular files
|
| 791 |
+
we need to download the raw content from the Hub.
|
| 792 |
+
|
| 793 |
+
Args:
|
| 794 |
+
copies (`Iterable` of :class:`CommitOperationCopy`):
|
| 795 |
+
Iterable of :class:`CommitOperationCopy` describing the files to
|
| 796 |
+
copy on the Hub.
|
| 797 |
+
repo_type (`str`):
|
| 798 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 799 |
+
repo_id (`str`):
|
| 800 |
+
A namespace (user or an organization) and a repo name separated
|
| 801 |
+
by a `/`.
|
| 802 |
+
headers (`dict[str, str]`):
|
| 803 |
+
Headers to use for the request, including authorization headers and user agent.
|
| 804 |
+
revision (`str`):
|
| 805 |
+
The git revision to upload the files to. Can be any valid git revision.
|
| 806 |
+
|
| 807 |
+
Returns: `dict[tuple[str, Optional[str]], Union[RepoFile, bytes]]]`
|
| 808 |
+
Key is the file path and revision of the file to copy.
|
| 809 |
+
Value is the raw content as bytes (for regular files) or the file information as a RepoFile (for LFS files).
|
| 810 |
+
|
| 811 |
+
Raises:
|
| 812 |
+
[`~utils.HfHubHTTPError`]
|
| 813 |
+
If the Hub API returned an error.
|
| 814 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 815 |
+
If the Hub API response is improperly formatted.
|
| 816 |
+
"""
|
| 817 |
+
from .hf_api import HfApi, RepoFolder
|
| 818 |
+
|
| 819 |
+
hf_api = HfApi(endpoint=endpoint, headers=headers)
|
| 820 |
+
files_to_copy: dict[tuple[str, Optional[str]], Union["RepoFile", bytes]] = {}
|
| 821 |
+
# Store (path, revision) -> oid mapping
|
| 822 |
+
oid_info: dict[tuple[str, Optional[str]], Optional[str]] = {}
|
| 823 |
+
# 1. Fetch OIDs for destination paths in batches.
|
| 824 |
+
dest_paths = [op.path_in_repo for op in copies]
|
| 825 |
+
for offset in range(0, len(dest_paths), FETCH_LFS_BATCH_SIZE):
|
| 826 |
+
dest_repo_files = hf_api.get_paths_info(
|
| 827 |
+
repo_id=repo_id,
|
| 828 |
+
paths=dest_paths[offset : offset + FETCH_LFS_BATCH_SIZE],
|
| 829 |
+
revision=revision,
|
| 830 |
+
repo_type=repo_type,
|
| 831 |
+
)
|
| 832 |
+
for file in dest_repo_files:
|
| 833 |
+
if not isinstance(file, RepoFolder):
|
| 834 |
+
oid_info[(file.path, revision)] = file.blob_id
|
| 835 |
+
|
| 836 |
+
# 2. Group by source revision and fetch source file info in batches.
|
| 837 |
+
for src_revision, operations in groupby(copies, key=lambda op: op.src_revision):
|
| 838 |
+
operations = list(operations) # type: ignore
|
| 839 |
+
src_paths = [op.src_path_in_repo for op in operations]
|
| 840 |
+
for offset in range(0, len(src_paths), FETCH_LFS_BATCH_SIZE):
|
| 841 |
+
src_repo_files = hf_api.get_paths_info(
|
| 842 |
+
repo_id=repo_id,
|
| 843 |
+
paths=src_paths[offset : offset + FETCH_LFS_BATCH_SIZE],
|
| 844 |
+
revision=src_revision or revision,
|
| 845 |
+
repo_type=repo_type,
|
| 846 |
+
)
|
| 847 |
+
|
| 848 |
+
for src_repo_file in src_repo_files:
|
| 849 |
+
if isinstance(src_repo_file, RepoFolder):
|
| 850 |
+
raise NotImplementedError("Copying a folder is not implemented.")
|
| 851 |
+
oid_info[(src_repo_file.path, src_revision)] = src_repo_file.blob_id
|
| 852 |
+
# If it's an LFS file, store the RepoFile object. Otherwise, download raw bytes.
|
| 853 |
+
if src_repo_file.lfs:
|
| 854 |
+
files_to_copy[(src_repo_file.path, src_revision)] = src_repo_file
|
| 855 |
+
else:
|
| 856 |
+
# TODO: (optimization) download regular files to copy concurrently
|
| 857 |
+
url = hf_hub_url(
|
| 858 |
+
endpoint=endpoint,
|
| 859 |
+
repo_type=repo_type,
|
| 860 |
+
repo_id=repo_id,
|
| 861 |
+
revision=src_revision or revision,
|
| 862 |
+
filename=src_repo_file.path,
|
| 863 |
+
)
|
| 864 |
+
response = get_session().get(url, headers=headers)
|
| 865 |
+
hf_raise_for_status(response)
|
| 866 |
+
files_to_copy[(src_repo_file.path, src_revision)] = response.content
|
| 867 |
+
# 3. Ensure all operations found a corresponding file in the Hub
|
| 868 |
+
# and track src/dest OIDs for each operation.
|
| 869 |
+
for operation in operations:
|
| 870 |
+
if (operation.src_path_in_repo, src_revision) not in files_to_copy:
|
| 871 |
+
raise EntryNotFoundError(
|
| 872 |
+
f"Cannot copy {operation.src_path_in_repo} at revision "
|
| 873 |
+
f"{src_revision or revision}: file is missing on repo."
|
| 874 |
+
)
|
| 875 |
+
operation._src_oid = oid_info.get((operation.src_path_in_repo, operation.src_revision))
|
| 876 |
+
operation._dest_oid = oid_info.get((operation.path_in_repo, revision))
|
| 877 |
+
return files_to_copy
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
def _prepare_commit_payload(
|
| 881 |
+
operations: Iterable[CommitOperation],
|
| 882 |
+
files_to_copy: dict[tuple[str, Optional[str]], Union["RepoFile", bytes]],
|
| 883 |
+
commit_message: str,
|
| 884 |
+
commit_description: Optional[str] = None,
|
| 885 |
+
parent_commit: Optional[str] = None,
|
| 886 |
+
) -> Iterable[dict[str, Any]]:
|
| 887 |
+
"""
|
| 888 |
+
Builds the payload to POST to the `/commit` API of the Hub.
|
| 889 |
+
|
| 890 |
+
Payload is returned as an iterator so that it can be streamed as a ndjson in the
|
| 891 |
+
POST request.
|
| 892 |
+
|
| 893 |
+
For more information, see:
|
| 894 |
+
- https://github.com/huggingface/huggingface_hub/issues/1085#issuecomment-1265208073
|
| 895 |
+
- http://ndjson.org/
|
| 896 |
+
"""
|
| 897 |
+
commit_description = commit_description if commit_description is not None else ""
|
| 898 |
+
|
| 899 |
+
# 1. Send a header item with the commit metadata
|
| 900 |
+
header_value = {"summary": commit_message, "description": commit_description}
|
| 901 |
+
if parent_commit is not None:
|
| 902 |
+
header_value["parentCommit"] = parent_commit
|
| 903 |
+
yield {"key": "header", "value": header_value}
|
| 904 |
+
|
| 905 |
+
nb_ignored_files = 0
|
| 906 |
+
|
| 907 |
+
# 2. Send operations, one per line
|
| 908 |
+
for operation in operations:
|
| 909 |
+
# Skip ignored files
|
| 910 |
+
if isinstance(operation, CommitOperationAdd) and operation._should_ignore:
|
| 911 |
+
logger.debug(f"Skipping file '{operation.path_in_repo}' in commit (ignored by gitignore file).")
|
| 912 |
+
nb_ignored_files += 1
|
| 913 |
+
continue
|
| 914 |
+
|
| 915 |
+
# 2.a. Case adding a regular file
|
| 916 |
+
if isinstance(operation, CommitOperationAdd) and operation._upload_mode == "regular":
|
| 917 |
+
yield {
|
| 918 |
+
"key": "file",
|
| 919 |
+
"value": {
|
| 920 |
+
"content": operation.b64content().decode(),
|
| 921 |
+
"path": operation.path_in_repo,
|
| 922 |
+
"encoding": "base64",
|
| 923 |
+
},
|
| 924 |
+
}
|
| 925 |
+
# 2.b. Case adding an LFS file
|
| 926 |
+
elif isinstance(operation, CommitOperationAdd) and operation._upload_mode == "lfs":
|
| 927 |
+
yield {
|
| 928 |
+
"key": "lfsFile",
|
| 929 |
+
"value": {
|
| 930 |
+
"path": operation.path_in_repo,
|
| 931 |
+
"algo": "sha256",
|
| 932 |
+
"oid": operation.upload_info.sha256.hex(),
|
| 933 |
+
"size": operation.upload_info.size,
|
| 934 |
+
},
|
| 935 |
+
}
|
| 936 |
+
# 2.c. Case deleting a file or folder
|
| 937 |
+
elif isinstance(operation, CommitOperationDelete):
|
| 938 |
+
yield {
|
| 939 |
+
"key": "deletedFolder" if operation.is_folder else "deletedFile",
|
| 940 |
+
"value": {"path": operation.path_in_repo},
|
| 941 |
+
}
|
| 942 |
+
# 2.d. Case copying a file or folder
|
| 943 |
+
elif isinstance(operation, CommitOperationCopy):
|
| 944 |
+
file_to_copy = files_to_copy[(operation.src_path_in_repo, operation.src_revision)]
|
| 945 |
+
if isinstance(file_to_copy, bytes):
|
| 946 |
+
yield {
|
| 947 |
+
"key": "file",
|
| 948 |
+
"value": {
|
| 949 |
+
"content": base64.b64encode(file_to_copy).decode(),
|
| 950 |
+
"path": operation.path_in_repo,
|
| 951 |
+
"encoding": "base64",
|
| 952 |
+
},
|
| 953 |
+
}
|
| 954 |
+
elif file_to_copy.lfs:
|
| 955 |
+
yield {
|
| 956 |
+
"key": "lfsFile",
|
| 957 |
+
"value": {
|
| 958 |
+
"path": operation.path_in_repo,
|
| 959 |
+
"algo": "sha256",
|
| 960 |
+
"oid": file_to_copy.lfs.sha256,
|
| 961 |
+
},
|
| 962 |
+
}
|
| 963 |
+
else:
|
| 964 |
+
raise ValueError(
|
| 965 |
+
"Malformed files_to_copy (should be raw file content as bytes or RepoFile objects with LFS info."
|
| 966 |
+
)
|
| 967 |
+
# 2.e. Never expected to happen
|
| 968 |
+
else:
|
| 969 |
+
raise ValueError(
|
| 970 |
+
f"Unknown operation to commit. Operation: {operation}. Upload mode:"
|
| 971 |
+
f" {getattr(operation, '_upload_mode', None)}"
|
| 972 |
+
)
|
| 973 |
+
|
| 974 |
+
if nb_ignored_files > 0:
|
| 975 |
+
logger.info(f"Skipped {nb_ignored_files} file(s) in commit (ignored by gitignore file).")
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_commit_scheduler.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import atexit
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
import time
|
| 5 |
+
from concurrent.futures import Future
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from io import SEEK_END, SEEK_SET, BytesIO
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from threading import Lock, Thread
|
| 10 |
+
from typing import Optional, Union
|
| 11 |
+
|
| 12 |
+
from .hf_api import DEFAULT_IGNORE_PATTERNS, CommitInfo, CommitOperationAdd, HfApi
|
| 13 |
+
from .utils import filter_repo_objects
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class _FileToUpload:
|
| 21 |
+
"""Temporary dataclass to store info about files to upload. Not meant to be used directly."""
|
| 22 |
+
|
| 23 |
+
local_path: Path
|
| 24 |
+
path_in_repo: str
|
| 25 |
+
size_limit: int
|
| 26 |
+
last_modified: float
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class CommitScheduler:
|
| 30 |
+
"""
|
| 31 |
+
Scheduler to upload a local folder to the Hub at regular intervals (e.g. push to hub every 5 minutes).
|
| 32 |
+
|
| 33 |
+
The recommended way to use the scheduler is to use it as a context manager. This ensures that the scheduler is
|
| 34 |
+
properly stopped and the last commit is triggered when the script ends. The scheduler can also be stopped manually
|
| 35 |
+
with the `stop` method. Checkout the [upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#scheduled-uploads)
|
| 36 |
+
to learn more about how to use it.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
repo_id (`str`):
|
| 40 |
+
The id of the repo to commit to.
|
| 41 |
+
folder_path (`str` or `Path`):
|
| 42 |
+
Path to the local folder to upload regularly.
|
| 43 |
+
every (`int` or `float`, *optional*):
|
| 44 |
+
The number of minutes between each commit. Defaults to 5 minutes.
|
| 45 |
+
path_in_repo (`str`, *optional*):
|
| 46 |
+
Relative path of the directory in the repo, for example: `"checkpoints/"`. Defaults to the root folder
|
| 47 |
+
of the repository.
|
| 48 |
+
repo_type (`str`, *optional*):
|
| 49 |
+
The type of the repo to commit to. Defaults to `model`.
|
| 50 |
+
revision (`str`, *optional*):
|
| 51 |
+
The revision of the repo to commit to. Defaults to `main`.
|
| 52 |
+
private (`bool`, *optional*):
|
| 53 |
+
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
|
| 54 |
+
token (`str`, *optional*):
|
| 55 |
+
The token to use to commit to the repo. Defaults to the token saved on the machine.
|
| 56 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 57 |
+
If provided, only files matching at least one pattern are uploaded.
|
| 58 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 59 |
+
If provided, files matching any of the patterns are not uploaded.
|
| 60 |
+
squash_history (`bool`, *optional*):
|
| 61 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
| 62 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
| 63 |
+
hf_api (`HfApi`, *optional*):
|
| 64 |
+
The [`HfApi`] client to use to commit to the Hub. Can be set with custom settings (user agent, token,...).
|
| 65 |
+
|
| 66 |
+
Example:
|
| 67 |
+
```py
|
| 68 |
+
>>> from pathlib import Path
|
| 69 |
+
>>> from huggingface_hub import CommitScheduler
|
| 70 |
+
|
| 71 |
+
# Scheduler uploads every 10 minutes
|
| 72 |
+
>>> csv_path = Path("watched_folder/data.csv")
|
| 73 |
+
>>> CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path=csv_path.parent, every=10)
|
| 74 |
+
|
| 75 |
+
>>> with csv_path.open("a") as f:
|
| 76 |
+
... f.write("first line")
|
| 77 |
+
|
| 78 |
+
# Some time later (...)
|
| 79 |
+
>>> with csv_path.open("a") as f:
|
| 80 |
+
... f.write("second line")
|
| 81 |
+
```
|
| 82 |
+
|
| 83 |
+
Example using a context manager:
|
| 84 |
+
```py
|
| 85 |
+
>>> from pathlib import Path
|
| 86 |
+
>>> from huggingface_hub import CommitScheduler
|
| 87 |
+
|
| 88 |
+
>>> with CommitScheduler(repo_id="test_scheduler", repo_type="dataset", folder_path="watched_folder", every=10) as scheduler:
|
| 89 |
+
... csv_path = Path("watched_folder/data.csv")
|
| 90 |
+
... with csv_path.open("a") as f:
|
| 91 |
+
... f.write("first line")
|
| 92 |
+
... (...)
|
| 93 |
+
... with csv_path.open("a") as f:
|
| 94 |
+
... f.write("second line")
|
| 95 |
+
|
| 96 |
+
# Scheduler is now stopped and last commit have been triggered
|
| 97 |
+
```
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
*,
|
| 103 |
+
repo_id: str,
|
| 104 |
+
folder_path: Union[str, Path],
|
| 105 |
+
every: Union[int, float] = 5,
|
| 106 |
+
path_in_repo: Optional[str] = None,
|
| 107 |
+
repo_type: Optional[str] = None,
|
| 108 |
+
revision: Optional[str] = None,
|
| 109 |
+
private: Optional[bool] = None,
|
| 110 |
+
token: Optional[str] = None,
|
| 111 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 112 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 113 |
+
squash_history: bool = False,
|
| 114 |
+
hf_api: Optional["HfApi"] = None,
|
| 115 |
+
) -> None:
|
| 116 |
+
self.api = hf_api or HfApi(token=token)
|
| 117 |
+
|
| 118 |
+
# Folder
|
| 119 |
+
self.folder_path = Path(folder_path).expanduser().resolve()
|
| 120 |
+
self.path_in_repo = path_in_repo or ""
|
| 121 |
+
self.allow_patterns = allow_patterns
|
| 122 |
+
|
| 123 |
+
if ignore_patterns is None:
|
| 124 |
+
ignore_patterns = []
|
| 125 |
+
elif isinstance(ignore_patterns, str):
|
| 126 |
+
ignore_patterns = [ignore_patterns]
|
| 127 |
+
self.ignore_patterns = ignore_patterns + DEFAULT_IGNORE_PATTERNS
|
| 128 |
+
|
| 129 |
+
if self.folder_path.is_file():
|
| 130 |
+
raise ValueError(f"'folder_path' must be a directory, not a file: '{self.folder_path}'.")
|
| 131 |
+
self.folder_path.mkdir(parents=True, exist_ok=True)
|
| 132 |
+
|
| 133 |
+
# Repository
|
| 134 |
+
repo_url = self.api.create_repo(repo_id=repo_id, private=private, repo_type=repo_type, exist_ok=True)
|
| 135 |
+
self.repo_id = repo_url.repo_id
|
| 136 |
+
self.repo_type = repo_type
|
| 137 |
+
self.revision = revision
|
| 138 |
+
self.token = token
|
| 139 |
+
|
| 140 |
+
# Keep track of already uploaded files
|
| 141 |
+
self.last_uploaded: dict[Path, float] = {} # key is local path, value is timestamp
|
| 142 |
+
|
| 143 |
+
# Scheduler
|
| 144 |
+
if not every > 0:
|
| 145 |
+
raise ValueError(f"'every' must be a positive integer, not '{every}'.")
|
| 146 |
+
self.lock = Lock()
|
| 147 |
+
self.every = every
|
| 148 |
+
self.squash_history = squash_history
|
| 149 |
+
|
| 150 |
+
logger.info(f"Scheduled job to push '{self.folder_path}' to '{self.repo_id}' every {self.every} minutes.")
|
| 151 |
+
self._scheduler_thread = Thread(target=self._run_scheduler, daemon=True)
|
| 152 |
+
self._scheduler_thread.start()
|
| 153 |
+
atexit.register(self._push_to_hub)
|
| 154 |
+
|
| 155 |
+
self.__stopped = False
|
| 156 |
+
|
| 157 |
+
def stop(self) -> None:
|
| 158 |
+
"""Stop the scheduler.
|
| 159 |
+
|
| 160 |
+
A stopped scheduler cannot be restarted. Mostly for tests purposes.
|
| 161 |
+
"""
|
| 162 |
+
self.__stopped = True
|
| 163 |
+
|
| 164 |
+
def __enter__(self) -> "CommitScheduler":
|
| 165 |
+
return self
|
| 166 |
+
|
| 167 |
+
def __exit__(self, exc_type, exc_value, traceback) -> None:
|
| 168 |
+
# Upload last changes before exiting
|
| 169 |
+
self.trigger().result()
|
| 170 |
+
self.stop()
|
| 171 |
+
return
|
| 172 |
+
|
| 173 |
+
def _run_scheduler(self) -> None:
|
| 174 |
+
"""Dumb thread waiting between each scheduled push to Hub."""
|
| 175 |
+
while True:
|
| 176 |
+
self.last_future = self.trigger()
|
| 177 |
+
time.sleep(self.every * 60)
|
| 178 |
+
if self.__stopped:
|
| 179 |
+
break
|
| 180 |
+
|
| 181 |
+
def trigger(self) -> Future:
|
| 182 |
+
"""Trigger a `push_to_hub` and return a future.
|
| 183 |
+
|
| 184 |
+
This method is automatically called every `every` minutes. You can also call it manually to trigger a commit
|
| 185 |
+
immediately, without waiting for the next scheduled commit.
|
| 186 |
+
"""
|
| 187 |
+
return self.api.run_as_future(self._push_to_hub)
|
| 188 |
+
|
| 189 |
+
def _push_to_hub(self) -> Optional[CommitInfo]:
|
| 190 |
+
if self.__stopped: # If stopped, already scheduled commits are ignored
|
| 191 |
+
return None
|
| 192 |
+
|
| 193 |
+
logger.info("(Background) scheduled commit triggered.")
|
| 194 |
+
try:
|
| 195 |
+
value = self.push_to_hub()
|
| 196 |
+
if self.squash_history:
|
| 197 |
+
logger.info("(Background) squashing repo history.")
|
| 198 |
+
self.api.super_squash_history(repo_id=self.repo_id, repo_type=self.repo_type, branch=self.revision)
|
| 199 |
+
return value
|
| 200 |
+
except Exception as e:
|
| 201 |
+
logger.error(f"Error while pushing to Hub: {e}") # Depending on the setup, error might be silenced
|
| 202 |
+
raise
|
| 203 |
+
|
| 204 |
+
def push_to_hub(self) -> Optional[CommitInfo]:
|
| 205 |
+
"""
|
| 206 |
+
Push folder to the Hub and return the commit info.
|
| 207 |
+
|
| 208 |
+
> [!WARNING]
|
| 209 |
+
> This method is not meant to be called directly. It is run in the background by the scheduler, respecting a
|
| 210 |
+
> queue mechanism to avoid concurrent commits. Making a direct call to the method might lead to concurrency
|
| 211 |
+
> issues.
|
| 212 |
+
|
| 213 |
+
The default behavior of `push_to_hub` is to assume an append-only folder. It lists all files in the folder and
|
| 214 |
+
uploads only changed files. If no changes are found, the method returns without committing anything. If you want
|
| 215 |
+
to change this behavior, you can inherit from [`CommitScheduler`] and override this method. This can be useful
|
| 216 |
+
for example to compress data together in a single file before committing. For more details and examples, check
|
| 217 |
+
out our [integration guide](https://huggingface.co/docs/huggingface_hub/main/en/guides/upload#scheduled-uploads).
|
| 218 |
+
"""
|
| 219 |
+
# Check files to upload (with lock)
|
| 220 |
+
with self.lock:
|
| 221 |
+
logger.debug("Listing files to upload for scheduled commit.")
|
| 222 |
+
|
| 223 |
+
# List files from folder (taken from `_prepare_upload_folder_additions`)
|
| 224 |
+
relpath_to_abspath = {
|
| 225 |
+
path.relative_to(self.folder_path).as_posix(): path
|
| 226 |
+
for path in sorted(self.folder_path.glob("**/*")) # sorted to be deterministic
|
| 227 |
+
if path.is_file()
|
| 228 |
+
}
|
| 229 |
+
prefix = f"{self.path_in_repo.strip('/')}/" if self.path_in_repo else ""
|
| 230 |
+
|
| 231 |
+
# Filter with pattern + filter out unchanged files + retrieve current file size
|
| 232 |
+
files_to_upload: list[_FileToUpload] = []
|
| 233 |
+
for relpath in filter_repo_objects(
|
| 234 |
+
relpath_to_abspath.keys(), allow_patterns=self.allow_patterns, ignore_patterns=self.ignore_patterns
|
| 235 |
+
):
|
| 236 |
+
local_path = relpath_to_abspath[relpath]
|
| 237 |
+
stat = local_path.stat()
|
| 238 |
+
if self.last_uploaded.get(local_path) is None or self.last_uploaded[local_path] != stat.st_mtime:
|
| 239 |
+
files_to_upload.append(
|
| 240 |
+
_FileToUpload(
|
| 241 |
+
local_path=local_path,
|
| 242 |
+
path_in_repo=prefix + relpath,
|
| 243 |
+
size_limit=stat.st_size,
|
| 244 |
+
last_modified=stat.st_mtime,
|
| 245 |
+
)
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
# Return if nothing to upload
|
| 249 |
+
if len(files_to_upload) == 0:
|
| 250 |
+
logger.debug("Dropping schedule commit: no changed file to upload.")
|
| 251 |
+
return None
|
| 252 |
+
|
| 253 |
+
# Convert `_FileToUpload` as `CommitOperationAdd` (=> compute file shas + limit to file size)
|
| 254 |
+
logger.debug("Removing unchanged files since previous scheduled commit.")
|
| 255 |
+
add_operations = [
|
| 256 |
+
CommitOperationAdd(
|
| 257 |
+
# Cap the file to its current size, even if the user append data to it while a scheduled commit is happening
|
| 258 |
+
path_or_fileobj=PartialFileIO(file_to_upload.local_path, size_limit=file_to_upload.size_limit),
|
| 259 |
+
path_in_repo=file_to_upload.path_in_repo,
|
| 260 |
+
)
|
| 261 |
+
for file_to_upload in files_to_upload
|
| 262 |
+
]
|
| 263 |
+
|
| 264 |
+
# Upload files (append mode expected - no need for lock)
|
| 265 |
+
logger.debug("Uploading files for scheduled commit.")
|
| 266 |
+
commit_info = self.api.create_commit(
|
| 267 |
+
repo_id=self.repo_id,
|
| 268 |
+
repo_type=self.repo_type,
|
| 269 |
+
operations=add_operations,
|
| 270 |
+
commit_message="Scheduled Commit",
|
| 271 |
+
revision=self.revision,
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
# Successful commit: keep track of the latest "last_modified" for each file
|
| 275 |
+
for file in files_to_upload:
|
| 276 |
+
self.last_uploaded[file.local_path] = file.last_modified
|
| 277 |
+
return commit_info
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
class PartialFileIO(BytesIO):
|
| 281 |
+
"""A file-like object that reads only the first part of a file.
|
| 282 |
+
|
| 283 |
+
Useful to upload a file to the Hub when the user might still be appending data to it. Only the first part of the
|
| 284 |
+
file is uploaded (i.e. the part that was available when the filesystem was first scanned).
|
| 285 |
+
|
| 286 |
+
In practice, only used internally by the CommitScheduler to regularly push a folder to the Hub with minimal
|
| 287 |
+
disturbance for the user. The object is passed to `CommitOperationAdd`.
|
| 288 |
+
|
| 289 |
+
Only supports `read`, `tell` and `seek` methods.
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
file_path (`str` or `Path`):
|
| 293 |
+
Path to the file to read.
|
| 294 |
+
size_limit (`int`):
|
| 295 |
+
The maximum number of bytes to read from the file. If the file is larger than this, only the first part
|
| 296 |
+
will be read (and uploaded).
|
| 297 |
+
"""
|
| 298 |
+
|
| 299 |
+
def __init__(self, file_path: Union[str, Path], size_limit: int) -> None:
|
| 300 |
+
self._file_path = Path(file_path)
|
| 301 |
+
self._file = self._file_path.open("rb")
|
| 302 |
+
self._size_limit = min(size_limit, os.fstat(self._file.fileno()).st_size)
|
| 303 |
+
|
| 304 |
+
def __del__(self) -> None:
|
| 305 |
+
self._file.close()
|
| 306 |
+
return super().__del__()
|
| 307 |
+
|
| 308 |
+
def __repr__(self) -> str:
|
| 309 |
+
return f"<PartialFileIO file_path={self._file_path} size_limit={self._size_limit}>"
|
| 310 |
+
|
| 311 |
+
def __len__(self) -> int:
|
| 312 |
+
return self._size_limit
|
| 313 |
+
|
| 314 |
+
def __getattribute__(self, name: str):
|
| 315 |
+
if name.startswith("_") or name in ("read", "tell", "seek", "fileno"): # only 4 public methods supported
|
| 316 |
+
return super().__getattribute__(name)
|
| 317 |
+
raise NotImplementedError(f"PartialFileIO does not support '{name}'.")
|
| 318 |
+
|
| 319 |
+
def fileno(self):
|
| 320 |
+
raise AttributeError("PartialFileIO does not have a fileno.")
|
| 321 |
+
|
| 322 |
+
def tell(self) -> int:
|
| 323 |
+
"""Return the current file position."""
|
| 324 |
+
return self._file.tell()
|
| 325 |
+
|
| 326 |
+
def seek(self, __offset: int, __whence: int = SEEK_SET) -> int:
|
| 327 |
+
"""Change the stream position to the given offset.
|
| 328 |
+
|
| 329 |
+
Behavior is the same as a regular file, except that the position is capped to the size limit.
|
| 330 |
+
"""
|
| 331 |
+
if __whence == SEEK_END:
|
| 332 |
+
# SEEK_END => set from the truncated end
|
| 333 |
+
__offset = len(self) + __offset
|
| 334 |
+
__whence = SEEK_SET
|
| 335 |
+
|
| 336 |
+
pos = self._file.seek(__offset, __whence)
|
| 337 |
+
if pos > self._size_limit:
|
| 338 |
+
return self._file.seek(self._size_limit)
|
| 339 |
+
return pos
|
| 340 |
+
|
| 341 |
+
def read(self, __size: Optional[int] = -1) -> bytes:
|
| 342 |
+
"""Read at most `__size` bytes from the file.
|
| 343 |
+
|
| 344 |
+
Behavior is the same as a regular file, except that it is capped to the size limit.
|
| 345 |
+
"""
|
| 346 |
+
current = self._file.tell()
|
| 347 |
+
if __size is None or __size < 0:
|
| 348 |
+
# Read until file limit
|
| 349 |
+
truncated_size = self._size_limit - current
|
| 350 |
+
else:
|
| 351 |
+
# Read until file limit or __size
|
| 352 |
+
truncated_size = min(__size, self._size_limit - current)
|
| 353 |
+
return self._file.read(truncated_size)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_dataset_viewer.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 json
|
| 16 |
+
import os
|
| 17 |
+
import shutil
|
| 18 |
+
import subprocess
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from typing import TYPE_CHECKING, Any, Union
|
| 21 |
+
|
| 22 |
+
from . import constants
|
| 23 |
+
from .utils import get_token
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
import duckdb
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@dataclass(frozen=True)
|
| 31 |
+
class DatasetParquetEntry:
|
| 32 |
+
"""Represents a single parquet file available for a dataset on the Hub."""
|
| 33 |
+
|
| 34 |
+
config: str
|
| 35 |
+
split: str
|
| 36 |
+
url: str
|
| 37 |
+
size: int
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def execute_raw_sql_query(sql_query: str, *, token: Union[str, bool, None] = None) -> list[dict[str, Any]]:
|
| 41 |
+
normalized_query = sql_query.strip().rstrip(";").strip()
|
| 42 |
+
_raise_on_forbidden_query(normalized_query)
|
| 43 |
+
|
| 44 |
+
connection = None
|
| 45 |
+
try:
|
| 46 |
+
connection = _get_duckdb_connection(token=token)
|
| 47 |
+
relation = connection.sql(normalized_query)
|
| 48 |
+
if relation is None:
|
| 49 |
+
raise ValueError("SQL query must return rows.")
|
| 50 |
+
|
| 51 |
+
if isinstance(relation, _DuckDBCliRelation):
|
| 52 |
+
# DuckDB binary => run CLI => parse JSON
|
| 53 |
+
return relation.execute()
|
| 54 |
+
else:
|
| 55 |
+
# DuckDB Python API => fetch columns + rows => convert to dicts
|
| 56 |
+
columns = tuple(column[0] for column in relation.description)
|
| 57 |
+
rows = tuple(tuple(row) for row in relation.fetchall())
|
| 58 |
+
return [dict(zip(columns, row)) for row in rows]
|
| 59 |
+
finally:
|
| 60 |
+
if connection is not None:
|
| 61 |
+
connection.close()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _raise_on_forbidden_query(query: str) -> None:
|
| 65 |
+
if len(query) == 0:
|
| 66 |
+
raise ValueError("SQL query cannot be empty.")
|
| 67 |
+
|
| 68 |
+
# DuckDB CLI meta-commands are dot-prefixed words (e.g. `.shell`, `.output`).
|
| 69 |
+
# Let's forbid them for now but allow SQL expressions like `.5` that can legitimately start a line.
|
| 70 |
+
for line in query.splitlines():
|
| 71 |
+
stripped = line.lstrip()
|
| 72 |
+
if stripped.startswith(".") and stripped[1:2].isalpha():
|
| 73 |
+
raise ValueError("DuckDB CLI meta-commands are not allowed in SQL queries.")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _get_duckdb_connection(
|
| 77 |
+
token: Union[str, bool, None],
|
| 78 |
+
) -> Union["duckdb.DuckDBPyConnection", "_DuckDBCliConnection"]:
|
| 79 |
+
try:
|
| 80 |
+
# If DuckDB is installed as a Python package, use it!
|
| 81 |
+
import duckdb
|
| 82 |
+
except ImportError as error:
|
| 83 |
+
# Otherwise, use the DuckDB CLI binary.
|
| 84 |
+
duckdb_binary = shutil.which("duckdb")
|
| 85 |
+
if duckdb_binary is None:
|
| 86 |
+
raise ImportError(
|
| 87 |
+
"DuckDB is required for `hf datasets sql`. Install the Python package with `pip install duckdb` or "
|
| 88 |
+
"install the DuckDB CLI binary (for example `brew install duckdb`)."
|
| 89 |
+
) from error
|
| 90 |
+
return _DuckDBCliConnection(binary_path=duckdb_binary, token=token)
|
| 91 |
+
|
| 92 |
+
# Create a new connection (Python API).
|
| 93 |
+
connection = duckdb.connect()
|
| 94 |
+
try:
|
| 95 |
+
for statement in _build_duckdb_secret_statements(token):
|
| 96 |
+
connection.execute(statement)
|
| 97 |
+
return connection
|
| 98 |
+
except Exception:
|
| 99 |
+
connection.close()
|
| 100 |
+
raise
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass
|
| 104 |
+
class _DuckDBCliConnection:
|
| 105 |
+
"""DuckDB connection.
|
| 106 |
+
|
| 107 |
+
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
binary_path: str
|
| 111 |
+
token: Union[str, bool, None]
|
| 112 |
+
|
| 113 |
+
def __post_init__(self) -> None:
|
| 114 |
+
self._setup_statements = _build_duckdb_secret_statements(self.token)
|
| 115 |
+
|
| 116 |
+
def sql(self, query: str) -> "_DuckDBCliRelation":
|
| 117 |
+
return _DuckDBCliRelation(binary_path=self.binary_path, setup_statements=self._setup_statements, query=query)
|
| 118 |
+
|
| 119 |
+
def close(self) -> None:
|
| 120 |
+
pass
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@dataclass
|
| 124 |
+
class _DuckDBCliRelation:
|
| 125 |
+
"""DuckDB relation.
|
| 126 |
+
|
| 127 |
+
Mimics the DuckDB Python API, but runs the queries via the DuckDB CLI binary.
|
| 128 |
+
"""
|
| 129 |
+
|
| 130 |
+
binary_path: str
|
| 131 |
+
setup_statements: list[str]
|
| 132 |
+
query: str
|
| 133 |
+
|
| 134 |
+
def execute(self) -> list[dict[str, Any]]:
|
| 135 |
+
# Build the DuckDB CLI input.
|
| 136 |
+
setup = []
|
| 137 |
+
if self.setup_statements:
|
| 138 |
+
setup = [
|
| 139 |
+
f".output {os.devnull}",
|
| 140 |
+
*(f"{stmt};" for stmt in self.setup_statements),
|
| 141 |
+
".output",
|
| 142 |
+
]
|
| 143 |
+
full_query = "\n".join(setup + [self.query + ";"])
|
| 144 |
+
|
| 145 |
+
# Run DuckDB binary
|
| 146 |
+
result = subprocess.run(
|
| 147 |
+
[self.binary_path, "-json"],
|
| 148 |
+
input=full_query,
|
| 149 |
+
capture_output=True,
|
| 150 |
+
text=True,
|
| 151 |
+
check=False,
|
| 152 |
+
)
|
| 153 |
+
if result.returncode != 0:
|
| 154 |
+
error_message = result.stderr.strip() or result.stdout.strip() or "DuckDB CLI command failed."
|
| 155 |
+
raise RuntimeError(error_message)
|
| 156 |
+
|
| 157 |
+
# Parse JSON output and return
|
| 158 |
+
return json.loads(result.stdout.strip())
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def _build_duckdb_secret_statements(token: Union[str, bool, None]) -> list[str]:
|
| 162 |
+
if token is None or token is True:
|
| 163 |
+
token = get_token()
|
| 164 |
+
|
| 165 |
+
if not token:
|
| 166 |
+
return []
|
| 167 |
+
|
| 168 |
+
escaped_token = token.replace("'", "''")
|
| 169 |
+
escaped_endpoint = constants.ENDPOINT.replace("'", "''")
|
| 170 |
+
return [
|
| 171 |
+
f"CREATE OR REPLACE SECRET hf_hub_token (TYPE HTTP, BEARER_TOKEN '{escaped_token}', SCOPE '{escaped_endpoint}')",
|
| 172 |
+
f"CREATE OR REPLACE SECRET hf_token (TYPE HUGGINGFACE, TOKEN '{escaped_token}')",
|
| 173 |
+
]
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_eval_results.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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docs/hub/eval-results for more details.
|
| 4 |
+
Specifications are available at https://github.com/huggingface/hub-docs/blob/main/eval_results.yaml.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from typing import Any, Optional
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass
|
| 12 |
+
class EvalResultEntry:
|
| 13 |
+
"""
|
| 14 |
+
Evaluation result entry for the `.eval_results/*.yaml` format.
|
| 15 |
+
|
| 16 |
+
Represents evaluation scores stored in model repos that automatically appear on
|
| 17 |
+
the model page and the benchmark dataset's leaderboard.
|
| 18 |
+
|
| 19 |
+
For the legacy `model-index` format in `README.md`, use [`EvalResult`] instead.
|
| 20 |
+
|
| 21 |
+
See https://huggingface.co/docs/hub/eval-results for more details.
|
| 22 |
+
|
| 23 |
+
Args:
|
| 24 |
+
dataset_id (`str`):
|
| 25 |
+
Benchmark dataset ID from the Hub. Example: "cais/hle", "Idavidrein/gpqa".
|
| 26 |
+
task_id (`str`):
|
| 27 |
+
Task identifier within the benchmark. Example: "gpqa_diamond".
|
| 28 |
+
value (`Any`):
|
| 29 |
+
The metric value. Example: 20.90.
|
| 30 |
+
dataset_revision (`str`, *optional*):
|
| 31 |
+
Git SHA of the benchmark dataset.
|
| 32 |
+
verify_token (`str`, *optional*):
|
| 33 |
+
A signature that can be used to prove that evaluation is provably auditable and reproducible.
|
| 34 |
+
date (`str`, *optional*):
|
| 35 |
+
When the evaluation was run (ISO-8601 datetime). Defaults to git commit time.
|
| 36 |
+
source_url (`str`, *optional*):
|
| 37 |
+
Link to the evaluation source (e.g., https://huggingface.co/spaces/SaylorTwift/smollm3-mmlu-pro). Required if `source_name`, `source_user`, or `source_org` is provided.
|
| 38 |
+
source_name (`str`, *optional*):
|
| 39 |
+
Display name for the source. Example: "Eval Logs".
|
| 40 |
+
source_user (`str`, *optional*):
|
| 41 |
+
HF user name for attribution. Example: "celinah".
|
| 42 |
+
source_org (`str`, *optional*):
|
| 43 |
+
HF org name for attribution. Example: "cais".
|
| 44 |
+
notes (`str`, *optional*):
|
| 45 |
+
Details about the evaluation setup. Example: "tools", "no-tools", "chain-of-thought".
|
| 46 |
+
|
| 47 |
+
Example:
|
| 48 |
+
```python
|
| 49 |
+
>>> from huggingface_hub import EvalResultEntry
|
| 50 |
+
>>> # Minimal example with required fields only
|
| 51 |
+
>>> result = EvalResultEntry(
|
| 52 |
+
... dataset_id="Idavidrein/gpqa",
|
| 53 |
+
... task_id="gpqa_diamond",
|
| 54 |
+
... value=0.412,
|
| 55 |
+
... )
|
| 56 |
+
>>> # Full example with all fields
|
| 57 |
+
>>> result = EvalResultEntry(
|
| 58 |
+
... dataset_id="cais/hle",
|
| 59 |
+
... task_id="default",
|
| 60 |
+
... value=20.90,
|
| 61 |
+
... dataset_revision="5503434ddd753f426f4b38109466949a1217c2bb",
|
| 62 |
+
... verify_token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
|
| 63 |
+
... date="2025-01-15T10:30:00Z",
|
| 64 |
+
... source_url="https://huggingface.co/datasets/cais/hle",
|
| 65 |
+
... source_name="CAIS HLE",
|
| 66 |
+
... source_org="cais",
|
| 67 |
+
... notes="no-tools",
|
| 68 |
+
... )
|
| 69 |
+
|
| 70 |
+
```
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
+
dataset_id: str
|
| 74 |
+
task_id: str
|
| 75 |
+
value: Any
|
| 76 |
+
dataset_revision: Optional[str] = None
|
| 77 |
+
verify_token: Optional[str] = None
|
| 78 |
+
date: Optional[str] = None
|
| 79 |
+
source_url: Optional[str] = None
|
| 80 |
+
source_name: Optional[str] = None
|
| 81 |
+
source_user: Optional[str] = None
|
| 82 |
+
source_org: Optional[str] = None
|
| 83 |
+
notes: Optional[str] = None
|
| 84 |
+
|
| 85 |
+
def __post_init__(self) -> None:
|
| 86 |
+
if (
|
| 87 |
+
self.source_name is not None or self.source_user is not None or self.source_org is not None
|
| 88 |
+
) and self.source_url is None:
|
| 89 |
+
raise ValueError(
|
| 90 |
+
"If `source_name`, `source_user`, or `source_org` is provided, `source_url` must also be provided."
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def eval_result_entries_to_yaml(entries: list[EvalResultEntry]) -> list[dict[str, Any]]:
|
| 95 |
+
"""Convert a list of [`EvalResultEntry`] objects to a YAML-serializable list of dicts.
|
| 96 |
+
|
| 97 |
+
This produces the format expected in `.eval_results/*.yaml` files.
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
entries (`list[EvalResultEntry]`):
|
| 101 |
+
List of evaluation result entries to serialize.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
`list[dict[str, Any]]`: A list of dictionaries ready to be dumped to YAML.
|
| 105 |
+
|
| 106 |
+
Example:
|
| 107 |
+
```python
|
| 108 |
+
>>> from huggingface_hub import EvalResultEntry, eval_result_entries_to_yaml
|
| 109 |
+
>>> entries = [
|
| 110 |
+
... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
|
| 111 |
+
... EvalResultEntry(dataset_id="Idavidrein/gpqa", task_id="gpqa_diamond", value=0.412),
|
| 112 |
+
... ]
|
| 113 |
+
>>> yaml_data = eval_result_entries_to_yaml(entries)
|
| 114 |
+
>>> yaml_data[0]
|
| 115 |
+
{'dataset': {'id': 'cais/hle', 'task_id': 'default'}, 'value': 20.9}
|
| 116 |
+
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
To upload eval results to the Hub:
|
| 120 |
+
```python
|
| 121 |
+
>>> import yaml
|
| 122 |
+
>>> from huggingface_hub import upload_file, EvalResultEntry, eval_result_entries_to_yaml
|
| 123 |
+
>>> entries = [
|
| 124 |
+
... EvalResultEntry(dataset_id="cais/hle", task_id="default", value=20.90),
|
| 125 |
+
... ]
|
| 126 |
+
>>> yaml_content = yaml.dump(eval_result_entries_to_yaml(entries))
|
| 127 |
+
>>> upload_file(
|
| 128 |
+
... path_or_fileobj=yaml_content.encode(),
|
| 129 |
+
... path_in_repo=".eval_results/hle.yaml",
|
| 130 |
+
... repo_id="your-username/your-model",
|
| 131 |
+
... )
|
| 132 |
+
|
| 133 |
+
```
|
| 134 |
+
"""
|
| 135 |
+
result = []
|
| 136 |
+
for entry in entries:
|
| 137 |
+
# build the dataset object
|
| 138 |
+
dataset: dict[str, Any] = {"id": entry.dataset_id, "task_id": entry.task_id}
|
| 139 |
+
if entry.dataset_revision is not None:
|
| 140 |
+
dataset["revision"] = entry.dataset_revision
|
| 141 |
+
|
| 142 |
+
data: dict[str, Any] = {"dataset": dataset, "value": entry.value}
|
| 143 |
+
if entry.verify_token is not None:
|
| 144 |
+
data["verifyToken"] = entry.verify_token
|
| 145 |
+
if entry.date is not None:
|
| 146 |
+
data["date"] = entry.date
|
| 147 |
+
# build the source object
|
| 148 |
+
if entry.source_url is not None:
|
| 149 |
+
source: dict[str, Any] = {"url": entry.source_url}
|
| 150 |
+
if entry.source_name is not None:
|
| 151 |
+
source["name"] = entry.source_name
|
| 152 |
+
if entry.source_user is not None:
|
| 153 |
+
source["user"] = entry.source_user
|
| 154 |
+
if entry.source_org is not None:
|
| 155 |
+
source["org"] = entry.source_org
|
| 156 |
+
data["source"] = source
|
| 157 |
+
if entry.notes is not None:
|
| 158 |
+
data["notes"] = entry.notes
|
| 159 |
+
|
| 160 |
+
result.append(data)
|
| 161 |
+
return result
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def parse_eval_result_entries(data: list[dict[str, Any]]) -> list[EvalResultEntry]:
|
| 165 |
+
"""Parse a list of dicts into [`EvalResultEntry`] objects.
|
| 166 |
+
|
| 167 |
+
This parses the `.eval_results/*.yaml` format. For the legacy `model-index` format,
|
| 168 |
+
use [`model_index_to_eval_results`] instead.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
data (`list[dict[str, Any]]`):
|
| 172 |
+
A list of dictionaries (e.g., parsed from YAML or API response).
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
`list[EvalResultEntry]`: A list of evaluation result entry objects.
|
| 176 |
+
|
| 177 |
+
Example:
|
| 178 |
+
```python
|
| 179 |
+
>>> from huggingface_hub import parse_eval_result_entries
|
| 180 |
+
>>> data = [
|
| 181 |
+
... {"dataset": {"id": "cais/hle", "task_id": "default"}, "value": 20.90},
|
| 182 |
+
... {"dataset": {"id": "Idavidrein/gpqa", "task_id": "gpqa_diamond"}, "value": 0.412},
|
| 183 |
+
... ]
|
| 184 |
+
>>> entries = parse_eval_result_entries(data)
|
| 185 |
+
>>> entries[0].dataset_id
|
| 186 |
+
'cais/hle'
|
| 187 |
+
>>> entries[0].value
|
| 188 |
+
20.9
|
| 189 |
+
|
| 190 |
+
```
|
| 191 |
+
"""
|
| 192 |
+
entries = []
|
| 193 |
+
for item in data:
|
| 194 |
+
entry_data = item.get("data", item)
|
| 195 |
+
dataset = entry_data.get("dataset", {})
|
| 196 |
+
source = entry_data.get("source", {})
|
| 197 |
+
entry = EvalResultEntry(
|
| 198 |
+
dataset_id=dataset["id"],
|
| 199 |
+
value=entry_data["value"],
|
| 200 |
+
task_id=dataset["task_id"],
|
| 201 |
+
dataset_revision=dataset.get("revision"),
|
| 202 |
+
verify_token=entry_data.get("verifyToken"),
|
| 203 |
+
date=entry_data.get("date"),
|
| 204 |
+
source_url=source.get("url") if source else None,
|
| 205 |
+
source_name=source.get("name") if source else None,
|
| 206 |
+
source_user=source.get("user") if source else None,
|
| 207 |
+
source_org=source.get("org") if source else None,
|
| 208 |
+
notes=entry_data.get("notes"),
|
| 209 |
+
)
|
| 210 |
+
entries.append(entry)
|
| 211 |
+
return entries
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_jobs_api.py
ADDED
|
@@ -0,0 +1,399 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025-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 |
+
from dataclasses import dataclass
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
from enum import Enum
|
| 18 |
+
from typing import Any, Optional, Union
|
| 19 |
+
|
| 20 |
+
from huggingface_hub import constants
|
| 21 |
+
from huggingface_hub._space_api import SpaceHardware
|
| 22 |
+
from huggingface_hub.utils._datetime import parse_datetime
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class JobStage(str, Enum):
|
| 26 |
+
"""
|
| 27 |
+
Enumeration of possible stage of a Job on the Hub.
|
| 28 |
+
|
| 29 |
+
Value can be compared to a string:
|
| 30 |
+
```py
|
| 31 |
+
assert JobStage.COMPLETED == "COMPLETED"
|
| 32 |
+
```
|
| 33 |
+
Possible values are: `COMPLETED`, `CANCELED`, `ERROR`, `DELETED`, `RUNNING`.
|
| 34 |
+
Taken from https://github.com/huggingface/moon-landing/blob/main/server/job_types/JobInfo.ts#L61 (private url).
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
# Copied from moon-landing > server > lib > Job.ts
|
| 38 |
+
COMPLETED = "COMPLETED"
|
| 39 |
+
CANCELED = "CANCELED"
|
| 40 |
+
ERROR = "ERROR"
|
| 41 |
+
DELETED = "DELETED"
|
| 42 |
+
RUNNING = "RUNNING"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass
|
| 46 |
+
class JobStatus:
|
| 47 |
+
stage: JobStage
|
| 48 |
+
message: Optional[str]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass
|
| 52 |
+
class JobOwner:
|
| 53 |
+
id: str
|
| 54 |
+
name: str
|
| 55 |
+
type: str
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class JobInfo:
|
| 60 |
+
"""
|
| 61 |
+
Contains information about a Job.
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
id (`str`):
|
| 65 |
+
Job ID.
|
| 66 |
+
created_at (`datetime` or `None`):
|
| 67 |
+
When the Job was created.
|
| 68 |
+
docker_image (`str` or `None`):
|
| 69 |
+
The Docker image from Docker Hub used for the Job.
|
| 70 |
+
Can be None if space_id is present instead.
|
| 71 |
+
space_id (`str` or `None`):
|
| 72 |
+
The Docker image from Hugging Face Spaces used for the Job.
|
| 73 |
+
Can be None if docker_image is present instead.
|
| 74 |
+
command (`list[str]` or `None`):
|
| 75 |
+
Command of the Job, e.g. `["python", "-c", "print('hello world')"]`
|
| 76 |
+
arguments (`list[str]` or `None`):
|
| 77 |
+
Arguments passed to the command
|
| 78 |
+
environment (`dict[str]` or `None`):
|
| 79 |
+
Environment variables of the Job as a dictionary.
|
| 80 |
+
secrets (`dict[str]` or `None`):
|
| 81 |
+
Secret environment variables of the Job (encrypted).
|
| 82 |
+
flavor (`str` or `None`):
|
| 83 |
+
Flavor for the hardware, as in Hugging Face Spaces. See [`SpaceHardware`] for possible values.
|
| 84 |
+
E.g. `"cpu-basic"`.
|
| 85 |
+
labels (`dict[str, str]` or `None`):
|
| 86 |
+
Labels to attach to the job (key-value pairs).
|
| 87 |
+
status: (`JobStatus` or `None`):
|
| 88 |
+
Status of the Job, e.g. `JobStatus(stage="RUNNING", message=None)`
|
| 89 |
+
See [`JobStage`] for possible stage values.
|
| 90 |
+
owner: (`JobOwner` or `None`):
|
| 91 |
+
Owner of the Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
|
| 92 |
+
|
| 93 |
+
Example:
|
| 94 |
+
|
| 95 |
+
```python
|
| 96 |
+
>>> from huggingface_hub import run_job
|
| 97 |
+
>>> job = run_job(
|
| 98 |
+
... image="python:3.12",
|
| 99 |
+
... command=["python", "-c", "print('Hello from the cloud!')"]
|
| 100 |
+
... )
|
| 101 |
+
>>> job
|
| 102 |
+
JobInfo(id='687fb701029421ae5549d998', created_at=datetime.datetime(2025, 7, 22, 16, 6, 25, 79000, tzinfo=datetime.timezone.utc), docker_image='python:3.12', space_id=None, command=['python', '-c', "print('Hello from the cloud!')"], arguments=[], environment={}, secrets={}, flavor='cpu-basic', labels=None, status=JobStatus(stage='RUNNING', message=None), owner=JobOwner(id='5e9ecfc04957053f60648a3e', name='lhoestq', type='user'), endpoint='https://huggingface.co', url='https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998')
|
| 103 |
+
>>> job.id
|
| 104 |
+
'687fb701029421ae5549d998'
|
| 105 |
+
>>> job.url
|
| 106 |
+
'https://huggingface.co/jobs/lhoestq/687fb701029421ae5549d998'
|
| 107 |
+
>>> job.status.stage
|
| 108 |
+
'RUNNING'
|
| 109 |
+
```
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
id: str
|
| 113 |
+
created_at: Optional[datetime]
|
| 114 |
+
docker_image: Optional[str]
|
| 115 |
+
space_id: Optional[str]
|
| 116 |
+
command: Optional[list[str]]
|
| 117 |
+
arguments: Optional[list[str]]
|
| 118 |
+
environment: Optional[dict[str, Any]]
|
| 119 |
+
secrets: Optional[dict[str, Any]]
|
| 120 |
+
flavor: Optional[SpaceHardware]
|
| 121 |
+
labels: Optional[dict[str, str]]
|
| 122 |
+
status: JobStatus
|
| 123 |
+
owner: JobOwner
|
| 124 |
+
|
| 125 |
+
# Inferred fields
|
| 126 |
+
endpoint: str
|
| 127 |
+
url: str
|
| 128 |
+
|
| 129 |
+
def __init__(self, **kwargs) -> None:
|
| 130 |
+
self.id = kwargs["id"]
|
| 131 |
+
created_at = kwargs.get("createdAt") or kwargs.get("created_at")
|
| 132 |
+
self.created_at = parse_datetime(created_at) if created_at else None
|
| 133 |
+
self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image")
|
| 134 |
+
self.space_id = kwargs.get("spaceId") or kwargs.get("space_id")
|
| 135 |
+
owner = kwargs.get("owner", {})
|
| 136 |
+
self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
|
| 137 |
+
self.command = kwargs.get("command")
|
| 138 |
+
self.arguments = kwargs.get("arguments")
|
| 139 |
+
self.environment = kwargs.get("environment")
|
| 140 |
+
self.secrets = kwargs.get("secrets")
|
| 141 |
+
self.flavor = kwargs.get("flavor")
|
| 142 |
+
self.labels = kwargs.get("labels")
|
| 143 |
+
status = kwargs.get("status", {})
|
| 144 |
+
self.status = JobStatus(stage=status["stage"], message=status.get("message"))
|
| 145 |
+
|
| 146 |
+
# Inferred fields
|
| 147 |
+
self.endpoint = kwargs.get("endpoint", constants.ENDPOINT)
|
| 148 |
+
self.url = f"{self.endpoint}/jobs/{self.owner.name}/{self.id}"
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
@dataclass
|
| 152 |
+
class JobSpec:
|
| 153 |
+
docker_image: Optional[str]
|
| 154 |
+
space_id: Optional[str]
|
| 155 |
+
command: Optional[list[str]]
|
| 156 |
+
arguments: Optional[list[str]]
|
| 157 |
+
environment: Optional[dict[str, Any]]
|
| 158 |
+
secrets: Optional[dict[str, Any]]
|
| 159 |
+
flavor: Optional[SpaceHardware]
|
| 160 |
+
timeout: Optional[int]
|
| 161 |
+
tags: Optional[list[str]]
|
| 162 |
+
arch: Optional[str]
|
| 163 |
+
labels: Optional[dict[str, str]]
|
| 164 |
+
|
| 165 |
+
def __init__(self, **kwargs) -> None:
|
| 166 |
+
self.docker_image = kwargs.get("dockerImage") or kwargs.get("docker_image")
|
| 167 |
+
self.space_id = kwargs.get("spaceId") or kwargs.get("space_id")
|
| 168 |
+
self.command = kwargs.get("command")
|
| 169 |
+
self.arguments = kwargs.get("arguments")
|
| 170 |
+
self.environment = kwargs.get("environment")
|
| 171 |
+
self.secrets = kwargs.get("secrets")
|
| 172 |
+
self.flavor = kwargs.get("flavor")
|
| 173 |
+
self.timeout = kwargs.get("timeout")
|
| 174 |
+
self.tags = kwargs.get("tags")
|
| 175 |
+
self.arch = kwargs.get("arch")
|
| 176 |
+
self.labels = kwargs.get("labels")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
@dataclass
|
| 180 |
+
class LastJobInfo:
|
| 181 |
+
id: str
|
| 182 |
+
at: datetime
|
| 183 |
+
|
| 184 |
+
def __init__(self, **kwargs) -> None:
|
| 185 |
+
self.id = kwargs["id"]
|
| 186 |
+
self.at = parse_datetime(kwargs["at"])
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
@dataclass
|
| 190 |
+
class ScheduledJobStatus:
|
| 191 |
+
last_job: Optional[LastJobInfo]
|
| 192 |
+
next_job_run_at: Optional[datetime]
|
| 193 |
+
|
| 194 |
+
def __init__(self, **kwargs) -> None:
|
| 195 |
+
last_job = kwargs.get("lastJob") or kwargs.get("last_job")
|
| 196 |
+
self.last_job = LastJobInfo(**last_job) if last_job else None
|
| 197 |
+
next_job_run_at = kwargs.get("nextJobRunAt") or kwargs.get("next_job_run_at")
|
| 198 |
+
self.next_job_run_at = parse_datetime(str(next_job_run_at)) if next_job_run_at else None
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
@dataclass
|
| 202 |
+
class ScheduledJobInfo:
|
| 203 |
+
"""
|
| 204 |
+
Contains information about a Job.
|
| 205 |
+
|
| 206 |
+
Args:
|
| 207 |
+
id (`str`):
|
| 208 |
+
Scheduled Job ID.
|
| 209 |
+
created_at (`datetime` or `None`):
|
| 210 |
+
When the scheduled Job was created.
|
| 211 |
+
tags (`list[str]` or `None`):
|
| 212 |
+
The tags of the scheduled Job.
|
| 213 |
+
schedule (`str` or `None`):
|
| 214 |
+
One of "@annually", "@yearly", "@monthly", "@weekly", "@daily", "@hourly", or a
|
| 215 |
+
CRON schedule expression (e.g., '0 9 * * 1' for 9 AM every Monday).
|
| 216 |
+
suspend (`bool` or `None`):
|
| 217 |
+
Whether the scheduled job is suspended (paused).
|
| 218 |
+
concurrency (`bool` or `None`):
|
| 219 |
+
Whether multiple instances of this Job can run concurrently.
|
| 220 |
+
status (`ScheduledJobStatus` or `None`):
|
| 221 |
+
Status of the scheduled Job.
|
| 222 |
+
owner: (`JobOwner` or `None`):
|
| 223 |
+
Owner of the scheduled Job, e.g. `JobOwner(id="5e9ecfc04957053f60648a3e", name="lhoestq", type="user")`
|
| 224 |
+
job_spec: (`JobSpec` or `None`):
|
| 225 |
+
Specifications of the Job.
|
| 226 |
+
|
| 227 |
+
Example:
|
| 228 |
+
|
| 229 |
+
```python
|
| 230 |
+
>>> from huggingface_hub import run_job
|
| 231 |
+
>>> scheduled_job = create_scheduled_job(
|
| 232 |
+
... image="python:3.12",
|
| 233 |
+
... command=["python", "-c", "print('Hello from the cloud!')"],
|
| 234 |
+
... schedule="@hourly",
|
| 235 |
+
... )
|
| 236 |
+
>>> scheduled_job.id
|
| 237 |
+
'687fb701029421ae5549d999'
|
| 238 |
+
>>> scheduled_job.status.next_job_run_at
|
| 239 |
+
datetime.datetime(2025, 7, 22, 17, 6, 25, 79000, tzinfo=datetime.timezone.utc)
|
| 240 |
+
```
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
id: str
|
| 244 |
+
created_at: Optional[datetime]
|
| 245 |
+
job_spec: JobSpec
|
| 246 |
+
schedule: Optional[str]
|
| 247 |
+
suspend: Optional[bool]
|
| 248 |
+
concurrency: Optional[bool]
|
| 249 |
+
status: ScheduledJobStatus
|
| 250 |
+
owner: JobOwner
|
| 251 |
+
|
| 252 |
+
def __init__(self, **kwargs) -> None:
|
| 253 |
+
self.id = kwargs["id"]
|
| 254 |
+
created_at = kwargs.get("createdAt") or kwargs.get("created_at")
|
| 255 |
+
self.created_at = parse_datetime(created_at) if created_at else None
|
| 256 |
+
self.job_spec = JobSpec(**(kwargs.get("job_spec") or kwargs.get("jobSpec", {})))
|
| 257 |
+
self.schedule = kwargs.get("schedule")
|
| 258 |
+
self.suspend = kwargs.get("suspend")
|
| 259 |
+
self.concurrency = kwargs.get("concurrency")
|
| 260 |
+
status = kwargs.get("status", {})
|
| 261 |
+
self.status = ScheduledJobStatus(
|
| 262 |
+
last_job=status.get("last_job") or status.get("lastJob"),
|
| 263 |
+
next_job_run_at=status.get("next_job_run_at") or status.get("nextJobRunAt"),
|
| 264 |
+
)
|
| 265 |
+
owner = kwargs.get("owner", {})
|
| 266 |
+
self.owner = JobOwner(id=owner["id"], name=owner["name"], type=owner["type"])
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
@dataclass
|
| 270 |
+
class JobAccelerator:
|
| 271 |
+
"""
|
| 272 |
+
Contains information about a Job accelerator (GPU).
|
| 273 |
+
|
| 274 |
+
Args:
|
| 275 |
+
type (`str`):
|
| 276 |
+
Type of accelerator, e.g. `"gpu"`.
|
| 277 |
+
model (`str`):
|
| 278 |
+
Model of accelerator, e.g. `"T4"`, `"A10G"`, `"A100"`, `"L4"`, `"L40S"`.
|
| 279 |
+
quantity (`str`):
|
| 280 |
+
Number of accelerators, e.g. `"1"`, `"2"`, `"4"`, `"8"`.
|
| 281 |
+
vram (`str`):
|
| 282 |
+
Total VRAM, e.g. `"16 GB"`, `"24 GB"`.
|
| 283 |
+
manufacturer (`str`):
|
| 284 |
+
Manufacturer of the accelerator, e.g. `"Nvidia"`.
|
| 285 |
+
"""
|
| 286 |
+
|
| 287 |
+
type: str
|
| 288 |
+
model: str
|
| 289 |
+
quantity: str
|
| 290 |
+
vram: str
|
| 291 |
+
manufacturer: str
|
| 292 |
+
|
| 293 |
+
def __init__(self, **kwargs) -> None:
|
| 294 |
+
self.type = kwargs["type"]
|
| 295 |
+
self.model = kwargs["model"]
|
| 296 |
+
self.quantity = kwargs["quantity"]
|
| 297 |
+
self.vram = kwargs["vram"]
|
| 298 |
+
self.manufacturer = kwargs["manufacturer"]
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@dataclass
|
| 302 |
+
class JobHardware:
|
| 303 |
+
"""
|
| 304 |
+
Contains information about available Job hardware.
|
| 305 |
+
|
| 306 |
+
Args:
|
| 307 |
+
name (`str`):
|
| 308 |
+
Machine identifier, e.g. `"cpu-basic"`, `"a10g-large"`.
|
| 309 |
+
pretty_name (`str`):
|
| 310 |
+
Human-readable name, e.g. `"CPU Basic"`, `"Nvidia A10G - large"`.
|
| 311 |
+
cpu (`str`):
|
| 312 |
+
CPU specification, e.g. `"2 vCPU"`, `"12 vCPU"`.
|
| 313 |
+
ram (`str`):
|
| 314 |
+
RAM specification, e.g. `"16 GB"`, `"46 GB"`.
|
| 315 |
+
accelerator (`JobAccelerator` or `None`):
|
| 316 |
+
GPU/accelerator details if available.
|
| 317 |
+
unit_cost_micro_usd (`int`):
|
| 318 |
+
Cost in micro-dollars per unit, e.g. `167` (= $0.000167).
|
| 319 |
+
unit_cost_usd (`float`):
|
| 320 |
+
Cost in USD per unit, e.g. `0.000167`.
|
| 321 |
+
unit_label (`str`):
|
| 322 |
+
Cost unit period, e.g. `"minute"`.
|
| 323 |
+
|
| 324 |
+
Example:
|
| 325 |
+
|
| 326 |
+
```python
|
| 327 |
+
>>> from huggingface_hub import list_jobs_hardware
|
| 328 |
+
>>> hardware_list = list_jobs_hardware()
|
| 329 |
+
>>> hardware_list[0]
|
| 330 |
+
JobHardware(name='cpu-basic', pretty_name='CPU Basic', cpu='2 vCPU', ram='16 GB', accelerator=None, unit_cost_micro_usd=167, unit_cost_usd=0.000167, unit_label='minute')
|
| 331 |
+
>>> hardware_list[0].name
|
| 332 |
+
'cpu-basic'
|
| 333 |
+
```
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
name: str
|
| 337 |
+
pretty_name: str
|
| 338 |
+
cpu: str
|
| 339 |
+
ram: str
|
| 340 |
+
accelerator: Optional[JobAccelerator]
|
| 341 |
+
unit_cost_micro_usd: int
|
| 342 |
+
unit_cost_usd: float
|
| 343 |
+
unit_label: str
|
| 344 |
+
|
| 345 |
+
def __init__(self, **kwargs) -> None:
|
| 346 |
+
self.name = kwargs["name"]
|
| 347 |
+
self.pretty_name = kwargs["prettyName"]
|
| 348 |
+
self.cpu = kwargs["cpu"]
|
| 349 |
+
self.ram = kwargs["ram"]
|
| 350 |
+
accelerator = kwargs.get("accelerator")
|
| 351 |
+
self.accelerator = JobAccelerator(**accelerator) if accelerator else None
|
| 352 |
+
self.unit_cost_micro_usd = kwargs["unitCostMicroUSD"]
|
| 353 |
+
self.unit_cost_usd = kwargs["unitCostUSD"]
|
| 354 |
+
self.unit_label = kwargs["unitLabel"]
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _create_job_spec(
|
| 358 |
+
*,
|
| 359 |
+
image: str,
|
| 360 |
+
command: list[str],
|
| 361 |
+
env: Optional[dict[str, Any]],
|
| 362 |
+
secrets: Optional[dict[str, Any]],
|
| 363 |
+
flavor: Optional[SpaceHardware],
|
| 364 |
+
timeout: Optional[Union[int, float, str]],
|
| 365 |
+
labels: Optional[dict[str, str]] = None,
|
| 366 |
+
) -> dict[str, Any]:
|
| 367 |
+
# prepare job spec to send to HF Jobs API
|
| 368 |
+
job_spec: dict[str, Any] = {
|
| 369 |
+
"command": command,
|
| 370 |
+
"arguments": [],
|
| 371 |
+
"environment": env or {},
|
| 372 |
+
"flavor": flavor or SpaceHardware.CPU_BASIC,
|
| 373 |
+
}
|
| 374 |
+
# secrets are optional
|
| 375 |
+
if secrets:
|
| 376 |
+
job_spec["secrets"] = secrets
|
| 377 |
+
# timeout is optional
|
| 378 |
+
if timeout:
|
| 379 |
+
time_units_factors = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}
|
| 380 |
+
if isinstance(timeout, str) and timeout[-1] in time_units_factors:
|
| 381 |
+
job_spec["timeoutSeconds"] = int(float(timeout[:-1]) * time_units_factors[timeout[-1]])
|
| 382 |
+
else:
|
| 383 |
+
job_spec["timeoutSeconds"] = int(timeout)
|
| 384 |
+
# labels are optional
|
| 385 |
+
if labels:
|
| 386 |
+
job_spec["labels"] = labels
|
| 387 |
+
# input is either from docker hub or from HF spaces
|
| 388 |
+
for prefix in (
|
| 389 |
+
"https://huggingface.co/spaces/",
|
| 390 |
+
"https://hf.co/spaces/",
|
| 391 |
+
"huggingface.co/spaces/",
|
| 392 |
+
"hf.co/spaces/",
|
| 393 |
+
):
|
| 394 |
+
if image.startswith(prefix):
|
| 395 |
+
job_spec["spaceId"] = image[len(prefix) :]
|
| 396 |
+
break
|
| 397 |
+
else:
|
| 398 |
+
job_spec["dockerImage"] = image
|
| 399 |
+
return job_spec
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_local_folder.py
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"""Contains utilities to handle the `../.cache/huggingface` folder in local directories.
|
| 16 |
+
|
| 17 |
+
First discussed in https://github.com/huggingface/huggingface_hub/issues/1738 to store
|
| 18 |
+
download metadata when downloading files from the hub to a local directory (without
|
| 19 |
+
using the cache).
|
| 20 |
+
|
| 21 |
+
./.cache/huggingface folder structure:
|
| 22 |
+
[4.0K] data
|
| 23 |
+
├── [4.0K] .cache
|
| 24 |
+
│ └── [4.0K] huggingface
|
| 25 |
+
│ └── [4.0K] download
|
| 26 |
+
│ ├── [ 16] file.parquet.metadata
|
| 27 |
+
│ ├── [ 16] file.txt.metadata
|
| 28 |
+
│ └── [4.0K] folder
|
| 29 |
+
│ └── [ 16] file.parquet.metadata
|
| 30 |
+
│
|
| 31 |
+
├── [6.5G] file.parquet
|
| 32 |
+
├── [1.5K] file.txt
|
| 33 |
+
└── [4.0K] folder
|
| 34 |
+
└── [ 16] file.parquet
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
Download metadata file structure:
|
| 38 |
+
```
|
| 39 |
+
# file.txt.metadata
|
| 40 |
+
11c5a3d5811f50298f278a704980280950aedb10
|
| 41 |
+
a16a55fda99d2f2e7b69cce5cf93ff4ad3049930
|
| 42 |
+
1712656091.123
|
| 43 |
+
|
| 44 |
+
# file.parquet.metadata
|
| 45 |
+
11c5a3d5811f50298f278a704980280950aedb10
|
| 46 |
+
7c5d3f4b8b76583b422fcb9189ad6c89d5d97a094541ce8932dce3ecabde1421
|
| 47 |
+
1712656091.123
|
| 48 |
+
}
|
| 49 |
+
```
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
import base64
|
| 53 |
+
import hashlib
|
| 54 |
+
import logging
|
| 55 |
+
import os
|
| 56 |
+
import time
|
| 57 |
+
from dataclasses import dataclass
|
| 58 |
+
from pathlib import Path
|
| 59 |
+
from typing import Optional
|
| 60 |
+
|
| 61 |
+
from .utils import WeakFileLock
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
logger = logging.getLogger(__name__)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class LocalDownloadFilePaths:
|
| 69 |
+
"""
|
| 70 |
+
Paths to the files related to a download process in a local dir.
|
| 71 |
+
|
| 72 |
+
Returned by [`get_local_download_paths`].
|
| 73 |
+
|
| 74 |
+
Attributes:
|
| 75 |
+
file_path (`Path`):
|
| 76 |
+
Path where the file will be saved.
|
| 77 |
+
lock_path (`Path`):
|
| 78 |
+
Path to the lock file used to ensure atomicity when reading/writing metadata.
|
| 79 |
+
metadata_path (`Path`):
|
| 80 |
+
Path to the metadata file.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
file_path: Path
|
| 84 |
+
lock_path: Path
|
| 85 |
+
metadata_path: Path
|
| 86 |
+
|
| 87 |
+
def incomplete_path(self, etag: str) -> Path:
|
| 88 |
+
"""Return the path where a file will be temporarily downloaded before being moved to `file_path`."""
|
| 89 |
+
path = self.metadata_path.parent / f"{_short_hash(self.metadata_path.name)}.{etag}.incomplete"
|
| 90 |
+
resolved_path = str(path.resolve())
|
| 91 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 92 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix.
|
| 93 |
+
if os.name == "nt" and len(resolved_path) > 255 and not resolved_path.startswith("\\\\?\\"):
|
| 94 |
+
path = Path("\\\\?\\" + resolved_path)
|
| 95 |
+
return path
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
@dataclass(frozen=True)
|
| 99 |
+
class LocalUploadFilePaths:
|
| 100 |
+
"""
|
| 101 |
+
Paths to the files related to an upload process in a local dir.
|
| 102 |
+
|
| 103 |
+
Returned by [`get_local_upload_paths`].
|
| 104 |
+
|
| 105 |
+
Attributes:
|
| 106 |
+
path_in_repo (`str`):
|
| 107 |
+
Path of the file in the repo.
|
| 108 |
+
file_path (`Path`):
|
| 109 |
+
Path where the file will be saved.
|
| 110 |
+
lock_path (`Path`):
|
| 111 |
+
Path to the lock file used to ensure atomicity when reading/writing metadata.
|
| 112 |
+
metadata_path (`Path`):
|
| 113 |
+
Path to the metadata file.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
path_in_repo: str
|
| 117 |
+
file_path: Path
|
| 118 |
+
lock_path: Path
|
| 119 |
+
metadata_path: Path
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class LocalDownloadFileMetadata:
|
| 124 |
+
"""
|
| 125 |
+
Metadata about a file in the local directory related to a download process.
|
| 126 |
+
|
| 127 |
+
Attributes:
|
| 128 |
+
filename (`str`):
|
| 129 |
+
Path of the file in the repo.
|
| 130 |
+
commit_hash (`str`):
|
| 131 |
+
Commit hash of the file in the repo.
|
| 132 |
+
etag (`str`):
|
| 133 |
+
ETag of the file in the repo. Used to check if the file has changed.
|
| 134 |
+
For LFS files, this is the sha256 of the file. For regular files, it corresponds to the git hash.
|
| 135 |
+
timestamp (`int`):
|
| 136 |
+
Unix timestamp of when the metadata was saved i.e. when the metadata was accurate.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
filename: str
|
| 140 |
+
commit_hash: str
|
| 141 |
+
etag: str
|
| 142 |
+
timestamp: float
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
@dataclass
|
| 146 |
+
class LocalUploadFileMetadata:
|
| 147 |
+
"""
|
| 148 |
+
Metadata about a file in the local directory related to an upload process.
|
| 149 |
+
"""
|
| 150 |
+
|
| 151 |
+
size: int
|
| 152 |
+
|
| 153 |
+
# Default values correspond to "we don't know yet"
|
| 154 |
+
timestamp: Optional[float] = None
|
| 155 |
+
should_ignore: Optional[bool] = None
|
| 156 |
+
sha256: Optional[str] = None
|
| 157 |
+
upload_mode: Optional[str] = None
|
| 158 |
+
remote_oid: Optional[str] = None
|
| 159 |
+
is_uploaded: bool = False
|
| 160 |
+
is_committed: bool = False
|
| 161 |
+
|
| 162 |
+
def save(self, paths: LocalUploadFilePaths) -> None:
|
| 163 |
+
"""Save the metadata to disk."""
|
| 164 |
+
with WeakFileLock(paths.lock_path):
|
| 165 |
+
with paths.metadata_path.open("w") as f:
|
| 166 |
+
new_timestamp = time.time()
|
| 167 |
+
f.write(str(new_timestamp) + "\n")
|
| 168 |
+
|
| 169 |
+
f.write(str(self.size)) # never None
|
| 170 |
+
f.write("\n")
|
| 171 |
+
|
| 172 |
+
if self.should_ignore is not None:
|
| 173 |
+
f.write(str(int(self.should_ignore)))
|
| 174 |
+
f.write("\n")
|
| 175 |
+
|
| 176 |
+
if self.sha256 is not None:
|
| 177 |
+
f.write(self.sha256)
|
| 178 |
+
f.write("\n")
|
| 179 |
+
|
| 180 |
+
if self.upload_mode is not None:
|
| 181 |
+
f.write(self.upload_mode)
|
| 182 |
+
f.write("\n")
|
| 183 |
+
|
| 184 |
+
if self.remote_oid is not None:
|
| 185 |
+
f.write(self.remote_oid)
|
| 186 |
+
f.write("\n")
|
| 187 |
+
|
| 188 |
+
f.write(str(int(self.is_uploaded)) + "\n")
|
| 189 |
+
f.write(str(int(self.is_committed)) + "\n")
|
| 190 |
+
|
| 191 |
+
self.timestamp = new_timestamp
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def get_local_download_paths(local_dir: Path, filename: str) -> LocalDownloadFilePaths:
|
| 195 |
+
"""Compute paths to the files related to a download process.
|
| 196 |
+
|
| 197 |
+
Folders containing the paths are all guaranteed to exist.
|
| 198 |
+
|
| 199 |
+
Args:
|
| 200 |
+
local_dir (`Path`):
|
| 201 |
+
Path to the local directory in which files are downloaded.
|
| 202 |
+
filename (`str`):
|
| 203 |
+
Path of the file in the repo.
|
| 204 |
+
|
| 205 |
+
Return:
|
| 206 |
+
[`LocalDownloadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path, incomplete_path).
|
| 207 |
+
"""
|
| 208 |
+
# filename is the path in the Hub repository (separated by '/')
|
| 209 |
+
# make sure to have a cross-platform transcription
|
| 210 |
+
sanitized_filename = os.path.join(*filename.split("/"))
|
| 211 |
+
if os.name == "nt":
|
| 212 |
+
if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
|
| 215 |
+
" owner to rename this file."
|
| 216 |
+
)
|
| 217 |
+
file_path = local_dir / sanitized_filename
|
| 218 |
+
metadata_path = _huggingface_dir(local_dir) / "download" / f"{sanitized_filename}.metadata"
|
| 219 |
+
lock_path = metadata_path.with_suffix(".lock")
|
| 220 |
+
|
| 221 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 222 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix
|
| 223 |
+
if os.name == "nt":
|
| 224 |
+
if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
|
| 225 |
+
file_path = Path("\\\\?\\" + os.path.abspath(file_path))
|
| 226 |
+
lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
|
| 227 |
+
metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
|
| 228 |
+
|
| 229 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 230 |
+
metadata_path.parent.mkdir(parents=True, exist_ok=True)
|
| 231 |
+
return LocalDownloadFilePaths(file_path=file_path, lock_path=lock_path, metadata_path=metadata_path)
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def get_local_upload_paths(local_dir: Path, filename: str) -> LocalUploadFilePaths:
|
| 235 |
+
"""Compute paths to the files related to an upload process.
|
| 236 |
+
|
| 237 |
+
Folders containing the paths are all guaranteed to exist.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
local_dir (`Path`):
|
| 241 |
+
Path to the local directory that is uploaded.
|
| 242 |
+
filename (`str`):
|
| 243 |
+
Path of the file in the repo.
|
| 244 |
+
|
| 245 |
+
Return:
|
| 246 |
+
[`LocalUploadFilePaths`]: the paths to the files (file_path, lock_path, metadata_path).
|
| 247 |
+
"""
|
| 248 |
+
# filename is the path in the Hub repository (separated by '/')
|
| 249 |
+
# make sure to have a cross-platform transcription
|
| 250 |
+
sanitized_filename = os.path.join(*filename.split("/"))
|
| 251 |
+
if os.name == "nt":
|
| 252 |
+
if sanitized_filename.startswith("..\\") or "\\..\\" in sanitized_filename:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
f"Invalid filename: cannot handle filename '{sanitized_filename}' on Windows. Please ask the repository"
|
| 255 |
+
" owner to rename this file."
|
| 256 |
+
)
|
| 257 |
+
file_path = local_dir / sanitized_filename
|
| 258 |
+
metadata_path = _huggingface_dir(local_dir) / "upload" / f"{sanitized_filename}.metadata"
|
| 259 |
+
lock_path = metadata_path.with_suffix(".lock")
|
| 260 |
+
|
| 261 |
+
# Some Windows versions do not allow for paths longer than 255 characters.
|
| 262 |
+
# In this case, we must specify it as an extended path by using the "\\?\" prefix
|
| 263 |
+
if os.name == "nt":
|
| 264 |
+
if not str(local_dir).startswith("\\\\?\\") and len(os.path.abspath(lock_path)) > 255:
|
| 265 |
+
file_path = Path("\\\\?\\" + os.path.abspath(file_path))
|
| 266 |
+
lock_path = Path("\\\\?\\" + os.path.abspath(lock_path))
|
| 267 |
+
metadata_path = Path("\\\\?\\" + os.path.abspath(metadata_path))
|
| 268 |
+
|
| 269 |
+
file_path.parent.mkdir(parents=True, exist_ok=True)
|
| 270 |
+
metadata_path.parent.mkdir(parents=True, exist_ok=True)
|
| 271 |
+
return LocalUploadFilePaths(
|
| 272 |
+
path_in_repo=filename, file_path=file_path, lock_path=lock_path, metadata_path=metadata_path
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def read_download_metadata(local_dir: Path, filename: str) -> Optional[LocalDownloadFileMetadata]:
|
| 277 |
+
"""Read metadata about a file in the local directory related to a download process.
|
| 278 |
+
|
| 279 |
+
Args:
|
| 280 |
+
local_dir (`Path`):
|
| 281 |
+
Path to the local directory in which files are downloaded.
|
| 282 |
+
filename (`str`):
|
| 283 |
+
Path of the file in the repo.
|
| 284 |
+
|
| 285 |
+
Return:
|
| 286 |
+
`[LocalDownloadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
|
| 287 |
+
"""
|
| 288 |
+
paths = get_local_download_paths(local_dir, filename)
|
| 289 |
+
with WeakFileLock(paths.lock_path):
|
| 290 |
+
if paths.metadata_path.exists():
|
| 291 |
+
try:
|
| 292 |
+
with paths.metadata_path.open() as f:
|
| 293 |
+
commit_hash = f.readline().strip()
|
| 294 |
+
etag = f.readline().strip()
|
| 295 |
+
timestamp = float(f.readline().strip())
|
| 296 |
+
metadata = LocalDownloadFileMetadata(
|
| 297 |
+
filename=filename,
|
| 298 |
+
commit_hash=commit_hash,
|
| 299 |
+
etag=etag,
|
| 300 |
+
timestamp=timestamp,
|
| 301 |
+
)
|
| 302 |
+
except Exception as e:
|
| 303 |
+
# remove the metadata file if it is corrupted / not the right format
|
| 304 |
+
logger.warning(
|
| 305 |
+
f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
|
| 306 |
+
)
|
| 307 |
+
try:
|
| 308 |
+
paths.metadata_path.unlink()
|
| 309 |
+
except Exception as e:
|
| 310 |
+
logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
|
| 311 |
+
return None
|
| 312 |
+
|
| 313 |
+
try:
|
| 314 |
+
# check if the file exists and hasn't been modified since the metadata was saved
|
| 315 |
+
stat = paths.file_path.stat()
|
| 316 |
+
if (
|
| 317 |
+
stat.st_mtime - 1 <= metadata.timestamp
|
| 318 |
+
): # allow 1s difference as stat.st_mtime might not be precise
|
| 319 |
+
return metadata
|
| 320 |
+
logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
|
| 321 |
+
except FileNotFoundError:
|
| 322 |
+
# file does not exist => metadata is outdated
|
| 323 |
+
return None
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def read_upload_metadata(local_dir: Path, filename: str) -> LocalUploadFileMetadata:
|
| 328 |
+
"""Read metadata about a file in the local directory related to an upload process.
|
| 329 |
+
|
| 330 |
+
TODO: factorize logic with `read_download_metadata`.
|
| 331 |
+
|
| 332 |
+
Args:
|
| 333 |
+
local_dir (`Path`):
|
| 334 |
+
Path to the local directory in which files are downloaded.
|
| 335 |
+
filename (`str`):
|
| 336 |
+
Path of the file in the repo.
|
| 337 |
+
|
| 338 |
+
Return:
|
| 339 |
+
`[LocalUploadFileMetadata]` or `None`: the metadata if it exists, `None` otherwise.
|
| 340 |
+
"""
|
| 341 |
+
paths = get_local_upload_paths(local_dir, filename)
|
| 342 |
+
with WeakFileLock(paths.lock_path):
|
| 343 |
+
if paths.metadata_path.exists():
|
| 344 |
+
try:
|
| 345 |
+
with paths.metadata_path.open() as f:
|
| 346 |
+
timestamp = float(f.readline().strip())
|
| 347 |
+
|
| 348 |
+
size = int(f.readline().strip()) # never None
|
| 349 |
+
|
| 350 |
+
_should_ignore = f.readline().strip()
|
| 351 |
+
should_ignore = None if _should_ignore == "" else bool(int(_should_ignore))
|
| 352 |
+
|
| 353 |
+
_sha256 = f.readline().strip()
|
| 354 |
+
sha256 = None if _sha256 == "" else _sha256
|
| 355 |
+
|
| 356 |
+
_upload_mode = f.readline().strip()
|
| 357 |
+
upload_mode = None if _upload_mode == "" else _upload_mode
|
| 358 |
+
if upload_mode not in (None, "regular", "lfs"):
|
| 359 |
+
raise ValueError(f"Invalid upload mode in metadata {paths.path_in_repo}: {upload_mode}")
|
| 360 |
+
|
| 361 |
+
_remote_oid = f.readline().strip()
|
| 362 |
+
remote_oid = None if _remote_oid == "" else _remote_oid
|
| 363 |
+
|
| 364 |
+
is_uploaded = bool(int(f.readline().strip()))
|
| 365 |
+
is_committed = bool(int(f.readline().strip()))
|
| 366 |
+
|
| 367 |
+
metadata = LocalUploadFileMetadata(
|
| 368 |
+
timestamp=timestamp,
|
| 369 |
+
size=size,
|
| 370 |
+
should_ignore=should_ignore,
|
| 371 |
+
sha256=sha256,
|
| 372 |
+
upload_mode=upload_mode,
|
| 373 |
+
remote_oid=remote_oid,
|
| 374 |
+
is_uploaded=is_uploaded,
|
| 375 |
+
is_committed=is_committed,
|
| 376 |
+
)
|
| 377 |
+
except Exception as e:
|
| 378 |
+
# remove the metadata file if it is corrupted / not the right format
|
| 379 |
+
logger.warning(
|
| 380 |
+
f"Invalid metadata file {paths.metadata_path}: {e}. Removing it from disk and continue."
|
| 381 |
+
)
|
| 382 |
+
try:
|
| 383 |
+
paths.metadata_path.unlink()
|
| 384 |
+
except Exception as e:
|
| 385 |
+
logger.warning(f"Could not remove corrupted metadata file {paths.metadata_path}: {e}")
|
| 386 |
+
|
| 387 |
+
# corrupted metadata => we don't know anything expect its size
|
| 388 |
+
return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
|
| 389 |
+
|
| 390 |
+
# TODO: can we do better?
|
| 391 |
+
if (
|
| 392 |
+
metadata.timestamp is not None
|
| 393 |
+
and metadata.is_uploaded # file was uploaded
|
| 394 |
+
and not metadata.is_committed # but not committed
|
| 395 |
+
and time.time() - metadata.timestamp > 20 * 3600 # and it's been more than 20 hours
|
| 396 |
+
): # => we consider it as garbage-collected by S3
|
| 397 |
+
metadata.is_uploaded = False
|
| 398 |
+
|
| 399 |
+
# check if the file exists and hasn't been modified since the metadata was saved
|
| 400 |
+
try:
|
| 401 |
+
if metadata.timestamp is not None and paths.file_path.stat().st_mtime <= metadata.timestamp:
|
| 402 |
+
return metadata
|
| 403 |
+
logger.info(f"Ignored metadata for '{filename}' (outdated). Will re-compute hash.")
|
| 404 |
+
except FileNotFoundError:
|
| 405 |
+
# file does not exist => metadata is outdated
|
| 406 |
+
pass
|
| 407 |
+
|
| 408 |
+
# empty metadata => we don't know anything expect its size
|
| 409 |
+
return LocalUploadFileMetadata(size=paths.file_path.stat().st_size)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def write_download_metadata(local_dir: Path, filename: str, commit_hash: str, etag: str) -> None:
|
| 413 |
+
"""Write metadata about a file in the local directory related to a download process.
|
| 414 |
+
|
| 415 |
+
Args:
|
| 416 |
+
local_dir (`Path`):
|
| 417 |
+
Path to the local directory in which files are downloaded.
|
| 418 |
+
"""
|
| 419 |
+
paths = get_local_download_paths(local_dir, filename)
|
| 420 |
+
with WeakFileLock(paths.lock_path):
|
| 421 |
+
with paths.metadata_path.open("w") as f:
|
| 422 |
+
f.write(f"{commit_hash}\n{etag}\n{time.time()}\n")
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
def _huggingface_dir(local_dir: Path) -> Path:
|
| 426 |
+
"""Return the path to the `.cache/huggingface` directory in a local directory."""
|
| 427 |
+
# Wrap in lru_cache to avoid overwriting the .gitignore file if called multiple times
|
| 428 |
+
path = local_dir / ".cache" / "huggingface"
|
| 429 |
+
path.mkdir(exist_ok=True, parents=True)
|
| 430 |
+
|
| 431 |
+
# Create a .gitignore file in the .cache/huggingface directory if it doesn't exist
|
| 432 |
+
# Should be thread-safe enough like this.
|
| 433 |
+
gitignore = path / ".gitignore"
|
| 434 |
+
gitignore_lock = path / ".gitignore.lock"
|
| 435 |
+
if not gitignore.exists():
|
| 436 |
+
try:
|
| 437 |
+
with WeakFileLock(gitignore_lock, timeout=0.1):
|
| 438 |
+
gitignore.write_text("*")
|
| 439 |
+
except IndexError:
|
| 440 |
+
pass
|
| 441 |
+
except OSError: # TimeoutError, FileNotFoundError, PermissionError, etc.
|
| 442 |
+
pass
|
| 443 |
+
try:
|
| 444 |
+
gitignore_lock.unlink()
|
| 445 |
+
except OSError:
|
| 446 |
+
pass
|
| 447 |
+
return path
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
def _short_hash(filename: str) -> str:
|
| 451 |
+
return base64.urlsafe_b64encode(hashlib.sha1(filename.encode()).digest()).decode()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_login.py
ADDED
|
@@ -0,0 +1,495 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2020 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains methods to log in to the Hub."""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import subprocess
|
| 18 |
+
from getpass import getpass
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Optional
|
| 21 |
+
|
| 22 |
+
import typer
|
| 23 |
+
|
| 24 |
+
from . import constants
|
| 25 |
+
from .utils import (
|
| 26 |
+
ANSI,
|
| 27 |
+
capture_output,
|
| 28 |
+
get_token,
|
| 29 |
+
is_google_colab,
|
| 30 |
+
is_notebook,
|
| 31 |
+
list_credential_helpers,
|
| 32 |
+
logging,
|
| 33 |
+
run_subprocess,
|
| 34 |
+
set_git_credential,
|
| 35 |
+
unset_git_credential,
|
| 36 |
+
)
|
| 37 |
+
from .utils._auth import (
|
| 38 |
+
_get_token_by_name,
|
| 39 |
+
_get_token_from_environment,
|
| 40 |
+
_get_token_from_file,
|
| 41 |
+
_get_token_from_google_colab,
|
| 42 |
+
_save_stored_tokens,
|
| 43 |
+
_save_token,
|
| 44 |
+
get_stored_tokens,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
logger = logging.get_logger(__name__)
|
| 49 |
+
|
| 50 |
+
_HF_LOGO_ASCII = """
|
| 51 |
+
_| _| _| _| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _|_|_|_| _|_| _|_|_| _|_|_|_|
|
| 52 |
+
_| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
| 53 |
+
_|_|_|_| _| _| _| _|_| _| _|_| _| _| _| _| _| _|_| _|_|_| _|_|_|_| _| _|_|_|
|
| 54 |
+
_| _| _| _| _| _| _| _| _| _| _|_| _| _| _| _| _| _| _|
|
| 55 |
+
_| _| _|_| _|_|_| _|_|_| _|_|_| _| _| _|_|_| _| _| _| _|_|_| _|_|_|_|
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def login(
|
| 60 |
+
token: Optional[str] = None,
|
| 61 |
+
*,
|
| 62 |
+
add_to_git_credential: bool = False,
|
| 63 |
+
skip_if_logged_in: bool = True,
|
| 64 |
+
) -> None:
|
| 65 |
+
"""Login the machine to access the Hub.
|
| 66 |
+
|
| 67 |
+
The `token` is persisted in cache and set as a git credential. Once done, the machine
|
| 68 |
+
is logged in and the access token will be available across all `huggingface_hub`
|
| 69 |
+
components. If `token` is not provided, it will be prompted to the user either with
|
| 70 |
+
a widget (in a notebook) or via the terminal.
|
| 71 |
+
|
| 72 |
+
To log in from outside of a script, one can also use `hf auth login` which is
|
| 73 |
+
a cli command that wraps [`login`].
|
| 74 |
+
|
| 75 |
+
> [!TIP]
|
| 76 |
+
> [`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and
|
| 77 |
+
> extends its capabilities.
|
| 78 |
+
|
| 79 |
+
> [!TIP]
|
| 80 |
+
> When the token is not passed, [`login`] will automatically detect if the script runs
|
| 81 |
+
> in a notebook or not. However, this detection might not be accurate due to the
|
| 82 |
+
> variety of notebooks that exists nowadays. If that is the case, you can always force
|
| 83 |
+
> the UI by using [`notebook_login`] or [`interpreter_login`].
|
| 84 |
+
|
| 85 |
+
Args:
|
| 86 |
+
token (`str`, *optional*):
|
| 87 |
+
User access token to generate from https://huggingface.co/settings/token.
|
| 88 |
+
add_to_git_credential (`bool`, defaults to `False`):
|
| 89 |
+
If `True`, token will be set as git credential. If no git credential helper
|
| 90 |
+
is configured, a warning will be displayed to the user. If `token` is `None`,
|
| 91 |
+
the value of `add_to_git_credential` is ignored and will be prompted again
|
| 92 |
+
to the end user.
|
| 93 |
+
skip_if_logged_in (`bool`, defaults to `True`):
|
| 94 |
+
If `True`, do not prompt for token if user is already logged in.
|
| 95 |
+
Set to `False` to force re-login. In CLI, use `--force` instead.
|
| 96 |
+
Raises:
|
| 97 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 98 |
+
If an organization token is passed. Only personal account tokens are valid
|
| 99 |
+
to log in.
|
| 100 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 101 |
+
If token is invalid.
|
| 102 |
+
[`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 103 |
+
If running in a notebook but `ipywidgets` is not installed.
|
| 104 |
+
"""
|
| 105 |
+
if token is not None:
|
| 106 |
+
if not add_to_git_credential:
|
| 107 |
+
logger.info(
|
| 108 |
+
"The token has not been saved to the git credentials helper. Pass "
|
| 109 |
+
"`add_to_git_credential=True` in this function directly or "
|
| 110 |
+
"`--add-to-git-credential` if using via `hf`CLI if "
|
| 111 |
+
"you want to set the git credential as well."
|
| 112 |
+
)
|
| 113 |
+
_login(token, add_to_git_credential=add_to_git_credential)
|
| 114 |
+
elif is_notebook():
|
| 115 |
+
notebook_login(skip_if_logged_in=skip_if_logged_in)
|
| 116 |
+
else:
|
| 117 |
+
interpreter_login(skip_if_logged_in=skip_if_logged_in)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def logout(token_name: Optional[str] = None) -> None:
|
| 121 |
+
"""Logout the machine from the Hub.
|
| 122 |
+
|
| 123 |
+
Token is deleted from the machine and removed from git credential.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
token_name (`str`, *optional*):
|
| 127 |
+
Name of the access token to logout from. If `None`, will log out from all saved access tokens.
|
| 128 |
+
Raises:
|
| 129 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
|
| 130 |
+
If the access token name is not found.
|
| 131 |
+
"""
|
| 132 |
+
if get_token() is None and not get_stored_tokens(): # No active token and no saved access tokens
|
| 133 |
+
logger.warning("Not logged in!")
|
| 134 |
+
return
|
| 135 |
+
if not token_name:
|
| 136 |
+
# Delete all saved access tokens and token
|
| 137 |
+
for file_path in (constants.HF_TOKEN_PATH, constants.HF_STORED_TOKENS_PATH):
|
| 138 |
+
try:
|
| 139 |
+
Path(file_path).unlink()
|
| 140 |
+
except FileNotFoundError:
|
| 141 |
+
pass
|
| 142 |
+
logger.info("Successfully logged out from all access tokens.")
|
| 143 |
+
else:
|
| 144 |
+
_logout_from_token(token_name)
|
| 145 |
+
logger.info(f"Successfully logged out from access token: {token_name}.")
|
| 146 |
+
|
| 147 |
+
unset_git_credential()
|
| 148 |
+
|
| 149 |
+
# Check if still logged in
|
| 150 |
+
if _get_token_from_google_colab() is not None:
|
| 151 |
+
raise EnvironmentError(
|
| 152 |
+
"You are automatically logged in using a Google Colab secret.\n"
|
| 153 |
+
"To log out, you must unset the `HF_TOKEN` secret in your Colab settings."
|
| 154 |
+
)
|
| 155 |
+
if _get_token_from_environment() is not None:
|
| 156 |
+
raise EnvironmentError(
|
| 157 |
+
"Token has been deleted from your machine but you are still logged in.\n"
|
| 158 |
+
"To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables."
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def auth_switch(token_name: str, add_to_git_credential: bool = False) -> None:
|
| 163 |
+
"""Switch to a different access token.
|
| 164 |
+
|
| 165 |
+
Args:
|
| 166 |
+
token_name (`str`):
|
| 167 |
+
Name of the access token to switch to.
|
| 168 |
+
add_to_git_credential (`bool`, defaults to `False`):
|
| 169 |
+
If `True`, token will be set as git credential. If no git credential helper
|
| 170 |
+
is configured, a warning will be displayed to the user. If `token` is `None`,
|
| 171 |
+
the value of `add_to_git_credential` is ignored and will be prompted again
|
| 172 |
+
to the end user.
|
| 173 |
+
|
| 174 |
+
Raises:
|
| 175 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
|
| 176 |
+
If the access token name is not found.
|
| 177 |
+
"""
|
| 178 |
+
token = _get_token_by_name(token_name)
|
| 179 |
+
if not token:
|
| 180 |
+
raise ValueError(f"Access token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
|
| 181 |
+
# Write token to HF_TOKEN_PATH
|
| 182 |
+
_set_active_token(token_name, add_to_git_credential)
|
| 183 |
+
logger.info(f"The current active token is: {token_name}")
|
| 184 |
+
token_from_environment = _get_token_from_environment()
|
| 185 |
+
if token_from_environment is not None and token_from_environment != token:
|
| 186 |
+
logger.warning(
|
| 187 |
+
"The environment variable `HF_TOKEN` is set and will override the access token you've just switched to."
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def auth_list() -> None:
|
| 192 |
+
"""List all stored access tokens."""
|
| 193 |
+
tokens = get_stored_tokens()
|
| 194 |
+
|
| 195 |
+
if not tokens:
|
| 196 |
+
if _get_token_from_environment():
|
| 197 |
+
logger.info("No stored access tokens found.")
|
| 198 |
+
logger.warning("Note: Environment variable `HF_TOKEN` is set and is the current active token.")
|
| 199 |
+
else:
|
| 200 |
+
logger.info("No access tokens found.")
|
| 201 |
+
return
|
| 202 |
+
# Find current token
|
| 203 |
+
current_token = get_token()
|
| 204 |
+
current_token_name = None
|
| 205 |
+
for token_name in tokens:
|
| 206 |
+
if tokens.get(token_name) == current_token:
|
| 207 |
+
current_token_name = token_name
|
| 208 |
+
# Print header
|
| 209 |
+
max_offset = max(len("token"), max(len(token) for token in tokens)) + 2
|
| 210 |
+
print(f" {{:<{max_offset}}}| {{:<15}}".format("name", "token"))
|
| 211 |
+
print("-" * (max_offset + 2) + "|" + "-" * 15)
|
| 212 |
+
|
| 213 |
+
# Print saved access tokens
|
| 214 |
+
for token_name in tokens:
|
| 215 |
+
token = tokens.get(token_name, "<not set>")
|
| 216 |
+
masked_token = f"{token[:3]}****{token[-4:]}" if token != "<not set>" else token
|
| 217 |
+
is_current = "*" if token == current_token else " "
|
| 218 |
+
|
| 219 |
+
print(f"{is_current} {{:<{max_offset}}}| {{:<15}}".format(token_name, masked_token))
|
| 220 |
+
|
| 221 |
+
if _get_token_from_environment():
|
| 222 |
+
logger.warning(
|
| 223 |
+
"\nNote: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above."
|
| 224 |
+
)
|
| 225 |
+
elif current_token_name is None:
|
| 226 |
+
logger.warning(
|
| 227 |
+
"\nNote: No active token is set and no environment variable `HF_TOKEN` is found. Use `hf auth login` to log in."
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
###
|
| 232 |
+
# Interpreter-based login (text)
|
| 233 |
+
###
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def interpreter_login(*, skip_if_logged_in: bool = True) -> None:
|
| 237 |
+
"""
|
| 238 |
+
Displays a prompt to log in to the HF website and store the token.
|
| 239 |
+
|
| 240 |
+
This is equivalent to [`login`] without passing a token when not run in a notebook.
|
| 241 |
+
[`interpreter_login`] is useful if you want to force the use of the terminal prompt
|
| 242 |
+
instead of a notebook widget.
|
| 243 |
+
|
| 244 |
+
For more details, see [`login`].
|
| 245 |
+
|
| 246 |
+
Args:
|
| 247 |
+
skip_if_logged_in (`bool`, defaults to `True`):
|
| 248 |
+
If `True`, do not prompt for token if user is already logged in.
|
| 249 |
+
Set to `False` to force re-login. In CLI, use `--force` instead.
|
| 250 |
+
"""
|
| 251 |
+
if skip_if_logged_in and get_token() is not None:
|
| 252 |
+
logger.info("User is already logged in. Use `hf auth login --force` to force re-login.")
|
| 253 |
+
return
|
| 254 |
+
|
| 255 |
+
print(_HF_LOGO_ASCII)
|
| 256 |
+
if get_token() is not None:
|
| 257 |
+
logger.info(
|
| 258 |
+
" A token is already saved on your machine. Run `hf auth whoami`"
|
| 259 |
+
" to get more information or `hf auth logout` if you want"
|
| 260 |
+
" to log out."
|
| 261 |
+
)
|
| 262 |
+
logger.info(" Setting a new token will erase the existing one.")
|
| 263 |
+
|
| 264 |
+
logger.info(
|
| 265 |
+
" To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens ."
|
| 266 |
+
)
|
| 267 |
+
if os.name == "nt":
|
| 268 |
+
logger.info("Token can be pasted using 'Right-Click'.")
|
| 269 |
+
token = getpass("Enter your token (input will not be visible): ")
|
| 270 |
+
add_to_git_credential = typer.confirm("Add token as git credential?")
|
| 271 |
+
|
| 272 |
+
_login(token=token, add_to_git_credential=add_to_git_credential)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
###
|
| 276 |
+
# Notebook-based login (widget)
|
| 277 |
+
###
|
| 278 |
+
|
| 279 |
+
NOTEBOOK_LOGIN_PASSWORD_HTML = """<center> <img
|
| 280 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
| 281 |
+
alt='Hugging Face'> <br> Immediately click login after typing your password or
|
| 282 |
+
it might be stored in plain text in this notebook file. </center>"""
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_START = """<center> <img
|
| 286 |
+
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
|
| 287 |
+
alt='Hugging Face'> <br> Copy a token from <a
|
| 288 |
+
href="https://huggingface.co/settings/tokens" target="_blank">your Hugging Face
|
| 289 |
+
tokens page</a> and paste it below. <br> Immediately click login after copying
|
| 290 |
+
your token or it might be stored in plain text in this notebook file. </center>"""
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
NOTEBOOK_LOGIN_TOKEN_HTML_END = """
|
| 294 |
+
<b>Pro Tip:</b> If you don't already have one, you can create a dedicated
|
| 295 |
+
'notebooks' token with 'write' access, that you can then easily reuse for all
|
| 296 |
+
notebooks. </center>"""
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def notebook_login(*, skip_if_logged_in: bool = True) -> None:
|
| 300 |
+
"""
|
| 301 |
+
Displays a widget to log in to the HF website and store the token.
|
| 302 |
+
|
| 303 |
+
This is equivalent to [`login`] without passing a token when run in a notebook.
|
| 304 |
+
[`notebook_login`] is useful if you want to force the use of the notebook widget
|
| 305 |
+
instead of a prompt in the terminal.
|
| 306 |
+
|
| 307 |
+
For more details, see [`login`].
|
| 308 |
+
|
| 309 |
+
Args:
|
| 310 |
+
skip_if_logged_in (`bool`, defaults to `True`):
|
| 311 |
+
If `True`, do not prompt for token if user is already logged in.
|
| 312 |
+
Set to `False` to force re-login. In CLI, use `--force` instead.
|
| 313 |
+
"""
|
| 314 |
+
try:
|
| 315 |
+
import ipywidgets.widgets as widgets # type: ignore
|
| 316 |
+
from IPython.display import display # type: ignore
|
| 317 |
+
except ImportError:
|
| 318 |
+
raise ImportError(
|
| 319 |
+
"The `notebook_login` function can only be used in a notebook (Jupyter or"
|
| 320 |
+
" Colab) and you need the `ipywidgets` module: `pip install ipywidgets`."
|
| 321 |
+
)
|
| 322 |
+
if skip_if_logged_in and get_token() is not None:
|
| 323 |
+
logger.info("User is already logged in. Use `hf auth login --force` to force re-login.")
|
| 324 |
+
return
|
| 325 |
+
|
| 326 |
+
box_layout = widgets.Layout(display="flex", flex_flow="column", align_items="center", width="50%")
|
| 327 |
+
|
| 328 |
+
token_widget = widgets.Password(description="Token:")
|
| 329 |
+
git_checkbox_widget = widgets.Checkbox(value=True, description="Add token as git credential?")
|
| 330 |
+
token_finish_button = widgets.Button(description="Login")
|
| 331 |
+
|
| 332 |
+
login_token_widget = widgets.VBox(
|
| 333 |
+
[
|
| 334 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_START),
|
| 335 |
+
token_widget,
|
| 336 |
+
git_checkbox_widget,
|
| 337 |
+
token_finish_button,
|
| 338 |
+
widgets.HTML(NOTEBOOK_LOGIN_TOKEN_HTML_END),
|
| 339 |
+
],
|
| 340 |
+
layout=box_layout,
|
| 341 |
+
)
|
| 342 |
+
display(login_token_widget)
|
| 343 |
+
|
| 344 |
+
# On click events
|
| 345 |
+
def login_token_event(t):
|
| 346 |
+
"""Event handler for the login button."""
|
| 347 |
+
token = token_widget.value
|
| 348 |
+
add_to_git_credential = git_checkbox_widget.value
|
| 349 |
+
# Erase token and clear value to make sure it's not saved in the notebook.
|
| 350 |
+
token_widget.value = ""
|
| 351 |
+
# Hide inputs
|
| 352 |
+
login_token_widget.children = [widgets.Label("Connecting...")]
|
| 353 |
+
try:
|
| 354 |
+
with capture_output() as captured:
|
| 355 |
+
_login(token, add_to_git_credential=add_to_git_credential)
|
| 356 |
+
message = captured.getvalue()
|
| 357 |
+
except Exception as error:
|
| 358 |
+
message = str(error)
|
| 359 |
+
# Print result (success message or error)
|
| 360 |
+
login_token_widget.children = [widgets.Label(line) for line in message.split("\n") if line.strip()]
|
| 361 |
+
|
| 362 |
+
token_finish_button.on_click(login_token_event)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
###
|
| 366 |
+
# Login private helpers
|
| 367 |
+
###
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _login(
|
| 371 |
+
token: str,
|
| 372 |
+
add_to_git_credential: bool,
|
| 373 |
+
) -> None:
|
| 374 |
+
from .hf_api import whoami # avoid circular import
|
| 375 |
+
|
| 376 |
+
if token.startswith("api_org"):
|
| 377 |
+
raise ValueError("You must use your personal account token, not an organization token.")
|
| 378 |
+
|
| 379 |
+
token_info = whoami(token)
|
| 380 |
+
permission = token_info["auth"]["accessToken"]["role"]
|
| 381 |
+
logger.info(f"Token is valid (permission: {permission}).")
|
| 382 |
+
|
| 383 |
+
token_name = token_info["auth"]["accessToken"]["displayName"]
|
| 384 |
+
# Store token locally
|
| 385 |
+
_save_token(token=token, token_name=token_name)
|
| 386 |
+
# Set active token
|
| 387 |
+
_set_active_token(token_name=token_name, add_to_git_credential=add_to_git_credential)
|
| 388 |
+
logger.info("Login successful.")
|
| 389 |
+
if _get_token_from_environment():
|
| 390 |
+
logger.warning(
|
| 391 |
+
"Note: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured."
|
| 392 |
+
)
|
| 393 |
+
else:
|
| 394 |
+
logger.info(f"The current active token is: `{token_name}`")
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def _logout_from_token(token_name: str) -> None:
|
| 398 |
+
"""Logout from a specific access token.
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
token_name (`str`):
|
| 402 |
+
The name of the access token to logout from.
|
| 403 |
+
Raises:
|
| 404 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
|
| 405 |
+
If the access token name is not found.
|
| 406 |
+
"""
|
| 407 |
+
stored_tokens = get_stored_tokens()
|
| 408 |
+
# If there is no access tokens saved or the access token name is not found, do nothing
|
| 409 |
+
if not stored_tokens or token_name not in stored_tokens:
|
| 410 |
+
return
|
| 411 |
+
|
| 412 |
+
token = stored_tokens.pop(token_name)
|
| 413 |
+
_save_stored_tokens(stored_tokens)
|
| 414 |
+
|
| 415 |
+
if token == _get_token_from_file():
|
| 416 |
+
logger.warning(f"Active token '{token_name}' has been deleted.")
|
| 417 |
+
Path(constants.HF_TOKEN_PATH).unlink(missing_ok=True)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _set_active_token(
|
| 421 |
+
token_name: str,
|
| 422 |
+
add_to_git_credential: bool,
|
| 423 |
+
) -> None:
|
| 424 |
+
"""Set the active access token.
|
| 425 |
+
|
| 426 |
+
Args:
|
| 427 |
+
token_name (`str`):
|
| 428 |
+
The name of the token to set as active.
|
| 429 |
+
"""
|
| 430 |
+
token = _get_token_by_name(token_name)
|
| 431 |
+
if not token:
|
| 432 |
+
raise ValueError(f"Token {token_name} not found in {constants.HF_STORED_TOKENS_PATH}")
|
| 433 |
+
if add_to_git_credential:
|
| 434 |
+
if _is_git_credential_helper_configured():
|
| 435 |
+
set_git_credential(token)
|
| 436 |
+
logger.info(
|
| 437 |
+
"Your token has been saved in your configured git credential helpers"
|
| 438 |
+
+ f" ({','.join(list_credential_helpers())})."
|
| 439 |
+
)
|
| 440 |
+
else:
|
| 441 |
+
logger.warning("Token has not been saved to git credential helper.")
|
| 442 |
+
# Write token to HF_TOKEN_PATH
|
| 443 |
+
path = Path(constants.HF_TOKEN_PATH)
|
| 444 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 445 |
+
path.write_text(token)
|
| 446 |
+
logger.info(f"Your token has been saved to {constants.HF_TOKEN_PATH}")
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _is_git_credential_helper_configured() -> bool:
|
| 450 |
+
"""Check if a git credential helper is configured.
|
| 451 |
+
|
| 452 |
+
Warns user if not the case (except for Google Colab where "store" is set by default
|
| 453 |
+
by `huggingface_hub`).
|
| 454 |
+
"""
|
| 455 |
+
helpers = list_credential_helpers()
|
| 456 |
+
if len(helpers) > 0:
|
| 457 |
+
return True # Do not warn: at least 1 helper is set
|
| 458 |
+
|
| 459 |
+
# Only in Google Colab to avoid the warning message
|
| 460 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1043#issuecomment-1247010710
|
| 461 |
+
if is_google_colab():
|
| 462 |
+
_set_store_as_git_credential_helper_globally()
|
| 463 |
+
return True # Do not warn: "store" is used by default in Google Colab
|
| 464 |
+
|
| 465 |
+
# Otherwise, warn user
|
| 466 |
+
print(
|
| 467 |
+
ANSI.red(
|
| 468 |
+
"Cannot authenticate through git-credential as no helper is defined on your"
|
| 469 |
+
" machine.\nYou might have to re-authenticate when pushing to the Hugging"
|
| 470 |
+
" Face Hub.\nRun the following command in your terminal in case you want to"
|
| 471 |
+
" set the 'store' credential helper as default.\n\ngit config --global"
|
| 472 |
+
" credential.helper store\n\nRead"
|
| 473 |
+
" https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more"
|
| 474 |
+
" details."
|
| 475 |
+
)
|
| 476 |
+
)
|
| 477 |
+
return False
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def _set_store_as_git_credential_helper_globally() -> None:
|
| 481 |
+
"""Set globally the credential.helper to `store`.
|
| 482 |
+
|
| 483 |
+
To be used only in Google Colab as we assume the user doesn't care about the git
|
| 484 |
+
credential config. It is the only particular case where we don't want to display the
|
| 485 |
+
warning message in [`notebook_login()`].
|
| 486 |
+
|
| 487 |
+
Related:
|
| 488 |
+
- https://github.com/huggingface/huggingface_hub/issues/1043
|
| 489 |
+
- https://github.com/huggingface/huggingface_hub/issues/1051
|
| 490 |
+
- https://git-scm.com/docs/git-credential-store
|
| 491 |
+
"""
|
| 492 |
+
try:
|
| 493 |
+
run_subprocess("git config --global credential.helper store")
|
| 494 |
+
except subprocess.CalledProcessError as exc:
|
| 495 |
+
raise EnvironmentError(exc.stderr)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_oauth.py
ADDED
|
@@ -0,0 +1,460 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import hashlib
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import time
|
| 6 |
+
import urllib.parse
|
| 7 |
+
import warnings
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from typing import TYPE_CHECKING, Literal, Optional, Union
|
| 10 |
+
|
| 11 |
+
from . import constants
|
| 12 |
+
from .hf_api import whoami
|
| 13 |
+
from .utils import experimental, get_token
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
if TYPE_CHECKING:
|
| 19 |
+
import fastapi
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass
|
| 23 |
+
class OAuthOrgInfo:
|
| 24 |
+
"""
|
| 25 |
+
Information about an organization linked to a user logged in with OAuth.
|
| 26 |
+
|
| 27 |
+
Attributes:
|
| 28 |
+
sub (`str`):
|
| 29 |
+
Unique identifier for the org. OpenID Connect field.
|
| 30 |
+
name (`str`):
|
| 31 |
+
The org's full name. OpenID Connect field.
|
| 32 |
+
preferred_username (`str`):
|
| 33 |
+
The org's username. OpenID Connect field.
|
| 34 |
+
picture (`str`):
|
| 35 |
+
The org's profile picture URL. OpenID Connect field.
|
| 36 |
+
plan (`str`, *optional*):
|
| 37 |
+
The org's plan (e.g., "enterprise", "team"). Hugging Face field.
|
| 38 |
+
can_pay (`Optional[bool]`, *optional*):
|
| 39 |
+
Whether the org has a payment method set up. Hugging Face field.
|
| 40 |
+
role_in_org (`Optional[str]`, *optional*):
|
| 41 |
+
The user's role in the org. Hugging Face field.
|
| 42 |
+
security_restrictions (`Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]]`, *optional*):
|
| 43 |
+
Array of security restrictions that the user hasn't completed for this org. Possible values: "ip", "token-policy", "mfa", "sso". Hugging Face field.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
sub: str
|
| 47 |
+
name: str
|
| 48 |
+
preferred_username: str
|
| 49 |
+
picture: str
|
| 50 |
+
plan: Optional[str] = None
|
| 51 |
+
can_pay: Optional[bool] = None
|
| 52 |
+
role_in_org: Optional[str] = None
|
| 53 |
+
security_restrictions: Optional[list[Literal["ip", "token-policy", "mfa", "sso"]]] = None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@dataclass
|
| 57 |
+
class OAuthUserInfo:
|
| 58 |
+
"""
|
| 59 |
+
Information about a user logged in with OAuth.
|
| 60 |
+
|
| 61 |
+
Attributes:
|
| 62 |
+
sub (`str`):
|
| 63 |
+
Unique identifier for the user, even in case of rename. OpenID Connect field.
|
| 64 |
+
name (`str`):
|
| 65 |
+
The user's full name. OpenID Connect field.
|
| 66 |
+
preferred_username (`str`):
|
| 67 |
+
The user's username. OpenID Connect field.
|
| 68 |
+
email_verified (`Optional[bool]`, *optional*):
|
| 69 |
+
Indicates if the user's email is verified. OpenID Connect field.
|
| 70 |
+
email (`Optional[str]`, *optional*):
|
| 71 |
+
The user's email address. OpenID Connect field.
|
| 72 |
+
picture (`str`):
|
| 73 |
+
The user's profile picture URL. OpenID Connect field.
|
| 74 |
+
profile (`str`):
|
| 75 |
+
The user's profile URL. OpenID Connect field.
|
| 76 |
+
website (`Optional[str]`, *optional*):
|
| 77 |
+
The user's website URL. OpenID Connect field.
|
| 78 |
+
is_pro (`bool`):
|
| 79 |
+
Whether the user is a pro user. Hugging Face field.
|
| 80 |
+
can_pay (`Optional[bool]`, *optional*):
|
| 81 |
+
Whether the user has a payment method set up. Hugging Face field.
|
| 82 |
+
orgs (`Optional[list[OrgInfo]]`, *optional*):
|
| 83 |
+
List of organizations the user is part of. Hugging Face field.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
sub: str
|
| 87 |
+
name: str
|
| 88 |
+
preferred_username: str
|
| 89 |
+
email_verified: Optional[bool]
|
| 90 |
+
email: Optional[str]
|
| 91 |
+
picture: str
|
| 92 |
+
profile: str
|
| 93 |
+
website: Optional[str]
|
| 94 |
+
is_pro: bool
|
| 95 |
+
can_pay: Optional[bool]
|
| 96 |
+
orgs: Optional[list[OAuthOrgInfo]]
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
@dataclass
|
| 100 |
+
class OAuthInfo:
|
| 101 |
+
"""
|
| 102 |
+
Information about the OAuth login.
|
| 103 |
+
|
| 104 |
+
Attributes:
|
| 105 |
+
access_token (`str`):
|
| 106 |
+
The access token.
|
| 107 |
+
access_token_expires_at (`datetime.datetime`):
|
| 108 |
+
The expiration date of the access token.
|
| 109 |
+
user_info ([`OAuthUserInfo`]):
|
| 110 |
+
The user information.
|
| 111 |
+
state (`str`, *optional*):
|
| 112 |
+
State passed to the OAuth provider in the original request to the OAuth provider.
|
| 113 |
+
scope (`str`):
|
| 114 |
+
Granted scope.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
access_token: str
|
| 118 |
+
access_token_expires_at: datetime.datetime
|
| 119 |
+
user_info: OAuthUserInfo
|
| 120 |
+
state: Optional[str]
|
| 121 |
+
scope: str
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@experimental
|
| 125 |
+
def attach_huggingface_oauth(app: "fastapi.FastAPI", route_prefix: str = "/"):
|
| 126 |
+
"""
|
| 127 |
+
Add OAuth endpoints to a FastAPI app to enable OAuth login with Hugging Face.
|
| 128 |
+
|
| 129 |
+
How to use:
|
| 130 |
+
- Call this method on your FastAPI app to add the OAuth endpoints.
|
| 131 |
+
- Inside your route handlers, call `parse_huggingface_oauth(request)` to retrieve the OAuth info.
|
| 132 |
+
- If user is logged in, an [`OAuthInfo`] object is returned with the user's info. If not, `None` is returned.
|
| 133 |
+
- In your app, make sure to add links to `/oauth/huggingface/login` and `/oauth/huggingface/logout` for the user to log in and out.
|
| 134 |
+
|
| 135 |
+
Example:
|
| 136 |
+
```py
|
| 137 |
+
from huggingface_hub import attach_huggingface_oauth, parse_huggingface_oauth
|
| 138 |
+
|
| 139 |
+
# Create a FastAPI app
|
| 140 |
+
app = FastAPI()
|
| 141 |
+
|
| 142 |
+
# Add OAuth endpoints to the FastAPI app
|
| 143 |
+
attach_huggingface_oauth(app)
|
| 144 |
+
|
| 145 |
+
# Add a route that greets the user if they are logged in
|
| 146 |
+
@app.get("/")
|
| 147 |
+
def greet_json(request: Request):
|
| 148 |
+
# Retrieve the OAuth info from the request
|
| 149 |
+
oauth_info = parse_huggingface_oauth(request) # e.g. OAuthInfo dataclass
|
| 150 |
+
if oauth_info is None:
|
| 151 |
+
return {"msg": "Not logged in!"}
|
| 152 |
+
return {"msg": f"Hello, {oauth_info.user_info.preferred_username}!"}
|
| 153 |
+
```
|
| 154 |
+
"""
|
| 155 |
+
# TODO: handle generic case (handling OAuth in a non-Space environment with custom dev values) (low priority)
|
| 156 |
+
|
| 157 |
+
# Add SessionMiddleware to the FastAPI app to store the OAuth info in the session.
|
| 158 |
+
# Session Middleware requires a secret key to sign the cookies. Let's use a hash
|
| 159 |
+
# of the OAuth secret key to make it unique to the Space + updated in case OAuth
|
| 160 |
+
# config gets updated. When ran locally, we use an empty string as a secret key.
|
| 161 |
+
try:
|
| 162 |
+
from starlette.middleware.sessions import SessionMiddleware
|
| 163 |
+
except ImportError as e:
|
| 164 |
+
raise ImportError(
|
| 165 |
+
"Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
|
| 166 |
+
"`huggingface_hub[oauth]` to your requirements.txt file in order to install the required dependencies."
|
| 167 |
+
) from e
|
| 168 |
+
session_secret = (constants.OAUTH_CLIENT_SECRET or "") + "-v1"
|
| 169 |
+
app.add_middleware(
|
| 170 |
+
SessionMiddleware, # type: ignore[arg-type]
|
| 171 |
+
secret_key=hashlib.sha256(session_secret.encode()).hexdigest(),
|
| 172 |
+
same_site="none",
|
| 173 |
+
https_only=True,
|
| 174 |
+
) # type: ignore
|
| 175 |
+
|
| 176 |
+
# Add OAuth endpoints to the FastAPI app:
|
| 177 |
+
# - {route_prefix}/oauth/huggingface/login
|
| 178 |
+
# - {route_prefix}/oauth/huggingface/callback
|
| 179 |
+
# - {route_prefix}/oauth/huggingface/logout
|
| 180 |
+
# If the app is running in a Space, OAuth is enabled normally.
|
| 181 |
+
# Otherwise, we mock the endpoints to make the user log in with a fake user profile - without any calls to hf.co.
|
| 182 |
+
route_prefix = route_prefix.strip("/")
|
| 183 |
+
if os.getenv("SPACE_ID") is not None:
|
| 184 |
+
logger.info("OAuth is enabled in the Space. Adding OAuth routes.")
|
| 185 |
+
_add_oauth_routes(app, route_prefix=route_prefix)
|
| 186 |
+
else:
|
| 187 |
+
logger.info("App is not running in a Space. Adding mocked OAuth routes.")
|
| 188 |
+
_add_mocked_oauth_routes(app, route_prefix=route_prefix)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def parse_huggingface_oauth(request: "fastapi.Request") -> Optional[OAuthInfo]:
|
| 192 |
+
"""
|
| 193 |
+
Returns the information from a logged-in user as a [`OAuthInfo`] object.
|
| 194 |
+
|
| 195 |
+
For flexibility and future-proofing, this method is very lax in its parsing and does not raise errors.
|
| 196 |
+
Missing fields are set to `None` without a warning.
|
| 197 |
+
|
| 198 |
+
Return `None`, if the user is not logged in (no info in session cookie).
|
| 199 |
+
|
| 200 |
+
See [`attach_huggingface_oauth`] for an example on how to use this method.
|
| 201 |
+
"""
|
| 202 |
+
if "oauth_info" not in request.session:
|
| 203 |
+
logger.debug("No OAuth info in session.")
|
| 204 |
+
return None
|
| 205 |
+
|
| 206 |
+
logger.debug("Parsing OAuth info from session.")
|
| 207 |
+
oauth_data = request.session["oauth_info"]
|
| 208 |
+
user_data = oauth_data.get("userinfo", {})
|
| 209 |
+
orgs_data = user_data.get("orgs", [])
|
| 210 |
+
|
| 211 |
+
orgs = (
|
| 212 |
+
[
|
| 213 |
+
OAuthOrgInfo(
|
| 214 |
+
sub=org.get("sub"),
|
| 215 |
+
name=org.get("name"),
|
| 216 |
+
preferred_username=org.get("preferred_username"),
|
| 217 |
+
picture=org.get("picture"),
|
| 218 |
+
plan=org.get("plan"),
|
| 219 |
+
can_pay=org.get("canPay"),
|
| 220 |
+
role_in_org=org.get("roleInOrg"),
|
| 221 |
+
security_restrictions=org.get("securityRestrictions"),
|
| 222 |
+
)
|
| 223 |
+
for org in orgs_data
|
| 224 |
+
]
|
| 225 |
+
if orgs_data
|
| 226 |
+
else None
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
user_info = OAuthUserInfo(
|
| 230 |
+
sub=user_data.get("sub"),
|
| 231 |
+
name=user_data.get("name"),
|
| 232 |
+
preferred_username=user_data.get("preferred_username"),
|
| 233 |
+
email_verified=user_data.get("email_verified"),
|
| 234 |
+
email=user_data.get("email"),
|
| 235 |
+
picture=user_data.get("picture"),
|
| 236 |
+
profile=user_data.get("profile"),
|
| 237 |
+
website=user_data.get("website"),
|
| 238 |
+
is_pro=user_data.get("isPro"),
|
| 239 |
+
can_pay=user_data.get("canPay"),
|
| 240 |
+
orgs=orgs,
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return OAuthInfo(
|
| 244 |
+
access_token=oauth_data.get("access_token"),
|
| 245 |
+
access_token_expires_at=datetime.datetime.fromtimestamp(oauth_data.get("expires_at")),
|
| 246 |
+
user_info=user_info,
|
| 247 |
+
state=oauth_data.get("state"),
|
| 248 |
+
scope=oauth_data.get("scope"),
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _add_oauth_routes(app: "fastapi.FastAPI", route_prefix: str) -> None:
|
| 253 |
+
"""Add OAuth routes to the FastAPI app (login, callback handler and logout)."""
|
| 254 |
+
try:
|
| 255 |
+
import fastapi
|
| 256 |
+
from authlib.integrations.base_client.errors import MismatchingStateError
|
| 257 |
+
from authlib.integrations.starlette_client import OAuth
|
| 258 |
+
from fastapi.responses import RedirectResponse
|
| 259 |
+
except ImportError as e:
|
| 260 |
+
raise ImportError(
|
| 261 |
+
"Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
|
| 262 |
+
"`huggingface_hub[oauth]` to your requirements.txt file."
|
| 263 |
+
) from e
|
| 264 |
+
|
| 265 |
+
# Check environment variables
|
| 266 |
+
msg = (
|
| 267 |
+
"OAuth is required but '{}' environment variable is not set. Make sure you've enabled OAuth in your Space by"
|
| 268 |
+
" setting `hf_oauth: true` in the Space metadata."
|
| 269 |
+
)
|
| 270 |
+
if constants.OAUTH_CLIENT_ID is None:
|
| 271 |
+
raise ValueError(msg.format("OAUTH_CLIENT_ID"))
|
| 272 |
+
if constants.OAUTH_CLIENT_SECRET is None:
|
| 273 |
+
raise ValueError(msg.format("OAUTH_CLIENT_SECRET"))
|
| 274 |
+
if constants.OAUTH_SCOPES is None:
|
| 275 |
+
raise ValueError(msg.format("OAUTH_SCOPES"))
|
| 276 |
+
if constants.OPENID_PROVIDER_URL is None:
|
| 277 |
+
raise ValueError(msg.format("OPENID_PROVIDER_URL"))
|
| 278 |
+
|
| 279 |
+
# Register OAuth server
|
| 280 |
+
oauth = OAuth()
|
| 281 |
+
oauth.register(
|
| 282 |
+
name="huggingface",
|
| 283 |
+
client_id=constants.OAUTH_CLIENT_ID,
|
| 284 |
+
client_secret=constants.OAUTH_CLIENT_SECRET,
|
| 285 |
+
client_kwargs={"scope": constants.OAUTH_SCOPES},
|
| 286 |
+
server_metadata_url=constants.OPENID_PROVIDER_URL + "/.well-known/openid-configuration",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
|
| 290 |
+
|
| 291 |
+
# Register OAuth endpoints
|
| 292 |
+
@app.get(login_uri)
|
| 293 |
+
async def oauth_login(request: fastapi.Request) -> RedirectResponse:
|
| 294 |
+
"""Endpoint that redirects to HF OAuth page."""
|
| 295 |
+
redirect_uri = _generate_redirect_uri(request)
|
| 296 |
+
return await oauth.huggingface.authorize_redirect(request, redirect_uri) # type: ignore
|
| 297 |
+
|
| 298 |
+
@app.get(callback_uri)
|
| 299 |
+
async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
|
| 300 |
+
"""Endpoint that handles the OAuth callback."""
|
| 301 |
+
try:
|
| 302 |
+
oauth_info = await oauth.huggingface.authorize_access_token(request) # type: ignore
|
| 303 |
+
except MismatchingStateError:
|
| 304 |
+
# Parse query params
|
| 305 |
+
nb_redirects = int(request.query_params.get("_nb_redirects", 0))
|
| 306 |
+
target_url = request.query_params.get("_target_url")
|
| 307 |
+
|
| 308 |
+
# Build redirect URI with the same query params as before and bump nb_redirects count
|
| 309 |
+
query_params: dict[str, Union[int, str]] = {"_nb_redirects": nb_redirects + 1}
|
| 310 |
+
if target_url:
|
| 311 |
+
query_params["_target_url"] = target_url
|
| 312 |
+
|
| 313 |
+
redirect_uri = f"{login_uri}?{urllib.parse.urlencode(query_params)}"
|
| 314 |
+
|
| 315 |
+
# If the user is redirected more than 3 times, it is very likely that the cookie is not working properly.
|
| 316 |
+
# (e.g. browser is blocking third-party cookies in iframe). In this case, redirect the user in the
|
| 317 |
+
# non-iframe view.
|
| 318 |
+
if nb_redirects > constants.OAUTH_MAX_REDIRECTS:
|
| 319 |
+
host = os.environ.get("SPACE_HOST")
|
| 320 |
+
if host is None: # cannot happen in a Space
|
| 321 |
+
raise RuntimeError(
|
| 322 |
+
"App is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view."
|
| 323 |
+
) from None
|
| 324 |
+
host_url = "https://" + host.rstrip("/")
|
| 325 |
+
return RedirectResponse(host_url + redirect_uri)
|
| 326 |
+
|
| 327 |
+
# Redirect the user to the login page again
|
| 328 |
+
return RedirectResponse(redirect_uri)
|
| 329 |
+
|
| 330 |
+
# OAuth login worked => store the user info in the session and redirect
|
| 331 |
+
logger.debug("Successfully logged in with OAuth. Storing user info in session.")
|
| 332 |
+
request.session["oauth_info"] = oauth_info
|
| 333 |
+
return RedirectResponse(_get_redirect_target(request))
|
| 334 |
+
|
| 335 |
+
@app.get(logout_uri)
|
| 336 |
+
async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
|
| 337 |
+
"""Endpoint that logs out the user (e.g. delete info from cookie session)."""
|
| 338 |
+
logger.debug("Logged out with OAuth. Removing user info from session.")
|
| 339 |
+
request.session.pop("oauth_info", None)
|
| 340 |
+
return RedirectResponse(_get_redirect_target(request))
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def _add_mocked_oauth_routes(app: "fastapi.FastAPI", route_prefix: str = "/") -> None:
|
| 344 |
+
"""Add fake oauth routes if app is run locally and OAuth is enabled.
|
| 345 |
+
|
| 346 |
+
Using OAuth will have the same behavior as in a Space but instead of authenticating with HF, a mocked user profile
|
| 347 |
+
is added to the session.
|
| 348 |
+
"""
|
| 349 |
+
try:
|
| 350 |
+
import fastapi
|
| 351 |
+
from fastapi.responses import RedirectResponse
|
| 352 |
+
from starlette.datastructures import URL
|
| 353 |
+
except ImportError as e:
|
| 354 |
+
raise ImportError(
|
| 355 |
+
"Cannot initialize OAuth to due a missing library. Please run `pip install huggingface_hub[oauth]` or add "
|
| 356 |
+
"`huggingface_hub[oauth]` to your requirements.txt file."
|
| 357 |
+
) from e
|
| 358 |
+
|
| 359 |
+
warnings.warn(
|
| 360 |
+
"OAuth is not supported outside of a Space environment. To help you debug your app locally, the oauth endpoints"
|
| 361 |
+
" are mocked to return your profile and token. To make it work, your machine must be logged in to Huggingface."
|
| 362 |
+
)
|
| 363 |
+
mocked_oauth_info = _get_mocked_oauth_info()
|
| 364 |
+
|
| 365 |
+
login_uri, callback_uri, logout_uri = _get_oauth_uris(route_prefix)
|
| 366 |
+
|
| 367 |
+
# Define OAuth routes
|
| 368 |
+
@app.get(login_uri)
|
| 369 |
+
async def oauth_login(request: fastapi.Request) -> RedirectResponse:
|
| 370 |
+
"""Fake endpoint that redirects to HF OAuth page."""
|
| 371 |
+
# Define target (where to redirect after login)
|
| 372 |
+
redirect_uri = _generate_redirect_uri(request)
|
| 373 |
+
return RedirectResponse(callback_uri + "?" + urllib.parse.urlencode({"_target_url": redirect_uri}))
|
| 374 |
+
|
| 375 |
+
@app.get(callback_uri)
|
| 376 |
+
async def oauth_redirect_callback(request: fastapi.Request) -> RedirectResponse:
|
| 377 |
+
"""Endpoint that handles the OAuth callback."""
|
| 378 |
+
request.session["oauth_info"] = mocked_oauth_info
|
| 379 |
+
return RedirectResponse(_get_redirect_target(request))
|
| 380 |
+
|
| 381 |
+
@app.get(logout_uri)
|
| 382 |
+
async def oauth_logout(request: fastapi.Request) -> RedirectResponse:
|
| 383 |
+
"""Endpoint that logs out the user (e.g. delete cookie session)."""
|
| 384 |
+
request.session.pop("oauth_info", None)
|
| 385 |
+
logout_url = URL("/").include_query_params(**request.query_params)
|
| 386 |
+
return RedirectResponse(url=logout_url, status_code=302) # see https://github.com/gradio-app/gradio/pull/9659
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _generate_redirect_uri(request: "fastapi.Request") -> str:
|
| 390 |
+
if "_target_url" in request.query_params:
|
| 391 |
+
# if `_target_url` already in query params => respect it
|
| 392 |
+
target = request.query_params["_target_url"]
|
| 393 |
+
else:
|
| 394 |
+
# otherwise => keep query params
|
| 395 |
+
target = "/?" + urllib.parse.urlencode(request.query_params)
|
| 396 |
+
|
| 397 |
+
redirect_uri = request.url_for("oauth_redirect_callback").include_query_params(_target_url=target)
|
| 398 |
+
redirect_uri_as_str = str(redirect_uri)
|
| 399 |
+
if redirect_uri.netloc.endswith(".hf.space"):
|
| 400 |
+
# In Space, FastAPI redirect as http but we want https
|
| 401 |
+
redirect_uri_as_str = redirect_uri_as_str.replace("http://", "https://")
|
| 402 |
+
return redirect_uri_as_str
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _get_redirect_target(request: "fastapi.Request", default_target: str = "/") -> str:
|
| 406 |
+
return request.query_params.get("_target_url", default_target)
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
def _get_mocked_oauth_info() -> dict:
|
| 410 |
+
token = get_token()
|
| 411 |
+
if token is None:
|
| 412 |
+
raise ValueError(
|
| 413 |
+
"Your machine must be logged in to HF to debug an OAuth app locally. Please"
|
| 414 |
+
" run `hf auth login` or set `HF_TOKEN` as environment variable "
|
| 415 |
+
"with one of your access token. You can generate a new token in your "
|
| 416 |
+
"settings page (https://huggingface.co/settings/tokens)."
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
user = whoami()
|
| 420 |
+
if user["type"] != "user":
|
| 421 |
+
raise ValueError(
|
| 422 |
+
"Your machine is not logged in with a personal account. Please use a "
|
| 423 |
+
"personal access token. You can generate a new token in your settings page"
|
| 424 |
+
" (https://huggingface.co/settings/tokens)."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
return {
|
| 428 |
+
"access_token": token,
|
| 429 |
+
"token_type": "bearer",
|
| 430 |
+
"expires_in": 8 * 60 * 60, # 8 hours
|
| 431 |
+
"id_token": "FOOBAR",
|
| 432 |
+
"scope": "openid profile",
|
| 433 |
+
"refresh_token": "hf_oauth__refresh_token",
|
| 434 |
+
"expires_at": int(time.time()) + 8 * 60 * 60, # 8 hours
|
| 435 |
+
"userinfo": {
|
| 436 |
+
"sub": "0123456789",
|
| 437 |
+
"name": user["fullname"],
|
| 438 |
+
"preferred_username": user["name"],
|
| 439 |
+
"profile": f"https://huggingface.co/{user['name']}",
|
| 440 |
+
"picture": user["avatarUrl"],
|
| 441 |
+
"website": "",
|
| 442 |
+
"aud": "00000000-0000-0000-0000-000000000000",
|
| 443 |
+
"auth_time": 1691672844,
|
| 444 |
+
"nonce": "aaaaaaaaaaaaaaaaaaa",
|
| 445 |
+
"iat": 1691672844,
|
| 446 |
+
"exp": 1691676444,
|
| 447 |
+
"iss": "https://huggingface.co",
|
| 448 |
+
},
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _get_oauth_uris(route_prefix: str = "/") -> tuple[str, str, str]:
|
| 453 |
+
route_prefix = route_prefix.strip("/")
|
| 454 |
+
if route_prefix:
|
| 455 |
+
route_prefix = f"/{route_prefix}"
|
| 456 |
+
return (
|
| 457 |
+
f"{route_prefix}/oauth/huggingface/login",
|
| 458 |
+
f"{route_prefix}/oauth/huggingface/callback",
|
| 459 |
+
f"{route_prefix}/oauth/huggingface/logout",
|
| 460 |
+
)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_snapshot_download.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from typing import Iterable, List, Literal, Optional, Union, overload
|
| 4 |
+
|
| 5 |
+
import httpx
|
| 6 |
+
from tqdm.auto import tqdm as base_tqdm
|
| 7 |
+
from tqdm.contrib.concurrent import thread_map
|
| 8 |
+
|
| 9 |
+
from . import constants
|
| 10 |
+
from .errors import (
|
| 11 |
+
DryRunError,
|
| 12 |
+
GatedRepoError,
|
| 13 |
+
HfHubHTTPError,
|
| 14 |
+
LocalEntryNotFoundError,
|
| 15 |
+
RepositoryNotFoundError,
|
| 16 |
+
RevisionNotFoundError,
|
| 17 |
+
)
|
| 18 |
+
from .file_download import REGEX_COMMIT_HASH, DryRunFileInfo, hf_hub_download, repo_folder_name
|
| 19 |
+
from .hf_api import DatasetInfo, HfApi, ModelInfo, RepoFile, SpaceInfo
|
| 20 |
+
from .utils import OfflineModeIsEnabled, filter_repo_objects, is_tqdm_disabled, logging, validate_hf_hub_args
|
| 21 |
+
from .utils import tqdm as hf_tqdm
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
logger = logging.get_logger(__name__)
|
| 25 |
+
|
| 26 |
+
LARGE_REPO_THRESHOLD = 1000 # After this limit, we don't consider `repo_info.siblings` to be reliable enough
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@overload
|
| 30 |
+
def snapshot_download(
|
| 31 |
+
repo_id: str,
|
| 32 |
+
*,
|
| 33 |
+
repo_type: Optional[str] = None,
|
| 34 |
+
revision: Optional[str] = None,
|
| 35 |
+
cache_dir: Union[str, Path, None] = None,
|
| 36 |
+
local_dir: Union[str, Path, None] = None,
|
| 37 |
+
library_name: Optional[str] = None,
|
| 38 |
+
library_version: Optional[str] = None,
|
| 39 |
+
user_agent: Optional[Union[dict, str]] = None,
|
| 40 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 41 |
+
force_download: bool = False,
|
| 42 |
+
token: Optional[Union[bool, str]] = None,
|
| 43 |
+
local_files_only: bool = False,
|
| 44 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 45 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 46 |
+
max_workers: int = 8,
|
| 47 |
+
tqdm_class: Optional[type[base_tqdm]] = None,
|
| 48 |
+
headers: Optional[dict[str, str]] = None,
|
| 49 |
+
endpoint: Optional[str] = None,
|
| 50 |
+
dry_run: Literal[False] = False,
|
| 51 |
+
) -> str: ...
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@overload
|
| 55 |
+
def snapshot_download(
|
| 56 |
+
repo_id: str,
|
| 57 |
+
*,
|
| 58 |
+
repo_type: Optional[str] = None,
|
| 59 |
+
revision: Optional[str] = None,
|
| 60 |
+
cache_dir: Union[str, Path, None] = None,
|
| 61 |
+
local_dir: Union[str, Path, None] = None,
|
| 62 |
+
library_name: Optional[str] = None,
|
| 63 |
+
library_version: Optional[str] = None,
|
| 64 |
+
user_agent: Optional[Union[dict, str]] = None,
|
| 65 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 66 |
+
force_download: bool = False,
|
| 67 |
+
token: Optional[Union[bool, str]] = None,
|
| 68 |
+
local_files_only: bool = False,
|
| 69 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 70 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 71 |
+
max_workers: int = 8,
|
| 72 |
+
tqdm_class: Optional[type[base_tqdm]] = None,
|
| 73 |
+
headers: Optional[dict[str, str]] = None,
|
| 74 |
+
endpoint: Optional[str] = None,
|
| 75 |
+
dry_run: Literal[True] = True,
|
| 76 |
+
) -> list[DryRunFileInfo]: ...
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@overload
|
| 80 |
+
def snapshot_download(
|
| 81 |
+
repo_id: str,
|
| 82 |
+
*,
|
| 83 |
+
repo_type: Optional[str] = None,
|
| 84 |
+
revision: Optional[str] = None,
|
| 85 |
+
cache_dir: Union[str, Path, None] = None,
|
| 86 |
+
local_dir: Union[str, Path, None] = None,
|
| 87 |
+
library_name: Optional[str] = None,
|
| 88 |
+
library_version: Optional[str] = None,
|
| 89 |
+
user_agent: Optional[Union[dict, str]] = None,
|
| 90 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 91 |
+
force_download: bool = False,
|
| 92 |
+
token: Optional[Union[bool, str]] = None,
|
| 93 |
+
local_files_only: bool = False,
|
| 94 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 95 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 96 |
+
max_workers: int = 8,
|
| 97 |
+
tqdm_class: Optional[type[base_tqdm]] = None,
|
| 98 |
+
headers: Optional[dict[str, str]] = None,
|
| 99 |
+
endpoint: Optional[str] = None,
|
| 100 |
+
dry_run: bool = False,
|
| 101 |
+
) -> Union[str, list[DryRunFileInfo]]: ...
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@validate_hf_hub_args
|
| 105 |
+
def snapshot_download(
|
| 106 |
+
repo_id: str,
|
| 107 |
+
*,
|
| 108 |
+
repo_type: Optional[str] = None,
|
| 109 |
+
revision: Optional[str] = None,
|
| 110 |
+
cache_dir: Union[str, Path, None] = None,
|
| 111 |
+
local_dir: Union[str, Path, None] = None,
|
| 112 |
+
library_name: Optional[str] = None,
|
| 113 |
+
library_version: Optional[str] = None,
|
| 114 |
+
user_agent: Optional[Union[dict, str]] = None,
|
| 115 |
+
etag_timeout: float = constants.DEFAULT_ETAG_TIMEOUT,
|
| 116 |
+
force_download: bool = False,
|
| 117 |
+
token: Optional[Union[bool, str]] = None,
|
| 118 |
+
local_files_only: bool = False,
|
| 119 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 120 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 121 |
+
max_workers: int = 8,
|
| 122 |
+
tqdm_class: Optional[type[base_tqdm]] = None,
|
| 123 |
+
headers: Optional[dict[str, str]] = None,
|
| 124 |
+
endpoint: Optional[str] = None,
|
| 125 |
+
dry_run: bool = False,
|
| 126 |
+
) -> Union[str, list[DryRunFileInfo]]:
|
| 127 |
+
"""Download repo files.
|
| 128 |
+
|
| 129 |
+
Download a whole snapshot of a repo's files at the specified revision. This is useful when you want all files from
|
| 130 |
+
a repo, because you don't know which ones you will need a priori. All files are nested inside a folder in order
|
| 131 |
+
to keep their actual filename relative to that folder. You can also filter which files to download using
|
| 132 |
+
`allow_patterns` and `ignore_patterns`.
|
| 133 |
+
|
| 134 |
+
If `local_dir` is provided, the file structure from the repo will be replicated in this location. When using this
|
| 135 |
+
option, the `cache_dir` will not be used and a `.cache/huggingface/` folder will be created at the root of `local_dir`
|
| 136 |
+
to store some metadata related to the downloaded files. While this mechanism is not as robust as the main
|
| 137 |
+
cache-system, it's optimized for regularly pulling the latest version of a repository.
|
| 138 |
+
|
| 139 |
+
An alternative would be to clone the repo but this requires git and git-lfs to be installed and properly
|
| 140 |
+
configured. It is also not possible to filter which files to download when cloning a repository using git.
|
| 141 |
+
|
| 142 |
+
Args:
|
| 143 |
+
repo_id (`str`):
|
| 144 |
+
A user or an organization name and a repo name separated by a `/`.
|
| 145 |
+
repo_type (`str`, *optional*):
|
| 146 |
+
Set to `"dataset"` or `"space"` if downloading from a dataset or space,
|
| 147 |
+
`None` or `"model"` if downloading from a model. Default is `None`.
|
| 148 |
+
revision (`str`, *optional*):
|
| 149 |
+
An optional Git revision id which can be a branch name, a tag, or a
|
| 150 |
+
commit hash.
|
| 151 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 152 |
+
Path to the folder where cached files are stored.
|
| 153 |
+
local_dir (`str` or `Path`, *optional*):
|
| 154 |
+
If provided, the downloaded files will be placed under this directory.
|
| 155 |
+
library_name (`str`, *optional*):
|
| 156 |
+
The name of the library to which the object corresponds.
|
| 157 |
+
library_version (`str`, *optional*):
|
| 158 |
+
The version of the library.
|
| 159 |
+
user_agent (`str`, `dict`, *optional*):
|
| 160 |
+
The user-agent info in the form of a dictionary or a string.
|
| 161 |
+
etag_timeout (`float`, *optional*, defaults to `10`):
|
| 162 |
+
When fetching ETag, how many seconds to wait for the server to send
|
| 163 |
+
data before giving up which is passed to `httpx.request`.
|
| 164 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 165 |
+
Whether the file should be downloaded even if it already exists in the local cache.
|
| 166 |
+
token (`str`, `bool`, *optional*):
|
| 167 |
+
A token to be used for the download.
|
| 168 |
+
- If `True`, the token is read from the HuggingFace config
|
| 169 |
+
folder.
|
| 170 |
+
- If a string, it's used as the authentication token.
|
| 171 |
+
headers (`dict`, *optional*):
|
| 172 |
+
Additional headers to include in the request. Those headers take precedence over the others.
|
| 173 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 174 |
+
If `True`, avoid downloading the file and return the path to the
|
| 175 |
+
local cached file if it exists.
|
| 176 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 177 |
+
If provided, only files matching at least one pattern are downloaded.
|
| 178 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 179 |
+
If provided, files matching any of the patterns are not downloaded.
|
| 180 |
+
max_workers (`int`, *optional*):
|
| 181 |
+
Number of concurrent threads to download files (1 thread = 1 file download).
|
| 182 |
+
Defaults to 8.
|
| 183 |
+
tqdm_class (`tqdm`, *optional*):
|
| 184 |
+
If provided, overwrites the default behavior for the progress bar. Passed
|
| 185 |
+
argument must inherit from `tqdm.auto.tqdm` or at least mimic its behavior.
|
| 186 |
+
Note that the `tqdm_class` is not passed to each individual download.
|
| 187 |
+
Defaults to the custom HF progress bar that can be disabled by setting
|
| 188 |
+
`HF_HUB_DISABLE_PROGRESS_BARS` environment variable.
|
| 189 |
+
dry_run (`bool`, *optional*, defaults to `False`):
|
| 190 |
+
If `True`, perform a dry run without actually downloading the files. Returns a list of
|
| 191 |
+
[`DryRunFileInfo`] objects containing information about what would be downloaded.
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
`str` or list of [`DryRunFileInfo`]:
|
| 195 |
+
- If `dry_run=False`: Local snapshot path.
|
| 196 |
+
- If `dry_run=True`: A list of [`DryRunFileInfo`] objects containing download information.
|
| 197 |
+
|
| 198 |
+
Raises:
|
| 199 |
+
[`~utils.RepositoryNotFoundError`]
|
| 200 |
+
If the repository to download from cannot be found. This may be because it doesn't exist,
|
| 201 |
+
or because it is set to `private` and you do not have access.
|
| 202 |
+
[`~utils.RevisionNotFoundError`]
|
| 203 |
+
If the revision to download from cannot be found.
|
| 204 |
+
[`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
|
| 205 |
+
If `token=True` and the token cannot be found.
|
| 206 |
+
[`OSError`](https://docs.python.org/3/library/exceptions.html#OSError) if
|
| 207 |
+
ETag cannot be determined.
|
| 208 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 209 |
+
if some parameter value is invalid.
|
| 210 |
+
"""
|
| 211 |
+
if cache_dir is None:
|
| 212 |
+
cache_dir = constants.HF_HUB_CACHE
|
| 213 |
+
if revision is None:
|
| 214 |
+
revision = constants.DEFAULT_REVISION
|
| 215 |
+
if isinstance(cache_dir, Path):
|
| 216 |
+
cache_dir = str(cache_dir)
|
| 217 |
+
|
| 218 |
+
if repo_type is None:
|
| 219 |
+
repo_type = "model"
|
| 220 |
+
if repo_type not in constants.REPO_TYPES:
|
| 221 |
+
raise ValueError(f"Invalid repo type: {repo_type}. Accepted repo types are: {str(constants.REPO_TYPES)}")
|
| 222 |
+
|
| 223 |
+
storage_folder = os.path.join(cache_dir, repo_folder_name(repo_id=repo_id, repo_type=repo_type))
|
| 224 |
+
|
| 225 |
+
api = HfApi(
|
| 226 |
+
library_name=library_name,
|
| 227 |
+
library_version=library_version,
|
| 228 |
+
user_agent=user_agent,
|
| 229 |
+
endpoint=endpoint,
|
| 230 |
+
headers=headers,
|
| 231 |
+
token=token,
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
repo_info: Union[ModelInfo, DatasetInfo, SpaceInfo, None] = None
|
| 235 |
+
api_call_error: Optional[Exception] = None
|
| 236 |
+
if not local_files_only:
|
| 237 |
+
# try/except logic to handle different errors => taken from `hf_hub_download`
|
| 238 |
+
try:
|
| 239 |
+
# if we have internet connection we want to list files to download
|
| 240 |
+
repo_info = api.repo_info(repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 241 |
+
except httpx.ProxyError:
|
| 242 |
+
# Actually raise on proxy error
|
| 243 |
+
raise
|
| 244 |
+
except (httpx.ConnectError, httpx.TimeoutException, OfflineModeIsEnabled) as error:
|
| 245 |
+
# Internet connection is down
|
| 246 |
+
# => will try to use local files only
|
| 247 |
+
api_call_error = error
|
| 248 |
+
pass
|
| 249 |
+
except RevisionNotFoundError:
|
| 250 |
+
# The repo was found but the revision doesn't exist on the Hub (never existed or got deleted)
|
| 251 |
+
raise
|
| 252 |
+
except HfHubHTTPError as error:
|
| 253 |
+
# Multiple reasons for an http error:
|
| 254 |
+
# - Repository is private and invalid/missing token sent
|
| 255 |
+
# - Repository is gated and invalid/missing token sent
|
| 256 |
+
# - Hub is down (error 500 or 504)
|
| 257 |
+
# => let's switch to 'local_files_only=True' to check if the files are already cached.
|
| 258 |
+
# (if it's not the case, the error will be re-raised)
|
| 259 |
+
api_call_error = error
|
| 260 |
+
pass
|
| 261 |
+
|
| 262 |
+
# At this stage, if `repo_info` is None it means either:
|
| 263 |
+
# - internet connection is down
|
| 264 |
+
# - internet connection is deactivated (local_files_only=True or HF_HUB_OFFLINE=True)
|
| 265 |
+
# - repo is private/gated and invalid/missing token sent
|
| 266 |
+
# - Hub is down
|
| 267 |
+
# => let's look if we can find the appropriate folder in the cache:
|
| 268 |
+
# - if the specified revision is a commit hash, look inside "snapshots".
|
| 269 |
+
# - f the specified revision is a branch or tag, look inside "refs".
|
| 270 |
+
# => if local_dir is not None, we will return the path to the local folder if it exists.
|
| 271 |
+
if repo_info is None:
|
| 272 |
+
if dry_run:
|
| 273 |
+
raise DryRunError(
|
| 274 |
+
"Dry run cannot be performed as the repository cannot be accessed. Please check your internet connection or authentication token."
|
| 275 |
+
) from api_call_error
|
| 276 |
+
|
| 277 |
+
# Try to get which commit hash corresponds to the specified revision
|
| 278 |
+
commit_hash = None
|
| 279 |
+
if REGEX_COMMIT_HASH.match(revision):
|
| 280 |
+
commit_hash = revision
|
| 281 |
+
else:
|
| 282 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
| 283 |
+
if os.path.exists(ref_path):
|
| 284 |
+
# retrieve commit_hash from refs file
|
| 285 |
+
with open(ref_path) as f:
|
| 286 |
+
commit_hash = f.read()
|
| 287 |
+
|
| 288 |
+
# Try to locate snapshot folder for this commit hash
|
| 289 |
+
if commit_hash is not None and local_dir is None:
|
| 290 |
+
snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
|
| 291 |
+
if os.path.exists(snapshot_folder):
|
| 292 |
+
# Snapshot folder exists => let's return it
|
| 293 |
+
# (but we can't check if all the files are actually there)
|
| 294 |
+
return snapshot_folder
|
| 295 |
+
|
| 296 |
+
# If local_dir is not None, return it if it exists and is not empty
|
| 297 |
+
if local_dir is not None:
|
| 298 |
+
local_dir = Path(local_dir)
|
| 299 |
+
if local_dir.is_dir() and any(local_dir.iterdir()):
|
| 300 |
+
logger.warning(
|
| 301 |
+
f"Returning existing local_dir `{local_dir}` as remote repo cannot be accessed in `snapshot_download` ({api_call_error})."
|
| 302 |
+
)
|
| 303 |
+
return str(local_dir.resolve())
|
| 304 |
+
# If we couldn't find the appropriate folder on disk, raise an error.
|
| 305 |
+
if local_files_only:
|
| 306 |
+
raise LocalEntryNotFoundError(
|
| 307 |
+
"Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
|
| 308 |
+
"outgoing traffic has been disabled. To enable repo look-ups and downloads online, pass "
|
| 309 |
+
"'local_files_only=False' as input."
|
| 310 |
+
)
|
| 311 |
+
elif isinstance(api_call_error, OfflineModeIsEnabled):
|
| 312 |
+
raise LocalEntryNotFoundError(
|
| 313 |
+
"Cannot find an appropriate cached snapshot folder for the specified revision on the local disk and "
|
| 314 |
+
"outgoing traffic has been disabled. To enable repo look-ups and downloads online, set "
|
| 315 |
+
"'HF_HUB_OFFLINE=0' as environment variable."
|
| 316 |
+
) from api_call_error
|
| 317 |
+
elif isinstance(api_call_error, (RepositoryNotFoundError, GatedRepoError)) or (
|
| 318 |
+
isinstance(api_call_error, HfHubHTTPError) and api_call_error.response.status_code == 401
|
| 319 |
+
):
|
| 320 |
+
# Repo not found, gated, or specific authentication error => let's raise the actual error
|
| 321 |
+
raise api_call_error
|
| 322 |
+
else:
|
| 323 |
+
# Otherwise: most likely a connection issue or Hub downtime => let's warn the user
|
| 324 |
+
raise LocalEntryNotFoundError(
|
| 325 |
+
f"Got: {api_call_error.__class__.__name__}: {api_call_error}"
|
| 326 |
+
"\nAn error happened while trying to locate the files on the Hub and we cannot find the appropriate"
|
| 327 |
+
" snapshot folder for the specified revision on the local disk. Please check your internet connection"
|
| 328 |
+
" and try again."
|
| 329 |
+
) from api_call_error
|
| 330 |
+
|
| 331 |
+
# At this stage, internet connection is up and running
|
| 332 |
+
# => let's download the files!
|
| 333 |
+
assert repo_info.sha is not None, "Repo info returned from server must have a revision sha."
|
| 334 |
+
|
| 335 |
+
# Corner case: on very large repos, the siblings list in `repo_info` might not contain all files.
|
| 336 |
+
# In that case, we need to use the `list_repo_tree` method to prevent caching issues.
|
| 337 |
+
repo_files: Iterable[str] = [f.rfilename for f in repo_info.siblings] if repo_info.siblings is not None else []
|
| 338 |
+
unreliable_nb_files = (
|
| 339 |
+
repo_info.siblings is None or len(repo_info.siblings) == 0 or len(repo_info.siblings) > LARGE_REPO_THRESHOLD
|
| 340 |
+
)
|
| 341 |
+
if unreliable_nb_files:
|
| 342 |
+
logger.info(
|
| 343 |
+
"Number of files in the repo is unreliable. Using `list_repo_tree` to ensure all files are listed."
|
| 344 |
+
)
|
| 345 |
+
repo_files = (
|
| 346 |
+
f.rfilename
|
| 347 |
+
for f in api.list_repo_tree(repo_id=repo_id, recursive=True, revision=revision, repo_type=repo_type)
|
| 348 |
+
if isinstance(f, RepoFile)
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
filtered_repo_files: Iterable[str] = filter_repo_objects(
|
| 352 |
+
items=repo_files,
|
| 353 |
+
allow_patterns=allow_patterns,
|
| 354 |
+
ignore_patterns=ignore_patterns,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
if not unreliable_nb_files:
|
| 358 |
+
filtered_repo_files = list(filtered_repo_files)
|
| 359 |
+
tqdm_desc = f"Fetching {len(filtered_repo_files)} files"
|
| 360 |
+
else:
|
| 361 |
+
tqdm_desc = "Fetching ... files"
|
| 362 |
+
if dry_run:
|
| 363 |
+
tqdm_desc = "[dry-run] " + tqdm_desc
|
| 364 |
+
|
| 365 |
+
commit_hash = repo_info.sha
|
| 366 |
+
snapshot_folder = os.path.join(storage_folder, "snapshots", commit_hash)
|
| 367 |
+
# if passed revision is not identical to commit_hash
|
| 368 |
+
# then revision has to be a branch name or tag name.
|
| 369 |
+
# In that case store a ref.
|
| 370 |
+
if revision != commit_hash:
|
| 371 |
+
ref_path = os.path.join(storage_folder, "refs", revision)
|
| 372 |
+
try:
|
| 373 |
+
os.makedirs(os.path.dirname(ref_path), exist_ok=True)
|
| 374 |
+
with open(ref_path, "w") as f:
|
| 375 |
+
f.write(commit_hash)
|
| 376 |
+
except OSError as e:
|
| 377 |
+
logger.warning(f"Ignored error while writing commit hash to {ref_path}: {e}.")
|
| 378 |
+
|
| 379 |
+
results: List[Union[str, DryRunFileInfo]] = []
|
| 380 |
+
|
| 381 |
+
# User can use its own tqdm class or the default one from `huggingface_hub.utils`
|
| 382 |
+
tqdm_class = tqdm_class or hf_tqdm
|
| 383 |
+
|
| 384 |
+
# Create a progress bar for the bytes downloaded
|
| 385 |
+
# This progress bar is shared across threads/files and gets updated each time we fetch
|
| 386 |
+
# metadata for a file.
|
| 387 |
+
bytes_progress = tqdm_class(
|
| 388 |
+
desc="Downloading (incomplete total...)",
|
| 389 |
+
disable=is_tqdm_disabled(log_level=logger.getEffectiveLevel()),
|
| 390 |
+
total=0,
|
| 391 |
+
initial=0,
|
| 392 |
+
unit="B",
|
| 393 |
+
unit_scale=True,
|
| 394 |
+
name="huggingface_hub.snapshot_download",
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
class _AggregatedTqdm:
|
| 398 |
+
"""Fake tqdm object to aggregate progress into the parent `bytes_progress` bar.
|
| 399 |
+
|
| 400 |
+
In practice the `_AggregatedTqdm` object won't be displayed, it's just used to update
|
| 401 |
+
the `bytes_progress` bar from each thread/file download.
|
| 402 |
+
"""
|
| 403 |
+
|
| 404 |
+
def __init__(self, *args, **kwargs):
|
| 405 |
+
# Adjust the total of the parent progress bar
|
| 406 |
+
total = kwargs.pop("total", None)
|
| 407 |
+
if total is not None:
|
| 408 |
+
bytes_progress.total += total
|
| 409 |
+
bytes_progress.refresh()
|
| 410 |
+
|
| 411 |
+
# Adjust initial of the parent progress bar
|
| 412 |
+
initial = kwargs.pop("initial", 0)
|
| 413 |
+
if initial:
|
| 414 |
+
bytes_progress.update(initial)
|
| 415 |
+
|
| 416 |
+
def __enter__(self):
|
| 417 |
+
return self
|
| 418 |
+
|
| 419 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 420 |
+
pass
|
| 421 |
+
|
| 422 |
+
def update(self, n: Optional[Union[int, float]] = 1) -> None:
|
| 423 |
+
bytes_progress.update(n)
|
| 424 |
+
|
| 425 |
+
# we pass the commit_hash to hf_hub_download
|
| 426 |
+
# so no network call happens if we already
|
| 427 |
+
# have the file locally.
|
| 428 |
+
def _inner_hf_hub_download(repo_file: str) -> None:
|
| 429 |
+
results.append(
|
| 430 |
+
hf_hub_download( # type: ignore
|
| 431 |
+
repo_id,
|
| 432 |
+
filename=repo_file,
|
| 433 |
+
repo_type=repo_type,
|
| 434 |
+
revision=commit_hash,
|
| 435 |
+
endpoint=endpoint,
|
| 436 |
+
cache_dir=cache_dir,
|
| 437 |
+
local_dir=local_dir,
|
| 438 |
+
library_name=library_name,
|
| 439 |
+
library_version=library_version,
|
| 440 |
+
user_agent=user_agent,
|
| 441 |
+
etag_timeout=etag_timeout,
|
| 442 |
+
force_download=force_download,
|
| 443 |
+
token=token,
|
| 444 |
+
headers=headers,
|
| 445 |
+
tqdm_class=_AggregatedTqdm, # type: ignore
|
| 446 |
+
dry_run=dry_run,
|
| 447 |
+
)
|
| 448 |
+
)
|
| 449 |
+
|
| 450 |
+
thread_map(
|
| 451 |
+
_inner_hf_hub_download,
|
| 452 |
+
filtered_repo_files,
|
| 453 |
+
desc=tqdm_desc,
|
| 454 |
+
max_workers=max_workers,
|
| 455 |
+
tqdm_class=tqdm_class,
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
bytes_progress.set_description("Download complete")
|
| 459 |
+
|
| 460 |
+
if dry_run:
|
| 461 |
+
assert all(isinstance(r, DryRunFileInfo) for r in results)
|
| 462 |
+
return results # type: ignore
|
| 463 |
+
|
| 464 |
+
if local_dir is not None:
|
| 465 |
+
return str(os.path.realpath(local_dir))
|
| 466 |
+
return snapshot_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-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 |
+
from dataclasses import dataclass
|
| 16 |
+
from datetime import datetime
|
| 17 |
+
from enum import Enum
|
| 18 |
+
from typing import Literal, Optional
|
| 19 |
+
|
| 20 |
+
from huggingface_hub.utils import parse_datetime
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class SpaceStage(str, Enum):
|
| 24 |
+
"""
|
| 25 |
+
Enumeration of possible stage of a Space on the Hub.
|
| 26 |
+
|
| 27 |
+
Value can be compared to a string:
|
| 28 |
+
```py
|
| 29 |
+
assert SpaceStage.BUILDING == "BUILDING"
|
| 30 |
+
```
|
| 31 |
+
|
| 32 |
+
Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceInfo.ts#L61 (private url).
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
# Copied from moon-landing > server > repo_types > SpaceInfo.ts (private repo)
|
| 36 |
+
NO_APP_FILE = "NO_APP_FILE"
|
| 37 |
+
CONFIG_ERROR = "CONFIG_ERROR"
|
| 38 |
+
BUILDING = "BUILDING"
|
| 39 |
+
BUILD_ERROR = "BUILD_ERROR"
|
| 40 |
+
RUNNING = "RUNNING"
|
| 41 |
+
RUNNING_BUILDING = "RUNNING_BUILDING"
|
| 42 |
+
RUNTIME_ERROR = "RUNTIME_ERROR"
|
| 43 |
+
DELETING = "DELETING"
|
| 44 |
+
STOPPED = "STOPPED"
|
| 45 |
+
PAUSED = "PAUSED"
|
| 46 |
+
APP_STARTING = "APP_STARTING"
|
| 47 |
+
RUNNING_APP_STARTING = "RUNNING_APP_STARTING"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class SpaceHardware(str, Enum):
|
| 51 |
+
"""
|
| 52 |
+
Enumeration of hardwares available to run your Space on the Hub.
|
| 53 |
+
|
| 54 |
+
Value can be compared to a string:
|
| 55 |
+
```py
|
| 56 |
+
assert SpaceHardware.CPU_BASIC == "cpu-basic"
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Taken from https://github.com/huggingface-internal/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts (private url).
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
# CPU
|
| 63 |
+
CPU_BASIC = "cpu-basic"
|
| 64 |
+
CPU_UPGRADE = "cpu-upgrade"
|
| 65 |
+
CPU_XL = "cpu-xl"
|
| 66 |
+
|
| 67 |
+
# ZeroGPU
|
| 68 |
+
ZERO_A10G = "zero-a10g"
|
| 69 |
+
|
| 70 |
+
# GPU
|
| 71 |
+
T4_SMALL = "t4-small"
|
| 72 |
+
T4_MEDIUM = "t4-medium"
|
| 73 |
+
L4X1 = "l4x1"
|
| 74 |
+
L4X4 = "l4x4"
|
| 75 |
+
L40SX1 = "l40sx1"
|
| 76 |
+
L40SX4 = "l40sx4"
|
| 77 |
+
L40SX8 = "l40sx8"
|
| 78 |
+
A10G_SMALL = "a10g-small"
|
| 79 |
+
A10G_LARGE = "a10g-large"
|
| 80 |
+
A10G_LARGEX2 = "a10g-largex2"
|
| 81 |
+
A10G_LARGEX4 = "a10g-largex4"
|
| 82 |
+
A100_LARGE = "a100-large"
|
| 83 |
+
A100x4 = "a100x4"
|
| 84 |
+
A100x8 = "a100x8"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class SpaceStorage(str, Enum):
|
| 88 |
+
"""
|
| 89 |
+
Enumeration of persistent storage available for your Space on the Hub.
|
| 90 |
+
|
| 91 |
+
Value can be compared to a string:
|
| 92 |
+
```py
|
| 93 |
+
assert SpaceStorage.SMALL == "small"
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
Taken from https://github.com/huggingface/moon-landing/blob/main/server/repo_types/SpaceHardwareFlavor.ts#L24 (private url).
|
| 97 |
+
"""
|
| 98 |
+
|
| 99 |
+
SMALL = "small"
|
| 100 |
+
MEDIUM = "medium"
|
| 101 |
+
LARGE = "large"
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
@dataclass
|
| 105 |
+
class SpaceHotReloading:
|
| 106 |
+
status: Literal["created", "canceled"]
|
| 107 |
+
replica_statuses: list[tuple[str, str]] # See _hot_reloading_types.ApiCreateReloadResponse.res.status
|
| 108 |
+
raw: dict
|
| 109 |
+
|
| 110 |
+
def __init__(self, data: dict) -> None:
|
| 111 |
+
self.status = data["status"]
|
| 112 |
+
self.replica_statuses = data["replicaStatuses"]
|
| 113 |
+
self.raw = data
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@dataclass
|
| 117 |
+
class SpaceRuntime:
|
| 118 |
+
"""
|
| 119 |
+
Contains information about the current runtime of a Space.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
stage (`str`):
|
| 123 |
+
Current stage of the space. Example: RUNNING.
|
| 124 |
+
hardware (`str` or `None`):
|
| 125 |
+
Current hardware of the space. Example: "cpu-basic". Can be `None` if Space
|
| 126 |
+
is `BUILDING` for the first time.
|
| 127 |
+
requested_hardware (`str` or `None`):
|
| 128 |
+
Requested hardware. Can be different from `hardware` especially if the request
|
| 129 |
+
has just been made. Example: "t4-medium". Can be `None` if no hardware has
|
| 130 |
+
been requested yet.
|
| 131 |
+
sleep_time (`int` or `None`):
|
| 132 |
+
Number of seconds the Space will be kept alive after the last request. By default (if value is `None`), the
|
| 133 |
+
Space will never go to sleep if it's running on an upgraded hardware, while it will go to sleep after 48
|
| 134 |
+
hours on a free 'cpu-basic' hardware. For more details, see https://huggingface.co/docs/hub/spaces-gpus#sleep-time.
|
| 135 |
+
raw (`dict`):
|
| 136 |
+
Raw response from the server. Contains more information about the Space
|
| 137 |
+
runtime like number of replicas, number of cpu, memory size,...
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
stage: SpaceStage
|
| 141 |
+
hardware: Optional[SpaceHardware]
|
| 142 |
+
requested_hardware: Optional[SpaceHardware]
|
| 143 |
+
sleep_time: Optional[int]
|
| 144 |
+
storage: Optional[SpaceStorage]
|
| 145 |
+
hot_reloading: Optional[SpaceHotReloading]
|
| 146 |
+
raw: dict
|
| 147 |
+
|
| 148 |
+
def __init__(self, data: dict) -> None:
|
| 149 |
+
self.stage = data["stage"]
|
| 150 |
+
self.hardware = data.get("hardware", {}).get("current")
|
| 151 |
+
self.requested_hardware = data.get("hardware", {}).get("requested")
|
| 152 |
+
self.sleep_time = data.get("gcTimeout")
|
| 153 |
+
self.storage = data.get("storage")
|
| 154 |
+
self.hot_reloading = SpaceHotReloading(raw_hr) if (raw_hr := data.get("hotReloading")) is not None else None
|
| 155 |
+
self.raw = data
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
@dataclass
|
| 159 |
+
class SpaceVariable:
|
| 160 |
+
"""
|
| 161 |
+
Contains information about the current variables of a Space.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
key (`str`):
|
| 165 |
+
Variable key. Example: `"MODEL_REPO_ID"`
|
| 166 |
+
value (`str`):
|
| 167 |
+
Variable value. Example: `"the_model_repo_id"`.
|
| 168 |
+
description (`str` or None):
|
| 169 |
+
Description of the variable. Example: `"Model Repo ID of the implemented model"`.
|
| 170 |
+
updatedAt (`datetime` or None):
|
| 171 |
+
datetime of the last update of the variable (if the variable has been updated at least once).
|
| 172 |
+
"""
|
| 173 |
+
|
| 174 |
+
key: str
|
| 175 |
+
value: str
|
| 176 |
+
description: Optional[str]
|
| 177 |
+
updated_at: Optional[datetime]
|
| 178 |
+
|
| 179 |
+
def __init__(self, key: str, values: dict) -> None:
|
| 180 |
+
self.key = key
|
| 181 |
+
self.value = values["value"]
|
| 182 |
+
self.description = values.get("description")
|
| 183 |
+
updated_at = values.get("updatedAt")
|
| 184 |
+
self.updated_at = parse_datetime(updated_at) if updated_at is not None else None
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_tensorboard_logger.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
"""Contains a logger to push training logs to the Hub, using Tensorboard."""
|
| 15 |
+
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Optional, Union
|
| 18 |
+
|
| 19 |
+
from ._commit_scheduler import CommitScheduler
|
| 20 |
+
from .errors import EntryNotFoundError
|
| 21 |
+
from .repocard import ModelCard
|
| 22 |
+
from .utils import experimental
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Depending on user's setup, SummaryWriter can come either from 'tensorboardX'
|
| 26 |
+
# or from 'torch.utils.tensorboard'. Both are compatible so let's try to load
|
| 27 |
+
# from either of them.
|
| 28 |
+
try:
|
| 29 |
+
from tensorboardX import SummaryWriter as _RuntimeSummaryWriter
|
| 30 |
+
|
| 31 |
+
is_summary_writer_available = True
|
| 32 |
+
except ImportError:
|
| 33 |
+
try:
|
| 34 |
+
from torch.utils.tensorboard import SummaryWriter as _RuntimeSummaryWriter
|
| 35 |
+
|
| 36 |
+
is_summary_writer_available = True
|
| 37 |
+
except ImportError:
|
| 38 |
+
# Dummy class to avoid failing at import. Will raise on instance creation.
|
| 39 |
+
class _DummySummaryWriter:
|
| 40 |
+
pass
|
| 41 |
+
|
| 42 |
+
_RuntimeSummaryWriter = _DummySummaryWriter # type: ignore[assignment]
|
| 43 |
+
is_summary_writer_available = False
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class HFSummaryWriter(_RuntimeSummaryWriter):
|
| 47 |
+
"""
|
| 48 |
+
Wrapper around the tensorboard's `SummaryWriter` to push training logs to the Hub.
|
| 49 |
+
|
| 50 |
+
Data is logged locally and then pushed to the Hub asynchronously. Pushing data to the Hub is done in a separate
|
| 51 |
+
thread to avoid blocking the training script. In particular, if the upload fails for any reason (e.g. a connection
|
| 52 |
+
issue), the main script will not be interrupted. Data is automatically pushed to the Hub every `commit_every`
|
| 53 |
+
minutes (default to every 5 minutes).
|
| 54 |
+
|
| 55 |
+
> [!WARNING]
|
| 56 |
+
> `HFSummaryWriter` is experimental. Its API is subject to change in the future without prior notice.
|
| 57 |
+
|
| 58 |
+
Args:
|
| 59 |
+
repo_id (`str`):
|
| 60 |
+
The id of the repo to which the logs will be pushed.
|
| 61 |
+
logdir (`str`, *optional*):
|
| 62 |
+
The directory where the logs will be written. If not specified, a local directory will be created by the
|
| 63 |
+
underlying `SummaryWriter` object.
|
| 64 |
+
commit_every (`int` or `float`, *optional*):
|
| 65 |
+
The frequency (in minutes) at which the logs will be pushed to the Hub. Defaults to 5 minutes.
|
| 66 |
+
squash_history (`bool`, *optional*):
|
| 67 |
+
Whether to squash the history of the repo after each commit. Defaults to `False`. Squashing commits is
|
| 68 |
+
useful to avoid degraded performances on the repo when it grows too large.
|
| 69 |
+
repo_type (`str`, *optional*):
|
| 70 |
+
The type of the repo to which the logs will be pushed. Defaults to "model".
|
| 71 |
+
repo_revision (`str`, *optional*):
|
| 72 |
+
The revision of the repo to which the logs will be pushed. Defaults to "main".
|
| 73 |
+
repo_private (`bool`, *optional*):
|
| 74 |
+
Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
|
| 75 |
+
path_in_repo (`str`, *optional*):
|
| 76 |
+
The path to the folder in the repo where the logs will be pushed. Defaults to "tensorboard/".
|
| 77 |
+
repo_allow_patterns (`list[str]` or `str`, *optional*):
|
| 78 |
+
A list of patterns to include in the upload. Defaults to `"*.tfevents.*"`. Check out the
|
| 79 |
+
[upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
|
| 80 |
+
repo_ignore_patterns (`list[str]` or `str`, *optional*):
|
| 81 |
+
A list of patterns to exclude in the upload. Check out the
|
| 82 |
+
[upload guide](https://huggingface.co/docs/huggingface_hub/guides/upload#upload-a-folder) for more details.
|
| 83 |
+
token (`str`, *optional*):
|
| 84 |
+
Authentication token. Will default to the stored token. See https://huggingface.co/settings/token for more
|
| 85 |
+
details
|
| 86 |
+
kwargs:
|
| 87 |
+
Additional keyword arguments passed to `SummaryWriter`.
|
| 88 |
+
|
| 89 |
+
Examples:
|
| 90 |
+
```diff
|
| 91 |
+
# Taken from https://pytorch.org/docs/stable/tensorboard.html
|
| 92 |
+
- from torch.utils.tensorboard import SummaryWriter
|
| 93 |
+
+ from huggingface_hub import HFSummaryWriter
|
| 94 |
+
|
| 95 |
+
import numpy as np
|
| 96 |
+
|
| 97 |
+
- writer = SummaryWriter()
|
| 98 |
+
+ writer = HFSummaryWriter(repo_id="username/my-trained-model")
|
| 99 |
+
|
| 100 |
+
for n_iter in range(100):
|
| 101 |
+
writer.add_scalar('Loss/train', np.random.random(), n_iter)
|
| 102 |
+
writer.add_scalar('Loss/test', np.random.random(), n_iter)
|
| 103 |
+
writer.add_scalar('Accuracy/train', np.random.random(), n_iter)
|
| 104 |
+
writer.add_scalar('Accuracy/test', np.random.random(), n_iter)
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
```py
|
| 108 |
+
>>> from huggingface_hub import HFSummaryWriter
|
| 109 |
+
|
| 110 |
+
# Logs are automatically pushed every 15 minutes (5 by default) + when exiting the context manager
|
| 111 |
+
>>> with HFSummaryWriter(repo_id="test_hf_logger", commit_every=15) as logger:
|
| 112 |
+
... logger.add_scalar("a", 1)
|
| 113 |
+
... logger.add_scalar("b", 2)
|
| 114 |
+
```
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
@experimental
|
| 118 |
+
def __new__(cls, *args, **kwargs) -> "HFSummaryWriter":
|
| 119 |
+
if not is_summary_writer_available:
|
| 120 |
+
raise ImportError(
|
| 121 |
+
"You must have `tensorboard` installed to use `HFSummaryWriter`. Please run `pip install --upgrade"
|
| 122 |
+
" tensorboardX` first."
|
| 123 |
+
)
|
| 124 |
+
return super().__new__(cls)
|
| 125 |
+
|
| 126 |
+
def __init__(
|
| 127 |
+
self,
|
| 128 |
+
repo_id: str,
|
| 129 |
+
*,
|
| 130 |
+
logdir: Optional[str] = None,
|
| 131 |
+
commit_every: Union[int, float] = 5,
|
| 132 |
+
squash_history: bool = False,
|
| 133 |
+
repo_type: Optional[str] = None,
|
| 134 |
+
repo_revision: Optional[str] = None,
|
| 135 |
+
repo_private: Optional[bool] = None,
|
| 136 |
+
path_in_repo: Optional[str] = "tensorboard",
|
| 137 |
+
repo_allow_patterns: Optional[Union[list[str], str]] = "*.tfevents.*",
|
| 138 |
+
repo_ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 139 |
+
token: Optional[str] = None,
|
| 140 |
+
**kwargs,
|
| 141 |
+
):
|
| 142 |
+
# Initialize SummaryWriter
|
| 143 |
+
super().__init__(logdir=logdir, **kwargs)
|
| 144 |
+
|
| 145 |
+
# Check logdir has been correctly initialized and fail early otherwise. In practice, SummaryWriter takes care of it.
|
| 146 |
+
if not isinstance(self.logdir, str):
|
| 147 |
+
raise ValueError(f"`self.logdir` must be a string. Got '{self.logdir}' of type {type(self.logdir)}.")
|
| 148 |
+
|
| 149 |
+
# Append logdir name to `path_in_repo`
|
| 150 |
+
if path_in_repo is None or path_in_repo == "":
|
| 151 |
+
path_in_repo = Path(self.logdir).name
|
| 152 |
+
else:
|
| 153 |
+
path_in_repo = path_in_repo.strip("/") + "/" + Path(self.logdir).name
|
| 154 |
+
|
| 155 |
+
# Initialize scheduler
|
| 156 |
+
self.scheduler = CommitScheduler(
|
| 157 |
+
folder_path=self.logdir,
|
| 158 |
+
path_in_repo=path_in_repo,
|
| 159 |
+
repo_id=repo_id,
|
| 160 |
+
repo_type=repo_type,
|
| 161 |
+
revision=repo_revision,
|
| 162 |
+
private=repo_private,
|
| 163 |
+
token=token,
|
| 164 |
+
allow_patterns=repo_allow_patterns,
|
| 165 |
+
ignore_patterns=repo_ignore_patterns,
|
| 166 |
+
every=commit_every,
|
| 167 |
+
squash_history=squash_history,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# Exposing some high-level info at root level
|
| 171 |
+
self.repo_id = self.scheduler.repo_id
|
| 172 |
+
self.repo_type = self.scheduler.repo_type
|
| 173 |
+
self.repo_revision = self.scheduler.revision
|
| 174 |
+
|
| 175 |
+
# Add `hf-summary-writer` tag to the model card metadata
|
| 176 |
+
try:
|
| 177 |
+
card = ModelCard.load(repo_id_or_path=self.repo_id, repo_type=self.repo_type)
|
| 178 |
+
except EntryNotFoundError:
|
| 179 |
+
card = ModelCard("")
|
| 180 |
+
tags = card.data.get("tags", [])
|
| 181 |
+
if "hf-summary-writer" not in tags:
|
| 182 |
+
tags.append("hf-summary-writer")
|
| 183 |
+
card.data["tags"] = tags
|
| 184 |
+
card.push_to_hub(repo_id=self.repo_id, repo_type=self.repo_type)
|
| 185 |
+
|
| 186 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 187 |
+
"""Push to hub in a non-blocking way when exiting the logger's context manager."""
|
| 188 |
+
super().__exit__(exc_type, exc_val, exc_tb)
|
| 189 |
+
future = self.scheduler.trigger()
|
| 190 |
+
future.result()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_upload_large_folder.py
ADDED
|
@@ -0,0 +1,765 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, Any, Optional, Union
|
| 28 |
+
from urllib.parse import quote
|
| 29 |
+
|
| 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, _format_size, filter_repo_objects, tqdm
|
| 34 |
+
from .utils._runtime import is_xet_available
|
| 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_FILES_FETCH_UPLOAD_MODE = 100
|
| 45 |
+
COMMIT_SIZE_SCALE: list[int] = [20, 50, 75, 100, 125, 200, 250, 400, 600, 1000]
|
| 46 |
+
|
| 47 |
+
UPLOAD_BATCH_SIZE_XET = 256 # Max 256 files per upload batch for XET-enabled repos
|
| 48 |
+
UPLOAD_BATCH_SIZE_LFS = 1 # Otherwise, batches of 1 for regular LFS upload
|
| 49 |
+
|
| 50 |
+
# Repository limits (from https://huggingface.co/docs/hub/repositories-recommendations)
|
| 51 |
+
MAX_FILES_PER_REPO = 100_000 # Recommended maximum number of files per repository
|
| 52 |
+
MAX_FILES_PER_FOLDER = 10_000 # Recommended maximum number of files per folder
|
| 53 |
+
MAX_FILE_SIZE_GB = 200 # Recommended maximum for individual file size (split larger files)
|
| 54 |
+
RECOMMENDED_FILE_SIZE_GB = 20 # Recommended maximum for individual file size
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _validate_upload_limits(paths_list: list[LocalUploadFilePaths]) -> None:
|
| 58 |
+
"""
|
| 59 |
+
Validate upload against repository limits and warn about potential issues.
|
| 60 |
+
|
| 61 |
+
Args:
|
| 62 |
+
paths_list: List of file paths to be uploaded
|
| 63 |
+
|
| 64 |
+
Warns about:
|
| 65 |
+
- Too many files in the repository (>100k)
|
| 66 |
+
- Too many entries (files or subdirectories) in a single folder (>10k)
|
| 67 |
+
- Files exceeding size limits (>20GB recommended, >200GB maximum)
|
| 68 |
+
"""
|
| 69 |
+
logger.info("Running validation checks on files to upload...")
|
| 70 |
+
|
| 71 |
+
# Check 1: Total file count
|
| 72 |
+
if len(paths_list) > MAX_FILES_PER_REPO:
|
| 73 |
+
logger.warning(
|
| 74 |
+
f"You are about to upload {len(paths_list):,} files. "
|
| 75 |
+
f"This exceeds the recommended limit of {MAX_FILES_PER_REPO:,} files per repository.\n"
|
| 76 |
+
f"Consider:\n"
|
| 77 |
+
f" - Splitting your data into multiple repositories\n"
|
| 78 |
+
f" - Using fewer, larger files (e.g., parquet files)\n"
|
| 79 |
+
f" - See: https://huggingface.co/docs/hub/repositories-recommendations"
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# Check 2: Files and subdirectories per folder
|
| 83 |
+
# Track immediate children (files and subdirs) for each folder
|
| 84 |
+
from collections import defaultdict
|
| 85 |
+
|
| 86 |
+
entries_per_folder: dict[str, Any] = defaultdict(lambda: {"files": 0, "subdirs": set()})
|
| 87 |
+
|
| 88 |
+
for paths in paths_list:
|
| 89 |
+
path = Path(paths.path_in_repo)
|
| 90 |
+
parts = path.parts
|
| 91 |
+
|
| 92 |
+
# Count this file in its immediate parent directory
|
| 93 |
+
parent = str(path.parent) if str(path.parent) != "." else "."
|
| 94 |
+
entries_per_folder[parent]["files"] += 1
|
| 95 |
+
|
| 96 |
+
# Track immediate subdirectories for each parent folder
|
| 97 |
+
# Walk through the path components to track parent-child relationships
|
| 98 |
+
for i, child in enumerate(parts[:-1]):
|
| 99 |
+
parent = "." if i == 0 else "/".join(parts[:i])
|
| 100 |
+
entries_per_folder[parent]["subdirs"].add(child)
|
| 101 |
+
|
| 102 |
+
# Check limits for each folder
|
| 103 |
+
for folder, data in entries_per_folder.items():
|
| 104 |
+
file_count = data["files"]
|
| 105 |
+
subdir_count = len(data["subdirs"])
|
| 106 |
+
total_entries = file_count + subdir_count
|
| 107 |
+
|
| 108 |
+
if total_entries > MAX_FILES_PER_FOLDER:
|
| 109 |
+
folder_display = "root" if folder == "." else folder
|
| 110 |
+
logger.warning(
|
| 111 |
+
f"Folder '{folder_display}' contains {total_entries:,} entries "
|
| 112 |
+
f"({file_count:,} files and {subdir_count:,} subdirectories). "
|
| 113 |
+
f"This exceeds the recommended {MAX_FILES_PER_FOLDER:,} entries per folder.\n"
|
| 114 |
+
"Consider reorganising into sub-folders."
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# Check 3: File sizes
|
| 118 |
+
large_files = []
|
| 119 |
+
very_large_files = []
|
| 120 |
+
|
| 121 |
+
for paths in paths_list:
|
| 122 |
+
size = paths.file_path.stat().st_size
|
| 123 |
+
size_gb = size / 1_000_000_000 # Use decimal GB as per Hub limits
|
| 124 |
+
|
| 125 |
+
if size_gb > MAX_FILE_SIZE_GB:
|
| 126 |
+
very_large_files.append((paths.path_in_repo, size_gb))
|
| 127 |
+
elif size_gb > RECOMMENDED_FILE_SIZE_GB:
|
| 128 |
+
large_files.append((paths.path_in_repo, size_gb))
|
| 129 |
+
|
| 130 |
+
# Warn about very large files (>200GB)
|
| 131 |
+
if very_large_files:
|
| 132 |
+
files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in very_large_files[:5])
|
| 133 |
+
more_str = f"\n ... and {len(very_large_files) - 5} more files" if len(very_large_files) > 5 else ""
|
| 134 |
+
logger.warning(
|
| 135 |
+
f"Found {len(very_large_files)} files exceeding the {MAX_FILE_SIZE_GB}GB recommended maximum:\n"
|
| 136 |
+
f" - {files_str}{more_str}\n"
|
| 137 |
+
f"Consider splitting these files into smaller chunks."
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
# Warn about large files (>20GB)
|
| 141 |
+
if large_files:
|
| 142 |
+
files_str = "\n - ".join(f"{path}: {size:.1f}GB" for path, size in large_files[:5])
|
| 143 |
+
more_str = f"\n ... and {len(large_files) - 5} more files" if len(large_files) > 5 else ""
|
| 144 |
+
logger.warning(
|
| 145 |
+
f"Found {len(large_files)} files larger than {RECOMMENDED_FILE_SIZE_GB}GB (recommended limit):\n"
|
| 146 |
+
f" - {files_str}{more_str}\n"
|
| 147 |
+
f"Large files may slow down loading and processing."
|
| 148 |
+
)
|
| 149 |
+
|
| 150 |
+
logger.info("Validation checks complete.")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def upload_large_folder_internal(
|
| 154 |
+
api: "HfApi",
|
| 155 |
+
repo_id: str,
|
| 156 |
+
folder_path: Union[str, Path],
|
| 157 |
+
*,
|
| 158 |
+
repo_type: str, # Repo type is required!
|
| 159 |
+
revision: Optional[str] = None,
|
| 160 |
+
private: Optional[bool] = None,
|
| 161 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 162 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 163 |
+
num_workers: Optional[int] = None,
|
| 164 |
+
print_report: bool = True,
|
| 165 |
+
print_report_every: int = 60,
|
| 166 |
+
):
|
| 167 |
+
"""Upload a large folder to the Hub in the most resilient way possible.
|
| 168 |
+
|
| 169 |
+
See [`HfApi.upload_large_folder`] for the full documentation.
|
| 170 |
+
"""
|
| 171 |
+
# 1. Check args and setup
|
| 172 |
+
if repo_type is None:
|
| 173 |
+
raise ValueError(
|
| 174 |
+
"For large uploads, `repo_type` is explicitly required. Please set it to `model`, `dataset` or `space`."
|
| 175 |
+
" If you are using the CLI, pass it as `--repo-type=model`."
|
| 176 |
+
)
|
| 177 |
+
if repo_type not in REPO_TYPES:
|
| 178 |
+
raise ValueError(f"Invalid repo type, must be one of {REPO_TYPES}")
|
| 179 |
+
if revision is None:
|
| 180 |
+
revision = DEFAULT_REVISION
|
| 181 |
+
|
| 182 |
+
folder_path = Path(folder_path).expanduser().resolve()
|
| 183 |
+
if not folder_path.is_dir():
|
| 184 |
+
raise ValueError(f"Provided path: '{folder_path}' is not a directory")
|
| 185 |
+
|
| 186 |
+
if ignore_patterns is None:
|
| 187 |
+
ignore_patterns = []
|
| 188 |
+
elif isinstance(ignore_patterns, str):
|
| 189 |
+
ignore_patterns = [ignore_patterns]
|
| 190 |
+
ignore_patterns += DEFAULT_IGNORE_PATTERNS
|
| 191 |
+
|
| 192 |
+
if num_workers is None:
|
| 193 |
+
nb_cores = os.cpu_count() or 1
|
| 194 |
+
num_workers = max(nb_cores // 2, 1) # Use at most half of cpu cores
|
| 195 |
+
|
| 196 |
+
# 2. Create repo if missing
|
| 197 |
+
repo_url = api.create_repo(repo_id=repo_id, repo_type=repo_type, private=private, exist_ok=True)
|
| 198 |
+
logger.info(f"Repo created: {repo_url}")
|
| 199 |
+
repo_id = repo_url.repo_id
|
| 200 |
+
|
| 201 |
+
# Warn on too many commits
|
| 202 |
+
try:
|
| 203 |
+
commits = api.list_repo_commits(repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 204 |
+
commit_count = len(commits)
|
| 205 |
+
if commit_count > 500:
|
| 206 |
+
logger.warning(
|
| 207 |
+
f"\n{'=' * 80}\n"
|
| 208 |
+
f"WARNING: This repository has {commit_count} commits.\n"
|
| 209 |
+
f"Repositories with a large number of commits can experience performance issues.\n"
|
| 210 |
+
f"\n"
|
| 211 |
+
f"Consider squashing your commit history using `super_squash_history()`.\n"
|
| 212 |
+
"To do so, you need to stop this process, run the snippet below and restart the upload command."
|
| 213 |
+
f" from huggingface_hub import super_squash_history\n"
|
| 214 |
+
f" super_squash_history(repo_id='{repo_id}', repo_type='{repo_type}')\n"
|
| 215 |
+
f"\n"
|
| 216 |
+
f"Note: This is a non-revertible operation. See the documentation for more details:\n"
|
| 217 |
+
f"https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_api#huggingface_hub.HfApi.super_squash_history\n"
|
| 218 |
+
f"{'=' * 80}\n"
|
| 219 |
+
)
|
| 220 |
+
except Exception as e:
|
| 221 |
+
# Don't fail the upload if we can't check commit count
|
| 222 |
+
logger.debug(f"Could not check commit count: {e}")
|
| 223 |
+
|
| 224 |
+
# 2.1 Check if xet is enabled to set batch file upload size
|
| 225 |
+
upload_batch_size = UPLOAD_BATCH_SIZE_XET if is_xet_available() else UPLOAD_BATCH_SIZE_LFS
|
| 226 |
+
|
| 227 |
+
# 3. List files to upload
|
| 228 |
+
filtered_paths_list = filter_repo_objects(
|
| 229 |
+
(path.relative_to(folder_path).as_posix() for path in folder_path.glob("**/*") if path.is_file()),
|
| 230 |
+
allow_patterns=allow_patterns,
|
| 231 |
+
ignore_patterns=ignore_patterns,
|
| 232 |
+
)
|
| 233 |
+
paths_list = [get_local_upload_paths(folder_path, relpath) for relpath in filtered_paths_list]
|
| 234 |
+
logger.info(f"Found {len(paths_list)} candidate files to upload")
|
| 235 |
+
|
| 236 |
+
# Validate upload against repository limits
|
| 237 |
+
_validate_upload_limits(paths_list)
|
| 238 |
+
|
| 239 |
+
logger.info("Starting upload...")
|
| 240 |
+
|
| 241 |
+
# Read metadata for each file
|
| 242 |
+
items = [
|
| 243 |
+
(paths, read_upload_metadata(folder_path, paths.path_in_repo))
|
| 244 |
+
for paths in tqdm(paths_list, desc="Recovering from metadata files")
|
| 245 |
+
]
|
| 246 |
+
|
| 247 |
+
# 4. Start workers
|
| 248 |
+
status = LargeUploadStatus(items, upload_batch_size)
|
| 249 |
+
threads = [
|
| 250 |
+
threading.Thread(
|
| 251 |
+
target=_worker_job,
|
| 252 |
+
kwargs={
|
| 253 |
+
"status": status,
|
| 254 |
+
"api": api,
|
| 255 |
+
"repo_id": repo_id,
|
| 256 |
+
"repo_type": repo_type,
|
| 257 |
+
"revision": revision,
|
| 258 |
+
},
|
| 259 |
+
)
|
| 260 |
+
for _ in range(num_workers)
|
| 261 |
+
]
|
| 262 |
+
|
| 263 |
+
for thread in threads:
|
| 264 |
+
thread.start()
|
| 265 |
+
|
| 266 |
+
# 5. Print regular reports
|
| 267 |
+
if print_report:
|
| 268 |
+
print("\n\n" + status.current_report())
|
| 269 |
+
last_report_ts = time.time()
|
| 270 |
+
while True:
|
| 271 |
+
time.sleep(1)
|
| 272 |
+
if time.time() - last_report_ts >= print_report_every:
|
| 273 |
+
if print_report:
|
| 274 |
+
_print_overwrite(status.current_report())
|
| 275 |
+
last_report_ts = time.time()
|
| 276 |
+
if status.is_done():
|
| 277 |
+
logging.info("Is done: exiting main loop")
|
| 278 |
+
break
|
| 279 |
+
|
| 280 |
+
for thread in threads:
|
| 281 |
+
thread.join()
|
| 282 |
+
|
| 283 |
+
logger.info(status.current_report())
|
| 284 |
+
logging.info("Upload is complete!")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
####################
|
| 288 |
+
# Logic to manage workers and synchronize tasks
|
| 289 |
+
####################
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
class WorkerJob(enum.Enum):
|
| 293 |
+
SHA256 = enum.auto()
|
| 294 |
+
GET_UPLOAD_MODE = enum.auto()
|
| 295 |
+
PREUPLOAD_LFS = enum.auto()
|
| 296 |
+
COMMIT = enum.auto()
|
| 297 |
+
WAIT = enum.auto() # if no tasks are available but we don't want to exit
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
JOB_ITEM_T = tuple[LocalUploadFilePaths, LocalUploadFileMetadata]
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
class LargeUploadStatus:
|
| 304 |
+
"""Contains information, queues and tasks for a large upload process."""
|
| 305 |
+
|
| 306 |
+
def __init__(self, items: list[JOB_ITEM_T], upload_batch_size: int = 1):
|
| 307 |
+
self.items = items
|
| 308 |
+
self.queue_sha256: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 309 |
+
self.queue_get_upload_mode: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 310 |
+
self.queue_preupload_lfs: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 311 |
+
self.queue_commit: "queue.Queue[JOB_ITEM_T]" = queue.Queue()
|
| 312 |
+
self.lock = Lock()
|
| 313 |
+
|
| 314 |
+
self.nb_workers_sha256: int = 0
|
| 315 |
+
self.nb_workers_get_upload_mode: int = 0
|
| 316 |
+
self.nb_workers_preupload_lfs: int = 0
|
| 317 |
+
self.upload_batch_size: int = upload_batch_size
|
| 318 |
+
self.nb_workers_commit: int = 0
|
| 319 |
+
self.nb_workers_waiting: int = 0
|
| 320 |
+
self.last_commit_attempt: Optional[float] = None
|
| 321 |
+
|
| 322 |
+
self._started_at = datetime.now()
|
| 323 |
+
self._chunk_idx: int = 1
|
| 324 |
+
self._chunk_lock: Lock = Lock()
|
| 325 |
+
|
| 326 |
+
# Setup queues
|
| 327 |
+
for item in self.items:
|
| 328 |
+
paths, metadata = item
|
| 329 |
+
if metadata.sha256 is None:
|
| 330 |
+
self.queue_sha256.put(item)
|
| 331 |
+
elif metadata.upload_mode is None:
|
| 332 |
+
self.queue_get_upload_mode.put(item)
|
| 333 |
+
elif metadata.upload_mode == "lfs" and not metadata.is_uploaded:
|
| 334 |
+
self.queue_preupload_lfs.put(item)
|
| 335 |
+
elif not metadata.is_committed:
|
| 336 |
+
self.queue_commit.put(item)
|
| 337 |
+
else:
|
| 338 |
+
logger.debug(f"Skipping file {paths.path_in_repo} (already uploaded and committed)")
|
| 339 |
+
|
| 340 |
+
def target_chunk(self) -> int:
|
| 341 |
+
with self._chunk_lock:
|
| 342 |
+
return COMMIT_SIZE_SCALE[self._chunk_idx]
|
| 343 |
+
|
| 344 |
+
def update_chunk(self, success: bool, nb_items: int, duration: float) -> None:
|
| 345 |
+
with self._chunk_lock:
|
| 346 |
+
if not success:
|
| 347 |
+
logger.warning(f"Failed to commit {nb_items} files at once. Will retry with less files in next batch.")
|
| 348 |
+
self._chunk_idx -= 1
|
| 349 |
+
elif nb_items >= COMMIT_SIZE_SCALE[self._chunk_idx] and duration < 40:
|
| 350 |
+
logger.info(f"Successfully committed {nb_items} at once. Increasing the limit for next batch.")
|
| 351 |
+
self._chunk_idx += 1
|
| 352 |
+
|
| 353 |
+
self._chunk_idx = max(0, min(self._chunk_idx, len(COMMIT_SIZE_SCALE) - 1))
|
| 354 |
+
|
| 355 |
+
def current_report(self) -> str:
|
| 356 |
+
"""Generate a report of the current status of the large upload."""
|
| 357 |
+
nb_hashed = 0
|
| 358 |
+
size_hashed = 0
|
| 359 |
+
nb_preuploaded = 0
|
| 360 |
+
nb_lfs = 0
|
| 361 |
+
nb_lfs_unsure = 0
|
| 362 |
+
size_preuploaded = 0
|
| 363 |
+
nb_committed = 0
|
| 364 |
+
size_committed = 0
|
| 365 |
+
total_size = 0
|
| 366 |
+
ignored_files = 0
|
| 367 |
+
total_files = 0
|
| 368 |
+
|
| 369 |
+
with self.lock:
|
| 370 |
+
for _, metadata in self.items:
|
| 371 |
+
if metadata.should_ignore:
|
| 372 |
+
ignored_files += 1
|
| 373 |
+
continue
|
| 374 |
+
total_size += metadata.size
|
| 375 |
+
total_files += 1
|
| 376 |
+
if metadata.sha256 is not None:
|
| 377 |
+
nb_hashed += 1
|
| 378 |
+
size_hashed += metadata.size
|
| 379 |
+
if metadata.upload_mode == "lfs":
|
| 380 |
+
nb_lfs += 1
|
| 381 |
+
if metadata.upload_mode is None:
|
| 382 |
+
nb_lfs_unsure += 1
|
| 383 |
+
if metadata.is_uploaded:
|
| 384 |
+
nb_preuploaded += 1
|
| 385 |
+
size_preuploaded += metadata.size
|
| 386 |
+
if metadata.is_committed:
|
| 387 |
+
nb_committed += 1
|
| 388 |
+
size_committed += metadata.size
|
| 389 |
+
total_size_str = _format_size(total_size)
|
| 390 |
+
|
| 391 |
+
now = datetime.now()
|
| 392 |
+
now_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
| 393 |
+
elapsed = now - self._started_at
|
| 394 |
+
elapsed_str = str(elapsed).split(".")[0] # remove milliseconds
|
| 395 |
+
|
| 396 |
+
message = "\n" + "-" * 10
|
| 397 |
+
message += f" {now_str} ({elapsed_str}) "
|
| 398 |
+
message += "-" * 10 + "\n"
|
| 399 |
+
|
| 400 |
+
message += "Files: "
|
| 401 |
+
message += f"hashed {nb_hashed}/{total_files} ({_format_size(size_hashed)}/{total_size_str}) | "
|
| 402 |
+
message += f"pre-uploaded: {nb_preuploaded}/{nb_lfs} ({_format_size(size_preuploaded)}/{total_size_str})"
|
| 403 |
+
if nb_lfs_unsure > 0:
|
| 404 |
+
message += f" (+{nb_lfs_unsure} unsure)"
|
| 405 |
+
message += f" | committed: {nb_committed}/{total_files} ({_format_size(size_committed)}/{total_size_str})"
|
| 406 |
+
message += f" | ignored: {ignored_files}\n"
|
| 407 |
+
|
| 408 |
+
message += "Workers: "
|
| 409 |
+
message += f"hashing: {self.nb_workers_sha256} | "
|
| 410 |
+
message += f"get upload mode: {self.nb_workers_get_upload_mode} | "
|
| 411 |
+
message += f"pre-uploading: {self.nb_workers_preupload_lfs} | "
|
| 412 |
+
message += f"committing: {self.nb_workers_commit} | "
|
| 413 |
+
message += f"waiting: {self.nb_workers_waiting}\n"
|
| 414 |
+
message += "-" * 51
|
| 415 |
+
|
| 416 |
+
return message
|
| 417 |
+
|
| 418 |
+
def is_done(self) -> bool:
|
| 419 |
+
with self.lock:
|
| 420 |
+
return all(metadata.is_committed or metadata.should_ignore for _, metadata in self.items)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def _worker_job(
|
| 424 |
+
status: LargeUploadStatus,
|
| 425 |
+
api: "HfApi",
|
| 426 |
+
repo_id: str,
|
| 427 |
+
repo_type: str,
|
| 428 |
+
revision: str,
|
| 429 |
+
):
|
| 430 |
+
"""
|
| 431 |
+
Main process for a worker. The worker will perform tasks based on the priority list until all files are uploaded
|
| 432 |
+
and committed. If no tasks are available, the worker will wait for 10 seconds before checking again.
|
| 433 |
+
|
| 434 |
+
If a task fails for any reason, the item(s) are put back in the queue for another worker to pick up.
|
| 435 |
+
|
| 436 |
+
Read `upload_large_folder` docstring for more information on how tasks are prioritized.
|
| 437 |
+
"""
|
| 438 |
+
while True:
|
| 439 |
+
next_job: Optional[tuple[WorkerJob, list[JOB_ITEM_T]]] = None
|
| 440 |
+
|
| 441 |
+
# Determine next task
|
| 442 |
+
next_job = _determine_next_job(status)
|
| 443 |
+
if next_job is None:
|
| 444 |
+
return
|
| 445 |
+
job, items = next_job
|
| 446 |
+
|
| 447 |
+
# Perform task
|
| 448 |
+
if job == WorkerJob.SHA256:
|
| 449 |
+
item = items[0] # single item
|
| 450 |
+
try:
|
| 451 |
+
_compute_sha256(item)
|
| 452 |
+
status.queue_get_upload_mode.put(item)
|
| 453 |
+
except KeyboardInterrupt:
|
| 454 |
+
raise
|
| 455 |
+
except Exception as e:
|
| 456 |
+
logger.error(f"Failed to compute sha256: {e}")
|
| 457 |
+
traceback.format_exc()
|
| 458 |
+
status.queue_sha256.put(item)
|
| 459 |
+
|
| 460 |
+
with status.lock:
|
| 461 |
+
status.nb_workers_sha256 -= 1
|
| 462 |
+
|
| 463 |
+
elif job == WorkerJob.GET_UPLOAD_MODE:
|
| 464 |
+
try:
|
| 465 |
+
_get_upload_mode(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 466 |
+
except KeyboardInterrupt:
|
| 467 |
+
raise
|
| 468 |
+
except Exception as e:
|
| 469 |
+
logger.error(f"Failed to get upload mode: {e}")
|
| 470 |
+
traceback.format_exc()
|
| 471 |
+
|
| 472 |
+
# Items are either:
|
| 473 |
+
# - dropped (if should_ignore)
|
| 474 |
+
# - put in LFS queue (if LFS)
|
| 475 |
+
# - put in commit queue (if regular)
|
| 476 |
+
# - or put back (if error occurred).
|
| 477 |
+
for item in items:
|
| 478 |
+
_, metadata = item
|
| 479 |
+
if metadata.should_ignore:
|
| 480 |
+
continue
|
| 481 |
+
if metadata.upload_mode == "lfs":
|
| 482 |
+
status.queue_preupload_lfs.put(item)
|
| 483 |
+
elif metadata.upload_mode == "regular":
|
| 484 |
+
status.queue_commit.put(item)
|
| 485 |
+
else:
|
| 486 |
+
status.queue_get_upload_mode.put(item)
|
| 487 |
+
|
| 488 |
+
with status.lock:
|
| 489 |
+
status.nb_workers_get_upload_mode -= 1
|
| 490 |
+
|
| 491 |
+
elif job == WorkerJob.PREUPLOAD_LFS:
|
| 492 |
+
try:
|
| 493 |
+
_preupload_lfs(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 494 |
+
for item in items:
|
| 495 |
+
status.queue_commit.put(item)
|
| 496 |
+
except KeyboardInterrupt:
|
| 497 |
+
raise
|
| 498 |
+
except Exception as e:
|
| 499 |
+
logger.error(f"Failed to preupload LFS: {e}")
|
| 500 |
+
traceback.format_exc()
|
| 501 |
+
for item in items:
|
| 502 |
+
status.queue_preupload_lfs.put(item)
|
| 503 |
+
|
| 504 |
+
with status.lock:
|
| 505 |
+
status.nb_workers_preupload_lfs -= 1
|
| 506 |
+
|
| 507 |
+
elif job == WorkerJob.COMMIT:
|
| 508 |
+
start_ts = time.time()
|
| 509 |
+
success = True
|
| 510 |
+
try:
|
| 511 |
+
_commit(items, api=api, repo_id=repo_id, repo_type=repo_type, revision=revision)
|
| 512 |
+
except KeyboardInterrupt:
|
| 513 |
+
raise
|
| 514 |
+
except Exception as e:
|
| 515 |
+
logger.error(f"Failed to commit: {e}")
|
| 516 |
+
traceback.format_exc()
|
| 517 |
+
for item in items:
|
| 518 |
+
status.queue_commit.put(item)
|
| 519 |
+
success = False
|
| 520 |
+
duration = time.time() - start_ts
|
| 521 |
+
status.update_chunk(success, len(items), duration)
|
| 522 |
+
with status.lock:
|
| 523 |
+
status.last_commit_attempt = time.time()
|
| 524 |
+
status.nb_workers_commit -= 1
|
| 525 |
+
|
| 526 |
+
elif job == WorkerJob.WAIT:
|
| 527 |
+
time.sleep(WAITING_TIME_IF_NO_TASKS)
|
| 528 |
+
with status.lock:
|
| 529 |
+
status.nb_workers_waiting -= 1
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def _determine_next_job(status: LargeUploadStatus) -> Optional[tuple[WorkerJob, list[JOB_ITEM_T]]]:
|
| 533 |
+
with status.lock:
|
| 534 |
+
# 1. Commit if more than 5 minutes since last commit attempt (and at least 1 file)
|
| 535 |
+
if (
|
| 536 |
+
status.nb_workers_commit == 0
|
| 537 |
+
and status.queue_commit.qsize() > 0
|
| 538 |
+
and status.last_commit_attempt is not None
|
| 539 |
+
and time.time() - status.last_commit_attempt > 5 * 60
|
| 540 |
+
):
|
| 541 |
+
status.nb_workers_commit += 1
|
| 542 |
+
logger.debug("Job: commit (more than 5 minutes since last commit attempt)")
|
| 543 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 544 |
+
|
| 545 |
+
# 2. Commit if at least 100 files are ready to commit
|
| 546 |
+
elif status.nb_workers_commit == 0 and status.queue_commit.qsize() >= 150:
|
| 547 |
+
status.nb_workers_commit += 1
|
| 548 |
+
logger.debug("Job: commit (>100 files ready)")
|
| 549 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 550 |
+
|
| 551 |
+
# 3. Get upload mode if at least 100 files
|
| 552 |
+
elif status.queue_get_upload_mode.qsize() >= MAX_NB_FILES_FETCH_UPLOAD_MODE:
|
| 553 |
+
status.nb_workers_get_upload_mode += 1
|
| 554 |
+
logger.debug(f"Job: get upload mode (>{MAX_NB_FILES_FETCH_UPLOAD_MODE} files ready)")
|
| 555 |
+
return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
|
| 556 |
+
|
| 557 |
+
# 4. Preupload LFS file if at least `status.upload_batch_size` files and no worker is preuploading LFS
|
| 558 |
+
elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size and status.nb_workers_preupload_lfs == 0:
|
| 559 |
+
status.nb_workers_preupload_lfs += 1
|
| 560 |
+
logger.debug("Job: preupload LFS (no other worker preuploading LFS)")
|
| 561 |
+
return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
|
| 562 |
+
|
| 563 |
+
# 5. Compute sha256 if at least 1 file and no worker is computing sha256
|
| 564 |
+
elif status.queue_sha256.qsize() > 0 and status.nb_workers_sha256 == 0:
|
| 565 |
+
status.nb_workers_sha256 += 1
|
| 566 |
+
logger.debug("Job: sha256 (no other worker computing sha256)")
|
| 567 |
+
return (WorkerJob.SHA256, _get_one(status.queue_sha256))
|
| 568 |
+
|
| 569 |
+
# 6. Get upload mode if at least 1 file and no worker is getting upload mode
|
| 570 |
+
elif status.queue_get_upload_mode.qsize() > 0 and status.nb_workers_get_upload_mode == 0:
|
| 571 |
+
status.nb_workers_get_upload_mode += 1
|
| 572 |
+
logger.debug("Job: get upload mode (no other worker getting upload mode)")
|
| 573 |
+
return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
|
| 574 |
+
|
| 575 |
+
# 7. Preupload LFS file if at least `status.upload_batch_size` files
|
| 576 |
+
elif status.queue_preupload_lfs.qsize() >= status.upload_batch_size:
|
| 577 |
+
status.nb_workers_preupload_lfs += 1
|
| 578 |
+
logger.debug("Job: preupload LFS")
|
| 579 |
+
return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
|
| 580 |
+
|
| 581 |
+
# 8. Compute sha256 if at least 1 file
|
| 582 |
+
elif status.queue_sha256.qsize() > 0:
|
| 583 |
+
status.nb_workers_sha256 += 1
|
| 584 |
+
logger.debug("Job: sha256")
|
| 585 |
+
return (WorkerJob.SHA256, _get_one(status.queue_sha256))
|
| 586 |
+
|
| 587 |
+
# 9. Get upload mode if at least 1 file
|
| 588 |
+
elif status.queue_get_upload_mode.qsize() > 0:
|
| 589 |
+
status.nb_workers_get_upload_mode += 1
|
| 590 |
+
logger.debug("Job: get upload mode")
|
| 591 |
+
return (WorkerJob.GET_UPLOAD_MODE, _get_n(status.queue_get_upload_mode, MAX_NB_FILES_FETCH_UPLOAD_MODE))
|
| 592 |
+
|
| 593 |
+
# 10. Preupload LFS file if at least 1 file
|
| 594 |
+
elif status.queue_preupload_lfs.qsize() > 0:
|
| 595 |
+
status.nb_workers_preupload_lfs += 1
|
| 596 |
+
logger.debug("Job: preupload LFS")
|
| 597 |
+
return (WorkerJob.PREUPLOAD_LFS, _get_n(status.queue_preupload_lfs, status.upload_batch_size))
|
| 598 |
+
|
| 599 |
+
# 11. Commit if at least 1 file and 1 min since last commit attempt
|
| 600 |
+
elif (
|
| 601 |
+
status.nb_workers_commit == 0
|
| 602 |
+
and status.queue_commit.qsize() > 0
|
| 603 |
+
and status.last_commit_attempt is not None
|
| 604 |
+
and time.time() - status.last_commit_attempt > 1 * 60
|
| 605 |
+
):
|
| 606 |
+
status.nb_workers_commit += 1
|
| 607 |
+
logger.debug("Job: commit (1 min since last commit attempt)")
|
| 608 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 609 |
+
|
| 610 |
+
# 12. Commit if at least 1 file all other queues are empty and all workers are waiting
|
| 611 |
+
# e.g. when it's the last commit
|
| 612 |
+
elif (
|
| 613 |
+
status.nb_workers_commit == 0
|
| 614 |
+
and status.queue_commit.qsize() > 0
|
| 615 |
+
and status.queue_sha256.qsize() == 0
|
| 616 |
+
and status.queue_get_upload_mode.qsize() == 0
|
| 617 |
+
and status.queue_preupload_lfs.qsize() == 0
|
| 618 |
+
and status.nb_workers_sha256 == 0
|
| 619 |
+
and status.nb_workers_get_upload_mode == 0
|
| 620 |
+
and status.nb_workers_preupload_lfs == 0
|
| 621 |
+
):
|
| 622 |
+
status.nb_workers_commit += 1
|
| 623 |
+
logger.debug("Job: commit")
|
| 624 |
+
return (WorkerJob.COMMIT, _get_n(status.queue_commit, status.target_chunk()))
|
| 625 |
+
|
| 626 |
+
# 13. If all queues are empty, exit
|
| 627 |
+
elif all(metadata.is_committed or metadata.should_ignore for _, metadata in status.items):
|
| 628 |
+
logger.info("All files have been processed! Exiting worker.")
|
| 629 |
+
return None
|
| 630 |
+
|
| 631 |
+
# 14. If no task is available, wait
|
| 632 |
+
else:
|
| 633 |
+
status.nb_workers_waiting += 1
|
| 634 |
+
logger.debug(f"No task available, waiting... ({WAITING_TIME_IF_NO_TASKS}s)")
|
| 635 |
+
return (WorkerJob.WAIT, [])
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
####################
|
| 639 |
+
# Atomic jobs (sha256, get_upload_mode, preupload_lfs, commit)
|
| 640 |
+
####################
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def _compute_sha256(item: JOB_ITEM_T) -> None:
|
| 644 |
+
"""Compute sha256 of a file and save it in metadata."""
|
| 645 |
+
paths, metadata = item
|
| 646 |
+
if metadata.sha256 is None:
|
| 647 |
+
with paths.file_path.open("rb") as f:
|
| 648 |
+
metadata.sha256 = sha_fileobj(f).hex()
|
| 649 |
+
metadata.save(paths)
|
| 650 |
+
|
| 651 |
+
|
| 652 |
+
def _get_upload_mode(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
|
| 653 |
+
"""Get upload mode for each file and update metadata.
|
| 654 |
+
|
| 655 |
+
Also receive info if the file should be ignored.
|
| 656 |
+
"""
|
| 657 |
+
additions = [_build_hacky_operation(item) for item in items]
|
| 658 |
+
_fetch_upload_modes(
|
| 659 |
+
additions=additions,
|
| 660 |
+
repo_type=repo_type,
|
| 661 |
+
repo_id=repo_id,
|
| 662 |
+
headers=api._build_hf_headers(),
|
| 663 |
+
revision=quote(revision, safe=""),
|
| 664 |
+
endpoint=api.endpoint,
|
| 665 |
+
)
|
| 666 |
+
for item, addition in zip(items, additions):
|
| 667 |
+
paths, metadata = item
|
| 668 |
+
metadata.upload_mode = addition._upload_mode
|
| 669 |
+
metadata.should_ignore = addition._should_ignore
|
| 670 |
+
metadata.remote_oid = addition._remote_oid
|
| 671 |
+
metadata.save(paths)
|
| 672 |
+
|
| 673 |
+
|
| 674 |
+
def _preupload_lfs(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
|
| 675 |
+
"""Preupload LFS files and update metadata."""
|
| 676 |
+
additions = [_build_hacky_operation(item) for item in items]
|
| 677 |
+
api.preupload_lfs_files(
|
| 678 |
+
repo_id=repo_id,
|
| 679 |
+
repo_type=repo_type,
|
| 680 |
+
revision=revision,
|
| 681 |
+
additions=additions,
|
| 682 |
+
)
|
| 683 |
+
|
| 684 |
+
for paths, metadata in items:
|
| 685 |
+
metadata.is_uploaded = True
|
| 686 |
+
metadata.save(paths)
|
| 687 |
+
|
| 688 |
+
|
| 689 |
+
def _commit(items: list[JOB_ITEM_T], api: "HfApi", repo_id: str, repo_type: str, revision: str) -> None:
|
| 690 |
+
"""Commit files to the repo."""
|
| 691 |
+
additions = [_build_hacky_operation(item) for item in items]
|
| 692 |
+
api.create_commit(
|
| 693 |
+
repo_id=repo_id,
|
| 694 |
+
repo_type=repo_type,
|
| 695 |
+
revision=revision,
|
| 696 |
+
operations=additions,
|
| 697 |
+
commit_message="Add files using upload-large-folder tool",
|
| 698 |
+
)
|
| 699 |
+
for paths, metadata in items:
|
| 700 |
+
metadata.is_committed = True
|
| 701 |
+
metadata.save(paths)
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
####################
|
| 705 |
+
# Hacks with CommitOperationAdd to bypass checks/sha256 calculation
|
| 706 |
+
####################
|
| 707 |
+
|
| 708 |
+
|
| 709 |
+
class HackyCommitOperationAdd(CommitOperationAdd):
|
| 710 |
+
def __post_init__(self) -> None:
|
| 711 |
+
if isinstance(self.path_or_fileobj, Path):
|
| 712 |
+
self.path_or_fileobj = str(self.path_or_fileobj)
|
| 713 |
+
|
| 714 |
+
|
| 715 |
+
def _build_hacky_operation(item: JOB_ITEM_T) -> HackyCommitOperationAdd:
|
| 716 |
+
paths, metadata = item
|
| 717 |
+
operation = HackyCommitOperationAdd(path_in_repo=paths.path_in_repo, path_or_fileobj=paths.file_path)
|
| 718 |
+
with paths.file_path.open("rb") as file:
|
| 719 |
+
sample = file.peek(512)[:512]
|
| 720 |
+
if metadata.sha256 is None:
|
| 721 |
+
raise ValueError("sha256 must have been computed by now!")
|
| 722 |
+
operation.upload_info = UploadInfo(sha256=bytes.fromhex(metadata.sha256), size=metadata.size, sample=sample)
|
| 723 |
+
operation._upload_mode = metadata.upload_mode # type: ignore[assignment]
|
| 724 |
+
operation._should_ignore = metadata.should_ignore
|
| 725 |
+
operation._remote_oid = metadata.remote_oid
|
| 726 |
+
return operation
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
####################
|
| 730 |
+
# Misc helpers
|
| 731 |
+
####################
|
| 732 |
+
|
| 733 |
+
|
| 734 |
+
def _get_one(queue: "queue.Queue[JOB_ITEM_T]") -> list[JOB_ITEM_T]:
|
| 735 |
+
return [queue.get()]
|
| 736 |
+
|
| 737 |
+
|
| 738 |
+
def _get_n(queue: "queue.Queue[JOB_ITEM_T]", n: int) -> list[JOB_ITEM_T]:
|
| 739 |
+
return [queue.get() for _ in range(min(queue.qsize(), n))]
|
| 740 |
+
|
| 741 |
+
|
| 742 |
+
def _print_overwrite(report: str) -> None:
|
| 743 |
+
"""Print a report, overwriting the previous lines.
|
| 744 |
+
|
| 745 |
+
Since tqdm in using `sys.stderr` to (re-)write progress bars, we need to use `sys.stdout`
|
| 746 |
+
to print the report.
|
| 747 |
+
|
| 748 |
+
Note: works well only if no other process is writing to `sys.stdout`!
|
| 749 |
+
"""
|
| 750 |
+
report += "\n"
|
| 751 |
+
# Get terminal width
|
| 752 |
+
terminal_width = shutil.get_terminal_size().columns
|
| 753 |
+
|
| 754 |
+
# Count number of lines that should be cleared
|
| 755 |
+
nb_lines = sum(len(line) // terminal_width + 1 for line in report.splitlines())
|
| 756 |
+
|
| 757 |
+
# Clear previous lines based on the number of lines in the report
|
| 758 |
+
for _ in range(nb_lines):
|
| 759 |
+
sys.stdout.write("\r\033[K") # Clear line
|
| 760 |
+
sys.stdout.write("\033[F") # Move cursor up one line
|
| 761 |
+
|
| 762 |
+
# Print the new report, filling remaining space with whitespace
|
| 763 |
+
sys.stdout.write(report)
|
| 764 |
+
sys.stdout.write(" " * (terminal_width - len(report.splitlines()[-1])))
|
| 765 |
+
sys.stdout.flush()
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_webhooks_payload.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 data structures to parse the webhooks payload."""
|
| 16 |
+
|
| 17 |
+
from typing import Literal, Optional
|
| 18 |
+
|
| 19 |
+
from .utils import is_pydantic_available
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
if is_pydantic_available():
|
| 23 |
+
from pydantic import BaseModel
|
| 24 |
+
else:
|
| 25 |
+
# Define a dummy BaseModel to avoid import errors when pydantic is not installed
|
| 26 |
+
# Import error will be raised when trying to use the class
|
| 27 |
+
|
| 28 |
+
class BaseModel: # type: ignore [no-redef]
|
| 29 |
+
def __init__(self, *args, **kwargs) -> None:
|
| 30 |
+
raise ImportError(
|
| 31 |
+
"You must have `pydantic` installed to use `WebhookPayload`. This is an optional dependency that"
|
| 32 |
+
" should be installed separately. Please run `pip install --upgrade pydantic` and retry."
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# This is an adaptation of the ReportV3 interface implemented in moon-landing. V0, V1 and V2 have been ignored as they
|
| 37 |
+
# are not in used anymore. To keep in sync when format is updated in
|
| 38 |
+
# https://github.com/huggingface/moon-landing/blob/main/server/lib/HFWebhooks.ts (internal link).
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
WebhookEvent_T = Literal[
|
| 42 |
+
"create",
|
| 43 |
+
"delete",
|
| 44 |
+
"move",
|
| 45 |
+
"update",
|
| 46 |
+
]
|
| 47 |
+
RepoChangeEvent_T = Literal[
|
| 48 |
+
"add",
|
| 49 |
+
"move",
|
| 50 |
+
"remove",
|
| 51 |
+
"update",
|
| 52 |
+
]
|
| 53 |
+
RepoType_T = Literal[
|
| 54 |
+
"dataset",
|
| 55 |
+
"model",
|
| 56 |
+
"space",
|
| 57 |
+
]
|
| 58 |
+
DiscussionStatus_T = Literal[
|
| 59 |
+
"closed",
|
| 60 |
+
"draft",
|
| 61 |
+
"open",
|
| 62 |
+
"merged",
|
| 63 |
+
]
|
| 64 |
+
SupportedWebhookVersion = Literal[3]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class ObjectId(BaseModel):
|
| 68 |
+
id: str
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class WebhookPayloadUrl(BaseModel):
|
| 72 |
+
web: str
|
| 73 |
+
api: Optional[str] = None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class WebhookPayloadMovedTo(BaseModel):
|
| 77 |
+
name: str
|
| 78 |
+
owner: ObjectId
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class WebhookPayloadWebhook(ObjectId):
|
| 82 |
+
version: SupportedWebhookVersion
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class WebhookPayloadEvent(BaseModel):
|
| 86 |
+
action: WebhookEvent_T
|
| 87 |
+
scope: str
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class WebhookPayloadDiscussionChanges(BaseModel):
|
| 91 |
+
base: str
|
| 92 |
+
mergeCommitId: Optional[str] = None
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class WebhookPayloadComment(ObjectId):
|
| 96 |
+
author: ObjectId
|
| 97 |
+
hidden: bool
|
| 98 |
+
content: Optional[str] = None
|
| 99 |
+
url: WebhookPayloadUrl
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class WebhookPayloadDiscussion(ObjectId):
|
| 103 |
+
num: int
|
| 104 |
+
author: ObjectId
|
| 105 |
+
url: WebhookPayloadUrl
|
| 106 |
+
title: str
|
| 107 |
+
isPullRequest: bool
|
| 108 |
+
status: DiscussionStatus_T
|
| 109 |
+
changes: Optional[WebhookPayloadDiscussionChanges] = None
|
| 110 |
+
pinned: Optional[bool] = None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class WebhookPayloadRepo(ObjectId):
|
| 114 |
+
owner: ObjectId
|
| 115 |
+
head_sha: Optional[str] = None
|
| 116 |
+
name: str
|
| 117 |
+
private: bool
|
| 118 |
+
subdomain: Optional[str] = None
|
| 119 |
+
tags: Optional[list[str]] = None
|
| 120 |
+
type: Literal["dataset", "model", "space"]
|
| 121 |
+
url: WebhookPayloadUrl
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class WebhookPayloadUpdatedRef(BaseModel):
|
| 125 |
+
ref: str
|
| 126 |
+
oldSha: Optional[str] = None
|
| 127 |
+
newSha: Optional[str] = None
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
class WebhookPayload(BaseModel):
|
| 131 |
+
event: WebhookPayloadEvent
|
| 132 |
+
repo: WebhookPayloadRepo
|
| 133 |
+
discussion: Optional[WebhookPayloadDiscussion] = None
|
| 134 |
+
comment: Optional[WebhookPayloadComment] = None
|
| 135 |
+
webhook: WebhookPayloadWebhook
|
| 136 |
+
movedTo: Optional[WebhookPayloadMovedTo] = None
|
| 137 |
+
updatedRefs: Optional[list[WebhookPayloadUpdatedRef]] = None
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/_webhooks_server.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 `WebhooksServer` and `webhook_endpoint` to create a webhook server easily."""
|
| 16 |
+
|
| 17 |
+
import atexit
|
| 18 |
+
import inspect
|
| 19 |
+
import os
|
| 20 |
+
from functools import wraps
|
| 21 |
+
from typing import TYPE_CHECKING, Any, Callable, Optional
|
| 22 |
+
|
| 23 |
+
from .utils import experimental, is_fastapi_available, is_gradio_available
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
import gradio as gr
|
| 28 |
+
from fastapi import Request
|
| 29 |
+
|
| 30 |
+
if is_fastapi_available():
|
| 31 |
+
from fastapi import FastAPI, Request
|
| 32 |
+
from fastapi.responses import JSONResponse
|
| 33 |
+
else:
|
| 34 |
+
# Will fail at runtime if FastAPI is not available
|
| 35 |
+
FastAPI = Request = JSONResponse = None # type: ignore
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
_global_app: Optional["WebhooksServer"] = None
|
| 39 |
+
_is_local = os.environ.get("SPACE_ID") is None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@experimental
|
| 43 |
+
class WebhooksServer:
|
| 44 |
+
"""
|
| 45 |
+
The [`WebhooksServer`] class lets you create an instance of a Gradio app that can receive Huggingface webhooks.
|
| 46 |
+
These webhooks can be registered using the [`~WebhooksServer.add_webhook`] decorator. Webhook endpoints are added to
|
| 47 |
+
the app as a POST endpoint to the FastAPI router. Once all the webhooks are registered, the `launch` method has to be
|
| 48 |
+
called to start the app.
|
| 49 |
+
|
| 50 |
+
It is recommended to accept [`WebhookPayload`] as the first argument of the webhook function. It is a Pydantic
|
| 51 |
+
model that contains all the information about the webhook event. The data will be parsed automatically for you.
|
| 52 |
+
|
| 53 |
+
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
|
| 54 |
+
WebhooksServer and deploy it on a Space.
|
| 55 |
+
|
| 56 |
+
> [!WARNING]
|
| 57 |
+
> `WebhooksServer` is experimental. Its API is subject to change in the future.
|
| 58 |
+
|
| 59 |
+
> [!WARNING]
|
| 60 |
+
> You must have `gradio` installed to use `WebhooksServer` (`pip install --upgrade gradio`).
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
ui (`gradio.Blocks`, optional):
|
| 64 |
+
A Gradio UI instance to be used as the Space landing page. If `None`, a UI displaying instructions
|
| 65 |
+
about the configured webhooks is created.
|
| 66 |
+
webhook_secret (`str`, optional):
|
| 67 |
+
A secret key to verify incoming webhook requests. You can set this value to any secret you want as long as
|
| 68 |
+
you also configure it in your [webhooks settings panel](https://huggingface.co/settings/webhooks). You
|
| 69 |
+
can also set this value as the `WEBHOOK_SECRET` environment variable. If no secret is provided, the
|
| 70 |
+
webhook endpoints are opened without any security.
|
| 71 |
+
|
| 72 |
+
Example:
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
import gradio as gr
|
| 76 |
+
from huggingface_hub import WebhooksServer, WebhookPayload
|
| 77 |
+
|
| 78 |
+
with gr.Blocks() as ui:
|
| 79 |
+
...
|
| 80 |
+
|
| 81 |
+
app = WebhooksServer(ui=ui, webhook_secret="my_secret_key")
|
| 82 |
+
|
| 83 |
+
@app.add_webhook("/say_hello")
|
| 84 |
+
async def hello(payload: WebhookPayload):
|
| 85 |
+
return {"message": "hello"}
|
| 86 |
+
|
| 87 |
+
app.launch()
|
| 88 |
+
```
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
def __new__(cls, *args, **kwargs) -> "WebhooksServer":
|
| 92 |
+
if not is_gradio_available():
|
| 93 |
+
raise ImportError(
|
| 94 |
+
"You must have `gradio` installed to use `WebhooksServer`. Please run `pip install --upgrade gradio`"
|
| 95 |
+
" first."
|
| 96 |
+
)
|
| 97 |
+
if not is_fastapi_available():
|
| 98 |
+
raise ImportError(
|
| 99 |
+
"You must have `fastapi` installed to use `WebhooksServer`. Please run `pip install --upgrade fastapi`"
|
| 100 |
+
" first."
|
| 101 |
+
)
|
| 102 |
+
return super().__new__(cls)
|
| 103 |
+
|
| 104 |
+
def __init__(
|
| 105 |
+
self,
|
| 106 |
+
ui: Optional["gr.Blocks"] = None,
|
| 107 |
+
webhook_secret: Optional[str] = None,
|
| 108 |
+
) -> None:
|
| 109 |
+
self._ui = ui
|
| 110 |
+
|
| 111 |
+
self.webhook_secret = webhook_secret or os.getenv("WEBHOOK_SECRET")
|
| 112 |
+
self.registered_webhooks: dict[str, Callable] = {}
|
| 113 |
+
_warn_on_empty_secret(self.webhook_secret)
|
| 114 |
+
|
| 115 |
+
def add_webhook(self, path: Optional[str] = None) -> Callable:
|
| 116 |
+
"""
|
| 117 |
+
Decorator to add a webhook to the [`WebhooksServer`] server.
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
path (`str`, optional):
|
| 121 |
+
The URL path to register the webhook function. If not provided, the function name will be used as the
|
| 122 |
+
path. In any case, all webhooks are registered under `/webhooks`.
|
| 123 |
+
|
| 124 |
+
Raises:
|
| 125 |
+
ValueError: If the provided path is already registered as a webhook.
|
| 126 |
+
|
| 127 |
+
Example:
|
| 128 |
+
```python
|
| 129 |
+
from huggingface_hub import WebhooksServer, WebhookPayload
|
| 130 |
+
|
| 131 |
+
app = WebhooksServer()
|
| 132 |
+
|
| 133 |
+
@app.add_webhook
|
| 134 |
+
async def trigger_training(payload: WebhookPayload):
|
| 135 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
| 136 |
+
# Trigger a training job if a dataset is updated
|
| 137 |
+
...
|
| 138 |
+
|
| 139 |
+
app.launch()
|
| 140 |
+
```
|
| 141 |
+
"""
|
| 142 |
+
# Usage: directly as decorator. Example: `@app.add_webhook`
|
| 143 |
+
if callable(path):
|
| 144 |
+
# If path is a function, it means it was used as a decorator without arguments
|
| 145 |
+
return self.add_webhook()(path)
|
| 146 |
+
|
| 147 |
+
# Usage: provide a path. Example: `@app.add_webhook(...)`
|
| 148 |
+
@wraps(FastAPI.post)
|
| 149 |
+
def _inner_post(*args, **kwargs):
|
| 150 |
+
func = args[0]
|
| 151 |
+
abs_path = f"/webhooks/{(path or func.__name__).strip('/')}"
|
| 152 |
+
if abs_path in self.registered_webhooks:
|
| 153 |
+
raise ValueError(f"Webhook {abs_path} already exists.")
|
| 154 |
+
self.registered_webhooks[abs_path] = func
|
| 155 |
+
|
| 156 |
+
return _inner_post
|
| 157 |
+
|
| 158 |
+
def launch(self, prevent_thread_lock: bool = False, **launch_kwargs: Any) -> None:
|
| 159 |
+
"""Launch the Gradio app and register webhooks to the underlying FastAPI server.
|
| 160 |
+
|
| 161 |
+
Input parameters are forwarded to Gradio when launching the app.
|
| 162 |
+
"""
|
| 163 |
+
ui = self._ui or self._get_default_ui()
|
| 164 |
+
|
| 165 |
+
# Start Gradio App
|
| 166 |
+
# - as non-blocking so that webhooks can be added afterwards
|
| 167 |
+
# - as shared if launch locally (to debug webhooks)
|
| 168 |
+
launch_kwargs.setdefault("share", _is_local)
|
| 169 |
+
self.fastapi_app, _, _ = ui.launch(prevent_thread_lock=True, **launch_kwargs)
|
| 170 |
+
|
| 171 |
+
# Register webhooks to FastAPI app
|
| 172 |
+
for path, func in self.registered_webhooks.items():
|
| 173 |
+
# Add secret check if required
|
| 174 |
+
if self.webhook_secret is not None:
|
| 175 |
+
func = _wrap_webhook_to_check_secret(func, webhook_secret=self.webhook_secret)
|
| 176 |
+
|
| 177 |
+
# Add route to FastAPI app
|
| 178 |
+
self.fastapi_app.post(path)(func)
|
| 179 |
+
|
| 180 |
+
# Print instructions and block main thread
|
| 181 |
+
space_host = os.environ.get("SPACE_HOST")
|
| 182 |
+
url = "https://" + space_host if space_host is not None else (ui.share_url or ui.local_url)
|
| 183 |
+
if url is None:
|
| 184 |
+
raise ValueError("Cannot find the URL of the app. Please provide a valid `ui` or update `gradio` version.")
|
| 185 |
+
url = url.strip("/")
|
| 186 |
+
message = "\nWebhooks are correctly setup and ready to use:"
|
| 187 |
+
message += "\n" + "\n".join(f" - POST {url}{webhook}" for webhook in self.registered_webhooks)
|
| 188 |
+
message += "\nGo to https://huggingface.co/settings/webhooks to setup your webhooks."
|
| 189 |
+
print(message)
|
| 190 |
+
|
| 191 |
+
if not prevent_thread_lock:
|
| 192 |
+
ui.block_thread()
|
| 193 |
+
|
| 194 |
+
def _get_default_ui(self) -> "gr.Blocks":
|
| 195 |
+
"""Default UI if not provided (lists webhooks and provides basic instructions)."""
|
| 196 |
+
import gradio as gr
|
| 197 |
+
|
| 198 |
+
with gr.Blocks() as ui:
|
| 199 |
+
gr.Markdown("# This is an app to process 🤗 Webhooks")
|
| 200 |
+
gr.Markdown(
|
| 201 |
+
"Webhooks are a foundation for MLOps-related features. They allow you to listen for new changes on"
|
| 202 |
+
" specific repos or to all repos belonging to particular set of users/organizations (not just your"
|
| 203 |
+
" repos, but any repo). Check out this [guide](https://huggingface.co/docs/hub/webhooks) to get to"
|
| 204 |
+
" know more about webhooks on the Huggingface Hub."
|
| 205 |
+
)
|
| 206 |
+
gr.Markdown(
|
| 207 |
+
f"{len(self.registered_webhooks)} webhook(s) are registered:"
|
| 208 |
+
+ "\n\n"
|
| 209 |
+
+ "\n ".join(
|
| 210 |
+
f"- [{webhook_path}]({_get_webhook_doc_url(webhook.__name__, webhook_path)})"
|
| 211 |
+
for webhook_path, webhook in self.registered_webhooks.items()
|
| 212 |
+
)
|
| 213 |
+
)
|
| 214 |
+
gr.Markdown(
|
| 215 |
+
"Go to https://huggingface.co/settings/webhooks to setup your webhooks."
|
| 216 |
+
+ "\nYou app is running locally. Please look at the logs to check the full URL you need to set."
|
| 217 |
+
if _is_local
|
| 218 |
+
else (
|
| 219 |
+
"\nThis app is running on a Space. You can find the corresponding URL in the options menu"
|
| 220 |
+
" (top-right) > 'Embed the Space'. The URL looks like 'https://{username}-{repo_name}.hf.space'."
|
| 221 |
+
)
|
| 222 |
+
)
|
| 223 |
+
return ui
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@experimental
|
| 227 |
+
def webhook_endpoint(path: Optional[str] = None) -> Callable:
|
| 228 |
+
"""Decorator to start a [`WebhooksServer`] and register the decorated function as a webhook endpoint.
|
| 229 |
+
|
| 230 |
+
This is a helper to get started quickly. If you need more flexibility (custom landing page or webhook secret),
|
| 231 |
+
you can use [`WebhooksServer`] directly. You can register multiple webhook endpoints (to the same server) by using
|
| 232 |
+
this decorator multiple times.
|
| 233 |
+
|
| 234 |
+
Check out the [webhooks guide](../guides/webhooks_server) for a step-by-step tutorial on how to set up your
|
| 235 |
+
server and deploy it on a Space.
|
| 236 |
+
|
| 237 |
+
> [!WARNING]
|
| 238 |
+
> `webhook_endpoint` is experimental. Its API is subject to change in the future.
|
| 239 |
+
|
| 240 |
+
> [!WARNING]
|
| 241 |
+
> You must have `gradio` installed to use `webhook_endpoint` (`pip install --upgrade gradio`).
|
| 242 |
+
|
| 243 |
+
Args:
|
| 244 |
+
path (`str`, optional):
|
| 245 |
+
The URL path to register the webhook function. If not provided, the function name will be used as the path.
|
| 246 |
+
In any case, all webhooks are registered under `/webhooks`.
|
| 247 |
+
|
| 248 |
+
Examples:
|
| 249 |
+
The default usage is to register a function as a webhook endpoint. The function name will be used as the path.
|
| 250 |
+
The server will be started automatically at exit (i.e. at the end of the script).
|
| 251 |
+
|
| 252 |
+
```python
|
| 253 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
| 254 |
+
|
| 255 |
+
@webhook_endpoint
|
| 256 |
+
async def trigger_training(payload: WebhookPayload):
|
| 257 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
| 258 |
+
# Trigger a training job if a dataset is updated
|
| 259 |
+
...
|
| 260 |
+
|
| 261 |
+
# Server is automatically started at the end of the script.
|
| 262 |
+
```
|
| 263 |
+
|
| 264 |
+
Advanced usage: register a function as a webhook endpoint and start the server manually. This is useful if you
|
| 265 |
+
are running it in a notebook.
|
| 266 |
+
|
| 267 |
+
```python
|
| 268 |
+
from huggingface_hub import webhook_endpoint, WebhookPayload
|
| 269 |
+
|
| 270 |
+
@webhook_endpoint
|
| 271 |
+
async def trigger_training(payload: WebhookPayload):
|
| 272 |
+
if payload.repo.type == "dataset" and payload.event.action == "update":
|
| 273 |
+
# Trigger a training job if a dataset is updated
|
| 274 |
+
...
|
| 275 |
+
|
| 276 |
+
# Start the server manually
|
| 277 |
+
trigger_training.launch()
|
| 278 |
+
```
|
| 279 |
+
"""
|
| 280 |
+
if callable(path):
|
| 281 |
+
# If path is a function, it means it was used as a decorator without arguments
|
| 282 |
+
return webhook_endpoint()(path)
|
| 283 |
+
|
| 284 |
+
@wraps(WebhooksServer.add_webhook)
|
| 285 |
+
def _inner(func: Callable) -> Callable:
|
| 286 |
+
app = _get_global_app()
|
| 287 |
+
app.add_webhook(path)(func)
|
| 288 |
+
if len(app.registered_webhooks) == 1:
|
| 289 |
+
# Register `app.launch` to run at exit (only once)
|
| 290 |
+
atexit.register(app.launch)
|
| 291 |
+
|
| 292 |
+
@wraps(app.launch)
|
| 293 |
+
def _launch_now():
|
| 294 |
+
# Run the app directly (without waiting atexit)
|
| 295 |
+
atexit.unregister(app.launch)
|
| 296 |
+
app.launch()
|
| 297 |
+
|
| 298 |
+
func.launch = _launch_now # type: ignore
|
| 299 |
+
return func
|
| 300 |
+
|
| 301 |
+
return _inner
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _get_global_app() -> WebhooksServer:
|
| 305 |
+
global _global_app
|
| 306 |
+
if _global_app is None:
|
| 307 |
+
_global_app = WebhooksServer()
|
| 308 |
+
return _global_app
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def _warn_on_empty_secret(webhook_secret: Optional[str]) -> None:
|
| 312 |
+
if webhook_secret is None:
|
| 313 |
+
print("Webhook secret is not defined. This means your webhook endpoints will be open to everyone.")
|
| 314 |
+
print(
|
| 315 |
+
"To add a secret, set `WEBHOOK_SECRET` as environment variable or pass it at initialization: "
|
| 316 |
+
"\n\t`app = WebhooksServer(webhook_secret='my_secret', ...)`"
|
| 317 |
+
)
|
| 318 |
+
print(
|
| 319 |
+
"For more details about webhook secrets, please refer to"
|
| 320 |
+
" https://huggingface.co/docs/hub/webhooks#webhook-secret."
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
print("Webhook secret is correctly defined.")
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def _get_webhook_doc_url(webhook_name: str, webhook_path: str) -> str:
|
| 327 |
+
"""Returns the anchor to a given webhook in the docs (experimental)"""
|
| 328 |
+
return "/docs#/default/" + webhook_name + webhook_path.replace("/", "_") + "_post"
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
def _wrap_webhook_to_check_secret(func: Callable, webhook_secret: str) -> Callable:
|
| 332 |
+
"""Wraps a webhook function to check the webhook secret before calling the function.
|
| 333 |
+
|
| 334 |
+
This is a hacky way to add the `request` parameter to the function signature. Since FastAPI based itself on route
|
| 335 |
+
parameters to inject the values to the function, we need to hack the function signature to retrieve the `Request`
|
| 336 |
+
object (and hence the headers). A far cleaner solution would be to use a middleware. However, since
|
| 337 |
+
`fastapi==0.90.1`, a middleware cannot be added once the app has started. And since the FastAPI app is started by
|
| 338 |
+
Gradio internals (and not by us), we cannot add a middleware.
|
| 339 |
+
|
| 340 |
+
This method is called only when a secret has been defined by the user. If a request is sent without the
|
| 341 |
+
"x-webhook-secret", the function will return a 401 error (unauthorized). If the header is sent but is incorrect,
|
| 342 |
+
the function will return a 403 error (forbidden).
|
| 343 |
+
|
| 344 |
+
Inspired by https://stackoverflow.com/a/33112180.
|
| 345 |
+
"""
|
| 346 |
+
initial_sig = inspect.signature(func)
|
| 347 |
+
|
| 348 |
+
@wraps(func)
|
| 349 |
+
async def _protected_func(request: Request, **kwargs):
|
| 350 |
+
request_secret = request.headers.get("x-webhook-secret")
|
| 351 |
+
if request_secret is None:
|
| 352 |
+
return JSONResponse({"error": "x-webhook-secret header not set."}, status_code=401)
|
| 353 |
+
if request_secret != webhook_secret:
|
| 354 |
+
return JSONResponse({"error": "Invalid webhook secret."}, status_code=403)
|
| 355 |
+
|
| 356 |
+
# Inject `request` in kwargs if required
|
| 357 |
+
if "request" in initial_sig.parameters:
|
| 358 |
+
kwargs["request"] = request
|
| 359 |
+
|
| 360 |
+
# Handle both sync and async routes
|
| 361 |
+
if inspect.iscoroutinefunction(func):
|
| 362 |
+
return await func(**kwargs)
|
| 363 |
+
else:
|
| 364 |
+
return func(**kwargs)
|
| 365 |
+
|
| 366 |
+
# Update signature to include request
|
| 367 |
+
if "request" not in initial_sig.parameters:
|
| 368 |
+
_protected_func.__signature__ = initial_sig.replace( # type: ignore
|
| 369 |
+
parameters=(
|
| 370 |
+
inspect.Parameter(name="request", kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, annotation=Request),
|
| 371 |
+
)
|
| 372 |
+
+ tuple(initial_sig.parameters.values())
|
| 373 |
+
)
|
| 374 |
+
|
| 375 |
+
# Return protected route
|
| 376 |
+
return _protected_func
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/community.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Data structures to interact with Discussions and Pull Requests on the Hub.
|
| 3 |
+
|
| 4 |
+
See [the Discussions and Pull Requests guide](https://huggingface.co/docs/hub/repositories-pull-requests-discussions)
|
| 5 |
+
for more information on Pull Requests, Discussions, and the community tab.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from dataclasses import dataclass
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from typing import Literal, Optional, TypedDict, Union
|
| 11 |
+
|
| 12 |
+
from . import constants
|
| 13 |
+
from .utils import parse_datetime
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
DiscussionStatus = Literal["open", "closed", "merged", "draft"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class Discussion:
|
| 21 |
+
"""
|
| 22 |
+
A Discussion or Pull Request on the Hub.
|
| 23 |
+
|
| 24 |
+
This dataclass is not intended to be instantiated directly.
|
| 25 |
+
|
| 26 |
+
Attributes:
|
| 27 |
+
title (`str`):
|
| 28 |
+
The title of the Discussion / Pull Request
|
| 29 |
+
status (`str`):
|
| 30 |
+
The status of the Discussion / Pull Request.
|
| 31 |
+
It must be one of:
|
| 32 |
+
* `"open"`
|
| 33 |
+
* `"closed"`
|
| 34 |
+
* `"merged"` (only for Pull Requests )
|
| 35 |
+
* `"draft"` (only for Pull Requests )
|
| 36 |
+
num (`int`):
|
| 37 |
+
The number of the Discussion / Pull Request.
|
| 38 |
+
repo_id (`str`):
|
| 39 |
+
The id (`"{namespace}/{repo_name}"`) of the repo on which
|
| 40 |
+
the Discussion / Pull Request was open.
|
| 41 |
+
repo_type (`str`):
|
| 42 |
+
The type of the repo on which the Discussion / Pull Request was open.
|
| 43 |
+
Possible values are: `"model"`, `"dataset"`, `"space"`.
|
| 44 |
+
author (`str`):
|
| 45 |
+
The username of the Discussion / Pull Request author.
|
| 46 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 47 |
+
is_pull_request (`bool`):
|
| 48 |
+
Whether or not this is a Pull Request.
|
| 49 |
+
created_at (`datetime`):
|
| 50 |
+
The `datetime` of creation of the Discussion / Pull Request.
|
| 51 |
+
endpoint (`str`):
|
| 52 |
+
Endpoint of the Hub. Default is https://huggingface.co.
|
| 53 |
+
git_reference (`str`, *optional*):
|
| 54 |
+
(property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
|
| 55 |
+
url (`str`):
|
| 56 |
+
(property) URL of the discussion on the Hub.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
title: str
|
| 60 |
+
status: DiscussionStatus
|
| 61 |
+
num: int
|
| 62 |
+
repo_id: str
|
| 63 |
+
repo_type: str
|
| 64 |
+
author: str
|
| 65 |
+
is_pull_request: bool
|
| 66 |
+
created_at: datetime
|
| 67 |
+
endpoint: str
|
| 68 |
+
|
| 69 |
+
@property
|
| 70 |
+
def git_reference(self) -> Optional[str]:
|
| 71 |
+
"""
|
| 72 |
+
If this is a Pull Request , returns the git reference to which changes can be pushed.
|
| 73 |
+
Returns `None` otherwise.
|
| 74 |
+
"""
|
| 75 |
+
if self.is_pull_request:
|
| 76 |
+
return f"refs/pr/{self.num}"
|
| 77 |
+
return None
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def url(self) -> str:
|
| 81 |
+
"""Returns the URL of the discussion on the Hub."""
|
| 82 |
+
if self.repo_type is None or self.repo_type == constants.REPO_TYPE_MODEL:
|
| 83 |
+
return f"{self.endpoint}/{self.repo_id}/discussions/{self.num}"
|
| 84 |
+
return f"{self.endpoint}/{self.repo_type}s/{self.repo_id}/discussions/{self.num}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@dataclass
|
| 88 |
+
class DiscussionWithDetails(Discussion):
|
| 89 |
+
"""
|
| 90 |
+
Subclass of [`Discussion`].
|
| 91 |
+
|
| 92 |
+
Attributes:
|
| 93 |
+
title (`str`):
|
| 94 |
+
The title of the Discussion / Pull Request
|
| 95 |
+
status (`str`):
|
| 96 |
+
The status of the Discussion / Pull Request.
|
| 97 |
+
It can be one of:
|
| 98 |
+
* `"open"`
|
| 99 |
+
* `"closed"`
|
| 100 |
+
* `"merged"` (only for Pull Requests )
|
| 101 |
+
* `"draft"` (only for Pull Requests )
|
| 102 |
+
num (`int`):
|
| 103 |
+
The number of the Discussion / Pull Request.
|
| 104 |
+
repo_id (`str`):
|
| 105 |
+
The id (`"{namespace}/{repo_name}"`) of the repo on which
|
| 106 |
+
the Discussion / Pull Request was open.
|
| 107 |
+
repo_type (`str`):
|
| 108 |
+
The type of the repo on which the Discussion / Pull Request was open.
|
| 109 |
+
Possible values are: `"model"`, `"dataset"`, `"space"`.
|
| 110 |
+
author (`str`):
|
| 111 |
+
The username of the Discussion / Pull Request author.
|
| 112 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 113 |
+
is_pull_request (`bool`):
|
| 114 |
+
Whether or not this is a Pull Request.
|
| 115 |
+
created_at (`datetime`):
|
| 116 |
+
The `datetime` of creation of the Discussion / Pull Request.
|
| 117 |
+
events (`list` of [`DiscussionEvent`])
|
| 118 |
+
The list of [`DiscussionEvents`] in this Discussion or Pull Request.
|
| 119 |
+
conflicting_files (`Union[list[str], bool, None]`, *optional*):
|
| 120 |
+
A list of conflicting files if this is a Pull Request.
|
| 121 |
+
`None` if `self.is_pull_request` is `False`.
|
| 122 |
+
`True` if there are conflicting files but the list can't be retrieved.
|
| 123 |
+
target_branch (`str`, *optional*):
|
| 124 |
+
The branch into which changes are to be merged if this is a
|
| 125 |
+
Pull Request . `None` if `self.is_pull_request` is `False`.
|
| 126 |
+
merge_commit_oid (`str`, *optional*):
|
| 127 |
+
If this is a merged Pull Request , this is set to the OID / SHA of
|
| 128 |
+
the merge commit, `None` otherwise.
|
| 129 |
+
diff (`str`, *optional*):
|
| 130 |
+
The git diff if this is a Pull Request , `None` otherwise.
|
| 131 |
+
endpoint (`str`):
|
| 132 |
+
Endpoint of the Hub. Default is https://huggingface.co.
|
| 133 |
+
git_reference (`str`, *optional*):
|
| 134 |
+
(property) Git reference to which changes can be pushed if this is a Pull Request, `None` otherwise.
|
| 135 |
+
url (`str`):
|
| 136 |
+
(property) URL of the discussion on the Hub.
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
events: list["DiscussionEvent"]
|
| 140 |
+
conflicting_files: Union[list[str], bool, None]
|
| 141 |
+
target_branch: Optional[str]
|
| 142 |
+
merge_commit_oid: Optional[str]
|
| 143 |
+
diff: Optional[str]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class DiscussionEventArgs(TypedDict):
|
| 147 |
+
id: str
|
| 148 |
+
type: str
|
| 149 |
+
created_at: datetime
|
| 150 |
+
author: str
|
| 151 |
+
_event: dict
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@dataclass
|
| 155 |
+
class DiscussionEvent:
|
| 156 |
+
"""
|
| 157 |
+
An event in a Discussion or Pull Request.
|
| 158 |
+
|
| 159 |
+
Use concrete classes:
|
| 160 |
+
* [`DiscussionComment`]
|
| 161 |
+
* [`DiscussionStatusChange`]
|
| 162 |
+
* [`DiscussionCommit`]
|
| 163 |
+
* [`DiscussionTitleChange`]
|
| 164 |
+
|
| 165 |
+
Attributes:
|
| 166 |
+
id (`str`):
|
| 167 |
+
The ID of the event. An hexadecimal string.
|
| 168 |
+
type (`str`):
|
| 169 |
+
The type of the event.
|
| 170 |
+
created_at (`datetime`):
|
| 171 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 172 |
+
object holding the creation timestamp for the event.
|
| 173 |
+
author (`str`):
|
| 174 |
+
The username of the Discussion / Pull Request author.
|
| 175 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
id: str
|
| 179 |
+
type: str
|
| 180 |
+
created_at: datetime
|
| 181 |
+
author: str
|
| 182 |
+
|
| 183 |
+
_event: dict
|
| 184 |
+
"""Stores the original event data, in case we need to access it later."""
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@dataclass
|
| 188 |
+
class DiscussionComment(DiscussionEvent):
|
| 189 |
+
"""A comment in a Discussion / Pull Request.
|
| 190 |
+
|
| 191 |
+
Subclass of [`DiscussionEvent`].
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
Attributes:
|
| 195 |
+
id (`str`):
|
| 196 |
+
The ID of the event. An hexadecimal string.
|
| 197 |
+
type (`str`):
|
| 198 |
+
The type of the event.
|
| 199 |
+
created_at (`datetime`):
|
| 200 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 201 |
+
object holding the creation timestamp for the event.
|
| 202 |
+
author (`str`):
|
| 203 |
+
The username of the Discussion / Pull Request author.
|
| 204 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 205 |
+
content (`str`):
|
| 206 |
+
The raw markdown content of the comment. Mentions, links and images are not rendered.
|
| 207 |
+
edited (`bool`):
|
| 208 |
+
Whether or not this comment has been edited.
|
| 209 |
+
hidden (`bool`):
|
| 210 |
+
Whether or not this comment has been hidden.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
content: str
|
| 214 |
+
edited: bool
|
| 215 |
+
hidden: bool
|
| 216 |
+
|
| 217 |
+
@property
|
| 218 |
+
def rendered(self) -> str:
|
| 219 |
+
"""The rendered comment, as a HTML string"""
|
| 220 |
+
return self._event["data"]["latest"]["html"]
|
| 221 |
+
|
| 222 |
+
@property
|
| 223 |
+
def last_edited_at(self) -> datetime:
|
| 224 |
+
"""The last edit time, as a `datetime` object."""
|
| 225 |
+
return parse_datetime(self._event["data"]["latest"]["updatedAt"])
|
| 226 |
+
|
| 227 |
+
@property
|
| 228 |
+
def last_edited_by(self) -> str:
|
| 229 |
+
"""The last edit time, as a `datetime` object."""
|
| 230 |
+
return self._event["data"]["latest"].get("author", {}).get("name", "deleted")
|
| 231 |
+
|
| 232 |
+
@property
|
| 233 |
+
def edit_history(self) -> list[dict]:
|
| 234 |
+
"""The edit history of the comment"""
|
| 235 |
+
return self._event["data"]["history"]
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def number_of_edits(self) -> int:
|
| 239 |
+
return len(self.edit_history)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
@dataclass
|
| 243 |
+
class DiscussionStatusChange(DiscussionEvent):
|
| 244 |
+
"""A change of status in a Discussion / Pull Request.
|
| 245 |
+
|
| 246 |
+
Subclass of [`DiscussionEvent`].
|
| 247 |
+
|
| 248 |
+
Attributes:
|
| 249 |
+
id (`str`):
|
| 250 |
+
The ID of the event. An hexadecimal string.
|
| 251 |
+
type (`str`):
|
| 252 |
+
The type of the event.
|
| 253 |
+
created_at (`datetime`):
|
| 254 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 255 |
+
object holding the creation timestamp for the event.
|
| 256 |
+
author (`str`):
|
| 257 |
+
The username of the Discussion / Pull Request author.
|
| 258 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 259 |
+
new_status (`str`):
|
| 260 |
+
The status of the Discussion / Pull Request after the change.
|
| 261 |
+
It can be one of:
|
| 262 |
+
* `"open"`
|
| 263 |
+
* `"closed"`
|
| 264 |
+
* `"merged"` (only for Pull Requests )
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
new_status: str
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@dataclass
|
| 271 |
+
class DiscussionCommit(DiscussionEvent):
|
| 272 |
+
"""A commit in a Pull Request.
|
| 273 |
+
|
| 274 |
+
Subclass of [`DiscussionEvent`].
|
| 275 |
+
|
| 276 |
+
Attributes:
|
| 277 |
+
id (`str`):
|
| 278 |
+
The ID of the event. An hexadecimal string.
|
| 279 |
+
type (`str`):
|
| 280 |
+
The type of the event.
|
| 281 |
+
created_at (`datetime`):
|
| 282 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 283 |
+
object holding the creation timestamp for the event.
|
| 284 |
+
author (`str`):
|
| 285 |
+
The username of the Discussion / Pull Request author.
|
| 286 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 287 |
+
summary (`str`):
|
| 288 |
+
The summary of the commit.
|
| 289 |
+
oid (`str`):
|
| 290 |
+
The OID / SHA of the commit, as a hexadecimal string.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
summary: str
|
| 294 |
+
oid: str
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
@dataclass
|
| 298 |
+
class DiscussionTitleChange(DiscussionEvent):
|
| 299 |
+
"""A rename event in a Discussion / Pull Request.
|
| 300 |
+
|
| 301 |
+
Subclass of [`DiscussionEvent`].
|
| 302 |
+
|
| 303 |
+
Attributes:
|
| 304 |
+
id (`str`):
|
| 305 |
+
The ID of the event. An hexadecimal string.
|
| 306 |
+
type (`str`):
|
| 307 |
+
The type of the event.
|
| 308 |
+
created_at (`datetime`):
|
| 309 |
+
A [`datetime`](https://docs.python.org/3/library/datetime.html?highlight=datetime#datetime.datetime)
|
| 310 |
+
object holding the creation timestamp for the event.
|
| 311 |
+
author (`str`):
|
| 312 |
+
The username of the Discussion / Pull Request author.
|
| 313 |
+
Can be `"deleted"` if the user has been deleted since.
|
| 314 |
+
old_title (`str`):
|
| 315 |
+
The previous title for the Discussion / Pull Request.
|
| 316 |
+
new_title (`str`):
|
| 317 |
+
The new title.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
old_title: str
|
| 321 |
+
new_title: str
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def deserialize_event(event: dict) -> DiscussionEvent:
|
| 325 |
+
"""Instantiates a [`DiscussionEvent`] from a dict"""
|
| 326 |
+
event_id: str = event["id"]
|
| 327 |
+
event_type: str = event["type"]
|
| 328 |
+
created_at = parse_datetime(event["createdAt"])
|
| 329 |
+
|
| 330 |
+
common_args: DiscussionEventArgs = {
|
| 331 |
+
"id": event_id,
|
| 332 |
+
"type": event_type,
|
| 333 |
+
"created_at": created_at,
|
| 334 |
+
"author": event.get("author", {}).get("name", "deleted"),
|
| 335 |
+
"_event": event,
|
| 336 |
+
}
|
| 337 |
+
|
| 338 |
+
if event_type == "comment":
|
| 339 |
+
return DiscussionComment(
|
| 340 |
+
**common_args,
|
| 341 |
+
edited=event["data"]["edited"],
|
| 342 |
+
hidden=event["data"]["hidden"],
|
| 343 |
+
content=event["data"]["latest"]["raw"],
|
| 344 |
+
)
|
| 345 |
+
if event_type == "status-change":
|
| 346 |
+
return DiscussionStatusChange(
|
| 347 |
+
**common_args,
|
| 348 |
+
new_status=event["data"]["status"],
|
| 349 |
+
)
|
| 350 |
+
if event_type == "commit":
|
| 351 |
+
return DiscussionCommit(
|
| 352 |
+
**common_args,
|
| 353 |
+
summary=event["data"]["subject"],
|
| 354 |
+
oid=event["data"]["oid"],
|
| 355 |
+
)
|
| 356 |
+
if event_type == "title-change":
|
| 357 |
+
return DiscussionTitleChange(
|
| 358 |
+
**common_args,
|
| 359 |
+
old_title=event["data"]["from"],
|
| 360 |
+
new_title=event["data"]["to"],
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
return DiscussionEvent(**common_args)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/constants.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import typing
|
| 4 |
+
from typing import Literal, Optional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
# Possible values for env variables
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
ENV_VARS_TRUE_VALUES = {"1", "ON", "YES", "TRUE"}
|
| 11 |
+
ENV_VARS_TRUE_AND_AUTO_VALUES = ENV_VARS_TRUE_VALUES.union({"AUTO"})
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _is_true(value: Optional[str]) -> bool:
|
| 15 |
+
if value is None:
|
| 16 |
+
return False
|
| 17 |
+
return value.upper() in ENV_VARS_TRUE_VALUES
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _as_int(value: Optional[str]) -> Optional[int]:
|
| 21 |
+
if value is None:
|
| 22 |
+
return None
|
| 23 |
+
return int(value)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Constants for file downloads
|
| 27 |
+
|
| 28 |
+
PYTORCH_WEIGHTS_NAME = "pytorch_model.bin"
|
| 29 |
+
TF2_WEIGHTS_NAME = "tf_model.h5"
|
| 30 |
+
TF_WEIGHTS_NAME = "model.ckpt"
|
| 31 |
+
FLAX_WEIGHTS_NAME = "flax_model.msgpack"
|
| 32 |
+
CONFIG_NAME = "config.json"
|
| 33 |
+
REPOCARD_NAME = "README.md"
|
| 34 |
+
EVAL_RESULTS_FOLDER = ".eval_results"
|
| 35 |
+
DEFAULT_ETAG_TIMEOUT = 10
|
| 36 |
+
DEFAULT_DOWNLOAD_TIMEOUT = 10
|
| 37 |
+
DEFAULT_REQUEST_TIMEOUT = 10
|
| 38 |
+
DOWNLOAD_CHUNK_SIZE = 10 * 1024 * 1024
|
| 39 |
+
MAX_HTTP_DOWNLOAD_SIZE = 50 * 1000 * 1000 * 1000 # 50 GB
|
| 40 |
+
|
| 41 |
+
# Constants for serialization
|
| 42 |
+
|
| 43 |
+
PYTORCH_WEIGHTS_FILE_PATTERN = "pytorch_model{suffix}.bin" # Unsafe pickle: use safetensors instead
|
| 44 |
+
SAFETENSORS_WEIGHTS_FILE_PATTERN = "model{suffix}.safetensors"
|
| 45 |
+
TF2_WEIGHTS_FILE_PATTERN = "tf_model{suffix}.h5"
|
| 46 |
+
|
| 47 |
+
# Constants for safetensors repos
|
| 48 |
+
|
| 49 |
+
SAFETENSORS_SINGLE_FILE = "model.safetensors"
|
| 50 |
+
SAFETENSORS_INDEX_FILE = "model.safetensors.index.json"
|
| 51 |
+
SAFETENSORS_MAX_HEADER_LENGTH = 25_000_000
|
| 52 |
+
|
| 53 |
+
# Timeout of aquiring file lock and logging the attempt
|
| 54 |
+
FILELOCK_LOG_EVERY_SECONDS = 10
|
| 55 |
+
|
| 56 |
+
# Git-related constants
|
| 57 |
+
|
| 58 |
+
DEFAULT_REVISION = "main"
|
| 59 |
+
REGEX_COMMIT_OID = re.compile(r"[A-Fa-f0-9]{5,40}")
|
| 60 |
+
|
| 61 |
+
HUGGINGFACE_CO_URL_HOME = "https://huggingface.co/"
|
| 62 |
+
|
| 63 |
+
_staging_mode = _is_true(os.environ.get("HUGGINGFACE_CO_STAGING"))
|
| 64 |
+
|
| 65 |
+
_HF_DEFAULT_ENDPOINT = "https://huggingface.co"
|
| 66 |
+
_HF_DEFAULT_STAGING_ENDPOINT = "https://hub-ci.huggingface.co"
|
| 67 |
+
ENDPOINT = os.getenv("HF_ENDPOINT", _HF_DEFAULT_ENDPOINT).rstrip("/")
|
| 68 |
+
HUGGINGFACE_CO_URL_TEMPLATE = ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
|
| 69 |
+
|
| 70 |
+
if _staging_mode:
|
| 71 |
+
ENDPOINT = _HF_DEFAULT_STAGING_ENDPOINT
|
| 72 |
+
HUGGINGFACE_CO_URL_TEMPLATE = _HF_DEFAULT_STAGING_ENDPOINT + "/{repo_id}/resolve/{revision}/{filename}"
|
| 73 |
+
|
| 74 |
+
DATASETS_SERVER_ENDPOINT = "https://datasets-server.huggingface.co"
|
| 75 |
+
|
| 76 |
+
HUGGINGFACE_HEADER_X_REPO_COMMIT = "X-Repo-Commit"
|
| 77 |
+
HUGGINGFACE_HEADER_X_LINKED_ETAG = "X-Linked-Etag"
|
| 78 |
+
HUGGINGFACE_HEADER_X_LINKED_SIZE = "X-Linked-Size"
|
| 79 |
+
HUGGINGFACE_HEADER_X_BILL_TO = "X-HF-Bill-To"
|
| 80 |
+
|
| 81 |
+
INFERENCE_ENDPOINT = os.environ.get("HF_INFERENCE_ENDPOINT", "https://api-inference.huggingface.co")
|
| 82 |
+
|
| 83 |
+
# See https://huggingface.co/docs/inference-endpoints/index
|
| 84 |
+
INFERENCE_ENDPOINTS_ENDPOINT = "https://api.endpoints.huggingface.cloud/v2"
|
| 85 |
+
INFERENCE_CATALOG_ENDPOINT = "https://endpoints.huggingface.co/api/catalog"
|
| 86 |
+
|
| 87 |
+
# See https://api.endpoints.huggingface.cloud/#post-/v2/endpoint/-namespace-
|
| 88 |
+
INFERENCE_ENDPOINT_IMAGE_KEYS = [
|
| 89 |
+
"custom",
|
| 90 |
+
"huggingface",
|
| 91 |
+
"huggingfaceNeuron",
|
| 92 |
+
"llamacpp",
|
| 93 |
+
"tei",
|
| 94 |
+
"tgi",
|
| 95 |
+
"tgiNeuron",
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
# Proxy for third-party providers
|
| 99 |
+
INFERENCE_PROXY_TEMPLATE = "https://router.huggingface.co/{provider}"
|
| 100 |
+
|
| 101 |
+
REPO_ID_SEPARATOR = "--"
|
| 102 |
+
# ^ this substring is not allowed in repo_ids on hf.co
|
| 103 |
+
# and is the canonical one we use for serialization of repo ids elsewhere.
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
REPO_TYPE_DATASET = "dataset"
|
| 107 |
+
REPO_TYPE_SPACE = "space"
|
| 108 |
+
REPO_TYPE_MODEL = "model"
|
| 109 |
+
REPO_TYPES = [None, REPO_TYPE_MODEL, REPO_TYPE_DATASET, REPO_TYPE_SPACE]
|
| 110 |
+
SPACES_SDK_TYPES = ["gradio", "streamlit", "docker", "static"]
|
| 111 |
+
|
| 112 |
+
REPO_TYPES_URL_PREFIXES = {
|
| 113 |
+
REPO_TYPE_DATASET: "datasets/",
|
| 114 |
+
REPO_TYPE_SPACE: "spaces/",
|
| 115 |
+
}
|
| 116 |
+
REPO_TYPES_MAPPING = {
|
| 117 |
+
"datasets": REPO_TYPE_DATASET,
|
| 118 |
+
"spaces": REPO_TYPE_SPACE,
|
| 119 |
+
"models": REPO_TYPE_MODEL,
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
DiscussionTypeFilter = Literal["all", "discussion", "pull_request"]
|
| 123 |
+
DISCUSSION_TYPES: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionTypeFilter)
|
| 124 |
+
DiscussionStatusFilter = Literal["all", "open", "closed"]
|
| 125 |
+
DISCUSSION_STATUS: tuple[DiscussionTypeFilter, ...] = typing.get_args(DiscussionStatusFilter)
|
| 126 |
+
|
| 127 |
+
# Webhook subscription types
|
| 128 |
+
WEBHOOK_DOMAIN_T = Literal["repo", "discussions"]
|
| 129 |
+
|
| 130 |
+
# default cache
|
| 131 |
+
default_home = os.path.join(os.path.expanduser("~"), ".cache")
|
| 132 |
+
HF_HOME = os.path.expandvars(
|
| 133 |
+
os.path.expanduser(
|
| 134 |
+
os.getenv(
|
| 135 |
+
"HF_HOME",
|
| 136 |
+
os.path.join(os.getenv("XDG_CACHE_HOME", default_home), "huggingface"),
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
default_cache_path = os.path.join(HF_HOME, "hub")
|
| 142 |
+
default_assets_cache_path = os.path.join(HF_HOME, "assets")
|
| 143 |
+
|
| 144 |
+
# Legacy env variables
|
| 145 |
+
HUGGINGFACE_HUB_CACHE = os.getenv("HUGGINGFACE_HUB_CACHE", default_cache_path)
|
| 146 |
+
HUGGINGFACE_ASSETS_CACHE = os.getenv("HUGGINGFACE_ASSETS_CACHE", default_assets_cache_path)
|
| 147 |
+
|
| 148 |
+
# New env variables
|
| 149 |
+
HF_HUB_CACHE = os.path.expandvars(
|
| 150 |
+
os.path.expanduser(
|
| 151 |
+
os.getenv(
|
| 152 |
+
"HF_HUB_CACHE",
|
| 153 |
+
HUGGINGFACE_HUB_CACHE,
|
| 154 |
+
)
|
| 155 |
+
)
|
| 156 |
+
)
|
| 157 |
+
HF_ASSETS_CACHE = os.path.expandvars(
|
| 158 |
+
os.path.expanduser(
|
| 159 |
+
os.getenv(
|
| 160 |
+
"HF_ASSETS_CACHE",
|
| 161 |
+
HUGGINGFACE_ASSETS_CACHE,
|
| 162 |
+
)
|
| 163 |
+
)
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
HF_HUB_OFFLINE = _is_true(os.environ.get("HF_HUB_OFFLINE") or os.environ.get("TRANSFORMERS_OFFLINE"))
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def is_offline_mode() -> bool:
|
| 170 |
+
"""Returns whether we are in offline mode for the Hub.
|
| 171 |
+
|
| 172 |
+
When offline mode is enabled, all HTTP requests made with `get_session` will raise an `OfflineModeIsEnabled` exception.
|
| 173 |
+
|
| 174 |
+
Example:
|
| 175 |
+
```py
|
| 176 |
+
from huggingface_hub import is_offline_mode
|
| 177 |
+
|
| 178 |
+
def list_files(repo_id: str):
|
| 179 |
+
if is_offline_mode():
|
| 180 |
+
... # list files from local cache (degraded experience but still functional)
|
| 181 |
+
else:
|
| 182 |
+
... # list files from Hub (complete experience)
|
| 183 |
+
```
|
| 184 |
+
"""
|
| 185 |
+
return HF_HUB_OFFLINE
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# File created to mark that the version check has been done.
|
| 189 |
+
# Check is performed once per 24 hours at most.
|
| 190 |
+
CHECK_FOR_UPDATE_DONE_PATH = os.path.join(HF_HOME, ".check_for_update_done")
|
| 191 |
+
|
| 192 |
+
# If set, log level will be set to DEBUG and all requests made to the Hub will be logged
|
| 193 |
+
# as curl commands for reproducibility.
|
| 194 |
+
HF_DEBUG = _is_true(os.environ.get("HF_DEBUG"))
|
| 195 |
+
|
| 196 |
+
# Opt-out from telemetry requests
|
| 197 |
+
HF_HUB_DISABLE_TELEMETRY = (
|
| 198 |
+
_is_true(os.environ.get("HF_HUB_DISABLE_TELEMETRY")) # HF-specific env variable
|
| 199 |
+
or _is_true(os.environ.get("DISABLE_TELEMETRY"))
|
| 200 |
+
or _is_true(os.environ.get("DO_NOT_TRACK")) # https://consoledonottrack.com/
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
HF_TOKEN_PATH = os.path.expandvars(
|
| 204 |
+
os.path.expanduser(
|
| 205 |
+
os.getenv(
|
| 206 |
+
"HF_TOKEN_PATH",
|
| 207 |
+
os.path.join(HF_HOME, "token"),
|
| 208 |
+
)
|
| 209 |
+
)
|
| 210 |
+
)
|
| 211 |
+
HF_STORED_TOKENS_PATH = os.path.join(os.path.dirname(HF_TOKEN_PATH), "stored_tokens")
|
| 212 |
+
|
| 213 |
+
if _staging_mode:
|
| 214 |
+
# In staging mode, we use a different cache to ensure we don't mix up production and staging data or tokens
|
| 215 |
+
# In practice in `huggingface_hub` tests, we monkeypatch these values with temporary directories. The following
|
| 216 |
+
# lines are only used in third-party libraries tests (e.g. `transformers`, `diffusers`, etc.).
|
| 217 |
+
_staging_home = os.path.join(os.path.expanduser("~"), ".cache", "huggingface_staging")
|
| 218 |
+
HUGGINGFACE_HUB_CACHE = os.path.join(_staging_home, "hub")
|
| 219 |
+
HF_TOKEN_PATH = os.path.join(_staging_home, "token")
|
| 220 |
+
|
| 221 |
+
# Here, `True` will disable progress bars globally without possibility of enabling it
|
| 222 |
+
# programmatically. `False` will enable them without possibility of disabling them.
|
| 223 |
+
# If environment variable is not set (None), then the user is free to enable/disable
|
| 224 |
+
# them programmatically.
|
| 225 |
+
# TL;DR: env variable has priority over code
|
| 226 |
+
__HF_HUB_DISABLE_PROGRESS_BARS = os.environ.get("HF_HUB_DISABLE_PROGRESS_BARS")
|
| 227 |
+
HF_HUB_DISABLE_PROGRESS_BARS: Optional[bool] = (
|
| 228 |
+
_is_true(__HF_HUB_DISABLE_PROGRESS_BARS) if __HF_HUB_DISABLE_PROGRESS_BARS is not None else None
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
# Disable warning on machines that do not support symlinks (e.g. Windows non-developer)
|
| 232 |
+
HF_HUB_DISABLE_SYMLINKS_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_SYMLINKS_WARNING"))
|
| 233 |
+
|
| 234 |
+
# Disable warning when using experimental features
|
| 235 |
+
HF_HUB_DISABLE_EXPERIMENTAL_WARNING: bool = _is_true(os.environ.get("HF_HUB_DISABLE_EXPERIMENTAL_WARNING"))
|
| 236 |
+
|
| 237 |
+
# Disable sending the cached token by default is all HTTP requests to the Hub
|
| 238 |
+
HF_HUB_DISABLE_IMPLICIT_TOKEN: bool = _is_true(os.environ.get("HF_HUB_DISABLE_IMPLICIT_TOKEN"))
|
| 239 |
+
|
| 240 |
+
HF_XET_HIGH_PERFORMANCE: bool = _is_true(os.environ.get("HF_XET_HIGH_PERFORMANCE"))
|
| 241 |
+
|
| 242 |
+
# hf_transfer is not used anymore. Let's warn user is case they set the env variable
|
| 243 |
+
if _is_true(os.environ.get("HF_HUB_ENABLE_HF_TRANSFER")) and not HF_XET_HIGH_PERFORMANCE:
|
| 244 |
+
import warnings
|
| 245 |
+
|
| 246 |
+
warnings.warn(
|
| 247 |
+
"The `HF_HUB_ENABLE_HF_TRANSFER` environment variable is deprecated as 'hf_transfer' is not used anymore. "
|
| 248 |
+
"Please use `HF_XET_HIGH_PERFORMANCE` instead to enable high performance transfer with Xet. "
|
| 249 |
+
"Visit https://huggingface.co/docs/huggingface_hub/package_reference/environment_variables#hfxethighperformance for more details.",
|
| 250 |
+
DeprecationWarning,
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
# Used to override the etag timeout on a system level
|
| 254 |
+
HF_HUB_ETAG_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_ETAG_TIMEOUT")) or DEFAULT_ETAG_TIMEOUT
|
| 255 |
+
|
| 256 |
+
# Used to override the get request timeout on a system level
|
| 257 |
+
# Also used as a default timeout for other requests if not specified (kept the naming for legacy reasons)
|
| 258 |
+
HF_HUB_DOWNLOAD_TIMEOUT: int = _as_int(os.environ.get("HF_HUB_DOWNLOAD_TIMEOUT")) or DEFAULT_DOWNLOAD_TIMEOUT
|
| 259 |
+
|
| 260 |
+
# Allows to add information about the requester in the user-agent (e.g. partner name)
|
| 261 |
+
HF_HUB_USER_AGENT_ORIGIN: Optional[str] = os.environ.get("HF_HUB_USER_AGENT_ORIGIN")
|
| 262 |
+
|
| 263 |
+
# If OAuth didn't work after 2 redirects, there's likely a third-party cookie issue in the Space iframe view.
|
| 264 |
+
# In this case, we redirect the user to the non-iframe view.
|
| 265 |
+
OAUTH_MAX_REDIRECTS = 2
|
| 266 |
+
|
| 267 |
+
# OAuth-related environment variables injected by the Space
|
| 268 |
+
OAUTH_CLIENT_ID = os.environ.get("OAUTH_CLIENT_ID")
|
| 269 |
+
OAUTH_CLIENT_SECRET = os.environ.get("OAUTH_CLIENT_SECRET")
|
| 270 |
+
OAUTH_SCOPES = os.environ.get("OAUTH_SCOPES")
|
| 271 |
+
OPENID_PROVIDER_URL = os.environ.get("OPENID_PROVIDER_URL")
|
| 272 |
+
|
| 273 |
+
# Xet constants
|
| 274 |
+
HUGGINGFACE_HEADER_X_XET_ENDPOINT = "X-Xet-Cas-Url"
|
| 275 |
+
HUGGINGFACE_HEADER_X_XET_ACCESS_TOKEN = "X-Xet-Access-Token"
|
| 276 |
+
HUGGINGFACE_HEADER_X_XET_EXPIRATION = "X-Xet-Token-Expiration"
|
| 277 |
+
HUGGINGFACE_HEADER_X_XET_HASH = "X-Xet-Hash"
|
| 278 |
+
HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTE = "X-Xet-Refresh-Route"
|
| 279 |
+
HUGGINGFACE_HEADER_LINK_XET_AUTH_KEY = "xet-auth"
|
| 280 |
+
|
| 281 |
+
default_xet_cache_path = os.path.join(HF_HOME, "xet")
|
| 282 |
+
HF_XET_CACHE = os.getenv("HF_XET_CACHE", default_xet_cache_path)
|
| 283 |
+
HF_HUB_DISABLE_XET: bool = _is_true(os.environ.get("HF_HUB_DISABLE_XET"))
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/dataclasses.py
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections.abc
|
| 2 |
+
import inspect
|
| 3 |
+
import sys
|
| 4 |
+
import types
|
| 5 |
+
from dataclasses import _MISSING_TYPE, MISSING, Field, field, fields, make_dataclass
|
| 6 |
+
from functools import lru_cache, wraps
|
| 7 |
+
from typing import (
|
| 8 |
+
Annotated,
|
| 9 |
+
Any,
|
| 10 |
+
Callable,
|
| 11 |
+
ForwardRef,
|
| 12 |
+
Literal,
|
| 13 |
+
Optional,
|
| 14 |
+
Type,
|
| 15 |
+
TypeVar,
|
| 16 |
+
Union,
|
| 17 |
+
get_args,
|
| 18 |
+
get_origin,
|
| 19 |
+
overload,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
# Python 3.11+
|
| 25 |
+
from typing import NotRequired, Required # type: ignore
|
| 26 |
+
except ImportError:
|
| 27 |
+
try:
|
| 28 |
+
# In case typing_extensions is installed
|
| 29 |
+
from typing_extensions import NotRequired, Required # type: ignore
|
| 30 |
+
except ImportError:
|
| 31 |
+
# Fallback: create dummy types that will never match
|
| 32 |
+
Required = type("Required", (), {}) # type: ignore
|
| 33 |
+
NotRequired = type("NotRequired", (), {}) # type: ignore
|
| 34 |
+
|
| 35 |
+
from .errors import (
|
| 36 |
+
StrictDataclassClassValidationError,
|
| 37 |
+
StrictDataclassDefinitionError,
|
| 38 |
+
StrictDataclassFieldValidationError,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
Validator_T = Callable[[Any], None]
|
| 43 |
+
T = TypeVar("T")
|
| 44 |
+
TypedDictType = TypeVar("TypedDictType", bound=dict[str, Any])
|
| 45 |
+
|
| 46 |
+
_TYPED_DICT_DEFAULT_VALUE = object() # used as default value in TypedDict fields (to distinguish from None)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
# The overload decorator helps type checkers understand the different return types
|
| 50 |
+
@overload
|
| 51 |
+
def strict(cls: Type[T]) -> Type[T]: ...
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@overload
|
| 55 |
+
def strict(*, accept_kwargs: bool = False) -> Callable[[Type[T]], Type[T]]: ...
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def strict(
|
| 59 |
+
cls: Optional[Type[T]] = None, *, accept_kwargs: bool = False
|
| 60 |
+
) -> Union[Type[T], Callable[[Type[T]], Type[T]]]:
|
| 61 |
+
"""
|
| 62 |
+
Decorator to add strict validation to a dataclass.
|
| 63 |
+
|
| 64 |
+
This decorator must be used on top of `@dataclass` to ensure IDEs and static typing tools
|
| 65 |
+
recognize the class as a dataclass.
|
| 66 |
+
|
| 67 |
+
Can be used with or without arguments:
|
| 68 |
+
- `@strict`
|
| 69 |
+
- `@strict(accept_kwargs=True)`
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
cls:
|
| 73 |
+
The class to convert to a strict dataclass.
|
| 74 |
+
accept_kwargs (`bool`, *optional*):
|
| 75 |
+
If True, allows arbitrary keyword arguments in `__init__`. Defaults to False.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
The enhanced dataclass with strict validation on field assignment.
|
| 79 |
+
|
| 80 |
+
Example:
|
| 81 |
+
```py
|
| 82 |
+
>>> from dataclasses import dataclass
|
| 83 |
+
>>> from huggingface_hub.dataclasses import as_validated_field, strict, validated_field
|
| 84 |
+
|
| 85 |
+
>>> @as_validated_field
|
| 86 |
+
>>> def positive_int(value: int):
|
| 87 |
+
... if not value >= 0:
|
| 88 |
+
... raise ValueError(f"Value must be positive, got {value}")
|
| 89 |
+
|
| 90 |
+
>>> @strict(accept_kwargs=True)
|
| 91 |
+
... @dataclass
|
| 92 |
+
... class User:
|
| 93 |
+
... name: str
|
| 94 |
+
... age: int = positive_int(default=10)
|
| 95 |
+
|
| 96 |
+
# Initialize
|
| 97 |
+
>>> User(name="John")
|
| 98 |
+
User(name='John', age=10)
|
| 99 |
+
|
| 100 |
+
# Extra kwargs are accepted
|
| 101 |
+
>>> User(name="John", age=30, lastname="Doe")
|
| 102 |
+
User(name='John', age=30, *lastname='Doe')
|
| 103 |
+
|
| 104 |
+
# Invalid type => raises
|
| 105 |
+
>>> User(name="John", age="30")
|
| 106 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 107 |
+
TypeError: Field 'age' expected int, got str (value: '30')
|
| 108 |
+
|
| 109 |
+
# Invalid value => raises
|
| 110 |
+
>>> User(name="John", age=-1)
|
| 111 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 112 |
+
ValueError: Value must be positive, got -1
|
| 113 |
+
```
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
def wrap(cls: Type[T]) -> Type[T]:
|
| 117 |
+
if not hasattr(cls, "__dataclass_fields__"):
|
| 118 |
+
raise StrictDataclassDefinitionError(
|
| 119 |
+
f"Class '{cls.__name__}' must be a dataclass before applying @strict."
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
# List and store validators
|
| 123 |
+
field_validators: dict[str, list[Validator_T]] = {}
|
| 124 |
+
for f in fields(cls): # type: ignore [arg-type]
|
| 125 |
+
validators = []
|
| 126 |
+
validators.append(_create_type_validator(f))
|
| 127 |
+
custom_validator = f.metadata.get("validator")
|
| 128 |
+
if custom_validator is not None:
|
| 129 |
+
if not isinstance(custom_validator, list):
|
| 130 |
+
custom_validator = [custom_validator]
|
| 131 |
+
for validator in custom_validator:
|
| 132 |
+
if not _is_validator(validator):
|
| 133 |
+
raise StrictDataclassDefinitionError(
|
| 134 |
+
f"Invalid validator for field '{f.name}': {validator}. Must be a callable taking a single argument."
|
| 135 |
+
)
|
| 136 |
+
validators.extend(custom_validator)
|
| 137 |
+
field_validators[f.name] = validators
|
| 138 |
+
cls.__validators__ = field_validators # type: ignore
|
| 139 |
+
|
| 140 |
+
# Override __setattr__ to validate fields on assignment
|
| 141 |
+
original_setattr = cls.__setattr__
|
| 142 |
+
|
| 143 |
+
def __strict_setattr__(self: Any, name: str, value: Any) -> None:
|
| 144 |
+
"""Custom __setattr__ method for strict dataclasses."""
|
| 145 |
+
# Run all validators
|
| 146 |
+
for validator in self.__validators__.get(name, []):
|
| 147 |
+
try:
|
| 148 |
+
validator(value)
|
| 149 |
+
except (ValueError, TypeError) as e:
|
| 150 |
+
raise StrictDataclassFieldValidationError(field=name, cause=e) from e
|
| 151 |
+
|
| 152 |
+
# If validation passed, set the attribute
|
| 153 |
+
original_setattr(self, name, value)
|
| 154 |
+
|
| 155 |
+
cls.__setattr__ = __strict_setattr__ # type: ignore[method-assign]
|
| 156 |
+
|
| 157 |
+
if accept_kwargs:
|
| 158 |
+
# (optional) Override __init__ to accept arbitrary keyword arguments
|
| 159 |
+
original_init = cls.__init__
|
| 160 |
+
|
| 161 |
+
@wraps(original_init)
|
| 162 |
+
def __init__(self, *args, **kwargs: Any) -> None:
|
| 163 |
+
# Extract only the fields that are part of the dataclass
|
| 164 |
+
dataclass_fields = {f.name for f in fields(cls)} # type: ignore [arg-type]
|
| 165 |
+
standard_kwargs = {k: v for k, v in kwargs.items() if k in dataclass_fields}
|
| 166 |
+
|
| 167 |
+
# User shouldn't define custom `__init__` when `accepts_kwargs`, and instead
|
| 168 |
+
# are advised to move field manipulation to `__post_init__` (e.g., derive new field from existing ones)
|
| 169 |
+
# We need to call bare `__init__` here without `__post_init__` but the``original_init`` would call
|
| 170 |
+
# post-init right away with no kwargs.
|
| 171 |
+
if len(args) > 0:
|
| 172 |
+
raise ValueError(
|
| 173 |
+
f"When `accept_kwargs=True`, {cls.__name__} accepts only keyword arguments, "
|
| 174 |
+
f"but found `{len(args)}` positional args."
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
for f in fields(cls): # type: ignore
|
| 178 |
+
if f.name in standard_kwargs:
|
| 179 |
+
setattr(self, f.name, standard_kwargs[f.name])
|
| 180 |
+
elif f.default is not MISSING:
|
| 181 |
+
setattr(self, f.name, f.default)
|
| 182 |
+
elif f.default_factory is not MISSING:
|
| 183 |
+
setattr(self, f.name, f.default_factory())
|
| 184 |
+
else:
|
| 185 |
+
raise TypeError(f"Missing required field - '{f.name}'")
|
| 186 |
+
|
| 187 |
+
# Pass any additional kwargs to `__post_init__` and let the object
|
| 188 |
+
# decide whether to set the attr or use for different purposes (e.g. BC checks)
|
| 189 |
+
additional_kwargs = {}
|
| 190 |
+
for name, value in kwargs.items():
|
| 191 |
+
if name not in dataclass_fields:
|
| 192 |
+
additional_kwargs[name] = value
|
| 193 |
+
|
| 194 |
+
self.__post_init__(**additional_kwargs)
|
| 195 |
+
|
| 196 |
+
cls.__init__ = __init__ # type: ignore[method-assign]
|
| 197 |
+
|
| 198 |
+
# Define a default __post_init__ if not defined
|
| 199 |
+
if not hasattr(cls, "__post_init__"):
|
| 200 |
+
|
| 201 |
+
def __post_init__(self, **kwargs: Any) -> None:
|
| 202 |
+
"""Default __post_init__ to accept additional kwargs."""
|
| 203 |
+
for name, value in kwargs.items():
|
| 204 |
+
setattr(self, name, value)
|
| 205 |
+
|
| 206 |
+
cls.__post_init__ = __post_init__ # type: ignore
|
| 207 |
+
|
| 208 |
+
# (optional) Override __repr__ to include additional kwargs
|
| 209 |
+
original_repr = cls.__repr__
|
| 210 |
+
|
| 211 |
+
@wraps(original_repr)
|
| 212 |
+
def __repr__(self) -> str:
|
| 213 |
+
# Call the original __repr__ to get the standard fields
|
| 214 |
+
standard_repr = original_repr(self)
|
| 215 |
+
|
| 216 |
+
# Get additional kwargs
|
| 217 |
+
additional_kwargs = [
|
| 218 |
+
# add a '*' in front of additional kwargs to let the user know they are not part of the dataclass
|
| 219 |
+
f"*{k}={v!r}"
|
| 220 |
+
for k, v in self.__dict__.items()
|
| 221 |
+
if k not in cls.__dataclass_fields__ # type: ignore [attr-defined]
|
| 222 |
+
]
|
| 223 |
+
additional_repr = ", ".join(additional_kwargs)
|
| 224 |
+
|
| 225 |
+
# Combine both representations
|
| 226 |
+
return f"{standard_repr[:-1]}, {additional_repr})" if additional_kwargs else standard_repr
|
| 227 |
+
|
| 228 |
+
if cls.__dataclass_params__.repr is True: # type: ignore [attr-defined]
|
| 229 |
+
cls.__repr__ = __repr__ # type: ignore [method-assign]
|
| 230 |
+
|
| 231 |
+
# List all public methods starting with `validate_` => class validators.
|
| 232 |
+
class_validators = []
|
| 233 |
+
|
| 234 |
+
for name in dir(cls):
|
| 235 |
+
if not name.startswith("validate_"):
|
| 236 |
+
continue
|
| 237 |
+
method = getattr(cls, name)
|
| 238 |
+
if not callable(method):
|
| 239 |
+
continue
|
| 240 |
+
if len(inspect.signature(method).parameters) != 1:
|
| 241 |
+
raise StrictDataclassDefinitionError(
|
| 242 |
+
f"Class '{cls.__name__}' has a class validator '{name}' that takes more than one argument."
|
| 243 |
+
" Class validators must take only 'self' as an argument. Methods starting with 'validate_'"
|
| 244 |
+
" are considered to be class validators."
|
| 245 |
+
)
|
| 246 |
+
class_validators.append(method)
|
| 247 |
+
|
| 248 |
+
cls.__class_validators__ = class_validators # type: ignore [attr-defined]
|
| 249 |
+
|
| 250 |
+
# Add `validate` method to the class, but first check if it already exists
|
| 251 |
+
def validate(self: T) -> None:
|
| 252 |
+
"""Run class validators on the instance."""
|
| 253 |
+
for validator in cls.__class_validators__: # type: ignore [attr-defined]
|
| 254 |
+
try:
|
| 255 |
+
validator(self)
|
| 256 |
+
except (ValueError, TypeError) as e:
|
| 257 |
+
raise StrictDataclassClassValidationError(validator=validator.__name__, cause=e) from e
|
| 258 |
+
|
| 259 |
+
# Hack to be able to raise if `.validate()` already exists except if it was created by this decorator on a parent class
|
| 260 |
+
# (in which case we just override it)
|
| 261 |
+
validate.__is_defined_by_strict_decorator__ = True # type: ignore [attr-defined]
|
| 262 |
+
|
| 263 |
+
if hasattr(cls, "validate"):
|
| 264 |
+
if not getattr(cls.validate, "__is_defined_by_strict_decorator__", False): # type: ignore [attr-defined]
|
| 265 |
+
raise StrictDataclassDefinitionError(
|
| 266 |
+
f"Class '{cls.__name__}' already implements a method called 'validate'."
|
| 267 |
+
" This method name is reserved when using the @strict decorator on a dataclass."
|
| 268 |
+
" If you want to keep your own method, please rename it."
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
cls.validate = validate # type: ignore
|
| 272 |
+
|
| 273 |
+
# Run class validators after initialization
|
| 274 |
+
initial_init = cls.__init__
|
| 275 |
+
|
| 276 |
+
@wraps(initial_init)
|
| 277 |
+
def init_with_validate(self, *args, **kwargs) -> None:
|
| 278 |
+
"""Run class validators after initialization."""
|
| 279 |
+
initial_init(self, *args, **kwargs) # type: ignore [call-arg]
|
| 280 |
+
cls.validate(self) # type: ignore [attr-defined]
|
| 281 |
+
|
| 282 |
+
setattr(cls, "__init__", init_with_validate)
|
| 283 |
+
|
| 284 |
+
return cls
|
| 285 |
+
|
| 286 |
+
# Return wrapped class or the decorator itself
|
| 287 |
+
return wrap(cls) if cls is not None else wrap
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def validate_typed_dict(schema: type[TypedDictType], data: dict) -> None:
|
| 291 |
+
"""
|
| 292 |
+
Validate that a dictionary conforms to the types defined in a TypedDict class.
|
| 293 |
+
|
| 294 |
+
Under the hood, the typed dict is converted to a strict dataclass and validated using the `@strict` decorator.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
schema (`type[TypedDictType]`):
|
| 298 |
+
The TypedDict class defining the expected structure and types.
|
| 299 |
+
data (`dict`):
|
| 300 |
+
The dictionary to validate.
|
| 301 |
+
|
| 302 |
+
Raises:
|
| 303 |
+
`StrictDataclassFieldValidationError`:
|
| 304 |
+
If any field in the dictionary does not conform to the expected type.
|
| 305 |
+
|
| 306 |
+
Example:
|
| 307 |
+
```py
|
| 308 |
+
>>> from typing import Annotated, TypedDict
|
| 309 |
+
>>> from huggingface_hub.dataclasses import validate_typed_dict
|
| 310 |
+
|
| 311 |
+
>>> def positive_int(value: int):
|
| 312 |
+
... if not value >= 0:
|
| 313 |
+
... raise ValueError(f"Value must be positive, got {value}")
|
| 314 |
+
|
| 315 |
+
>>> class User(TypedDict):
|
| 316 |
+
... name: str
|
| 317 |
+
... age: Annotated[int, positive_int]
|
| 318 |
+
|
| 319 |
+
>>> # Valid data
|
| 320 |
+
>>> validate_typed_dict(User, {"name": "John", "age": 30})
|
| 321 |
+
|
| 322 |
+
>>> # Invalid type for age
|
| 323 |
+
>>> validate_typed_dict(User, {"name": "John", "age": "30"})
|
| 324 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 325 |
+
TypeError: Field 'age' expected int, got str (value: '30')
|
| 326 |
+
|
| 327 |
+
>>> # Invalid value for age
|
| 328 |
+
>>> validate_typed_dict(User, {"name": "John", "age": -1})
|
| 329 |
+
huggingface_hub.errors.StrictDataclassFieldValidationError: Validation error for field 'age':
|
| 330 |
+
ValueError: Value must be positive, got -1
|
| 331 |
+
```
|
| 332 |
+
"""
|
| 333 |
+
# Convert typed dict to dataclass
|
| 334 |
+
strict_cls = _build_strict_cls_from_typed_dict(schema)
|
| 335 |
+
|
| 336 |
+
# Validate the data by instantiating the strict dataclass
|
| 337 |
+
strict_cls(**data) # will raise if validation fails
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@lru_cache
|
| 341 |
+
def _build_strict_cls_from_typed_dict(schema: type[TypedDictType]) -> Type:
|
| 342 |
+
# Extract type hints from the TypedDict class
|
| 343 |
+
type_hints = _get_typed_dict_annotations(schema)
|
| 344 |
+
|
| 345 |
+
# If the TypedDict is not total, wrap fields as NotRequired (unless explicitly Required or NotRequired)
|
| 346 |
+
if not getattr(schema, "__total__", True):
|
| 347 |
+
for key, value in type_hints.items():
|
| 348 |
+
origin = get_origin(value)
|
| 349 |
+
|
| 350 |
+
if origin is Annotated:
|
| 351 |
+
base, *meta = get_args(value)
|
| 352 |
+
if not _is_required_or_notrequired(base):
|
| 353 |
+
base = NotRequired[base]
|
| 354 |
+
type_hints[key] = Annotated[tuple([base] + list(meta))] # type: ignore
|
| 355 |
+
elif not _is_required_or_notrequired(value):
|
| 356 |
+
type_hints[key] = NotRequired[value]
|
| 357 |
+
|
| 358 |
+
# Convert type hints to dataclass fields
|
| 359 |
+
fields = []
|
| 360 |
+
for key, value in type_hints.items():
|
| 361 |
+
if get_origin(value) is Annotated:
|
| 362 |
+
base, *meta = get_args(value)
|
| 363 |
+
fields.append((key, base, field(default=_TYPED_DICT_DEFAULT_VALUE, metadata={"validator": meta[0]})))
|
| 364 |
+
else:
|
| 365 |
+
fields.append((key, value, field(default=_TYPED_DICT_DEFAULT_VALUE)))
|
| 366 |
+
|
| 367 |
+
# Create a strict dataclass from the TypedDict fields
|
| 368 |
+
return strict(make_dataclass(schema.__name__, fields))
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def _get_typed_dict_annotations(schema: type[TypedDictType]) -> dict[str, Any]:
|
| 372 |
+
"""Extract type annotations from a TypedDict class."""
|
| 373 |
+
try:
|
| 374 |
+
# Available in Python 3.14+
|
| 375 |
+
import annotationlib
|
| 376 |
+
|
| 377 |
+
return annotationlib.get_annotations(schema)
|
| 378 |
+
except ImportError:
|
| 379 |
+
return {
|
| 380 |
+
# We do not use `get_type_hints` here to avoid evaluating ForwardRefs (which might fail).
|
| 381 |
+
# ForwardRefs are not validated by @strict anyway.
|
| 382 |
+
name: value if value is not None else type(None)
|
| 383 |
+
for name, value in schema.__dict__.get("__annotations__", {}).items()
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def validated_field(
|
| 388 |
+
validator: Union[list[Validator_T], Validator_T],
|
| 389 |
+
default: Union[Any, _MISSING_TYPE] = MISSING,
|
| 390 |
+
default_factory: Union[Callable[[], Any], _MISSING_TYPE] = MISSING,
|
| 391 |
+
init: bool = True,
|
| 392 |
+
repr: bool = True,
|
| 393 |
+
hash: Optional[bool] = None,
|
| 394 |
+
compare: bool = True,
|
| 395 |
+
metadata: Optional[dict] = None,
|
| 396 |
+
**kwargs: Any,
|
| 397 |
+
) -> Any:
|
| 398 |
+
"""
|
| 399 |
+
Create a dataclass field with a custom validator.
|
| 400 |
+
|
| 401 |
+
Useful to apply several checks to a field. If only applying one rule, check out the [`as_validated_field`] decorator.
|
| 402 |
+
|
| 403 |
+
Args:
|
| 404 |
+
validator (`Callable` or `list[Callable]`):
|
| 405 |
+
A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
|
| 406 |
+
Can be a list of validators to apply multiple checks.
|
| 407 |
+
**kwargs:
|
| 408 |
+
Additional arguments to pass to `dataclasses.field()`.
|
| 409 |
+
|
| 410 |
+
Returns:
|
| 411 |
+
A field with the validator attached in metadata
|
| 412 |
+
"""
|
| 413 |
+
if not isinstance(validator, list):
|
| 414 |
+
validator = [validator]
|
| 415 |
+
if metadata is None:
|
| 416 |
+
metadata = {}
|
| 417 |
+
metadata["validator"] = validator
|
| 418 |
+
return field( # type: ignore
|
| 419 |
+
default=default, # type: ignore [arg-type]
|
| 420 |
+
default_factory=default_factory, # type: ignore [arg-type]
|
| 421 |
+
init=init,
|
| 422 |
+
repr=repr,
|
| 423 |
+
hash=hash,
|
| 424 |
+
compare=compare,
|
| 425 |
+
metadata=metadata,
|
| 426 |
+
**kwargs,
|
| 427 |
+
)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def as_validated_field(validator: Validator_T):
|
| 431 |
+
"""
|
| 432 |
+
Decorates a validator function as a [`validated_field`] (i.e. a dataclass field with a custom validator).
|
| 433 |
+
|
| 434 |
+
Args:
|
| 435 |
+
validator (`Callable`):
|
| 436 |
+
A method that takes a value as input and raises ValueError/TypeError if the value is invalid.
|
| 437 |
+
"""
|
| 438 |
+
|
| 439 |
+
def _inner(
|
| 440 |
+
default: Union[Any, _MISSING_TYPE] = MISSING,
|
| 441 |
+
default_factory: Union[Callable[[], Any], _MISSING_TYPE] = MISSING,
|
| 442 |
+
init: bool = True,
|
| 443 |
+
repr: bool = True,
|
| 444 |
+
hash: Optional[bool] = None,
|
| 445 |
+
compare: bool = True,
|
| 446 |
+
metadata: Optional[dict] = None,
|
| 447 |
+
**kwargs: Any,
|
| 448 |
+
):
|
| 449 |
+
return validated_field(
|
| 450 |
+
validator,
|
| 451 |
+
default=default,
|
| 452 |
+
default_factory=default_factory,
|
| 453 |
+
init=init,
|
| 454 |
+
repr=repr,
|
| 455 |
+
hash=hash,
|
| 456 |
+
compare=compare,
|
| 457 |
+
metadata=metadata,
|
| 458 |
+
**kwargs,
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
return _inner
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def type_validator(name: str, value: Any, expected_type: Any) -> None:
|
| 465 |
+
"""Validate that 'value' matches 'expected_type'."""
|
| 466 |
+
origin = get_origin(expected_type)
|
| 467 |
+
args = get_args(expected_type)
|
| 468 |
+
|
| 469 |
+
if expected_type is Any:
|
| 470 |
+
return
|
| 471 |
+
elif validator := _BASIC_TYPE_VALIDATORS.get(origin):
|
| 472 |
+
validator(name, value, args)
|
| 473 |
+
elif isinstance(expected_type, type): # simple types
|
| 474 |
+
_validate_simple_type(name, value, expected_type)
|
| 475 |
+
elif isinstance(expected_type, ForwardRef) or isinstance(expected_type, str):
|
| 476 |
+
return
|
| 477 |
+
elif origin is Required:
|
| 478 |
+
if value is _TYPED_DICT_DEFAULT_VALUE:
|
| 479 |
+
raise TypeError(f"Field '{name}' is required but missing.")
|
| 480 |
+
type_validator(name, value, args[0])
|
| 481 |
+
elif origin is NotRequired:
|
| 482 |
+
if value is _TYPED_DICT_DEFAULT_VALUE:
|
| 483 |
+
return
|
| 484 |
+
type_validator(name, value, args[0])
|
| 485 |
+
else:
|
| 486 |
+
raise TypeError(f"Unsupported type for field '{name}': {expected_type}")
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _validate_union(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 490 |
+
"""Validate that value matches one of the types in a Union."""
|
| 491 |
+
errors = []
|
| 492 |
+
for t in args:
|
| 493 |
+
try:
|
| 494 |
+
type_validator(name, value, t)
|
| 495 |
+
return # Valid if any type matches
|
| 496 |
+
except TypeError as e:
|
| 497 |
+
errors.append(str(e))
|
| 498 |
+
|
| 499 |
+
raise TypeError(
|
| 500 |
+
f"Field '{name}' with value {repr(value)} doesn't match any type in {args}. Errors: {'; '.join(errors)}"
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _validate_literal(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 505 |
+
"""Validate Literal type."""
|
| 506 |
+
if value not in args:
|
| 507 |
+
raise TypeError(f"Field '{name}' expected one of {args}, got {value}")
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def _validate_list(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 511 |
+
"""Validate list[T] type."""
|
| 512 |
+
if not isinstance(value, list):
|
| 513 |
+
raise TypeError(f"Field '{name}' expected a list, got {type(value).__name__}")
|
| 514 |
+
|
| 515 |
+
# Validate each item in the list
|
| 516 |
+
item_type = args[0]
|
| 517 |
+
for i, item in enumerate(value):
|
| 518 |
+
try:
|
| 519 |
+
type_validator(f"{name}[{i}]", item, item_type)
|
| 520 |
+
except TypeError as e:
|
| 521 |
+
raise TypeError(f"Invalid item at index {i} in list '{name}'") from e
|
| 522 |
+
|
| 523 |
+
|
| 524 |
+
def _validate_dict(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 525 |
+
"""Validate dict[K, V] type."""
|
| 526 |
+
if not isinstance(value, dict):
|
| 527 |
+
raise TypeError(f"Field '{name}' expected a dict, got {type(value).__name__}")
|
| 528 |
+
|
| 529 |
+
# Validate keys and values
|
| 530 |
+
key_type, value_type = args
|
| 531 |
+
for k, v in value.items():
|
| 532 |
+
try:
|
| 533 |
+
type_validator(f"{name}.key", k, key_type)
|
| 534 |
+
type_validator(f"{name}[{k!r}]", v, value_type)
|
| 535 |
+
except TypeError as e:
|
| 536 |
+
raise TypeError(f"Invalid key or value in dict '{name}'") from e
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _validate_tuple(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 540 |
+
"""Validate Tuple type."""
|
| 541 |
+
if not isinstance(value, tuple):
|
| 542 |
+
raise TypeError(f"Field '{name}' expected a tuple, got {type(value).__name__}")
|
| 543 |
+
|
| 544 |
+
# Handle variable-length tuples: tuple[T, ...]
|
| 545 |
+
if len(args) == 2 and args[1] is Ellipsis:
|
| 546 |
+
for i, item in enumerate(value):
|
| 547 |
+
try:
|
| 548 |
+
type_validator(f"{name}[{i}]", item, args[0])
|
| 549 |
+
except TypeError as e:
|
| 550 |
+
raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
|
| 551 |
+
# Handle fixed-length tuples: tuple[T1, T2, ...]
|
| 552 |
+
elif len(args) != len(value):
|
| 553 |
+
raise TypeError(f"Field '{name}' expected a tuple of length {len(args)}, got {len(value)}")
|
| 554 |
+
else:
|
| 555 |
+
for i, (item, expected) in enumerate(zip(value, args)):
|
| 556 |
+
try:
|
| 557 |
+
type_validator(f"{name}[{i}]", item, expected)
|
| 558 |
+
except TypeError as e:
|
| 559 |
+
raise TypeError(f"Invalid item at index {i} in tuple '{name}'") from e
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _validate_set(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 563 |
+
"""Validate set[T] type."""
|
| 564 |
+
if not isinstance(value, set):
|
| 565 |
+
raise TypeError(f"Field '{name}' expected a set, got {type(value).__name__}")
|
| 566 |
+
|
| 567 |
+
# Validate each item in the set
|
| 568 |
+
item_type = args[0]
|
| 569 |
+
for i, item in enumerate(value):
|
| 570 |
+
try:
|
| 571 |
+
type_validator(f"{name} item", item, item_type)
|
| 572 |
+
except TypeError as e:
|
| 573 |
+
raise TypeError(f"Invalid item in set '{name}'") from e
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _validate_sequence(name: str, value: Any, args: tuple[Any, ...]) -> None:
|
| 577 |
+
"""Validate Sequence or Sequence[T] type."""
|
| 578 |
+
if not isinstance(value, collections.abc.Sequence):
|
| 579 |
+
raise TypeError(f"Field '{name}' expected a Sequence, got {type(value).__name__}")
|
| 580 |
+
|
| 581 |
+
# If no type argument is provided (i.e., just `Sequence`), skip item validation
|
| 582 |
+
if not args:
|
| 583 |
+
return
|
| 584 |
+
|
| 585 |
+
# Validate each item in the sequence
|
| 586 |
+
item_type = args[0]
|
| 587 |
+
for i, item in enumerate(value):
|
| 588 |
+
try:
|
| 589 |
+
type_validator(f"{name}[{i}]", item, item_type)
|
| 590 |
+
except TypeError as e:
|
| 591 |
+
raise TypeError(f"Invalid item at index {i} in sequence '{name}'") from e
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def _validate_simple_type(name: str, value: Any, expected_type: type) -> None:
|
| 595 |
+
"""Validate simple type (int, str, etc.)."""
|
| 596 |
+
if not isinstance(value, expected_type):
|
| 597 |
+
raise TypeError(
|
| 598 |
+
f"Field '{name}' expected {expected_type.__name__}, got {type(value).__name__} (value: {repr(value)})"
|
| 599 |
+
)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def _create_type_validator(field: Field) -> Validator_T:
|
| 603 |
+
"""Create a type validator function for a field."""
|
| 604 |
+
# Hacky: we cannot use a lambda here because of reference issues
|
| 605 |
+
|
| 606 |
+
def validator(value: Any) -> None:
|
| 607 |
+
type_validator(field.name, value, field.type)
|
| 608 |
+
|
| 609 |
+
return validator
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def _is_validator(validator: Any) -> bool:
|
| 613 |
+
"""Check if a function is a validator.
|
| 614 |
+
|
| 615 |
+
A validator is a Callable that can be called with a single positional argument.
|
| 616 |
+
The validator can have more arguments with default values.
|
| 617 |
+
|
| 618 |
+
Basically, returns True if `validator(value)` is possible.
|
| 619 |
+
"""
|
| 620 |
+
if not callable(validator):
|
| 621 |
+
return False
|
| 622 |
+
|
| 623 |
+
signature = inspect.signature(validator)
|
| 624 |
+
parameters = list(signature.parameters.values())
|
| 625 |
+
if len(parameters) == 0:
|
| 626 |
+
return False
|
| 627 |
+
if parameters[0].kind not in (
|
| 628 |
+
inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
| 629 |
+
inspect.Parameter.POSITIONAL_ONLY,
|
| 630 |
+
inspect.Parameter.VAR_POSITIONAL,
|
| 631 |
+
):
|
| 632 |
+
return False
|
| 633 |
+
for parameter in parameters[1:]:
|
| 634 |
+
if parameter.default == inspect.Parameter.empty:
|
| 635 |
+
return False
|
| 636 |
+
return True
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def _is_required_or_notrequired(type_hint: Any) -> bool:
|
| 640 |
+
"""Helper to check if a type is Required/NotRequired."""
|
| 641 |
+
return type_hint in (Required, NotRequired) or (get_origin(type_hint) in (Required, NotRequired))
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
_BASIC_TYPE_VALIDATORS: dict[Any, Callable[[str, Any, tuple[Any, ...]], None]] = {
|
| 645 |
+
Union: _validate_union,
|
| 646 |
+
Literal: _validate_literal,
|
| 647 |
+
list: _validate_list,
|
| 648 |
+
dict: _validate_dict,
|
| 649 |
+
tuple: _validate_tuple,
|
| 650 |
+
set: _validate_set,
|
| 651 |
+
collections.abc.Sequence: _validate_sequence,
|
| 652 |
+
}
|
| 653 |
+
|
| 654 |
+
if sys.version_info >= (3, 10):
|
| 655 |
+
# TODO: make it first class citizen when bumping to Python 3.10+
|
| 656 |
+
_BASIC_TYPE_VALIDATORS[types.UnionType] = _validate_union # x | y syntax, available only Python 3.10+
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
__all__ = [
|
| 660 |
+
"strict",
|
| 661 |
+
"validate_typed_dict",
|
| 662 |
+
"validated_field",
|
| 663 |
+
"Validator_T",
|
| 664 |
+
"StrictDataclassClassValidationError",
|
| 665 |
+
"StrictDataclassDefinitionError",
|
| 666 |
+
"StrictDataclassFieldValidationError",
|
| 667 |
+
]
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/fastai_utils.py
ADDED
|
@@ -0,0 +1,414 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import os
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from pickle import DEFAULT_PROTOCOL, PicklingError
|
| 5 |
+
from typing import Any, Optional, Union
|
| 6 |
+
|
| 7 |
+
from packaging import version
|
| 8 |
+
|
| 9 |
+
from huggingface_hub import constants, snapshot_download
|
| 10 |
+
from huggingface_hub.hf_api import HfApi
|
| 11 |
+
from huggingface_hub.utils import (
|
| 12 |
+
SoftTemporaryDirectory,
|
| 13 |
+
get_fastai_version,
|
| 14 |
+
get_fastcore_version,
|
| 15 |
+
get_python_version,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from .utils import logging, validate_hf_hub_args
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
logger = logging.get_logger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _check_fastai_fastcore_versions(
|
| 25 |
+
fastai_min_version: str = "2.4",
|
| 26 |
+
fastcore_min_version: str = "1.3.27",
|
| 27 |
+
):
|
| 28 |
+
"""
|
| 29 |
+
Checks that the installed fastai and fastcore versions are compatible for pickle serialization.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
fastai_min_version (`str`, *optional*):
|
| 33 |
+
The minimum fastai version supported.
|
| 34 |
+
fastcore_min_version (`str`, *optional*):
|
| 35 |
+
The minimum fastcore version supported.
|
| 36 |
+
|
| 37 |
+
> [!TIP]
|
| 38 |
+
> Raises the following error:
|
| 39 |
+
>
|
| 40 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 41 |
+
> if the fastai or fastcore libraries are not available or are of an invalid version.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
if (get_fastcore_version() or get_fastai_version()) == "N/A":
|
| 45 |
+
raise ImportError(
|
| 46 |
+
f"fastai>={fastai_min_version} and fastcore>={fastcore_min_version} are"
|
| 47 |
+
f" required. Currently using fastai=={get_fastai_version()} and"
|
| 48 |
+
f" fastcore=={get_fastcore_version()}."
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
current_fastai_version = version.Version(get_fastai_version())
|
| 52 |
+
current_fastcore_version = version.Version(get_fastcore_version())
|
| 53 |
+
|
| 54 |
+
if current_fastai_version < version.Version(fastai_min_version):
|
| 55 |
+
raise ImportError(
|
| 56 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
| 57 |
+
f" fastai>={fastai_min_version} version, but you are using fastai version"
|
| 58 |
+
f" {get_fastai_version()} which is incompatible. Upgrade with `pip install"
|
| 59 |
+
" fastai==2.5.6`."
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
if current_fastcore_version < version.Version(fastcore_min_version):
|
| 63 |
+
raise ImportError(
|
| 64 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require a"
|
| 65 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
| 66 |
+
f" version {get_fastcore_version()} which is incompatible. Upgrade with"
|
| 67 |
+
" `pip install fastcore==1.3.27`."
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _check_fastai_fastcore_pyproject_versions(
|
| 72 |
+
storage_folder: str,
|
| 73 |
+
fastai_min_version: str = "2.4",
|
| 74 |
+
fastcore_min_version: str = "1.3.27",
|
| 75 |
+
):
|
| 76 |
+
"""
|
| 77 |
+
Checks that the `pyproject.toml` file in the directory `storage_folder` has fastai and fastcore versions
|
| 78 |
+
that are compatible with `from_pretrained_fastai` and `push_to_hub_fastai`. If `pyproject.toml` does not exist
|
| 79 |
+
or does not contain versions for fastai and fastcore, then it logs a warning.
|
| 80 |
+
|
| 81 |
+
Args:
|
| 82 |
+
storage_folder (`str`):
|
| 83 |
+
Folder to look for the `pyproject.toml` file.
|
| 84 |
+
fastai_min_version (`str`, *optional*):
|
| 85 |
+
The minimum fastai version supported.
|
| 86 |
+
fastcore_min_version (`str`, *optional*):
|
| 87 |
+
The minimum fastcore version supported.
|
| 88 |
+
|
| 89 |
+
> [!TIP]
|
| 90 |
+
> Raises the following errors:
|
| 91 |
+
>
|
| 92 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 93 |
+
> if the `toml` module is not installed.
|
| 94 |
+
> - [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
|
| 95 |
+
> if the `pyproject.toml` indicates a lower than minimum supported version of fastai or fastcore.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
try:
|
| 99 |
+
import toml
|
| 100 |
+
except ModuleNotFoundError:
|
| 101 |
+
raise ImportError(
|
| 102 |
+
"`push_to_hub_fastai` and `from_pretrained_fastai` require the toml module."
|
| 103 |
+
" Install it with `pip install toml`."
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Checks that a `pyproject.toml`, with `build-system` and `requires` sections, exists in the repository. If so, get a list of required packages.
|
| 107 |
+
if not os.path.isfile(f"{storage_folder}/pyproject.toml"):
|
| 108 |
+
logger.warning(
|
| 109 |
+
"There is no `pyproject.toml` in the repository that contains the fastai"
|
| 110 |
+
" `Learner`. The `pyproject.toml` would allow us to verify that your fastai"
|
| 111 |
+
" and fastcore versions are compatible with those of the model you want to"
|
| 112 |
+
" load."
|
| 113 |
+
)
|
| 114 |
+
return
|
| 115 |
+
pyproject_toml = toml.load(f"{storage_folder}/pyproject.toml")
|
| 116 |
+
|
| 117 |
+
if "build-system" not in pyproject_toml.keys():
|
| 118 |
+
logger.warning(
|
| 119 |
+
"There is no `build-system` section in the pyproject.toml of the repository"
|
| 120 |
+
" that contains the fastai `Learner`. The `build-system` would allow us to"
|
| 121 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
| 122 |
+
" of the model you want to load."
|
| 123 |
+
)
|
| 124 |
+
return
|
| 125 |
+
build_system_toml = pyproject_toml["build-system"]
|
| 126 |
+
|
| 127 |
+
if "requires" not in build_system_toml.keys():
|
| 128 |
+
logger.warning(
|
| 129 |
+
"There is no `requires` section in the pyproject.toml of the repository"
|
| 130 |
+
" that contains the fastai `Learner`. The `requires` would allow us to"
|
| 131 |
+
" verify that your fastai and fastcore versions are compatible with those"
|
| 132 |
+
" of the model you want to load."
|
| 133 |
+
)
|
| 134 |
+
return
|
| 135 |
+
package_versions = build_system_toml["requires"]
|
| 136 |
+
|
| 137 |
+
# Extracts contains fastai and fastcore versions from `pyproject.toml` if available.
|
| 138 |
+
# If the package is specified but not the version (e.g. "fastai" instead of "fastai=2.4"), the default versions are the highest.
|
| 139 |
+
fastai_packages = [pck for pck in package_versions if pck.startswith("fastai")]
|
| 140 |
+
if len(fastai_packages) == 0:
|
| 141 |
+
logger.warning("The repository does not have a fastai version specified in the `pyproject.toml`.")
|
| 142 |
+
# fastai_version is an empty string if not specified
|
| 143 |
+
else:
|
| 144 |
+
fastai_version = str(fastai_packages[0]).partition("=")[2]
|
| 145 |
+
if fastai_version != "" and version.Version(fastai_version) < version.Version(fastai_min_version):
|
| 146 |
+
raise ImportError(
|
| 147 |
+
"`from_pretrained_fastai` requires"
|
| 148 |
+
f" fastai>={fastai_min_version} version but the model to load uses"
|
| 149 |
+
f" {fastai_version} which is incompatible."
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
fastcore_packages = [pck for pck in package_versions if pck.startswith("fastcore")]
|
| 153 |
+
if len(fastcore_packages) == 0:
|
| 154 |
+
logger.warning("The repository does not have a fastcore version specified in the `pyproject.toml`.")
|
| 155 |
+
# fastcore_version is an empty string if not specified
|
| 156 |
+
else:
|
| 157 |
+
fastcore_version = str(fastcore_packages[0]).partition("=")[2]
|
| 158 |
+
if fastcore_version != "" and version.Version(fastcore_version) < version.Version(fastcore_min_version):
|
| 159 |
+
raise ImportError(
|
| 160 |
+
"`from_pretrained_fastai` requires"
|
| 161 |
+
f" fastcore>={fastcore_min_version} version, but you are using fastcore"
|
| 162 |
+
f" version {fastcore_version} which is incompatible."
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
README_TEMPLATE = """---
|
| 167 |
+
tags:
|
| 168 |
+
- fastai
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
# Amazing!
|
| 172 |
+
|
| 173 |
+
🥳 Congratulations on hosting your fastai model on the Hugging Face Hub!
|
| 174 |
+
|
| 175 |
+
# Some next steps
|
| 176 |
+
1. Fill out this model card with more information (see the template below and the [documentation here](https://huggingface.co/docs/hub/model-repos))!
|
| 177 |
+
|
| 178 |
+
2. Create a demo in Gradio or Streamlit using 🤗 Spaces ([documentation here](https://huggingface.co/docs/hub/spaces)).
|
| 179 |
+
|
| 180 |
+
3. Join the fastai community on the [Fastai Discord](https://discord.com/invite/YKrxeNn)!
|
| 181 |
+
|
| 182 |
+
Greetings fellow fastlearner 🤝! Don't forget to delete this content from your model card.
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
# Model card
|
| 189 |
+
|
| 190 |
+
## Model description
|
| 191 |
+
More information needed
|
| 192 |
+
|
| 193 |
+
## Intended uses & limitations
|
| 194 |
+
More information needed
|
| 195 |
+
|
| 196 |
+
## Training and evaluation data
|
| 197 |
+
More information needed
|
| 198 |
+
"""
|
| 199 |
+
|
| 200 |
+
PYPROJECT_TEMPLATE = f"""[build-system]
|
| 201 |
+
requires = ["setuptools>=40.8.0", "wheel", "python={get_python_version()}", "fastai={get_fastai_version()}", "fastcore={get_fastcore_version()}"]
|
| 202 |
+
build-backend = "setuptools.build_meta:__legacy__"
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def _create_model_card(repo_dir: Path):
|
| 207 |
+
"""
|
| 208 |
+
Creates a model card for the repository.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
repo_dir (`Path`):
|
| 212 |
+
Directory where model card is created.
|
| 213 |
+
"""
|
| 214 |
+
readme_path = repo_dir / "README.md"
|
| 215 |
+
|
| 216 |
+
if not readme_path.exists():
|
| 217 |
+
with readme_path.open("w", encoding="utf-8") as f:
|
| 218 |
+
f.write(README_TEMPLATE)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _create_model_pyproject(repo_dir: Path):
|
| 222 |
+
"""
|
| 223 |
+
Creates a `pyproject.toml` for the repository.
|
| 224 |
+
|
| 225 |
+
Args:
|
| 226 |
+
repo_dir (`Path`):
|
| 227 |
+
Directory where `pyproject.toml` is created.
|
| 228 |
+
"""
|
| 229 |
+
pyproject_path = repo_dir / "pyproject.toml"
|
| 230 |
+
|
| 231 |
+
if not pyproject_path.exists():
|
| 232 |
+
with pyproject_path.open("w", encoding="utf-8") as f:
|
| 233 |
+
f.write(PYPROJECT_TEMPLATE)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def _save_pretrained_fastai(
|
| 237 |
+
learner,
|
| 238 |
+
save_directory: Union[str, Path],
|
| 239 |
+
config: Optional[dict[str, Any]] = None,
|
| 240 |
+
):
|
| 241 |
+
"""
|
| 242 |
+
Saves a fastai learner to `save_directory` in pickle format using the default pickle protocol for the version of python used.
|
| 243 |
+
|
| 244 |
+
Args:
|
| 245 |
+
learner (`Learner`):
|
| 246 |
+
The `fastai.Learner` you'd like to save.
|
| 247 |
+
save_directory (`str` or `Path`):
|
| 248 |
+
Specific directory in which you want to save the fastai learner.
|
| 249 |
+
config (`dict`, *optional*):
|
| 250 |
+
Configuration object. Will be uploaded as a .json file. Example: 'https://huggingface.co/espejelomar/fastai-pet-breeds-classification/blob/main/config.json'.
|
| 251 |
+
|
| 252 |
+
> [!TIP]
|
| 253 |
+
> Raises the following error:
|
| 254 |
+
>
|
| 255 |
+
> - [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError)
|
| 256 |
+
> if the config file provided is not a dictionary.
|
| 257 |
+
"""
|
| 258 |
+
_check_fastai_fastcore_versions()
|
| 259 |
+
|
| 260 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 261 |
+
|
| 262 |
+
# if the user provides config then we update it with the fastai and fastcore versions in CONFIG_TEMPLATE.
|
| 263 |
+
if config is not None:
|
| 264 |
+
if not isinstance(config, dict):
|
| 265 |
+
raise RuntimeError(f"Provided config should be a dict. Got: '{type(config)}'")
|
| 266 |
+
path = os.path.join(save_directory, constants.CONFIG_NAME)
|
| 267 |
+
with open(path, "w") as f:
|
| 268 |
+
json.dump(config, f)
|
| 269 |
+
|
| 270 |
+
_create_model_card(Path(save_directory))
|
| 271 |
+
_create_model_pyproject(Path(save_directory))
|
| 272 |
+
|
| 273 |
+
# learner.export saves the model in `self.path`.
|
| 274 |
+
learner.path = Path(save_directory)
|
| 275 |
+
os.makedirs(save_directory, exist_ok=True)
|
| 276 |
+
try:
|
| 277 |
+
learner.export(
|
| 278 |
+
fname="model.pkl",
|
| 279 |
+
pickle_protocol=DEFAULT_PROTOCOL,
|
| 280 |
+
)
|
| 281 |
+
except PicklingError:
|
| 282 |
+
raise PicklingError(
|
| 283 |
+
"You are using a lambda function, i.e., an anonymous function. `pickle`"
|
| 284 |
+
" cannot pickle function objects and requires that all functions have"
|
| 285 |
+
" names. One possible solution is to name the function."
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
@validate_hf_hub_args
|
| 290 |
+
def from_pretrained_fastai(
|
| 291 |
+
repo_id: str,
|
| 292 |
+
revision: Optional[str] = None,
|
| 293 |
+
):
|
| 294 |
+
"""
|
| 295 |
+
Load pretrained fastai model from the Hub or from a local directory.
|
| 296 |
+
|
| 297 |
+
Args:
|
| 298 |
+
repo_id (`str`):
|
| 299 |
+
The location where the pickled fastai.Learner is. It can be either of the two:
|
| 300 |
+
- Hosted on the Hugging Face Hub. E.g.: 'espejelomar/fatai-pet-breeds-classification' or 'distilgpt2'.
|
| 301 |
+
You can add a `revision` by appending `@` at the end of `repo_id`. E.g.: `dbmdz/bert-base-german-cased@main`.
|
| 302 |
+
Revision is the specific model version to use. Since we use a git-based system for storing models and other
|
| 303 |
+
artifacts on the Hugging Face Hub, it can be a branch name, a tag name, or a commit id.
|
| 304 |
+
- Hosted locally. `repo_id` would be a directory containing the pickle and a pyproject.toml
|
| 305 |
+
indicating the fastai and fastcore versions used to build the `fastai.Learner`. E.g.: `./my_model_directory/`.
|
| 306 |
+
revision (`str`, *optional*):
|
| 307 |
+
Revision at which the repo's files are downloaded. See documentation of `snapshot_download`.
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
The `fastai.Learner` model in the `repo_id` repo.
|
| 311 |
+
"""
|
| 312 |
+
_check_fastai_fastcore_versions()
|
| 313 |
+
|
| 314 |
+
# Load the `repo_id` repo.
|
| 315 |
+
# `snapshot_download` returns the folder where the model was stored.
|
| 316 |
+
# `cache_dir` will be the default '/root/.cache/huggingface/hub'
|
| 317 |
+
if not os.path.isdir(repo_id):
|
| 318 |
+
storage_folder = snapshot_download(
|
| 319 |
+
repo_id=repo_id,
|
| 320 |
+
revision=revision,
|
| 321 |
+
library_name="fastai",
|
| 322 |
+
library_version=get_fastai_version(),
|
| 323 |
+
)
|
| 324 |
+
else:
|
| 325 |
+
storage_folder = repo_id
|
| 326 |
+
|
| 327 |
+
_check_fastai_fastcore_pyproject_versions(storage_folder)
|
| 328 |
+
|
| 329 |
+
from fastai.learner import load_learner # type: ignore
|
| 330 |
+
|
| 331 |
+
return load_learner(os.path.join(storage_folder, "model.pkl"))
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
@validate_hf_hub_args
|
| 335 |
+
def push_to_hub_fastai(
|
| 336 |
+
learner,
|
| 337 |
+
*,
|
| 338 |
+
repo_id: str,
|
| 339 |
+
commit_message: str = "Push FastAI model using huggingface_hub.",
|
| 340 |
+
private: Optional[bool] = None,
|
| 341 |
+
token: Optional[str] = None,
|
| 342 |
+
config: Optional[dict] = None,
|
| 343 |
+
branch: Optional[str] = None,
|
| 344 |
+
create_pr: Optional[bool] = None,
|
| 345 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 346 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 347 |
+
delete_patterns: Optional[Union[list[str], str]] = None,
|
| 348 |
+
api_endpoint: Optional[str] = None,
|
| 349 |
+
):
|
| 350 |
+
"""
|
| 351 |
+
Upload learner checkpoint files to the Hub.
|
| 352 |
+
|
| 353 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
| 354 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
| 355 |
+
details.
|
| 356 |
+
|
| 357 |
+
Args:
|
| 358 |
+
learner (`Learner`):
|
| 359 |
+
The `fastai.Learner' you'd like to push to the Hub.
|
| 360 |
+
repo_id (`str`):
|
| 361 |
+
The repository id for your model in Hub in the format of "namespace/repo_name". The namespace can be your individual account or an organization to which you have write access (for example, 'stanfordnlp/stanza-de').
|
| 362 |
+
commit_message (`str`, *optional*):
|
| 363 |
+
Message to commit while pushing. Will default to :obj:`"add model"`.
|
| 364 |
+
private (`bool`, *optional*):
|
| 365 |
+
Whether or not the repository created should be private.
|
| 366 |
+
If `None` (default), will default to been public except if the organization's default is private.
|
| 367 |
+
token (`str`, *optional*):
|
| 368 |
+
The Hugging Face account token to use as HTTP bearer authorization for remote files. If :obj:`None`, the token will be asked by a prompt.
|
| 369 |
+
config (`dict`, *optional*):
|
| 370 |
+
Configuration object to be saved alongside the model weights.
|
| 371 |
+
branch (`str`, *optional*):
|
| 372 |
+
The git branch on which to push the model. This defaults to
|
| 373 |
+
the default branch as specified in your repository, which
|
| 374 |
+
defaults to `"main"`.
|
| 375 |
+
create_pr (`boolean`, *optional*):
|
| 376 |
+
Whether or not to create a Pull Request from `branch` with that commit.
|
| 377 |
+
Defaults to `False`.
|
| 378 |
+
api_endpoint (`str`, *optional*):
|
| 379 |
+
The API endpoint to use when pushing the model to the hub.
|
| 380 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 381 |
+
If provided, only files matching at least one pattern are pushed.
|
| 382 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 383 |
+
If provided, files matching any of the patterns are not pushed.
|
| 384 |
+
delete_patterns (`list[str]` or `str`, *optional*):
|
| 385 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
| 386 |
+
|
| 387 |
+
Returns:
|
| 388 |
+
The url of the commit of your model in the given repository.
|
| 389 |
+
|
| 390 |
+
> [!TIP]
|
| 391 |
+
> Raises the following error:
|
| 392 |
+
>
|
| 393 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 394 |
+
> if the user is not log on to the Hugging Face Hub.
|
| 395 |
+
"""
|
| 396 |
+
_check_fastai_fastcore_versions()
|
| 397 |
+
api = HfApi(endpoint=api_endpoint)
|
| 398 |
+
repo_id = api.create_repo(repo_id=repo_id, token=token, private=private, exist_ok=True).repo_id
|
| 399 |
+
|
| 400 |
+
# Push the files to the repo in a single commit
|
| 401 |
+
with SoftTemporaryDirectory() as tmp:
|
| 402 |
+
saved_path = Path(tmp) / repo_id
|
| 403 |
+
_save_pretrained_fastai(learner, saved_path, config=config)
|
| 404 |
+
return api.upload_folder(
|
| 405 |
+
repo_id=repo_id,
|
| 406 |
+
token=token,
|
| 407 |
+
folder_path=saved_path,
|
| 408 |
+
commit_message=commit_message,
|
| 409 |
+
revision=branch,
|
| 410 |
+
create_pr=create_pr,
|
| 411 |
+
allow_patterns=allow_patterns,
|
| 412 |
+
ignore_patterns=ignore_patterns,
|
| 413 |
+
delete_patterns=delete_patterns,
|
| 414 |
+
)
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/hf_api.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/hf_file_system.py
ADDED
|
@@ -0,0 +1,1454 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
import tempfile
|
| 4 |
+
import threading
|
| 5 |
+
from collections import deque
|
| 6 |
+
from contextlib import ExitStack
|
| 7 |
+
from copy import deepcopy
|
| 8 |
+
from dataclasses import dataclass, field
|
| 9 |
+
from datetime import datetime
|
| 10 |
+
from itertools import chain
|
| 11 |
+
from pathlib import Path, PurePosixPath
|
| 12 |
+
from typing import Any, Iterable, Iterator, NoReturn, Optional, Union
|
| 13 |
+
from urllib.parse import quote, unquote
|
| 14 |
+
|
| 15 |
+
import fsspec
|
| 16 |
+
import httpx
|
| 17 |
+
from fsspec.callbacks import _DEFAULT_CALLBACK, NoOpCallback, TqdmCallback
|
| 18 |
+
from fsspec.utils import isfilelike
|
| 19 |
+
|
| 20 |
+
from . import constants
|
| 21 |
+
from ._commit_api import CommitOperationCopy, CommitOperationDelete
|
| 22 |
+
from .errors import (
|
| 23 |
+
BucketNotFoundError,
|
| 24 |
+
EntryNotFoundError,
|
| 25 |
+
HfHubHTTPError,
|
| 26 |
+
RepositoryNotFoundError,
|
| 27 |
+
RevisionNotFoundError,
|
| 28 |
+
)
|
| 29 |
+
from .file_download import hf_hub_url, http_get
|
| 30 |
+
from .hf_api import BucketFile, BucketFolder, HfApi, LastCommitInfo, RepoFile, RepoFolder
|
| 31 |
+
from .utils import HFValidationError, hf_raise_for_status, http_backoff, http_stream_backoff
|
| 32 |
+
from .utils.insecure_hashlib import md5
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Regex used to match special revisions with "/" in them (see #1710)
|
| 36 |
+
SPECIAL_REFS_REVISION_REGEX = re.compile(
|
| 37 |
+
r"""
|
| 38 |
+
(^refs\/convert\/\w+) # `refs/convert/parquet` revisions
|
| 39 |
+
|
|
| 40 |
+
(^refs\/pr\/\d+) # PR revisions
|
| 41 |
+
""",
|
| 42 |
+
re.VERBOSE,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@dataclass
|
| 47 |
+
class HfFileSystemResolvedPath:
|
| 48 |
+
"""Top level Data structure containing information about a resolved Hugging Face file system path."""
|
| 49 |
+
|
| 50 |
+
root: str
|
| 51 |
+
path: str
|
| 52 |
+
|
| 53 |
+
def unresolve(self) -> str:
|
| 54 |
+
return f"{self.root}/{self.path}".rstrip("/")
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass
|
| 58 |
+
class HfFileSystemResolvedRepositoryPath(HfFileSystemResolvedPath):
|
| 59 |
+
"""Data structure containing information about a resolved path in a repository."""
|
| 60 |
+
|
| 61 |
+
repo_type: str
|
| 62 |
+
repo_id: str
|
| 63 |
+
revision: str
|
| 64 |
+
path_in_repo: str
|
| 65 |
+
root: str = field(init=False)
|
| 66 |
+
path: str = field(init=False)
|
| 67 |
+
# The part placed after '@' in the initial path. It can be a quoted or unquoted refs revision.
|
| 68 |
+
# Used to reconstruct the unresolved path to return to the user.
|
| 69 |
+
_raw_revision: Optional[str] = field(default=None, repr=False)
|
| 70 |
+
|
| 71 |
+
def __post_init__(self):
|
| 72 |
+
repo_path = constants.REPO_TYPES_URL_PREFIXES.get(self.repo_type, "") + self.repo_id
|
| 73 |
+
if self._raw_revision:
|
| 74 |
+
self.root = f"{repo_path}@{self._raw_revision}"
|
| 75 |
+
elif self.revision != constants.DEFAULT_REVISION:
|
| 76 |
+
self.root = f"{repo_path}@{safe_revision(self.revision)}"
|
| 77 |
+
else:
|
| 78 |
+
self.root = repo_path
|
| 79 |
+
self.path = self.path_in_repo
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@dataclass
|
| 83 |
+
class HfFileSystemResolvedBucketPath(HfFileSystemResolvedPath):
|
| 84 |
+
"""Data structure containing information about a resolved path in a bucket."""
|
| 85 |
+
|
| 86 |
+
bucket_id: str
|
| 87 |
+
root: str = field(init=False)
|
| 88 |
+
|
| 89 |
+
def __post_init__(self):
|
| 90 |
+
self.root = "buckets/" + self.bucket_id
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# We need to improve fsspec.spec._Cached which is AbstractFileSystem's metaclass
|
| 94 |
+
_cached_base: Any = type(fsspec.AbstractFileSystem)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class _Cached(_cached_base):
|
| 98 |
+
"""
|
| 99 |
+
Metaclass for caching HfFileSystem instances according to the args.
|
| 100 |
+
|
| 101 |
+
This creates an additional reference to the filesystem, which prevents the
|
| 102 |
+
filesystem from being garbage collected when all *user* references go away.
|
| 103 |
+
A call to the :meth:`AbstractFileSystem.clear_instance_cache` must *also*
|
| 104 |
+
be made for a filesystem instance to be garbage collected.
|
| 105 |
+
|
| 106 |
+
This is a slightly modified version of `fsspec.spec._Cached` to improve it.
|
| 107 |
+
In particular in `_tokenize` the pid isn't taken into account for the
|
| 108 |
+
`fs_token` used to identify cached instances. The `fs_token` logic is also
|
| 109 |
+
robust to defaults values and the order of the args. Finally new instances
|
| 110 |
+
reuse the states from sister instances in the main thread.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
def __init__(cls, *args, **kwargs):
|
| 114 |
+
# Hack: override https://github.com/fsspec/filesystem_spec/blob/dcb167e8f50e6273d4cfdfc4cab8fc5aa4c958bf/fsspec/spec.py#L53
|
| 115 |
+
super().__init__(*args, **kwargs)
|
| 116 |
+
# Note: we intentionally create a reference here, to avoid garbage
|
| 117 |
+
# collecting instances when all other references are gone. To really
|
| 118 |
+
# delete a FileSystem, the cache must be cleared.
|
| 119 |
+
cls._cache = {}
|
| 120 |
+
|
| 121 |
+
def __call__(cls, *args, **kwargs):
|
| 122 |
+
# Hack: override https://github.com/fsspec/filesystem_spec/blob/dcb167e8f50e6273d4cfdfc4cab8fc5aa4c958bf/fsspec/spec.py#L65
|
| 123 |
+
skip = kwargs.pop("skip_instance_cache", False)
|
| 124 |
+
fs_token = cls._tokenize(cls, threading.get_ident(), *args, **kwargs)
|
| 125 |
+
fs_token_main_thread = cls._tokenize(cls, threading.main_thread().ident, *args, **kwargs)
|
| 126 |
+
if not skip and cls.cachable and fs_token in cls._cache:
|
| 127 |
+
# reuse cached instance
|
| 128 |
+
cls._latest = fs_token
|
| 129 |
+
return cls._cache[fs_token]
|
| 130 |
+
else:
|
| 131 |
+
# create new instance
|
| 132 |
+
obj = type.__call__(cls, *args, **kwargs)
|
| 133 |
+
if not skip and cls.cachable and fs_token_main_thread in cls._cache:
|
| 134 |
+
# reuse the cache from the main thread instance in the new instance
|
| 135 |
+
instance_state = cls._cache[fs_token_main_thread]._get_instance_state()
|
| 136 |
+
for attr, state_value in instance_state.items():
|
| 137 |
+
setattr(obj, attr, state_value)
|
| 138 |
+
obj._fs_token_ = fs_token
|
| 139 |
+
obj.storage_args = args
|
| 140 |
+
obj.storage_options = kwargs
|
| 141 |
+
if cls.cachable and not skip:
|
| 142 |
+
cls._latest = fs_token
|
| 143 |
+
cls._cache[fs_token] = obj
|
| 144 |
+
return obj
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
class HfFileSystem(fsspec.AbstractFileSystem, metaclass=_Cached):
|
| 148 |
+
"""
|
| 149 |
+
Access a remote Hugging Face Hub repository as if were a local file system.
|
| 150 |
+
|
| 151 |
+
> [!WARNING]
|
| 152 |
+
> [`HfFileSystem`] provides fsspec compatibility, which is useful for libraries that require it (e.g., reading
|
| 153 |
+
> Hugging Face datasets directly with `pandas`). However, it introduces additional overhead due to this compatibility
|
| 154 |
+
> layer. For better performance and reliability, it's recommended to use `HfApi` methods when possible.
|
| 155 |
+
|
| 156 |
+
The file system supports paths for the `hf://` protocol, which follows those URL schemes:
|
| 157 |
+
|
| 158 |
+
* Models, Datasets and Spaces repositories:
|
| 159 |
+
|
| 160 |
+
```
|
| 161 |
+
hf://<repo-id>[@<revision>]/<path/in/repo>
|
| 162 |
+
hf://datasets/<repo-id>[@<revision>]/<path/in/repo>
|
| 163 |
+
hf://spaces/<repo-id>[@<revision>]/<path/in/repo>
|
| 164 |
+
```
|
| 165 |
+
|
| 166 |
+
* Buckets (generic storage):
|
| 167 |
+
|
| 168 |
+
```
|
| 169 |
+
hf://buckets/<bucket-id>/<path/in/bucket>
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
Note: when using the [`HfFileSystem`] directly, passing the `hf://` protocol prefix is optional in paths.
|
| 173 |
+
|
| 174 |
+
Args:
|
| 175 |
+
endpoint (`str`, *optional*):
|
| 176 |
+
Endpoint of the Hub. Defaults to <https://huggingface.co>.
|
| 177 |
+
token (`bool` or `str`, *optional*):
|
| 178 |
+
A valid user access token (string). Defaults to the locally saved
|
| 179 |
+
token, which is the recommended method for authentication (see
|
| 180 |
+
https://huggingface.co/docs/huggingface_hub/quick-start#authentication).
|
| 181 |
+
To disable authentication, pass `False`.
|
| 182 |
+
block_size (`int`, *optional*):
|
| 183 |
+
Block size for reading and writing files.
|
| 184 |
+
expand_info (`bool`, *optional*):
|
| 185 |
+
Whether to expand the information of the files.
|
| 186 |
+
**storage_options (`dict`, *optional*):
|
| 187 |
+
Additional options for the filesystem. See [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.__init__).
|
| 188 |
+
|
| 189 |
+
Usage:
|
| 190 |
+
|
| 191 |
+
```python
|
| 192 |
+
>>> from huggingface_hub import hffs
|
| 193 |
+
|
| 194 |
+
>>> # List files
|
| 195 |
+
>>> hffs.glob("my-username/my-model/*.bin")
|
| 196 |
+
['my-username/my-model/pytorch_model.bin']
|
| 197 |
+
>>> hffs.ls("datasets/my-username/my-dataset", detail=False)
|
| 198 |
+
['datasets/my-username/my-dataset/.gitattributes', 'datasets/my-username/my-dataset/README.md', 'datasets/my-username/my-dataset/data.json']
|
| 199 |
+
|
| 200 |
+
>>> # Read/write files
|
| 201 |
+
>>> with hffs.open("my-username/my-model/pytorch_model.bin") as f:
|
| 202 |
+
... data = f.read()
|
| 203 |
+
>>> with hffs.open("my-username/my-model/pytorch_model.bin", "wb") as f:
|
| 204 |
+
... f.write(data)
|
| 205 |
+
```
|
| 206 |
+
|
| 207 |
+
Specify a token for authentication:
|
| 208 |
+
```python
|
| 209 |
+
>>> from huggingface_hub import HfFileSystem
|
| 210 |
+
>>> hffs = HfFileSystem(token=token)
|
| 211 |
+
```
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
root_marker = ""
|
| 215 |
+
protocol = "hf"
|
| 216 |
+
|
| 217 |
+
def __init__(
|
| 218 |
+
self,
|
| 219 |
+
*args,
|
| 220 |
+
endpoint: Optional[str] = None,
|
| 221 |
+
token: Union[bool, str, None] = None,
|
| 222 |
+
block_size: Optional[int] = None,
|
| 223 |
+
expand_info: Optional[bool] = None,
|
| 224 |
+
**storage_options,
|
| 225 |
+
):
|
| 226 |
+
super().__init__(*args, **storage_options)
|
| 227 |
+
self.endpoint = endpoint or constants.ENDPOINT
|
| 228 |
+
self.token = token
|
| 229 |
+
self._api = HfApi(endpoint=endpoint, token=token)
|
| 230 |
+
self.block_size = block_size
|
| 231 |
+
self.expand_info = expand_info
|
| 232 |
+
# Maps (repo_type, repo_id, revision) to a 2-tuple with:
|
| 233 |
+
# * the 1st element indicating whether the repository and the revision exist
|
| 234 |
+
# * the 2nd element being the exception raised if the repository or revision doesn't exist
|
| 235 |
+
self._repo_and_revision_exists_cache: dict[
|
| 236 |
+
tuple[str, str, Optional[str]], tuple[bool, Optional[Exception]]
|
| 237 |
+
] = {}
|
| 238 |
+
# Same for buckets
|
| 239 |
+
self._bucket_exists_cache: dict[str, tuple[bool, Optional[Exception]]] = {}
|
| 240 |
+
# Note: special case for buckets: revision is always None
|
| 241 |
+
# Maps parent directory path to path infos
|
| 242 |
+
self.dircache: dict[str, list[dict[str, Any]]] = {}
|
| 243 |
+
|
| 244 |
+
@classmethod
|
| 245 |
+
def _tokenize(cls, threading_ident: int, *args, **kwargs) -> str:
|
| 246 |
+
"""Deterministic token for caching"""
|
| 247 |
+
# make fs_token robust to default values and to kwargs order
|
| 248 |
+
kwargs["endpoint"] = kwargs.get("endpoint") or constants.ENDPOINT
|
| 249 |
+
kwargs["token"] = kwargs.get("token")
|
| 250 |
+
kwargs = {key: kwargs[key] for key in sorted(kwargs)}
|
| 251 |
+
# contrary to fsspec, we don't include pid here
|
| 252 |
+
tokenize_args = (cls, threading_ident, args, kwargs)
|
| 253 |
+
h = md5(str(tokenize_args).encode())
|
| 254 |
+
return h.hexdigest()
|
| 255 |
+
|
| 256 |
+
def _repo_and_revision_exist(
|
| 257 |
+
self, repo_type: str, repo_id: str, revision: Optional[str]
|
| 258 |
+
) -> tuple[bool, Optional[Exception]]:
|
| 259 |
+
if (repo_type, repo_id, revision) not in self._repo_and_revision_exists_cache:
|
| 260 |
+
try:
|
| 261 |
+
self._api.repo_info(
|
| 262 |
+
repo_id, revision=revision, repo_type=repo_type, timeout=constants.HF_HUB_ETAG_TIMEOUT
|
| 263 |
+
)
|
| 264 |
+
except (RepositoryNotFoundError, HFValidationError) as e:
|
| 265 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
|
| 266 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = False, e
|
| 267 |
+
except RevisionNotFoundError as e:
|
| 268 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = False, e
|
| 269 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
|
| 270 |
+
else:
|
| 271 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)] = True, None
|
| 272 |
+
self._repo_and_revision_exists_cache[(repo_type, repo_id, None)] = True, None
|
| 273 |
+
return self._repo_and_revision_exists_cache[(repo_type, repo_id, revision)]
|
| 274 |
+
|
| 275 |
+
def _bucket_exists(self, bucket_id: str) -> tuple[bool, Optional[Exception]]:
|
| 276 |
+
if bucket_id not in self._bucket_exists_cache:
|
| 277 |
+
try:
|
| 278 |
+
self._api.bucket_info(bucket_id)
|
| 279 |
+
except BucketNotFoundError as e:
|
| 280 |
+
self._bucket_exists_cache[bucket_id] = False, e
|
| 281 |
+
else:
|
| 282 |
+
self._bucket_exists_cache[bucket_id] = True, None
|
| 283 |
+
return self._bucket_exists_cache[bucket_id]
|
| 284 |
+
|
| 285 |
+
def resolve_path(
|
| 286 |
+
self, path: str, revision: Optional[str] = None
|
| 287 |
+
) -> Union[HfFileSystemResolvedRepositoryPath, HfFileSystemResolvedBucketPath]:
|
| 288 |
+
"""
|
| 289 |
+
Resolve a Hugging Face file system path into its components.
|
| 290 |
+
|
| 291 |
+
Args:
|
| 292 |
+
path (`str`):
|
| 293 |
+
Path to resolve.
|
| 294 |
+
revision (`str`, *optional*):
|
| 295 |
+
The revision of the repo to resolve. Defaults to the revision specified in the path.
|
| 296 |
+
|
| 297 |
+
Returns:
|
| 298 |
+
[`HfFileSystemResolvedPath`]: Resolved path information containing `repo_type`, `repo_id`, `revision` and `path_in_repo`.
|
| 299 |
+
|
| 300 |
+
Raises:
|
| 301 |
+
`ValueError`:
|
| 302 |
+
If path contains conflicting revision information.
|
| 303 |
+
`NotImplementedError`:
|
| 304 |
+
If trying to list repositories.
|
| 305 |
+
"""
|
| 306 |
+
|
| 307 |
+
def _align_revision_in_path_with_revision(
|
| 308 |
+
revision_in_path: Optional[str], revision: Optional[str]
|
| 309 |
+
) -> Optional[str]:
|
| 310 |
+
if revision is not None:
|
| 311 |
+
if revision_in_path is not None and revision_in_path != revision:
|
| 312 |
+
raise ValueError(
|
| 313 |
+
f'Revision specified in path ("{revision_in_path}") and in `revision` argument ("{revision}")'
|
| 314 |
+
" are not the same."
|
| 315 |
+
)
|
| 316 |
+
else:
|
| 317 |
+
revision = revision_in_path
|
| 318 |
+
return revision
|
| 319 |
+
|
| 320 |
+
path = self._strip_protocol(path)
|
| 321 |
+
if not path:
|
| 322 |
+
# can't list repositories at root
|
| 323 |
+
raise NotImplementedError("Access to buckets and repositories lists is not implemented.")
|
| 324 |
+
elif path.split("/")[0] == "buckets":
|
| 325 |
+
bucket_id = "/".join(path.split("/")[1:3])
|
| 326 |
+
path = "/".join(path.split("/")[3:])
|
| 327 |
+
bucket_exists, err = self._bucket_exists(bucket_id)
|
| 328 |
+
if not bucket_exists:
|
| 329 |
+
_raise_file_not_found(path, err)
|
| 330 |
+
return HfFileSystemResolvedBucketPath(bucket_id=bucket_id, path=path)
|
| 331 |
+
elif path.split("/")[0] + "/" in constants.REPO_TYPES_URL_PREFIXES.values():
|
| 332 |
+
if "/" not in path:
|
| 333 |
+
# can't list repositories at the repository type level
|
| 334 |
+
raise NotImplementedError("Access to repositories lists is not implemented.")
|
| 335 |
+
repo_type, path = path.split("/", 1)
|
| 336 |
+
repo_type = constants.REPO_TYPES_MAPPING[repo_type]
|
| 337 |
+
else:
|
| 338 |
+
repo_type = constants.REPO_TYPE_MODEL
|
| 339 |
+
if path.count("/") > 0:
|
| 340 |
+
if "@" in "/".join(path.split("/")[:2]):
|
| 341 |
+
repo_id, revision_in_path = path.split("@", 1)
|
| 342 |
+
if "/" in revision_in_path:
|
| 343 |
+
match = SPECIAL_REFS_REVISION_REGEX.search(revision_in_path)
|
| 344 |
+
if match is not None and revision in (None, match.group()):
|
| 345 |
+
# Handle `refs/convert/parquet` and PR revisions separately
|
| 346 |
+
path_in_repo = SPECIAL_REFS_REVISION_REGEX.sub("", revision_in_path).lstrip("/")
|
| 347 |
+
revision_in_path = match.group()
|
| 348 |
+
else:
|
| 349 |
+
revision_in_path, path_in_repo = revision_in_path.split("/", 1)
|
| 350 |
+
else:
|
| 351 |
+
path_in_repo = ""
|
| 352 |
+
revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
|
| 353 |
+
repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 354 |
+
if not repo_and_revision_exist:
|
| 355 |
+
_raise_file_not_found(path, err)
|
| 356 |
+
else:
|
| 357 |
+
revision_in_path = None
|
| 358 |
+
repo_id_with_namespace = "/".join(path.split("/")[:2])
|
| 359 |
+
path_in_repo_with_namespace = "/".join(path.split("/")[2:])
|
| 360 |
+
repo_id_without_namespace = path.split("/")[0]
|
| 361 |
+
path_in_repo_without_namespace = "/".join(path.split("/")[1:])
|
| 362 |
+
repo_id = repo_id_with_namespace
|
| 363 |
+
path_in_repo = path_in_repo_with_namespace
|
| 364 |
+
repo_and_revision_exist, err = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 365 |
+
if not repo_and_revision_exist:
|
| 366 |
+
if isinstance(err, (RepositoryNotFoundError, HFValidationError)):
|
| 367 |
+
repo_id = repo_id_without_namespace
|
| 368 |
+
path_in_repo = path_in_repo_without_namespace
|
| 369 |
+
repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 370 |
+
if not repo_and_revision_exist:
|
| 371 |
+
_raise_file_not_found(path, err)
|
| 372 |
+
else:
|
| 373 |
+
_raise_file_not_found(path, err)
|
| 374 |
+
else:
|
| 375 |
+
repo_id = path
|
| 376 |
+
path_in_repo = ""
|
| 377 |
+
if "@" in path:
|
| 378 |
+
repo_id, revision_in_path = path.split("@", 1)
|
| 379 |
+
revision = _align_revision_in_path_with_revision(unquote(revision_in_path), revision)
|
| 380 |
+
else:
|
| 381 |
+
revision_in_path = None
|
| 382 |
+
repo_and_revision_exist, _ = self._repo_and_revision_exist(repo_type, repo_id, revision)
|
| 383 |
+
if not repo_and_revision_exist:
|
| 384 |
+
raise NotImplementedError("Access to repositories lists is not implemented.")
|
| 385 |
+
|
| 386 |
+
revision = revision if revision is not None else constants.DEFAULT_REVISION
|
| 387 |
+
return HfFileSystemResolvedRepositoryPath(
|
| 388 |
+
repo_type, repo_id, revision, path_in_repo, _raw_revision=revision_in_path
|
| 389 |
+
)
|
| 390 |
+
|
| 391 |
+
def invalidate_cache(self, path: Optional[str] = None) -> None:
|
| 392 |
+
"""
|
| 393 |
+
Clear the cache for a given path.
|
| 394 |
+
|
| 395 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.invalidate_cache).
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
path (`str`, *optional*):
|
| 399 |
+
Path to clear from cache. If not provided, clear the entire cache.
|
| 400 |
+
|
| 401 |
+
"""
|
| 402 |
+
if not path:
|
| 403 |
+
self.dircache.clear()
|
| 404 |
+
self._repo_and_revision_exists_cache.clear()
|
| 405 |
+
else:
|
| 406 |
+
resolved_path = self.resolve_path(path)
|
| 407 |
+
path = resolved_path.unresolve()
|
| 408 |
+
while path:
|
| 409 |
+
self.dircache.pop(path, None)
|
| 410 |
+
path = self._parent(path)
|
| 411 |
+
|
| 412 |
+
# Only clear repo cache if path is to repo root
|
| 413 |
+
if not resolved_path.path:
|
| 414 |
+
if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath):
|
| 415 |
+
self._repo_and_revision_exists_cache.pop(
|
| 416 |
+
(resolved_path.repo_type, resolved_path.repo_id, None), None
|
| 417 |
+
)
|
| 418 |
+
self._repo_and_revision_exists_cache.pop(
|
| 419 |
+
(resolved_path.repo_type, resolved_path.repo_id, resolved_path.revision), None
|
| 420 |
+
)
|
| 421 |
+
else:
|
| 422 |
+
self._bucket_exists_cache.pop(resolved_path.bucket_id, None)
|
| 423 |
+
|
| 424 |
+
def _open( # type: ignore[override]
|
| 425 |
+
self,
|
| 426 |
+
path: str,
|
| 427 |
+
mode: str = "rb",
|
| 428 |
+
block_size: Optional[int] = None,
|
| 429 |
+
revision: Optional[str] = None,
|
| 430 |
+
**kwargs,
|
| 431 |
+
) -> Union["HfFileSystemFile", "HfFileSystemStreamFile"]:
|
| 432 |
+
block_size = block_size if block_size is not None else self.block_size
|
| 433 |
+
if block_size is not None:
|
| 434 |
+
kwargs["block_size"] = block_size
|
| 435 |
+
if "a" in mode:
|
| 436 |
+
raise NotImplementedError("Appending to remote files is not yet supported.")
|
| 437 |
+
if block_size == 0:
|
| 438 |
+
return HfFileSystemStreamFile(self, path, mode=mode, revision=revision, **kwargs)
|
| 439 |
+
else:
|
| 440 |
+
return HfFileSystemFile(self, path, mode=mode, revision=revision, **kwargs)
|
| 441 |
+
|
| 442 |
+
def _rm(self, path: str, revision: Optional[str] = None, **kwargs) -> None:
|
| 443 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 444 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 445 |
+
self._api.batch_bucket_files(resolved_path.bucket_id, delete=[resolved_path.path])
|
| 446 |
+
else:
|
| 447 |
+
self._api.delete_file(
|
| 448 |
+
path_in_repo=resolved_path.path_in_repo,
|
| 449 |
+
repo_id=resolved_path.repo_id,
|
| 450 |
+
token=self.token,
|
| 451 |
+
repo_type=resolved_path.repo_type,
|
| 452 |
+
revision=resolved_path.revision,
|
| 453 |
+
commit_message=kwargs.get("commit_message"),
|
| 454 |
+
commit_description=kwargs.get("commit_description"),
|
| 455 |
+
)
|
| 456 |
+
self.invalidate_cache(path=resolved_path.unresolve())
|
| 457 |
+
|
| 458 |
+
def rm(
|
| 459 |
+
self,
|
| 460 |
+
path: str,
|
| 461 |
+
recursive: bool = False,
|
| 462 |
+
maxdepth: Optional[int] = None,
|
| 463 |
+
revision: Optional[str] = None,
|
| 464 |
+
**kwargs,
|
| 465 |
+
) -> None:
|
| 466 |
+
"""
|
| 467 |
+
Delete files from a repository.
|
| 468 |
+
|
| 469 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.rm).
|
| 470 |
+
|
| 471 |
+
> [!WARNING]
|
| 472 |
+
> Note: When possible, use `HfApi.delete_file()` for better performance.
|
| 473 |
+
|
| 474 |
+
Args:
|
| 475 |
+
path (`str`):
|
| 476 |
+
Path to delete.
|
| 477 |
+
recursive (`bool`, *optional*):
|
| 478 |
+
If True, delete directory and all its contents. Defaults to False.
|
| 479 |
+
maxdepth (`int`, *optional*):
|
| 480 |
+
Maximum number of subdirectories to visit when deleting recursively.
|
| 481 |
+
revision (`str`, *optional*):
|
| 482 |
+
The git revision to delete from.
|
| 483 |
+
|
| 484 |
+
"""
|
| 485 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 486 |
+
paths = self.expand_path(path, recursive=recursive, maxdepth=maxdepth, revision=revision)
|
| 487 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 488 |
+
delete = [self.resolve_path(path).path for path in paths if not self.isdir(path)]
|
| 489 |
+
self._api.batch_bucket_files(resolved_path.bucket_id, delete=delete)
|
| 490 |
+
else:
|
| 491 |
+
paths_in_repo = [self.resolve_path(path).path for path in paths if not self.isdir(path)]
|
| 492 |
+
operations = [CommitOperationDelete(path_in_repo=path_in_repo) for path_in_repo in paths_in_repo]
|
| 493 |
+
commit_message = f"Delete {path} "
|
| 494 |
+
commit_message += "recursively " if recursive else ""
|
| 495 |
+
commit_message += f"up to depth {maxdepth} " if maxdepth is not None else ""
|
| 496 |
+
# TODO: use `commit_description` to list all the deleted paths?
|
| 497 |
+
self._api.create_commit(
|
| 498 |
+
repo_id=resolved_path.repo_id,
|
| 499 |
+
repo_type=resolved_path.repo_type,
|
| 500 |
+
token=self.token,
|
| 501 |
+
operations=operations,
|
| 502 |
+
revision=resolved_path.revision,
|
| 503 |
+
commit_message=kwargs.get("commit_message", commit_message),
|
| 504 |
+
commit_description=kwargs.get("commit_description"),
|
| 505 |
+
)
|
| 506 |
+
self.invalidate_cache(path=resolved_path.unresolve())
|
| 507 |
+
|
| 508 |
+
def ls(
|
| 509 |
+
self, path: str, detail: bool = True, refresh: bool = False, revision: Optional[str] = None, **kwargs
|
| 510 |
+
) -> list[Union[str, dict[str, Any]]]:
|
| 511 |
+
"""
|
| 512 |
+
List the contents of a directory.
|
| 513 |
+
|
| 514 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.ls).
|
| 515 |
+
|
| 516 |
+
> [!WARNING]
|
| 517 |
+
> Note: When possible, use `HfApi.list_repo_tree()` for better performance.
|
| 518 |
+
|
| 519 |
+
Args:
|
| 520 |
+
path (`str`):
|
| 521 |
+
Path to the directory.
|
| 522 |
+
detail (`bool`, *optional*):
|
| 523 |
+
If True, returns a list of dictionaries containing file information. If False,
|
| 524 |
+
returns a list of file paths. Defaults to True.
|
| 525 |
+
refresh (`bool`, *optional*):
|
| 526 |
+
If True, bypass the cache and fetch the latest data. Defaults to False.
|
| 527 |
+
revision (`str`, *optional*):
|
| 528 |
+
The git revision to list from.
|
| 529 |
+
|
| 530 |
+
Returns:
|
| 531 |
+
`list[Union[str, dict[str, Any]]]`: List of file paths (if detail=False) or list of file information
|
| 532 |
+
dictionaries (if detail=True).
|
| 533 |
+
"""
|
| 534 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 535 |
+
path = resolved_path.unresolve()
|
| 536 |
+
try:
|
| 537 |
+
out = self._ls_tree(path, refresh=refresh, revision=revision, **kwargs)
|
| 538 |
+
except EntryNotFoundError:
|
| 539 |
+
# Path could be a file
|
| 540 |
+
if not resolved_path.path:
|
| 541 |
+
_raise_file_not_found(path, None)
|
| 542 |
+
out = self._ls_tree(self._parent(path), refresh=refresh, revision=revision, **kwargs)
|
| 543 |
+
out = [o for o in out if o["name"] == path]
|
| 544 |
+
if len(out) == 0:
|
| 545 |
+
_raise_file_not_found(path, None)
|
| 546 |
+
return out if detail else [o["name"] for o in out]
|
| 547 |
+
|
| 548 |
+
def _ls_tree(
|
| 549 |
+
self,
|
| 550 |
+
path: str,
|
| 551 |
+
recursive: bool = False,
|
| 552 |
+
refresh: bool = False,
|
| 553 |
+
revision: Optional[str] = None,
|
| 554 |
+
expand_info: Optional[bool] = None,
|
| 555 |
+
maxdepth: Optional[int] = None,
|
| 556 |
+
):
|
| 557 |
+
expand_info = (
|
| 558 |
+
expand_info if expand_info is not None else (self.expand_info if self.expand_info is not None else False)
|
| 559 |
+
)
|
| 560 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 561 |
+
path = resolved_path.unresolve()
|
| 562 |
+
root_path = resolved_path.root
|
| 563 |
+
maxdepth = maxdepth if recursive else 1
|
| 564 |
+
|
| 565 |
+
out = []
|
| 566 |
+
if path in self.dircache and not refresh:
|
| 567 |
+
cached_path_infos = self.dircache[path]
|
| 568 |
+
out.extend(cached_path_infos)
|
| 569 |
+
dirs_not_in_dircache = []
|
| 570 |
+
if recursive:
|
| 571 |
+
# Use BFS to traverse the cache and build the "recursive "output
|
| 572 |
+
# (The Hub uses a so-called "tree first" strategy for the tree endpoint but we sort the output to follow the spec so the result is (eventually) the same)
|
| 573 |
+
depth = 2
|
| 574 |
+
dirs_to_visit = deque(
|
| 575 |
+
[(depth, path_info) for path_info in cached_path_infos if path_info["type"] == "directory"]
|
| 576 |
+
)
|
| 577 |
+
while dirs_to_visit:
|
| 578 |
+
depth, dir_info = dirs_to_visit.popleft()
|
| 579 |
+
if maxdepth is None or depth <= maxdepth:
|
| 580 |
+
if dir_info["name"] not in self.dircache:
|
| 581 |
+
dirs_not_in_dircache.append(dir_info["name"])
|
| 582 |
+
else:
|
| 583 |
+
cached_path_infos = self.dircache[dir_info["name"]]
|
| 584 |
+
out.extend(cached_path_infos)
|
| 585 |
+
dirs_to_visit.extend(
|
| 586 |
+
[
|
| 587 |
+
(depth + 1, path_info)
|
| 588 |
+
for path_info in cached_path_infos
|
| 589 |
+
if path_info["type"] == "directory"
|
| 590 |
+
]
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
dirs_not_expanded = []
|
| 594 |
+
if expand_info and isinstance(resolved_path, HfFileSystemResolvedRepositoryPath):
|
| 595 |
+
# Check if there are directories in repos with non-expanded entries
|
| 596 |
+
dirs_not_expanded = [self._parent(o["name"]) for o in out if o["last_commit"] is None]
|
| 597 |
+
|
| 598 |
+
if (recursive and dirs_not_in_dircache) or (expand_info and dirs_not_expanded):
|
| 599 |
+
# If the dircache is incomplete, find the common path of the missing and non-expanded entries
|
| 600 |
+
# and extend the output with the result of `_ls_tree(common_path, recursive=True)`
|
| 601 |
+
common_prefix = os.path.commonprefix(dirs_not_in_dircache + dirs_not_expanded)
|
| 602 |
+
# Get the parent directory if the common prefix itself is not a directory
|
| 603 |
+
common_path = (
|
| 604 |
+
common_prefix.rstrip("/")
|
| 605 |
+
if common_prefix.endswith("/")
|
| 606 |
+
or common_prefix == root_path
|
| 607 |
+
or common_prefix in chain(dirs_not_in_dircache, dirs_not_expanded)
|
| 608 |
+
else self._parent(common_prefix)
|
| 609 |
+
)
|
| 610 |
+
if maxdepth is not None:
|
| 611 |
+
common_path_depth = common_path[len(path) :].count("/")
|
| 612 |
+
maxdepth -= common_path_depth
|
| 613 |
+
out = [o for o in out if not o["name"].startswith(common_path + "/")]
|
| 614 |
+
for cached_path in list(self.dircache):
|
| 615 |
+
if cached_path.startswith(common_path + "/"):
|
| 616 |
+
self.dircache.pop(cached_path, None)
|
| 617 |
+
self.dircache.pop(common_path, None)
|
| 618 |
+
out.extend(
|
| 619 |
+
self._ls_tree(
|
| 620 |
+
common_path,
|
| 621 |
+
recursive=recursive,
|
| 622 |
+
refresh=True,
|
| 623 |
+
revision=revision,
|
| 624 |
+
expand_info=expand_info,
|
| 625 |
+
maxdepth=maxdepth,
|
| 626 |
+
)
|
| 627 |
+
)
|
| 628 |
+
else:
|
| 629 |
+
tree: Iterable[Union[RepoFile, RepoFolder, BucketFile, BucketFolder]]
|
| 630 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 631 |
+
tree = self._list_bucket_tree_with_folders(
|
| 632 |
+
resolved_path.bucket_id,
|
| 633 |
+
prefix=resolved_path.path,
|
| 634 |
+
recursive=recursive,
|
| 635 |
+
)
|
| 636 |
+
else:
|
| 637 |
+
tree = self._api.list_repo_tree(
|
| 638 |
+
resolved_path.repo_id,
|
| 639 |
+
resolved_path.path,
|
| 640 |
+
recursive=recursive,
|
| 641 |
+
expand=expand_info,
|
| 642 |
+
revision=resolved_path.revision,
|
| 643 |
+
repo_type=resolved_path.repo_type,
|
| 644 |
+
)
|
| 645 |
+
for path_info in tree:
|
| 646 |
+
cache_path = root_path + "/" + path_info.path
|
| 647 |
+
if isinstance(path_info, RepoFile):
|
| 648 |
+
cache_path_info = {
|
| 649 |
+
"name": cache_path,
|
| 650 |
+
"size": path_info.size,
|
| 651 |
+
"type": "file",
|
| 652 |
+
"blob_id": path_info.blob_id,
|
| 653 |
+
"lfs": path_info.lfs,
|
| 654 |
+
"xet_hash": path_info.xet_hash,
|
| 655 |
+
"last_commit": path_info.last_commit,
|
| 656 |
+
"security": path_info.security,
|
| 657 |
+
}
|
| 658 |
+
elif isinstance(path_info, BucketFile):
|
| 659 |
+
cache_path_info = {
|
| 660 |
+
"name": cache_path,
|
| 661 |
+
"size": path_info.size,
|
| 662 |
+
"type": "file",
|
| 663 |
+
"xet_hash": path_info.xet_hash,
|
| 664 |
+
"mtime": path_info.mtime,
|
| 665 |
+
"uploaded_at": path_info.uploaded_at,
|
| 666 |
+
}
|
| 667 |
+
elif isinstance(path_info, RepoFolder):
|
| 668 |
+
cache_path_info = {
|
| 669 |
+
"name": cache_path,
|
| 670 |
+
"size": 0,
|
| 671 |
+
"type": "directory",
|
| 672 |
+
"tree_id": path_info.tree_id,
|
| 673 |
+
"last_commit": path_info.last_commit,
|
| 674 |
+
}
|
| 675 |
+
else:
|
| 676 |
+
cache_path_info = {
|
| 677 |
+
"name": cache_path,
|
| 678 |
+
"size": 0,
|
| 679 |
+
"type": "directory",
|
| 680 |
+
"uploaded_at": path_info.uploaded_at,
|
| 681 |
+
}
|
| 682 |
+
parent_path = self._parent(cache_path_info["name"])
|
| 683 |
+
self.dircache.setdefault(parent_path, []).append(cache_path_info)
|
| 684 |
+
depth = cache_path[len(path) :].count("/")
|
| 685 |
+
if maxdepth is None or depth <= maxdepth:
|
| 686 |
+
out.append(cache_path_info)
|
| 687 |
+
return out
|
| 688 |
+
|
| 689 |
+
def _list_bucket_tree_with_folders(
|
| 690 |
+
self, bucket_id: str, prefix: str, recursive: bool
|
| 691 |
+
) -> Iterable[Union[BucketFile, BucketFolder]]:
|
| 692 |
+
"""Same as `HfApi.list_bucket_tree` but always includes folders"""
|
| 693 |
+
bucket_files = self._api.list_bucket_tree(bucket_id, prefix, recursive=recursive)
|
| 694 |
+
bucket_folders: dict[str, BucketFolder] = {}
|
| 695 |
+
min_depth = 1 + prefix.count("/") if prefix else 0
|
| 696 |
+
out: list[Union[BucketFile, BucketFolder]] = []
|
| 697 |
+
|
| 698 |
+
for bucket_entry in bucket_files:
|
| 699 |
+
out.append(bucket_entry)
|
| 700 |
+
|
| 701 |
+
# If recursive=False, both files and folders are returned by the server => nothing to do
|
| 702 |
+
if not recursive:
|
| 703 |
+
continue
|
| 704 |
+
|
| 705 |
+
# Otherwise, let's rebuild BucketFolders manually
|
| 706 |
+
for parent_bucket_folder_str in list(PurePosixPath(bucket_entry.path).parents)[: -min_depth - 1]:
|
| 707 |
+
parent_bucket_folder = BucketFolder(
|
| 708 |
+
type="directory", path=str(parent_bucket_folder_str), uploaded_at=bucket_entry.uploaded_at
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
# If folder not visited yet, add it
|
| 712 |
+
if parent_bucket_folder.path not in bucket_folders:
|
| 713 |
+
out.append(parent_bucket_folder)
|
| 714 |
+
bucket_folders[parent_bucket_folder.path] = parent_bucket_folder
|
| 715 |
+
continue
|
| 716 |
+
|
| 717 |
+
# Otherwise, get back BucketFolder object and update its 'uploaded_at'
|
| 718 |
+
if parent_bucket_folder.uploaded_at is not None:
|
| 719 |
+
bucket_folder = bucket_folders[parent_bucket_folder.path]
|
| 720 |
+
if bucket_folder.uploaded_at is None or (
|
| 721 |
+
bucket_folder.uploaded_at < parent_bucket_folder.uploaded_at
|
| 722 |
+
):
|
| 723 |
+
bucket_folder.uploaded_at = parent_bucket_folder.uploaded_at
|
| 724 |
+
|
| 725 |
+
if not out:
|
| 726 |
+
raise EntryNotFoundError(f"File not found in bucket '{bucket_id}': '{prefix}'")
|
| 727 |
+
return out
|
| 728 |
+
|
| 729 |
+
def walk(self, path: str, *args, **kwargs) -> Iterator[tuple[str, list[str], list[str]]]:
|
| 730 |
+
"""
|
| 731 |
+
Return all files below the given path.
|
| 732 |
+
|
| 733 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.walk).
|
| 734 |
+
|
| 735 |
+
Args:
|
| 736 |
+
path (`str`):
|
| 737 |
+
Root path to list files from.
|
| 738 |
+
|
| 739 |
+
Returns:
|
| 740 |
+
`Iterator[tuple[str, list[str], list[str]]]`: An iterator of (path, list of directory names, list of file names) tuples.
|
| 741 |
+
"""
|
| 742 |
+
path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
|
| 743 |
+
yield from super().walk(path, *args, **kwargs)
|
| 744 |
+
|
| 745 |
+
def glob(self, path: str, maxdepth: Optional[int] = None, **kwargs) -> list[str]:
|
| 746 |
+
"""
|
| 747 |
+
Find files by glob-matching.
|
| 748 |
+
|
| 749 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.glob).
|
| 750 |
+
|
| 751 |
+
Args:
|
| 752 |
+
path (`str`):
|
| 753 |
+
Path pattern to match.
|
| 754 |
+
|
| 755 |
+
Returns:
|
| 756 |
+
`list[str]`: List of paths matching the pattern.
|
| 757 |
+
"""
|
| 758 |
+
path = self.resolve_path(path, revision=kwargs.get("revision")).unresolve()
|
| 759 |
+
return super().glob(path, maxdepth=maxdepth, **kwargs)
|
| 760 |
+
|
| 761 |
+
def find(
|
| 762 |
+
self,
|
| 763 |
+
path: str,
|
| 764 |
+
maxdepth: Optional[int] = None,
|
| 765 |
+
withdirs: bool = False,
|
| 766 |
+
detail: bool = False,
|
| 767 |
+
refresh: bool = False,
|
| 768 |
+
revision: Optional[str] = None,
|
| 769 |
+
**kwargs,
|
| 770 |
+
) -> Union[list[str], dict[str, dict[str, Any]]]:
|
| 771 |
+
"""
|
| 772 |
+
List all files below path.
|
| 773 |
+
|
| 774 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.find).
|
| 775 |
+
|
| 776 |
+
Args:
|
| 777 |
+
path (`str`):
|
| 778 |
+
Root path to list files from.
|
| 779 |
+
maxdepth (`int`, *optional*):
|
| 780 |
+
Maximum depth to descend into subdirectories.
|
| 781 |
+
withdirs (`bool`, *optional*):
|
| 782 |
+
Include directory paths in the output. Defaults to False.
|
| 783 |
+
detail (`bool`, *optional*):
|
| 784 |
+
If True, returns a dict mapping paths to file information. Defaults to False.
|
| 785 |
+
refresh (`bool`, *optional*):
|
| 786 |
+
If True, bypass the cache and fetch the latest data. Defaults to False.
|
| 787 |
+
revision (`str`, *optional*):
|
| 788 |
+
The git revision to list from.
|
| 789 |
+
|
| 790 |
+
Returns:
|
| 791 |
+
`Union[list[str], dict[str, dict[str, Any]]]`: List of paths or dict of file information.
|
| 792 |
+
"""
|
| 793 |
+
if maxdepth is not None and maxdepth < 1:
|
| 794 |
+
raise ValueError("maxdepth must be at least 1")
|
| 795 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 796 |
+
path = resolved_path.unresolve()
|
| 797 |
+
try:
|
| 798 |
+
out = self._ls_tree(path, recursive=True, refresh=refresh, maxdepth=maxdepth, **kwargs)
|
| 799 |
+
except EntryNotFoundError:
|
| 800 |
+
# Path could be a file
|
| 801 |
+
try:
|
| 802 |
+
if self.info(path, revision=revision, **kwargs)["type"] == "file":
|
| 803 |
+
out = {path: {}}
|
| 804 |
+
else:
|
| 805 |
+
out = {}
|
| 806 |
+
except FileNotFoundError:
|
| 807 |
+
out = {}
|
| 808 |
+
else:
|
| 809 |
+
if not withdirs:
|
| 810 |
+
out = [o for o in out if o["type"] != "directory"]
|
| 811 |
+
else:
|
| 812 |
+
# If `withdirs=True`, include the directory itself to be consistent with the spec
|
| 813 |
+
path_info = self.info(path, **kwargs)
|
| 814 |
+
out = [path_info] + out if path_info["type"] == "directory" else out
|
| 815 |
+
out = {o["name"]: o for o in out}
|
| 816 |
+
names = sorted(out)
|
| 817 |
+
if not detail:
|
| 818 |
+
return names
|
| 819 |
+
else:
|
| 820 |
+
return {name: out[name] for name in names}
|
| 821 |
+
|
| 822 |
+
def cp_file(self, path1: str, path2: str, revision: Optional[str] = None, **kwargs) -> None:
|
| 823 |
+
"""
|
| 824 |
+
Copy a file within or between repositories.
|
| 825 |
+
|
| 826 |
+
> [!WARNING]
|
| 827 |
+
> Note: When possible, use `HfApi.upload_file()` for better performance.
|
| 828 |
+
|
| 829 |
+
Args:
|
| 830 |
+
path1 (`str`):
|
| 831 |
+
Source path to copy from.
|
| 832 |
+
path2 (`str`):
|
| 833 |
+
Destination path to copy to.
|
| 834 |
+
revision (`str`, *optional*):
|
| 835 |
+
The git revision to copy from.
|
| 836 |
+
|
| 837 |
+
"""
|
| 838 |
+
resolved_path1 = self.resolve_path(path1, revision=revision)
|
| 839 |
+
resolved_path2 = self.resolve_path(path2, revision=revision)
|
| 840 |
+
if isinstance(resolved_path1, HfFileSystemResolvedBucketPath) or isinstance(
|
| 841 |
+
resolved_path2, HfFileSystemResolvedBucketPath
|
| 842 |
+
):
|
| 843 |
+
raise NotImplementedError("Copy from/to buckets is not available yet")
|
| 844 |
+
|
| 845 |
+
same_repo = (
|
| 846 |
+
resolved_path1.repo_type == resolved_path2.repo_type and resolved_path1.repo_id == resolved_path2.repo_id
|
| 847 |
+
)
|
| 848 |
+
|
| 849 |
+
if same_repo:
|
| 850 |
+
commit_message = f"Copy {path1} to {path2}"
|
| 851 |
+
self._api.create_commit(
|
| 852 |
+
repo_id=resolved_path1.repo_id,
|
| 853 |
+
repo_type=resolved_path1.repo_type,
|
| 854 |
+
revision=resolved_path2.revision,
|
| 855 |
+
commit_message=kwargs.get("commit_message", commit_message),
|
| 856 |
+
commit_description=kwargs.get("commit_description", ""),
|
| 857 |
+
operations=[
|
| 858 |
+
CommitOperationCopy(
|
| 859 |
+
src_path_in_repo=resolved_path1.path_in_repo,
|
| 860 |
+
path_in_repo=resolved_path2.path_in_repo,
|
| 861 |
+
src_revision=resolved_path1.revision,
|
| 862 |
+
)
|
| 863 |
+
],
|
| 864 |
+
)
|
| 865 |
+
else:
|
| 866 |
+
with self.open(path1, "rb", revision=resolved_path1.revision) as f:
|
| 867 |
+
content = f.read()
|
| 868 |
+
commit_message = f"Copy {path1} to {path2}"
|
| 869 |
+
self._api.upload_file(
|
| 870 |
+
path_or_fileobj=content,
|
| 871 |
+
path_in_repo=resolved_path2.path_in_repo,
|
| 872 |
+
repo_id=resolved_path2.repo_id,
|
| 873 |
+
token=self.token,
|
| 874 |
+
repo_type=resolved_path2.repo_type,
|
| 875 |
+
revision=resolved_path2.revision,
|
| 876 |
+
commit_message=kwargs.get("commit_message", commit_message),
|
| 877 |
+
commit_description=kwargs.get("commit_description"),
|
| 878 |
+
)
|
| 879 |
+
self.invalidate_cache(path=resolved_path1.unresolve())
|
| 880 |
+
self.invalidate_cache(path=resolved_path2.unresolve())
|
| 881 |
+
|
| 882 |
+
def modified(self, path: str, **kwargs) -> datetime:
|
| 883 |
+
"""
|
| 884 |
+
Get the last modified time of a file.
|
| 885 |
+
|
| 886 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.modified).
|
| 887 |
+
|
| 888 |
+
Args:
|
| 889 |
+
path (`str`):
|
| 890 |
+
Path to the file.
|
| 891 |
+
|
| 892 |
+
Returns:
|
| 893 |
+
`datetime`: Last modified time of the file.
|
| 894 |
+
"""
|
| 895 |
+
info = self.info(path, **{**kwargs, "expand_info": True}) # type: ignore
|
| 896 |
+
if "last_commit" in info:
|
| 897 |
+
if info["last_commit"] is None:
|
| 898 |
+
raise NotImplementedError(f"'modified' is not implemented for repository paths like '{path}'")
|
| 899 |
+
return info["last_commit"].date
|
| 900 |
+
elif "mtime" in info and info["mtime"]:
|
| 901 |
+
return info["mtime"]
|
| 902 |
+
elif "uploaded_at" in info and info["uploaded_at"]:
|
| 903 |
+
return info["uploaded_at"]
|
| 904 |
+
else:
|
| 905 |
+
raise NotImplementedError(f"Cannot determined 'modified' for path '{path}' (info: {info})")
|
| 906 |
+
|
| 907 |
+
def info(self, path: str, refresh: bool = False, revision: Optional[str] = None, **kwargs) -> dict[str, Any]:
|
| 908 |
+
"""
|
| 909 |
+
Get information about a file or directory.
|
| 910 |
+
|
| 911 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.info).
|
| 912 |
+
|
| 913 |
+
> [!WARNING]
|
| 914 |
+
> Note: When possible, use `HfApi.get_paths_info()` or `HfApi.repo_info()` for better performance
|
| 915 |
+
> (or `HfApi.get_bucket_paths_info()` or `HfApi.bucket_info()` for buckets)
|
| 916 |
+
|
| 917 |
+
Args:
|
| 918 |
+
path (`str`):
|
| 919 |
+
Path to get info for.
|
| 920 |
+
refresh (`bool`, *optional*):
|
| 921 |
+
If True, bypass the cache and fetch the latest data. Defaults to False.
|
| 922 |
+
revision (`str`, *optional*):
|
| 923 |
+
The git revision to get info from.
|
| 924 |
+
|
| 925 |
+
Returns:
|
| 926 |
+
`dict[str, Any]`: Dictionary containing file information (type, size, commit info, etc.).
|
| 927 |
+
|
| 928 |
+
"""
|
| 929 |
+
resolved_path = self.resolve_path(path, revision=revision)
|
| 930 |
+
path = resolved_path.unresolve()
|
| 931 |
+
expand_info = kwargs.get(
|
| 932 |
+
"expand_info", self.expand_info if self.expand_info is not None else False
|
| 933 |
+
) # don't expose it as a parameter in the public API to follow the spec
|
| 934 |
+
out: Optional[dict[str, Any]]
|
| 935 |
+
if not resolved_path.path:
|
| 936 |
+
# Path is the root directory
|
| 937 |
+
out = {
|
| 938 |
+
"name": path,
|
| 939 |
+
"size": 0,
|
| 940 |
+
"type": "directory",
|
| 941 |
+
}
|
| 942 |
+
if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath):
|
| 943 |
+
out["last_commit"] = None
|
| 944 |
+
if isinstance(resolved_path, HfFileSystemResolvedRepositoryPath) and expand_info:
|
| 945 |
+
last_commit = self._api.list_repo_commits(
|
| 946 |
+
resolved_path.repo_id, repo_type=resolved_path.repo_type, revision=resolved_path.revision
|
| 947 |
+
)[-1]
|
| 948 |
+
out = {
|
| 949 |
+
**out,
|
| 950 |
+
"tree_id": None, # TODO: tree_id of the root directory?
|
| 951 |
+
"last_commit": LastCommitInfo(
|
| 952 |
+
oid=last_commit.commit_id, title=last_commit.title, date=last_commit.created_at
|
| 953 |
+
),
|
| 954 |
+
}
|
| 955 |
+
elif isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 956 |
+
parent_path = self._parent(path)
|
| 957 |
+
# Fill the cache with cheap call
|
| 958 |
+
self.ls(parent_path, refresh=refresh)
|
| 959 |
+
out1 = [o for o in self.dircache[parent_path] if o["name"] == path]
|
| 960 |
+
if not out1:
|
| 961 |
+
_raise_file_not_found(path, None)
|
| 962 |
+
out = out1[0]
|
| 963 |
+
else:
|
| 964 |
+
out = None
|
| 965 |
+
parent_path = self._parent(path)
|
| 966 |
+
if not expand_info and parent_path not in self.dircache:
|
| 967 |
+
# Fill the cache with cheap call
|
| 968 |
+
self.ls(parent_path)
|
| 969 |
+
if parent_path in self.dircache:
|
| 970 |
+
# Check if the path is in the cache
|
| 971 |
+
out1 = [o for o in self.dircache[parent_path] if o["name"] == path]
|
| 972 |
+
if not out1:
|
| 973 |
+
_raise_file_not_found(path, None)
|
| 974 |
+
out = out1[0]
|
| 975 |
+
if refresh or out is None or (expand_info and out and out["last_commit"] is None):
|
| 976 |
+
paths_info = self._api.get_paths_info(
|
| 977 |
+
resolved_path.repo_id,
|
| 978 |
+
resolved_path.path_in_repo,
|
| 979 |
+
expand=expand_info,
|
| 980 |
+
revision=resolved_path.revision,
|
| 981 |
+
repo_type=resolved_path.repo_type,
|
| 982 |
+
)
|
| 983 |
+
if not paths_info:
|
| 984 |
+
_raise_file_not_found(path, None)
|
| 985 |
+
path_info = paths_info[0]
|
| 986 |
+
root_path = HfFileSystemResolvedRepositoryPath(
|
| 987 |
+
resolved_path.repo_type,
|
| 988 |
+
resolved_path.repo_id,
|
| 989 |
+
resolved_path.revision,
|
| 990 |
+
path_in_repo="",
|
| 991 |
+
_raw_revision=resolved_path._raw_revision,
|
| 992 |
+
).unresolve()
|
| 993 |
+
if isinstance(path_info, RepoFile):
|
| 994 |
+
out = {
|
| 995 |
+
"name": root_path + "/" + path_info.path,
|
| 996 |
+
"size": path_info.size,
|
| 997 |
+
"type": "file",
|
| 998 |
+
"blob_id": path_info.blob_id,
|
| 999 |
+
"lfs": path_info.lfs,
|
| 1000 |
+
"xet_hash": path_info.xet_hash,
|
| 1001 |
+
"last_commit": path_info.last_commit,
|
| 1002 |
+
"security": path_info.security,
|
| 1003 |
+
}
|
| 1004 |
+
else:
|
| 1005 |
+
out = {
|
| 1006 |
+
"name": root_path + "/" + path_info.path,
|
| 1007 |
+
"size": 0,
|
| 1008 |
+
"type": "directory",
|
| 1009 |
+
"tree_id": path_info.tree_id,
|
| 1010 |
+
"last_commit": path_info.last_commit,
|
| 1011 |
+
}
|
| 1012 |
+
if not expand_info:
|
| 1013 |
+
out = {k: out[k] for k in ["name", "size", "type"]}
|
| 1014 |
+
assert out is not None
|
| 1015 |
+
return out
|
| 1016 |
+
|
| 1017 |
+
def exists(self, path, **kwargs):
|
| 1018 |
+
"""
|
| 1019 |
+
Check if a file exists.
|
| 1020 |
+
|
| 1021 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.exists).
|
| 1022 |
+
|
| 1023 |
+
> [!WARNING]
|
| 1024 |
+
> Note: When possible, use `HfApi.file_exists()` for better performance.
|
| 1025 |
+
|
| 1026 |
+
Args:
|
| 1027 |
+
path (`str`):
|
| 1028 |
+
Path to check.
|
| 1029 |
+
|
| 1030 |
+
Returns:
|
| 1031 |
+
`bool`: True if file exists, False otherwise.
|
| 1032 |
+
"""
|
| 1033 |
+
try:
|
| 1034 |
+
if kwargs.get("refresh", False):
|
| 1035 |
+
self.invalidate_cache(path)
|
| 1036 |
+
|
| 1037 |
+
self.info(path, **kwargs)
|
| 1038 |
+
return True
|
| 1039 |
+
except: # noqa: E722
|
| 1040 |
+
return False
|
| 1041 |
+
|
| 1042 |
+
def isdir(self, path):
|
| 1043 |
+
"""
|
| 1044 |
+
Check if a path is a directory.
|
| 1045 |
+
|
| 1046 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isdir).
|
| 1047 |
+
|
| 1048 |
+
Args:
|
| 1049 |
+
path (`str`):
|
| 1050 |
+
Path to check.
|
| 1051 |
+
|
| 1052 |
+
Returns:
|
| 1053 |
+
`bool`: True if path is a directory, False otherwise.
|
| 1054 |
+
"""
|
| 1055 |
+
try:
|
| 1056 |
+
return self.info(path)["type"] == "directory"
|
| 1057 |
+
except OSError:
|
| 1058 |
+
return False
|
| 1059 |
+
|
| 1060 |
+
def isfile(self, path):
|
| 1061 |
+
"""
|
| 1062 |
+
Check if a path is a file.
|
| 1063 |
+
|
| 1064 |
+
For more details, refer to [fsspec documentation](https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.spec.AbstractFileSystem.isfile).
|
| 1065 |
+
|
| 1066 |
+
Args:
|
| 1067 |
+
path (`str`):
|
| 1068 |
+
Path to check.
|
| 1069 |
+
|
| 1070 |
+
Returns:
|
| 1071 |
+
`bool`: True if path is a file, False otherwise.
|
| 1072 |
+
"""
|
| 1073 |
+
try:
|
| 1074 |
+
return self.info(path)["type"] == "file"
|
| 1075 |
+
except: # noqa: E722
|
| 1076 |
+
return False
|
| 1077 |
+
|
| 1078 |
+
def url(self, path: str) -> str:
|
| 1079 |
+
"""
|
| 1080 |
+
Get the HTTP URL of the given path.
|
| 1081 |
+
|
| 1082 |
+
Args:
|
| 1083 |
+
path (`str`):
|
| 1084 |
+
Path to get URL for.
|
| 1085 |
+
|
| 1086 |
+
Returns:
|
| 1087 |
+
`str`: HTTP URL to access the file or directory on the Hub.
|
| 1088 |
+
"""
|
| 1089 |
+
resolved_path = self.resolve_path(path)
|
| 1090 |
+
if isinstance(resolved_path, HfFileSystemResolvedBucketPath):
|
| 1091 |
+
url = f"{self.endpoint}/buckets/{resolved_path.bucket_id}/resolve/{quote(resolved_path.path)}"
|
| 1092 |
+
else:
|
| 1093 |
+
url = hf_hub_url(
|
| 1094 |
+
resolved_path.repo_id,
|
| 1095 |
+
resolved_path.path_in_repo,
|
| 1096 |
+
repo_type=resolved_path.repo_type,
|
| 1097 |
+
revision=resolved_path.revision,
|
| 1098 |
+
endpoint=self.endpoint,
|
| 1099 |
+
)
|
| 1100 |
+
if self.isdir(path):
|
| 1101 |
+
url = url.replace("/resolve/", "/tree/", 1)
|
| 1102 |
+
return url
|
| 1103 |
+
|
| 1104 |
+
def get_file(self, rpath, lpath, callback=_DEFAULT_CALLBACK, outfile=None, **kwargs) -> None:
|
| 1105 |
+
"""
|
| 1106 |
+
Copy single remote file to local.
|
| 1107 |
+
|
| 1108 |
+
> [!WARNING]
|
| 1109 |
+
> Note: When possible, use `HfApi.hf_hub_download()` or `HfApi.download_bucket_files` for better performance.
|
| 1110 |
+
|
| 1111 |
+
Args:
|
| 1112 |
+
rpath (`str`):
|
| 1113 |
+
Remote path to download from.
|
| 1114 |
+
lpath (`str`):
|
| 1115 |
+
Local path to download to.
|
| 1116 |
+
callback (`Callback`, *optional*):
|
| 1117 |
+
Optional callback to track download progress. Defaults to no callback.
|
| 1118 |
+
outfile (`IO`, *optional*):
|
| 1119 |
+
Optional file-like object to write to. If provided, `lpath` is ignored.
|
| 1120 |
+
|
| 1121 |
+
"""
|
| 1122 |
+
revision = kwargs.get("revision")
|
| 1123 |
+
unhandled_kwargs = set(kwargs.keys()) - {"revision"}
|
| 1124 |
+
if not isinstance(callback, (NoOpCallback, TqdmCallback)) or len(unhandled_kwargs) > 0:
|
| 1125 |
+
# for now, let's not handle custom callbacks
|
| 1126 |
+
# and let's not handle custom kwargs
|
| 1127 |
+
return super().get_file(rpath, lpath, callback=callback, outfile=outfile, **kwargs)
|
| 1128 |
+
|
| 1129 |
+
# Taken from https://github.com/fsspec/filesystem_spec/blob/47b445ae4c284a82dd15e0287b1ffc410e8fc470/fsspec/spec.py#L883
|
| 1130 |
+
if isfilelike(lpath):
|
| 1131 |
+
outfile = lpath
|
| 1132 |
+
elif self.isdir(rpath):
|
| 1133 |
+
os.makedirs(lpath, exist_ok=True)
|
| 1134 |
+
return None
|
| 1135 |
+
|
| 1136 |
+
if isinstance(lpath, (str, Path)): # otherwise, let's assume it's a file-like object
|
| 1137 |
+
os.makedirs(os.path.dirname(lpath), exist_ok=True)
|
| 1138 |
+
|
| 1139 |
+
# Open file if not already open
|
| 1140 |
+
close_file = False
|
| 1141 |
+
if outfile is None:
|
| 1142 |
+
outfile = open(lpath, "wb")
|
| 1143 |
+
close_file = True
|
| 1144 |
+
initial_pos = outfile.tell()
|
| 1145 |
+
|
| 1146 |
+
# Custom implementation of `get_file` to use `http_get`.
|
| 1147 |
+
resolve_remote_path = self.resolve_path(rpath, revision=revision)
|
| 1148 |
+
expected_size = self.info(rpath, revision=revision)["size"]
|
| 1149 |
+
callback.set_size(expected_size)
|
| 1150 |
+
try:
|
| 1151 |
+
http_get(
|
| 1152 |
+
url=self.url(resolve_remote_path.unresolve()),
|
| 1153 |
+
temp_file=outfile, # type: ignore[arg-type]
|
| 1154 |
+
displayed_filename=rpath,
|
| 1155 |
+
expected_size=expected_size,
|
| 1156 |
+
resume_size=0,
|
| 1157 |
+
headers=self._api._build_hf_headers(),
|
| 1158 |
+
_tqdm_bar=callback.tqdm if isinstance(callback, TqdmCallback) else None,
|
| 1159 |
+
)
|
| 1160 |
+
outfile.seek(initial_pos)
|
| 1161 |
+
finally:
|
| 1162 |
+
# Close file only if we opened it ourselves
|
| 1163 |
+
if close_file:
|
| 1164 |
+
outfile.close()
|
| 1165 |
+
|
| 1166 |
+
@property
|
| 1167 |
+
def transaction(self):
|
| 1168 |
+
"""A context within which files are committed together upon exit
|
| 1169 |
+
|
| 1170 |
+
Requires the file class to implement `.commit()` and `.discard()`
|
| 1171 |
+
for the normal and exception cases.
|
| 1172 |
+
"""
|
| 1173 |
+
# Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L231
|
| 1174 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1733
|
| 1175 |
+
raise NotImplementedError("Transactional commits are not supported.")
|
| 1176 |
+
|
| 1177 |
+
def start_transaction(self):
|
| 1178 |
+
"""Begin write transaction for deferring files, non-context version"""
|
| 1179 |
+
# Taken from https://github.com/fsspec/filesystem_spec/blob/3fbb6fee33b46cccb015607630843dea049d3243/fsspec/spec.py#L241
|
| 1180 |
+
# See https://github.com/huggingface/huggingface_hub/issues/1733
|
| 1181 |
+
raise NotImplementedError("Transactional commits are not supported.")
|
| 1182 |
+
|
| 1183 |
+
def __reduce__(self):
|
| 1184 |
+
# re-populate the instance cache at HfFileSystem._cache and re-populate the state of every instance
|
| 1185 |
+
return make_instance, (
|
| 1186 |
+
type(self),
|
| 1187 |
+
self.storage_args,
|
| 1188 |
+
self.storage_options,
|
| 1189 |
+
self._get_instance_state(),
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
def _get_instance_state(self):
|
| 1193 |
+
return {
|
| 1194 |
+
"dircache": deepcopy(self.dircache),
|
| 1195 |
+
"_repo_and_revision_exists_cache": deepcopy(self._repo_and_revision_exists_cache),
|
| 1196 |
+
"_bucket_exists_cache": deepcopy(self._bucket_exists_cache),
|
| 1197 |
+
}
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
class HfFileSystemFile(fsspec.spec.AbstractBufferedFile):
|
| 1201 |
+
def __init__(self, fs: HfFileSystem, path: str, revision: Optional[str] = None, **kwargs):
|
| 1202 |
+
try:
|
| 1203 |
+
self.resolved_path = fs.resolve_path(path, revision=revision)
|
| 1204 |
+
except FileNotFoundError as e:
|
| 1205 |
+
if "w" in kwargs.get("mode", ""):
|
| 1206 |
+
raise FileNotFoundError(
|
| 1207 |
+
f"{e}.\nMake sure the repository and revision exist before writing data."
|
| 1208 |
+
) from e
|
| 1209 |
+
raise
|
| 1210 |
+
super().__init__(fs, self.resolved_path.unresolve(), **kwargs)
|
| 1211 |
+
self.fs: HfFileSystem
|
| 1212 |
+
|
| 1213 |
+
def __del__(self):
|
| 1214 |
+
if not hasattr(self, "resolved_path"):
|
| 1215 |
+
# Means that the constructor failed. Nothing to do.
|
| 1216 |
+
return
|
| 1217 |
+
return super().__del__()
|
| 1218 |
+
|
| 1219 |
+
def _fetch_range(self, start: int, end: int) -> bytes:
|
| 1220 |
+
headers = {
|
| 1221 |
+
"range": f"bytes={start}-{end - 1}",
|
| 1222 |
+
**self.fs._api._build_hf_headers(),
|
| 1223 |
+
}
|
| 1224 |
+
url = self.url()
|
| 1225 |
+
r = http_backoff("GET", url, headers=headers, timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT)
|
| 1226 |
+
hf_raise_for_status(r)
|
| 1227 |
+
return r.content
|
| 1228 |
+
|
| 1229 |
+
def _initiate_upload(self) -> None:
|
| 1230 |
+
self.temp_file = tempfile.NamedTemporaryFile(prefix="hffs-", delete=False)
|
| 1231 |
+
|
| 1232 |
+
def _upload_chunk(self, final: bool = False) -> None:
|
| 1233 |
+
self.buffer.seek(0)
|
| 1234 |
+
block = self.buffer.read()
|
| 1235 |
+
self.temp_file.write(block)
|
| 1236 |
+
if final:
|
| 1237 |
+
self.temp_file.close()
|
| 1238 |
+
if isinstance(self.resolved_path, HfFileSystemResolvedBucketPath):
|
| 1239 |
+
self.fs._api.batch_bucket_files(
|
| 1240 |
+
self.resolved_path.bucket_id, add=[(self.temp_file.name, self.resolved_path.path)]
|
| 1241 |
+
)
|
| 1242 |
+
else:
|
| 1243 |
+
self.fs._api.upload_file(
|
| 1244 |
+
path_or_fileobj=self.temp_file.name,
|
| 1245 |
+
path_in_repo=self.resolved_path.path_in_repo,
|
| 1246 |
+
repo_id=self.resolved_path.repo_id,
|
| 1247 |
+
token=self.fs.token,
|
| 1248 |
+
repo_type=self.resolved_path.repo_type,
|
| 1249 |
+
revision=self.resolved_path.revision,
|
| 1250 |
+
commit_message=self.kwargs.get("commit_message"),
|
| 1251 |
+
commit_description=self.kwargs.get("commit_description"),
|
| 1252 |
+
)
|
| 1253 |
+
os.remove(self.temp_file.name)
|
| 1254 |
+
self.fs.invalidate_cache(
|
| 1255 |
+
path=self.resolved_path.unresolve(),
|
| 1256 |
+
)
|
| 1257 |
+
|
| 1258 |
+
def read(self, length=-1):
|
| 1259 |
+
"""Read remote file.
|
| 1260 |
+
|
| 1261 |
+
If `length` is not provided or is -1, the entire file is downloaded and read. On POSIX systems the file is
|
| 1262 |
+
loaded in memory directly. Otherwise, the file is downloaded to a temporary file and read from there.
|
| 1263 |
+
"""
|
| 1264 |
+
if self.mode == "rb" and (length is None or length == -1) and self.loc == 0:
|
| 1265 |
+
with self.fs.open(self.path, "rb", block_size=0) as f: # block_size=0 enables fast streaming
|
| 1266 |
+
out = f.read()
|
| 1267 |
+
self.loc += len(out)
|
| 1268 |
+
return out
|
| 1269 |
+
return super().read(length)
|
| 1270 |
+
|
| 1271 |
+
def url(self) -> str:
|
| 1272 |
+
return self.fs.url(self.path)
|
| 1273 |
+
|
| 1274 |
+
|
| 1275 |
+
class HfFileSystemStreamFile(fsspec.spec.AbstractBufferedFile):
|
| 1276 |
+
def __init__(
|
| 1277 |
+
self,
|
| 1278 |
+
fs: HfFileSystem,
|
| 1279 |
+
path: str,
|
| 1280 |
+
mode: str = "rb",
|
| 1281 |
+
revision: Optional[str] = None,
|
| 1282 |
+
block_size: int = 0,
|
| 1283 |
+
cache_type: str = "none",
|
| 1284 |
+
**kwargs,
|
| 1285 |
+
):
|
| 1286 |
+
if block_size != 0:
|
| 1287 |
+
raise ValueError(f"HfFileSystemStreamFile only supports block_size=0 but got {block_size}")
|
| 1288 |
+
if cache_type != "none":
|
| 1289 |
+
raise ValueError(f"HfFileSystemStreamFile only supports cache_type='none' but got {cache_type}")
|
| 1290 |
+
if "w" in mode:
|
| 1291 |
+
raise ValueError(f"HfFileSystemStreamFile only supports reading but got mode='{mode}'")
|
| 1292 |
+
try:
|
| 1293 |
+
self.resolved_path = fs.resolve_path(path, revision=revision)
|
| 1294 |
+
except FileNotFoundError as e:
|
| 1295 |
+
if "w" in kwargs.get("mode", ""):
|
| 1296 |
+
raise FileNotFoundError(
|
| 1297 |
+
f"{e}.\nMake sure the repository and revision exist before writing data."
|
| 1298 |
+
) from e
|
| 1299 |
+
# avoid an unnecessary .info() call to instantiate .details
|
| 1300 |
+
self.details = {"name": self.resolved_path.unresolve(), "size": None}
|
| 1301 |
+
super().__init__(
|
| 1302 |
+
fs, self.resolved_path.unresolve(), mode=mode, block_size=block_size, cache_type=cache_type, **kwargs
|
| 1303 |
+
)
|
| 1304 |
+
self.response: Optional[httpx.Response] = None
|
| 1305 |
+
self.fs: HfFileSystem
|
| 1306 |
+
self._exit_stack = ExitStack()
|
| 1307 |
+
# streaming state
|
| 1308 |
+
self._stream_iterator: Optional[Iterator[bytes]] = None
|
| 1309 |
+
self._stream_buffer = bytearray()
|
| 1310 |
+
|
| 1311 |
+
def seek(self, loc: int, whence: int = 0):
|
| 1312 |
+
if loc == 0 and whence == 1:
|
| 1313 |
+
return
|
| 1314 |
+
if loc == self.loc and whence == 0:
|
| 1315 |
+
return
|
| 1316 |
+
raise ValueError("Cannot seek streaming HF file")
|
| 1317 |
+
|
| 1318 |
+
def read(self, length: int = -1):
|
| 1319 |
+
"""Read the remote file.
|
| 1320 |
+
|
| 1321 |
+
If the file is already open, we reuse the connection.
|
| 1322 |
+
Otherwise, open a new connection and read from it.
|
| 1323 |
+
|
| 1324 |
+
If reading the stream fails, we retry with a new connection.
|
| 1325 |
+
"""
|
| 1326 |
+
if self.response is None:
|
| 1327 |
+
self._open_connection()
|
| 1328 |
+
|
| 1329 |
+
retried_once = False
|
| 1330 |
+
while True:
|
| 1331 |
+
try:
|
| 1332 |
+
if self.response is None or self._stream_iterator is None:
|
| 1333 |
+
return b"" # Already read the entire file
|
| 1334 |
+
out = self._read_from_stream(self._stream_iterator, length)
|
| 1335 |
+
self.loc += len(out)
|
| 1336 |
+
return out
|
| 1337 |
+
except Exception:
|
| 1338 |
+
if self.response is not None:
|
| 1339 |
+
self.response.close()
|
| 1340 |
+
if retried_once: # Already retried once, give up
|
| 1341 |
+
raise
|
| 1342 |
+
# First failure, retry with range header
|
| 1343 |
+
self._open_connection()
|
| 1344 |
+
retried_once = True
|
| 1345 |
+
|
| 1346 |
+
def _read_from_stream(self, iterator: Iterator[bytes], length: int = -1) -> bytes:
|
| 1347 |
+
"""Read up to `length` bytes from stream buffer and stream.
|
| 1348 |
+
|
| 1349 |
+
If length < 0, read until EOF.
|
| 1350 |
+
|
| 1351 |
+
If EOF is reached before length, fewer bytes may be returned.
|
| 1352 |
+
"""
|
| 1353 |
+
if length == 0:
|
| 1354 |
+
return b""
|
| 1355 |
+
|
| 1356 |
+
if length < 0:
|
| 1357 |
+
buf = bytearray(self._stream_buffer)
|
| 1358 |
+
self._stream_buffer.clear()
|
| 1359 |
+
for chunk in iterator:
|
| 1360 |
+
buf.extend(chunk)
|
| 1361 |
+
return bytes(buf)
|
| 1362 |
+
|
| 1363 |
+
if length <= len(self._stream_buffer):
|
| 1364 |
+
result = bytes(self._stream_buffer[:length])
|
| 1365 |
+
del self._stream_buffer[:length]
|
| 1366 |
+
return result
|
| 1367 |
+
|
| 1368 |
+
buf = bytearray(self._stream_buffer)
|
| 1369 |
+
self._stream_buffer.clear()
|
| 1370 |
+
for chunk in iterator:
|
| 1371 |
+
need = length - len(buf)
|
| 1372 |
+
if need > len(chunk):
|
| 1373 |
+
buf.extend(chunk)
|
| 1374 |
+
else:
|
| 1375 |
+
buf.extend(chunk[:need])
|
| 1376 |
+
self._stream_buffer.extend(chunk[need:])
|
| 1377 |
+
break
|
| 1378 |
+
return bytes(buf)
|
| 1379 |
+
|
| 1380 |
+
def url(self) -> str:
|
| 1381 |
+
return self.fs.url(self.path)
|
| 1382 |
+
|
| 1383 |
+
def __del__(self):
|
| 1384 |
+
if not hasattr(self, "resolved_path"):
|
| 1385 |
+
# Means that the constructor failed. Nothing to do.
|
| 1386 |
+
return
|
| 1387 |
+
self._exit_stack.close()
|
| 1388 |
+
return super().__del__()
|
| 1389 |
+
|
| 1390 |
+
def __reduce__(self):
|
| 1391 |
+
return reopen, (self.fs, self.path, self.mode, self.blocksize, self.cache.name)
|
| 1392 |
+
|
| 1393 |
+
def _open_connection(self):
|
| 1394 |
+
"""Open a connection to the remote file."""
|
| 1395 |
+
# reset streaming state
|
| 1396 |
+
self._stream_buffer.clear()
|
| 1397 |
+
self._stream_iterator = None
|
| 1398 |
+
|
| 1399 |
+
url = self.url()
|
| 1400 |
+
headers = self.fs._api._build_hf_headers()
|
| 1401 |
+
if self.loc > 0:
|
| 1402 |
+
headers["Range"] = f"bytes={self.loc}-"
|
| 1403 |
+
self.response = self._exit_stack.enter_context(
|
| 1404 |
+
http_stream_backoff(
|
| 1405 |
+
"GET",
|
| 1406 |
+
url,
|
| 1407 |
+
headers=headers,
|
| 1408 |
+
timeout=constants.HF_HUB_DOWNLOAD_TIMEOUT,
|
| 1409 |
+
)
|
| 1410 |
+
)
|
| 1411 |
+
|
| 1412 |
+
try:
|
| 1413 |
+
hf_raise_for_status(self.response)
|
| 1414 |
+
except HfHubHTTPError as e:
|
| 1415 |
+
if e.response.status_code == 416:
|
| 1416 |
+
# Range not satisfiable => means that we have already read the entire file
|
| 1417 |
+
self.response = None
|
| 1418 |
+
return
|
| 1419 |
+
raise
|
| 1420 |
+
|
| 1421 |
+
self._stream_iterator = self.response.iter_bytes()
|
| 1422 |
+
|
| 1423 |
+
|
| 1424 |
+
def safe_revision(revision: str) -> str:
|
| 1425 |
+
return revision if SPECIAL_REFS_REVISION_REGEX.match(revision) else safe_quote(revision)
|
| 1426 |
+
|
| 1427 |
+
|
| 1428 |
+
def safe_quote(s: str) -> str:
|
| 1429 |
+
return quote(s, safe="")
|
| 1430 |
+
|
| 1431 |
+
|
| 1432 |
+
def _raise_file_not_found(path: str, err: Optional[Exception]) -> NoReturn:
|
| 1433 |
+
msg = path
|
| 1434 |
+
if isinstance(err, RepositoryNotFoundError):
|
| 1435 |
+
msg = f"{path} (repository not found)"
|
| 1436 |
+
elif isinstance(err, RevisionNotFoundError):
|
| 1437 |
+
msg = f"{path} (revision not found)"
|
| 1438 |
+
elif isinstance(err, HFValidationError):
|
| 1439 |
+
msg = f"{path} (invalid repository id)"
|
| 1440 |
+
raise FileNotFoundError(msg) from err
|
| 1441 |
+
|
| 1442 |
+
|
| 1443 |
+
def reopen(fs: HfFileSystem, path: str, mode: str, block_size: int, cache_type: str):
|
| 1444 |
+
return fs.open(path, mode=mode, block_size=block_size, cache_type=cache_type)
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
def make_instance(cls, args, kwargs, instance_state):
|
| 1448 |
+
fs = cls(*args, **kwargs)
|
| 1449 |
+
for attr, state_value in instance_state.items():
|
| 1450 |
+
setattr(fs, attr, state_value)
|
| 1451 |
+
return fs
|
| 1452 |
+
|
| 1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
| 3 |
+
import os
|
| 4 |
+
from dataclasses import Field, asdict, dataclass, is_dataclass
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any, Callable, ClassVar, Optional, Protocol, Type, TypeVar, Union
|
| 7 |
+
|
| 8 |
+
import packaging.version
|
| 9 |
+
|
| 10 |
+
from . import constants
|
| 11 |
+
from .errors import EntryNotFoundError, HfHubHTTPError
|
| 12 |
+
from .file_download import hf_hub_download
|
| 13 |
+
from .hf_api import HfApi
|
| 14 |
+
from .repocard import ModelCard, ModelCardData
|
| 15 |
+
from .utils import (
|
| 16 |
+
SoftTemporaryDirectory,
|
| 17 |
+
is_jsonable,
|
| 18 |
+
is_safetensors_available,
|
| 19 |
+
is_simple_optional_type,
|
| 20 |
+
is_torch_available,
|
| 21 |
+
logging,
|
| 22 |
+
unwrap_simple_optional_type,
|
| 23 |
+
validate_hf_hub_args,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if is_torch_available():
|
| 28 |
+
import torch # type: ignore
|
| 29 |
+
|
| 30 |
+
if is_safetensors_available():
|
| 31 |
+
import safetensors
|
| 32 |
+
from safetensors.torch import load_model as load_model_as_safetensor
|
| 33 |
+
from safetensors.torch import save_model as save_model_as_safetensor
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# Type alias for dataclass instances, copied from https://github.com/python/typeshed/blob/9f28171658b9ca6c32a7cb93fbb99fc92b17858b/stdlib/_typeshed/__init__.pyi#L349
|
| 40 |
+
class DataclassInstance(Protocol):
|
| 41 |
+
__dataclass_fields__: ClassVar[dict[str, Field]]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Generic variable that is either ModelHubMixin or a subclass thereof
|
| 45 |
+
T = TypeVar("T", bound="ModelHubMixin")
|
| 46 |
+
# Generic variable to represent an args type
|
| 47 |
+
ARGS_T = TypeVar("ARGS_T")
|
| 48 |
+
ENCODER_T = Callable[[ARGS_T], Any]
|
| 49 |
+
DECODER_T = Callable[[Any], ARGS_T]
|
| 50 |
+
CODER_T = tuple[ENCODER_T, DECODER_T]
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
DEFAULT_MODEL_CARD = """
|
| 54 |
+
---
|
| 55 |
+
# For reference on model card metadata, see the spec: https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
|
| 56 |
+
# Doc / guide: https://huggingface.co/docs/hub/model-cards
|
| 57 |
+
{{ card_data }}
|
| 58 |
+
---
|
| 59 |
+
|
| 60 |
+
This model has been pushed to the Hub using the [PytorchModelHubMixin](https://huggingface.co/docs/huggingface_hub/package_reference/mixins#huggingface_hub.PyTorchModelHubMixin) integration:
|
| 61 |
+
- Code: {{ repo_url | default("[More Information Needed]", true) }}
|
| 62 |
+
- Paper: {{ paper_url | default("[More Information Needed]", true) }}
|
| 63 |
+
- Docs: {{ docs_url | default("[More Information Needed]", true) }}
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass
|
| 68 |
+
class MixinInfo:
|
| 69 |
+
model_card_template: str
|
| 70 |
+
model_card_data: ModelCardData
|
| 71 |
+
docs_url: Optional[str] = None
|
| 72 |
+
paper_url: Optional[str] = None
|
| 73 |
+
repo_url: Optional[str] = None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class ModelHubMixin:
|
| 77 |
+
"""
|
| 78 |
+
A generic mixin to integrate ANY machine learning framework with the Hub.
|
| 79 |
+
|
| 80 |
+
To integrate your framework, your model class must inherit from this class. Custom logic for saving/loading models
|
| 81 |
+
have to be overwritten in [`_from_pretrained`] and [`_save_pretrained`]. [`PyTorchModelHubMixin`] is a good example
|
| 82 |
+
of mixin integration with the Hub. Check out our [integration guide](../guides/integrations) for more instructions.
|
| 83 |
+
|
| 84 |
+
When inheriting from [`ModelHubMixin`], you can define class-level attributes. These attributes are not passed to
|
| 85 |
+
`__init__` but to the class definition itself. This is useful to define metadata about the library integrating
|
| 86 |
+
[`ModelHubMixin`].
|
| 87 |
+
|
| 88 |
+
For more details on how to integrate the mixin with your library, checkout the [integration guide](../guides/integrations).
|
| 89 |
+
|
| 90 |
+
Args:
|
| 91 |
+
repo_url (`str`, *optional*):
|
| 92 |
+
URL of the library repository. Used to generate model card.
|
| 93 |
+
paper_url (`str`, *optional*):
|
| 94 |
+
URL of the library paper. Used to generate model card.
|
| 95 |
+
docs_url (`str`, *optional*):
|
| 96 |
+
URL of the library documentation. Used to generate model card.
|
| 97 |
+
model_card_template (`str`, *optional*):
|
| 98 |
+
Template of the model card. Used to generate model card. Defaults to a generic template.
|
| 99 |
+
language (`str` or `list[str]`, *optional*):
|
| 100 |
+
Language supported by the library. Used to generate model card.
|
| 101 |
+
library_name (`str`, *optional*):
|
| 102 |
+
Name of the library integrating ModelHubMixin. Used to generate model card.
|
| 103 |
+
license (`str`, *optional*):
|
| 104 |
+
License of the library integrating ModelHubMixin. Used to generate model card.
|
| 105 |
+
E.g: "apache-2.0"
|
| 106 |
+
license_name (`str`, *optional*):
|
| 107 |
+
Name of the library integrating ModelHubMixin. Used to generate model card.
|
| 108 |
+
Only used if `license` is set to `other`.
|
| 109 |
+
E.g: "coqui-public-model-license".
|
| 110 |
+
license_link (`str`, *optional*):
|
| 111 |
+
URL to the license of the library integrating ModelHubMixin. Used to generate model card.
|
| 112 |
+
Only used if `license` is set to `other` and `license_name` is set.
|
| 113 |
+
E.g: "https://coqui.ai/cpml".
|
| 114 |
+
pipeline_tag (`str`, *optional*):
|
| 115 |
+
Tag of the pipeline. Used to generate model card. E.g. "text-classification".
|
| 116 |
+
tags (`list[str]`, *optional*):
|
| 117 |
+
Tags to be added to the model card. Used to generate model card. E.g. ["computer-vision"]
|
| 118 |
+
coders (`dict[Type, tuple[Callable, Callable]]`, *optional*):
|
| 119 |
+
Dictionary of custom types and their encoders/decoders. Used to encode/decode arguments that are not
|
| 120 |
+
jsonable by default. E.g. dataclasses, argparse.Namespace, OmegaConf, etc.
|
| 121 |
+
|
| 122 |
+
Example:
|
| 123 |
+
|
| 124 |
+
```python
|
| 125 |
+
>>> from huggingface_hub import ModelHubMixin
|
| 126 |
+
|
| 127 |
+
# Inherit from ModelHubMixin
|
| 128 |
+
>>> class MyCustomModel(
|
| 129 |
+
... ModelHubMixin,
|
| 130 |
+
... library_name="my-library",
|
| 131 |
+
... tags=["computer-vision"],
|
| 132 |
+
... repo_url="https://github.com/huggingface/my-cool-library",
|
| 133 |
+
... paper_url="https://arxiv.org/abs/2304.12244",
|
| 134 |
+
... docs_url="https://huggingface.co/docs/my-cool-library",
|
| 135 |
+
... # ^ optional metadata to generate model card
|
| 136 |
+
... ):
|
| 137 |
+
... def __init__(self, size: int = 512, device: str = "cpu"):
|
| 138 |
+
... # define how to initialize your model
|
| 139 |
+
... super().__init__()
|
| 140 |
+
... ...
|
| 141 |
+
...
|
| 142 |
+
... def _save_pretrained(self, save_directory: Path) -> None:
|
| 143 |
+
... # define how to serialize your model
|
| 144 |
+
... ...
|
| 145 |
+
...
|
| 146 |
+
... @classmethod
|
| 147 |
+
... def from_pretrained(
|
| 148 |
+
... cls: type[T],
|
| 149 |
+
... pretrained_model_name_or_path: Union[str, Path],
|
| 150 |
+
... *,
|
| 151 |
+
... force_download: bool = False,
|
| 152 |
+
... token: Optional[Union[str, bool]] = None,
|
| 153 |
+
... cache_dir: Optional[Union[str, Path]] = None,
|
| 154 |
+
... local_files_only: bool = False,
|
| 155 |
+
... revision: Optional[str] = None,
|
| 156 |
+
... **model_kwargs,
|
| 157 |
+
... ) -> T:
|
| 158 |
+
... # define how to deserialize your model
|
| 159 |
+
... ...
|
| 160 |
+
|
| 161 |
+
>>> model = MyCustomModel(size=256, device="gpu")
|
| 162 |
+
|
| 163 |
+
# Save model weights to local directory
|
| 164 |
+
>>> model.save_pretrained("my-awesome-model")
|
| 165 |
+
|
| 166 |
+
# Push model weights to the Hub
|
| 167 |
+
>>> model.push_to_hub("my-awesome-model")
|
| 168 |
+
|
| 169 |
+
# Download and initialize weights from the Hub
|
| 170 |
+
>>> reloaded_model = MyCustomModel.from_pretrained("username/my-awesome-model")
|
| 171 |
+
>>> reloaded_model.size
|
| 172 |
+
256
|
| 173 |
+
|
| 174 |
+
# Model card has been correctly populated
|
| 175 |
+
>>> from huggingface_hub import ModelCard
|
| 176 |
+
>>> card = ModelCard.load("username/my-awesome-model")
|
| 177 |
+
>>> card.data.tags
|
| 178 |
+
["x-custom-tag", "pytorch_model_hub_mixin", "model_hub_mixin"]
|
| 179 |
+
>>> card.data.library_name
|
| 180 |
+
"my-library"
|
| 181 |
+
```
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
_hub_mixin_config: Optional[Union[dict, DataclassInstance]] = None
|
| 185 |
+
# ^ optional config attribute automatically set in `from_pretrained`
|
| 186 |
+
_hub_mixin_info: MixinInfo
|
| 187 |
+
# ^ information about the library integrating ModelHubMixin (used to generate model card)
|
| 188 |
+
_hub_mixin_inject_config: bool # whether `_from_pretrained` expects `config` or not
|
| 189 |
+
_hub_mixin_init_parameters: dict[str, inspect.Parameter] # __init__ parameters
|
| 190 |
+
_hub_mixin_jsonable_default_values: dict[str, Any] # default values for __init__ parameters
|
| 191 |
+
_hub_mixin_jsonable_custom_types: tuple[Type, ...] # custom types that can be encoded/decoded
|
| 192 |
+
_hub_mixin_coders: dict[Type, CODER_T] # encoders/decoders for custom types
|
| 193 |
+
# ^ internal values to handle config
|
| 194 |
+
|
| 195 |
+
def __init_subclass__(
|
| 196 |
+
cls,
|
| 197 |
+
*,
|
| 198 |
+
# Generic info for model card
|
| 199 |
+
repo_url: Optional[str] = None,
|
| 200 |
+
paper_url: Optional[str] = None,
|
| 201 |
+
docs_url: Optional[str] = None,
|
| 202 |
+
# Model card template
|
| 203 |
+
model_card_template: str = DEFAULT_MODEL_CARD,
|
| 204 |
+
# Model card metadata
|
| 205 |
+
language: Optional[list[str]] = None,
|
| 206 |
+
library_name: Optional[str] = None,
|
| 207 |
+
license: Optional[str] = None,
|
| 208 |
+
license_name: Optional[str] = None,
|
| 209 |
+
license_link: Optional[str] = None,
|
| 210 |
+
pipeline_tag: Optional[str] = None,
|
| 211 |
+
tags: Optional[list[str]] = None,
|
| 212 |
+
# How to encode/decode arguments with custom type into a JSON config?
|
| 213 |
+
coders: Optional[
|
| 214 |
+
dict[Type, CODER_T]
|
| 215 |
+
# Key is a type.
|
| 216 |
+
# Value is a tuple (encoder, decoder).
|
| 217 |
+
# Example: {MyCustomType: (lambda x: x.value, lambda data: MyCustomType(data))}
|
| 218 |
+
] = None,
|
| 219 |
+
) -> None:
|
| 220 |
+
"""Inspect __init__ signature only once when subclassing + handle modelcard."""
|
| 221 |
+
super().__init_subclass__()
|
| 222 |
+
|
| 223 |
+
# Will be reused when creating modelcard
|
| 224 |
+
tags = tags or []
|
| 225 |
+
tags.append("model_hub_mixin")
|
| 226 |
+
|
| 227 |
+
# Initialize MixinInfo if not existent
|
| 228 |
+
info = MixinInfo(model_card_template=model_card_template, model_card_data=ModelCardData())
|
| 229 |
+
|
| 230 |
+
# If parent class has a MixinInfo, inherit from it as a copy
|
| 231 |
+
if hasattr(cls, "_hub_mixin_info"):
|
| 232 |
+
# Inherit model card template from parent class if not explicitly set
|
| 233 |
+
if model_card_template == DEFAULT_MODEL_CARD:
|
| 234 |
+
info.model_card_template = cls._hub_mixin_info.model_card_template
|
| 235 |
+
|
| 236 |
+
# Inherit from parent model card data
|
| 237 |
+
info.model_card_data = ModelCardData(**cls._hub_mixin_info.model_card_data.to_dict())
|
| 238 |
+
|
| 239 |
+
# Inherit other info
|
| 240 |
+
info.docs_url = cls._hub_mixin_info.docs_url
|
| 241 |
+
info.paper_url = cls._hub_mixin_info.paper_url
|
| 242 |
+
info.repo_url = cls._hub_mixin_info.repo_url
|
| 243 |
+
cls._hub_mixin_info = info
|
| 244 |
+
|
| 245 |
+
# Update MixinInfo with metadata
|
| 246 |
+
if model_card_template is not None and model_card_template != DEFAULT_MODEL_CARD:
|
| 247 |
+
info.model_card_template = model_card_template
|
| 248 |
+
if repo_url is not None:
|
| 249 |
+
info.repo_url = repo_url
|
| 250 |
+
if paper_url is not None:
|
| 251 |
+
info.paper_url = paper_url
|
| 252 |
+
if docs_url is not None:
|
| 253 |
+
info.docs_url = docs_url
|
| 254 |
+
if language is not None:
|
| 255 |
+
info.model_card_data.language = language
|
| 256 |
+
if library_name is not None:
|
| 257 |
+
info.model_card_data.library_name = library_name
|
| 258 |
+
if license is not None:
|
| 259 |
+
info.model_card_data.license = license
|
| 260 |
+
if license_name is not None:
|
| 261 |
+
info.model_card_data.license_name = license_name
|
| 262 |
+
if license_link is not None:
|
| 263 |
+
info.model_card_data.license_link = license_link
|
| 264 |
+
if pipeline_tag is not None:
|
| 265 |
+
info.model_card_data.pipeline_tag = pipeline_tag
|
| 266 |
+
if tags is not None:
|
| 267 |
+
normalized_tags = list(tags)
|
| 268 |
+
if info.model_card_data.tags is not None:
|
| 269 |
+
info.model_card_data.tags.extend(normalized_tags)
|
| 270 |
+
else:
|
| 271 |
+
info.model_card_data.tags = normalized_tags
|
| 272 |
+
|
| 273 |
+
if info.model_card_data.tags is not None:
|
| 274 |
+
info.model_card_data.tags = sorted(set(info.model_card_data.tags))
|
| 275 |
+
|
| 276 |
+
# Handle encoders/decoders for args
|
| 277 |
+
cls._hub_mixin_coders = coders or {}
|
| 278 |
+
cls._hub_mixin_jsonable_custom_types = tuple(cls._hub_mixin_coders.keys())
|
| 279 |
+
|
| 280 |
+
# Inspect __init__ signature to handle config
|
| 281 |
+
cls._hub_mixin_init_parameters = dict(inspect.signature(cls.__init__).parameters)
|
| 282 |
+
cls._hub_mixin_jsonable_default_values = {
|
| 283 |
+
param.name: cls._encode_arg(param.default)
|
| 284 |
+
for param in cls._hub_mixin_init_parameters.values()
|
| 285 |
+
if param.default is not inspect.Parameter.empty and cls._is_jsonable(param.default)
|
| 286 |
+
}
|
| 287 |
+
cls._hub_mixin_inject_config = "config" in inspect.signature(cls._from_pretrained).parameters
|
| 288 |
+
|
| 289 |
+
def __new__(cls: type[T], *args, **kwargs) -> T:
|
| 290 |
+
"""Create a new instance of the class and handle config.
|
| 291 |
+
|
| 292 |
+
3 cases:
|
| 293 |
+
- If `self._hub_mixin_config` is already set, do nothing.
|
| 294 |
+
- If `config` is passed as a dataclass, set it as `self._hub_mixin_config`.
|
| 295 |
+
- Otherwise, build `self._hub_mixin_config` from default values and passed values.
|
| 296 |
+
"""
|
| 297 |
+
instance = super().__new__(cls)
|
| 298 |
+
|
| 299 |
+
# If `config` is already set, return early
|
| 300 |
+
if instance._hub_mixin_config is not None:
|
| 301 |
+
return instance
|
| 302 |
+
|
| 303 |
+
# Infer passed values
|
| 304 |
+
passed_values = {
|
| 305 |
+
**{
|
| 306 |
+
key: value
|
| 307 |
+
for key, value in zip(
|
| 308 |
+
# [1:] to skip `self` parameter
|
| 309 |
+
list(cls._hub_mixin_init_parameters)[1:],
|
| 310 |
+
args,
|
| 311 |
+
)
|
| 312 |
+
},
|
| 313 |
+
**kwargs,
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
# If config passed as dataclass => set it and return early
|
| 317 |
+
if is_dataclass(passed_values.get("config")):
|
| 318 |
+
instance._hub_mixin_config = passed_values["config"]
|
| 319 |
+
return instance
|
| 320 |
+
|
| 321 |
+
# Otherwise, build config from default + passed values
|
| 322 |
+
init_config = {
|
| 323 |
+
# default values
|
| 324 |
+
**cls._hub_mixin_jsonable_default_values,
|
| 325 |
+
# passed values
|
| 326 |
+
**{
|
| 327 |
+
key: cls._encode_arg(value) # Encode custom types as jsonable value
|
| 328 |
+
for key, value in passed_values.items()
|
| 329 |
+
if instance._is_jsonable(value) # Only if jsonable or we have a custom encoder
|
| 330 |
+
},
|
| 331 |
+
}
|
| 332 |
+
passed_config = init_config.pop("config", {})
|
| 333 |
+
|
| 334 |
+
# Populate `init_config` with provided config
|
| 335 |
+
if isinstance(passed_config, dict):
|
| 336 |
+
init_config.update(passed_config)
|
| 337 |
+
|
| 338 |
+
# Set `config` attribute and return
|
| 339 |
+
if init_config != {}:
|
| 340 |
+
instance._hub_mixin_config = init_config
|
| 341 |
+
return instance
|
| 342 |
+
|
| 343 |
+
@classmethod
|
| 344 |
+
def _is_jsonable(cls, value: Any) -> bool:
|
| 345 |
+
"""Check if a value is JSON serializable."""
|
| 346 |
+
if is_dataclass(value):
|
| 347 |
+
return True
|
| 348 |
+
if isinstance(value, cls._hub_mixin_jsonable_custom_types):
|
| 349 |
+
return True
|
| 350 |
+
return is_jsonable(value)
|
| 351 |
+
|
| 352 |
+
@classmethod
|
| 353 |
+
def _encode_arg(cls, arg: Any) -> Any:
|
| 354 |
+
"""Encode an argument into a JSON serializable format."""
|
| 355 |
+
if is_dataclass(arg):
|
| 356 |
+
return asdict(arg) # type: ignore[arg-type]
|
| 357 |
+
for type_, (encoder, _) in cls._hub_mixin_coders.items():
|
| 358 |
+
if isinstance(arg, type_):
|
| 359 |
+
if arg is None:
|
| 360 |
+
return None
|
| 361 |
+
return encoder(arg)
|
| 362 |
+
return arg
|
| 363 |
+
|
| 364 |
+
@classmethod
|
| 365 |
+
def _decode_arg(cls, expected_type: type[ARGS_T], value: Any) -> Optional[ARGS_T]:
|
| 366 |
+
"""Decode a JSON serializable value into an argument."""
|
| 367 |
+
if is_simple_optional_type(expected_type):
|
| 368 |
+
if value is None:
|
| 369 |
+
return None
|
| 370 |
+
expected_type = unwrap_simple_optional_type(expected_type) # type: ignore[assignment]
|
| 371 |
+
# Dataclass => handle it
|
| 372 |
+
if is_dataclass(expected_type):
|
| 373 |
+
return _load_dataclass(expected_type, value) # type: ignore[return-value]
|
| 374 |
+
# Otherwise => check custom decoders
|
| 375 |
+
for type_, (_, decoder) in cls._hub_mixin_coders.items():
|
| 376 |
+
if inspect.isclass(expected_type) and issubclass(expected_type, type_):
|
| 377 |
+
return decoder(value)
|
| 378 |
+
# Otherwise => don't decode
|
| 379 |
+
return value
|
| 380 |
+
|
| 381 |
+
def save_pretrained(
|
| 382 |
+
self,
|
| 383 |
+
save_directory: Union[str, Path],
|
| 384 |
+
*,
|
| 385 |
+
config: Optional[Union[dict, DataclassInstance]] = None,
|
| 386 |
+
repo_id: Optional[str] = None,
|
| 387 |
+
push_to_hub: bool = False,
|
| 388 |
+
model_card_kwargs: Optional[dict[str, Any]] = None,
|
| 389 |
+
**push_to_hub_kwargs,
|
| 390 |
+
) -> Optional[str]:
|
| 391 |
+
"""
|
| 392 |
+
Save weights in local directory.
|
| 393 |
+
|
| 394 |
+
Args:
|
| 395 |
+
save_directory (`str` or `Path`):
|
| 396 |
+
Path to directory in which the model weights and configuration will be saved.
|
| 397 |
+
config (`dict` or `DataclassInstance`, *optional*):
|
| 398 |
+
Model configuration specified as a key/value dictionary or a dataclass instance.
|
| 399 |
+
push_to_hub (`bool`, *optional*, defaults to `False`):
|
| 400 |
+
Whether or not to push your model to the Huggingface Hub after saving it.
|
| 401 |
+
repo_id (`str`, *optional*):
|
| 402 |
+
ID of your repository on the Hub. Used only if `push_to_hub=True`. Will default to the folder name if
|
| 403 |
+
not provided.
|
| 404 |
+
model_card_kwargs (`dict[str, Any]`, *optional*):
|
| 405 |
+
Additional arguments passed to the model card template to customize the model card.
|
| 406 |
+
push_to_hub_kwargs:
|
| 407 |
+
Additional key word arguments passed along to the [`~ModelHubMixin.push_to_hub`] method.
|
| 408 |
+
Returns:
|
| 409 |
+
`str` or `None`: url of the commit on the Hub if `push_to_hub=True`, `None` otherwise.
|
| 410 |
+
"""
|
| 411 |
+
save_directory = Path(save_directory)
|
| 412 |
+
save_directory.mkdir(parents=True, exist_ok=True)
|
| 413 |
+
|
| 414 |
+
# Remove config.json if already exists. After `_save_pretrained` we don't want to overwrite config.json
|
| 415 |
+
# as it might have been saved by the custom `_save_pretrained` already. However we do want to overwrite
|
| 416 |
+
# an existing config.json if it was not saved by `_save_pretrained`.
|
| 417 |
+
config_path = save_directory / constants.CONFIG_NAME
|
| 418 |
+
config_path.unlink(missing_ok=True)
|
| 419 |
+
|
| 420 |
+
# save model weights/files (framework-specific)
|
| 421 |
+
self._save_pretrained(save_directory)
|
| 422 |
+
|
| 423 |
+
# save config (if provided and if not serialized yet in `_save_pretrained`)
|
| 424 |
+
if config is None:
|
| 425 |
+
config = self._hub_mixin_config
|
| 426 |
+
if config is not None:
|
| 427 |
+
if is_dataclass(config):
|
| 428 |
+
config = asdict(config) # type: ignore[arg-type]
|
| 429 |
+
if not config_path.exists():
|
| 430 |
+
config_str = json.dumps(config, sort_keys=True, indent=2)
|
| 431 |
+
config_path.write_text(config_str)
|
| 432 |
+
|
| 433 |
+
# save model card
|
| 434 |
+
model_card_path = save_directory / "README.md"
|
| 435 |
+
model_card_kwargs = model_card_kwargs if model_card_kwargs is not None else {}
|
| 436 |
+
if not model_card_path.exists(): # do not overwrite if already exists
|
| 437 |
+
self.generate_model_card(**model_card_kwargs).save(save_directory / "README.md")
|
| 438 |
+
|
| 439 |
+
# push to the Hub if required
|
| 440 |
+
if push_to_hub:
|
| 441 |
+
kwargs = push_to_hub_kwargs.copy() # soft-copy to avoid mutating input
|
| 442 |
+
if config is not None: # kwarg for `push_to_hub`
|
| 443 |
+
kwargs["config"] = config
|
| 444 |
+
if repo_id is None:
|
| 445 |
+
repo_id = save_directory.name # Defaults to `save_directory` name
|
| 446 |
+
return self.push_to_hub(repo_id=repo_id, model_card_kwargs=model_card_kwargs, **kwargs)
|
| 447 |
+
return None
|
| 448 |
+
|
| 449 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 450 |
+
"""
|
| 451 |
+
Overwrite this method in subclass to define how to save your model.
|
| 452 |
+
Check out our [integration guide](../guides/integrations) for instructions.
|
| 453 |
+
|
| 454 |
+
Args:
|
| 455 |
+
save_directory (`str` or `Path`):
|
| 456 |
+
Path to directory in which the model weights and configuration will be saved.
|
| 457 |
+
"""
|
| 458 |
+
raise NotImplementedError
|
| 459 |
+
|
| 460 |
+
@classmethod
|
| 461 |
+
@validate_hf_hub_args
|
| 462 |
+
def from_pretrained(
|
| 463 |
+
cls: type[T],
|
| 464 |
+
pretrained_model_name_or_path: Union[str, Path],
|
| 465 |
+
*,
|
| 466 |
+
force_download: bool = False,
|
| 467 |
+
token: Optional[Union[str, bool]] = None,
|
| 468 |
+
cache_dir: Optional[Union[str, Path]] = None,
|
| 469 |
+
local_files_only: bool = False,
|
| 470 |
+
revision: Optional[str] = None,
|
| 471 |
+
**model_kwargs,
|
| 472 |
+
) -> T:
|
| 473 |
+
"""
|
| 474 |
+
Download a model from the Huggingface Hub and instantiate it.
|
| 475 |
+
|
| 476 |
+
Args:
|
| 477 |
+
pretrained_model_name_or_path (`str`, `Path`):
|
| 478 |
+
- Either the `model_id` (string) of a model hosted on the Hub, e.g. `bigscience/bloom`.
|
| 479 |
+
- Or a path to a `directory` containing model weights saved using
|
| 480 |
+
[`~transformers.PreTrainedModel.save_pretrained`], e.g., `../path/to/my_model_directory/`.
|
| 481 |
+
revision (`str`, *optional*):
|
| 482 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id.
|
| 483 |
+
Defaults to the latest commit on `main` branch.
|
| 484 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 485 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
| 486 |
+
the existing cache.
|
| 487 |
+
token (`str` or `bool`, *optional*):
|
| 488 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
| 489 |
+
cached when running `hf auth login`.
|
| 490 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 491 |
+
Path to the folder where cached files are stored.
|
| 492 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 493 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
| 494 |
+
model_kwargs (`dict`, *optional*):
|
| 495 |
+
Additional kwargs to pass to the model during initialization.
|
| 496 |
+
"""
|
| 497 |
+
model_id = str(pretrained_model_name_or_path)
|
| 498 |
+
config_file: Optional[str] = None
|
| 499 |
+
if os.path.isdir(model_id):
|
| 500 |
+
if constants.CONFIG_NAME in os.listdir(model_id):
|
| 501 |
+
config_file = os.path.join(model_id, constants.CONFIG_NAME)
|
| 502 |
+
else:
|
| 503 |
+
logger.warning(f"{constants.CONFIG_NAME} not found in {Path(model_id).resolve()}")
|
| 504 |
+
else:
|
| 505 |
+
try:
|
| 506 |
+
config_file = hf_hub_download(
|
| 507 |
+
repo_id=model_id,
|
| 508 |
+
filename=constants.CONFIG_NAME,
|
| 509 |
+
revision=revision,
|
| 510 |
+
cache_dir=cache_dir,
|
| 511 |
+
force_download=force_download,
|
| 512 |
+
token=token,
|
| 513 |
+
local_files_only=local_files_only,
|
| 514 |
+
)
|
| 515 |
+
except HfHubHTTPError as e:
|
| 516 |
+
logger.info(f"{constants.CONFIG_NAME} not found on the HuggingFace Hub: {str(e)}")
|
| 517 |
+
|
| 518 |
+
# Read config
|
| 519 |
+
config = None
|
| 520 |
+
if config_file is not None:
|
| 521 |
+
with open(config_file, "r", encoding="utf-8") as f:
|
| 522 |
+
config = json.load(f)
|
| 523 |
+
|
| 524 |
+
# Decode custom types in config
|
| 525 |
+
for key, value in config.items():
|
| 526 |
+
if key in cls._hub_mixin_init_parameters:
|
| 527 |
+
expected_type = cls._hub_mixin_init_parameters[key].annotation
|
| 528 |
+
if expected_type is not inspect.Parameter.empty:
|
| 529 |
+
config[key] = cls._decode_arg(expected_type, value)
|
| 530 |
+
|
| 531 |
+
# Populate model_kwargs from config
|
| 532 |
+
for param in cls._hub_mixin_init_parameters.values():
|
| 533 |
+
if param.name not in model_kwargs and param.name in config:
|
| 534 |
+
model_kwargs[param.name] = config[param.name]
|
| 535 |
+
|
| 536 |
+
# Check if `config` argument was passed at init
|
| 537 |
+
if "config" in cls._hub_mixin_init_parameters and "config" not in model_kwargs:
|
| 538 |
+
# Decode `config` argument if it was passed
|
| 539 |
+
config_annotation = cls._hub_mixin_init_parameters["config"].annotation
|
| 540 |
+
config = cls._decode_arg(config_annotation, config)
|
| 541 |
+
|
| 542 |
+
# Forward config to model initialization
|
| 543 |
+
model_kwargs["config"] = config
|
| 544 |
+
|
| 545 |
+
# Inject config if `**kwargs` are expected
|
| 546 |
+
if is_dataclass(cls):
|
| 547 |
+
for key in cls.__dataclass_fields__:
|
| 548 |
+
if key not in model_kwargs and key in config:
|
| 549 |
+
model_kwargs[key] = config[key]
|
| 550 |
+
elif any(param.kind == inspect.Parameter.VAR_KEYWORD for param in cls._hub_mixin_init_parameters.values()):
|
| 551 |
+
for key, value in config.items(): # type: ignore[union-attr]
|
| 552 |
+
if key not in model_kwargs:
|
| 553 |
+
model_kwargs[key] = value
|
| 554 |
+
|
| 555 |
+
# Finally, also inject if `_from_pretrained` expects it
|
| 556 |
+
if cls._hub_mixin_inject_config and "config" not in model_kwargs:
|
| 557 |
+
model_kwargs["config"] = config
|
| 558 |
+
|
| 559 |
+
instance = cls._from_pretrained(
|
| 560 |
+
model_id=str(model_id),
|
| 561 |
+
revision=revision,
|
| 562 |
+
cache_dir=cache_dir,
|
| 563 |
+
force_download=force_download,
|
| 564 |
+
local_files_only=local_files_only,
|
| 565 |
+
token=token,
|
| 566 |
+
**model_kwargs,
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# Implicitly set the config as instance attribute if not already set by the class
|
| 570 |
+
# This way `config` will be available when calling `save_pretrained` or `push_to_hub`.
|
| 571 |
+
if config is not None and (getattr(instance, "_hub_mixin_config", None) in (None, {})):
|
| 572 |
+
instance._hub_mixin_config = config
|
| 573 |
+
|
| 574 |
+
return instance
|
| 575 |
+
|
| 576 |
+
@classmethod
|
| 577 |
+
def _from_pretrained(
|
| 578 |
+
cls: type[T],
|
| 579 |
+
*,
|
| 580 |
+
model_id: str,
|
| 581 |
+
revision: Optional[str],
|
| 582 |
+
cache_dir: Optional[Union[str, Path]],
|
| 583 |
+
force_download: bool,
|
| 584 |
+
local_files_only: bool,
|
| 585 |
+
token: Optional[Union[str, bool]],
|
| 586 |
+
**model_kwargs,
|
| 587 |
+
) -> T:
|
| 588 |
+
"""Overwrite this method in subclass to define how to load your model from pretrained.
|
| 589 |
+
|
| 590 |
+
Use [`hf_hub_download`] or [`snapshot_download`] to download files from the Hub before loading them. Most
|
| 591 |
+
args taken as input can be directly passed to those 2 methods. If needed, you can add more arguments to this
|
| 592 |
+
method using "model_kwargs". For example [`PyTorchModelHubMixin._from_pretrained`] takes as input a `map_location`
|
| 593 |
+
parameter to set on which device the model should be loaded.
|
| 594 |
+
|
| 595 |
+
Check out our [integration guide](../guides/integrations) for more instructions.
|
| 596 |
+
|
| 597 |
+
Args:
|
| 598 |
+
model_id (`str`):
|
| 599 |
+
ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
|
| 600 |
+
revision (`str`, *optional*):
|
| 601 |
+
Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
|
| 602 |
+
latest commit on `main` branch.
|
| 603 |
+
force_download (`bool`, *optional*, defaults to `False`):
|
| 604 |
+
Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
|
| 605 |
+
the existing cache.
|
| 606 |
+
token (`str` or `bool`, *optional*):
|
| 607 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
| 608 |
+
cached when running `hf auth login`.
|
| 609 |
+
cache_dir (`str`, `Path`, *optional*):
|
| 610 |
+
Path to the folder where cached files are stored.
|
| 611 |
+
local_files_only (`bool`, *optional*, defaults to `False`):
|
| 612 |
+
If `True`, avoid downloading the file and return the path to the local cached file if it exists.
|
| 613 |
+
model_kwargs:
|
| 614 |
+
Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
|
| 615 |
+
"""
|
| 616 |
+
raise NotImplementedError
|
| 617 |
+
|
| 618 |
+
@validate_hf_hub_args
|
| 619 |
+
def push_to_hub(
|
| 620 |
+
self,
|
| 621 |
+
repo_id: str,
|
| 622 |
+
*,
|
| 623 |
+
config: Optional[Union[dict, DataclassInstance]] = None,
|
| 624 |
+
commit_message: str = "Push model using huggingface_hub.",
|
| 625 |
+
private: Optional[bool] = None,
|
| 626 |
+
token: Optional[str] = None,
|
| 627 |
+
branch: Optional[str] = None,
|
| 628 |
+
create_pr: Optional[bool] = None,
|
| 629 |
+
allow_patterns: Optional[Union[list[str], str]] = None,
|
| 630 |
+
ignore_patterns: Optional[Union[list[str], str]] = None,
|
| 631 |
+
delete_patterns: Optional[Union[list[str], str]] = None,
|
| 632 |
+
model_card_kwargs: Optional[dict[str, Any]] = None,
|
| 633 |
+
) -> str:
|
| 634 |
+
"""
|
| 635 |
+
Upload model checkpoint to the Hub.
|
| 636 |
+
|
| 637 |
+
Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
|
| 638 |
+
`delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
|
| 639 |
+
details.
|
| 640 |
+
|
| 641 |
+
Args:
|
| 642 |
+
repo_id (`str`):
|
| 643 |
+
ID of the repository to push to (example: `"username/my-model"`).
|
| 644 |
+
config (`dict` or `DataclassInstance`, *optional*):
|
| 645 |
+
Model configuration specified as a key/value dictionary or a dataclass instance.
|
| 646 |
+
commit_message (`str`, *optional*):
|
| 647 |
+
Message to commit while pushing.
|
| 648 |
+
private (`bool`, *optional*):
|
| 649 |
+
Whether the repository created should be private.
|
| 650 |
+
If `None` (default), the repo will be public unless the organization's default is private.
|
| 651 |
+
token (`str`, *optional*):
|
| 652 |
+
The token to use as HTTP bearer authorization for remote files. By default, it will use the token
|
| 653 |
+
cached when running `hf auth login`.
|
| 654 |
+
branch (`str`, *optional*):
|
| 655 |
+
The git branch on which to push the model. This defaults to `"main"`.
|
| 656 |
+
create_pr (`boolean`, *optional*):
|
| 657 |
+
Whether or not to create a Pull Request from `branch` with that commit. Defaults to `False`.
|
| 658 |
+
allow_patterns (`list[str]` or `str`, *optional*):
|
| 659 |
+
If provided, only files matching at least one pattern are pushed.
|
| 660 |
+
ignore_patterns (`list[str]` or `str`, *optional*):
|
| 661 |
+
If provided, files matching any of the patterns are not pushed.
|
| 662 |
+
delete_patterns (`list[str]` or `str`, *optional*):
|
| 663 |
+
If provided, remote files matching any of the patterns will be deleted from the repo.
|
| 664 |
+
model_card_kwargs (`dict[str, Any]`, *optional*):
|
| 665 |
+
Additional arguments passed to the model card template to customize the model card.
|
| 666 |
+
|
| 667 |
+
Returns:
|
| 668 |
+
The url of the commit of your model in the given repository.
|
| 669 |
+
"""
|
| 670 |
+
api = HfApi(token=token)
|
| 671 |
+
repo_id = api.create_repo(repo_id=repo_id, private=private, exist_ok=True).repo_id
|
| 672 |
+
|
| 673 |
+
# Push the files to the repo in a single commit
|
| 674 |
+
with SoftTemporaryDirectory() as tmp:
|
| 675 |
+
saved_path = Path(tmp) / repo_id
|
| 676 |
+
self.save_pretrained(saved_path, config=config, model_card_kwargs=model_card_kwargs)
|
| 677 |
+
return api.upload_folder(
|
| 678 |
+
repo_id=repo_id,
|
| 679 |
+
repo_type="model",
|
| 680 |
+
folder_path=saved_path,
|
| 681 |
+
commit_message=commit_message,
|
| 682 |
+
revision=branch,
|
| 683 |
+
create_pr=create_pr,
|
| 684 |
+
allow_patterns=allow_patterns,
|
| 685 |
+
ignore_patterns=ignore_patterns,
|
| 686 |
+
delete_patterns=delete_patterns,
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
def generate_model_card(self, *args, **kwargs) -> ModelCard:
|
| 690 |
+
card = ModelCard.from_template(
|
| 691 |
+
card_data=self._hub_mixin_info.model_card_data,
|
| 692 |
+
template_str=self._hub_mixin_info.model_card_template,
|
| 693 |
+
repo_url=self._hub_mixin_info.repo_url,
|
| 694 |
+
paper_url=self._hub_mixin_info.paper_url,
|
| 695 |
+
docs_url=self._hub_mixin_info.docs_url,
|
| 696 |
+
**kwargs,
|
| 697 |
+
)
|
| 698 |
+
return card
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class PyTorchModelHubMixin(ModelHubMixin):
|
| 702 |
+
"""
|
| 703 |
+
Implementation of [`ModelHubMixin`] to provide model Hub upload/download capabilities to PyTorch models. The model
|
| 704 |
+
is set in evaluation mode by default using `model.eval()` (dropout modules are deactivated). To train the model,
|
| 705 |
+
you should first set it back in training mode with `model.train()`.
|
| 706 |
+
|
| 707 |
+
See [`ModelHubMixin`] for more details on how to use the mixin.
|
| 708 |
+
|
| 709 |
+
Example:
|
| 710 |
+
|
| 711 |
+
```python
|
| 712 |
+
>>> import torch
|
| 713 |
+
>>> import torch.nn as nn
|
| 714 |
+
>>> from huggingface_hub import PyTorchModelHubMixin
|
| 715 |
+
|
| 716 |
+
>>> class MyModel(
|
| 717 |
+
... nn.Module,
|
| 718 |
+
... PyTorchModelHubMixin,
|
| 719 |
+
... library_name="keras-nlp",
|
| 720 |
+
... repo_url="https://github.com/keras-team/keras-nlp",
|
| 721 |
+
... paper_url="https://arxiv.org/abs/2304.12244",
|
| 722 |
+
... docs_url="https://keras.io/keras_nlp/",
|
| 723 |
+
... # ^ optional metadata to generate model card
|
| 724 |
+
... ):
|
| 725 |
+
... def __init__(self, hidden_size: int = 512, vocab_size: int = 30000, output_size: int = 4):
|
| 726 |
+
... super().__init__()
|
| 727 |
+
... self.param = nn.Parameter(torch.rand(hidden_size, vocab_size))
|
| 728 |
+
... self.linear = nn.Linear(output_size, vocab_size)
|
| 729 |
+
|
| 730 |
+
... def forward(self, x):
|
| 731 |
+
... return self.linear(x + self.param)
|
| 732 |
+
>>> model = MyModel(hidden_size=256)
|
| 733 |
+
|
| 734 |
+
# Save model weights to local directory
|
| 735 |
+
>>> model.save_pretrained("my-awesome-model")
|
| 736 |
+
|
| 737 |
+
# Push model weights to the Hub
|
| 738 |
+
>>> model.push_to_hub("my-awesome-model")
|
| 739 |
+
|
| 740 |
+
# Download and initialize weights from the Hub
|
| 741 |
+
>>> model = MyModel.from_pretrained("username/my-awesome-model")
|
| 742 |
+
>>> model.hidden_size
|
| 743 |
+
256
|
| 744 |
+
```
|
| 745 |
+
"""
|
| 746 |
+
|
| 747 |
+
def __init_subclass__(cls, *args, tags: Optional[list[str]] = None, **kwargs) -> None:
|
| 748 |
+
tags = tags or []
|
| 749 |
+
tags.append("pytorch_model_hub_mixin")
|
| 750 |
+
kwargs["tags"] = tags
|
| 751 |
+
return super().__init_subclass__(*args, **kwargs)
|
| 752 |
+
|
| 753 |
+
def _save_pretrained(self, save_directory: Path) -> None:
|
| 754 |
+
"""Save weights from a Pytorch model to a local directory."""
|
| 755 |
+
model_to_save = self.module if hasattr(self, "module") else self # type: ignore
|
| 756 |
+
save_model_as_safetensor(model_to_save, str(save_directory / constants.SAFETENSORS_SINGLE_FILE)) # type: ignore [arg-type]
|
| 757 |
+
|
| 758 |
+
@classmethod
|
| 759 |
+
def _from_pretrained(
|
| 760 |
+
cls,
|
| 761 |
+
*,
|
| 762 |
+
model_id: str,
|
| 763 |
+
revision: Optional[str],
|
| 764 |
+
cache_dir: Optional[Union[str, Path]],
|
| 765 |
+
force_download: bool,
|
| 766 |
+
local_files_only: bool,
|
| 767 |
+
token: Union[str, bool, None],
|
| 768 |
+
map_location: str = "cpu",
|
| 769 |
+
strict: bool = False,
|
| 770 |
+
**model_kwargs,
|
| 771 |
+
):
|
| 772 |
+
"""Load Pytorch pretrained weights and return the loaded model."""
|
| 773 |
+
model = cls(**model_kwargs)
|
| 774 |
+
if os.path.isdir(model_id):
|
| 775 |
+
print("Loading weights from local directory")
|
| 776 |
+
model_file = os.path.join(model_id, constants.SAFETENSORS_SINGLE_FILE)
|
| 777 |
+
return cls._load_as_safetensor(model, model_file, map_location, strict)
|
| 778 |
+
else:
|
| 779 |
+
try:
|
| 780 |
+
model_file = hf_hub_download(
|
| 781 |
+
repo_id=model_id,
|
| 782 |
+
filename=constants.SAFETENSORS_SINGLE_FILE,
|
| 783 |
+
revision=revision,
|
| 784 |
+
cache_dir=cache_dir,
|
| 785 |
+
force_download=force_download,
|
| 786 |
+
token=token,
|
| 787 |
+
local_files_only=local_files_only,
|
| 788 |
+
)
|
| 789 |
+
return cls._load_as_safetensor(model, model_file, map_location, strict)
|
| 790 |
+
except EntryNotFoundError:
|
| 791 |
+
model_file = hf_hub_download(
|
| 792 |
+
repo_id=model_id,
|
| 793 |
+
filename=constants.PYTORCH_WEIGHTS_NAME,
|
| 794 |
+
revision=revision,
|
| 795 |
+
cache_dir=cache_dir,
|
| 796 |
+
force_download=force_download,
|
| 797 |
+
token=token,
|
| 798 |
+
local_files_only=local_files_only,
|
| 799 |
+
)
|
| 800 |
+
return cls._load_as_pickle(model, model_file, map_location, strict)
|
| 801 |
+
|
| 802 |
+
@classmethod
|
| 803 |
+
def _load_as_pickle(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
|
| 804 |
+
state_dict = torch.load(model_file, map_location=torch.device(map_location), weights_only=True)
|
| 805 |
+
model.load_state_dict(state_dict, strict=strict) # type: ignore
|
| 806 |
+
model.eval() # type: ignore
|
| 807 |
+
return model
|
| 808 |
+
|
| 809 |
+
@classmethod
|
| 810 |
+
def _load_as_safetensor(cls, model: T, model_file: str, map_location: str, strict: bool) -> T:
|
| 811 |
+
if packaging.version.parse(safetensors.__version__) < packaging.version.parse("0.4.3"): # type: ignore [attr-defined]
|
| 812 |
+
load_model_as_safetensor(model, model_file, strict=strict) # type: ignore [arg-type]
|
| 813 |
+
if map_location != "cpu":
|
| 814 |
+
logger.warning(
|
| 815 |
+
"Loading model weights on other devices than 'cpu' is not supported natively in your version of safetensors."
|
| 816 |
+
" This means that the model is loaded on 'cpu' first and then copied to the device."
|
| 817 |
+
" This leads to a slower loading time."
|
| 818 |
+
" Please update safetensors to version 0.4.3 or above for improved performance."
|
| 819 |
+
)
|
| 820 |
+
model.to(map_location) # type: ignore [attr-defined]
|
| 821 |
+
else:
|
| 822 |
+
safetensors.torch.load_model(model, model_file, strict=strict, device=map_location) # type: ignore [arg-type]
|
| 823 |
+
return model
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def _load_dataclass(datacls: type[DataclassInstance], data: dict) -> DataclassInstance:
|
| 827 |
+
"""Load a dataclass instance from a dictionary.
|
| 828 |
+
|
| 829 |
+
Fields not expected by the dataclass are ignored.
|
| 830 |
+
"""
|
| 831 |
+
return datacls(**{k: v for k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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2019-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 |
+
"""Git LFS related type definitions and utilities"""
|
| 16 |
+
|
| 17 |
+
import io
|
| 18 |
+
import re
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from math import ceil
|
| 21 |
+
from os.path import getsize
|
| 22 |
+
from typing import TYPE_CHECKING, BinaryIO, Iterable, Optional, TypedDict
|
| 23 |
+
from urllib.parse import unquote
|
| 24 |
+
|
| 25 |
+
from huggingface_hub import constants
|
| 26 |
+
|
| 27 |
+
from .utils import (
|
| 28 |
+
build_hf_headers,
|
| 29 |
+
fix_hf_endpoint_in_url,
|
| 30 |
+
hf_raise_for_status,
|
| 31 |
+
http_backoff,
|
| 32 |
+
logging,
|
| 33 |
+
validate_hf_hub_args,
|
| 34 |
+
)
|
| 35 |
+
from .utils._lfs import SliceFileObj
|
| 36 |
+
from .utils.sha import sha256, sha_fileobj
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
if TYPE_CHECKING:
|
| 40 |
+
from ._commit_api import CommitOperationAdd
|
| 41 |
+
|
| 42 |
+
logger = logging.get_logger(__name__)
|
| 43 |
+
|
| 44 |
+
OID_REGEX = re.compile(r"^[0-9a-f]{40}$")
|
| 45 |
+
|
| 46 |
+
LFS_MULTIPART_UPLOAD_COMMAND = "lfs-multipart-upload"
|
| 47 |
+
|
| 48 |
+
LFS_HEADERS = {
|
| 49 |
+
"Accept": "application/vnd.git-lfs+json",
|
| 50 |
+
"Content-Type": "application/vnd.git-lfs+json",
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass
|
| 55 |
+
class UploadInfo:
|
| 56 |
+
"""
|
| 57 |
+
Dataclass holding required information to determine whether a blob
|
| 58 |
+
should be uploaded to the hub using the LFS protocol or the regular protocol
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
sha256 (`bytes`):
|
| 62 |
+
SHA256 hash of the blob
|
| 63 |
+
size (`int`):
|
| 64 |
+
Size in bytes of the blob
|
| 65 |
+
sample (`bytes`):
|
| 66 |
+
First 512 bytes of the blob
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
sha256: bytes
|
| 70 |
+
size: int
|
| 71 |
+
sample: bytes
|
| 72 |
+
|
| 73 |
+
@classmethod
|
| 74 |
+
def from_path(cls, path: str):
|
| 75 |
+
size = getsize(path)
|
| 76 |
+
with io.open(path, "rb") as file:
|
| 77 |
+
sample = file.peek(512)[:512]
|
| 78 |
+
sha = sha_fileobj(file)
|
| 79 |
+
return cls(size=size, sha256=sha, sample=sample)
|
| 80 |
+
|
| 81 |
+
@classmethod
|
| 82 |
+
def from_bytes(cls, data: bytes):
|
| 83 |
+
sha = sha256(data).digest()
|
| 84 |
+
return cls(size=len(data), sample=data[:512], sha256=sha)
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def from_fileobj(cls, fileobj: BinaryIO):
|
| 88 |
+
sample = fileobj.read(512)
|
| 89 |
+
fileobj.seek(0, io.SEEK_SET)
|
| 90 |
+
sha = sha_fileobj(fileobj)
|
| 91 |
+
size = fileobj.tell()
|
| 92 |
+
fileobj.seek(0, io.SEEK_SET)
|
| 93 |
+
return cls(size=size, sha256=sha, sample=sample)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@validate_hf_hub_args
|
| 97 |
+
def post_lfs_batch_info(
|
| 98 |
+
upload_infos: Iterable[UploadInfo],
|
| 99 |
+
token: Optional[str],
|
| 100 |
+
repo_type: str,
|
| 101 |
+
repo_id: str,
|
| 102 |
+
revision: Optional[str] = None,
|
| 103 |
+
endpoint: Optional[str] = None,
|
| 104 |
+
headers: Optional[dict[str, str]] = None,
|
| 105 |
+
transfers: Optional[list[str]] = None,
|
| 106 |
+
) -> tuple[list[dict], list[dict], Optional[str]]:
|
| 107 |
+
"""
|
| 108 |
+
Requests the LFS batch endpoint to retrieve upload instructions
|
| 109 |
+
|
| 110 |
+
Learn more: https://github.com/git-lfs/git-lfs/blob/main/docs/api/batch.md
|
| 111 |
+
|
| 112 |
+
Args:
|
| 113 |
+
upload_infos (`Iterable` of `UploadInfo`):
|
| 114 |
+
`UploadInfo` for the files that are being uploaded, typically obtained
|
| 115 |
+
from `CommitOperationAdd.upload_info`
|
| 116 |
+
repo_type (`str`):
|
| 117 |
+
Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
|
| 118 |
+
repo_id (`str`):
|
| 119 |
+
A namespace (user or an organization) and a repo name separated
|
| 120 |
+
by a `/`.
|
| 121 |
+
revision (`str`, *optional*):
|
| 122 |
+
The git revision to upload to.
|
| 123 |
+
headers (`dict`, *optional*):
|
| 124 |
+
Additional headers to include in the request
|
| 125 |
+
transfers (`list`, *optional*):
|
| 126 |
+
List of transfer methods to use. Defaults to ["basic", "multipart"].
|
| 127 |
+
|
| 128 |
+
Returns:
|
| 129 |
+
`LfsBatchInfo`: 3-tuple:
|
| 130 |
+
- First element is the list of upload instructions from the server
|
| 131 |
+
- Second element is a list of errors, if any
|
| 132 |
+
- Third element is the chosen transfer adapter if provided by the server (e.g. "basic", "multipart", "xet")
|
| 133 |
+
|
| 134 |
+
Raises:
|
| 135 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 136 |
+
If an argument is invalid or the server response is malformed.
|
| 137 |
+
[`HfHubHTTPError`]
|
| 138 |
+
If the server returned an error.
|
| 139 |
+
"""
|
| 140 |
+
endpoint = endpoint if endpoint is not None else constants.ENDPOINT
|
| 141 |
+
url_prefix = ""
|
| 142 |
+
if repo_type in constants.REPO_TYPES_URL_PREFIXES:
|
| 143 |
+
url_prefix = constants.REPO_TYPES_URL_PREFIXES[repo_type]
|
| 144 |
+
batch_url = f"{endpoint}/{url_prefix}{repo_id}.git/info/lfs/objects/batch"
|
| 145 |
+
payload: dict = {
|
| 146 |
+
"operation": "upload",
|
| 147 |
+
"transfers": transfers if transfers is not None else ["basic", "multipart"],
|
| 148 |
+
"objects": [
|
| 149 |
+
{
|
| 150 |
+
"oid": upload.sha256.hex(),
|
| 151 |
+
"size": upload.size,
|
| 152 |
+
}
|
| 153 |
+
for upload in upload_infos
|
| 154 |
+
],
|
| 155 |
+
"hash_algo": "sha256",
|
| 156 |
+
}
|
| 157 |
+
if revision is not None:
|
| 158 |
+
payload["ref"] = {"name": unquote(revision)} # revision has been previously 'quoted'
|
| 159 |
+
|
| 160 |
+
headers = {
|
| 161 |
+
**LFS_HEADERS,
|
| 162 |
+
**build_hf_headers(token=token),
|
| 163 |
+
**(headers or {}),
|
| 164 |
+
}
|
| 165 |
+
resp = http_backoff("POST", batch_url, headers=headers, json=payload)
|
| 166 |
+
hf_raise_for_status(resp)
|
| 167 |
+
batch_info = resp.json()
|
| 168 |
+
|
| 169 |
+
objects = batch_info.get("objects", None)
|
| 170 |
+
if not isinstance(objects, list):
|
| 171 |
+
raise ValueError("Malformed response from server")
|
| 172 |
+
|
| 173 |
+
chosen_transfer = batch_info.get("transfer")
|
| 174 |
+
chosen_transfer = chosen_transfer if isinstance(chosen_transfer, str) else None
|
| 175 |
+
|
| 176 |
+
return (
|
| 177 |
+
[_validate_batch_actions(obj) for obj in objects if "error" not in obj],
|
| 178 |
+
[_validate_batch_error(obj) for obj in objects if "error" in obj],
|
| 179 |
+
chosen_transfer,
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class PayloadPartT(TypedDict):
|
| 184 |
+
partNumber: int
|
| 185 |
+
etag: str
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class CompletionPayloadT(TypedDict):
|
| 189 |
+
"""Payload that will be sent to the Hub when uploading multi-part."""
|
| 190 |
+
|
| 191 |
+
oid: str
|
| 192 |
+
parts: list[PayloadPartT]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def lfs_upload(
|
| 196 |
+
operation: "CommitOperationAdd",
|
| 197 |
+
lfs_batch_action: dict,
|
| 198 |
+
token: Optional[str] = None,
|
| 199 |
+
headers: Optional[dict[str, str]] = None,
|
| 200 |
+
endpoint: Optional[str] = None,
|
| 201 |
+
) -> None:
|
| 202 |
+
"""
|
| 203 |
+
Handles uploading a given object to the Hub with the LFS protocol.
|
| 204 |
+
|
| 205 |
+
Can be a No-op if the content of the file is already present on the hub large file storage.
|
| 206 |
+
|
| 207 |
+
Args:
|
| 208 |
+
operation (`CommitOperationAdd`):
|
| 209 |
+
The add operation triggering this upload.
|
| 210 |
+
lfs_batch_action (`dict`):
|
| 211 |
+
Upload instructions from the LFS batch endpoint for this object. See [`~utils.lfs.post_lfs_batch_info`] for
|
| 212 |
+
more details.
|
| 213 |
+
headers (`dict`, *optional*):
|
| 214 |
+
Headers to include in the request, including authentication and user agent headers.
|
| 215 |
+
|
| 216 |
+
Raises:
|
| 217 |
+
[`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 218 |
+
If `lfs_batch_action` is improperly formatted
|
| 219 |
+
[`HfHubHTTPError`]
|
| 220 |
+
If the upload resulted in an error
|
| 221 |
+
"""
|
| 222 |
+
# 0. If LFS file is already present, skip upload
|
| 223 |
+
_validate_batch_actions(lfs_batch_action)
|
| 224 |
+
actions = lfs_batch_action.get("actions")
|
| 225 |
+
if actions is None:
|
| 226 |
+
# The file was already uploaded
|
| 227 |
+
logger.debug(f"Content of file {operation.path_in_repo} is already present upstream - skipping upload")
|
| 228 |
+
return
|
| 229 |
+
|
| 230 |
+
# 1. Validate server response (check required keys in dict)
|
| 231 |
+
upload_action = lfs_batch_action["actions"]["upload"]
|
| 232 |
+
_validate_lfs_action(upload_action)
|
| 233 |
+
verify_action = lfs_batch_action["actions"].get("verify")
|
| 234 |
+
if verify_action is not None:
|
| 235 |
+
_validate_lfs_action(verify_action)
|
| 236 |
+
|
| 237 |
+
# 2. Upload file (either single part or multi-part)
|
| 238 |
+
header = upload_action.get("header", {})
|
| 239 |
+
chunk_size = header.get("chunk_size")
|
| 240 |
+
upload_url = fix_hf_endpoint_in_url(upload_action["href"], endpoint=endpoint)
|
| 241 |
+
if chunk_size is not None:
|
| 242 |
+
try:
|
| 243 |
+
chunk_size = int(chunk_size)
|
| 244 |
+
except (ValueError, TypeError):
|
| 245 |
+
raise ValueError(
|
| 246 |
+
f"Malformed response from LFS batch endpoint: `chunk_size` should be an integer. Got '{chunk_size}'."
|
| 247 |
+
)
|
| 248 |
+
_upload_multi_part(operation=operation, header=header, chunk_size=chunk_size, upload_url=upload_url)
|
| 249 |
+
else:
|
| 250 |
+
_upload_single_part(operation=operation, upload_url=upload_url)
|
| 251 |
+
|
| 252 |
+
# 3. Verify upload went well
|
| 253 |
+
if verify_action is not None:
|
| 254 |
+
_validate_lfs_action(verify_action)
|
| 255 |
+
verify_url = fix_hf_endpoint_in_url(verify_action["href"], endpoint)
|
| 256 |
+
verify_resp = http_backoff(
|
| 257 |
+
"POST",
|
| 258 |
+
verify_url,
|
| 259 |
+
headers=build_hf_headers(token=token, headers=headers),
|
| 260 |
+
json={"oid": operation.upload_info.sha256.hex(), "size": operation.upload_info.size},
|
| 261 |
+
)
|
| 262 |
+
hf_raise_for_status(verify_resp)
|
| 263 |
+
logger.debug(f"{operation.path_in_repo}: Upload successful")
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _validate_lfs_action(lfs_action: dict):
|
| 267 |
+
"""validates response from the LFS batch endpoint"""
|
| 268 |
+
if not (
|
| 269 |
+
isinstance(lfs_action.get("href"), str)
|
| 270 |
+
and (lfs_action.get("header") is None or isinstance(lfs_action.get("header"), dict))
|
| 271 |
+
):
|
| 272 |
+
raise ValueError("lfs_action is improperly formatted")
|
| 273 |
+
return lfs_action
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def _validate_batch_actions(lfs_batch_actions: dict):
|
| 277 |
+
"""validates response from the LFS batch endpoint"""
|
| 278 |
+
if not (isinstance(lfs_batch_actions.get("oid"), str) and isinstance(lfs_batch_actions.get("size"), int)):
|
| 279 |
+
raise ValueError("lfs_batch_actions is improperly formatted")
|
| 280 |
+
|
| 281 |
+
upload_action = lfs_batch_actions.get("actions", {}).get("upload")
|
| 282 |
+
verify_action = lfs_batch_actions.get("actions", {}).get("verify")
|
| 283 |
+
if upload_action is not None:
|
| 284 |
+
_validate_lfs_action(upload_action)
|
| 285 |
+
if verify_action is not None:
|
| 286 |
+
_validate_lfs_action(verify_action)
|
| 287 |
+
return lfs_batch_actions
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def _validate_batch_error(lfs_batch_error: dict):
|
| 291 |
+
"""validates response from the LFS batch endpoint"""
|
| 292 |
+
if not (isinstance(lfs_batch_error.get("oid"), str) and isinstance(lfs_batch_error.get("size"), int)):
|
| 293 |
+
raise ValueError("lfs_batch_error is improperly formatted")
|
| 294 |
+
error_info = lfs_batch_error.get("error")
|
| 295 |
+
if not (
|
| 296 |
+
isinstance(error_info, dict)
|
| 297 |
+
and isinstance(error_info.get("message"), str)
|
| 298 |
+
and isinstance(error_info.get("code"), int)
|
| 299 |
+
):
|
| 300 |
+
raise ValueError("lfs_batch_error is improperly formatted")
|
| 301 |
+
return lfs_batch_error
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def _upload_single_part(operation: "CommitOperationAdd", upload_url: str) -> None:
|
| 305 |
+
"""
|
| 306 |
+
Uploads `fileobj` as a single PUT HTTP request (basic LFS transfer protocol)
|
| 307 |
+
|
| 308 |
+
Args:
|
| 309 |
+
upload_url (`str`):
|
| 310 |
+
The URL to PUT the file to.
|
| 311 |
+
fileobj:
|
| 312 |
+
The file-like object holding the data to upload.
|
| 313 |
+
|
| 314 |
+
Raises:
|
| 315 |
+
[`HfHubHTTPError`]
|
| 316 |
+
If the upload resulted in an error.
|
| 317 |
+
"""
|
| 318 |
+
with operation.as_file(with_tqdm=True) as fileobj:
|
| 319 |
+
# S3 might raise a transient 500 error -> let's retry if that happens
|
| 320 |
+
response = http_backoff("PUT", upload_url, data=fileobj)
|
| 321 |
+
hf_raise_for_status(response)
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def _upload_multi_part(operation: "CommitOperationAdd", header: dict, chunk_size: int, upload_url: str) -> None:
|
| 325 |
+
"""
|
| 326 |
+
Uploads file using HF multipart LFS transfer protocol.
|
| 327 |
+
"""
|
| 328 |
+
# 1. Get upload URLs for each part
|
| 329 |
+
sorted_parts_urls = _get_sorted_parts_urls(header=header, upload_info=operation.upload_info, chunk_size=chunk_size)
|
| 330 |
+
|
| 331 |
+
# 2. Upload parts (pure Python)
|
| 332 |
+
response_headers = _upload_parts_iteratively(
|
| 333 |
+
operation=operation, sorted_parts_urls=sorted_parts_urls, chunk_size=chunk_size
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# 3. Send completion request
|
| 337 |
+
# NOTE: `upload_url` is the Hub completion endpoint (not the S3 upload URLs).
|
| 338 |
+
completion_res = http_backoff(
|
| 339 |
+
"POST",
|
| 340 |
+
upload_url,
|
| 341 |
+
json=_get_completion_payload(response_headers, operation.upload_info.sha256.hex()),
|
| 342 |
+
headers=LFS_HEADERS,
|
| 343 |
+
)
|
| 344 |
+
hf_raise_for_status(completion_res)
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _get_sorted_parts_urls(header: dict, upload_info: UploadInfo, chunk_size: int) -> list[str]:
|
| 348 |
+
sorted_part_upload_urls = [
|
| 349 |
+
upload_url
|
| 350 |
+
for _, upload_url in sorted(
|
| 351 |
+
[
|
| 352 |
+
(int(part_num, 10), upload_url)
|
| 353 |
+
for part_num, upload_url in header.items()
|
| 354 |
+
if part_num.isdigit() and len(part_num) > 0
|
| 355 |
+
],
|
| 356 |
+
key=lambda t: t[0],
|
| 357 |
+
)
|
| 358 |
+
]
|
| 359 |
+
num_parts = len(sorted_part_upload_urls)
|
| 360 |
+
if num_parts != ceil(upload_info.size / chunk_size):
|
| 361 |
+
raise ValueError("Invalid server response to upload large LFS file")
|
| 362 |
+
return sorted_part_upload_urls
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _get_completion_payload(response_headers: list[dict], oid: str) -> CompletionPayloadT:
|
| 366 |
+
parts: list[PayloadPartT] = []
|
| 367 |
+
for part_number, header in enumerate(response_headers):
|
| 368 |
+
etag = header.get("etag")
|
| 369 |
+
if etag is None or etag == "":
|
| 370 |
+
raise ValueError(f"Invalid etag (`{etag}`) returned for part {part_number + 1}")
|
| 371 |
+
parts.append(
|
| 372 |
+
{
|
| 373 |
+
"partNumber": part_number + 1,
|
| 374 |
+
"etag": etag,
|
| 375 |
+
}
|
| 376 |
+
)
|
| 377 |
+
return {"oid": oid, "parts": parts}
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _upload_parts_iteratively(
|
| 381 |
+
operation: "CommitOperationAdd", sorted_parts_urls: list[str], chunk_size: int
|
| 382 |
+
) -> list[dict]:
|
| 383 |
+
headers = []
|
| 384 |
+
with operation.as_file(with_tqdm=True) as fileobj:
|
| 385 |
+
for part_idx, part_upload_url in enumerate(sorted_parts_urls):
|
| 386 |
+
with SliceFileObj(
|
| 387 |
+
fileobj,
|
| 388 |
+
seek_from=chunk_size * part_idx,
|
| 389 |
+
read_limit=chunk_size,
|
| 390 |
+
) as fileobj_slice:
|
| 391 |
+
# S3 might raise a transient 500 error -> let's retry if that happens
|
| 392 |
+
part_upload_res = http_backoff("PUT", part_upload_url, data=fileobj_slice)
|
| 393 |
+
hf_raise_for_status(part_upload_res)
|
| 394 |
+
headers.append(part_upload_res.headers)
|
| 395 |
+
return headers # type: ignore
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/py.typed
ADDED
|
File without changes
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/huggingface_hub/repocard.py
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Any, Literal, Optional, Union
|
| 5 |
+
|
| 6 |
+
import yaml
|
| 7 |
+
|
| 8 |
+
from huggingface_hub.file_download import hf_hub_download
|
| 9 |
+
from huggingface_hub.hf_api import upload_file
|
| 10 |
+
from huggingface_hub.repocard_data import (
|
| 11 |
+
CardData,
|
| 12 |
+
DatasetCardData,
|
| 13 |
+
EvalResult,
|
| 14 |
+
ModelCardData,
|
| 15 |
+
SpaceCardData,
|
| 16 |
+
eval_results_to_model_index,
|
| 17 |
+
model_index_to_eval_results,
|
| 18 |
+
)
|
| 19 |
+
from huggingface_hub.utils import HfHubHTTPError, get_session, hf_raise_for_status, is_jinja_available, yaml_dump
|
| 20 |
+
|
| 21 |
+
from . import constants
|
| 22 |
+
from .errors import EntryNotFoundError
|
| 23 |
+
from .utils import SoftTemporaryDirectory, logging, validate_hf_hub_args
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
logger = logging.get_logger(__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
TEMPLATE_MODELCARD_PATH = Path(__file__).parent / "templates" / "modelcard_template.md"
|
| 30 |
+
TEMPLATE_DATASETCARD_PATH = Path(__file__).parent / "templates" / "datasetcard_template.md"
|
| 31 |
+
|
| 32 |
+
# exact same regex as in the Hub server. Please keep in sync.
|
| 33 |
+
# See https://github.com/huggingface/moon-landing/blob/main/server/lib/ViewMarkdown.ts#L18
|
| 34 |
+
REGEX_YAML_BLOCK = re.compile(r"^(\s*---[\r\n]+)([\S\s]*?)([\r\n]+---(\r\n|\n|$))")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class RepoCard:
|
| 38 |
+
card_data_class = CardData
|
| 39 |
+
default_template_path = TEMPLATE_MODELCARD_PATH
|
| 40 |
+
repo_type = "model"
|
| 41 |
+
|
| 42 |
+
def __init__(self, content: str, ignore_metadata_errors: bool = False):
|
| 43 |
+
"""Initialize a RepoCard from string content. The content should be a
|
| 44 |
+
Markdown file with a YAML block at the beginning and a Markdown body.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
content (`str`): The content of the Markdown file.
|
| 48 |
+
|
| 49 |
+
Example:
|
| 50 |
+
```python
|
| 51 |
+
>>> from huggingface_hub.repocard import RepoCard
|
| 52 |
+
>>> text = '''
|
| 53 |
+
... ---
|
| 54 |
+
... language: en
|
| 55 |
+
... license: mit
|
| 56 |
+
... ---
|
| 57 |
+
...
|
| 58 |
+
... # My repo
|
| 59 |
+
... '''
|
| 60 |
+
>>> card = RepoCard(text)
|
| 61 |
+
>>> card.data.to_dict()
|
| 62 |
+
{'language': 'en', 'license': 'mit'}
|
| 63 |
+
>>> card.text
|
| 64 |
+
'\\n# My repo\\n'
|
| 65 |
+
|
| 66 |
+
```
|
| 67 |
+
> [!TIP]
|
| 68 |
+
> Raises the following error:
|
| 69 |
+
>
|
| 70 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 71 |
+
> when the content of the repo card metadata is not a dictionary.
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
# Set the content of the RepoCard, as well as underlying .data and .text attributes.
|
| 75 |
+
# See the `content` property setter for more details.
|
| 76 |
+
self.ignore_metadata_errors = ignore_metadata_errors
|
| 77 |
+
self.content = content
|
| 78 |
+
|
| 79 |
+
@property
|
| 80 |
+
def content(self):
|
| 81 |
+
"""The content of the RepoCard, including the YAML block and the Markdown body."""
|
| 82 |
+
line_break = _detect_line_ending(self._content) or "\n"
|
| 83 |
+
return f"---{line_break}{self.data.to_yaml(line_break=line_break, original_order=self._original_order)}{line_break}---{line_break}{self.text}"
|
| 84 |
+
|
| 85 |
+
@content.setter
|
| 86 |
+
def content(self, content: str):
|
| 87 |
+
"""Set the content of the RepoCard."""
|
| 88 |
+
self._content = content
|
| 89 |
+
|
| 90 |
+
match = REGEX_YAML_BLOCK.search(content)
|
| 91 |
+
if match:
|
| 92 |
+
# Metadata found in the YAML block
|
| 93 |
+
yaml_block = match.group(2)
|
| 94 |
+
self.text = content[match.end() :]
|
| 95 |
+
data_dict = yaml.safe_load(yaml_block)
|
| 96 |
+
|
| 97 |
+
if data_dict is None:
|
| 98 |
+
data_dict = {}
|
| 99 |
+
|
| 100 |
+
# The YAML block's data should be a dictionary
|
| 101 |
+
if not isinstance(data_dict, dict):
|
| 102 |
+
raise ValueError("repo card metadata block should be a dict")
|
| 103 |
+
else:
|
| 104 |
+
# Model card without metadata... create empty metadata
|
| 105 |
+
logger.warning("Repo card metadata block was not found. Setting CardData to empty.")
|
| 106 |
+
data_dict = {}
|
| 107 |
+
self.text = content
|
| 108 |
+
|
| 109 |
+
self.data = self.card_data_class(**data_dict, ignore_metadata_errors=self.ignore_metadata_errors)
|
| 110 |
+
self._original_order = list(data_dict.keys())
|
| 111 |
+
|
| 112 |
+
def __str__(self):
|
| 113 |
+
return self.content
|
| 114 |
+
|
| 115 |
+
def save(self, filepath: Union[Path, str]):
|
| 116 |
+
r"""Save a RepoCard to a file.
|
| 117 |
+
|
| 118 |
+
Args:
|
| 119 |
+
filepath (`Union[Path, str]`): Filepath to the markdown file to save.
|
| 120 |
+
|
| 121 |
+
Example:
|
| 122 |
+
```python
|
| 123 |
+
>>> from huggingface_hub.repocard import RepoCard
|
| 124 |
+
>>> card = RepoCard("---\nlanguage: en\n---\n# This is a test repo card")
|
| 125 |
+
>>> card.save("/tmp/test.md")
|
| 126 |
+
|
| 127 |
+
```
|
| 128 |
+
"""
|
| 129 |
+
filepath = Path(filepath)
|
| 130 |
+
filepath.parent.mkdir(parents=True, exist_ok=True)
|
| 131 |
+
# Preserve newlines as in the existing file.
|
| 132 |
+
with open(filepath, mode="w", newline="", encoding="utf-8") as f:
|
| 133 |
+
f.write(str(self))
|
| 134 |
+
|
| 135 |
+
@classmethod
|
| 136 |
+
def load(
|
| 137 |
+
cls,
|
| 138 |
+
repo_id_or_path: Union[str, Path],
|
| 139 |
+
repo_type: Optional[str] = None,
|
| 140 |
+
token: Optional[str] = None,
|
| 141 |
+
ignore_metadata_errors: bool = False,
|
| 142 |
+
):
|
| 143 |
+
"""Initialize a RepoCard from a Hugging Face Hub repo's README.md or a local filepath.
|
| 144 |
+
|
| 145 |
+
Args:
|
| 146 |
+
repo_id_or_path (`Union[str, Path]`):
|
| 147 |
+
The repo ID associated with a Hugging Face Hub repo or a local filepath.
|
| 148 |
+
repo_type (`str`, *optional*):
|
| 149 |
+
The type of Hugging Face repo to push to. Defaults to None, which will use "model". Other options
|
| 150 |
+
are "dataset" and "space". Not used when loading from a local filepath. If this is called from a child
|
| 151 |
+
class, the default value will be the child class's `repo_type`.
|
| 152 |
+
token (`str`, *optional*):
|
| 153 |
+
Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to the stored token.
|
| 154 |
+
ignore_metadata_errors (`str`):
|
| 155 |
+
If True, errors while parsing the metadata section will be ignored. Some information might be lost during
|
| 156 |
+
the process. Use it at your own risk.
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 159 |
+
[`huggingface_hub.repocard.RepoCard`]: The RepoCard (or subclass) initialized from the repo's
|
| 160 |
+
README.md file or filepath.
|
| 161 |
+
|
| 162 |
+
Example:
|
| 163 |
+
```python
|
| 164 |
+
>>> from huggingface_hub.repocard import RepoCard
|
| 165 |
+
>>> card = RepoCard.load("nateraw/food")
|
| 166 |
+
>>> assert card.data.tags == ["generated_from_trainer", "image-classification", "pytorch"]
|
| 167 |
+
|
| 168 |
+
```
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
if Path(repo_id_or_path).is_file():
|
| 172 |
+
card_path = Path(repo_id_or_path)
|
| 173 |
+
elif isinstance(repo_id_or_path, str):
|
| 174 |
+
card_path = Path(
|
| 175 |
+
hf_hub_download(
|
| 176 |
+
repo_id_or_path,
|
| 177 |
+
constants.REPOCARD_NAME,
|
| 178 |
+
repo_type=repo_type or cls.repo_type,
|
| 179 |
+
token=token,
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
else:
|
| 183 |
+
raise ValueError(f"Cannot load RepoCard: path not found on disk ({repo_id_or_path}).")
|
| 184 |
+
|
| 185 |
+
# Preserve newlines in the existing file.
|
| 186 |
+
with card_path.open(mode="r", newline="", encoding="utf-8") as f:
|
| 187 |
+
return cls(f.read(), ignore_metadata_errors=ignore_metadata_errors)
|
| 188 |
+
|
| 189 |
+
def validate(self, repo_type: Optional[str] = None):
|
| 190 |
+
"""Validates card against Hugging Face Hub's card validation logic.
|
| 191 |
+
Using this function requires access to the internet, so it is only called
|
| 192 |
+
internally by [`huggingface_hub.repocard.RepoCard.push_to_hub`].
|
| 193 |
+
|
| 194 |
+
Args:
|
| 195 |
+
repo_type (`str`, *optional*, defaults to "model"):
|
| 196 |
+
The type of Hugging Face repo to push to. Options are "model", "dataset", and "space".
|
| 197 |
+
If this function is called from a child class, the default will be the child class's `repo_type`.
|
| 198 |
+
|
| 199 |
+
> [!TIP]
|
| 200 |
+
> Raises the following errors:
|
| 201 |
+
>
|
| 202 |
+
> - [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
|
| 203 |
+
> if the card fails validation checks.
|
| 204 |
+
> - [`HTTPError`](https://requests.readthedocs.io/en/latest/api/#requests.HTTPError)
|
| 205 |
+
> if the request to the Hub API fails for any other reason.
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
# If repo type is provided, otherwise, use the repo type of the card.
|
| 209 |
+
repo_type = repo_type or self.repo_type
|
| 210 |
+
|
| 211 |
+
body = {
|
| 212 |
+
"repoType": repo_type,
|
| 213 |
+
"content": str(self),
|
| 214 |
+
}
|
| 215 |
+
headers = {"Accept": "text/plain"}
|
| 216 |
+
|
| 217 |
+
try:
|
| 218 |
+
response = get_session().post("https://huggingface.co/api/validate-yaml", json=body, headers=headers)
|
| 219 |
+
hf_raise_for_status(response)
|
| 220 |
+
except HfHubHTTPError as exc:
|
| 221 |
+
if response.status_code == 400:
|
| 222 |
+
raise ValueError(response.text)
|
| 223 |
+
else:
|
| 224 |
+
raise exc
|
| 225 |
+
|
| 226 |
+
def push_to_hub(
|
| 227 |
+
self,
|
| 228 |
+
repo_id: str,
|
| 229 |
+
token: Optional[str] = None,
|
| 230 |
+
repo_type: Optional[str] = None,
|
| 231 |
+
commit_message: Optional[str] = None,
|
| 232 |
+
commit_description: Optional[str] = None,
|
| 233 |
+
revision: Optional[str] = None,
|
| 234 |
+
create_pr: Optional[bool] = None,
|
| 235 |
+
parent_commit: Optional[str] = None,
|
| 236 |
+
):
|
| 237 |
+
"""Push a RepoCard to a Hugging Face Hub repo.
|
| 238 |
+
|
| 239 |
+
Args:
|
| 240 |
+
repo_id (`str`):
|
| 241 |
+
The repo ID of the Hugging Face Hub repo to push to. Example: "nateraw/food".
|
| 242 |
+
token (`str`, *optional*):
|
| 243 |
+
Authentication token, obtained with `huggingface_hub.HfApi.login` method. Will default to
|
| 244 |
+
the stored token.
|
| 245 |
+
repo_type (`str`, *optional*, defaults to "model"):
|
| 246 |
+
The type of Hugging Face repo to push to. Options are "model", "dataset", and "space". If this
|
| 247 |
+
function is called by a child class, it will default to the child class's `repo_type`.
|
| 248 |
+
commit_message (`str`, *optional*):
|
| 249 |
+
The summary / title / first line of the generated commit.
|
| 250 |
+
commit_description (`str`, *optional*)
|
| 251 |
+
The description of the generated commit.
|
| 252 |
+
revision (`str`, *optional*):
|
| 253 |
+
The git revision to commit from. Defaults to the head of the `"main"` branch.
|
| 254 |
+
create_pr (`bool`, *optional*):
|
| 255 |
+
Whether or not to create a Pull Request with this commit. Defaults to `False`.
|
| 256 |
+
parent_commit (`str`, *optional*):
|
| 257 |
+
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
|
| 258 |
+
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
|
| 259 |
+
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
|
| 260 |
+
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
|
| 261 |
+
especially useful if the repo is updated / committed too concurrently.
|
| 262 |
+
Returns:
|
| 263 |
+
`str`: URL of the commit which updated the card metadata.
|
| 264 |
+
"""
|
| 265 |
+
|
| 266 |
+
# If repo type is provided, otherwise, use the repo type of the card.
|
| 267 |
+
repo_type = repo_type or self.repo_type
|
| 268 |
+
|
| 269 |
+
# Validate card before pushing to hub
|
| 270 |
+
self.validate(repo_type=repo_type)
|
| 271 |
+
|
| 272 |
+
with SoftTemporaryDirectory() as tmpdir:
|
| 273 |
+
tmp_path = Path(tmpdir) / constants.REPOCARD_NAME
|
| 274 |
+
tmp_path.write_text(str(self), encoding="utf-8")
|
| 275 |
+
url = upload_file(
|
| 276 |
+
path_or_fileobj=str(tmp_path),
|
| 277 |
+
path_in_repo=constants.REPOCARD_NAME,
|
| 278 |
+
repo_id=repo_id,
|
| 279 |
+
token=token,
|
| 280 |
+
repo_type=repo_type,
|
| 281 |
+
commit_message=commit_message,
|
| 282 |
+
commit_description=commit_description,
|
| 283 |
+
create_pr=create_pr,
|
| 284 |
+
revision=revision,
|
| 285 |
+
parent_commit=parent_commit,
|
| 286 |
+
)
|
| 287 |
+
return url
|
| 288 |
+
|
| 289 |
+
@classmethod
|
| 290 |
+
def from_template(
|
| 291 |
+
cls,
|
| 292 |
+
card_data: CardData,
|
| 293 |
+
template_path: Optional[str] = None,
|
| 294 |
+
template_str: Optional[str] = None,
|
| 295 |
+
**template_kwargs,
|
| 296 |
+
):
|
| 297 |
+
"""Initialize a RepoCard from a template. By default, it uses the default template.
|
| 298 |
+
|
| 299 |
+
Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| 300 |
+
|
| 301 |
+
Args:
|
| 302 |
+
card_data (`huggingface_hub.CardData`):
|
| 303 |
+
A huggingface_hub.CardData instance containing the metadata you want to include in the YAML
|
| 304 |
+
header of the repo card on the Hugging Face Hub.
|
| 305 |
+
template_path (`str`, *optional*):
|
| 306 |
+
A path to a markdown file with optional Jinja template variables that can be filled
|
| 307 |
+
in with `template_kwargs`. Defaults to the default template.
|
| 308 |
+
|
| 309 |
+
Returns:
|
| 310 |
+
[`huggingface_hub.repocard.RepoCard`]: A RepoCard instance with the specified card data and content from the
|
| 311 |
+
template.
|
| 312 |
+
"""
|
| 313 |
+
if is_jinja_available():
|
| 314 |
+
import jinja2
|
| 315 |
+
else:
|
| 316 |
+
raise ImportError(
|
| 317 |
+
"Using RepoCard.from_template requires Jinja2 to be installed. Please"
|
| 318 |
+
" install it with `pip install Jinja2`."
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
kwargs = card_data.to_dict().copy()
|
| 322 |
+
kwargs.update(template_kwargs) # Template_kwargs have priority
|
| 323 |
+
|
| 324 |
+
if template_path is not None:
|
| 325 |
+
template_str = Path(template_path).read_text()
|
| 326 |
+
if template_str is None:
|
| 327 |
+
template_str = Path(cls.default_template_path).read_text()
|
| 328 |
+
template = jinja2.Template(template_str)
|
| 329 |
+
content = template.render(card_data=card_data.to_yaml(), **kwargs)
|
| 330 |
+
return cls(content)
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
class ModelCard(RepoCard):
|
| 334 |
+
card_data_class = ModelCardData # type: ignore[assignment]
|
| 335 |
+
default_template_path = TEMPLATE_MODELCARD_PATH
|
| 336 |
+
repo_type = "model"
|
| 337 |
+
|
| 338 |
+
@classmethod
|
| 339 |
+
def from_template( # type: ignore # violates Liskov property but easier to use
|
| 340 |
+
cls,
|
| 341 |
+
card_data: ModelCardData,
|
| 342 |
+
template_path: Optional[str] = None,
|
| 343 |
+
template_str: Optional[str] = None,
|
| 344 |
+
**template_kwargs,
|
| 345 |
+
):
|
| 346 |
+
"""Initialize a ModelCard from a template. By default, it uses the default template, which can be found here:
|
| 347 |
+
https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/modelcard_template.md
|
| 348 |
+
|
| 349 |
+
Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| 350 |
+
|
| 351 |
+
Args:
|
| 352 |
+
card_data (`huggingface_hub.ModelCardData`):
|
| 353 |
+
A huggingface_hub.ModelCardData instance containing the metadata you want to include in the YAML
|
| 354 |
+
header of the model card on the Hugging Face Hub.
|
| 355 |
+
template_path (`str`, *optional*):
|
| 356 |
+
A path to a markdown file with optional Jinja template variables that can be filled
|
| 357 |
+
in with `template_kwargs`. Defaults to the default template.
|
| 358 |
+
|
| 359 |
+
Returns:
|
| 360 |
+
[`huggingface_hub.ModelCard`]: A ModelCard instance with the specified card data and content from the
|
| 361 |
+
template.
|
| 362 |
+
|
| 363 |
+
Example:
|
| 364 |
+
```python
|
| 365 |
+
>>> from huggingface_hub import ModelCard, ModelCardData, EvalResult
|
| 366 |
+
|
| 367 |
+
>>> # Using the Default Template
|
| 368 |
+
>>> card_data = ModelCardData(
|
| 369 |
+
... language='en',
|
| 370 |
+
... license='mit',
|
| 371 |
+
... library_name='timm',
|
| 372 |
+
... tags=['image-classification', 'resnet'],
|
| 373 |
+
... datasets=['beans'],
|
| 374 |
+
... metrics=['accuracy'],
|
| 375 |
+
... )
|
| 376 |
+
>>> card = ModelCard.from_template(
|
| 377 |
+
... card_data,
|
| 378 |
+
... model_description='This model does x + y...'
|
| 379 |
+
... )
|
| 380 |
+
|
| 381 |
+
>>> # Including Evaluation Results
|
| 382 |
+
>>> card_data = ModelCardData(
|
| 383 |
+
... language='en',
|
| 384 |
+
... tags=['image-classification', 'resnet'],
|
| 385 |
+
... eval_results=[
|
| 386 |
+
... EvalResult(
|
| 387 |
+
... task_type='image-classification',
|
| 388 |
+
... dataset_type='beans',
|
| 389 |
+
... dataset_name='Beans',
|
| 390 |
+
... metric_type='accuracy',
|
| 391 |
+
... metric_value=0.9,
|
| 392 |
+
... ),
|
| 393 |
+
... ],
|
| 394 |
+
... model_name='my-cool-model',
|
| 395 |
+
... )
|
| 396 |
+
>>> card = ModelCard.from_template(card_data)
|
| 397 |
+
|
| 398 |
+
>>> # Using a Custom Template
|
| 399 |
+
>>> card_data = ModelCardData(
|
| 400 |
+
... language='en',
|
| 401 |
+
... tags=['image-classification', 'resnet']
|
| 402 |
+
... )
|
| 403 |
+
>>> card = ModelCard.from_template(
|
| 404 |
+
... card_data=card_data,
|
| 405 |
+
... template_path='./src/huggingface_hub/templates/modelcard_template.md',
|
| 406 |
+
... custom_template_var='custom value', # will be replaced in template if it exists
|
| 407 |
+
... )
|
| 408 |
+
|
| 409 |
+
```
|
| 410 |
+
"""
|
| 411 |
+
return super().from_template(card_data, template_path, template_str, **template_kwargs)
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
class DatasetCard(RepoCard):
|
| 415 |
+
card_data_class = DatasetCardData # type: ignore[assignment]
|
| 416 |
+
default_template_path = TEMPLATE_DATASETCARD_PATH
|
| 417 |
+
repo_type = "dataset"
|
| 418 |
+
|
| 419 |
+
@classmethod
|
| 420 |
+
def from_template( # type: ignore # violates Liskov property but easier to use
|
| 421 |
+
cls,
|
| 422 |
+
card_data: DatasetCardData,
|
| 423 |
+
template_path: Optional[str] = None,
|
| 424 |
+
template_str: Optional[str] = None,
|
| 425 |
+
**template_kwargs,
|
| 426 |
+
):
|
| 427 |
+
"""Initialize a DatasetCard from a template. By default, it uses the default template, which can be found here:
|
| 428 |
+
https://github.com/huggingface/huggingface_hub/blob/main/src/huggingface_hub/templates/datasetcard_template.md
|
| 429 |
+
|
| 430 |
+
Templates are Jinja2 templates that can be customized by passing keyword arguments.
|
| 431 |
+
|
| 432 |
+
Args:
|
| 433 |
+
card_data (`huggingface_hub.DatasetCardData`):
|
| 434 |
+
A huggingface_hub.DatasetCardData instance containing the metadata you want to include in the YAML
|
| 435 |
+
header of the dataset card on the Hugging Face Hub.
|
| 436 |
+
template_path (`str`, *optional*):
|
| 437 |
+
A path to a markdown file with optional Jinja template variables that can be filled
|
| 438 |
+
in with `template_kwargs`. Defaults to the default template.
|
| 439 |
+
|
| 440 |
+
Returns:
|
| 441 |
+
[`huggingface_hub.DatasetCard`]: A DatasetCard instance with the specified card data and content from the
|
| 442 |
+
template.
|
| 443 |
+
|
| 444 |
+
Example:
|
| 445 |
+
```python
|
| 446 |
+
>>> from huggingface_hub import DatasetCard, DatasetCardData
|
| 447 |
+
|
| 448 |
+
>>> # Using the Default Template
|
| 449 |
+
>>> card_data = DatasetCardData(
|
| 450 |
+
... language='en',
|
| 451 |
+
... license='mit',
|
| 452 |
+
... annotations_creators='crowdsourced',
|
| 453 |
+
... task_categories=['text-classification'],
|
| 454 |
+
... task_ids=['sentiment-classification', 'text-scoring'],
|
| 455 |
+
... multilinguality='monolingual',
|
| 456 |
+
... pretty_name='My Text Classification Dataset',
|
| 457 |
+
... )
|
| 458 |
+
>>> card = DatasetCard.from_template(
|
| 459 |
+
... card_data,
|
| 460 |
+
... pretty_name=card_data.pretty_name,
|
| 461 |
+
... )
|
| 462 |
+
|
| 463 |
+
>>> # Using a Custom Template
|
| 464 |
+
>>> card_data = DatasetCardData(
|
| 465 |
+
... language='en',
|
| 466 |
+
... license='mit',
|
| 467 |
+
... )
|
| 468 |
+
>>> card = DatasetCard.from_template(
|
| 469 |
+
... card_data=card_data,
|
| 470 |
+
... template_path='./src/huggingface_hub/templates/datasetcard_template.md',
|
| 471 |
+
... custom_template_var='custom value', # will be replaced in template if it exists
|
| 472 |
+
... )
|
| 473 |
+
|
| 474 |
+
```
|
| 475 |
+
"""
|
| 476 |
+
return super().from_template(card_data, template_path, template_str, **template_kwargs)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
class SpaceCard(RepoCard):
|
| 480 |
+
card_data_class = SpaceCardData # type: ignore[assignment]
|
| 481 |
+
default_template_path = TEMPLATE_MODELCARD_PATH
|
| 482 |
+
repo_type = "space"
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _detect_line_ending(content: str) -> Literal["\r", "\n", "\r\n", None]: # noqa: F722
|
| 486 |
+
"""Detect the line ending of a string. Used by RepoCard to avoid making huge diff on newlines.
|
| 487 |
+
|
| 488 |
+
Uses same implementation as in Hub server, keep it in sync.
|
| 489 |
+
|
| 490 |
+
Returns:
|
| 491 |
+
str: The detected line ending of the string.
|
| 492 |
+
"""
|
| 493 |
+
cr = content.count("\r")
|
| 494 |
+
lf = content.count("\n")
|
| 495 |
+
crlf = content.count("\r\n")
|
| 496 |
+
if cr + lf == 0:
|
| 497 |
+
return None
|
| 498 |
+
if crlf == cr and crlf == lf:
|
| 499 |
+
return "\r\n"
|
| 500 |
+
if cr > lf:
|
| 501 |
+
return "\r"
|
| 502 |
+
else:
|
| 503 |
+
return "\n"
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def metadata_load(local_path: Union[str, Path]) -> Optional[dict]:
|
| 507 |
+
content = Path(local_path).read_text()
|
| 508 |
+
match = REGEX_YAML_BLOCK.search(content)
|
| 509 |
+
if match:
|
| 510 |
+
yaml_block = match.group(2)
|
| 511 |
+
data = yaml.safe_load(yaml_block)
|
| 512 |
+
if data is None or isinstance(data, dict):
|
| 513 |
+
return data
|
| 514 |
+
raise ValueError("repo card metadata block should be a dict")
|
| 515 |
+
else:
|
| 516 |
+
return None
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def metadata_save(local_path: Union[str, Path], data: dict) -> None:
|
| 520 |
+
"""
|
| 521 |
+
Save the metadata dict in the upper YAML part Trying to preserve newlines as
|
| 522 |
+
in the existing file. Docs about open() with newline="" parameter:
|
| 523 |
+
https://docs.python.org/3/library/functions.html?highlight=open#open Does
|
| 524 |
+
not work with "^M" linebreaks, which are replaced by \n
|
| 525 |
+
"""
|
| 526 |
+
line_break = "\n"
|
| 527 |
+
content = ""
|
| 528 |
+
# try to detect existing newline character
|
| 529 |
+
if os.path.exists(local_path):
|
| 530 |
+
with open(local_path, "r", newline="", encoding="utf8") as readme:
|
| 531 |
+
content = readme.read()
|
| 532 |
+
if isinstance(readme.newlines, tuple):
|
| 533 |
+
line_break = readme.newlines[0]
|
| 534 |
+
elif isinstance(readme.newlines, str):
|
| 535 |
+
line_break = readme.newlines
|
| 536 |
+
|
| 537 |
+
# creates a new file if it not
|
| 538 |
+
with open(local_path, "w", newline="", encoding="utf8") as readme:
|
| 539 |
+
data_yaml = yaml_dump(data, sort_keys=False, line_break=line_break)
|
| 540 |
+
# sort_keys: keep dict order
|
| 541 |
+
match = REGEX_YAML_BLOCK.search(content)
|
| 542 |
+
if match:
|
| 543 |
+
output = content[: match.start()] + f"---{line_break}{data_yaml}---{line_break}" + content[match.end() :]
|
| 544 |
+
else:
|
| 545 |
+
output = f"---{line_break}{data_yaml}---{line_break}{content}"
|
| 546 |
+
|
| 547 |
+
readme.write(output)
|
| 548 |
+
readme.close()
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
def metadata_eval_result(
|
| 552 |
+
*,
|
| 553 |
+
model_pretty_name: str,
|
| 554 |
+
task_pretty_name: str,
|
| 555 |
+
task_id: str,
|
| 556 |
+
metrics_pretty_name: str,
|
| 557 |
+
metrics_id: str,
|
| 558 |
+
metrics_value: Any,
|
| 559 |
+
dataset_pretty_name: str,
|
| 560 |
+
dataset_id: str,
|
| 561 |
+
metrics_config: Optional[str] = None,
|
| 562 |
+
metrics_verified: bool = False,
|
| 563 |
+
dataset_config: Optional[str] = None,
|
| 564 |
+
dataset_split: Optional[str] = None,
|
| 565 |
+
dataset_revision: Optional[str] = None,
|
| 566 |
+
metrics_verification_token: Optional[str] = None,
|
| 567 |
+
) -> dict:
|
| 568 |
+
"""
|
| 569 |
+
Creates a metadata dict with the result from a model evaluated on a dataset.
|
| 570 |
+
|
| 571 |
+
Args:
|
| 572 |
+
model_pretty_name (`str`):
|
| 573 |
+
The name of the model in natural language.
|
| 574 |
+
task_pretty_name (`str`):
|
| 575 |
+
The name of a task in natural language.
|
| 576 |
+
task_id (`str`):
|
| 577 |
+
Example: automatic-speech-recognition. A task id.
|
| 578 |
+
metrics_pretty_name (`str`):
|
| 579 |
+
A name for the metric in natural language. Example: Test WER.
|
| 580 |
+
metrics_id (`str`):
|
| 581 |
+
Example: wer. A metric id from https://hf.co/metrics.
|
| 582 |
+
metrics_value (`Any`):
|
| 583 |
+
The value from the metric. Example: 20.0 or "20.0 ± 1.2".
|
| 584 |
+
dataset_pretty_name (`str`):
|
| 585 |
+
The name of the dataset in natural language.
|
| 586 |
+
dataset_id (`str`):
|
| 587 |
+
Example: common_voice. A dataset id from https://hf.co/datasets.
|
| 588 |
+
metrics_config (`str`, *optional*):
|
| 589 |
+
The name of the metric configuration used in `load_metric()`.
|
| 590 |
+
Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
|
| 591 |
+
metrics_verified (`bool`, *optional*, defaults to `False`):
|
| 592 |
+
Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
|
| 593 |
+
dataset_config (`str`, *optional*):
|
| 594 |
+
Example: fr. The name of the dataset configuration used in `load_dataset()`.
|
| 595 |
+
dataset_split (`str`, *optional*):
|
| 596 |
+
Example: test. The name of the dataset split used in `load_dataset()`.
|
| 597 |
+
dataset_revision (`str`, *optional*):
|
| 598 |
+
Example: 5503434ddd753f426f4b38109466949a1217c2bb. The name of the dataset dataset revision
|
| 599 |
+
used in `load_dataset()`.
|
| 600 |
+
metrics_verification_token (`bool`, *optional*):
|
| 601 |
+
A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
|
| 602 |
+
|
| 603 |
+
Returns:
|
| 604 |
+
`dict`: a metadata dict with the result from a model evaluated on a dataset.
|
| 605 |
+
|
| 606 |
+
Example:
|
| 607 |
+
```python
|
| 608 |
+
>>> from huggingface_hub import metadata_eval_result
|
| 609 |
+
>>> results = metadata_eval_result(
|
| 610 |
+
... model_pretty_name="RoBERTa fine-tuned on ReactionGIF",
|
| 611 |
+
... task_pretty_name="Text Classification",
|
| 612 |
+
... task_id="text-classification",
|
| 613 |
+
... metrics_pretty_name="Accuracy",
|
| 614 |
+
... metrics_id="accuracy",
|
| 615 |
+
... metrics_value=0.2662102282047272,
|
| 616 |
+
... dataset_pretty_name="ReactionJPEG",
|
| 617 |
+
... dataset_id="julien-c/reactionjpeg",
|
| 618 |
+
... dataset_config="default",
|
| 619 |
+
... dataset_split="test",
|
| 620 |
+
... )
|
| 621 |
+
>>> results == {
|
| 622 |
+
... 'model-index': [
|
| 623 |
+
... {
|
| 624 |
+
... 'name': 'RoBERTa fine-tuned on ReactionGIF',
|
| 625 |
+
... 'results': [
|
| 626 |
+
... {
|
| 627 |
+
... 'task': {
|
| 628 |
+
... 'type': 'text-classification',
|
| 629 |
+
... 'name': 'Text Classification'
|
| 630 |
+
... },
|
| 631 |
+
... 'dataset': {
|
| 632 |
+
... 'name': 'ReactionJPEG',
|
| 633 |
+
... 'type': 'julien-c/reactionjpeg',
|
| 634 |
+
... 'config': 'default',
|
| 635 |
+
... 'split': 'test'
|
| 636 |
+
... },
|
| 637 |
+
... 'metrics': [
|
| 638 |
+
... {
|
| 639 |
+
... 'type': 'accuracy',
|
| 640 |
+
... 'value': 0.2662102282047272,
|
| 641 |
+
... 'name': 'Accuracy',
|
| 642 |
+
... 'verified': False
|
| 643 |
+
... }
|
| 644 |
+
... ]
|
| 645 |
+
... }
|
| 646 |
+
... ]
|
| 647 |
+
... }
|
| 648 |
+
... ]
|
| 649 |
+
... }
|
| 650 |
+
True
|
| 651 |
+
|
| 652 |
+
```
|
| 653 |
+
"""
|
| 654 |
+
|
| 655 |
+
return {
|
| 656 |
+
"model-index": eval_results_to_model_index(
|
| 657 |
+
model_name=model_pretty_name,
|
| 658 |
+
eval_results=[
|
| 659 |
+
EvalResult(
|
| 660 |
+
task_name=task_pretty_name,
|
| 661 |
+
task_type=task_id,
|
| 662 |
+
metric_name=metrics_pretty_name,
|
| 663 |
+
metric_type=metrics_id,
|
| 664 |
+
metric_value=metrics_value,
|
| 665 |
+
dataset_name=dataset_pretty_name,
|
| 666 |
+
dataset_type=dataset_id,
|
| 667 |
+
metric_config=metrics_config,
|
| 668 |
+
verified=metrics_verified,
|
| 669 |
+
verify_token=metrics_verification_token,
|
| 670 |
+
dataset_config=dataset_config,
|
| 671 |
+
dataset_split=dataset_split,
|
| 672 |
+
dataset_revision=dataset_revision,
|
| 673 |
+
)
|
| 674 |
+
],
|
| 675 |
+
)
|
| 676 |
+
}
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
@validate_hf_hub_args
|
| 680 |
+
def metadata_update(
|
| 681 |
+
repo_id: str,
|
| 682 |
+
metadata: dict,
|
| 683 |
+
*,
|
| 684 |
+
repo_type: Optional[str] = None,
|
| 685 |
+
overwrite: bool = False,
|
| 686 |
+
token: Optional[str] = None,
|
| 687 |
+
commit_message: Optional[str] = None,
|
| 688 |
+
commit_description: Optional[str] = None,
|
| 689 |
+
revision: Optional[str] = None,
|
| 690 |
+
create_pr: bool = False,
|
| 691 |
+
parent_commit: Optional[str] = None,
|
| 692 |
+
) -> str:
|
| 693 |
+
"""
|
| 694 |
+
Updates the metadata in the README.md of a repository on the Hugging Face Hub.
|
| 695 |
+
If the README.md file doesn't exist yet, a new one is created with metadata and
|
| 696 |
+
the default ModelCard or DatasetCard template. For `space` repo, an error is thrown
|
| 697 |
+
as a Space cannot exist without a `README.md` file.
|
| 698 |
+
|
| 699 |
+
Args:
|
| 700 |
+
repo_id (`str`):
|
| 701 |
+
The name of the repository.
|
| 702 |
+
metadata (`dict`):
|
| 703 |
+
A dictionary containing the metadata to be updated.
|
| 704 |
+
repo_type (`str`, *optional*):
|
| 705 |
+
Set to `"dataset"` or `"space"` if updating to a dataset or space,
|
| 706 |
+
`None` or `"model"` if updating to a model. Default is `None`.
|
| 707 |
+
overwrite (`bool`, *optional*, defaults to `False`):
|
| 708 |
+
If set to `True` an existing field can be overwritten, otherwise
|
| 709 |
+
attempting to overwrite an existing field will cause an error.
|
| 710 |
+
token (`str`, *optional*):
|
| 711 |
+
The Hugging Face authentication token.
|
| 712 |
+
commit_message (`str`, *optional*):
|
| 713 |
+
The summary / title / first line of the generated commit. Defaults to
|
| 714 |
+
`f"Update metadata with huggingface_hub"`
|
| 715 |
+
commit_description (`str` *optional*)
|
| 716 |
+
The description of the generated commit
|
| 717 |
+
revision (`str`, *optional*):
|
| 718 |
+
The git revision to commit from. Defaults to the head of the
|
| 719 |
+
`"main"` branch.
|
| 720 |
+
create_pr (`boolean`, *optional*):
|
| 721 |
+
Whether or not to create a Pull Request from `revision` with that commit.
|
| 722 |
+
Defaults to `False`.
|
| 723 |
+
parent_commit (`str`, *optional*):
|
| 724 |
+
The OID / SHA of the parent commit, as a hexadecimal string. Shorthands (7 first characters) are also supported.
|
| 725 |
+
If specified and `create_pr` is `False`, the commit will fail if `revision` does not point to `parent_commit`.
|
| 726 |
+
If specified and `create_pr` is `True`, the pull request will be created from `parent_commit`.
|
| 727 |
+
Specifying `parent_commit` ensures the repo has not changed before committing the changes, and can be
|
| 728 |
+
especially useful if the repo is updated / committed too concurrently.
|
| 729 |
+
Returns:
|
| 730 |
+
`str`: URL of the commit which updated the card metadata.
|
| 731 |
+
|
| 732 |
+
Example:
|
| 733 |
+
```python
|
| 734 |
+
>>> from huggingface_hub import metadata_update
|
| 735 |
+
>>> metadata = {'model-index': [{'name': 'RoBERTa fine-tuned on ReactionGIF',
|
| 736 |
+
... 'results': [{'dataset': {'name': 'ReactionGIF',
|
| 737 |
+
... 'type': 'julien-c/reactiongif'},
|
| 738 |
+
... 'metrics': [{'name': 'Recall',
|
| 739 |
+
... 'type': 'recall',
|
| 740 |
+
... 'value': 0.7762102282047272}],
|
| 741 |
+
... 'task': {'name': 'Text Classification',
|
| 742 |
+
... 'type': 'text-classification'}}]}]}
|
| 743 |
+
>>> url = metadata_update("hf-internal-testing/reactiongif-roberta-card", metadata)
|
| 744 |
+
|
| 745 |
+
```
|
| 746 |
+
"""
|
| 747 |
+
commit_message = commit_message if commit_message is not None else "Update metadata with huggingface_hub"
|
| 748 |
+
|
| 749 |
+
# Card class given repo_type
|
| 750 |
+
card_class: type[RepoCard]
|
| 751 |
+
if repo_type is None or repo_type == "model":
|
| 752 |
+
card_class = ModelCard
|
| 753 |
+
elif repo_type == "dataset":
|
| 754 |
+
card_class = DatasetCard
|
| 755 |
+
elif repo_type == "space":
|
| 756 |
+
card_class = RepoCard
|
| 757 |
+
else:
|
| 758 |
+
raise ValueError(f"Unknown repo_type: {repo_type}")
|
| 759 |
+
|
| 760 |
+
# Either load repo_card from the Hub or create an empty one.
|
| 761 |
+
# NOTE: Will not create the repo if it doesn't exist.
|
| 762 |
+
try:
|
| 763 |
+
card = card_class.load(repo_id, token=token, repo_type=repo_type)
|
| 764 |
+
except EntryNotFoundError:
|
| 765 |
+
if repo_type == "space":
|
| 766 |
+
raise ValueError("Cannot update metadata on a Space that doesn't contain a `README.md` file.")
|
| 767 |
+
|
| 768 |
+
# Initialize a ModelCard or DatasetCard from default template and no data.
|
| 769 |
+
# Cast to the concrete expected card type to satisfy type checkers.
|
| 770 |
+
card = card_class.from_template(CardData()) # type: ignore[return-value]
|
| 771 |
+
|
| 772 |
+
for key, value in metadata.items():
|
| 773 |
+
if key == "model-index":
|
| 774 |
+
# if the new metadata doesn't include a name, either use existing one or repo name
|
| 775 |
+
if "name" not in value[0]:
|
| 776 |
+
value[0]["name"] = getattr(card, "model_name", repo_id)
|
| 777 |
+
model_name, new_results = model_index_to_eval_results(value)
|
| 778 |
+
if card.data.eval_results is None:
|
| 779 |
+
card.data.eval_results = new_results
|
| 780 |
+
card.data.model_name = model_name
|
| 781 |
+
else:
|
| 782 |
+
existing_results = card.data.eval_results
|
| 783 |
+
|
| 784 |
+
# Iterate over new results
|
| 785 |
+
# Iterate over existing results
|
| 786 |
+
# If both results describe the same metric but value is different:
|
| 787 |
+
# If overwrite=True: overwrite the metric value
|
| 788 |
+
# Else: raise ValueError
|
| 789 |
+
# Else: append new result to existing ones.
|
| 790 |
+
for new_result in new_results:
|
| 791 |
+
result_found = False
|
| 792 |
+
for existing_result in existing_results:
|
| 793 |
+
if new_result.is_equal_except_value(existing_result):
|
| 794 |
+
if new_result != existing_result and not overwrite:
|
| 795 |
+
raise ValueError(
|
| 796 |
+
"You passed a new value for the existing metric"
|
| 797 |
+
f" 'name: {new_result.metric_name}, type: "
|
| 798 |
+
f"{new_result.metric_type}'. Set `overwrite=True`"
|
| 799 |
+
" to overwrite existing metrics."
|
| 800 |
+
)
|
| 801 |
+
result_found = True
|
| 802 |
+
existing_result.metric_value = new_result.metric_value
|
| 803 |
+
if existing_result.verified is True:
|
| 804 |
+
existing_result.verify_token = new_result.verify_token
|
| 805 |
+
if not result_found:
|
| 806 |
+
card.data.eval_results.append(new_result)
|
| 807 |
+
else:
|
| 808 |
+
# Any metadata that is not a result metric
|
| 809 |
+
if card.data.get(key) is not None and not overwrite and card.data.get(key) != value:
|
| 810 |
+
raise ValueError(
|
| 811 |
+
f"You passed a new value for the existing meta data field '{key}'."
|
| 812 |
+
" Set `overwrite=True` to overwrite existing metadata."
|
| 813 |
+
)
|
| 814 |
+
else:
|
| 815 |
+
card.data[key] = value
|
| 816 |
+
|
| 817 |
+
return card.push_to_hub(
|
| 818 |
+
repo_id,
|
| 819 |
+
token=token,
|
| 820 |
+
repo_type=repo_type,
|
| 821 |
+
commit_message=commit_message,
|
| 822 |
+
commit_description=commit_description,
|
| 823 |
+
create_pr=create_pr,
|
| 824 |
+
revision=revision,
|
| 825 |
+
parent_commit=parent_commit,
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
from collections import defaultdict
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any, Optional, Union
|
| 5 |
+
|
| 6 |
+
from huggingface_hub.utils import logging, yaml_dump
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
logger = logging.get_logger(__name__)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass
|
| 13 |
+
class EvalResult:
|
| 14 |
+
"""
|
| 15 |
+
Flattened representation of individual evaluation results found in model-index of Model Cards.
|
| 16 |
+
|
| 17 |
+
For more information on the model-index spec, see https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1.
|
| 18 |
+
|
| 19 |
+
Args:
|
| 20 |
+
task_type (`str`):
|
| 21 |
+
The task identifier. Example: "image-classification".
|
| 22 |
+
dataset_type (`str`):
|
| 23 |
+
The dataset identifier. Example: "common_voice". Use dataset id from https://hf.co/datasets.
|
| 24 |
+
dataset_name (`str`):
|
| 25 |
+
A pretty name for the dataset. Example: "Common Voice (French)".
|
| 26 |
+
metric_type (`str`):
|
| 27 |
+
The metric identifier. Example: "wer". Use metric id from https://hf.co/metrics.
|
| 28 |
+
metric_value (`Any`):
|
| 29 |
+
The metric value. Example: 0.9 or "20.0 ± 1.2".
|
| 30 |
+
task_name (`str`, *optional*):
|
| 31 |
+
A pretty name for the task. Example: "Speech Recognition".
|
| 32 |
+
dataset_config (`str`, *optional*):
|
| 33 |
+
The name of the dataset configuration used in `load_dataset()`.
|
| 34 |
+
Example: fr in `load_dataset("common_voice", "fr")`. See the `datasets` docs for more info:
|
| 35 |
+
https://hf.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
|
| 36 |
+
dataset_split (`str`, *optional*):
|
| 37 |
+
The split used in `load_dataset()`. Example: "test".
|
| 38 |
+
dataset_revision (`str`, *optional*):
|
| 39 |
+
The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
|
| 40 |
+
Example: 5503434ddd753f426f4b38109466949a1217c2bb
|
| 41 |
+
dataset_args (`dict[str, Any]`, *optional*):
|
| 42 |
+
The arguments passed during `Metric.compute()`. Example for `bleu`: `{"max_order": 4}`
|
| 43 |
+
metric_name (`str`, *optional*):
|
| 44 |
+
A pretty name for the metric. Example: "Test WER".
|
| 45 |
+
metric_config (`str`, *optional*):
|
| 46 |
+
The name of the metric configuration used in `load_metric()`.
|
| 47 |
+
Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
|
| 48 |
+
See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
|
| 49 |
+
metric_args (`dict[str, Any]`, *optional*):
|
| 50 |
+
The arguments passed during `Metric.compute()`. Example for `bleu`: max_order: 4
|
| 51 |
+
verified (`bool`, *optional*):
|
| 52 |
+
Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
|
| 53 |
+
verify_token (`str`, *optional*):
|
| 54 |
+
A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
|
| 55 |
+
source_name (`str`, *optional*):
|
| 56 |
+
The name of the source of the evaluation result. Example: "Open LLM Leaderboard".
|
| 57 |
+
source_url (`str`, *optional*):
|
| 58 |
+
The URL of the source of the evaluation result. Example: "https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard".
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
# Required
|
| 62 |
+
|
| 63 |
+
# The task identifier
|
| 64 |
+
# Example: automatic-speech-recognition
|
| 65 |
+
task_type: str
|
| 66 |
+
|
| 67 |
+
# The dataset identifier
|
| 68 |
+
# Example: common_voice. Use dataset id from https://hf.co/datasets
|
| 69 |
+
dataset_type: str
|
| 70 |
+
|
| 71 |
+
# A pretty name for the dataset.
|
| 72 |
+
# Example: Common Voice (French)
|
| 73 |
+
dataset_name: str
|
| 74 |
+
|
| 75 |
+
# The metric identifier
|
| 76 |
+
# Example: wer. Use metric id from https://hf.co/metrics
|
| 77 |
+
metric_type: str
|
| 78 |
+
|
| 79 |
+
# Value of the metric.
|
| 80 |
+
# Example: 20.0 or "20.0 ± 1.2"
|
| 81 |
+
metric_value: Any
|
| 82 |
+
|
| 83 |
+
# Optional
|
| 84 |
+
|
| 85 |
+
# A pretty name for the task.
|
| 86 |
+
# Example: Speech Recognition
|
| 87 |
+
task_name: Optional[str] = None
|
| 88 |
+
|
| 89 |
+
# The name of the dataset configuration used in `load_dataset()`.
|
| 90 |
+
# Example: fr in `load_dataset("common_voice", "fr")`.
|
| 91 |
+
# See the `datasets` docs for more info:
|
| 92 |
+
# https://huggingface.co/docs/datasets/package_reference/loading_methods#datasets.load_dataset.name
|
| 93 |
+
dataset_config: Optional[str] = None
|
| 94 |
+
|
| 95 |
+
# The split used in `load_dataset()`.
|
| 96 |
+
# Example: test
|
| 97 |
+
dataset_split: Optional[str] = None
|
| 98 |
+
|
| 99 |
+
# The revision (AKA Git Sha) of the dataset used in `load_dataset()`.
|
| 100 |
+
# Example: 5503434ddd753f426f4b38109466949a1217c2bb
|
| 101 |
+
dataset_revision: Optional[str] = None
|
| 102 |
+
|
| 103 |
+
# The arguments passed during `Metric.compute()`.
|
| 104 |
+
# Example for `bleu`: max_order: 4
|
| 105 |
+
dataset_args: Optional[dict[str, Any]] = None
|
| 106 |
+
|
| 107 |
+
# A pretty name for the metric.
|
| 108 |
+
# Example: Test WER
|
| 109 |
+
metric_name: Optional[str] = None
|
| 110 |
+
|
| 111 |
+
# The name of the metric configuration used in `load_metric()`.
|
| 112 |
+
# Example: bleurt-large-512 in `load_metric("bleurt", "bleurt-large-512")`.
|
| 113 |
+
# See the `datasets` docs for more info: https://huggingface.co/docs/datasets/v2.1.0/en/loading#load-configurations
|
| 114 |
+
metric_config: Optional[str] = None
|
| 115 |
+
|
| 116 |
+
# The arguments passed during `Metric.compute()`.
|
| 117 |
+
# Example for `bleu`: max_order: 4
|
| 118 |
+
metric_args: Optional[dict[str, Any]] = None
|
| 119 |
+
|
| 120 |
+
# Indicates whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not. Automatically computed by Hugging Face, do not set.
|
| 121 |
+
verified: Optional[bool] = None
|
| 122 |
+
|
| 123 |
+
# A JSON Web Token that is used to verify whether the metrics originate from Hugging Face's [evaluation service](https://huggingface.co/spaces/autoevaluate/model-evaluator) or not.
|
| 124 |
+
verify_token: Optional[str] = None
|
| 125 |
+
|
| 126 |
+
# The name of the source of the evaluation result.
|
| 127 |
+
# Example: Open LLM Leaderboard
|
| 128 |
+
source_name: Optional[str] = None
|
| 129 |
+
|
| 130 |
+
# The URL of the source of the evaluation result.
|
| 131 |
+
# Example: https://huggingface.co/spaces/open-llm-leaderboard/open_llm_leaderboard
|
| 132 |
+
source_url: Optional[str] = None
|
| 133 |
+
|
| 134 |
+
@property
|
| 135 |
+
def unique_identifier(self) -> tuple:
|
| 136 |
+
"""Returns a tuple that uniquely identifies this evaluation."""
|
| 137 |
+
return (
|
| 138 |
+
self.task_type,
|
| 139 |
+
self.dataset_type,
|
| 140 |
+
self.dataset_config,
|
| 141 |
+
self.dataset_split,
|
| 142 |
+
self.dataset_revision,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
def is_equal_except_value(self, other: "EvalResult") -> bool:
|
| 146 |
+
"""
|
| 147 |
+
Return True if `self` and `other` describe exactly the same metric but with a
|
| 148 |
+
different value.
|
| 149 |
+
"""
|
| 150 |
+
for key, _ in self.__dict__.items():
|
| 151 |
+
if key == "metric_value":
|
| 152 |
+
continue
|
| 153 |
+
# For metrics computed by Hugging Face's evaluation service, `verify_token` is derived from `metric_value`,
|
| 154 |
+
# so we exclude it here in the comparison.
|
| 155 |
+
if key != "verify_token" and getattr(self, key) != getattr(other, key):
|
| 156 |
+
return False
|
| 157 |
+
return True
|
| 158 |
+
|
| 159 |
+
def __post_init__(self) -> None:
|
| 160 |
+
if self.source_name is not None and self.source_url is None:
|
| 161 |
+
raise ValueError("If `source_name` is provided, `source_url` must also be provided.")
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@dataclass
|
| 165 |
+
class CardData:
|
| 166 |
+
"""Structure containing metadata from a RepoCard.
|
| 167 |
+
|
| 168 |
+
[`CardData`] is the parent class of [`ModelCardData`] and [`DatasetCardData`].
|
| 169 |
+
|
| 170 |
+
Metadata can be exported as a dictionary or YAML. Export can be customized to alter the representation of the data
|
| 171 |
+
(example: flatten evaluation results). `CardData` behaves as a dictionary (can get, pop, set values) but do not
|
| 172 |
+
inherit from `dict` to allow this export step.
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
def __init__(self, ignore_metadata_errors: bool = False, **kwargs):
|
| 176 |
+
self.__dict__.update(kwargs)
|
| 177 |
+
|
| 178 |
+
def to_dict(self):
|
| 179 |
+
"""Converts CardData to a dict.
|
| 180 |
+
|
| 181 |
+
Returns:
|
| 182 |
+
`dict`: CardData represented as a dictionary ready to be dumped to a YAML
|
| 183 |
+
block for inclusion in a README.md file.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
data_dict = copy.deepcopy(self.__dict__)
|
| 187 |
+
self._to_dict(data_dict)
|
| 188 |
+
return {key: value for key, value in data_dict.items() if value is not None}
|
| 189 |
+
|
| 190 |
+
def _to_dict(self, data_dict):
|
| 191 |
+
"""Use this method in child classes to alter the dict representation of the data. Alter the dict in-place.
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
data_dict (`dict`): The raw dict representation of the card data.
|
| 195 |
+
"""
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
def to_yaml(self, line_break=None, original_order: Optional[list[str]] = None) -> str:
|
| 199 |
+
"""Dumps CardData to a YAML block for inclusion in a README.md file.
|
| 200 |
+
|
| 201 |
+
Args:
|
| 202 |
+
line_break (str, *optional*):
|
| 203 |
+
The line break to use when dumping to yaml.
|
| 204 |
+
|
| 205 |
+
Returns:
|
| 206 |
+
`str`: CardData represented as a YAML block.
|
| 207 |
+
"""
|
| 208 |
+
if original_order:
|
| 209 |
+
self.__dict__ = {
|
| 210 |
+
k: self.__dict__[k]
|
| 211 |
+
for k in original_order + list(set(self.__dict__.keys()) - set(original_order))
|
| 212 |
+
if k in self.__dict__
|
| 213 |
+
}
|
| 214 |
+
return yaml_dump(self.to_dict(), sort_keys=False, line_break=line_break).strip()
|
| 215 |
+
|
| 216 |
+
def __repr__(self):
|
| 217 |
+
return repr(self.__dict__)
|
| 218 |
+
|
| 219 |
+
def __str__(self):
|
| 220 |
+
return self.to_yaml()
|
| 221 |
+
|
| 222 |
+
def get(self, key: str, default: Any = None) -> Any:
|
| 223 |
+
"""Get value for a given metadata key."""
|
| 224 |
+
value = self.__dict__.get(key)
|
| 225 |
+
return default if value is None else value
|
| 226 |
+
|
| 227 |
+
def pop(self, key: str, default: Any = None) -> Any:
|
| 228 |
+
"""Pop value for a given metadata key."""
|
| 229 |
+
return self.__dict__.pop(key, default)
|
| 230 |
+
|
| 231 |
+
def __getitem__(self, key: str) -> Any:
|
| 232 |
+
"""Get value for a given metadata key."""
|
| 233 |
+
return self.__dict__[key]
|
| 234 |
+
|
| 235 |
+
def __setitem__(self, key: str, value: Any) -> None:
|
| 236 |
+
"""Set value for a given metadata key."""
|
| 237 |
+
self.__dict__[key] = value
|
| 238 |
+
|
| 239 |
+
def __contains__(self, key: str) -> bool:
|
| 240 |
+
"""Check if a given metadata key is set."""
|
| 241 |
+
return key in self.__dict__
|
| 242 |
+
|
| 243 |
+
def __len__(self) -> int:
|
| 244 |
+
"""Return the number of metadata keys set."""
|
| 245 |
+
return len(self.__dict__)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _validate_eval_results(
|
| 249 |
+
eval_results: Optional[Union[EvalResult, list[EvalResult]]],
|
| 250 |
+
model_name: Optional[str],
|
| 251 |
+
) -> list[EvalResult]:
|
| 252 |
+
if eval_results is None:
|
| 253 |
+
return []
|
| 254 |
+
if isinstance(eval_results, EvalResult):
|
| 255 |
+
eval_results = [eval_results]
|
| 256 |
+
if not isinstance(eval_results, list) or not all(isinstance(r, EvalResult) for r in eval_results):
|
| 257 |
+
raise ValueError(
|
| 258 |
+
f"`eval_results` should be of type `EvalResult` or a list of `EvalResult`, got {type(eval_results)}."
|
| 259 |
+
)
|
| 260 |
+
if model_name is None:
|
| 261 |
+
raise ValueError("Passing `eval_results` requires `model_name` to be set.")
|
| 262 |
+
return eval_results
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class ModelCardData(CardData):
|
| 266 |
+
"""Model Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 267 |
+
|
| 268 |
+
Args:
|
| 269 |
+
base_model (`str` or `list[str]`, *optional*):
|
| 270 |
+
The identifier of the base model from which the model derives. This is applicable for example if your model is a
|
| 271 |
+
fine-tune or adapter of an existing model. The value must be the ID of a model on the Hub (or a list of IDs
|
| 272 |
+
if your model derives from multiple models). Defaults to None.
|
| 273 |
+
datasets (`Union[str, list[str]]`, *optional*):
|
| 274 |
+
Dataset or list of datasets that were used to train this model. Should be a dataset ID
|
| 275 |
+
found on https://hf.co/datasets. Defaults to None.
|
| 276 |
+
eval_results (`Union[list[EvalResult], EvalResult]`, *optional*):
|
| 277 |
+
List of `huggingface_hub.EvalResult` that define evaluation results of the model. If provided,
|
| 278 |
+
`model_name` is used to as a name on PapersWithCode's leaderboards. Defaults to `None`.
|
| 279 |
+
language (`Union[str, list[str]]`, *optional*):
|
| 280 |
+
Language of model's training data or metadata. It must be an ISO 639-1, 639-2 or
|
| 281 |
+
639-3 code (two/three letters), or a special value like "code", "multilingual". Defaults to `None`.
|
| 282 |
+
library_name (`str`, *optional*):
|
| 283 |
+
Name of library used by this model. Example: keras or any library from
|
| 284 |
+
https://github.com/huggingface/huggingface.js/blob/main/packages/tasks/src/model-libraries.ts.
|
| 285 |
+
Defaults to None.
|
| 286 |
+
license (`str`, *optional*):
|
| 287 |
+
License of this model. Example: apache-2.0 or any license from
|
| 288 |
+
https://huggingface.co/docs/hub/repositories-licenses. Defaults to None.
|
| 289 |
+
license_name (`str`, *optional*):
|
| 290 |
+
Name of the license of this model. Defaults to None. To be used in conjunction with `license_link`.
|
| 291 |
+
Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a name. In that case, use `license` instead.
|
| 292 |
+
license_link (`str`, *optional*):
|
| 293 |
+
Link to the license of this model. Defaults to None. To be used in conjunction with `license_name`.
|
| 294 |
+
Common licenses (Apache-2.0, MIT, CC-BY-SA-4.0) do not need a link. In that case, use `license` instead.
|
| 295 |
+
metrics (`list[str]`, *optional*):
|
| 296 |
+
List of metrics used to evaluate this model. Should be a metric name that can be found
|
| 297 |
+
at https://hf.co/metrics. Example: 'accuracy'. Defaults to None.
|
| 298 |
+
model_name (`str`, *optional*):
|
| 299 |
+
A name for this model. It is used along with
|
| 300 |
+
`eval_results` to construct the `model-index` within the card's metadata. The name
|
| 301 |
+
you supply here is what will be used on PapersWithCode's leaderboards. If None is provided
|
| 302 |
+
then the repo name is used as a default. Defaults to None.
|
| 303 |
+
pipeline_tag (`str`, *optional*):
|
| 304 |
+
The pipeline tag associated with the model. Example: "text-classification".
|
| 305 |
+
tags (`list[str]`, *optional*):
|
| 306 |
+
List of tags to add to your model that can be used when filtering on the Hugging
|
| 307 |
+
Face Hub. Defaults to None.
|
| 308 |
+
ignore_metadata_errors (`str`):
|
| 309 |
+
If True, errors while parsing the metadata section will be ignored. Some information might be lost during
|
| 310 |
+
the process. Use it at your own risk.
|
| 311 |
+
kwargs (`dict`, *optional*):
|
| 312 |
+
Additional metadata that will be added to the model card. Defaults to None.
|
| 313 |
+
|
| 314 |
+
Example:
|
| 315 |
+
```python
|
| 316 |
+
>>> from huggingface_hub import ModelCardData
|
| 317 |
+
>>> card_data = ModelCardData(
|
| 318 |
+
... language="en",
|
| 319 |
+
... license="mit",
|
| 320 |
+
... library_name="timm",
|
| 321 |
+
... tags=['image-classification', 'resnet'],
|
| 322 |
+
... )
|
| 323 |
+
>>> card_data.to_dict()
|
| 324 |
+
{'language': 'en', 'license': 'mit', 'library_name': 'timm', 'tags': ['image-classification', 'resnet']}
|
| 325 |
+
|
| 326 |
+
```
|
| 327 |
+
"""
|
| 328 |
+
|
| 329 |
+
def __init__(
|
| 330 |
+
self,
|
| 331 |
+
*,
|
| 332 |
+
base_model: Optional[Union[str, list[str]]] = None,
|
| 333 |
+
datasets: Optional[Union[str, list[str]]] = None,
|
| 334 |
+
eval_results: Optional[list[EvalResult]] = None,
|
| 335 |
+
language: Optional[Union[str, list[str]]] = None,
|
| 336 |
+
library_name: Optional[str] = None,
|
| 337 |
+
license: Optional[str] = None,
|
| 338 |
+
license_name: Optional[str] = None,
|
| 339 |
+
license_link: Optional[str] = None,
|
| 340 |
+
metrics: Optional[list[str]] = None,
|
| 341 |
+
model_name: Optional[str] = None,
|
| 342 |
+
pipeline_tag: Optional[str] = None,
|
| 343 |
+
tags: Optional[list[str]] = None,
|
| 344 |
+
ignore_metadata_errors: bool = False,
|
| 345 |
+
**kwargs,
|
| 346 |
+
):
|
| 347 |
+
self.base_model = base_model
|
| 348 |
+
self.datasets = datasets
|
| 349 |
+
self.eval_results = eval_results
|
| 350 |
+
self.language = language
|
| 351 |
+
self.library_name = library_name
|
| 352 |
+
self.license = license
|
| 353 |
+
self.license_name = license_name
|
| 354 |
+
self.license_link = license_link
|
| 355 |
+
self.metrics = metrics
|
| 356 |
+
self.model_name = model_name
|
| 357 |
+
self.pipeline_tag = pipeline_tag
|
| 358 |
+
self.tags = _to_unique_list(tags)
|
| 359 |
+
|
| 360 |
+
model_index = kwargs.pop("model-index", None)
|
| 361 |
+
if model_index:
|
| 362 |
+
try:
|
| 363 |
+
model_name, eval_results = model_index_to_eval_results(model_index)
|
| 364 |
+
self.model_name = model_name
|
| 365 |
+
self.eval_results = eval_results
|
| 366 |
+
except (KeyError, TypeError) as error:
|
| 367 |
+
if ignore_metadata_errors:
|
| 368 |
+
logger.warning("Invalid model-index. Not loading eval results into CardData.")
|
| 369 |
+
else:
|
| 370 |
+
raise ValueError(
|
| 371 |
+
f"Invalid `model_index` in metadata cannot be parsed: {error.__class__} {error}. Pass"
|
| 372 |
+
" `ignore_metadata_errors=True` to ignore this error while loading a Model Card. Warning:"
|
| 373 |
+
" some information will be lost. Use it at your own risk."
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
super().__init__(**kwargs)
|
| 377 |
+
|
| 378 |
+
if self.eval_results:
|
| 379 |
+
try:
|
| 380 |
+
self.eval_results = _validate_eval_results(self.eval_results, self.model_name)
|
| 381 |
+
except Exception as e:
|
| 382 |
+
if ignore_metadata_errors:
|
| 383 |
+
logger.warning(f"Failed to validate eval_results: {e}. Not loading eval results into CardData.")
|
| 384 |
+
else:
|
| 385 |
+
raise ValueError(f"Failed to validate eval_results: {e}") from e
|
| 386 |
+
|
| 387 |
+
def _to_dict(self, data_dict):
|
| 388 |
+
"""Format the internal data dict. In this case, we convert eval results to a valid model index"""
|
| 389 |
+
if self.eval_results is not None:
|
| 390 |
+
data_dict["model-index"] = eval_results_to_model_index(self.model_name, self.eval_results) # type: ignore
|
| 391 |
+
del data_dict["eval_results"], data_dict["model_name"]
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class DatasetCardData(CardData):
|
| 395 |
+
"""Dataset Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 396 |
+
|
| 397 |
+
Args:
|
| 398 |
+
language (`list[str]`, *optional*):
|
| 399 |
+
Language of dataset's data or metadata. It must be an ISO 639-1, 639-2 or
|
| 400 |
+
639-3 code (two/three letters), or a special value like "code", "multilingual".
|
| 401 |
+
license (`Union[str, list[str]]`, *optional*):
|
| 402 |
+
License(s) of this dataset. Example: apache-2.0 or any license from
|
| 403 |
+
https://huggingface.co/docs/hub/repositories-licenses.
|
| 404 |
+
annotations_creators (`Union[str, list[str]]`, *optional*):
|
| 405 |
+
How the annotations for the dataset were created.
|
| 406 |
+
Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'no-annotation', 'other'.
|
| 407 |
+
language_creators (`Union[str, list[str]]`, *optional*):
|
| 408 |
+
How the text-based data in the dataset was created.
|
| 409 |
+
Options are: 'found', 'crowdsourced', 'expert-generated', 'machine-generated', 'other'
|
| 410 |
+
multilinguality (`Union[str, list[str]]`, *optional*):
|
| 411 |
+
Whether the dataset is multilingual.
|
| 412 |
+
Options are: 'monolingual', 'multilingual', 'translation', 'other'.
|
| 413 |
+
size_categories (`Union[str, list[str]]`, *optional*):
|
| 414 |
+
The number of examples in the dataset. Options are: 'n<1K', '1K<n<10K', '10K<n<100K',
|
| 415 |
+
'100K<n<1M', '1M<n<10M', '10M<n<100M', '100M<n<1B', '1B<n<10B', '10B<n<100B', '100B<n<1T', 'n>1T', and 'other'.
|
| 416 |
+
source_datasets (`list[str]]`, *optional*):
|
| 417 |
+
Indicates whether the dataset is an original dataset or extended from another existing dataset.
|
| 418 |
+
Options are: 'original' and 'extended'.
|
| 419 |
+
task_categories (`Union[str, list[str]]`, *optional*):
|
| 420 |
+
What categories of task does the dataset support?
|
| 421 |
+
task_ids (`Union[str, list[str]]`, *optional*):
|
| 422 |
+
What specific tasks does the dataset support?
|
| 423 |
+
paperswithcode_id (`str`, *optional*):
|
| 424 |
+
ID of the dataset on PapersWithCode.
|
| 425 |
+
pretty_name (`str`, *optional*):
|
| 426 |
+
A more human-readable name for the dataset. (ex. "Cats vs. Dogs")
|
| 427 |
+
train_eval_index (`dict`, *optional*):
|
| 428 |
+
A dictionary that describes the necessary spec for doing evaluation on the Hub.
|
| 429 |
+
If not provided, it will be gathered from the 'train-eval-index' key of the kwargs.
|
| 430 |
+
config_names (`Union[str, list[str]]`, *optional*):
|
| 431 |
+
A list of the available dataset configs for the dataset.
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
def __init__(
|
| 435 |
+
self,
|
| 436 |
+
*,
|
| 437 |
+
language: Optional[Union[str, list[str]]] = None,
|
| 438 |
+
license: Optional[Union[str, list[str]]] = None,
|
| 439 |
+
annotations_creators: Optional[Union[str, list[str]]] = None,
|
| 440 |
+
language_creators: Optional[Union[str, list[str]]] = None,
|
| 441 |
+
multilinguality: Optional[Union[str, list[str]]] = None,
|
| 442 |
+
size_categories: Optional[Union[str, list[str]]] = None,
|
| 443 |
+
source_datasets: Optional[list[str]] = None,
|
| 444 |
+
task_categories: Optional[Union[str, list[str]]] = None,
|
| 445 |
+
task_ids: Optional[Union[str, list[str]]] = None,
|
| 446 |
+
paperswithcode_id: Optional[str] = None,
|
| 447 |
+
pretty_name: Optional[str] = None,
|
| 448 |
+
train_eval_index: Optional[dict] = None,
|
| 449 |
+
config_names: Optional[Union[str, list[str]]] = None,
|
| 450 |
+
ignore_metadata_errors: bool = False,
|
| 451 |
+
**kwargs,
|
| 452 |
+
):
|
| 453 |
+
self.annotations_creators = annotations_creators
|
| 454 |
+
self.language_creators = language_creators
|
| 455 |
+
self.language = language
|
| 456 |
+
self.license = license
|
| 457 |
+
self.multilinguality = multilinguality
|
| 458 |
+
self.size_categories = size_categories
|
| 459 |
+
self.source_datasets = source_datasets
|
| 460 |
+
self.task_categories = task_categories
|
| 461 |
+
self.task_ids = task_ids
|
| 462 |
+
self.paperswithcode_id = paperswithcode_id
|
| 463 |
+
self.pretty_name = pretty_name
|
| 464 |
+
self.config_names = config_names
|
| 465 |
+
|
| 466 |
+
# TODO - maybe handle this similarly to EvalResult?
|
| 467 |
+
self.train_eval_index = train_eval_index or kwargs.pop("train-eval-index", None)
|
| 468 |
+
super().__init__(**kwargs)
|
| 469 |
+
|
| 470 |
+
def _to_dict(self, data_dict):
|
| 471 |
+
data_dict["train-eval-index"] = data_dict.pop("train_eval_index")
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
class SpaceCardData(CardData):
|
| 475 |
+
"""Space Card Metadata that is used by Hugging Face Hub when included at the top of your README.md
|
| 476 |
+
|
| 477 |
+
To get an exhaustive reference of Spaces configuration, please visit https://huggingface.co/docs/hub/spaces-config-reference#spaces-configuration-reference.
|
| 478 |
+
|
| 479 |
+
Args:
|
| 480 |
+
title (`str`, *optional*)
|
| 481 |
+
Title of the Space.
|
| 482 |
+
sdk (`str`, *optional*)
|
| 483 |
+
SDK of the Space (one of `gradio`, `streamlit`, `docker`, or `static`).
|
| 484 |
+
sdk_version (`str`, *optional*)
|
| 485 |
+
Version of the used SDK (if Gradio/Streamlit sdk).
|
| 486 |
+
python_version (`str`, *optional*)
|
| 487 |
+
Python version used in the Space (if Gradio/Streamlit sdk).
|
| 488 |
+
app_file (`str`, *optional*)
|
| 489 |
+
Path to your main application file (which contains either gradio or streamlit Python code, or static html code).
|
| 490 |
+
Path is relative to the root of the repository.
|
| 491 |
+
app_port (`str`, *optional*)
|
| 492 |
+
Port on which your application is running. Used only if sdk is `docker`.
|
| 493 |
+
license (`str`, *optional*)
|
| 494 |
+
License of this model. Example: apache-2.0 or any license from
|
| 495 |
+
https://huggingface.co/docs/hub/repositories-licenses.
|
| 496 |
+
duplicated_from (`str`, *optional*)
|
| 497 |
+
ID of the original Space if this is a duplicated Space.
|
| 498 |
+
models (list[`str`], *optional*)
|
| 499 |
+
List of models related to this Space. Should be a dataset ID found on https://hf.co/models.
|
| 500 |
+
datasets (`list[str]`, *optional*)
|
| 501 |
+
List of datasets related to this Space. Should be a dataset ID found on https://hf.co/datasets.
|
| 502 |
+
tags (`list[str]`, *optional*)
|
| 503 |
+
List of tags to add to your Space that can be used when filtering on the Hub.
|
| 504 |
+
ignore_metadata_errors (`str`):
|
| 505 |
+
If True, errors while parsing the metadata section will be ignored. Some information might be lost during
|
| 506 |
+
the process. Use it at your own risk.
|
| 507 |
+
kwargs (`dict`, *optional*):
|
| 508 |
+
Additional metadata that will be added to the space card.
|
| 509 |
+
|
| 510 |
+
Example:
|
| 511 |
+
```python
|
| 512 |
+
>>> from huggingface_hub import SpaceCardData
|
| 513 |
+
>>> card_data = SpaceCardData(
|
| 514 |
+
... title="Dreambooth Training",
|
| 515 |
+
... license="mit",
|
| 516 |
+
... sdk="gradio",
|
| 517 |
+
... duplicated_from="multimodalart/dreambooth-training"
|
| 518 |
+
... )
|
| 519 |
+
>>> card_data.to_dict()
|
| 520 |
+
{'title': 'Dreambooth Training', 'sdk': 'gradio', 'license': 'mit', 'duplicated_from': 'multimodalart/dreambooth-training'}
|
| 521 |
+
```
|
| 522 |
+
"""
|
| 523 |
+
|
| 524 |
+
def __init__(
|
| 525 |
+
self,
|
| 526 |
+
*,
|
| 527 |
+
title: Optional[str] = None,
|
| 528 |
+
sdk: Optional[str] = None,
|
| 529 |
+
sdk_version: Optional[str] = None,
|
| 530 |
+
python_version: Optional[str] = None,
|
| 531 |
+
app_file: Optional[str] = None,
|
| 532 |
+
app_port: Optional[int] = None,
|
| 533 |
+
license: Optional[str] = None,
|
| 534 |
+
duplicated_from: Optional[str] = None,
|
| 535 |
+
models: Optional[list[str]] = None,
|
| 536 |
+
datasets: Optional[list[str]] = None,
|
| 537 |
+
tags: Optional[list[str]] = None,
|
| 538 |
+
ignore_metadata_errors: bool = False,
|
| 539 |
+
**kwargs,
|
| 540 |
+
):
|
| 541 |
+
self.title = title
|
| 542 |
+
self.sdk = sdk
|
| 543 |
+
self.sdk_version = sdk_version
|
| 544 |
+
self.python_version = python_version
|
| 545 |
+
self.app_file = app_file
|
| 546 |
+
self.app_port = app_port
|
| 547 |
+
self.license = license
|
| 548 |
+
self.duplicated_from = duplicated_from
|
| 549 |
+
self.models = models
|
| 550 |
+
self.datasets = datasets
|
| 551 |
+
self.tags = _to_unique_list(tags)
|
| 552 |
+
super().__init__(**kwargs)
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
def model_index_to_eval_results(model_index: list[dict[str, Any]]) -> tuple[str, list[EvalResult]]:
|
| 556 |
+
"""Takes in a model index and returns the model name and a list of `huggingface_hub.EvalResult` objects.
|
| 557 |
+
|
| 558 |
+
A detailed spec of the model index can be found here:
|
| 559 |
+
https://github.com/huggingface/hub-docs/blob/main/modelcard.md?plain=1
|
| 560 |
+
|
| 561 |
+
Args:
|
| 562 |
+
model_index (`list[dict[str, Any]]`):
|
| 563 |
+
A model index data structure, likely coming from a README.md file on the
|
| 564 |
+
Hugging Face Hub.
|
| 565 |
+
|
| 566 |
+
Returns:
|
| 567 |
+
model_name (`str`):
|
| 568 |
+
The name of the model as found in the model index. This is used as the
|
| 569 |
+
identifier for the model on leaderboards like PapersWithCode.
|
| 570 |
+
eval_results (`list[EvalResult]`):
|
| 571 |
+
A list of `huggingface_hub.EvalResult` objects containing the metrics
|
| 572 |
+
reported in the provided model_index.
|
| 573 |
+
|
| 574 |
+
Example:
|
| 575 |
+
```python
|
| 576 |
+
>>> from huggingface_hub.repocard_data import model_index_to_eval_results
|
| 577 |
+
>>> # Define a minimal model index
|
| 578 |
+
>>> model_index = [
|
| 579 |
+
... {
|
| 580 |
+
... "name": "my-cool-model",
|
| 581 |
+
... "results": [
|
| 582 |
+
... {
|
| 583 |
+
... "task": {
|
| 584 |
+
... "type": "image-classification"
|
| 585 |
+
... },
|
| 586 |
+
... "dataset": {
|
| 587 |
+
... "type": "beans",
|
| 588 |
+
... "name": "Beans"
|
| 589 |
+
... },
|
| 590 |
+
... "metrics": [
|
| 591 |
+
... {
|
| 592 |
+
... "type": "accuracy",
|
| 593 |
+
... "value": 0.9
|
| 594 |
+
... }
|
| 595 |
+
... ]
|
| 596 |
+
... }
|
| 597 |
+
... ]
|
| 598 |
+
... }
|
| 599 |
+
... ]
|
| 600 |
+
>>> model_name, eval_results = model_index_to_eval_results(model_index)
|
| 601 |
+
>>> model_name
|
| 602 |
+
'my-cool-model'
|
| 603 |
+
>>> eval_results[0].task_type
|
| 604 |
+
'image-classification'
|
| 605 |
+
>>> eval_results[0].metric_type
|
| 606 |
+
'accuracy'
|
| 607 |
+
|
| 608 |
+
```
|
| 609 |
+
"""
|
| 610 |
+
|
| 611 |
+
eval_results = []
|
| 612 |
+
for elem in model_index:
|
| 613 |
+
name = elem["name"]
|
| 614 |
+
results = elem["results"]
|
| 615 |
+
for result in results:
|
| 616 |
+
task_type = result["task"]["type"]
|
| 617 |
+
task_name = result["task"].get("name")
|
| 618 |
+
dataset_type = result["dataset"]["type"]
|
| 619 |
+
dataset_name = result["dataset"]["name"]
|
| 620 |
+
dataset_config = result["dataset"].get("config")
|
| 621 |
+
dataset_split = result["dataset"].get("split")
|
| 622 |
+
dataset_revision = result["dataset"].get("revision")
|
| 623 |
+
dataset_args = result["dataset"].get("args")
|
| 624 |
+
source_name = result.get("source", {}).get("name")
|
| 625 |
+
source_url = result.get("source", {}).get("url")
|
| 626 |
+
|
| 627 |
+
for metric in result["metrics"]:
|
| 628 |
+
metric_type = metric["type"]
|
| 629 |
+
metric_value = metric["value"]
|
| 630 |
+
metric_name = metric.get("name")
|
| 631 |
+
metric_args = metric.get("args")
|
| 632 |
+
metric_config = metric.get("config")
|
| 633 |
+
verified = metric.get("verified")
|
| 634 |
+
verify_token = metric.get("verifyToken")
|
| 635 |
+
|
| 636 |
+
eval_result = EvalResult(
|
| 637 |
+
task_type=task_type, # Required
|
| 638 |
+
dataset_type=dataset_type, # Required
|
| 639 |
+
dataset_name=dataset_name, # Required
|
| 640 |
+
metric_type=metric_type, # Required
|
| 641 |
+
metric_value=metric_value, # Required
|
| 642 |
+
task_name=task_name,
|
| 643 |
+
dataset_config=dataset_config,
|
| 644 |
+
dataset_split=dataset_split,
|
| 645 |
+
dataset_revision=dataset_revision,
|
| 646 |
+
dataset_args=dataset_args,
|
| 647 |
+
metric_name=metric_name,
|
| 648 |
+
metric_args=metric_args,
|
| 649 |
+
metric_config=metric_config,
|
| 650 |
+
verified=verified,
|
| 651 |
+
verify_token=verify_token,
|
| 652 |
+
source_name=source_name,
|
| 653 |
+
source_url=source_url,
|
| 654 |
+
)
|
| 655 |
+
eval_results.append(eval_result)
|
| 656 |
+
return name, eval_results
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _remove_none(obj):
|
| 660 |
+
"""
|
| 661 |
+
Recursively remove `None` values from a dict. Borrowed from: https://stackoverflow.com/a/20558778
|
| 662 |
+
"""
|
| 663 |
+
if isinstance(obj, (list, tuple, set)):
|
| 664 |
+
return type(obj)(_remove_none(x) for x in obj if x is not None)
|
| 665 |
+
elif isinstance(obj, dict):
|
| 666 |
+
return type(obj)((_remove_none(k), _remove_none(v)) for k, v in obj.items() if k is not None and v is not None)
|
| 667 |
+
else:
|
| 668 |
+
return obj
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def eval_results_to_model_index(model_name: str, eval_results: list[EvalResult]) -> list[dict[str, Any]]:
|
| 672 |
+
"""Takes in given model name and list of `huggingface_hub.EvalResult` and returns a
|
| 673 |
+
valid model-index that will be compatible with the format expected by the
|
| 674 |
+
Hugging Face Hub.
|
| 675 |
+
|
| 676 |
+
Args:
|
| 677 |
+
model_name (`str`):
|
| 678 |
+
Name of the model (ex. "my-cool-model"). This is used as the identifier
|
| 679 |
+
for the model on leaderboards like PapersWithCode.
|
| 680 |
+
eval_results (`list[EvalResult]`):
|
| 681 |
+
List of `huggingface_hub.EvalResult` objects containing the metrics to be
|
| 682 |
+
reported in the model-index.
|
| 683 |
+
|
| 684 |
+
Returns:
|
| 685 |
+
model_index (`list[dict[str, Any]]`): The eval_results converted to a model-index.
|
| 686 |
+
|
| 687 |
+
Example:
|
| 688 |
+
```python
|
| 689 |
+
>>> from huggingface_hub.repocard_data import eval_results_to_model_index, EvalResult
|
| 690 |
+
>>> # Define minimal eval_results
|
| 691 |
+
>>> eval_results = [
|
| 692 |
+
... EvalResult(
|
| 693 |
+
... task_type="image-classification", # Required
|
| 694 |
+
... dataset_type="beans", # Required
|
| 695 |
+
... dataset_name="Beans", # Required
|
| 696 |
+
... metric_type="accuracy", # Required
|
| 697 |
+
... metric_value=0.9, # Required
|
| 698 |
+
... )
|
| 699 |
+
... ]
|
| 700 |
+
>>> eval_results_to_model_index("my-cool-model", eval_results)
|
| 701 |
+
[{'name': 'my-cool-model', 'results': [{'task': {'type': 'image-classification'}, 'dataset': {'name': 'Beans', 'type': 'beans'}, 'metrics': [{'type': 'accuracy', 'value': 0.9}]}]}]
|
| 702 |
+
|
| 703 |
+
```
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
# Metrics are reported on a unique task-and-dataset basis.
|
| 707 |
+
# Here, we make a map of those pairs and the associated EvalResults.
|
| 708 |
+
task_and_ds_types_map: dict[Any, list[EvalResult]] = defaultdict(list)
|
| 709 |
+
for eval_result in eval_results:
|
| 710 |
+
task_and_ds_types_map[eval_result.unique_identifier].append(eval_result)
|
| 711 |
+
|
| 712 |
+
# Use the map from above to generate the model index data.
|
| 713 |
+
model_index_data: list[dict[str, Any]] = []
|
| 714 |
+
for results in task_and_ds_types_map.values():
|
| 715 |
+
# All items from `results` share same metadata
|
| 716 |
+
sample_result = results[0]
|
| 717 |
+
data: dict[str, Any] = {
|
| 718 |
+
"task": {
|
| 719 |
+
"type": sample_result.task_type,
|
| 720 |
+
"name": sample_result.task_name,
|
| 721 |
+
},
|
| 722 |
+
"dataset": {
|
| 723 |
+
"name": sample_result.dataset_name,
|
| 724 |
+
"type": sample_result.dataset_type,
|
| 725 |
+
"config": sample_result.dataset_config,
|
| 726 |
+
"split": sample_result.dataset_split,
|
| 727 |
+
"revision": sample_result.dataset_revision,
|
| 728 |
+
"args": sample_result.dataset_args,
|
| 729 |
+
},
|
| 730 |
+
"metrics": [
|
| 731 |
+
{
|
| 732 |
+
"type": result.metric_type,
|
| 733 |
+
"value": result.metric_value,
|
| 734 |
+
"name": result.metric_name,
|
| 735 |
+
"config": result.metric_config,
|
| 736 |
+
"args": result.metric_args,
|
| 737 |
+
"verified": result.verified,
|
| 738 |
+
"verifyToken": result.verify_token,
|
| 739 |
+
}
|
| 740 |
+
for result in results
|
| 741 |
+
],
|
| 742 |
+
}
|
| 743 |
+
if sample_result.source_url is not None:
|
| 744 |
+
source: dict[str, str] = {
|
| 745 |
+
"url": sample_result.source_url,
|
| 746 |
+
}
|
| 747 |
+
if sample_result.source_name is not None:
|
| 748 |
+
source["name"] = sample_result.source_name
|
| 749 |
+
data["source"] = source
|
| 750 |
+
model_index_data.append(data)
|
| 751 |
+
|
| 752 |
+
# TODO - Check if there cases where this list is longer than one?
|
| 753 |
+
# Finally, the model index itself is list of dicts.
|
| 754 |
+
model_index = [
|
| 755 |
+
{
|
| 756 |
+
"name": model_name,
|
| 757 |
+
"results": model_index_data,
|
| 758 |
+
}
|
| 759 |
+
]
|
| 760 |
+
return _remove_none(model_index)
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def _to_unique_list(tags: Optional[list[str]]) -> Optional[list[str]]:
|
| 764 |
+
if tags is None:
|
| 765 |
+
return tags
|
| 766 |
+
unique_tags = [] # make tags unique + keep order explicitly
|
| 767 |
+
for tag in tags:
|
| 768 |
+
if tag not in unique_tags:
|
| 769 |
+
unique_tags.append(tag)
|
| 770 |
+
return unique_tags
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: ipykernel
|
| 3 |
+
Version: 7.2.0
|
| 4 |
+
Summary: IPython Kernel for Jupyter
|
| 5 |
+
Project-URL: Homepage, https://ipython.org
|
| 6 |
+
Project-URL: Documentation, https://ipykernel.readthedocs.io
|
| 7 |
+
Project-URL: Source, https://github.com/ipython/ipykernel
|
| 8 |
+
Project-URL: Tracker, https://github.com/ipython/ipykernel/issues
|
| 9 |
+
Author-email: IPython Development Team <ipython-dev@scipy.org>
|
| 10 |
+
License-Expression: BSD-3-Clause
|
| 11 |
+
License-File: LICENSE
|
| 12 |
+
Keywords: Interactive,Interpreter,Shell,Web
|
| 13 |
+
Classifier: Intended Audience :: Developers
|
| 14 |
+
Classifier: Intended Audience :: Science/Research
|
| 15 |
+
Classifier: Intended Audience :: System Administrators
|
| 16 |
+
Classifier: Programming Language :: Python
|
| 17 |
+
Classifier: Programming Language :: Python :: 3
|
| 18 |
+
Requires-Python: >=3.10
|
| 19 |
+
Requires-Dist: appnope>=0.1.2; platform_system == 'Darwin'
|
| 20 |
+
Requires-Dist: comm>=0.1.1
|
| 21 |
+
Requires-Dist: debugpy>=1.6.5
|
| 22 |
+
Requires-Dist: ipython>=7.23.1
|
| 23 |
+
Requires-Dist: jupyter-client>=8.8.0
|
| 24 |
+
Requires-Dist: jupyter-core!=6.0.*,>=5.1
|
| 25 |
+
Requires-Dist: matplotlib-inline>=0.1
|
| 26 |
+
Requires-Dist: nest-asyncio>=1.4
|
| 27 |
+
Requires-Dist: packaging>=22
|
| 28 |
+
Requires-Dist: psutil>=5.7
|
| 29 |
+
Requires-Dist: pyzmq>=25
|
| 30 |
+
Requires-Dist: tornado>=6.4.1
|
| 31 |
+
Requires-Dist: traitlets>=5.4.0
|
| 32 |
+
Provides-Extra: cov
|
| 33 |
+
Requires-Dist: coverage[toml]; extra == 'cov'
|
| 34 |
+
Requires-Dist: matplotlib; extra == 'cov'
|
| 35 |
+
Requires-Dist: pytest-cov; extra == 'cov'
|
| 36 |
+
Requires-Dist: trio; extra == 'cov'
|
| 37 |
+
Provides-Extra: docs
|
| 38 |
+
Requires-Dist: intersphinx-registry; extra == 'docs'
|
| 39 |
+
Requires-Dist: myst-parser; extra == 'docs'
|
| 40 |
+
Requires-Dist: pydata-sphinx-theme; extra == 'docs'
|
| 41 |
+
Requires-Dist: sphinx-autodoc-typehints; extra == 'docs'
|
| 42 |
+
Requires-Dist: sphinx<8.2.0; extra == 'docs'
|
| 43 |
+
Requires-Dist: sphinxcontrib-github-alt; extra == 'docs'
|
| 44 |
+
Requires-Dist: sphinxcontrib-spelling; extra == 'docs'
|
| 45 |
+
Requires-Dist: trio; extra == 'docs'
|
| 46 |
+
Provides-Extra: pyqt5
|
| 47 |
+
Requires-Dist: pyqt5; extra == 'pyqt5'
|
| 48 |
+
Provides-Extra: pyside6
|
| 49 |
+
Requires-Dist: pyside6; extra == 'pyside6'
|
| 50 |
+
Provides-Extra: test
|
| 51 |
+
Requires-Dist: flaky; extra == 'test'
|
| 52 |
+
Requires-Dist: ipyparallel; extra == 'test'
|
| 53 |
+
Requires-Dist: pre-commit; extra == 'test'
|
| 54 |
+
Requires-Dist: pytest-asyncio>=0.23.5; extra == 'test'
|
| 55 |
+
Requires-Dist: pytest-cov; extra == 'test'
|
| 56 |
+
Requires-Dist: pytest-timeout; extra == 'test'
|
| 57 |
+
Requires-Dist: pytest<10,>=7.0; extra == 'test'
|
| 58 |
+
Description-Content-Type: text/markdown
|
| 59 |
+
|
| 60 |
+
# IPython Kernel for Jupyter
|
| 61 |
+
|
| 62 |
+
[](https://github.com/ipython/ipykernel/actions/workflows/ci.yml/badge.svg?query=branch%3Amain++)
|
| 63 |
+
[](http://ipykernel.readthedocs.io/en/latest/?badge=latest)
|
| 64 |
+
|
| 65 |
+
This package provides the IPython kernel for Jupyter.
|
| 66 |
+
|
| 67 |
+
## Installation from source
|
| 68 |
+
|
| 69 |
+
1. `git clone`
|
| 70 |
+
1. `cd ipykernel`
|
| 71 |
+
1. `pip install -e ".[test]"`
|
| 72 |
+
|
| 73 |
+
After that, all normal `ipython` commands will use this newly-installed version of the kernel.
|
| 74 |
+
|
| 75 |
+
## Running tests
|
| 76 |
+
|
| 77 |
+
Follow the instructions from `Installation from source`.
|
| 78 |
+
|
| 79 |
+
and then from the root directory
|
| 80 |
+
|
| 81 |
+
```bash
|
| 82 |
+
pytest
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
## Running tests with coverage
|
| 86 |
+
|
| 87 |
+
Follow the instructions from `Installation from source`.
|
| 88 |
+
|
| 89 |
+
and then from the root directory
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
pytest -vv -s --cov ipykernel --cov-branch --cov-report term-missing:skip-covered --durations 10
|
| 93 |
+
```
|
| 94 |
+
|
| 95 |
+
## About the IPython Development Team
|
| 96 |
+
|
| 97 |
+
The IPython Development Team is the set of all contributors to the IPython project.
|
| 98 |
+
This includes all of the IPython subprojects.
|
| 99 |
+
|
| 100 |
+
The core team that coordinates development on GitHub can be found here:
|
| 101 |
+
https://github.com/ipython/.
|
| 102 |
+
|
| 103 |
+
## Our Copyright Policy
|
| 104 |
+
|
| 105 |
+
IPython uses a shared copyright model. Each contributor maintains copyright
|
| 106 |
+
over their contributions to IPython. But, it is important to note that these
|
| 107 |
+
contributions are typically only changes to the repositories. Thus, the IPython
|
| 108 |
+
source code, in its entirety is not the copyright of any single person or
|
| 109 |
+
institution. Instead, it is the collective copyright of the entire IPython
|
| 110 |
+
Development Team. If individual contributors want to maintain a record of what
|
| 111 |
+
changes/contributions they have specific copyright on, they should indicate
|
| 112 |
+
their copyright in the commit message of the change, when they commit the
|
| 113 |
+
change to one of the IPython repositories.
|
| 114 |
+
|
| 115 |
+
With this in mind, the following banner should be used in any source code file
|
| 116 |
+
to indicate the copyright and license terms:
|
| 117 |
+
|
| 118 |
+
```
|
| 119 |
+
# Copyright (c) IPython Development Team.
|
| 120 |
+
# Distributed under the terms of the Modified BSD License.
|
| 121 |
+
```
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
../../../share/jupyter/kernels/python3/kernel.json,sha256=noWduy_yDUU5IvYFbIbaIMGbN4NILzC4fTDoqKAhW8A,228
|
| 2 |
+
../../../share/jupyter/kernels/python3/logo-32x32.png,sha256=4ytcKCBy1xeIe2DacxeP3TWmXcPK6sunoCblpCVcyZc,1084
|
| 3 |
+
../../../share/jupyter/kernels/python3/logo-64x64.png,sha256=XJBjtDbO3wVnSA_kh-zg0UeeqVRfMQy6k_oYTMurKQ0,2180
|
| 4 |
+
../../../share/jupyter/kernels/python3/logo-svg.svg,sha256=uuyGYqFGHCyswya1TScnyy8c4HugLQD1uCbQNRBPZJ8,9605
|
| 5 |
+
__pycache__/ipykernel_launcher.cpython-311.pyc,,
|
| 6 |
+
ipykernel-7.2.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 7 |
+
ipykernel-7.2.0.dist-info/METADATA,sha256=2k4RExi3luHX5zn5OJS7AlF4BAlPaoKtGl7EDA3A-54,4479
|
| 8 |
+
ipykernel-7.2.0.dist-info/RECORD,,
|
| 9 |
+
ipykernel-7.2.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
|
| 10 |
+
ipykernel-7.2.0.dist-info/licenses/LICENSE,sha256=NuwpyHH3o4LN4wHLpHaYGRzzJ8P5X_XCQAZeld3oC_0,1533
|
| 11 |
+
ipykernel/__init__.py,sha256=kk-QWpKS_WnCbslt1hAhz47muGijsDQqj75oxIbimkU,161
|
| 12 |
+
ipykernel/__main__.py,sha256=9HDqz4R5PkE8OHzgIMp-7xheNaWl8j7jTtjKEOWVuek,143
|
| 13 |
+
ipykernel/__pycache__/__init__.cpython-311.pyc,,
|
| 14 |
+
ipykernel/__pycache__/__main__.cpython-311.pyc,,
|
| 15 |
+
ipykernel/__pycache__/_eventloop_macos.cpython-311.pyc,,
|
| 16 |
+
ipykernel/__pycache__/_version.cpython-311.pyc,,
|
| 17 |
+
ipykernel/__pycache__/compiler.cpython-311.pyc,,
|
| 18 |
+
ipykernel/__pycache__/connect.cpython-311.pyc,,
|
| 19 |
+
ipykernel/__pycache__/control.cpython-311.pyc,,
|
| 20 |
+
ipykernel/__pycache__/debugger.cpython-311.pyc,,
|
| 21 |
+
ipykernel/__pycache__/displayhook.cpython-311.pyc,,
|
| 22 |
+
ipykernel/__pycache__/embed.cpython-311.pyc,,
|
| 23 |
+
ipykernel/__pycache__/eventloops.cpython-311.pyc,,
|
| 24 |
+
ipykernel/__pycache__/heartbeat.cpython-311.pyc,,
|
| 25 |
+
ipykernel/__pycache__/iostream.cpython-311.pyc,,
|
| 26 |
+
ipykernel/__pycache__/ipkernel.cpython-311.pyc,,
|
| 27 |
+
ipykernel/__pycache__/jsonutil.cpython-311.pyc,,
|
| 28 |
+
ipykernel/__pycache__/kernelapp.cpython-311.pyc,,
|
| 29 |
+
ipykernel/__pycache__/kernelbase.cpython-311.pyc,,
|
| 30 |
+
ipykernel/__pycache__/kernelspec.cpython-311.pyc,,
|
| 31 |
+
ipykernel/__pycache__/log.cpython-311.pyc,,
|
| 32 |
+
ipykernel/__pycache__/parentpoller.cpython-311.pyc,,
|
| 33 |
+
ipykernel/__pycache__/shellchannel.cpython-311.pyc,,
|
| 34 |
+
ipykernel/__pycache__/socket_pair.cpython-311.pyc,,
|
| 35 |
+
ipykernel/__pycache__/subshell.cpython-311.pyc,,
|
| 36 |
+
ipykernel/__pycache__/subshell_manager.cpython-311.pyc,,
|
| 37 |
+
ipykernel/__pycache__/thread.cpython-311.pyc,,
|
| 38 |
+
ipykernel/__pycache__/trio_runner.cpython-311.pyc,,
|
| 39 |
+
ipykernel/__pycache__/utils.cpython-311.pyc,,
|
| 40 |
+
ipykernel/__pycache__/zmqshell.cpython-311.pyc,,
|
| 41 |
+
ipykernel/_eventloop_macos.py,sha256=7oxrFAcW2wPQc3YKtmHc4rRtg3ZMely1OIFjZQ7jJgs,4550
|
| 42 |
+
ipykernel/_version.py,sha256=WpRp3TSywdBKP9HnTXJMp2gZH3rHVPTlOCictmnL7WU,608
|
| 43 |
+
ipykernel/comm/__init__.py,sha256=BqmYOrTRM3hAMvp7r7UKH0fwX2WQzR7YZELBwmcpj5Y,91
|
| 44 |
+
ipykernel/comm/__pycache__/__init__.cpython-311.pyc,,
|
| 45 |
+
ipykernel/comm/__pycache__/comm.cpython-311.pyc,,
|
| 46 |
+
ipykernel/comm/__pycache__/manager.cpython-311.pyc,,
|
| 47 |
+
ipykernel/comm/comm.py,sha256=sm4aysr4iCNJinMZk-rL0f0G8ZplVKcdc6Wty-IfCVE,3191
|
| 48 |
+
ipykernel/comm/manager.py,sha256=WEw-HnATldktdQ5mTzi9MQHlYnXBVc74vQezhpPeelg,2086
|
| 49 |
+
ipykernel/compiler.py,sha256=b1po25Ri_BVRxVQevGv0MwHbuh2FOWKXeMAd9ZAAe3w,2875
|
| 50 |
+
ipykernel/connect.py,sha256=gCLq79ywaHb6Ve6EVGqgb9hSQ-XO7mx_xwLlQwK5q8M,4104
|
| 51 |
+
ipykernel/control.py,sha256=W4zaHx-4OzKm9CmwUv38mLCSID8LP0mBubEFalfJ760,301
|
| 52 |
+
ipykernel/debugger.py,sha256=sbNRfMFrjVSOHUIIkba3mcpsWrZIvdAbkdrVkB3yS7M,26683
|
| 53 |
+
ipykernel/displayhook.py,sha256=jqjtmDi1zsB1t-QuDpNnzKoMU0IL52Eq_-ZKz_WCwSU,4076
|
| 54 |
+
ipykernel/embed.py,sha256=DdGuiLvk-KcNWOUqOiR9G1YhXxf0G-480_Wf9jmnsUw,2129
|
| 55 |
+
ipykernel/eventloops.py,sha256=ydVr8k74Upv1vDXBSSVTKtDQ5hJfRgKx50RIMEiGLTg,20588
|
| 56 |
+
ipykernel/gui/__init__.py,sha256=8HapLY_ZoePEfwubASLykl3ihkoIHZQeUgrLhdaP1Uw,578
|
| 57 |
+
ipykernel/gui/__pycache__/__init__.cpython-311.pyc,,
|
| 58 |
+
ipykernel/gui/__pycache__/gtk3embed.cpython-311.pyc,,
|
| 59 |
+
ipykernel/gui/__pycache__/gtkembed.cpython-311.pyc,,
|
| 60 |
+
ipykernel/gui/gtk3embed.py,sha256=BW6HSQqmu3QyTFppqPRTWDn2j3vXR9_3BxCMmSFEBM0,3432
|
| 61 |
+
ipykernel/gui/gtkembed.py,sha256=Eil8N4gqnRE-AJeAhKcSZgdqFvtALxMn7f_6UX5lRd0,3328
|
| 62 |
+
ipykernel/heartbeat.py,sha256=yoHzt3CD7JwBAgXMqtd1jSmu-T78wf85NDTuIL8I-58,4528
|
| 63 |
+
ipykernel/inprocess/__init__.py,sha256=CJ6UeFe2xf6tkXC-mYggI_qs2X3thf-GJ_2CDZxTOIM,197
|
| 64 |
+
ipykernel/inprocess/__pycache__/__init__.cpython-311.pyc,,
|
| 65 |
+
ipykernel/inprocess/__pycache__/blocking.cpython-311.pyc,,
|
| 66 |
+
ipykernel/inprocess/__pycache__/channels.cpython-311.pyc,,
|
| 67 |
+
ipykernel/inprocess/__pycache__/client.cpython-311.pyc,,
|
| 68 |
+
ipykernel/inprocess/__pycache__/constants.cpython-311.pyc,,
|
| 69 |
+
ipykernel/inprocess/__pycache__/ipkernel.cpython-311.pyc,,
|
| 70 |
+
ipykernel/inprocess/__pycache__/manager.cpython-311.pyc,,
|
| 71 |
+
ipykernel/inprocess/__pycache__/socket.cpython-311.pyc,,
|
| 72 |
+
ipykernel/inprocess/blocking.py,sha256=K4Ux3BOeWJSsiE7O0kRJVAvUMjDb8Z8TC6ZkokAHjNw,3660
|
| 73 |
+
ipykernel/inprocess/channels.py,sha256=hehr4pj39otMj2oQexs5aB-xRbSFKW8o0btZRYurBDM,2993
|
| 74 |
+
ipykernel/inprocess/client.py,sha256=9j4FOTIN9ij-tqagegOmmnM2j53MPtvJYb7TMN-cwLE,8523
|
| 75 |
+
ipykernel/inprocess/constants.py,sha256=mHkiAdtnS4oeVL9RR-VztmPq5cSVQzFSPP2PrMuS4xc,302
|
| 76 |
+
ipykernel/inprocess/ipkernel.py,sha256=NzmP_cOuLMYcRn3QDeQL8j3h9sTK64LweQIhbDUB5Fs,7333
|
| 77 |
+
ipykernel/inprocess/manager.py,sha256=-B31z9CZOk8zeJ_MTpVPiq6mP-0g1jK8LubYB_WT-ns,3054
|
| 78 |
+
ipykernel/inprocess/socket.py,sha256=J171WSjsKfJfg3ZgxCqtmFZjjOgnQzbZECO8ZVW6c7c,1380
|
| 79 |
+
ipykernel/iostream.py,sha256=iWEknaGsmWnffA8a-lE-KJdyFIY4XYZSpz-BKuAVSrE,29144
|
| 80 |
+
ipykernel/ipkernel.py,sha256=nS6JOHad8O2txC7jNuiK7GCcF8jlk1jggSNHItKfOhg,26505
|
| 81 |
+
ipykernel/jsonutil.py,sha256=q5VnbClLoueoECVVOCBZ9ISXitco6hFDlKtwGNdtquI,5049
|
| 82 |
+
ipykernel/kernelapp.py,sha256=v4X1Ro-bfGG4QE-1tbxqcVxqwZwKuxh4bRDj6s4nGPA,29825
|
| 83 |
+
ipykernel/kernelbase.py,sha256=pGPZEewuOvRshM1a17tEZgOy6KxOlXi8rpXrFmgnkdU,56997
|
| 84 |
+
ipykernel/kernelspec.py,sha256=7m8gPNhr91Tqcikoq65_uVzLOeK4ByFE_QOAdozoYho,9850
|
| 85 |
+
ipykernel/log.py,sha256=QEL6YIFY4sikORdmVkbkh4Fu2fO0k0nCQRTbB6lsYWU,873
|
| 86 |
+
ipykernel/parentpoller.py,sha256=KHD4b5JE9mtoppHIawWmmNSsWp9rFhhb-gu6TF3k7yo,5188
|
| 87 |
+
ipykernel/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 88 |
+
ipykernel/pylab/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 89 |
+
ipykernel/pylab/__pycache__/__init__.cpython-311.pyc,,
|
| 90 |
+
ipykernel/pylab/__pycache__/backend_inline.cpython-311.pyc,,
|
| 91 |
+
ipykernel/pylab/__pycache__/config.cpython-311.pyc,,
|
| 92 |
+
ipykernel/pylab/backend_inline.py,sha256=i1qDANhsIsp1NI3SNWyCwd-OFP-LZFAoK_6TfVL6Vuw,438
|
| 93 |
+
ipykernel/pylab/config.py,sha256=fDHNTl_WB5SleNSfC7qqv77x-Ayfp2EsmO9POW3k66k,355
|
| 94 |
+
ipykernel/resources/logo-32x32.png,sha256=4ytcKCBy1xeIe2DacxeP3TWmXcPK6sunoCblpCVcyZc,1084
|
| 95 |
+
ipykernel/resources/logo-64x64.png,sha256=XJBjtDbO3wVnSA_kh-zg0UeeqVRfMQy6k_oYTMurKQ0,2180
|
| 96 |
+
ipykernel/resources/logo-svg.svg,sha256=uuyGYqFGHCyswya1TScnyy8c4HugLQD1uCbQNRBPZJ8,9605
|
| 97 |
+
ipykernel/shellchannel.py,sha256=lWsfryMVU3xwadl3qSoQS-K6fG3LPfCd21-o5Dud-m8,1562
|
| 98 |
+
ipykernel/socket_pair.py,sha256=H_5sWfahoNQbXcOE_Zg2ZF5WlP7uTmBS3wiRh900mVs,1696
|
| 99 |
+
ipykernel/subshell.py,sha256=0tam9KwNmJvCzzfx7FsTs15N7zLwMHMMrtf3D93uZBo,1023
|
| 100 |
+
ipykernel/subshell_manager.py,sha256=oU1cv3HZPLoGfWAQj6jogF_ynL4rLyeKJrfID08jx7A,9160
|
| 101 |
+
ipykernel/thread.py,sha256=X3zj7OPOD4AU8bhdYJvdoKp-bAFc15rWIyf6vAEEXtU,785
|
| 102 |
+
ipykernel/trio_runner.py,sha256=BrzCyXutNe76CUt74yawcl5FF9dhNWGJaUewmTbt0wU,2477
|
| 103 |
+
ipykernel/utils.py,sha256=BmmzjSoNYZfhOMpFBLxC8vAxv-P88YSu6CIU_TDwkwA,2246
|
| 104 |
+
ipykernel/zmqshell.py,sha256=H_BgStHKT4ItKO8KtDdj-daRYAhdqdP_mLf_kBtPrHc,29304
|
| 105 |
+
ipykernel_launcher.py,sha256=-e63UZjDeYNngw3Mf-wx-5EyROM0GhuWOWD233pJhaA,512
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipykernel-7.2.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: hatchling 1.28.0
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/METADATA
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.4
|
| 2 |
+
Name: ipython
|
| 3 |
+
Version: 9.10.0
|
| 4 |
+
Summary: IPython: Productive Interactive Computing
|
| 5 |
+
Author: The IPython Development Team
|
| 6 |
+
Author-email: ipython-dev@python.org
|
| 7 |
+
License-Expression: BSD-3-Clause
|
| 8 |
+
Project-URL: Homepage, https://ipython.org
|
| 9 |
+
Project-URL: Documentation, https://ipython.readthedocs.io/
|
| 10 |
+
Project-URL: Funding, https://jupyter.org/about#donate
|
| 11 |
+
Project-URL: Source, https://github.com/ipython/ipython
|
| 12 |
+
Project-URL: Tracker, https://github.com/ipython/ipython/issues
|
| 13 |
+
Keywords: Interactive,Interpreter,Shell,Embedding
|
| 14 |
+
Platform: Linux
|
| 15 |
+
Platform: Mac OSX
|
| 16 |
+
Platform: Windows
|
| 17 |
+
Classifier: Framework :: IPython
|
| 18 |
+
Classifier: Framework :: Jupyter
|
| 19 |
+
Classifier: Intended Audience :: Developers
|
| 20 |
+
Classifier: Intended Audience :: Science/Research
|
| 21 |
+
Classifier: Programming Language :: Python
|
| 22 |
+
Classifier: Programming Language :: Python :: 3
|
| 23 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 24 |
+
Classifier: Topic :: System :: Shells
|
| 25 |
+
Requires-Python: >=3.11
|
| 26 |
+
Description-Content-Type: text/x-rst
|
| 27 |
+
License-File: LICENSE
|
| 28 |
+
License-File: COPYING.rst
|
| 29 |
+
Requires-Dist: colorama>=0.4.4; sys_platform == "win32"
|
| 30 |
+
Requires-Dist: decorator>=4.3.2
|
| 31 |
+
Requires-Dist: ipython-pygments-lexers>=1.0.0
|
| 32 |
+
Requires-Dist: jedi>=0.18.1
|
| 33 |
+
Requires-Dist: matplotlib-inline>=0.1.5
|
| 34 |
+
Requires-Dist: pexpect>4.3; sys_platform != "win32" and sys_platform != "emscripten"
|
| 35 |
+
Requires-Dist: prompt_toolkit<3.1.0,>=3.0.41
|
| 36 |
+
Requires-Dist: pygments>=2.11.0
|
| 37 |
+
Requires-Dist: stack_data>=0.6.0
|
| 38 |
+
Requires-Dist: traitlets>=5.13.0
|
| 39 |
+
Requires-Dist: typing_extensions>=4.6; python_version < "3.12"
|
| 40 |
+
Provides-Extra: black
|
| 41 |
+
Requires-Dist: black; extra == "black"
|
| 42 |
+
Provides-Extra: doc
|
| 43 |
+
Requires-Dist: docrepr; extra == "doc"
|
| 44 |
+
Requires-Dist: exceptiongroup; extra == "doc"
|
| 45 |
+
Requires-Dist: intersphinx_registry; extra == "doc"
|
| 46 |
+
Requires-Dist: ipykernel; extra == "doc"
|
| 47 |
+
Requires-Dist: ipython[matplotlib,test]; extra == "doc"
|
| 48 |
+
Requires-Dist: setuptools>=70.0; extra == "doc"
|
| 49 |
+
Requires-Dist: sphinx_toml==0.0.4; extra == "doc"
|
| 50 |
+
Requires-Dist: sphinx-rtd-theme>=0.1.8; extra == "doc"
|
| 51 |
+
Requires-Dist: sphinx>=8.0; extra == "doc"
|
| 52 |
+
Requires-Dist: typing_extensions; extra == "doc"
|
| 53 |
+
Provides-Extra: test
|
| 54 |
+
Requires-Dist: pytest>=7.0.0; extra == "test"
|
| 55 |
+
Requires-Dist: pytest-asyncio>=1.0.0; extra == "test"
|
| 56 |
+
Requires-Dist: testpath>=0.2; extra == "test"
|
| 57 |
+
Requires-Dist: packaging>=20.1.0; extra == "test"
|
| 58 |
+
Requires-Dist: setuptools>=61.2; extra == "test"
|
| 59 |
+
Provides-Extra: test-extra
|
| 60 |
+
Requires-Dist: ipython[test]; extra == "test-extra"
|
| 61 |
+
Requires-Dist: curio; extra == "test-extra"
|
| 62 |
+
Requires-Dist: jupyter_ai; extra == "test-extra"
|
| 63 |
+
Requires-Dist: ipython[matplotlib]; extra == "test-extra"
|
| 64 |
+
Requires-Dist: nbformat; extra == "test-extra"
|
| 65 |
+
Requires-Dist: nbclient; extra == "test-extra"
|
| 66 |
+
Requires-Dist: ipykernel>6.30; extra == "test-extra"
|
| 67 |
+
Requires-Dist: numpy>=1.27; extra == "test-extra"
|
| 68 |
+
Requires-Dist: pandas>2.1; extra == "test-extra"
|
| 69 |
+
Requires-Dist: trio>=0.1.0; extra == "test-extra"
|
| 70 |
+
Provides-Extra: matplotlib
|
| 71 |
+
Requires-Dist: matplotlib>3.9; extra == "matplotlib"
|
| 72 |
+
Provides-Extra: all
|
| 73 |
+
Requires-Dist: ipython[doc,matplotlib,terminal,test,test_extra]; extra == "all"
|
| 74 |
+
Requires-Dist: argcomplete>=3.0; extra == "all"
|
| 75 |
+
Dynamic: author
|
| 76 |
+
Dynamic: author-email
|
| 77 |
+
Dynamic: license-file
|
| 78 |
+
|
| 79 |
+
IPython provides a rich toolkit to help you make the most out of using Python
|
| 80 |
+
interactively. Its main components are:
|
| 81 |
+
|
| 82 |
+
* A powerful interactive Python shell
|
| 83 |
+
* A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter
|
| 84 |
+
notebooks and other interactive frontends.
|
| 85 |
+
|
| 86 |
+
The enhanced interactive Python shells have the following main features:
|
| 87 |
+
|
| 88 |
+
* Comprehensive object introspection.
|
| 89 |
+
|
| 90 |
+
* Input history, persistent across sessions.
|
| 91 |
+
|
| 92 |
+
* Caching of output results during a session with automatically generated
|
| 93 |
+
references.
|
| 94 |
+
|
| 95 |
+
* Extensible tab completion, with support by default for completion of python
|
| 96 |
+
variables and keywords, filenames and function keywords.
|
| 97 |
+
|
| 98 |
+
* Extensible system of 'magic' commands for controlling the environment and
|
| 99 |
+
performing many tasks related either to IPython or the operating system.
|
| 100 |
+
|
| 101 |
+
* A rich configuration system with easy switching between different setups
|
| 102 |
+
(simpler than changing $PYTHONSTARTUP environment variables every time).
|
| 103 |
+
|
| 104 |
+
* Session logging and reloading.
|
| 105 |
+
|
| 106 |
+
* Extensible syntax processing for special purpose situations.
|
| 107 |
+
|
| 108 |
+
* Access to the system shell with user-extensible alias system.
|
| 109 |
+
|
| 110 |
+
* Easily embeddable in other Python programs and GUIs.
|
| 111 |
+
|
| 112 |
+
* Integrated access to the pdb debugger and the Python profiler.
|
| 113 |
+
|
| 114 |
+
The latest development version is always available from IPython's `GitHub
|
| 115 |
+
site <http://github.com/ipython>`_.
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/RECORD
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 2 |
+
../../../bin/ipython3,sha256=iVqsgYM-0lh9JO08JVWN6ADEJUowgUw6nOFTa6UFBfw,208
|
| 3 |
+
../../../share/man/man1/ipython.1,sha256=PVdQP2hHmHyUEwzLOPcgavnCe9jTDVrM1jKZt4cnF_Q,2058
|
| 4 |
+
IPython/__init__.py,sha256=7dlVw4pigpyavG4T9nWRdkYQJCRK-y3YFRsMEAFjUh4,5704
|
| 5 |
+
IPython/__main__.py,sha256=55A5B-sd2ntWU36X9AEipKWnDvFM9JFSb4FOlC8hATA,489
|
| 6 |
+
IPython/__pycache__/__init__.cpython-311.pyc,,
|
| 7 |
+
IPython/__pycache__/__main__.cpython-311.pyc,,
|
| 8 |
+
IPython/__pycache__/display.cpython-311.pyc,,
|
| 9 |
+
IPython/__pycache__/paths.cpython-311.pyc,,
|
| 10 |
+
IPython/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 11 |
+
IPython/core/__pycache__/__init__.cpython-311.pyc,,
|
| 12 |
+
IPython/core/__pycache__/alias.cpython-311.pyc,,
|
| 13 |
+
IPython/core/__pycache__/application.cpython-311.pyc,,
|
| 14 |
+
IPython/core/__pycache__/async_helpers.cpython-311.pyc,,
|
| 15 |
+
IPython/core/__pycache__/autocall.cpython-311.pyc,,
|
| 16 |
+
IPython/core/__pycache__/builtin_trap.cpython-311.pyc,,
|
| 17 |
+
IPython/core/__pycache__/compilerop.cpython-311.pyc,,
|
| 18 |
+
IPython/core/__pycache__/completer.cpython-311.pyc,,
|
| 19 |
+
IPython/core/__pycache__/completerlib.cpython-311.pyc,,
|
| 20 |
+
IPython/core/__pycache__/crashhandler.cpython-311.pyc,,
|
| 21 |
+
IPython/core/__pycache__/debugger.cpython-311.pyc,,
|
| 22 |
+
IPython/core/__pycache__/debugger_backport.cpython-311.pyc,,
|
| 23 |
+
IPython/core/__pycache__/display.cpython-311.pyc,,
|
| 24 |
+
IPython/core/__pycache__/display_functions.cpython-311.pyc,,
|
| 25 |
+
IPython/core/__pycache__/display_trap.cpython-311.pyc,,
|
| 26 |
+
IPython/core/__pycache__/displayhook.cpython-311.pyc,,
|
| 27 |
+
IPython/core/__pycache__/displaypub.cpython-311.pyc,,
|
| 28 |
+
IPython/core/__pycache__/doctb.cpython-311.pyc,,
|
| 29 |
+
IPython/core/__pycache__/error.cpython-311.pyc,,
|
| 30 |
+
IPython/core/__pycache__/events.cpython-311.pyc,,
|
| 31 |
+
IPython/core/__pycache__/extensions.cpython-311.pyc,,
|
| 32 |
+
IPython/core/__pycache__/formatters.cpython-311.pyc,,
|
| 33 |
+
IPython/core/__pycache__/getipython.cpython-311.pyc,,
|
| 34 |
+
IPython/core/__pycache__/guarded_eval.cpython-311.pyc,,
|
| 35 |
+
IPython/core/__pycache__/history.cpython-311.pyc,,
|
| 36 |
+
IPython/core/__pycache__/historyapp.cpython-311.pyc,,
|
| 37 |
+
IPython/core/__pycache__/hooks.cpython-311.pyc,,
|
| 38 |
+
IPython/core/__pycache__/inputtransformer2.cpython-311.pyc,,
|
| 39 |
+
IPython/core/__pycache__/interactiveshell.cpython-311.pyc,,
|
| 40 |
+
IPython/core/__pycache__/latex_symbols.cpython-311.pyc,,
|
| 41 |
+
IPython/core/__pycache__/logger.cpython-311.pyc,,
|
| 42 |
+
IPython/core/__pycache__/macro.cpython-311.pyc,,
|
| 43 |
+
IPython/core/__pycache__/magic.cpython-311.pyc,,
|
| 44 |
+
IPython/core/__pycache__/magic_arguments.cpython-311.pyc,,
|
| 45 |
+
IPython/core/__pycache__/oinspect.cpython-311.pyc,,
|
| 46 |
+
IPython/core/__pycache__/page.cpython-311.pyc,,
|
| 47 |
+
IPython/core/__pycache__/payload.cpython-311.pyc,,
|
| 48 |
+
IPython/core/__pycache__/payloadpage.cpython-311.pyc,,
|
| 49 |
+
IPython/core/__pycache__/prefilter.cpython-311.pyc,,
|
| 50 |
+
IPython/core/__pycache__/profileapp.cpython-311.pyc,,
|
| 51 |
+
IPython/core/__pycache__/profiledir.cpython-311.pyc,,
|
| 52 |
+
IPython/core/__pycache__/pylabtools.cpython-311.pyc,,
|
| 53 |
+
IPython/core/__pycache__/release.cpython-311.pyc,,
|
| 54 |
+
IPython/core/__pycache__/shellapp.cpython-311.pyc,,
|
| 55 |
+
IPython/core/__pycache__/splitinput.cpython-311.pyc,,
|
| 56 |
+
IPython/core/__pycache__/tbtools.cpython-311.pyc,,
|
| 57 |
+
IPython/core/__pycache__/tips.cpython-311.pyc,,
|
| 58 |
+
IPython/core/__pycache__/ultratb.cpython-311.pyc,,
|
| 59 |
+
IPython/core/__pycache__/usage.cpython-311.pyc,,
|
| 60 |
+
IPython/core/alias.py,sha256=TOLqWTs2sWkEhUFKofaaazFD5aGP5X7lLD5TjU9pwdI,10234
|
| 61 |
+
IPython/core/application.py,sha256=OhW5Ye-aptd68yS-bSiv2bH4Kntvyq7MTf2jTu0i2xw,18940
|
| 62 |
+
IPython/core/async_helpers.py,sha256=fY0iEsQr3kBfpJja7p0rxsfP96vr8ovo0wTEQrG2iKg,4097
|
| 63 |
+
IPython/core/autocall.py,sha256=zw7siKc1ocagCuXn4OuT0o7YbyZSuW3a7la204ANRk4,1983
|
| 64 |
+
IPython/core/builtin_trap.py,sha256=4Bls1x1Xaf3oGbj6GFXE--G6qZlNq7AYFjp_vyu55p8,3006
|
| 65 |
+
IPython/core/compilerop.py,sha256=tA8xHh10gp85brI2OYmvl7kW0TgDghdKbzmZE7nS4sw,6990
|
| 66 |
+
IPython/core/completer.py,sha256=7bXi_Jef0yUY0MfeiEfmaK5edM_O2gf8vtAYDQ8IKX4,136724
|
| 67 |
+
IPython/core/completerlib.py,sha256=C_1uFwR4eiqIsemMRbluMQV1WJ3qSfnGxO01PsGSpr8,12641
|
| 68 |
+
IPython/core/crashhandler.py,sha256=8-kyI6aNkqbaB_lBlbNKAOFv34HDBCpLggMfiu4oIDg,8747
|
| 69 |
+
IPython/core/debugger.py,sha256=yegzQ3qvlABPbTiX_Gir0ips6Kpy83wIKbU9soTYVls,46635
|
| 70 |
+
IPython/core/debugger_backport.py,sha256=qP96tVbfH7wpOFIjhuFyFVVM1zIgCGbP1AyQzOBfw28,8216
|
| 71 |
+
IPython/core/display.py,sha256=wQgVFY_U1O-a-jJSLb00nJ9m2w9-NsBhEBGnQUcWUd0,41129
|
| 72 |
+
IPython/core/display_functions.py,sha256=sZ7izRUxZ4zBUDupwQguxFXUOtgA-AxVa9c-pDIglXI,12411
|
| 73 |
+
IPython/core/display_trap.py,sha256=r9AeMqllLicJvY8JfrGTQMkyxz37QT7X_RwwXxNk7R0,2185
|
| 74 |
+
IPython/core/displayhook.py,sha256=9bEWAUGTS9jxsFvCG91WyI7iI0hPhaPw_ee45FGMWBI,13266
|
| 75 |
+
IPython/core/displaypub.py,sha256=XMFrJRDAj0fewFUzYYXE7q_hBbIm7nfWGUYf5NBthRM,6859
|
| 76 |
+
IPython/core/doctb.py,sha256=Xq9V8r0_FR6LkQAfUGuOvuEmQf96DsYXpaXXunn5DP4,15644
|
| 77 |
+
IPython/core/error.py,sha256=lL5WP3E0sGNWkBTQL0u795wLQJCSrDCf328ft8TfCjk,1734
|
| 78 |
+
IPython/core/events.py,sha256=vL0VWet1wiyerXT69Yiq9Eh8KIpOtpKSXKWVyYdkg4s,5798
|
| 79 |
+
IPython/core/extensions.py,sha256=KgohNiowl71W-V0WYXWKw7g-q85QN9c_FxtraJoEOvY,5020
|
| 80 |
+
IPython/core/formatters.py,sha256=qKXTsGmpht8IEIXMm58AImzLC16e-UCKx1gtBf6bKPc,36507
|
| 81 |
+
IPython/core/getipython.py,sha256=RjTylt9N3c8AFZ-Y440A8My4tfFCgO-lVkyOL0xoOzQ,894
|
| 82 |
+
IPython/core/guarded_eval.py,sha256=hNY1e7mKp18BXBnfgnfVTfAWBDba3299_e4hN1y11DY,57501
|
| 83 |
+
IPython/core/history.py,sha256=myvJQJo5moMWW8bNgUCrTyRqg73TFqCOdYfvUzguaAg,42520
|
| 84 |
+
IPython/core/historyapp.py,sha256=5H38INsWXRacscKz_5PQHYrEnHEayDtc1D1qcSyHRBU,5847
|
| 85 |
+
IPython/core/hooks.py,sha256=xBWTZqycxZi97yj01IFc-SoJBzV5B73IoDHbAAlKUpQ,5193
|
| 86 |
+
IPython/core/inputtransformer2.py,sha256=7T9wEOBHZUit2JJd7H8KtRm-FK5NkgobdEEjpb6WfiY,32472
|
| 87 |
+
IPython/core/interactiveshell.py,sha256=A-ixWSFT8vfx9aaFFL2XSgW5M_NK3DnGvS392gY3-jI,159683
|
| 88 |
+
IPython/core/latex_symbols.py,sha256=DzFecvqWVSsdN7vWAsp0mlYAHRDQKfZGAmvuDUh0M-s,30127
|
| 89 |
+
IPython/core/logger.py,sha256=Iwe4xKMmxEdvSwHYPMfsTWkmdaqVCgvZT3R3I3qTmrU,8436
|
| 90 |
+
IPython/core/macro.py,sha256=OhvXWNhLe393rI2wTpMgbUVHWSnmC_ycHiYqzqSHXZU,1726
|
| 91 |
+
IPython/core/magic.py,sha256=it59u0imRkbY57rty8MMw1QW__InPPnLPhcQkKUihXM,29162
|
| 92 |
+
IPython/core/magic_arguments.py,sha256=d27MepJqF1XME27x_OlyPD-Lf3Qfx6_nx3Yx4_jbwpc,9841
|
| 93 |
+
IPython/core/magics/__init__.py,sha256=pkd-UfzjDGp5UHuFKjw192vZnigpTP9ftXzG3oLdiS8,1619
|
| 94 |
+
IPython/core/magics/__pycache__/__init__.cpython-311.pyc,,
|
| 95 |
+
IPython/core/magics/__pycache__/ast_mod.cpython-311.pyc,,
|
| 96 |
+
IPython/core/magics/__pycache__/auto.cpython-311.pyc,,
|
| 97 |
+
IPython/core/magics/__pycache__/basic.cpython-311.pyc,,
|
| 98 |
+
IPython/core/magics/__pycache__/code.cpython-311.pyc,,
|
| 99 |
+
IPython/core/magics/__pycache__/config.cpython-311.pyc,,
|
| 100 |
+
IPython/core/magics/__pycache__/display.cpython-311.pyc,,
|
| 101 |
+
IPython/core/magics/__pycache__/execution.cpython-311.pyc,,
|
| 102 |
+
IPython/core/magics/__pycache__/extension.cpython-311.pyc,,
|
| 103 |
+
IPython/core/magics/__pycache__/history.cpython-311.pyc,,
|
| 104 |
+
IPython/core/magics/__pycache__/logging.cpython-311.pyc,,
|
| 105 |
+
IPython/core/magics/__pycache__/namespace.cpython-311.pyc,,
|
| 106 |
+
IPython/core/magics/__pycache__/osm.cpython-311.pyc,,
|
| 107 |
+
IPython/core/magics/__pycache__/packaging.cpython-311.pyc,,
|
| 108 |
+
IPython/core/magics/__pycache__/pylab.cpython-311.pyc,,
|
| 109 |
+
IPython/core/magics/__pycache__/script.cpython-311.pyc,,
|
| 110 |
+
IPython/core/magics/ast_mod.py,sha256=06OoRO7Z7Jzfc-cflf8Z3wyqF17fkYv6fJ_Nw4d7eQE,10295
|
| 111 |
+
IPython/core/magics/auto.py,sha256=yEouIjsQ6LmfSEfNvkZbNmNDFl19KLRnaJciYdR7a1A,4816
|
| 112 |
+
IPython/core/magics/basic.py,sha256=SiF362-eSrSchnPpbfzeM-lw3ejhr96IjCF_0n2W0K4,26528
|
| 113 |
+
IPython/core/magics/code.py,sha256=h_dho9niPvtf_IpoOZf5GAD6CYbT0EQGsfLfutyX-7I,28144
|
| 114 |
+
IPython/core/magics/config.py,sha256=QBL5uY7m-Q7C46mO3q1Yio9s73w1TnI9y__j5E-j44Y,4881
|
| 115 |
+
IPython/core/magics/display.py,sha256=STRq66GlZwcvFyBxbkqslclpP_s9LnqD0ew9Z3S4-Jo,3130
|
| 116 |
+
IPython/core/magics/execution.py,sha256=klGMvWYHCyZD_zzoD2WhHoviRteAZ-j7zTb2czVqSew,63587
|
| 117 |
+
IPython/core/magics/extension.py,sha256=Jj6OlkM71PS0j1HfEMDc-jU2Exwo9Ff_K0nD7e_W4N0,2477
|
| 118 |
+
IPython/core/magics/history.py,sha256=nf4WZxF2tD8--4AvALyEDKY4WMo_SFk1YqrTR-L54xQ,13293
|
| 119 |
+
IPython/core/magics/logging.py,sha256=VuDiF5QZrgzTT7Lr1NkkMCtUM1EHoGCw2pYlKsSQc4Q,6867
|
| 120 |
+
IPython/core/magics/namespace.py,sha256=Bo4sckKaXpcVFLIIGL3fZWiDRHDeMU1LGrHN4ZdvJNs,25293
|
| 121 |
+
IPython/core/magics/osm.py,sha256=mNlHBS8ZEMf687nDpLGYKj6aC-i_r7d9iUTFKw6WtY4,30695
|
| 122 |
+
IPython/core/magics/packaging.py,sha256=5m2pt1bkosMdiQxB46hDdD4KisfPJpNnebCqMnygodE,6030
|
| 123 |
+
IPython/core/magics/pylab.py,sha256=BBRczZ0khoZB5NPipgvVtOWYpdkLatB9mQFYzyg-vpg,6624
|
| 124 |
+
IPython/core/magics/script.py,sha256=WNvtYy4sHmO7hJet_rt9cu3iJmeVoXfQ18SMyttYrPE,13706
|
| 125 |
+
IPython/core/oinspect.py,sha256=_BPFTJ8RZ8LNwRx0rJkeIHOnLfBm4osW5rEtGvJFSow,40279
|
| 126 |
+
IPython/core/page.py,sha256=P8Dmo0MjUq71DEnIPM_kaSGZoKTaPkrk4sUuM4I6HDA,11788
|
| 127 |
+
IPython/core/payload.py,sha256=uHcwG5Ahm3fnz2dsIKbzYK_lHOilqfen0IhQffOUQbE,1763
|
| 128 |
+
IPython/core/payloadpage.py,sha256=xGz4Ov82-0lmhKSIlM-kyIa50COk-ojB7tXLkGIRnPw,1177
|
| 129 |
+
IPython/core/prefilter.py,sha256=Jy0SFtkbEe_-I9Xr4xJFpraP-Fq8FIBT9fmE0t6xhQI,25779
|
| 130 |
+
IPython/core/profile/README_STARTUP,sha256=Y47GtYQkWy6pdzkqylUNL6eBSZMUIRGwTxXPUF_BBBc,371
|
| 131 |
+
IPython/core/profileapp.py,sha256=bFMFIyehxeF9pDUtxw_6D3b0nxeqsupKTe7XhH7GMkc,10711
|
| 132 |
+
IPython/core/profiledir.py,sha256=-vjOa1I_UajMZJblJRYXh16Y0RaAUn5a2swQBsw2qEU,8459
|
| 133 |
+
IPython/core/pylabtools.py,sha256=r72NQIhZAW9RL1w9WWAWAMbYoYC8KfaGNKB9JBbMg74,17296
|
| 134 |
+
IPython/core/release.py,sha256=DjyQ_JvxtVFoxIrgEuzfmoylgvQ9ZKhriFDSn5EFczY,1506
|
| 135 |
+
IPython/core/shellapp.py,sha256=fm8bGf2r2uML2gXgOawAQTGYzdDeKl7ExklOZlWBM6Y,19501
|
| 136 |
+
IPython/core/splitinput.py,sha256=6XePqBpZjqRE6U6Prm4WSzlfcGhykas0QDJa-Wmho_A,4998
|
| 137 |
+
IPython/core/tbtools.py,sha256=2QwAkGcdij1Y0rheIumF-fqpI3UvqhaIR2CbTOAFYlA,16907
|
| 138 |
+
IPython/core/tips.py,sha256=J0ntm05gvQdn0Bd05DYSKGAZXFsCtEnKAXA5gRMHXiY,6453
|
| 139 |
+
IPython/core/ultratb.py,sha256=cstx3_zHRyYRtup37ar77YDcgsF0eDfyDSW72Uu8EHg,46677
|
| 140 |
+
IPython/core/usage.py,sha256=agrZE5eZIvJnXoqI8VV9e-oWZx5LbLxUq9MdQpEyts4,13542
|
| 141 |
+
IPython/display.py,sha256=PZ3-IJ1pPXGlTlpJh0Y_B0nhZFWWA4LMOEEe9sSqxx8,1392
|
| 142 |
+
IPython/extensions/__init__.py,sha256=V4vSllFd18CVUvDTbXLYqfwTFmPXUiQZGCs5LX2IliE,78
|
| 143 |
+
IPython/extensions/__pycache__/__init__.cpython-311.pyc,,
|
| 144 |
+
IPython/extensions/__pycache__/autoreload.cpython-311.pyc,,
|
| 145 |
+
IPython/extensions/__pycache__/storemagic.cpython-311.pyc,,
|
| 146 |
+
IPython/extensions/autoreload.py,sha256=KxmsHGayzY2NcR10DyMlkguEV_xiJHfX_l6Wv-cdu4w,31950
|
| 147 |
+
IPython/extensions/deduperreload/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 148 |
+
IPython/extensions/deduperreload/__pycache__/__init__.cpython-311.pyc,,
|
| 149 |
+
IPython/extensions/deduperreload/__pycache__/deduperreload.cpython-311.pyc,,
|
| 150 |
+
IPython/extensions/deduperreload/__pycache__/deduperreload_patching.cpython-311.pyc,,
|
| 151 |
+
IPython/extensions/deduperreload/deduperreload.py,sha256=zspWZ6Jjgv0lr7THnUgQqrgFpeBRouY86VGB29UbW9g,25985
|
| 152 |
+
IPython/extensions/deduperreload/deduperreload_patching.py,sha256=MReG-xk9X3Rvk1xJlmwaCnYja6JemlUBNwXd-abdTG8,4985
|
| 153 |
+
IPython/extensions/storemagic.py,sha256=ths8PLtGmYZAYaibRuS1QetLm1Xu1soyGwehBjayByg,8168
|
| 154 |
+
IPython/external/__init__.py,sha256=-EQHbuUnBe1RS1_CwaLGzNSZQsCJsrxHW_r15smvVW0,126
|
| 155 |
+
IPython/external/__pycache__/__init__.cpython-311.pyc,,
|
| 156 |
+
IPython/external/__pycache__/pickleshare.cpython-311.pyc,,
|
| 157 |
+
IPython/external/__pycache__/qt_for_kernel.cpython-311.pyc,,
|
| 158 |
+
IPython/external/__pycache__/qt_loaders.cpython-311.pyc,,
|
| 159 |
+
IPython/external/pickleshare.py,sha256=TxTMuKsRBTJg3rhyC-z4gTRcf4fF5EtTFbCtlA3BdG8,8827
|
| 160 |
+
IPython/external/qt_for_kernel.py,sha256=ROLfN-NcA_h-ZgZsm9pBW1y57I_gxnJmOdpRwvpw8DA,3442
|
| 161 |
+
IPython/external/qt_loaders.py,sha256=3ynYvEE-juM83XRq7-6tf-nuHswKmSn7vR7hEbpk-pY,11863
|
| 162 |
+
IPython/lib/__init__.py,sha256=Cj-42grGOsG6Gz976stackKz9-ISoFK1QSYAmConqFQ,411
|
| 163 |
+
IPython/lib/__pycache__/__init__.cpython-311.pyc,,
|
| 164 |
+
IPython/lib/__pycache__/backgroundjobs.cpython-311.pyc,,
|
| 165 |
+
IPython/lib/__pycache__/clipboard.cpython-311.pyc,,
|
| 166 |
+
IPython/lib/__pycache__/deepreload.cpython-311.pyc,,
|
| 167 |
+
IPython/lib/__pycache__/demo.cpython-311.pyc,,
|
| 168 |
+
IPython/lib/__pycache__/display.cpython-311.pyc,,
|
| 169 |
+
IPython/lib/__pycache__/editorhooks.cpython-311.pyc,,
|
| 170 |
+
IPython/lib/__pycache__/guisupport.cpython-311.pyc,,
|
| 171 |
+
IPython/lib/__pycache__/latextools.cpython-311.pyc,,
|
| 172 |
+
IPython/lib/__pycache__/lexers.cpython-311.pyc,,
|
| 173 |
+
IPython/lib/__pycache__/pretty.cpython-311.pyc,,
|
| 174 |
+
IPython/lib/backgroundjobs.py,sha256=zZ-4E2PPPi8jNl-JWl9ObkWpG8Dzb5xxFtD1Jttmab8,17680
|
| 175 |
+
IPython/lib/clipboard.py,sha256=Ulrpzp9Wy7XXOes7QNOps6O3ss2_8recXuYF49vIj4s,3051
|
| 176 |
+
IPython/lib/deepreload.py,sha256=iymTEcJpP_hpcO1H5GRgb2aODGUtiUFksodoIe9738E,9431
|
| 177 |
+
IPython/lib/demo.py,sha256=PZoAgVYvWOqOJ4lFzJl5a14xnyMszPdFRwIRIkuM_bo,24502
|
| 178 |
+
IPython/lib/display.py,sha256=XZiwHjguoDzMMHQtgrPcryr5-pXPZqHa8AT0LRi6FiA,24577
|
| 179 |
+
IPython/lib/editorhooks.py,sha256=KmQaAEZawUhHqy9CvRkbmc8BNXx4b1pqqLFhTEBf1CY,3982
|
| 180 |
+
IPython/lib/guisupport.py,sha256=e3gQE2-rYF2Mj9EFqSYOKOjMDmys8o-yae7SEjiOeEs,6300
|
| 181 |
+
IPython/lib/latextools.py,sha256=wzwckGrWf84U5pcmu2jn8ZzBl126aDBi5SySwe4Z8eI,8122
|
| 182 |
+
IPython/lib/lexers.py,sha256=mt5QnEBuZaDXdL3Qwh9ZGHomjKgxNKW1IT4lM_78Rag,865
|
| 183 |
+
IPython/lib/pretty.py,sha256=uPqW4LMyq96W75UXa_s-o3wJH_bwXsAz8wDfqcIRjv0,30962
|
| 184 |
+
IPython/paths.py,sha256=QOPstpt2CVCrDUTn5a-Q1kcGBAwDLbq9omqc-2aoLU4,4126
|
| 185 |
+
IPython/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 186 |
+
IPython/sphinxext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 187 |
+
IPython/sphinxext/__pycache__/__init__.cpython-311.pyc,,
|
| 188 |
+
IPython/sphinxext/__pycache__/custom_doctests.cpython-311.pyc,,
|
| 189 |
+
IPython/sphinxext/__pycache__/ipython_console_highlighting.cpython-311.pyc,,
|
| 190 |
+
IPython/sphinxext/__pycache__/ipython_directive.cpython-311.pyc,,
|
| 191 |
+
IPython/sphinxext/custom_doctests.py,sha256=e6nLB1dsLrmYEwsKuJab6epdOfZg-rXTqmYIrg8aSBI,4610
|
| 192 |
+
IPython/sphinxext/ipython_console_highlighting.py,sha256=VzlykN7guz3dQV9nFuZM_x2M98yDZP3eyLhDp5fJ3wI,895
|
| 193 |
+
IPython/sphinxext/ipython_directive.py,sha256=hOQCdWx2N7WzBJVHMw7qVvAwLJxBZJxFCElqR4uXvqY,45154
|
| 194 |
+
IPython/terminal/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 195 |
+
IPython/terminal/__pycache__/__init__.cpython-311.pyc,,
|
| 196 |
+
IPython/terminal/__pycache__/debugger.cpython-311.pyc,,
|
| 197 |
+
IPython/terminal/__pycache__/embed.cpython-311.pyc,,
|
| 198 |
+
IPython/terminal/__pycache__/interactiveshell.cpython-311.pyc,,
|
| 199 |
+
IPython/terminal/__pycache__/ipapp.cpython-311.pyc,,
|
| 200 |
+
IPython/terminal/__pycache__/magics.cpython-311.pyc,,
|
| 201 |
+
IPython/terminal/__pycache__/prompts.cpython-311.pyc,,
|
| 202 |
+
IPython/terminal/__pycache__/ptutils.cpython-311.pyc,,
|
| 203 |
+
IPython/terminal/debugger.py,sha256=0LdBmCKVHKNGpmBKdb4bBgKlyuTVyfz2Dg2Y8wE4FTM,6937
|
| 204 |
+
IPython/terminal/embed.py,sha256=uR1Z7wp5z5SpYto7sa9A63sPDtX5h0XD048Y3gDE_V0,16164
|
| 205 |
+
IPython/terminal/interactiveshell.py,sha256=5pZqfjqeResaN7NIy0pzg_CYhaGROiQIMCygJYdERf0,40099
|
| 206 |
+
IPython/terminal/ipapp.py,sha256=d2Rog4DRkVv0_fReqZOuorKMXAtEqsCskwPejtjj0Lg,12512
|
| 207 |
+
IPython/terminal/magics.py,sha256=49ZVJzbAUkG_EFpebxIBEqm3tEClvqefoeM6QnxGrrk,7705
|
| 208 |
+
IPython/terminal/prompts.py,sha256=AeOYKX8o9KrPLuZb0Bpu6BjwQhq1VjOsjx3m7hlB9sQ,4559
|
| 209 |
+
IPython/terminal/pt_inputhooks/__init__.py,sha256=xhhHg1NRIjOtMdmKRW819sbs58QJvOXqsfd6INMhmyk,3633
|
| 210 |
+
IPython/terminal/pt_inputhooks/__pycache__/__init__.cpython-311.pyc,,
|
| 211 |
+
IPython/terminal/pt_inputhooks/__pycache__/asyncio.cpython-311.pyc,,
|
| 212 |
+
IPython/terminal/pt_inputhooks/__pycache__/glut.cpython-311.pyc,,
|
| 213 |
+
IPython/terminal/pt_inputhooks/__pycache__/gtk.cpython-311.pyc,,
|
| 214 |
+
IPython/terminal/pt_inputhooks/__pycache__/gtk3.cpython-311.pyc,,
|
| 215 |
+
IPython/terminal/pt_inputhooks/__pycache__/gtk4.cpython-311.pyc,,
|
| 216 |
+
IPython/terminal/pt_inputhooks/__pycache__/osx.cpython-311.pyc,,
|
| 217 |
+
IPython/terminal/pt_inputhooks/__pycache__/pyglet.cpython-311.pyc,,
|
| 218 |
+
IPython/terminal/pt_inputhooks/__pycache__/qt.cpython-311.pyc,,
|
| 219 |
+
IPython/terminal/pt_inputhooks/__pycache__/tk.cpython-311.pyc,,
|
| 220 |
+
IPython/terminal/pt_inputhooks/__pycache__/wx.cpython-311.pyc,,
|
| 221 |
+
IPython/terminal/pt_inputhooks/asyncio.py,sha256=ffxVjt0RIsh0yYzcPDpSTrhWv5JDNRBTof0OlJgksFU,1271
|
| 222 |
+
IPython/terminal/pt_inputhooks/glut.py,sha256=CchyzpkfAqVytLzuKv_XWsU4rmAJXCgxBksACM2bk2s,4999
|
| 223 |
+
IPython/terminal/pt_inputhooks/gtk.py,sha256=qx0OTtDdinx39bD9Fbf6m0JZWBXmuoypr56yUITFtfE,2427
|
| 224 |
+
IPython/terminal/pt_inputhooks/gtk3.py,sha256=_MuZIjZuLsW2i4vvUjNQh9u4xIU8kcITyJpXNiH2Zu0,279
|
| 225 |
+
IPython/terminal/pt_inputhooks/gtk4.py,sha256=r_MxCT7a0nTHZtqyuZpPgCW2Cl7iuomC0PjgFteSL9c,557
|
| 226 |
+
IPython/terminal/pt_inputhooks/osx.py,sha256=TnndyR_SPbmWC_A--0ORB06rhH7IS2_7kjphfPcRqXo,4448
|
| 227 |
+
IPython/terminal/pt_inputhooks/pyglet.py,sha256=wDDQDgilvK9uzwGB3XyAqcf8LfKr-Lc_NMAzunZMu_Y,2371
|
| 228 |
+
IPython/terminal/pt_inputhooks/qt.py,sha256=ivVQu3UzzfGGeuowh6lNeVtuOJOL7g_VTKcgMG8JHpM,3479
|
| 229 |
+
IPython/terminal/pt_inputhooks/tk.py,sha256=FjejvtwbvpeBZLoBCci1RDo_jWD5qElMy7PP-atd8j4,3651
|
| 230 |
+
IPython/terminal/pt_inputhooks/wx.py,sha256=9yI52lDSZ3O_5Gww_3IeenEk_3PepLIME3Onh4X3kW0,7126
|
| 231 |
+
IPython/terminal/ptutils.py,sha256=6PWDVPuBzpMxLdl_jqK7QtdnYVoVIjUP4Vl1JpFZFoM,8067
|
| 232 |
+
IPython/terminal/shortcuts/__init__.py,sha256=ecxnkz3DiaYWpog-4QlDgBCc39ymKnVqRgtMnqKoleI,18636
|
| 233 |
+
IPython/terminal/shortcuts/__pycache__/__init__.cpython-311.pyc,,
|
| 234 |
+
IPython/terminal/shortcuts/__pycache__/auto_match.cpython-311.pyc,,
|
| 235 |
+
IPython/terminal/shortcuts/__pycache__/auto_suggest.cpython-311.pyc,,
|
| 236 |
+
IPython/terminal/shortcuts/__pycache__/filters.cpython-311.pyc,,
|
| 237 |
+
IPython/terminal/shortcuts/auto_match.py,sha256=9uT1fDb-c4Ew7TSIs_zET1jSxDlbfWGluxfW_pj39tk,3066
|
| 238 |
+
IPython/terminal/shortcuts/auto_suggest.py,sha256=3Rh_d_ODDbn7PYx-ps7cbewblsPhS7yQ5K5oYxINLOI,23830
|
| 239 |
+
IPython/terminal/shortcuts/filters.py,sha256=cFEYlh5snmuShUL6EILUUgFzxgAxmqcUjm3QkXpGuqo,11025
|
| 240 |
+
IPython/testing/__init__.py,sha256=9t97XO03Ez9GdZA5FWZYmfyHZt2c3AqQe2dj_0AiPJY,784
|
| 241 |
+
IPython/testing/__pycache__/__init__.cpython-311.pyc,,
|
| 242 |
+
IPython/testing/__pycache__/decorators.cpython-311.pyc,,
|
| 243 |
+
IPython/testing/__pycache__/globalipapp.cpython-311.pyc,,
|
| 244 |
+
IPython/testing/__pycache__/ipunittest.cpython-311.pyc,,
|
| 245 |
+
IPython/testing/__pycache__/skipdoctest.cpython-311.pyc,,
|
| 246 |
+
IPython/testing/__pycache__/tools.cpython-311.pyc,,
|
| 247 |
+
IPython/testing/decorators.py,sha256=AgfFt06solAN0fByXvHaRJvZu0aLvgdMLuL91wbm_bI,4429
|
| 248 |
+
IPython/testing/globalipapp.py,sha256=F-RD6xLFJ2R1jNPycA9zk116GfH8qTsgsYFECWCeDRY,3948
|
| 249 |
+
IPython/testing/ipunittest.py,sha256=KlZ_FnzDo15Lqq-yx8iLOGiFPcO4TSIs8sHdjZcjVxo,6756
|
| 250 |
+
IPython/testing/plugin/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 251 |
+
IPython/testing/plugin/__pycache__/__init__.cpython-311.pyc,,
|
| 252 |
+
IPython/testing/plugin/__pycache__/dtexample.cpython-311.pyc,,
|
| 253 |
+
IPython/testing/plugin/__pycache__/ipdoctest.cpython-311.pyc,,
|
| 254 |
+
IPython/testing/plugin/__pycache__/pytest_ipdoctest.cpython-311.pyc,,
|
| 255 |
+
IPython/testing/plugin/__pycache__/setup.cpython-311.pyc,,
|
| 256 |
+
IPython/testing/plugin/__pycache__/simple.cpython-311.pyc,,
|
| 257 |
+
IPython/testing/plugin/__pycache__/simplevars.cpython-311.pyc,,
|
| 258 |
+
IPython/testing/plugin/__pycache__/test_ipdoctest.cpython-311.pyc,,
|
| 259 |
+
IPython/testing/plugin/__pycache__/test_refs.cpython-311.pyc,,
|
| 260 |
+
IPython/testing/plugin/dtexample.py,sha256=yedUX2aIUpFLkeDyshT5fqaODJg0iQzU_zvGOSr4JLc,2921
|
| 261 |
+
IPython/testing/plugin/ipdoctest.py,sha256=vYQpSy0jhk9G7r3ocBjWr7CT2JEWIxKrH2KgH_Bmgao,11881
|
| 262 |
+
IPython/testing/plugin/pytest_ipdoctest.py,sha256=zgzYReZfv23jXyZwQEWVdoWljmWL6zanAHR8Fj3Ha8M,30074
|
| 263 |
+
IPython/testing/plugin/setup.py,sha256=945a09Zm2HWWvukd5IVZ4v5p1czQPJfVlr5_Idey2AA,539
|
| 264 |
+
IPython/testing/plugin/simple.py,sha256=F7e3Zj_Cc59xdkhCkW2xaocYGGG5T_GHDlRwdUk7-qo,727
|
| 265 |
+
IPython/testing/plugin/simplevars.py,sha256=YZnDvFqQuFcrgzkgmm-koVRJKDnHCf0278Y5S_tyI3g,24
|
| 266 |
+
IPython/testing/plugin/test_combo.txt,sha256=rrXjdOlRh9DltFu3GpuWuD0Hojtj4QQcEBOm52Z3-dE,923
|
| 267 |
+
IPython/testing/plugin/test_example.txt,sha256=CGM8aZIYHlePDdAnR1yX3MfDGu0OceZpUiI_Y4tZGaU,730
|
| 268 |
+
IPython/testing/plugin/test_exampleip.txt,sha256=5gLcj8iCk-WCOGz0ObpQpuZMhGwS1jUMyH3mouGxQJI,814
|
| 269 |
+
IPython/testing/plugin/test_ipdoctest.py,sha256=Lc3qQdZ3amXf9EKA7JlXf30b3BzP8RwdNS9-SMRe2P0,1907
|
| 270 |
+
IPython/testing/plugin/test_refs.py,sha256=y-Y2Q8niRIbaanbwpIzvEwwaHkJfAq10HYfb4bAXHBc,715
|
| 271 |
+
IPython/testing/skipdoctest.py,sha256=haSEhd8EJr2Y0EbXXxv3pGvK6AQ8Lb7SyqkX5O8EU6s,717
|
| 272 |
+
IPython/testing/tools.py,sha256=TlUbGAQoz_-hQVbZ8wTn_a-Pq7eDDv0umbXcEnHlr78,12936
|
| 273 |
+
IPython/utils/PyColorize.py,sha256=dU7RrYZSAvc3ukNLpj-U_DK45s0fZKOrWe5Ibg6_pvI,17417
|
| 274 |
+
IPython/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 275 |
+
IPython/utils/__pycache__/PyColorize.cpython-311.pyc,,
|
| 276 |
+
IPython/utils/__pycache__/__init__.cpython-311.pyc,,
|
| 277 |
+
IPython/utils/__pycache__/_process_cli.cpython-311.pyc,,
|
| 278 |
+
IPython/utils/__pycache__/_process_common.cpython-311.pyc,,
|
| 279 |
+
IPython/utils/__pycache__/_process_emscripten.cpython-311.pyc,,
|
| 280 |
+
IPython/utils/__pycache__/_process_posix.cpython-311.pyc,,
|
| 281 |
+
IPython/utils/__pycache__/_process_win32.cpython-311.pyc,,
|
| 282 |
+
IPython/utils/__pycache__/_process_win32_controller.cpython-311.pyc,,
|
| 283 |
+
IPython/utils/__pycache__/_sysinfo.cpython-311.pyc,,
|
| 284 |
+
IPython/utils/__pycache__/capture.cpython-311.pyc,,
|
| 285 |
+
IPython/utils/__pycache__/coloransi.cpython-311.pyc,,
|
| 286 |
+
IPython/utils/__pycache__/contexts.cpython-311.pyc,,
|
| 287 |
+
IPython/utils/__pycache__/data.cpython-311.pyc,,
|
| 288 |
+
IPython/utils/__pycache__/decorators.cpython-311.pyc,,
|
| 289 |
+
IPython/utils/__pycache__/dir2.cpython-311.pyc,,
|
| 290 |
+
IPython/utils/__pycache__/docs.cpython-311.pyc,,
|
| 291 |
+
IPython/utils/__pycache__/encoding.cpython-311.pyc,,
|
| 292 |
+
IPython/utils/__pycache__/eventful.cpython-311.pyc,,
|
| 293 |
+
IPython/utils/__pycache__/frame.cpython-311.pyc,,
|
| 294 |
+
IPython/utils/__pycache__/generics.cpython-311.pyc,,
|
| 295 |
+
IPython/utils/__pycache__/importstring.cpython-311.pyc,,
|
| 296 |
+
IPython/utils/__pycache__/io.cpython-311.pyc,,
|
| 297 |
+
IPython/utils/__pycache__/ipstruct.cpython-311.pyc,,
|
| 298 |
+
IPython/utils/__pycache__/jsonutil.cpython-311.pyc,,
|
| 299 |
+
IPython/utils/__pycache__/log.cpython-311.pyc,,
|
| 300 |
+
IPython/utils/__pycache__/module_paths.cpython-311.pyc,,
|
| 301 |
+
IPython/utils/__pycache__/openpy.cpython-311.pyc,,
|
| 302 |
+
IPython/utils/__pycache__/path.cpython-311.pyc,,
|
| 303 |
+
IPython/utils/__pycache__/process.cpython-311.pyc,,
|
| 304 |
+
IPython/utils/__pycache__/py3compat.cpython-311.pyc,,
|
| 305 |
+
IPython/utils/__pycache__/sentinel.cpython-311.pyc,,
|
| 306 |
+
IPython/utils/__pycache__/strdispatch.cpython-311.pyc,,
|
| 307 |
+
IPython/utils/__pycache__/sysinfo.cpython-311.pyc,,
|
| 308 |
+
IPython/utils/__pycache__/syspathcontext.cpython-311.pyc,,
|
| 309 |
+
IPython/utils/__pycache__/tempdir.cpython-311.pyc,,
|
| 310 |
+
IPython/utils/__pycache__/terminal.cpython-311.pyc,,
|
| 311 |
+
IPython/utils/__pycache__/text.cpython-311.pyc,,
|
| 312 |
+
IPython/utils/__pycache__/timing.cpython-311.pyc,,
|
| 313 |
+
IPython/utils/__pycache__/tokenutil.cpython-311.pyc,,
|
| 314 |
+
IPython/utils/__pycache__/wildcard.cpython-311.pyc,,
|
| 315 |
+
IPython/utils/_process_cli.py,sha256=tJWYMEgNYgeMx9v-n3YLbKW0tPbFtpczfDH28RC3n4A,2020
|
| 316 |
+
IPython/utils/_process_common.py,sha256=bz3P6MuadSG9OqCFd75gikSWPeqB7OIKiiVuyBLQXQM,7333
|
| 317 |
+
IPython/utils/_process_emscripten.py,sha256=lGLQb2IgmanNtb502KflfuKIhgOF119Ji3cwo4fnJYg,503
|
| 318 |
+
IPython/utils/_process_posix.py,sha256=aOEtguhS3vdWngBpws1XQURO8Ozqd5gRiCk9VLky6tA,7502
|
| 319 |
+
IPython/utils/_process_win32.py,sha256=Pcf6ZiqMbqDT79edzegE_AX3D367UtE8bbhT41no54A,6775
|
| 320 |
+
IPython/utils/_process_win32_controller.py,sha256=hi2eR7mLbl3TTMCVbgps85GppxdtYbhOYK_l13WvYaM,21343
|
| 321 |
+
IPython/utils/_sysinfo.py,sha256=sJVJ9XpZ6gg_Ebh6SOovmtVD-wnf0wYQBQtbJgnlG0Q,43
|
| 322 |
+
IPython/utils/capture.py,sha256=h5yL5Lxq8bgO1SFpoNDYjEi6mh1IW_2X9CE7vOsUxE4,5137
|
| 323 |
+
IPython/utils/coloransi.py,sha256=CML-SkzLa7oaIK1qypb3uwcfPXDeKHxZQiMJ0IWvUY0,293
|
| 324 |
+
IPython/utils/contexts.py,sha256=w5_uXc0WTU3KKV1kcCW9A0_Mz5mGRoeGWMq_P_eo-Dg,1610
|
| 325 |
+
IPython/utils/data.py,sha256=oyIkeaottVFYKkqaRYWvp6Di-iGOg1pWgCmgpq5WO0k,1672
|
| 326 |
+
IPython/utils/decorators.py,sha256=-m6ie8uS1HYcUOE1TbkM29YmLuywbsgv0pt54fySJws,2689
|
| 327 |
+
IPython/utils/dir2.py,sha256=wh_yb2_D9EvJ3PkrFGiDXuElAznUzv3gaSuV1Zrllv8,2231
|
| 328 |
+
IPython/utils/docs.py,sha256=QY8n0cFrTS6gePmT3Tppv9Tzgc3Pzlf33XuzAwiE_wE,86
|
| 329 |
+
IPython/utils/encoding.py,sha256=L_3GjDG83eM247PgAjYT0KNjsTEm-WRTXKFkcbg4pP8,3477
|
| 330 |
+
IPython/utils/eventful.py,sha256=idbcT7GyZ43hrX9e6cI2bz7kKr389yMBE9hos6amMzE,138
|
| 331 |
+
IPython/utils/frame.py,sha256=XPVbwf05vtvUA9Ast7oaOJibgtvyYEOc8rJQ5f1cQdo,3122
|
| 332 |
+
IPython/utils/generics.py,sha256=XEH8UKjqW002XaFZpWprelEOpDYz5R56jeVH-Ay1O28,807
|
| 333 |
+
IPython/utils/importstring.py,sha256=IAZLK8lGYYjkSsjmPm5t_bCAbI55xG4UKyJPzQHGOcM,1082
|
| 334 |
+
IPython/utils/io.py,sha256=rKaq1gtIEbvApkvV2IGJo9NAhijstTdQKjIGJvQJQ6Y,3928
|
| 335 |
+
IPython/utils/ipstruct.py,sha256=XPfl1b0rRjISwyG3P1e2kJLSFHawzcPY71UBoa5v7qo,11856
|
| 336 |
+
IPython/utils/jsonutil.py,sha256=2QsAXueCIbbmjyz37Im9yXU41XK_XGJ9aGA7NGilDIs,148
|
| 337 |
+
IPython/utils/log.py,sha256=3tYJLqZEa40zTX0tgKnpb-bvj4NhI64PijiRV6mnc78,123
|
| 338 |
+
IPython/utils/module_paths.py,sha256=1mUNj1y5ZSL_X4LXEU2EA9vcvzjboIQy72Ang0X4TOE,2517
|
| 339 |
+
IPython/utils/openpy.py,sha256=bLucY-ZKDkI-chE3CKfJ7O7eJYrfJhZwh0RNQZBTYPM,3396
|
| 340 |
+
IPython/utils/path.py,sha256=7xtVfsVCjvk-p-jpbqSLjOcacsOrXNSQxwlveHjfO_U,10902
|
| 341 |
+
IPython/utils/process.py,sha256=EZkyui1PQgpuDBPvGPxC5a-qWP90KbJYza5SOqr8ltw,1990
|
| 342 |
+
IPython/utils/py3compat.py,sha256=wD7nlJ3mC-wFZWQatFduHnFnE77zNTJUDjcN9i1GNJ0,1365
|
| 343 |
+
IPython/utils/sentinel.py,sha256=zoqkKAxVUvrlQ7xMAw02gaSTFdSUS0DBo6OGKZfZ1e0,454
|
| 344 |
+
IPython/utils/strdispatch.py,sha256=tNKeUZL1Di7WxxbJiHRc0EEoxhqHWOtakZQbD-NWuvg,1832
|
| 345 |
+
IPython/utils/sysinfo.py,sha256=rbNOtqDKYYYd4v8KK0oCcJikiMmrcoPsFAa--fTTaHE,3720
|
| 346 |
+
IPython/utils/syspathcontext.py,sha256=91ixPHBKlw0LkuWtkuJQhSGu8djkYP8mQNYEzaxQ43E,963
|
| 347 |
+
IPython/utils/tempdir.py,sha256=L3niStyEXLh07TS0mQEY-Nm4sEekBGmk_tlY1_cuSek,1852
|
| 348 |
+
IPython/utils/terminal.py,sha256=YBhc-mYFa6MVujEjjA0KKUaN5uRn9toT1iOYOOGOzfs,3259
|
| 349 |
+
IPython/utils/text.py,sha256=LWOVg-ZzW_oRlVT9GRBCyIDHN-lSgaZm79Eu4kcOQrk,19002
|
| 350 |
+
IPython/utils/timing.py,sha256=nND-ZUBkHWfYevvbRG-YfOSIFczz_epzMqWK5PH6nqA,4275
|
| 351 |
+
IPython/utils/tokenutil.py,sha256=wpIbZV95I7ykomUkXqXvohfJ8zstVNsaiOJjkiCXnXA,6579
|
| 352 |
+
IPython/utils/wildcard.py,sha256=6EEc3OEYp-IuSoidL6nwpaHg--GxnzbAJTmFiz77CNE,4612
|
| 353 |
+
ipython-9.10.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 354 |
+
ipython-9.10.0.dist-info/METADATA,sha256=Umka-hO7WyrGeO9B4-ueJTCaYssy_xfLjhPhqEq1RF8,4565
|
| 355 |
+
ipython-9.10.0.dist-info/RECORD,,
|
| 356 |
+
ipython-9.10.0.dist-info/WHEEL,sha256=e4ZgaE3gcPB5J9oItkKZMIKPCuBSalJmC3we5bi2OTE,91
|
| 357 |
+
ipython-9.10.0.dist-info/entry_points.txt,sha256=z5BEEohWgg0SHdgdeNABf4T3fu-lr9W6F_bWOQHLdVs,83
|
| 358 |
+
ipython-9.10.0.dist-info/licenses/COPYING.rst,sha256=NBr8vXKYh7cEb-e5j8T07f867Y048G7v2bMGcPBD3xc,1639
|
| 359 |
+
ipython-9.10.0.dist-info/licenses/LICENSE,sha256=4OOQdI7UQKuJPKHxNaiKkgqvVAnbuQpbQnx1xeUSaPs,1720
|
| 360 |
+
ipython-9.10.0.dist-info/top_level.txt,sha256=PKjvHtNCBZ9EHTmd2mwJ1J_k3j0F6D1lTFzIcJFFPEU,8
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (9.10.0)
|
| 3 |
+
Root-Is-Purelib: true
|
| 4 |
+
Tag: py3-none-any
|
| 5 |
+
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[console_scripts]
|
| 2 |
+
ipython = IPython:start_ipython
|
| 3 |
+
ipython3 = IPython:start_ipython
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython-9.10.0.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
IPython
|
data/conda_envs/evalclaw/lib/python3.11/site-packages/ipython_pygments_lexers-1.1.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|