§
    l¬¸j©& ã                  óâ  — d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	m
Z
 ddlZddlZddlZddlmc mZ ddlmZ ddlmZ dd	lmZ dd
lmZmZmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z, e	rddl-m.Z.  G d„ de¦  «        Z/ G d„ de/¦  «        Z0 G d„ de0¦  «        Z1 G d„ de0¦  «        Z2 G d„ de0¦  «        Z3 G d„ de3¦  «        Z4 G d„ de1e3¦  «        Z5 G d„ de4¦  «        Z6dS ) aº  
Generate predictions using the Segment Anything Model (SAM).

SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
segmentation tasks.
é    )Úannotations)ÚOrderedDictÚdefaultdict)Údeepcopy)ÚTYPE_CHECKINGÚAnyN)Ú	LetterBox)ÚBasePredictor)ÚResults)ÚDEFAULT_CFGÚLOGGERÚops)Úbox_iouÚmask_iou)Úselect_deviceÚsmart_inference_modeé   )	Úbatch_iteratorÚbatched_mask_to_boxÚbuild_all_layer_point_gridsÚcalculate_stability_scoreÚgenerate_crop_boxesÚis_box_near_crop_edgeÚremove_small_regionsÚuncrop_boxes_xyxyÚuncrop_masks©ÚPromptc                  ó^  ‡ — e Zd ZdZdZeddfd#ˆ fd„Zd„ Zd„ Ze	d	„ ¦   «         Z
d$d„Zd$d„Z	 	 	 	 	 d$d„Zd%d„Z	 	 	 	 	 	 	 	 	 	 	 d&d„Z ed
¦  «        d'd„¦   «         Zd„ Zd„ Z e¦   «         d„ ¦   «         Zˆ fd„Zd„ Zd„ Zd „ Zed(d!„¦   «         Z e¦   «         	 	 	 	 	 	 d)d"„¦   «         Zˆ xZS )*Ú	PredictoraJ	  Predictor class for SAM, enabling real-time image segmentation with promptable capabilities.

    This class extends BasePredictor and implements the Segment Anything Model (SAM) for advanced image segmentation
    tasks. It supports various input prompts like points, bounding boxes, and masks for fine-grained control over
    segmentation results.

    Attributes:
        args (SimpleNamespace): Configuration arguments for the predictor.
        model (torch.nn.Module): The loaded SAM model.
        device (torch.device): The device (CPU or GPU) on which the model is loaded.
        im (torch.Tensor): The preprocessed input image.
        features (torch.Tensor): Extracted image features.
        prompts (dict[str, Any]): Dictionary to store various types of prompts (e.g., bboxes, points, masks).
        segment_all (bool): Flag to indicate if full image segmentation should be performed.
        non_overlap_masks (bool): Whether each pixel is assigned to at most one of the predicted masks.
        mean (torch.Tensor): Mean values for image normalization.
        std (torch.Tensor): Standard deviation values for image normalization.

    Methods:
        preprocess: Prepare input images for model inference.
        pre_transform: Perform initial transformations on the input image.
        inference: Perform segmentation inference based on input prompts.
        prompt_inference: Internal function for prompt-based segmentation inference.
        generate: Generate segmentation masks for an entire image.
        setup_model: Initialize the SAM model for inference.
        get_model: Build and return a SAM model.
        postprocess: Post-process model outputs to generate final results.
        setup_source: Set up the data source for inference.
        set_image: Set and preprocess a single image for inference.
        get_im_features: Extract image features using the SAM image encoder.
        set_prompts: Set prompts for subsequent inference.
        reset_image: Reset the current image and its features.
        remove_small_regions: Remove small disconnected regions and holes from masks.

    Examples:
        >>> predictor = Predictor()
        >>> predictor.setup_model(model_path="sam_model.pt")
        >>> predictor.set_image("image.jpg")
        >>> bboxes = [[100, 100, 200, 200]]
        >>> results = predictor(bboxes=bboxes)
    é   NÚ
_callbacksúdict | Nonec                óæ   •— |€i }|                      ddddœ¦  «         t          ¦   «                              |||¦  «         d| j        _        d| _        d| _        i | _        d| _        d| _	        dS )ae  Initialize the Predictor with configuration, overrides, and callbacks.

        Sets up the Predictor object for SAM (Segment Anything Model) and applies any configuration overrides or
        callbacks provided. Initializes task-specific settings for SAM, such as retina_masks being set to True for
        optimal results.

        Args:
            cfg (dict): Configuration dictionary containing default settings.
            overrides (dict | None): Dictionary of values to override default configuration.
            _callbacks (dict | None): Dictionary of callback functions to customize behavior.
        NÚsegmentÚpredictr   )ÚtaskÚmodeÚbatchTF)
ÚupdateÚsuperÚ__init__ÚargsÚretina_masksÚimÚfeaturesÚpromptsÚsegment_allÚnon_overlap_masks©ÚselfÚcfgÚ	overridesr"   Ú	__class__s       €ún/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/ultralytics/models/sam/predict.pyr,   zPredictor.__init__Z   s   ø€ ð ÐØˆIØ×Ò )°YÈÐKÐKÑLÔLÐLÝ‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ø!%ˆŒ	ÔØˆŒØˆŒØˆŒØ ˆÔØ!&ˆÔÐÐó    c                óþ  — | j         �| j         S t          |t          j        ¦  «         }|rot	          j        |                      |¦  «        ¦  «        }|dddd…f                              d¦  «        }t	          j        |¦  «        }t          j	        |¦  «        }| 
                    | j        ¦  «        }|r|| j        z
  | j        z  }| j        j        r|                     ¦   «         n|                     ¦   «         }|S )av  Preprocess the input image for model inference.

        This method prepares the input image by applying transformations and normalization. It supports both
        torch.Tensor and list of np.ndarray as input formats. For OpenCV-loaded images, the input is typically BGR and
        is converted to RGB during preprocessing.

        Args:
            im (torch.Tensor | list[np.ndarray]): Input image(s) in BCHW tensor format or a list of HWC NumPy arrays.
                NumPy arrays are expected to be in BGR order (as returned by OpenCV) and will be converted to RGB.

        Returns:
            (torch.Tensor): The preprocessed image tensor, normalized and converted to the appropriate dtype.

        Examples:
            >>> predictor = Predictor()
            >>> image = torch.rand(1, 3, 640, 640)
            >>> preprocessed_image = predictor.preprocess(image)
        N.éÿÿÿÿ)r   é   r   é   )r/   Ú
isinstanceÚtorchÚTensorÚnpÚstackÚpre_transformÚ	transposeÚascontiguousarrayÚ
from_numpyÚtoÚdeviceÚmeanÚstdÚmodelÚfp16ÚhalfÚfloat)r5   r/   Ú
not_tensors      r9   Ú
preprocesszPredictor.preprocessq   sá   € ð& Œ7ÐØ”7ˆNÝ# B­¬Ñ5Ô5Ð5ˆ
Øð 	&Ý”˜$×,Ò,¨RÑ0Ô0Ñ1Ô1ˆBØ�C˜˜˜2˜�I”×(Ò(¨Ñ6Ô6ˆBÝÔ% bÑ)Ô)ˆBÝÔ! "Ñ%Ô%ˆBà�UŠU�4”;ÑÔˆØð 	-Ø�t”y‘. D¤HÑ,ˆBØœ*œ/Ð9ˆR�WŠW‰YŒYˆY¨r¯xªx©z¬zˆØˆ	r:   c                óˆ   ‡— t          |¦  «        dk    s
J d¦   «         ‚t          | j        dd¬¦  «        Šˆfd„|D ¦   «         S )a�  Perform initial transformations on the input image for preprocessing.

        This method applies transformations such as resizing to prepare the image for further preprocessing. Currently,
        batched inference is not supported; hence the list length should be 1.

        Args:
            im (list[np.ndarray]): List containing a single image in HWC numpy array format.

        Returns:
            (list[np.ndarray]): List containing the transformed image.

        Raises:
            AssertionError: If the input list contains more than one image.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.imgsz = [1024, 1024]  # normally set by setup_source()
            >>> image = np.random.rand(480, 640, 3)  # Single HWC image
            >>> transformed = predictor.pre_transform([image])
            >>> print(len(transformed))
            1
        r   ú6SAM model does not currently support batched inferenceF)ÚautoÚcenterc                ó(   •— g | ]} ‰|¬ ¦  «        ‘ŒS ©)Úimage© ©Ú.0ÚxÚ	letterboxs     €r9   ú
<listcomp>z+Predictor.pre_transform.<locals>.<listcomp>¬   ó&   ø€ Ð/Ð/Ð/ q�	�	 Ð"Ñ"Ô"Ð/Ð/Ð/r:   ©Úlenr	   Úimgsz©r5   r/   r]   s     @r9   rD   zPredictor.pre_transform“   sO   ø€ õ. �2‰wŒw˜!Š|ˆ|ˆ|ÐU‰|Œ|ˆ|Ý˜dœj¨u¸UÐCÑCÔCˆ	Ø/Ð/Ð/Ð/¨BÐ/Ñ/Ô/Ð/r:   c                ó˜   — | j         d         d         }t          |t          j        ¦  «        r|j        dd…         n|j        dd…         S )zeReturn the source image (height, width): an HWC array from files and streams, or a CHW tensor source.r   r   éþÿÿÿNr>   )r)   r?   r@   rA   Úshape)r5   Úim0s     r9   Ú	src_shapezPredictor.src_shape®   sC   € ð Œj˜Œm˜AÔˆÝ!+¨Cµ´Ñ!>Ô!>ÐQˆsŒy˜˜˜Œ~ˆ~ÀCÄIÈbÈqÈbÄMÐQr:   Fc                óh  — | j                              d|¦  «        }| j                              d|¦  «        }| j                              d|¦  «        }| j                              d|¦  «        }t          d„ |||fD ¦   «         ¦  «        r | j        |g|¢R i |¤ŽS |                      ||||||¦  «        S )a=  Perform image segmentation inference based on the given input cues, using the currently loaded image.

        This method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt encoder,
        and mask decoder for real-time and promptable segmentation tasks.

        Args:
            im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
            bboxes (np.ndarray | list | None): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | list | None): Points indicating object locations with shape (N, 2), in pixels.
            labels (np.ndarray | list | None): Labels for point prompts, shape (N,). 1 = foreground, 0 = background.
            masks (np.ndarray | None): Low-resolution masks from previous predictions, shape (N, H, W). For SAM H=W=256.
            multimask_output (bool): Flag to return multiple masks. Helpful for ambiguous prompts.
            *args (Any): Additional positional arguments.
            **kwargs (Any): Additional keyword arguments.

        Returns:
            pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
            pred_scores (torch.Tensor): An array of length C containing quality scores predicted by the model for each
                mask.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_model(model_path="sam_model.pt")
            >>> predictor.set_image("image.jpg")
            >>> results = predictor(bboxes=[[0, 0, 100, 100]])
        ÚbboxesÚpointsÚmasksÚlabelsc              3  ó   K  — | ]}|d u V — Œ	d S ©NrY   ©r[   Úis     r9   ú	<genexpr>z&Predictor.inference.<locals>.<genexpr>Õ   s&   è è € Ð:Ð:˜Qˆq�DˆyÐ:Ð:Ð:Ð:Ð:Ð:r:   )r1   ÚpopÚallÚgenerateÚprompt_inference)	r5   r/   rj   rk   rm   rl   Úmultimask_outputr-   Úkwargss	            r9   Ú	inferencezPredictor.inference´   sÇ   € ð8 ”×!Ò! (¨FÑ3Ô3ˆØ”×!Ò! (¨FÑ3Ô3ˆØ”× Ò  ¨%Ñ0Ô0ˆØ”×!Ò! (¨FÑ3Ô3ˆåÐ:Ð: 6¨6°5Ð"9Ð:Ñ:Ô:Ñ:Ô:ð 	6Ø �4”= Ð5 dÐ5Ð5Ð5¨fÐ5Ð5Ð5à×$Ò$ R¨°¸ÀÐHXÑYÔYÐYr:   c                óÀ   — | j         €|                      |¦  «        n| j         }|                      |j        dd…         | j        ||||¦  «        } | j        |g|¢|‘R Ž S )aö  Perform image segmentation inference based on input cues using SAM's specialized architecture.

        This internal function leverages the Segment Anything Model (SAM) for prompt-based, real-time segmentation. It
        processes various input prompts such as bounding boxes, points, and masks to generate segmentation masks.

        Args:
            im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
            bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
            points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points,
                2), in pixels.
            labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground,
                0 for background.
            masks (np.ndarray | None): Low-res masks from previous predictions with shape (N, H, W). For SAM, H=W=256.
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.

        Returns:
            pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
            pred_scores (torch.Tensor): Quality scores predicted by the model for each mask, with length C.

        Examples:
            >>> predictor = Predictor()
            >>> im = torch.rand(1, 3, 1024, 1024)
            >>> bboxes = [[100, 100, 200, 200]]
            >>> masks, scores = predictor.prompt_inference(im, bboxes=bboxes)
        Nr>   )r0   Úget_im_featuresÚ_prepare_promptsrf   rh   Ú_inference_features)	r5   r/   rj   rk   rm   rl   rw   r0   r1   s	            r9   rv   zPredictor.prompt_inferenceÚ   sq   € ð4 04¬}Ð/D�4×'Ò'¨Ñ+Ô+Ð+È$Ì-ˆØ×'Ò'¨¬°°°¬°d´nÀfÈfÐV\Ð^cÑdÔdˆØ'ˆtÔ'¨ÐM°7ÐMÐ<LÐMÐMÐMÐMr:   c                ó&  — |�||fnd}| j                              |||¬¦  «        \  }}| j                              || j         j                             ¦   «         |||¬¦  «        \  }	}
|	                     dd¦  «        |
                     dd¦  «        fS )aÄ  Perform inference on image features using the SAM model.

        Args:
            features (torch.Tensor): Extracted image features with shape (B, C, H, W) from the SAM model image encoder.
            bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in XYXY format with shape (N, 4).
            points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels.
            labels (np.ndarray | list[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
            masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.

        Returns:
            pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
            pred_scores (torch.Tensor): Quality scores for each mask, with length C.
        N©rk   Úboxesrl   )Úimage_embeddingsÚimage_peÚsparse_prompt_embeddingsÚdense_prompt_embeddingsrw   r   r   )rL   Úprompt_encoderÚmask_decoderÚget_dense_peÚflatten)r5   r0   rj   rk   rm   rl   rw   Úsparse_embeddingsÚdense_embeddingsÚ
pred_masksÚpred_scoress              r9   r}   zPredictor._inference_featuresø   s­   € ð. &,Ð%7�&˜&Ð!Ð!¸Tˆà.2¬j×.GÒ.GÈvÐ]cÐkpÐ.GÑ.qÔ.qÑ+ÐÐ+ð #'¤*×"9Ò"9Ø%Ø”ZÔ.×;Ò;Ñ=Ô=Ø%6Ø$4Ø-ð #:ñ #
ô #
Ñˆ
�Kð ×!Ò! ! QÑ'Ô'¨×)<Ò)<¸QÀÑ)BÔ)BÐBÐBr:   c                ó  ‡— | j         rdn-t          |d         |d         z  |d         |d         z  ¦  «        }|�ít          j        || j        | j        ¬¦  «        }|j        dk    r|d         n|}|€!t          j        |j	        dd…         ¦  «        }t          j        |t          j
        | j        ¬¦  «        }|j	        d         |j	        d         k    s'J d|j	        d         › d	|j	        d         › d
�¦   «         ‚||z  }|j        dk    r|dd…ddd…f         |dd…df         }}|�;t          j        || j        | j        ¬¦  «        }|j        dk    r|d         n|}||z  }|�–t          j        |t          j        ¬¦  «        }|j        dk    r|d         n|}t          |dddt          j        ¬¦  «        Št          j        ˆfd„|D ¦   «         d¬¦  «        }t          j        || j        | j        ¬¦  «        }||||fS )aÜ  Prepare and transform the input prompts for processing based on the destination shape.

        Args:
            dst_shape (tuple[int, int]): The target shape (height, width) for the prompts.
            src_shape (tuple[int, int]): The source shape (height, width) of the input image.
            bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
            points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points,
                2), in pixels.
            labels (np.ndarray | list | None): Point prompt labels with shape (N) or (N, num_points). 1 for foreground,
                0 for background.
            masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array with
                shape (H, W).

        Returns:
            bboxes (torch.Tensor | None): Transformed bounding boxes.
            points (torch.Tensor | None): Transformed points.
            labels (torch.Tensor | None): Transformed labels.
            masks (torch.Tensor | None): Transformed masks.

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.
        ç      ð?r   r   N©ÚdtyperI   r<   re   úNumber of points ú should match number of labels ú.r>   ©r�   F)rT   rU   Úpadding_valueÚinterpolationc                óL   •— g | ] } ‰|¬ ¦  «                              ¦   «         ‘Œ!S rW   )ÚsqueezerZ   s     €r9   r^   z.Predictor._prepare_prompts.<locals>.<listcomp>O  s2   ø€ ÐJÐJÐJ¸q˜i˜i¨aÐ0Ñ0Ô0×8Ò8Ñ:Ô:ÐJÐJÐJr:   ©Úaxis)r2   Úminr@   Ú	as_tensorÚtorch_dtyperI   ÚndimrB   Úonesrf   Úint32ÚasarrayÚuint8r	   Úcv2ÚINTER_NEARESTrC   Útensor)	r5   Ú	dst_shaperh   rj   rk   rm   rl   Úrr]   s	           @r9   r|   zPredictor._prepare_prompts   s&  ø€ ð. Ô#ÐfˆCˆC­¨Y°q¬\¸IÀa¼LÑ-HÈ)ÐTUÌ,ÐYbÐcdÔYeÑJeÑ)fÔ)fˆàÐÝ”_ V°4Ô3CÈDÌKÐXÑXÔXˆFØ%+¤[°AÒ%5Ð%5�V˜D”\�\¸6ˆFàˆ~Ýœ ¤¨c¨r¨cÔ!2Ñ3Ô3�Ý”_ Vµ5´;ÀtÄ{ÐSÑSÔSˆFØ”< Ô# v¤|°BÔ'7Ò7Ð7Ð7Øh F¤L°Ô$4ÐhÐhÐU[ÔUaÐbdÔUeÐhÐhÐhñ 8Ô7Ð7ð �a‰KˆFØŒ{˜aÒÐà!'¨¨¨¨4°°°¨
Ô!3°V¸A¸A¸A¸t¸G´_˜�ØÐÝ”_ V°4Ô3CÈDÌKÐXÑXÔXˆFØ%+¤[°AÒ%5Ð%5�V˜D”\�\¸6ˆFØ�a‰KˆFØÐÝ”J˜u­B¬HÐ5Ñ5Ô5ˆEØ#(¤:°¢? ?�E˜$”K�K¸ˆEÝ! )°%ÀÐUVÕfiÔfwÐxÑxÔxˆIÝ”HÐJÐJÐJÐJÀEÐJÑJÔJÐQRÐSÑSÔSˆEÝ”L ¨dÔ.>ÀtÄ{ÐSÑSÔSˆEØ�v˜v uÐ,Ð,r:   r   ç¥âìÃgØÕ?r   é    é@   ç)\�Âõ(ì?çffffffî?çffffffæ?c           
     óš	  — ddl }d| _        |j        dd…         \  }}t          ||f||¦  «        \  }}|€t	          |||¦  «        }g g g g f\  }}}}t          ||¦  «        D �]\  }}|\  }}}}||z
  ||z
  }}t          j        ||z  |j        ¬¦  «        }t          j
        ||gg¦  «        }t          j        |d||…||…f         ||fdd¬	¦  «        } |                      | ¦  «        }!||         |z  }"g g g }%}$}#t          ||"¦  «        D �]b\  }&|                      | j        dd…         | j        |&¬
¦  «        }' | j        |!g|'¢R ddiŽ\  }(})t          j        |(d         ||fdd¬	¦  «        d         }(|)|k    }*|(|*         |)|*         })}(t%          |(| j        j        |
¦  «        }+|+|	k    }*|(|*         |)|*         })}(|(| j        j        k    }(t+          |(¦  «                             ¦   «         },t/          |,|dd||g¦  «         }-t          j        |-¦  «        s|,|-         |(|-         |)|-         })}(},|#                     |(¦  «         |%                     |,¦  «         |$                     |)¦  «         �Œdt          j        |#¦  «        }#t          j        |%¦  «        }%t          j        |$¦  «        }$|j                             |%|$| j        j        ¦  «        }.t?          |%|.         |¦  «        }%tA          |#|.         |||¦  «        }#|$|.         }$|                     |#¦  «         |                     |%¦  «         |                     |$¦  «         |                     | !                    |#j        d         ¦  «        ¦  «         �Œt          j        |¦  «        }t          j        |¦  «        }t          j        |¦  «        }t          j        |¦  «        }tE          |¦  «        dk    r9d|z  }/|j                             ||/|¦  «        }.||.         ||.         ||.         }}}|| j        j#        k    }*||*         ||*         ||*         }}}|dk    rƒ| j        \  }0}1tI          ||0z  ||1z  ¦  «        }2||2z  |2z  }3|  %                    ||3tM          | j        j        |¦  «        ¦  «        \  }}.||.         t+          |¦  «                             ¦   «         }}|||fS )a†  Perform image segmentation using the Segment Anything Model (SAM).

        This method segments an entire image into constituent parts by leveraging SAM's advanced architecture and
        real-time performance capabilities. It can optionally work on image crops for finer segmentation.

        Args:
            im (torch.Tensor): Input tensor representing the preprocessed image with shape (N, C, H, W).
            crop_n_layers (int): Number of layers for additional mask predictions on image crops.
            crop_overlap_ratio (float): Overlap between crops, scaled down in subsequent layers.
            crop_downscale_factor (int): Scaling factor for sampled points-per-side in each layer.
            point_grids (list[np.ndarray] | None): Custom grids for point sampling normalized to [0,1].
            points_stride (int): Number of points to sample along each side of the image.
            points_batch_size (int): Batch size for the number of points processed simultaneously.
            conf_thres (float): Confidence threshold [0,1] on the predicted mask quality; the predictor's conf also
                applies after the cross-crop NMS.
            stability_score_thresh (float): Stability threshold [0,1] for mask filtering based on stability.
            stability_score_offset (float): Offset value for calculating stability score.
            crop_nms_thresh (float): IoU cutoff for NMS to remove duplicate masks between crops.
            min_mask_region_area (int): If > 0, remove disconnected regions and holes smaller than this area in
                original-image pixels (the largest region of a mask is always kept), then re-run NMS on the
                cleaned masks.

        Returns:
            pred_masks (torch.Tensor): Segmented masks with shape (N, H, W).
            pred_scores (torch.Tensor): Confidence scores for each mask with shape (N,).
            pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 4).

        Examples:
            >>> predictor = Predictor()
            >>> im = torch.rand(1, 3, 1024, 1024)  # Example input image
            >>> masks, scores, boxes = predictor.generate(im)
        r   NTr>   ©rI   .ÚbilinearF)r(   Úalign_corners)rk   rw   r   )'Útorchvisionr2   rf   r   r   Úzipr@   r¥   rI   rB   ÚarrayÚFÚinterpolater{   r   r|   rh   r}   r   rL   Úmask_thresholdr   rO   r   rt   ÚappendÚcatr   Únmsr-   Úiour   r   Úexpandra   Úconfr›   r   Úmax)4r5   r/   Úcrop_n_layersÚcrop_overlap_ratioÚcrop_downscale_factorÚpoint_gridsÚpoints_strideÚpoints_batch_sizeÚ
conf_thresÚstability_score_threshÚstability_score_offsetÚcrop_nms_threshÚmin_mask_region_arear²   ÚihÚiwÚcrop_regionsÚ
layer_idxsr‹   rŒ   Úpred_bboxesÚregion_areasÚcrop_regionÚ	layer_idxÚx1Úy1Úx2Úy2ÚwÚhÚareaÚpoints_scaleÚcrop_imÚcrop_featuresÚpoints_for_imageÚ
crop_masksÚcrop_scoresÚcrop_bboxesrk   r1   Ú	pred_maskÚ
pred_scoreÚidxÚstability_scoreÚ	pred_bboxÚ	keep_maskÚkeepÚscoresÚh0Úw0ÚgainÚmin_areas4                                                       r9   ru   zPredictor.generateS  s%  € ð^ 	ÐÐÐàˆÔØ”˜!˜"˜"”‰ˆˆBÝ#6¸¸B°xÀÐPbÑ#cÔ#cÑ ˆ�jØÐÝ5°mÀ]ÐTiÑjÔjˆKØ=?ÀÀRÈ¸^Ñ:ˆ
�K ¨lÝ&)¨,¸
Ñ&CÔ&Cð /	Bñ /	BÑ"ˆK˜Ø(‰NˆB��B˜Ø˜‘7˜B ™GˆqˆAÝ”<  A¡¨b¬iÐ8Ñ8Ô8ˆDÝœ8 b¨" X JÑ/Ô/ˆLå”m B s¨B¨r¨E°2°b°5Ð'8Ô$9¸BÀ¸8È*ÐdiÐjÑjÔjˆGØ ×0Ò0°Ñ9Ô9ˆMØ*¨9Ô5¸ÑDÐØ35°r¸2 [˜ˆJÝ+Ð,=Ð?OÑPÔPð /ñ /‘	�Ø×/Ò/°´¸a¸b¸bÔ0AÀ4Ä>ÐZ`Ð/ÑaÔa�Ø(@¨Ô(@ÀÐ(pÐQXÐ(pÐ(pÐ(pÐkoÐ(pÐ(pÑ%�	˜:åœM¨)°D¬/¸A¸q¸6È
ÐbgÐhÑhÔhÐijÔk�	Ø  :Ò-�Ø(1°#¬¸
À3¼˜:�	å";Ø˜tœzÔ8Ð:Pñ#ô #�ð &Ð(>Ò>�Ø(1°#¬¸
À3¼˜:�	à%¨¬
Ô(AÒA�	å/°	Ñ:Ô:×@Ò@ÑBÔB�	Ý2°9¸kÈAÈqÐRTÐVXÈ>ÑZÔZÐZ�	Ý”y Ñ+Ô+ð yØ7@ÀÔ7KÈYÐW`ÔMaÐcmÐnwÔcx¨*˜y�Ià×!Ò! )Ñ,Ô,Ð,Ø×"Ò" 9Ñ-Ô-Ð-Ø×"Ò" :Ñ.Ô.Ð.Ñ.õ œ :Ñ.Ô.ˆJÝœ) KÑ0Ô0ˆKÝœ) KÑ0Ô0ˆKØ”?×&Ò& {°KÀÄÄÑOÔOˆDÝ+¨K¸Ô,=¸{ÑKÔKˆKÝ% j°Ô&6¸ÀRÈÑLÔLˆJØ% dÔ+ˆKà×Ò˜jÑ)Ô)Ð)Ø×Ò˜{Ñ+Ô+Ð+Ø×Ò˜{Ñ+Ô+Ð+Ø×Ò §¢¨JÔ,<¸QÔ,?Ñ @Ô @ÑAÔAÐAÑAå”Y˜zÑ*Ô*ˆ
Ý”i Ñ,Ô,ˆÝ”i Ñ,Ô,ˆÝ”y Ñ.Ô.ˆõ ˆ|ÑÔ˜qÒ Ð Ø˜Ñ%ˆFØ”?×&Ò& {°F¸OÑLÔLˆDØ3=¸dÔ3CÀ[ÐQUÔEVÐXcÐdhÔXi [˜ˆJà˜DœIœNÒ*ˆØ/9¸#¬ÀÈCÔ@PÐR]Ð^aÔRb �Kˆ
à !Ò#Ð#Ø”^‰FˆB�Ý�r˜B‘w  R¡Ñ(Ô(ˆDØ+¨dÑ2°TÑ9ˆHØ#×8Ò8¸ÀXÍsÐSWÔS\ÔS`ÐbqÑOrÔOrÑsÔsÑˆJ˜Ø'2°4Ô'8Õ:MÈjÑ:YÔ:Y×:_Ò:_Ñ:aÔ:a˜ˆKà˜;¨Ð3Ð3r:   Tc                ón  — t          | j        j        |¬¦  «        }| j        j        rt	          j        d¦  «         |€|                      ¦   «         }|                     |¦  «        }| j        j        dk    r| 	                    ¦   «         n| 
                    ¦   «         }|                     ¦   «          || _        || _        t          j        g d¢¦  «                             ddd¦  «                             |¦  «        | _        t          j        g d¢¦  «                             ddd¦  «                             |¦  «        | _        d	| j        _        d
