Ë
    Fêñi| ã                  ó¨  — d Z ddlmZ ddlmZmZ ddlmZ ddl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+ ddl,m-Z-  G d„ de«      Z. G d„ de.«      Z/ G d„ de/«      Z0 G d„ de/«      Z1 G d„ de/«      Z2 G d„ de2«      Z3 G d„ de0e2«      Z4 G d„ de3«      Z5y) 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)Ú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dd„Z	dd„Z
	 	 	 	 	 dd	„Zdd
„Z	 	 	 	 	 	 	 	 	 	 dd„Zdd„Zd„ Zd„ Zd„ Zˆ fd„Zd„ Zd„ Zd„ Zedd„«       Z e«       	 	 	 	 	 	 dd„«       Zˆ xZS )Ú	Predictoraâ  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.
        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)
    é   Nc                óÄ   •— |€i }|j                  t        ddd¬«      «       t        ‰| �  |||«       d| j                  _        d| _        d| _        i | _        d| _	        y)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ÚdictÚsuperÚ__init__ÚargsÚretina_masksÚimÚfeaturesÚpromptsÚsegment_all©ÚselfÚcfgÚ	overridesÚ
_callbacksÚ	__class__s       €ú`/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/models/sam/predict.pyr)   zPredictor.__init__W   sa   ø€ ð ÐØˆIØ×Ñœ 9°9ÀAÔFÔGÜ‰Ñ˜˜i¨Ô4Ø!%ˆ�	‰	ÔØˆŒØˆŒØˆŒØ ˆÕó    c                ó   — | j                   �| j                   S t        |t        j                  «       }|rgt	        j
                  | j                  |«      «      }|dddd…f   j                  d«      }t	        j                  |«      }t        j                  |«      }|j                  | j                  «      }|r|| j                  z
  | j                  z  }| j                  j                  r|j!                  «       }|S |j#                  «       }|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)r1   r,   Ú
not_tensors      r6   Ú
preprocesszPredictor.preprocessm   sÙ   € ð& �7‰7ÐØ—7‘7ˆNÜ# B¬¯©Ó5Ð5ˆ
ÙÜ—‘˜$×,Ñ,¨RÓ0Ó1ˆBØ�C™˜2˜�I‘×(Ñ(¨Ó6ˆBÜ×%Ñ% bÓ)ˆBÜ×!Ñ! "Ó%ˆBà�U‰U�4—;‘;ÓˆÙØ�t—y‘y‘. D§H¡HÑ,ˆBØŸ*™*Ÿ/š/ˆR�W‰W‹YˆØˆ	ð 02¯x©x«zˆØˆ	r7   c                ó”   — t        |«      dk(  sJ d«       ‚t        | j                  dd¬«      }|D �cg c]  } ||¬«      ‘Œ c}S c c}w )á0  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()
            >>> 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Úcenter©Úimage©Úlenr   Úimgsz©r1   r,   Ú	letterboxÚxs       r6   rA   zPredictor.pre_transform�   sE   € ô, �2‹w˜!Š|ÐUÐUÓUˆ|Ü˜dŸj™j¨u¸UÔCˆ	Ø,.Ö/ q‘	 Ö"Ò/Ð/ùÒ/s   ²Ac                ód  — | j                   j                  d|«      }| j                   j                  d|«      }| j                   j                  d|«      }| j                   j                  d|«      }t        d„ |||fD «       «      r | j                  |g|¢­i |¤ŽS | j	                  ||||||«      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 –— Œ
 y ­w©N© ©Ú.0Úis     r6   ú	<genexpr>z&Predictor.inference.<locals>.<genexpr>Ê   s   è ø€ Ò:˜Qˆq�DŒyÑ:ùs   ‚)r.   ÚpopÚallÚgenerateÚprompt_inference)	r1   r,   r]   r^   r`   r_   Úmultimask_outputr*   Úkwargss	            r6   Ú	inferencezPredictor.inference©   s¨   € ð8 —‘×!Ñ! (¨FÓ3ˆØ—‘×!Ñ! (¨FÓ3ˆØ—‘× Ñ  ¨%Ó0ˆØ—‘×!Ñ! (¨FÓ3ˆäÑ: 6¨6°5Ð"9Ô:Ô:Ø �4—=‘= Ð5 dÒ5¨fÑ5Ð5à×$Ñ$ R¨°¸ÀÐHXÓYÐYr7   c                óþ   — | j                   €| j                  |«      n| j                   }| j                  |j                  dd | j                  d   d   j                  dd ||||«      } | j
                  |g|¢|‘­Ž 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, logits = predictor.prompt_inference(im, bboxes=bboxes)
        Nr;   r   r   )r-   Úget_im_featuresÚ_prepare_promptsÚshaper%   Ú_inference_features)	r1   r,   r]   r^   r`   r_   rl   r-   r.   s	            r6   rk   zPredictor.prompt_inferenceÏ   sƒ   € ð4 04¯}©}Ð/D�4×'Ñ'¨Ô+È$Ï-É-ˆà×'Ñ'¨¯©°°¨°d·j±jÀ±mÀAÑ6F×6LÑ6LÈRÈaÐ6PÐRXÐZ`ÐbhÐjoÓpˆØ'ˆt×'Ñ'¨ÐM°7ÐMÐ<LÒMÐMr7   c                ó&  — |�||fnd}| j                   j                  |||¬«      \  }}| j                   j                  || j                   j                  j                  «       |||¬«      \  }	}
|	j	                  dd«      |
j	                  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©r^   Úboxesr_   )Úimage_embeddingsÚimage_peÚsparse_prompt_embeddingsÚdense_prompt_embeddingsrl   r   r   )rI   Úprompt_encoderÚmask_decoderÚget_dense_peÚflatten)r1   r-   r]   r^   r`   r_   rl   Úsparse_embeddingsÚdense_embeddingsÚ
pred_masksÚpred_scoress              r6   rs   zPredictor._inference_featuresî   s¢   € ð. &,Ð%7�&˜&Ñ!¸Tˆà.2¯j©j×.GÑ.GÈvÐ]cÐkpÐ.GÓ.qÑ+ÐÐ+ð #'§*¡*×"9Ñ"9Ø%Ø—Z‘Z×.Ñ.×;Ñ;Ó=Ø%6Ø$4Ø-ð #:ó #
Ñˆ
�Kð ×!Ñ! ! QÓ'¨×)<Ñ)<¸QÀÓ)BÐBÐBr7   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   }}|�Gt        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                   |D �	cg c]  }	 ||	¬«      j#                  «       ‘Œ c}	d¬«      }t        j$                  || j                  | j
                  ¬«      }||||fS c c}	w )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©ÚdtyperF   r9   éþÿÿÿúNumber of points ú should match number of labels ú.r;   ©r†   F)rR   rS   Úpadding_valueÚinterpolationrT   ©Úaxis)r/   Úminr=   Ú	as_tensorÚtorch_dtyperF   Úndimr?   Úonesrr   Úint32ÚasarrayÚuint8r   Úcv2ÚINTER_NEARESTr@   ÚsqueezeÚtensor)
r1   Ú	dst_shapeÚ	src_shaper]   r^   r`   r_   ÚrrZ   r[   s
             r6   rq   zPredictor._prepare_prompts  s  € ð. ×#Ò#‰C¬¨Y°q©\¸IÀa¹LÑ-HÈ)ÐTUÉ,ÐYbÐcdÑYeÑJeÓ)fˆàÑÜ—_‘_ V°4×3CÑ3CÈDÏKÉKÔXˆFØ%+§[¡[°AÒ%5�V˜D’\¸6ˆFàˆ~ÜŸ™ §¡¨c¨rÐ!2Ó3�Ü—_‘_ V´5·;±;ÀtÇ{Á{ÔSˆFØ—<‘< Ñ# v§|¡|°BÑ'7Ò7ð Ø# F§L¡L°Ñ$4Ð#5Ð5TÐU[×UaÑUaÐbdÑUeÐTfÐfgÐhóÐ7ð �a‰KˆFØ�{‰{˜aÒà!'ª¨4²¨
Ñ!3°VºA¸t¸G±_˜�ØÐÜ—_‘_ V°4×3CÑ3CÈDÏKÉKÔXˆFØ%+§[¡[°AÒ%5�V˜D’\¸6ˆFØ�a‰KˆFØÐÜ—J‘J˜u¬B¯H©HÔ5ˆEØ#(§:¡:°¢?�E˜$’K¸ˆEÜ! )°%ÀÐUVÔfi×fwÑfwÔxˆIÜ—H‘HÀEÖJ¸q™i¨aÔ0×8Ñ8Õ:ÒJÐQRÔSˆEÜ—L‘L ¨d×.>Ñ.>ÀtÇ{Á{ÔSˆEØ�v˜v uÐ,Ð,ùò Ks   Ç-I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 �]  \  }$| j                  ||$d¬
«      \  }%}&t        j                  |%d   ||fdd¬	«      d   }%|&|kD  }'|%|'   |&|'   }&}%t        |%| j                   j"                  |
«      }(|(|	kD  }'|%|'   |&|'   }&}%|%| j                   j"                  kD  }%t%        |%«      j'                  «       })t)        |)|dd||g«       }*t        j*                  |*«      s|)|*   |%|*   |&|*   }&}%})|!j-                  |%«       |#j-                  |)«       |"j-                  |&«       �Œ t        j.                  |!«      }!t        j.                  |#«      }#t        j.                  |"«      }"|j0                  j3                  |#|"| j4                  j6                  «      }+t9        |#|+   |«      }#t;        |!|+   |||«      }!|"|+   }"|j-                  |!«       |j-                  |#«       |j-                  |"«       |j-                  |j=                  |!j                  d   «      «       �Œ¥ t        j.                  |«      }t        j.                  |«      }t        j.                  |«      }t        j.                  |«      }t?        |«      dkD  r1d|z  },|j0                  j3                  ||,|«      }+||+   ||+   ||+   }}}|||fS )aP  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] for filtering based on mask quality prediction.
            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.

        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;   ©rF   .ÚbilinearF)r$   Úalign_corners)r^   rl   r   ) Útorchvisionr/   rr   r   r   Úzipr=   r›   rF   r?   ÚarrayÚFÚinterpolater   rk   r   rI   Úmask_thresholdr   rL   r   ri   ÚappendÚcatr   Únmsr*   Úiour   r   ÚexpandrW   )-r1   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_threshr£   Ú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Úpoints_for_imageÚ
crop_masksÚcrop_scoresÚcrop_bboxesr^   Ú	pred_maskÚ
pred_scoreÚidxÚstability_scoreÚ	pred_bboxÚ	keep_maskÚkeepÚscoress-                                                r6   rj   zPredictor.generateI  s¾  € óT 	àˆÔØ—‘˜!˜"�‰ˆˆBÜ#6¸¸B°xÀÐPbÓ#cÑ ˆ�jØÐÜ5°mÀ]ÐTiÓjˆKØ=?ÀÀRÈ¸^Ñ:ˆ
�K ¨lÜ&)¨,¸
Ó&Có .	BÑ"ˆK˜Ø(‰NˆB��B˜Ø˜‘7˜B ™GˆqˆAÜ—<‘<  A¡¨b¯i©iÔ8ˆDÜŸ8™8 a¨ V HÓ-ˆLä—m‘m B s¨B¨r¨E°2°b°5Ð'8Ñ$9¸BÀ¸8È*ÐdiÔjˆGà*¨9Ñ5¸ÑDÐØ35°r¸2 [˜ˆJÜ+Ð,=Ð?OÓPó /‘	�Ø(,×(=Ñ(=¸gÈfÐgkÐ(=Ó(lÑ%�	˜:äŸM™M¨)°D©/¸A¸q¸6È
ÐbgÔhÐijÑk�	Ø  :Ñ-�Ø(1°#©¸
À3¹˜:�	ä";Ø˜tŸz™z×8Ñ8Ð:Pó#�ð &Ð(>Ñ>�Ø(1°#©¸
À3¹˜:�	à%¨¯
©
×(AÑ(AÑA�	ä/°	Ó:×@Ñ@ÓB�	Ü2°9¸kÈAÈqÐRTÐVXÈ>ÓZÐZ�	Ü—y‘y Ô+Ø7@ÀÑ7KÈYÐW`ÑMaÐcmÐnwÑcx¨*˜y�Ià×!Ñ! )Ô,Ø×"Ñ" 9Ô-Ø×"Ñ" :Ö.ð-/ô2 Ÿ™ :Ó.ˆJÜŸ)™) KÓ0ˆKÜŸ)™) KÓ0ˆKØ—?‘?×&Ñ& {°KÀÇÁÇÁÓOˆDÜ+¨K¸Ñ,=¸{ÓKˆKÜ% j°Ñ&6¸ÀRÈÓLˆJØ% dÑ+ˆKà×Ñ˜jÔ)Ø×Ñ˜{Ô+Ø×Ñ˜{Ô+Ø×Ñ §¡¨J×,<Ñ,<¸QÑ,?Ó @ÖAð].	Bô` —Y‘Y˜zÓ*ˆ
Ü—i‘i Ó,ˆÜ—i‘i Ó,ˆÜ—y‘y Ó.ˆô ˆ|Ó˜qÒ Ø˜Ñ%ˆFØ—?‘?×&Ñ& {°F¸OÓLˆDØ3=¸dÑ3CÀ[ÐQUÑEVÐXcÐdhÑXi [˜ˆJà˜;¨Ð3Ð3r7   c                óB  — t        | j                  j                  |¬«      }|€| j                  «       }|j	                  |«      }| j                  j
                  r|j                  «       n|j                  «       }|j                  «        || _        || _        t        j                  g d¢«      j                  ddd«      j	                  |«      | _        t        j                  g d¢«      j                  ddd«      j	                  |«      | _        d| j                  _        d| j                  _        | j                  j
                  | j                  _        d	| _        | j                  j                   rt        j$                  | _        yt        j&                  | _        y)
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)
        )ÚverboseN)g33333ë^@gR¸…ë]@gR¸…ëáY@r9   r   )gÃõ(\�2M@g�Âõ(\�L@g     °L@Úsamé    T)r   r*   rF   Ú	get_modelrE   rK   rL   ÚevalrI   r=   r›   ÚviewrG   rH   ÚformatÚstriderJ   Údone_warmupÚfloat16Úfloat32r’   )r1   rI   rÖ   rF   s       r6   Úsetup_modelzPredictor.setup_model¸  s  € ô ˜tŸy™y×/Ñ/¸ÔAˆØˆ=Ø—N‘NÓ$ˆEà—‘˜Ó ˆØ $§	¡	§¢�—
‘
”°E·K±K³MˆØ�
‰
ŒØˆŒ
ØˆŒÜ—L‘LÒ!:Ó;×@Ñ@ÀÀQÈÓJ×MÑMÈfÓUˆŒ	Ü—<‘<Ò 7Ó8×=Ñ=¸bÀ!ÀQÓG×JÑJÈ6ÓRˆŒð "ˆ�
‰
ÔØˆ�
‰
ÔØŸ)™)Ÿ.™.ˆ�
‰
ŒØˆÔØ,0¯J©J¯OªOœ5Ÿ=™=ˆÕÄÇÁˆÕr7   c                óF   — ddl m}  || j                  j                  «      S )zPRetrieve or build the Segment Anything Model (SAM) for image segmentation tasks.r   ©Ú	build_sam©Úbuildrä   r*   rI   ©r1   rä   s     r6   rÙ   zPredictor.get_modelÙ  ó   € å$á˜Ÿ™Ÿ™Ó)Ð)r7   c           
     óJ  — |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                  ¬«      }}	�n$t        j                  |	d   j                  «       |
j                  dd d	¬
«      d   }	|	| j                   j"                  kD  }	|�?t        j$                  |j                  dd |j                  «       |
j                  d	¬
«      }nt'        |	«      }t        j(                  |j                  d   t        j*                  |j                  ¬«      }|| j,                  j.                  kD  }t        j0                  ||dd…df   |dd…df   gd¬«      |   }|	|   }	|j3                  t5        |
|||	|¬«      «       �Œ„ 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  ó2   K  — | ]  }t        |«      –— Œ y ­wrb   ©Ústrrd   s     r6   rg   z(Predictor.postprocess.<locals>.<genexpr>ù  s   è ø€ ÒJ¨!œs 1ŸvÑJùó   ‚r   .r9   ©r   é   r    F©Úpaddingr…   ©Údim©ÚpathÚnamesr_   rv   )r/   r'   Ú	enumerateÚrangerr   r<   Úlistr   Úconvert_torch2numpy_batchr¤   r%   r=   ÚzerosrF   Úscale_masksrL   rI   r¨   Úscale_boxesr   Úaranger•   r*   Úconfrª   r©   r
   )r1   ÚpredsÚimgÚ	orig_imgsr�   r‚   r¼   rö   Úresultsr_   Úorig_imgÚimg_pathÚclsrÏ   s                 r6   ÚpostprocesszPredictor.postprocessß  sð  € ð0 #(¨¨ )Ñˆ
�KØ"&×"2Ò"2�e˜A’h¸ˆÜ”YÑJ¬u°Z×5EÑ5EÀaÑ5HÓ/IÔJÓJÓKˆä˜)¤TÔ*Ü×5Ñ5°iÓ@ÀÁdÈÀdÀÑKˆIàˆÜ),¨j¨\¸9ÀdÇjÁjÐQRÁmÓ)Tó 	jÑ%ˆE�8˜XØ�{‰{˜1‰~ Ò"Ø%)¬5¯;©;°vÀj×FWÑFWÔ+X�{’äŸ™¨¨d©×(9Ñ(9Ó(;¸X¿^¹^ÈBÈQÐ=OÐY^Ô_Ð`aÑb�Ø §
¡
× 9Ñ 9Ñ9�ØÐ*Ü"%§/¡/°#·)±)¸A¸B°-À×ARÑARÓATÐV^×VdÑVdÐnsÔ"t‘Kä"5°eÓ"<�Kä—l‘l :×#3Ñ#3°AÑ#6¼e¿k¹kÐR\×RcÑRcÔd�Ø! D§I¡I§N¡NÑ2�Ü#Ÿi™i¨°kÂ!ÀTÀ'Ñ6JÈCÒPQÐSWÐPWÉLÐ(YÐ_aÔbÐcfÑg�Ø˜c™
�Ø�N‰Nœ7 8°(À%ÈuÐ\gÔhÖið	jð" !ˆÔØˆr7   c                ó  — | j                   €| j                  «        | j                  |«       t        | j                  «      dk(  sJ d«       ‚| j                  D ]-  }| j                  |d   «      }| j                  |«      | _         y y)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!)rI   rá   Úsetup_sourcerW   ÚdatasetrN   rp   r-   )r1   rU   r%   r,   s       r6   Ú	set_imagezPredictor.set_image  s   € ð. �:‰:ÐØ×ÑÔØ×Ñ˜%Ô Ü�4—<‘<Ó  AÒ%ÐUÐ'UÓUÐ%Ø—\‘\ò 	ˆEØ—‘  q¡Ó*ˆBØ ×0Ñ0°Ó4ˆDŒMÙñ	r7   c                ó2  •— |€yt         ‰| �  || j                  «       t        | j                  t
        t        f«      r| j                  d   | j                  d   k(  sJ d| j                  › d�«       ‚| j                  j                  | j                  «       y)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<   rX   Útuplerù   rI   Ú	set_imgsz)r1   Úsourcer5   s     €r6   r	  zPredictor.setup_source3  s}   ø€ àˆ>ØÜ‰Ñ˜V T§[¡[Ô1Ü˜$Ÿ*™*¤u¬d mÔ4¸¿¹ÀA¹È$Ï*É*ÐUVÉ-Ò9Wð 	
ØAÀ$Ç*Á*ÀÈQÐOó	
ÐWð 	�
‰
×Ñ˜TŸZ™ZÕ(r7   c                ó8   — | j                   j                  |«      S )zZExtract image features using the SAM model's image encoder for subsequent mask prediction.)rI   Úimage_encoder©r1   r,   s     r6   rp   zPredictor.get_im_features=  s   € à�z‰z×'Ñ'¨Ó+Ð+r7   c                ó   — || _         y)z0Set prompts for subsequent inference operations.N)r.   )r1   r.   s     r6   Úset_promptszPredictor.set_promptsA  s	   € àˆ�r7   c                ó    — d| _         d| _        y)zQReset the current image and its features, clearing them for subsequent inference.N)r,   r-   ©r1   s    r6   Úreset_imagezPredictor.reset_imageE  s   € àˆŒØˆ�r7   c                óÈ  — ddl }| j                  d   dk(  r| S g }g }| D ]¶  }|j                  «       j                  «       j	                  t
        j                  «      }t        ||d¬«      \  }}| }t        ||d¬«      \  }}|xr | }|j                  t        j                  |«      j                  d«      «       |j                  t        |«      «       Œ¸ t        j                  |d¬«      }t        |«      }	|j                  j!                  |	j                  «       t        j                  |«      |«      }
||
   j#                  | j$                  | j&                  ¬«      |
fS )aW  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 (int): 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 (list[int]): 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ò   ©rF   r†   )r£   rr   ÚcpuÚnumpyÚastyper?   r—   r   r©   r=   r‘   Ú	unsqueezerL   rª   r   r   r«   rE   rF   r†   )r_   Úmin_areaÚ
nms_threshr£   Ú	new_masksrÔ   ÚmaskÚchangedÚ	unchangedrv   rÓ   s              r6   r   zPredictor.remove_small_regionsJ  s.  € ó2 	à�;‰;�q‰>˜QÒØˆLð ˆ	ØˆØò 		,ˆDØ—8‘8“:×#Ñ#Ó%×,Ñ,¬R¯X©XÓ6ˆDÜ0°°xÀgÔN‰MˆD�'Ø#˜ˆIÜ0°°xÀiÔP‰MˆD�'Ø!Ò1¨' kˆIà×ÑœUŸ_™_¨TÓ2×<Ñ<¸QÓ?Ô@à�M‰Mœ% 	Ó*Õ+ð		,ô —I‘I˜i¨QÔ/ˆ	Ü# IÓ.ˆØ�‰×"Ñ" 5§;¡;£=´%·/±/À&Ó2IÈ:ÓVˆà˜‰×!Ñ!¨¯©¸U¿[¹[Ð!ÓIÈ4ÐOÐOr7   c	                ó¢  — |xs, | j                   j                  | j                   j                  f}| j                  ||||||«      }	 | j                  |g|	¢|‘­Ž \  }
}|
j                  d   dk(  r'dt        j                  d|
j                  ¬«      }}
|
|fS t        j                  |
d   j                  «       |d¬«      d   }
|
| j                  j                  kD  }
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…   r9   rò   )r*   rX   rq   rs   rr   r=   rû   rF   r   rü   rL   rI   r¨   r   rþ   r•   rª   )r1   r-   r�   rœ   r]   r^   r`   r_   rl   r.   r�   r‚   r¼   r  s                 r6   Úinference_featureszPredictor.inference_features}  s=  € ðD ÒC $§)¡)§/¡/°4·9±9·?±?Ð!Cˆ	Ø×'Ñ'¨	°9¸fÀfÈfÐV[Ó\ˆØ": $×":Ñ":¸8Ð"`ÀgÐ"`ÐO_Ò"`Ñˆ
�KØ×Ñ˜AÑ !Ò#Ø&*¬E¯K©K¸Àz×GXÑGXÔ,Y˜ˆJð ˜;Ð&Ð&ô Ÿ™¨°DÑ)9×)?Ñ)?Ó)AÀ9ÐV[Ô\Ð]^Ñ_ˆJØ# d§j¡j×&?Ñ&?Ñ?ˆJÜ-¨jÓ9ˆKä—,‘,˜z×/Ñ/°Ñ2¼%¿+¹+Èj×N_ÑN_Ô`ˆCÜŸ)™) [°+ºaÀ¸gÑ2FÈÊAÈtÈGÉÐ$UÐ[]Ô^ˆKØ˜;Ð&Ð&r7   ©r4   údict | None)NNNNF©NNNN)
r   g¥âìÃgØÕ?r   NrØ   é@   g)\�Âõ(ì?çffffffî?r-  çffffffæ?©NT)r   r.  ©NNNNNF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rÝ   r   r)   rN   rA   rn   rk   rs   rq   rj   rá   rÙ   r  r  r	  rp   r  r  Ústaticmethodr   r   r(  Ú__classcell__©r5   s   @r6   r   r   +   sé   ø„ ñ'ðR €Fà&°$ÐRVö !ò, òD0ó4$ZóLNðD ØØØØó&CóP1-ðl Ø%ØØØØØØ#Ø#Øóm4ó^OòB*ò2òhô@)ò,òòð
 ò0Pó ð0Pñd Óð
 ØØØØØò-'ó ô-'r7   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}")
    ))é   r:  )é€   r;  )r,  r,  r   c                óF   — 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     r6   rÙ   zSAM2Predictor.get_modelÑ  rè   r7   c                ó|  •— t         ‰| �  ||||||«      \  }}}}|�œ|j                  ddd«      }t        j                  ddggt        j
                  |j                  ¬«      j                  |j                  d   d«      }|�3t        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.
        r9   r;   r:   r…   r   r   rò   )
