
    FPh.6                     L   d dl mZmZmZmZmZ 	 erJ ed   du sJ d dlZ eed      sJ d dlZd dl	m
Z
 dgZdZd	Zd ad
 Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd#dZd#dZd Zd Zd Z d#dZ!d Z"d Z#d Z$d Z%d Z&d  Z'd! Z(ere%e&e'e(d"Z)yi Z)y# eef$ r dZY cw xY w)$    )LOGGERRANKSETTINGSTESTS_RUNNINGopscometTN__version__)Pathdetect)F1_curveP_curveR_curvePR_curveconfusion_matrix)labelslabels_correlogramc                  .    t        j                  dd      S )z\Returns the mode of comet set in the environment variables, defaults to 'online' if not set.
COMET_MODEonlineosgetenv     lC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/utils/callbacks/comet.py_get_comet_moder      s    99\8,,r   c                  .    t        j                  dd      S )zjReturns the model name for Comet from the environment variable 'COMET_MODEL_NAME' or defaults to 'YOLOv8'.COMET_MODEL_NAMEYOLOv8r   r   r   r   _get_comet_model_namer    !   s    99'22r   c                  @    t        t        j                  dd            S )z[Get the evaluation batch logging interval from environment variable or use default value 1.!COMET_EVAL_BATCH_LOGGING_INTERVAL   intr   r   r   r   r    _get_eval_batch_logging_intervalr&   &   s    ryy<a@AAr   c                  @    t        t        j                  dd            S )zRGet the maximum number of image predictions to log from the environment variables.COMET_MAX_IMAGE_PREDICTIONSd   r$   r   r   r   !_get_max_image_predictions_to_logr*   +   s    ryy6<==r   c                 J    t        t        j                  dd            }| |z  S )zSScales the given confidence score by a factor specified in an environment variable.COMET_MAX_CONFIDENCE_SCOREg      Y@)floatr   r   )scorescales     r   _scale_confidence_scorer0   0   s"    "))8%@AE5=r   c                  P    t        j                  dd      j                         dk(  S )z_Determines if the confusion matrix should be logged based on the environment variable settings.COMET_EVAL_LOG_CONFUSION_MATRIXfalsetruer   r   lowerr   r   r   _should_log_confusion_matrixr7   6   s"    996@FFHFRRr   c                  P    t        j                  dd      j                         dk(  S )zVDetermines whether to log image predictions based on a specified environment variable. COMET_EVAL_LOG_IMAGE_PREDICTIONSr4   r5   r   r   r   _should_log_image_predictionsr:   ;   s"    997@FFHFRRr   c                 d    | dk(  rt        j                  |      S t        j                  |      S )z4Return an experiment based on mode and project name.offline)project_name)comet_mlOfflineExperiment
Experiment)moder=   s     r   _get_experiment_typerB   @   s,    y))|DDL99r   c                    t         dvry	 t               }t        j                  d| j                        }t        ||      }|j                  t        |              |j                  t               t               t               t               d       |j                  dd       y# t        $ r"}t        j                   d|        Y d}~yd}~ww xY w)zcEnsures that the experiment object is only created in a single process during distributed training.)r   NCOMET_PROJECT_NAME)eval_batch_logging_intervallog_confusion_matrix_on_evallog_image_predictionsmax_image_predictionszCreated fromyolov8uT   WARNING ⚠️ Comet installed but not initialized correctly, not logging this run. )r   r   r   r   projectrB   log_parametersvars
log_othersr&   r7   r:   r*   	log_other	Exceptionr   warning)args
comet_mode_project_name
experimentes        r   _create_experimentrW   H   s    7s$&
		"6E)*mD
!!$t*-+K+M,H,J%B%D%F%H	L 	M
 	^X6 smnompqrrss   BB$ $	C-C

Cc                 J   | j                   dz   }t        | j                  j                        | j                  z  }||z  }|| j
                  k(  }| j                  j                  }| j                  j                  }||z  dk(  }|xr |dkD  xr |xr | }t        ||||      S )zKReturns metadata for YOLO training including epoch and asset saving status.r#   r   )
