
    hht]              	       h   d dl mZ d dlmZ d dlmZmZmZ d dlZd dl	Z
d dlmZmZmZmZmZ 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dgZdZdZdZdZ dZ!d a"de%fdZ&de%fdZ'de(fdZ)de(fdZ*de+de+fdZ,de-fdZ.de-fdZ/deddfdZ0de1fdZ2dee+   fdZ3d2dee1   fdZ4d3dee1   fd Z5d!e%d"edeeee         fd#Z6dee   fd$Z7de1fd%Z8d4d&Z9d2d4d'Z:d4d(Z;d4d)Z<d4d*Z=d+e(ddfd,Z>d4d-Z?d4d.Z@d4d/ZAd4d0ZBere?e@eAeBd1ZCyi ZCy# e#e$f$ r dZY w xY w)5    )Callable)SimpleNamespace)AnyListOptionalN)LOGGERRANKSETTINGSTESTS_RUNNINGops)ClassifyMetrics
DetMetrics
OBBMetricsPoseMetricsSegmentMetricscometT__version__)Pathdetectsegment)confusion_matrixconfusion_matrix_normalized)F1_curveP_curveR_curvePR_curve)labelslabels_correlogram)BoxMask)r   Posereturnc                  `    t        j                  d      } | t        j                  d       | S y)zIReturn the Comet mode from environment variables, defaulting to 'online'.
COMET_MODEa  The COMET_MODE environment variable is deprecated. Please use COMET_START_ONLINE to set the Comet experiment mode. To start an offline Comet experiment, use 'export COMET_START_ONLINE=0'. If COMET_START_ONLINE is not set or is set to '1', an online Comet experiment will be created.online)osgetenvr   warning)
comet_modes    _/var/www/html/dev/engine/venv/lib/python3.12/site-packages/ultralytics/utils/callbacks/comet.py_get_comet_moder+   '   s3    <(Jm	
     c                  .    t        j                  dd      S )zRReturn the Comet model name from environment variable or default to 'Ultralytics'.COMET_MODEL_NAMEUltralytics)r&   r'    r,   r*   _get_comet_model_namer1   6   s    99'77r,   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'   r0   r,   r*    _get_eval_batch_logging_intervalr7   ;   s    ryy<a@AAr,   c                  @    t        t        j                  dd            S )zNGet the maximum number of image predictions to log from environment variables.COMET_MAX_IMAGE_PREDICTIONSd   r5   r0   r,   r*   !_get_max_image_predictions_to_logr;   @   s    ryy6<==r,   scorec                 J    t        t        j                  dd            }| |z  S )zIScale the confidence score by a factor specified in environment variable.COMET_MAX_CONFIDENCE_SCOREg      Y@)floatr&   r'   )r<   scales     r*   _scale_confidence_scorerA   E   s"    "))8%@AE5=r,   c                  P    t        j                  dd      j                         dk(  S )zZDetermine if the confusion matrix should be logged based on environment variable settings.COMET_EVAL_LOG_CONFUSION_MATRIXfalsetruer&   r'   lowerr0   r,   r*   _should_log_confusion_matrixrH   K   s"    996@FFHFRRr,   c                  P    t        j                  dd      j                         dk(  S )zIDetermine whether to log image predictions based on environment variable. COMET_EVAL_LOG_IMAGE_PREDICTIONSrE   rF   r0   r,   r*   _should_log_image_predictionsrK   P   s"    997@FFHFRRr,   argsc                    t         dvryt        j                  d      $t               }|dk7  rdndt        j                  d<   	 t        j                  d| j
                        }t        j                  |      }|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)a+  
    Resume CometML experiment or create a new experiment based on args.

    Ensures that the experiment object is only created in a single process during distributed training.

    Args:
        args (SimpleNamespace): Training arguments containing project configuration and other parameters.
    >   r   NCOMET_START_ONLINEoffline10COMET_PROJECT_NAME)project_name)eval_batch_logging_intervallog_confusion_matrix_on_evallog_image_predictionsmax_image_predictionszCreated fromultralyticszEComet installed but not initialized correctly, not logging this run. )r	   r&   r'   r+   environprojectcomet_mlstartlog_parametersvars
log_othersr7   rH   rK   r;   	log_other	Exceptionr   r(   )rL   r)   _project_name
experimentes        r*   _resume_or_create_experimentrf   U   s     7 
yy%&.$&
2<	2I3s

'(d		"6E^^?
!!$t*-/O/Q0L0N)F)H)J)L		
 	^]; d^_`^abccds   BC 	D&DD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 )aH  
    Return metadata for YOLO training including epoch and asset saving status.

    Args:
        trainer (ultralytics.engine.trainer.BaseTrainer): The YOLO trainer object containing training state and config.

    Returns:
        (dict): Dictionary containing current epoch, step, save assets flag, and final epoch flag.
    r4   r   )
