o
    yqi                     @   s  d dl mZ d dlmZ d dl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'dejdee dee fddZdeeef dee fddZededeeef defddZedddddededed ee deeef dee d!eeeef  defd"d#Ze	d'd$edeeef d!eeeef  defd%d&ZdS )(    )	dataclass)Enum)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   a/home/app/PaddleOCR-VL/.venv_paddleocr/lib/python3.10/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u rdS z| j tj }tj| jv r| jtj d }n| j tj }W n
 ty-   Y dS w |dur4|ntj}|tj	rJ|
tj	d|d}t||dS )a^  
    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 (`httpx.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$   c              
   C   sP   z| t j }| t j }t| t j }W n tttfy    Y dS w 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_datac                 C   s   | j du 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)r/   r$   r   r   r   refresh_xet_connection_info[   s   
r1   )revisionr   params
token_typerepo_id	repo_typer2   r3   c              	   C   s@   |du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'   valuer0   )r4   r5   r6   r2   r$   r   r3   r"   r   r   r   (fetch_xet_connection_info_from_repo_infow   s   %"r8   r"   c                 C   s8   t  j|| |d}t| t|j}|du rt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"   r3   Nz6Xet headers have not been correctly set by the server.)r   getr	   r.   r$   r,   )r"   r$   r3   respmetadatar   r   r   r0      s   
r0   )N)dataclassesr   enumr   typingr   Zhttpx r   r   r	   r
   r   r   r   r   Responser+   dictr.   r1   r8   r0   r   r   r   r   <module>   sx    
%

	)