r(   rq   rÛ   r=   r›   r•   rF   r­   rr   rª   )	r1   rœ   r�   r]   r^   r`   r_   Úbbox_labelsr5   s	           €r6   rq   zSAM2Predictor._prepare_prompts×  sÆ   ø€ ô* ).©Ñ(@ÀÈIÐW]Ð_eÐgmÐotÓ(uÑ%ˆ�˜ ØÐØ—[‘[  Q¨Ó*ˆFÜŸ,™,¨¨A¨ x´u·{±{È6Ï=É=ÔY×`Ñ`Ðag×amÑamÐnoÑapÐrtÓuˆKð Ð!ÜŸ™ F¨FÐ#3¸Ô;�ÜŸ™ K°Ð#8¸aÔ@‘à!'¨˜�Ø�v˜uÐ$Ð$r7   c                óÊ   •— t         ‰| �  |«       dD ��cg c]5  }| j                  D �cg c]  }t        || j                  |z  z  «      ‘Œ c}‘Œ7 c}}| _        yc c}w c c}}w )z9Set up the data source and image size for SAM2 inference.©g      Ð?ç      à?r   N)r(   r	  rX   ÚintrÝ   Ú_bb_feat_sizes©r1   r  rf   r[   r5   s       €r6   r	  zSAM2Predictor.setup_sourceù  sK   ø€ ä‰Ñ˜VÔ$ØYj×kÐTUÀDÇJÁJÖO¸q¤ A¨¯©°q©Ñ$9Õ :ÔOÓkˆÕùÒOùÓks   –A©"AÁAÁAc           
     óš  — | j                   j                  |«      }| j                   j                  |«      \  }}}}| j                   j                  r|d   | j                   j                  z   |d<   t        || j                  «      D ��cg c]*  \  }} |j                  ddd«      j                  ddg|¢­Ž ‘Œ, }}}|d   |dd dœS c c}}w )zLExtract image features from the SAM image encoder for subsequent processing.r9   r   r;   r   N)Úimage_embedÚhigh_res_feats)	rI   Úforward_imageÚ_prepare_backbone_featuresÚdirectly_add_no_mem_embedÚno_mem_embedr¤   rC  ÚpermuterÛ   )r1   r,   Úbackbone_outÚ_Úvision_featsÚfeatÚ	feat_sizeÚfeatss           r6   rp   zSAM2Predictor.get_im_featuresþ  sÉ   € à—z‘z×/Ñ/°Ó3ˆØ $§
¡
× EÑ EÀlÓ SÑˆˆ<˜˜AØ�:‰:×/Ò/Ø+¨BÑ/°$·*±*×2IÑ2IÑIˆL˜ÑäQTÐUaÐcg×cvÑcvÓQw÷
Ù>M¸dÀIÐ&ˆD�L‰L˜˜A˜qÓ!×&Ñ& q¨"Ð9¨yÔ9ð
ˆñ 
ð  % R™y¸EÀ#À2¸JÑGÐGùó
s   Â
/Cc           	     óì  — |�||fnd}| j                   j                  |d|¬«      \  }}|duxr |d   j                  d   dkD  }	d}
t        |t        «      r-|d   D �cg c]  }||   j                  d«      ‘Œ }
}|d   |g   }| j                   j                  || j                   j                  j                  «       ||||	|
¬«      \  }}}}|j                  dd«      |j                  dd«      fS c c}w )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.
        Nru   r   r   rG  rF  )rw   rx   ry   rz   rl   Úrepeat_imageÚhigh_res_features)	rI   Úsam_prompt_encoderrr   r<   r'   r   Úsam_mask_decoderr}   r~   )r1   r-   r^   r`   r_   rl   Úimg_idxr   r€   Úbatched_moderU  Ú
feat_levelr�   r‚   rN  s                  r6   rs   z!SAM2Predictor._inference_features	  s%  € ð2 &,Ð%7�&˜&Ñ!¸TˆØ.2¯j©j×.KÑ.KØØØð /Ló /
Ñ+ÐÐ+ð  TÐ)ÒD¨f°Q©i¯o©o¸aÑ.@À1Ñ.DˆØ ÐÜ�h¤Ô%ØT\Ð]mÑTnÖ oÀj ¨GÑ!4×!>Ñ!>¸qÕ!AÐ oÐÐ oØ Ñ.°¨yÑ9ˆHØ(,¯
©
×(CÑ(CØ%Ø—Z‘Z×2Ñ2×?Ñ?ÓAØ%6Ø$4Ø-Ø%Ø/ð )Dó )
Ñ%ˆ
�K  Að ×!Ñ! ! QÓ'¨×)<Ñ)<¸QÀÓ)BÐBÐBùò !ps   ÁC1r+  )NNNFr9   )r1  r2  r3  r4  rC  rÝ   rÙ   rq   r	  rp   rs   r6  r7  s   @r6   r9  r9  ®  sD   ø„ ñò6€Nð
 €Fò*õ %ôDlò
	Hð ØØØØ÷0Cr7   r9  c                  ó†  ‡ — e Zd ZdZeddfdˆ fd„Zˆ fd„Zdd„Zˆ f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, clearing memory for
    non-conditional inputs, and setting up callbacks for prediction events.

    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.
        callbacks (dict): A dictionary of callbacks for various prediction lifecycle events.

    Methods:
        get_model: Retrieve and configure the model with binarization enabled.
        inference: Perform image segmentation inference based on the given input cues.
        postprocess: Post-process the predictions to apply non-overlapping constraints if required.
        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.
    Nc                ó¾   •— t         ‰| �  |||«       i | _        d| _        d| _        d| _        | j                  d   j                  | j                  «       d| _	        y)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.
        TFÚon_predict_startN)
r(   r)   Úinference_stateÚnon_overlap_masksÚclear_non_cond_mem_around_inputÚ clear_non_cond_mem_for_multi_objÚ	callbacksr©   Ú
init_stateÚclear_non_cond_memr0   s       €r6   r)   zSAM2VideoPredictor.__init__`  sZ   ø€ ô 	‰Ñ˜˜i¨Ô4Ø!ˆÔØ!%ˆÔØ/4ˆÔ,Ø05ˆÔ-Ø�‰Ð)Ñ*×1Ñ1°$·/±/ÔBØ"&ˆÕr7   c                óF   •— t         ‰| �  «       }|j                  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)r1   rI   r5   s     €r6   rÙ   zSAM2VideoPredictor.get_models  s%   ø€ ô ‘Ñ!Ó#ˆØ×Ñ˜4Ô Øˆr7   c           
     ó¤  — | j                   j                  d|«      }| j                   j                  d|«      }| j                   j                  d|«      }| j                  j                  }|| j                  d<   | j                  d   }t        |d   «      dk(  r°| j                  |j                  dd	 | j                  d
   d   j                  d	d ||||«      \  }}}|�7t        t        |«      «      D ]  }| j                  |||g   ||g   |¬«       Œ! n3|�1t        t        |«      «      D ]  }| j                  |||g   |¬«       Œ | j                  «        | j                  d   }	t        | j                  d   «      }
t        |d   «      dk(  rt        d«      ‚||	d   v r9d}||   |   }| j                  ri| j                  s|
d
k  rX| j                  |«       nF||	d   v rd}||   |   }n4d}| j!                  |||
dd	d	dd¬«      }|||   |<   | j#                  |«       | j%                  |||«       | j                  d   j'                  |«       |d   j)                  dd
«      }||| j*                  j,                  kD  j/                  d«      dkD     }|t1        j2                  |j                  d   |j4                  |j6                  ¬«      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.
        r]   r^   r_   r,   Úoutput_dictÚcond_frame_outputsr   r;   Nr   )Úobj_idr^   r`   Ú	frame_idx)rk  r_   rl  Úconsolidated_frame_indsÚobj_idx_to_idú/No points are provided; please add points firstÚnon_cond_frame_outputsFT)ri  rl  Ú
batch_sizeÚis_init_cond_frameÚpoint_inputsÚmask_inputsÚreverseÚrun_mem_encoderÚframes_already_trackedr�   ©r   r;   r…   )r.   rh   r
  Úframer_  rW   rq   rr   r%   rø   Úadd_new_promptsÚpropagate_in_video_preflightÚRuntimeErrorra  rb  Ú _clear_non_cond_mem_around_inputÚ_run_single_frame_inferenceÚ_prune_non_cond_memoryÚ_add_output_per_objectr©   r~   rI   r¨   Úsumr=   r”   r†   rF   )r1   r,   r]   r^   r`   r_   ry  ri  rf   rm  rq  Ústorage_keyÚcurrent_outr�   s                 r6   rn   zSAM2VideoPredictor.inference}  s  € ð" —‘×!Ñ! (¨FÓ3ˆØ—‘×!Ñ! (¨FÓ3ˆØ—‘× Ñ  ¨%Ó0ˆà—‘×"Ñ"ˆØ%'ˆ×Ñ˜TÑ"Ø×*Ñ*¨=Ñ9ˆÜˆ{Ð/Ñ0Ó1°QÒ6Ø$(×$9Ñ$9Ø—‘˜˜�˜dŸj™j¨™m¨AÑ.×4Ñ4°R°aÐ8¸&À&È&ÐRWó%Ñ!ˆF�F˜Eð Ð!Üœs 6›{Ó+ò l�AØ×(Ñ(°¸&À!À¹+ÈfÐVWÐUXÉkÐejÐ(ÕkñlàÐ"Üœs 5›zÓ*ò V�AØ×(Ñ(°¸À¸s¹ÈuÐ(ÕUðVà×)Ñ)Ô+à"&×"6Ñ"6Ð7PÑ"QÐÜ˜×-Ñ-¨oÑ>Ó?ˆ
Üˆ{Ð/Ñ0Ó1°QÒ6ÜÐPÓQÐQàÐ+Ð,@ÑAÑAØ.ˆKØ% kÑ2°5Ñ9ˆKØ×3Ò3¸×9^Ò9^ÐblÐpqÒbqà×5Ñ5°eÕ<ØÐ-Ð.FÑGÑGØ2ˆKØ% kÑ2°5Ñ9‰Kà2ˆKØ×:Ñ:Ø'ØØ%Ø#(Ø!Ø ØØ $ð ;ó 	ˆKð /:ˆK˜Ñ$ UÑ+Ø×'Ñ'¨Ô.ð 	×#Ñ# E¨;¸ÔDØ×ÑÐ5Ñ6×=Ñ=¸eÔDØ  Ñ.×6Ñ6°q¸!Ó<ˆ
Ø ¨d¯j©j×.GÑ.GÑ!G× LÑ LÈVÓ TÐWXÑ XÑYˆ
àœ5Ÿ:™: j×&6Ñ&6°qÑ&9À×AQÑAQÐZd×ZkÑZkÔlÐlÐlr7   c                ó:  •— t         ‰| �  |||«      }| j                  r||D ]w  }|j                  �t	        |j                  «      dk(  rŒ(| j
                  j                  |j                  j                  j                  d«      «      d   |j                  _        Œy |S )a3  Post-process the predictions to apply non-overlapping constraints if required.

        This method extends the post-processing functionality by applying non-overlapping constraints to the predicted
        masks if the `non_overlap_masks` flag is set to True. This ensures that the masks do not overlap, which can be
        useful for certain applications.

        Args:
            preds (tuple[torch.Tensor, torch.Tensor]): The predicted masks and scores from the model.
            img (torch.Tensor): The processed image tensor.
            orig_imgs (list[np.ndarray]): The original images before processing.

        Returns:
            (list): The post-processed predictions.

        Notes:
            If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
        r   )	r(   r  r`  r_   rW   rI   Ú"_apply_non_overlapping_constraintsÚdatar   )r1   r   r  r  r  Úresultr5   s         €r6   r  zSAM2VideoPredictor.postprocessÆ  s�   ø€ ô$ ‘'Ñ% e¨S°)Ó<ˆØ×!Ò!Ø!ò u�Ø—<‘<Ð'¬3¨v¯|©|Ó+<ÀÒ+AØØ$(§J¡J×$QÑ$QÐRX×R^ÑR^×RcÑRc×RmÑRmÐnoÓRpÓ$qÐrsÑ$t�—‘Õ!ðuð ˆr7   c                ó   — |xs | j                   }|du |du z  sJ d«       ‚| j                  ||«      }d}d}	|�||dœ}||d   |   |<   d}	||d   |   |<   ||	   |   j                  |d«       ||d   v}
|d   |   }|d   |   }|
xs | j                  j                  }|rd	nd
}d}|�œ||   j                  |«      xs* |d	   j                  |«      xs |d
   j                  |«      }|�Z|j                  d«      �I|d   j                  | j                  | j                  j                  dk(  ¬«      }|j                  dd«       | j                  ||d|
||dd||¬«
      }|||   |<   | j                  ||d|¬«      }|d   j                  dd«      }|j                  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_objrw  Úoutput_dict_per_objÚtemp_output_dict_per_objrj  rp  r�   Úcuda)rF   Únon_blockingg      @Àg      @@r   F)
ri  rl  rq  rr  rs  rt  ru  rv  Úprev_sam_mask_logitsr_  ©Úis_condrv  r_  r   r…   )r_  Ú_obj_id_to_idxrh   rI   Ú!add_all_frames_to_correct_as_condÚgetrE   rF   ÚtypeÚclamp_r~  Ú#_consolidate_temp_output_across_objr~   r=   r”   r†   )r1   rk  r^   r`   r_   rl  r_  Úobj_idxrs  Úpop_keyrr  Úobj_output_dictÚobj_temp_output_dictr”  r‚  r’  Úprev_outrƒ  Úconsolidated_outr�   s                       r6   rz  z"SAM2VideoPredictor.add_new_promptsà  sk  € ðL *ÒA¨T×-AÑ-AˆØ˜� &¨D .Ò1ÐuÐ3uÓuÐ1Ø×%Ñ% f¨oÓ>ˆàˆØ(ˆØÐØ,2ÀFÑ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Ñ(TˆÙ.5Ñ*Ð;Sˆð  $Ðð Ð#à$ [Ñ1×5Ñ5°iÓ@ò LØ"Ð#7Ñ8×<Ñ<¸YÓGòLà"Ð#;Ñ<×@Ñ@ÀÓKð ð Ð#¨¯©°\Ó(BÐ(NØ'/°Ñ'=×'@Ñ'@ØŸ;™;°T·[±[×5EÑ5EÈÑ5Oð (Aó (Ð$ð %×+Ñ+¨E°4Ô8Ø×6Ñ6Ø'ØØØ1Ø%ØØð
 "Ø!5Ø+ð 7ó 
ˆð" 8CÐ˜[Ñ)¨)Ñ4ð  ×CÑCØØØ!Ø+ð	 Dó 
Ðð & lÑ3×;Ñ;¸A¸qÓAˆ
Ø×!Ñ! ! QÓ'¬¯©°A¸Z×=MÑ=MÐV`×VgÑVgÔ)hÐhÐhr7   c                ó\  — |xs | j                   }d|d<   t        |d   «      }|d   }|d   }|d   }dD ]î  }|rdnd	}t        «       }|j                  «       D ]$  }	|j	                  |	|   j                  «       «       Œ& ||   j	                  |«       |D ]d  }
| j                  |
|d|¬
«      }|||   |
<   | j                  |
|||¬«       | j                  sŒB| j                  s|dk  sŒT| j                  |
«       Œf |j                  «       D ]  }	|	|   j                  «        Œ Œð |d   D ]  }
|d	   j                  |
d«       Œ |d   j                  «       D ]!  }|d   D ]  }
|d	   j                  |
d«       Œ Œ# |d   D ]  }
|
|d   v sJ ‚|d	   j                  |
«       Œ! |d   |d	   z  }t        «       }|d   j                  «       D ]!  }|j	                  |j                  «       «       Œ# |d   j                  «       D ]!  }|j	                  |j                  «       «       Œ# ||k(  sJ ‚y)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_startedrn  r�  ri  rm  >   FTrj  rp  r“  ©r_  r   NrŽ  r‰  r�  )r_  rW   ÚsetÚvaluesr&   Úkeysrš  r€  ra  rb  r}  Úclearrh   Údiscard)r1   r_  rq  r�  ri  rm  r”  r‚  Útemp_frame_indsrž  rl  r   r�  Úall_consolidated_frame_indsÚinput_frames_indsÚpoint_inputs_per_frameÚmask_inputs_per_frames                    r6   r{  z/SAM2VideoPredictor.propagate_in_video_preflightM  sØ  € ð *ÒA¨T×-AÑ-Aˆà26ˆÐ.Ñ/Ü˜¨Ñ9Ó:ˆ
ð $3Ð3MÑ#NÐ Ø% mÑ4ˆð #2Ð2KÑ"LÐØ$ò 	:ˆGá29Ñ.Ð?WˆKô "›eˆOØ(@×(GÑ(GÓ(Iò QÐ$Ø×&Ñ&Ð';¸KÑ'H×'MÑ'MÓ'OÕPðQà# KÑ0×7Ñ7¸ÔHà,ò 	E�	Ø#'×#KÑ#KØ wÀÐVeð $Ló $Ð ð 7G�˜KÑ(¨Ñ3Ø×+Ñ+¨IÐ7GÈÐfuÐ+ÔvØ×7Ó7¸T×=bÒ=bÐfpÐtuÓfuà×9Ñ9¸)ÕDð	Eð )A×(GÑ(GÓ(Iò :Ð$Ø$ [Ñ1×7Ñ7Õ9ñ:ð/	:ð8 %Ð%9Ñ:ò 	GˆIØÐ0Ñ1×5Ñ5°iÀÕFð	Gà.Ð/DÑE×LÑLÓNò 	OˆOØ,Ð-AÑBò O�	ØÐ 8Ñ9×=Ñ=¸iÈÕNñOð	Oð 1Ð1EÑFò 	QˆIØ Ð,@Ñ AÑAÐAÐAØ#Ð$<Ñ=×EÑEÀiÕPð	Qð $Ð$8Ñ9Ð<SÐTlÑ<mÑmð 	$ô  ›EÐØ&5Ð6LÑ&M×&TÑ&TÓ&Vò 	DÐ"Ø×$Ñ$Ð%;×%@Ñ%@Ó%BÕCð	Dà%4Ð5JÑ%K×%RÑ%RÓ%Tò 	CÐ!Ø×$Ñ$Ð%:×%?Ñ%?Ó%AÕBð	Cà*Ð.?Ò?Ð?Ñ?r7   c                óÜ   — t        | j                  «      dkD  ry| j                  €J ‚| j                  j                  dk(  sJ ‚| j	                  | j                  j
                  «      | _        y)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   NÚvideo)rW   r_  r
  r$   Ú_init_stateÚframes)Ú	predictors    r6   rd  zSAM2VideoPredictor.init_state˜  se   € ô ˆy×(Ñ(Ó)¨AÒ-ØØ× Ñ Ð,Ð,Ð,Ø× Ñ ×%Ñ%¨Ò0Ð0Ð0Ø$-×$9Ñ$9¸)×:KÑ:K×:RÑ:RÓ$Sˆ	Õ!r7   c                ór   — | 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.
        ©rj  rp  F)Ú
