
    IThc                        % S r SSKrSSKrSSKrSSKrSSKrSSKrSSKJr  SSK	J
r
  SSKJr  SSKJrJrJrJrJrJrJr  SSKrSSKJrJr  SSKJr  SS	KJr  SS
KJr  SSKJr  SSK J!r!J"r"J#r#J$r$J%r%J&r&J'r'  SSKJ(r(  SSK)J*r*  SSK+J,r,  SSK-J.r.  \(R^                  " \05      r1Sr2Sr3\Rh                  " S\Rj                  S9r6 " S S\5      r7 " S S\5      r8S\Rr                  4S jr:\/ \Rr                  4   r;\:q<\;\=S'   \:4S\;SS4S jjr>S\Rr                  4S  jr?S?S! jr@\S"\AS#\AS\Rr                  4S$ j5       rBS%SS&\R                  \R                  4\
R                  S'.S(\.S)\FS*\AS+\GS,\GS-\\\H   \\\H   S.4   4   S/\\A\\AS.4   4   S\4S0 jjrIS)\FS1\\F   S\F4S2 jrJS@S3\S4\\F   SS4S5 jjrKS6\\%   S7\FS3\S\%4S8 jrLS9\R6                  S\F4S: jrM\Rh                  " S;\R                  5      rOS<\\F   S=\AS\\F   4S> jrPg)Az>Contains utilities to handle HTTP requests in Huggingface Hub.    N)	lru_cache)
HTTPStatus)quote)AnyCallableListOptionalTupleTypeUnion)	HTTPErrorResponse)HTTPAdapter)PreparedRequest)OfflineModeIsEnabled   )	constants)BadRequestErrorDisabledRepoErrorEntryNotFoundErrorGatedRepoErrorHfHubHTTPErrorRepositoryNotFoundErrorRevisionNotFoundError   )logging)JSONDecodeError)SliceFileObj)HTTP_METHOD_TX-Amzn-Trace-Idzx-request-ida  
        # staging or production endpoint
        ^https://[^/]+
        (
            # on /api/repo_type/repo_id
            /api/(models|datasets|spaces)/(.+)
            |
            # or /repo_id/resolve/revision/...
            /(.+)/resolve/(.+)
        )
    )flagsc                   D   ^  \ rS rSrSrU 4S jrS\S\4U 4S jjrSr	U =r
