o
    Zh%;                     @   s  d dl Z d dlmZ d dlmZmZ ddlmZ e jde j	dZ
G dd	 d	eZG d
d deZG dd deZG dd deZG dd deZG dd deZG dd deZG dd deeeZG dd deeZd$dedee ddfddZded ee d!ee defd"d#ZdS )%    N)Optional)	HTTPErrorResponse   )JSONDecodeErrora  
        # staging or production endpoint
        ^https://[^/]+
        (
            # on /api/repo_type/repo_id
            /api/(models|datasets|spaces)/(.+)
            |
            # or /repo_id/resolve/revision/...
            /(.+)/resolve/(.+)
        )
    )flagsc                   @      e Zd ZdZdS )FileMetadataErrorzError triggered when the metadata of a file on the Hub cannot be retrieved (missing ETag or commit_hash).

    Inherits from `OSError` for backward compatibility.
    N__name__
__module____qualname____doc__ r   r   T/var/www/html/lang_env/lib/python3.10/site-packages/huggingface_hub/utils/_errors.pyr	          r	   c                       sd   e Zd ZU dZdZee ed< dZee ed< ddedee	 f fddZ
d	ed
dfddZ  ZS )HfHubHTTPErrora  
    HTTPError to inherit from for any custom HTTP Error raised in HF Hub.

    Any HTTPError is converted at least into a `HfHubHTTPError`. If some information is
    sent back by the server, it will be added to the error message.

    Added details:
    - Request id from "X-Request-Id" header if exists.
    - Server error message from the header "X-Error-Message".
    - Server error message if we can found one in the response body.

    Example:
    ```py
        import requests
        from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError

        response = get_session().post(...)
        try:
            hf_raise_for_status(response)
        except HfHubHTTPError as e:
            print(str(e)) # formatted message
            e.request_id, e.server_message # details returned by server

            # Complete the error message with additional information once it's raised
            e.append_to_message("
`create_commit` expects the repository to exist.")
            raise
    ```
    N
request_idserver_messagemessageresponsec                    s  |d urs|j d| _z| }W n ty   i }Y nw |j d}|d}ddd |dg D }d}|d urB||d 7 }|d urZt|trPd|}||vrZ||d 7 }|d urh||vrh||d 7 }| }|dkrs|| _	t
 jt|| j| j	d	||d ur|jnd d
 d S )NzX-Request-IdX-Error-Messageerror
c                 s   s     | ]}d |v r|d  V  qdS )r   Nr   ).0r   r   r   r   	<genexpr>M   s    z*HfHubHTTPError.__init__.<locals>.<genexpr>errors )r   r   )r   request)headersgetr   jsonr   join
isinstanceliststripr   super__init___format_error_messager   )selfr   r   Zserver_dataZserver_message_from_headersZserver_message_from_bodyZ"server_multiple_messages_from_bodyZ_server_message	__class__r   r   r'   A   sF   