num_framesr‰  r�  Ú	constantsÚobj_id_to_idxrn  Úobj_idsri  rŽ  r�  rm  r¢  rw  )r   r¤  )rµ  r_  s     r6   r°  zSAM2VideoPredictor._init_state©  s\   € ð %Ø$&Ø#%Øä(›]Ü(›]Øð ')Ø*,ñð
 $&ð )+ô '*£eÜ*-«%ñ(ð
 %*Ø&(ñ7
ˆð: Ðr7   c                ó¤   — t        | dd«      }|€| j                  j                  |«      }| 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.
        rM  N©r%   )ÚgetattrrI   rH  rI  )r1   r,   r%   rM  rN  Ú	vis_featsÚvis_pos_embedÚ
feat_sizess           r6   rp   z"SAM2VideoPredictor.get_im_featuresÓ  s]   € ô" ˜t ^°TÓ:ˆØÐØŸ:™:×3Ñ3°BÓ7ˆLØ26·*±*×2WÑ2WÐXdÐlqÐ2WÓ2rÑ/ˆˆ9�m ZØ˜-¨Ð3Ð3r7   c                ó<  — |xs | j                   }|d   j                  |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¢  rn  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—  rW   rù   r|  )r1   rk  r_  r›  Úallow_new_objects        r6   r•  z!SAM2VideoPredictor._obj_id_to_idxê  s  € ð* *ÒA¨T×-AÑ-AˆØ! /Ñ2×6Ñ6°v¸tÓDˆØÐØˆNð  /Ð/EÑFÐFÐÙä˜/¨/Ñ:Ó;ˆGØ7>ˆO˜OÑ,¨VÑ4Ø8>ˆO˜OÑ,¨WÑ5Ü)-¨o¸oÑ.NÓ)OˆO˜IÑ&à?AˆOÐ2Ñ3°GÑ<Ø>@ˆOÐ1Ñ2°7Ñ;à&(Ø*,ñ?ˆOÐ1Ñ2°7Ñ;ð
 ')Ø*,ñDˆOÐ6Ñ7¸Ñ@ð ˆNäØ+¨F¨8ð 4,Ø,;¸IÑ,FÐ+Gð HEðFóð r7   c                ó‚  — |
xs | j                   }
| j                  |
d   |«      \  }}}|�|�J ‚| j                  j                  |||||||||
d   |||	¬«      }|d   }|�F|j	                  t
        j                  | j                  | j                  j                  dk(  ¬«      |d<   | j                  |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,   rµ  ©rl  rr  Úcurrent_vision_featsÚcurrent_vision_pos_embedsr¾  rs  rt  ri  rµ  Útrack_in_reverserv  r’  Úmaskmem_featuresr�  ©r†   rF   r‘  Úmaskmem_pos_enc)
r_  rp   rI   Ú
track_steprE   r=   rß   rF   r˜  Ú_get_maskmem_pos_enc)r1   ri  rl  rq  rr  rs  rt  ru  rv  r’  r_  rÃ  rÄ  r¾  rƒ  rÆ  s                   r6   r~  z.SAM2VideoPredictor._run_single_frame_inference   s  € ðP *ÒA¨T×-AÑ-AˆàFJ×FZÑFZØ˜DÑ! :óG
ÑCÐÐ7¸ð
 Ð# {Ð':Ð:Ð:Ø—j‘j×+Ñ+ØØ1Ø!5Ø&?Ø!Ø%Ø#Ø#Ø& |Ñ4Ø$Ø+Ø!5ð ,ó 
ˆð 'Ð'9Ñ:ÐØÐ'Ø.>×.AÑ.AÜ—m‘m¨D¯K©KÀdÇkÁk×FVÑFVÐZ`ÑF`ð /Bó /ˆKÐ*Ñ+ð *.×)BÑ)BÀ;ÐO`ÑCaÐcrÓ)sˆÐ%Ñ&ØÐr7   c           	     ó:  — |xs | j                   }|d   }|�yd|vr8t        |t        «      sJ ‚|D �cg c]  }|dd j                  «       ‘Œ }}||d<   n|d   }|d   j                  d   }|dkD  r!|D �cg c]  }|j                  |ddd«      ‘Œ }}|S c c}w c c}w )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È  r   r   r9   )r_  r<   rù   Úclonerr   r­   )r1   Úout_maskmem_pos_encr_  Úmodel_constantsr[   rÈ  rq  s          r6   rÊ  z'SAM2VideoPredictor._get_maskmem_pos_encn  sÃ   € ð0 *ÒA¨T×-AÑ-AˆØ)¨+Ñ6ˆàÐ*Ø ¨Ñ7Ü!Ð"5´tÔ<Ð<Ð<à:MÖ"N°Q 1 R a 5§;¡;¥=Ð"N�Ð"NØ5D�Ð 1Ò2à"1Ð2CÑ"D�à,¨QÑ/×5Ñ5°aÑ8ˆJØ˜AŠ~ØQ`Ö&aÈA q§x¡x°
¸BÀÀBÕ'GÐ&aÐ#Ð&aØ"Ð"ùò #Oùò 'bs   ²BÁ4Bc           
     óà  — |xs | j                   }t        |d   «      }|rdnd}ddt        j                  |dg| j                  d   ¢­d| j
                  | j                  ¬«      t        j                  || j                  j                  fd| j
                  | j                  ¬«      t        j                  |dfd	| j
                  | j                  ¬«      d
œ}t        |«      D ]�  }|d   |   }	|d   |   }
|	|   j                  |«      xs* |
d   j                  |«      xs |
d   j                  |«      }|€|r| j                  |«      |d   ||dz    Œr|d   |d   ||dz    |d   |d   ||dz    Œ� |ryt        j                  |d   | j                  dd¬«      }| j                  j                  r| j                  j!                  |«      }| 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.
        rn  rj  rp  Nr   r   ç      �À©ÚsizeÚ
fill_valuer†   rF   ç      $@©rÆ  rÈ  r�   Úobj_ptrÚobject_score_logitsr�  rŽ  rÖ  r�   r¡   F©rÒ  r$   r¢   Tr×  )rq  Úhigh_res_masksÚis_mask_from_ptsr×  r_  rÆ  rÈ  )r_  rW   r=   ÚfullrC  r’   rF   rI   Ú
hidden_dimrø   r—  Ú_get_empty_mask_ptrr¦   r§   rX   Únon_overlap_masks_for_mem_encr…  Ú_run_memory_encoder)r1   rl  r”  rv  r_  rq  r‚  r   r›  rž  r�  ÚoutrÙ  s                r6   rš  z6SAM2VideoPredictor._consolidate_temp_output_across_obj—  sT  € ð> *ÒA¨T×-AÑ-AˆÜ˜¨Ñ9Ó:ˆ
Ù.5Ñ*Ð;Sˆð !%Ø#ÜŸ*™*à  !Ð= d×&9Ñ&9¸!Ñ&<Ñ=Ø"Ø×&Ñ&Ø—{‘{ôô —z‘zØ  $§*¡*×"7Ñ"7Ð8Ø"Ø×&Ñ&Ø—{‘{ô	ô $)§:¡:Ø  !�_ð  Ø×&Ñ&Ø—{‘{ô$ñ!
Ðô2 ˜ZÓ(ò 	PˆGØ#2Ð3MÑ#NÈwÑ#WÐ Ø-Ð.CÑDÀWÑMˆOà$ [Ñ1×5Ñ5°iÓ@ò Lð
 #Ð#7Ñ8×<Ñ<¸YÓGòLð #Ð#;Ñ<×@Ñ@ÀÓKð ð ˆ{ñ #àIM×IaÑIaÐbkÓIlÐ$ YÑ/°¸'ÀA¹+ÐFØàDGÈÑDUÐ˜\Ñ*¨7°W¸q±[ÐAØADÀYÁÐ˜YÑ'¨°'¸A±+Ñ>ð3	Pñ8 ÜŸ]™]Ø  Ñ.Ø—Z‘ZØØ#ô	ˆNð �z‰z×7Ò7Ø!%§¡×!NÑ!NÈ~Ó!^�ØX\×XpÑXpØ%Ø-Ø!%Ø$4Ð5JÑ$KØ /ð Yqó YÑUÐÐ/Ñ0Ð2BÐCTÑ2Uð  Ðr7   c                ó"  — |xs | j                   }| j                  |d   «      \  }}}| j                  j                  |d|||dt	        j
                  ddg| j                  ¢­| 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_  rp   rI   rÉ  r=   rû   rX   r’   rF   )r1   rl  r_  rÃ  rÄ  r¾  rƒ  s          r6   rÝ  z&SAM2VideoPredictor._get_empty_mask_ptr  s­   € ð *ÒA¨T×-AÑ-AˆàFJ×FZÑFZÐ[jÐkoÑ[pÓFqÑCÐÐ7¸ð —j‘j×+Ñ+ØØ#Ø!5Ø&?Ø!ØäŸ™ Q¨Ð$7¨D¯J©JÑ$7¸t×?OÑ?OÐX\×XcÑXcÔdØØ& |Ñ4Ø"Ø!Ø!%ð ,ó 
ˆð ˜9Ñ%Ð%r7   c                óH  — |xs | j                   }| j                  |d   |«      \  }}}| j                  j                  |||||¬«      \  }	}
| j	                  |
|«      }
|	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_  rp   rI   Ú_encode_new_memoryrÊ  rE   r=   rß   rF   r˜  )r1   rq  rÙ  r×  rÚ  r_  rÃ  rN  r¾  rÆ  rÈ  s              r6   rß  z&SAM2VideoPredictor._run_memory_encoder'  s·   € ð2 *ÒA¨T×-AÑ-Aˆà.2×.BÑ.BÀ?ÐSWÑCXÐZdÓ.eÑ+Ð˜a Ø,0¯J©J×,IÑ,IØ!5Ø!Ø .Ø-Ø 3ð -Jó -
Ñ)Ð˜/ð ×3Ñ3°OÀ_ÓUˆØ×"Ñ"Ü—-‘-¨¯©À$Ç+Á+×BRÑBRÐV\ÑB\ð #ó 
àðð 	r7   c                ót  — |xs | j                   }|d   }|�t        |t        j                  «      sJ ‚|d   }|�t        |t        «      sJ ‚|d   j                  «       D ]Q  \  }}t        ||dz   «      }	dd|d   |	   |d   |	   dœ}
|�||	   |
d<   |�|D �cg c]  }||	   ‘Œ	 c}|
d<   |
||   |<   ŒS yc c}w )	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Ö  )r_  r<   r=   r>   rù   ÚitemsÚslice)r1   rl  rƒ  r‚  r_  rÆ  rÈ  r›  r�  Ú	obj_sliceÚobj_outr[   s               r6   r€  z)SAM2VideoPredictor._add_output_per_objectQ  s  € ð *ÒA¨T×-AÑ-AˆØ&Ð'9Ñ:ÐØÐ'¬:Ð6FÌÏÉÔ+UÐUÐUà%Ð&7Ñ8ˆØÐ&¬*°_ÄdÔ*KÐKÐKà(7Ð8MÑ(N×(TÑ(TÓ(Vò 	>Ñ$ˆG�_Ü˜g w°¡{Ó3ˆIà$(Ø#'Ø)¨,Ñ7¸	ÑBØ& yÑ1°)Ñ<ñ	ˆGð  Ð+Ø.>¸yÑ.I�Ð*Ñ+ØÐ*ØDSÖ-T¸q¨a°	«lÒ-T�Ð)Ñ*Ø6=ˆO˜KÑ(¨Ò3ñ	>ùò .Us   ÂB5c                ór  — |xs | j                   }| j                  j                  }||| j                  j                  z  z
  }||| j                  j                  z  z   }t	        ||dz   «      D ]G  }|d   d   j                  |d«       |d   j                  «       D ]  }|d   j                  |d«       Œ ŒI y)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   ri  rp  NrŽ  )r_  rI   Úmemory_temporal_stride_for_evalÚnum_maskmemrø   rh   r¥  )r1   rl  r_  rž   Úframe_idx_beginÚframe_idx_endÚtr�  s           r6   r}  z3SAM2VideoPredictor._clear_non_cond_mem_around_inputt  sÃ   € ð *ÒA¨T×-AÑ-AˆØ�J‰J×6Ñ6ˆØ# a¨$¯*©*×*@Ñ*@Ñ&@Ñ@ˆØ! A¨¯
©
×(>Ñ(>Ñ$>Ñ>ˆÜ�¨¸Ñ(9Ó:ò 	GˆAØ˜MÑ*Ð+CÑD×HÑHÈÈDÔQØ#2Ð3HÑ#I×#PÑ#PÓ#Rò G�ØÐ 8Ñ9×=Ñ=¸aÀÕFñGñ	Gr7   c                ó’  ‡ ‡‡‡‡— ‰d   j                  |d«      }|€|s‰d   S t        d|› d‰d   › d�«      ‚t        ‰d   «      dk(  r‰ j                  ‰«       ‰d   S t	        «       }|j                  ‰d   |   «       |j                  ‰d	   |   «       |D ]  }‰ j                  ‰||«       Œ ‰d   }t        t        t        |«      «      «      Š‰j                  «       Š‰j                  |«       ‰D �cg c]  }||   ‘Œ	 }	}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 c c}w )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�  rn  c                ó’   •— g }‰D ].  }| j                  |«      }|‰v sŒ|j                  ‰|   |f«       Œ0 | j                  |«       y rb   )rh   r©   r&   )Ú	containerÚnew_kvsÚkÚvÚold_idx_to_new_idxÚold_obj_indss       €€r6   Ú	_map_keysz3SAM2VideoPredictor.remove_object.<locals>._map_keysº  sU   ø€ ØˆGØ!ò ?�Ø—M‘M !Ó$�ØÐ*Ò*Ø—N‘NÐ$6°qÑ$9¸1Ð#=Õ>ð?ð ×Ñ˜WÕ%r7   rŽ  r�  c                ó*  •— | |   j                  «       D ]w  \  }}|d   ‰   |d<   |d   D �cg c]  }|‰   ‘Œ	 c}|d<   ‰j                  |d   ‰«      |d<   |d   ‰   |d<   |d   ‰   |d<   |d   ‰   |d<   ‰j                  |||‰¬«       Œy y c c}w )NrÆ  rÈ  r�   rÖ  r×  r£  )ræ  rÊ  r€  )ri  r‚  rl  rà  r[   r_  Úremain_old_obj_indsr1   s        €€€r6   Ú_slice_statez6SAM2VideoPredictor.remove_object.<locals>._slice_stateÈ  sØ   ø€ Ø"-¨kÑ":×"@Ñ"@Ó"Bò 	j‘�	˜3Ø*-Ð.@Ñ*AÐBUÑ*V�Ð&Ñ'ØJMÐN_ÑJ`Ö)aÀQ¨!Ð,?Ó*@Ò)a�Ð%Ñ&à)-×)BÑ)BÀ3ÐGXÑCYÐ[jÓ)k�Ð%Ñ&Ø$'¨Ñ$5Ð6IÑ$J��LÑ!Ø!$ Y¡Ð0CÑ!D��I‘Ø-0Ð1FÑ-GÐH[Ñ-\�Ð)Ñ*à×+Ñ+¨I°s¸KÐYhÐ+Õiñ	jùâ)as   ­Bri  rj  rp  )r—  r|  rW   Úclear_all_points_in_videor¤  r&   Úclear_all_points_in_framerù   rø   ÚcopyÚremover'   r¤   )r1   r_  rk  ÚstrictÚold_obj_idx_to_rmÚobj_input_frames_indsrl  Úold_obj_idsÚold_idxÚnew_obj_idsÚnew_obj_indsrø  rû  rö  r÷  rú  s   ``           @@@r6   Úremove_objectz SAM2VideoPredictor.remove_objectŠ  s  ü€ ð
 ,¨OÑ<×@Ñ@ÀÈÓNÐàÐ$ÙØ& yÑ1Ð1ÜØ*¨6¨(ð 3,Ø,;¸IÑ,FÐ+GÀqðJóð ô ˆ˜Ñ/Ó0°AÒ5Ø×*Ñ*¨?Ô;Ø" 9Ñ-Ð-ô !$£ÐØ×$Ñ$ _Ð5KÑ%LÐM^Ñ%_Ô`Ø×$Ñ$ _Ð5JÑ%KÐL]Ñ%^Ô_Ø.ò 	OˆIØ×*Ñ*¨?¸IÀvÕNð	Oð
 & iÑ0ˆÜœE¤# kÓ"2Ó3Ó4ˆØ*×/Ñ/Ó1ÐØ×"Ñ"Ð#4Ô5Ø;NÖO°�{ 7Ó+ÐOˆÐOÜœE¤# kÓ"2Ó3Ó4ˆä!¤#Ð&9¸<Ó"HÓIÐÜ+/´°KÀÓ0NÓ+Oˆ˜Ñ(Ü+/´°LÀ+Ó0NÓ+Oˆ˜Ñ(Ø%0ˆ˜	Ñ"õ
	&ñ 	�/Ð"8Ñ9Ô:Ù�/Ð"7Ñ8Ô9Ù�/Ð"7Ñ8Ô9Ù�/Ð"<Ñ=Ô>ö
	jñ 	�_ ]Ñ3Ð5IÔJÙ�_ ]Ñ3Ð5MÔNà˜yÑ)Ð)ùòQ Ps   Ã9Gc                óò  — | j                  ||«      }|d   |   j                  |d«       |d   |   j                  |d«       |d   }||   d   j                  |d«       ||   d   j                  |d«       t        |d   «      }d}t        |«      D ]  }||d   |   v rd	} n||d   |   v sŒd	} n |sÂ|d
   }	|d   }
|
d   j	                  |«       |
d   j	                  |«       |	d   j                  |d«      }|�||	d   |<   |d   j                  |d«       t        |«      D ]*  }|d   |   }|d   j                  |d«      }|€Œ#||d   |<   Œ, t        |	d   «      dk(  r| j                  |«       yyy)zGRemove all input points or mask in a specific frame for a given object.r‰  Nr�  r�  rj  rp  rn  FTri  rm  rw  rŽ  r   )r•  rh   rW   rø   r¨  Ú_reset_tracking_results)r1   r_  rl  rk  r›  r�  rq  Úframe_has_inputÚobj_idx2ri  rm  rà  r�  ré  s                 r6   rý  z,SAM2VideoPredictor.clear_all_points_in_frameÙ  sü  € ð ×%Ñ% f¨oÓ>ˆð 	Ð.Ñ/°Ñ8×<Ñ<¸YÈÔMØÐ-Ñ.¨wÑ7×;Ñ;¸IÀtÔLà#2Ð3MÑ#NÐ Ø  Ñ)Ð*>Ñ?×CÑCÀIÈtÔTØ  Ñ)Ð*BÑC×GÑGÈ	ÐSWÔXô ˜¨Ñ9Ó:ˆ
ØˆÜ˜jÓ)ò 	ˆHØ˜OÐ,BÑCÀHÑMÑMØ"&�ÙØ˜OÐ,AÑBÀ8ÑLÒLØ"&�Ùð	ñ Ø)¨-Ñ8ˆKØ&5Ð6OÑ&PÐ#Ø#Ð$8Ñ9×AÑAÀ)ÔLØ#Ð$<Ñ=×EÑEÀiÔPàÐ2Ñ3×7Ñ7¸	À4ÓHˆCØˆð DG�Ð4Ñ5°iÑ@ØÐ 8Ñ9×=Ñ=¸iÈÔNä! *Ó-ò S�Ø"1Ð2GÑ"HÈÑ"R�Ø)Ð*>Ñ?×CÑCÀIÈtÓT�ØÑ&ØKR�OÐ$<Ñ=¸iÒHð	Sô �;Ð3Ñ4Ó5¸Ò:Ø×,Ñ,¨_Õ=ð ;ð) r7   c                ó0  — | j                  |«       |d   j                  «        |d   j                  «        |d   j                  «        |d   j                  «        |d   j                  «        |d   j                  «        |d   j                  «        y)	zCRemove all input points or mask in all frames throughout the video.r·  rn  r¸  r‰  r�  rŽ  r�  N)r	  r§  )r1   r_  s     r6   rü  z,SAM2VideoPredictor.clear_all_points_in_video
  s�   € ð 	×$Ñ$ _Ô5à˜Ñ(×.Ñ.Ô0Ø˜Ñ(×.Ñ.Ô0Ø˜	Ñ"×(Ñ(Ô*ØÐ.Ñ/×5Ñ5Ô7ØÐ-Ñ.×4Ñ4Ô6ØÐ-Ñ.×4Ñ4Ô6ØÐ2Ñ3×9Ñ9Õ;r7   c                ó†  — | d   j                  «       D ]  }|j                  «        Œ | d   j                  «       D ]  }|j                  «        Œ | d   j                  «       D ](  }|d   j                  «        |d   j                  «        Œ* | d   j                  «       D ](  }|d   j                  «        |d   j                  «        Œ* | d   d   j                  «        | d   d   j                  «        | d   d   j                  «        | d   d   j                  «        d	| d
<   | d   j                  «        d| d<   y)z8Reset all tracking inputs and results across the videos.r‰  r�  rŽ  rj  rp  r�  ri  rm  Fr¢  rw  NÚfirst_ann_frame_idx)r¥  r§  )r_  rõ  s     r6   r	  z*SAM2VideoPredictor._reset_tracking_results  s`  € ð !Ð!7Ñ8×?Ñ?ÓAò 	ˆAØ�G‰G�Ið	à Ð!6Ñ7×>Ñ>Ó@ò 	ˆAØ�G‰G�Ið	à Ð!6Ñ7×>Ñ>Ó@ò 	0ˆAØÐ"Ñ#×)Ñ)Ô+ØÐ&Ñ'×-Ñ-Õ/ð	0ð !Ð!;Ñ<×CÑCÓEò 	0ˆAØÐ"Ñ#×)Ñ)Ô+ØÐ&Ñ'×-Ñ-Õ/ð	0ð 	˜Ñ&Ð';Ñ<×BÑBÔDØ˜Ñ&Ð'?Ñ@×FÑFÔHØÐ1Ñ2Ð3GÑH×NÑNÔPØÐ1Ñ2Ð3KÑL×RÑRÔTØ27ˆÐ.Ñ/ØÐ0Ñ1×7Ñ7Ô9Ø15ˆÐ-Ò.r7   c                óÒ  — | j                   sy|xs | j                  }|| j                  j                  | j                  j                  z  z
  }|d   }|d   D �cg c]
  }||k  sŒ	|‘Œ c}D ]  }|d   j                  |d«       Œ |j                  di «      j                  «       D ]5  }|d   D �cg c]
  }||k  sŒ	|‘Œ c}D ]  }|d   j                  |d«       Œ Œ7 yc c}w c c}w )z8Prune old non-conditioning frames to bound memory usage.Nri  rp  rŽ  )re  r_  rI   rì  rë  rh   r—  r¥  )r1   rl  r_  Ú	min_frameri  rô  Úfr�  s           r6   r  z)SAM2VideoPredictor._prune_non_cond_memory,  s   € à×&Ò&ØØ)ÒA¨T×-AÑ-Aˆð  §
¡
× 6Ñ 6¸¿¹×9cÑ9cÑ cÑcˆ	Ø% mÑ4ˆð )Ð)AÑBÖT˜ÀaÈ)Ãm’!ÒTò 	?ˆAØÐ0Ñ1×5Ñ5°a¸Õ>ð	?ð  /×2Ñ2Ð3HÈ"ÓM×TÑTÓVò 	GˆOØ!0Ð1IÑ!JÖ\˜AÈaÐR[Ëm’aÒ\ò G�ØÐ 8Ñ9×=Ñ=¸aÀÕFñGñ	Gùò	 Uùò
 ]s   Á
CÁ%CÂ0
C$Â;C$r)  r+  )NNNr   N)r_  údict[str, Any] | Nonerb   ©r   ©NN)FFN©F)r1  r2  r3  r4  r   r)   rÙ   rn   r  r   rz  r{  r5  rd  r°  rp   r•  r~  rÊ  rš  rÝ  rß  r€  r}  r  rý  rü  r	  r  r6  r7  s   @r6   r\  r\  <  s‹  ø„ ñðF '°$ÐRVö 'ô&óGmôRñ4 Óð ØØØØ15ðjið /òjió ðjiñX ÓóH@ó ðH@ðT ñTó ðTð  ñ'ó ð'óR4ô.4ð@ "Ø15ðLð /óLô\'#ðX ØØ15ðm ð
 /óm ô^&ðN 26ð(ð /ó(ðV ]að!>ØDYó!>ôFGñ, ÓòL*ó ðL*ñ\ Óñ.>ó ð.>ñ` Óñ
