
    gjO                     4   U 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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 d	d
lmZ d	dlmZ d	dlmZmZ dZdZdededdfdZda e
            Zda edz  e!d<    ej"        e#          Z$dedz  fdZ%dedz  fdZ&dedz  fdZ'dedz  fdZ( G d de          Z) e
            Z*da+e)dz  e!d<   dZ,dedz  fdZ- G d de          Z. e
            Z/da0e.dz  e!d <   d!Z1dZ2da3dedz  fd"Z4d#edefd$Z5d%eddfd&Z6d'e7eef         de8dz  fd(Z9de7eef         fd)Z:de7ee7eef         f         fd*Z;d+e7ee7eef         f         ddfd,Z<d-ededz  fd.Z=ddd/d#ed-ed0edz  d1e8dz  ddf
d2Z>d#edz  dedz  fd3Z?dS )4zVContains a helper to get the token from machine (env variable, secret or config file).    N)Path)Lock)	TypedDict   )	constants)DeviceCodeErrorOAuthErrorCode	OIDCError   )WeakFileLock)refresh_access_token)is_colab_enterpriseis_google_colabi  i  pathcontentreturnc                 
   | j                             ddt                     t          j        t          |           t          j        t          j        z  t          j        z  t                    }t          j
        |d          5 }|                    |           ddd           n# 1 swxY w Y   	 |                     t                     | j                             t                     dS # t          t          f$ r Y dS w xY w)ziWrite content to file, restricting both the file and its parent directory to owner-only on POSIX systems.T)parentsexist_okmodewN)parentmkdir_SECRET_DIR_MODEosopenstrO_WRONLYO_CREATO_TRUNC_SECRET_FILE_MODEfdopenwritechmodOSErrorNotImplementedError)r   r   fdfs       _/var/www/app.qaans.com/backend/venv/lib/python3.11/site-packages/huggingface_hub/utils/_auth.py_write_secretr*   %   s   KdT8HIII	TBK"*4rzACT	U	UB	2s		 q	              

$%%%*+++++()   s$   B&&B*-B*29C- -DDF_GOOGLE_COLAB_SECRETc                  r    t                      p)t                      pt                      pt                      S )a]  
    Get token if user is logged in.

    Note: in most cases, you should use [`huggingface_hub.utils.build_hf_headers`] instead. This method is only useful
          if you want to retrieve the token for other purposes than sending an HTTP request.

    If `HF_OIDC_RESOURCE` is set (Trusted Publishers, typically in CI), a short-lived token obtained via OIDC token
    exchange takes precedence. Otherwise the token is retrieved from the `HF_TOKEN` environment variable, then from the
    token file in the Hugging Face home folder. Returns None if user is not logged in. To log in, use [`login`] or
    `hf auth login`.

    OAuth tokens obtained with the browser-based login come with a refresh token: when such a token is close to
    expiry, it is transparently refreshed and persisted before being returned.

    Note: if `HF_OIDC_RESOURCE` is set but the OIDC token exchange fails, this raises instead of returning `None`,
    opting into OIDC is explicit, so a failure surfaces as a clear error rather than a silent fallback.

    Returns:
        `str` or `None`: The token, `None` if it doesn't exist.
    )_get_token_from_oidc_get_token_from_environment_get_token_from_file_refreshed_get_token_from_google_colab     r)   	get_tokenr3   :   s>    , 	 	*&((	*)++	* ())	r2   c                  h   t                      rt                      rdS t          5  t          rt          cddd           S 	 ddlm}  ddlm} n# t          $ r Y ddd           dS w xY w	 | 
                    d          }t          |          an# | j        $ r t          j        d           daY n_| j        $ r t                               d           daY n8|$ r1}t          j        dt%          |           d	           daY d}~nd}~ww xY wd
at          cddd           S # 1 swxY w Y   dS )zGet token from Google Colab secrets vault using `google.colab.userdata.get(...)`.

    Token is read from the vault only once per session and then stored in a global variable to avoid re-requesting
    access to the vault.
    Nr   )userdata)ErrorHF_TOKENz