zHfHubHTTPError.__init__additional_messagereturnc                 C   s$   | j d | f| j dd  | _ dS )zFAppend additional information to the `HfHubHTTPError` initial message.r   r   N)args)r)   r,   r   r   r   append_to_messagem   s   $z HfHubHTTPError.append_to_messageN)r   r   r   r   r   r   str__annotations__r   r   r'   r/   __classcell__r   r   r*   r   r       s   
 ,r   c                   @   r   )RepositoryNotFoundErrora  
    Raised when trying to access a hf.co URL with an invalid repository name, or
    with a private repo name the user does not have access to.

    Example:

    ```py
    >>> from huggingface_hub import model_info
    >>> model_info("<non_existent_repository>")
    (...)
    huggingface_hub.utils._errors.RepositoryNotFoundError: 401 Client Error. (Request ID: PvMw_VjBMjVdMz53WKIzP)

    Repository Not Found for url: https://huggingface.co/api/models/%3Cnon_existent_repository%3E.
    Please make sure you specified the correct `repo_id` and `repo_type`.
    If the repo is private, make sure you are authenticated.
    Invalid username or password.
    ```
    Nr
   r   r   r   r   r4   r   r   r4   c                   @   r   )GatedRepoErrora  
    Raised when trying to access a gated repository for which the user is not on the
    authorized list.

    Note: derives from `RepositoryNotFoundError` to ensure backward compatibility.

    Example:

    ```py
    >>> from huggingface_hub import model_info
    >>> model_info("<gated_repository>")
    (...)
    huggingface_hub.utils._errors.GatedRepoError: 403 Client Error. (Request ID: ViT1Bf7O_026LGSQuVqfa)

    Cannot access gated repo for url https://huggingface.co/api/models/ardent-figment/gated-model.
    Access to model ardent-figment/gated-model is restricted and you are not in the authorized list.
    Visit https://huggingface.co/ardent-figment/gated-model to ask for access.
    ```
    Nr
   r   r   r   r   r5      r   r5   c                   @   r   )DisabledRepoErrora  
    Raised when trying to access a repository that has been disabled by its author.

    Example:

    ```py
    >>> from huggingface_hub import dataset_info
    >>> dataset_info("laion/laion-art")
    (...)
    huggingface_hub.utils._errors.DisabledRepoError: 403 Client Error. (Request ID: Root=1-659fc3fa-3031673e0f92c71a2260dbe2;bc6f4dfb-b30a-4862-af0a-5cfe827610d8)

    Cannot access repository for url https://huggingface.co/api/datasets/laion/laion-art.
    Access to this resource is disabled.
    ```
    Nr
   r   r   r   r   r6      r   r6   c                   @   r   )RevisionNotFoundErrora  
    Raised when trying to access a hf.co URL with a valid repository but an invalid
    revision.

    Example:

    ```py
    >>> from huggingface_hub import hf_hub_download
    >>> hf_hub_download('bert-base-cased', 'config.json', revision='<non-existent-revision>')
    (...)
    huggingface_hub.utils._errors.RevisionNotFoundError: 404 Client Error. (Request ID: Mwhe_c3Kt650GcdKEFomX)

    Revision Not Found for url: https://huggingface.co/bert-base-cased/resolve/%3Cnon-existent-revision%3E/config.json.
    ```
    Nr
   r   r   r   r   r7      r   r7   c                   @   r   )EntryNotFoundErrora  
    Raised when trying to access a hf.co URL with a valid repository and revision
    but an invalid filename.

    Example:

    ```py
    >>> from huggingface_hub import hf_hub_download
    >>> hf_hub_download('bert-base-cased', '<non-existent-file>')
    (...)
    huggingface_hub.utils._errors.EntryNotFoundError: 404 Client Error. (Request ID: 53pNl6M0MxsnG5Sw8JA6x)

    Entry Not Found for url: https://huggingface.co/bert-base-cased/resolve/main/%3Cnon-existent-file%3E.
    ```
    Nr
   r   r   r   r   r8      r   r8   c                       s&   e Zd ZdZdef fddZ  ZS )LocalEntryNotFoundErrora  
    Raised when trying to access a file or snapshot that is not on the disk when network is
    disabled or unavailable (connection issue). The entry may exist on the Hub.

    Note: `ValueError` type is to ensure backward compatibility.
    Note: `LocalEntryNotFoundError` derives from `HTTPError` because of `EntryNotFoundError`
          even when it is not a network issue.

    Example:

    ```py
    >>> from huggingface_hub import hf_hub_download
    >>> hf_hub_download('bert-base-cased', '<non-cached-file>',  local_files_only=True)
    (...)
    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.
    ```
    r   c                    s   t  j|d d d S )Nr   )r&   r'   )r)   r   r*   r   r   r'      s   z LocalEntryNotFoundError.__init__)r   r   r   r   r1   r'   r3   r   r   r*   r   r9      s    r9   c                   @   r   )BadRequestErroraQ  
    Raised by `hf_raise_for_status` when the server returns a HTTP 400 error.

    Example:

    ```py
    >>> resp = requests.post("hf.co/api/check", ...)
    >>> hf_raise_for_status(resp, endpoint_name="check")
    huggingface_hub.utils._errors.BadRequestError: Bad request for check endpoint: {details} (Request ID: XXX)
    ```
    Nr
   r   r   r   r   r;      r   r;   r   endpoint_namer-   c              
   C   s  z|    W dS  ty } z| jd}| jd}|dkr4| j dd d| j d }t|| ||dkrM| j dd d	| j d }t|| ||d
