a
    yf@                     @   s   d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ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rde d	n
de d
ZG dd dZdS )    N)
HTTPStatus)Path)parse_qsurlparse)HELP_MSGHUB_WEB_ROOTPREFIXTQDM)IS_COLABLOGGERSETTINGS__version__checksemojis)HUBModelErrorzpython-z-colabz-localc                   @   s   e Zd ZdZdd Zed&ddZdd Zd	d
 Ze	dd Z
dd Zd'ddZe	dd ZejeedddZdd Zd(eeeeeddddZe	eejdd d!d"Ze	ejdd#d$d%ZdS ))HUBTrainingSessiona  
    HUB training session for Ultralytics HUB YOLO models. Handles model initialization, heartbeats, and checkpointing.

    Attributes:
        model_id (str): Identifier for the YOLO model being trained.
        model_url (str): URL for the model in Ultralytics HUB.
        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.
    c                 C   s   ddl m} dddd| _i | _i | _i | _d| _d| _d| _d| _	| 
|\}}| _|pbtd}|rpd|ind}||| _z |r| | n| j | _W n: ty   |t d	r| jjstt d
 Y n0 dS )a  
        Initialize the HUBTrainingSession with the provided model identifier.

        Args:
            identifier (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.
            ModuleNotFoundError: If hub-sdk package is not installed.
        r   )	HUBClient   i  ,  )metricsZckpt	heartbeatNapi_key/models/u   WARNING ⚠️ Please log in using 'yolo login API_KEY'. You can find your API Key at: https://hub.ultralytics.com/settings?tab=api+keys.)Zhub_sdkr   rate_limitsmetrics_queuemetrics_upload_failed_queueZtimersmodel	model_url
model_file
train_args_parse_identifierfilenamer   getclient
load_model	Exception
startswithr   authenticatedr   warningr   )self
identifierr   r   model_idZ
active_keycredentials r-   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/hub/session.py__init__    s,    
zHUBTrainingSession.__init__Nc              
   C   s\   z<| |}|r8| t ds8|| |jjs8J d|W S  tttfyV   Y dS 0 dS )zJClass method to create an authenticated HUBTrainingSession or return None.r   zHUB model not loaded correctlyN)r&   r   create_modelr   idPermissionErrorModuleNotFoundErrorAssertionError)clsr*   argssessionr-   r-   r.   create_sessionO   s    
z!HUBTrainingSession.create_sessionc                 C   s   | j || _| jjs"ttdt d| jj | _| j rt	td| j d | j
d}tj|ttd d | jj d| _d	S |   | j| jd
  tt d| j d d	S )zQLoads an existing model from Ultralytics HUB using the provided model identifier.u*   ❌ The specified HUB model does not existr   zLoading trained HUB model     🚀bestZweights_dirZhub)download_dirNr   View model at )r#   r   data
ValueErrorr   r   r1   r   Z
is_trainedprintget_weights_urlr   Z
check_filer   r   r   _set_train_argsstart_heartbeatr   r   infor   )r)   r+   urlr-   r-   r.   r$   \   s    
$zHUBTrainingSession.load_modelc              
   C   s   | dd| dd| dd| ddt| d	d
t| dddd| did| jdd
dd
ii dd| jid}| jdr| j|d d d< | j| | jjsdS t d| jj | _	| j
| jd  tt d| j	 d dS )zGInitializes a HUB training session with the specified model identifier.batchepochsr   Zimgszi  patienced   device cacheram)Z	batchSizerG   Z	imageSizerH   rJ   rL   namer=   .pt.yaml)architectureparent)configZdatasetlineagemetarT   rR   Nr   r   r<   r9   )r"   strr!   replaceendswithr   r0   r1   r   r   rB   r   r   rC   r   )r)   Z
model_argspayloadr-   r-   r.   r0   n   s*    



