
    /j                     "   d dl Z d dlZd dlZd dlmZ d dlmZmZmZm	Z	m
Z
 e j                            dd          Ze j                            dd          Z e
d          Zd	Zd
edefdZded
efdZ	 	 	 	 	 	 dded
ededededededefdZdS )    N)Any)IS_COLABLOGGERTQDM	TryExceptcolorstrULTRALYTICS_HUB_APIzhttps://api.ultralytics.comULTRALYTICS_HUB_WEBzhttps://hub.ultralytics.comzUltralytics HUB: z]If this issue persists please visit https://github.com/ultralytics/hub/issues for assistance.urlreturnc                     t           st          d          ddlm} ddlm} |                    |                    d|  d                     |                    d          S )a*  Make an AJAX request with cookies attached in a Google Colab environment.

    Args:
        url (str): The URL to make the request to.

    Returns:
        (Any): The response data from the AJAX request.

    Raises:
        OSError: If the function is not run in a Google Colab environment.
    z:request_with_credentials() must run in a Colab environmentr   )output)displayz
            window._hub_tmp = new Promise((resolve, reject) => {
                const timeout = setTimeout(() => reject("Failed authenticating existing browser session"), 5000)
                fetch("a  ", {
                    method: 'POST',
                    credentials: 'include'
                })
                    .then((response) => resolve(response.json()))
                    .then((json) => {
                    clearTimeout(timeout);
                    }).catch((err) => {
                    clearTimeout(timeout);
                    reject(err);
                });
            });
            _hub_tmp)r   OSErrorgoogle.colabr   IPythonr   
Javascripteval_js)r   r   r   s      Z/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/hub/utils.pyrequest_with_credentialsr      s      TRSSS######OO   	
 	
  ( >>*%%%    methodc                    ddl }|                    dd          }|s |j        | |fi |S  |j        | |fddi|}t          t	          |t
                    r|j                            dd          n|          }	 t          |ddd	
          }|	                    d	          D ]$}|
                    t          |                     %|                                 n)# |j        j        $ r |                                 Y nw xY w|S )a  Make an HTTP request using the specified method and URL, with an optional progress bar.

    Args:
        method (str): The HTTP method to use (e.g. 'GET', 'POST').
        url (str): The URL to send the request to.
        **kwargs (Any): Additional keyword arguments to pass to the underlying `requests.request` function.

    Returns:
        (requests.Response): The response object from the HTTP request.

    Notes:
        - If 'progress' is set to True, the progress bar will display the download progress for responses with a known
          content length.
        - If 'progress' is a number then progress bar will display assuming content length = progress.
    r   NprogressFstreamTzcontent-lengthBi   )totalunit
unit_scaleunit_divisor)
chunk_size)requestspoprequestint
isinstanceboolheadersgetr   iter_contentupdatelenclose
exceptionsChunkedEncodingError)	r   r   kwargsr#   r   responser   pbardatas	            r   requests_with_progressr5   ?   s>     OOOzz*e,,H 7x66v666xCCDCFCCHZRV=W=We $$%5q999]effE%cdNNN))T):: 	# 	#DKKD		""""

3   Os   =A"C   #DD      TFretrytimeoutthreadcodeverboser   c                     dt                    fd            }	| |f}
||d<   |r,t          j        |	|
|d                                           dS  |	|
i |S )a$  Make an HTTP request using the 'requests' library, with exponential backoff retries up to a specified timeout.

    Args:
        method (str): The HTTP method to use for the request. Choices are 'post' and 'get'.
        url (str): The URL to make the request to.
        retry (int, optional): Number of retries to attempt before giving up.
        timeout (int, optional): Timeout in seconds after which the function will give up retrying.
        thread (bool, optional): Whether to execute the request in a separate daemon thread.
        code (int, optional): An identifier for the request, used for logging purposes.
        verbose (bool, optional): A flag to determine whether to print out to console or not.
        progress (bool, optional): Whether to show a progress bar during the request.
        **kwargs (Any): Keyword arguments to be passed to the requests function specified in method.

    Returns:
        (requests.Response | None): The HTTP response object. If the request is executed in a separate thread, returns
            None.
    )i  i  )r=   c                    d}t          j                     }t          	dz             D ]}t          j                     |z
  k    r n t          | |fi |}|j        dk     r n	 |                                                    dd          }n# t          $ r d}Y nw xY w|dk    r|j        
v r|	r	d	 d	 d
ndz  }n0|j        dk    r%|j        }d|d          d|d          d|d          d
}r1t          j	        t           | dt           d|j         d d	           |j        
vr|c S t          j        d|z              |S )zNMake HTTP requests with retries and timeouts, with optional progress tracking.N   i,  messagezNo JSON message.zUnable to read JSON.r   z
 Retrying zx for zs. i  zRate limit reached (zX-RateLimit-Remaining/zX-RateLimit-Limitz). Please retry after zRetry-After z (z #)   )timeranger5   status_codejsonr*   AttributeErrorr)   r   warningPREFIXHELP_MSGsleep)func_methodfunc_urlfunc_kwargsrt0imhr<   r9   retry_codesr:   r=   s           r   funczsmart_request.<locals>.func~   s    Y[[uqy!! 	 	A	b G++&{HLLLLA}s""+FFHHLL,>??! + + +*+Avv=K//%O>e>>7>>>>ROAA]c))	ACq1H/I C CANaLb C C./.>C C C   XNf#Va#V#V(#V#Vam#V#Vt#V#V#VWWW=33HHHJq!ts   %(BBBr   T)targetargsr1   daemonN)r   	threadingThreadstart)r   r   r9   r:   r;   r<   r=   r   r1   rY   r[   rX   s     `` ``    @r   smart_requestr`   `   s    8 Kw         < 3;D!F: %4tLLLRRTTTTTtT$V$$$r   )r6   r7   Tr8   TF)osr]   rG   typingr   ultralytics.utilsr   r   r   r   r   environr*   HUB_API_ROOTHUB_WEB_ROOTrM   rN   strr   r5   r&   r(   r`    r   r   <module>ri      s   
			                         z~~35RSSz~~35RSS	%	&	&j%&# %&# %& %& %& %&P3 S    H B% B%B%	B% B% 	B%
 B% B% B% B% B% B% B% B% B%r   