krf| j dd d| j d }t|| ||dkr| j dd d| j d d d }t	|| ||dks| jdkr| j
dur| j
jdurt| j
jdur| j dd d| j d d }t|| || jdkr|durd| dnd}t|| d|| jdkrd| j d| dd| j d d d }t|| d|tt|| d|d}~ww )a  
    Internal version of `response.raise_for_status()` that will refine a
    potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`.

    This helper is meant to be the unique method to raise_for_status when making a call
    to the Hugging Face Hub.

    Example:
    ```py
        import requests
        from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError

        response = get_session().post(...)
        try:
            hf_raise_for_status(response)
        except HfHubHTTPError as e:
            print(str(e)) # formatted message
            e.request_id, e.server_message # details returned by server

            # Complete the error message with additional information once it's raised
            e.append_to_message("
`create_commit` expects the repository to exist.")
            raise
    ```

    Args:
        response (`Response`):
            Response from the server.
        endpoint_name (`str`, *optional*):
            Name of the endpoint that has been called. If provided, the error message
            will be more complete.

    <Tip warning={true}>

    Raises when the request has failed:

        - [`~utils.RepositoryNotFoundError`]
            If the repository to download from cannot be found. This may be because it
            doesn't exist, because `repo_type` is not set correctly, or because the repo
            is `private` and you do not have access.
        - [`~utils.GatedRepoError`]
            If the repository exists but is gated and the user is not on the authorized
            list.
        - [`~utils.RevisionNotFoundError`]
            If the repository exists but the revision couldn't be find.
        - [`~utils.EntryNotFoundError`]
            If the repository exists but the entry (e.g. the requested file) couldn't be
            find.
        - [`~utils.BadRequestError`]
            If request failed with a HTTP 400 BadRequest error.
        - [`~utils.HfHubHTTPError`]
            If request failed for a reason not listed above.

    </Tip>
    zX-Error-Coder   ZRevisionNotFoundz Client Error.

zRevision Not Found for url: .ZEntryNotFoundzEntry Not Found for url: Z	GatedRepoz!Cannot access gated repo for url z$Access to this resource is disabled.z!Cannot access repository for url r   ZRepoNotFoundi  NzRepository Not Found for url: z
Please make sure you specified the correct `repo_id` and `repo_type`.
If you are trying to access a private or gated repo, make sure you are authenticated.i  z

Bad request for z
 endpoint:z

Bad request:r:   i  z Forbidden: z
Cannot access content at: z/
If you are trying to create or update content,z1make sure you have a token with the `write` role.)raise_for_statusr   r   r    status_codeurlr7   r8   r5   r6   r   REPO_API_REGEXsearchr4   r;   r   r1   )r   r<   eZ
error_codeerror_messager   r   r   r   hf_raise_for_status   st   7





rF   r   r   r   c                 C   s   |dur#t |dkr#| |  vr#d| v r| d| 7 } n| d| 7 } |durTt| |  vrTd| d}d| v rP| d}| d| | | |d  } | S | |7 } | S )z
    Format the `HfHubHTTPError` error message based on initial message and information
    returned by the server.

    Used when initializing `HfHubHTTPError`.
    Nr   r=   r   z (Request ID: ))lenlowerr1   index)r   r   r   Zrequest_id_messageZnewline_indexr   r   r   r(   v  s   $
r(   r0   )retypingr   requestsr   r   Z_fixesr   compileVERBOSErB   OSErrorr	   r   r4   r5   r6   r7   r8   FileNotFoundError
ValueErrorr9   r;   r1   rF   r(   r   r   r   r   <module>   s&    R&~