curr_epoch	curr_stepsave_assetsfinal_epoch)
epochlentrain_loaderdataset
batch_sizeepochsrR   savesave_perioddict)	trainerrY   train_num_steps_per_epochrZ   r\   rc   rd   save_intervalr[   s	            r   _fetch_trainer_metadatari   \   s    "J #G$8$8$@$@ AWEWEW W66I.K<<D,,**K,1MP;?P}P[K	 r   c                     |\  }}t        j                  | ||      } t        j                  || ||      } t        j                  |       } | ddxxx | dd dz  z  ccc | j	                         } | 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   
xywhn2xyxyscale_boxes	xyxy2xywhtolist)boxresized_image_shapeoriginal_image_shape	ratio_padresized_image_heightresized_image_widths         r   +_scale_bounding_box_to_original_image_shaperx   q   su     1D-- .. 48K
LC
//-s4H)
TC
--
CGs12w{G
**,CJr   c                    |d   | k(  }|d   |   }t        |      dk(  rt        j                  d| d       y|d   |   j                  d      j	                         }|r|D cg c]  }t        ||          }}|d	   |    }|d
   |    }	|d   |    }
g }t        ||      D ]5  \  }}t        ||	||
      }|j                  |gd| t        d      d       7 d|dS c c}w )z.Format ground truth annotations for detection.	batch_idxbboxesr   COMET WARNING: Image: z has no bounding boxes labelsNclsr#   	ori_shaperesized_shaperu   gt_g      ?boxeslabelr.   ground_truthnamedata)
r^   r   debugsqueezerq   strziprx   appendr0   )img_idx
image_pathbatchclass_name_mapindicesr{   
cls_labelsr   rt   rs   ru   r   rr   s                r   ._format_ground_truth_annotations_for_detectionr      s   K G+G8_W%F
6{a-j\9VWXug&..q188:J>HIjUc./0j
I -g609k"7+ID&*-
U9#?RThjstU5'],S15 	6 . #D11 Js   $Cc                 F   | j                   }|j                         rt        |      n|}|j                  |      }|st	        j
                  d|  d       yg }|D ]@  }|d   }t        |d         }	|d   }
|rt        ||
         }
