Skip to content

Commit

Permalink
Define errors in errors.py (#2170)
Browse files Browse the repository at this point in the history
* Moved inference endpoint errors

* Moved safetensors errors

* Moved headers errors

* Moved http errors

* Moved validation errors

* Fix redefinition
  • Loading branch information
Y4suyuki committed Apr 8, 2024
1 parent 887f03d commit aaf23b4
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 41 deletions.
10 changes: 2 additions & 8 deletions src/huggingface_hub/_inference_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from enum import Enum
from typing import TYPE_CHECKING, Dict, Optional, Union

from huggingface_hub.errors import InferenceEndpointError, InferenceEndpointTimeoutError

from .inference._client import InferenceClient
from .inference._generated._async_client import AsyncInferenceClient
from .utils import logging, parse_datetime
Expand All @@ -16,14 +18,6 @@
logger = logging.get_logger(__name__)


class InferenceEndpointError(Exception):
"""Generic exception when dealing with Inference Endpoints."""


class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
"""Exception for timeouts while waiting for Inference Endpoint."""


class InferenceEndpointStatus(str, Enum):
PENDING = "pending"
INITIALIZING = "initializing"
Expand Down
51 changes: 51 additions & 0 deletions src/huggingface_hub/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,54 @@ class IncompleteGenerationError(TextGenerationError):

class UnknownError(TextGenerationError):
pass


# INFERENCE ENDPOINT ERRORS


class InferenceEndpointError(Exception):
"""Generic exception when dealing with Inference Endpoints."""


class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
"""Exception for timeouts while waiting for Inference Endpoint."""


# SAFETENSORS ERRORS


class SafetensorsParsingError(Exception):
"""Raised when failing to parse a safetensors file metadata.
This can be the case if the file is not a safetensors file or does not respect the specification.
"""


class NotASafetensorsRepoError(Exception):
"""Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
`model.safetensors.index.json` file.
"""


# HEADERS ERRORS


class LocalTokenNotFoundError(EnvironmentError):
"""Raised if local token is required but not found."""


# HTTP ERRORS


class OfflineModeIsEnabled(ConnectionError):
"""Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""


# VALIDATION ERRORS


class HFValidationError(ValueError):
"""Generic exception thrown by `huggingface_hub` validators.
Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
"""
14 changes: 9 additions & 5 deletions src/huggingface_hub/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@

# ruff: noqa: F401

from huggingface_hub.errors import (
HFValidationError,
LocalTokenNotFoundError,
NotASafetensorsRepoError,
OfflineModeIsEnabled,
SafetensorsParsingError,
)

from . import tqdm as _tqdm # _tqdm is the module
from ._cache_assets import cached_assets_path
from ._cache_manager import (
Expand Down Expand Up @@ -45,10 +53,9 @@
from ._experimental import experimental
from ._fixes import SoftTemporaryDirectory, WeakFileLock, yaml_dump
from ._git_credential import list_credential_helpers, set_git_credential, unset_git_credential
from ._headers import LocalTokenNotFoundError, build_hf_headers, get_token_to_send
from ._headers import build_hf_headers, get_token_to_send
from ._hf_folder import HfFolder
from ._http import (
OfflineModeIsEnabled,
configure_http_backend,
fix_hf_endpoint_in_url,
get_session,
Expand Down Expand Up @@ -97,9 +104,7 @@
is_torch_available,
)
from ._safetensors import (
NotASafetensorsRepoError,
SafetensorsFileMetadata,
SafetensorsParsingError,
SafetensorsRepoMetadata,
TensorInfo,
)
Expand All @@ -108,7 +113,6 @@
from ._token import get_token
from ._typing import is_jsonable
from ._validators import (
HFValidationError,
smoothly_deprecate_use_auth_token,
validate_hf_hub_args,
validate_repo_id,
Expand Down
6 changes: 2 additions & 4 deletions src/huggingface_hub/utils/_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

from typing import Dict, Optional, Union

from huggingface_hub.errors import LocalTokenNotFoundError

from .. import constants
from ._runtime import (
get_fastai_version,
Expand All @@ -33,10 +35,6 @@
from ._validators import validate_hf_hub_args


class LocalTokenNotFoundError(EnvironmentError):
"""Raised if local token is required but not found."""


@validate_hf_hub_args
def build_hf_headers(
*,
Expand Down
6 changes: 2 additions & 4 deletions src/huggingface_hub/utils/_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
from requests.adapters import HTTPAdapter
from requests.models import PreparedRequest

from huggingface_hub.errors import OfflineModeIsEnabled

from .. import constants
from . import logging
from ._typing import HTTP_METHOD_T
Expand All @@ -42,10 +44,6 @@
X_REQUEST_ID = "x-request-id"


class OfflineModeIsEnabled(ConnectionError):
"""Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""


class UniqueRequestIdAdapter(HTTPAdapter):
X_AMZN_TRACE_ID = "X-Amzn-Trace-Id"

Expand Down
13 changes: 0 additions & 13 deletions src/huggingface_hub/utils/_safetensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,6 @@
DTYPE_T = Literal["F64", "F32", "F16", "BF16", "I64", "I32", "I16", "I8", "U8", "BOOL"]


class SafetensorsParsingError(Exception):
"""Raised when failing to parse a safetensors file metadata.
This can be the case if the file is not a safetensors file or does not respect the specification.
"""


class NotASafetensorsRepoError(Exception):
"""Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
`model.safetensors.index.json` file.
"""


@dataclass
class TensorInfo:
"""Information about a tensor.
Expand Down
9 changes: 2 additions & 7 deletions src/huggingface_hub/utils/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
from itertools import chain
from typing import Any, Dict

from huggingface_hub.errors import HFValidationError

from ._typing import CallableT


Expand All @@ -37,13 +39,6 @@
)


class HFValidationError(ValueError):
"""Generic exception thrown by `huggingface_hub` validators.
Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
"""


def validate_hf_hub_args(fn: CallableT) -> CallableT:
"""Validate values received as argument for any public method of `huggingface_hub`.
Expand Down

0 comments on commit aaf23b4

Please sign in to comment.