errors.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. """Contains all custom errors."""
  2. from pathlib import Path
  3. from typing import Optional, Union
  4. from httpx 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, OSError):
  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 httpx
  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__(
  45. self,
  46. message: str,
  47. *,
  48. response: Response,
  49. server_message: Optional[str] = None,
  50. ):
  51. self.request_id = response.headers.get("x-request-id") or response.headers.get("X-Amzn-Trace-Id")
  52. self.server_message = server_message
  53. self.response = response
  54. self.request = response.request
  55. super().__init__(message)
  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. @classmethod
  60. def _reconstruct_hf_hub_http_error(
  61. cls, message: str, response: Response, server_message: Optional[str]
  62. ) -> "HfHubHTTPError":
  63. return cls(message, response=response, server_message=server_message)
  64. def __reduce_ex__(self, protocol):
  65. """Fix pickling of Exception subclass with kwargs. We need to override __reduce_ex__ of the parent class"""
  66. return (self.__class__._reconstruct_hf_hub_http_error, (str(self), self.response, self.server_message))
  67. # INFERENCE CLIENT ERRORS
  68. class InferenceTimeoutError(HTTPError, TimeoutError):
  69. """Error raised when a model is unavailable or the request times out."""
  70. # INFERENCE ENDPOINT ERRORS
  71. class InferenceEndpointError(Exception):
  72. """Generic exception when dealing with Inference Endpoints."""
  73. class InferenceEndpointTimeoutError(InferenceEndpointError, TimeoutError):
  74. """Exception for timeouts while waiting for Inference Endpoint."""
  75. # SAFETENSORS ERRORS
  76. class SafetensorsParsingError(Exception):
  77. """Raised when failing to parse a safetensors file metadata.
  78. This can be the case if the file is not a safetensors file or does not respect the specification.
  79. """
  80. class NotASafetensorsRepoError(Exception):
  81. """Raised when a repo is not a Safetensors repo i.e. doesn't have either a `model.safetensors` or a
  82. `model.safetensors.index.json` file.
  83. """
  84. # TEXT GENERATION ERRORS
  85. class TextGenerationError(HTTPError):
  86. """Generic error raised if text-generation went wrong."""
  87. # Text Generation Inference Errors
  88. class ValidationError(TextGenerationError):
  89. """Server-side validation error."""
  90. class GenerationError(TextGenerationError):
  91. pass
  92. class OverloadedError(TextGenerationError):
  93. pass
  94. class IncompleteGenerationError(TextGenerationError):
  95. pass
  96. class UnknownError(TextGenerationError):
  97. pass
  98. # VALIDATION ERRORS
  99. class HFValidationError(ValueError):
  100. """Generic exception thrown by `huggingface_hub` validators.
  101. Inherits from [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError).
  102. """
  103. # FILE METADATA ERRORS
  104. class DryRunError(OSError):
  105. """Error triggered when a dry run is requested but cannot be performed (e.g. invalid repo)."""
  106. class FileMetadataError(OSError):
  107. """Error triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).
  108. Inherits from `OSError` for backward compatibility.
  109. """
  110. # REPOSITORY ERRORS
  111. class RepositoryNotFoundError(HfHubHTTPError):
  112. """
  113. Raised when trying to access a hf.co URL with an invalid repository name, or
  114. with a private repo name the user does not have access to.
  115. Example:
  116. ```py
  117. >>> from huggingface_hub import model_info
  118. >>> model_info("<non_existent_repository>")
  119. (...)
  120. huggingface_hub.errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)
  121. Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
  122. Please make sure you specified the correct `repo_id` and `repo_type`.
  123. If the repo is private, make sure you are authenticated.
  124. Invalid username or password.
  125. ```
  126. """
  127. class GatedRepoError(RepositoryNotFoundError):
  128. """
  129. Raised when trying to access a gated repository for which the user is not on the
  130. authorized list.
  131. Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.
  132. Example:
  133. ```py
  134. >>> from huggingface_hub import model_info
  135. >>> model_info("<gated_repository>")
  136. (...)
  137. huggingface_hub.errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)
  138. Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
  139. Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
  140. Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
  141. ```
  142. """
  143. class DisabledRepoError(HfHubHTTPError):
  144. """
  145. Raised when trying to access a repository that has been disabled by its author.
  146. Example:
  147. ```py
  148. >>> from huggingface_hub import dataset_info
  149. >>> dataset_info("laion/laion-art")
  150. (...)
  151. huggingface_hub.errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)
  152. Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
  153. Access to this resource is disabled.
  154. ```
  155. """
  156. # REVISION ERROR
  157. class RevisionNotFoundError(HfHubHTTPError):
  158. """
  159. Raised when trying to access a hf.co URL with a valid repository but an invalid
  160. revision.
  161. Example:
  162. ```py
  163. >>> from huggingface_hub import hf_hub_download
  164. >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
  165. (...)
  166. huggingface_hub.errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)
  167. Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
  168. ```
  169. """
  170. # ENTRY ERRORS
  171. class EntryNotFoundError(Exception):
  172. """
  173. Raised when entry not found, either locally or remotely.
  174. Example:
  175. ```py
  176. >>> from huggingface_hub import hf_hub_download
  177. >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
  178. (...)
  179. huggingface_hub.errors.RemoteEntryNotFoundError (...)
  180. >>> hf_hub_download('bert-base-cased', '<non-existent-file>', local_files_only=True)
  181. (...)
  182. huggingface_hub.utils.errors.LocalEntryNotFoundError (...)
  183. ```
  184. """
  185. class RemoteEntryNotFoundError(HfHubHTTPError, EntryNotFoundError):
  186. """
  187. Raised when trying to access a hf.co URL with a valid repository and revision
  188. but an invalid filename.
  189. Example:
  190. ```py
  191. >>> from huggingface_hub import hf_hub_download
  192. >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
  193. (...)
  194. huggingface_hub.errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)
  195. Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
  196. ```
  197. """
  198. class LocalEntryNotFoundError(FileNotFoundError, EntryNotFoundError):
  199. """
  200. Raised when trying to access a file or snapshot that is not on the disk when network is
  201. disabled or unavailable (connection issue). The entry may exist on the Hub.
  202. Example:
  203. ```py
  204. >>> from huggingface_hub import hf_hub_download
  205. >>> hf_hub_download('bert-base-cased', '<non-cached-file>', local_files_only=True)
  206. (...)
  207. 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.
  208. ```
  209. """
  210. def __init__(self, message: str):
  211. super().__init__(message)
  212. # REQUEST ERROR
  213. class BadRequestError(HfHubHTTPError, ValueError):
  214. """
  215. Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.
  216. Example:
  217. ```py
  218. >>> resp = httpx.post("hf.co/api/check", ...)
  219. >>> hf_raise_for_status(resp, endpoint_name="check")
  220. huggingface_hub.errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
  221. ```
  222. """
  223. # DDUF file format ERROR
  224. class DDUFError(Exception):
  225. """Base exception for errors related to the DDUF format."""
  226. class DDUFCorruptedFileError(DDUFError):
  227. """Exception thrown when the DDUF file is corrupted."""
  228. class DDUFExportError(DDUFError):
  229. """Base exception for errors during DDUF export."""
  230. class DDUFInvalidEntryNameError(DDUFExportError):
  231. """Exception thrown when the entry name is invalid."""
  232. # STRICT DATACLASSES ERRORS
  233. class StrictDataclassError(Exception):
  234. """Base exception for strict dataclasses."""
  235. class StrictDataclassDefinitionError(StrictDataclassError):
  236. """Exception thrown when a strict dataclass is defined incorrectly."""
  237. class StrictDataclassFieldValidationError(StrictDataclassError):
  238. """Exception thrown when a strict dataclass fails validation for a given field."""
  239. def __init__(self, field: str, cause: Exception):
  240. error_message = f"Validation error for field '{field}':"
  241. error_message += f"\n {cause.__class__.__name__}: {cause}"
  242. super().__init__(error_message)
  243. class StrictDataclassClassValidationError(StrictDataclassError):
  244. """Exception thrown when a strict dataclass fails validation on a class validator."""
  245. def __init__(self, validator: str, cause: Exception):
  246. error_message = f"Class validation error for validator '{validator}':"
  247. error_message += f"\n {cause.__class__.__name__}: {cause}"
  248. super().__init__(error_message)
  249. # XET ERRORS
  250. class XetError(Exception):
  251. """Base exception for errors related to Xet Storage."""
  252. class XetAuthorizationError(XetError):
  253. """Exception thrown when the user does not have the right authorization to use Xet Storage."""
  254. class XetRefreshTokenError(XetError):
  255. """Exception thrown when the refresh token is invalid."""
  256. class XetDownloadError(Exception):
  257. """Exception thrown when the download from Xet Storage fails."""