o
    Whl                  
   @   s.  d dl mZ d dlmZmZmZmZ z*erJ ed du sJ d dlZejdddds-J d dl	Z	d dl
Z
dai Zd	aW n eeefyJ   dZY nw d"dededdfddZd"dededdfddZd#ddZd#ddZd#ddZd#ddZd#ddZd#ddZd#dd Zereeeeeed!ZdS i ZdS )$    )Path)LOGGERSETTINGSTESTS_RUNNINGchecksdvcTNdvclivez2.11.0)verboseF pathprefixreturnc                 C   sd   t r0| j}td| }r#|d }tdd| j}t|| | j}t 	t
j|||  dS dS )a[  
    Log images at specified path with an optional prefix using DVCLive.

    This function logs images found at the given path to DVCLive, organizing them by batch to enable slider
    functionality in the UI. It processes image filenames to extract batch information and restructures the path
    accordingly.

    Args:
        path (Path): Path to the image file to be logged.
        prefix (str): Optional prefix to add to the image name when logging.

    Examples:
        >>> from pathlib import Path
        >>> _log_images(Path("runs/train/exp/val_batch0_pred.jpg"), prefix="validation")
    z_batch(\d+)   _batchN)livenameresearchsubstemr   with_suffixsuffix	log_imageosr   join)r   r   r   mninew_stem r   S/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/utils/callbacks/dvc.py_log_images   s   r    plotsc                 C   s>   |   D ]\}}|d }t||krt|| |t|< qdS )a  
    Log plot images for training progress if they have not been previously processed.

    Args:
        plots (dict): Dictionary containing plot information with timestamps.
        prefix (str, optional): Optional prefix to add to the logged image paths.
    	timestampN)items_processed_plotsgetr    )r!   r   r   paramsr"   r   r   r   
_log_plots9   s   
r'   c           	      C   s   g }g }| j j}t| j }| j jdkr|dg7 }t|jt	D ]!\}}t|D ]\}}|
|| g|  |
|| g|  q*q"tjd||ddd dS )a  
    Log confusion matrix for a validator using DVCLive.

    This function processes the confusion matrix from a validator object and logs it to DVCLive by converting
    the matrix into lists of target and prediction labels.

    Args:
        validator (BaseValidator): The validator object containing the confusion matrix and class names.
            Must have attributes: confusion_matrix.matrix, confusion_matrix.task, and names.

    Returns:
        None
    detect
backgroundconfusion_matrixzcf.jsonT)r   
normalizedN)r*   matrixlistnamesvaluestask	enumerateTastypeintextendr   log_sklearn_plot)		validatortargetspredsr,   r.   tipredpinumr   r   r   _log_confusion_matrixH   s   
r>   c              
   C   sV   zt jdddatd W dS  ty* } ztd|  W Y d}~dS d}~ww )zMInitializes DVCLive logger for training metadata during pre-training routine.T)save_dvc_expcache_imagesz[DVCLive is detected and auto logging is enabled (run 'yolo settings dvc=False' to disable).zGDVCLive installed but not initialized correctly, not logging this run. N)r   Liver   r   info	Exceptionwarning)trainerer   r   r   on_pretrain_routine_starte   s   rG   c                 C   s   t | jd dS )zQLogs plots related to the training process at the end of the pretraining routine.trainN)r'   r!   rE   r   r   r   on_pretrain_routine_endo   s   rJ   c                 C   s   t r
t | j dS dS )z:Logs the training parameters if DVCLive logging is active.N)r   
log_paramsargsrI   r   r   r   on_train_startt   s   rM   c                 C   s   da dS )z[Sets the global variable _training_epoch value to True at the start of training each epoch.TN)_training_epochrI   r   r   r   on_train_epoch_startz   s   rO   c                 C   s   t rVtrXi | j| jdd| j| j}| D ]
\}}t || q| jdkrAddl	m
} ||  D ]\}}t j||dd q4t| jd t| jjd t   dadS dS dS )	a  
    Log training metrics, model info, and advance to next step at the end of each fit epoch.

    This function is called at the end of each fit epoch during training. It logs various metrics including
    training loss items, validation metrics, and learning rates. On the first epoch, it also logs model
    information. Additionally, it logs training and validation plots and advances the DVCLive step counter.

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

    Notes:
        This function only performs logging operations when DVCLive logging is active and during a training epoch.
        The global variable _training_epoch is used to track whether the current epoch is a training epoch.
    rH   r   r   )model_info_for_loggersFplotvalN)r   rN   label_loss_itemstlossmetricslrr#   
log_metricepochultralytics.utils.torch_utilsrQ   r'   r!   r7   	next_step)rE   all_metricsmetricvaluerQ   r   r   r   on_fit_epoch_end   s    
r`   c                 C   s   t rIi | j| jdd| j| j}| D ]\}}t j||dd qt| jd t| j	jd t
| j	 | j rCt j| jddd t   d	S d	S )
a  
    Log best metrics, plots, and confusion matrix at the end of training.

    This function is called at the conclusion of the training process to log final metrics, visualizations, and
    model artifacts if DVCLive logging is active. It captures the best model performance metrics, training plots,
    validation plots, and confusion matrix for later analysis.

    Args:
        trainer (BaseTrainer): The trainer object containing training state, metrics, and validation results.

    Examples:
        >>> # Inside a custom training loop
        >>> from ultralytics.utils.callbacks.dvc import on_train_end
        >>> on_train_end(trainer)  # Log final metrics and artifacts
    rH   rP   FrR   rT   Tmodel)copytypeN)r   rU   rV   rW   rX   r#   rY   r'   r!   r7   r>   bestexistslog_artifactend)rE   r]   r^   r_   r   r   r   on_train_end   s    

rh   )rG   rJ   rM   rO   r`   rh   )r
   )r   N)pathlibr   ultralytics.utilsr   r   r   r   r   check_versionr   r   r   r$   rN   ImportErrorAssertionError	TypeErrorstrr    dictr'   r>   rG   rJ   rM   rO   r`   rh   	callbacksr   r   r   r   <module>   sH   







")