| j        _        d| j        _        | j        j        dk    | j        _        d| _        | j        j        rt          j        nt          j        | _        dS )a\  Initialize the Segment Anything Model (SAM) for inference.

        This method sets up the SAM model by allocating it to the appropriate device and initializing the necessary
        parameters for image normalization and other Ultralytics compatibility settings.

        Args:
            model (torch.nn.Module | None): A pretrained SAM model. If None, a new model is built based on config.
            verbose (bool): If True, prints selected device information.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_model(model=sam_model, verbose=True)
        )ÚverbosezC'channels_last=True' is not supported for SAM predictors, ignoring.Nr!   )g33333ë^@gR¸…ë]@gR¸…ëáY@r<   r   )gÃõ(\�2M@g�Âõ(\�L@g     °L@ÚsamFr©   T)r   r-   rI   Úchannels_lastr   ÚwarningÚ	get_modelrH   ÚquantizerN   rO   ÚevalrL   r@   r¥   ÚviewrJ   rK   ÚformatÚ
base_modelÚstriderM   Údone_warmupÚfloat16Úfloat32r�   )r5   rL   rí   rI   s       r9   Úsetup_modelzPredictor.setup_modelÒ  sl  € õ ˜tœyÔ/¸ÐAÑAÔAˆØŒ9Ô"ð 	bÝŒNÐ`ÑaÔaÐaØˆ=Ø—N’NÑ$Ô$ˆEà—’˜Ñ Ô ˆØ $¤	Ô 2°bÒ 8Ð 8�—
’
‘”�¸e¿kºk¹m¼mˆØ�
Š
‰ŒˆØˆŒ
ØˆŒÝ”LÐ!:Ð!:Ð!:Ñ;Ô;×@Ò@ÀÀQÈÑJÔJ×MÒMÈfÑUÔUˆŒ	Ý”<Ð 7Ð 7Ð 7Ñ8Ô8×=Ò=¸bÀ!ÀQÑGÔG×JÒJÈ6ÑRÔRˆŒð "ˆŒ
ÔØ %ˆŒ
ÔØˆŒ
ÔØœ)Ô,°Ò2ˆŒ
ŒØˆÔØ,0¬J¬OÐN�5œ=˜=ÅÄˆÔÐÐr:   c                ó8   — ddl m}  || j        j        ¦  «        S )zPRetrieve or build the Segment Anything Model (SAM) for image segmentation tasks.r   ©Ú	build_sam©Úbuildrþ   r-   rL   ©r5   rþ   s     r9   rñ   zPredictor.get_model÷  ó(   € à$Ð$Ð$Ð$Ð$Ð$àˆy˜œœÑ)Ô)Ð)r:   c           
     óØ  — |dd…         \  }}| j         r|d         nd}t          t          d„ t          |j        d         ¦  «        D ¦   «         ¦  «        ¦  «        }t          |t          ¦  «        st          j        |¦  «        dddd…f         }g }t          |g|| j
        d         ¦  «        D �]±\  }	}
}|	j        d         dk    rdt          j        d|j        ¬¦  «        }}	�nS|| j        j        k    }t          j        |	|         d                              ¦   «         |
j        dd…         d	¬
¦  «        d         }	| j        r.| j                             |	dd…df         ¦  «        dd…df         }	|	| j        j        k    }	|�Ct          j        |j        dd…         ||                              ¦   «         |
j        d	¬
¦  «        }nt/          |	¦  «        }t          j        |j        d         t          j        |j        ¬¦  «        |         }t          j        |||df         |dd…df         gd¬¦  «        }|                     t9          |
|||	|¬¦  «        ¦  «         �Œ³d	| _         |S )aË  Post-process SAM's inference outputs to generate object detection masks and bounding boxes.

        This method scales masks and boxes to the original image size and applies a threshold to the mask
        predictions. It leverages SAM's advanced architecture for real-time, promptable segmentation tasks.

        Args:
            preds (tuple): The output from SAM model inference, containing:
                - pred_masks (torch.Tensor): Predicted masks with shape (N, 1, H, W).
                - pred_scores (torch.Tensor): Confidence scores for each mask with shape (N, 1).
                - pred_bboxes (torch.Tensor, optional): Predicted bounding boxes if segment_all is True.
            img (torch.Tensor): The processed input image tensor with shape (C, H, W).
            orig_imgs (list[np.ndarray] | torch.Tensor): The original, unprocessed images.

        Returns:
            (list[Results]): List of Results objects containing detection masks, bounding boxes, and other metadata for
                each processed image.

        Examples:
            >>> predictor = Predictor()
            >>> preds = predictor.inference(img)
            >>> results = predictor.postprocess(preds, img, orig_imgs)
        Nr>   c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ro   ©Ústrrp   s     r9   rr   z(Predictor.postprocess.<locals>.<genexpr>  s(   è è € ÐJÐJ¨!�s 1™vœvÐJÐJÐJÐJÐJÐJr:   r   .r<   ©r   é   r¯   F©Úpaddingr�   ©Údim©ÚpathÚnamesrl   r€   )r2   ÚdictÚ	enumerateÚrangerf   r?   Úlistr   Úconvert_torch2numpy_batchr³   r)   r@   ÚzerosrI   r-   r½   Úscale_masksrO   r3   rL   Ú"_apply_non_overlapping_constraintsr·   Úscale_boxesr   Úaranger    r¹   r¸   r   )r5   ÚpredsÚimgÚ	orig_imgsr‹   rŒ   rÎ   r  Úresultsrl   Úorig_imgÚimg_pathrâ   Úclss                 r9   ÚpostprocesszPredictor.postprocessý  s|  € ð0 #(¨¨¨¤)Ñˆ
�KØ"&Ô"2Ð<�e˜A”h�h¸ˆÝ•YÐJÐJ­u°ZÔ5EÀaÔ5HÑ/IÔ/IÐJÑJÔJÑJÔJÑKÔKˆå˜)¥TÑ*Ô*ð 	LÝÔ5°iÑ@Ô@ÀÀdÀdÈÀdÀÔKˆIàˆÝ),¨j¨\¸9ÀdÄjÐQRÄmÑ)TÔ)Tð 	jñ 	jÑ%ˆE�8˜XØŒ{˜1Œ~ Ò"Ð"Ø%)­5¬;°vÀjÔFWÐ+XÑ+XÔ+X�{�‘à! D¤I¤NÒ2�Ýœ¨¨c¬
°4Ô(8×(>Ò(>Ñ(@Ô(@À(Ä.ÐQSÐRSÐQSÔBTÐ^cÐdÑdÔdÐefÔg�ØÔ)ð `Ø œJ×IÒIÈ%ÐPQÐPQÐPQÐSWÐPWÌ.ÑYÔYÐZ[ÐZ[ÐZ[Ð]^ÐZ^Ô_�EØ ¤
Ô 9Ò9�ØÐ*Ý"%¤/Øœ	 ! " "œ {°3Ô'7×'=Ò'=Ñ'?Ô'?ÀÄÐY^ð#ñ #ô #�K�Kõ #6°eÑ"<Ô"<�Kå”l :Ô#3°AÔ#6½e¼kÐR\ÔRcÐdÑdÔdÐehÔi�Ý#œi¨°kÀ#ÀtÀ)Ô6LÈcÐRSÐRSÐRSÐUYÐRYÌlÐ([ÐacÐdÑdÔd�Ø�NŠN�7 8°(À%ÈuÐ\gÐhÑhÔhÑiÔiÐiÑià ˆÔØˆr:   c                ó,  — | j         €|                      ¦   «          |                      |¦  «         t          | j        ¦  «        dk    s
J d¦   «         ‚| j        D ]9}|                      |d         ¦  «        }|                      |¦  «        | _         dS dS )a  Preprocess and set a single image for inference.

        This method prepares the model for inference on a single image by setting up the model if not already
        initialized, configuring the data source, and preprocessing the image for feature extraction. It ensures that
        only one image is set at a time and extracts image features for subsequent use.

        Args:
            image (str | np.ndarray): Path to the image file as a string, or a numpy array representing an image read by
                cv2 (BGR channel order).

        Raises:
            AssertionError: If more than one image is attempted to be set.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.set_image("path/to/image.jpg")
            >>> predictor.set_image(cv2.imread("path/to/image.jpg"))

        Notes:
            - This method should be called before performing inference on a new image.
            - The extracted features are stored in the `self.features` attribute for later use.
        Nr   z,`set_image` only supports setting one image!)rL   rû   Úsetup_sourcera   ÚdatasetrQ   r{   r0   )r5   rX   r)   r/   s       r9   Ú	set_imagezPredictor.set_image4  s¢   € ð0 Œ:ÐØ×ÒÑÔÐØ×Ò˜%Ñ Ô Ð Ý�4”<Ñ Ô  AÒ%Ð%Ð%Ð'UÑ%Ô%Ð%Ø”\ð 	ð 	ˆEØ—’  q¤Ñ*Ô*ˆBØ ×0Ò0°Ñ4Ô4ˆDŒMØˆEˆEð	ð 	r:   c                ó<  •— |€dS t          ¦   «                              || j        ¦  «         t          | j        t
          t          f¦  «        r| j        d         | j        d         k    sJ d| j        › d�¦   «         ‚| j                             | j        ¦  «         dS )z)Set up the data source for SAM inference.Nr   r   z3SAM models only support square image size, but got r“   )	r+   r#  r÷   r?   rb   Útupler  rL   Ú	set_imgsz©r5   Úsourcer8   s     €r9   r#  zPredictor.setup_sourceU  s—   ø€ àˆ>ØˆFÝ‰Œ×Ò˜V T¤[Ñ1Ô1Ð1Ý˜$œ*¥u­d mÑ4Ô4ð 	
¸¼ÀA¼È$Ì*ÐUVÌ-Ò9WÐ9WÐ9WØOÀ$Ä*ÐOÐOÐOñ :XÔ9WÐWð 	Œ
×Ò˜TœZÑ(Ô(Ð(Ð(Ð(r:   c                ó6   — | j                              |¦  «        S )zZExtract image features using the SAM model's image encoder for subsequent mask prediction.)rL   Úimage_encoder©r5   r/   s     r9   r{   zPredictor.get_im_features_  s   € àŒz×'Ò'¨Ñ+Ô+Ð+r:   c                ó   — || _         dS )z0Set prompts for subsequent inference operations.N)r1   )r5   r1   s     r9   Úset_promptszPredictor.set_promptsc  s   € àˆŒˆˆr:   c                ó"   — d| _         d| _        dS )zQReset the current image and its features, clearing them for subsequent inference.N)r/   r0   ©r5   s    r9   Úreset_imagezPredictor.reset_imageg  s   € àˆŒØˆŒˆˆr:   c                óL  — ddl }| j        d         dk    r| t          j        d¦  «        fS g }g }| D ]Ó}|                     ¦   «                              ¦   «                              t          j        ¦  «        }t          ||d¬¦  «        \  }}| }t          ||d¬¦  «        \  }}|o| }| 
                    t          j        |¦  «                             d¦  «        ¦  «         | 
                    t          |¦  «        ¦  «         ŒÔt          j        |d¬¦  «        }t          |                     ¦   «         ¦  «        }	|j                             |	                     ¦   «         t          j        |¦  «        |¦  «        }
||
                              | j        | j        ¬¦  «        |
fS )a\  Remove small disconnected regions and holes from segmentation masks.

        This function performs post-processing on segmentation masks generated by the Segment Anything Model (SAM). It
        removes small disconnected regions and holes from the input masks, and then performs Non-Maximum Suppression
        (NMS) to eliminate any newly created duplicate boxes.

        Args:
            masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
                masks, H is height, and W is width.
            min_area (float): Minimum area threshold for removing disconnected regions and holes. Regions smaller than
                this will be removed.
            nms_thresh (float): IoU threshold for the NMS algorithm to remove duplicate boxes.

        Returns:
            new_masks (torch.Tensor): Processed masks with small regions removed, shape (N, H, W).
            keep (torch.Tensor): Indices of remaining masks after NMS, for filtering corresponding boxes.

        Examples:
            >>> masks = torch.rand(5, 640, 640) > 0.5  # 5 random binary masks
            >>> new_masks, keep = remove_small_regions(masks, min_area=100, nms_thresh=0.7)
            >>> print(f"Original masks: {masks.shape}, Processed masks: {new_masks.shape}")
            >>> print(f"Indices of kept masks: {keep}")
        r   NÚholes©r(   Úislandsr  ©rI   r�   )r²   rf   r@   r  ÚcpuÚnumpyÚastyperB   r¢   r   r¸   rœ   Ú	unsqueezerO   r¹   r   Úboolr   rº   rH   rI   r�   )rl   rë   Ú
nms_threshr²   Ú	new_masksrç   ÚmaskÚchangedÚ	unchangedr€   ræ   s              r9   r   zPredictor.remove_small_regionsl  s‚  € ð2 	ÐÐÐàŒ;�qŒ>˜QÒÐØ�%œ, q™/œ/Ð)Ð)ð ˆ	ØˆØð 		,ð 		,ˆDØ—8’8‘:”:×#Ò#Ñ%Ô%×,Ò,­R¬XÑ6Ô6ˆDÝ0°°xÀgÐNÑNÔN‰MˆD�'Ø#˜ˆIÝ0°°xÀiÐPÑPÔP‰MˆD�'Ø!Ð1¨' kˆIà×Ò�Uœ_¨TÑ2Ô2×<Ò<¸QÑ?Ô?Ñ@Ô@Ð@à�MŠM�% 	Ñ*Ô*Ñ+Ô+Ð+Ð+õ ”I˜i¨QÐ/Ñ/Ô/ˆ	å# I§N¢NÑ$4Ô$4Ñ5Ô5ˆØŒ×"Ò" 5§;¢;¡=¤=µ%´/À&Ñ2IÔ2IÈ:ÑVÔVˆà˜Œ×!Ò!¨¬¸U¼[Ð!ÑIÔIÈ4ÐOÐOr:   c	                óZ  — |p| j         j        | j         j        f}|                      ||||||¦  «        }	 | j        |g|	¢|‘R Ž \  }
}|
j        d         dk    rdt          j        d|
j        ¬¦  «        }}
n²t          j	        |
d          
                    ¦   «         |d¬¦  «        d         }
|
| j        j        k    }
t          |
¦  «        }t          j        |
j        d         t
          j        |
j        ¬¦  «        }t          j        ||dd…df         |dd…df         gd¬	¦  «        }|
|fS )
aî  Perform prompts preprocessing and inference on provided image features using the SAM model.

        Args:
            features (torch.Tensor | dict[str, Any]): Extracted image features from the SAM/SAM2 model image encoder.
            src_shape (tuple[int, int]): The source shape (height, width) of the input image.
            dst_shape (tuple[int, int] | None): The target shape (height, width) for the prompts. If None, defaults to
                (imgsz, imgsz).
            bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4).
            points (np.ndarray | list[list[float]] | None): Points indicating object locations with shape (N, 2), in
                pixels.
            labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ).
            masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.

        Returns:
            pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
            pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes.
                Each box is in xyxy format with additional columns for score and class.

        Notes:
            - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2.
        r   Nr  r¯   Fr	  r�   r<   r  )r-   rb   r|   r}   rf   r@   r  rI   r   r  rO   rL   r·   r   r  r    r¹   )r5   r0   rh   r¦   rj   rk   rm   rl   rw   r1   r‹   rŒ   rÎ   r   s                 r9   Úinference_featureszPredictor.inference_features   s<  € ðD ÐC $¤)¤/°4´9´?Ð!Cˆ	Ø×'Ò'¨	°9¸fÀfÈfÐV[Ñ\Ô\ˆØ": $Ô":¸8Ð"`ÀgÐ"`ÐO_Ð"`Ð"`Ð"`Ñˆ
�KØÔ˜AÔ !Ò#Ð#Ø&*­E¬K¸ÀzÔGXÐ,YÑ,YÔ,Y˜ˆJˆJåœ¨°DÔ)9×)?Ò)?Ñ)AÔ)AÀ9ÐV[Ð\Ñ\Ô\Ð]^Ô_ˆJØ# d¤jÔ&?Ò?ˆJÝ-¨jÑ9Ô9ˆKå”,˜zÔ/°Ô2½%¼+ÈjÔN_Ð`Ñ`Ô`ˆCÝœ) [°+¸a¸a¸aÀ¸gÔ2FÈÈAÈAÈAÈtÈGÌÐ$UÐ[]Ð^Ñ^Ô^ˆKØ˜;Ð&Ð&r:   ©r"   r#   )NNNNF©NNNN)r   r¨   r   Nr©   rª   r«   r¬   r¬   r­   r   ©NT)r   r­   ©NNNNNF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r÷   r   r,   rQ   rD   Úpropertyrh   ry   rv   r}   r|   ru   r   rû   rñ   r!  r%  r#  r{   r/  r2  Ústaticmethodr   rC  Ú__classcell__©r8   s   @r9   r    r    -   se  ø€ € € € € ð(ð (ðT €Fà&°$ÐRVð 'ð 'ð 'ð 'ð 'ð 'ð 'ð. ð  ð  ðD0ð 0ð 0ð6 ðRð Rñ „XðRð
$Zð $Zð $Zð $ZðLNð Nð Nð NðB ØØØØð&Cð &Cð &Cð &CðP1-ð 1-ð 1-ð 1-ðl Ø%ØØØØØØ#Ø#ØØð}4ð }4ð }4ð }4ð~ Ð˜%Ñ Ô ð"Oð "Oð "Oñ !Ô ð"OðH*ð *ð *ð5ð 5ð 5ðn ÐÑÔðð ñ Ôðð@)ð )ð )ð )ð )ð,ð ,ð ,ðð ð ðð ð ð
 ð1Pð 1Pð 1Pñ „\ð1Pðf ÐÑÔð
 ØØØØØð-'ð -'ð -'ñ Ôð-'ð -'ð -'ð -'ð -'r:   r    c                  óX   ‡ — e Zd ZdZg d¢ZdZd„ Zdˆ fd„	Zˆ fd„Zd„ Z		 	 	 	 	 dd„Z
ˆ xZS )ÚSAM2Predictoraž  SAM2Predictor class for advanced image segmentation using Segment Anything Model 2 architecture.

    This class extends the base Predictor class to implement SAM2-specific functionality for image segmentation tasks.
    It provides methods for model initialization, feature extraction, and prompt-based inference.

    Attributes:
        _bb_feat_sizes (list[tuple]): Feature sizes for different backbone levels.
        model (torch.nn.Module): The loaded SAM2 model.
        device (torch.device): The device (CPU or GPU) on which the model is loaded.
        features (dict): Cached image features for efficient inference.
        segment_all (bool): Flag to indicate if all segments should be predicted.
        prompts (dict[str, Any]): Dictionary to store various types of prompts for inference.

    Methods:
        get_model: Retrieve and initialize the SAM2 model.
        prompt_inference: Perform image segmentation inference based on various prompts.
        set_image: Preprocess and set a single image for inference.
        get_im_features: Extract and process image features using SAM2's image encoder.

    Examples:
        >>> predictor = SAM2Predictor(cfg)
        >>> predictor.set_image("path/to/image.jpg")
        >>> bboxes = [[100, 100, 200, 200]]
        >>> result = predictor(bboxes=bboxes)[0]
        >>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}")
    ))é   rR  )é€   rS  )rª   rª   r!   c                ó8   — ddl m}  || j        j        ¦  «        S )zYRetrieve and initialize the Segment Anything Model 2 (SAM2) for image segmentation tasks.r   rý   rÿ   r  s     r9   rñ   zSAM2Predictor.get_modelô  r  r:   Nc                ó”  •— t          ¦   «                              ||||||¦  «        \  }}}}|�–|                     ddd¦  «        }t          j        ddggt          j        |j        ¬¦  «                             |j        d         d¦  «        }|�1t          j	        ||gd¬¦  «        }t          j	        ||gd¬¦  «        }n||}}|||fS )	ai  Prepare and transform the input prompts for processing based on the destination shape.

        Args:
            dst_shape (tuple[int, int]): The target shape (height, width) for the prompts.
            src_shape (tuple[int, int]): The source shape (height, width) of the input image.
            bboxes (np.ndarray | list | None): Bounding boxes in XYXY format with shape (N, 4).
            points (np.ndarray | list | None): Points indicating object locations with shape (N, 2) or (N, num_points,
                2), in pixels.
            labels (np.ndarray | list | None): Point prompt labels with shape (N,) or (N, num_points). 1 for foreground,
                0 for background.
            masks (list | np.ndarray | None): Masks for the objects, where each mask is a 2D array.

        Returns:
            points (torch.Tensor | None): Transformed points.
            labels (torch.Tensor | None): Transformed labels.
            masks (torch.Tensor | None): Transformed masks.

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.
        Nr<   r>   r=   r�   r   r   r  )
r+   r|   rô   r@   r¥   r    rI   r¼   rf   r¹   )	r5   r¦   rh   rj   rk   rm   rl   Úbbox_labelsr8   s	           €r9   r|   zSAM2Predictor._prepare_promptsú  sÛ   ø€ õ* ).©¬×(@Ò(@ÀÈIÐW]Ð_eÐgmÐotÑ(uÔ(uÑ%ˆ�˜ ØÐØ—[’[  Q¨Ñ*Ô*ˆFÝœ,¨¨A¨ xµu´{È6Ì=ÐYÑYÔY×`Ò`ÐagÔamÐnoÔapÐrtÑuÔuˆKð Ð!Ýœ F¨FÐ#3¸Ð;Ñ;Ô;�Ýœ K°Ð#8¸aÐ@Ñ@Ô@��à!'¨˜�Ø�v˜uÐ$Ð$r:   c                ór   •‡ — t          ¦   «                              |¦  «         ˆ fd„dD ¦   «         ‰ _        dS )z9Set up the data source and image size for SAM2 inference.c                ó:   •‡— g | ]Šˆˆfd „‰j         D ¦   «         ‘ŒS )c                óD   •— g | ]}t          |‰j        ‰z  z  ¦  «        ‘ŒS rY   ©Úintr÷   ©r[   r\   rq   r5   s     €€r9   r^   z9SAM2Predictor.setup_source.<locals>.<listcomp>.<listcomp>  s,   ø€ ÐOÐOÐO¸q¥ A¨¬°q©Ñ$9Ñ :Ô :ÐOÐOÐOr:   ©rb   ©r[   rq   r5   s    @€r9   r^   z.SAM2Predictor.setup_source.<locals>.<listcomp>  s5   øø€ ÐkÐkÐkÐTUÐOÐOÐOÐOÐOÀDÄJÐOÑOÔOÐkÐkÐkr:   ©g      Ð?ç      à?r   N)r+   r#  Ú_bb_feat_sizesr)  s   ` €r9   r#  zSAM2Predictor.setup_source  s?   øø€ å‰Œ×Ò˜VÑ$Ô$Ð$ØkÐkÐkÐkÐYjÐkÑkÔkˆÔÐÐr:   c                ó   — | j                              |¦  «        }| j                              |¦  «        \  }}}}| j         j        r|d         | j         j        z   |d<   d„ t          || j        ¦  «        D ¦   «         }|d         |dd…         dœS )zLExtract image features from the SAM image encoder for subsequent processing.r<   c                ó\   — g | ])\  }} |                      d dd¦  «        j        d dg|¢R Ž ‘Œ*S )r   r>   r   r<   )Úpermuterô   ©r[   ÚfeatÚ	feat_sizes      r9   r^   z1SAM2Predictor.get_im_features.<locals>.<listcomp>'  sQ   € ð 
ð 
ð 
Ù>M¸dÀIÐ&ˆD�LŠL˜˜A˜qÑ!Ô!Ô& q¨"Ð9¨yÐ9Ð9Ð9ð
ð 
ð 
r:   N)Úimage_embedÚhigh_res_feats)rL   Úforward_imageÚ_prepare_backbone_featuresÚdirectly_add_no_mem_embedÚno_mem_embedr³   ra  )r5   r/   Úbackbone_outÚ_Úvision_featsÚfeatss         r9   r{   zSAM2Predictor.get_im_features!  s¥   € à”z×/Ò/°Ñ3Ô3ˆØ $¤
× EÒ EÀlÑ SÔ SÑˆˆ<˜˜AØŒ:Ô/ð 	JØ+¨BÔ/°$´*Ô2IÑIˆL˜Ñð
ð 
ÝQTÐUaÐcgÔcvÑQwÔQwð
ñ 
ô 
ˆð  % Rœy¸EÀ#À2À#¼JÐGÐGÐGr:   Fr<   c           	     óÚ  ‡— |�||fnd}| j                              |d|¬¦  «        \  }}|duo|d         j        d         dk    }	d}
t          |t          ¦  «        r#ˆfd„|d         D ¦   «         }
|d         ‰g         }| j                              || j         j                             ¦   «         ||||	|
¬¦  «        \  }}}}|                     dd¦  «        |                     dd¦  «        fS )	av  Perform inference on image features using the SAM2 model.

        Args:
            features (torch.Tensor | dict[str, Any]): Extracted image features with shape (B, C, H, W) from the SAM2
                model image encoder. Can also be a dict with 'image_embed' (torch.Tensor) of shape (B, C, H, W) and
                'high_res_feats' (list[torch.Tensor]) high-resolution feature maps from the backbone.
            points (np.ndarray | list[list[float]] | None): Object location points with shape (N, 2), in pixels.
            labels (np.ndarray | list[int] | None): Point prompt labels with shape (N,). 1 = foreground, 0 = background.
            masks (list[np.ndarray] | np.ndarray | None): Masks for the objects, where each mask is a 2D array.
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
            img_idx (int): Index of the image in the batch to process.

        Returns:
            pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
            pred_scores (torch.Tensor): Quality scores for each mask, with length C.
        Nr   r   r   c                óF   •— g | ]}|‰                               d ¦  «        ‘ŒS )r   )r;  )r[   Ú
feat_levelÚimg_idxs     €r9   r^   z5SAM2Predictor._inference_features.<locals>.<listcomp>O  s,   ø€ Ð oÐ oÐ oÀj ¨GÔ!4×!>Ò!>¸qÑ!AÔ!AÐ oÐ oÐ or:   ri  rh  )r�   r‚   rƒ   r„   rw   Úrepeat_imageÚhigh_res_features)rL   Úsam_prompt_encoderrf   r?   r  Úsam_mask_decoderr‡   rˆ   )r5   r0   rk   rm   rl   rw   ru  r‰   rŠ   Úbatched_moderw  r‹   rŒ   ro  s         `       r9   r}   z!SAM2Predictor._inference_features,  s*  ø€ ð2 &,Ð%7�&˜&Ð!Ð!¸TˆØ.2¬j×.KÒ.KØØØð /Lñ /
ô /
Ñ+ÐÐ+ð  TÐ)ÐD¨f°Q¬i¬o¸aÔ.@À1Ò.DˆØ ÐÝ�h¥Ñ%Ô%ð 	:Ø oÐ oÐ oÐ oÐT\Ð]mÔTnÐ oÑ oÔ oÐØ Ô.°¨yÔ9ˆHØ(,¬
×(CÒ(CØ%Ø”ZÔ2×?Ò?ÑAÔAØ%6Ø$4Ø-Ø%Ø/ð )Dñ )
ô )
Ñ%ˆ
�K  Að ×!Ò! ! QÑ'Ô'¨×)<Ò)<¸QÀÑ)BÔ)BÐBÐBr:   rE  )NNNFr<   )rH  rI  rJ  rK  ra  r÷   rñ   r|   r#  r{   r}   rN  rO  s   @r9   rQ  rQ  Ñ  sÌ   ø€ € € € € ðð ð6ð ð €Nð
 €Fð*ð *ð *ð %ð  %ð  %ð  %ð  %ð  %ðDlð lð lð lð lð
	Hð 	Hð 	Hð ØØØØð0Cð 0Cð 0Cð 0Cð 0Cð 0Cð 0Cð 0Cr:   rQ  c                  óÊ  ‡ — e Zd ZdZeddfd ˆ fd„Zˆ fd„Zˆ fd„Zd!d„Z e	¦   «         	 	 	 	 	 d"d#d„¦   «         Z
 e	¦   «         d$d#d„¦   «         Zed„ ¦   «         Zed„ ¦   «         Z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d$d#d„Z e	¦   «         d(d„¦   «         Z e	¦   «         d„ ¦   «         Z e	¦   «         d„ ¦   «         Zed„ ¦   «         Zd$d„Zˆ xZS ))ÚSAM2VideoPredictora¤  SAM2VideoPredictor to handle user interactions with videos and manage inference states.

    This class extends the functionality of SAM2Predictor to support video processing and maintains the state of
    inference operations. It includes configurations for managing non-overlapping masks and clearing memory for
    non-conditional inputs.

    Attributes:
        inference_state (dict): A dictionary to store the current state of inference operations.
        non_overlap_masks (bool): A flag indicating whether masks should be non-overlapping.
        clear_non_cond_mem_around_input (bool): A flag to control clearing non-conditional memory around inputs.
        clear_non_cond_mem_for_multi_obj (bool): A flag to control clearing non-conditional memory for multi-object
            scenarios.

    Methods:
        get_model: Retrieve and configure the model with binarization enabled.
        inference: Perform image segmentation inference based on the given input cues.
        add_new_prompts: Add new points or masks to a specific frame for a given object ID.
        propagate_in_video_preflight: Prepare inference_state and consolidate temporary outputs before tracking.
        init_state: Initialize an inference state for the predictor.
        get_im_features: Extract image features using SAM2's image encoder for subsequent segmentation tasks.

    Examples:
        >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
        >>> predictor.set_image("path/to/video_frame.jpg")
        >>> bboxes = [[100, 100, 200, 200]]
        >>> results = predictor(bboxes=bboxes)

    Notes:
        The `fill_hole_area` attribute is defined but not used in the current implementation.
    Nr"   r#   c                ó”   •— t          ¦   «                              |||¦  «         i | _        d| _        d| _        d| _        d| _        dS )aK  Initialize the predictor with configuration and optional overrides.

        This constructor initializes the SAM2VideoPredictor with a given configuration, applies any specified overrides,
        and sets up the inference state along with certain flags that control the behavior of the predictor.

        Args:
            cfg (dict): Configuration dictionary containing default settings.
            overrides (dict | None): Dictionary of values to override default configuration.
            _callbacks (dict | None): Dictionary of callback functions to customize behavior.
        TFN)r+   r,   Úinference_stater3   Úclear_non_cond_mem_around_inputÚ clear_non_cond_mem_for_multi_objÚclear_non_cond_memr4   s       €r9   r,   zSAM2VideoPredictor.__init__�  sO   ø€ õ 	‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ø!ˆÔØ!%ˆÔØ/4ˆÔ,Ø05ˆÔ-Ø"&ˆÔÐÐr:   c                óª   •— t          ¦   «                              |¦  «         | j        �'| j        j        dk    r|                      | ¦  «         dS dS dS )zZSet up the source and build the video inference state before any prediction callback runs.NÚvideo)r+   r#  r$  r(   Ú
init_stater)  s     €r9   r#  zSAM2VideoPredictor.setup_source“  sX   ø€ å‰Œ×Ò˜VÑ$Ô$Ð$ØŒ<Ð#¨¬Ô(9¸WÒ(DÐ(DØ�OŠO˜DÑ!Ô!Ð!Ð!Ð!ð $Ð#Ð(DÐ(Dr:   c                ór   •— t          ¦   «                              ¦   «         }|                     d¦  «         |S )z¶Retrieve and configure the model with binarization enabled.

        Notes:
            This method overrides the base class implementation to set the binarize flag to True.
        T)r+   rñ   Úset_binarize)r5   rL   r8   s     €r9   rñ   zSAM2VideoPredictor.get_model™  s3   ø€ õ ‘”×!Ò!Ñ#Ô#ˆØ×Ò˜4Ñ Ô Ð Øˆr:   c           
     óì  — | j                              d|¦  «        }| j                              d|¦  «        }| j                              d|¦  «        }| j        j        }|| j        d<   | j        d         }t          |d         ¦  «        dk    r¹|                      |j        dd	…         | j        ||||¦  «        \  }}}|�Gt          t          |¦  «        ¦  «        D ])}|  
                    |||g         ||g         |¬
¦  «         Œ*n@|�>t          t          |¦  «        ¦  «        D ]!}|  
                    |||g         |¬¦  «         Œ"|                      ¦   «          | j        d         }	t          | j        d         ¦  «        }
t          |d         ¦  «        dk    rt          d¦  «        ‚||	d         v r:d}||         |         }| j        r"| j        s|
dk    r|                      |¦  «         nZ||	d         v rd}||         |         }n?d}|                      |||
dd	d	dd¬¦  «        }|||         |<   |                      |¦  «         |                      |||¦  «         | j        d                              |¦  «         |d                              dd¦  «        }||| j        j        k                         d¦  «        dk             }|t1          j        |j        d         |j        |j        ¬¦  «        fS )ab  Perform image segmentation inference based on the given input cues, using the currently loaded image. This
        method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
        encoder, and mask decoder for real-time and promptable segmentation tasks.

        Args:
            im (torch.Tensor): The preprocessed input image in tensor format, with shape (N, C, H, W).
            bboxes (np.ndarray | list, optional): Bounding boxes with shape (N, 4), in XYXY format.
            points (np.ndarray | list, optional): Points indicating object locations with shape (N, 2), in pixels.
            labels (np.ndarray | list, optional): Labels for point prompts, shape (N, ). 1 = foreground, 0 = background.
            masks (np.ndarray, optional): Low-resolution masks from previous predictions shape (N,H,W). For SAM H=W=256.

        Returns:
            pred_masks (torch.Tensor): The output masks in shape CxHxW, where C is the number of generated masks.
            pred_scores (torch.Tensor): An array of length C containing predicted quality scores for each mask.
        rj   rk   rl   r/   Úoutput_dictÚcond_frame_outputsr   r>   N)Úobj_idrk   rm   Ú	frame_idx)rŠ  rl   r‹  Úconsolidated_frame_indsÚobj_idx_to_idú/No points are provided; please add points firstr   Únon_cond_frame_outputsFT)rˆ  r‹  Ú
batch_sizeÚis_init_cond_frameÚpoint_inputsÚmask_inputsÚreverseÚrun_mem_encoderÚframes_already_trackedr‹   ©r   r>   r�   )r1   rs   r$  Úframer~  ra   r|   rf   rh   r  Úadd_new_promptsÚpropagate_in_video_preflightÚRuntimeErrorr  r€  Ú _clear_non_cond_mem_around_inputÚ_run_single_frame_inferenceÚ_prune_non_cond_memoryÚ_add_output_per_objectr¸   rˆ   rL   r·   Úsumr@   rŸ   r�   rI   )r5   r/   rj   rk   rm   rl   r˜  rˆ  rq   rŒ  r�  Ústorage_keyÚcurrent_outr‹   s                 r9   ry   zSAM2VideoPredictor.inference£  s?  € ð" ”×!Ò! (¨FÑ3Ô3ˆØ”×!Ò! (¨FÑ3Ô3ˆØ”× Ò  ¨%Ñ0Ô0ˆà”Ô"ˆØ%'ˆÔ˜TÑ"ØÔ*¨=Ô9ˆÝˆ{Ð/Ô0Ñ1Ô1°QÒ6Ð6Ø$(×$9Ò$9¸"¼(À1À2À2¼,ÈÌÐX^Ð`fÐhnÐpuÑ$vÔ$vÑ!ˆF�F˜EØÐ!Ý�s 6™{œ{Ñ+Ô+ð lð l�AØ×(Ò(°¸&À!À¼+ÈfÐVWÐUXÌkÐejÐ(ÑkÔkÐkÐkðlàÐ"Ý�s 5™zœzÑ*Ô*ð Vð V�AØ×(Ò(°¸À¸s¼ÈuÐ(ÑUÔUÐUÐUØ×)Ò)Ñ+Ô+Ð+à"&Ô"6Ð7PÔ"QÐÝ˜Ô-¨oÔ>Ñ?Ô?ˆ
Ýˆ{Ð/Ô0Ñ1Ô1°QÒ6Ð6ÝÐPÑQÔQÐQàÐ+Ð,@ÔAÐAÐAØ.ˆKØ% kÔ2°5Ô9ˆKØÔ3ð =¸Ô9^ð =ÐblÐpqÒbqÐbqà×5Ò5°eÑ<Ô<Ð<øØÐ-Ð.FÔGÐGÐGØ2ˆKØ% kÔ2°5Ô9ˆKˆKà2ˆKØ×:Ò:Ø'ØØ%Ø#(Ø!Ø ØØ $ð ;ñ 	ô 	ˆKð /:ˆK˜Ô$ UÑ+Ø×'Ò'¨Ñ.Ô.Ð.ð 	×#Ò# E¨;¸ÑDÔDÐDØÔÐ5Ô6×=Ò=¸eÑDÔDÐDØ  Ô.×6Ò6°q¸!Ñ<Ô<ˆ
Ø ¨d¬jÔ.GÒ!G× LÒ LÈVÑ TÔ TÐWXÒ XÔYˆ
à�5œ: jÔ&6°qÔ&9ÀÔAQÐZdÔZkÐlÑlÔlÐlÐlr:   r   r~  údict[str, Any] | Nonec                ó  — |p| j         }|du |du z  s
J d¦   «         ‚|                      ||¦  «        }d}d}	|�||dœ}||d         |         |<   d}	||d         |         |<   ||	         |                              |d¦  «         ||d         v}
|d         |         }|d         |         }|
p| j        j        }|rd	nd
}d}|�®||                              |¦  «        p5|d	                              |¦  «        p|d
                              |¦  «        }|�[|                     d¦  «        �F|d                              | j        | j        j        dk    ¬¦  «        }| 	                    dd¦  «         |  
                    ||d|
