Ë
    Fêñiÿ#  ã                  óœ   — d dl mZ d dlmZ d dlmZ d dlZd dlmZ d dl	m
Z
mZmZ d dlmZ d dlmZmZ d	Z G d
„ de«      Z G d„ de«      Zy)é    )Úannotations)ÚPath)ÚAnyN)ÚYOLODataset)ÚComposeÚFormatÚv8_transforms)ÚDetectionValidator)ÚcolorstrÚops)ÚRTDETRValidatorc                  ó<   ‡ — e Zd ZdZddœˆ fd„
Zdˆ fd„	Zdd„Zˆ xZS )	ÚRTDETRDatasetaƒ  Real-Time DEtection and TRacking (RT-DETR) dataset class extending the base YOLODataset class.

    This specialized dataset class is designed for use with the RT-DETR object detection model and is optimized for
    real-time detection and tracking tasks.

    Attributes:
        augment (bool): Whether to apply data augmentation.
        rect (bool): Whether to use rectangular training.
        use_segments (bool): Whether to use segmentation masks.
        use_keypoints (bool): Whether to use keypoint annotations.
        imgsz (int): Target image size for training.

    Methods:
        load_image: Load one image from dataset index.
        build_transforms: Build transformation pipeline for the dataset.

    Examples:
        Initialize an RT-DETR dataset
        >>> dataset = RTDETRDataset(img_path="path/to/images", imgsz=640)
        >>> image, hw0, hw = dataset.load_image(0)
    N)Údatac               ó(   •— t        ‰| �  |d|i|¤Ž y)aL  Initialize the RTDETRDataset class by inheriting from the YOLODataset class.

        This constructor sets up a dataset specifically optimized for the RT-DETR (Real-Time DEtection and TRacking)
        model, building upon the base YOLODataset functionality.

        Args:
            *args (Any): Variable length argument list passed to the parent YOLODataset class.
            data (dict | None): Dictionary containing dataset information. If None, default values will be used.
            **kwargs (Any): Additional keyword arguments passed to the parent YOLODataset class.
        r   N)ÚsuperÚ__init__)Úselfr   ÚargsÚkwargsÚ	__class__s       €ú_/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/models/rtdetr/val.pyr   zRTDETRDataset.__init__)   s   ø€ ô 	‰Ñ˜$Ð4 TÐ4¨VÓ4ó    c                ó&   •— t         ‰| �  ||¬«      S )a�  Load one image from dataset index 'i'.

        Args:
            i (int): Index of the image to load.
            rect_mode (bool, optional): Whether to use rectangular mode for batch inference.

        Returns:
            im (np.ndarray): Loaded image as a NumPy array.
            hw_original (tuple[int, int]): Original image dimensions in (height, width) format.
            hw_resized (tuple[int, int]): Resized image dimensions in (height, width) format.

        Examples:
            Load an image from the dataset
            >>> dataset = RTDETRDataset(img_path="path/to/images")
            >>> image, hw0, hw = dataset.load_image(0)
        )ÚiÚ	rect_mode)r   Ú
load_image)r   r   r   r   s      €r   r   zRTDETRDataset.load_image6   s   ø€ ô" ‰wÑ! A°Ð!Ó;Ð;r   c                óü  — | j                   r›| j                   r| j                  s|j                  nd|_        | j                   r| j                  s|j                  nd|_        | j                   r| j                  s|j                  nd|_        t        | | j                  |d¬«      }nt        g «      }|j                  t        dd| j                  | j                  d|j                  |j                  ¬«      «       |S )zßBuild transformation pipeline for the dataset.

        Args:
            hyp (dict, optional): Hyperparameters for transformations.

        Returns:
            (Compose): Composition of transformation functions.
        g        T)ÚstretchÚxywh)Úbbox_formatÚ	normalizeÚreturn_maskÚreturn_keypointÚ	batch_idxÚ
mask_ratioÚmask_overlap)ÚaugmentÚrectÚmosaicÚmixupÚcutmixr	   Úimgszr   Úappendr   Úuse_segmentsÚuse_keypointsr&   Úoverlap_mask)r   ÚhypÚ
transformss      r   Úbuild_transformszRTDETRDataset.build_transformsI   s¾   € ð �<Š<Ø'+§|¢|¸D¿IºI˜ŸšÈ3ˆCŒJØ%)§\¢\¸$¿)º)˜Ÿ	š	ÈˆCŒIØ'+§|¢|¸D¿IºI˜ŸšÈ3ˆCŒJÜ& t¨T¯Z©Z¸ÀdÔK‰Jô ! ›ˆJØ×ÑÜØ"ØØ ×-Ñ-Ø $× 2Ñ 2ØØŸ>™>Ø ×-Ñ-ôô
	
