
    FPhm%                     X   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Zd dl	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZ d dlmZ  ed      ZdZe j8                  j;                  dd      Ze j8                  j;                  d	d
      Zde de!fdZ"d Z#ddZ$ G d d      Z% e%       Z&y)    N)Path)ENVIRONMENTLOGGERONLINERANKSETTINGSTESTS_RUNNINGTQDM	TryExcept__version__colorstrget_git_origin_urlis_colab
is_git_diris_pip_package)GITHUB_ASSETS_NAMESzUltralytics HUB: z]If this issue persists please visit https://github.com/ultralytics/hub/issues for assistance.ULTRALYTICS_HUB_APIzhttps://api.ultralytics.comULTRALYTICS_HUB_WEBzhttps://hub.ultralytics.comurlreturnc                     t               st        d      ddlm} ddlm} |j                  |j                  d| z               |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)displayaj  
            window._hub_tmp = new Promise((resolve, reject) => {
                const timeout = setTimeout(() => reject("Failed authenticating existing browser session"), 5000)
                fetch("%s", {
                    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      `C:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/hub/utils.pyrequest_with_credentialsr!      sU     :RSS#OO   	" >>*%%    c                    |j                  dd      }|st        j                  | |fi |S t        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 # t        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 (dict): Additional keyword arguments to pass to the underlying `requests.request` function.

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

    Note:
        - 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.
    progressFstreamTzcontent-lengthr   Bi   )totalunit
unit_scaleunit_divisor)
chunk_size)poprequestsrequestint
isinstanceboolheadersgetr
   iter_contentupdatelenclose
exceptionsChunkedEncodingError)methodr   kwargsr$   responser'   pbardatas           r    requests_with_progressr?   <   s    " zz*e,H6v66CDCFCHZRV=W  $$%5q9]efE%cdN))T):DKKD	" ;

 O 33 Os   =AC -D ?D c                     dt              fd       }	| |f}
||d<   |r(t        j                  |	|
|d      j                          y |	|
i |S )ax  
    Makes 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. Default is 3.
        timeout (int, optional): Timeout in seconds after which the function will give up retrying. Default is 30.
        thread (bool, optional): Whether to execute the request in a separate daemon thread. Default is True.
        code (int, optional): An identifier for the request, used for logging purposes. Default is -1.
        verbose (bool, optional): A flag to determine whether to print out to console or not. Default is True.
        progress (bool, optional): Whether to show a progress bar during the request. Default is False.
        **kwargs (dict): Keyword arguments to be passed to the requests function specified in method.

    Returns:
        (requests.Response): The HTTP response object. If the request is executed in a separate thread, returns None.
    )i  i  )verbosec                    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ranger?   status_codejsonr3   AttributeErrorr2   r   warningPREFIXHELP_MSGsleep)func_methodfunc_urlfunc_kwargsrt0imhcoderetryretry_codestimeoutrA   s           r    funczsmart_request.<locals>.funcp   sv    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ANNfXaS(2amm_BtfTU#VW==3HJJqAv+ ",  " +*+s   ' EEEr$   T)targetargsr;   daemonN)r   	threadingThreadstart)r:   r   r\   r^   threadr[   rA   r$   r;   r_   ra   r]   s     `` ``    @r    smart_requestrg   \   sf    $ Kw  8 3;D!F:4tLRRTT$V$$r"   c                        e Zd ZdZdZd Zd Zy)Eventsa  
    A class for collecting anonymous event analytics. Event analytics are enabled when sync=True in settings and
    disabled when sync=False. Run 'yolo settings' to see and update settings YAML file.

    Attributes:
        url (str): The URL to send anonymous events.
        rate_limit (float): The rate limit in seconds for sending events.
        metadata (dict): A dictionary containing metadata about the environment.
        enabled (bool): A flag to enable or disable Events based on certain conditions.
    zihttps://www.google-analytics.com/mp/collect?measurement_id=G-X8NCJYTQXM&api_secret=QLQrATrNSwGRFRLE-cbHJwc           	         g | _         d| _        d| _        t        t        j
                  d         j                  dk(  t               rdnt               rdnddj                  t        j                         d	d
       t        t        t        t        j                         dz        dd| _        t"        d   xr4 t$        dv xr* t&         xr! t(        xr t               xs t+               dk(  | _        y	)zWInitializes the Events object with default values for events, rate_limit, and metadata.g      N@g        r   yologitpipother.NrI   g  4&kCi  )cliinstallpythonversionenv
session_idengagement_time_msecsync)r   z.https://github.com/ultralytics/ultralytics.git)events
rate_limittr   sysargvnamer   r   joinplatformpython_version_tupler   r   roundrandommetadatar   r   r	   r   r   enabled)selfs    r    __init__zEvents.__init__   s    $))V3 *u>;K%QXhhx<<>rBC"$ 67$(* V kGOkk k i!3!59i!i 	r"   c                 .   | j                   syt        | j                        dk  ri | j                  |j                  |j
                  t        v r|j
                  ndd}|j                  dk(  r|j                  |d<   | j                  j                  |j                  |d       t        j                         }|| j                  z
  | j                  k  ryt        d   | j                  d	}t        d
| j                  |dd       g | _        || _        y)z
        Attempts to add a new event to the events list and send events if the rate limit is reached.

        Args:
            cfg (IterableSimpleNamespace): The configuration object containing mode and task information.
        N   custom)taskmodelexportformat)r~   paramsuuid)	client_idry   postr   F)rM   r\   rA   )r   r6   ry   r   r   r   r   moder   appendrJ   r{   rz   r   rg   r   )r   cfgr   r{   r>   s        r    __call__zEvents.__call__   s     || t{{b V--V),&)ii3F&FHVF xx8##&::x KKFCD IIKJ$//) &f-E 	fdhhTEJ r"   N)__name__
__module____qualname____doc__r   r   r    r"   r    ri   ri      s    	 vCk("r"   ri   )      Trx   TF)'osr   r   r|   rc   rJ   pathlibr   r-   ultralytics.utilsr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   ultralytics.utils.downloadsr   rP   rQ   environr3   HUB_API_ROOTHUB_WEB_ROOTstranyr!   r?   rg   ri   ry   r   r"   r    <module>r      s    
   
    c c c c ;	%	&jzz~~35RSzz~~35RS"&# "&# "&J@6%rD DP 
r"   