curr_epoch	curr_stepsave_assetsfinal_epoch)
epochlentrain_loaderdataset
batch_sizeepochsrL   savesave_perioddict)	trainerrh   train_num_steps_per_epochri   rk   rr   rs   save_intervalrj   s	            r*   _fetch_trainer_metadatarx   y   s     "J #G$8$8$@$@ AWEWEW W66I.K<<D,,**K,1MP;?P}P[K:almmr,   c                     |\  }}t        j                  | ||      } t        j                  || ||      } t        j                  |       } | ddxxx | dd dz  z  ccc | j	                         } | S )a  
    Scale bounding box from resized image coordinates to original image coordinates.

    YOLO 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.

    Args:
        box (torch.Tensor): Bounding box in normalized xywh format.
        resized_image_shape (tuple): Shape of the resized image (height, width).
        original_image_shape (tuple): Shape of the original image (height, width).
        ratio_pad (tuple): Ratio and padding information for scaling.

    Returns:
        (List[float]): Scaled bounding box coordinates in xywh format with top-left corner adjustment.
    )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_shaper      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 )a9  
    Format ground truth annotations for object detection.

    This function processes ground truth annotations from a batch of images for object detection tasks. It extracts
    bounding boxes, class labels, and other metadata for a specific image in the batch, and formats them for
    visualization or evaluation.

    Args:
        img_idx (int): Index of the image in the batch to process.
        image_path (str | Path): Path to the image file.
        batch (dict): Batch dictionary containing detection data with keys:
            - 'batch_idx': Tensor of batch indices
            - 'bboxes': Tensor of bounding boxes in normalized xywh format
            - 'cls': Tensor of class labels
            - 'ori_shape': Original image shapes
            - 'resized_shape': Resized image shapes
            - 'ratio_pad': Ratio and padding information
        class_name_map (dict, optional): Mapping from class indices to class names.

    Returns:
        (dict | None): Formatted ground truth annotations with the following structure:
            - 'boxes': List of box coordinates [x, y, width, height]
            - 'label': Label string with format "gt_{class_name}"
            - 'score': Confidence score (always 1.0, scaled by _scale_confidence_score)
        Returns None if no bounding boxes are found for the image.
    	batch_idxbboxesr   Comet Image: z has no bounding boxes labelsNclsr4   	ori_shaperesized_shaper   gt_g      ?boxeslabelr<   ground_truthnamedata)
rm   r   debugsqueezer   strzipr   appendrA   )img_idx
image_pathbatchclass_name_mapindicesr   
cls_labelsr   r   r   r   r   r   s                r*   ._format_ground_truth_annotations_for_detectionr      s#   6 K G+G8_W%F
6{a}ZL0MNOug&..q188:J>HIUc./0I
I -g609k"7+ID&*- 

U9#?RThjstug05	

 #D11# Js   $Cc                 ,   | j                   }|j                         rt        |      n|}|j                  |      }|st	        j
                  d|  d       y|r(|r&|j                         D ci c]  \  }}||   | }}}	 ddlm}	 g }
