o
    Vh%                     @   s   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	 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 jddZe jdd	Zed
ZdZ de!de"fddZ#dd Z$dddZ%G dd dZ&e& Z'dS )    N)Path)__version__)ARGVENVIRONMENTIS_COLAB
IS_GIT_DIRIS_PIP_PACKAGELOGGERONLINERANKSETTINGSTESTS_RUNNINGTQDM	TryExceptcolorstrget_git_origin_url)GITHUB_ASSETS_NAMES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                 C   sF   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    r   I/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/hub/utils.pyrequest_with_credentials&   s   
r!   c                 K   s   | dd}|stj| |fi |S tj| |fddi|}tt|tr+|jddn|}zt|dddd	}|j	dd
D ]	}|
t| q=|  W |S  tjjy]   |  Y |S 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.
    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datar   r   r    requests_with_progressO   s    

r=         TFc                    s^   dt d fdd}	| |f}
||d< |r(tj|	|
|d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): The HTTP response object. If the request is executed in a separate thread, returns None.
    )i  i  )verbosec                    s8  d}t   }td D ]}t   | kr |S t| |fi |}|jdk r* |S z
| dd}W n ty?   d}Y nw |dkr|jv rY|rUd d	 d
nd7 }n|jdkrs|j}d|d  d|d  d|d  d
}rt	t
 | dt d|j d  d	 |jvr|  S t d|  q|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ranger=   status_codejsonr1   AttributeErrorr0   r	   warningPREFIXHELP_MSGsleep)func_methodfunc_urlfunc_kwargsrt0imhcoderetryretry_codestimeoutrA   r   r    func   s<   

 
(
zsmart_request.<locals>.funcr"   T)targetargsr9   daemonN)r   	threadingThreadstart)r8   r   r\   r^   threadr[   rA   r"   r9   r_   ra   r   rZ   r    smart_requesto   s   rg   c                   @   s$   e Zd ZdZdZdd Zdd ZdS )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.

    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                 C   s   g | _ d| _d| _ttd jdktrdntrdnddt	
 d	d
 tttt d dd| _td oEtdv oEt oEtoEtpEt dk| _d	S )zVInitialize the Events object with default values for events, rate_limit, and metadata.g      >@g        r   yologitpipother.NrH   g  4&kCi  )cliinstallpythonversionenv
session_idengagement_time_msecsync>   r   r@   z.https://github.com/ultralytics/ultralytics.git)events
rate_limittr   r   namer   r   joinplatformpython_version_tupler   r   roundrandommetadatar   r   r   r
   r   enabled)selfr   r   r    __init__   s(   
zEvents.__init__c                 C   s   | j sdS t| jdk r3i | j|j|jtv r|jndd}|jdkr)|j|d< | j	|j|d t

 }|| j | jk rAdS td | jd	}td
| j|ddd g | _|| _dS )z
        Attempt 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)ry   paramsuuid)	client_idrv   postr   F)rL   r\   rA   )r   r4   rv   r   r   r   r   moder   appendrI   rx   rw   r   rg   r   )r   cfgr   rx   r<   r   r   r    __call__   s&   


zEvents.__call__N)__name__
__module____qualname____doc__r   r   r   r   r   r   r    rh      s
    rh   )r>   r?   Tr@   TF)(osr{   r~   rc   rI   pathlibr   r+   ultralyticsr   ultralytics.utilsr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   ultralytics.utils.downloadsr   environr1   HUB_API_ROOTHUB_WEB_ROOTrO   rP   stranyr!   r=   rg   rh   rv   r   r   r   r    <module>   s&   @)
 ;
N