<ó ð
<ð ñ6ó ð6÷(Gr7   r\  c                  ó  ‡ — e Zd ZdZedddf	 	 	 	 	 	 	 	 	 dˆ fd„Z e«       	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd„«       Zdd„Z e«       	 	 	 	 d	 	 	 	 	 	 	 	 	 dd„«       Z	dd„Z
dd	„Zdd
„Z	 	 	 	 d	 	 	 	 	 	 	 	 	 dd„Zˆ xZS )Ú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:   c                óÂ   •— t         ‰| �  |||«       d| _        g | _        t	        «       | _        t        t        t        |«      «      «      x| _	        | _
        || _        y)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)   r`  Úmemory_bankr¤  Úobj_idx_setr   r÷   rø   r·  rn  Ú_max_obj_num)r1   r2   r3   Úmax_obj_numr4   r5   s        €r6   r)   z(SAM2DynamicInteractivePredictor.__init__Z  s[   ø€ ô& 	‰Ñ˜˜i¨Ô4Ø!%ˆÔð ˆÔô ›5ˆÔÜ2=¼iÌÈkÓHZÓ>[Ó2\Ð\ˆÔ˜TÔ/Ø'ˆÕr7   c                ó¼  — | j                  |«       | j                  | j                  | j                  d   d   j                  dd ||||¬«      \  }}}|rît        |t        «      r|g}|€J d«       ‚|€	|€J d«       ‚|€st        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
«       ‚| j                  ||||«       | j                  «       }|d   |d   }
}	t        | j                  «      dk(  rt!        d«      ‚t#        | j                  «      }|	|   |
|   }
}	t        j$                  |
dz  d¬«      }
|	j'                  dd«      |
j'                  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   r   Nr;   )rœ   r�   r^   r]   r`   r_   z3obj_ids must be provided when update_memory is TruezDbboxes, masks, or points must be provided when update_memory is Truer…   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�   )rp   rq   rX   r%   rr   r<   rB  r=   rû   rW   r’   rF   r•   Úupdate_memoryrÉ  r  r|  rù   r™  r~   )r1   r,   r]   r_   r^   r`   r¸  r  rƒ  r�   r‚   rÏ   s               r6   rn   z)SAM2DynamicInteractivePredictor.inferencey  sç  € ð< 	×Ñ˜RÔ Ø $× 5Ñ 5Ø—j‘jØ—j‘j ‘m AÑ&×,Ñ,¨R¨aÐ0ØØØØð !6ó !
Ñˆ�˜ñ Ü˜'¤3Ô'Ø"˜)�ØÐ&Ð]Ð(]Ó]Ð&ØÐ$¨Ð(:ð ØVóÐ:ð ˆ~ÜŸ™¤c¨'£l°A°qÐ%9À×AQÑAQÐZ^×ZeÑZeÔf�ÜŸ™¤c¨'£l°AÐ%6¼e¿k¹kÐRV×R]ÑR]Ô^�ØÐ Ü˜5“z¤S¨£\Ò1ÐaÐ3aÓaÐ1Ü�v“;¤# g£,Ò.Ð_Ð0_Ó_Ð.Ø×Ñ˜w¨°¸Ô>à—o‘oÓ'ˆØ"-¨lÑ";¸[ÐI^Ñ=_�Kˆ
äˆt×ÑÓ  AÒ%ÜÐnÓoÐoÜ�4×#Ñ#Ó$ˆØ",¨S¡/°;¸sÑ3C�Kˆ
ô —l‘l ;°Ñ#3¸Ô;ˆØ×!Ñ! ! QÓ'¨×)<Ñ)<¸QÀÓ)BÐBÐBr7   c           
     ó:  — t         j                  | || j                  ¬«      \  }}}t        |dd |dd «      D ��cg c]7  \  }} |j	                  ddd«      j
                  g |j                  dd ¢|¢­Ž ‘Œ9 c}}| _        || _        || _	        || _
        yc c}}w )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º  Nr9   r   r;   r   )r\  rp   r  r¤   rL  rÛ   rr   rU  rO  Úvision_pos_embedsr¾  )r1   r  r¼  r½  r¾  rP  rQ  s          r6   rp   z/SAM2DynamicInteractivePredictor.get_im_features¼  sª   € ô 0B×/QÑ/QÐRVÐX[Ðcg×ctÑctÐ/QÓ/uÑ,ˆ	�= *ô $' y°°" ~°zÀ#À2°Ó#G÷"
á��ið 'ˆD�L‰L˜˜A˜qÓ!×&Ñ&ÐC¨¯
©
°1°2¨ÐC¸ÔCó"
ˆÔð
 &ˆÔØ!.ˆÔØ$ˆ�ùó"
s   ¼<Bc           
     óÈ  — 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 ‚| j                  t        |«      «      }| j                  j                  |«       ||g   ||g   }
}	|�	||g   d   nd}|	€	|€J d	«       ‚| j                  ||	|
|«      }|€Œˆ|d
   }|j                  dd |d
   j                  dd k(  s.J d|d
   j                  dd › d|j                  dd › d|› d�«       ‚||d
   ||dz    |d   |d   ||dz    d|v sŒû|d   |d   ||dz    �Œ t        j                   |d
   j#                  | j
                  | j
                  j$                  dk(  ¬«      | j                  dd¬«      }| j                  j&                  r| j                  j)                  |«      }| j                  j+                  | j,                  | j.                  ||d   d¬«      \  }}||d<   ||d<   | j0                  j3                  |«       y)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�   r‡   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  rX   r’   rF   rI   rÜ  r÷   r•  rB  r  ÚaddrÉ  rr   r¦   r§   rE   r˜  rÞ  r…  rä  rO  r¾  r  r©   )r1   r¸  r^   r`   r_   r   rf   rk  r›  ÚpointÚlabelr$  rà  Úobj_maskrÙ  rÆ  rÈ  s                    r6   r  z-SAM2DynamicInteractivePredictor.update_memoryÌ  sC  € ð" !%Ø#ÜŸ*™*Ø×'Ñ'¨¨D¯J©J°q©M¸QÑ,>ÀÇ
Á
È1ÁÐQRÑ@RÐSØ"Ø×&Ñ&Ø—{‘{ô	ô —z‘zØ×'Ñ'¨¯©×)>Ñ)>Ð?Ø"Ø×&Ñ&Ø—{‘{ô	ô $)§:¡:Ø×'Ñ'¨Ð+ð Ø×&Ñ&Ø—{‘{ô$ñ
Ðô2 # 7Ó+ó 	p‰IˆAˆvØ˜D×-Ñ-Ò-Ð-Ð-Ø×)Ñ)¬#¨f«+Ó6ˆGØ×Ñ× Ñ  Ô)Ø! 1 #™;¨°¨s©�5ˆEØ',Ð'8�5˜!˜‘:˜dÒ#¸dˆDàÐ$¨Ð(8ÐcÐ:cÓcÐ8Ø—/‘/ '¨5°%¸Ó>ˆCØ‰Ø˜|Ñ,�Ø—~‘~ b cÐ*Ð.>¸|Ñ.L×.RÑ.RÐSUÐSVÐ.WÒWð Ø*Ð+;¸LÑ+I×+OÑ+OÐPRÐPSÐ+TÐ*UÐU^Ð_g×_mÑ_mÐnpÐnqÐ_rÐ^sÐsð  AHð  @Ið  IJð  KóÐWð IQÐ  Ñ.¨w¸À1¹ÐEØEHÈÁ^Ð  Ñ+¨G°gÀ±kÐBà(¨CÒ/ØUXÐYnÑUoÐ$Ð%:Ñ;¸GÀgÐPQÁkÒRð%	pô( Ÿ™Ø˜\Ñ*×-Ñ-¨d¯k©kÈÏÉ×HXÑHXÐ\bÑHbÐ-ÓcØ—‘ØØô	
ˆð �:‰:×3Ò3Ø!ŸZ™Z×JÑJÈ>ÓZˆNØ,0¯J©J×,IÑ,IØ!%×!2Ñ!2Ø—‘Ø .Ø 0Ð1FÑ GØ!ð -Jó -
Ñ)Ð˜/ð 0@ÐÐ+Ñ,Ø.=ÐÐ*Ñ+Ø×Ñ×ÑÐ 0Õ1r7   c                óî  — t        | j                  «      dk(  st        |t        «      r'| j                  d   | j
                  j                  z   }nM| j                  «       \  }}| j
                  j                  | j                  dd | j                  dd ||d¬«      } |j                  ddd«      j                  | j                  | j
                  j                  j                  g| j                  d   ¢­Ž 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   r9   N)ÚcurrÚcurr_posÚmemoryÚ
memory_posÚnum_obj_ptr_tokensr   r;   )rW   r  r<   rB  rO  rI   rK  Úget_maskmem_encÚmemory_attentionr   rL  rÛ   r  Úd_modelr¾  )r1   r›  Úpix_feat_with_memr*  Úmemory_pos_embeds        r6   Ú$_prepare_memory_conditioned_featureszDSAM2DynamicInteractivePredictor._prepare_memory_conditioned_features  sñ   € ô ˆt×ÑÓ  AÒ%¬°G¼SÔ)Að !%× 1Ñ 1°"Ñ 5¸¿
¹
×8OÑ8OÑ OÑð (,×';Ñ';Ó'=Ñ$ˆFÐ$Ø $§
¡
× ;Ñ ;Ø×&Ñ& r sÐ+Ø×/Ñ/°°Ð4ØØ+Ø#$ð !<ó !Ðð 7Ð ×(Ñ(¨¨A¨qÓ1×6Ñ6Ø×ÑØ�J‰J×'Ñ'×/Ñ/ð
ð �_‰_˜RÑ ò
ð 	
r7   c                óÐ  — g g }}| j                   D ]¢  }|j                  |d   j                  d«      j                  ddd«      «       |d   d   j                  d«      j                  ddd«      }|| j                  j
                  | j                  j                  dz
     z   }|j                  |«       Œ¤ 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È  r9   rò   )	r  r©   r~   rL  rI   Úmaskmem_tpos_encrì  r=   rª   )r1   Úto_cat_memoryÚto_cat_memory_pos_embedr   Úmaskmem_encr*  r1  s          r6   r-  z/SAM2DynamicInteractivePredictor.get_maskmem_enc@  sè   € à13°RÐ.ˆØ $× 0Ñ 0ò 	8ÐØ× Ñ Ð!1Ð2DÑ!E×!MÑ!MÈaÓ!P×!XÑ!XÐYZÐ\]Ð_`Ó!aÔbØ*Ð+<Ñ=¸bÑA×IÑIÈ!ÓL×TÑTÐUVÐXYÐ[\Ó]ˆKØ%¨¯
©
×(CÑ(CÀDÇJÁJ×DZÑDZÐ]^ÑD^Ñ(_Ñ_ˆKØ#×*Ñ*¨;Õ7ð		8ô —‘˜=¨aÔ0ˆÜ Ÿ9™9Ð%<À!ÔDÐØÐ'Ð'Ð'r7   c                ó:   — | j                   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—  )r1   rk  s     r6   r•  z.SAM2DynamicInteractivePredictor._obj_id_to_idxM  s   € ð ×!Ñ!×%Ñ% f¨dÓ3Ð3r7   c                ó2  — |�™| j                   j                  rƒ| j                  d   j                  ddd«      } |j                  d| j                   j
                  j                  g| j                  d   ¢­Ž }| j                   j                  |«      \  }}}}}}	}
nq| j                  |«      }|�|dd n|}| j                   j                  ||�||dœnd|d| j                  D �cg c]  }|d|j                  d    ‘Œ c}¬«      \  }}}}}}	}
|||	|
d	œS c c}w )
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'.
        Nr9   r   r;   r   rŠ  F)Úbackbone_featuresrs  rt  rl   rU  )r�   rã  rÖ  r×  )rI   Ú$use_mask_input_as_output_without_samrO  rL  rÛ   r.  r/  r¾  Ú_use_mask_as_outputr2  Ú_forward_sam_headsrU  rr   )r1   r›  r$  r%  r$  Úpix_featrN  Úlow_res_masksrÙ  rÖ  r×  r0  rP  s                r6   rÉ  z*SAM2DynamicInteractivePredictor.track_stepX  sE  € ð4 Ð §
¡
× OÒ Oð ×(Ñ(¨Ñ,×4Ñ4°Q¸¸1Ó=ˆHØ$�x—}‘} R¨¯©×)DÑ)D×)LÑ)LÐcÈtÏÉÐ_aÑObÒcˆHØSW×S]ÑS]×SqÑSqÐrvÓSwÑPˆAˆq�!�] N°GÑ=Pð !%× IÑ IÈ'Ó RÐà9@Ð9LÐ 1°"°1Ñ 5ÐRcÐØSW×S]ÑS]×SpÑSpØ"3ØOVÐOb¨eÀUÒKÐhlØ Ø!&ØRV×RhÑRhÖ"iÈ$ 4Ð(DÐ*;×*AÑ*AÀ!Ñ*DÒ#EÒ"ið Tqó TÑPˆAˆq�!�] N°GÐ=Pð (Ø#1ØØ#6ñ	
ð 	
ùò #js   Ã$D)
r2   r   r3   r  r  rB  r4   r*  ÚreturnÚNoner0  )r,   útorch.Tensor | np.ndarrayr]   úlist[list[float]] | Noner_   z torch.Tensor | np.ndarray | Noner^   rC  r`   úlist[int] | Noner¸  rD  r  Úboolr@  ú!tuple[torch.Tensor, torch.Tensor])r  rB  r@  rA  r+  )
r¸  rD  r^   útorch.Tensor | Noner`   rG  r_   rG  r@  rA  )r›  ú
int | Noner@  útorch.Tensor)r@  rF  )rk  rB  r@  rH  )
r›  rH  r$  rG  r%  rG  r$  rG  r@  údict[str, Any])r1  r2  r3  r4  r   r)   r   rn   rp   r  r2  r-  r•  rÉ  r6  r7  s   @r6   r  r  @  sŽ  ø„ ñð6 Ø+/ØØ"&ð(àð(ð )ð(ð ð	(ð
  ð(ð 
õ(ñ> Óð ,0Ø26Ø+/Ø#'Ø$(Ø#ð@Cà%ð@Cð )ð@Cð 0ð	@Cð
 )ð@Cð !ð@Cð "ð@Cð ð@Cð 
+ò@Có ð@CóD%ñ  Óð %)Ø&*Ø&*Ø%)ðN2à!ðN2ð $ðN2ð $ð	N2ð
 #ðN2ð 
òN2ó ðN2ó`!
óF(ó	4ð #Ø%)Ø%)Ø$(ð1
àð1
ð #ð1
ð #ð	1
ð
 "ð1
ð 
÷1
r7   r  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.©)é   rN  )é�   rO  )éH   rP  é   c                ó>  •— t         ‰| �  ||«       t        j                  g d¢«      j	                  ddd«      j                  | j                  «      | _        t        j                  g d¢«      j	                  ddd«      j                  | j                  «      | _        y)zTSetup the SAM3 model with appropriate mean and standard deviation for preprocessing.)ç     à_@rS  rS  r9   r   N)	r(   rá   r=   r›   rÛ   rE   rF   rG   rH   )r1   rI   rÖ   r5   s      €r6   rá   zSAM3Predictor.setup_model–  sp   ø€ ä‰Ñ˜E 7Ô+ä—L‘LÒ!6Ó7×<Ñ<¸RÀÀAÓF×IÑIÈ$Ï+É+ÓVˆŒ	Ü—<‘<Ò 5Ó6×;Ñ;¸BÀÀ1ÓE×HÑHÈÏÉÓUˆ�r7   c                ór   — ddl m}  || j                  j                  | j                  j                  ¬«      S )úYRetrieve and initialize the Segment Anything Model 3 (SAM3) for image segmentation tasks.r   ©Úbuild_interactive_sam3©Úcompile)Ú
build_sam3rW  r*   rI   rY  )r1   rW  s     r6   rÙ   zSAM3Predictor.get_model�  ó$   € å6á% d§i¡i§o¡o¸t¿y¹y×?PÑ?PÔQÐQr7   r/  )	r1  r2  r3  r4  rC  rÝ   rá   rÙ   r6  r7  s   @r6   rL  rL  Œ  s    ø„ Ù]ò€Nð
 €FõVöRr7   rL  c                  óŒ   — e Zd ZdZd„ Z e«       d„ «       Zd„ Zdd„Zddd„Z	d„ Z