Access to the secret `HF_TOKEN` has not been granted on this notebook.
You will not be requested again.
Please restart the session if you want to be prompted again.zThe secret `HF_TOKEN` does not exist in your Colab secrets. Run `huggingface_hub.login()` to authenticate (recommended but still optional to access public models or datasets).z@
Error while fetching `HF_TOKEN` secret value from your vault: 'z'.
You are not authenticated with the Hugging Face Hub in this notebook.
If the error persists, please let us know by opening an issue on GitHub (https://github.com/huggingface/huggingface_hub/issues/new).T)r   r   _GOOGLE_COLAB_SECRET_LOCK_IS_GOOGLE_COLAB_CHECKEDr+   google.colabr5   google.colab.errorsr6   ImportErrorget_clean_tokenNotebookAccessErrorwarningswarnSecretNotFoundErrorloggerinfor   )r5   
ColabErrortokenes       r)   r0   r0   W   sY      3 5 5 t 
# -$ -$ $ 	('-$ -$ -$ -$ -$ -$ -$ -$	------??????? 	 	 	-$ -$ -$ -$ -$ -$ -$ -$		(LL,,E#/#6#6  + 	( 	( 	( MQ  
 $(   + 	( 	( 	( KKf   $(    	( 	( 	(MOTWXYTZTZ O O O   $(      	( $( #[-$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$ -$sw   D'AD'
A(D''A((D',$BD' D1D'3%DD'D'D
D'
DD''D+.D+c                      t          t          j                            d          pt          j                            d                    S )Nr7   HUGGING_FACE_HUB_TOKEN)r>   r   environr=   r1   r2   r)   r.   r.      s2    
z22^bjnnE]6^6^___r2   c                      	 t          t          t          j                                                            S # t
          $ r Y d S w xY w)N)r>   r   r   HF_TOKEN_PATH	read_textFileNotFoundErrorr1   r2   r)   _get_token_from_filerO      sN    D!899CCEEFFF   tts   7: 
AAc                   .    e Zd ZU eed<   eed<   eed<   dS )_OidcTokenCacheresourcerF   
expires_atN__name__
__module____qualname__r   __annotations__floatr1   r2   r)   rQ   rQ      s0         MMMJJJr2   rQ   _OIDC_TOKEN_CACHEi,  c                  z   t           j                            d          } | sdS ddlm}m} t          5  t          j                    }t          ;t          d         | k    r*|t          d         k     rt          d         cddd           S t           j                            d          pd}| |            t          d	           || |
          }|d         }t          |                    dd                    }|dnt          }| ||t          ||z
  d          z   da	|cddd           S # 1 swxY w Y   dS )a  Get a short-lived OIDC token in CI (Trusted Publishers).

    Enabled by setting `HF_OIDC_RESOURCE`, which scopes the token to a repo or user.
    The ID token is read from `HF_OIDC_ID_TOKEN` if available, or minted from a supported CI provider (e.g. GitHub Actions).

    Returns `None` when OIDC is not enabled.
    If enabled, any failure is raised explicitly rather than falling back silently.

    See `huggingface_hub._oidc` and https://huggingface.co/docs/hub/trusted-publishers.
    HF_OIDC_RESOURCENr   )detect_provider
