codekingpro/portable-devtools
114k
1"""Contains all custom errors."""2 3from pathlib import Path4 5from httpx import HTTPError, Response6 7 8# CACHE ERRORS9 10 11class CacheNotFound(Exception):12 """Exception thrown when the Huggingface cache is not found."""13 14 cache_dir: str | Path15 16 def __init__(self, msg: str, cache_dir: str | Path, *args, **kwargs):17 super().__init__(msg, *args, **kwargs)18 self.cache_dir = cache_dir19 20 21class CorruptedCacheException(Exception):22 """Exception for any unexpected structure in the Huggingface cache-system."""23 24 25# HEADERS ERRORS26 27 28class LocalTokenNotFoundError(EnvironmentError):29 """Raised if local token is required but not found."""30 31 32# HTTP ERRORS33 34 35class OfflineModeIsEnabled(ConnectionError):36 """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""37 38 39class HfHubHTTPError(HTTPError, OSError):40 """41 HTTPError to inherit from for any custom HTTP Error raised in HF Hub.42 43 Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is44 sent back by the server, it will be added to the error message.45 46 Added details:47 - Request ID sourced from headers in order of precedence: "X-Request-Id", "X-Amzn-Trace-Id", "X-Amz-Cf-Id".48 - Server error message from the header "X-Error-Message".49 - Server error message if we can found one in the response body.50 51 Example:52 ```py53 import httpx54 from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError55 56 response = get_session().post(...)57 try:58 hf_raise_for_status(response)59 except HfHubHTTPError as e:60 print(str(e)) # formatted message61 e.request_id, e.server_message # details returned by server62 63 # Complete the error message with additional information once it's raised64 e.append_to_message("\n`create_commit` expects the repository to exist.")65 raise66 ```67 """68 69 def __init__(70 self,71 message: str,72 *,73 response: Response,74 server_message: str | None = None,75 ):76 self.request_id = (77 response.headers.get("x-request-id")78 or response.headers.get("X-Amzn-Trace-Id")79 or response.headers.get("x-amz-cf-id")80 )81 self.server_message = server_message82 self.response = response83 self.request = response.request84 super().__init__(message)85 86 def append_to_message(self, additional_message: str) -> None:87 """Append additional information to the `HfHubHTTPError` initial message."""88 self.args = (self.args[0] + additional_message,) + self.args[1:]89 90 @classmethod91 def _reconstruct_hf_hub_http_error(92 cls, message: str, response: Response, server_message: str | None93 ) -> "HfHubHTTPError":94 return cls(message, response=response, server_message=server_message)95 96 def __reduce_ex__(self, protocol):97 """Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class"""98 return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message))99 100 101# INFERENCE CLIENT ERRORS102 103 104class InferenceTimeoutError(HTTPError, TimeoutError):105 """Error raised when a model is unavailable or the request times out."""106 107 108# INFERENCE ENDPOINT ERRORS109 110 111class InferenceEndpointError(Exception):112 """Generic exception when dealing with Inference Endpoints."""113 114 115class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):116 """Exception for timeouts while waiting for Inference Endpoint."""117 118 119# SAFETENSORS ERRORS120 121 122class SafetensorsParsingError(Exception):123 """Raised when failing to parse a safetensors file metadata.124 125 This can be the case if the file is not a safetensors file or does not respect the specification.126 """127 128 129class NotASafetensorsRepoError(Exception):130 """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a131 `model.safetensors.index.json` file.132 """133 134 135# TEXT GENERATION ERRORS136 137 138class TextGenerationError(HTTPError):139 """Generic error raised if text-generation went wrong."""140 141 142# Text Generation Inference Errors143class ValidationError(TextGenerationError):144 """Server-side validation error."""145 146 147class GenerationError(TextGenerationError):148 pass149 150 151class OverloadedError(TextGenerationError):152 pass153 154 155class IncompleteGenerationError(TextGenerationError):156 pass157 158 159class UnknownError(TextGenerationError):160 pass161 162 163# VALIDATION ERRORS164 165 166class HFValidationError(ValueError):167 """Generic exception thrown by `huggingface_hub` validators.168 169 Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).170 """171 172 173class HfUriError(ValueError):174 """Raised when an `hf://...` URI is malformed.175 176 See [`parse_hf_uri`] and the177 [HF URIs reference](https://huggingface.co/docs/huggingface_hub/main/en/package_reference/hf_uris)178 for the canonical syntax.179 180 Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).181 """182 183 def __init__(self, uri: str, msg: str):184 self.uri = uri185 self.msg = msg186 full_msg = f"Invalid HF URI '{uri}'. {msg}" if uri else f"Invalid HF URI. {msg}"187 super().__init__(full_msg)188 189 190# FILE METADATA ERRORS191 192 193class DryRunError(OSError):194 """Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo)."""195 196 197class FileMetadataError(OSError):198 """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).199 200 Inherits from `OSError` for backward compatibility.201 """202 203 204# BUCKET ERRORS205 206 207class BucketNotFoundError(HfHubHTTPError):208 """209 Raised when trying to access a bucket that does not exist.210 211 Attributes:212 bucket_id (`str` or `None`):213 The bucket id (namespace/name) that was not found, if it could be determined from the request URL.214 215 Example:216 217 ```py218 >>> from huggingface_hub import bucket_info219 >>> bucket_info("<non_existent_bucket>")220 (...)221 huggingface_hub.errors.BucketNotFoundError: 404 Client Error. (Request ID: XXX)222 223 Bucket Not Found for url: https://huggingface.co/api/buckets/namespace/name.224 Please make sure you specified the correct bucket id (namespace/name).225 If the bucket is private, make sure you are authenticated and your token has the required permissions.226 ```227 """228 229 bucket_id: str | None = None230 231 232# REPOSITORY ERRORS233 234 235class RepositoryNotFoundError(HfHubHTTPError):236 """237 Raised when trying to access a hf.co URL with an invalid repository name, or238 with a private repo name the user does not have access to.239 240 Attributes:241 repo_id (`str` or `None`):242 The repo id that was not found, if it could be determined from the request URL.243 repo_type (`str` or `None`):244 The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.245 246 Example:247 248 ```py249 >>> from huggingface_hub import model_info250 >>> model_info("<non_existent_repository>")251 (...)252 huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)253 254 Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.255 Please make sure you specified the correct `repo_id` and `repo_type`.256 If the repo is private, make sure you are authenticated and your token has the required permissions.257 Invalid username or password.258 ```259 """260 261 repo_id: str | None = None262 repo_type: str | None = None263 264 265class GatedRepoError(RepositoryNotFoundError):266 """267 Raised when trying to access a gated repository for which the user is not on the268 authorized list.269 270 Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.271 272 Example:273 274 ```py275 >>> from huggingface_hub import model_info276 >>> model_info("<gated_repository>")277 (...)278 huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)279 280 Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.281 Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.282 Visit https://huggingface.co/ardent-figment/gated-model to ask for access.283 ```284 """285 286 287class DisabledRepoError(HfHubHTTPError):288 """289 Raised when trying to access a repository that has been disabled by its author.290 291 Example:292 293 ```py294 >>> from huggingface_hub import dataset_info295 >>> dataset_info("laion/laion-art")296 (...)297 huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)298 299 Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.300 Access to this resource is disabled.301 ```302 """303 304 305# REVISION ERROR306 307 308class RevisionNotFoundError(HfHubHTTPError):309 """310 Raised when trying to access a hf.co URL with a valid repository but an invalid311 revision.312 313 Attributes:314 repo_id (`str` or `None`):315 The repo id, if it could be determined from the request URL.316 repo_type (`str` or `None`):317 The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.318 319 Example:320 321 ```py322 >>> from huggingface_hub import hf_hub_download323 >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')324 (...)325 huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)326 327 Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.328 ```329 """330 331 repo_id: str | None = None332 repo_type: str | None = None333 334 335# ENTRY ERRORS336class EntryNotFoundError(Exception):337 """338 Raised when entry not found, either locally or remotely.339 340 Example:341 342 ```py343 >>> from huggingface_hub import hf_hub_download344 >>> hf_hub_download('bert-base-cased', '<non-existent-file>')345 (...)346 huggingface_hub.errors.RemoteEntryNotFoundError (...)347 >>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True)348 (...)349 huggingface_hub.utils.errors.LocalEntryNotFoundError (...)350 ```351 """352 353 354class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError):355 """356 Raised when trying to access a hf.co URL with a valid repository and revision357 but an invalid filename.358 359 Attributes:360 repo_id (`str` or `None`):361 The repo id, if it could be determined from the request URL.362 repo_type (`str` or `None`):363 The repo type ("model", "dataset", or "space"), if it could be determined from the request URL.364 365 Example:366 367 ```py368 >>> from huggingface_hub import hf_hub_download369 >>> hf_hub_download('bert-base-cased', '<non-existent-file>')370 (...)371 huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)372 373 Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.374 ```375 """376 377 repo_id: str | None = None378 repo_type: str | None = None379 380 381class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError):382 """383 Raised when trying to access a file or snapshot that is not on the disk when network is384 disabled or unavailable (connection issue). The entry may exist on the Hub.385 386 Example:387 388 ```py389 >>> from huggingface_hub import hf_hub_download390 >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)391 (...)392 huggingface_hub.errors.LocalEntryNotFoundError: Cannot find the requested files in the disk cache and outgoing traffic has been disabled. To enable hf.co look-ups and downloads online, set 'local_files_only' to False.393 ```394 """395 396 def __init__(self, message: str):397 super().__init__(message)398 399 400# REQUEST ERROR401class BadRequestError(HfHubHTTPError, ValueError):402 """403 Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.404 405 Example:406 407 ```py408 >>> resp = httpx.post("hf.co/api/check", ...)409 >>> hf_raise_for_status(resp, endpoint_name="check")410 huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)411 ```412 """413 414 415# DDUF file format ERROR416 417 418class DDUFError(Exception):419 """Base exception for errors related to the DDUF format."""420 421 422class DDUFCorruptedFileError(DDUFError):423 """Exception thrown when the DDUF file is corrupted."""424 425 426class DDUFExportError(DDUFError):427 """Base exception for errors during DDUF export."""428 429 430class DDUFInvalidEntryNameError(DDUFExportError):431 """Exception thrown when the entry name is invalid."""432 433 434# STRICT DATACLASSES ERRORS435 436 437class StrictDataclassError(Exception):438 """Base exception for strict dataclasses."""439 440 441class StrictDataclassDefinitionError(StrictDataclassError):442 """Exception thrown when a strict dataclass is defined incorrectly."""443 444 445class StrictDataclassFieldValidationError(StrictDataclassError):446 """Exception thrown when a strict dataclass fails validation for a given field."""447 448 def __init__(self, field: str, cause: Exception):449 error_message = f"Validation error for field '{field}':"450 error_message += f"\n {cause.__class__.__name__}: {cause}"451 super().__init__(error_message)452 453 454class StrictDataclassClassValidationError(StrictDataclassError):455 """Exception thrown when a strict dataclass fails validation on a class validator."""456 457 def __init__(self, validator: str, cause: Exception):458 error_message = f"Class validation error for validator '{validator}':"459 error_message += f"\n {cause.__class__.__name__}: {cause}"460 super().__init__(error_message)461 462 463# XET ERRORS464 465 466class XetError(Exception):467 """Base exception for errors related to Xet Storage."""468 469 470class XetAuthorizationError(XetError):471 """Exception thrown when the user does not have the right authorization to use Xet Storage."""472 473 474class XetRefreshTokenError(XetError):475 """Exception thrown when the refresh token is invalid."""476 477 478class XetDownloadError(Exception):479 """Exception thrown when the download from Xet Storage fails."""480 481 482# CLI ERRORS483 484 485class CLIError(Exception):486 """CLI error with clean message (no traceback by default)."""487 488 489class ConfirmationError(CLIError):490 """Raised when a confirmation prompt is declined (non-interactive mode)."""491 492 493class CLIExtensionInstallError(CLIError):494 """Error during CLI extension installation."""495 