o
    vZhJO                     @   s  d Z ddlZddlZddlmZ ddlmZ ddl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 dd
lmZmZmZmZmZmZmZ ddlmZm Z  e!e"Z#dZ$edddde dd	d4dddddee% de&de&de&ddf
ddZ'd4dee% ddfddZ(d5de%de&ddfddZ)d6d d!Z*edddde ddddd"de&de&ddfd#d$Z+d%Z,d&Z-d'Z.edddde ddddd"de&de&ddfd(d)Z/de%de&ddfd*d+Z0de%ddfd,d-Z1de%de&ddfd.d/Z2de&fd0d1Z3d6d2d3Z4dS )7z&Contains methods to log in to the Hub.    N)getpass)Path)Optional   )	constants)ANSI)	capture_output	get_tokenis_google_colabis_notebooklist_credential_helpersloggingrun_subprocessset_git_credentialunset_git_credential)_get_token_by_name_get_token_from_environment_get_token_from_file_get_token_from_google_colab_save_stored_tokens_save_tokenget_stored_tokens)_deprecate_arguments_deprecate_positional_argsa<  
    _|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|
    _|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|
    _|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|
    _|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|
    _|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|
z1.0write_permissionzuFine-grained tokens added complexity to the permissions, making it irrelevant to check if a token has 'write' access.)versionZdeprecated_argsZcustom_message)r   FT)add_to_git_credentialnew_sessionr   tokenr   r   returnc                C   sH   | dur|st d t| |d dS t rt|d dS t|d dS )au  Login the machine to access the Hub.

    The `token` is persisted in cache and set as a git credential. Once done, the machine
    is logged in and the access token will be available across all `huggingface_hub`
    components. If `token` is not provided, it will be prompted to the user either with
    a widget (in a notebook) or via the terminal.

    To log in from outside of a script, one can also use `huggingface-cli login` which is
    a cli command that wraps [`login`].

    <Tip>

    [`login`] is a drop-in replacement method for [`notebook_login`] as it wraps and
    extends its capabilities.

    </Tip>

    <Tip>

    When the token is not passed, [`login`] will automatically detect if the script runs
    in a notebook or not. However, this detection might not be accurate due to the
    variety of notebooks that exists nowadays. If that is the case, you can always force
    the UI by using [`notebook_login`] or [`interpreter_login`].

    </Tip>

    Args:
        token (`str`, *optional*):
            User access token to generate from https://huggingface.co/settings/token.
        add_to_git_credential (`bool`, defaults to `False`):
            If `True`, token will be set as git credential. If no git credential helper
            is configured, a warning will be displayed to the user. If `token` is `None`,
            the value of `add_to_git_credential` is ignored and will be prompted again
            to the end user.
        new_session (`bool`, defaults to `True`):
            If `True`, will request a token even if one is already saved on the machine.
        write_permission (`bool`):
            Ignored and deprecated argument.
    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If an organization token is passed. Only personal account tokens are valid
            to log in.
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If token is invalid.
        [`ImportError`](https://docs.python.org/3/library/exceptions.html#ImportError)
            If running in a notebook but `ipywidgets` is not installed.
    NzThe token has not been saved to the git credentials helper. Pass `add_to_git_credential=True` in this function directly or `--add-to-git-credential` if using via `huggingface-cli` if you want to set the git credential as well.r   )r   )loggerinfo_loginr   notebook_logininterpreter_login)r   r   r   r    r&   E/var/www/auris/lib/python3.10/site-packages/huggingface_hub/_login.pylogin:   s   <r(   
token_namec              	   C   s   t  du rt std dS | s1tjtjfD ]}zt|  W q t	y*   Y qw t
d nt|  t
d|  d t  t durJtdt durStddS )a  Logout the machine from the Hub.

    Token is deleted from the machine and removed from git credential.

    Args:
        token_name (`str`, *optional*):
            Name of the access token to logout from. If `None`, will logout from all saved access tokens.
    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
            If the access token name is not found.
    NzNot logged in!z/Successfully logged out from all access tokens.z+Successfully logged out from access token: .zYou are automatically logged in using a Google Colab secret.
To log out, you must unset the `HF_TOKEN` secret in your Colab settings.zToken has been deleted from your machine but you are still logged in.
To log out, you must clear out both `HF_TOKEN` and `HUGGING_FACE_HUB_TOKEN` environment variables.)r	   r   r!   warningr   HF_TOKEN_PATHHF_STORED_TOKENS_PATHr   unlinkFileNotFoundErrorr"   _logout_from_tokenr   r   EnvironmentErrorr   )r)   	file_pathr&   r&   r'   logout   s.   