oidc_loginrR   rS   rF   HF_OIDC_ID_TOKENzHF_OIDC_RESOURCE is set but no OIDC id token is available: not running in a supported CI provider (github) and HF_OIDC_ID_TOKEN is not set. Set HF_OIDC_ID_TOKEN to the id token minted by your CI provider, or unset HF_OIDC_RESOURCE.)rR   subject_tokenaccess_token
expires_ini  r   )rR   rF   rS   )r   rJ   r=   _oidcr]   r^   _OIDC_TOKEN_LOCKtime	monotonicrZ   r
   int_OIDC_REFRESH_MARGINmax)	rR   r]   r^   nowr`   resultrF   rb   margins	            r)   r-   r-      s    z~~011H t33333333 
  n)!*-99'555$W-        
'9::Bd __%6%6%>O   X]KKK~&L$7788
 $/5I J$7 ; ;;
 

 =                 s   A	D0	BD00D47D4c                   .    e Zd ZU eed<   eed<   eed<   dS )_OAuthRefreshCache
file_tokenresolved_token
recheck_atNrT   r1   r2   r)   rn   rn      s3         OOOr2   rn   _OAUTH_REFRESH_CACHEiQ c                  D    t                      } | dS t          |           S )zSGet the token from `HF_TOKEN_PATH`, transparently refreshing it if close to expiry.N)rO   _refresh_oauth_token_if_neededrF   s    r)   r/   r/      s%     ""E}t)%000r2   rF   c           	          t           5  t          j                    }t          }|,|d          k    r ||d         k     r|d         cddd           S t           fdt	                                                      D             di f          \  }}|                    d          }t          |          }|||@t                      }|| k    r|cddd           S   |t          z   da cddd           S |t          z
  |k    r  |t          z
  da cddd           S 	 t          t          j        dz   d	
          5  t	                                          |i           }|                    d           k    r'|                    d          p }t          |          }	nt          |          }
|
d         }d|
v r%t          |          t          |
d                   z   nd}	t!          |||
                    d          p||	           t                       k    r't#          t%          t          j                  |           t(                              d| d           ddd           n# 1 swxY w Y   n# t,          $ r}t/          |t0                    rC|j        t4          j        k    r.t(                              d| d           t;          d          }nt=          d| d           |t          z   }  |da cY d}~cddd           S d}~ww xY w||t?          |t          z   |	r
|	t          z
  nd          da|cddd           S # 1 swxY w Y   dS )a  Refresh an OAuth access token if it is close to expiry. Best-effort: never raises.

    OAuth tokens obtained with the browser-based login are stored with a `refresh_token` and an
    `expires_at` timestamp (see `_save_token`). When the active token is one of them and about to
    expire, exchange the refresh token for a new access token and persist it. Any other token is
    returned unchanged.
    Nro   rq   rp   c              3   X   K   | ]$\  }}|                     d           k    ||fV  %dS )hf_tokenNr=   ).0namefieldsrF   s      r)   	<genexpr>z1_refresh_oauth_token_if_needed.<locals>.<genexpr>	  sF      vvfV\V`V`akVlVlpuVuVudF^VuVuVuVuvvr2   refresh_token)ro   rp   rq   z.lock   )timeoutrx   ra   rb   )rF   
token_namer~   rS   zAccess token `z` has been refreshed.zYour Hugging Face access token has expired and could not be refreshed (session expired or revoked). Run `hf auth login` to re-authenticate. ()infz2Could not refresh your Hugging Face access token: z. Will retry later.r   ) _OAUTH_REFRESH_LOCKre   rr   next_read_stored_tokens_fullitemsr=   _parse_expires_atrO   _OAUTH_RECHECK_INTERVAL_OAUTH_REFRESH_MARGINr   r   HF_STORED_TOKENS_PATHr   rg   _save_tokenr*   r   rL   rC   rD   	Exception
isinstancer   
error_coder	   INVALID_GRANTwarningrY   _warn_refresh_failure_onceri   )rF   rj   cacher   r|   r~   rS   current_file_token	new_tokennew_expires_atresponserG   rq   s   `            r)   rt   rt      sZ    
 W Wikk$|!4!=!=#lH[B[B[)*	W W W W W W W W "vvvv0H0J0J0P0P0R0Rvvv2J
 

F 

?33&v..
!6*:L "6!7!7!-2D2M2M)#W W W W W W W W( $"'!$;;$ $ 
 1W W W W W W W W4 --33#"'(+@@$ $ 
 AW W W W W W W WD)	 i=GQSTTT T T13377
BGG::j))U22 &

: 6 6 ?%I%6v%>%>NN3MBBH ( 8IO[_gOgOgSXXH\4J0K0K%K%KmqN'#-&.ll?&C&C&T}#1    ,--66%d9+B&C&CYOOOKK R R R RSSS+T T T T T T T T T T T T T T T,  	 	 	!_-- ;!,.B^2^2^ c^_c c c   #5\\

 ++v`a+v+v+vwww #::
275`j#k#k LLLLLWW W W W W W W Wv	& $' --:HO!666a 	 
 	 
 oW W W W W W W W W W W W W W W W W Wsz   <MB MM;M&J D$I4(J 4I8	8J ;I8	<J ?M 
L
A<LLML,MMMmessagec                 P    t           st                              |            da d S d S )NT)_OAUTH_REFRESH_WARNEDrC   r   )r   s    r)   r   r   \  s2      %w $% %r2   r|   c                 ^    	 t          | d                   S # t          t          f$ r Y dS w xY w)zVParse the `expires_at` field of a stored-tokens section, `None` if missing or corrupt.rS   N)rg   KeyError
ValueError)r|   s    r)   r   r   c  sA    6,'(((j!   tts    ,,c                  V    d t                                                      D             S )aA  
    Returns the parsed INI file containing the access tokens.
    The file is located at `HF_STORED_TOKENS_PATH`, defaulting to `~/.cache/huggingface/stored_tokens`.
    If the file does not exist, an empty dictionary is returned.

    Returns: `dict[str, str]`
        Key is the token name and value is the token.
    c                 B    i | ]\  }}||                     d d          S )rx    ry   )rz   r   r|   s      r)   