ddd	„Z e«       	 	 	 d	 dd
„«       Zd„ Zdd„Zy)ÚSAM3SemanticPredictorzGSegment Anything Model 3 (SAM3) Predictor for image segmentation tasks.c                ór   — ddl m}  || j                  j                  | j                  j                  ¬«      S )rU  r   )Úbuild_sam3_image_modelrX  )rZ  r_  r*   rI   rY  )r1   r_  s     r6   rÙ   zSAM3SemanticPredictor.get_model§  r[  r7   c                óL   — | j                   j                  j                  |«      S )z2Extract image features using the model's backbone.)rI   ÚbackbonerH  r  s     r6   rp   z%SAM3SemanticPredictor.get_im_features­  s   € ð �z‰z×"Ñ"×0Ñ0°Ó4Ð4r7   c                ó–   — t        |«      dk(  sJ d«       ‚t        | j                  ddd¬«      }|D �cg c]  } ||¬«      ‘Œ c}S c c}w )rP   r   rQ   FT)rR   rS   Ú
scale_fillrT   rV   rY   s       r6   rA   z#SAM3SemanticPredictor.pre_transform²  sG   € ô, �2‹w˜!Š|ÐUÐUÓUˆ|Ü˜dŸj™j¨u¸UÈtÔTˆ	Ø,.Ö/ q‘	 Ö"Ò/Ð/ùÒ/s   ³ANc                óš  — |��Et        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
�«       ‚|j                  ddd«      }|j                  dd«      }||fS )zRPrepare prompts by normalizing bounding boxes and points to the destination shape.Nr…   r   r   r;   r9   r‡   rˆ   r‰   rŠ   r"  )r=   r‘   r’   rF   r“   r   Ú	xyxy2xywhr?   r”   rr   r•   rÛ   )r1   r�   r]   r`   s       r6   Ú_prepare_geometric_promptsz0SAM3SemanticPredictor._prepare_geometric_promptsÌ  s9  € àÑÜ—_‘_ V°4×3CÑ3CÈDÏKÉKÔXˆFØ%+§[¡[°AÒ%5�V˜D’\¸6ˆFä—]‘] 6Ó*ˆFØ’1�a�d˜�d�7‹O˜y¨™|Ñ+‹OØ’1�a�d˜�d�7‹O˜y¨™|Ñ+‹Oàˆ~ÜŸ™ §¡¨c¨rÐ!2Ó3�Ü—_‘_ V´5·;±;ÀtÇ{Á{ÔSˆFØ—<‘< Ñ# v§|¡|°BÑ'7Ò7ð Ø# F§L¡L°Ñ$4Ð#5Ð5TÐU[×UaÑUaÐbdÑUeÐTfÐfgÐhóÐ7ð —[‘[  Q¨Ó*ˆFØ—[‘[  QÓ'ˆFØ�vˆ~Ðr7   c                ó  — |�dn+|�t        |«      nt        | j                  j                  «      }d}|�I| j                  |«      }t	        t        |«      «      D ]  }|j                  ||g   ||g   «       Œ |€dg}|�5| j                  j                  |k7  r| j                  j                  |¬«       | j                  j                  |t        j                  || j                  t        j                  ¬«      |¬«      }|S )zPRun inference on the extracted features with optional bounding boxes and labels.Nr   Úvisual©Útextr  ©rM  Útext_idsÚgeometric_prompt)rW   rI   rö   Ú_get_dummy_promptrø   Úappend_boxesÚset_classesÚforward_groundingr=   rþ   rF   Úlong)	r1   r-   r]   r`   rj  Úncrm  rf   Úoutputss	            r6   rs   z)SAM3SemanticPredictor._inference_featuresà  sö   € ð Ð$‰Q°tÐ7G¬#¨d¬)ÌSÐQU×Q[ÑQ[×QaÑQaÓMbˆØÐØÐØ#×5Ñ5°bÓ9ÐÜœ3˜v›;Ó'ò H�Ø ×-Ñ-¨f°a°S©k¸6À1À#¹;ÕGðHàˆ|Ø �z�ØÐ §
¡
× 0Ñ 0°DÒ 8Ø�J‰J×"Ñ"¨Ð"Ô-Ø—*‘*×.Ñ.Ø!Ü—\‘\ "¨T¯[©[ÄÇ
Á
ÔKØ-ð /ó 
ˆð
 ˆr7   c           
     ó  — ddl }|d   }|d   }|d   }|j                  «       }|d   j                  «       j                  d«      }	||	z  j                  d«      }t	        j
                  t        t        |j                  d   «      «      |j                  |j                  ¬	«      dd…df   j                  |«      }
t	        j                  ||d
   |
d
   gd¬«      }|| j                  j                  kD  }||   ||   }}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                  j%                  ||dd…df   | j                  j&                  «      }||   ||   }}t)        | j*                  dt        |j                  d   «      D �cg c]  }t-        |«      ‘Œ c}«      }t/        |t        «      st        j0                  |«      }g }t3        |g|g|| j4                  d   «      D ]Ô  \  }}}}|j                  d   dk(  r$dt	        j6                  d|j                  ¬«      }}nxt9        j:                  |j=                  «       d   |j                  dd d¬«      d   dkD  }|dddgfxx   |j                  d   z  cc<   |dddgfxx   |j                  d   z  cc<   |j?                  tA        |||||¬«      «       ŒÖ |S c c}w )úNPost-process the predictions to apply non-overlapping constraints if required.r   NÚ
pred_boxesÚpred_logitsr�   Úpresence_logit_decr   r9   r…   ©.Nrò   r"  é   rï   é   rö   rî   r    r;   r¡   r  rA  .r:   rô   )!r£   Úsigmoidr   rš   r=   r›   rù   rø   rr   r†   rF   Ú	expand_asrª   r*   rÿ   r   Ú	xywh2xyxyÚagnostic_nmsr«   r¬   r»  rI   rì   r<   rú   r¤   r%   rû   r¦   r§   rL   r©   r
   )r1   r   r  r  r£   rw  rx  r�   r‚   Úpresence_scoreÚpred_clsrÓ   ÚcÚ	nms_boxesrf   rö   r  r_   rv   r  r  s                        r6   r  z!SAM3SemanticPredictor.postprocessô  só  € ãà˜<Ñ(ˆ
Ø˜MÑ*ˆØ˜<Ñ(ˆ
Ø!×)Ñ)Ó+ˆØÐ3Ñ4×<Ñ<Ó>×HÑHÈÓKˆØ" ^Ñ3×<Ñ<¸RÓ@ˆÜ—<‘<Ü”�{×(Ñ(¨Ñ+Ó,Ó-Ø×#Ñ#Ø×%Ñ%ô
ò ˆTˆ'ñ	÷ ‘9˜[Ó)ð	 	ô
 —Y‘Y 
¨K¸	Ñ,BÀHÈYÑDWÐXÐ^`Ôaˆ
à˜TŸY™YŸ^™^Ñ+ˆØ!+¨DÑ!1°:¸dÑ3C�Jˆ
ÜŸM™M¨*²Q¸¸¸°UÑ*;Ó<ˆ
’1�b�q�b�5Ñà’q˜!˜A˜#�vÑ t§y¡y×'=Ò'=¡!À4ÑHˆØšq " 1 "˜uÑ%¨Ñ)ˆ	Ø�‰×"Ñ" 9¨jº¸A¸Ñ.>ÀÇ	Á	ÇÁÓNˆØ!+¨DÑ!1°:¸dÑ3C�Jˆ
ä˜Ÿ
™
 G¼eÀK×DUÑDUÐVWÑDXÓ>YÖ-Z¸¬c°!­fÒ-ZÓ[ˆÜ˜)¤TÔ*Ü×5Ñ5°iÓ@ˆIØˆÜ03°Z°LÀ:À,ÐPYÐ[_×[eÑ[eÐfgÑ[hÓ0iò 	dÑ,ˆE�5˜( HØ�{‰{˜1‰~ Ò"Ø#¤U§[¡[°À
×@QÑ@QÔ%R�u‘äŸ™ e§k¡k£m°DÑ&9¸8¿>¹>È"È1Ð;MÐT^Ô_Ð`aÑbÐehÑh�Ø�c˜A˜q˜6�kÓ" h§n¡n°QÑ&7Ñ7Ó"Ø�c˜A˜q˜6�kÓ" h§n¡n°QÑ&7Ñ7Ó"Ø�N‰Nœ7 8°(À%ÈuÐ\aÔbÕcð	dð ˆùò .[s   ÇK<c                óˆ  — | j                   j                  d|«      }| j                   j                  d|«      }| j                   j                  d|«      }| j                  €| j                  |«      n| j                  }| j	                  | j
                  d   d   j                  dd ||«      } | j                  |g|¢­d|iŽS )z:Perform inference on a single image with optional prompts.r]   r`   rj  Nr   r   r;   )r.   rh   r-   rp   rf  r%   rr   rs   )	r1   r,   r]   r`   rj  r*   rm   r-   r.   s	            r6   rn   zSAM3SemanticPredictor.inference	  s¯   € à—‘×!Ñ! (¨FÓ3ˆØ—‘×!Ñ! (¨FÓ3ˆØ�|‰|×Ñ ¨Ó-ˆØ/3¯}©}Ð/D�4×'Ñ'¨Ô+È$Ï-É-ˆØ×1Ñ1°$·*±*¸Q±-ÀÑ2B×2HÑ2HÈÈ!Ð2LÈfÐV\Ó]ˆØ'ˆt×'Ñ'¨ÐF°7ÒFÀÑFÐFr7   c                óì  — ddl }| j                  |dd ||«      } | j                  |g|¢­d|iŽ}|d   }	|d   }
|d   }|
j                  «       }|d   j                  «       j	                  d	«      }||z  j                  d
«      }t        j                  t        t        |j                  d   «      «      |j                  |j                  ¬«      dd…df   j                  |«      }t        j                  |	|d   |d   gd
¬«      }	|| j                  j                   kD  }||   |	|   }	}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"                  j)                  ||	dd…df   | j                  j*                  «      }|	|   ||   }}	|j                  d   dk(  r'dt        j,                  d|j                  ¬«      }	}||	fS t/        j0                  |j3                  «       d   |dd d¬«      d   dkD  }|	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;   rj  rw  rx  r�   ry  r   r9   r…   rz  rò   r"  r{  rï   r|  rî   r    r¡   r  rA  ).r   ).r   ).r;   ).r:   )r£   rf  rs   r}  r   rš   r=   r›   rù   rø   rr   r†   rF   r~  rª   r*   rÿ   r   r  r€  r«   r¬   rû   r¦   r§   rL   )r1   r-   r�   r]   r`   rj  r£   r.   r   rw  rx  r�   r‚   r�  r‚  rÓ   rƒ  r„  s                     r6   r(  z(SAM3SemanticPredictor.inference_features%	  s¥  € ó4 	à×1Ñ1°)¸B¸Q°-ÀÈÓPˆØ(�×(Ñ(¨ÐG°GÒGÀ$ÑGˆØ˜<Ñ(ˆ
Ø˜MÑ*ˆØ˜<Ñ(ˆ
Ø!×)Ñ)Ó+ˆØÐ3Ñ4×<Ñ<Ó>×HÑHÈÓKˆØ" ^Ñ3×<Ñ<¸RÓ@ˆÜ—<‘<Ü”�{×(Ñ(¨Ñ+Ó,Ó-Ø×#Ñ#Ø×%Ñ%ô
ò ˆTˆ'ñ	÷ ‘9˜[Ó)ð	 	ô
 —Y‘Y 
¨K¸	Ñ,BÀHÈYÑDWÐXÐ^`Ôaˆ
à˜TŸY™YŸ^™^Ñ+ˆØ!+¨DÑ!1°:¸dÑ3C�Jˆ
ÜŸM™M¨*²Q¸¸¸°UÑ*;Ó<ˆ
’1�b�q�b�5Ñà’q˜!˜A˜#�vÑ t§y¡y×'=Ò'=¡!À4ÑHˆØšq " 1 "˜uÑ%¨Ñ)ˆ	Ø�‰×"Ñ" 9¨jº¸A¸Ñ.>ÀÇ	Á	ÇÁÓNˆØ!+¨DÑ!1°:¸dÑ3C�Jˆ
à×Ñ˜AÑ !Ò#Ø%)¬5¯;©;°vÀj×FWÑFWÔ+X˜
ˆJð ˜:Ð%Ð%ô Ÿ™ z×'7Ñ'7Ó'9¸$Ñ'?ÀÈ2ÈAÀÐU_Ô`ÐabÑcÐfiÑiˆJØ�vÓ )¨A¡,Ñ.ÓØ�vÓ )¨A¡,Ñ.ÓØ�vÓ )¨A¡,Ñ.ÓØ�vÓ )¨A¡,Ñ.ÓØ˜:Ð%Ð%r7   c                ó4   — i | _         i | j                  _        y)z$Reset the prompts for the predictor.N)r.   rI   Útext_embeddingsr  s    r6   Úreset_promptsz#SAM3SemanticPredictor.reset_promptsc	  s   € àˆŒØ%'ˆ�
‰
Õ"r7   c           	     óÀ   — t        t        j                  d|d| j                  ¬«      t        j                  |d| j                  t        j                  ¬«      ¬«      }|S )z-Get a dummy geometric prompt with zero boxes.r   r"  r    r  )Úbox_embeddingsÚbox_mask)r   r=   rû   rF   rE  )r1   Únum_promptsrm  s      r6   rn  z'SAM3SemanticPredictor._get_dummy_prompth	  sE   € ä!Ü Ÿ;™; q¨+°qÀÇÁÔMÜ—[‘[ ¨a¸¿¹Ì5Ï:É:ÔVô
Ðð  Ðr7   r  ©NNN©rj  zlist[str] | Noner  )r1  r2  r3  r4  rÙ   r   rp   rA   rf  rs   r  rn   r(  r‰  rn  rc   r7   r6   r]  r]  ¤  st   „ ÙQòRñ Óñ5ó ð5ò0ó4ô(ò(&ôPGñ Óð
 ØØ!%ð;&ð ò;&ó ð;&òz(ô
 r7   r]  c                  ó   — e Zd ZdZd„ Zy)Ú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 r9d}||   |   }	| j                  rl| j                  s|dk  r[| j	                  |«       nI||d	   v rd	}||   |   }	n7d	}| j                  |||d
ddd
d|¬«	      }	|	||   |<   | j                  ||¬«       | j                  ||	||¬«       |d   j                  |«       |	d   j                  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.
        ri  r¸  rm  rn  rj  r   ro  r   rp  FNT)	ri  rl  rq  rr  rs  rt  ru  rv  r_  r£  rw  r�   r×  )
rW   r|  ra  rb  r}  r~  r  r€  r©   r~   )r1   r_  rl  ry  ri  r¸  rm  rq  r‚  rƒ  r�   Ú
obj_scoress               r6   Úpropagate_in_videoz%SAM3VideoPredictor.propagate_in_videot	  s{  € ð ˆØ% mÑ4ˆØ! )Ñ,ˆØ"1Ð2KÑ"LÐÜ˜¨Ñ9Ó:ˆ
Üˆ{Ð/Ñ0Ó1°QÒ6ÜÐPÓQÐQàÐ+Ð,@ÑAÑAØ.ˆKØ% kÑ2°5Ñ9ˆKØ×3Ò3¸×9^Ò9^ÐblÐpqÒbqà×5Ñ5°eÕ<ØÐ-Ð.FÑGÑGØ2ˆKØ% kÑ2°5Ñ9‰Kà2ˆKØ×:Ñ:Ø'ØØ%Ø#(Ø!Ø ØØ $Ø /ð ;ó 
ˆKð /:ˆK˜Ñ$ UÑ+Ø×'Ñ'¨¸Ð'ÔOð 	×#Ñ# E¨;¸ÐUdÐ#ÔeØÐ0Ñ1×8Ñ8¸Ô?Ø  Ñ.×6Ñ6°q¸!Ó<ˆ
Ø Ð!6Ñ7ˆ
à˜
 JÐ.Ð.r7   N)r1  r2  r3  r4  r”  rc   r7   r6   r‘  r‘  q	  s
   „ ÙWó0/r7   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	 d4ˆ fd„Zd5ˆ fd„	Zˆ fd„Zed„ «       Zd6d7d„Zd„ Zd8d„Z e«       	 	 	 	 d9d„«       Zd:d„Z	 d;	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d<d„Zed=d„«       Z	 	 	 	 	 	 	 	 d>d„Zd „ Zd!„ Z	 	 	 	 	 	 d?d"„Z	 	 	 	 	 	 	 	 	 	 d@d#„Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 dAd$„Z 	 dB	 	 	 	 	 	 	 	 	 	 	 dCd%„Z!	 	 	 	 	 	 	 	 	 	 dDd&„Z"e	 dE	 	 	 	 	 	 	 	 	 dFd'„«       Z#	 	 dG	 	 	 	 	 	 	 	 	 dHd(„Z$dId)„Z%	 	 	 	 	 	 	 	 dJd*„Z&	 	 	 	 	 	 	 	 	 	 	 	 	 	 dKd+„Z'	 	 	 	 	 	 dLd,„Z(	 	 	 	 	 	 	 	 	 	 dMd-„Z)dNd.„Z*d/„ Z+	 	 	 	 	 	 	 	 	 	 dOd0„Z,d;dPd1„Z-d2„ Z.ed3„ «       Z/ˆ xZ0S )QÚSAM3VideoSemanticPredictorz9Segment Anything Model 3 (SAM3) Video Semantic Predictor.çš™™™™™é?ç      $Àr9   i † r   r;   rM  rQ  NrA  ç        r   r:   é
   éüÿÿÿTFr   c                ó&  •— t         ‰| �  |||«       || _        || _        || _        || _        || _        |	dkD  r|
|	k  sJ ‚||	k  sJ ‚|	| _        |
| _        || _	        || _
        || _        || _        || _        || _        || _        || _        || _        d| _        d}d}|| _        || _        || _        || _        || _        || _        || _        t5        |¬«      | _        i | _        | j:                  d   j=                  | j>                  «       y)zTInitialize the SAM3VideoSemanticPredictor with configuration and optional overrides.r   Ni'  r   )r3   r^  ) 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_  rc  r©   rd  )r1   r2   r3   r4   r�  rž  rŸ  r   r¡  r¢  r£  r¤  r¥  r¦  r§  r¨  rª  r«  r©  r¬  r®  r°  r±  r²  r³  r´  r¯  r5   s                              €r6   r)   z#SAM3VideoSemanticPredictor.__init__¹	  s@  ø€ ô\ 	‰Ñ˜˜i¨Ô4Ø)BˆÔ&Ø,ˆÔØ 0ˆÔØ$8ˆÔ!Ø,ˆÔð ˜AÒØ*¨nÒ<Ð<Ð<Ø&¨.Ò8Ð8Ð8Ø,ˆÔØ'>ˆÔ$Ø#6ˆÔ Ø#6ˆÔ Ø"4ˆÔØ"4ˆÔàDð 	ÔEð /MˆÔ+Ø:dˆÔ7Ø,HˆÔ)Ø,ˆÔØ ˆÔàˆØ ÐØ.ˆÔØ#6ˆÔ Ø+FˆÔ(Ø+FˆÔ(Ø;fˆÔ8Ø.LˆÔ+Ø-JˆÔ*ô *°IÔ>ˆŒà!ˆÔØ�‰Ð)Ñ*×1Ñ1°$·/±/ÕBr7   c                ó¨   •— t         ‰| �  ||«       ddlm}  || j                  j
                  d¬«      }| j                  j                  |d¬«       y)z+Setup the SAM3VideoSemanticPredictor model.r   rV  F)Úwith_backbone)rI   rÖ   N)r(   rá   rZ  rW  r*   rI   rµ  )r1   rI   rÖ   rW  r5   s       €r6   rá   z&SAM3VideoSemanticPredictor.setup_model
  sB   ø€ ä‰Ñ˜E 7Ô+Ý6ñ ' t§y¡y§¡ÀeÔLˆØ�‰× Ñ  u°eÐ Õ<r7   c                óä  •— t         ‰| �  |«       | j                  | j                  _        | j                  j                  j                  | j                  «       dD ��cg c]5  }| j                  D �cg c]  }t        || j                  |z  z  «      ‘Œ c}‘Œ7 c}}| j                  _        | j                  j                  j                  j                  j                  | _        yc c}w c c}}w )z:Setup the source for the SAM3VideoSemanticPredictor model.r@  N)r(   r	  rX   rµ  rI   r  rB  rÝ   rC  Úmemory_encoderÚmask_downsamplerÚinterpol_sizerD  s       €r6   r	  z'SAM3VideoSemanticPredictor.setup_source
  s¢   ø€ ä‰Ñ˜VÔ$Ø!ŸZ™Zˆ�‰ÔØ�‰×Ñ×$Ñ$ T§Z¡ZÔ0Øar×&sÐ\]ÈDÏJÉJÖ'WÀq¬¨A°·±¸q±Ñ,AÕ(BÔ'WÓ&sˆ�‰Ô#Ø!Ÿ\™\×/Ñ/×>Ñ>×OÑO×]Ñ]ˆÕùò (XùÓ&ss   Á C,Á3"C'ÂC,Ã'C,c                óÚ   — t        | j                  «      dkD  ry| j                  €J ‚| j                  j                  dk(  sJ ‚| j                  j                  }|g i ddg|z  dœ}|| _        y)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)rW   r_  r
  r$   r±  )r²  rµ  r_  s      r6   rd  z%SAM3VideoSemanticPredictor.init_state"
  s~   € ô ˆy×(Ñ(Ó)¨AÒ-ØØ× Ñ Ð,Ð,Ð,Ø× Ñ ×%Ñ%¨Ò0Ð0Ð0Ø×&Ñ&×-Ñ-ˆ
à$Ø(*Ø "ØØ+/¨&°:Ñ*=ñ
ˆð %4ˆ	Õ!r7   c                ó¾   — | j                   j                  dz
  }|| j                  d<   d| j                  vr| j                  ||||¬«       | j	                  |d¬«      S )z<Perform inference on a video sequence with optional prompts.r   r,   rl  )rl  rj  r]   r`   F)ru  )r
  ry  r_  Ú
