
    {bj                     	   % 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rSSKrSSK	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Jr  SSKJrJr  SSK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%J&r&J'r'  SSKJ(r(  SSK)J*r*  SSK+J,r,  \(RZ                  " \.5      r/\" SS9 " S S5      5       r0\Rb                  " S5      r2\Rb                  " S5      r3S\\4\44   S\0S-  4S jr5S\\4\44   S\6S-  4S jr7Sr8Sr9Sr:\Rb                  " S\Rv                  S9r<\Rb                  " S \Rv                  S9r=\Rb                  " S!5      r>\Rb                  " S"5      r?\Rb                  " S#5      r@1 S$krAS%\4S\B\4S-  \4S-  4   4S& jrCS%\4S\4S-  4S' jrDS%\4S\4S-  4S( jrES)\R                  SS4S* jrGS)\R                  SS4S+ jrHS,\R                  SS4S- jrJS\R                  4S. jrLS\R                  4S/ jrN\
/ \R                  4   rO\
/ \R                  4   rP\R                  " 5       rR\LqS\O\TS0'   \NqU\P\TS1'   SqV\R                  S-  \TS2'   S3\OSS4S4 jrWS5\PSS4S6 jrXS\R                  4S7 jrYS\R                  4S8 jrZSnS9 jr[\R                  " \[5        \]" \S:5      (       a  \R                  " \[S;9  \R                  \R                  \R                  4rb\B\c\d   S<4   \TS='   S>re\B\6S<4   \TS?'   S@SSA\b\eSBSC.SD\,S%\4SE\6SF\fSG\fSH\c\d   \B\c\d   S<4   -  SI\6\B\6S<4   -  SJ\gS\\R                  SS4   4SK jjrhS@SSA\b\eSL.SD\,S%\4SE\6SF\fSG\fSH\c\d   \B\c\d   S<4   -  SI\6\B\6S<4   -  S\R                  4SM jjri\S@SSA\b\eSL.SD\,S%\4SE\6SF\fSG\fSH\c\d   \B\c\d   S<4   -  SI\6\B\6S<4   -  S\\R                  SS4   4SN jj5       rjSOrkSBSP.SD\,S%\4SQ\gS\R                  4SR jjrlS%\4SS\4S\g4ST jrmS%\4SU\4S-  S\44SV jrnSoS,\R                  SW\4S-  SS4SX jjro\p" 5       rqS,\R                  SS4SY jrr\" SZ\#S[9rsS\\c\s   S]\4S,\R                  S^\S\s4
S_ jrtS`ru\u V Vs/ s H;  n \Rc                  SaU  Sb35      Sc4\Rc                  SdU  Se35      Sf44  H  nUPM     M=     snn rvSg\4S\44Sh jrwS)\R                  S\44Si jrx\Rb                  " Sj\R                  5      rzSk\4S-  Sl\6S\4S-  4Sm jr{gs  snn f )pz>Contains utilities to handle HTTP requests in huggingface_hub.    N)Callable	GeneratorMapping)contextmanager)	dataclass)quote)AnyTypeVar)urljoinurlparse)OfflineModeIsEnabled   )	constants)	BadRequestErrorBucketNotFoundErrorDisabledRepoErrorGatedRepoErrorHfHubHTTPErrorJobNotFoundErrorRemoteEntryNotFoundErrorRepositoryNotFoundErrorRevisionNotFoundError   )logging)SliceFileObj)HTTP_METHOD_TT)frozenc                   `    \ rS rSr% Sr\\S'   \\S'   \\S'   Sr\S-  \S'   Sr	\S-  \S'   S	r
g)
RateLimitInfo7   a  
Parsed rate limit information from HTTP response headers.

Attributes:
    resource_type (`str`): The type of resource being rate limited.
    remaining (`int`): The number of requests remaining in the current window.
    reset_in_seconds (`int`): The number of seconds until the rate limit resets.
    limit (`int`, *optional*): The maximum number of requests allowed in the current window.
    window_seconds (`int`, *optional*): The number of seconds in the current window.

resource_type	remainingreset_in_secondsNlimitwindow_seconds )__name__
__module____qualname____firstlineno____doc__str__annotations__intr$   r%   __static_attributes__r&       ڗ/tmp/claude-0/-home-danvics-docker-quiz/c1e0577a-e42c-4a3d-b1ea-3edd61103a4e/scratchpad/stt/lib/python3.13/site-packages/huggingface_hub/utils/_http.pyr   r   7   s6    
 NE3:!%NC$J%r0   r   zL\"(?P<resource_type>\w+)\"\s*;\s*r\s*=\s*(?P<r>\d+)\s*;\s*t\s*=\s*(?P<t>\d+)z'q\s*=\s*(?P<q>\d+).*?w\s*=\s*(?P<w>\d+)headersreturnc                    SnSnU  H+  nUR                  5       nUS:X  a  X   nM  US:X  d  M'  X   nM-     U(       d  g[        R                  U5      nU(       d  gUR                  S5      n[	        UR                  S5      5      n[	        UR                  S5      5      nSn	Sn
U(       aP  [
        R                  U5      nU(       a4  [	        UR                  S5      5      n	[	        UR                  S5      5      n
[        UUUU	U
S	9$ )
a  Parse rate limit information from HTTP response headers.

Follows IETF draft: https://www.ietf.org/archive/id/draft-ietf-httpapi-ratelimit-headers-09.html
Only a subset is implemented.

Example:
```python
>>> from huggingface_hub.utils import parse_ratelimit_headers
>>> headers = {
...     "ratelimit": '"api";r=0;t=55',
...     "ratelimit-policy": '"fixed window";"api";q=500;w=300',
... }
>>> info = parse_ratelimit_headers(headers)
>>> info.remaining
0
>>> info.reset_in_seconds
55
```
N	ratelimitzratelimit-policyr!   rtqw)r!   r"   r#   r$   r%   )lower_RATELIMIT_REGEXsearchgroupr.   _RATELIMIT_POLICY_REGEXr   )r2   r5   policykey	lower_keymatchr!   r"   r#   r$   r%   policy_matchs               r1   parse_ratelimit_headersrD   S   s    * !IFIIK	#I,,\F  ##I.EKK0MEKK$%I5;;s+,E!%N.55f=**3/0E !3!3C!89N#)% r0   c                     SnU  H  nUR                  5       S:X  d  M  X   n  O   Uc  gUR                  5       nU(       d  gUR                  5       (       a  [        U5      $ g)aK  Parse the standard `Retry-After` HTTP header into a number of seconds to wait.

The `Retry-After` header can be either a non-negative number of seconds (delay-seconds)
or an HTTP-date after which to retry. We handle only the delay-seconds case.

See https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Retry-After.
Nzretry-after)r:   stripisdigitr.   )r2   valuer@   s      r1   _parse_retry_afterrI      s^     E99;-'LE 
 }KKME}}5zr0   zx-request-idzX-Amzn-Trace-Idzx-amz-cf-ida  
        # staging or production endpoint
        ^https://[^/]+
        (
            # on /api/repo_type/repo_id
            /api/(models|datasets|spaces)/(.+)
            |
            # or /repo_id/resolve/revision/...
            /(.+)/resolve/(.+)
        )
    )flagszz
        # staging or production endpoint
        ^https?://[^/]+
        # on /api/buckets/...
        /api/buckets/
    z:^https?://[^/]+/api/(?:scheduled-jobs|jobs)/[^/]+/([^/?]+)zA^https?://[^/]+/api/(models|datasets|spaces)/([^/]+)(?:/([^/]+))?z)^https?://[^/]+/api/buckets/([^/]+/[^/]+)>	   rawblobrefstreecommitresolverevisionsettingsdiscussionsurlc                    [         R                  U 5      nU(       d  g[        R                  R	                  UR                  S5      5      nUR                  S5      UR                  S5      pCU(       a  U[        ;  a
  U SU 3nX%4$ UnX%4$ )a  Extract (repo_type, repo_id) from an API URL.