zHUBTrainingSession.create_modelc                 C   s   d\}}}t | jdv r| }nX| t dr`t| }t |jj}t|j}|	ddgd }nt
d|  dt d	|||fS )
a  
        Parses the given identifier to determine the type of identifier and extract relevant components.

        The method supports different identifier formats:
            - A HUB model URL https://hub.ultralytics.com/models/MODEL
            - A HUB model URL with API Key https://hub.ultralytics.com/models/MODEL?api_key=APIKEY
            - A local filename that ends with '.pt' or '.yaml'

        Args:
            identifier (str): The identifier string to be parsed.

        Returns:
            (tuple): A tuple containing the API key, model ID, and filename as applicable.

        Raises:
            HUBModelError: If the identifier format is not recognized.
        )NNN>   rO   rP   r   r   Nr   zmodel='z invalid, correct format is z/models/MODEL_ID)r   suffixr&   r   r   pathstemr   queryr"   r   )r*   r   r+   r!   
parsed_urlZquery_paramsr-   r-   r.   r       s    

z$HUBTrainingSession._parse_identifierc                 C   s   | j  r,| j  dd| _| j d| _n2| j jd| _| j  rR| j dn| j 	 | _d| jvrpt
dtj| jdd	| _| j j| _d
S )a0  
        Initializes training arguments and creates a model entry on the Ultralytics HUB.

        This method sets up training arguments based on the model's state and updates them with any additional
        arguments provided. It handles different states of the model, such as whether it's resumable, pretrained,
        or requires specific file setup.

        Raises:
            ValueError: If the model is already trained, if required dataset information is missing, or if there are
                issues with the provided training arguments.
        T)r=   resumelastr   rR   r=   zDDataset may still be processing. Please wait a minute and try again.F)verboseN)r   Zis_resumableZget_dataset_urlr   r@   r   r=   r"   Zis_pretrainedZget_architecturer>   r   Zcheck_yolov5u_filenamer1   r+   r)   r-   r-   r.   rA      s    

z"HUBTrainingSession._set_train_argsr      Tc              	      s>    f	dd}
|r4t j|
dd  n|
 S dS )zdAttempts to execute `request_func` with retries, timeout handling, optional threading, and progress.c               
      s  t   } d}td D ]<}t   |  krHtt dt   qX i }|du rtt dt  t d|  qr| nr| t	j
|j  krt	jk rn ndri _|  S |dkr|}rtt | dt d	|j d
 |jsHtt dt d	|j   qXt d|  q|du rdrjd |S )zNAttempts to call `request_func` with retries, timeout, and optional threading.N   zTimeout for request reached. z'Received no response from the request.    r   r    z ()zRequest failed. )timeranger   r(   r   r   sleep_show_upload_progress_iterate_contentr   OKstatus_codeMULTIPLE_CHOICESr"   r   _get_failure_message_should_retryupdate)t0responseimessage	r6   kwargsprogress_totalrequest_funcretryr)   stream_responsetimeoutra   r-   r.   retry_request   s<    


"z7HUBTrainingSession.request_queue.<locals>.retry_requestT)targetdaemonN)	threadingThreadstart)r)   rz   r{   r}   threadra   ry   r|   r6   rx   r~   r-   rw   r.   request_queue   s    -z HUBTrainingSession.request_queuec                 C   s   t jt jt jh}| |v S )zHDetermines if a request should be retried based on the HTTP status code.)r   REQUEST_TIMEOUTBAD_GATEWAYGATEWAY_TIMEOUT)rn   Zretry_codesr-   r-   r.   rq     s
    z HUBTrainingSession._should_retry)rt   r{   r}   c                 C   s   |  |jr&|r"d| d| dS dS |jtjkr\|j}d|d  d|d  d	|d
  dS z| ddW S  ty   Y dS 0 dS )a0  
        Generate a retry message based on the response status code.

        Args:
            response: The HTTP response object.
            retry: The number of retry attempts allowed.
            timeout: The maximum timeout duration.

        Returns:
            (str): The retry message.
        z	Retrying zx for zs.rK   zRate limit reached (zX-RateLimit-Remaining/zX-RateLimit-Limitz). Please retry after zRetry-Afterrv   zNo JSON message.zUnable to read JSON.N)rq   rn   r   TOO_MANY_REQUESTSheadersjsonr"   AttributeError)r)   rt   r{   r}   r   r-   r-   r.   rp     s    z'HUBTrainingSession._get_failure_messagec                 C   s   | j | jj| j ddS )z(Upload model metrics to Ultralytics HUB.T)r   r   )r   r   upload_metricsr   copyrb   r-   r-   r.   r   7  s    z!HUBTrainingSession.upload_metricsF        )epochweightsis_bestmapfinalreturnc                 C   s   t |}| sf|d|j }|rL| rLtt d t|| ntt d| d dS | j	| j
j|t||||dd| |r| jnddd	 dS )
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.
        r`   u0   WARNING ⚠️ Model 'best.pt' not found, copying 'last.pt' to 'best.pt' and uploading. This often happens when resuming training in transient environments like Google Colab. For more reliable training, consider using Ultralytics HUB Cloud. Learn more at https://docs.ultralytics.com/hub/cloud-training.u2    WARNING ⚠️ Model upload issue. Missing model .N
   i  T)
r   r   r   r   r   r{   r}   r   ry   r|   )r   is_file	with_namerZ   r   r(   r   shutilr   r   r   upload_modelrV   statst_size)r)   r   r   r   r   r   r`   r-   r-   r.   r   ;  s.    zHUBTrainingSession.upload_model)content_lengthrt   r   c                 C   sT   t | dddd0}|jddD ]}|t| qW d   n1 sF0    Y  dS )aD  
        Display a progress bar to track the upload progress of a file download.

        Args:
            content_length (int): The total size of the content to be downloaded in bytes.
            response (requests.Response): The response object from the file download request.

        Returns:
            None
        BT   )totalunitZ
unit_scaleZunit_divisor
chunk_sizeN)r	   iter_contentrr   len)r   rt   Zpbarr=   r-   r-   r.   rk   j  s    z(HUBTrainingSession._show_upload_progress)rt   r   c                 C   s   | j ddD ]}qdS )z
        Process the streamed HTTP response data.

        Args:
            response (requests.Response): The response object from the file download request.

        Returns:
            None
        r   r   N)r   )rt   _r-   r-   r.   rl   z  s    z#HUBTrainingSession._iterate_content)N)r   rc   TTNN)Fr   F)__name__
__module____qualname____doc__r/   classmethodr8   r$   r0   staticmethodr    rA   r   rq   requestsResponseintrp   r   rV   boolfloatr   rk   rl   r-   r-   r-   r.   r      sF   /$
#      
B
	   /r   )r   r   rh   httpr   pathlibr   urllib.parser   r   r   Zultralytics.hub.utilsr   r   r   r	   Zultralytics.utilsr
   r   r   r   r   r   Zultralytics.utils.errorsr   Z
AGENT_NAMEr   r-   r-   r-   r.   <module>   s    