add_promptr~  )r1   r,   r]   r`   rj  r*   rm   ry  s           r6   rn   z$SAM3VideoSemanticPredictor.inference;
  s^   € à—‘×"Ñ" QÑ&ˆØ%'ˆ×Ñ˜TÑ"Ø˜T×1Ñ1Ñ1Ø�O‰O e°$¸vÈfˆOÔUØ×/Ñ/°¸uÐ/ÓEÐEr7   c           
     óÐ  — |d   }t        |j                  «       «      }t        |t        «      st	        j
                  |«      }| j                  j                  dk7  r| j                  j                  ni }t        |«      dk(  r%dt        j                  d| j                  ¬«      }}�nbt        j                  |D �	cg c]  }	||	   ‘Œ	 c}	d¬«      }t        j                  |j                  «       d   |d   j                   dd d	¬
«      d   dkD  }t        j"                  |t        j$                  |j                  ¬«      }
t        j"                  |D �	cg c]
  }	|d   |	   ‘Œ c}	|j                  ¬«      }t        j"                  |D �	cg c]
  }	|d   |	   ‘Œ c}	|j                  ¬«      }|| j&                  j(                  kD  |j+                  d¬«      z  }||   }t-        |«      }t        j                  ||
|   dd…df   ||   d   ||   d   gd¬«      }|j                   d   rN|xsJ t/        t1        d„ t3        |dd…df   j5                  «       j7                  «       dz   «      D «       «      «      }|j                   d   dkD  r…t        j"                  |D �	cg c]  }	|	|d   v r|d   |	   nd‘Œ c}	|j                  ¬«      |   }| j9                  |j;                  d«      |j;                  d«      d¬«      j=                  d«      dkD  }g }t?        |g|g|| j@                  d   «      D ]&  \  }}}}|jC                  tE        |||||¬«      «       Œ( |S c c}	w c c}	w c c}	w c c}	w )rv  Úobj_id_to_maskrh  r   N)r   é   r    rò   r;   r¡   r  rA  r…   Úobj_id_to_scoreÚobj_id_to_clsrx  rz  r9   c              3  ó2   K  — | ]  }t        |«      –— Œ y ­wrb   rë   rd   s     r6   rg   z9SAM3VideoSemanticPredictor.postprocess.<locals>.<genexpr>^
  s   è ø€ Ò/h¸1´°A·Ñ/hùrí   rï   r   Úobj_id_to_tracker_scorer™  )Úbackground_valuerô   )#Úsortedr¦  r<   rù   r   rú   rI   rö   rW   r=   rû   rF   rª   r¦   r§   rL   rr   r›   r•   r*   rÿ   Úanyr   r'   r÷   rø   rB  ÚmaxÚ._apply_object_wise_non_overlapping_constraintsr   rš   r¤   r%   r©   r
   )r1   r   r  r  rÄ  Úcurr_obj_idsrö   r�   rw  rk  Úpred_idsr‚   r‚  rÓ   Útracker_scoresr  r_   rv   r  r  s                       r6   r  z&SAM3VideoSemanticPredictor.postprocessC
  s]  € àÐ/Ñ0ˆÜ˜n×1Ñ1Ó3Ó4ˆÜ˜)¤TÔ*Ü×5Ñ5°iÓ@ˆIà$(§J¡J×$4Ñ$4¸Ò$@�—
‘
× Ò ÀbˆÜˆ|Ó Ò!Ø%)¬5¯;©;°vÀdÇkÁkÔ+R˜
ŠJäŸ™ÈÖ#V¸v N°6Ó$:Ò#VÐ\]Ô^ˆJÜŸ™ z×'7Ñ'7Ó'9¸$Ñ'?ÀÈ1Á×ASÑASÐTVÐUVÐAWÐ^hÔiÐjkÑlÐorÑrˆJÜ—|‘| L¼¿¹ÈJ×L]ÑL]Ô^ˆHÜŸ,™,Ø@LÖM°f�Ð(Ñ)¨&Ó1ÒMÐV`×VgÑVgôˆKô —|‘|Ø>JÖK°F��Ñ'¨Ó/ÒKÐT^×TeÑTeôˆHð   $§)¡)§.¡.Ñ0°J·N±NÀv°NÓ4NÑNˆDØ# DÑ)ˆJÜ,¨ZÓ8ˆJÜŸ™Ø˜X d™^ªA¨t¨GÑ4°kÀ$Ñ6GÈ	Ñ6RÐT\Ð]aÑTbÐclÑTmÐnÐtvôˆJð ×Ñ Ò"ØÒi¤¤iÑ/hÄÀjÒQRÐTUÐQUÑFV×FZÑFZÓF\×F`ÑF`ÓFbÐefÑFfÓ@gÔ/hÓ&hÓ!i�Ø×Ñ Ñ" QÒ&Ü!&§¡ð '3öð #ð  &¨Ð/HÑ)IÑIð "Ð";Ñ<¸VÒDà!$ñ%òð &×,Ñ,ô
"ð ñ
"�ð ×GÑGØ"×,Ñ,¨QÓ/Ø&×0Ñ0°Ó3Ø)*ð Hó ÷ ‘g˜a“jØñ�
ð ˆÜ03°Z°LÀ:À,ÐPYÐ[_×[eÑ[eÐfgÑ[hÓ0iò 	dÑ,ˆE�5˜( HØ�N‰Nœ7 8°(À%ÈuÐ\aÔbÕcð	dàˆùòQ $Wùò Nùò Lùòs   Â;MÅMÆMÊM#c                óÞ  — |xs | j                   }|d   }|d   du}|d   |   du}| j                  ||d   ||d   |d   |s| j                  t        |d   «      ¬«      n|d   |   ||d	   |xs |¬
«	      \  }}}	}
}}}|
|d<   ||d	<   |||	|d   |   dœ}|d   }|d   }||d<   ||d<   | j                  r2|d   d   }|| j
                  k(  }|d   |   j                  «       |d<   |S g |d<   |S )zBPerform inference on a single frame and get its inference results.r½  r¿  NrÀ  rµ  r,   rl  ©r�  r¾  )	rl  rµ  ru  r,   rl  rm  Ú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_framern  rW   r±  ÚUNCONFIRMEDÚtolist)r1   rl  ru  r_  rÔ  Úhas_text_promptÚhas_geometric_promptrÄ  rÆ  rÇ  Útracker_states_local_newÚtracker_metadata_newrÚ  rN  rà  rØ  rÙ  rÜ  Úis_unconfirmeds                      r6   r~  z6SAM3VideoSemanticPredictor._run_single_frame_inferencex
  sœ  € à)ÒA¨T×-AÑ-Aˆà.Ð/IÑJÐØ)¨-Ñ8ÀÐDˆØ.Ð/KÑLÈYÑWÐ_cÐcÐð ×%Ñ%ØØ& |Ñ4ØØ˜tÑ$Ø$ ZÑ0ñ ,ð ×&Ñ&´3°ÀzÑ7RÓ3SÐ&Ô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Ñ7ˆNØ)=¸iÑ)HÈÑ)X×)_Ñ)_Ó)aˆCÐ%Ñ&ð ˆ
ð *,ˆCÐ%Ñ&Øˆ
r7   c                óÀ  — |xs | j                   }|€	|€J d«       ‚|du}|r|nd}t        |t        «      r|gn|}|r|nd|d<   t        |«      }t	        j
                  || j                  t        j                  ¬«      }	|	|d<   |�5| j                  j                  |k7  r| j                  j                  |¬«       | j                  | j                  d   d	   j                  dd
 ||«      \  }}|du|duk(  sJ ‚| j                  |¬«      }
|�3t        t        |«      «      D ]  }|
j!                  ||g   ||g   «       Œ |
|d   |<   | j#                  |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 providedrh  r¿  r  rl  ri  r   r   r;   rÓ  rÀ  F)ru  r_  )r_  r<   rì   rW   r=   rþ   rF   rr  rI   rö   rp  rf  r%   rr   rn  rø   ro  r~  )r1   rl  rj  r]   r`   r_  Úuse_textÚ
text_batchÚnrl  rm  rf   rà  s                r6   rÂ  z%SAM3VideoSemanticPredictor.add_prompt®
  s‹  € ð *ÒA¨T×-AÑ-AˆØÐ 6Ð#5ÐsÐ7sÓsÐ5ð ˜tÐ#ˆÙ‰t XˆÜ)¨$´Ô4�d‘V¸$ˆ
Ù19©¸tˆ˜Ñ&Ü�
‹OˆÜ—<‘< ¨$¯+©+¼U¿Z¹ZÔHˆØ&.ˆ˜
Ñ#ØÐ §
¡
× 0Ñ 0°DÒ 8Ø�J‰J×"Ñ"¨Ð"Ô-ð ×8Ñ8¸¿¹ÀA¹ÀqÑ9I×9OÑ9OÐPRÐQRÐ9SÐU[Ð]cÓd‰ˆ�Ø˜dÐ"¨°dÐ(:Ò;Ð;Ð;Ø×1Ñ1¸aÐ1Ó@ÐØÐÜœ3˜v›;Ó'ò H�Ø ×-Ñ-¨f°a°S©k¸6À1À#¹;ÕGðHàCSˆÐ4Ñ5°iÑ@Ø×.Ñ.¨yÀ%ÐYhÐ.ÓiˆØ˜#ˆ~Ðr7   c                óè   — t        j                  |dkD  |d   |«      }| j                  j                  j	                  |«      }t        j                  |dkD  |t        j
                  ||¬«      «      }|S )zhApplies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region).r   ).NN)rÍ  )r=   Úwhererµ  rI   r…  Úclamp)r1   r�   r“  rÊ  Úpred_masks_single_scoreÚ!pixel_level_non_overlapping_maskss         r6   rÎ  zISAM3VideoSemanticPredictor._apply_object_wise_non_overlapping_constraintsÖ
  sq   € ô #(§+¡+¨j¸1©n¸jÈÑ>YÐ[kÓ"lÐà,0¯L©L×,>Ñ,>×,aÑ,aØ#ó-
Ð)ô —[‘[Ø-°Ñ1ØÜ�K‰K˜
Ð(8Ô9ó
ˆ
ð
 Ðr7   c
           	     ó„  — | j                  ||||	¬«      }
|i k(  r|j                  | j                  «       «       | j                  |||¬«      \  }}| j	                  |||
||||¬«      \  }}|j                  dt        «       «      }| j                  |||
||¬«      }| j                  |
||||¬«      }|d   }|d   }t        j                  |d	   «      |d
   dœ}|j                  d   dkD  rM|j                  «       j                  «       }|d   }|d   |   j                  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,   rl  rm  rÖ  )rl  rÔ  rÕ  )rl  ru  Údet_outÚtracker_low_res_masks_globalÚtracker_obj_scores_globalrÕ  rÔ  Úreconditioned_obj_ids)rl  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_outputsr?   r�  rr   r}  rà  r'   r¤   )r1   r,   rl  rl  rµ  ru  rm  rÔ  rÕ  rÖ  rð  rñ  rò  rô  rä  ró  rã  rÄ  rÆ  rÇ  rÚ  Útracker_obj_idss                         r6   rÞ  z/SAM3VideoSemanticPredictor._det_track_one_frameæ
  sÆ  € ð. ×1Ñ1ØØØ-Ø!5ð	 2ó 
ˆð ! BÒ&à!×(Ñ(¨×)BÑ)BÓ)DÔEØBF×B^ÑB^ØØ!5Ø"7ð C_ó C
Ñ?Ð$Ð&?ð 59×4ZÑ4ZØØØØ)EØ&?Ø"7Ø!5ð 5[ó 5
Ñ1ÐÐ1ð !4× 7Ñ 7Ð8OÔQTÓQVÓ WÐð $(×#JÑ#JØØ!ØØ!5Ø 3ð $Kó $
Ð ð ×+Ñ+ØØ)EØ"7Ø 3Ø"7ð ,ó 
ˆð /Ð/@ÑAˆØ,¨_Ñ=ˆô  "Ÿv™vÐ&:¸9Ñ&EÓFØ2Ð3QÑRñ
ˆð
 %×*Ñ*¨1Ñ-°Ò1à(A×(IÑ(IÓ(K×(RÑ(RÓ(TÐ%Ø3°IÑ>ˆOØ Ð!EÑFÀyÑQ×XÑXÜ”S˜Ð*CÓDÓEôð ØØØ$Ø ØØ%ð
ð 	
r7   c                óŒ   — | j                  d«      \  }}}}||z   dz  }||z   dz  }||kD  |d|z
  k  z  ||kD  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
        r9   r;   r„   )Úunbind)	rv   ÚmarginÚx_minÚy_minÚx_maxÚy_maxÚx_cÚy_crÓ   s	            r6   Ú&_suppress_detections_close_to_boundaryzASAM3VideoSemanticPredictor._suppress_detections_close_to_boundaryQ  sk   € ð &+§\¡\°"Ó%5Ñ"ˆˆu�e˜UØ�u‰} Ñ!ˆØ�u‰} Ñ!ˆØ�f‘  s¨V¡|Ñ!3Ñ4¸¸f¹ÑEÈÈsÐU[É|ÑI[Ñ\ˆàˆr7   c                óª   — | j                  |«      }| j                  j                  |||¬«      }| j                  ||«      }| j	                  |«       |S )z.Run backbone and detection for a single frame.rk  )rp   rI   rq  Ú_extract_detection_outputsÚ_cache_backbone_features)r1   r,   rl  rm  rÖ  r-   Úsam3_image_outrð  s           r6   rù  z5SAM3VideoSemanticPredictor.run_backbone_and_detection_  s]   € ð ×'Ñ'¨Ó+ˆØŸ™×5Ñ5Ø!¨HÐGWð 6ó 
ˆð ×1Ñ1°.ÐBVÓWˆØ×%Ñ% nÔ5Øˆr7   c                ón  — |d   j                  d«      j                  «       }|s|dz
  }t        j                  t	        t        |j                  d   «      «      |j                  |j                  ¬«      dd…df   j                  |«      }|d   }|d   }|| j                  kD  }||   ||   ||   ||   d	œS )
z%Extract and filter detection outputs.rx  r9   g    „×—Ar   r…   NÚpred_boxes_xyxyr�   )Úbboxr$  rÔ   r  )rš   r}  r=   r›   rù   rø   rr   r†   rF   r~  r�  )r1   r  rÖ  Ú
pred_probsr‚  r  r�   rÓ   s           r6   r  z5SAM3VideoSemanticPredictor._extract_detection_outputsk  sÒ   € à# MÑ2×:Ñ:¸2Ó>×FÑFÓHˆ
Ù#Ø# cÑ)ˆJä—<‘<Ü”�z×'Ñ'¨Ñ*Ó+Ó,Ø×"Ñ"Ø×$Ñ$ô
ò ˆTˆ'ñ	÷ ‘9˜ZÓ(ð	 	ð )Ð):Ñ;ˆØ# LÑ1ˆ
à˜D×:Ñ:Ñ:ˆà# DÑ)Ø˜tÑ$Ø  Ñ&Ø˜D‘>ñ	
ð 	
r7   c                óø   — | j                   j                  j                  }|d   d   }|j                  |d   d   «      |j	                  |d   d   «      |d   d   g}|d   |d   |d	œ}|| j                   _        y
)z'Build and cache SAM2 backbone features.rM  Úsam2_backbone_outÚbackbone_fpnr   r   r;   r9   Úvision_pos_enc)Úvision_featuresr  r  N)rµ  rI   rW  Úconv_s0Úconv_s1rM  )r1   r  rW  rR  Útracker_backbone_fpnÚtracker_backbone_outs         r6   r  z3SAM3VideoSemanticPredictor._cache_backbone_features‚  s™   € àŸ<™<×-Ñ-×>Ñ>ÐØ˜~Ñ.Ð/BÑCˆà×$Ñ$ U¨>Ñ%:¸1Ñ%=Ó>Ø×$Ñ$ U¨>Ñ%:¸1Ñ%=Ó>Ø�.Ñ! !Ñ$ð 
Ðð  4°BÑ7Ø#Ð$4Ñ5Ø0ñ 
Ðð %9ˆ�‰Õ!r7   c                óª   — | j                  ||¬«      \  }}}t        j                  ||d   k(  «      sJ dj                  ||d   «      «       ‚|}|}||fS )zGRun the tracker propagation phase for a single frame in an SPMD manner.©rl  r¸  z{} != {})Ú&_propogate_tracker_one_frame_local_gpur?   ri   rÜ   )	r1   rl  rÔ  rÕ  Úobj_ids_localÚlow_res_masks_localÚobj_scores_localÚlow_res_masks_globalÚobj_scores_globals	            r6   rû  z2SAM3VideoSemanticPredictor.run_tracker_propagation“  s…   € ð @D×?jÑ?jØ ¨Ið @kó @
Ñ<ˆÐ*Ð,<ô �v‰v�mÐ'<¸YÑ'GÑGÔHð 	
È*×J[ÑJ[ØÐ0°Ñ;óK
ó 	
ÐHð  3ÐØ,ÐØ#Ð%6Ð6Ð6r7   c                ód  — |j                  «       D �]  \  }}|d   ||dz    }	t        j                  |	j                  d«      | j                  dd¬«      dkD  }
d}t        «       }t        j                  |d   |k(  «      d   j                  «       }||   }t        |«      D ]e  \  }}||d   v sŒ||kD  sŒt        j                  d	|› d
|› d|d   › d�«       | j                  j                  ||||
¬«       |j                  |«       Œg |D ]   }| j                  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_  rl  rk  r_   )ræ  r¦   r§   r   r»  r¤  r?   rë  Úitemr÷   r   Údebugrµ  rz  r#  r{  )r1   rl  rð  Útrk_id_to_max_iou_high_conf_detrÔ  r¾  rò  Ú
trk_obj_idÚdet_idxÚnew_maskÚnew_mask_binaryÚHIGH_CONF_THRESHÚreconditioned_states_idxr›  Ú	obj_scoreÚ	state_idxr_  rÏ   s                     r6   Ú_recondition_maskletsz0SAM3VideoSemanticPredictor._recondition_masklets©  sx  € ð $C×#HÑ#HÓ#Jó 	UÑˆJ˜Ø˜v‘ w°¸1±Ð=ˆHä—‘˜h×0Ñ0°Ó3¸$×:LÑ:LÐS]ÐmrÔsÐvwÑwð ð  #ÐÜ'*£uÐ$Ü—h‘hÐ/°	Ñ:¸jÑHÓIÈ!ÑL×QÑQÓSˆGØ1°'Ñ:ˆIÜ.7Ð8LÓ.Mò <Ñ*�	˜?à /°)Ñ"<Ò<ð "Ð$4Ó4ä—L‘LØ4°Z°LÀ
È9È+ÐU_Ð`oÐpyÑ`zÐ_{ð  |Sð  Tôð —L‘L×0Ñ0Ø(7Ø"+Ø)Ø-ð	 1ô ð -×0Ñ0°Õ;ð!<ð$ 0ò U�Ø—‘×9Ñ9Ð:NÈsÑ:SÕTòUð7	Uð: $Ð#r7   c           
     óÔ  — t        |d   «      t        |d   «      t        |d   «      t        |d   «      t        |d   «      i t        |d   «      dœ}t        «       }	|d   }
|d	   j                  «       j                  «       j	                  «       }|d
   j                  «       j                  «       j	                  «       }|d   }| j                  |
|||d   ¬«      \  }}}}}| j                  r5| j                  ||   «      }||j                  «       j	                  «          }t        j                  |d   «      }t        |«      }d}||z   | j                  kD  rjt        j                  d| j                  ›d|›d|›�«       | j                  |z
  }||z
  }| j                  |||«      }t        |«      |k(  sJ ‚t        |«      }|d   dz   t        j                  |«      z   }t        |d   «      }t!        | d«      r| j"                  r| j%                  |||||||¬«      \  }}n
t        «       }||d<   ||||||||	dœ}d}| j&                  dkD  �rct        |«      dkD  �rT|j)                  «       D �]@  \  }}|d   |   }|d	   |   } 	 t+        |d   «      j-                  |«      }!||!   }"|"dkD  }#|#j                  «       j1                  «       }$|$dk(  rŒct3        |#j5                  d«      «      j7                  d«      }%|"j8                  dd \  }&}'t;        j<                  |%d   |'z  |%d   |&z  |%d   |'z  |%d   |&z  g|%j>                  ¬«      }(|j5                  d«      })|(j5                  d«      }*tA        |)|*«      d   }+|+| j&                  k  s�Œ| | jB                  k\  s�Œ.d}|	jE                  |«       �ŒC | jF                  dkD  xr" || jF                  z  dk(  xr t        |«      dkD  },|,s|r| jI                  ||||||«       |jK                  d«      }-|-dkD  rQt!        | d«      r| j"                  r%| jL                  dkD  r| jO                  ||||||«      }| jQ                  |||¬«       |d   }.t        |«      dkD  rt        jR                  |.|g«      }.t        |«      dkD  r%t        jT                  |.t+        |«      «      }/|.|/    }.|.|d<   t        |.«      |d<   t        |«      dkD  r‹|d   jW                  tY        |||   «      «       |d   jW                  tY        |||   «      «       |d   |   jW                  tY        |||   «      «       t[        |d   t        jZ                  |«      «      |d<   |D ]*  }0d|d   |0<   d|d   |   |0<   |d    j]                  |0d«       Œ, d|v sJ ‚| j^                  r$| ja                  |d   |d   |d   ||¬!«      }1|1|d<   ||fS # t.        $ r Y �Œvw xY w)"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_occludedr3  r$  rÔ   r  r  )Ú	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)rl  ru  Údet_to_matched_trk_obj_idsÚnew_det_obj_idsÚempty_trk_obj_idsÚunmatched_trk_obj_idsrØ  )Únew_det_fa_indsr;  r=  r:  Úobj_ids_newly_removedrö  r(  ró  Fr‡   Nr;   r:   r    Tr™  )r?  g     ˆÃÀr4  )rØ  Úobj_ids_all_gpu_prevÚobj_ids_all_gpu_updatedr:  r;  )1r   r¤  rL   r  r  Ú_associate_det_trkr©  r	  r?   r�  rW   r®  r   ÚwarningÚ_drop_new_det_with_obj_limitrþ   Úhasattrr9  Ú_process_hotstartr³  ræ  rù   ÚindexÚ
ValueErrorr&  r   r   rš   rr   r=   r›   rF   r   r´  r#  r°  r1  rÒ  r¨  Ú/_suppress_overlapping_based_on_recent_occlusionÚ_tracker_update_memoriesÚconcatenateÚisinr&   r¤   rÍ  rh   r±  Ú"update_masklet_confirmation_status)2r1   rl  ru  rð  rñ  rò  rÕ  rÔ  rä  ró  Údet_mask_predsr6  Ú
det_cls_npÚdet_bbox_xyxyr>  r=  r:  r(  r<  rÓ   Úprev_obj_numÚnew_det_numrö  Únew_det_num_to_keepr;  Úmetadata_newr?  rô  Úshould_recondition_iour)  r*  Ú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_periodicrq  Úupdated_obj_ids_this_gpuÚ
is_removedrk  rØ  s2                                                     r6   rü  z<SAM3VideoSemanticPredictor.run_tracker_update_planning_phaseÓ  s  € ô  Ð 5°iÑ @ÓAÜÐ 5°iÑ @ÓAÜ'Ð(=Ð>OÑ(PÓQÜ%Ð&;¸OÑ&LÓMÜ2:Ð;PÐQuÑ;vÓ2wØ')Ü"Ð#8¸Ñ#FÓGñ 
Ðô !$£Ðð (/¨v¡ˆØ$+¨HÑ$5×$;Ñ$;Ó$=×$AÑ$AÓ$C×$IÑ$IÓ$KˆØ!(¨¡×!5Ñ!5Ó!7×!;Ñ!;Ó!=×!CÑ!CÓ!Eˆ
Ø&-¨f¡oˆð ×#Ñ#Ø$Ø'Ø2Ø-¨iÑ8ð	 $ó 
ñ	
ØØ!Ø&Ø+Øð ×.Ò.Ø×>Ñ>¸}È_Ñ?]Ó^ˆDØ-¨d¯h©h«j×.>Ñ.>Ó.@ÑAˆOô —v‘vÐ3°IÑ>Ó?ˆÜ˜/Ó*ˆØ'(Ð$Ø˜+Ñ%¨×(<Ñ(<Ò<Ü�N‰NÐ; d×&:Ñ&:Ð%<Ð<OÀ;À.ÐPcÐVbÐUdÐeÔfØ"&×"6Ñ"6¸Ñ"EÐØ+6Ð9LÑ+LÐ(Ø"×?Ñ?ÀÐQ^Ð`sÓtˆOÜ�Ó'Ð+>Ò>Ð>Ð>Ü˜oÓ.ˆKð 0°Ñ=ÀÑAÄBÇIÁIÈkÓDZÑZˆô  Ð 5°jÑ AÓBˆÜ�tÐ0Ô1°T×5KÒ5KØ26×2HÑ2HØ#ØØ+EØ /Ø"3Ø&;Ø%ð 3Ió 3Ñ/Ð!¡<ô %(£EÐ!Ø+7Ð˜ZÑ(ð  /Ø.à%:Ø*DØ%:Ø,HØ/NØ%:ñ

