a
    Dfb                  	   @   s   d Z ddlZddlZddlmZ ddlZddlZddlm	Z	m
Z
 z*ddlZddlmZmZ eedshJ W n eefy   dZY n0 dd ZG d	d
 d
ZdS )z2Main Logger class for ClearML experiment tracking.    N)Path)	Annotatorcolors)DatasetTask__version__c                 C   s\  |  dd}tj|d}t| }ttt|d tt|d  }t|dkrbt	dnt|dkrvt	d	t
|d }t|}W d
   n1 s0    Y  t| h dsJ dt }|d rt||d   nd
|d< |d rt||d   nd
|d< |d r8t||d   nd
|d< |d |d< |d |d< |S )zQLoad in a clearml dataset and fill the internal data_dict with its contents.
    
clearml:// )
dataset_idz*.yamlz*.yml   z{More than one yaml file was found in the dataset root, cannot determine which one contains the dataset definition this way.r   ztNo yaml definition found in dataset root path, check that there is a correct yaml file inside the dataset root path.N>   nctestvaltrainnameszThe right keys were not found in the yaml file, make sure it at least has the following keys: ('train', 'test', 'val', 'nc', 'names')r   r   r   r   r   )replacer   getr   Zget_local_copylistglobstrlen
ValueErroropenyaml	safe_loadsetkeys
issupersetdictresolve)Zclearml_info_stringr
   datasetZdataset_root_pathZyaml_filenamesfZdataset_definition	data_dict r#   Y/data/NAS7/SABIOD/METHODE/ermites/yolo-dyni/yolov5/utils/loggers/clearml/clearml_utils.pyconstruct_dataset   sJ    (
(r%   c                   @   s,   e Zd ZdZdd ZdddZddd	Zd
S )ClearmlLoggera  Log training runs, datasets, models, and predictions to ClearML.

    This logger sends information to ClearML at app.clear.ml or to your own hosted server. By default,
    this information includes hyperparameters, system configuration and metrics, model metrics, code information and
    basic data metrics and analyses.

    By providing additional command line arguments to train.py, datasets,
    models and predictions can also be logged.
    c                 C   s   d| _ t | _d| _|j| _t| _d| _d| _| jrtj	|j
dkrH|j
nd|jdkrZ|jnddgd|jd	d
id| _| jj|dd | jj|dd | jjdddd |jdrt|j| _| j|_dS )a)  
        - Initialize ClearML Task, this object will capture the experiment
        - Upload dataset version to ClearML Data if opt.upload_dataset is True

        arguments:
        opt (namespace) -- Commandline arguments for this run
        hyp (dict) -- Hyperparameters for this run

        r      Nz
runs/trainYOLOv5expTrainingTpytorchF)project_nameZ	task_nametagsZ
output_uriZreuse_last_task_idZauto_connect_frameworksZHyperparameters)nameArgszultralytics/yolov5:latestz7--ipc=host -e="CLEARML_AGENT_SKIP_PYTHON_ENV_INSTALL=1"zpip install clearml)Zdocker_argumentsZdocker_setup_bash_scriptr   )current_epochr   current_epoch_logged_imagesmax_imgs_to_log_per_epochbbox_intervalclearmltaskr"   r   initprojectr.   exist_okconnectZset_base_dockerdata
startswithr%   )selfopthypr#   r#   r$   __init__B   s2    
zClearmlLogger.__init__Debug Samplesc                 C   sf   |D ]\}|  rtd|j}|r2t| d nd}| j j||j	|
 dt||d qdS )z
        Log files (images) as debug samples in the ClearML task.

        arguments:
        files (List(PosixPath)) a list of file paths in PosixPath format
        title (str) A title that groups together images with the same values
        z_batch(\d+)r   r	   )titleseriesZ
local_path	iterationN)existsresearchr.   intgroupsr5   
get_loggerreport_imager   groupr   )r<   filesrA   r!   itrC   r#   r#   r$   log_debug_samplest   s    zClearmlLogger.log_debug_samples      ?c                 C   s^  t | j| jk rZ| jdkrZ| j| j dkrZ|| jvrZtt|d	dd
   dd}t|dd}tt|dddf |dddf |ddddf D ]z\}\}	}
}t|}|t|
 }tt|	d	 d}| d
| d}|	|kr|j|  |d |j|  ||d q| }| j jd|j| j|d | j| dS )a  
        Draw the bounding boxes on a single image and report the result as a ClearML debug sample.

        arguments:
        image_path (PosixPath) the path the original image file
        boxes (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
        class_names (dict): dict containing mapping of class int to class name
        image (Tensor): A torch tensor containing the actual image data
        r         T)impilN      d   z: %)outline)labelcolorzBounding Boxes)rA   rB   rC   image)r   r1   r2   r0   r3   npascontiguousarraymoveaxismulclampbytecpunumpyr   	enumeratezipr   rG   roundfloat	rectangle	box_labelresultr5   rI   rJ   r.   add)r<   
image_pathboxesclass_namesr[   Zconf_thresholdrR   	annotatoriconfZclass_nrboxrZ   
class_nameZconfidence_percentagerY   Zannotated_imager#   r#   r$   log_image_with_boxes   s&    
.Fz"ClearmlLogger.log_image_with_boxesN)r@   )rO   )__name__
__module____qualname____doc__r?   rN   rt   r#   r#   r#   r$   r&   7   s   
2
r&   )rx   r   rE   pathlibr   rc   r\   r   utils.plotsr   r   r4   r   r   hasattrImportErrorAssertionErrorr%   r&   r#   r#   r#   r$   <module>   s   
#