||dd||¬¦
  «
        }|||         |<   |                      ||d|¬¦  «        }|d                              dd¦  «        }|                     dd¦  «        t          j        d|j        |j        ¬¦  «        fS )av  Add new points or masks to a specific frame for a given object ID.

        This method updates the inference state with new prompts (points or masks) for a specified object and frame
        index. It ensures that the prompts are either points or masks, but not both, and updates the internal state
        accordingly. It also handles the generation of new segmentations based on the provided prompts and the existing
        state.

        Args:
            obj_id (int): The ID of the object to which the prompts are associated.
            points (torch.Tensor, optional): The coordinates of the points of interest.
            labels (torch.Tensor, optional): The labels corresponding to the points.
            masks (torch.Tensor, optional): Binary masks for the object.
            frame_idx (int, optional): The index of the frame to which the prompts are applied.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            pred_masks (torch.Tensor): The flattened predicted masks.
            pred_scores (torch.Tensor): A tensor of ones indicating the number of objects.

        Raises:
            AssertionError: If both `masks` and `points` are provided, or neither is provided.

        Notes:
            - Only one type of prompt (either points or masks) can be added per call.
            - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
            - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
        Nz@'masks' and 'points' prompts are not compatible with each other.Úpoint_inputs_per_obj©Úpoint_coordsÚpoint_labelsÚmask_inputs_per_objr–  Úoutput_dict_per_objÚtemp_output_dict_per_objr‰  r�  r‹   Úcuda)rI   Únon_blockingg      @Àg      @@r   F)
rˆ  r‹  r�  r‘  r’  r“  r”  r•  Úprev_sam_mask_logitsr~  ©Úis_condr•  r~  r   r�   )r~  Ú_obj_id_to_idxrs   rL   Ú!add_all_frames_to_correct_as_condÚgetrH   rI   ÚtypeÚclamp_r�  Ú#_consolidate_temp_output_across_objrˆ   r@   rŸ   r�   )r5   rŠ  rk   rm   rl   r‹  r~  Úobj_idxr’  Úpop_keyr‘  Úobj_output_dictÚobj_temp_output_dictr°  r¡  r®  Úprev_outr¢  Úconsolidated_outr‹   s                       r9   r™  z"SAM2VideoPredictor.add_new_promptsê  s™  € ðL *ÐA¨TÔ-AˆØ˜� &¨D .Ñ1ÐuÐuÐ3uÑuÔuÐ1Ø×%Ò% f¨oÑ>Ô>ˆàˆØ(ˆØÐØ,2ÀFÐKÐKˆLØJVˆOÐ2Ô3°GÔ<¸YÑGØ+ˆGØEJˆÐ-Ô.¨wÔ7¸	ÑBØ˜Ô  Ô)×-Ò-¨i¸Ñ>Ô>Ð>ð
 '¨oÐ>VÔ.WÐWÐØ)Ð*?Ô@ÀÔIˆØ.Ð/IÔJÈ7ÔSÐð %ÐT¨¬
Ô(TˆØ.5ÐSÐ*Ð*Ð;Sˆð  $Ðð Ð#à$ [Ô1×5Ò5°iÑ@Ô@ð LØ"Ð#7Ô8×<Ò<¸YÑGÔGðLà"Ð#;Ô<×@Ò@ÀÑKÔKð ð Ð#¨¯ª°\Ñ(BÔ(BÐ(NØ'/°Ô'=×'@Ò'@Øœ;°T´[Ô5EÈÒ5Oð (Añ (ô (Ð$ð %×+Ò+¨E°4Ñ8Ô8Ð8Ø×6Ò6Ø'ØØØ1Ø%ØØð
 "Ø!5Ø+ð 7ñ 
ô 
ˆð" 8CÐ˜[Ô)¨)Ñ4ð  ×CÒCØØØ!Ø+ð	 Dñ 
ô 
Ðð & lÔ3×;Ò;¸A¸qÑAÔAˆ
Ø×!Ò! ! QÑ'Ô'­¬°A¸ZÔ=MÐV`ÔVgÐ)hÑ)hÔ)hÐhÐhr:   c                ó@  — |p| j         }d|d<   t          |d         ¦  «        }|d         }|d         }|d         }dD �]}|rdnd	}t          ¦   «         }|                     ¦   «         D ]/}	|                     |	|                              ¦   «         ¦  «         Œ0||                              |¦  «         |D ]h}
|                      |
|d|¬
¦  «        }|||         |
<   |                      |
|||¬¦  «         | j        r"| j	        s|dk    r|  
                    |
¦  «         Œi|                     ¦   «         D ]}	|	|                              ¦   «          Œ�Œ|d         D ]}
|d	                              |
d¦  «         Œ|d                              ¦   «         D ])}|d         D ]}
|d	                              |
d¦  «         ŒŒ*|d         D ])}
|
|d         v sJ ‚|d	                              |
¦  «         Œ*|d         |d	         z  }t          ¦   «         }|d                              ¦   «         D ])}|                     |                     ¦   «         ¦  «         Œ*|d                              ¦   «         D ])}|                     |                     ¦   «         ¦  «         Œ*||k    sJ ‚dS )ap  Prepare inference_state and consolidate temporary outputs before tracking.

        This method marks the start of tracking, disallowing the addition of new objects until the session is reset. It
        consolidates temporary outputs from `temp_output_dict_per_obj` and merges them into `output_dict`. Additionally,
        it clears non-conditioning memory around input frames and ensures that the state is consistent with the provided
        inputs.

        Args:
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.
        TÚtracking_has_startedr�  r«  rˆ  rŒ  )FTr‰  r�  r¯  ©r~  r   Nrª  r¥  r©  )r~  ra   ÚsetÚvaluesr*   Úkeysr¶  rŸ  r  r€  rœ  Úclearrs   Údiscard)r5   r~  r�  r«  rˆ  rŒ  r°  r¡  Útemp_frame_indsrº  r‹  r¼  r¹  Úall_consolidated_frame_indsÚinput_frames_indsÚpoint_inputs_per_frameÚmask_inputs_per_frames                    r9   rš  z/SAM2VideoPredictor.propagate_in_video_preflightW  so  € ð *ÐA¨TÔ-Aˆà26ˆÐ.Ñ/Ý˜¨Ô9Ñ:Ô:ˆ
ð $3Ð3MÔ#NÐ Ø% mÔ4ˆð #2Ð2KÔ"LÐØ$ð 	:ñ 	:ˆGà29ÐWÐ.Ð.Ð?WˆKõ "™eœeˆOØ(@×(GÒ(GÑ(IÔ(Ið Qð QÐ$Ø×&Ò&Ð';¸KÔ'H×'MÒ'MÑ'OÔ'OÑPÔPÐPÐPØ# KÔ0×7Ò7¸ÑHÔHÐHà,ð 	Eð 	E�	Ø#'×#KÒ#KØ wÀÐVeð $Lñ $ô $Ð ð 7G�˜KÔ(¨Ñ3Ø×+Ò+¨IÐ7GÈÐfuÐ+ÑvÔvÐvØÔ7ð E¸TÔ=bð EÐfpÐtuÒfuÐfuà×9Ò9¸)ÑDÔDÐDøð )A×(GÒ(GÑ(IÔ(Ið :ð :Ð$Ø$ [Ô1×7Ò7Ñ9Ô9Ð9Ð9ñ:ð
 %Ð%9Ô:ð 	Gð 	GˆIØÐ0Ô1×5Ò5°iÀÑFÔFÐFÐFØ.Ð/DÔE×LÒLÑNÔNð 	Oð 	OˆOØ,Ð-AÔBð Oð O�	ØÐ 8Ô9×=Ò=¸iÈÑNÔNÐNÐNðOà0Ð1EÔFð 	Qð 	QˆIØ Ð,@Ô AÐAÐAÐAÐAØ#Ð$<Ô=×EÒEÀiÑPÔPÐPÐPð
 $Ð$8Ô9Ð<SÐTlÔ<mÑmð 	$õ  ™EœEÐØ&5Ð6LÔ&M×&TÒ&TÑ&VÔ&Vð 	Dð 	DÐ"Ø×$Ò$Ð%;×%@Ò%@Ñ%BÔ%BÑCÔCÐCÐCØ%4Ð5JÔ%K×%RÒ%RÑ%TÔ%Tð 	Cð 	CÐ!Ø×$Ò$Ð%:×%?Ò%?Ñ%AÔ%AÑBÔBÐBÐBØ*Ð.?Ò?Ð?Ð?Ð?Ð?Ð?r:   c                ó¸   — t          | j        ¦  «        dk    rdS | j        €J ‚| j        j        dk    sJ ‚|                      | j        j        ¦  «        | _        dS )a»  Initialize an inference state for the predictor.

        This function sets up the initial state required for performing inference on video data. It includes
        initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
        relevant to the tracking process.

        Args:
            predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
        r   Nrƒ  )ra   r~  r$  r(   Ú_init_stateÚframes)Ú	predictors    r9   r„  zSAM2VideoPredictor.init_state¢  sg   € õ ˆyÔ(Ñ)Ô)¨AÒ-Ð-ØˆFØÔ Ð,Ð,Ð,ØÔ Ô%¨Ò0Ð0Ð0Ð0Ø$-×$9Ò$9¸)Ô:KÔ:RÑ$SÔ$Sˆ	Ô!Ð!Ð!r:   c                ó’   — | i i i t          ¦   «         t          ¦   «         g i i dœi i t          ¦   «         t          ¦   «         dœdg dœ}|S )a†  Initialize an inference state.

        This function sets up the initial state required for performing inference on video data. It includes
        initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
        relevant to the tracking process.

        Args:
            num_frames (int): The number of frames in the video.
        ©r‰  r�  F)Ú
num_framesr¥  r©  Ú	constantsÚobj_id_to_idxr�  Úobj_idsrˆ  rª  r«  rŒ  r¾  r–  )r   rÀ  )rÐ  r~  s     r9   rË  zSAM2VideoPredictor._init_state³  ss   € ð %Ø$&Ø#%Øå(™]œ]Ý(™]œ]Øð ')Ø*,ðð ð
 $&ð )+õ '*¡e¤eÝ*-©%¬%ð(ð (ð
 %*Ø&(ð7
ð 
ˆð: Ðr:   r   c                ó¨   — t          | dd¦  «        }|€| j                             |¦  «        }| j                             ||¬¦  «        \  }}}}|||fS )a  Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.

        Args:
            im (torch.Tensor): The input image tensor.
            batch (int, optional): The batch size for expanding features if there are multiple prompts.

        Returns:
            vis_feats (torch.Tensor): The visual features extracted from the image.
            vis_pos_embed (torch.Tensor): The positional embeddings for the visual features.
            feat_sizes (list[tuple]): A list containing the sizes of the extracted features.

        Notes:
            - If `batch` is greater than 1, the features are expanded to fit the batch size.
            - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
        rn  N©r)   )ÚgetattrrL   rj  rk  )r5   r/   r)   rn  ro  Ú	vis_featsÚvis_pos_embedÚ
feat_sizess           r9   r{   z"SAM2VideoPredictor.get_im_featuresÝ  sb   € õ" ˜t ^°TÑ:Ô:ˆØÐØœ:×3Ò3°BÑ7Ô7ˆLØ26´*×2WÒ2WÐXdÐlqÐ2WÑ2rÔ2rÑ/ˆˆ9�m ZØ˜-¨Ð3Ð3r:   c                ó�  — |p| j         }|d                              |d¦  «        }|�|S |d          }|rwt          |d         ¦  «        }||d         |<   ||d         |<   t          |d         ¦  «        |d<   i |d         |<   i |d         |<   i i dœ|d	         |<   i i dœ|d
         |<   |S t	          d|› d|d         › d�¦  «        ‚)a¸  Map client-side object id to model-side object index.

        Args:
            obj_id (int): The unique identifier of the object provided by the client side.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            (int): The index of the object on the model side.

        Raises:
            RuntimeError: If an attempt is made to add a new object after tracking has started.

        Notes:
            - The method updates or retrieves mappings between object IDs and indices stored in
              `inference_state`.
            - It ensures that new objects can only be added before tracking commences.
            - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
            - Additional data structures are initialized for the new object to store inputs and outputs.
        rÒ  Nr¾  r�  rÓ  r¥  r©  rÏ  rª  r«  zCannot add new object id z1 after tracking starts. All existing object ids: z4. Please call 'reset_state' to restart from scratch.)r~  r³  ra   r  r›  )r5   rŠ  r~  r·  Úallow_new_objects        r9   r±  z!SAM2VideoPredictor._obj_id_to_idxô  s;  € ð* *ÐA¨TÔ-AˆØ! /Ô2×6Ò6°v¸tÑDÔDˆØÐØˆNð  /Ð/EÔFÐFÐØð 	å˜/¨/Ô:Ñ;Ô;ˆGØ7>ˆO˜OÔ,¨VÑ4Ø8>ˆO˜OÔ,¨WÑ5Ý)-¨o¸oÔ.NÑ)OÔ)OˆO˜IÑ&à?AˆOÐ2Ô3°GÑ<Ø>@ˆOÐ1Ô2°7Ñ;à&(Ø*,ð?ð ?ˆOÐ1Ô2°7Ñ;ð
 ')Ø*,ðDð DˆOÐ6Ô7¸Ñ@ð ˆNåðF¨Fð Fð FØ,;¸IÔ,FðFð Fð Fñô ð r:   c                ó~  — |
p| j         }
|                      |
d         |¦  «        \  }}}|�|�J ‚| j                             |||||||||
d         |||	¬¦  «        }|d         }|�8|                     t
          j        | j        | j        j        dk    ¬¦  «        |d<   |  	                    |d         |
¦  «        |d<   |S )	aŸ  Run tracking on a single frame based on current inputs and previous memory.

        Args:
            output_dict (dict): The dictionary containing the output states of the tracking process.
            frame_idx (int): The index of the current frame.
            batch_size (int): The batch size for processing the frame.
            is_init_cond_frame (bool): Indicates if the current frame is an initial conditioning frame.
            point_inputs (dict | None): Input points and their labels.
            mask_inputs (torch.Tensor | None): Input binary masks.
            reverse (bool): Indicates if the tracking should be performed in reverse order.
            run_mem_encoder (bool): Indicates if the memory encoder should be executed.
            prev_sam_mask_logits (torch.Tensor | None): Previous mask logits for the current object.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            (dict): A dictionary containing the output of the tracking step, including updated features and predictions.

        Raises:
            AssertionError: If both `point_inputs` and `mask_inputs` are provided simultaneously.

        Notes:
            - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
            - The method retrieves image features using the `get_im_features` method.
            - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
            - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
        r/   NrÐ  ©r‹  r‘  Úcurrent_vision_featsÚcurrent_vision_pos_embedsrÙ  r’  r“  rˆ  rÐ  Útrack_in_reverser•  r®  Úmaskmem_featuresr¬  ©r�   rI   r­  Úmaskmem_pos_enc)
r~  r{   rL   Ú
track_steprH   r@   rù   rI   r´  Ú_get_maskmem_pos_enc)r5   rˆ  r‹  r�  r‘  r’  r“  r”  r•  r®  r~  rÞ  rß  rÙ  r¢  rá  s                   r9   r�  z.SAM2VideoPredictor._run_single_frame_inference*  s	  € ðP *ÐA¨TÔ-AˆàFJ×FZÒFZØ˜DÔ! :ñG
ô G
ÑCÐÐ7¸ð
 Ð# {Ð':Ð':Ð:Ø”j×+Ò+ØØ1Ø!5Ø&?Ø!Ø%Ø#Ø#Ø& |Ô4Ø$Ø+Ø!5ð ,ñ 
ô 
ˆð 'Ð'9Ô:ÐØÐ'Ø.>×.AÒ.AÝ”m¨D¬KÀdÄkÔFVÐZ`ÒF`ð /Bñ /ô /ˆKÐ*Ñ+ð *.×)BÒ)BÀ;ÐO`ÔCaÐcrÑ)sÔ)sˆÐ%Ñ&ØÐr:   c                óæ   ‡— |p| j         }|d         }|�\d|vr)t          |t          ¦  «        sJ ‚d„ |D ¦   «         }||d<   n|d         }|d         j        d         Š‰dk    rˆfd„|D ¦   «         }|S )a°  Cache and manage the positional encoding for mask memory across frames and objects.

        This method optimizes storage by caching the positional encoding (`maskmem_pos_enc`) for mask memory, which is
        constant across frames and objects, thus reducing the amount of redundant information stored during an inference
        session. It checks if the positional encoding has already been cached; if not, it caches a slice of the provided
        encoding. If the batch size is greater than one, it expands the cached positional encoding to match the current
        batch size.

        Args:
            out_maskmem_pos_enc (list[torch.Tensor] | None): The positional encoding for mask memory. Should be a list
                of tensors or None.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            (list[torch.Tensor]): The positional encoding for mask memory, either cached or expanded.

        Notes:
            - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
            - Only a single object's slice is cached since the encoding is the same across objects.
            - The method checks if the positional encoding has already been cached in the session's constants.
            - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
        rÑ  Nrã  c                óF   — g | ]}|d d…                               ¦   «         ‘ŒS )Nr   )Úclone)r[   r\   s     r9   r^   z;SAM2VideoPredictor._get_maskmem_pos_enc.<locals>.<listcomp>—  s(   € Ð"NÐ"NÐ"N°Q 1 R a R¤5§;¢;¡=¤=Ð"NÐ"NÐ"Nr:   r   r   c                ó@   •— g | ]}|                      ‰d d d ¦  «        ‘ŒS )r<   )r¼   )r[   r\   r�  s     €r9   r^   z;SAM2VideoPredictor._get_maskmem_pos_enc.<locals>.<listcomp>ž  s+   ø€ Ð&aÐ&aÐ&aÈA q§x¢x°
¸BÀÀBÑ'GÔ'GÐ&aÐ&aÐ&ar:   )r~  r?   r  rf   )r5   Úout_maskmem_pos_encr~  Úmodel_constantsrã  r�  s        @r9   rå  z'SAM2VideoPredictor._get_maskmem_pos_encx  s­   ø€ ð0 *ÐA¨TÔ-AˆØ)¨+Ô6ˆàÐ*Ø ¨Ð7Ð7Ý!Ð"5µtÑ<Ô<Ð<Ð<Ð<à"NÐ"NÐ:MÐ"NÑ"NÔ"N�Ø5D�Ð 1Ñ2Ð2à"1Ð2CÔ"D�à,¨QÔ/Ô5°aÔ8ˆJØ˜AŠ~ˆ~Ø&aÐ&aÐ&aÐ&aÐQ`Ð&aÑ&aÔ&aÐ#Ø"Ð"r:   Fc           
     óè  — |p| j         }t          |d         ¦  «        }|rdnd}ddt          j        |dg| j        d         ¢R d| j        | j        ¬¦  «        t          j        || j        j        fd| j        | j        ¬¦  «        t          j        |dfd	| j        | j        ¬¦  «        d
œ}t          |¦  «        D ]Ã}|d         |         }	|d         |         }
|	|          
                    |¦  «        p5|
d          
                    |¦  «        p|
d          
                    |¦  «        }|€&|r#|                      |¦  «        |d         ||dz   …<   Œ—|d         |d         ||dz   …<   |d         |d         ||dz   …<   ŒÄ|rrt          j        |d         | j        dd¬¦  «        }| j        j        r| j                             |¦  «        }|                      ||d|d         |¬¦  «        \  |d<   |d<   |S )aá  Consolidate per-object temporary outputs into a single output for all objects.

        This method combines the temporary outputs for each object on a given frame into a unified
        output. It fills in any missing objects either from the main output dictionary or leaves
        placeholders if they do not exist in the main output. Optionally, it can re-run the memory encoder after
        applying non-overlapping constraints to the object scores.

        Args:
            frame_idx (int): The index of the frame for which to consolidate outputs.
            is_cond (bool, optional): Indicates if the frame is considered a conditioning frame.
            run_mem_encoder (bool, optional): Specifies whether to run the memory encoder after consolidating the
                outputs.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            (dict): A consolidated output dictionary containing the combined results for all objects.

        Notes:
            - The method initializes the consolidated output with placeholder values for missing objects.
            - It searches for outputs in both the temporary and main output dictionaries.
            - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
            - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
        r�  r‰  r�  Nr   r   ç      �À©ÚsizeÚ
fill_valuer�   rI   ç      $@©rá  rã  r‹   Úobj_ptrÚobject_score_logitsr«  rª  ró  r‹   r°   F©rï  r(   r±   Trô  )r�  Úhigh_res_masksÚis_mask_from_ptsrô  r~  rá  rã  )r~  ra   r@   Úfullra  r�   rI   rL   Ú
hidden_dimr  r³  Ú_get_empty_mask_ptrrµ   r¶   rb   Únon_overlap_masks_for_mem_encr  Ú_run_memory_encoder)r5   r‹  r°  r•  r~  r�  r¡  r¼  r·  rº  r¹  Úoutrö  s                r9   r¶  z6SAM2VideoPredictor._consolidate_temp_output_across_obj¡  s—  € ð> *ÐA¨TÔ-AˆÝ˜¨Ô9Ñ:Ô:ˆ
Ø.5ÐSÐ*Ð*Ð;Sˆð !%Ø#Ýœ*à  !Ð= dÔ&9¸!Ô&<Ð=Ð=Ø"ØÔ&Ø”{ðñ ô õ ”zØ  $¤*Ô"7Ð8Ø"ØÔ&Ø”{ð	ñ ô õ $)¤:Ø  !�_ð  ØÔ&Ø”{ð$ñ $ô $ð!
ð 
Ðõ2 ˜ZÑ(Ô(ð 	Pð 	PˆGØ#2Ð3MÔ#NÈwÔ#WÐ Ø-Ð.CÔDÀWÔMˆOà$ [Ô1×5Ò5°iÑ@Ô@ð Lð
 #Ð#7Ô8×<Ò<¸YÑGÔGðLð #Ð#;Ô<×@Ò@ÀÑKÔKð ð ˆ{ð #ð màIM×IaÒIaÐbkÑIlÔIlÐ$ YÔ/°¸'ÀA¹+Ð0EÑFØàDGÈÔDUÐ˜\Ô*¨7°W¸q±[Ð+@ÑAØADÀYÄÐ˜YÔ'¨°'¸A±+Ð(=Ñ>Ð>ð ð 	Ýœ]Ø  Ô.Ø”ZØØ#ð	ñ ô ˆNð ŒzÔ7ð _Ø!%¤×!NÒ!NÈ~Ñ!^Ô!^�ØX\×XpÒXpØ%Ø-Ø!%Ø$4Ð5JÔ$KØ /ð Yqñ Yô YÑUÐÐ/Ñ0Ð2BÐCTÑ2Uð  Ðr:   c                ó  — |p| j         }|                      |d         ¦  «        \  }}}| j                             |d|||dt	          j        ddg| j        ¢R | j        | j        ¬¦  «        i |d         ddd¬¦  «        }|d	         S )
aÚ  Get a dummy object pointer based on an empty mask on the current frame.

        Args:
            frame_idx (int): The index of the current frame for which to generate the dummy object pointer.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
        r/   TNr   r�   rÐ  FrÝ  ró  )	r~  r{   rL   rä  r@   r  rb   r�   rI   )r5   r‹  r~  rÞ  rß  rÙ  r¢  s          r9   rú  z&SAM2VideoPredictor._get_empty_mask_ptr  s¯   € ð *ÐA¨TÔ-AˆàFJ×FZÒFZÐ[jÐkoÔ[pÑFqÔFqÑCÐÐ7¸ð ”j×+Ò+ØØ#Ø!5Ø&?Ø!Øåœ Q¨Ð$7¨D¬JÐ$7Ð$7¸tÔ?OÐX\ÔXcÐdÑdÔdØØ& |Ô4Ø"Ø!Ø!%ð ,ñ 
ô 
ˆð ˜9Ô%Ð%r:   c                ó2  — |p| j         }|                      |d         |¦  «        \  }}}| j                             |||||¬¦  «        \  }	}
|                      |
|¦  «        }
|	                     t          j        | j        | j        j	        dk    ¬¦  «        |
fS )a‰  Run the memory encoder on masks.

        This is usually after applying non-overlapping constraints to object scores. Since their scores changed, their
        memory also needs to be computed again with the memory encoder.

        Args:
            batch_size (int): The batch size for processing the frame.
            high_res_masks (torch.Tensor): High-resolution masks for which to compute the memory.
            object_score_logits (torch.Tensor): Logits representing the object scores.
            is_mask_from_pts (bool): Indicates if the mask is derived from point interactions.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.

        Returns:
            maskmem_features (torch.Tensor): The encoded mask features.
            maskmem_pos_enc (torch.Tensor): The positional encoding.
        r/   )rÞ  rÙ  Úpred_masks_high_resr÷  rô  r¬  râ  )
r~  r{   rL   Ú_encode_new_memoryrå  rH   r@   rù   rI   r´  )r5   r�  rö  rô  r÷  r~  rÞ  ro  rÙ  rá  rã  s              r9   rü  z&SAM2VideoPredictor._run_memory_encoder1  s¹   € ð2 *ÐA¨TÔ-Aˆà.2×.BÒ.BÀ?ÐSWÔCXÐZdÑ.eÔ.eÑ+Ð˜a Ø,0¬J×,IÒ,IØ!5Ø!Ø .Ø-Ø 3ð -Jñ -
ô -
Ñ)Ð˜/ð ×3Ò3°OÀ_ÑUÔUˆØ×"Ò"Ý”-¨¬À$Ä+ÔBRÐV\ÒB\ð #ñ 
ô 
àðð 	r:   c                ó¢  ‡
— |p| j         }|d         }|�t          |t          j        ¦  «        sJ ‚|d         }|�t          |t          ¦  «        sJ ‚|d                              ¦   «         D ]b\  }}t          ||dz   ¦  «        Š
dd|d         ‰
         |d         ‰
         dœ}	|�|‰
         |	d<   |�ˆ
