
    |hQ                         d dl m Z  d dlmZ d dlmZmZmZmZ d dlm	Z	 d dl
mZ d dlmZmZ d dlmZ  G d d	e	j"                  j$                        Zy
)    )copy)Path)AnyDictOptionalUnion)yolo)	PoseModel)DEFAULT_CFGLOGGER)plot_resultsc            	            e Zd ZdZeddfdeeeef      f fdZ		 	 	 ddee
eeeeef   f      dee
eef      dedefd	Z fd
Zd Zd Zdeeef   f fdZ x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): Names of the loss components used in training.

    Methods:
        get_model: Retrieve a pose estimation model with specified configuration.
        set_model_attributes: Set keypoints shape attribute on the model.
        get_validator: Create a validator instance for model evaluation.
        plot_training_samples: Visualize training samples with keypoints.
        plot_metrics: Generate and save training/validation metric plots.
        get_dataset: Retrieve the dataset and ensure it contains required kpt_shape key.

    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()
    N	overridesc                     |i }d|d<   t         |   |||       t        | j                  j                  t
              r>| j                  j                  j                         dk(  rt        j                  d       yyy)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="yolo11n-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cfgr   
_callbacks	__class__s       a/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/models/yolo/pose/train.pyr   zPoseTrainer.__init__)   st    , I"	&i4dii&&,1A1A1G1G1IU1RNNN 2S,    r   weightsverbosereturnc                     t        || j                  d   | j                  d   | j                  d   |      }|r|j                  |       |S )a  
        Get pose estimation model with specified configuration and weights.

        Args:
            cfg (str | Path | dict, optional): Model configuration file path or dictionary.
            weights (str | Path, optional): 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_shaper$   )r
   dataload)r   r   r#   r$   models        r!   	get_modelzPoseTrainer.get_modelJ   sK    " DIIdO		*(=diiXcNdnu
 JJwr"   c                 ^    t         |           | j                  d   | j                  _        y)z+Set keypoints shape attribute of PoseModel.r)   N)r   set_model_attributesr,   r.   r)   )r   r    s    r!   r1   z PoseTrainer.set_model_attributesc   s#    $&#yy5

r"   c                     d| _         t        j                  j                  | j                  | j
                  t        | j                        | j                        S )z=Return 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_loaderr8   r   r   	callbacksr   s    r!   get_validatorzPoseTrainer.get_validatorh   sG    Vyy&&t}}4		?W[WeWe ' 
 	
r"   c                 H    t        | j                  d| j                         y)z!Plot training/validation metrics.T)filer   on_plotN)r   csvrA   r=   s    r!   plot_metricszPoseTrainer.plot_metricso   s    $((t||Dr"   c                 r    t         |          }d|vr#t        d| j                  j                   d      |S )a/  
        Retrieve the dataset and ensure it contains the required `kpt_shape` key.

        Returns:
            (dict): A dictionary containing the training/validation/test dataset and category names.

        Raises:
            KeyError: If the `kpt_shape` key is not present in the dataset.
        r)   zNo `kpt_shape` in the z1. See https://docs.ultralytics.com/datasets/pose/)r   get_datasetKeyErrorr   r,   )r   r,   r    s     r!   rE   zPoseTrainer.get_datasets   s>     w"$d"3DIINN3CCtuvvr"   )NNT)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   boolr
   r/   r1   r>   rC   rE   __classcell__)r    s   @r!   r   r      s    6 'd_c 8DcN3K F ;?.2	eCtCH~567 %T	*+ 	
 
26

ET#s(^  r"   r   N)r   pathlibr   typingr   r   r   r   ultralytics.modelsr	   ultralytics.nn.tasksr
   ultralytics.utilsr   r   ultralytics.utils.plottingr   detectDetectionTrainerr    r"   r!   <module>rV      s7      - - # * 1 3s$++.. sr"   