$ )UniqueRequestIdAdapterK   r    c                   > [         TU ]  " U40 UD6  [        UR                  ;  aU  UR                  R	                  [
        5      =(       d    [        [        R                  " 5       5      UR                  [        '   [        [        UR                  R	                  SS5      5      5      S:  n[        R                  SUR                  [            SUR                   SUR                   SU S3	5        g )	Nauthorization r   zRequest z:  z (authenticated: ))superadd_headersX_AMZN_TRACE_IDheadersgetX_REQUEST_IDstruuiduuid4lenloggerdebugmethodurl)selfrequestkwargs	has_token	__class__s       S/var/www/auris/envauris/lib/python3.13/site-packages/huggingface_hub/utils/_http.pyr+   "UniqueRequestIdAdapter.add_headersN   s    G.v. '//1/6/B/B</P/eTWX\XbXbXdTeGOOO, GOO//DEFJ	w787>>:J!GKK=Xijsittuv	
    r9   returnc                 L  > [         R                  (       a!  [        R                  S[	        U5       35         [
        TU ]  " U/UQ70 UD6$ ! [        R                   aB  nUR                  R                  [        5      nUb  / UR                  QSU S3P7Ul        e SnAff = f)zSCatch any RequestException to append request id to the error message for debugging.zSend: Nz(Request ID: r)   )r   HF_DEBUGr4   r5   _curlifyr*   sendrequestsRequestExceptionr-   r.   r,   args)r8   r9   rG   r:   e
request_idr<   s         r=   rD   UniqueRequestIdAdapter.send[   s    LL6(7"3!456	7<9$9&99(( 	 ,,_=J%A166A]:,a#@A	s   A B#!=BB# )__name__
__module____qualname____firstlineno__r,   r+   r   r   rD   __static_attributes____classcell__)r<   s   @r=   r#   r#   K   s%    'O
O   r?   r#   c                   &    \ rS rSrS\S\4S jrSrg)OfflineAdapteri   r9   r@   c                 4    [        SUR                   S35      e)NzCannot reach za: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable.)r   r7   )r8   r9   rG   r:   s       r=   rD   OfflineAdapter.sendj   s&    "GKK=  )J  K
 	
r?   rK   N)rL   rM   rN   rO   r   r   rD   rP   rK   r?   r=   rS   rS   i   s    
O 
 
r?   rS   r@   c                  .   [         R                  " 5       n [        R                  (       a6  U R	                  S[        5       5        U R	                  S[        5       5        U $ U R	                  S[        5       5        U R	                  S[        5       5        U $ )Nzhttp://zhttps://)rE   Sessionr   HF_HUB_OFFLINEmountrS   r#   )sessions    r=   _default_backend_factoryr\   p   sm     Gi!12j."23 N 	i!7!9:j"8":;Nr?   _GLOBAL_BACKEND_FACTORYbackend_factoryc                     U q [        5         g)ao  
Configure the HTTP backend by providing a `backend_factory`. Any HTTP calls made by `huggingface_hub` will use a
Session object instantiated by this factory. This can be useful if you are running your scripts in a specific
environment requiring custom configuration (e.g. custom proxy or certifications).

Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
`huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.

See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.

Example:
```py
import requests
from huggingface_hub import configure_http_backend, get_session

# Create a factory function that returns a Session with configured proxies
def backend_factory() -> requests.Session:
    session = requests.Session()
    session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
    return session

# Set it as the default session factory
configure_http_backend(backend_factory=backend_factory)

# In practice, this is mostly done internally in `huggingface_hub`
session = get_session()
```
N)r]   reset_sessions)r^   s    r=   configure_http_backendra      s    @ .r?   c                  b    [        [        R                  " 5       [        R                  " 5       S9$ )a  
Get a `requests.Session` object, using the session factory from the user.

Use [`get_session`] to get a configured Session. Since `requests.Session` is not guaranteed to be thread-safe,
`huggingface_hub` creates 1 Session instance per thread. They are all instantiated using the same `backend_factory`
set in [`configure_http_backend`]. A LRU cache is used to cache the created sessions (and connections) between
calls. Max size is 128 to avoid memory leaks if thousands of threads are spawned.

See [this issue](https://github.com/psf/requests/issues/2766) to know more about thread-safety in `requests`.

Example:
```py
import requests
from huggingface_hub import configure_http_backend, get_session

# Create a factory function that returns a Session with configured proxies
def backend_factory() -> requests.Session:
    session = requests.Session()
    session.proxies = {"http": "http://10.10.1.10:3128", "https": "https://10.10.1.11:1080"}
    return session

# Set it as the default session factory
configure_http_backend(backend_factory=backend_factory)

# In practice, this is mostly done internally in `huggingface_hub`
session = get_session()
```

process_id	thread_id)_get_session_from_cacheosgetpid	threading	get_identrK   r?   r=   get_sessionrk      s     : #biikYEXEXEZ[[r?   c                  ,    [         R                  5         g)zReset the cache of sessions.

Mostly used internally when sessions are reconfigured or an SSLError is raised.
See [`configure_http_backend`] for more details.
N)rf   cache_clearrK   r?   r=   r`   r`      s     '')r?   rd   re   c                     [        5       $ )z
Create a new session per thread using global factory. Using LRU cache (maxsize 128) to avoid memory leaks when
using thousands of threads. Cache is cleared when `configure_http_backend` is called.
)r]   rc   s     r=   rf   rf      s     #$$r?         )max_retriesbase_wait_timemax_wait_timeretry_on_exceptionsretry_on_status_codesr6   r7   rq   rr   rs   rt   .ru   c          	      X   [        U[        5      (       a  U4n[        U[        5      (       a  U4nSnUn	Sn
SU;   a;  [        US   [        R                  [
        45      (       a  US   R                  5       n
[        5       n US-  n U
b  US   R                  U
5        UR                  " SXS.UD6nUR                  U;  a  U$ [        R                  SUR                   SU  SU 35        X:  a  UR                  5         U$  [        R                  SU	 SU SU S35        ["        R$                  " U	5        ['        XIS-  5      n	M  ! U aX  n[        R                  S	U S
U  SU 35        [        U[        R                  5      (       a
  [!        5         X:  a  Ue SnANSnAff = f)ag
  Wrapper around requests to retry calls on an endpoint, with exponential backoff.

Endpoint call is retried on exceptions (ex: connection timeout, proxy error,...)
and/or on specific status codes (ex: service unavailable). If the call failed more
than `max_retries`, the exception is thrown or `raise_for_status` is called on the
response object.

Re-implement mechanisms from the `backoff` library to avoid adding an external
dependencies to `hugging_face_hub`. See https://github.com/litl/backoff.

Args:
    method (`Literal["GET", "OPTIONS", "HEAD", "POST", "PUT", "PATCH", "DELETE"]`):
        HTTP method to perform.
    url (`str`):
        The URL of the resource to fetch.
    max_retries (`int`, *optional*, defaults to `5`):
        Maximum number of retries, defaults to 5 (no retries).
    base_wait_time (`float`, *optional*, defaults to `1`):
        Duration (in seconds) to wait before retrying the first time.
        Wait time between retries then grows exponentially, capped by
        `max_wait_time`.
    max_wait_time (`float`, *optional*, defaults to `8`):
        Maximum duration (in seconds) to wait before retrying.
    retry_on_exceptions (`Type[Exception]` or `Tuple[Type[Exception]]`, *optional*):
        Define which exceptions must be caught to retry the request. Can be a single type or a tuple of types.
        By default, retry on `requests.Timeout` and `requests.ConnectionError`.
    retry_on_status_codes (`int` or `Tuple[int]`, *optional*, defaults to `503`):
        Define on which status codes the request must be retried. By default, only
        HTTP 503 Service Unavailable is retried.
    **kwargs (`dict`, *optional*):
        kwargs to pass to `requests.request`.

Example:
```
>>> from huggingface_hub.utils import http_backoff

# Same usage as "requests.request".
>>> response = http_backoff("GET", "https://www.google.com")
>>> response.raise_for_status()

# If you expect a Gateway Timeout from time to time
>>> http_backoff("PUT", upload_url, data=data, retry_on_status_codes=504)
>>> response.raise_for_status()
```

<Tip warning={true}>

When using `requests` it is possible to stream data by passing an iterator to the
`data` argument. On http backoff this is a problem as the iterator is not reset
after a failed call. This issue is mitigated for file objects or any IO streams
by saving the initial position of the cursor (with `data.tell()`) and resetting the
cursor between each call (with `data.seek()`). For arbitrary iterators, http backoff
will fail. If this is a hard constraint for you, please let us know by opening an
issue on [Github](https://github.com/huggingface/huggingface_hub).

</Tip>
r   Ndatar   )r6   r7   zHTTP Error z thrown while requesting r(   'z' thrown while requesting zRetrying in z	s [Retry /z].r   rK   )
isinstancetypeintioIOBaser   tellrk   seekr9   status_coder4   warningraise_for_statusrE   ConnectionErrorr`   timesleepmin)r6   r7   rq   rr   rs   rt   ru   r:   nb_tries
sleep_timeio_obj_initial_posr[   responseerrs                 r=   http_backoffr      s   N %t,,24'--!6 8HJ
 Jvf~		<7PQQ#F^002mG
A	 "-v##$67 HfHHH##+@@ NN[)=)=(>>WX^W__`ad`efg%))+  	 &  	j\8*Ak]RTUV

: Q7
G * # 	NNQse#=fXQseLM#x7788 %	 &	s   	<E >E F)AF$$F)endpointc                    U(       a  UR                  S5      O[        R                  nU[        R                  [        R                  4;  a@  U R                  [        R                  U5      n U R                  [        R                  U5      n U $ )zReplace the default endpoint in a URL by a custom one.

This is useful when using a proxy and the Hugging Face Hub returns a URL with the default endpoint.
ry   )rstripr   ENDPOINT_HF_DEFAULT_ENDPOINT_HF_DEFAULT_STAGING_ENDPOINTreplace)r7   r   s     r=   fix_hf_endpoint_in_urlr   S  sf    
 (0xs#Y5G5GH	66	8^8^__kk)88(Ckk)@@(KJr?   r   endpoint_namec                     U R                  5         g! [         Ga  nU R                  R                  S5      nU R                  R                  S5      nUS:X  a4  U R                   S3S-   SU R
                   S3-   n[        [        XP5      UeUS:X  a4  U R                   S3S-   S	U R
                   S3-   n[        [        XP5      UeUS
:X  a4  U R                   S3S-   SU R
                   S3-   n[        [        XP5      UeUS:X  a:  U R                   S3S-   SU R
                   S3-   S-   S-   n[        [        XP5      UeUS:X  dd  U R                  S:X  a  US:w  a  U R                  bx  U R                  R
                  ba  [        R                  U R                  R
                  5      b7  U R                   S3S-   SU R
                   S3-   S-   n[        [        XP5      UeU R                  S:X  a  Ub  SU S3OSn[        [        XP5      UeU R                  S:X  a8  SU R                   SU S3SU R
                   S3-   S-   n[        [         XP5      UeU R                  S:X  aZ  U R                  R                  R                  S5      nU SU S U R                  R                  S!5       S3n[        [         XP5      Ue[        [         [#        U5      U 5      UeSnAff = f)"a  
    Internal version of `response.raise_for_status()` that will refine a
    potential HTTPError. Raised exception will be an instance of `HfHubHTTPError`.

    This helper is meant to be the unique method to raise_for_status when making a call
    to the Hugging Face Hub.


    Example:
    ```py
        import requests
        from huggingface_hub.utils import get_session, hf_raise_for_status, HfHubHTTPError

        response = get_session().post(...)
        try:
            hf_raise_for_status(response)
        except HfHubHTTPError as e:
            print(str(e)) # formatted message
            e.request_id, e.server_message # details returned by server

            # Complete the error message with additional information once it's raised
            e.append_to_message("
`create_commit` expects the repository to exist.")
            raise
    ```

    Args:
        response (`Response`):
            Response from the server.
        endpoint_name (`str`, *optional*):
            Name of the endpoint that has been called. If provided, the error message
            will be more complete.

    <Tip warning={true}>

    Raises when the request has failed:

        - [`~utils.RepositoryNotFoundError`]
            If the repository to download from cannot be found. This may be because it
            doesn't exist, because `repo_type` is not set correctly, or because the repo
            is `private` and you do not have access.
        - [`~utils.GatedRepoError`]
            If the repository exists but is gated and the user is not on the authorized
            list.
        - [`~utils.RevisionNotFoundError`]
            If the repository exists but the revision couldn't be find.
        - [`~utils.EntryNotFoundError`]
            If the repository exists but the entry (e.g. the requested file) couldn't be
            find.
        - [`~utils.BadRequestError`]
            If request failed with a HTTP 400 BadRequest error.
        - [`~utils.HfHubHTTPError`]
            If request failed for a reason not listed above.

    </Tip>
    zX-Error-CodeX-Error-MessageRevisionNotFoundz Client Error.

zRevision Not Found for url: .EntryNotFoundzEntry Not Found for url: 	GatedRepoz!Cannot access gated repo for url z$Access to this resource is disabled.z!Cannot access repository for url 
RepoNotFoundi  z+Invalid credentials in Authorization headerNzRepository Not Found for url: z
Please make sure you specified the correct `repo_id` and `repo_type`.
If you are trying to access a private or gated repo, make sure you are authenticated. For more details, see https://huggingface.co/docs/huggingface_hub/authenticationi  z

Bad request for z
 endpoint:z

Bad request:i  z Forbidden: z
Cannot access content at: z2
Make sure your token has the correct permissions.i  Rangez. Requested range: z. Content-Range: zContent-Range)r   r   r-   r.   r   r7   _formatr   r   r   r   r9   REPO_API_REGEXsearchr   r   r   r0   )r   r   rH   
error_codeerror_messagemessagerange_headers          r=   hf_raise_for_statusr   `  sV   pJ?!!# H?%%)).9
 ((,,->?++!--.n=FKghphthtguuvIwwG/CJ?*!--.n=FKdemeqeqdrrsIttG,g@aG;&''(7&@EfgogsgsfttuCvv  .'<!CDD''(75hll^1EF  9	9  +W?QF>)  C'!NN  ,  $$0%%h&6&6&:&:;G ''(728<<.BCNN  17E1L!!S(DQD]&}oZ@cu  /7=1D!!S(x++,LqI0a@AGH 
 .'<!C!!S(#++3377@L.|n<MhN^N^NbNbcrNsMttuvG.'<!C nc!fh7Q>QH?s    K!J>KK!
error_typecustom_messagec                    / nUR                   R                  S5      nUb  UR                  U5         UR                  5       nUR                  S5      nUb8  [	        U[
        5      (       a  UR                  U5        OUR                  U5        UR                  S5      nUb%  U H  nSU;   d  M  UR                  US   5        M!     U V	s/ s H<  n	[        U	5      R                  5       (       d  M#  [        U	5      R                  5       PM>     nn	[        [        R                  U5      5      nSR                  U5      n
UnU
(       a9  U
R                  5       UR                  5       ;  a  S	U;   a	  USU
-   -  nOUS	U
-   -  n[        UR                   R                  [        S5      5      nU(       a  S
U S3nO6[        UR                   R                  [         S5      5      nU(       a  SU S3nU(       aL  UR                  5       UR                  5       ;  a*  SU;   a  UR#                  S5      nUS U W-   XS  -   nOUW-  nU " UR                  5       X*=(       d    S S9$ ! [         a`    UR                   R                  SS5      nUR                  (       a/  SUR                  5       ;  a  UR                  UR                  5         GNf = fs  sn	f )Nr   errorerrorsr   zContent-Typer'   htmlr   r   z (Request ID: r)   z (Amzn Trace ID: )r   server_message)r-   r.   appendjsonrz   listextendr   textlowerr0   stripdictfromkeysjoinr/   r,   index)r   r   r   server_errorsfrom_headersrw   r   r   content_typeliner   final_error_messagerI   request_id_messagenewline_indexs                  r=   r   r     s   M ##''(9:L\*0}}!%&&$$U+ $$U+(#%!((y)9:   4AV=4CIOODU&SY__&=MV }56M YY}-N )...08L8L8NN^#4.#886N#::X%%)),;<J-j\; ))--orBC
#4ZL!Bj&&(0C0I0I0KK&&/55d;M#N]36HHK^_mKnn    #55 )//1HUkgkllU  0''++NB?==V<+=+=+??  /	0 Ws%   A9I  0I  "K2K A&K
	K
r9   c                    SSU R                   4/n[        U R                  R                  5       5       H2  u  p#UR	                  5       S:X  a  SnUSSR                  X#5      4/-  nM4     U R                  (       at  U R                  n[        U[        5      (       a  UR                  SSS	9nO[        US
5      (       a  Sn[        U5      S:  a  USS S-   nUSUR                  SS5      4/-  nUSU R                  4/-  n/ nU HI  u  p#U(       a  UR                  [        U5      5        U(       d  M/  UR                  [        U5      5        MK     SR!                  U5      $ )zConvert a `requests.PreparedRequest` into a curl command (str).

Used for debug purposes only.

Implementation vendored from https://github.com/ofw/curlify/blob/master/curlify.py.
MIT License Copyright (c) 2016 Egor.
)curlNz-Xr&   z<TOKEN>z-Hz{0}: {1}zutf-8ignore)r   readz<file-like object>i  Nz ... [truncated]z-dr   r'   r(   )r6   sortedr-   itemsr   formatbodyrz   bytesdecodehasattrr3   r   r7   r   r   r   )r9   partskvr   
flat_partss         r=   rC   rC   /  sK    		w~~$E
 w,,./779'A4**10122 0
 ||||dE"";;wx;8DT6""'Dt9t;!33D4dB/011	tW[[!""EJeAh'1eAh'	  88Jr?   z%^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$original_rangeresume_sizec                    U (       d  SU S3$ SU ;   a  [        SU < S35      e[        R                  U 5      nU(       d  [        SU < S35      eUR	                  5       u  p4U(       dB  U(       d  [        SU < S35      e[        U5      U-
  nSU 3nUS	::  a  [        S
U< S35      eU$ [        U5      nX1-   nU(       a*  [        U5      nSU SU 3nXt:  a  [        S
U< S35      eU$ SU S3$ )z:
Adjust HTTP Range header to account for resume position.
zbytes=-,zMultiple ranges detected - z, not supported yet.zInvalid range format - r   zbytes=-r   zEmpty new range - )
ValueErrorRANGE_REGEXmatchRuntimeErrorgroupsr|   )r   r   r   startend
new_suffix	new_range	new_starts           r=   _adjust_range_headerr   [  s!    }A&&
n6~6HH\]^^n-E4^4FaHIIJE!88J!LMMX+
j\*	?!3I=BCCJE#I
#hYKq.	?!3I=BCCI;a  r?   )r@   N)N)Q__doc__r}   rg   reri   r   r1   	functoolsr   httpr   shlexr   typingr   r   r   r	   r
   r   r   rE   r   r   requests.adaptersr   requests.modelsr   huggingface_hub.errorsr   r'   r   r   r   r   r   r   r   r   r   r   _fixesr   _lfsr   _typingr   
get_loggerrL   r4   r,   r/   compileVERBOSEr   r#   rS   rX   r\   BACKEND_FACTORY_Tr]   __annotations__ra   rk   r`   r|   rf   Timeoutr   SERVICE_UNAVAILABLEr0   float	Exceptionr   r   r   r   rC   
IGNORECASEr   r   rK   r?   r=   <module>r      s   E 	 	 	       D D D  ( ) + 7     #  " 
		H	%
 $
 ** [ <
[ 
("2"2  R!1!112 -E * E AY !,= !]a !H\X%% \@* % % %@P@P % %   P :D9W9W{8{8	{8 	{8
 {8 {8 tId9os6J0KKL{8 !eCHo!56{8 {8|
 
x} 
 
B?( B?8C= B?TX B?JGm^, Gmc GmX GmZh GmT% h.. % 3 % R jjA2==Q"!# "!S "!XVY] "!r?   