U
    ”Ê¹j�  ã                   @   sb  d dl mZ d dlmZ d dlmZmZ d dlZddlm	Z	 ddlm
Z
mZmZ G d	d
„ d
eeƒZedd�G dd„ dƒƒZedd�G dd„ dƒƒZd!ejee ee dœdd„Zeeef ee dœdd„Zeeeeef edœdd„ƒZeddddœeeeee eeef ee eeeef  edœdd„ƒZed"eeeef eeeef  edœdd „ƒZdS )#é    )Ú	dataclass)ÚEnum)ÚDictÚOptionalNé   )Ú	constantsé   )Úget_sessionÚhf_raise_for_statusÚvalidate_hf_hub_argsc                   @   s   e Zd ZdZdZdS )ÚXetTokenTypeÚreadÚwriteN)Ú__name__Ú
__module__Ú__qualname__ÚREADÚWRITE© r   r   úY/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/utils/_xet.pyr      s   r   T)Úfrozenc                   @   s   e Zd ZU eed< eed< dS )ÚXetFileDataÚ	file_hashÚrefresh_routeN)r   r   r   ÚstrÚ__annotations__r   r   r   r   r      s   
r   c                   @   s&   e Zd ZU eed< eed< eed< dS )ÚXetConnectionInfoÚaccess_tokenÚexpiration_unix_epochÚendpointN)r   r   r   r   r   Úintr   r   r   r   r      s   
r   )Úresponser   Úreturnc                 C   s¢   | dkrdS z:| j tj }tj| jkr8| jtj d }n| j tj }W n tk
r\   Y dS X |dk	rj|ntj}| tj	¡r–| 
tj	 d¡| d¡¡}t||d�S )aa  
    Parse XET file metadata from an HTTP response.

    This function extracts XET file metadata from the HTTP headers or HTTP links
    of a given response object. If the required metadata is not found, it returns `None`.

    Args:
        response (`requests.Response`):
            The HTTP response object containing headers dict and links dict to extract the XET metadata from.
    Returns:
        `Optional[XetFileData]`:
            An instance of `XetFileData` containing the file hash and refresh route if the metadata
            is found. Returns `None` if the required metadata is missing.
    NÚurlú/)r   r   )Úheadersr   ZHUGGINGFACE_HEADER_X_XET_HASHZ$HUGGINGFACE_HEADER_LINK_XET_AUTH_KEYÚlinksZ&HUGGINGFACE_HEADER_X_XET_REFRESH_ROUTEÚKeyErrorÚENDPOINTÚ
startswithZHUGGINGFACE_CO_URL_HOMEÚreplaceÚrstripr   )r!   r   r   r   r   r   r   Ú!parse_xet_file_data_from_response   s     þr,   )r%   r"   c              
   C   sR   z&| t j }| t j }t| t j ƒ}W n tttfk
rB   Y dS X t|||d�S )a„  
    Parse XET connection info from the HTTP headers or return None if not found.
    Args:
        headers (`Dict`):
           HTTP headers to extract the XET metadata from.
    Returns:
        `XetConnectionInfo` or `None`:
            The information needed to connect to the XET storage service.
            Returns `None` if the headers do not contain the XET connection info.
    N)r   r   r   )	r   Z!HUGGINGFACE_HEADER_X_XET_ENDPOINTZ%HUGGINGFACE_HEADER_X_XET_ACCESS_TOKENr    Z#HUGGINGFACE_HEADER_X_XET_EXPIRATIONr'   Ú
ValueErrorÚ	TypeErrorr   )r%   r   r   r   r   r   r   Ú&parse_xet_connection_info_from_headersB   s    

ýr/   )Ú	file_datar%   r"   c                 C   s   | j dkrtdƒ‚t| j |ƒS )a  
    Utilizes the information in the parsed metadata to request the Hub xet connection information.
    This includes the access token, expiration, and XET service URL.
    Args:
        file_data: (`XetFileData`):
            The file data needed to refresh the xet connection information.
        headers (`Dict[str, str]`):
            Headers to use for the request, including authorization headers and user agent.
    Returns:
        `XetConnectionInfo`:
            The connection information needed to make the request to the xet storage service.
    Raises:
        [`~utils.HfHubHTTPError`]
            If the Hub API returned an error.
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If the Hub API response is improperly formatted.
    Nz>The provided xet metadata does not contain a refresh endpoint.)r   r-   Ú#_fetch_xet_connection_info_with_url)r0   r%   r   r   r   Úrefresh_xet_connection_info[   s    
r2   )Úrevisionr   Úparams)Ú
token_typeÚrepo_idÚ	repo_typer3   r%   r   r4   r"   c              	   C   s@   |dk	r|nt j}|› d|› d|› d| j› d|› �	}t|||ƒS )aÅ  
    Uses the repo info to request a xet access token from Hub.
    Args:
        token_type (`XetTokenType`):
            Type of the token to request: `"read"` or `"write"`.
        repo_id (`str`):
            A namespace (user or an organization) and a repo name separated by a `/`.
        repo_type (`str`):
            Type of the repo to upload to: `"model"`, `"dataset"` or `"space"`.
        revision (`str`, `optional`):
            The revision of the repo to get the token for.
        headers (`Dict[str, str]`):
            Headers to use for the request, including authorization headers and user agent.
        endpoint (`str`, `optional`):
            The endpoint to use for the request. Defaults to the Hub endpoint.
        params (`Dict[str, str]`, `optional`):
            Additional parameters to pass with the request.
    Returns:
        `XetConnectionInfo`:
            The connection information needed to make the request to the xet storage service.
    Raises:
        [`~utils.HfHubHTTPError`]
            If the Hub API returned an error.
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If the Hub API response is improperly formatted.
    Nz/api/zs/z/xet-z-token/)r   r(   Úvaluer1   )r5   r6   r7   r3   r%   r   r4   r#   r   r   r   Ú(fetch_xet_connection_info_from_repo_infow   s    %"r9   )r#   r%   r4   r"   c                 C   s8   t ƒ j|| |d�}t|ƒ t|jƒ}|dkr4tdƒ‚|S )aS  
    Requests the xet connection info from the supplied URL. This includes the
    access token, expiration time, and endpoint to use for the xet storage service.
    Args:
        url: (`str`):
            The access token endpoint URL.
        headers (`Dict[str, str]`):
            Headers to use for the request, including authorization headers and user agent.
        params (`Dict[str, str]`, `optional`):
            Additional parameters to pass with the request.
    Returns:
        `XetConnectionInfo`:
            The connection information needed to make the request to the xet storage service.
    Raises:
        [`~utils.HfHubHTTPError`]
            If the Hub API returned an error.
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If the Hub API response is improperly formatted.
    )r%   r#   r4   Nz6Xet headers have not been correctly set by the server.)r	   Úgetr
   r/   r%   r-   )r#   r%   r4   ÚrespÚmetadatar   r   r   r1   ¡   s    
r1   )N)N)Údataclassesr   Úenumr   Útypingr   r   ÚrequestsÚ r   r	   r
   r   r   r   r   r   ÚResponser,   r/   r2   r9   r1   r   r   r   r   Ú<module>   sX    ÿ þ%
üø
÷) ý
ü