Ðð "'Ðð ×.Ñ.°Ó2´sÐ;ZÓ7[Ð^_Ó7_Ø'F×'LÑ'LÓ'Nó $:Ñ#�
˜GØ! &™/¨'Ñ2�Ø# HÑ-¨gÑ6�	ðÜ"Ð#8¸Ñ#CÓD×JÑJÈ:ÓV�Gð  <¸GÑD�Ø*¨QÑ.�Ø'ŸO™OÓ-×2Ñ2Ó4�	à ’>Øô &9¸×9NÑ9NÈqÓ9QÓ%R×%ZÑ%ZÐ[\Ó%]Ð"Ø*6×*<Ñ*<¸R¸SÐ*AÑ'�˜ZÜ).¯©à*¨1Ñ-°
Ñ:Ø*¨1Ñ-°Ñ;Ø*¨1Ñ-°
Ñ:Ø*¨1Ñ-°Ñ;ð	ð .×4Ñ4ô*Ð&ð !(× 1Ñ 1°!Ó 4�Ø$:×$DÑ$DÀQÓ$GÐ!Ü˜mÐ->Ó?ÀÑB�à˜×<Ñ<Ô<ÀÈd×NpÑNpÔApØ-1Ð*Ø)×-Ñ-¨jÖ9ðI$:ðN ×,Ñ,¨qÑ0ò 9Ø˜D×<Ñ<Ñ<ÀÑAò9äÐ3Ó4°qÑ8ð 	$ñ 'Ñ*@Ø×&Ñ&ØØØ/Ø$Ø%Ø)ôð 2×6Ñ6°qÓ9ˆ
Ø˜Š>Ü˜4Ð!4Ô5¸×9OÒ9OØ×PÑPÐSVÒVà37×3gÑ3gØ!Ø4Ø-Ø,Ø-Øó4Ð0ð ×)Ñ)Ð*>À	ÐYuÐ)Ôvð $8¸	Ñ#BÐ ÜˆÓ !Ò#Ü')§~¡~Ð7OÐQ`Ð6aÓ'bÐ$ÜÐ$Ó%¨Ò)ÜŸ™Ð!9¼4Ð@UÓ;VÓWˆJØ'?ÀÀÑ'LÐ$Ø*BÐ˜YÑ'Ü*-Ð.FÓ*GÐ˜YÑ'äˆÓ !Ò#Ø Ð!2Ñ3×:Ñ:¼3¸ÐP]Ð^mÑPnÓ;oÔpØ  Ñ1×8Ñ8¼¸_ÈjÐYhÑNiÓ9jÔkà Ð!EÑFÀyÑQ×XÑXÜ�O ]°?Ñ%CÓDôô 25Ð5IÈ,Ñ5WÔY[×Y_ÑY_Ð`oÓYpÓ1qÐ  Ñ.ð ,ò 	NˆFØ>BÐ Ð!2Ñ3°FÑ;Ø\`Ð Ð!EÑFÀyÑQÐRXÑYØ Ð!:Ñ;×?Ñ?ÀÈÕMð	Nð
 Ð1Ñ1Ð1Ð1Ø×+Ò+Ø×>Ñ>Ø-¨jÑ9Ø%:¸9Ñ%EØ(<¸YÑ(GØ+EØ /ð ?ó ˆHð 08Ð  Ñ,à"Ð$8Ð8Ð8øôO "ò Úðús   ÊW×	W'×&W'c                óš  — |d   }|dkD  }|j                  d«      }	|	dkD  �rt        |«      |	k(  sJ dt        |«      › d|	› �«       ‚t        j                  |D �
cg c]`  }
|d   j	                  |
t        j
                  d|
|vr| j                  n| j                  |j                  t        j                  ¬«      «      ‘Œb c}
d¬«      }| j                  |||||«      }|j                  d	¬«       }||z  }|j                  «       }|||<   t        |«      D ��
ci c]  \  }}
|
|||d
z    “Œ c}
}|d<   | j                  ||<   |S c c}
w c c}
}w )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 r4  r  )rÓ  rF   r†   rò   ©r9   r‡   r   )rÒ  rW   r=   rª   r—  rÛ  ÚNEVER_OCCLUDEDÚALWAYS_OCCLUDEDrF   rr  Ú8_get_objects_to_suppress_based_on_most_recently_occludedrÌ  rÌ  r÷   ÚNO_OBJ_LOGIT)r1   rl  rñ  rÕ  rä  r?  ru  Úobj_ids_globalÚ#binary_tracker_low_res_masks_globalrq  rk  Úlast_occluded_prevÚto_suppressÚis_obj_occludedÚis_obj_occluded_or_suppressedÚlast_occluded_newr›  s                    r6   rI  zJSAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusion§  sœ  € ð. /¨yÑ9ˆØ.JÈQÑ.NÐ+Ø1×6Ñ6°qÓ9ˆ
Ø˜‹>Ü�~Ó&¨*Ò4ð Ø1´#°nÓ2EÐ1FÀdÈ:È,ÐWóÐ4ô "'§¡ð #1öð ð *Ð*CÑD×HÑHØÜŸ
™
Ø à7=ÐEZÑ7Z × 3Ò 3Ð`d×`tÑ`tà#F×#MÑ#MÜ"'§*¡*ôõ
òð ô"Ðð" ×WÑWØ3Ø"ØØØóˆKð !D× GÑ GÈHÐ GÓ UÐVˆOØ,;¸kÑ,IÐ)Ø 2× 8Ñ 8Ó :ÐØ?HÐÐ;Ñ<ô YbÐbpÓXq÷?ÙETÀWÈf�Ð)¨'°G¸a±KÐ@Ñ@ó?Ð Ð!:Ñ;ð
 9=×8IÑ8IÐ(¨Ñ5à+Ð+ùòKùó<?s   ÁA%EÄEc                óî   — |d   }|d   }|}|}	|d   }
t        |	«      dkD  r3t        j                  |	«      }|d   |   }| j                  |||||¬«      }t        |
«      dkD  r| j	                  ||
«       |S )zEExecute the tracker update plan for a single frame in an SPMD manner.r>  r;  r?  r   r$  )rl  rµ  r  Únew_obj_masksrÔ  )rW   r=   rD   Ú_tracker_add_new_objectsÚ_tracker_remove_objects)r1   rl  rµ  rð  rÔ  rô  r>  r;  Únew_det_obj_ids_localÚnew_det_fa_inds_localr?  Únew_det_fa_inds_local_tÚnew_det_maskss                r6   rý  z=SAM3VideoSemanticPredictor.run_tracker_update_execution_phaseí  s±   € ð ':Ð:KÑ&LˆØ&9Ð:KÑ&Lˆà,;ÐØ,;ÐØ*=Ð>UÑ*VÐô Ð$Ó%¨Ò)Ü&+×&6Ñ&6Ð7LÓ&MÐ#Ø*1°&©/Ð:QÑ*RˆMà#'×#@Ñ#@Ø#Ø%Ø1Ø+Ø%9ð $Aó $Ð ô Ð$Ó%¨Ò)Ø×(Ñ(Ð)=Ð?TÔUà#Ð#r7   c                ó  — |d   }|d   }i }|d   }|j                  d«      }	t        |«      t        |	«      k(  sJ ‚t        ||	«      D ]
  \  }
}|||
<   Œ t        j                  |«      }| d   |   j                  d«      }t        |«      t        |«      k(  sJ ‚t        ||«      D ]
  \  }
}|||
<   Œ |�Ut        |«      dkD  rG|j                  di «      }|D ]0  }
|j                  |
«      }|€Œ| d   |   j                  d«      ||
<   Œ2 |S )z-Build the output masks for the current frame.r>  r;  r¸  r   r$  r   r(  )r   rW   r¤   r=   rD   r—  )rð  rñ  rÕ  rô  ró  r>  r;  rÄ  Úexisting_masklet_obj_idsÚexisting_masklet_binaryrk  r$  Únew_det_fa_inds_tÚnew_det_low_res_masksr(  r*  s                   r6   rþ  z(SAM3VideoSemanticPredictor.build_outputs  sa  € ð ':Ð:KÑ&LˆØ&9Ð:KÑ&LˆØˆð $9¸Ñ#CÐ Ø">×"HÑ"HÈÓ"KÐÜÐ+Ó,´Ð4KÓ0LÒLÐLÐLÜÐ 8Ð:QÓRò 	*‰LˆF�DØ%)ˆN˜6Ò"ð	*ô "×,Ñ,¨_Ó=ÐØ '¨¡Ð0AÑ B× LÑ LÈQÓ OÐÜ�?Ó#¤sÐ+@Ó'AÒAÐAÐAÜ Ð1FÓGò 	*‰LˆF�DØ%)ˆN˜6Ò"ð	*ð !Ð,´Ð5JÓ1KÈaÒ1OØ.A×.EÑ.EÐFgÐikÓ.lÐ+à/ò S�Ø9×=Ñ=¸fÓE�àÑ&Ø-4°V©_¸WÑ-E×-OÑ-OÐPQÓ-R�N 6Ò*ð	Sð Ðr7   c                ó$  — |j                   t        j                  k(  sJ d|j                   › �«       ‚t        j                  |j	                  d«      |j
                  t        j                  ¬«      }t        |«      dk  r|S t        |j                  d«      |j                  d«      «      }|| j                  k\  }t        j                  |d¬«      }	|j                  d«      }
|j                  d«      }|st        j                  nt        j                  }|	 ||
|«      z  |dkD  z  }|	 |||
«      z  |
dkD  z  }|j                  d¬«      |j                  d¬«      z  }t        j                   d«      �r|��|j#                  «       j%                  «       }|j#                  «       j%                  «       }|j#                  «       j%                  «       }|j&                  d   }t)        |«      D ]J  }t)        |«      D ]:  }|||f   sŒt        j*                  d	|›d
||   › d||   › d||   › d||   › �
«       Œ< ŒL t)        |«      D ]J  }t)        |«      D ]:  }|||f   sŒt        j*                  d	|›d
||   › d||   › d||   › d||   › �
«       Œ< ŒL |S )NzExpected boolean tensor, got r   r  r   )Údiagonalr9   rò   rš  z
frame_idx=z: Suppressing obj z last occluded z in favor of )r†   r=   rE  rû   rÒ  rF   rW   r   r~   r¨  Útriur   ÚgtÚltrÌ  r   ÚisEnabledForr  r  rr   rø   r'  )r1   Úbinary_low_res_masksÚlast_occludedr¸  rl  ru  ro  r¬   Úmask_iou_threshÚoverlapping_pairsÚlast_occ_expanded_iÚlast_occ_expanded_jÚcmp_opÚsuppress_i_maskÚsuppress_j_maskrq  rf   Újs                     r6   rj  zSSAM3VideoSemanticPredictor._get_objects_to_suppress_based_on_most_recently_occluded8  s"  € ð $×)Ñ)¬U¯Z©ZÒ7ÐuÐ;XÐYm×YsÑYsÐXtÐ9uÓuÐ7Ü—k‘kØ ×%Ñ% aÓ(Ø'×.Ñ.Ü—*‘*ô
ˆô
 ˆw‹<˜1ÒØÐäÐ+×3Ñ3°AÓ6Ð8L×8TÑ8TÐUVÓ8WÓXˆð  ×!^Ñ!^Ñ^ˆÜ!ŸJ™J ÀÔCÐà+×5Ñ5°aÓ8ÐØ+×5Ñ5°aÓ8Ðá!(”—’¬e¯h©hˆàÙÐ(Ð*=Ó>ñ?à" RÑ'ñ)ð 	ð ÙÐ(Ð*=Ó>ñ?à" RÑ'ñ)ð 	ð &×)Ñ)¨aÐ)Ó0°?×3FÑ3FÈ1Ð3FÓ3MÑMˆô ×Ñ˜rÕ" yÑ'<Ø-×1Ñ1Ó3×9Ñ9Ó;ˆOØ-×1Ñ1Ó3×9Ñ9Ó;ˆOØ)×-Ñ-Ó/×5Ñ5Ó7ˆMð )×.Ñ.¨qÑ1ˆJô ˜:Ó&ò �Ü˜zÓ*ò �AØ& q¨! tÓ,ÜŸ™Ø)˜y˜lÐ*<¸WÀQ¹Z¸LÈÐXeÐfgÑXhÐWiÐivÐw~ð  @Añ  xBð  wCð  CRð  S`ð  abñ  Scð  Rdð  eõñðô ˜:Ó&ò �Ü˜zÓ*ò �AØ& q¨! tÓ,ÜŸ™Ø)˜y˜lÐ*<¸WÀQ¹Z¸LÈÐXeÐfgÑXhÐWiÐivÐw~ð  @Añ  xBð  wCð  CRð  S`ð  abñ  Scð  Rdð  eõñðð Ðr7   c                ó�  — g }g }g }|D ]˜  }t        |d   «      dk(  rŒ| j                  j                  ||¬«      \  }}}	t        |t        «      sJ ‚|j                  |«       |j                  |j                  d«      «       |j                  |	j                  d«      «       Œš t        |«      dkD  r@t        j                  |d¬«      }
t        j                  |d¬«      }|
j                  d«      }
nQt        j                  dg| j                  d   ¢­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   r  r   rò   rF   r    )rW   rµ  r”  r<   rù   Úextendr©   rš   r=   rª   rû   rC  rF   )r1   Úinference_statesrl  r  Úlow_res_masks_listÚobj_scores_listr_  Úout_obj_idsÚout_low_res_masksÚout_obj_scoresr  r   s               r6   r  zASAM3VideoSemanticPredictor._propogate_tracker_one_frame_local_gpu|  sC  € àˆØÐØˆØ/ò 
	>ˆOÜ�? 9Ñ-Ó.°!Ò3Øà=A¿\¹\×=\Ñ=\Ø¨9ð >]ó >Ñ:ˆKÐ*¨Nô ˜k¬4Ô0Ð0Ð0Ø× Ñ  Ô-Ø×%Ñ%Ð&7×&?Ñ&?ÀÓ&BÔCØ×"Ñ" >×#9Ñ#9¸!Ó#<Õ=ð
	>ô Ð!Ó" QÒ&Ü"'§)¡)Ð,>ÀAÔ"FÐÜ$Ÿy™y¨¸aÔ@ÐØ"5×"=Ñ"=¸aÓ"@Ñä"'§+¡+¨aÐ"]°$×2EÑ2EÀaÑ2HÒ"]ÐQU×Q\ÑQ\Ñ"]ÐÜ$Ÿ{™{¨1°T·[±[ÔAÐàÐ1Ð3CÐCÐCr7   c           	     óô	  — | j                   }| j                  }| j                  }|j                  «       sJ d«       ‚|j                  «       sJ d«       ‚|j	                  d«      t        |«      k(  s%J d|j	                  d«      › dt        |«      › �«       ‚|j	                  d«      dk(  rwt        j                  |j	                  d«      «      }t        j                  g t        j                  «      }	t        j                  g t        j                  «      }
i }i }||	|||
fS |j	                  d«      dk(  rkt        j                  g t        j                  «      }|dkD  j                  d¬«      j                  «       j                  «       }||   }	||    }
i }i }||	|||
fS |j                  dd |j                  dd k7  rÎt        j                  |j                  dd «      t        j                  |j                  dd «      k  rEt        j                   |j#                  d	«      |j                  dd d
d¬«      j%                  d	«      }nDt        j                   |j#                  d	«      |j                  dd d
d¬«      j%                  d	«      }|dkD  }|dkD  }t'        |j)                  d	«      j+                  «       |j)                  d	«      j+                  «       «      }|j                  «       j                  «       }| j,                  reddlm} d	|z
  } ||«      \  }}t        j2                  |j	                  d«      t4        ¬«      }t7        ||«      D ]  \  }}|||f   |k\  sŒd||<   Œ n||k\  j                  d¬«      }|j                  d¬«      j                  «       j                  «       }t        j8                  || «      }||   }	||    }
t        j8                  ||k\  t        j:                  t        j                  ||k\  d	¬«      «      «      }t        j<                  |«      d   }i }i }t        j>                  |d	¬«      }|| j@                  k\  | z  }t        jB                  |d	¬«      | jD                  k\  }tG        t        j<                  ||z  «      d   «      }tI        |j	                  d«      «      D ]4  }|||dd…f   |k\     ||<   ||v sŒ|||      jK                  «       }|||<   Œ6 ||	|||
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, rf  rx  rò   r‡   Nr   r¡   FrØ  )Úlinear_sum_assignmentr‹   TrŽ   )&rŸ  r   r¡  Úis_floating_pointrÒ  rW   r?   rþ   r¥   Úint64rÌ  r  r  rr   Úprodr¦   r§   r   rš   r   r~   rL   r«  Úscipy.optimizer™  rû   rE  r¤   Úlogical_andÚlogical_notÚnonzeroÚargmaxr-  rÍ  ÚHIGH_IOU_THRESHr¤  rø   r&  ) r1   r5  r6  r7  r8  Úiou_thresholdÚiou_threshold_trkr¡  r>  r=  r<  r:  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_iour)  s                                    r6   rB  z-SAM3VideoSemanticPredictor._associate_det_trk˜  só  € ð. ×-Ñ-ˆØ ×5Ñ5ÐØ×,Ñ,ˆà×*Ñ*Ô,ÐWÐ.WÓWÐ,Ø×*Ñ*Ô,ÐWÐ.WÓWÐ,Ø�~‰~˜aÓ ¤C¨Ó$4Ò4ð 	
ØEÀiÇnÁnÐUVÓFWÐEXÐX\Ô]`ÐalÓ]mÐ\nÐoó	
Ð4ð �>‰>˜!Ó Ò!ä Ÿi™i¨	¯©°qÓ(9Ó:ˆOÜ$&§H¡H¨R´·±Ó$:Ð!Ü "§¡¨¬R¯X©XÓ 6ÐØ)+Ð&Ø.0Ð+àØ%Ø*Ø/Ø!ðð ð �^‰^˜AÓ !Ò#ä Ÿh™h r¬2¯8©8Ó4ˆOØ(¨1™}×1Ñ1°fÐ1Ó=×AÑAÓC×IÑIÓKˆOØ$/°Ñ$@Ð!Ø +¨_Ð,<Ñ =ÐØ)+Ð&Ø.0Ð+àØ%Ø*Ø/Ø!ðð ð �?‰?˜2˜3Ð 9§?¡?°2°3Ð#7Ò7ä�w‰w�y—‘ r sÐ+Ó,¬r¯w©w°y·±ÀrÀsÐ7KÓ/LÒLÜŸM™MØ×'Ñ'¨Ó*Ø"Ÿ™¨¨Ð-Ø#Ø"'ô	÷
 ‘'˜!“*ñ ô ŸM™MØ×'Ñ'¨Ó*Ø"Ÿ™¨¨Ð-Ø#Ø"'ô	÷
 ‘'˜!“*ð ð % q™=ÐØ$ q™=ÐÜÐ(×0Ñ0°Ó3×9Ñ9Ó;Ð=M×=UÑ=UÐVWÓ=X×=^Ñ=^Ó=`Óaˆà—(‘(“*×"Ñ"Ó$ˆØ×,Ò,Ý<ð ˜g™+ˆKÙ4°[ÓAÑˆG�WÜŸX™X i§n¡n°QÓ&7¼tÔDˆNÜ˜G WÓ-ò -‘��1Ø˜1˜a˜4‘=Ð$5Ó5Ø(,�N 1Ò%ñ-ð &Ð):Ñ:×?Ñ?ÀQÐ?ÓGˆNà*×.Ñ.°6Ð.Ó:×>Ñ>Ó@×FÑFÓHˆÜŸ>™>¨/¸N¸?ÓKÐØ +Ð,<Ñ =Ðà'¨Ð(8Ñ9Ðô —^‘^Ø˜^Ñ+Ü�N‰Nœ2Ÿ6™6 '¨]Ñ":ÀÔCÓDó
ˆ
ô Ÿ*™* ZÓ0°Ñ3ˆð &(Ð"Ø*,Ð'Ü!#§¡¨7¸Ô!;ÐØ)¨T×-BÑ-BÑBÀzÀkÑQÐÜŸ&™& ¨qÔ1°T×5IÑ5IÑIˆÜ#&¤r§z¡zÐ2BÀ_Ñ2TÓ'UÐVWÑ'XÓ#YÐ Ü�y—~‘~ aÓ(Ó)ò 	@ˆAØ,7¸ÀÂ1À¹ÈÑ8VÑ,WÐ& qÑ)ØÐ,Ò,Ø(Ð)?ÀÑ)BÑC×HÑHÓJ�
Ø>?Ð/°
Ò;ð		@ð Ø!Ø&Ø+Øð
ð 	
r7   c                óò  ‡— |d   Š|d   }|d   }	|d   }
|d   }t        «       }|s|| j                  z
  n|| j                  z   }|D ]   }|‰vr|‰|<   ||	vsJ ‚| j                  |	|<   Œ" t        «       }|j                  «       D ]  }|j	                  |«       Œ |D ]!  }t        | j                  |	|   dz   «      |	|<   Œ# |D ]5  }||   j                  |«       t        | j                  |	|   dz
  «      |	|<   Œ7 | j                  r&|D ]!  }t        | j                  |	|   dz
  «      |	|<   Œ# |j                  «       D ]²  \  }}||v s||v rŒt        |«      | j                  k\  rL‰|   |kD  xr | xs ‰|   |k  xr |}|r/|j                  |«       t        j                   d|› d|› d	|› �«       |	|   d
