
    /j(/                        d dl mZ d dlmZ d dlmZ d dlZd dlZd dl	m
Z
 d dlmZ d dlmZmZmZ  G d d	e
          ZdS )
    )annotations)Path)AnyN)DetectionValidator)ops)	OKS_SIGMAPoseMetricskpt_iouc                       e Zd ZdZd'd( fdZd) fd
Zd*dZd+ fdZd, fdZd- fdZ	d. fdZ
d/d!Zd0 fd#Zd1 fd$Zd2 fd&Z xZS )3PoseValidatora  A class extending the DetectionValidator class for validation based on a pose model.

    This validator is specifically designed for pose estimation tasks, handling keypoints and implementing specialized
    metrics for pose evaluation.

    Attributes:
        sigma (np.ndarray): Sigma values for OKS calculation, either OKS_SIGMA or ones divided by number of keypoints.
        kpt_shape (list[int]): Shape of the keypoints, typically [17, 3] for COCO format.
        args (dict): Arguments for the validator including task set to "pose".
        metrics (PoseMetrics): Metrics object for pose evaluation.

    Methods:
        preprocess: Preprocess batch by converting keypoints data to float and moving it to the device.
        get_desc: Return description of evaluation metrics in string format.
        init_metrics: Initialize pose estimation metrics for YOLO model.
        _prepare_batch: Prepare a batch for processing by converting keypoints to float and scaling to original
            dimensions.
        _prepare_pred: Prepare and scale keypoints in predictions for pose processing.
        _process_batch: Return correct prediction matrix by computing Intersection over Union (IoU) between detections
            and ground truth.
        plot_val_samples: Plot and save validation set samples with ground truth bounding boxes and keypoints.
        plot_predictions: Plot and save model predictions with bounding boxes and keypoints.
        save_one_txt: Save YOLO pose detections to a text file in normalized coordinates.
        pred_to_json: Convert YOLO predictions to COCO JSON format.
        eval_json: Evaluate object detection model using COCO JSON format.

    Examples:
        >>> from ultralytics.models.yolo.pose import PoseValidator
        >>> args = dict(model="yolo26n-pose.pt", data="coco8-pose.yaml")
        >>> validator = PoseValidator(args=args)
        >>> validator()

    Notes:
        This class extends DetectionValidator with pose-specific functionality. It initializes with sigma values
        for OKS calculation and sets up PoseMetrics for evaluation. A warning is displayed when using Apple MPS
        due to a known bug with pose models.
    N
_callbacksdict | NonereturnNonec                    t                                          ||||           d| _        d| _        d| j        _        t                      | _        dS )aq  Initialize a PoseValidator object for pose estimation validation.

        This validator is specifically designed for pose estimation tasks, handling keypoints and implementing
        specialized metrics for pose evaluation.

        Args:
            dataloader (torch.utils.data.DataLoader, optional): DataLoader to be used for validation.
            save_dir (Path | str, optional): Directory to save results.
            args (dict, optional): Arguments for the validator including task set to "pose".
            _callbacks (dict, optional): Dictionary of callback functions to be executed during validation.
        Npose)super__init__sigma	kpt_shapeargstaskr	   metrics)self
dataloadersave_dirr   r   	__class__s        e/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/models/yolo/pose/val.pyr   zPoseValidator.__init__7   sI     	XtZ@@@
	"}}    batchdict[str, Any]c                    t                                          |          }|d                                         |d<   |S )zSPreprocess batch by converting keypoints data to float and moving it to the device.	keypoints)r   
preprocessfloat)r   r    r   s     r   r$   zPoseValidator.preprocessI   s:    ""5))";/5577kr   strc                    ddz  S )z:Return description of evaluation metrics in string format.z,%22s%11s%11s%11s%11s%11s%11s%11s%11s%11s%11s)ClassImages	InstanceszBox(PRmAP50	mAP50-95)zPose(Pr+   r,   r-    )r   s    r   get_desczPoseValidator.get_descO   s    $ )
 
 	
r   modeltorch.nn.Modulec                    t                                          |           | j        d         | _        | j        ddgk    }| j        d         }|rt          nt          j        |          |z  | _        dS )zInitialize evaluation metrics for YOLO pose validation.

        Args:
            model (torch.nn.Module): Model to validate.
        r         r   N)r   init_metricsdatar   r   nponesr   )r   r0   is_posenkptr   s       r   r5   zPoseValidator.init_metrics_   sh     	U###;/.RG+~a ")CYYrwt}}t/C


