
    -:j:U                     b   d Z ddlZddlZddl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mZ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'  ejP                  e)      Z*	 d)dddde+dz  de,de,ddfdZ-d)de+dz  ddfdZ.d*de+de,ddfdZ/d+dZ0d+dZ1de%de2e+e+f   fdZ3de%de+dz  fdZ4ddde,ddfdZ5de+fdZ6d+dZ7ddde,ddfd Z8	 	 d,de+de,d!e+dz  d"e9dz  de2e+e+f   f
d#Z:de+ddfd$Z;d"e+dz  de+fd%Z<de+de,ddfd&Z=de,fd'Z>d+d(Z?y)-z&Contains methods to log in to the Hub.    N)datetime)getpass)Path   )	constants)DeviceCodeError)ANSI	get_tokenis_google_colabis_notebooklist_credential_helpersloggingrun_subprocessselect_choiceset_git_credentialtabulateunset_git_credential)	_get_token_by_name_get_token_from_environment_get_token_from_file_get_token_from_google_colab_read_stored_tokens_full_save_stored_tokens_full_save_token_write_secretget_stored_tokens)OAuthTokenResponsepoll_device_tokenrequest_device_codeFT)add_to_git_credentialskip_if_logged_intokenr    r!   returnc                    | %|st         j                  d       t        | |       y|rt         j                  d       t	               rt        |       yt        |       y)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, a browser-based OAuth flow is used to
    authenticate: open a URL, enter a short code, and the token is retrieved and saved.
    In a terminal, you can also choose to paste an existing access token instead.

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

    > [!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`].

    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. Only used when `token`
            is provided; ignored by the browser-based flow.
        skip_if_logged_in (`bool`, defaults to `True`):
            If `True`, do not prompt for token if user is already logged in.
            Set to `False` to force re-login. In CLI, use `--force` instead.
    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.
        [`DeviceCodeError`]
            If the browser-based login fails (authorization denied, code expired, ...).
    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 `hf`CLI if you want to set the git credential as well.)r    zy`add_to_git_credential=True` is only supported when a token is passed directly. It is ignored by the browser-based login.r!   )loggerinfo_validate_and_save_tokenwarningr   notebook_logininterpreter_login)r"   r    r!   s      X/var/www/html/tokenscope/api/venv/lib/python3.12/site-packages/huggingface_hub/_login.pyloginr-   9   s\    T $KK> 	!>ST8	
 }):;,=>    
token_namec                    t                t               st        j                  d       y| sUt        j
                  t        j                  fD ]  }	 t        |      j                           t        j                  d       n$t        |        t        j                  d|  d       t                t               t        d      t               t        d      y# t        $ r Y w xY w)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 log out 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&   r)   r   HF_TOKEN_PATHHF_STORED_TOKENS_PATHr   unlinkFileNotFoundErrorr'   _logout_from_tokenr   r   OSErrorr   )r/   	file_paths     r,   logoutr9   x   s     {#4#6'(#1193R3RS 	IY&&(	
 	EF:&A*QOP $%1W
 	
 #$0q
 	
 1 % s   C	C'&C'c                     t        |       }|st        d|  dt        j                         t	        | |       t
        j                  d|         t               }|||k7  rt
        j                  d       yyy)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   r3   _set_active_tokenr&   r'   r   r)   )r/   r    r"   token_from_environments       r,   auth_switchr?      s~      z*E=N9CbCbBcdeej"78
KK/
|<=8:).D.Mt	
 /N)r.   c                     t               } t               }|sKt               r+t        j	                  d       t        j                  d       yt        j	                  d       yt        d |j                         D              }g d|rdgng z   }d}g }|j                         D ]z  \  }}|j                  dd	      }|| k(  r|}|d	k7  r|dd
  d|dd  n|}	|| k(  rdnd||	g}
|r)|
j                  t        |j                  d                   |j                  |
       | t        t        ||             t               rt        j                  d       y|t        j                  d       yy)zList all stored access tokens.zNo stored access tokens found.zMNote: Environment variable `HF_TOKEN` is set and is the current active token.zNo access tokens found.Nc              3   $   K   | ]  }d |v  
 yw)
expires_atN ).0fieldss     r,   	<genexpr>zauth_list.<locals>.<genexpr>   s     S&|v-Ss   ) namer"   expireshf_tokenz	<not set>   z***** rB   )headersz
Note: Environment variable `HF_TOKEN` is set and is the current active token independently from the stored tokens listed above.zm
Note: No active token is set and no environment variable `HF_TOKEN` is found. Use `hf auth login` to log in.)r
   r   r   r&   r'   r)   anyvaluesitemsgetappend_format_expirationprintr   )current_tokenstored_tokensshow_expiresrO   current_token_namerowsr/   rE   r"   masked_tokenrows              r,   	auth_listr^      sg    KM,.M&(KK89NNjk 	 KK12SM<P<P<RSSL$|LG"$D+113 
F

:{3M!!+9>+9M%)Drs5SX','=2zS_`JJ)&**\*BCDC 
(4
)*"$ P	
 
	#|	
 
