a
    Df<                   	   @   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	 ee
 Zejd Zeeejvrtejee eeddZe	d d	Zz$d dlZeed
sJ ee W n eefy   dZY n0 G dd dZee jfddZdS )    N)contextmanager)Path)LOGGERcolorstr   RANKwandbu   : WARNING ⚠️ wandb is deprecated and will be removed in a future release. See supported integrations at https://github.com/ultralytics/yolov5#integrations.__version__c                   @   sL   e Zd ZdZdddZdd Zdd	d
Zdd Zdd Zdd Z	dd Z
dS )WandbLoggera  Log training runs, datasets, models, and predictions to Weights & Biases.

    This logger sends information to W&B at wandb.ai. By default, this information
    includes hyperparameters, system configuration and metrics, model metrics,
    and basic data metrics and analyses.

    By providing additional command line arguments to train.py, datasets,
    models and predictions can also be logged.

    For more on how this logger is used, see the Weights & Biases documentation:
    https://docs.wandb.com/guides/integrations/yolov5
    NTrainingc              
   C   s   || _ ttrtjnd | _| _d\| _| _d\| _| _d| _d\| _	| _
d| _d| _| jrtjstj|d|jdkrvdn
t|jj|j|jdkr|jnd||dd	ntj| _| jr| j d
krt|jtr|j| _| | dS )al  
        - Initialize WandbLogger instance
        - Upload dataset if opt.upload_dataset is True
        - Setup training processes if job_type is 'Training'

        arguments:
        opt (namespace) -- Commandline arguments for this run
        run_id (str) -- Run ID of W&B run to be resumed
        job_type (str) -- To set the job_type for this run

       N)NN   allowz
runs/trainYOLOv5expT)configresumeprojectentitynamejob_typeidallow_val_changer   )r   r	   run	wandb_runZval_artifactZtrain_artifactZtrain_artifact_pathZval_artifact_pathZresult_artifactZ	val_tableZresult_tableZmax_imgs_to_log	data_dictinitr   r   stemr   r   
isinstancedatadictsetup_training)selfoptrun_idr    r%   U/data/NAS7/SABIOD/METHODE/ermites/yolo-dyni/yolov5/utils/loggers/wandb/wandb_utils.py__init__-   s4    	
zWandbLogger.__init__c                 C   s   i d | _ | _|j| _t|jtr| |\}}|rt|d | _| j	j
}t| j|j|j|j|j|j|jf\|_|_|_|_|_|_|_|jdkr|jdkr|jd nd | _|_|js|jr|jd  | _|_dS )a  
        Setup the necessary processes for training YOLO models:
          - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
          - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
          - Setup log_dict, initialize bbox_interval

        arguments:
        opt (namespace) -- commandline arguments for this run

        r   last.ptr   
      N)log_dictcurrent_epochbbox_intervalr   r   strZdownload_model_artifactr   weightsr   r   save_period
batch_sizeepochshypimgszevolvenoplots)r"   r#   	model_dir_r   r%   r%   r&   r!   T   s"     
 zWandbLogger.setup_trainingFc              
   C   s   t jdt jj d dt||d |j|j|j|dd}|jt|d dd t j	|d	d
dt| j
 |rldndgd td|d   dS )a  
        Log the model checkpoint as W&B artifact

        arguments:
        path (Path)   -- Path of directory containing the checkpoints
        opt (namespace) -- Command line arguments for this run
        epoch (int)  -- Current epoch number
        fitness_score (float) -- fitness score for current epoch
        best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
        run__modelmodelr*   )Zoriginal_urlZepochs_trainedzsave periodr   Ztotal_epochsfitness_score)typemetadatar(   )r   latestlastzepoch best )aliaseszSaving model artifact on epoch N)r	   Artifactr   r   r.   r0   r   r2   add_filelog_artifactr,   r   info)r"   pathr#   epochr<   
best_modelZmodel_artifactr%   r%   r&   	log_modelo   s    	zWandbLogger.log_modelc                 C   s   d S )Nr%   )r"   predprednrH   namesimr%   r%   r&   val_one_image   s    zWandbLogger.val_one_imagec                 C   s&   | j r"| D ]\}}|| j|< qdS )z
        save the metrics to the logging dictionary

        arguments:
        log_dict (Dict) -- metrics/media to be logged in current step
        N)r   itemsr+   )r"   r+   keyvaluer%   r%   r&   log   s    zWandbLogger.logc                 C   s   | j rt l zt| j W nD tyb } z,td|  | j   d| _ W Y d}~n
d}~0 0 i | _W d   n1 s~0    Y  dS )z
        commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.

        arguments:
        best_result (boolean): Boolean representing if the result of this evaluation is best or not
        z]An error occurred in wandb logger. The training will proceed without interruption. More info
N)	r   all_logging_disabledr	   rT   r+   BaseExceptionr   rG   finish)r"   er%   r%   r&   	end_epoch   s    
zWandbLogger.end_epochc                 C   sV   | j rR| jr>t  t| j W d   n1 s40    Y  tj  tt	 dS )zC
        Log metrics if any and finish the current W&B run
        N)
r   r+   rU   r	   rT   r   rW   r   warningDEPRECATION_WARNING)r"   r%   r%   r&   
finish_run   s    *
zWandbLogger.finish_run)Nr   )F)__name__
__module____qualname____doc__r'   r!   rK   rP   rT   rY   r\   r%   r%   r%   r&   r      s   
'
r   c              	   c   s:   t jjj}t |  zdV  W t | nt | 0 dS )a@   source - https://gist.github.com/simon-weber/7853144
    A context manager that will prevent any logging messages triggered during the body from being processed.
    :param highest_level: the maximum logging level in use.
      This would only need to be changed if a custom level greater than CRITICAL is defined.
    N)loggingrootmanagerdisable)Zhighest_levelZprevious_levelr%   r%   r&   rU      s
    

rU   )ra   ossys
contextlibr   pathlibr   utils.generalr   r   __file__resolveFILEparentsROOTr.   rH   appendintgetenvr   r[   r	   hasattrrZ   ImportErrorAssertionErrorr   CRITICALrU   r%   r%   r%   r&   <module>   s*   

 