o
    Wh6                     @   s\   d dl m Z  d dlmZ d dlmZ d dlmZmZ d dlm	Z	m
Z
 G dd dejjZdS )	    )copy)yolo)	PoseModel)DEFAULT_CFGLOGGER)plot_imagesplot_resultsc                       sV   e Zd ZdZeddf fdd	ZdddZ fdd	Zd
d Zdd Z	dd Z
  ZS )PoseTrainera  
    A class extending the DetectionTrainer class for training YOLO pose estimation models.

    This trainer specializes in handling pose estimation tasks, managing model training, validation, and visualization
    of pose keypoints alongside bounding boxes.

    Attributes:
        args (dict): Configuration arguments for training.
        model (PoseModel): The pose estimation model being trained.
        data (dict): Dataset configuration including keypoint shape information.
        loss_names (Tuple[str]): Names of the loss components used in training.

    Methods:
        get_model: Retrieves a pose estimation model with specified configuration.
        set_model_attributes: Sets keypoints shape attribute on the model.
        get_validator: Creates a validator instance for model evaluation.
        plot_training_samples: Visualizes training samples with keypoints.
        plot_metrics: Generates and saves training/validation metric plots.

    Examples:
        >>> from ultralytics.models.yolo.pose import PoseTrainer
        >>> args = dict(model="yolo11n-pose.pt", data="coco8-pose.yaml", epochs=3)
        >>> trainer = PoseTrainer(overrides=args)
        >>> trainer.train()
    Nc                    sX   |du ri }d|d< t  ||| t| jjtr(| jj dkr*td dS dS dS )a8  
        Initialize a PoseTrainer object for training YOLO pose estimation models.

        This initializes a trainer specialized for pose estimation tasks, setting the task to 'pose' and
        handling specific configurations needed for keypoint detection models.

        Args:
            cfg (dict, optional): Default configuration dictionary containing training parameters.
            overrides (dict, optional): Dictionary of parameter overrides for the default configuration.
            _callbacks (list, optional): List of callback functions to be executed during training.

        Notes:
            This trainer will automatically set the task to 'pose' regardless of what is provided in overrides.
            A warning is issued when using Apple MPS device due to known bugs with pose models.

        Examples:
            >>> from ultralytics.models.yolo.pose import PoseTrainer
            >>> args = dict(model="yolov8n-pose.pt", data="coco8-pose.yaml", epochs=3)
            >>> trainer = PoseTrainer(overrides=args)
            >>> trainer.train()
        Nposetaskmpsz}Apple MPS known Pose bug. Recommend 'device=cpu' for Pose models. See https://github.com/ultralytics/ultralytics/issues/4031.)	super__init__
isinstanceargsdevicestrlowerr   warning)selfcfg	overrides
_callbacks	__class__ V/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/yolo/pose/train.pyr   &   s   zPoseTrainer.__init__Tc                 C   s6   t || jd | jd | jd |d}|r|| |S )a  
        Get pose estimation model with specified configuration and weights.

        Args:
            cfg (str | Path | dict | None): Model configuration file path or dictionary.
            weights (str | Path | None): Path to the model weights file.
            verbose (bool): Whether to display model information.

        Returns:
            (PoseModel): Initialized pose estimation model.
        ncchannels	kpt_shape)r   chdata_kpt_shapeverbose)r   dataload)r   r   weightsr"   modelr   r   r   	get_modelG   s   
zPoseTrainer.get_modelc                    s   t    | jd | j_dS )z,Sets keypoints shape attribute of PoseModel.r   N)r   set_model_attributesr#   r&   r   r   r   r   r   r(   [   s   
z PoseTrainer.set_model_attributesc                 C   s&   d| _ tjj| j| jt| j| jdS )z>Returns an instance of the PoseValidator class for validation.)box_loss	pose_loss	kobj_losscls_lossdfl_loss)save_dirr   r   )	
loss_namesr   r
   PoseValidatortest_loaderr/   r   r   	callbacksr)   r   r   r   get_validator`   s   zPoseTrainer.get_validatorc           	      C   sb   |d }|d }|d  d}|d }|d }|d }t||||||| jd| d	 | jd
 dS )aP  
        Plot a batch of training samples with annotated class labels, bounding boxes, and keypoints.

        Args:
            batch (dict): Dictionary containing batch data with the following keys:
                - img (torch.Tensor): Batch of images
                - keypoints (torch.Tensor): Keypoints coordinates for pose estimation
                - cls (torch.Tensor): Class labels
                - bboxes (torch.Tensor): Bounding box coordinates
                - im_file (list): List of image file paths
                - batch_idx (torch.Tensor): Batch indices for each instance
            ni (int): Current training iteration number used for filename

        The function saves the plotted batch as an image in the trainer's save directory with the filename
        'train_batch{ni}.jpg', where ni is the iteration number.
        img	keypointsclsbboxesim_file	batch_idxtrain_batchz.jpg)kptspathsfnameon_plotN)squeezer   r/   r@   )	r   batchniimagesr=   r7   r9   r>   r;   r   r   r   plot_training_samplesg   s    
z!PoseTrainer.plot_training_samplesc                 C   s   t | jd| jd dS )zPlots training/val metrics.T)filer
   r@   N)r   csvr@   r)   r   r   r   plot_metrics   s   zPoseTrainer.plot_metrics)NNT)__name__
__module____qualname____doc__r   r   r'   r(   r4   rE   rH   __classcell__r   r   r   r   r	      s    
!"r	   N)r   ultralytics.modelsr   ultralytics.nn.tasksr   ultralytics.utilsr   r   ultralytics.utils.plottingr   r   detectDetectionTrainerr	   r   r   r   r   <module>   s   