
    FPh                          d dl Z d dlZd dlmZ d dlmZ d dlZd dlmZm	Z	m
Z
mZ d dlmZmZmZmZmZmZ d dlmZ  e       rde dnde d	Z G d
 d      Zy)    N)Path)sleep)HUB_API_ROOTHUB_WEB_ROOTPREFIXsmart_request)LOGGER__version__checksemojisis_colabthreaded)HUBModelErrorzpython-z-colabz-localc                   L    e Zd ZdZd Zd Zd Zd Zd Zd Z	ddZ
ed	        Zy
)HUBTrainingSessiona  
    HUB training session for Ultralytics HUB YOLO models. Handles model initialization, heartbeats, and checkpointing.

    Args:
        url (str): Model identifier used to initialize the HUB training session.

    Attributes:
        agent_id (str): Identifier for the instance communicating with the server.
        model_id (str): Identifier for the YOLO model being trained.
        model_url (str): URL for the model in Ultralytics HUB.
        api_url (str): API URL for the model in Ultralytics HUB.
        auth_header (dict): Authentication header for the Ultralytics HUB API requests.
        rate_limits (dict): Rate limits for different API calls (in seconds).
        timers (dict): Timers for rate limiting.
        metrics_queue (dict): Queue for the model's metrics.
        model (dict): Model data fetched from Ultralytics HUB.
        alive (bool): Indicates if the heartbeat loop is active.
    c                    ddl m} |j                  t         d      r|j	                  t         d      d   }|j	                  d      D cg c]  }t        |       c}ddgk(  r|j	                  d      \  }}n)t        |      dk(  rd|}}nt        d	| d
t         d       ||      }d| _        || _        t         d| | _	        t         d| | _        |j                         | _        dddd| _        i | _        i | _        | j#                         | _        d| _        | j)                          | j+                          t-        j.                  t0         d| j                   d       yc c}w )a  
        Initialize the HUBTrainingSession with the provided model identifier.

        Args:
            url (str): Model identifier used to initialize the HUB training session.
                         It can be a URL string or a model key with specific format.

        Raises:
            ValueError: If the provided model identifier is invalid.
            ConnectionError: If connecting with global API key is not supported.
        r   )Authz/models/_*       zmodel='z2' not found. Check format is correct, i.e. model='z /models/MODEL_ID' and try again.N/v1/models/g      @g      @g     r@)metricsckpt	heartbeatTzView model at     🚀)ultralytics.hub.authr   
startswithr   splitlenr   agent_idmodel_id	model_urlr   api_urlget_auth_headerauth_headerrate_limitstimersmetrics_queue
_get_modelmodelalive_start_heartbeat_register_signal_handlersr	   infor   )selfurlr   xkeyr#   auths          bC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/hub/session.py__init__zHUBTrainingSession.__init__%   sf    	. >>\N(34))|nH56r:CIIcN+NqCFN+Bx7IIcNMCX^C'# /**67W!Y Z Z Cy (>(<&{8*=//1'*EN__&

&&(vhnT^^,<EBC- ,s   E/c                     t        j                   t         j                  | j                         t        j                   t         j                  | j                         y)zYRegister signal handlers for SIGTERM and SIGINT signals to gracefully handle termination.N)signalSIGTERM_handle_signalSIGINTr1   s    r6   r/   z,HUBTrainingSession._register_signal_handlersO   s2    fnnd&9&9:fmmT%8%89    c                     | j                   du rBt        j                  t         d       | j	                          t        j                  |       yy)z
        Handle kill signals and prevent heartbeats from being sent on Colab after termination.

        This method does not use frame, it is included as it is passed by signal.
        Tu   Kill signal received! ❌N)r-   r	   r0   r   _stop_heartbeatsysexit)r1   signumframes      r6   r;   z!HUBTrainingSession._handle_signalT   sA     ::KK6(";<=  "HHV r>   c                     d| _         y)zTerminate the heartbeat loop.FN)r-   r=   s    r6   r@   z"HUBTrainingSession._stop_heartbeat_   s	    
