U
    9%e$                  
   @   sF  d Z ddlmZmZmZ ddlmZ ddlmZ ddl	m
Z
mZmZmZmZmZmZmZmZmZ ddlmZ G d	d
 d
eZeddddddeeeef  eee ee eeedf eeef dddZeeeef  ee dddZee eddddZddddee ee eeedf edddZeedddZdS )zIContains utilities to handle headers to send in calls to Huggingface Hub.    )DictOptionalUnion   )	constants   )HfFolder)
get_fastai_versionget_fastcore_versionget_hf_hub_versionget_python_versionget_tf_versionget_torch_versionis_fastai_availableis_fastcore_availableis_tf_availableis_torch_available)validate_hf_hub_argsc                   @   s   e Zd ZdZdS )LocalTokenNotFoundErrorz0Raised if local token is required but not found.N)__name__
__module____qualname____doc__ r   r   ]/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/huggingface_hub/utils/_headers.pyr   #   s   r   NF)tokenis_write_actionlibrary_namelibrary_version
user_agent)r   r   r   r   r   returnc                 C   s@   t | }t||d dt|||di}|dk	r<d| |d< |S )a  
    Build headers dictionary to send in a HF Hub call.

    By default, authorization token is always provided either from argument (explicit
    use) or retrieved from the cache (implicit use). To explicitly avoid sending the
    token to the Hub, set `token=False` or set the `HF_HUB_DISABLE_IMPLICIT_TOKEN`
    environment variable.

    In case of an API call that requires write access, an error is thrown if token is
    `None` or token is an organization token (starting with `"api_org***"`).

    In addition to the auth header, a user-agent is added to provide information about
    the installed packages (versions of python, huggingface_hub, torch, tensorflow,
    fastai and fastcore).

    Args:
        token (`str`, `bool`, *optional*):
            The token to be sent in authorization header for the Hub call:
                - if a string, it is used as the Hugging Face token
                - if `True`, the token is read from the machine (cache or env variable)
                - if `False`, authorization header is not set
                - if `None`, the token is read from the machine only except if
                  `HF_HUB_DISABLE_IMPLICIT_TOKEN` env variable is set.
        is_write_action (`bool`, default to `False`):
            Set to True if the API call requires a write access. If `True`, the token
            will be validated (cannot be `None`, cannot start by `"api_org***"`).
        library_name (`str`, *optional*):
            The name of the library that is making the HTTP request. Will be added to
            the user-agent header.
        library_version (`str`, *optional*):
            The version of the library that is making the HTTP request. Will be added
            to the user-agent header.
        user_agent (`str`, `dict`, *optional*):
            The user agent info in the form of a dictionary or a single string. It will
            be completed with information about the installed packages.

    Returns:
        A `Dict` of headers to pass in your API call.

    Example:
    ```py
        >>> build_hf_headers(token="hf_***") # explicit token
        {"authorization": "Bearer hf_***", "user-agent": ""}

        >>> build_hf_headers(token=True) # explicitly use cached token
        {"authorization": "Bearer hf_***",...}

        >>> build_hf_headers(token=False) # explicitly don't use cached token
        {"user-agent": ...}

        >>> build_hf_headers() # implicit use of the cached token
        {"authorization": "Bearer hf_***",...}

        # HF_HUB_DISABLE_IMPLICIT_TOKEN=True # to set as env variable
        >>> build_hf_headers() # token is not sent
        {"user-agent": ...}

        >>> build_hf_headers(token="api_org_***", is_write_action=True)
        ValueError: You must use your personal account token for write-access methods.

        >>> build_hf_headers(library_name="transformers", library_version="1.2.3")
        {"authorization": ..., "user-agent": "transformers/1.2.3; hf_hub/0.10.2; python/3.10.4; tensorflow/1.55"}
    ```

    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If organization token is passed and "write" access is required.
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If "write" access is required but token is not passed and not saved locally.
        [`EnvironmentError`](https://docs.python.org/3/library/exceptions.html#EnvironmentError)
            If `token=True` but token is not saved locally.
    )r   z
user-agentr   r   r   NzBearer authorization)get_token_to_send_validate_token_to_send_http_user_agent)r   r   r   r   r   Ztoken_to_sendheadersr   r   r   build_hf_headers'   s    R r'   )r   r    c                 C   sN   t | tr| S | dkrdS t  }| dkr@|dkr<td|S tjrJdS |S )z:Select the token to send from either `token` or the cache.FNTzToken is required (`token=True`), but no token found. You need to provide a token or be logged in to Hugging Face with `huggingface-cli login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens.)
isinstancestrr   	get_tokenr   r   ZHF_HUB_DISABLE_IMPLICIT_TOKEN)r   Zcached_tokenr   r   r   r#      s    

r#   )r   r   r    c                 C   s*   |r&| d krt d| dr&t dd S )NzToken is required (write-access action) but no token found. You need to provide a token or be logged in to Hugging Face with `huggingface-cli login` or `huggingface_hub.login`. See https://huggingface.co/settings/tokens.Zapi_orgzYou must use your personal account token for write-access methods. To generate a write-access token, go to https://huggingface.co/settings/tokens)
ValueError
startswith)r   r   r   r   r   r$      s    
r$   r!   )r   r   r   r    c                 C   s   | dk	r|  d| }nd}|dt   7 }|dt  7 }tjst rX|dt  7 }t rn|dt  7 }t r|dt	  7 }t
 r|d	t  7 }t|tr|d
d
dd | D  7 }nt|tr|d
| 7 }t|S )a  Format a user-agent string containing information about the installed packages.

    Args:
        library_name (`str`, *optional*):
            The name of the library that is making the HTTP request.
        library_version (`str`, *optional*):
            The version of the library that is making the HTTP request.
        user_agent (`str`, `dict`, *optional*):
            The user agent info in the form of a dictionary or a single string.

    Returns:
        The formatted user-agent string.
    N/zunknown/Nonez	; hf_hub/z	; python/z; torch/z; tensorflow/z	; fastai/z; fastcore/; c                 s   s    | ]\}}| d | V  qdS )r-   Nr   ).0kvr   r   r   	<genexpr>   s     z#_http_user_agent.<locals>.<genexpr>)r   r   r   ZHF_HUB_DISABLE_TELEMETRYr   r   r   r   r   r	   r   r
   r(   dictjoinitemsr)   _deduplicate_user_agent)r   r   r   Zuar   r   r   r%      s&    
"
r%   )r   r    c                 C   s   d dd | dD  S )z>Deduplicate redundant information in the generated user-agent.r.   c                 S   s   i | ]}|  d qS )N)strip)r/   keyr   r   r   
<dictcomp>   s      z+_deduplicate_user_agent.<locals>.<dictcomp>;)r4   splitkeys)r   r   r   r   r6      s    r6   )r   typingr   r   r    r   Z
_hf_folderr   Z_runtimer	   r
   r   r   r   r   r   r   r   r   Z_validatorsr   EnvironmentErrorr   boolr)   r'   r#   r$   r%   r6   r   r   r   r   <module>   s@   0
a  ,