fd	„|D ¦   «         |	d<   |	||         |<   ŒcdS )
aI  Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.

        The resulting slices share the same tensor storage.

        Args:
            frame_idx (int): The index of the current frame.
            current_out (dict): The current output dictionary containing multi-object outputs.
            storage_key (str): The key used to store the output in the per-object output dictionary.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.
        rá  Nrã  rª  r   r‹   ró  )rá  rã  r‹   ró  c                ó    •— g | ]
}|‰         ‘ŒS rY   rY   )r[   r\   Ú	obj_slices     €r9   r^   z=SAM2VideoPredictor._add_output_per_object.<locals>.<listcomp>{  s   ø€ Ð-TÐ-TÐ-T¸q¨a°	¬lÐ-TÐ-TÐ-Tr:   )r~  r?   r@   rA   r  ÚitemsÚslice)r5   r‹  r¢  r¡  r~  rá  rã  r·  r¹  Úobj_outr  s             @r9   rŸ  z)SAM2VideoPredictor._add_output_per_object[  s   ø€ ð *ÐA¨TÔ-AˆØ&Ð'9Ô:ÐØÐ'­:Ð6FÍÌÑ+UÔ+UÐ'Ð'ÐUà%Ð&7Ô8ˆØÐ&­*°_ÅdÑ*KÔ*KÐ&Ð&ÐKà(7Ð8MÔ(N×(TÒ(TÑ(VÔ(Vð 	>ð 	>Ñ$ˆG�_Ý˜g w°¡{Ñ3Ô3ˆIà$(Ø#'Ø)¨,Ô7¸	ÔBØ& yÔ1°)Ô<ð	ð ˆGð  Ð+Ø.>¸yÔ.I�Ð*Ñ+ØÐ*Ø-TÐ-TÐ-TÐ-TÀOÐ-TÑ-TÔ-T�Ð)Ñ*Ø6=ˆO˜KÔ(¨Ñ3Ð3ð	>ð 	>r:   c                óZ  — |p| j         }| j        j        }||| j        j        z  z
  }||| j        j        z  z   }t	          ||dz   ¦  «        D ]]}|d         d                              |d¦  «         |d                              ¦   «         D ]}|d                              |d¦  «         ŒŒ^dS )a®  Remove the non-conditioning memory around the input frame.

        When users provide correction clicks, the surrounding frames' non-conditioning memories can still contain
        outdated object appearance information and could confuse the model. This method clears those non-conditioning
        memories surrounding the interacted frame to avoid giving the model both old and new information about the
        object.

        Args:
            frame_idx (int): The index of the current frame where user interaction occurred.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.
        r   rˆ  r�  Nrª  )r~  rL   Úmemory_temporal_stride_for_evalÚnum_maskmemr  rs   rÁ  )r5   r‹  r~  r§   Úframe_idx_beginÚframe_idx_endÚtr¹  s           r9   rœ  z3SAM2VideoPredictor._clear_non_cond_mem_around_input~  sØ   € ð *ÐA¨TÔ-AˆØŒJÔ6ˆØ# a¨$¬*Ô*@Ñ&@Ñ@ˆØ! A¨¬
Ô(>Ñ$>Ñ>ˆÝ�¨¸Ñ(9Ñ:Ô:ð 	Gð 	GˆAØ˜MÔ*Ð+CÔD×HÒHÈÈDÑQÔQÐQØ#2Ð3HÔ#I×#PÒ#PÑ#RÔ#Rð Gð G�ØÐ 8Ô9×=Ò=¸aÀÑFÔFÐFÐFðGð	Gð 	Gr:   c                óº  ‡ ‡‡‡‡‡— ‰d                               |d¦  «        }|€&|s‰d         S t          d|› d‰d         › d�¦  «        ‚t          ‰d         ¦  «        dk    r‰                      ‰¦  «         ‰d         S t	          ¦   «         }|                     ‰d         |         ¦  «         |                     ‰d	         |         ¦  «         |D ]}‰                      ‰||¦  «         Œ‰d         Št          t          t          ‰¦  «        ¦  «        ¦  «        Š‰ 	                    ¦   «         Š‰ 
                    |¦  «         ˆfd
„‰D ¦   «         }t          t          t          |¦  «        ¦  «        ¦  «        }t          t          ‰|¦  «        ¦  «        Št          t          ||¦  «        ¦  «        ‰d<   t          t          ||¦  «        ¦  «        ‰d<   |‰d<   ˆˆfd„}	 |	‰d         ¦  «          |	‰d	         ¦  «          |	‰d         ¦  «          |	‰d         ¦  «         ˆˆˆ fd„}
 |
‰d         d¦  «          |
‰d         d¦  «         ‰d         S )z§Remove an object id from the tracking state. If strict is True, we check whether the object id actually
        exists and raise an error if it doesn't exist.
        rÒ  NrÓ  zCannot remove object id z/ as it doesn't exist. All existing object ids: r“   r   r¥  r©  c                ó    •— g | ]
}‰|         ‘ŒS rY   rY   )r[   Úold_idxÚold_obj_idss     €r9   r^   z4SAM2VideoPredictor.remove_object.<locals>.<listcomp>¹  s   ø€ ÐOÐOÐO°�{ 7Ô+ÐOÐOÐOr:   r�  c                ó¬   •— g }‰D ]8}|                       |¦  «        }|‰v r|                     ‰|         |f¦  «         Œ9|                      |¦  «         d S ro   )rs   r¸   r*   )Ú	containerÚnew_kvsÚkÚvÚold_idx_to_new_idxÚold_obj_indss       €€r9   Ú	_map_keysz3SAM2VideoPredictor.remove_object.<locals>._map_keysÄ  sl   ø€ ØˆGØ!ð ?ð ?�Ø—M’M !Ñ$Ô$�ØÐ*Ð*Ð*Ø—N’NÐ$6°qÔ$9¸1Ð#=Ñ>Ô>Ð>øØ×Ò˜WÑ%Ô%Ð%Ð%Ð%r:   rª  r«  c                ón  •— | |                               ¦   «         D ]˜\  }}|d         ‰         |d<   ˆfd„|d         D ¦   «         |d<   ‰                     |d         ‰¦  «        |d<   |d         ‰         |d<   |d         ‰         |d<   |d         ‰         |d<   ‰                     |||‰¬¦  «         Œ™d S )Nrá  c                ó    •— g | ]
}|‰         ‘ŒS rY   rY   )r[   r\   Úremain_old_obj_indss     €r9   r^   zJSAM2VideoPredictor.remove_object.<locals>._slice_state.<locals>.<listcomp>Õ  s   ø€ Ð)aÐ)aÐ)aÀQ¨!Ð,?Ô*@Ð)aÐ)aÐ)ar:   rã  r‹   ró  rô  r¿  )r  rå  rŸ  )rˆ  r¡  r‹  rý  r~  r  r5   s       €€€r9   Ú_slice_statez6SAM2VideoPredictor.remove_object.<locals>._slice_stateÒ  só   ø€ Ø"-¨kÔ":×"@Ò"@Ñ"BÔ"Bð 	jð 	j‘�	˜3Ø*-Ð.@Ô*AÐBUÔ*V�Ð&Ñ'Ø)aÐ)aÐ)aÐ)aÈ#ÐN_ÔJ`Ð)aÑ)aÔ)a�Ð%Ñ&à)-×)BÒ)BÀ3ÐGXÔCYÐ[jÑ)kÔ)k�Ð%Ñ&Ø$'¨Ô$5Ð6IÔ$J��LÑ!Ø!$ Y¤Ð0CÔ!D��I‘Ø-0Ð1FÔ-GÐH[Ô-\�Ð)Ñ*à×+Ò+¨I°s¸KÐYhÐ+ÑiÔiÐiÐið	jð 	jr:   rˆ  r‰  r�  )r³  r›  ra   Úclear_all_points_in_videorÀ  r*   Úclear_all_points_in_framer  r  ÚcopyÚremover  r³   )r5   r~  rŠ  ÚstrictÚold_obj_idx_to_rmÚobj_input_frames_indsr‹  Únew_obj_idsÚnew_obj_indsr  r  r  r  r  r  s   ``         @@@@r9   Úremove_objectz SAM2VideoPredictor.remove_object”  sð  øøøøøø€ ð
 ,¨OÔ<×@Ò@ÀÈÑNÔNÐàÐ$Øð 2Ø& yÔ1Ð1ÝðJ¨6ð Jð JØ,;¸IÔ,FðJð Jð Jñô ð õ ˆ˜Ô/Ñ0Ô0°AÒ5Ð5Ø×*Ò*¨?Ñ;Ô;Ð;Ø" 9Ô-Ð-õ !$¡¤ÐØ×$Ò$ _Ð5KÔ%LÐM^Ô%_Ñ`Ô`Ð`Ø×$Ò$ _Ð5JÔ%KÐL]Ô%^Ñ_Ô_Ð_Ø.ð 	Oð 	OˆIØ×*Ò*¨?¸IÀvÑNÔNÐNÐNð & iÔ0ˆÝ�E¥# kÑ"2Ô"2Ñ3Ô3Ñ4Ô4ˆØ*×/Ò/Ñ1Ô1ÐØ×"Ò"Ð#4Ñ5Ô5Ð5ØOÐOÐOÐOÐ;NÐOÑOÔOˆÝ�E¥# kÑ"2Ô"2Ñ3Ô3Ñ4Ô4ˆå!¥#Ð&9¸<Ñ"HÔ"HÑIÔIÐÝ+/µ°KÀÑ0NÔ0NÑ+OÔ+Oˆ˜Ñ(Ý+/µ°LÀ+Ñ0NÔ0NÑ+OÔ+Oˆ˜Ñ(Ø%0ˆ˜	Ñ"ð
	&ð 	&ð 	&ð 	&ð 	&ð 	&ð 	ˆ	�/Ð"8Ô9Ñ:Ô:Ð:Øˆ	�/Ð"7Ô8Ñ9Ô9Ð9Øˆ	�/Ð"7Ô8Ñ9Ô9Ð9Øˆ	�/Ð"<Ô=Ñ>Ô>Ð>ð
	jð 
	jð 
	jð 
	jð 
	jð 
	jð 
	jð 	ˆ�_ ]Ô3Ð5IÑJÔJÐJØˆ�_ ]Ô3Ð5MÑNÔNÐNà˜yÔ)Ð)r:   c                ó  — |                       ||¦  «        }|d         |                              |d¦  «         |d         |                              |d¦  «         |d         }||         d                              |d¦  «         ||         d                              |d¦  «         t          |d         ¦  «        }d}t          |¦  «        D ]*}||d         |         v rd	} n||d         |         v rd	} nŒ+|�s|d
         }	|d         }
|
d                              |¦  «         |
d                              |¦  «         |	d                              |d¦  «        }|�'||	d         |<   |d                              |d¦  «         t          |¦  «        D ]9}|d         |         }|d                              |d¦  «        }|�||d         |<   Œ:t          |	d         ¦  «        dk    r|                      |¦  «         dS dS dS )zGRemove all input points or mask in a specific frame for a given object.r¥  Nr©  r«  r‰  r�  r�  FTrˆ  rŒ  r–  rª  r   )r±  rs   ra   r  rÄ  Ú_reset_tracking_results)r5   r~  r‹  rŠ  r·  r«  r�  Úframe_has_inputÚobj_idx2rˆ  rŒ  rý  r¹  r  s                 r9   r  z,SAM2VideoPredictor.clear_all_points_in_frameã  sh  € ð ×%Ò% f¨oÑ>Ô>ˆð 	Ð.Ô/°Ô8×<Ò<¸YÈÑMÔMÐMØÐ-Ô.¨wÔ7×;Ò;¸IÀtÑLÔLÐLà#2Ð3MÔ#NÐ Ø  Ô)Ð*>Ô?×CÒCÀIÈtÑTÔTÐTØ  Ô)Ð*BÔC×GÒGÈ	ÐSWÑXÔXÐXõ ˜¨Ô9Ñ:Ô:ˆ
ØˆÝ˜jÑ)Ô)ð 	ð 	ˆHØ˜OÐ,BÔCÀHÔMÐMÐMØ"&�Ø�Ø˜OÐ,AÔBÀ8ÔLÐLÐLØ"&�Ø�ð Mð ñ 	>Ø)¨-Ô8ˆKØ&5Ð6OÔ&PÐ#Ø#Ð$8Ô9×AÒAÀ)ÑLÔLÐLØ#Ð$<Ô=×EÒEÀiÑPÔPÐPàÐ2Ô3×7Ò7¸	À4ÑHÔHˆCØˆð DG�Ð4Ô5°iÑ@ØÐ 8Ô9×=Ò=¸iÈÑNÔNÐNå! *Ñ-Ô-ð Sð S�Ø"1Ð2GÔ"HÈÔ"R�Ø)Ð*>Ô?×CÒCÀIÈtÑTÔT�ØÐ&ØKR�OÐ$<Ô=¸iÑHøõ �;Ð3Ô4Ñ5Ô5¸Ò:Ð:Ø×,Ò,¨_Ñ=Ô=Ð=Ð=Ð=ð+	>ð 	>ð( ;Ð:r:   c                óœ  — |                       |¦  «         |d                              ¦   «          |d                              ¦   «          |d                              ¦   «          |d                              ¦   «          |d                              ¦   «          |d                              ¦   «          |d                              ¦   «          dS )	zCRemove all input points or mask in all frames throughout the video.rÒ  r�  rÓ  r¥  r©  rª  r«  N)r)  rÃ  )r5   r~  s     r9   r  z,SAM2VideoPredictor.clear_all_points_in_video  sÃ   € ð 	×$Ò$ _Ñ5Ô5Ð5à˜Ô(×.Ò.Ñ0Ô0Ð0Ø˜Ô(×.Ò.Ñ0Ô0Ð0Ø˜	Ô"×(Ò(Ñ*Ô*Ð*ØÐ.Ô/×5Ò5Ñ7Ô7Ð7ØÐ-Ô.×4Ò4Ñ6Ô6Ð6ØÐ-Ô.×4Ò4Ñ6Ô6Ð6ØÐ2Ô3×9Ò9Ñ;Ô;Ð;Ð;Ð;r:   c                óV  — | d                               ¦   «         D ]}|                     ¦   «          Œ| d                               ¦   «         D ]}|                     ¦   «          Œ| d                               ¦   «         D ]6}|d                              ¦   «          |d                              ¦   «          Œ7| d                               ¦   «         D ]6}|d                              ¦   «          |d                              ¦   «          Œ7| d         d                              ¦   «          | d         d                              ¦   «          | d         d                              ¦   «          | d         d                              ¦   «          d	| d
<   | d                              ¦   «          d| d<   dS )z8Reset all tracking inputs and results across the videos.r¥  r©  rª  r‰  r�  r«  rˆ  rŒ  Fr¾  r–  NÚfirst_ann_frame_idx)rÁ  rÃ  )r~  r  s     r9   r)  z*SAM2VideoPredictor._reset_tracking_results!  s¶  € ð !Ð!7Ô8×?Ò?ÑAÔAð 	ð 	ˆAØ�GŠG‰IŒIˆIˆIØ Ð!6Ô7×>Ò>Ñ@Ô@ð 	ð 	ˆAØ�GŠG‰IŒIˆIˆIØ Ð!6Ô7×>Ò>Ñ@Ô@ð 	0ð 	0ˆAØÐ"Ô#×)Ò)Ñ+Ô+Ð+ØÐ&Ô'×-Ò-Ñ/Ô/Ð/Ð/Ø Ð!;Ô<×CÒCÑEÔEð 	0ð 	0ˆAØÐ"Ô#×)Ò)Ñ+Ô+Ð+ØÐ&Ô'×-Ò-Ñ/Ô/Ð/Ð/Ø˜Ô&Ð';Ô<×BÒBÑDÔDÐDØ˜Ô&Ð'?Ô@×FÒFÑHÔHÐHØÐ1Ô2Ð3GÔH×NÒNÑPÔPÐPØÐ1Ô2Ð3KÔL×RÒRÑTÔTÐTØ27ˆÐ.Ñ/ØÐ0Ô1×7Ò7Ñ9Ô9Ð9Ø15ˆÐ-Ñ.Ð.Ð.r:   c                ó–  ‡— | j         sdS |p| j        }|| j        j        | j        j        z  z
  Š|d         }ˆfd„|d         D ¦   «         D ]}|d                              |d¦  «         Œ|                     di ¦  «                             ¦   «         D ]5}ˆfd„|d         D ¦   «         D ]}|d                              |d¦  «         ŒŒ6dS )z8Prune old non-conditioning frames to bound memory usage.Nrˆ  c                ó    •— g | ]
}|‰k     ¯|‘ŒS rY   rY   ©r[   r  Ú	min_frames     €r9   r^   z=SAM2VideoPredictor._prune_non_cond_memory.<locals>.<listcomp>A  s   ø€ ÐTÐTÐT˜ÀaÈ)ÂmÀm�!ÀmÀmÀmr:   r�  rª  c                ó    •— g | ]
}|‰k     ¯|‘ŒS rY   rY   r1  s     €r9   r^   z=SAM2VideoPredictor._prune_non_cond_memory.<locals>.<listcomp>F  s   ø€ Ð\Ð\Ð\˜AÈaÐR[ÊmÈm�aÈmÈmÈmr:   )r�  r~  rL   r
  r	  rs   r³  rÁ  )r5   r‹  r~  rˆ  Úfr¹  r2  s         @r9   rž  z)SAM2VideoPredictor._prune_non_cond_memory6  s  ø€ àÔ&ð 	ØˆFØ)ÐA¨TÔ-Aˆð  ¤
Ô 6¸¼Ô9cÑ cÑcˆ	Ø% mÔ4ˆð UÐTÐTÐT˜[Ð)AÔBÐTÑTÔTð 	?ð 	?ˆAØÐ0Ô1×5Ò5°a¸Ñ>Ô>Ð>Ð>ð  /×2Ò2Ð3HÈ"ÑMÔM×TÒTÑVÔVð 	Gð 	GˆOØ\Ð\Ð\Ð\ Ð1IÔ!JÐ\Ñ\Ô\ð Gð G�ØÐ 8Ô9×=Ò=¸aÀÑFÔFÐFÐFðGð	Gð 	Gr:   rD  rE  )NNNr   N)r~  r£  ro   ©r   ©NN)FFN©F)rH  rI  rJ  rK  r   r,   r#  rñ   ry   r   r™  rš  rM  r„  rË  r{   r±  r�  rå  r¶  rú  rü  rŸ  rœ  r'  r  r  r)  rž  rN  rO  s   @r9   r|  r|  _  s'  ø€ € € € € ðð ðB '°$ÐRVð 'ð 'ð 'ð 'ð 'ð 'ð 'ð$"ð "ð "ð "ð "ðð ð ð ð ðEmð Emð Emð EmðN ÐÑÔð ØØØØ15ðjið jið jið jiñ ÔðjiðX ÐÑÔðH@ð H@ð H@ð H@ñ ÔðH@ðT ðTð Tñ „\ðTð  ð'ð 'ñ „\ð'ðR4ð 4ð 4ð 4ð.4ð 4ð 4ð 4ð 4ð@ "Ø15ðLð Lð Lð Lð Lð\'#ð '#ð '#ð '#ð '#ðX ØØ15ðm ð m ð m ð m ð m ð^&ð &ð &ð &ð &ðN 26ð(ð (ð (ð (ð (ðV ]að!>ð !>ð !>ð !>ð !>ðFGð Gð Gð Gð Gð, ÐÑÔðL*ð L*ð L*ñ ÔðL*ð\ ÐÑÔð.>ð .>ñ Ôð.>ð` ÐÑÔð
<ð 
<ñ Ôð
<ð ð6ð 6ñ „\ð6ð(Gð Gð Gð Gð Gð Gð Gð Gr:   r|  c                  óÈ   ‡ — e Zd ZdZedddfd.ˆ fd„Z e¦   «         	 	 	 	 	 	 d/d0d„¦   «         Zd1d„Z e¦   «         	 	 	 	 d2d3d!„¦   «         Z	d4d%„Z
d5d&„Zd6d(„Z	 	 	 	 d2d7d-„Zˆ xZS )8ÚSAM2DynamicInteractivePredictora²  SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a
    sequence of images.

    Attributes:
        memory_bank (list): OrderedDict: Stores the states of each image with prompts.
        obj_idx_set (set): A set to keep track of the object indices that have been added.
        obj_id_to_idx (OrderedDict): Maps object IDs to their corresponding indices.
        obj_idx_to_id (OrderedDict): Maps object indices to their corresponding IDs.

    Methods:
        get_model: Retrieves and configures the model with binarization enabled.
        inference: Performs inference on a single image with optional prompts and object IDs.
        postprocess: Post-processes the predictions to apply non-overlapping constraints if required.
        update_memory: Append the imgState to the memory_bank and update the memory for the model.
        track_step: Tracking step for the current image state to predict masks.
        get_maskmem_enc: Get memory and positional encoding from the memory bank.

    Examples:
            >>> predictor = SAM2DynamicInteractivePredictor(cfg=DEFAULT_CFG)
            >>> predictor(source=support_img1, bboxes=bboxes1, obj_ids=labels1, update_memory=True)
            >>> results1 = predictor(source=query_img1)
            >>> predictor(source=support_img2, bboxes=bboxes2, obj_ids=labels2, update_memory=True)
            >>> results2 = predictor(source=query_img2)
    Nr=   r6   r   r7   r£  Úmax_obj_numr[  r"   r#   ÚreturnÚNonec                ó  •— t          ¦   «                              |||¦  «         d| _        g | _        t	          ¦   «         | _        t          t          t          |¦  «        ¦  «        ¦  «        x| _	        | _
        || _        dS )a’  Initialize the predictor with configuration and optional overrides.

        This constructor initializes the SAM2DynamicInteractivePredictor with a given configuration, applies any
        specified overrides

        Args:
            cfg (Any): Configuration dictionary containing default settings.
            overrides (dict[str, Any] | None): Dictionary of values to override default configuration.
            max_obj_num (int): Maximum number of objects to track. Default is 3. This is set to keep fixed feature size
                for the model.
            _callbacks (dict | None): Dictionary of callback functions to customize behavior.
        TN)r+   r,   r3   Úmemory_bankrÀ  Úobj_idx_setr   r  r  rÒ  r�  Ú_max_obj_num)r5   r6   r7   r:  r"   r8   s        €r9   r,   z(SAM2DynamicInteractivePredictor.__init__d  sw   ø€ õ& 	‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ø!%ˆÔð ˆÔõ ™5œ5ˆÔÝ2=½iÍÈkÑHZÔHZÑ>[Ô>[Ñ2\Ô2\Ð\ˆÔ˜TÔ/Ø'ˆÔÐÐr:   Fr/   útorch.Tensor | np.ndarrayrj   úlist[list[float]] | Nonerl   ú torch.Tensor | np.ndarray | Nonerk   rm   úlist[int] | NonerÓ  Úupdate_memoryr<  ú!tuple[torch.Tensor, torch.Tensor]c                óü  — |                       |¦  «         |                      | j        | j        ||||¬¦  «        \  }}}|�rt	          |t
          ¦  «        r|g}|€
J d¦   «         ‚|€|€
J d¦   «         ‚|€ft          j        t          |¦  «        ddf| j	        | j
        ¬¦  «        }t          j        t          |¦  «        dft          j        | j
        ¬¦  «        }|�*t          |¦  «        t          |¦  «        k    s
J d¦   «         ‚t          |¦  «        t          |¦  «        k    s
J d	¦   «         ‚|                      ||||¦  «         |                      ¦   «         }|d
         |d         }
}	t          | j        ¦  «        dk    rt          d¦  «        ‚t!          | j        ¦  «        }|	|         |
|         }
}	t          j        |
dz  d¬¦  «        }
|	                     dd¦  «        |
                     dd¦  «        fS )ao  Perform inference on a single image with optional bounding boxes, masks, points and object IDs. It has two
        modes: one is to run inference on a single image without updating the memory, and the other is to update
        the memory with the provided prompts and object IDs. When update_memory is True, it will update the
        memory with the provided prompts and obj_ids. When update_memory is False, it will only run inference on
        the provided image without updating the memory.

        Args:
            im (torch.Tensor | np.ndarray): The input image tensor or numpy array.
            bboxes (list[list[float]] | None): Optional list of bounding boxes to update the memory.
            masks (torch.Tensor | np.ndarray | None): Optional masks to update the memory.
            points (list[list[float]] | None): Optional list of points to update the memory, each point is [x, y].
            labels (list[int] | None): Optional list of labels for point prompts (>0 for positive, 0 for negative).
            obj_ids (list[int] | None): Optional list of object IDs corresponding to the prompts.
            update_memory (bool): Flag to indicate whether to update the memory with new objects.

        Returns:
            res_masks (torch.Tensor): The output masks in shape (C, H, W)
            object_score_logits (torch.Tensor): Quality scores for each mask
        )r¦   rh   rk   rj   rm   rl   Nz3obj_ids must be provided when update_memory is TruezDbboxes, masks, or points must be provided when update_memory is Truer   r>   r�   z,masks and obj_ids must have the same length.z-points and obj_ids must have the same length.r‹   rô  zMNo objects have been added to the state. Please add objects before inference.r©   )r›   r   )r{   r|   rb   rh   r?   r[  r@   r  ra   r�   rI   r    rE  rä  r?  r›  r  rµ  rˆ   )r5   r/   rj   rl   rk   rm   rÓ  rE  r¢  r‹   rŒ   râ   s               r9   ry   z)SAM2DynamicInteractivePredictor.inferenceƒ  s  € ð< 	×Ò˜RÑ Ô Ð Ø $× 5Ò 5Ø”jØ”nØØØØð !6ñ !
ô !
Ñˆ�˜ð ñ 	?Ý˜'¥3Ñ'Ô'ð $Ø"˜)�ØÐ&Ð&Ð(]Ñ&Ô&Ð&ØÐ$¨Ð(:Ð(:ØVñ );Ô(:Ð:ð ˆ~Ýœ¥c¨'¡l¤l°A°qÐ%9ÀÔAQÐZ^ÔZeÐfÑfÔf�Ýœ¥c¨'¡l¤l°AÐ%6½e¼kÐRVÔR]Ð^Ñ^Ô^�ØÐ Ý˜5‘z”z¥S¨¡\¤\Ò1Ð1Ð1Ð3aÑ1Ô1Ð1Ý�v‘;”;¥# g¡,¤,Ò.Ð.Ð.Ð0_Ñ.Ô.Ð.Ø×Ò˜w¨°¸Ñ>Ô>Ð>à—o’oÑ'Ô'ˆØ"-¨lÔ";¸[ÐI^Ô=_�Kˆ
åˆtÔÑ Ô  AÒ%Ð%ÝÐnÑoÔoÐoÝ�4Ô#Ñ$Ô$ˆØ",¨S¤/°;¸sÔ3C�Kˆ
õ ”l ;°Ñ#3¸Ð;Ñ;Ô;ˆØ×!Ò! ! QÑ'Ô'¨×)<Ò)<¸QÀÑ)BÔ)BÐBÐBr:   r  c                óÚ   — t                                | || j        ¬¦  «        \  }}}d„ t          |dd…         |dd…         ¦  «        D ¦   «         | _        || _        || _        || _        dS )z½Initialize the image state by processing the input image and extracting features.

        Args:
            img (torch.Tensor | np.ndarray): The input image tensor or numpy array.
        rÕ  c                óv   — g | ]6\  }} |                      d dd¦  «        j        g |j        d d…         ¢|¢R Ž ‘Œ7S )r   r>   r   N)rd  rô   rf   re  s      r9   r^   zCSAM2DynamicInteractivePredictor.get_im_features.<locals>.<listcomp>Í  s^   € ð "
ð "
ð "
á��ið 'ˆD�LŠL˜˜A˜qÑ!Ô!Ô&ÐC¨¬
°1°2°2¬ÐC¸ÐCÐCÐCð"
ð "
ð "
r:   Nr<   )r|  r{   r@  r³   rw  rp  Úvision_pos_embedsrÙ  )r5   r  r×  rØ  rÙ  s        r9   r{   z/SAM2DynamicInteractivePredictor.get_im_featuresÆ  s„   € õ 0B×/QÒ/QÐRVÐX[ÐcgÔctÐ/QÑ/uÔ/uÑ,ˆ	�= *ð"
ð "
å#& y°°"°¤~°zÀ#À2À#´Ñ#GÔ#Gð"
ñ "
ô "
ˆÔð
 &ˆÔØ!.ˆÔØ$ˆŒˆˆr:   útorch.Tensor | Nonec           
     ó|  — ddt          j        | j        d| j        d         dz  | j        d         dz  fd| j        | j        ¬¦  «        t          j        | j        | j        j        fd| j        | j        ¬¦  «        t          j        | j        dfd| j        | j        ¬¦  «        dœ}t          |¦  «        D �]>\  }}|| j        k     sJ ‚|  	                    t          |¦  «        ¦  «        }| j                             |¦  «         ||g         ||g         }
}	|�||g         d         nd}|	€|€
J d	¦   «         ‚|                      ||	|
|¦  «        }|�¢|d
         }|j        dd…         |d
         j        dd…         k    s4J d|d
         j        dd…         › d|j        dd…         › d|› d�¦   «         ‚||d
         ||dz   …<   |d         |d         ||dz   …<   d|v r|d         |d         ||dz   …<   �Œ@t          j        |d
                              | j        | j        j        dk    ¬¦  «        | j        dd¬¦  «        }| j        j        r| j                             |¦  «        }| j                             | j        | j        ||d         d¬¦  «        \  }}||d<   ||d<   | j                             |¦  «         dS )a  Append the imgState to the memory_bank and update the memory for the model.

        Args:
            obj_ids (list[int]): List of object IDs corresponding to the prompts.
            points (torch.Tensor | None): Tensor of shape (B, N, 2) representing the input points for N objects.
            labels (torch.Tensor | None): Tensor of shape (B, N) representing the labels for the input points.
            masks (torch.Tensor | None): Optional tensor of shape (N, H, W) representing the input masks for N objects.
        Nr   r   é   rí  rî  iàÿÿÿrò  z'Either bbox, points or mask is requiredr‹   re   zExpected mask shape z	 but got z for object r“   ró  rô  r¬  )r­  r°   Frõ  T)rÞ  rÙ  r   rô  r÷  rá  rã  )r@   rø  r@  rb   r�   rI   rL   rù  r  r±  r[  r?  Úaddrä  rf   rµ   r¶   rH   r´  rû  r  r  rp  rÙ  r>  r¸   )r5   rÓ  rk   rm   rl   r¼  rq   rŠ  r·  ÚpointÚlabelr?  rý  Úobj_maskrö  rá  rã  s                    r9   rE  z-SAM2DynamicInteractivePredictor.update_memoryÖ  s{  € ð" !%Ø#Ýœ*ØÔ'¨¨D¬J°q¬M¸QÑ,>ÀÄ