|D ]k  }|d   }t        |d         }|d   }|rt        ||         }|g||d	}|	'|j                  d
d      }|t        ||	      }|||d<   |
j                  |       m d|
dS c c}}w # t        $ r d}	Y w xY w)a  
    Format YOLO predictions for object detection visualization.

    Args:
        image_path (Path): Path to the image file.
        metadata (dict): Prediction metadata containing bounding boxes and class information.
        class_label_map (dict, optional): Mapping from class indices to class names.
        class_map (dict, optional): Additional class mapping for label conversion.

    Returns:
        (dict | None): Formatted prediction annotations or None if no predictions exist.
    r   z" has no bounding boxes predictionsNr   )decodebboxr<   category_idr   segmentationpoints
predictionr   )stem	isnumericr6   getr   r   itemsfaster_coco_eval.core.maskr   ImportErrorrA   r    _extract_segmentation_annotationr   )r   metadataclass_label_map	class_mapr   image_idpredictionskvr   r   r   r   r<   	cls_labelannotation_datasegmentss                    r*   _format_prediction_annotationsr      sH    ??D NN,s4y$H,,x(K}ZL0RST 97F7L7L7NOtq!9Q<?OO5 D! %
6"'
7(;<}-	OI67I%*Gi%P!~~nd;H#;HfM#,4)O$#%& !$//7 P  s   .C?D DDsegmentation_rawr   c                    	  ||       }t        j                  |t         j                  t         j                        \  }}|D cg c]4  }t	        |      dk\  st        j                  |      j                         6 }}|D cg c]   }|j                         j                         " c}S c c}w c c}w # t        $ r"}t        j                  d|        Y d}~yd}~ww xY w)ag  
    Extract segmentation annotation from compressed segmentations as list of polygons.

    Args:
        segmentation_raw (str): Raw segmentation data in compressed format.
        decode (Callable): Function to decode the compressed segmentation data.

    Returns:
        (List[List[Any]] | None): List of polygon points or None if extraction fails.
       z1Comet Failed to extract segmentation annotation: N)cv2findContours	RETR_LISTCHAIN_APPROX_SIMPLErm   nparrayr   ravelr   rb   r   r(   )	r   r   maskcontours_polygonannotations
annotationre   s	            r*   r   r     s    P&'&&tS]]C<S<ST!BJ`wcRYl^_N_rxx(002``>IJ

  "))+JJ aJ PJ1#NOOPs<   AB5 B+%B+=B5 %B0(B5 +
B5 5	C >CC c                 z    t        | |||      }t        ||||      }||fD cg c]  }||	 }	}|	r|	gS dS c c}w )aO  
    Join the ground truth and prediction annotations if they exist.

    Args:
        img_idx (int): Index of the image in the batch.
        image_path (Path): Path to the image file.
        batch (dict): Batch data containing ground truth annotations.
        prediction_metadata_map (dict): Map of prediction metadata by image ID.
        class_label_map (dict): Mapping from class indices to class names.
        class_map (dict): Additional class mapping for label conversion.

    Returns:
        (List | None): List of annotation dictionaries or None if no annotations exist.
    N)r   r   )
r   r   r   prediction_metadata_mapr   r   ground_truth_annotationsprediction_annotationsr   r   s
             r*   _fetch_annotationsr   3  sn    "  NUO  <+_i
 '?@V%W![e[q
K  (K=1T1s   88c                 p    i }| D ].  }|j                  |d   g        ||d      j                  |       0 |S )zMCreate metadata map for model predictions by grouping them based on image ID.r   )
setdefaultr   )model_predictionspred_metadata_mapr   s      r*   _create_prediction_metadata_mapr   Q  sN    ' E
$$Z
%;R@*Z0188DE 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_categoriesrl   stepN)	validatorr   r   listr   valueslog_confusion_matrixrm   )rd   ru   ri   rh   conf_matr   s         r*   _log_confusion_matrixr   [  s_      1188Hg&--/0L>AE##c%j
Yb $ r,   c                     |r4t        ||      D ]$  \  }}| j                  ||j                  ||       & y|D ]   }| j                  ||j                  |       " y)a  
    Log images to the experiment with optional annotations.

    This function logs images to a Comet ML experiment, optionally including annotation data for visualization
    such as bounding boxes or segmentation masks.

    Args:
        experiment (comet_ml.Experiment): The Comet ML experiment to log images to.
        image_paths (List[Path]): List of paths to images that will be logged.
        curr_step (int): Current training step/iteration for tracking in the experiment timeline.
        annotations (List[List[dict]], optional): Nested list of annotation dictionaries for each image. Each
            annotation contains visualization data like bounding boxes, labels, and confidence scores.
    )r   r   r   )r   r   N)r   	log_imager   )rd   image_pathsri   r   r   r   s         r*   _log_imagesr   d  sl     &)+{&C 	k"J
  *//	_i j	k & 	SJ  *//	 R	Sr,   c           
         |j                   j                  }|t        vry|j                  }|syt	        |      }|j
                  }|j                  }t        |dd      }t               }	t               }