|j                  |g|
|	d       B d|d	S )
z;Format YOLO predictions for object detection visualization.r|   z" has no bounding boxes predictionsNbboxr.   category_idr   
predictionr   )	stem	isnumericr%   getr   r   r0   r   r   )r   metadataclass_label_mapr   image_idpredictionsr   r   r   r.   	cls_labels              r   ,_format_prediction_annotations_for_detectionr      s    ??D NN,s4y$H,,x(K-j\9[\]D!
6"'
7(;<}-	OI67Iug	EJK " !$//r   c                 x    t        | |||      }t        |||      }||fD cg c]  }||	 }}|r|gS dS c c}w )z?Join the ground truth and prediction annotations if they exist.N)r   r   )	r   r   r   prediction_metadata_mapr   ground_truth_annotationsprediction_annotations
annotationannotationss	            r   _fetch_annotationsr      so    MgWachN] _I*VmJY[ '?@V%Ws%Wz[e[q
%W  s'K=1T1ss   77c                 p    i }| D ].  }|j                  |d   g        ||d      j                  |       0 |S )zNCreate metadata map for model predictions by groupings them based on image ID.r   )
setdefaultr   )model_predictionspred_metadata_mapr   s      r   _create_prediction_metadata_mapr      sG    '
$$Z
%;R@*Z0188D ( r   c                     |j                   j                  j                  }t        |j                  d   j                               dgz   }| j                  ||t        |      ||       y)z-Log the confusion matrix to Comet experiment.names
background)matrixr   max_categoriesr]   stepN)	validatorr   r   listr   valueslog_confusion_matrixr^   )rU   rf   rZ   rY   conf_matr   s         r   _log_confusion_matrixr      sb      1188Hg&--/0L>AE##5z $ r   c                     |r4t        ||      D ]$  \  }}| j                  ||j                  ||       & y|D ]   }| j                  ||j                  |       " y)z8Logs images to the experiment with optional annotations.)r   r   r   )r   r   N)r   	log_imager   )rU   image_pathsrZ   r   r   r   s         r   _log_imagesr      s]    &)+{&C"J
  *//	_i j 'D &J  *//	 R &r   c           	         |j                   j                  }|t        vry|j                  }|syt	        |      }|j
                  }|j                  }t               }t               }	t        |      D ]h  \  }
}|
dz   |z  dk7  r|d   }t        |      D ]D  \  }}t        |	k\  r  yt        |      }t        |||||      }t        | |g||       t        dz  a
F j y)z8Logs predicted boxes for a single image during training.Nr#   r   im_file)r   )rR   taskCOMET_SUPPORTED_TASKSjdictr   
dataloaderr   r&   r*   	enumerate_comet_image_prediction_countr
   r   r   )rU   r   rZ   r   r   predictions_metadata_mapr   r   batch_logging_intervalrI   rz   r   r   r   r   r   s                   r   _log_image_predictionsr      s     >>D((OOE>uE%%JooO=?=?%j1	5M33q8I&#,[#9GZ,0EEj)J,(K '	 *Q.)% $: 2r   c                     t         D cg c]  }|j                  | dz   }}t        | |d       t        D cg c]  }|j                  | dz   }}t        | |d       yc c}w c c}w )z9Logs evaluation plots and label plots for the experiment.z.pngNz.jpg)EVALUATION_PLOT_NAMESsave_dirr   LABEL_PLOT_NAMES)rU   rf   plotsplot_filenamesr   label_plot_filenamess         r   
_log_plotsr     sv    EZ[EZEg&&E7$7EZN[
ND1M]^M]6G,,&>M]^
0$7	 \ _s
   A"A'c                 h    t               }| j                  |t        |j                        dd       y)z'Log the best-trained model to Comet.ml.zbest.ptT)file_or_folder	file_name	overwriteN)r    	log_modelr   best)rU   rf   
model_names      r   
_log_modelr     s2    &(J7<<(	  r   c                 z    t        j                         }t        |dd      }|r|st        | j                         yy)zTCreates or resumes a CometML experiment at the start of a YOLO pre-training routine.aliveFN)r>   get_global_experimentgetattrrW   rR   )rf   rU   is_alives      r   on_pretrain_routine_startr   (  s4    //1Jz7E2HX7<<( &r   c                    t        j                         }|syt        |       }|d   }|d   }|j                  | j	                  | j
                  d      ||       |dk(  r't        || j                  j                  d      |       yy)	z@Log metrics and save batch images at the end of training epochs.NrY   rZ   train)prefixr   r]   r#   ztrain_batch*.jpg)	r>   r   ri   log_metricslabel_loss_itemstlossr   r   glob)rf   rU   r   rY   rZ   s        r   on_train_epoch_endr   0  s    //1J&w/H,'J%I  w ?   QJ 0 0 5 56H I9U r   c                    t        j                         }|syt        |       }|d   }|d   }|d   }|j                  | j                  ||       |j                  | j
                  ||       |dk(  r ddlm} |j                   ||       ||       |syt        ||        t               rt        || ||       t               rt        || j                  |       yy)	z+Logs model assets at the end of each epoch.NrY   rZ   r[   r   r#   r   )model_info_for_loggers)r>   r   ri   r   metricslrultralytics.utils.torch_utilsr   r   r7   r   r:   r   r   )rf   rU   r   rY   rZ   r[   r   s          r   on_fit_epoch_endr   D  s    //1J&w/H,'J%I=)K7??*M7::IZHQH5g>YV`az7##%j'9jI$&z7+<+<iH 'r   c                 *   t        j                         }|syt        |       }|d   }|d   }| j                  j                  }t        ||        |rt        ||        t        || ||       t        || j                  |       |j                          day)z*Perform operations at the end of training.NrY   rZ   r   )r>   r   ri   rR   r   r   r   r   r   r   endr   )rf   rU   r   rY   rZ   r   s         r   on_train_endr   _  s    //1J&w/H,'J%ILLEz7#:w'*gy*E:w'8'8)DNN %&!r   )r   r   r   r   )N)*ultralytics.utilsr   r   r   r   r   r>   hasattrr   pathlibr
   r   r   r   r   ImportErrorAssertionErrorr   r    r&   r*   r0   r7   r:   rB   rW   ri   rx   r   r   r   r   r   r   r   r   r   r   r   r   r   	callbacksr   r   r   <module>r      s'   I HG$$$8]+++ &J ]5$%!-
3
B
>
S
S
:s(*,260.	2
S*/Z8)V(I6&6 &. ";,( 	"	 46	 
}
 	^$ Hs   /B 	B#"B#