È1ÄÐQRÑ@RÐSØ"ØÔ&Ø”{ð	ñ ô õ ”zØÔ'¨¬Ô)>Ð?Ø"ØÔ&Ø”{ð	ñ ô õ $)¤:ØÔ'¨Ð+ð ØÔ&Ø”{ð$ñ $ô $ð
ð 
Ðõ2 # 7Ñ+Ô+ð 	pñ 	p‰IˆAˆvØ˜DÔ-Ò-Ð-Ð-Ð-Ø×)Ò)­#¨f©+¬+Ñ6Ô6ˆGØÔ× Ò  Ñ)Ô)Ð)Ø! 1 #œ;¨°¨s¬�5ˆEØ',Ð'8�5˜!˜”:˜dÔ#Ð#¸dˆDàÐ$¨Ð(8Ð(8Ð:cÑ(8Ô(8Ð8Ø—/’/ '¨5°%¸Ñ>Ô>ˆCØˆØ˜|Ô,�Ø”~ b c cÔ*Ð.>¸|Ô.LÔ.RÐSUÐSVÐSVÔ.WÒWÐWÐWð KÐ+;¸LÔ+IÔ+OÐPRÐPSÐPSÔ+Tð  Kð  KÐ_gÔ_mÐnpÐnqÐnqÔ_rð  Kð  Kð  AHð  Kð  Kð  Kñ XÔWÐWð IQÐ  Ô.¨w¸À1¹Ð/DÑEØEHÈÄ^Ð  Ô+¨G°gÀ±kÐ,AÑBà(¨CÐ/Ð/ØUXÐYnÔUoÐ$Ð%:Ô;¸GÀgÐPQÁkÐ<QÑRùåœØ˜\Ô*×-Ò-¨d¬kÈÌÔHXÐ\bÒHbÐ-ÑcÔcØ”ØØð	
ñ 
ô 
ˆð Œ:Ô3ð 	[Ø!œZ×JÒJÈ>ÑZÔZˆNØ,0¬J×,IÒ,IØ!%Ô!2Ø”Ø .Ø 0Ð1FÔ GØ!ð -Jñ -
ô -
Ñ)Ð˜/ð 0@ÐÐ+Ñ,Ø.=ÐÐ*Ñ+ØÔ×ÒÐ 0Ñ1Ô1Ð1Ð1Ð1r:   r·  ú
int | Noneútorch.Tensorc                ó¸  — t          | j        ¦  «        dk    st          |t          ¦  «        r| j        d         | j        j        z   }nP|                      ¦   «         \  }}| j                             | j        dd…         | j	        dd…         ||d¬¦  «        } | 
                    ddd¦  «        j        | j        | j        j        j        g| j        d         ¢R Ž S )a´  Prepare memory-conditioned features for the current image state.

        If ``obj_idx`` is provided, features are prepared for a specific prompted object in the image. If ``obj_idx`` is
        None, features are prepared for all objects. If no memory is available, a no-memory embedding is added to the
        current vision features. Otherwise, memory from previous frames is used to condition the current vision features
        via a transformer attention mechanism.

        Args:
            obj_idx (int | None): The index of the object for which to prepare the features.

        Returns:
            pix_feat_with_mem (torch.Tensor): The memory-conditioned pixel features.
        r   r<   N)ÚcurrÚcurr_posÚmemoryÚ
memory_posÚnum_obj_ptr_tokensr   r>   )ra   r>  r?   r[  rp  rL   rm  Úget_maskmem_encÚmemory_attentionrJ  rd  rô   r@  Úd_modelrÙ  )r5   r·  Úpix_feat_with_memrW  Úmemory_pos_embeds        r9   Ú$_prepare_memory_conditioned_featureszDSAM2DynamicInteractivePredictor._prepare_memory_conditioned_features'  sö   € õ ˆtÔÑ Ô  AÒ%Ð%­°G½SÑ)AÔ)AÐ%ð !%Ô 1°"Ô 5¸¼
Ô8OÑ OÐÐð (,×';Ò';Ñ'=Ô'=Ñ$ˆFÐ$Ø $¤
× ;Ò ;ØÔ& r s sÔ+ØÔ/°°°Ô4ØØ+Ø#$ð !<ñ !ô !Ðð 7Ð ×(Ò(¨¨A¨qÑ1Ô1Ô6ØÔØŒJÔ'Ô/ð
ð Œ_˜RÔ ð
ð 
ð 
ð 	
r:   c                óÞ  — g g }}| j         D ]²}|                     |d                              d¦  «                             ddd¦  «        ¦  «         |d         d                              d¦  «                             ddd¦  «        }|| j        j        | j        j        dz
           z   }|                     |¦  «         Œ³t          j        |d¬¦  «        }t          j        |d¬¦  «        }||fS )zfGet memory and positional encoding from memory, which is used to condition the current image features.rá  r>   r   r   rã  r<   r  )	r>  r¸   rˆ   rd  rL   Úmaskmem_tpos_encr
  r@   r¹   )r5   Úto_cat_memoryÚto_cat_memory_pos_embedr¼  Úmaskmem_encrW  r^  s          r9   rZ  z/SAM2DynamicInteractivePredictor.get_maskmem_encJ  sü   € à13°RÐ.ˆØ $Ô 0ð 	8ð 	8ÐØ× Ò Ð!1Ð2DÔ!E×!MÒ!MÈaÑ!PÔ!P×!XÒ!XÐYZÐ\]Ð_`Ñ!aÔ!aÑbÔbÐbØ*Ð+<Ô=¸bÔA×IÒIÈ!ÑLÔL×TÒTÐUVÐXYÐ[\Ñ]Ô]ˆKØ%¨¬
Ô(CÀDÄJÔDZÐ]^ÑD^Ô(_Ñ_ˆKØ#×*Ò*¨;Ñ7Ô7Ð7Ð7å”˜=¨aÐ0Ñ0Ô0ˆÝ œ9Ð%<À!ÐDÑDÔDÐØÐ'Ð'Ð'r:   rŠ  c                ó8   — | j                              |d¦  «        S )záMap client-side object id to model-side object index.

        Args:
            obj_id (int): The client-side object ID.

        Returns:
            (int | None): The model-side object index, or None if not found.
        N)rÒ  r³  )r5   rŠ  s     r9   r±  z.SAM2DynamicInteractivePredictor._obj_id_to_idxW  s   € ð Ô!×%Ò% f¨dÑ3Ô3Ð3r:   rO  rP  r?  údict[str, Any]c                óÎ  ‡— |�z| j         j        rn| j        d                              ddd¦  «        } |j        d| j         j        j        g| j        d         ¢R Ž }| j                              |¦  «        \  }}}}}}	}
nb|  	                    |¦  «        Š|�
‰dd…         n‰Š| j          
                    ‰|�||dœnd|dˆfd„| j        D ¦   «         ¬	¦  «        \  }}}}}}	}
|||	|
d
œS )a×  Tracking step for the current image state to predict masks.

        This method processes the image features and runs the SAM heads to predict masks. If obj_idx is provided, it
        processes the features for a specific prompted object in the image. If obj_idx is None, it processes the
        features for all objects in the image. The method supports both mask-based output without SAM and full SAM
        processing with memory-conditioned features.

        Args:
            obj_idx (int | None): The index of the object for which to predict masks. If None, it processes all objects.
            point (torch.Tensor | None): The coordinates of the points of interest with shape (N, 2).
            label (torch.Tensor | None): The labels corresponding to the points where 1 means positive clicks, 0 means
                negative clicks.
            mask (torch.Tensor | None): The mask input for the object with shape (H, W).

        Returns:
            current_out (dict[str, Any]): A dictionary containing the current output with mask predictions and object
                pointers. Keys include 'point_inputs', 'mask_inputs', 'pred_masks', 'pred_masks_high_res',
                'obj_ptr', 'object_score_logits'.
        Nr<   r   r>   r   r¦  Fc                ó:   •— g | ]}|d ‰j         d         …         ‘ŒS )Nr   )rf   )r[   rf  r]  s     €r9   r^   z>SAM2DynamicInteractivePredictor.track_step.<locals>.<listcomp>Œ  s-   ø€ Ð"iÐ"iÐ"iÈ$ 4Ð(DÐ*;Ô*AÀ!Ô*DÐ(DÔ#EÐ"iÐ"iÐ"ir:   )Úbackbone_featuresr’  r“  rw   rw  )r‹   r   ró  rô  )rL   Ú$use_mask_input_as_output_without_samrp  rd  rô   r[  r\  rÙ  Ú_use_mask_as_outputr_  Ú_forward_sam_headsrw  )r5   r·  rO  rP  r?  Úpix_featro  Úlow_res_masksrö  ró  rô  r]  s              @r9   rä  z*SAM2DynamicInteractivePredictor.track_stepb  sD  ø€ ð4 Ð ¤
Ô OÐð Ô(¨Ô,×4Ò4°Q¸¸1Ñ=Ô=ˆHØ$�x”} R¨¬Ô)DÔ)LÐcÈtÌÐ_aÔObÐcÐcÐcˆHØSWÔS]×SqÒSqÐrvÑSwÔSwÑPˆAˆq�!�] N°GÐ=PÐ=Pð !%× IÒ IÈ'Ñ RÔ RÐà9@Ð9LÐ 1°"°1°"Ô 5Ð 5ÐRcÐØSWÔS]×SpÒSpØ"3ØOVÐOb¨eÀUÐKÐKÐKÐhlØ Ø!&Ø"iÐ"iÐ"iÐ"iÐRVÔRhÐ"iÑ"iÔ"ið Tqñ Tô TÑPˆAˆq�!�] N°GÐ=Pð (Ø#1ØØ#6ð	
ð 
ð 	
r:   )
r6   r   r7   r£  r:  r[  r"   r#   r;  r<  rG  )r/   rA  rj   rB  rl   rC  rk   rB  rm   rD  rÓ  rD  rE  r<  r;  rF  )r  rA  r;  r<  rE  )
rÓ  rD  rk   rK  rm   rK  rl   rK  r;  r<  )r·  rR  r;  rS  )r;  rF  )rŠ  r[  r;  rR  )
r·  rR  rO  rK  rP  rK  r?  rK  r;  rf  )rH  rI  rJ  rK  r   r,   r   ry   r{   rE  r_  rZ  r±  rä  rN  rO  s   @r9   r9  r9  J  sc  ø€ € € € € ðð ð6 Ø+/ØØ"&ð(ð (ð (ð (ð (ð (ð (ð> ÐÑÔð ,0Ø26Ø+/Ø#'Ø$(Ø#ð@Cð @Cð @Cð @Cñ Ôð@CðD%ð %ð %ð %ð  ÐÑÔð %)Ø&*Ø&*Ø%)ðN2ð N2ð N2ð N2ñ ÔðN2ð`!
ð !
ð !
ð !
ðF(ð (ð (ð (ð	4ð 	4ð 	4ð 	4ð #Ø%)Ø%)Ø$(ð1
ð 1
ð 1
ð 1
ð 1
ð 1
ð 1
ð 1
ð 1
r:   r9  c                  ó6   ‡ — e Zd ZdZg d¢ZdZdˆ fd„	Zd„ Zˆ xZS )	ÚSAM3PredictorzSSegment Anything Model 3 (SAM3) Interactive Predictor for image segmentation tasks.©)é   rr  )é�   rs  )éH   rt  é   NTc                ól  •— t          ¦   «                              ||¦  «         t          j        g d¢¦  «                             ddd¦  «                             | j        ¦  «        | _        t          j        g d¢¦  «                             ddd¦  «                             | j        ¦  «        | _        dS )zTSetup the SAM3 model with appropriate mean and standard deviation for preprocessing.)ç     à_@rw  rw  r<   r   N)	r+   rû   r@   r¥   rô   rH   rI   rJ   rK   )r5   rL   rí   r8   s      €r9   rû   zSAM3Predictor.setup_model   s•   ø€ å‰Œ×Ò˜E 7Ñ+Ô+Ð+å”LÐ!6Ð!6Ð!6Ñ7Ô7×<Ò<¸RÀÀAÑFÔF×IÒIÈ$Ì+ÑVÔVˆŒ	Ý”<Ð 5Ð 5Ð 5Ñ6Ô6×;Ò;¸BÀÀ1ÑEÔE×HÒHÈÌÑUÔUˆŒˆˆr:   c                óx   — ddl m} | j        j        du rdn| j        j        pd} || j        j        |¬¦  «        S )úYRetrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks.r   ©Úbuild_interactive_sam3TÚdefaultN©Úcompile)Ú
build_sam3r{  r-   r~  rL   )r5   r{  Úcompile_modes      r9   rñ   zSAM3Predictor.get_model§  sQ   € à6Ð6Ð6Ð6Ð6Ð6à$(¤IÔ$5¸Ð$=Ð$=�y�yÀ4Ä9ÔCTÐC\ÐX\ˆØ%Ð% d¤i¤o¸|ÐLÑLÔLÐLr:   rF  )	rH  rI  rJ  rK  ra  r÷   rû   rñ   rN  rO  s   @r9   rp  rp  –  sw   ø€ € € € € Ø]Ð]ðð ð €Nð
 €FðVð Vð Vð Vð Vð VðMð Mð Mð Mð Mð Mð Mr:   rp  c                  ó¬   — e Zd ZdZd„ Z e¦   «         d„ ¦   «         Zd„ Zdd„Zddd	„Z	dd„Z
d„ Zddd„Z e¦   «         	 	 	 ddd„¦   «         Zd„ Zdd„ZdS )ÚSAM3SemanticPredictorzGSegment Anything Model 3 (SAM3) Predictor for image segmentation tasks.c                óP   — ddl m}  || j        j        | j        j        ¬¦  «        S )ry  r   )Úbuild_sam3_image_modelr}  )r  r„  r-   rL   r~  )r5   r„  s     r9   rñ   zSAM3SemanticPredictor.get_model²  s3   € à6Ð6Ð6Ð6Ð6Ð6à%Ð% d¤i¤o¸t¼yÔ?PÐQÑQÔQÐQr:   c                ó@   — | j         j                             |¦  «        S )z2Extract image features using the model's backbone.)rL   Úbackbonerj  r-  s     r9   r{   z%SAM3SemanticPredictor.get_im_features¸  s   € ð ŒzÔ"×0Ò0°Ñ4Ô4Ð4r:   c                óŠ   ‡— t          |¦  «        dk    s
J d¦   «         ‚t          | j        ddd¬¦  «        Šˆfd„|D ¦   «         S )a�  Perform initial transformations on the input image for preprocessing.

        This method applies transformations such as resizing to prepare the image for further preprocessing. Currently,
        batched inference is not supported; hence the list length should be 1.

        Args:
            im (list[np.ndarray]): List containing a single image in HWC numpy array format.

        Returns:
            (list[np.ndarray]): List containing the transformed image.

        Raises:
            AssertionError: If the input list contains more than one image.

        Examples:
            >>> predictor = SAM3SemanticPredictor()
            >>> predictor.imgsz = [1024, 1024]  # normally set by setup_source()
            >>> image = np.random.rand(480, 640, 3)  # Single HWC image
            >>> transformed = predictor.pre_transform([image])
            >>> print(len(transformed))
            1
        r   rS   FT)rT   rU   Ú
scale_fillc                ó(   •— g | ]} ‰|¬ ¦  «        ‘ŒS rW   rY   rZ   s     €r9   r^   z7SAM3SemanticPredictor.pre_transform.<locals>.<listcomp>Ö  r_   r:   r`   rc   s     @r9   rD   z#SAM3SemanticPredictor.pre_transform½  sQ   ø€ õ. �2‰wŒw˜!Š|ˆ|ˆ|ÐU‰|Œ|ˆ|Ý˜dœj¨u¸UÈtÐTÑTÔTˆ	Ø/Ð/Ð/Ð/¨BÐ/Ñ/Ô/Ð/r:   Nc                óŠ  — |��=t          j        || j        | j        ¬¦  «        }|j        dk    r|d         n|}t          j        |¦  «        }|dd…ddd…fxx         |d         z  cc<   |dd…ddd…fxx         |d         z  cc<   |€!t          j        |j	        dd…         ¦  «        }t          j        |t           j
        | j        ¬¦  «        }|j	        d         |j	        d         k    s'J d|j	        d         › d	|j	        d         › d
�¦   «         ‚|                     ddd¦  «        }|                     dd¦  «        }||fS )zRPrepare prompts by normalizing bounding boxes and points to the destination shape.Nr�   r   r   r>   r<   re   r‘   r’   r“   rM  )r@   rœ   r�   rI   rž   r   Ú	xyxy2xywhrB   rŸ   rf   r    rô   )r5   rh   rj   rm   s       r9   Ú_prepare_geometric_promptsz0SAM3SemanticPredictor._prepare_geometric_promptsØ  sV  € àÑÝ”_ V°4Ô3CÈDÌKÐXÑXÔXˆFØ%+¤[°AÒ%5Ð%5�V˜D”\�\¸6ˆFå”] 6Ñ*Ô*ˆFØ�1�1�1�a�d˜�d�7ˆOˆOŒO˜y¨œ|Ñ+ˆOˆO‰OØ�1�1�1�a�d˜�d�7ˆOˆOŒO˜y¨œ|Ñ+ˆOˆO‰Oàˆ~Ýœ ¤¨c¨r¨cÔ!2Ñ3Ô3�Ý”_ Vµ5´;ÀtÄ{ÐSÑSÔSˆFØ”< Ô# v¤|°BÔ'7Ò7Ð7Ð7Øh F¤L°Ô$4ÐhÐhÐU[ÔUaÐbdÔUeÐhÐhÐhñ 8Ô7Ð7ð —[’[  Q¨Ñ*Ô*ˆFØ—[’[  QÑ'Ô'ˆFØ�vˆ~Ðr:   Útextúlist[str] | Nonec                ó   — |�dn)|�t          |¦  «        nt          | j        j        ¦  «        }d}|�]|                      |¦  «        }t	          t          |¦  «        ¦  «        D ]&}|                     ||g         ||g         ¦  «         Œ'|€dg}|�+| j        j        |k    r| j                             |¬¦  «         | j                             |t          j	        || j
        t          j        ¬¦  «        |¬¦  «        }|S )zPRun inference on the extracted features with optional bounding boxes and labels.Nr   Úvisual©r�  r7  ©rn  Útext_idsÚgeometric_prompt)ra   rL   r  Ú_get_dummy_promptr  Úappend_boxesÚset_classesÚforward_groundingr@   r  rI   Úlong)	r5   r0   rj   rm   r�  Úncr”  rq   Úoutputss	            r9   r}   z)SAM3SemanticPredictor._inference_featuresì  s  € ð Ð$ˆQˆQ°tÐ7G­#¨d©)¬)¨)ÍSÐQUÔQ[ÔQaÑMbÔMbˆØÐØÐØ#×5Ò5°bÑ9Ô9ÐÝ�3˜v™;œ;Ñ'Ô'ð Hð H�Ø ×-Ò-¨f°a°S¬k¸6À1À#¼;ÑGÔGÐGÐGØˆ|Ø �z�ØÐ ¤
Ô 0°DÒ 8Ð 8ØŒJ×"Ò"¨Ð"Ñ-Ô-Ð-Ø”*×.Ò.Ø!Ý”\ "¨T¬[ÅÄ
ÐKÑKÔKØ-ð /ñ 
ô 
ˆð
 ˆr:   rl   rS  rf   útuple[int, int]r;  c           	     óÌ  — d}|                      |j        d         g|¢R t          j        ¬¦  «        }t	          d|dz  d|d         z  |d         z  z  ¦  «        }t          d|j        d         |¦  «        D ]l}t          j        t          j        ||||z   …          	                    ¦   «         d         |d¬	¦  «        d         | j
        j        ||||z   …         ¬
¦  «         Œm|S )aQ  Upscale (N, h, w) mask logits to a boolean (N, *shape) mask in memory-bounded chunks.

        Args:
            masks (torch.Tensor): Low resolution mask logits with shape (N, h, w).
            shape (tuple[int, int]): Target height and width.

        Returns:
            (torch.Tensor): Binary masks with shape (N, *shape).
        i   r   r”   r   i   rM  Nr°   r5  )rý  )Ú	new_emptyrf   r@   r<  r¾   r  Úgtrµ   r¶   rO   rL   r·   )r5   rl   rf   ÚMAX_CHUNK_MEMÚupscaledÚchunkrq   s          r9   Ú_upscale_masksz$SAM3SemanticPredictor._upscale_masks 	  sñ   € ð ˆØ—?’? E¤K°¤NÐ#;°UÐ#;Ð#;Å5Ä:�?ÑNÔNˆÝ�A�} uÑ,°°U¸1´X±ÀÀaÄÑ1HÑIÑJÔJˆÝ�q˜%œ+ aœ.¨%Ñ0Ô0ð 	ð 	ˆAÝŒHÝ”˜e A¨¨E©	 MÔ2×8Ò8Ñ:Ô:¸4Ô@À%ÈjÐYÑYÔYÐZ[Ô\Ø”
Ô)Ø˜Q  U¡˜]Ô+ðñ ô ð ð ð
 ˆr:   c           
     óô  — ddl }|d         }|d         }|d         }|                     ¦   «         }|d                              ¦   «                              d¦  «        }	||	z                       d¦  «        }t	          j        t          t          |j        d         ¦  «        ¦  «        |j	        |j
        ¬	¦  «        dd…df                              |¦  «        }
t	          j        ||d
         |
d
         gd¬¦  «        }|| j        j        k    }||         ||         }}t          j        |dd…dd…f         ¦  «        |dd…dd…f<   |dd…dd…f         | j        j        rdndz  }|dd…dd…f         |z   }|j                             ||dd…df         | j        j        ¦  «        }||         ||         }}t)          | j        dd„ t          |j        d         ¦  «        D ¦   «         ¦  «        }t-          |t          ¦  «        st          j        |¦  «        }g }t1          |g|g|| j        d         ¦  «        D ]¾\  }}}}|j        d         dk    rdt	          j        d|j
        ¬¦  «        }}na|                      ||j        dd…         ¦  «        }|dddgfxx         |j        d         z  cc<   |dddgfxx         |j        d         z  cc<   |                     t;          |||||¬¦  «        ¦  «         Œ¿|S )úNPost-process the predictions to apply non-overlapping constraints if required.r   NÚ
pred_boxesÚpred_logitsr‹   Úpresence_logit_decr   r<   r�   ©.Nr  rM  é   r  é   r  c                ó,   — g | ]}t          |¦  «        ‘ŒS rY   r  rp   s     r9   r^   z5SAM3SemanticPredictor.postprocess.<locals>.<listcomp>/	  s   € Ð-ZÐ-ZÐ-Z¸­c°!©f¬fÐ-ZÐ-ZÐ-Zr:   r  r¯   r>   .r=   r  )r²   Úsigmoidr;  r˜   r@   r¥   r  r  rf   r�   rI   Ú	expand_asr¹   r-   r½   r   Ú	xywh2xyxyÚagnostic_nmsrº   r»   rÖ  rL   r?   r  r³   r)   r  r£  r¸   r   )r5   r  r  r  r²   r¦  r§  r‹   rŒ   Úpresence_scoreÚpred_clsræ   ÚcÚ	nms_boxesr  r  rl   r€   r  r  s                       r9   r!  z!SAM3SemanticPredictor.postprocess	  s:  € àÐÐÐà˜<Ô(ˆ
Ø˜MÔ*ˆØ˜<Ô(ˆ
Ø!×)Ò)Ñ+Ô+ˆØÐ3Ô4×<Ò<Ñ>Ô>×HÒHÈÑKÔKˆØ" ^Ñ3×<Ò<¸RÑ@Ô@ˆÝ”<Ý•�{Ô(¨Ô+Ñ,Ô,Ñ-Ô-ØÔ#ØÔ%ð
ñ 
ô 
ð ˆ!ˆ!ˆTˆ'ô	÷ ’9˜[Ñ)Ô)ð	 	õ
 ”Y 
¨K¸	Ô,BÀHÈYÔDWÐXÐ^`ÐaÑaÔaˆ
à˜TœYœ^Ò+ˆØ!+¨DÔ!1°:¸dÔ3C�Jˆ
ÝœM¨*°Q°Q°Q¸¸¸°UÔ*;Ñ<Ô<ˆ
�1�1�1�b�q�b�5Ñà�q�q�q˜!˜A˜#�vÔ t¤yÔ'=Ð"G ! !À4ÑHˆØ˜q˜q˜q " 1 "˜uÔ%¨Ñ)ˆ	ØŒ×"Ò" 9¨j¸¸¸¸A¸Ô.>ÀÄ	ÄÑNÔNˆØ!+¨DÔ!1°:¸dÔ3C�Jˆ
å˜œ
 GÐ-ZÐ-Z½eÀKÔDUÐVWÔDXÑ>YÔ>YÐ-ZÑ-ZÔ-ZÑ[Ô[ˆÝ˜)¥TÑ*Ô*ð 	AÝÔ5°iÑ@Ô@ˆIØˆÝ03°Z°LÀ:À,ÐPYÐ[_Ô[eÐfgÔ[hÑ0iÔ0ið 	dð 	dÑ,ˆE�5˜( HØŒ{˜1Œ~ Ò"Ð"Ø#¥U¤[°À
Ô@QÐ%RÑ%RÔ%R�u��à×+Ò+¨E°8´>À"À1À"Ô3EÑFÔF�Ø�c˜A˜q˜6�kÐ"Ð"Ô" h¤n°QÔ&7Ñ7Ð"Ð"Ñ"Ø�c˜A˜q˜6�kÐ"Ð"Ô" h¤n°QÔ&7Ñ7Ð"Ð"Ñ"Ø�NŠN�7 8°(À%ÈuÐ\aÐbÑbÔbÑcÔcÐcÐcØˆr:   c                óD  — | j                              d|¦  «        }| j                              d|¦  «        }| j                              d|¦  «        }| j        €|                      |¦  «        n| j        }|                      | j        ||¦  «        } | j        |g|¢R d|iŽS )z:Perform inference on a single image with optional prompts.rj   rm   r�  )r1   rs   r0   r{   rŒ  rh   r}   )	r5   r/   rj   rm   r�  r-   rx   r0   r1   s	            r9   ry   zSAM3SemanticPredictor.inference=	  s¤   € à”×!Ò! (¨FÑ3Ô3ˆØ”×!Ò! (¨FÑ3Ô3ˆØŒ|×Ò ¨Ñ-Ô-ˆØ/3¬}Ð/D�4×'Ò'¨Ñ+Ô+Ð+È$Ì-ˆØ×1Ò1°$´.À&È&ÑQÔQˆØ'ˆtÔ'¨ÐF°7ÐFÐFÐFÀÐFÐFÐFr:   c                ó   — ddl }|                      |dd…         ||¦  «        } | j        |g|¢R d|iŽ}|d         }	|d         }
|d         }|
                     ¦   «         }|d                              ¦   «                              d	¦  «        }||z                       d
¦  «        }t          j        t          t          |j
        d         ¦  «        ¦  «        |j        |j        ¬¦  «        dd…df                              |¦  «        }t          j        |	|d         |d         gd