r   predstorch.Tensorlist[dict[str, torch.Tensor]]c                    t                                          |          }|D ]+} |                    d          j        dg| j        R  |d<   ,|S )a  Postprocess YOLO predictions to extract and reshape keypoints for pose estimation.

        This method extends the parent class postprocessing by extracting keypoints from the 'extra' field of
        predictions and reshaping them according to the keypoint shape configuration. The keypoints are reshaped from a
        flattened format to the proper dimensional structure (typically [N, 17, 3] for COCO pose format).

        Args:
            preds (torch.Tensor): Raw prediction tensor from the YOLO pose model containing bounding boxes, confidence
                scores, class predictions, and keypoint data.

        Returns:
            (list[dict[str, torch.Tensor]]): List of processed prediction dictionaries, each containing:
                - 'bboxes': Bounding box coordinates
                - 'conf': Confidence scores
                - 'cls': Class predictions
                - 'keypoints': Reshaped keypoint coordinates with shape (-1, *self.kpt_shape)

        Notes:
            If no keypoints are present in a prediction (empty keypoints), that prediction is skipped and continues
            to the next one. The keypoints are extracted from the 'extra' field which contains additional
            task-specific data beyond basic detection.
        extrar#   )r   postprocesspopviewr   )r   r;   predr   s      r   rA   zPoseValidator.postprocessk   sb    . ##E** 	L 	LD 6 1 1 6r KDN K K KDr   siintc                   t                                          ||          }|d         |d         |k             }|d         \  }}|                                }|dxx         |z  cc<   |dxx         |z  cc<   ||d<   |S )ai  Prepare a batch for processing by converting keypoints to float and scaling to original dimensions.

        Args:
            si (int): Sample index within the batch.
            batch (dict[str, Any]): Dictionary containing batch data with keys like 'keypoints', 'batch_idx', etc.

        Returns:
            (dict[str, Any]): Prepared batch with keypoints scaled to original image dimensions.

        Notes:
            This method extends the parent class's _prepare_batch method by adding keypoint processing.
            Keypoints are scaled from normalized coordinates to original image dimensions.
        r#   	batch_idximgsz).r   ).   )r   _prepare_batchclone)r   rE   r    pbatchkptshwr   s          r   rK   zPoseValidator._prepare_batch   s     ''E22[!%"4":;g1zz||VV"{r   dict[str, torch.Tensor]dict[str, np.ndarray]c                   t                                          ||          }|d         }|j        d         dk    s|d         j        d         dk    r4t          j        |d         j        d         | j        ft                    }nt          j        |d                   ddddf         	                    d          dz  }t          |d	         |d	         | j        |
          }|                     |d         ||                                                                          }|                    d|i           |S )ay  Return correct prediction matrix by computing Intersection over Union (IoU) between detections and ground
        truth.

        Args:
            preds (dict[str, torch.Tensor]): Dictionary containing prediction data with keys 'cls' for class predictions
                and 'keypoints' for keypoint predictions.
            batch (dict[str, Any]): Dictionary containing ground truth data with keys 'cls' for class labels, 'bboxes'
                for bounding boxes, and 'keypoints' for keypoint annotations.

        Returns:
            (dict[str, np.ndarray]): Dictionary containing the correct prediction matrix including 'tp_p' for pose true
                positives across 10 IoU levels.

        Notes:
            `0.53` scale factor used in area computation is referenced from
            https://github.com/jin-s13/xtcocoapi/blob/master/xtcocotools/cocoeval.py#L384.
        clsr   dtypebboxesN   rJ   g(\?r#   )r   areatp_p)r   _process_batchshaper7   zerosniouboolr   	xyxy2xywhprodr
   r   match_predictionscpunumpyupdate)	r   r;   r    tpgt_clsrZ   rY   iour   s	           r   r[   zPoseValidator._process_batch   s!   $ WW##E511u<?a5<#5a#8A#=#=8U5\/2DI>dKKKDD =x11!!!QRR%8==a@@4GD%,eK.@
Y]^^^C))%,DDHHJJPPRRD
		64.!!!	r   predn	save_confr_   r\   tuple[int, int]filer   c                h   ddl m}  |t          j        |d         |d         ft          j                  d| j        t          j        |d         |d                             d          |d	                             d          gd
          |d                   	                    ||           dS )aa  Save YOLO pose detections to a text file in normalized coordinates.

        Args:
            predn (dict[str, torch.Tensor]): Prediction dict with keys 'bboxes', 'conf', 'cls', and 'keypoints'.
            save_conf (bool): Whether to save confidence scores.
            shape (tuple[int, int]): Shape of the original image (height, width).
            file (Path): Output file path to save detections.

        Notes:
            The output format is: class_id x_center y_center width height confidence keypoints where keypoints are
            normalized (x, y, visibility) values for each point.
        r   )ResultsrJ   rU   NrW   confr@   rT   )dimr#   )pathnamesboxesr#   )rj   )