t        |      D ]j  \  }}|dz   |	z  dk7  r|d   }t        |      D ]F  \  }}t        |
k\  r  yt        |      }t        ||||||      }t        | |g||       t        dz  aH l y)a  
    Log predicted boxes for a single image during training.

    This function logs image predictions to a Comet ML experiment during model validation. It processes
    validation data and formats both ground truth and prediction annotations for visualization in the Comet
    dashboard. The function respects configured limits on the number of images to log.

    Args:
        experiment (comet_ml.Experiment): The Comet ML experiment to log to.
        validator (BaseValidator): The validator instance containing validation data and predictions.
        curr_step (int): The current training step for logging timeline.

    Notes:
        This function uses global state to track the number of logged predictions across calls.
        It only logs predictions for supported tasks defined in COMET_SUPPORTED_TASKS.
        The number of logged images is limited by the COMET_MAX_IMAGE_PREDICTIONS environment variable.
    Nr   r4   r   im_file)r   )r   )rL   taskCOMET_SUPPORTED_TASKSjdictr   
dataloaderr   getattrr7   r;   	enumerate_comet_image_prediction_countr   r   r   )rd   r   ri   r   r   predictions_metadata_mapr   r   r   batch_logging_intervalrX   r   r   r   r   r   r   s                    r*   _log_image_predictionsr   {  s   ( >>D((OOE>uE%%JooO	;5I=?=?%j1 /	5M33q8I&#,[#9 	/GZ,0EEj)J,(#K '	 *Q.)'	//r,   c           	      \   d}t        |j                  j                  t              r3t        D cg c]!  }t
        D ]  }|j                  | | dz   # }}}nt        |j                  j                  t              r3t        D cg c]!  }t        D ]  }|j                  | | dz   # }}}nMt        |j                  j                  t        t        f      r#t        D cg c]  }|j                  | dz   }}|t        | |d       t        D cg c]  }|j                  | dz   }}t        | |d       t        |j                  j                  t              s1t        D cg c]  }|j                  | dz   }}t        | |d       yyc c}}w c c}}w c c}w c c}w c c}w )a  
    Log evaluation plots and label plots for the experiment.

    This function logs various evaluation plots and confusion matrices to the experiment tracking system. It handles
    different types of metrics (SegmentMetrics, PoseMetrics, DetMetrics, OBBMetrics) and logs the appropriate plots
    for each type.

    Args:
        experiment (comet_ml.Experiment): The Comet ML experiment to log plots to.
        trainer (ultralytics.engine.trainer.BaseTrainer): The trainer object containing validation metrics and save
            directory information.

    Examples:
        >>> from ultralytics.utils.callbacks.comet import _log_plots
        >>> _log_plots(experiment, trainer)
    Nz.pngz.jpg)
isinstancer   metricsr   EVALUATION_PLOT_NAMESSEGMENT_METRICS_PLOT_PREFIXsave_dirr   POSE_METRICS_PLOT_PREFIXr   r   r   CONFUSION_MATRIX_PLOT_NAMESr   LABEL_PLOT_NAMES)rd   ru   plot_filenamesplotsprefixconfusion_matrix_filenamesr   label_plot_filenamess           r*   
_log_plotsr     s   " N'##++^< /
5
  &%55