¬¦  «        }	|| j        j        k    }||         |	|         }	}t#          j        |	dd…dd…f         ¦  «        |	dd…dd…f<   |	dd…dd…f         | j        j        rdndz  }|	dd…dd…f         |z   }|j                             ||	dd…df         | j        j        ¦  «        }|	|         ||         }}	|j
        d         dk    rdt          j        d|j        ¬¦  «        }	}nv|                      ||dd…         ¦  «        }|	dxx         |d	         z  cc<   |	dxx         |d         z  cc<   |	dxx         |d	         z  cc<   |	dxx         |d         z  cc<   ||	fS )aM  Perform prompts preprocessing and inference on provided image features using the SAM model.

        Args:
            features (dict[str, Any]): Extracted image features from the SAM3 model image encoder.
            src_shape (tuple[int, int]): The source shape (height, width) of the input image.
            bboxes (np.ndarray | list[list[float]] | None): Bounding boxes in xyxy format with shape (N, 4). pixels.
            labels (np.ndarray | list[int] | None): Point prompt labels with shape (N, ).
            text (list[str] | None): List of text prompts corresponding to the classes.

        Returns:
            pred_masks (torch.Tensor): The output masks in shape (C, H, W), where C is the number of generated masks.
            pred_bboxes (torch.Tensor): Bounding boxes for each mask with shape (N, 6), where N is the number of boxes.
                Each box is in xyxy format with additional columns for score and class.

        Notes:
            - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2.
        r   Nr>   r�  r¦  r§  r‹   r¨  r   r<   r�   r©  r  rM  rª  r  r«  r  r¯   ).r   ).r   ).r>   ).r=   )r²   rŒ  r}   r­  r;  r˜   r@   r¥   r  r  rf   r�   rI   r®  r¹   r-   r½   r   r¯  r°  rº   r»   r  r£  )r5   r0   rh   rj   rm   r�  r²   r1   r  r¦  r§  r‹   rŒ   r±  r²  ræ   r³  r´  s                     r9   rC  z(SAM3SemanticPredictor.inference_featuresF	  sñ  € ð4 	ÐÐÐà×1Ò1°)¸B¸Q¸B´-ÀÈÑPÔPˆØ(�Ô(¨ÐG°GÐGÐGÐGÀ$ÐGÐGˆØ˜<Ô(ˆ
Ø˜MÔ*ˆØ˜<Ô(ˆ
Ø!×)Ò)Ñ+Ô+ˆØÐ3Ô4×<Ò<Ñ>Ô>×HÒHÈÑKÔKˆØ" ^Ñ3×<Ò<¸RÑ@Ô@ˆÝ”<Ý•�{Ô(¨Ô+Ñ,Ô,Ñ-Ô-ØÔ#ØÔ%ð
ñ 
ô 
ð ˆ!ˆ!ˆTˆ'ô	÷ ’9˜[Ñ)Ô)ð	 	õ
 ”Y 
¨K¸	Ô,BÀHÈYÔDWÐXÐ^`ÐaÑaÔaˆ
à˜TœYœ^Ò+ˆØ!+¨DÔ!1°:¸dÔ3C�Jˆ
ÝœM¨*°Q°Q°Q¸¸¸°UÔ*;Ñ<Ô<ˆ
�1�1�1�b�q�b�5Ñà�q�q�q˜!˜A˜#�vÔ t¤yÔ'=Ð"G ! !À4ÑHˆØ˜q˜q˜q " 1 "˜uÔ%¨Ñ)ˆ	ØŒ×"Ò" 9¨j¸¸¸¸A¸Ô.>ÀÄ	ÄÑNÔNˆØ!+¨DÔ!1°:¸dÔ3C�Jˆ
àÔ˜AÔ !Ò#Ð#Ø%)­5¬;°vÀjÔFWÐ+XÑ+XÔ+X˜
ˆJˆJà×,Ò,¨Z¸À2ÀAÀ2¼ÑGÔGˆJØ�vÐÐÔ )¨A¤,Ñ.ÐÐÑØ�vÐÐÔ )¨A¤,Ñ.ÐÐÑØ�vÐÐÔ )¨A¤,Ñ.ÐÐÑØ�vÐÐÔ )¨A¤,Ñ.ÐÐÑØ˜:Ð%Ð%r:   c                ó,   — i | _         i | j        _        dS )z$Reset the prompts for the predictor.N)r1   rL   Útext_embeddingsr1  s    r9   Úreset_promptsz#SAM3SemanticPredictor.reset_prompts„	  s   € àˆŒØ%'ˆŒ
Ô"Ð"Ð"r:   r   c           	     ó¬   — ddl m}  |t          j        d|d| j        ¬¦  «        t          j        |d| j        t          j        ¬¦  «        ¬¦  «        }|S )z-Get a dummy geometric prompt with zero boxes.r   r   r   rM  r¯   r7  )Úbox_embeddingsÚbox_mask)Úsam3.geometry_encodersr   r@   r  rI   r<  )r5   Únum_promptsr   r”  s       r9   r•  z'SAM3SemanticPredictor._get_dummy_prompt‰	  sg   € ð 	3Ð2Ð2Ð2Ð2Ð2à!˜6Ý œ; q¨+°qÀÄÐMÑMÔMÝ”[ ¨a¸¼Í5Ì:ÐVÑVÔVð
ñ 
ô 
Ðð  Ðr:   r6  ©NNN©r�  rŽ  )rl   rS  rf   rœ  r;  rS  r5  )rH  rI  rJ  rK  rñ   r   r{   rD   rŒ  r}   r£  r!  ry   rC  r¹  r•  rY   r:   r9   r‚  r‚  ¯  s-  € € € € € ØQÐQðRð Rð Rð ÐÑÔð5ð 5ñ Ôð5ð0ð 0ð 0ð6ð ð ð ð(ð ð ð ð ð(ð ð ð ð*&ð &ð &ðPGð Gð Gð Gð Gð ÐÑÔð
 ØØ!%ð;&ð ;&ð ;&ð ;&ñ Ôð;&ðz(ð (ð (ð
	 ð 	 ð 	 ð 	 ð 	 ð 	 r:   r‚  c                  ó   — e Zd ZdZd„ ZdS )ÚSAM3VideoPredictorzMSegment Anything Model 3 (SAM3) Video Predictor for video segmentation tasks.c                ó¬  — |}|d         }|d         }|d         }t          |d         ¦  «        }t          |d         ¦  «        dk    rt          d¦  «        ‚||d         v r:d}||         |         }	| j        r"| j        s|dk    r|                      |¦  «         n]||d	         v rd	}||         |         }	nBd	}|                      |||d
ddd
d|¬¦	  «	        }	|	||         |<   |                      ||¬¦  «         |                      ||	||¬¦  «         |d                              |¦  «         |	d          	                    dd¦  «        }
|	d         }||
|fS )a   Perform image segmentation inference based on the given input cues, using the currently loaded image. This
        method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
        encoder, and mask decoder for real-time and promptable segmentation tasks.

        Args:
            inference_state (dict): The current state of inference, including input cues and previous outputs.
            frame_idx (int): The index of the current frame in the video sequence.
        rˆ  rÓ  rŒ  r�  r‰  r   rŽ  r   r�  FNT)	rˆ  r‹  r�  r‘  r’  r“  r”  r•  r~  r¿  r–  r‹   rô  )
ra   r›  r  r€  rœ  r�  rž  rŸ  r¸   rˆ   )r5   r~  r‹  r˜  rˆ  rÓ  rŒ  r�  r¡  r¢  r‹   Ú
obj_scoress               r9   Úpropagate_in_videoz%SAM3VideoPredictor.propagate_in_video˜	  s·  € ð ˆØ% mÔ4ˆØ! )Ô,ˆØ"1Ð2KÔ"LÐÝ˜¨Ô9Ñ:Ô:ˆ
Ýˆ{Ð/Ô0Ñ1Ô1°QÒ6Ð6ÝÐPÑQÔQÐQàÐ+Ð,@ÔAÐAÐAØ.ˆKØ% kÔ2°5Ô9ˆKØÔ3ð =¸Ô9^ð =ÐblÐpqÒbqÐbqà×5Ò5°eÑ<Ô<Ð<øØÐ-Ð.FÔGÐGÐGØ2ˆKØ% kÔ2°5Ô9ˆKˆKà2ˆKØ×:Ò:Ø'ØØ%Ø#(Ø!Ø ØØ $Ø /ð ;ñ 
ô 
ˆKð /:ˆK˜Ô$ UÑ+Ø×'Ò'¨¸Ð'ÑOÔOÐOð 	×#Ò# E¨;¸ÐUdÐ#ÑeÔeÐeØÐ0Ô1×8Ò8¸Ñ?Ô?Ð?Ø  Ô.×6Ò6°q¸!Ñ<Ô<ˆ
Ø Ð!6Ô7ˆ
à˜
 JÐ.Ð.r:   N)rH  rI  rJ  rK  rÅ  rY   r:   r9   rÂ  rÂ  •	  s)   € € € € € ØWÐWð0/ð 0/ð 0/ð 0/ð 0/r:   rÂ  c                  ó  ‡ — e Zd ZdZdZdZdZdZdZdZ	dZ
g d¢Zd	Zed
d
ddddddddddddddddddddddfdoˆ fd„Z ed¦  «        dpˆ fd„	¦   «         Zˆ fd„Zed„ ¦   «         Zdqdrd„Zd„ Zdsd„Z e¦   «         	 	 	 	 dtd„¦   «         Zdud „Z	 dvdwd0„Zedxd2„¦   «         Zdyd3„Zd4„ Zd5„ Zdzd7„Zd{d>„Zd|d@„Z 	 d}d~dD„Z!ddF„Z"e	 d€d�dI„¦   «         Z#	 	 d‚dƒdN„Z$d„dP„Z%d…dV„Z&d†d]„Z'd‡d`„Z(dˆdc„Z)d‰dd„Z*de„ Z+dŠdh„Z,dvd‹dl„Z-dm„ Z.edn„ ¦   «         Z/ˆ xZ0S )ŒÚSAM3VideoSemanticPredictorz9Segment Anything Model 3 (SAM3) Video Semantic Predictor.çš™™™™™é?ç      $Àr<   i † r   r>   rq  ru  Nr`  ç        r   r=   é
   éüÿÿÿTFr!   r"   r#   c                ó
  •— t          ¦   «                              |||¦  «         || _        || _        || _        || _        || _        |	dk    r|
|	k    sJ ‚||	k    sJ ‚|	| _        |
| _        || _	        || _
        || _        || _        || _        || _        || _        || _        || _        d| _        d}d}|| _        || _        || _        || _        || _        || _        || _        t5          |¬¦  «        | _        i | _        dS )zTInitialize the SAM3VideoSemanticPredictor with configuration and optional overrides.r   Ni'  r!   )r7   )r+   r,   Úscore_threshold_detectionÚdet_nms_threshÚassoc_iou_threshÚtrk_assoc_iou_threshÚnew_det_threshÚhotstart_delayÚhotstart_unmatch_threshÚhotstart_dup_threshÚinit_trk_keep_aliveÚmax_trk_keep_aliveÚmin_trk_keep_aliveÚ8suppress_overlapping_based_on_recent_occlusion_thresholdÚsuppress_det_close_to_boundaryÚ*decrease_trk_keep_alive_for_empty_maskletsÚo2o_matching_masklets_enableÚfill_hole_areaÚ_dist_pg_cpuÚmax_num_objectsÚnum_obj_for_compileÚrecondition_every_nth_frameÚmasklet_confirmation_enableÚ+masklet_confirmation_consecutive_det_threshÚreconstruction_bbox_iou_threshÚreconstruction_bbox_det_scorerÂ  Útrackerr~  )r5   r6   r7   r"   rÎ  rÏ  rÐ  rÑ  rÒ  rÓ  rÔ  rÕ  rÖ  r×  rØ  rÙ  rÛ  rÜ  rÚ  rÝ  rß  rá  râ  rã  rä  rå  rà  r8   s                              €r9   r,   z#SAM3VideoSemanticPredictor.__init__Ý	  sD  ø€ õ\ 	‰Œ×Ò˜˜i¨Ñ4Ô4Ð4Ø)BˆÔ&Ø,ˆÔØ 0ˆÔØ$8ˆÔ!Ø,ˆÔð ˜AÒÐØ*¨nÒ<Ð<Ð<Ð<Ø&¨.Ò8Ð8Ð8Ð8Ø,ˆÔØ'>ˆÔ$Ø#6ˆÔ Ø#6ˆÔ Ø"4ˆÔØ"4ˆÔàDð 	ÔEð /MˆÔ+Ø:dˆÔ7Ø,HˆÔ)Ø,ˆÔØ ˆÔàˆØ ÐØ.ˆÔØ#6ˆÔ Ø+FˆÔ(Ø+FˆÔ(Ø;fˆÔ8Ø.LˆÔ+Ø-JˆÔ*õ *°IÐ>Ñ>Ô>ˆŒà!ˆÔÐÐr:   c                ó¾   •— t          ¦   «                              ||¦  «         ddlm}  || j        j        d¬¦  «        }| j                             |d¬¦  «         dS )z+Setup the SAM3VideoSemanticPredictor model.r   rz  F)Úwith_backbone)rL   rí   N)r+   rû   r  r{  r-   rL   ræ  )r5   rL   rí   r{  r8   s       €r9   rû   z&SAM3VideoSemanticPredictor.setup_model4
  sm   ø€ õ 	‰Œ×Ò˜E 7Ñ+Ô+Ð+Ø6Ð6Ð6Ð6Ð6Ð6ð 'Ð& t¤y¤ÀeÐLÑLÔLˆØŒ× Ò  u°eÐ Ñ<Ô<Ð<Ð<Ð<r:   c                ó†  •‡ — t          ¦   «                              |¦  «         ‰ j        ‰ j        _        ‰ j        j                             ‰ j        ¦  «         ˆ fd„dD ¦   «         ‰ j        _        ‰ j        j        j        j        j	        ‰ _	        ‰ j
        �'‰ j
        j        dk    r‰                      ‰ ¦  «         dS dS dS )z:Setup the source for the SAM3VideoSemanticPredictor model.c                ó:   •‡— g | ]Šˆˆfd „‰j         D ¦   «         ‘ŒS )c                óD   •— g | ]}t          |‰j        ‰z  z  ¦  «        ‘ŒS rY   rZ  r\  s     €€r9   r^   zFSAM3VideoSemanticPredictor.setup_source.<locals>.<listcomp>.<listcomp>C
  s,   ø€ Ð'WÐ'WÐ'WÀq­¨A°´¸q±Ñ,AÑ(BÔ(BÐ'WÐ'WÐ'Wr:   r]  r^  s    @€r9   r^   z;SAM3VideoSemanticPredictor.setup_source.<locals>.<listcomp>C
  s5   øø€ Ð&sÐ&sÐ&sÐ\]Ð'WÐ'WÐ'WÐ'WÐ'WÈDÌJÐ'WÑ'WÔ'WÐ&sÐ&sÐ&sr:   r_  Nrƒ  )r+   r#  rb   ræ  rL   r(  ra  Úmemory_encoderÚmask_downsamplerÚinterpol_sizer$  r(   r„  r)  s   ` €r9   r#  z'SAM3VideoSemanticPredictor.setup_source>
  sµ   øø€ å‰Œ×Ò˜VÑ$Ô$Ð$Ø!œZˆŒÔØŒÔ×$Ò$ T¤ZÑ0Ô0Ð0Ø&sÐ&sÐ&sÐ&sÐarÐ&sÑ&sÔ&sˆŒÔ#Ø!œ\Ô/Ô>ÔOÔ]ˆÔØŒ<Ð#¨¬Ô(9¸WÒ(DÐ(DØ�OŠO˜DÑ!Ô!Ð!Ð!Ð!ð $Ð#Ð(DÐ(Dr:   c                ó®   — t          | j        ¦  «        dk    rdS | j        €J ‚| j        j        dk    sJ ‚| j        j        }|g i ddg|z  dœ}|| _        dS )aÃ  Initialize an inference state for the predictor.

        This function sets up the initial state required for performing inference on video data. It includes
        initializing various dictionaries and ordered dictionaries that will store inputs, outputs, and other metadata
        relevant to the tracking process.

        Args:
            predictor (SAM3VideoSemanticPredictor): The predictor object for which to initialize the state.
        r   Nrƒ  )rÐ  Útracker_inference_statesÚtracker_metadataÚtext_promptÚper_frame_geometric_prompt)ra   r~  r$  r(   rÌ  )rÍ  rÐ  r~  s      r9   r„  z%SAM3VideoSemanticPredictor.init_stateH
  s‚   € õ ˆyÔ(Ñ)Ô)¨AÒ-Ð-ØˆFØÔ Ð,Ð,Ð,ØÔ Ô%¨Ò0Ð0Ð0Ð0ØÔ&Ô-ˆ
à$Ø(*Ø "ØØ+/¨&°:Ñ*=ð
ð 
ˆð %4ˆ	Ô!Ð!Ð!r:   r�  rŽ  c                ó¦   — | j         j        dz
  }|| j        d<   d| j        vr|                      ||||¬¦  «         |                      |d¬¦  «        S )z<Perform inference on a video sequence with optional prompts.r   r/   r“  )r‹  r�  rj   rm   F)r”  )r$  r˜  r~  Ú
add_promptr�  )r5   r/   rj   rm   r�  r-   rx   r˜  s           r9   ry   z$SAM3VideoSemanticPredictor.inferencea
  s_   € à”Ô" QÑ&ˆØ%'ˆÔ˜TÑ"Ø˜TÔ1Ð1Ð1Ø�OŠO e°$¸vÈfˆOÑUÔUÐUØ×/Ò/°¸uÐ/ÑEÔEÐEr:   c           
     óx  ‡‡— ‰d         Št          ‰                     ¦   «         ¦  «        }t          |t          ¦  «        st	          j        |¦  «        }| j        j        dk    r| j        j        ni }t          |¦  «        dk    rdt          j
        d| j        ¬¦  «        }}�nEt          j        ˆfd„|D ¦   «         d¬¦  «        }|                      ||d         j        dd	…         ¦  «        }t          j        |t          j        |j        ¬
¦  «        }t          j        ˆfd„|D ¦   «         |j        ¬¦  «        }	t          j        ˆfd„|D ¦   «         |j        ¬¦  «        }
|	| j        j        k    |                     d¬¦  «        z  }||         }t)          |¦  «        }t          j        |||         dd…df         |	|         d         |
|         d         gd¬¦  «        }|j        d         rf|pct+          t-          d„ t/          |dd…df                              ¦   «                              ¦   «         dz   ¦  «        D ¦   «         ¦  «        ¦  «        }|j        d         dk    r‚t          j        ˆfd„|D ¦   «         |j        ¬¦  «        |         }|                      |                     d¦  «        |                     d¦  «        d¬¦  «                             d¦  «        dk    }g }t;          |g|g|| j        d         ¦  «        D ].\  }}}}|                     tA          |||||¬¦  «        ¦  «         Œ/|S )r¥  Úobj_id_to_maskr�  r   N)r   é   r¯   c                ó    •— g | ]
}‰|         ‘ŒS rY   rY   )r[   rŠ  r÷  s     €r9   r^   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>t
  s   ø€ Ð#VÐ#VÐ#V¸v N°6Ô$:Ð#VÐ#VÐ#Vr:   r  r>   r�   c                ó,   •— g | ]}‰d          |         ‘ŒS )Úobj_id_to_scorerY   ©r[   rŠ  r  s     €r9   r^   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>x
  s$   ø€ ÐMÐMÐM°f�Ð(Ô)¨&Ô1ÐMÐMÐMr:   c                ó,   •— g | ]}‰d          |         ‘ŒS )Úobj_id_to_clsrY   rü  s     €r9   r^   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>{
  s#   ø€ ÐKÐKÐK°F��Ô'¨Ô/ÐKÐKÐKr:   r—  r©  r<   c              3  ó4   K  — | ]}t          |¦  «        V — Œd S ro   r  rp   s     r9   rr   z9SAM3VideoSemanticPredictor.postprocess.<locals>.<genexpr>„
  s(   è è € Ð/hÐ/h¸1µ°A±´Ð/hÐ/hÐ/hÐ/hÐ/hÐ/hr:   r  r   c                óH   •— g | ]}‰d                                |d¦  «        ‘ŒS )Úobj_id_to_tracker_scorerÊ  )r³  rü  s     €r9   r^   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>‡
  s/   ø€ ÐdÐdÐdÈV�eÐ5Ô6×:Ò:¸6À3ÑGÔGÐdÐdÐdr:   )Úbackground_valuer  )!ÚsortedrÂ  r?   r  r   r  rL   r  ra   r@   r  rI   r¹   r£  rf   r¥   r    r-   r½   Úanyr   r  r  r  r[  r¾   Ú._apply_object_wise_non_overlapping_constraintsr;  r˜   r³   r)   r¸   r   )r5   r  r  r  Úcurr_obj_idsr  r‹   r¦  Úpred_idsrŒ   r²  ræ   Útracker_scoresr  rl   r€   r  r  r÷  s    `                @r9   r!  z&SAM3VideoSemanticPredictor.postprocessi
  sy  øø€ àÐ/Ô0ˆÝ˜n×1Ò1Ñ3Ô3Ñ4Ô4ˆÝ˜)¥TÑ*Ô*ð 	AÝÔ5°iÑ@Ô@ˆIà$(¤JÔ$4¸Ò$@Ð$@�”
Ô Ð ÀbˆÝˆ|ÑÔ Ò!Ð!Ø%)­5¬;°vÀdÄkÐ+RÑ+RÔ+R˜
ˆJ‰JåœÐ#VÐ#VÐ#VÐ#VÈÐ#VÑ#VÔ#VÐ\]Ð^Ñ^Ô^ˆJØ×,Ò,¨Z¸À1¼Ô9KÈBÈQÈBÔ9OÑPÔPˆJÝ”| L½¼ÈJÔL]Ð^Ñ^Ô^ˆHÝœ,ØMÐMÐMÐMÀÐMÑMÔMÐV`ÔVgðñ ô ˆKõ ”|ØKÐKÐKÐK¸lÐKÑKÔKÐT^ÔTeðñ ô ˆHð   $¤)¤.Ò0°J·N²NÀv°NÑ4NÔ4NÑNˆDØ# DÔ)ˆJÝ,¨ZÑ8Ô8ˆJÝœØ˜X dœ^¨A¨A¨A¨t¨GÔ4°kÀ$Ô6GÈ	Ô6RÐT\Ð]aÔTbÐclÔTmÐnÐtvðñ ô ˆJð Ô Ô"ð jØÐi¥¥iÐ/hÐ/hÅÀjÐQRÐQRÐQRÐTUÐQUÔFV×FZÒFZÑF\ÔF\×F`ÒF`ÑFbÔFbÐefÑFfÑ@gÔ@gÐ/hÑ/hÔ/hÑ&hÔ&hÑ!iÔ!i�ØÔ Ô" QÒ&Ð&Ý!&¤ØdÐdÐdÐdÐWcÐdÑdÔdØ%Ô,ð"ñ "ô "ð ô"�ð
 ×GÒGØ"×,Ò,¨QÑ/Ô/Ø&×0Ò0°Ñ3Ô3Ø)*ð Hñ ô ÷ ’g˜a‘j”jØò�
ð ˆÝ03°Z°LÀ:À,ÐPYÐ[_Ô[eÐfgÔ[hÑ0iÔ0ið 	dð 	dÑ,ˆE�5˜( HØ�NŠN�7 8°(À%ÈuÐ\aÐbÑbÔbÑcÔcÐcÐcØˆr:   c                óJ  — |p| j         }|d         }|d         du}|d         |         du}|                      ||d         ||d         |d         |s)|                      t          |d         ¦  «        ¬¦  «        n|d         |         ||d	         |p|¬
¦	  «	        \  }}}	}
}}}|
|d<   ||d	<   |||	|d         |         dœ}|d         }|d         }||d<   ||d<   | j        r=|d         d         }|| j        k    }|d         |                              ¦   «         |d<   ng |d<   |S )zBPerform inference on a single frame and get its inference results.rð  rò  Nró  rÐ  r/   r“  ©r¾  rñ  )	r‹  rÐ  r”  r/   r“  r”  Útracker_states_localÚtracker_metadata_prevÚallow_new_detectionsÚ"obj_id_to_tracker_score_frame_wise)r÷  rû  rþ  r  ÚmetadataÚremoved_obj_idsÚframe_statsÚmasklet_confirmationÚstatusrÓ  Úunconfirmed_obj_ids)r~  Ú_det_track_one_framer•  ra   râ  ÚUNCONFIRMEDÚtolist)r5   r‹  r”  r~  r  Úhas_text_promptÚhas_geometric_promptr÷  rû  rþ  Útracker_states_local_newÚtracker_metadata_newr  ro  rý  r  r  r  Úis_unconfirmeds                      r9   r�  z6SAM3VideoSemanticPredictor._run_single_frame_inference—
  s«  € à)ÐA¨TÔ-Aˆà.Ð/IÔJÐØ)¨-Ô8ÀÐDˆØ.Ð/KÔLÈYÔWÐ_cÐcÐð ×%Ò%ØØ& |Ô4ØØ˜tÔ$Ø$ ZÔ0ð ,ðN�×&Ò&µ3°ÀzÔ7RÑ3SÔ3SÐ&ÑTÔTÐTà$Ð%AÔBÀ9ÔMà!5Ø"1Ð2DÔ"EØ!0Ð!HÐ4Hð &ñ 
ô 
ñ	
ØØØØ$Ø ØØð" 7OˆÐ2Ñ3Ø.BˆÐ*Ñ+ð -Ø.Ø*Ø';Ð<`Ô'aÐbkÔ'lð	
ð 
ˆð (¨
Ô3ˆØ"Ð#4Ô5ˆØ!0ˆÐÑØ(ˆˆMÑØÔ+ð 	,ØÐ4Ô5°hÔ?ˆFØ# tÔ'7Ò7ˆNØ)=¸iÔ)HÈÔ)X×)_Ò)_Ñ)aÔ)aˆCÐ%Ñ&Ð&à)+ˆCÐ%Ñ&Øˆ
r:   c                ó²  — |p| j         }|€|€
J d¦   «         ‚|du}|r|nd}t          |t          ¦  «        r|gn|}|r|nd|d<   t          |¦  «        }t	          j        || j        t          j        ¬¦  «        }	|	|d<   |�+| j        j	        |k    r| j         
                    |¬¦  «         |                      | j        ||¦  «        \  }}|du|duk    sJ ‚|                      |¬¦  «        }
|�Ct          t          |¦  «        ¦  «        D ]&}|
                     ||g         ||g         ¦  «         Œ'|
|d	         |<   |                      |d
|¬¦  «        }||fS )aB  Add text, point or box prompts on a single frame. This method returns the inference outputs only on the
        prompted frame.

        Note that text prompts are NOT associated with a particular frame (i.e. they apply
        to all frames). However, we only run inference on the frame specified in `frame_idx`.
        Nz:at least one type of prompt (text, boxes) must be providedr�  rò  r7  r“  r‘  r
  ró  F)r”  r~  )r~  r?   r  ra   r@   r  rI   r™  rL   r  r—  rŒ  rh   r•  r  r–  r�  )r5   r‹  r�  rj   rm   r~  Úuse_textÚ
text_batchÚnr“  r”  rq   rý  s                r9   rõ  z%SAM3VideoSemanticPredictor.add_promptÍ
  s   € ð *ÐA¨TÔ-AˆØÐ 6Ð#5Ð#5Ð7sÑ#5Ô#5Ð5ð ˜tÐ#ˆØÐ-ˆtˆt XˆÝ)¨$µÑ4Ô4Ð>�d�V�V¸$ˆ
Ø19Ð)C¨¨¸tˆ˜Ñ&Ý�
‰OŒOˆÝ”< ¨$¬+½U¼ZÐHÑHÔHˆØ&.ˆ˜
Ñ#ØÐ ¤
Ô 0°DÒ 8Ð 8ØŒJ×"Ò"¨Ð"Ñ-Ô-Ð-ð ×8Ò8¸¼ÈÐQWÑXÔX‰ˆ�Ø˜dÐ"¨°dÐ(:Ò;Ð;Ð;Ð;Ø×1Ò1¸aÐ1Ñ@Ô@ÐØÐÝ�3˜v™;œ;Ñ'Ô'ð Hð H�Ø ×-Ò-¨f°a°S¬k¸6À1À#¼;ÑGÔGÐGÐGØCSˆÐ4Ô5°iÑ@Ø×.Ò.¨yÀ%ÐYhÐ.ÑiÔiˆØ˜#ˆ~Ðr:   c                óà   — t          j        |dk    |d         |¦  «        }| j        j                             |¦  «        }t          j        |dk    |t          j        ||¬¦  «        ¦  «        }|S )zhApplies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region).r   ).NN)r¾   )r@   Úwhereræ  rL   r  Úclamp)r5   r‹   rÄ  r  Úpred_masks_single_scoreÚ!pixel_level_non_overlapping_maskss         r9   r  zISAM3VideoSemanticPredictor._apply_object_wise_non_overlapping_constraintsõ
  sy   € õ #(¤+¨j¸1ªn¸jÈÔ>YÐ[kÑ"lÔ"lÐà,0¬LÔ,>×,aÒ,aØ#ñ-
ô -
Ð)õ ”[Ø-°Ò1ØÝŒK˜
Ð(8Ð9Ñ9Ô9ñ
ô 
ˆ
ð
 Ðr:   r/   rS  r“  r‹  r[  rÐ  r”  r<  r”  r   r  ú	list[Any]r  rf  r  c
           	     ó  — |                       ||||	¬¦  «        }
|i k    r'|                     |                      ¦   «         ¦  «         |                      |||¬¦  «        \  }}|                      |||
||||¬¦  «        \  }}|                     dt          ¦   «         ¦  «        }|                      |||
||¬¦  «        }|                      |
||||¬¦  «        }|d         }|d         }t          j
        |d	         ¦  «        |d
         dœ}|j        d         dk    rj|                     ¦   «                              ¦   «         }|d         }|d         |                              t          t          ||¦  «        ¦  «        ¦  «         |||||||fS )a°  This function handles one-step inference for the DenseTracking model in an SPMD manner. At a high-level, all
        GPUs execute the same function calls as if it's done on a single GPU, while under the hood, some
        function calls involve distributed computation based on sharded SAM2 states.

        - `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs
        - `tracker_states_local` holds the local masklet information in this GPU shard
        - `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs
          it contains both global and local masklet information
        )r/   r“  r”  r  )r‹  r  r  )r‹  r”  Údet_outÚtracker_low_res_masks_globalÚtracker_obj_scores_globalr  r  Úreconditioned_obj_ids)r‹  rÐ  r(  r  Útracker_update_plan)r(  r)  r  r,  r+  rû  rþ  Únum_objÚnum_obj_dropped_due_to_limit)Únum_obj_trackedÚnum_obj_droppedr   rÓ  r  )Úrun_backbone_and_detectionr*   Ú_initialize_metadataÚrun_tracker_propagationÚ!run_tracker_update_planning_phaser³  rÀ  Ú"run_tracker_update_execution_phaseÚbuild_outputsrB   r   rf   r­  r  r  r³   )r5   r/   r“  r‹  rÐ  r”  r”  r  r  r  r(  r)  r*  r,  r  r+  r  r÷  rû  rþ  r  Útracker_obj_idss                         r9   r  z/SAM3VideoSemanticPredictor._det_track_one_frame  s  € ð. ×1Ò1ØØØ-Ø!5ð	 2ñ 
ô 
ˆð ! BÒ&Ð&à!×(Ò(¨×)BÒ)BÑ)DÔ)DÑEÔEÐEØBF×B^ÒB^ØØ!5Ø"7ð C_ñ C
ô C
Ñ?Ð$Ð&?ð 59×4ZÒ4ZØØØØ)EØ&?Ø"7Ø!5ð 5[ñ 5
ô 5
Ñ1ÐÐ1ð !4× 7Ò 7Ð8OÕQTÑQVÔQVÑ WÔ WÐð $(×#JÒ#JØØ!ØØ!5Ø 3ð $Kñ $
ô $
Ð ð ×+Ò+ØØ)EØ"7Ø 3Ø"7ð ,ñ 
ô 
ˆð /Ð/@ÔAˆØ,¨_Ô=ˆõ  "œvÐ&:¸9Ô&EÑFÔFØ2Ð3QÔRð
ð 
ˆð
 %Ô*¨1Ô-°Ò1Ð1à(A×(IÒ(IÑ(KÔ(K×(RÒ(RÑ(TÔ(TÐ%Ø3°IÔ>ˆOØ Ð!EÔFÀyÔQ×XÒXÝ•S˜Ð*CÑDÔDÑEÔEñô ð ð ØØØ$Ø ØØ%ð
ð 	
r:   çš™™™™™™?c                óœ   — |                       d¦  «        \  }}}}||z   dz  }||z   dz  }||k    |d|z
  k     z  ||k    z  |d|z
  k     z  }|S )z§Suppress detections too close to image edges (for normalized boxes).

        boxes: (N, 4) in xyxy format, normalized [0,1]
        margin: fraction of image
        r<   r>   rŽ   )Úunbind)	r€   ÚmarginÚx_minÚy_minÚx_maxÚy_maxÚx_cÚy_cræ   s	            r9   Ú&_suppress_detections_close_to_boundaryzASAM3VideoSemanticPredictor._suppress_detections_close_to_boundaryp  sn   € ð &+§\¢\°"Ñ%5Ô%5Ñ"ˆˆu�e˜UØ�u‰} Ñ!ˆØ�u‰} Ñ!ˆØ�f’  s¨V¡|Ò!3Ñ4¸¸fºÑEÈÈsÐU[É|ÒI[Ñ\ˆàˆr:   c                óÀ   — |                       |¦  «        }| j                             |||¬¦  «        }|                      ||¦  «        }|                      |¦  «         |S )z.Run backbone and detection for a single frame.r’  )r{   rL   r˜  Ú_extract_detection_outputsÚ_cache_backbone_features)r5   r/   r“  r”  r  r0   Úsam3_image_outr(  s           r9   r1  z5SAM3VideoSemanticPredictor.run_backbone_and_detection~  sl   € ð ×'Ò'¨Ñ+Ô+ˆØœ×5Ò5Ø!¨HÐGWð 6ñ 
ô 
ˆð ×1Ò1°.ÐBVÑWÔWˆØ×%Ò% nÑ5Ô5Ð5Øˆr:   c                ó¤  — |d                               d¦  «                             ¦   «         }|s|dz
  }t          j        t	          t          |j        d         ¦  «        ¦  «        |j        |j        ¬¦  «        dd…df          	                    |¦  «        }|d         }|d         }|| j
        k    }||         ||         ||         ||         d	œS )