r>   c                     | j                   j                         dd}t        d| j                  || j                  d       y)z(Upload model metrics to Ultralytics HUB.r   )r   typepost   )jsonheaderscodeN)r*   copyr   r%   r'   )r1   payloads     r6   upload_metricsz!HUBTrainingSession.upload_metricsc   s6    "00557Kfdll$BRBRYZ[r>   c                    t          d| j                   }	 t        d|| j                  dd      }|j	                         j                  dd      }|j                  dd      d	k(  r"t        t        d
| j                   d            |j                  dd      st        d      |d   | _        |d   dk(  ru|d   |d   |d   |d   |d   |d   |d   d| _	        |j                  d      xs |j                  d      | _
        t        j                  | j                  d      | _
        |S |d   dk(  r|d   dd| _	        |d   | _
        |S # t        j                  j                  $ r}t!        d      |d}~wt"        $ r  w xY w)z1Fetch and return model data from Ultralytics HUB.r   getFr   )rK   threadrL   dataNstatustrainedz)Model is already trained and uploaded to r   zDDataset may still be processing. Please wait a minute and try again.idnew
batch_sizeepochsimgszpatiencedevicecache)batchrY   rZ   r[   r\   r]   rS   cfgweights)verbosetrainingT)rS   resumerc   z<ERROR: The HUB server is not online. Please try again later.)r   r#   r   r'   rJ   rQ   
ValueErrorr   r$   
train_args
model_filer   check_yolov5u_filenamerequests
exceptionsConnectionErrorConnectionRefusedError	Exception)r1   r%   responserS   es        r6   r+   zHUBTrainingSession._get_modelh   s   !N+dmm_=	$UGT=M=MV[bcdH==?&&vt4Dxx$'94 *STXTbTbScch(i!jkk88FD) !ghh JDMH~&!,/"8n!'] $Z 0"8n!'] L#* #'((5/"HTXXi5H"("?"?Y^"_
 K	 h:-+/<4"H"&x.K""22 	p()ghnoo 		s   DE , E F*E66Fc                 ,   t        |      j                         r&t        |d      5 }|j                         }ddd       n!t	        j
                  t         d| d       d}| j                   d}d|i}	|rY|	j                  d|d       t        |      j                         j                  }
t        d	||	d
i| j                  ddd|
d
       y|	j                  dt        |      d       t        d	||	di| j                  d       y# 1 sw Y   xY w)a  
        Upload a model checkpoint to Ultralytics HUB.

        Args:
            epoch (int): The current training epoch.
            weights (str): Path to the model weights file.
            is_best (bool): Indicates if the current model is the best one so far.
            map (float): Mean average precision of the model.
            final (bool): Indicates if the model is the final model after training.
        rbNu1   WARNING ⚠️ Model upload issue. Missing model .z/uploadepochfinal)rG   maprH   zbest.pt
   i  F   )rS   filesrK   retrytimeoutrR   progressrL   )rG   isBestzlast.pt   )rS   rw   rK   rL   )r   is_fileopenreadr	   warningr   r%   updatestatst_sizer   r'   bool)r1   rr   r`   is_bestrt   rs   ffiler2   rS   filesizes              r6   upload_modelzHUBTrainingSession.upload_model   s    =  "gt$vvx %$ NNfX%VW^V__`abDg&KK56G}))+33H&#!*D 1"&"2"2 ""&!&#+ 	" KKDMBC&#DD8ISWScScjkl/ %$s   D

Dc           	      R   | j                   rt        dt         d| j                   t        | j
                  d| j                  ddd      }|j                         j                  di       j                  d	d
      | _        t        | j                  d          | j                   ry
y
)zPBegin a threaded heartbeat loop to report the agent's status to Ultralytics HUB.rH   z/v1/agent/heartbeat/models/)agentagentIdr      F)rJ   rK   rx   rL   rR   rS   r   Nr   )r-   r   r   r#   
AGENT_NAMEr"   r'   rJ   rQ   r   r(   )r1   rs     r6   r.   z#HUBTrainingSession._start_heartbeat   s     jjf!-.I$--Y+5-1]]$< '+&6&6$%#$%*,A FFHLL488DIDM$"";/0 jjr>   N)Fg        F)__name__
__module____qualname____doc__r7   r/   r;   r@   rO   r+   r   r   r.    r>   r6   r   r      sD    &(DT:
	\
"H#mJ 1 1r>   r   )r9   rA   pathlibr   timer   rh   ultralytics.hub.utilsr   r   r   r   ultralytics.utilsr	   r
   r   r   r   r   ultralytics.utils.errorsr   r   r   r   r>   r6   <module>r      sO     
    S S U U 2.6jw{m6*}TZ>[
n1 n1r>   