Returns canonical repo_type values: "model", "dataset", "space" (or None).

Examples:
    >>> _parse_repo_info_from_url("https://huggingface.co/api/models/user/repo")
    ("model", "user/repo")
    >>> _parse_repo_info_from_url("https://huggingface.co/api/datasets/user/repo/resolve/main/data.csv")
    ("dataset", "user/repo")
    >>> _parse_repo_info_from_url("https://huggingface.co/api/models/bert-base-cased/resolve/main/config.json")
    ("model", "bert-base-cased")
NNr   r      /)_REPO_ID_FROM_URL_REGEXr<   r   REPO_TYPES_MAPPINGgetr=   _REPO_URL_SUBPATHS)rT   rB   	repo_typefirstsecondrepo_ids         r1   _parse_repo_info_from_urlra      s     $**3/E,,00Q@IKKNEKKN6& 22G1VH%  r0   c                 `    [         R                  U 5      nU(       a  UR                  S5      $ S$ )z9Extract bucket_id (namespace/name) from a bucket API URL.r   N)_BUCKET_ID_FROM_URL_REGEXr<   r=   rT   rB   s     r1   _parse_bucket_id_from_urlre      s'    %,,S1E"5;;q>,,r0   c                 `    [         R                  U 5      nU(       a  UR                  S5      $ S$ )z>Extract the job_id from a (scheduled) job API URL, if present.r   N)_JOB_ID_FROM_URL_REGEXr<   r=   rd   s     r1   _parse_job_id_from_urlrh      s'    "))#.E"5;;q>,,r0   requestc           	      t   [         R                  " 5       (       a  [        SU R                   S35      e[        U R
                  ;  aU  U R
                  R                  [        5      =(       d    [        [        R                  " 5       5      U R
                  [        '   U R
                  R                  [        5      n[        R                  SUU R                  U R                  U R
                  R                  S5      SL5        [         R                  (       a  [        R                  S[        U 5      5        U$ )z
Event hook that will be used to make HTTP requests to the Hugging Face Hub.

What it does:
- Block requests if offline mode is enabled
- Add a request ID to the request headers
- Log the request if debug mode is enabled
zCannot reach za: offline mode is enabled. To disable it, please unset the `HF_HUB_OFFLINE` environment variable.z%Request %s: %s %s (authenticated: %s)authorizationNzSend: %s)r   is_offline_moder   rT   X_AMZN_TRACE_IDr2   r[   X_REQUEST_IDr,   uuiduuid4loggerdebugmethodHF_DEBUG_curlify)ri   
request_ids     r1   hf_request_event_hookrw      s       """GKK=  )J  K
 	

 goo-+2??+>+>|+L+aPSTXT^T^T`Pa($$_5J LL/O,D8 Z'!23r0   c                     #    [        U 5      $ 7f)z+
Async version of `hf_request_event_hook`.
)rw   )ri   s    r1   async_hf_request_event_hookry     s      !))s   responsec                    #    U R                   S:  aJ  SU R                  ;   a9   [        U R                  S   5      nUS:  a  U R	                  5       I S h  vN   g g g g ! [         a     g f = f N7f)N  zContent-lengthi@B )status_coder2   r.   
ValueErroraread)rz   lengths     r1   async_hf_response_event_hookr   "  s     s" x///X--.>?@ 	!nn&&& " 0 #   's3   !A0A A0A.A0
A+(A0*A++A0c                  <    [         R                  " S[        /0SSS9$ )zI
Factory function to create a `httpx.Client` with the default transport.
ri   TNevent_hooksfollow_redirectstimeout)httpxClientrw   r&   r0   r1   default_client_factoryr   0  s'     <<!6 78 r0   c                  H    [         R                  " [        /[        /S.SSS9$ )zN
Factory function to create a `httpx.AsyncClient` with the default transport.
)ri   rz   TNr   )r   AsyncClientry   r   r&   r0   r1   default_async_client_factoryr   ;  s,     !< =LhKij r0   _GLOBAL_CLIENT_FACTORY_GLOBAL_ASYNC_CLIENT_FACTORY_GLOBAL_CLIENTclient_factoryc                 \    [            [        5         U qSSS5        g! , (       d  f       g= f)a  
Set the HTTP client factory to be used by `huggingface_hub`.

The client factory is a method that returns a `httpx.Client` object. On the first call to [`get_session`] the client factory
will be used to create a new `httpx.Client` object that will be shared between all calls made by `huggingface_hub`.

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 correctly configured `httpx.Client`.
N)_CLIENT_LOCKclose_sessionr   )r   s    r1   set_client_factoryr   O  s     
!/ 
s   
+async_client_factoryc                     U q g)a~  
Set the HTTP async client factory to be used by `huggingface_hub`.

The async client factory is a method that returns a `httpx.AsyncClient` object.
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_async_client`] to get a correctly configured `httpx.AsyncClient`.

> [!WARNING]
> Contrary to the `httpx.Client` that is shared between all calls made by `huggingface_hub`, the `httpx.AsyncClient` is not shared.
> It is recommended to use an async context manager to ensure the client is properly closed when the context is exited.
Nr   )r   s    r1   set_async_client_factoryr   `  s
     $8 r0   c                      [         c  [           [        5       q SSS5        [         $ [         $ ! , (       d  f       [         $ = f)z
Get a `httpx.Client` object, using the transport factory from the user.

This client is shared between all calls made by `huggingface_hub`. Therefore you should not close it manually.

Use [`set_client_factory`] to customize the `httpx.Client`.
N)r   r   r   r&   r0   r1   get_sessionr   p  s3     35N > \s	   -
A c                      [        5       $ )a  
Return a `httpx.AsyncClient` object, using the transport factory from the user.

Use [`set_async_client_factory`] to customize the `httpx.AsyncClient`.

> [!WARNING]
> Contrary to the `httpx.Client` that is shared between all calls made by `huggingface_hub`, the `httpx.AsyncClient` is not shared.
> It is recommended to use an async context manager to ensure the client is properly closed when the context is exited.
r   r&   r0   r1   get_async_sessionr     s     ())r0   c                      [         n Sq U b   U R                  5         gg! [         a"  n[        R	                  SU 35         SnAgSnAff = f)z
Close the global `httpx.Client` used by `huggingface_hub`.

If a Client is closed, it will be recreated on the next call to [`get_session`].

Can be useful if e.g. an SSL certificate has been updated.
NzError closing client: )r   close	Exceptionrq   warning)clientes     r1   r   r     sT     F N 	9LLN   	9NN3A3788	9s    
AAAregister_at_fork)after_in_child._DEFAULT_RETRY_ON_EXCEPTIONS)i    i  i  i  i  _DEFAULT_RETRY_ON_STATUS_CODES      F)max_retriesbase_wait_timemax_wait_timeretry_on_exceptionsretry_on_status_codesstreamrs   r   r   r   r   r   r   c          	   +   N  ^ ^^^^^#    [        U[        5      (       a  U4n[        T[        5      (       a  T4mSmUn	SmSn
SU;   a;  [        US   [        R                  [
        45      (       a  US   R                  5       n
 TS-  mSm[        5       n U
b  US   R                  U
5        S[        R                  S[        4UU UUUU4S jjnU(       a;  UR                  " ST TS.UD6 nU" U5      (       d  Uv    SSS5        g SSS5        O(UR                  " ST TS.UD6nU" U5      (       d  Uv   g Tb.  [%        T5      S-   n[        R                  SU ST ST S35        O!U	n[        R                  SU ST ST S35        [&        R(                  " U5        [+        XIS-  5      n	GM/  ! , (       d  f       N= f! U aY  n[        R                  S	U S
T  ST 35        [        U[        R                   5      (       a
  [#        5         TT:  a  Ue SnANSnAff = f7f)zfInternal implementation of HTTP backoff logic shared between `http_backoff` and `http_stream_backoff`.r   Ndatar   rz   r3   c                 Z  > U R                   T;  a  g[        R                  SU R                    ST ST 35        TT:  a  [        U 5        gU R                   S:X  a5  [	        U R
                  5      =nb  UR                  S:X  a  UR                  mg[        U R
                  5      =nb  Umg)zNHandle response and return True if should retry, False if should return/yield.FzHTTP Error z thrown while requesting  r   r   T)	r}   rq   r   hf_raise_for_statusrD   r2   r"   r#   rI   )	rz   ratelimit_inforetry_afterr   rs   nb_triesratelimit_resetr   rT   s	      r1   _should_retry)_http_backoff_base.<locals>._should_retry  s     ''/DD  X-A-A,BB[\b[ccdehdijkk)'1 ! ((C/+B8CSCS+TTa&00A5&4&E&EO  &88H8H%IIkV&1Or0   rs   rT   'z' thrown while requesting r   zRate limited. Waiting zs before retry [Retry rX   z].zRetrying in z	s [Retry r   r&   )
isinstancetyper.   ioIOBaser   tellr   seekr   Responseboolr   ri   rq   r   ConnectErrorr   floattimesleepmin)rs   rT   r   r   r   r   r   r   kwargs
sleep_timeio_obj_initial_posr   r   rz   erractual_sleepr   r   s   ```   `         @@r1   _http_backoff_baser     s<     %t,,24'--!6 8HJ"&O
 Jvf~		<7PQQ#F^002
A 4	 "-v##$67 4  6 ]]D&cDVD(22& ED2 ED
 ">>KSKFK$X.."N / & 1A5LNN3L>AWX`Waabcnbooqrs%LNN\,y
!K=XZ[\

<  Q7
M R ED # 	NNQse#=fXQseLM#u1122+%	 &	so   BH%AG +F2>G H%G H%&G 7A;H%2
G <G ?H% G H"	AHH%H""H%)r   r   r   r   r   c                <    [        [        SU UUUUUUSS.UD65      $ )a
  Wrapper around httpx 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. Set to `0` to disable 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 `httpx.TimeoutException`, `httpx.NetworkError` and `httpx.RemoteProtocolError`.
    retry_on_status_codes (`int` or `tuple[int]`, *optional*, defaults to `(429, 500, 502, 503, 504)`):
        Define on which status codes the request must be retried. By default, retries
        on rate limit (429) and server errors (5xx).
    **kwargs (`dict`, *optional*):
        kwargs to pass to `httpx.request`.

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

# Same usage as "httpx.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()
```

> [!WARNING]
> 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).
Frs   rT   r   r   r   r   r   r   r&   )nextr   rs   rT   r   r   r   r   r   r   s           r1   http_backoffr     sA    B  
	
#)' 3"7
	
 
	
 r0   c             +   H   #    [        SU UUUUUUSS.UD6 Sh  vN   g N7f)a
  Wrapper around httpx 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. Set to `0` to disable 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 `httpx.TimeoutException`, `httpx.NetworkError` and `httpx.RemoteProtocolError`.
    retry_on_status_codes (`int` or `tuple[int]`, *optional*, defaults to `(429, 500, 502, 503, 504)`):
        Define on which status codes the request must be retried. By default, retries
        on rate limit (429) and server errors (5xx).
    **kwargs (`dict`, *optional*):
        kwargs to pass to `httpx.request`.

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

# Same usage as "httpx.stream".
>>> with http_stream_backoff("GET", "https://www.google.com") as response:
...     for chunk in response.iter_bytes():
...         print(chunk)

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

> [!WARNING]
> When using `httpx` 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).
Tr   Nr&   )r   r   s           r1   http_stream_backoffr   f  sA     F " 
%#/3
 
 
 
s   " "   )retry_on_errorsr   c                P   U(       a  0 OSSS.n[        [        5       He  n[        SU US.UDSS0DUD6n[        U5        UR                  (       d  Us  $ [        XR                  S   5      n[        X5      (       d  Us  $ UnMg     [        R                  " S[         SU S	35      e)
a  Perform an HTTP request with backoff, following redirects that stay on the Hub.

Used to fetch HEAD /resolve on repo or bucket files.

Redirects to the same host or another Hub host are followed. Redirects to any other host (CDN, storage
bucket) are not: the file metadata is on the redirect response itself and the auth header must not leave the Hub.

A backoff mechanism retries the HTTP call on errors (429, 5xx, timeout, network errors).

Args:
    method (`str`):
        HTTP method, such as 'GET' or 'HEAD'.
    url (`str`):
        The URL of the resource to fetch.
    retry_on_errors (`bool`, *optional*, defaults to `False`):
        Whether to retry on errors. If False, no retry is performed (fast fallback to local cache).
        If True, uses default retry behavior (429, 5xx, timeout, network errors).
    **httpx_kwargs (`dict`, *optional*):
        Params to pass to `httpx.request`.
r&   )r   r   r   r   FLocationz	Exceeded z redirects while resolving 'z'.)
range_MAX_REDIRECTSr   r   has_redirect_locationr   r2   _is_same_or_hub_hostr   TooManyRedirects)rs   rT   r   httpx_kwargsno_retry_kwargs_rz   targets           r1   (_httpx_follow_hub_redirects_with_backoffr     s    2 2XZ#[  >" 

 
 #	

 
 	H%--O..z:;#C00 O' #* 
 
 9^,<<XY\X]]_!`
aar0   r   c                     [        U5      R                  =(       d    SR                  5       nU[        U 5      R                  =(       d    SR                  5       :H  =(       d    U[        R                  ;   $ )zMWhether `target` is served by the same host as `url`, or by a known Hub host. )r   hostnamer:   r   HF_URL_HOSTS)rT   r   target_hosts      r1   r   r     sT    F#,,299;K8C=117R>>@@iKS\SiSiDiir0   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.
rX   )rstripr   ENDPOINT_HF_DEFAULT_ENDPOINT_HF_DEFAULT_STAGING_ENDPOINTreplace)rT   r   s     r1   fix_hf_endpoint_in_urlr     sf    
 (0xs#Y5G5GH	66	8^8^__kk)88(Ckk)@@(KJr0   endpoint_namec           	      	    [        U 5         U R	                  5         g! [         a    [        R                  SSS9   N2f = f! [
        R                   Ga  nU R                  S-  S:X  a   SnAgU R                  R                  S5      nU R                  R                  S5      nU R                  b6  U R                  R                  b  [        U R                  R                  5      OSnU(       a  [        U5      OS	u  pgUS
:X  a3  U R                   S3S-   SU R                   S3-   n[        [        XXgS9UeUS:X  a3  U R                   S3S-   SU R                   S3-   n[        [         XXgS9UeUS:X  a3  U R                   S3S-   SU R                   S3-   n[        ["        XXgS9UeUS:X  a:  U R                   S3S-   SU R                   S3-   S-   S-   n[        [$        X5      UeUS:X  a[  UbX  [&        R)                  U5      bB  U R                   S3S-   SU R                   S3-   S-   S-   n[        [*        X[-        U5      S9UeU R                  S:X  aG  UbD  [/        U5      =n	b6  U R                   S3S-   SU R                   S3-   S-   n[        [0        XU	S9UeUS:X  d/  U R                  S :X  aX  US!:w  aR  UbO  [2        R)                  U5      b9  U R                   S3S-   S"U R                   S3-   S#-   S$-   n[        [4        XXgS9UeU R                  S%:X  a  Ub  S&U S'3OS(n[        [6        X5      UeU R                  S):X  a8  SU R                   S*U S3S+U R                   S3-   S,-   n[        [8        X5      UeU R                  S-:X  a  [;        U R                  5      n
U
b  U
R<                  S.:X  a  S/U
R>                   S03nUS1U
R@                   S23-  nU
RB                  b;  U
RD                  b.  US3U
R<                   S4U
RB                   S5U
RD                   S63-  nOUS-  nUS7U R                   S3-  nOS8U R                   S3n[        [8        X5      UeU R                  S9:X  aZ  U R                  R                  R                  S:5      nU S;U S<U R                  R                  S=5       S3n[        [8        X5      Ue[        [8        [        U5      U 5      UeSnAff = f)>ad  
Internal version of `response.raise_for_status()` that will refine a potential HTTPError.
Raised exception will be an instance of [`~errors.HfHubHTTPError`].

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

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.

> [!WARNING]
> 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 found.
>     - [`~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.
zFailed to parse warning headersT)exc_infod   rW   NzX-Error-CodeX-Error-MessagerV   RevisionNotFoundz Client Error.

zRevision Not Found for url: .)r]   r`   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 
RepoNotFoundzBucket Not Found for url: zG
Please make sure you specified the correct bucket id (namespace/name).zg
If the bucket is private, make sure you are authenticated and your token has the required permissions.)	bucket_idi  zJob Not Found for url: zA
Please make sure you specified the correct job ID and namespace.)job_idi  z+Invalid credentials in Authorization headerz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 and your token has the required permissions.zQ
For more details, see https://huggingface.co/docs/huggingface_hub/authenticationr|   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.r   r   z0

429 Too Many Requests: you have reached your 'z' rate limit.z
Retry after z seconds (rX   z requests remaining in current z
s window).z
Url: z!

429 Too Many Requests for url: i  Rangez. Requested range: z. Content-Range: zContent-Range)#_warn_on_warning_headersr   rq   rr   raise_for_statusr   HTTPStatusErrorr}   r2   r[   ri   rT   r,   ra   _formatr   r   r   r   BUCKET_API_REGEXr<   r   re   rh   r   REPO_API_REGEXr   r   r   rD   r"   r!   r#   r$   r%   )rz   r   r   
error_codeerror_messagerequest_urlr]   r`   messager   r   range_headers               r1   r   r      s   BG *
C?!!#  G6FG    A?3&!+%%)).9
 ((,,->? *2)9)9)E(JZJZJ^J^JjC  $$%pt 	 HS6{CXd	++!--.n=FKghphthtguuvIwwG/iiopp?*!--.n=FKdemeqeqdrrsIttG2GQZlrss;&''(7&@EfgogsgsfttuCvv  .'ybhiiDD''(75hll^1EF  9	9  +W?QF .(' ''4@ ''(7.x||nA>? ]] }	}  #WB[\gBh
   C''1+>>K ''(7+HLL>;< WW  *GfMSTT>)  C'!NN'%%k2> ''(728<<.BC`` gg  17PYkqrr!!S(DQD]&}oZ@cu  /7=1D!!S(x++,LqI0a@AGH 
 .'<!C!!S(4X5E5EFN)n.F.F!.KHIeIeHffst  ^N,K,K+LHUU!''38U8U8a^556a8L8L7M N''5'D'D&EZQG
 sNGWX\\N!44?~QO.'<!C!!S(#++3377@L.|n<MhN^N^NbNbcrNsMttuvG.'<!C nc!fh7Q>CA?s,    A A A S-S(0Q8S((S-c                 F   U R                   R                  S5      nU H  nSU;   a  UR                  SS5      OSU4u  p4UR                  5       nU[        ;  d  M=  UR                  5       nU(       d  MV  [        R                  U5        [        R                  U5        M     g)a}  
Emit warnings if warning headers are present in the HTTP response.

Expected header format: 'X-HF-Warning: topic; message'

Only the first warning for each topic will be shown. Topic is optional and can be empty. Note that several warning
headers can be present in a single response.

Args:
    response (`httpx.Response`):
        The HTTP response to check for warning headers.
zX-HF-Warning;r   r   N)r2   get_listsplitrF   _WARNED_TOPICSaddrq   r   )rz   server_warningsserver_warningtopicr  s        r1   r  r    s     &&//?O)9<9N--c15UWYgTh&mmoGw""5)w' *r0   _HfHubHTTPErrorT)bound
error_typecustom_messageattrsc                    / nUR                   R                  S5      nUb  UR                  U5          UR                  5       nUR                  S5      nUR                  S5      nUbS  [        U[        5      (       a  UR                  U5        O@Ub  UR                  U SU 35        O&UR                  U5        OUb  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SnSn[&        S4[(        S4[*        S44 H>  u  nnUR                   R                  U5      nU(       d  M*  [        U5      nSU SU S3n  O   U(       aL  UR                  5       UR                  5       ;  a*  S
U;   a   UR-                  S
5      nUS U U-   UUS  -   nOX-  nU " UR                  5       X,=(       d    S S9nUR/                  5        H  u  nn[1        UUU5        M     U$ ! [        R
                   a9     UR                  5         UR                  5       n GN! [         a    0 n  GNf = ff = f! [        R                   a`    UR                   R                  SS5      n
UR                  (       a/  S	U
R                  5       ;  a  UR                  UR                  5         GNtf = fs  snf )Nr   errorerror_description: errorsr  zContent-Typer   htmlr   r   z
Request IDzAmzn Trace IDz	Amz CF IDr   ))rz   server_message)r2   r[   appendjsonr   ResponseNotReadreadRuntimeErrorr   listextendJSONDecodeErrortextr:   r,   rF   dictfromkeysjoinrn   rm   X_AMZ_CF_IDindexitemssetattr)r  r  rz   r  server_errorsfrom_headersr   r  r  r  content_typeliner"  final_error_messagerv   request_id_messageheaderlabelrH   newline_indexr   kvs                          r1   r  r    sp    M ##''(9:L\*+0	==?D ! HH%89%&&$$U+".$$wb1B0C%DE $$U+*  !23(#%!((y)9:   4AV=4CIOODU&SY__&=MV }56M YY}-N )...08L8L8NN^#4.#886N#:: J	|$	/*	k"
   $$V,5UJ#%eWBugQ!7 j&&(0C0I0I0KK&&/55d;M#N]36HHK^_l_mKnn    5 (..08Tjfj
kC1Q Jo $$ 
		}}  	
	F  0''++NB?==V<+=+=+??  /	0 Wsa   J: B)L
 1L
 "N3N:L K2/L
 2L>L?L
 LLL
 
A0M>=M>)subject_tokenaccess_tokenrefresh_tokenclient_secretdevice_codez("z"\s*:\s*")[^"]*(")z\1<REDACTED>\2z(^|&)(z=)[^&]*z\1\2<REDACTED>bodyc                 F    [          H  u  pUR                  X 5      n M     U $ )zRRedact OAuth credential values from a JSON or form-urlencoded request body string.)_SENSITIVE_BODY_PATTERNSsub)rC  patternreplacements      r1   _redact_sensitive_bodyrI  @  s"     8{{;- !9Kr0   c                    SSU R                   4/n[        U R                  R                  5       5       H(  u  p#UR	                  5       S:X  a  SnUSU SU 34/-  nM*     Sn U R
                  b<  U R
                  R                  SS	S
9n[        U5      S:  a  USS  S3n[        U5      nUb  USUR                  SS5      4/-  nUSU R                  4/-  n/ nU H[  u  p#U(       a#  UR                  [        [        U5      5      5        U(       d  M8  UR                  [        [        U5      5      5        M]     SR!                  U5      $ ! [        R                   a    Sn Nf = f)zConvert a `httpx.Request` 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-Xrk   z<TOKEN>z-Hr  Nzutf-8ignore)r  i  z ... [truncated]z<streaming body>z-dr   r   r   )rs   sortedr2   r1  r:   contentdecodelenrI  r   RequestNotReadr   rT   r#  r   r,   r.  )ri   partsr<  r=  rC  
flat_partss         r1   ru   ru   G  sn    		w~~$E
 w,,./779'A4A3b%&& 0
 D"??&??))'()CD4y4u+&67)$/D 4dB/011	tW[[!""EJeCFm,1eCFm,	  88J  "!"s   #A	E E&%E&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 - )r~   RANGE_REGEXrB   r'  groupsr.   )rT  rU  rB   startend
new_suffix	new_range	new_starts           r1   _adjust_range_headerr`  u  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  r0   )r3   N)N)|r+   atexitr   r$  osre	threadingr   ro   collections.abcr   r   r   
contextlibr   dataclassesr   shlexr   typingr	   r
   urllib.parser   r   r   huggingface_hub.errorsr   r   r   r  r   r   r   r   r   r   r   r   r   r   _lfsr   _typingr   
get_loggerr'   rq   r   compiler;   r>   r,   rD   r.   rI   rn   rm   r/  VERBOSEr  r  rg   rY   rc   r\   tuplera   re   rh   Requestrw   ry   r   r   r   r   r   r   CLIENT_FACTORY_TASYNC_CLIENT_FACTORY_TLockr   r   r-   r   r   r   r   r   r   r   registerhasattrr   TimeoutExceptionNetworkErrorRemoteProtocolErrorr   r   r   r   r   r   r   r   r   r   r   r   r   r   setr  r  r  r  _SENSITIVE_BODY_KEYSrE  rI  ru   
IGNORECASErY  r`  )r@   rG  s   00r1   <module>r~     s>   E  	  	 	    8 8 % !   *  7 
 
 
   " 
		H	% $& & &, ::mn **%OP 8WS#X%6 8=4;O 8vS 1 cDj 6 #
 ** :: **  $ab  **%ij  JJ'ST  q 3 5tS4Z1G+H 2-3 -3: -- -d
 -5== T B*u}} * *' 'D ' e&7&7  B,- !"e&7&7"78 ~~+A ( A7S 4 S&*t# *0'7 0D 0"83I 8d 8 U\\ 
*5,, 
*9,  
2!""}5 
		= eDOS$89 
 3Q c3h P Ie3Qd8d8	d8 	d8
 d8 d8 i5i#1E+FFd8 sCx0d8 d8 u~~tT)*d8V Ie3QMM	M 	M
 M M i5i#1E+FFM sCx0M ^^M` 
 Ie3QLL	L 	L
 L L i5i#1E+FFL sCx0L u~~tT)*L L^  AF1b1b #1b9=1b
^^1bhjc j3 j4 j
 
sTz 
c 
j?%.. j?t j?W[ j?Z (u~~ ($ (0 -^D f%&f8;fGL~~f`cffT j  $#	r#01	24EF	vcU'*	+->?  #   ' emm '  ' V jjA2==Q"!t "!# "!#PT* "!s   	AS