U
    9%e7                     @   s6  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 dd
lmZmZmZmZmZmZmZmZmZ eeZd%ee eeeddddZddddZd&eeddddZdZ dZ!dZ"d'eeddddZ#d(eeeddddZ$d)eddd Z%edd!d"Z&ddd#d$Z'dS )*z%Contains methods to login to the Hub.    N)partial)getpass)Optional   )ANSI)_ask_for_confirmation_no_tuiget_token_permission)	HfFoldercapture_outputis_google_colabis_notebooklist_credential_helpersloggingrun_subprocessset_git_credentialunset_git_credentialFT)tokenadd_to_git_credentialnew_sessionwrite_permissionreturnc                 C   sH   | dk	r$|st d t| ||d n t r8t||d nt||d dS )a  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 login 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`, defaults to `False`):
            If `True`, requires a token with write permission.
    Raises:
        [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError)
            If an organization token is passed. Only personal account tokens are valid
            to login.
        [`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.
    NzToken will not been saved to git credential helper. Pass `add_to_git_credential=True` if you want to set the git credential as well.r   r   )r   r   )print_loginr   notebook_logininterpreter_login)r   r   r   r    r   U/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/huggingface_hub/_login.pylogin(   s    1r   )r   c                  C   s6   t  } | dkrtd dS t   t  td dS )zmLogout the machine from the Hub.

    Token is deleted from the machine and removed from git credential.
    NzNot logged in!zSuccessfully logged out.)r
   	get_tokenr   Zdelete_tokenr   )r   r   r   r   logoutg   s    r!   )r   r   r   c                 C   sz   | st |drtd dS td t dk	r>td td td tjdkrXtd	 td
}td}t|||d dS )aR  
    Displays a prompt to login 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`, defaults to `False`):
            If `True`, requires a token with write permission.

    r   User is already logged in.Na@  
    _|    _|  _|    _|    _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|_|_|_|    _|_|      _|_|_|  _|_|_|_|
    _|    _|  _|    _|  _|        _|          _|    _|_|    _|  _|            _|        _|    _|  _|        _|
    _|_|_|_|  _|    _|  _|  _|_|  _|  _|_|    _|    _|  _|  _|  _|  _|_|      _|_|_|    _|_|_|_|  _|        _|_|_|
    _|    _|  _|    _|  _|    _|  _|    _|    _|    _|    _|_|  _|    _|      _|        _|    _|  _|        _|
    _|    _|    _|_|      _|_|_|    _|_|_|  _|_|_|  _|      _|    _|_|_|      _|        _|    _|    _|_|_|  _|_|_|_|
    z    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.zh    To login, `huggingface_hub` requires a token generated from https://huggingface.co/settings/tokens .ntz(Token can be pasted using 'Right-Click'.zToken: Add token as git credential?)r   r   r   )	_current_token_okayr   r
   r    osnamer   r   r   )r   r   r   r   r   r   r   r   z   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k
r8   tdY nX | sTt|drTtd dS jddd	d
d}jddj	ddd j
dd}jt |tg|d| dtd fdd}|t||d dS )aQ  
    Displays a widget to login 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`, defaults to `False`):
            If `True`, requires a token with write permission.
    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`.r"   r#   Zflexcolumncenterz50%)r)   Z	flex_flowZalign_itemswidthzToken:)descriptionTr%   )valuer-   ZLogin)ZlayoutFc              
      s   j } j }d_ dg_z,t }t|||d W 5 Q R X | }W n* tk
rv } zt|}W 5 d}~X Y nX fdd|dD _dS )z
        Event handler for the login button.

        Args:
            write_permission (`bool`, defaults to `False`):
                If `True`, requires a token with write permission.
         zConnecting...r   Nc                    s   g | ]}|  r |qS r   )stripLabel).0line)widgetsr   r   
<listcomp>  s      z=notebook_login.<locals>.login_token_event.<locals>.<listcomp>
)	r.   r1   childrenr   r   getvalue	Exceptionstrsplit)tr   r   r   ZcapturedmessageerrorZgit_checkbox_widgetZlogin_token_widgetZtoken_widgetr4   r   r   login_token_event   s    z)notebook_login.<locals>.login_token_event)F)Zipywidgets.widgetsr4   IPython.displayr)   ImportErrorr&   r   ZLayoutZPasswordZCheckboxZButtonZVBoxHTMLNOTEBOOK_LOGIN_TOKEN_HTML_STARTNOTEBOOK_LOGIN_TOKEN_HTML_ENDboolZon_clickr   )r   r   r)   Z
box_layoutZtoken_finish_buttonr@   r   r?   r   r      s4    

r   )r   r   r   r   c                 C   s   |  drtdt| }|d kr,tdn|r@|dkr@tdtd| d |rt rt|  tdd	d
t  d  ntd t	|  tdtj
  td d S )NZapi_orgzDYou must use your personal account token, not an organization token.zInvalid token passed!writezvToken is valid but is 'read-only' and a 'write' token is required.
Please provide a new token with correct permission.zToken is valid (permission: z).zCYour token has been saved in your configured git credential helpersz (,z2Token has not been saved to git credential helper.zYour token has been saved to zLogin successful)
startswith
ValueErrorr	   r   $_is_git_credential_helper_configuredr   joinr   r
   Z
save_tokenZ
path_token)r   r   r   
permissionr   r   r   r     s,    


r   r"   c                 C   s"   t  }|dks| r|dkrdS dS )a  Check if the current token is valid.

    Args:
        write_permission (`bool`, defaults to `False`):
            If `True`, requires a token with write permission.

    Returns:
        `bool`: `True` if the current token is valid, `False` otherwise.
    NrG   FTr   )r   rM   r   r   r   r&   *  s    
r&   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   lenr   ,_set_store_as_git_credential_helper_globallyr   r   red)helpersr   r   r   rK   :  s    rK   c               
   C   s@   zt d W n. tjk
r: }  zt| jW 5 d} ~ X Y nX dS )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CalledProcessErrorEnvironmentErrorstderr)excr   r   r   rO   Y  s    rO   )NFTF)TF)TF)F)F)(__doc__r'   rR   	functoolsr   r   typingr   Zcommands._cli_utilsr   Zcommands.delete_cacher   Zhf_apir	   utilsr
   r   r   r   r   r   r   r   r   Z
get_logger__name__loggerr:   rF   r   r!   r   ZNOTEBOOK_LOGIN_PASSWORD_HTMLrD   rE   r   r   r&   rK   rO   r   r   r   r   <module>   s>   ,
    ?1N