r3   c                 C   sh   t | }|std|  dtj t| | td|   t }|dur0||kr2td dS dS dS )a{  Switch to a different access token.

    Args:
        token_name (`str`):
            Name of the access token to switch to.
        add_to_git_credential (`bool`, defaults to `False`):
            If `True`, token will be set as git credential. If no git credential helper
            is configured, a warning will be displayed to the user. If `token` is `None`,
            the value of `add_to_git_credential` is ignored and will be prompted again
            to the end user.

    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
            If the access token name is not found.
    zAccess token  not found in zThe current active token is: NzfThe environment variable `HF_TOKEN` is set and will override the access token you've just switched to.)	r   
ValueErrorr   r-   _set_active_tokenr!   r"   r   r+   )r)   r   r   Ztoken_from_environmentr&   r&   r'   auth_switch   s   
r7   c                  C   s(  t  } | std dS t }d}| D ]}| ||kr|}qttdtdd | D d }td| dd	d td
|d  d d  | D ]3}| |d}|dkrd|dd  d|dd  n|}||krldnd}t| d| d|| qIt	 rt
d dS |du rt
d dS dS )zList all stored access tokens.zNo access tokens found.Nr   c                 s   s    | ]}t |V  qd S N)len).0r   r&   r&   r'   	<genexpr>   s    zauth_list.<locals>.<genexpr>   z  {:<z	}| {:<15}name-|z---------------z	<not set>   z***** z {:<z
Note: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above.zu
Note: No active token is set and no environment variable `HF_TOKEN` is found. Use `huggingface-cli login` to log in.)r   r!   r"   r	   getmaxr9   printformatr   r+   )tokenscurrent_tokenZcurrent_token_namer)   
max_offsetr   Zmasked_tokenZ
is_currentr&   r&   r'   	auth_list   s6   
 *rK   )r   r   c                 C   s   | st  durtd dS ddlm} tt t  dur'td td td tjdkr6td	 t	d
}|d}t
||d dS )a+  
    Displays a prompt to log in to the HF website and store the token.

    This is equivalent to [`login`] without passing a token when not run in a notebook.
    [`interpreter_login`] is useful if you want to force the use of the terminal prompt
    instead of a notebook widget.

    For more details, see [`login`].

    Args:
        new_session (`bool`, defaults to `True`):
            If `True`, will request a token even if one is already saved on the machine.
        write_permission (`bool`):
            Ignored and deprecated argument.
    NUser is already logged in.r   )_ask_for_confirmation_no_tuiz    A token is already saved on your machine. Run `huggingface-cli whoami` to get more information or `huggingface-cli logout` if you want to log out.z4    Setting a new token will erase the existing one.zi    To log in, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .ntz(Token can be pasted using 'Right-Click'.z.Enter your token (input will not be visible): Add token as git credential?)r   r   )r	   r!   r"   Zcommands.delete_cacherM   rF   _HF_LOGO_ASCIIosr=   r   r#   )r   r   rM   r   r   r&   r&   r'   r%      s$   




r%   z<center> <img
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
alt='Hugging Face'> <br> Immediately click login after typing your password or
it might be stored in plain text in this notebook file. </center>ap  <center> <img
src=https://huggingface.co/front/assets/huggingface_logo-noborder.svg
alt='Hugging Face'> <br> Copy a token from <a
href="https://huggingface.co/settings/tokens" target="_blank">your Hugging Face
tokens page</a> and paste it below. <br> Immediately click login after copying
your token or it might be stored in plain text in this notebook file. </center>z
<b>Pro Tip:</b> If you don't already have one, you can create a dedicated
'notebooks' token with 'write' access, that you can then easily reuse for all
notebooks. </center>c                    s   zddl m ddlm} W n ty   tdw | s(t dur(td dS jdddd	d
}j	ddj
ddd jdd}jt |tg|d|  fdd}|| dS )a+  
    Displays a widget to log in to the HF website and store the token.

    This is equivalent to [`login`] without passing a token when run in a notebook.
    [`notebook_login`] is useful if you want to force the use of the notebook widget
    instead of a prompt in the terminal.

    For more details, see [`login`].

    Args:
        new_session (`bool`, defaults to `True`):
            If `True`, will request a token even if one is already saved on the machine.
        write_permission (`bool`):
            Ignored and deprecated argument.
    r   N)displayzThe `notebook_login` function can only be used in a notebook (Jupyter or Colab) and you need the `ipywidgets` module: `pip install ipywidgets`.rL   Zflexcolumncenterz50%)rR   Z	flex_flowZalign_itemswidthzToken:)descriptionTrO   )valuerV   ZLogin)Zlayoutc              
      s   j } j }d_ dg_zt }t||d W d   n1 s%w   Y  | }W n tyE } z
