errors.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. """Contains all custom errors."""
  2. from pathlib import Path
  3. from typing import Optional, Union
  4. from requests import HTTPError, Response
  5. # CACHE ERRORS
  6. class CacheNotFound(Exception):
  7. """Exception thrown when the Huggingface cache is not found."""
  8. cache_dir: Union[str, Path]
  9. def __init__(self, msg: str, cache_dir: Union[str, Path], *args, **kwargs):
  10. super().__init__(msg, *args, **kwargs)
  11. self.cache_dir = cache_dir
  12. class CorruptedCacheException(Exception):
  13. """Exception for any unexpected structure in the Huggingface cache-system."""
  14. # HEADERS ERRORS
  15. class LocalTokenNotFoundError(EnvironmentError):
  16. """Raised if local token is required but not found."""
  17. # HTTP ERRORS
  18. class OfflineModeIsEnabled(ConnectionError):
  19. """Raised when a request is made but `HF_HUB_OFFLINE=1` is set as environment variable."""
  20. class HfHubHTTPError(HTTPError):
  21. """
  22. HTTPError to inherit from for any custom HTTP Error raised in HF Hub.
  23. Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
  24. sent back by the server, it will be added to the error message.
  25. Added details:
  26. - Request id from "X-Request-Id" header if exists. If not, fallback to "X-Amzn-Trace-Id" header if exists.
  27. - Server error message from the header "X-Error-Message".
  28. - Server error message if we can found one in the response body.
  29. Example:
  30. ```py
  31. import requests
  32. from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError
  33. response = get_session().post(...)
  34. try:
  35. hf_raise_for_status(response)
  36. except HfHubHTTPError as e:
  37. print(str(e)) # formatted message
  38. e.request_id, e.server_message # details returned by server
  39. # Complete the error message with additional information once it's raised
  40. e.append_to_message("\n`create_commit` expects the repository to exist.")
  41. raise
  42. ```
  43. """
  44. def __init__(self, message: str, response: Optional[Response] = None, *, server_message: Optional[str] = None):
  45. self.request_id = (
  46. response.headers.get("x-request-id") or response.headers.get("X-Amzn-Trace-Id")
  47. if response is not None
  48. else None
  49. )
  50. self.server_message = server_message
  51. super().__init__(
  52. message,
  53. response=response, # type: ignore [arg-type]
  54. request=response.request if response is not None else None, # type: ignore [arg-type]
  55. )
  56. def append_to_message(self, additional_message: str) -> None:
  57. """Append additional information to the `HfHubHTTPError` initial message."""
  58. self.args = (self.args[0] + additional_message,) + self.args[1:]
  59. # INFERENCE CLIENT ERRORS
  60. class InferenceTimeoutError(HTTPError, TimeoutError):
  61. """Error raised when a model is unavailable or the request times out."""
  62. # INFERENCE ENDPOINT ERRORS
  63. class InferenceEndpointError(Exception):
  64. """Generic exception when dealing with Inference Endpoints."""
  65. class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
  66. """Exception for timeouts while waiting for Inference Endpoint."""
  67. # SAFETENSORS ERRORS
  68. class SafetensorsParsingError(Exception):
  69. """Raised when failing to parse a safetensors file metadata.
  70. This can be the case if the file is not a safetensors file or does not respect the specification.
  71. """
  72. class NotASafetensorsRepoError(Exception):
  73. """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
  74. `model.safetensors.index.json` file.
  75. """
  76. # TEXT GENERATION ERRORS
  77. class TextGenerationError(HTTPError):
  78. """Generic error raised if text-generation went wrong."""
  79. # Text Generation Inference Errors
  80. class ValidationError(TextGenerationError):
  81. """Server-side validation error."""
  82. class GenerationError(TextGenerationError):
  83. pass
  84. class OverloadedError(TextGenerationError):
  85. pass
  86. class IncompleteGenerationError(TextGenerationError):
  87. pass
  88. class UnknownError(TextGenerationError):
  89. pass
  90. # VALIDATION ERRORS
  91. class HFValidationError(ValueError):
  92. """Generic exception thrown by `huggingface_hub` validators.
  93. Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
  94. """
  95. # FILE METADATA ERRORS
  96. class FileMetadataError(OSError):
  97. """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
  98. Inherits from `OSError` for backward compatibility.
  99. """
  100. # REPOSITORY ERRORS
  101. class RepositoryNotFoundError(HfHubHTTPError):
  102. """
  103. Raised when trying to access a hf.co URL with an invalid repository name, or
  104. with a private repo name the user does not have access to.
  105. Example:
  106. ```py
  107. >>> from huggingface_hub import model_info
  108. >>> model_info("<non_existent_repository>")
  109. (...)
  110. huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
  111. Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
  112. Please make sure you specified the correct `repo_id` and `repo_type`.
  113. If the repo is private, make sure you are authenticated.
  114. Invalid username or password.
  115. ```
  116. """
  117. class GatedRepoError(RepositoryNotFoundError):
  118. """
  119. Raised when trying to access a gated repository for which the user is not on the
  120. authorized list.
  121. Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
  122. Example:
  123. ```py
  124. >>> from huggingface_hub import model_info
  125. >>> model_info("<gated_repository>")
  126. (...)
  127. huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
  128. Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
  129. Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
  130. Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
  131. ```
  132. """
  133. class DisabledRepoError(HfHubHTTPError):
  134. """
  135. Raised when trying to access a repository that has been disabled by its author.
  136. Example:
  137. ```py
  138. >>> from huggingface_hub import dataset_info
  139. >>> dataset_info("laion/laion-art")
  140. (...)
  141. huggingface_hub.utils._errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
  142. Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
  143. Access to this resource is disabled.
  144. ```
  145. """
  146. # REVISION ERROR
  147. class RevisionNotFoundError(HfHubHTTPError):
  148. """
  149. Raised when trying to access a hf.co URL with a valid repository but an invalid
  150. revision.
  151. Example:
  152. ```py
  153. >>> from huggingface_hub import hf_hub_download
  154. >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
  155. (...)
  156. huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
  157. Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
  158. ```
  159. """
  160. # ENTRY ERRORS
  161. class EntryNotFoundError(HfHubHTTPError):
  162. """
  163. Raised when trying to access a hf.co URL with a valid repository and revision
  164. but an invalid filename.
  165. Example:
  166. ```py
  167. >>> from huggingface_hub import hf_hub_download
  168. >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
  169. (...)
  170. huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
  171. Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
  172. ```
  173. """
  174. class LocalEntryNotFoundError(EntryNotFoundError, FileNotFoundError, ValueError):
  175. """
  176. Raised when trying to access a file or snapshot that is not on the disk when network is
  177. disabled or unavailable (connection issue). The entry may exist on the Hub.
  178. Note: `ValueError` type is to ensure backward compatibility.
  179. Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError`
  180. even when it is not a network issue.
  181. Example:
  182. ```py
  183. >>> from huggingface_hub import hf_hub_download
  184. >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
  185. (...)
  186. huggingface_hub.utils._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.
  187. ```
  188. """
  189. def __init__(self, message: str):
  190. super().__init__(message, response=None)
  191. # REQUEST ERROR
  192. class BadRequestError(HfHubHTTPError, ValueError):
  193. """
  194. Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
  195. Example:
  196. ```py
  197. >>> resp = requests.post("hf.co/api/check", ...)
  198. >>> hf_raise_for_status(resp, endpoint_name="check")
  199. huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
  200. ```
  201. """
  202. # DDUF file format ERROR
  203. class DDUFError(Exception):
  204. """Base exception for errors related to the DDUF format."""
  205. class DDUFCorruptedFileError(DDUFError):
  206. """Exception thrown when the DDUF file is corrupted."""
  207. class DDUFExportError(DDUFError):
  208. """Base exception for errors during DDUF export."""
  209. class DDUFInvalidEntryNameError(DDUFExportError):
  210. """Exception thrown when the entry name is invalid."""
  211. # STRICT DATACLASSES ERRORS
  212. class StrictDataclassError(Exception):
  213. """Base exception for strict dataclasses."""
  214. class StrictDataclassDefinitionError(StrictDataclassError):
  215. """Exception thrown when a strict dataclass is defined incorrectly."""
  216. class StrictDataclassFieldValidationError(StrictDataclassError):
  217. """Exception thrown when a strict dataclass fails validation for a given field."""
  218. def __init__(self, field: str, cause: Exception):
  219. error_message = f"Validation error for field '{field}':"
  220. error_message += f"\n {cause.__class__.__name__}: {cause}"
  221. super().__init__(error_message)
  222. class StrictDataclassClassValidationError(StrictDataclassError):
  223. """Exception thrown when a strict dataclass fails validation on a class validator."""
  224. def __init__(self, validator: str, cause: Exception):
  225. error_message = f"Class validation error for validator '{validator}':"
  226. error_message += f"\n {cause.__class__.__name__}: {cause}"
  227. super().__init__(error_message)
  228. # XET ERRORS
  229. class XetError(Exception):
  230. """Base exception for errors related to Xet Storage."""
  231. class XetAuthorizationError(XetError):
  232. """Exception thrown when the user does not have the right authorization to use Xet Storage."""
  233. class XetRefreshTokenError(XetError):
  234. """Exception thrown when the refresh token is invalid."""
  235. class XetDownloadError(Exception):
  236. """Exception thrown when the download from Xet Storage fails."""