<dictcomp>z%get_stored_tokens.<locals>.<dictcomp>t  s-    ppp7Iz6J

:r22pppr2   )r   r   r1   r2   r)   get_stored_tokensr   k  s,     qpMeMgMgMmMmMoMoppppr2   c                  n   t          t          j                  } |                                 si S t	          j        d          	                     |            fd                                D             S # t          j        $ r)}t          
                    d|            i cY d}~S d}~ww xY w)zRead all sections of the stored tokens INI file, with all their fields.

    Beside `hf_token`, sections for OAuth tokens also carry `refresh_token` and `expires_at`
    (unix timestamp), used by [`get_token`] to transparently refresh them.
    Ninterpolationc                 V    i | ]%}|t                              |                    &S r1   )dictr   )rz   r   configs     r)   r   z,_read_stored_tokens_full.<locals>.<dictcomp>  s/    ___z
Dj!9!9::___r2   z"Error parsing stored tokens file: )r   r   r   existsconfigparserConfigParserreadsectionsr6   rC   error)tokens_pathrG   r   s     @r)   r   r   w  s     y677K 	&T:::FK   ____V__M^M^____   =!==>>>						s   4A< <B4B/)B4/B4stored_tokensc                    t          j        d          }t          |                                           D ]N}|                    |           | |                                         D ]\  }}|                    |||           Ot          j                    }|	                    |           t          t          t          j                  |                                           dS )zBWrite all sections and their fields to the stored tokens INI file.Nr   )r   r   sortedkeysadd_sectionr   setioStringIOr#   r*   r   r   r   getvalue)r   r   r   keyvaluebufs         r)   _save_stored_tokens_fullr     s    &T:::F]//1122 / /
:&&&'
399;; 	/ 	/JCJJz3....	/ +--C
LL$y677HHHHHr2   r   c                 T    t                      }| |vrdS t          ||                    S )z
    Get the token by name.

    Args:
        token_name (`str`):
            The name of the token to get.

    Returns:
        `str` or `None`: The token, `None` if it doesn't exist.

    N)r   r>   )r   r   s     r)   _get_token_by_namer     s2     &''M&&tj1222r2   )r~   rS   r~   rS   c                    t                      }d| i}|||d<   |t          |          |d<   |||<   t          |           t                              d| dt
          j                    dS )a  
    Save the given token.

    If the stored tokens file does not exist, it will be created.
    Args:
        token (`str`):
            The token to save.
        token_name (`str`):
            The name of the token.
        refresh_token (`str`, *optional*):
            OAuth refresh token used to renew the access token when it expires.
        expires_at (`int`, *optional*):
            Unix timestamp at which the access token expires.
    rx   Nr~   rS   zThe token `z` has been saved to )r   r   r   rC   rD   r   r   )rF   r   r~   rS   r   r|   s         r)   r   r     s    " -..M% F "/":| &M*]+++
KK_j__i>]__`````r2   c                     | dS |                      dd                               dd                                          pdS )zuClean token by removing trailing and leading spaces and newlines.

    If token is an empty string, return None.
    Nr   
)replacestripru   s    r)   r>   r>     sC    
 }t==r""**444::<<DDr2   )@__doc__r   r   loggingr   re   r@   pathlibr   	threadingr   typingr   r   r   errorsr   r	   r
   _fixesr   _oauth_devicer   _runtimer   r   r!   r   r   r*   r9   r8   r+   rX   	getLoggerrU   rC   r3   r0   r.   rO   rQ   rd   rZ   rh   r-   rn   r   rr   r   r   r   r/   rt   r   r   rg   r   r   r   r   r   r   r>   r1   r2   r)   <module>r      s   ] \ \     				  				                           ? ? ? ? ? ? ? ? ? ?             / / / / / / : : : : : : : :    s t     !  DFF #' cDj ' ' '		8	$	$3:    :<$cDj <$ <$ <$ <$~`S4Z ` ` ` `
cDj        i    466 ,0 ?T) 0 0 0 0cDj 0 0 0 0f        dff 26 (4/ 6 6 6!   1d
 1 1 1 1`# `# ` ` ` `F% % % % % %d38n t    	q4S> 	q 	q 	q 	q$sDcN':";    &
IDd38n1D,E 
I$ 
I 
I 
I 
I33 33: 3 3 3 3& AE_ca a aaa36:aRUX\R\a	a a a a:Ed
 EsTz E E E E E Er2   