k  sŒ|||vsŒ�||vsŒ†t        j                   d|› d|› d�«       |j                  |«       Œ´ |j                  «       D ][  \  }}t        |«      dk  rŒ|st        |ˆfd„¬«      nt        |ˆfd„¬«      }|D ]   }||k7  sŒ	||f}|
|   j                  |«       Œ" Œ] |
j                  «       D ]r  \  \  }}}||v s||v rŒ‰|   |kD  r|r‰|   |k  sŒ%|sŒ(t        |«      | j"                  k\  sŒA|j                  |«       t        j                   d|› d|› d|› d|› �«       Œt |j	                  |«       ||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 r$  z# since it is unmatched for frames: r   z, due to being unmatchedr;   c                ó   •— ‰|    S rb   rc   ©r[   r¶  s    €r6   ú<lambda>z>SAM3VideoSemanticPredictor._process_hotstart.<locals>.<lambda>q  s   ø€ Ð7JÈ1Ñ7M€ r7   )Úkeyc                ó   •— ‰|    S rb   rc   r»  s    €r6   r¼  z>SAM3VideoSemanticPredictor._process_hotstart.<locals>.<lambda>s  s   ø€ Ð<OÐPQÑ<R€ r7   z& since it overlaps with another track z at frames: )r¤  r¢  r¥  r¥  r&   r�   r¦  r©   rÍ  r§  rª  ræ  rW   r£  r#  r   r'  r¤  )r1   rl  ru  r:  r;  r<  r=  rØ  r·  r¸  r¹  rÙ  r?  Úhotstart_diffrk  Úmatched_trksÚmatched_trks_per_detÚframe_indicesÚis_within_hotstartrN  Úmatched_trk_obj_idsÚfirst_appear_obj_idr½  Úfirst_obj_idr¶  s                           @r6   rF  z,SAM3VideoSemanticPredictor._process_hotstart  sï  ø€ ð 'Ð'<Ñ=Ðà'Ð(>Ñ?ÐØ!Ð"2Ñ3ˆà%-Ð.JÑ%KÐ"à"Ð#4Ñ5ˆä #£ÐÙ?F˜	 D×$7Ñ$7Ò7ÈIÐX\×XkÑXkÑLkˆð &ò 	>ˆFØÐ0Ñ0Ø.7Ð# FÑ+Ø Ñ/Ð/Ð/Ø%)×%=Ñ%=ˆN˜6Ò"ð		>ô “uˆà$>×$EÑ$EÓ$Gò 	6Ð Ø×ÑÐ 4Õ5ð	6à"ò 	^ˆFä%(¨×)@Ñ)@À.ÐQWÑBXÐ[\ÑB\Ó%]ˆN˜6Ò"ð	^ð ,ò 	^ˆFØ  Ñ(×/Ñ/°	Ô:ô &)¨×)@Ñ)@À.ÐQWÑBXÐ[\ÑB\Ó%]ˆN˜6Ò"ð		^ð
 ×:Ò:Ø+ò b�ä),¨T×-DÑ-DÀnÐU[ÑF\Ð_`ÑF`Ó)a�˜vÒ&ðbð &:×%?Ñ%?Ó%Aò 	2Ñ!ˆF�MØ˜Ñ(¨FÐ6KÑ,KØÜ�=Ó! T×%AÑ%AÒAØ&9¸&Ñ&AÀMÑ&QÒ&aÐZaÐVaò &Ø'¨Ñ/°-Ñ?ÒKÀGð #ñ &Ø)×-Ñ-¨fÔ5Ü—L‘LØ*¨6¨(°*¸Y¸Kð H=Ø=J¸OðMôð
 ˜vÑ&¨!Ó+Ø /Ò1ØÐ"7Ò7ä—‘Ð/°¨x°zÀ)ÀÐLdÐeÔfà%×)Ñ)¨&Õ1ð)	2ð0 'A×&FÑ&FÓ&Hò 	FÑ"ˆAÐ"ÜÐ&Ó'¨!Ò+Øñ
 ô Ð'Ó-MÕNäÐ,Ó2RÔSð  ð
 .ò F�ØÐ0Ó0Ø.°Ð7�CØ.¨sÑ3×:Ñ:¸9ÕEñFð	Fð" 6P×5UÑ5UÓ5Wò 	Ñ1Ñ"ˆ\˜6 MØ˜Ñ(¨FÐ6KÑ,KØØ# FÑ+¨mÒ;ÁGØ# FÑ+¨mÓ;Âä�}Ó%¨×)AÑ)AÓAØ)×-Ñ-¨fÔ5Ü—L‘LØ*¨6¨(°*¸Y¸Kð H@Ø@L¸~È\ÐZgÐYhðjõð	ð 	×ÑÐ4Ô5Ø$ hÐ.Ð.r7   c                óê  — t        |«      dk(  ryt        j                  |j                  d«      | j                  dd¬«      }t        | d«      r| j                  r%| j                  j                  j                  |«      }t        j                  |dkD  j                  d¬	«      d
d«      }d}|}|D ]½  }t        |d   «      }	|	dk(  rŒ||	z   }
|||
 }|||
 }|j                  d«      }| j                  j                  |||d|¬«      }|\  }}|d   }dD ]S  }|||   vrŒ|||   |   d<   |D �cg c]  }|‘Œ c}||   |   d<   | j                  j                  ||||   |   |¬«       ŒU ||	z  }Œ¿ yc c}w )zHRun Sam2 memory encoder, enforcing non-overlapping constraints globally.r   Nr   r¡   FrØ  r9  rg  rò   rÔ  r˜  r¸  )rÚ  r_  ri  r´  rÆ  rÈ  )r_  rl  rƒ  r‚  )rW   r¦   r§   r   r»  rE  r9  rµ  rI   Ú"_suppress_object_pw_area_shrinkager=   rë  rÌ  rÒ  rß  r€  )r1   r½  rl  r?  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_encri  r‚  Úposs                       r6   rJ  z3SAM3VideoSemanticPredictor._tracker_update_memoriesŒ  sà  € ô Ð'Ó(¨AÒ-ØäŸ™Ø×#Ñ# AÓ&Ø×#Ñ#ØØô	
ˆô �tÐ0Ô1°T×5KÒ5KØ!Ÿ\™\×/Ñ/×RÑRÐSaÓbˆNä#Ÿk™k¨>¸AÑ+=×*BÑ*BÀxÐ*BÓ*PÐRVÐX]Ó^Ðð ˆØ'ˆØ5ò "	1ˆMÜ # M°)Ñ$<Ó =ÐØ  AÒ%Øà+Ð.?Ñ?ˆMØ#1°/À-Ð#PÐ Ø(;¸OÈMÐ(ZÐ%Ø3×8Ñ8¸Ó;Ðð Ÿ,™,×:Ñ:Ø Ø$Ø)Ø!&Ø -ð ;ó ˆKð =HÑ9Ð"Ð$9à'¨Ñ6ˆKØOò �Ø K°Ñ$<Ñ<ØØJ`�˜KÑ(¨Ñ3Ð4FÑGØYnÖIoÐRUÊ#ÒIo�˜KÑ(¨Ñ3Ð4EÑFð —‘×3Ñ3Ø$1Ø'Ø +¨KÑ 8¸Ñ CØ +ð	 4õ ðð Ð0Ñ0‰OñE"	1ùò2 Jps   Ä,	E0c                óV  — t        |«      dkD  r|d   nd}| j                  j                  |¬«      }d|d<   |�|j                  dd«      nd|d<   t        |«      |j	                  d«      k(  sJ ‚|j                  «       sJ ‚t        j                  |j                  d«      | j                  dd¬«      j                  d«      }|dkD  }t        ||«      D ]'  \  }}	| j                  j                  ||||	d	   ¬
«       Œ) | j                  j                  |«       |j                  |«       |S )z*Add a new object to SAM2 inference states.r   N)rµ  r,   rM  r¡   FrØ  r  r%  )rW   rµ  r°  r—  rÒ  rš  r¦   r§   r   r»  rš   r¤   rz  r{  r©   )
r1   rl  rµ  r  rt  rÔ  Úprev_tracker_stateÚnew_tracker_stateÚ
new_obj_idr+  s
             r6   ru  z3SAM3VideoSemanticPredictor._tracker_add_new_objectsÆ  sO  € ô 9<Ð<PÓ8QÐTUÒ8UÐ1°!Ò4Ð[_Ðð
 !ŸL™L×4Ñ4À
Ð4ÓKÐà"&Ð˜$Ñà<NÐ<ZÐ×"Ñ" >°4Ô8Ð`dð 	˜.Ñ)ô �;Ó =×#5Ñ#5°aÓ#8Ò8Ð8Ð8Ø×.Ñ.Ô0Ð0Ð0ÜŸ™Ø×#Ñ# AÓ&Ø×#Ñ#ØØô	
÷
 ‰'�!‹*ð 	ð &¨Ñ)ˆô %(¨°]Ó$Cò 	Ñ ˆJ˜Ø�L‰L×(Ñ(Ø 1Ø#Ø!Ø˜zÑ*ð	 )õ ð	ð 	�‰×1Ñ1Ð2CÔDØ×#Ñ#Ð$5Ô6Ø#Ð#r7   c                ó¶   — |syg }|D ]J  }|D ]   }| j                   j                  ||d¬«       Œ" t        |d   «      dkD  sŒ:|j                  |«       ŒL ||dd y)zgRemove an object from SAM2 inference states. This would remove the object from all frames in the video.NF©r   r¸  r   )rµ  r  rW   r©   )r1   rÔ  r¸  Úactive_statesÚstaterk  s         r6   rv  z2SAM3VideoSemanticPredictor._tracker_remove_objectsò  sw   € áØàˆØ)ò 	,ˆEØ!ò H�ð —‘×*Ñ*¨5°&ÀÐ*ÕGðHô
 �5˜Ñ#Ó$ qÓ(Ø×$Ñ$ UÕ+ð	,ð #0Ð™QÑr7   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                  rLt        j                  g t         j                  «      t        j                  g t         j                  «      dœ|d<   ||d<   |S )z%Initialize metadata for the masklets.r   r9   )r¸  rõ  r3  rÆ  rÇ  r×  r4  )r¶  r·  r¸  r¹  rÙ  )rÜ  Úconsecutive_det_numrÛ  rØ  )r?   r¥   r•   rû   r   r'   rù   rB  r¤  r±  r›  )r1   r¾  rØ  s      r6   rú  z/SAM3VideoSemanticPredictor._initialize_metadata  sÀ   € ô —x‘x ¤B§H¡HÓ-Ü—x‘x ¤2§8¡8Ó,ØØ!ØÜ2=¼dÓ2CØ')ñ
Ðð $&Ü$/´Ó$5Ü)¬#Ó.Ü*5´dÓ*;Ü"›uñ
ˆð ×+Ò+ô Ÿ(™( 2¤r§x¡xÓ0ô (*§x¡x°´B·H±HÓ'=ñ0ˆHÐ+Ñ,ð (0Ð˜Ñ$àÐr7   c                ó(  — |d   }|d   }|d   }|j                   |j                   k(  s!J d|j                   › d|j                   › �«       ‚t        |«      D �	�
ci c]  \  }	}
|
|	“Œ
 }}	}
t        j                  ||«      }||   }t        j                  |D �
cg c]  }
||
   ‘Œ	 c}
t        j
                  ¬«      }| j                  }t        j                  ||¬«      }||   ||<   t        j                  |«      }||   ||<   t        j                  ||«      }|j                  «       D ]  }|t        j                  ||«      z  }Œ t        j                  ||dz   d	«      }|| j                  k\  }| j                  ||<   ||d<   ||d<   |S c c}
}	w c c}
w )
zZUpdate the confirmation status of masklets based on the current frame's detection results.rÛ  rÜ  rÞ  zGot rf  r‹   )rÓ  r   r   )rr   r÷   r?   rL  r¥   r›  rß  Ú	full_likeÚ
zeros_liker¥  rë  r²  Ú	CONFIRMED)r1   rØ  r@  rA  r:  r;  Úconfirmation_dataÚstatus_prevÚconsecutive_det_num_prevrÏ   rk  Úobj_id_to_updated_idxÚprev_elem_is_in_updatedÚprev_elem_obj_ids_in_updatedÚprev_elem_inds_in_updatedÚunconfirmed_valrÜ  rÞ  Ú
is_matchedrÄ  Úchange_to_confirmeds                        r6   rM  z=SAM3VideoSemanticPredictor.update_masklet_confirmation_status(  sÑ  € ð %Ð%;Ñ<Ðð (¨Ñ1ˆØ#4Ð5JÑ#KÐ Ø× Ñ Ð$8×$>Ñ$>Ò>ð 	
Ø�;×$Ñ$Ð% TÐ*>×*DÑ*DÐ)EÐFó	
Ð>ô AJÐJaÓ@b× c±°°f ¨¡Ð cÐÑ cÜ"$§'¡'Ð*>Ð@WÓ"XÐØ';Ð<SÑ'TÐ$Ü$&§H¡HØ9UÖV¨vÐ" 6Ó*ÒVÜ—(‘(ô%
Ð!ð
 ×*Ñ*ˆÜ—‘Ð5À/ÔRˆØ,7Ð8OÑ,PˆÐ(Ñ)Ü Ÿm™mÐ,CÓDÐØ9QÐRiÑ9jÐÐ5Ñ6ô
 —W‘WÐ4°oÓFˆ
Ø#=×#DÑ#DÓ#Fò 	PÐØœ"Ÿ'™'Ð"9Ð;NÓOÑO‰Jð	Pä Ÿh™h zÐ3FÈÑ3JÈAÓNÐð 2°T×5eÑ5eÑeÐØ&*§n¡nˆÐ"Ñ#à&,Ð˜(Ñ#Ø3FÐÐ/Ñ0Øˆùó9 !dùò Ws   ÁF	ÂFc                ó   — t        j                  |dd¬«      d   }| j                  ||¬«      \  }}t        |«      dkD  st        |«      dkD  rt	        j
                  d|›d|›�«       y t	        j                  d	«       y )
Nr  T)Úmap_locationÚweights_onlyrI   rÚ  r   zLoaded ckpt with missing_keys=z, unexpected_keys=z;Loaded ckpt successfully without missing or unexpected keys)r=   ÚloadÚload_state_dictrW   r   rC  Úinfo)r1   Ú	ckpt_pathr   ÚsdÚmissing_keysÚunexpected_keyss         r6   Ú_load_checkpointz+SAM3VideoSemanticPredictor._load_checkpointX  su   € Ü�Z‰Z˜	°ÀDÔIÈ'ÑRˆØ(,×(<Ñ(<¸RÈÐ(<Ó(OÑ%ˆ�oÜˆ|Ó˜qÒ ¤C¨Ó$8¸1Ò$<Ü�N‰NÐ<¨|¨oÐ=PÀÐ?QÐRÕSä�K‰KÐUÕVr7   c                ó:   —  | j                   j                  di |¤ŽS )Nrc   )rI   Ú_encode_prompt)r1   rm   s     r6   rù  z)SAM3VideoSemanticPredictor._encode_prompt`  s   € Ø(ˆt�z‰z×(Ñ(Ñ2¨6Ñ2Ð2r7   c                óö   — d|cxk  rt        | «      k  sJ ‚ 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   Nr9   )rW   r?   r¥   r›  Úargsort)r>  r6  Únum_to_keepÚscore_orders       r6   rD  z7SAM3VideoSemanticPredictor._drop_new_det_with_obj_limitc  s‡   € ð
 �KÔ7¤3 Ó#7Ò7Ð7Ñ7Ð7Ð7Ø˜!ÒÜ—8‘8˜B¤§¡Ó)Ð)Øœ#˜oÓ.Ò.Ø"Ð"ô —j‘j ¨Ñ!?Ó@ÁÀ2ÀÑFˆØ)¨+°l°{Ð*CÑDˆØÐr7   r)  r/  rŽ  r�  )FNr+  )r˜  )T)r,   rI  rl  rI  rl  rB  rµ  rB  ru  rE  rm  r   rÔ  ú	list[Any]rÕ  rJ  rÖ  rE  )gš™™™™™™?)r,   rI  rl  rI  rm  r   rÖ  rE  )rl  rB  rÔ  rþ  rÕ  údict[str, np.ndarray])
rð  údict[str, torch.Tensor]r(  ú	list[int]rÔ  rþ  r¾  rÿ  rò  rI  )rl  rB  ru  rE  rð  r   rñ  rI  rò  rI  rÕ  rÿ  rÔ  rþ  r  )rl  rB  rñ  rI  rÕ  rJ  rä  rJ  r?  zset[int]ru  rE  )
rl  rB  rµ  rB  rð  r   rÔ  rþ  rô  rÿ  rb   )
rð  r   rñ  rI  rÕ  rÿ  rô  rÿ  ró  z
set | None)NF)
r†  rI  r‡  r  r¸  r  rl  rH  ru  rE  )r’  rþ  rl  rB  )r5  rI  r6  ú
np.ndarrayr7  rI  r8  r  )rl  rB  ru  rE  r:  údict[int, np.ndarray]r;  r  r<  r  r=  r  rØ  rJ  )r½  rþ  rl  rB  r?  rI  )
rl  rB  rµ  rB  r  r  rt  rI  rÔ  rþ  )rÔ  rþ  r¸  r  )
rØ  rJ  r@  r  rA  r  r:  r  r;  r  )ró  rì   r   rE  )1r1  r2  r3  r4  r-  r¢  rk  rh  ri  rß  râ  rC  rÝ   r   r)   rá   r	  r5  rd  rn   r  r~  r   rÂ  rÎ  rÞ  r	  rù  r  r  rû  r1  rü  rI  rý  rþ  rj  r  rB  rF  rJ  ru  rv  rú  rM  r÷  rù  rD  r6  r7  s   @r6   r–  r–  §	  s¢  ø„ ÙCàÐØ€OØ€LØ€NØ€Oà€KØ€Iò€Nð
 €Fð ØØ"&ð #&àð ð !àð Ø !ØØØØàADØ37Ø%*Ø',ØàØ$&à$(ð 56à'*Ø&)ðWVCð  õ	VCõp=ô^ð ñ4ó ð4ô0Fò3ój4ñl Óð ØØØò%ó ð%óNð4 &*ði
àði
ð ði
ð ð	i
ð
 ði
ð ði
ð !ði
ð (ði
ð  .ði
ð #ói
ðV òó ðð
Øð
Ø*6ð
ØJPð
Øhló
ò
ò.9ð"7Øð7Ø4=ð7ØVkó7ð,($ð )ð($ð *3ð	($ð
 (ð($ð 0ð($ð $0ó($ðTR9àðR9ð ðR9ð )ð	R9ð
 '3ðR9ð $0ðR9ð  5ðR9ð (óR9ðv ðD,àðD,ð '3ðD,ð  .ð	D,ð
 -ðD,ð  (ðD,ð óD,ðL"$àð"$ð ð"$ð )ð	"$ð
 (ð"$ð 3ó"$ðH ð -1ð$Ø(ð$à&2ð$ð  5ð$ð 3ð	$ð
  *ò$ó ð$ðV !%ØðBà*ðBð !ðBð ð	Bð
 ðBð óBóHDð8C
àðC
ð "ðC
ð  ð	C
ð
  óC
ðJm/àðm/ð ðm/ð %:ð	m/ð
 $ðm/ð &ðm/ð  *ðm/ð !óm/ð^81Ø(1ð81Ø>Að81ØR^ó81ðt*$àð*$ð ð*$ð ð	*$ð
 $ð*$ð (ó*$óX0ò$" ðH.à ð.ð )ð.ð ",ð	.ð
 %:ð.ð $ó.ô`Wò3ð ñó ôr7   r–  )6r4  Ú
__future__r   Úcollectionsr   r   rþ  r   Útypingr   r˜   r  r?   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   Úsam3.geometry_encodersr   r   r9  r\  r  rL  r]  r‘  r–  rc   r7   r6   ú<module>r     sÌ   ðñõ #ç 0Ý Ý ã 
Û Û ß Ð å .Ý 6Ý .ß 6Ñ 6ß 7ß M÷
÷ 
õ 
õ +ô@
'�ô @
'ôFKC�Iô KCô\AG˜ô AGôH I
 mô I
ôX
R�Mô Rô0J ˜Mô J ôZ3/Ð+¨]ô 3/ôlJÐ!6õ Jr7   