ð Ðr   )F)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r4   Ú__classcell__)r   s   @r   r   r      s   ø„ ñð, $(ö 5õ<÷&r   r   c                  ó8   — e Zd ZdZdd„Zdd„Z	 	 	 	 d	d„Zd
d„Zy)r   a  RTDETRValidator extends the DetectionValidator class to provide validation capabilities specifically tailored for
    the RT-DETR (Real-Time DETR) object detection model.

    The class allows building of an RTDETR-specific dataset for validation, applies confidence thresholding for
    post-processing, and updates evaluation metrics accordingly.

    Attributes:
        args (Namespace): Configuration arguments for validation.
        data (dict): Dataset configuration dictionary.

    Methods:
        build_dataset: Build an RTDETR Dataset for validation.
        postprocess: Apply confidence thresholding to prediction outputs.

    Examples:
        Initialize and run RT-DETR validation
        >>> from ultralytics.models.rtdetr import RTDETRValidator
        >>> args = dict(model="rtdetr-l.pt", data="coco8.yaml")
        >>> validator = RTDETRValidator(args=args)
        >>> validator()

    Notes:
        For further details on the attributes and methods, refer to the parent DetectionValidator class.
    Nc                óÂ   — t        || j                  j                  |d| j                  d| j                  j                  xs dt	        |› d�«      | j
                  ¬«	      S )a¥  Build an RTDETR Dataset.

        Args:
            img_path (str): Path to the folder containing images.
            mode (str, optional): `train` mode or `val` mode, users are able to customize different augmentations for
                each mode.
            batch (int, optional): Size of batches, this is for `rect`.

        Returns:
            (RTDETRDataset): Dataset configured for RT-DETR validation.
        FNz: )	Úimg_pathr-   Ú
batch_sizer(   r2   r)   ÚcacheÚprefixr   )r   r   r-   r>   r   r   )r   r<   ÚmodeÚbatchs       r   Úbuild_datasetzRTDETRValidator.build_dataset‚   sT   € ô ØØ—)‘)—/‘/ØØØ—	‘	ØØ—)‘)—/‘/Ò) TÜ˜t˜f B˜KÓ(Ø—‘ô

ð 
	
r   c                ó   — |S )zJReturn predictions unchanged as RT-DETR handles scaling in postprocessing.© )r   ÚprednÚpbatchs      r   Úscale_predszRTDETRValidator.scale_predsš   s   € àˆr   c                óš  — t        |t        t        f«      s|dg}|d   j                  \  }}}|d   j	                  d|dz
  fd¬«      \  }}|| j
                  j                  z  }t        j                  d|j                  ¬«      g|z  }t        |«      D ]…  \  }}	t        j                  |	«      }	||   j                  d«      \  }
}t        j                  |	|
d   |d   gd¬«      }||
j                  d	¬
«         }||
| j
                  j                   kD     ||<   Œ‡ |D �cg c]  }|dd…dd…f   |dd…df   |dd…df   dœ‘Œ! c}S c c}w )a’  Apply confidence thresholding to prediction outputs.

        Args:
            preds (torch.Tensor | list | tuple): Raw predictions from the model. If tensor, should have shape
                (batch_size, num_predictions, num_classes + 4) where last dimension contains bbox coords and
                class scores.

        Returns:
            (list[dict[str, torch.Tensor]]): List of dictionaries for each image, each containing:
                - 'bboxes': Tensor of shape (N, 4) with bounding box coordinates
                - 'conf': Tensor of shape (N,) with confidence scores
                - 'cls': Tensor of shape (N,) with class indices
        Nr   é   éÿÿÿÿ)Údim)r   é   )Údevice).NT)Ú