z%Extract and filter detection outputs.r§  r<   g    „×—Ar   r�   NÚpred_boxes_xyxyr‹   )Úbboxr?  rç   r   )r˜   r­  r@   r¥   r  r  rf   r�   rI   r®  rÎ  )r5   rF  r  Ú
pred_probsr²  rH  r‹   ræ   s           r9   rD  z5SAM3VideoSemanticPredictor._extract_detection_outputsŠ  së   € à# MÔ2×:Ò:¸2Ñ>Ô>×FÒFÑHÔHˆ
Ø#ð 	*Ø# cÑ)ˆJå”<Ý•�zÔ'¨Ô*Ñ+Ô+Ñ,Ô,ØÔ"ØÔ$ð
ñ 
ô 
ð ˆ!ˆ!ˆTˆ'ô	÷ ’9˜ZÑ(Ô(ð	 	ð )Ð):Ô;ˆØ# LÔ1ˆ
à˜DÔ:Ò:ˆà# DÔ)Ø˜tÔ$Ø  Ô&Ø˜D”>ð	
ð 
ð 	
r:   c                ó  — | j         j        j        }|d         d         }|                     |d         d         ¦  «        |                     |d         d         ¦  «        |d         d         g}|d         |d         |d	œ}|| j         _        d
S )z'Build and cache SAM2 backbone features.rn  Úsam2_backbone_outÚbackbone_fpnr   r   r>   r<   Úvision_pos_enc)Úvision_featuresrN  rM  N)ræ  rL   ry  Úconv_s0Úconv_s1rn  )r5   rF  ry  rq  Útracker_backbone_fpnÚtracker_backbone_outs         r9   rE  z3SAM3VideoSemanticPredictor._cache_backbone_features¡  s    € àœ<Ô-Ô>ÐØ˜~Ô.Ð/BÔCˆà×$Ò$ U¨>Ô%:¸1Ô%=Ñ>Ô>Ø×$Ò$ U¨>Ô%:¸1Ô%=Ñ>Ô>Ø�.Ô! !Ô$ð 
Ðð  4°BÔ7Ø#Ð$4Ô5Ø0ð 
ð  
Ðð %9ˆŒÔ!Ð!Ð!r:   údict[str, np.ndarray]c                óÌ   — |                       ||¬¦  «        \  }}}t          j        ||d         k    ¦  «        s$J d                     ||d         ¦  «        ¦   «         ‚|}|}||fS )zGRun the tracker propagation phase for a single frame in an SPMD manner.©r‹  rÓ  z{} != {})Ú&_propogate_tracker_one_frame_local_gpurB   rt   rõ   )	r5   r‹  r  r  Úobj_ids_localÚlow_res_masks_localÚobj_scores_localÚlow_res_masks_globalÚobj_scores_globals	            r9   r3  z2SAM3VideoSemanticPredictor.run_tracker_propagation²  sœ   € ð @D×?jÒ?jØ ¨Ið @kñ @
ô @
Ñ<ˆÐ*Ð,<õ Œv�mÐ'<¸YÔ'GÒGÑHÔHð 	
ð 	
È*×J[ÒJ[ØÐ0°Ô;ñK
ô K
ñ 	
ô 	
ÐHð  3ÐØ,ÐØ#Ð%6Ð6Ð6r:   r(  údict[str, torch.Tensor]Útrk_id_to_max_iou_high_conf_detú	list[int]rñ  r*  c                óª  — |                      ¦   «         D �]<\  }}|d         ||dz   …         }	t          j        |	                     d¦  «        | j        dd¬¦  «        dk    }
d}t          ¦   «         }t          j        |d         |k    ¦  «        d                              ¦   «         }||         }t          |¦  «        D ]l\  }}||d         v r]||k    rWt          j        d	|› d
|› d|d         › d�¦  «         | j                             ||||
¬¦  «         |                     |¦  «         Œm|D ]"}| j                             ||         ¦  «         Œ#�Œ>|S )z=Recondition masklets based on new high-confidence detections.r?  r   r°   Frõ  r   rÈ  rÓ  zAdding new mask for track ú
 at frame z
. Objects z are all reconditioned.©r~  r‹  rŠ  rl   )r  rµ   r¶   r;  rî  rÀ  rB   r"  Úitemr  r   Údebugræ  r™  rN  rš  )r5   r‹  r(  r^  r  rñ  r*  Ú
trk_obj_idÚdet_idxÚnew_maskÚnew_mask_binaryÚHIGH_CONF_THRESHÚreconditioned_states_idxr·  Ú	obj_scoreÚ	state_idxr~  râ   s                     r9   Ú_recondition_maskletsz0SAM3VideoSemanticPredictor._recondition_maskletsÈ  sÅ  € ð $C×#HÒ#HÑ#JÔ#Jð 	Uñ 	UÑˆJ˜Ø˜v” w°¸1±Ð'<Ô=ˆHå”˜h×0Ò0°Ñ3Ô3¸$Ô:LÐS]ÐmrÐsÑsÔsÐvwÒwð ð  #ÐÝ'*¡u¤uÐ$Ý”hÐ/°	Ô:¸jÒHÑIÔIÈ!ÔL×QÒQÑSÔSˆGØ1°'Ô:ˆIÝ.7Ð8LÑ.MÔ.Mð <ð <Ñ*�	˜?à /°)Ô"<Ð<Ð<ð "Ð$4Ò4Ð4å”Lð T°Zð  Tð  TÈ9ð  Tð  TÐ`oÐpyÔ`zð  Tð  Tð  Tñô ð ð ”L×0Ò0Ø(7Ø"+Ø)Ø-ð	 1ñ ô ð ð -×0Ò0°Ñ;Ô;Ð;øà/ð Uð U�Ø”×9Ò9Ð:NÈsÔ:SÑTÔTÐTÐTñUà#Ð#r:   r)  c           
     ó(  — t          |d         ¦  «        t          |d         ¦  «        t          |d         ¦  «        t          |d         ¦  «        t          |d         ¦  «        i t          |d         ¦  «        dœ}t          ¦   «         }	|d         }
|d	                              ¦   «                              ¦   «                              ¦   «         }|d
                              ¦   «                              ¦   «                              ¦   «         }|d         }|                      |
|||d         ¬¦  «        \  }}}}}| j        rG|                      ||         ¦  «        }||                     ¦   «                              ¦   «                  }t          j	        |d         ¦  «        }t          |¦  «        }d}||z   | j        k    rlt          j        d| j        ›d|›d|›�¦  «         | j        |z
  }||z
  }|                      |||¦  «        }t          |¦  «        |k    sJ ‚t          |¦  «        }|d         dz   t          j        |¦  «        z   }t          |d         ¦  «        }t!          | d¦  «        r| j        r |                      |||||||¬¦  «        \  }}nt          ¦   «         }||d<   ||||||||	dœ}d}| j        dk    �r¸t          |¦  «        dk    �r¤|                     ¦   «         D �]Ž\  }}|d         |         }|d	         |         } 	 t+          |d         ¦  «                             |¦  «        }!n# t.          $ r Y ŒXw xY w||!         }"|"dk    }#|# 	                    ¦   «                              ¦   «         }$|$dk    rŒ—t3          |#                     d¦  «        ¦  «                             d¦  «        }%|"j        dd…         \  }&}'t;          j        |%d         |'z  |%d         |&z  |%d         |'z  |%d         |&z  g|%j        ¬¦  «        }(|                     d¦  «        })|(                     d¦  «        }*tA          |)|*¦  «        d         }+|+| j        k     r"| | j!        k    rd}|	 "                    |¦  «         �Œ�| j#        dk    o || j#        z  dk    ot          |¦  «        dk    },|,s|r|  $                    ||||||¦  «         | %                    d¦  «        }-|-dk    r<t!          | d¦  «        r| j        r%| j&        dk    r|  '                    ||||||¦  «        }|-dk    r|  (                    |||¬¦  «         |d         }.t          |¦  «        dk    rt          j)        |.|g¦  «        }.t          |¦  «        dk    r+t          j*        |.t+          |¦  «        ¦  «        }/|.|/          }.|.|d<   t          |.¦  «        |d<   t          |¦  «        dk    r¾|d          +                    tY          |||         ¦  «        ¦  «         |d          +                    tY          |||         ¦  «        ¦  «         |d         |          +                    tY          |||         ¦  «        ¦  «         t[          |d         t          j-        |¦  «        ¦  «        |d<   |D ]:}0d|d         |0<   d|d         |         |0<   |d           .                    |0d¦  «         Œ;d|v sJ ‚| j/        r1|  0                    |d         |d         |d         ||¬!¦  «        }1|1|d<   ||fS )"zKRun the tracker update planning phase for a single frame in an SPMD manner.rÓ  r-  rû  rþ  r  Ú
max_obj_id)rÓ  r-  rû  rþ  r  Úobj_id_to_last_occludedro  r?  rç   r   rI  )Ú	det_masksÚdet_scores_npÚ	trk_masksÚtrk_obj_idsr   zhitting self.max_num_objects=z with new_det_num=z and prev_obj_num=r   r  Ú_warm_up_complete)r‹  r”  Údet_to_matched_trk_obj_idsÚnew_det_obj_idsÚempty_trk_obj_idsÚunmatched_trk_obj_idsr  )Únew_det_fa_indsrw  ry  rv  Úobj_ids_newly_removedr.  r^  r+  Fre   Nr>   r=   r¯   TrÊ  )rn  g     ˆÃÀrp  )r  Úobj_ids_all_gpu_prevÚobj_ids_all_gpu_updatedrv  rw  )1r   rÀ  rO   r8  r9  Ú_associate_det_trkrÚ  rB  rB   r   ra   rß  r   rð   Ú_drop_new_det_with_obj_limitr  Úhasattrru  Ú_process_hotstarträ  r  r  ÚindexÚ
ValueErrorrc  r   r;  r˜   rf   r@   r¥   rI   r   rå  rN  rá  rm  rï  rÙ  Ú/_suppress_overlapping_based_on_recent_occlusionÚ_tracker_update_memoriesÚconcatenateÚisinr*   r³   r¾   rs   râ  Ú"update_masklet_confirmation_status)2r5   r‹  r”  r(  r)  r*  r  r  r  r+  Údet_mask_predsrr  Ú
det_cls_npÚdet_bbox_xyxyrz  ry  rv  r^  rx  ræ   Úprev_obj_numÚnew_det_numr.  Únew_det_num_to_keeprw  Úmetadata_newr{  r,  Úshould_recondition_ioure  rf  Údet_boxÚ	det_scoreÚtrk_idxÚtracker_maskÚmask_binaryÚ	mask_areaÚtracker_box_pixelsÚmask_heightÚ
mask_widthÚtracker_box_normalizedÚdet_box_batchÚtracker_box_batchr»   Úshould_recondition_periodicr�  Úupdated_obj_ids_this_gpuÚ
is_removedrŠ  r  s2                                                     r9   r4  z<SAM3VideoSemanticPredictor.run_tracker_update_planning_phaseò  s9  € õ  Ð 5°iÔ @ÑAÔAÝÐ 5°iÔ @ÑAÔAÝ'Ð(=Ð>OÔ(PÑQÔQÝ%Ð&;¸OÔ&LÑMÔMÝ2:Ð;PÐQuÔ;vÑ2wÔ2wØ')Ý"Ð#8¸Ô#FÑGÔGð 
ð  
Ðõ !$¡¤Ðð (/¨v¤ˆØ$+¨HÔ$5×$;Ò$;Ñ$=Ô$=×$AÒ$AÑ$CÔ$C×$IÒ$IÑ$KÔ$KˆØ!(¨¤×!5Ò!5Ñ!7Ô!7×!;Ò!;Ñ!=Ô!=×!CÒ!CÑ!EÔ!Eˆ
Ø&-¨f¤oˆð ×#Ò#Ø$Ø'Ø2Ø-¨iÔ8ð	 $ñ 
ô 
ñ	
ØØ!Ø&Ø+Øð Ô.ð 	BØ×>Ò>¸}È_Ô?]Ñ^Ô^ˆDØ-¨d¯hªh©j¬j×.>Ò.>Ñ.@Ô.@ÔAˆOõ ”vÐ3°IÔ>Ñ?Ô?ˆÝ˜/Ñ*Ô*ˆØ'(Ð$Ø˜+Ñ%¨Ô(<Ò<Ð<ÝŒNÐe dÔ&:ÐeÐeÀ;ÐeÐeÐVbÐeÐeÑfÔfÐfØ"&Ô"6¸Ñ"EÐØ+6Ð9LÑ+LÐ(Ø"×?Ò?ÀÐQ^Ð`sÑtÔtˆOÝ�Ñ'Ô'Ð+>Ò>Ð>Ð>Ð>Ý˜oÑ.Ô.ˆKð 0°Ô=ÀÑAÅBÄIÈkÑDZÔDZÑZˆõ  Ð 5°jÔ AÑBÔBˆÝ�tÐ0Ñ1Ô1ð 	*°TÔ5Kð 	*Ø26×2HÒ2HØ#ØØ+EØ /Ø"3Ø&;Ø%ð 3Iñ 3ô 3Ñ/Ð! < <õ %(¡E¤EÐ!Ø+7Ð˜ZÑ(ð  /Ø.à%:Ø*DØ%:Ø,HØ/NØ%:ð

ð 

Ðð "'Ðð Ô.°Ò2Ñ2µsÐ;ZÑ7[Ô7[Ð^_Ò7_Ñ7_Ø'F×'LÒ'LÑ'NÔ'Nð $:ñ $:Ñ#�
˜GØ! &œ/¨'Ô2�Ø# HÔ-¨gÔ6�	ðÝ"Ð#8¸Ô#CÑDÔD×JÒJÈ:ÑVÔV�G�GøÝ!ð ð ð Ø�Hðøøøð  <¸GÔD�Ø*¨QÒ.�Ø'ŸOšOÑ-Ô-×2Ò2Ñ4Ô4�	à ’>�>Øõ &9¸×9NÒ9NÈqÑ9QÔ9QÑ%RÔ%R×%ZÒ%ZÐ[\Ñ%]Ô%]Ð"Ø*6Ô*<¸R¸S¸SÔ*AÑ'�˜ZÝ).¬à*¨1Ô-°
Ñ:Ø*¨1Ô-°Ñ;Ø*¨1Ô-°
Ñ:Ø*¨1Ô-°Ñ;ð	ð .Ô4ð*ñ *ô *Ð&ð !(× 1Ò 1°!Ñ 4Ô 4�Ø$:×$DÒ$DÀQÑ$GÔ$GÐ!Ý˜mÐ->Ñ?Ô?ÀÔB�à˜Ô<Ò<Ð<ÀÈdÔNpÒApÐApØ-1Ð*Ø)×-Ò-¨jÑ9Ô9Ð9ùð Ô,¨qÒ0ð 9Ø˜DÔ<Ñ<ÀÒAð9åÐ3Ñ4Ô4°qÒ8ð 	$ð 'ð 	Ð*@ð 	Ø×&Ò&ØØØ/Ø$Ø%Ø)ñô ð ð 2×6Ò6°qÑ9Ô9ˆ
à˜ŠNˆNÝ˜TÐ#6Ñ7Ô7ð Ø;?Ô;Qð àÔMÐPSÒSÐSð ,0×+_Ò+_ØØ,Ø%Ø$Ø%Øñ,ô ,Ð(ð ˜Š>ˆ>Ø×)Ò)Ð*>À	ÐYuÐ)ÑvÔvÐvð $8¸	Ô#BÐ ÝˆÑÔ !Ò#Ð#Ý')¤~Ð7OÐQ`Ð6aÑ'bÔ'bÐ$ÝÐ$Ñ%Ô%¨Ò)Ð)ÝœÐ!9½4Ð@UÑ;VÔ;VÑWÔWˆJØ'?ÀÀÔ'LÐ$Ø*BÐ˜YÑ'Ý*-Ð.FÑ*GÔ*GÐ˜YÑ'åˆÑÔ !Ò#Ð#Ø Ð!2Ô3×:Ò:½3¸ÐP]Ð^mÔPnÑ;oÔ;oÑpÔpÐpØ  Ô1×8Ò8½¸_ÈjÐYhÔNiÑ9jÔ9jÑkÔkÐkà Ð!EÔFÀyÔQ×XÒXÝ�O ]°?Ô%CÑDÔDñô ð õ 25Ð5IÈ,Ô5WÕY[ÔY_Ð`oÑYpÔYpÑ1qÔ1qÐ  Ñ.ð ,ð 	Nð 	NˆFØ>BÐ Ð!2Ô3°FÑ;Ø\`Ð Ð!EÔFÀyÔQÐRXÑYØ Ð!:Ô;×?Ò?ÀÈÑMÔMÐMÐMàÐ1Ð1Ð1Ð1Ð1ØÔ+ð 	8Ø×>Ò>Ø-¨jÔ9Ø%:¸9Ô%EØ(<¸YÔ(GØ+EØ /ð ?ñ ô ˆHð 08Ð  Ñ,à"Ð$8Ð8Ð8s   Ì(L;Ì;
MÍMr  r{  úset[int]c                óø  ‡ ‡‡‡‡— ‰d         }|dk    Š|                      d¦  «        }|dk    rËt          |¦  «        |k    sJ dt          |¦  «        › d|› �¦   «         ‚t          j        ˆˆˆ ˆfd„|D ¦   «         d¬¦  «        }	‰                      ‰|	|||¦  «        }
‰                     d¬¦  «         }||
z  }|	                     ¦   «         Š|‰|<   ˆfd„t          |¦  «        D ¦   «         |d	<   ‰ j        ||
<   |S )
a#  Suppress overlapping masks based on the most recent occlusion information. If an object is removed by
        hotstart, we always suppress it if it overlaps with any other object.

        Args:
            frame_idx (int): The current frame index.
            tracker_low_res_masks_global (torch.Tensor): The low-resolution masks for the current frame.
            tracker_metadata_prev (dict[str, Any]): The metadata from the previous frame.
            tracker_metadata_new (dict[str, Any]): The metadata for the current frame.
            obj_ids_newly_removed (set[int]): The object IDs that have been removed.
            reverse (bool): Whether the tracking is in reverse order.

        Returns:
            (torch.Tensor): The updated low-resolution masks with some objects suppressed.
        rÓ  r   zMismatch in number of objects: ú vs c                ó²   •— g | ]S}‰d                                |t          j        d|‰vr‰j        n‰j        ‰j        t          j        ¬¦  «        ¦  «        ‘ŒTS )rp  r5  )rð  rI   r�   )r³  r@   rø  ÚNEVER_OCCLUDEDÚALWAYS_OCCLUDEDrI   r™  )r[   rŠ  Ú#binary_tracker_low_res_masks_globalr{  r5   r  s     €€€€r9   r^   z^SAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusion.<locals>.<listcomp>è  s€   ø€ ð ð ð ð ð *Ð*CÔD×HÒHØÝœ
Ø à7=ÐEZÐ7ZÐ7Z Ô 3Ð 3Ð`dÔ`tà#FÔ#MÝ"'¤*ðñ ô ñ
ô 
ðð ð r:   r  ©r<   re   c                ó2   •— i | ]\  }}|‰||d z   …         “ŒS r5  rY   )r[   r·  rŠ  Úlast_occluded_news      €r9   ú
<dictcomp>z^SAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusion.<locals>.<dictcomp>  s;   ø€ ð ?ð ?ð ?ÙETÀWÈf�Ð)¨'°G¸a±KÐ*?Ô@ð?ð ?ð ?r:   rp  )	rï  ra   r@   r¹   Ú8_get_objects_to_suppress_based_on_most_recently_occludedr  rè  r  ÚNO_OBJ_LOGIT)r5   r‹  r)  r  r  r{  r”  Úobj_ids_globalr�  Úlast_occluded_prevÚto_suppressÚis_obj_occludedÚis_obj_occluded_or_suppressedr¦  r©  s   `  ` `       @@r9   r„  zJSAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusionÉ  s„  øøøøø€ ð. /¨yÔ9ˆØ.JÈQÒ.NÐ+Ø1×6Ò6°qÑ9Ô9ˆ
Ø˜Š>ˆ>Ý�~Ñ&Ô&¨*Ò4Ð4Ð4ØWµ#°nÑ2EÔ2EÐWÐWÈ:ÐWÐWñ 5Ô4Ð4õ "'¤ðð ð ð ð ð ð ð #1ðñ ô ð ð"ñ "ô "Ðð" ×WÒWØ3Ø"ØØØñô ˆKð !D× GÒ GÈHÐ GÑ UÔ UÐVˆOØ,;¸kÑ,IÐ)Ø 2× 8Ò 8Ñ :Ô :ÐØ?HÐÐ;Ñ<ð?ð ?ð ?ð ?ÝXaÐbpÑXqÔXqð?ñ ?ô ?Ð Ð!:Ñ;ð
 9=Ô8IÐ(¨Ñ5à+Ð+r:   r,  c                ó.  — |d         }|d         }|}|}	|d         }
t          |	¦  «        dk    r<t          j        |	¦  «        }|d         |         }|                      |||||¬¦  «        }t          |
¦  «        dk    r|                      ||
¦  «         |S )zEExecute the tracker update plan for a single frame in an SPMD manner.rz  rw  r{  r   r?  )r‹  rÐ  r%  Únew_obj_masksr  )ra   r@   rG   Ú_tracker_add_new_objectsÚ_tracker_remove_objects)r5   r‹  rÐ  r(  r  r,  rz  rw  Únew_det_obj_ids_localÚnew_det_fa_inds_localr{  Únew_det_fa_inds_local_tÚnew_det_maskss                r9   r5  z=SAM3VideoSemanticPredictor.run_tracker_update_execution_phase  sÈ   € ð ':Ð:KÔ&LˆØ&9Ð:KÔ&Lˆà,;ÐØ,;ÐØ*=Ð>UÔ*VÐõ Ð$Ñ%Ô%¨Ò)Ð)Ý&+Ô&6Ð7LÑ&MÔ&MÐ#Ø*1°&¬/Ð:QÔ*RˆMà#'×#@Ò#@Ø#Ø%Ø1Ø+Ø%9ð $Añ $ô $Ð õ Ð$Ñ%Ô%¨Ò)Ð)Ø×(Ò(Ð)=Ð?TÑUÔUÐUà#Ð#r:   r+  ú
set | Nonec                ó˜  — |d         }|d         }i }|d         }|                      d¦  «        }	t          |¦  «        t          |	¦  «        k    sJ ‚t          ||	¦  «        D ]
\  }
}|||
<   Œt          j        |¦  «        }| d         |                               d¦  «        }t          |¦  «        t          |¦  «        k    sJ ‚t          ||¦  «        D ]
\  }
}|||
<   Œ|�it          |¦  «        dk    rV|                     di ¦  «        }|D ]=}
|                     |
¦  «        }|�$| d         |                               d¦  «        ||
<   Œ>|S )	z-Build the output masks for the current frame.rz  rw  rÓ  r   r?  Nr   r^  )r;  ra   r³   r@   rG   r³  )r(  r)  r  r,  r+  rz  rw  r÷  Úexisting_masklet_obj_idsÚexisting_masklet_logitsrŠ  r?  Únew_det_fa_inds_tÚnew_det_low_res_masksr^  rf  s                   r9   r6  z(SAM3VideoSemanticPredictor.build_outputs3  s“  € ð ':Ð:KÔ&LˆØ&9Ð:KÔ&LˆØˆð $9¸Ô#CÐ Ø">×"HÒ"HÈÑ"KÔ"KÐÝÐ+Ñ,Ô,µÐ4KÑ0LÔ0LÒLÐLÐLÐLÝÐ 8Ð:QÑRÔRð 	*ð 	*‰LˆF�DØ%)ˆN˜6Ñ"Ð"õ "Ô,¨_Ñ=Ô=ÐØ '¨¤Ð0AÔ B× LÒ LÈQÑ OÔ OÐÝ�?Ñ#Ô#¥sÐ+@Ñ'AÔ'AÒAÐAÐAÐAÝ Ð1FÑGÔGð 	*ð 	*‰LˆF�DØ%)ˆN˜6Ñ"Ð"ð !Ð,µÐ5JÑ1KÔ1KÈaÒ1OÐ1OØ.A×.EÒ.EÐFgÐikÑ.lÔ.lÐ+à/ð Sð S�Ø9×=Ò=¸fÑEÔE�àÐ&Ø-4°V¬_¸WÔ-E×-OÒ-OÐPQÑ-RÔ-R�N 6Ñ*øàÐr:   Úbinary_low_res_masksÚlast_occludedrÓ  rR  c                óª  — |j         t          j        k    sJ d|j         › �¦   «         ‚t          j        |                     d¦  «        |j        t          j        ¬¦  «        }t          |¦  «        dk    r|S t          |                     d¦  «        |                     d¦  «        ¦  «        }|| j	        k    }t          j
        |d¬¦  «        }	|                     d¦  «        }
|                     d¦  «        }|st          j        nt          j        }|	 ||
|¦  «        z  |dk    z  }|	 |||
¦  «        z  |
dk    z  }|                     d¬¦  «        |                     d¬¦  «        z  }t          j        d¦  «        �rT|��Q|                     ¦   «                              ¦   «         }|                     ¦   «                              ¦   «         }|                     ¦   «                              ¦   «         }|j        d         }t)          |¦  «        D ]Y}t)          |¦  «        D ]G}|||f         r;t          j        d	|›d
||         › d||         › d||         › d||         › �
¦  «         ŒHŒZt)          |¦  «        D ]Y}t)          |¦  «        D ]G}|||f         r;t          j        d	|›d
||         › d||         › d||         › d||         › �
¦  «         ŒHŒZ|S )NzExpected boolean tensor, got r   r7  r   )Údiagonalr<   r  rË  z
frame_idx=z: Suppressing obj z last occluded z in favor of )r�   r@   r<  r  rï  rI   ra   r   rˆ   rÙ  Útriur;  rŸ  Últr  r   ÚisEnabledForr8  r9  rf   r  rd  )r5   rÀ  rÁ  rÓ  r‹  r”  r¯  r»   Úmask_iou_threshÚoverlapping_pairsÚlast_occ_expanded_iÚlast_occ_expanded_jÚcmp_opÚsuppress_i_maskÚsuppress_j_maskr�  rq   Újs                     r9   r«  zSSAM3VideoSemanticPredictor._get_objects_to_suppress_based_on_most_recently_occludedZ  s¼  € ð $Ô)­U¬ZÒ7Ð7Ð7Ð9uÐYmÔYsÐ9uÐ9uÑ7Ô7Ð7Ý”kØ ×%Ò% aÑ(Ô(Ø'Ô.Ý”*ð
ñ 
ô 
ˆõ
 ˆw‰<Œ<˜1ÒÐØÐåÐ+×3Ò3°AÑ6Ô6Ð8L×8TÒ8TÐUVÑ8WÔ8WÑXÔXˆð  Ô!^Ò^ˆÝ!œJ ÀÐCÑCÔCÐà+×5Ò5°aÑ8Ô8ÐØ+×5Ò5°aÑ8Ô8Ðà!(Ð6•”�­e¬hˆàØˆfÐ(Ð*=Ñ>Ô>ñ?à" RÒ'ñ)ð 	ð ØˆfÐ(Ð*=Ñ>Ô>ñ?à" RÒ'ñ)ð 	ð &×)Ò)¨aÐ)Ñ0Ô0°?×3FÒ3FÈ1Ð3FÑ3MÔ3MÑMˆõ Ô˜rÑ"Ô"ñ 	 yÑ'<Ø-×1Ò1Ñ3Ô3×9Ò9Ñ;Ô;ˆOØ-×1Ò1Ñ3Ô3×9Ò9Ñ;Ô;ˆOØ)×-Ò-Ñ/Ô/×5Ò5Ñ7Ô7ˆMð )Ô.¨qÔ1ˆJõ ˜:Ñ&Ô&ð ð �Ý˜zÑ*Ô*ð ð �AØ& q¨! tÔ,ð Ýœð e˜yð  eð  e¸WÀQ¼Zð  eð  eÐXeÐfgÔXhð  eð  eÐw~ð  @Aô  xBð  eð  eð  S`ð  abô  Scð  eð  eñô ð øðõ ˜:Ñ&Ô&ð ð �Ý˜zÑ*Ô*ð ð �AØ& q¨! tÔ,ð Ýœð e˜yð  eð  e¸WÀQ¼Zð  eð  eÐXeÐfgÔXhð  eð  eÐw~ð  @Aô  xBð  eð  eð  S`ð  abô  Scð  eð  eñô ð øðð Ðr:   Úinference_statesc                ó¸  — g }g }g }|D ]¸}t          |d         ¦  «        dk    rŒ| j                             ||¬¦  «        \  }}}	t          |t          ¦  «        sJ ‚|                     |¦  «         |                     |                     d¦  «        ¦  «         |                     |	                     d¦  «        ¦  «         Œ¹t          |¦  «        dk    rBt          j	        |d¬¦  «        }
t          j	        |d¬¦  «        }|
                     d¦  «        }
n@t          j
        dg| j        d         ¢R d| j        iŽ}
t          j
        d| j        ¬¦  «        }||
|fS )zaInference_states: list of inference states, each state corresponds to a different set of objects.rÓ  r   rV  r   r  rI   r¯   )ra   ræ  rÅ  r?   r  Úextendr¸   r˜   r@   r¹   r  ra  rI   )r5   rÏ  r‹  rX  Úlow_res_masks_listÚobj_scores_listr~  Úout_obj_idsÚout_low_res_masksÚout_obj_scoresrY  rZ  s               r9   rW  zASAM3VideoSemanticPredictor._propogate_tracker_one_frame_local_gpuž  s„  € àˆØÐØˆØ/ð 
	>ð 
	>ˆOÝ�? 9Ô-Ñ.Ô.°!Ò3Ð3Øà=A¼\×=\Ò=\Ø¨9ð >]ñ >ô >Ñ:ˆKÐ*¨Nõ ˜k­4Ñ0Ô0Ð0Ð0Ð0Ø× Ò  Ñ-Ô-Ð-Ø×%Ò%Ð&7×&?Ò&?ÀÑ&BÔ&BÑCÔCÐCØ×"Ò" >×#9Ò#9¸!Ñ#<Ô#<Ñ=Ô=Ð=Ð=õ Ð!Ñ"Ô" QÒ&Ð&Ý"'¤)Ð,>ÀAÐ"FÑ"FÔ"FÐÝ$œy¨¸aÐ@Ñ@Ô@ÐØ"5×"=Ò"=¸aÑ"@Ô"@ÐÐå"'¤+¨aÐ"]°$Ô2EÀaÔ2HÐ"]Ð"]Ð"]ÐQUÔQ\Ð"]Ð"]ÐÝ$œ{¨1°T´[ÐAÑAÔAÐàÐ1Ð3CÐCÐCr:   rq  rr  ú
np.ndarrayrs  rt  c           	     óô
  — | j         }| j        }| j        }|                     ¦   «         s
J d¦   «         ‚|                     ¦   «         s
J d¦   «         ‚|                     d¦  «        t          |¦  «        k    s0J d|                     d¦  «        › dt          |¦  «        › �¦   «         ‚|                     d¦  «        dk    rpt          j        |                     d¦  «        ¦  «        }t          j        g t          j	        ¦  «        }	t          j        g t          j	        ¦  «        }
i }i }||	|||
fS |                     d¦  «        dk    ryt          j        g t          j	        ¦  «        }|dk     
                    d¬¦  «                             ¦   «                              ¦   «         }||         }	||          }
i }i }||	|||
fS |j        dd…         |j        dd…         k    rÛt          j        |j        dd…         ¦  «        t          j        |j        dd…         ¦  «        k     rLt          j        |                     d	¦  «        |j        dd…         d
d¬¦  «                             d	¦  «        }nKt          j        |                     d	¦  «        |j        dd…         d
d¬¦  «                             d	¦  «        }|dk    }|dk    }t'          |                     d	¦  «                             ¦   «         |                     d	¦  «                             ¦   «         ¦  «        }|                     ¦   «                              ¦   «         }| j        rqddlm} d	|z
  } ||¦  «        \  }}t          j        |                     d¦  «        t4          ¬¦  «        }t7          ||¦  «        D ]\  }}|||f         |k    rd||<   Œn||k     
                    d¬¦  «        }| 
                    d¬¦  «                             ¦   «                              ¦   «         }t          j        || ¦  «        }||         }	||          }
t          j        ||k    t          j        t          j
        ||k    d	¬¦  «        ¦  «        ¦  «        }t          j        |¦  «        d         }i }i }t          j        |d	¬¦  «        }|| j         k    | z  }t          j!        |d	¬¦  «        | j"        k    }tG          t          j        ||z  ¦  «        d         ¦  «        }tI          |                     d¦  «        ¦  «        D ]D}|||dd…f         |k             ||<   ||v r%|||                   %                    ¦   «         }|||<   ŒE||	|||