$r.   c                      t               } t        d| d    d       t        d| d    d       t        ddd	       	 t        | d
       }t                t        |       y# t                w xY w)zRun the Device Code OAuth flow: request a code, prompt the user to authorize it in a browser,
    poll for the token and save it.z,
    Open this URL in your browser:
        verification_uri_complete
z    And enter the code: 	user_codez    Waiting for authorizationrN   Tendflushc                      t        ddd      S )Nr1   rN   Trc   )rV   rC   r.   r,   <lambda>z$_device_code_login.<locals>.<lambda>   s    U3TV^bEc r.   )
on_pendingN)r   rV   r   _save_oauth_token)device_inforesponses     r,   _device_code_loginrl      su     &'K 
:;Gb;c:ddf
gh	$[%=$>b
AB	
)r>$[=cdh 	s   A" "A.rk   c           	         | j                  d      }t        | d   d| j                  d      |r)t        t        j                               t        |      z   nd      \  }}t	        |       x}rt
        j                  d|        ||fS )z\Validate and persist a token response from the device code flow, including refresh metadata.
expires_inaccess_tokenFrefresh_tokenN)r    rp   rB   zNote: )rS   r(   inttime_expiration_noter&   r'   )rk   rn   r/   usernamenotes        r,   ri   ri      s    l+J3 #ll?39C3tyy{#c*o5	J  ))t)fTFO$xr.   c                     | j                  d      }|sy| j                  d      ryt        dt        |      dz        }d| dS )	zSHuman-readable note about the lifetime of a freshly obtained OAuth token, if known.rn   Nrp   z;This token will be refreshed automatically when it expires.r   iQ zThis token expires in z  days. Log in again to renew it.)rS   maxrq   )rk   rn   dayss      r,   rs   rs     sJ    l+J||O$Lq#j/U*+D#D6)IJJr.   r%   c                     | r t               t        j                  d       yt               t        j                  d       t               dk(  rt	                yt                y)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 flow.

    For more details, see [`login`].

    Args:
        skip_if_logged_in (`bool`, defaults to `True`):
            If `True`, do not prompt for token if user is already logged in.
            Set to `False` to force re-login. In CLI, use `--force` instead.
    NIUser is already logged in. Use `hf auth login --force` to force re-login.z_Note: a token is already saved on this machine. Logging in again will replace the active token.r"   )r
   r&   r'   _prompt_login_method_paste_token_loginrl   r%   s    r,   r+   r+     sJ     Y[4_`{uv(r.   c                      t         j                  t         j                  j                         syt        dddg      } | dk(  rdS dS )zXAsk the user how to log in: "browser" (default) or "token". Never prompts without a TTY.browserzHow would you like to log in?zLog in with your browserzPaste an access tokenr   r"   )sysstdinisattyr   )choices    r,   r{   r{   8  sC    
yy		 0 0 2:=WYp<qrF!900r.   c                      t         j                  d       t        j                  dk(  rt         j                  d       t	        d      } t        | d       y )Nzi    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): F)r"   r    )r&   r'   osrH   r   r(   )r"   s    r,   r|   r|   @  s@    
KKs 
ww$>?DEE5Fr.   c                    | r t               t        j                  d       y	 ddlm}m} t               }t        j                  |d         }t        j                  |d         } | |d	| d
| dt        j                  |d          d              | |d             	 t        |      }	 t        |      \  }}	dt        j                  |	       dt        j                  |       d}t!        |      x}r|dt        j                  |       z  } | |d| d             y# t        $ r t        d       Y yw xY w# t        $ r8} | |dt        j                  t        |             d             Y d}~yd}~ww xY w# t        $ r8}
 | |dt        j                  t        |
             d             Y d}