ultralytics.engine.resultsrn   r7   r]   uint8rr   torchcat	unsqueezesave_txt)r   ri   rj   r\   rl   rn   s         r   save_one_txtzPoseValidator.save_one_txt   s     	766666HeAha):::*)U8_eFm.E.Eb.I.I5QV<KaKabdKeKeflmnnnK(	
 	
 	
 (49(
-
-
-
-
-r   rM   c                   t                                          ||           |d         }t          |                    dd                                                    D ]&\  }}|| j        t          |           |z            d<   'dS )aI  Convert YOLO predictions to COCO JSON format.

        This method takes prediction tensors and batch data, converts the bounding boxes from YOLO format to COCO
        format, and appends the results with keypoints to the internal JSON dictionary (self.jdict).

        Args:
            predn (dict[str, torch.Tensor]): Prediction dictionary containing 'bboxes', 'conf', 'cls', and 'kpts'
                tensors.
            pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'.

        Notes:
            The method extracts the image ID from the filename stem (either as an integer if numeric, or as a string),
            converts bounding boxes from xyxy to xywh format, and adjusts coordinates from center to top-left corner
            before saving to the JSON dictionary.
        rN   rJ   rX   r#   N)r   pred_to_json	enumerateflattentolistjdictlen)r   ri   rM   rN   ikr   s         r   r|   zPoseValidator.pred_to_json   s      	UF+++V}dll1a007799:: 	8 	8DAq67DJD		zA~&{33	8 	8r   c           	         i t                                          ||          dt          j        |d         |d                                         |d         |d                   iS )z.Scales predictions to the original image size.rN   rI   r#   	ori_shape	ratio_pad)r   )r   scale_predsr   scale_coordsrL   )r   ri   rM   r   s      r   r   zPoseValidator.scale_preds   su    
gg!!%00
C$wk"((**{# -	  
 
 	
r   statsc                    | j         d         dz  }| j        dz  }t                                          |||ddgddg          S )	z7Evaluate object detection model using COCO JSON format.rq   z)annotations/person_keypoints_val2017.jsonzpredictions.jsonbboxr#   BoxPose)suffix)r6   r   r   coco_evaluate)r   r   	anno_json	pred_jsonr   s       r   	eval_jsonzPoseValidator.eval_json   sQ    If%(SS	M$66	ww$$UIy6;BWafhn`o$pppr   )NNNN)r   r   r   r   )r    r!   r   r!   )r   r&   )r0   r1   r   r   )r;   r<   r   r=   )rE   rF   r    r!   r   r!   )r;   rQ   r    r!   r   rR   )
ri   rQ   rj   r_   r\   rk   rl   r   r   r   )ri   rQ   rM   r!   r   r   )ri   rQ   rM   r!   r   rQ   )r   r!   r   r!   )__name__
__module____qualname____doc__r   r$   r/   r5   rA   rK   r[   rz   r|   r   r   __classcell__)r   s   @r   r   r      su       $ $L% % % % % % %$     
 
 
 
 
D 
D 
D 
D 
D 
D     8     .     <. . . ..8 8 8 8 8 8*

 

 

 

 

 

q q q q q q q q q qr   r   )
__future__r   pathlibr   typingr   rd   r7   rv   ultralytics.models.yolo.detectr   ultralytics.utilsr   ultralytics.utils.metricsr   r	   r
   r   r.   r   r   <module>r      s    # " " " " "                  = = = = = = ! ! ! ! ! ! E E E E E E E E E Ehq hq hq hq hq& hq hq hq hq hqr   