5
 

 
G%%--{	; /
2
  &%55
5
 

 
G%%--
J/G	HI^_'**wd^;__!J5Ql!m'"2"2wd^"C!m!m
6=g''//AQabv 0 0fXT? BbbJ 4d; B)

 `
 "n  cs   &F&F#FF$)F)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)r1   	log_modelr   best)rd   ru   
model_names      r*   
_log_modelr    s,    &(JC4EQZfjkr,   ri   c                     t        | |j                  j                  d      |       t        | |j                  j                  d      |       y)z=Log samples of image batches for train, validation, and test.ztrain_batch*.jpgzval_batch*.jpgN)r   r   glob)rd   ru   ri   s      r*   _log_image_batchesr    s>    
G,,112DEyQ
G,,112BCYOr,   c                 .    t        | j                         y)zRCreate or resume a CometML experiment at the start of a YOLO pre-training routine.N)rf   rL   )ru   s    r*   on_pretrain_routine_startr    s     .r,   c                     t        j                         }|syt        |       }|d   }|d   }|j                  | j	                  | j
                  d      ||       y)z@Log metrics and save batch images at the end of training epochs.Nrh   ri   train)r   r   rl   )r\   get_running_experimentrx   log_metricslabel_loss_itemstloss)ru   rd   r   rh   ri   s        r*   on_train_epoch_endr    s_    002J&w/H,'J%I733GMM'3RYbjtur,   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)	aM  
    Log model assets at the end of each epoch during training.

    This function is called at the end of each training epoch to log metrics, learning rates, and model information
    to a Comet ML experiment. It also logs model assets, confusion matrices, and image predictions based on
    configuration settings.

    The function retrieves the current Comet ML experiment and logs various training metrics. If it's the first epoch,
    it also logs model information. On specified save intervals, it logs the model, confusion matrix (if enabled),
    and image predictions (if enabled).

    Args:
        trainer (BaseTrainer): The YOLO trainer object containing training state, metrics, and configuration.

    Examples:
        >>> # Inside a training loop
        >>> on_fit_epoch_end(trainer)  # Log metrics and assets to Comet ML
    Nrh   ri   rj   r  r4   r   )model_info_for_loggers)r\   r  rx   r  r   lrultralytics.utils.torch_utilsr  r  rH   r   rK   r   r   )ru   rd   r   rh   ri   rj   r  s          r*   on_fit_epoch_endr    s    & 002J&w/H,'J%I=)K7??*M7::IZHQH5g>YV`az7##%j'9jI$&z7+<+<iH 'r,   c                 D   t        j                         }|syt        |       }|d   }|d   }| j                  j                  }t        ||        |rt        ||        t        || ||       t        || j                  |       t        || |       |j                          day)z*Perform operations at the end of training.Nrh   ri   r   )r\   r  rx   rL   r   r  r   r   r   r   r  endr   )ru   rd   r   rh   ri   r   s         r*   on_train_endr  1  s    002J&w/H,'J%ILLEz7#:w'*gy*E:w'8'8)Dz7I6NN %&!r,   )r  r  r  r  )N)NN)r"   N)Dcollections.abcr   typesr   typingr   r   r   r   numpyr   ultralytics.utilsr   r	   r
   r   r   ultralytics.utils.metricsr   r   r   r   r   r\   hasattrr&   pathlibr   r   r   r   r   r   r   r   r   AssertionErrorr   r+   r1   r6   r7   r;   r?   rA   boolrH   rK   rf   rt   rx   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r  r  	callbacksr0   r,   r*   <module>r)     s*   % ! & & 
  H H j jG$$$8]+++ &y1 #TH5"/,$%! 8s 8
B# B
>3 >
5 U Sd S
St S
!d !d4 !dHn n0	%[B42goptgu 42n20bjkobp 20js H QYZ^_cdg_hZiQj *2d^2<$ S.</~)<XlPs Pt P/

v*IZ&>  &?0,$	 
 
 
M 	^$ Hs   6D% %	D10D1