
    .h                        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                  j                  dd      Ze j                  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y)    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} |j                  |j                  d|  d             |j                  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      S/var/www/html/ai-service/venv/lib/python3.12/site-packages/ultralytics/hub/utils.pyrequest_with_credentialsr      sZ     RSS#OO u 	
( >>*%%    methodc                    ddl }|j                  dd      }|s |j                  | |fi |S  |j                  | |fddi|}t        t	        |t
              r|j                  j                  dd      n|      }	 t        |ddd	
      }|j                  d	      D ]  }|j                  t        |              |j                          |S # |j                  j                  $ r |j                          Y |S w xY w)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    " zz*e,Hx6v66xCDCFCHZRV=W  $$%5q9]efE%cdN))T): 	#DKKD	"	#

 O 33 Os   ;AC )C:9C:retrytimeoutthreadcodeverboser   c                     dt              fd       }	| |f}
||d<   |r(t        j                  |	|
|d      j                          y |	|
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
  kD  r |S t        | |fi |}|j                  dk  r |S 	 |j	                         j                  dd      }|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
}r5t        j                  t         | dt         d|j                   d d	       |j                  
vr|c S t        j                  d|z          |S # t        $ r d}Y w xY w)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hr9   r6   retry_codesr7   r:   s           r   funczsmart_request.<locals>.func   s    YY[uqy! 	A		b G+, + '{HLLA}}s"& %+FFHLL,>? Av==K/%:eWF7)2>ROA]]c)		A.q1H/I.J!ANaLbKc d../.>-?rC  NNfXaS(2amm_BtfTU#VW==3HJJq!t/	0 ! " +*+s   ' EEEr   T)targetargsr1   daemonN)r   	threadingThreadstart)r   r   r6   r7   r8   r9   r:   r   r1   rV   rX   rU   s     `` ``    @r   smart_requestr]   b   sf    : Kw  < 3;D!F:4tLRRTT$V$$r   )      TTF)osrZ   rD   typingr   ultralytics.utilsr   r   r   r   r   environr*   HUB_API_ROOTHUB_WEB_ROOTrJ   rK   strr   r5   r&   r(   r]    r   r   <module>ri      s    
     zz~~35RSzz~~35RS	%	&j&&# &&# &&R3 S J C%C%	C% C% 	C%
 C% C% C% C%r   