a
    yf5                  	   @   sr  d dl mZmZmZmZmZ zXer&J ed du s6J d dlZeedsLJ d dlZd dl	m
Z
 dgZdZd	Zd aW n eefy   dZY n0 d
d Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd;d d!Zd<d"d#Zd$d% Zd&d' Zd(d) Z d=d*d+Z!d,d- Z"d.d/ Z#d0d1 Z$d2d3 Z%d4d5 Z&d6d7 Z'd8d9 Z(erje%e&e'e(d:ni Z)dS )>    )LOGGERRANKSETTINGSTESTS_RUNNINGopscometTN__version__)Pathdetect)ZF1_curveZP_curveZR_curveZPR_curveconfusion_matrix)labelsZlabels_correlogramc                   C   s   t ddS )z\Returns the mode of comet set in the environment variables, defaults to 'online' if not set.Z
COMET_MODEZonlineosgetenv r   r   ]/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/utils/callbacks/comet.py_get_comet_mode   s    r   c                   C   s   t ddS )zjReturns the model name for Comet from the environment variable 'COMET_MODEL_NAME' or defaults to 'YOLOv8'.ZCOMET_MODEL_NAMEZYOLOv8r   r   r   r   r   _get_comet_model_name!   s    r   c                   C   s   t tddS )z[Get the evaluation batch logging interval from environment variable or use default value 1.Z!COMET_EVAL_BATCH_LOGGING_INTERVAL   intr   r   r   r   r   r    _get_eval_batch_logging_interval&   s    r   c                   C   s   t tddS )zRGet the maximum number of image predictions to log from the environment variables.ZCOMET_MAX_IMAGE_PREDICTIONSd   r   r   r   r   r   !_get_max_image_predictions_to_log+   s    r   c                 C   s   t tdd}| | S )zSScales the given confidence score by a factor specified in an environment variable.ZCOMET_MAX_CONFIDENCE_SCOREg      Y@)floatr   r   )scorescaler   r   r   _scale_confidence_score0   s    r   c                   C   s   t dd dkS )z_Determines if the confusion matrix should be logged based on the environment variable settings.ZCOMET_EVAL_LOG_CONFUSION_MATRIXfalsetruer   r   lowerr   r   r   r   _should_log_confusion_matrix6   s    r"   c                   C   s   t dd dkS )zVDetermines whether to log image predictions based on a specified environment variable.Z COMET_EVAL_LOG_IMAGE_PREDICTIONSr   r    r   r   r   r   _should_log_image_predictions;   s    r#   c                 C   s    | dkrt j|dS t j|dS )z4Return an experiment based on mode and project name.Zoffline)project_name)comet_mlZOfflineExperimentZ
Experiment)moder$   r   r   r   _get_experiment_type@   s    r'   c              
   C   s   t dvrdS zXt }td| j}t||}|t|  |t	 t
 t t d |dd W n4 ty } ztd|  W Y d}~n
d}~0 0 dS )zcEnsures that the experiment object is only created in a single process during distributed training.>   r   NZCOMET_PROJECT_NAME)Zeval_batch_logging_intervalZlog_confusion_matrix_on_evalZlog_image_predictionsmax_image_predictionszCreated fromZyolov8uT   WARNING ⚠️ Comet installed but not initialized correctly, not logging this run. )r   r   r   r   projectr'   Zlog_parametersvarsZ
log_othersr   r"   r#   r   Z	log_other	Exceptionr   warning)argsZ
comet_mode_project_name
experimenter   r   r   _create_experimentH   s"    
r2   c           	      C   sp   | j d }t| jj| j }|| }|| jk}| jj}| jj}|| dk}|o^|dko^|o^| }t	||||dS )zKReturns metadata for YOLO training including epoch and asset saving status.r   r   )
curr_epoch	curr_stepsave_assetsfinal_epoch)
epochlenZtrain_loaderZdatasetZ
batch_sizeZepochsr.   savesave_perioddict)	trainerr3   Ztrain_num_steps_per_epochr4   r6   r9   r:   Zsave_intervalr5   r   r   r   _fetch_trainer_metadata_   s    

r=   c                 C   s^   |\}}t j| ||d} t || ||} t | } | dd  | dd d 8  < |  } | S )z
    YOLOv8 resizes images during training and the label values are normalized based on this resized shape.

    This function rescales the bounding box labels to the original image shape.
    )hwN   )r   Z
xywhn2xyxyZscale_boxesZ	xyxy2xywhtolist)boxresized_image_shapeoriginal_image_shape	ratio_padZresized_image_heightZresized_image_widthr   r   r   +_scale_bounding_box_to_original_image_shapeo   s    
 rF   c                    s   |d | k}|d | }t |dkr:td| d dS |d | d } rf fd	d
|D }|d |  }|d |  }|d |  }	g }
t||D ]4\}}t||||	}|
|gd| tdd qd|
dS )z.Format ground truth annotations for detection.	batch_idxbboxesr   COMET WARNING: Image: z has no bounding boxes labelsNclsr   c                    s   g | ]}t  | qS r   )str).0labelclass_name_mapr   r   
<listcomp>       zB_format_ground_truth_annotations_for_detection.<locals>.<listcomp>Z	ori_shapeZresized_shaperE   Zgt_g      ?boxesrM   r   Zground_truthnamedata)	r8   r   debugZsqueezerA   ziprF   appendr   )img_idx
image_pathbatchrO   indicesrH   Z
cls_labelsrD   rC   rE   rV   rB   rM   r   rN   r   ._format_ground_truth_annotations_for_detection   s*    r^   c                 C   s   | j }| rt|n|}||}|s>td|  d dS g }|D ]D}|d }t|d }	|d }
|rvt||
 }