descendingé   )ÚbboxesÚconfÚcls)Ú
isinstanceÚlistÚtupleÚshapeÚsplitr   r-   ÚtorchÚzerosrM   Ú	enumerater   Ú	xywh2xyxyÚmaxÚcatÚargsortrQ   )r   ÚpredsÚbsÚ_ÚndrP   ÚscoresÚoutputsr   ÚbboxÚscorerR   ÚpredÚxs                 r   ÚpostprocesszRTDETRValidator.postprocessž   sE  € ô  ˜%¤$¬ Ô/Ø˜D�MˆEà˜!‘H—N‘N‰	ˆˆAˆrØ˜q™Ÿ™¨¨B°©F¨¸˜Ó<‰ˆ�Ø�$—)‘)—/‘/Ñ!ˆÜ—;‘;˜v¨f¯m©mÔ<Ð=ÀÑBˆÜ  Ó(ò 	6‰GˆAˆtÜ—=‘= Ó&ˆDØ ™Ÿ™ rÓ*‰JˆE�3Ü—9‘9˜d E¨)Ñ$4°c¸)±nÐEÈ2ÔNˆDà˜Ÿ™°˜Ó6Ñ7ˆDØ˜e d§i¡i§n¡nÑ4Ñ5ˆG�AŠJð	6ð PWÖWÈ!˜1šQ   ˜U™8¨Qªq°!¨t©W¸QºqÀ!¸t¹WÓEÒWÐWùÒWs   Ä!$Ec                ó  — t        |d   «      }|j                  }|j                  «       rt        |«      n|}|d   j	                  «       }|dddgfxx   |d   d   | j
                  j                  z  z  cc<   |dddgfxx   |d   d   | j
                  j                  z  z  cc<   t        j                  |«      }|d	d	…d	d…fxx   |d	d	…dd	…f   dz  z  cc<   t        |j                  «       |d
   j                  «       |d   j                  «       «      D ]i  \  }}}	| j                  j                  ||j                  | j                  t        |	«         |D �
cg c]  }
t        |
d«      ‘Œ c}
t        |d«      dœ«       Œk y	c c}
w )aƒ  Serialize YOLO predictions to COCO json format.

        Args:
            predn (dict[str, torch.Tensor]): Predictions dictionary containing 'bboxes', 'conf', and 'cls' keys with
                bounding box coordinates, confidence scores, and class predictions.
            pbatch (dict[str, Any]): Batch dictionary containing 'imgsz', 'ori_shape', 'ratio_pad', and 'im_file'.
        Úim_filerP   .r   é   Ú	ori_shapeé   é   NrQ   rR   rO   )Úimage_idÚ	file_nameÚcategory_idre   rf   )r   ÚstemÚ	isnumericÚintÚcloner   r-   r   Ú	xyxy2xywhÚzipÚtolistÚjdictr.   ÚnameÚ	class_mapÚround)r   rE   rF   Úpathrs   rp   ÚboxÚbÚsÚcrh   s              r   Úpred_to_jsonzRTDETRValidator.pred_to_json¿   sc  € ô �F˜9Ñ%Ó&ˆØ�y‰yˆØ $§¡Ô 0”3�t”9°dˆØ�H‰o×#Ñ#Ó%ˆØˆC�!�Q�ˆKÓ˜F ;Ñ/°Ñ2°T·Y±Y·_±_ÑDÑDÓØˆC�!�Q�ˆKÓ˜F ;Ñ/°Ñ2°T·Y±Y·_±_ÑDÑDÓÜ�m‰m˜CÓ ˆØŠAˆr�ˆrˆE‹
�cš!˜Q™R˜%‘j 1‘nÑ$‹
Ü˜3Ÿ:™:›<¨¨v©×)=Ñ)=Ó)?ÀÀuÁ×ATÑATÓAVÓWò 		‰GˆAˆq�!Ø�J‰J×Ñà (Ø!%§¡Ø#'§>¡>´#°a³&Ñ#9Ø23Ö4¨QœU 1 a�[Ò4Ü" 1 a›[ñõñ		ùò 5s   ÅF)ÚvalN)rE   údict[str, torch.Tensor]rF   údict[str, Any]Úreturnr…   )r_   z7torch.Tensor | list[torch.Tensor] | tuple[torch.Tensor]r‡   zlist[dict[str, torch.Tensor]])rE   r…   rF   r†   r‡   ÚNone)r5   r6   r7   r8   rB   rG   ri   rƒ   rD   r   r   r   r   h   s/   „ ñó2
ó0ðXØLðXà	&óXôBr   r   )Ú
__future__r   Úpathlibr   Útypingr   rX   Úultralytics.datar   Úultralytics.data.augmentr   r   r	   Úultralytics.models.yolo.detectr
   Úultralytics.utilsr   r   Ú__all__r   r   rD   r   r   ú<module>r‘      sE   ðõ #å Ý ã å (ß CÑ CÝ =ß +à
€ôS�Kô SôlpÐ(õ pr   