~
yd}
~
ww xY w)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 run in a notebook.
    [`notebook_login`] is useful if you want to force the use of the notebook flow
    instead of a prompt in the terminal.

    For more details, see [`login`].

    Args:
        skip_if_logged_in (`bool`, defaults to `True`):
            If `True`, do not prompt for token if user is already logged in.
            Set to `False` to force re-login. In CLI, use `--force` instead.
    Nrz   r   )HTMLdisplayFr%   verification_urir`   z<center><img src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg" width="100" alt="Hugging Face"><br><br><p>To log in, open this URL and enter the code:</p><p><a href="z" target="_blank"><b>z[</b></a></p><p style="font-size: 1.6em; letter-spacing: 0.3em; font-family: monospace;"><b>rb   z</b></p></center>z4<center><i>Waiting for authorization...</i></center>z-<center><b style='color: red;'>Login failed: z</b></center>z<center><b style='color: red;'>z"Login successful. Logged in as <b>z</b> (token: <code>z	</code>).z<br>z<center>z	</center>)r
   r&   r'   IPython.displayr   r   ImportErrorr+   r   htmlescaper   r   strri   	Exceptionrs   )r!   r   r   rj   r   r`   rk   er/   rt   errormessageru   s                r,   r*   r*   O  s    Y[4_`1 &'K{{;/A#BC $K8S,T U 555JK[J\ ]++k+6788IK	
	 DGHI$[1
0:
H
 34;;x3H2II\]a]h]his]t\uu~G))t)T$++d+,--D8G9I./0I  E2.  DT[[QTUVQWEXDYYfghi  6t{{3u:7N6O}]^_sA   D' #E /F 'D?>D?	F.E>>F	G.GGrp   rB   c                 F   ddl m} | j                  d      rt        d       ||       }|d   }|j	                  d      xs i j	                  d      xs i }|j	                  d      x}rt
        j                  d	| d
       nt
        j                  d       |j	                  d      xs d| }	t        | |	||       t        |	|       t
        j                  d       t               rt
        j                  d       |	|fS t
        j                  d|	 d       |	|fS )a  Validate a token against the Hub, save it to the stored tokens file and set it as active.

    The token is stored under its `displayName` from the whoami response, or `oauth-{username}`
    for OAuth tokens (which have no display name).

    Args:
        token (`str`):
            The access token.
        add_to_git_credential (`bool`):
            Whether to save the token to the git credential helpers.
        refresh_token (`str`, *optional*):
            OAuth refresh token to persist alongside the access token.
        expires_at (`int`, *optional*):
            Unix timestamp at which the access token expires.

    Returns:
        `tuple[str, str]`: The token name and the username.
    r   )whoamiapi_orgzDYou must use your personal account token, not an organization token.rH   authaccessTokenrolezToken is valid (permission: ).zToken is valid.displayNamezoauth-)r"   r/   rp   rB   )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: ``)hf_apir   
startswithr<   rS   r&   r'   r   r=   r   r)   )
r"   r    rp   rB   r   
token_infort   access_token_infor   r/   s
             r,   r(   r(     s   0 	"_``J&!H#/52::=IOR $$V,,t,24&;<%&"&&}5L6(9LJ e
-\fgCXY
KK#$"$ O	

 x 	4ZLBCxr.   c                    t               }| |vry|j                  |       }t        |       |j                  d      t	               k(  rCt
        j                  d|  d       t        t        j                        j                  d       yy)zLogout from a specific access token.

    Args:
        token_name (`str`):
            The name of the access token to logout from.
    NrJ   zActive token 'z' has been deleted.T)
missing_ok)r   popr   rS   r   r&   r)   r   r   r2   r4   )r/   rX   rE   s      r,   r6   r6     s{     -.M&z*F]+zz*!5!77
|3FGHY$$%,,,= 8r.   c                     | sy	 t        |       }t        j                  |      j	                  d      }|t        j
                         k  r| dS |S # t        $ r Y yw xY w)zAFormat an `expires_at` unix timestamp for display in `auth list`.rN   z%Y-%m-%dz
 (expired))rq   r<   r   fromtimestampstrftimerr   )rB   	timestampdate_strs      r,   rU   rU     sf    
O	 %%i099*EH&/$))+&=hZz"K8K  s   A 	AAc                    t        |       }|st        d|  dt        j                         |r^t	               r?t        |       t        j                  dddj                  t                      dz          nt        j                  d       t        t        t        j                        |       t        j                  dt        j                          y	)
z|Set the active access token.

    Args:
        token_name (`str`):
            The name of the token to set as active.
    zToken r;   zCYour token has been saved in your configured git credential helpersz (,r   z2Token has not been saved to git credential helper.zYour token has been saved to N)r   r<   r   r3   $_is_git_credential_helper_configuredr   r&   r'   joinr   r)   r   r   r2   )r/   r    r"   s      r,   r=   r=     s     z*E6*^I<[<[;\]^^/1u%KKUsxx 7 9:;2>?
 NNOP$y../7
KK/	0G0G/HIJr.   c                      t               } t        |       dkD  ryt               rt                yt	        t        j                  d             y)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_globallyrV   r	   red)helperss    r,   r   r     sL     &'G
7|a 46 
	

 r.   c                  |    	 t        d       y# t        j                  $ r} t        | j                        d} ~ ww xY 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CalledProcessErrorr7   stderr)excs    r,   r   r      s5    "DE(( "cjj!!"s    ;6;)N)F)r#   N)NN)@__doc__r   r   r   r   rr   r   r   pathlibr   rN   r   errorsr   utilsr	   r
   r   r   r   r   r   r   r   r   r   utils._authr   r   r   r   r   r   r   r   r   utils._oauth_devicer   r   r   
get_logger__name__r&   r   boolr-   r9   r?   r^   rl   tupleri   rs   r+   r{   r|   r*   rq   r(   r6   rU   r=   r   r   rC   r.   r,   <module>r      s   -  	  
      #   
 
 
 \ [ 
		H	% <? #("	<?:<?  <? 	<?
 
<?~'
sTz '
T '
T
C 
 
 
:%
Z $  2  uS#X  K1 KcDj K  48 D D 81c 1G 15 91 91 91H !%!	3 3 3  :3  d
	3 
 38_3 l>3 >4 >(	L3: 	L# 	LKKK 
K6d >"r.   