t|}W Y d}~nd}~ww fdd|dD _dS )z#Event handler for the login button. zConnecting...r    Nc                    s   g | ]}|  r |qS r&   )stripLabel)r:   line)widgetsr&   r'   
<listcomp>  s    z=notebook_login.<locals>.login_token_event.<locals>.<listcomp>
)	rW   rZ   childrenr   r#   getvalue	Exceptionstrsplit)tr   r   ZcapturedmessageerrorZgit_checkbox_widgetZlogin_token_widgetZtoken_widgetr\   r&   r'   login_token_eventr  s   z)notebook_login.<locals>.login_token_event)Zipywidgets.widgetsr\   IPython.displayrR   ImportErrorr	   r!   r"   ZLayoutZPasswordZCheckboxZButtonZVBoxHTMLNOTEBOOK_LOGIN_TOKEN_HTML_STARTNOTEBOOK_LOGIN_TOKEN_HTML_ENDZon_click)r   r   rR   Z
box_layoutZtoken_finish_buttonrh   r&   rg   r'   r$   =  s6   

r$   c                 C   s   ddl m} | drtd|| }|d d d }td| d	 |d d d
 }t| |d t||d td t rGt	d d S td| d d S )Nr   )whoamiZapi_orgzDYou must use your personal account token, not an organization token.authZaccessTokenZrolezToken is valid (permission: ).ZdisplayName)r   r)   )r)   r   zLogin successful.zNote: Environment variable`HF_TOKEN` is set and is the current active token independently from the token you've just configured.zThe current active token is: ``)
Zhf_apirn   
startswithr5   r!   r"   r   r6   r   r+   )r   r   rn   Z
token_infoZ
permissionr)   r&   r&   r'   r#     s   

r#   c                 C   s^   t  }|r	| |vrdS || }t| |t kr-td|  d ttjj	dd dS dS )a  Logout from a specific access token.

    Args:
        token_name (`str`):
            The name of the access token to logout from.
    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError):
            If the access token name is not found.
    NzActive token 'z' has been deleted.T)
missing_ok)
r   popr   r   r!   r+   r   r   r,   r.   )r)   Zstored_tokensr   r&   r&   r'   r0     s   


r0   c                 C   s   t | }|std|  dtj |r/t r*t| tdddt	  d  nt
d ttj}|jjddd	 || td
tj  dS )z|Set the active access token.

    Args:
        token_name (`str`):
            The name of the token to set as active.
    zToken r4   zCYour token has been saved in your configured git credential helpersz (,rp   z2Token has not been saved to git credential helper.T)parentsexist_okzYour token has been saved to N)r   r5   r   r-   $_is_git_credential_helper_configuredr   r!   r"   joinr   r+   r   r,   parentmkdir
write_text)r)   r   r   pathr&   r&   r'   r6     s    



r6   c                  C   s8   t  } t| dkrdS t rt  dS ttd dS )zCheck if a git credential helper is configured.

    Warns user if not the case (except for Google Colab where "store" is set by default
    by `huggingface_hub`).
    r   Ta  Cannot authenticate through git-credential as no helper is defined on your machine.
You might have to re-authenticate when pushing to the Hugging Face Hub.
Run the following command in your terminal in case you want to set the 'store' credential helper as default.

git config --global credential.helper store

Read https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for more details.F)r   r9   r
   ,_set_store_as_git_credential_helper_globallyrF   r   red)helpersr&   r&   r'   rx     s   rx   c               
   C   s4   zt d W dS  tjy }  zt| jd} ~ ww )a  Set globally the credential.helper to `store`.

    To be used only in Google Colab as we assume the user doesn't care about the git
    credential config. It is the only particular case where we don't want to display the
    warning message in [`notebook_login()`].

    Related:
    - https://github.com/huggingface/huggingface_hub/issues/1043
    - https://github.com/huggingface/huggingface_hub/issues/1051
    - https://git-scm.com/docs/git-credential-store
    z+git config --global credential.helper storeN)r   
subprocessCalledProcessErrorr1   stderr)excr&   r&   r'   r~     s   
r~   r8   )F)r   N)5__doc__rQ   r   r   pathlibr   typingr   rX   r   Zcommands._cli_utilsr   utilsr   r	   r
   r   r   r   r   r   r   Zutils._authr   r   r   r   r   r   r   Zutils._deprecationr   r   Z
get_logger__name__r!   rP   rb   boolr(   r3   r7   rK   r%   ZNOTEBOOK_LOGIN_PASSWORD_HTMLrl   rm   r$   r#   r0   r6   rx   r~   r&   r&   r&   r'   <module>   s   ,$	
	E*
)"."H