||g|
|	d qFd|d	S )
z;Format YOLO predictions for object detection visualization.rI   z" has no bounding boxes predictionsNZbboxr   Zcategory_idrR   
predictionrT   )	stem	isnumericr   getr   rW   r   rK   rY   )r[   metadataclass_label_mapr`   image_idZpredictionsrV   r_   rS   r   Z	cls_labelr   r   r   ,_format_prediction_annotations_for_detection   s    
rf   c                 C   s:   t | |||}t|||}dd ||fD }|r6|gS dS )z?Join the ground truth and prediction annotations if they exist.c                 S   s   g | ]}|d ur|qS )Nr   )rL   
annotationr   r   r   rP      s   z&_fetch_annotations.<locals>.<listcomp>N)r^   rf   )rZ   r[   r\   Zprediction_metadata_maprd   Zground_truth_annotationsZprediction_annotationsannotationsr   r   r   _fetch_annotations   s    ri   c                 C   s4   i }| D ]&}| |d g  ||d  | q|S )zNCreate metadata map for model predictions by groupings them based on image ID.re   )
setdefaultrY   )Zmodel_predictionsZpred_metadata_mapr_   r   r   r   _create_prediction_metadata_map   s
    rk   c                 C   s>   |j jj}t|jd  dg }| j||t|||d dS )z-Log the confusion matrix to Comet experiment.names
background)matrixr   Zmax_categoriesr7   stepN)	validatorr   rn   listrV   valuesZlog_confusion_matrixr8   )r0   r<   r4   r3   Zconf_matrl   r   r   r   _log_confusion_matrix   s
    
rs   c                 C   sN   |r.t ||D ]\}}| j||j||d qn|D ]}| j||j|d q2dS )z8Logs images to the experiment with optional annotations.)rU   ro   rh   )rU   ro   N)rX   Z	log_imager`   )r0   image_pathsr4   rh   r[   rg   r   r   r   _log_images   s
    ru   c                 C   s   |j j}|tvrdS |j}|s"dS t|}|j}|j}t }t }	t	|D ]v\}
}|
d | dkrdqJ|d }t	|D ]J\}}t
|	kr  dS t|}t|||||}t| |g||d t
d7 a
qtqJdS )z8Logs predicted boxes for a single image during training.Nr   r   Zim_file)rh   )r.   taskCOMET_SUPPORTED_TASKSjdictrk   
dataloaderrl   r   r   	enumerate_comet_image_prediction_countr	   ri   ru   )r0   rp   r4   rv   rx   Zpredictions_metadata_mapry   rd   Zbatch_logging_intervalr)   rG   r\   rt   rZ   r[   rh   r   r   r   _log_image_predictions   sB    r|   c                    s@    fddt D }t| |d  fddtD }t| |d dS )z9Logs evaluation plots and label plots for the experiment.c                    s   g | ]} j | d  qS )z.pngsave_dir)rL   plotsr<   r   r   rP     rQ   z_log_plots.<locals>.<listcomp>Nc                    s   g | ]} j | d  qS )z.jpgr}   )rL   r   r   r   r   rP     rQ   )EVALUATION_PLOT_NAMESru   LABEL_PLOT_NAMES)r0   r<   Zplot_filenamesZlabel_plot_filenamesr   r   r   
_log_plots  s    r   c                 C   s"   t  }| j|t|jddd dS )z'Log the best-trained model to Comet.ml.zbest.ptT)Zfile_or_folder	file_name	overwriteN)r   Z	log_modelrK   best)r0   r<   Z
model_namer   r   r   
_log_model  s    r   c                 C   s*   t  }t|dd}|r|s&t| j dS )zTCreates or resumes a CometML experiment at the start of a YOLO pre-training routine.aliveFN)r%   get_global_experimentgetattrr2   r.   )r<   r0   is_aliver   r   r   on_pretrain_routine_start"  s    r   c                 C   sd   t  }|sdS t| }|d }|d }|j| j| jdd||d |dkr`t|| jd| dS )	z@Log metrics and save batch images at the end of training epochs.Nr3   r4   train)prefixro   r7   r   ztrain_batch*.jpg)	r%   r   r=   log_metricsZlabel_loss_itemsZtlossru   r~   glob)r<   r0   rc   r3   r4   r   r   r   on_train_epoch_end*  s    r   c                 C   s   t  }|sdS t| }|d }|d }|d }|j| j||d |j| j||d |dkr|ddlm} |j|| ||d |sdS t||  t	 rt
|| || t rt|| j| dS )	z+Logs model assets at the end of each epoch.Nr3   r4   r5   r   r   r   )model_info_for_loggers)r%   r   r=   r   ZmetricslrZultralytics.utils.torch_utilsr   r   r"   rs   r#   r|   rp   )r<   r0   rc   r3   r4   r5   r   r   r   r   on_fit_epoch_end:  s&    
r   c                 C   st   t  }|sdS t| }|d }|d }| jj}t||  |rHt||  t|| || t|| j	| |
  dadS )z*Perform operations at the end of training.Nr3   r4   r   )r%   r   r=   r.   r   r   r   rs   r|   rp   endr{   )r<   r0   rc   r3   r4   r   r   r   r   on_train_endV  s    

r   )r   r   r   r   )N)N)N)*Zultralytics.utilsr   r   r   r   r   r%   hasattrr   pathlibr	   rw   r   r   r{   ImportErrorAssertionErrorr   r   r   r   r   r"   r#   r'   r2   r=   rF   r^   rf   ri   rk   rs   ru   r|   r   r   r   r   r   r   	callbacksr   r   r   r   <module>   s\   



	
-	