fS )aj  Match detections on the current frame with the existing masklets.

        Args:
            det_masks: (N, H, W) tensor of predicted masks
            det_scores_np: (N,) array of detection scores
            trk_masks: (M, H, W) tensor of track masks
            trk_obj_ids: (M,) array of object IDs corresponding to trk_masks

        Returns:
            new_det_fa_inds: array of new object indices.
            unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched to any detections on this
                frame (for unmatched, we only count masklets with >0 area)
            det_to_matched_trk_obj_ids: dict[int, np.ndarray]: mapping from detector's detection indices to the list of
                matched tracklet object IDs
            empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
        z'float tensor expected (do not binarize)r   z7trk_masks and trk_obj_ids should have the same length, r¢  r—  r  re   Nr   r°   Frõ  )Úlinear_sum_assignmentr”   Tr™   )&rÐ  rÑ  rÒ  Úis_floating_pointrï  ra   rB   r  r´   Úint64r  r8  r9  rf   Úprodrµ   r¶   r;  r˜   r   rˆ   rO   rÜ  Úultralytics.utils.opsrÙ  r  r<  r³   Úlogical_andÚlogical_notÚnonzeroÚargmaxri  r¾   ÚHIGH_IOU_THRESHrÀ  r  rc  ) r5   rq  rr  rs  rt  Úiou_thresholdÚiou_threshold_trkrÒ  rz  ry  rx  rv  r^  Útrk_is_nonemptyÚdet_masks_binaryÚtrk_masks_binaryÚiousÚious_nprÙ  Úcost_matrixÚrow_indÚcol_indÚtrk_is_matchedÚdr  Útrk_is_unmatchedÚ
is_new_detÚdet_to_max_iou_trk_idxÚdet_is_high_confÚdet_is_high_iouÚdet_is_high_conf_and_ioure  s                                    r9   r~  z-SAM3VideoSemanticPredictor._associate_det_trkº  s²  € ð. Ô-ˆØ Ô5ÐØÔ,ˆà×*Ò*Ñ,Ô,ÐWÐWÐ.WÑWÔWÐ,Ø×*Ò*Ñ,Ô,ÐWÐWÐ.WÑWÔWÐ,Ø�~Š~˜aÑ Ô ¥C¨Ñ$4Ô$4Ò4Ð4Ð4ØoÀiÇnÂnÐUVÑFWÔFWÐoÐoÕ]`ÐalÑ]mÔ]mÐoÐoñ 5Ô4Ð4ð �>Š>˜!ÑÔ Ò!Ð!å œi¨	¯ª°qÑ(9Ô(9Ñ:Ô:ˆOÝ$&¤H¨Rµ´Ñ$:Ô$:Ð!Ý "¤¨­R¬XÑ 6Ô 6ÐØ)+Ð&Ø.0Ð+àØ%Ø*Ø/Ø!ðð ð �^Š^˜AÑÔ !Ò#Ð#å œh r­2¬8Ñ4Ô4ˆOØ(¨1š}×1Ò1°fÐ1Ñ=Ô=×AÒAÑCÔC×IÒIÑKÔKˆOØ$/°Ô$@Ð!Ø +¨_Ð,<Ô =ÐØ)+Ð&Ø.0Ð+àØ%Ø*Ø/Ø!ðð ð Œ?˜2˜3˜3Ô 9¤?°2°3°3Ô#7Ò7Ð7åŒw�y” r s sÔ+Ñ,Ô,­r¬w°y´ÀrÀsÀsÔ7KÑ/LÔ/LÒLÐLÝœMØ×'Ò'¨Ñ*Ô*Ø"œ¨¨¨Ô-Ø#Ø"'ð	ñ ô ÷
 ’'˜!‘*”*ð �	õ œMØ×'Ò'¨Ñ*Ô*Ø"œ¨¨¨Ô-Ø#Ø"'ð	ñ ô ÷
 ’'˜!‘*”*ð ð % qš=ÐØ$ qš=ÐÝÐ(×0Ò0°Ñ3Ô3×9Ò9Ñ;Ô;Ð=M×=UÒ=UÐVWÑ=XÔ=X×=^Ò=^Ñ=`Ô=`ÑaÔaˆà—(’(‘*”*×"Ò"Ñ$Ô$ˆØÔ,ð 	HØCÐCÐCÐCÐCÐCð ˜g™+ˆKØ4Ð4°[ÑAÔAÑˆG�WÝœX i§n¢n°QÑ&7Ô&7½tÐDÑDÔDˆNÝ˜G WÑ-Ô-ð -ð -‘��1Ø˜1˜a˜4”=Ð$5Ò5Ð5Ø(,�N 1Ñ%øð-ð &Ð):Ò:×?Ò?ÀQÐ?ÑGÔGˆNà*×.Ò.°6Ð.Ñ:Ô:×>Ò>Ñ@Ô@×FÒFÑHÔHˆÝœ>¨/¸N¸?ÑKÔKÐØ +Ð,<Ô =Ðà'¨Ð(8Ô9Ðõ ”^Ø˜^Ò+ÝŒN�2œ6 '¨]Ò":ÀÐCÑCÔCÑDÔDñ
ô 
ˆ
õ œ* ZÑ0Ô0°Ô3ˆð &(Ð"Ø*,Ð'Ý!#¤¨7¸Ð!;Ñ!;Ô!;ÐØ)¨TÔ-BÒBÀzÀkÑQÐÝœ& ¨qÐ1Ñ1Ô1°TÔ5IÒIˆÝ#&¥r¤zÐ2BÀ_Ñ2TÑ'UÔ'UÐVWÔ'XÑ#YÔ#YÐ Ý�y—~’~ aÑ(Ô(Ñ)Ô)ð 	@ð 	@ˆAØ,7¸ÀÀ1À1À1À¼ÈÒ8VÔ,WÐ& qÑ)ØÐ,Ð,Ð,Ø(Ð)?ÀÔ)BÔC×HÒHÑJÔJ�
Ø>?Ð/°
Ñ;øð Ø!Ø&Ø+Øð
ð 	
r:   rv  údict[int, np.ndarray]rw  rx  ry  r  c                ób  ‡— |d         Š|d         }|d         }	|d         }
|d         }t          ¦   «         }|s
|| j        z
  n	|| j        z   }|D ]}|‰vr|‰|<   ||	vsJ ‚| j        |	|<   Œt          ¦   «         }|                     ¦   «         D ]}|                     |¦  «         Œ|D ]#}t          | j        |	|         dz   ¦  «        |	|<   Œ$|D ]>}||                              |¦  «         t          | j	        |	|         dz
  ¦  «        |	|<   Œ?| j
        r&|D ]#}t          | j	        |	|         dz
  ¦  «        |	|<   Œ$|                     ¦   «         D ]»\  }}||v s||v rŒt          |¦  «        | j        k    rQ‰|         |k    r| p‰|         |k     o|}|r2|                     |¦  «         t          j        d|› d|› d	|› �¦  «         |	|         d
k    r8||vr4||vr0t          j        d|› d|› d�¦  «         |                     |¦  «         Œ¼|                     ¦   «         D ]j}t          |¦  «        dk     rŒ|st          |ˆfd„¬¦  «        nt          |ˆfd„¬¦  «        }|D ]'}||k    r||f}|
|                              |¦  «         Œ(Œk|
                     ¦   «         D ]z\  \  }}}||v s||v rŒ‰|         |k    r|r‰|         |k     rO|rMt          |¦  «        | j        k    r5|                     |¦  «         t          j        d|› d|› d|› d|› �¦  «         Œ{|                     |¦  «         ||fS )zEHandle hotstart heuristics to remove unmatched or duplicated objects.Úobj_first_frame_idxÚunmatched_frame_indsÚtrk_keep_aliveÚoverlap_pair_to_frame_indsr  r   zRemoving object ra  z# since it is unmatched for frames: r   z, due to being unmatchedr>   c                ó   •— ‰|          S ro   rY   ©r\   r÷  s    €r9   ú<lambda>z>SAM3VideoSemanticPredictor._process_hotstart.<locals>.<lambda>“  s   ø€ Ð7JÈ1Ô7M€ r:   )Úkeyc                ó   •— ‰|          S ro   rY   rü  s    €r9   rý  z>SAM3VideoSemanticPredictor._process_hotstart.<locals>.<lambda>•  s   ø€ Ð<OÐPQÔ<R€ r:   z& since it overlaps with another track z at frames: )rÀ  rÓ  rÖ  rÁ  r*   r›   r×  r¸   r¾   rØ  rÛ  r  ra   rÔ  rN  r   rd  rÕ  )r5   r‹  r”  rv  rw  rx  ry  r  rø  rù  rú  r  r{  Úhotstart_diffrŠ  Úmatched_trksÚmatched_trks_per_detÚframe_indicesÚis_within_hotstartÚmatched_trk_obj_idsÚfirst_appear_obj_idrþ  Úfirst_obj_idr÷  s                          @r9   r�  z,SAM3VideoSemanticPredictor._process_hotstart?  s×  ø€ ð 'Ð'<Ô=Ðà'Ð(>Ô?ÐØ!Ð"2Ô3ˆà%-Ð.JÔ%KÐ"à"Ð#4Ô5ˆå #¡¤ÐØ?FÐk˜	 DÔ$7Ñ7Ð7ÈIÐX\ÔXkÑLkˆð &ð 	>ð 	>ˆFØÐ0Ð0Ð0Ø.7Ð# FÑ+Ø Ð/Ð/Ð/Ð/Ø%)Ô%=ˆN˜6Ñ"Ð"å‘u”uˆà$>×$EÒ$EÑ$GÔ$Gð 	6ð 	6Ð Ø×ÒÐ 4Ñ5Ô5Ð5Ð5Ø"ð 	^ð 	^ˆFå%(¨Ô)@À.ÐQWÔBXÐ[\ÑB\Ñ%]Ô%]ˆN˜6Ñ"Ð"Ø+ð 	^ð 	^ˆFØ  Ô(×/Ò/°	Ñ:Ô:Ð:õ &)¨Ô)@À.ÐQWÔBXÐ[\ÑB\Ñ%]Ô%]ˆN˜6Ñ"Ð"ØÔ:ð 	bØ+ð bð b�å),¨TÔ-DÀnÐU[ÔF\Ð_`ÑF`Ñ)aÔ)a�˜vÑ&Ð&ð &:×%?Ò%?Ñ%AÔ%Að 	2ð 	2Ñ!ˆF�MØ˜Ð(Ð(¨FÐ6KÐ,KÐ,KØÝ�=Ñ!Ô! TÔ%AÒAÐAØ&9¸&Ô&AÀMÒ&QÐ&aÐZaÐVað &Ø'¨Ô/°-Ò?ÐKÀGð #ð &ð Ø)×-Ò-¨fÑ5Ô5Ð5Ý”LðM¨6ð Mð M¸Yð Mð MØ=JðMð Mñô ð ð
 ˜vÔ&¨!Ò+Ð+Ø /Ð1Ð1ØÐ"7Ð7Ð7å”Ðe°ÐeÐeÀ)ÐeÐeÐeÑfÔfÐfà%×)Ò)¨&Ñ1Ô1Ð1øð $>×#DÒ#DÑ#FÔ#Fð 	Fð 	FÐÝÐ&Ñ'Ô'¨!Ò+Ð+Øð
 ðT•Ð'Ð-MÐ-MÐ-MÐ-MÐNÑNÔNÐNåÐ,Ð2RÐ2RÐ2RÐ2RÐSÑSÔSð  ð
 .ð Fð F�ØÐ0Ò0Ð0Ø.°Ð7�CØ.¨sÔ3×:Ò:¸9ÑEÔEÐEøðFð 6P×5UÒ5UÑ5WÔ5Wð 	ð 	Ñ1Ñ"ˆ\˜6 MØ˜Ð(Ð(¨FÐ6KÐ,KÐ,KØà$ VÔ,¨}Ò<Ð<ÀWÐ<Ø'¨Ô/°-Ò?Ð?ÀGÐ?Ý�mÑ$Ô$¨Ô(@Ò@Ð@Ø%×)Ò)¨&Ñ1Ô1Ð1Ý”ðf vð fð f¸ð fð fØ<Hðfð fØVcðfð fñô ð øð
 	×ÒÐ4Ñ5Ô5Ð5Ø$ hÐ.Ð.r:   rð  rn  c                ó,  — t          |¦  «        dk    rdS t          j        |                     d¦  «        | j        dd¬¦  «        }t          | d¦  «        r| j        r| j        j         	                    |¦  «        }t          j        |dk                         d¬	¦  «        d
d¦  «        }d}|}|D ]ã}t          |d         ¦  «        }	|	dk    rŒ||	z   }
|||
…         }|||
…         }|                     d¦  «        }| j                             |||d|¬¦  «        }|\  }}|d         }dD ]c}|||         vrŒ|||         |         d<   d„ |D ¦   «         ||         |         d<   | j                             ||||         |         |¬¦  «         Œd||	z  }ŒädS )zHRun Sam2 memory encoder, enforcing non-overlapping constraints globally.r   Nr   r°   Frõ  ru  r§  r  rñ  rÉ  rÓ  )r÷  r~  rˆ  rÏ  rá  c                ó   — g | ]}|‘ŒS rY   rY   )r[   Úposs     r9   r^   zGSAM3VideoSemanticPredictor._tracker_update_memories.<locals>.<listcomp>Ý  s   € ÐIoÐIoÐIoÐRUÈ#ÐIoÐIoÐIor:   rã  )r~  r‹  r¢  r¡  )ra   rµ   r¶   r;  rî  r€  ru  ræ  rL   Ú"_suppress_object_pw_area_shrinkager@   r"  r  rï  rü  rŸ  )r5   rð  r‹  rn  rö  rô  Ústart_idx_gpuÚstart_idx_stateÚtracker_stateÚnum_obj_per_stateÚend_idx_stateÚlocal_high_res_masksÚlocal_object_score_logitsÚlocal_batch_sizeÚencoded_memÚlocal_maskmem_featuresÚlocal_maskmem_pos_encrˆ  r¡  s                      r9   r…  z3SAM3VideoSemanticPredictor._tracker_update_memories®  s(  € õ Ð'Ñ(Ô(¨AÒ-Ð-ØˆFåœØ×#Ò# AÑ&Ô&ØÔ#ØØð	
ñ 
ô 
ˆõ �tÐ0Ñ1Ô1ð 	c°TÔ5Kð 	cØ!œ\Ô/×RÒRÐSaÑbÔbˆNå#œk¨>¸AÒ+=×*BÒ*BÀxÐ*BÑ*PÔ*PÐRVÐX]Ñ^Ô^Ðð ˆØ'ˆØ5ð "	1ð "	1ˆMÝ # M°)Ô$<Ñ =Ô =ÐØ  AÒ%Ð%Øà+Ð.?Ñ?ˆMØ#1°/À-Ð2OÔ#PÐ Ø(;¸OÈMÐ<YÔ(ZÐ%Ø3×8Ò8¸Ñ;Ô;Ðð œ,×:Ò:Ø Ø$Ø)Ø!&Ø -ð ;ñ ô ˆKð =HÑ9Ð"Ð$9à'¨Ô6ˆKØOð ð �Ø K°Ô$<Ð<Ð<ØØJ`�˜KÔ(¨Ô3Ð4FÑGØIoÐIoÐYnÐIoÑIoÔIo�˜KÔ(¨Ô3Ð4EÑFð ”×3Ò3Ø$1Ø'Ø +¨KÔ 8¸Ô CØ +ð	 4ñ ô ð ð ð Ð0Ñ0ˆOˆOðE"	1ð "	1r:   r%  r³  c                óš  — t          |¦  «        dk    r|d         nd}| j                             |¬¦  «        }d|d<   |�|                     dd¦  «        nd|d<   t          |¦  «        |                     d¦  «        k    sJ ‚|                     ¦   «         sJ ‚t          j        |                     d¦  «        | j	        dd¬¦  «         
                    d¦  «        }|dk    }t          ||¦  «        D ])\  }}	| j                             ||||	d	         ¬
¦  «         Œ*| j                             |¦  «         |                     |¦  «         |S )z*Add a new object to SAM2 inference states.r   N)rÐ  r/   rn  r°   Frõ  r6  rb  )ra   ræ  rË  r³  rï  rÚ  rµ   r¶   r;  rî  r˜   r³   r™  rš  r¸   )
r5   r‹  rÐ  r%  r³  r  Úprev_tracker_stateÚnew_tracker_stateÚ
new_obj_idrg  s
             r9   r´  z3SAM3VideoSemanticPredictor._tracker_add_new_objectsè  s’  € õ 9<Ð<PÑ8QÔ8QÐTUÒ8UÐ8UÐ1°!Ô4Ð4Ð[_Ðð
 !œL×4Ò4À
Ð4ÑKÔKÐà"&Ð˜$Ñà<NÐ<ZÐ×"Ò" >°4Ñ8Ô8Ð8Ð`dð 	˜.Ñ)õ �;ÑÔ =×#5Ò#5°aÑ#8Ô#8Ò8Ð8Ð8Ð8Ø×.Ò.Ñ0Ô0Ð0Ð0Ð0ÝœØ×#Ò# AÑ&Ô&ØÔ#ØØð	
ñ 
ô 
÷
 Š'�!‰*Œ*ð 	ð &¨Ò)ˆõ %(¨°]Ñ$CÔ$Cð 	ð 	Ñ ˆJ˜ØŒL×(Ò(Ø 1Ø#Ø!Ø˜zÔ*ð	 )ñ ô ð ð ð 	Œ×1Ò1Ð2CÑDÔDÐDØ×#Ò#Ð$5Ñ6Ô6Ð6Ø#Ð#r:   c                óÊ   — |sdS g }|D ]R}|D ]}| j                              ||d¬¦  «         Œ t          |d         ¦  «        dk    r|                     |¦  «         ŒS||dd…<   dS )zgRemove an object from SAM2 inference states. This would remove the object from all frames in the video.NF©r"  rÓ  r   )ræ  r'  ra   r¸   )r5   r  rÓ  Úactive_statesÚstaterŠ  s         r9   rµ  z2SAM3VideoSemanticPredictor._tracker_remove_objects  sš   € àð 	ØˆFàˆØ)ð 	,ð 	,ˆEØ!ð Hð H�ð ”×*Ò*¨5°&ÀÐ*ÑGÔGÐGÐGå�5˜Ô#Ñ$Ô$ qÒ(Ð(Ø×$Ò$ UÑ+Ô+Ð+øð #0Ð˜Q˜Q˜QÑÐÐr:   c                óâ  — t          j        g t           j        ¦  «        t          j        dt           j        ¦  «        di i t	          t
          ¦  «        i dœ}i t	          t          ¦  «        t	          t          ¦  «        t	          t          ¦  «        t          ¦   «         dœ}| j	        rBt          j        g t           j
        ¦  «        t          j        g t           j
        ¦  «        dœ|d<   ||d<   |S )z%Initialize metadata for the masklets.r   r<   )rÓ  r-  ro  rû  rþ  r  rp  )r÷  rø  rù  rú  r  )r  Úconsecutive_det_numr  r  )rB   r´   r    r  r   r  r  r[  rÀ  râ  rÛ  )r5   rñ  r  s      r9   r2  z/SAM3VideoSemanticPredictor._initialize_metadata&  sÛ   € õ ”x ¥B¤HÑ-Ô-Ý”x ¥2¤8Ñ,Ô,ØØ!ØÝ2=½dÑ2CÔ2CØ')ð
ð 
Ðð $&Ý$/µÑ$5Ô$5Ý)­#Ñ.Ô.Ý*5µdÑ*;Ô*;Ý"™uœuð
ð 
ˆð Ô+ð 	õ œ( 2¥r¤xÑ0Ô0õ (*¤x°µB´HÑ'=Ô'=ð0ð 0ˆHÐ+Ñ,ð (0Ð˜Ñ$àÐr:   r|  r}  c                óÖ  ‡— |d         }|d         }|d         }|j         |j         k    sJ d|j         › d|j         › �¦   «         ‚d„ t          |¦  «        D ¦   «         Št          j        ||¦  «        }	||	         }
t          j        ˆfd„|
D ¦   «         t          j        ¬¦  «        }| j        }t          j        ||¬	¦  «        }||	         ||<   t          j        |¦  «        }||	         ||<   t          j        ||¦  «        }| 	                    ¦   «         D ]}|t          j        ||¦  «        z  }Œt          j
        ||d
z   d¦  «        }|| j        k    }| j        ||<   ||d<   ||d<   |S )zZUpdate the confirmation status of masklets based on the current frame's detection results.r  r  r   zGot r¢  c                ó   — i | ]\  }}||“Œ	S rY   rY   )r[   râ   rŠ  s      r9   rª  zQSAM3VideoSemanticPredictor.update_masklet_confirmation_status.<locals>.<dictcomp>\  s   € Ð cÐ cÐ c±°°f ¨Ð cÐ cÐ cr:   c                ó    •— g | ]
}‰|         ‘ŒS rY   rY   )r[   rŠ  Úobj_id_to_updated_idxs     €r9   r^   zQSAM3VideoSemanticPredictor.update_masklet_confirmation_status.<locals>.<listcomp>`  s   ø€ ÐVÐVÐV¨vÐ" 6Ô*ÐVÐVÐVr:   r”   )rð  r   r   )rf   r  rB   r‡  r´   rÛ  r  Ú	full_likeÚ
zeros_likerÁ  r"  rã  Ú	CONFIRMED)r5   r  r|  r}  rv  rw  Úconfirmation_dataÚstatus_prevÚconsecutive_det_num_prevÚprev_elem_is_in_updatedÚprev_elem_obj_ids_in_updatedÚprev_elem_inds_in_updatedÚunconfirmed_valr  r   Ú
is_matchedr  Úchange_to_confirmedr$  s                     @r9   rˆ  z=SAM3VideoSemanticPredictor.update_masklet_confirmation_statusJ  sÉ  ø€ ð %Ð%;Ô<Ðð (¨Ô1ˆØ#4Ð5JÔ#KÐ ØÔ Ð$8Ô$>Ò>Ð>Ð>ØF�;Ô$ÐFÐFÐ*>Ô*DÐFÐFñ ?Ô>Ð>ð !dÐ cÅ	ÐJaÑ@bÔ@bÐ cÑ cÔ cÐÝ"$¤'Ð*>Ð@WÑ"XÔ"XÐØ';Ð<SÔ'TÐ$Ý$&¤HØVÐVÐVÐVÐ9UÐVÑVÔVÝ”(ð%
ñ %
ô %
Ð!ð
 Ô*ˆÝ”Ð5À/ÐRÑRÔRˆØ,7Ð8OÔ,PˆÐ(Ñ)Ý œmÐ,CÑDÔDÐØ9QÐRiÔ9jÐÐ5Ñ6õ
 ”WÐ4°oÑFÔFˆ
Ø#=×#DÒ#DÑ#FÔ#Fð 	Pð 	PÐØ�"œ'Ð"9Ð;NÑOÔOÑOˆJˆJÝ œh zÐ3FÈÑ3JÈAÑNÔNÐð 2°TÔ5eÒeÐØ&*¤nˆÐ"Ñ#à&,Ð˜(Ñ#Ø3FÐÐ/Ñ0Øˆr:   Ú	ckpt_pathr  r"  c                ó   — t          j        |dd¬¦  «        d         }|                      ||¬¦  «        \  }}t          |¦  «        dk    st          |¦  «        dk    rt	          j        d|›d|›�¦  «         d S t	          j        d	¦  «         d S )
Nr8  T)Úmap_locationÚweights_onlyrL   r  r   zLoaded ckpt with missing_keys=z, unexpected_keys=z;Loaded ckpt successfully without missing or unexpected keys)r@   ÚloadÚload_state_dictra   r   rð   Úinfo)r5   r1  r"  ÚsdÚmissing_keysÚunexpected_keyss         r9   Ú_load_checkpointz+SAM3VideoSemanticPredictor._load_checkpointz  s�   € ÝŒZ˜	°ÀDÐIÑIÔIÈ'ÔRˆØ(,×(<Ò(<¸RÈÐ(<Ñ(OÔ(OÑ%ˆ�oÝˆ|ÑÔ˜qÒ Ð ¥C¨Ñ$8Ô$8¸1Ò$<Ð$<ÝŒNÐR¨|ÐRÐRÀÐRÐRÑSÔSÐSÐSÐSåŒKÐUÑVÔVÐVÐVÐVr:   c                ó&   —  | j         j        di |¤ŽS )NrY   )rL   Ú_encode_prompt)r5   rx   s     r9   r=  z)SAM3VideoSemanticPredictor._encode_prompt‚  s   € Ø(ˆtŒzÔ(Ð2Ð2¨6Ð2Ð2Ð2r:   c                ó  — d|cxk    rt          | ¦  «        k    sn J ‚|dk    rt          j        g t          j        ¦  «        S |t          | ¦  «        k    r| S t          j        ||          ¦  «        ddd…         }| |d|…                  } | S )zÈDrop a few new detections based on the maximum number of objects. We drop new objects based on their
        detection scores, keeping the high-scoring ones and dropping the low-scoring ones.
        r   Nr<   )ra   rB   r´   rÛ  Úargsort)rz  rr  Únum_to_keepÚscore_orders       r9   r  z7SAM3VideoSemanticPredictor._drop_new_det_with_obj_limit…  s£   € ð
 �KÐ7Ð7Ò7Ð7¥3 Ñ#7Ô#7Ò7Ð7Ð7Ð7Ð7Ð7Ø˜!ÒÐÝ”8˜B¥¤Ñ)Ô)Ð)Ø�#˜oÑ.Ô.Ò.Ð.Ø"Ð"õ ”j ¨Ô!?Ñ@Ô@ÀÀÀ2ÀÔFˆØ)¨+°l°{°lÔ*CÔDˆØÐr:   rD  rF  r¿  rÀ  )FNrE  )rÉ  )T)r/   rS  r“  rS  r‹  r[  rÐ  r[  r”  r<  r”  r   r  r&  r  rf  r  r<  )r8  )r/   rS  r“  rS  r”  r   r  r<  )r‹  r[  r  r&  r  rT  )
r(  r]  r^  r_  r  r&  rñ  rT  r*  rS  )r‹  r[  r”  r<  r(  r]  r)  rS  r*  rS  r  rT  r  r&  r7  )r‹  r[  r)  rS  r  rf  r  rf  r{  r   r”  r<  )
r‹  r[  rÐ  r[  r(  r]  r  r&  r,  rT  ro   )
r(  r]  r)  rS  r  rT  r,  rT  r+  rº  )NF)
rÀ  rS  rÁ  r_  rÓ  r_  r‹  rR  r”  r<  )rÏ  r&  r‹  r[  )rq  rS  rr  r×  rs  rS  rt  r×  )r‹  r[  r”  r<  rv  rõ  rw  r×  rx  r×  ry  r×  r  rf  )rð  r&  r‹  r[  rn  rS  )
r‹  r[  rÐ  r[  r%  r_  r³  rS  r  r&  )r  r&  rÓ  r_  )
r  rf  r|  r×  r}  r×  rv  rõ  rw  r×  )r1  r  r"  r<  )1rH  rI  rJ  rK  ri  râ  r¬  r¤  r¥  r  r'  ra  r÷   r   r,   r   rû   r#  rM  r„  ry   r!  r�  rõ  r  r  rB  r1  rD  rE  r3  rm  r4  r„  r5  r6  r«  rW  r~  r�  r…  r´  rµ  r2  rˆ  r;  r=  r  rN  rO  s   @r9   rÇ  rÇ  Ë	  s  ø€ € € € € ØCÐCàÐØ€OØ€LØ€NØ€Oà€KØ€Iðð ð €Nð
 €Fð ØØ"&ð #&àð ð !àð Ø !ØØØØàADØ37Ø%*Ø',ØàØ$&à$(ð 56à'*Ø&)ðWU"ð U"ð U"ð U"ð U"ð U"ð U"ðn Ð˜%Ñ Ô ð=ð =ð =ð =ð =ñ !Ô ð=ð"ð "ð "ð "ð "ð ð4ð 4ñ „\ð4ð0Fð Fð Fð Fð Fð,ð ,ð ,ð\4ð 4ð 4ð 4ðl ÐÑÔð ØØØð%ð %ð %ñ Ôð%ðNð ð ð ð4 &*ði
ð i
ð i
ð i
ð i
ðV ðð ð ñ „\ðð
ð 
ð 
ð 
ð
ð 
ð 
ð.9ð 9ð 9ð"7ð 7ð 7ð 7ð,($ð ($ð ($ð ($ðTU9ð U9ð U9ð U9ð| ðD,ð D,ð D,ð D,ð D,ðL"$ð "$ð "$ð "$ðH ð -1ð$ð $ð $ð $ñ „\ð$ðV !%ØðBð Bð Bð Bð BðHDð Dð Dð Dð8C
ð C
ð C
ð C
ðJm/ð m/ð m/ð m/ð^81ð 81ð 81ð 81ðt*$ð *$ð *$ð *$ðX0ð 0ð 0ð 0ð$" ð " ð " ðH.ð .ð .ð .ð`Wð Wð Wð Wð Wð3ð 3ð 3ð ðð ñ „\ðð ð ð ð r:   rÇ  )7rK  Ú
__future__r   Úcollectionsr   r   r   r   Útypingr   r   r£   r9  rB   r@   Útorch.nn.functionalÚnnÚ
functionalrµ   Úultralytics.data.augmentr	   Úultralytics.engine.predictorr
   Úultralytics.engine.resultsr   Úultralytics.utilsr   r   r   Úultralytics.utils.metricsr   r   Úultralytics.utils.torch_utilsr   r   Úamgr   r   r   r   r   r   r   r   r   r½  r   r    rQ  r|  r9  rp  r‚  rÂ  rÇ  rY   r:   r9   ú<module>rO     sZ  ððð ð #Ð "Ð "Ð "Ð "Ð "à 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ð 0Ø Ð Ð Ð Ð Ð Ø %Ð %Ð %Ð %Ð %Ð %Ð %Ð %à 
€
€
€
Ø Ð Ð Ð Ø €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð à .Ð .Ð .Ð .Ð .Ð .Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø .Ð .Ð .Ð .Ð .Ð .Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ø 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ø MÐ MÐ MÐ MÐ MÐ MÐ MÐ Mð
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð 
ð ð /Ø.Ð.Ð.Ð.Ð.Ð.ða
'ð a
'ð a
'ð a
'ð a
'�ñ a
'ô a
'ð a
'ðHKCð KCð KCð KCð KC�Iñ KCô KCð KCð\hGð hGð hGð hGð hG˜ñ hGô hGð hGðVI
ð I
ð I
ð I
ð I
 mñ I
ô I
ð I
ðX
Mð Mð Mð Mð M�Mñ Mô Mð Mð2c ð c ð c ð c ð c ˜Mñ c ô c ð c ðL3/ð 3/ð 3/ð 3/ð 3/Ð+¨]ñ 3/ô 3/ð 3/ðlHð Hð Hð Hð HÐ!6ñ Hô Hð Hð Hð Hr:   