
    /jh                      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          Z5dS ) a  
Generate predictions using the Segment Anything Model (SAM).

SAM is an advanced image segmentation model offering features like promptable segmentation and zero-shot performance.
This module contains the implementation of the prediction logic and auxiliary utilities required to perform segmentation
using SAM. It forms an integral part of the Ultralytics framework and is designed for high-performance, real-time image
segmentation tasks.
    )annotations)OrderedDictdefaultdict)deepcopy)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)
       N
_callbacksdict | Nonec                    |i }|                     t          ddd                     t                                          |||           d| j        _        d| _        d| _        i | _        d| _	        dS )ae  Initialize the Predictor with configuration, overrides, and callbacks.

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

        Args:
            cfg (dict): Configuration dictionary containing default settings.
            overrides (dict | None): Dictionary of values to override default configuration.
            _callbacks (dict | None): Dictionary of callback functions to customize behavior.
        Nsegmentpredictr   )taskmodebatchTF)
updatedictsuper__init__argsretina_masksimfeaturespromptssegment_allselfcfg	overridesr    	__class__s       c/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/models/sam/predict.pyr+   zPredictor.__init__W   s|     I99AFFFGGGi444!%	     c                   | j         | j         S t          |t          j                   }|rot	          j        |                     |                    }|ddddf                             d          }t	          j        |          }t          j	        |          }|
                    | j                  }|r|| j        z
  | j        z  }| j        j        r|                                n|                                }|S )av  Preprocess the input image for model inference.

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

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

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

        Examples:
            >>> predictor = Predictor()
            >>> image = torch.rand(1, 3, 640, 640)
            >>> preprocessed_image = predictor.preprocess(image)
        N.)r      r      )r.   
isinstancetorchTensornpstackpre_transform	transposeascontiguousarray
from_numpytodevicemeanstdmodelfp16halffloat)r3   r.   
not_tensors      r7   
preprocesszPredictor.preprocessm   s    & 77N#B555
 	&$,,R0011BC2I((66B%b))B!"%%BUU4; 	-ty.DH,B*/9RWWYYYrxxzz	r8   c                    t          |          dk    s
J d            t          | j        dd          fd|D             S )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centerc                (    g | ]} |           S )image .0x	letterboxs     r7   
<listcomp>z+Predictor.pre_transform.<locals>.<listcomp>   &    ///q		"""///r8   lenr   imgszr3   r.   r\   s     @r7   rB   zPredictor.pre_transform   sO    , 2ww!|||U|||djuUCCC	////B////r8   Fc                h   | j                             d|          }| j                             d|          }| j                             d|          }| j                             d|          }t          d |||fD                       r | j        |g|R i |S |                     ||||||          S )a=  Perform image segmentation inference based on the given input cues, using the currently loaded image.

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

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

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

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_model(model_path="sam_model.pt")
            >>> predictor.set_image("image.jpg")
            >>> results = predictor(bboxes=[[0, 0, 100, 100]])
        bboxespointsmaskslabelsc              3     K   | ]}|d u V  	d S NrX   rZ   is     r7   	<genexpr>z&Predictor.inference.<locals>.<genexpr>   s&      ::QqDy::::::r8   )r0   popallgenerateprompt_inference)	r3   r.   rd   re   rg   rf   multimask_outputr,   kwargss	            r7   	inferencezPredictor.inference   s    8 !!(F33!!(F33  %00!!(F33::665"9::::: 	6 4=5d555f555$$RHXYYYr8   c                    | j         |                     |          n| j         }|                     |j        dd         | j        d         d         j        dd         ||||          } | j        |g||R  S )a  Perform image segmentation inference based on input cues using SAM's specialized architecture.

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

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

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

        Examples:
            >>> predictor = Predictor()
            >>> im = torch.rand(1, 3, 1024, 1024)
            >>> bboxes = [[100, 100, 200, 200]]
            >>> masks, scores, logits = predictor.prompt_inference(im, bboxes=bboxes)
        Nr<   r   r   )r/   get_im_features_prepare_promptsshaper'   _inference_features)	r3   r.   rd   re   rg   rf   rq   r/   r0   s	            r7   rp   zPredictor.prompt_inference   s    4 04}/D4''+++$-''djmA6F6LRaR6PRXZ`bhjopp't'M7M<LMMMMr8   c                &   |||fnd}| j                             |||          \  }}| j                             || j         j                                        |||          \  }	}
|	                    dd          |
                    dd          fS )a  Perform inference on image features using the SAM model.

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

        Returns:
            pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
            pred_scores (torch.Tensor): Quality scores for each mask, with length C.
        Nre   boxesrf   )image_embeddingsimage_pesparse_prompt_embeddingsdense_prompt_embeddingsrq   r   r   )rJ   prompt_encodermask_decoderget_dense_peflatten)r3   r/   rd   re   rg   rf   rq   sparse_embeddingsdense_embeddings
pred_maskspred_scoress              r7   rx   zPredictor._inference_features   s    . &,%7&&!!T.2j.G.Gv]ckp.G.q.q++ #'*"9"9%Z.;;==%6$4- #: #
 #

K !!!Q'')<)<Q)B)BBBr8   c                   | j         rdn-t          |d         |d         z  |d         |d         z            }|t          j        || j        | j                  }|j        dk    r|d         n|}|!t          j        |j	        dd                   }t          j        |t          j
        | j                  }|j	        d         |j	        d         k    s'J d|j	        d          d	|j	        d          d
            ||z  }|j        dk    r|dddddf         |dddf         }}|;t          j        || j        | j                  }|j        dk    r|d         n|}||z  }|t          j        |t          j                  }|j        dk    r|d         n|}t          |dddt          j                  t          j        fd|D             d          }t          j        || j        | j                  }||||fS )a  Prepare and transform the input prompts for processing based on the destination shape.

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

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

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.
              ?r   r   NdtyperG   r:   Number of points  should match number of labels .r<   r   F)rS   rT   padding_valueinterpolationc                L    g | ] } |                                            !S rV   )squeezerY   s     r7   r]   z.Predictor._prepare_prompts.<locals>.<listcomp>E  s2    JJJqiia00088::JJJr8   axis)r1   minr>   	as_tensortorch_dtyperG   ndimr@   onesrw   int32asarrayuint8r   cv2INTER_NEARESTrA   tensor)	r3   	dst_shape	src_shaperd   re   rg   rf   rr\   s	           @r7   rv   zPredictor._prepare_prompts  s&   . #fCCYq\IaL-H)TU,YbcdYeJe)f)f_V43CDKXXXF%+[A%5%5VD\\6F~crc!233_V5;t{SSSF<#v|B'7777hFL$4hhU[UabdUehhh 877 aKF{a!'4
!3VAAAtG__V43CDKXXXF%+[A%5%5VD\\6FaKFJuBH555E#(:??E$KKE!)%UVfifwxxxIHJJJJEJJJQRSSSELd.>t{SSSEvvu,,r8   r   g?r       @   )\(?ffffff?ffffff?c           
        ddl }d| _        |j        dd         \  }}t          ||f||          \  }}|t	          |||          }g g g g f\  }}}}t          ||          D ]\  }}|\  }}}}||z
  ||z
  }}t          j        ||z  |j                  }t          j
        ||gg          }t          j        |d||||f         ||fdd	          }||         |z  } g g g }#}"}!t          ||           D ]?\  }$|                     ||$d
          \  }%}&t          j        |%d         ||fdd	          d         }%|&|k    }'|%|'         |&|'         }&}%t          |%| j        j        |
          }(|(|	k    }'|%|'         |&|'         }&}%|%| j        j        k    }%t%          |%                                          })t)          |)|dd||g           }*t          j        |*          s|)|*         |%|*         |&|*         }&}%})|!                    |%           |#                    |)           |"                    |&           At          j        |!          }!t          j        |#          }#t          j        |"          }"|j                            |#|"| j        j                  }+t9          |#|+         |          }#t;          |!|+         |||          }!|"|+         }"|                    |!           |                    |#           |                    |"           |                    |                    |!j        d                              t          j        |          }t          j        |          }t          j        |          }t          j        |          }t?          |          dk    r9d|z  },|j                            ||,|          }+||+         ||+         ||+         }}}|||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<   rG   .bilinearF)r&   align_corners)re   rq   r   ) torchvisionr1   rw   r   r   zipr>   r   rG   r@   arrayFinterpolater   rp   r   rJ   mask_thresholdr   rM   r   rn   appendcatr   nmsr,   iour   r   expandr`   )-r3   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_bboxesre   	pred_mask
pred_scoreidxstability_score	pred_bbox	keep_maskkeepscoress-                                                r7   ro   zPredictor.generateI  s)   T 	!""B#6BxPb#c#c j5m]TijjK=?R^:
Kl&),
&C&C .	B .	B"K(NBB7BGqA<Abi888D8aVH--LmBsBrE2b5'8$9B8*dijjjG*95D35r2[J+,=?OPP / /	(,(=(=gfgk(=(l(l%	:M)D/Aq6
bghhhijk	 :-(1#
3:	";tz8:P# # &(>>(1#
3:	%
(AA	/	::@@BB	29kAqRTVX>ZZZ	y++ y7@7KYW`Macmnwcx*yI!!),,,""9---"":.... :..J)K00K)K00K?&&{KOOD+K,={KKK%j&6RLLJ%d+Kj))){+++{+++J,<Q,? @ @AAAAYz**
i,,i,,y.. |q  %F?&&{FOLLD3=d3C[QUEVXcdhXi[J;33r8   Tc                   t          | j        j        |          }||                                 }|                    |          }| j        j        r|                                n|                                }|                                 || _        || _        t          j
        g d                              ddd                              |          | _        t          j
        g d                              ddd                              |          | _        d| j        _        d| j        _        | j        j        | j        _        d	| _        | j        j        rt          j        nt          j        | _        dS )
a\  Initialize the Segment Anything Model (SAM) for inference.

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

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

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_model(model=sam_model, verbose=True)
        )verboseN)g33333^@gR]@gRY@r:   r   )g(\2M@g(\L@g     L@samr   T)r   r,   rG   	get_modelrF   rL   rM   evalrJ   r>   r   viewrH   rI   formatstriderK   done_warmupfloat16float32r   )r3   rJ   r   rG   s       r7   setup_modelzPredictor.setup_model  s7    ty/AAA=NN$$E   $	A

EKKMM


L!:!:!:;;@@QJJMMfUU	< 7 7 788==b!QGGJJ6RR "

).
,0JON5==r8   c                8    ddl m}  || j        j                  S )zPRetrieve or build the Segment Anything Model (SAM) for image segmentation tasks.r   	build_sambuildr   r,   rJ   r3   r   s     r7   r   zPredictor.get_model  (    $$$$$$y)))r8   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 ]z\  }	}
}|	j        d         dk    rdt          j        d|j                  }}	nt          j        |	d                                         |
j        dd         d	
          d         }	|	| j        j        k    }	|=t          j        |j        dd         |                                |
j        d	
          }nt'          |	          }t          j        |j        d         t          j        |j                  }|| j        j        k    }t          j        ||dddf         |dddf         gd          |         }|	|         }	|                    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  4   K   | ]}t          |          V  d S ri   strrj   s     r7   rl   z(Predictor.postprocess.<locals>.<genexpr>  s(      JJ!s1vvJJJJJJr8   r   .r:   r      r   Fpaddingr   dimpathnamesrf   r{   )r1   r)   	enumeraterangerw   r=   listr   convert_torch2numpy_batchr   r'   r>   zerosrG   scale_masksrM   rJ   r   scale_boxesr   aranger   r,   confr   r   r
   )r3   predsimg	orig_imgsr   r   r   r   resultsrf   orig_imgimg_pathclsr   s                 r7   postprocesszPredictor.postprocess  s1   0 #()
K"&"2<eAhhYJJuZ5Ea5H/I/IJJJJJKK)T** 	L5i@@dddKI),j\9djQRm)T)T 	j 	j%E8X{1~""%)5;vjFW+X+X+X{d(9(9(;(;X^BQB=OY^___`ab
 99*"%/#)ABB-ARARATATV^Vdns"t"t"tKK"5e"<"<Kl:#3A#6ekR\Rcddd!DIN2#ik!!!T'6JCPQPQPQSWPWL(Y_abbbcfgc
NN78(%u\ghhhiiii r8   c                ,   | j         |                                  |                     |           t          | j                  dk    s
J d            | j        D ]9}|                     |d                   }|                     |          | _         dS dS )a  Preprocess and set a single image for inference.

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

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

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

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

        Notes:
            - This method should be called before performing inference on a new image.
            - The extracted features are stored in the `self.features` attribute for later use.
        Nr   z,`set_image` only supports setting one image!)rJ   r   setup_sourcer`   datasetrO   ru   r/   )r3   rW   r'   r.   s       r7   	set_imagezPredictor.set_image  s    . :%   4<  A%%%'U%%%\ 	 	Eq**B 0044DMEE	 	r8   c                <   |dS t                                          || j                   t          | j        t
          t          f          r| j        d         | j        d         k    sJ d| j         d            | j                            | j                   dS )z)Set up the data source for SAM inference.Nr   r   z3SAM models only support square image size, but got r   )	r*   r  r   r=   ra   tupler  rJ   	set_imgszr3   sourcer6   s     r7   r  zPredictor.setup_source3  s    >FVT[111$*udm44 	
A$*UV-9W9W9WO$*OOO :X9WW 	
TZ(((((r8   c                6    | j                             |          S )zZExtract image features using the SAM model's image encoder for subsequent mask prediction.)rJ   image_encoderr3   r.   s     r7   ru   zPredictor.get_im_features=  s    z''+++r8   c                    || _         dS )z0Set prompts for subsequent inference operations.N)r0   )r3   r0   s     r7   set_promptszPredictor.set_promptsA  s    r8   c                "    d| _         d| _        dS )zQReset the current image and its features, clearing them for subsequent inference.N)r.   r/   r3   s    r7   reset_imagezPredictor.reset_imageE  s    r8   c                    ddl }| j        d         dk    r| S g }g }| D ]}|                                                                                    t
          j                  }t          ||d          \  }}| }t          ||d          \  }}|o| }|                    t          j
        |                              d                     |                    t          |                     t          j        |d          }t          |          }	|j                            |	                                t          j
        |          |          }
||
                             | j        | j                  |
fS )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   rG   r   )r   rw   cpunumpyastyper@   r   r   r   r>   r   	unsqueezerM   r   r   r   r   rF   rG   r   )rf   min_area
nms_threshr   	new_masksr   maskchanged	unchangedr{   r   s              r7   r   zPredictor.remove_small_regionsJ  sj   2 	;q>QL 	 		, 		,D88::##%%,,RX66D0xgNNNMD'#I0xiPPPMD'!1'kIU_T22<<Q??@@@MM%	**++++ IiQ///	#I..""5;;==%/&2I2I:VV!!U[!II4OOr8   c	                Z   |p| j         j        | j         j        f}|                     ||||||          }	 | j        |g|	|R  \  }
}|
j        d         dk    rdt          j        d|
j                  }}
nt          j	        |
d         
                                |d          d         }
|
| j        j        k    }
t          |
          }t          j        |
j        d         t
          j        |
j                  }t          j        ||dddf         |dddf         gd	          }|
|fS )
a  Perform prompts preprocessing and inference on provided image features using the SAM model.

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

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

        Notes:
            - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2.
        r   Nr   r   Fr   r   r:   r   )r,   ra   rv   rx   rw   r>   r  rG   r   r  rM   rJ   r   r   r  r   r   )r3   r/   r   r   rd   re   rg   rf   rq   r0   r   r   r   r  s                 r7   inference_featureszPredictor.inference_features}  s<   D C$)/49?!C	''	9fffV[\\":$":8"`g"`O_"`"`"`
KA!##&*EKzGX,Y,Y,YJJD)9)?)?)A)A9V[\\\]^_J#dj&??J-j99K,z/2%+jN_```C)[+aaag2FAAAtG$U[]^^^K;&&r8   r    r!   )NNNNFNNNN)
r   r   r   Nr   r   r   r   r   r   NT)r   r   NNNNNF)__name__
__module____qualname____doc__r   r   r+   rO   rB   rs   rp   rx   rv   ro   r   r   r  r  r  ru   r  r"  staticmethodr   r   r3  __classcell__r6   s   @r7   r   r   +   s       ' 'R F&$RV ! ! ! ! ! ! !,     D0 0 04$Z $Z $Z $ZLN N N ND &C &C &C &CP1- 1- 1- 1-l %##m4 m4 m4 m4^O O O OB* * *2 2 2h  @) ) ) ) ), , ,    
 0P 0P 0P \0Pd 
 -' -' -' -' -' -' -' -'r8   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}")
    ))   rA  )   rB  )r   r   r   c                8    ddl m}  || j        j                  S )zYRetrieve and initialize the Segment Anything Model 2 (SAM2) for image segmentation tasks.r   r   r   r   s     r7   r   zSAM2Predictor.get_model  r   r8   Nc                   t                                          ||||||          \  }}}}||                    ddd          }t          j        ddggt          j        |j                                      |j        d         d          }|1t          j	        ||gd          }t          j	        ||gd          }n||}}|||fS )	ai  Prepare and transform the input prompts for processing based on the destination shape.

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

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

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.
        Nr:   r<   r;   r   r   r   r   )
r*   rv   r   r>   r   r   rG   r   rw   r   )	r3   r   r   rd   re   rg   rf   bbox_labelsr6   s	           r7   rv   zSAM2Predictor._prepare_prompts  s    * ).(@(@IW]_egmot(u(u%[[Q**F,Axu{6=YYY``agamnoaprtuuK !FF#3;;;K#8a@@@!'vu$$r8   c                r     t                                          |            fddD              _        dS )z9Set up the data source and image size for SAM2 inference.c                :    g | ]fd j         D             S )c                D    g | ]}t          |j        z  z            S rX   intr   rZ   r[   rk   r3   s     r7   r]   z9SAM2Predictor.setup_source.<locals>.<listcomp>.<listcomp>  s,    OOOqAq$9 : :OOOr8   ra   rZ   rk   r3   s    @r7   r]   z.SAM2Predictor.setup_source.<locals>.<listcomp>  s5    kkkTUOOOOODJOOOkkkr8   g      ?      ?r   N)r*   r  _bb_feat_sizesr  s   ` r7   r  zSAM2Predictor.setup_source  s?    V$$$kkkkYjkkkr8   c                    | j                             |          }| j                             |          \  }}}}| j         j        r|d         | j         j        z   |d<   d t          || j                  D             }|d         |dd         dS )zLExtract image features from the SAM image encoder for subsequent processing.r:   c                \    g | ])\  }} |                     d dd          j        d dg|R  *S )r   r<   r   r:   )permuter   rZ   feat	feat_sizes      r7   r]   z1SAM2Predictor.get_im_features.<locals>.<listcomp>  sQ     
 
 
>MdI&DLLAq!!&q"9y999
 
 
r8   N)image_embedhigh_res_feats)rJ   forward_image_prepare_backbone_featuresdirectly_add_no_mem_embedno_mem_embedr   rP  )r3   r.   backbone_out_vision_featsfeatss         r7   ru   zSAM2Predictor.get_im_features  s    z//33 $
 E El S S<A:/ 	J+B/$*2IIL
 
QTUacgcvQwQw
 
 
  %RyE#2#JGGGr8   Fr:   c           	        |||fnd}| j                             |d|          \  }}|duo|d         j        d         dk    }	d}
t          |t                    r#fd|d         D             }
|d         g         }| j                             || j         j                                        ||||	|
          \  }}}}|                    dd          |                    dd          fS )	av  Perform inference on image features using the SAM2 model.

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

        Returns:
            pred_masks (torch.Tensor): Output masks with shape (C, H, W), where C is the number of generated masks.
            pred_scores (torch.Tensor): Quality scores for each mask, with length C.
        Nrz   r   r   c                F    g | ]}|                              d           S )r   )r+  )rZ   
feat_levelimg_idxs     r7   r]   z5SAM2Predictor._inference_features.<locals>.<listcomp>,  s,     o o ojG!4!>!>q!A!A o o or8   rX  rW  )r|   r}   r~   r   rq   repeat_imagehigh_res_features)rJ   sam_prompt_encoderrw   r=   r)   sam_mask_decoderr   r   )r3   r/   re   rg   rf   rq   rd  r   r   batched_moderf  r   r   r^  s         `       r7   rx   z!SAM2Predictor._inference_features	  s*   2 &,%7&&!!T.2j.K.K /L /
 /
++ T)DfQioa.@1.D h%% 	: o o o oT\]mTn o o o.y9H(,
(C(C%Z2??AA%6$4-%/ )D )
 )
%
KA !!!Q'')<)<Q)B)BBBr8   r5  )NNNFr:   )r8  r9  r:  r;  rP  r   r   rv   r  ru   rx   r=  r>  s   @r7   r@  r@    s         6  N
 F* * * %  %  %  %  %  %Dl l l l l
	H 	H 	H 0C 0C 0C 0C 0C 0C 0C 0Cr8   r@  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.
    Nr    r!   c                    t                                          |||           i | _        d| _        d| _        d| _        | j        d                             | j                   d| _	        dS )aK  Initialize the predictor with configuration and optional overrides.

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

        Args:
            cfg (dict): Configuration dictionary containing default settings.
            overrides (dict | None): Dictionary of values to override default configuration.
            _callbacks (dict | None): Dictionary of callback functions to customize behavior.
        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_memr2   s       r7   r+   zSAM2VideoPredictor.__init__`  sm     	i444!!%/4,05-)*11$/BBB"&r8   c                r    t                                                      }|                    d           |S )zRetrieve 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)r3   rJ   r6   s     r7   r   zSAM2VideoPredictor.get_models  s3     !!##4   r8   c           
        | j                             d|          }| j                             d|          }| j                             d|          }| j        j        }|| j        d<   | j        d         }t          |d                   dk    r|                     |j        dd	         | j        d
         d         j        d	d         ||||          \  }}}|Gt          t          |                    D ])}| 
                    |||g         ||g         |           *n@|>t          t          |                    D ]!}| 
                    |||g         |           "|                                  | j        d         }	t          | j        d                   }
t          |d                   dk    rt          d          ||	d         v r:d}||         |         }| j        r"| j        s|
d
k    r|                     |           nZ||	d         v rd}||         |         }n?d}|                     |||
dd	d	dd          }|||         |<   |                     |           |                     |||           | j        d                             |           |d                             dd
          }||| j        j        k                        d          dk             }|t1          j        |j        d         |j        |j                  fS )ab  Perform image segmentation inference based on the given input cues, using the currently loaded image. This
        method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
        encoder, and mask decoder for real-time and promptable segmentation tasks.

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

        Returns:
            pred_masks (torch.Tensor): The output masks in shape CxHxW, where C is the number of generated masks.
            pred_scores (torch.Tensor): An array of length C containing predicted quality scores for each mask.
        rd   re   rf   r.   output_dictcond_frame_outputsr   r<   Nr   )obj_idre   rg   	frame_idx)rz  rf   r{  consolidated_frame_indsobj_idx_to_id/No points are provided; please add points firstnon_cond_frame_outputsFT)rx  r{  
batch_sizeis_init_cond_framepoint_inputsmask_inputsreverserun_mem_encoderframes_already_trackedr   r   r<   r   )r0   rm   r  framern  r`   rv   rw   r'   r  add_new_promptspropagate_in_video_preflightRuntimeErrorrp  rq   _clear_non_cond_mem_around_input_run_single_frame_inference_prune_non_cond_memory_add_output_per_objectr   r   rJ   r   sumr>   r   r   rG   )r3   r.   rd   re   rg   rf   r  rx  rk   r|  r  storage_keycurrent_outr   s                 r7   rs   zSAM2VideoPredictor.inference}  sX   " !!(F33!!(F33  %00"%'T"*=9{/011Q66$($9$9djmA.4RaR8&&&RW% %!FFE !s6{{++ l lA((&!+fVWUXkej(kkkkl"s5zz** V VA((su(UUUU))+++"&"67P"Q-o>??
{/011Q66PQQQ+,@AAA.K%k259K3 =9^ =blpqbqbq55e<<<-.FGGG2K%k259KK2K::'%#(!  $ ; 	 	K /:K$U+''... 	##E;DDD56==eDDD .66q!<<
dj.G!G L LV T TWX XY
5:j&6q&9AQZdZklllllr8   c                4   t                                          |||          }| j        rl|D ]i}|j        t	          |j                  dk    r"| j                            |j        j                            d                    d         |j        _        j|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.
        Nr   )	r*   r  ro  rf   r`   rJ   "_apply_non_overlapping_constraintsdatar+  )r3   r
  r  r  r  resultr6   s         r7   r  zSAM2VideoPredictor.postprocess  s    $ ''%%eS)<<! 	u! u u<'3v|+<+<+A+A$(J$Q$QRXR^RcRmRmnoRpRp$q$qrs$t!!r8   r   rn  dict[str, Any] | Nonec                   |p| j         }|du |du z  s
J d            |                     ||          }d}d}	|||d}||d         |         |<   d}	||d         |         |<   ||	         |                             |d           ||d         v}
|d         |         }|d         |         }|
p| j        j        }|rd	nd
}d}|||                             |          p5|d	                             |          p|d
                             |          }|[|                    d          F|d                             | j        | j        j        dk              }|	                    dd           | 
                    ||d|
||dd||
  
        }|||         |<   |                     ||d|          }|d                             dd          }|                    dd          t          j        d|j        |j                  fS )av  Add new points or masks to a specific frame for a given object ID.

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

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

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

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

        Notes:
            - Only one type of prompt (either points or masks) can be added per call.
            - If the frame is being tracked for the first time, it is treated as an initial conditioning frame.
            - The method handles the consolidation of outputs and resizing of masks to the original video resolution.
        Nz@'masks' and 'points' prompts are not compatible with each other.point_inputs_per_objpoint_coordspoint_labelsmask_inputs_per_objr  output_dict_per_objtemp_output_dict_per_objry  r  r   cuda)rG   non_blockingg      @g      @@r   F)
rx  r{  r  r  r  r  r  r  prev_sam_mask_logitsrn  is_condr  rn  r   r   )rn  _obj_id_to_idxrm   rJ   !add_all_frames_to_correct_as_condgetrF   rG   typeclamp_r  #_consolidate_temp_output_across_objr   r>   r   r   )r3   rz  re   rg   rf   r{  rn  obj_idxr  pop_keyr  obj_output_dictobj_temp_output_dictr  r  r  prev_outr  consolidated_outr   s                       r7   r  z"SAM2VideoPredictor.add_new_prompts  s   L *AT-A&D.1uu3uuu1%%fo>>(,2FKKLJVO23G<YG+GEJ-.w7	B )--i>>>
 'o>V.WW)*?@I./IJ7S %T
(T.5S**;S  $ #$[155i@@ L"#78<<YGGL"#;<@@KK  #\(B(B(N'/'='@'@;T[5E5O (A ( ($ %++E488866'1%
 "!5+ 7 
 
" 8C[))4  CC!+	 D 
 
 &l3;;AqAA
!!!Q''AZ=MV`Vg)h)h)hhhr8   c                @   |p| j         }d|d<   t          |d                   }|d         }|d         }|d         }dD ]}|rdnd	}t                      }|                                D ]/}	|                    |	|                                                    0||                             |           |D ]h}
|                     |
|d|
          }|||         |
<   |                     |
|||           | j        r"| j	        s|dk    r| 
                    |
           i|                                D ]}	|	|                                          |d         D ]}
|d	                             |
d           |d                                         D ])}|d         D ]}
|d	                             |
d           *|d         D ])}
|
|d         v sJ |d	                             |
           *|d         |d	         z  }t                      }|d                                         D ])}|                    |                                           *|d                                         D ])}|                    |                                           *||k    sJ dS )ap  Prepare inference_state and consolidate temporary outputs before tracking.

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

        Args:
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.
        Ttracking_has_startedr}  r  rx  r|  >   FTry  r  r  rn  r   Nr  r  r  )rn  r`   setvaluesr(   keysr  r  rp  rq  r  clearrm   discard)r3   rn  r  r  rx  r|  r  r  temp_frame_indsr  r{  r  r  all_consolidated_frame_indsinput_frames_indspoint_inputs_per_framemask_inputs_per_frames                    r7   r  z/SAM2VideoPredictor.propagate_in_video_preflightM  so    *AT-A26./9::
 $33M#N %m4 #22K"L$ 	: 	:G29W..?WK "eeO(@(G(G(I(I Q Q$&&';K'H'M'M'O'OPPPP#K077HHH, 	E 	E	#'#K#KwVe $L $ $  7GK(3++I7Gfu+vvv7 ET=b Efptufufu99)DDD )A(G(G(I(I : :$$[1779999:
 %%9: 	G 	GI0155iFFFF./DELLNN 	O 	OO,-AB O O	 89==iNNNNO01EF 	Q 	QI,@ AAAAA#$<=EEiPPPP
 $$89<STl<mm 	$  EE&56L&M&T&T&V&V 	D 	D"$$%;%@%@%B%BCCCC%45J%K%R%R%T%T 	C 	C!$$%:%?%?%A%ABBBB*.???????r8   c                    t          | j                  dk    rdS | j        J | j        j        dk    sJ |                     | j        j                  | _        dS )a  Initialize an inference state for the predictor.

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

        Args:
            predictor (SAM2VideoPredictor): The predictor object for which to initialize the state.
        r   Nvideo)r`   rn  r  r&   _init_stateframes)	predictors    r7   rs  zSAM2VideoPredictor.init_state  sg     y())A--F ,,, %0000$-$9$9):K:R$S$S	!!!r8   c                    | i i i t                      t                      g i i di i t                      t                      ddg d}|S )a  Initialize an inference state.

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

        Args:
            num_frames (int): The number of frames in the video.
        ry  r  F)
num_framesr  r  	constantsobj_id_to_idxr}  obj_idsrx  r  r  r|  r  r  )r   r  )r  rn  s     r7   r  zSAM2VideoPredictor._init_state  ss     %$&#%(]](]] ')*, 
 $& )+ '*ee*-%%( (
 %*&(7
 
: r8   r   c                    t          | dd          }|| j                            |          }| j                            ||          \  }}}}|||fS )a  Extract and process image features using SAM2's image encoder for subsequent segmentation tasks.

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

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

        Notes:
            - If `batch` is greater than 1, the features are expanded to fit the batch size.
            - The method leverages the model's `_prepare_backbone_features` method to prepare the backbone features.
        r]  Nr'   )getattrrJ   rY  rZ  )r3   r.   r'   r]  r^  	vis_featsvis_pos_embed
feat_sizess           r7   ru   z"SAM2VideoPredictor.get_im_features  sb    " t^T:::33B77L26*2W2WXdlq2W2r2r/9mZ-33r8   c                   |p| j         }|d                             |d          }||S |d          }|rwt          |d                   }||d         |<   ||d         |<   t          |d                   |d<   i |d         |<   i |d         |<   i i d|d	         |<   i i d|d
         |<   |S t	          d| d|d          d          )a  Map client-side object id to model-side object index.

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

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

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

        Notes:
            - The method updates or retrieves mappings between object IDs and indices stored in
              `inference_state`.
            - It ensures that new objects can only be added before tracking commences.
            - It maintains two-way mappings between IDs and indices (`obj_id_to_idx` and `obj_idx_to_id`).
            - Additional data structures are initialized for the new object to store inputs and outputs.
        r  Nr  r}  r  r  r  r  r  r  zCannot add new object id z1 after tracking starts. All existing object ids: z4. Please call 'reset_state' to restart from scratch.)rn  r  r`   r  r  )r3   rz  rn  r  allow_new_objects        r7   r  z!SAM2VideoPredictor._obj_id_to_idx  s;   * *AT-A!/266vtDDN  //EFF 	//:;;G7>OO,V48>OO,W5)-oo.N)O)OOI&?AO23G<>@O127;&(*,? ?O127;
 ')*,D DO67@ NFF F F,;I,FF F F  r8   c                ~   |
p| j         }
|                     |
d         |          \  }}}||J | j                            |||||||||
d         |||	          }|d         }|8|                    t
          j        | j        | j        j        dk              |d<   | 	                    |d         |
          |d<   |S )	a  Run tracking on a single frame based on current inputs and previous memory.

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

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

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

        Notes:
            - The method assumes that `point_inputs` and `mask_inputs` are mutually exclusive.
            - The method retrieves image features using the `get_im_features` method.
            - The `maskmem_pos_enc` is assumed to be constant across frames, hence only one copy is stored.
            - The `fill_holes_in_mask_scores` function is commented out and currently unsupported due to CUDA extension requirements.
        r.   Nr  r{  r  current_vision_featscurrent_vision_pos_embedsr  r  r  rx  r  track_in_reverser  r  maskmem_featuresr  r   rG   r  maskmem_pos_enc)
rn  ru   rJ   
track_steprF   r>   r   rG   r  _get_maskmem_pos_enc)r3   rx  r{  r  r  r  r  r  r  r  rn  r  r  r  r  r  s                   r7   r  z.SAM2VideoPredictor._run_single_frame_inference   s	   P *AT-AFJFZFZD!:G
 G
C7
 #{':'::j++1!5&?!%##&|4$+!5 , 
 
 ''9:'.>.A.AmDKdkFVZ`F` /B / /K*+ *.)B)B;O`Cacr)s)s%&r8   c                    |p| j         }|d         }|\d|vr)t          |t                    sJ d |D             }||d<   n|d         }|d         j        d         dk    rfd|D             }|S )a  Cache and manage the positional encoding for mask memory across frames and objects.

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

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

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

        Notes:
            - The method assumes that `out_maskmem_pos_enc` is a list of tensors or None.
            - Only a single object's slice is cached since the encoding is the same across objects.
            - The method checks if the positional encoding has already been cached in the session's constants.
            - If the batch size is greater than one, the cached encoding is expanded to fit the batch size.
        r  Nr  c                F    g | ]}|d d                                          S )Nr   )clone)rZ   r[   s     r7   r]   z;SAM2VideoPredictor._get_maskmem_pos_enc.<locals>.<listcomp>  s(    "N"N"NQ1RaR5;;=="N"N"Nr8   r   r   c                @    g | ]}|                     d d d           S )r:   )r   )rZ   r[   r  s     r7   r]   z;SAM2VideoPredictor._get_maskmem_pos_enc.<locals>.<listcomp>  s+    &a&a&aAqxx
BB'G'G&a&a&ar8   )rn  r=   r  rw   )r3   out_maskmem_pos_encrn  model_constantsr  r  s        @r7   r  z'SAM2VideoPredictor._get_maskmem_pos_encn  s    0 *AT-A)+6* 77!"5t<<<<<"N"N:M"N"N"N5D 122"12C"D,Q/5a8JA~~&a&a&a&aQ`&a&a&a#""r8   Fc           
        |p| j         }t          |d                   }|rdnd}ddt          j        |dg| j        d         R d| j        | j                  t          j        || j        j        fd| j        | j                  t          j        |dfd	| j        | j                  d
}t          |          D ]}|d         |         }	|d         |         }
|	|         
                    |          p5|
d         
                    |          p|
d         
                    |          }|&|r#|                     |          |d         ||dz   <   |d         |d         ||dz   <   |d         |d         ||dz   <   |rrt          j        |d         | j        dd          }| j        j        r| j                            |          }|                     ||d|d         |          \  |d<   |d<   |S )a  Consolidate per-object temporary outputs into a single output for all objects.

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

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

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

        Notes:
            - The method initializes the consolidated output with placeholder values for missing objects.
            - It searches for outputs in both the temporary and main output dictionaries.
            - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
            - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
        r}  ry  r  Nr   r         size
fill_valuer   rG         $@r  r  r   obj_ptrobject_score_logitsr  r  r  r   r   Fr  r&   r   Tr  )r  high_res_masksis_mask_from_ptsr  rn  r  r  )rn  r`   r>   fullrP  r   rG   rJ   
hidden_dimr  r  _get_empty_mask_ptrr   r   ra   non_overlap_masks_for_mem_encr  _run_memory_encoder)r3   r{  r  r  rn  r  r  r  r  r  r  outr  s                r7   r  z6SAM2VideoPredictor._consolidate_temp_output_across_obj  s   > *AT-A9::
.5S**;S !%#* !=d&9!&<=="&{   z $*"78"&{	   $): !_  &{$ $ $!
 
2 Z(( 	P 	PG#23M#Nw#W -.CDWMO$[155i@@ L
 ##78<<YGGL ##;<@@KK  { # mIMIaIabkIlIl$Y/'A+0EFDGDU\*7Wq[+@AADYY''A+(=>>  	] .Z#	  N z7 _!%!N!N~!^!^X\XpXp%-!%$45J$K / Yq Y YU/02BCT2U  r8   c                   |p| j         }|                     |d                   \  }}}| j                            |d|||dt	          j        ddg| j        R | j        | j                  i |d         ddd          }|d	         S )
a  Get a dummy object pointer based on an empty mask on the current frame.

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

        Returns:
            (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
        r.   TNr   r   r  Fr  r  )	rn  ru   rJ   r  r>   r  ra   r   rG   )r3   r{  rn  r  r  r  r  s          r7   r  z&SAM2VideoPredictor._get_empty_mask_ptr  s     *AT-AFJFZFZ[jko[pFqFqC7 j++#!5&?!Q$7DJ$7$7t?OX\Xcddd&|4"!!% , 
 
 9%%r8   c                2   |p| j         }|                     |d         |          \  }}}| j                            |||||          \  }	}
|                     |
|          }
|	                    t          j        | j        | j        j	        dk              |
fS )a  Run the memory encoder on masks.

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

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

        Returns:
            maskmem_features (torch.Tensor): The encoded mask features.
            maskmem_pos_enc (torch.Tensor): The positional encoding.
        r.   )r  r  pred_masks_high_resr  r  r  r  )
rn  ru   rJ   _encode_new_memoryr  rF   r>   r   rG   r  )r3   r  r  r  r  rn  r  r^  r  r  r  s              r7   r  z&SAM2VideoPredictor._run_memory_encoder'  s    2 *AT-A.2.B.B?SWCXZd.e.e+a,0J,I,I!5! .- 3 -J -
 -
)/ 33O_UU""-$+BRV\B\ # 
 
 	r8   c                  
 |p| j         }|d         }|t          |t          j                  sJ |d         }|t          |t                    sJ |d                                         D ]b\  }}t          ||dz             
dd|d         
         |d         
         d}	||
         |	d<   |
fd	|D             |	d<   |	||         |<   cdS )
aI  Split a multi-object output into per-object output slices and add them into Output_Dict_Per_Obj.

        The resulting slices share the same tensor storage.

        Args:
            frame_idx (int): The index of the current frame.
            current_out (dict): The current output dictionary containing multi-object outputs.
            storage_key (str): The key used to store the output in the per-object output dictionary.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.
        r  Nr  r  r   r   r  )r  r  r   r  c                     g | ]
}|         S rX   rX   )rZ   r[   	obj_slices     r7   r]   z=SAM2VideoPredictor._add_output_per_object.<locals>.<listcomp>q  s    -T-T-Tqa	l-T-T-Tr8   )rn  r=   r>   r?   r  itemsslice)r3   r{  r  r  rn  r  r  r  r  obj_outr  s             @r7   r  z)SAM2VideoPredictor._add_output_per_objectQ  s     *AT-A&'9:':6F+U+U''U%&78&*_d*K*K&&K(78M(N(T(T(V(V 	> 	>$G_gw{33I$(#'),7	B&y1)<	 G  +.>y.I*+*-T-T-T-TO-T-T-T)*6=OK(33	> 	>r8   c                Z   |p| j         }| j        j        }||| j        j        z  z
  }||| j        j        z  z   }t	          ||dz             D ]]}|d         d                             |d           |d                                         D ]}|d                             |d           ^dS )a  Remove the non-conditioning memory around the input frame.

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

        Args:
            frame_idx (int): The index of the current frame where user interaction occurred.
            inference_state (dict[str, Any], optional): The current inference state. If None, uses the instance's
                inference state.
        r   rx  r  Nr  )rn  rJ   memory_temporal_stride_for_evalnum_maskmemr  rm   r  )r3   r{  rn  r   frame_idx_beginframe_idx_endtr  s           r7   r  z3SAM2VideoPredictor._clear_non_cond_mem_around_inputt  s     *AT-AJ6#a$**@&@@!A
(>$>>(9:: 	G 	GAM*+CDHHDQQQ#23H#I#P#P#R#R G G 89==aFFFFG	G 	Gr8   c                    d                              |d          }|&|sd         S t          d| dd          d          t          d                   dk    r                                d         S t	                      }|                    d         |                    |                    d	         |                    |D ]}                     ||           d         t          t          t                                        	                                
                    |           fd
D             }t          t          t          |                              }t          t          |                    t          t          ||                    d<   t          t          ||                    d<   |d<   fd}	 |	d                     |	d	                     |	d                     |	d                     fd}
 |
d         d            |
d         d           d         S )zRemove an object id from the tracking state. If strict is True, we check whether the object id actually
        exists and raise an error if it doesn't exist.
        r  Nr  zCannot remove object id z/ as it doesn't exist. All existing object ids: r   r   r  r  c                     g | ]
}|         S rX   rX   )rZ   old_idxold_obj_idss     r7   r]   z4SAM2VideoPredictor.remove_object.<locals>.<listcomp>  s    OOO{7+OOOr8   r}  c                    g }D ]8}|                      |          }|v r|                    |         |f           9|                     |           d S ri   )rm   r   r(   )	containernew_kvskvold_idx_to_new_idxold_obj_indss       r7   	_map_keysz3SAM2VideoPredictor.remove_object.<locals>._map_keys  sl    G! ? ?MM!$$***NN$6q$91#=>>>W%%%%%r8   r  r  c                n   | |                                          D ]\  }}|d                  |d<   fd|d         D             |d<                       |d                   |d<   |d                  |d<   |d                  |d<   |d                  |d<                       |||           d S )Nr  c                     g | ]
}|         S rX   rX   )rZ   r[   remain_old_obj_indss     r7   r]   zJSAM2VideoPredictor.remove_object.<locals>._slice_state.<locals>.<listcomp>  s    )a)a)aQ!,?*@)a)a)ar8   r  r   r  r  r  )r  r  r  )rx  r  r{  r  rn  r  r3   s       r7   _slice_statez6SAM2VideoPredictor.remove_object.<locals>._slice_state  s    "-k":"@"@"B"B 	j 	j	3*-.@*ABU*V&')a)a)a)a#N_J`)a)a)a%&)-)B)B3GXCY[j)k)k%&$'$56I$JL!!$Y0C!DI-01F-GH[-\)*++IsKYh+iiii	j 	jr8   rx  ry  r  )r  r  r`   clear_all_points_in_videor  r(   clear_all_points_in_framer  r  copyremover)   r   )r3   rn  rz  strictold_obj_idx_to_rmobj_input_frames_indsr{  new_obj_idsnew_obj_indsr  r  r  r  r  r  s   ``         @@@@r7   remove_objectz SAM2VideoPredictor.remove_object  s   
 ,O<@@NN$ 2&y11J6 J J,;I,FJ J J   /00A55**?;;;"9-- !$$$_5K%LM^%_```$$_5J%KL]%^___. 	O 	OI**?IvNNNN &i0E#k"2"23344*//11""#4555OOOO;NOOOE#k"2"23344!#&9<"H"HII+/K0N0N+O+O(+/L+0N0N+O+O(%0	"
	& 	& 	& 	& 	& 	& 		/"89:::	/"78999	/"78999	/"<=>>>
	j 
	j 
	j 
	j 
	j 
	j 
	j 	_]35IJJJ_]35MNNNy))r8   c                   |                      ||          }|d         |                             |d           |d         |                             |d           |d         }||         d                             |d           ||         d                             |d           t          |d                   }d}t          |          D ]*}||d         |         v rd	} n||d         |         v rd	} n+|s|d
         }	|d         }
|
d                             |           |
d                             |           |	d                             |d          }|'||	d         |<   |d                             |d           t          |          D ]9}|d         |         }|d                             |d          }|||d         |<   :t          |	d                   dk    r|                     |           dS dS dS )zGRemove all input points or mask in a specific frame for a given object.r  Nr  r  ry  r  r}  FTrx  r|  r  r  r   )r  rm   r`   r  r  _reset_tracking_results)r3   rn  r{  rz  r  r  r  frame_has_inputobj_idx2rx  r|  r  r  r  s                 r7   r  z,SAM2VideoPredictor.clear_all_points_in_frame  sh    %%fo>> 	./8<<YMMM-.w7;;ItLLL#23M#N  )*>?CCItTTT )*BCGG	SWXXX 9::
j)) 	 	HO,BCHMMM"&O,AB8LLL"& M  	>)-8K&56O&P##$89AA)LLL#$<=EEiPPP2377	4HHC DG45i@ 89==iNNN!*-- S S"12G"H"R)*>?CCItTT&KRO$<=iH ;3455::,,_=====+	> 	>( ;:r8   c                   |                      |           |d                                          |d                                          |d                                          |d                                          |d                                          |d                                          |d                                          dS )	zCRemove all input points or mask in all frames throughout the video.r  r}  r  r  r  r  r  N)r  r  )r3   rn  s     r7   r  z,SAM2VideoPredictor.clear_all_points_in_video
  s     	$$_555(..000(..000	"((***./55777-.44666-.446662399;;;;;r8   c                V   | d                                          D ]}|                                 | d                                          D ]}|                                 | d                                          D ]6}|d                                          |d                                          7| d                                          D ]6}|d                                          |d                                          7| d         d                                          | d         d                                          | d         d                                          | d         d                                          d	| d
<   | d                                          d| d<   dS )z8Reset all tracking inputs and results across the videos.r  r  r  ry  r  r  rx  r|  Fr  r  Nfirst_ann_frame_idx)r  r  )rn  r  s     r7   r  z*SAM2VideoPredictor._reset_tracking_results  s    !!78??AA 	 	AGGIIII !67>>@@ 	 	AGGIIII !67>>@@ 	0 	0A"#))+++&'--//// !;<CCEE 	0 	0A"#))+++&'--////&';<BBDDD&'?@FFHHH123GHNNPPP123KLRRTTT27./017799915-...r8   c                   | j         sdS |p| j        }|| j        j        | j        j        z  z
  |d         }fd|d         D             D ]}|d                             |d           |                    di                                           D ]5}fd|d         D             D ]}|d                             |d           6dS )z8Prune old non-conditioning frames to bound memory usage.Nrx  c                     g | ]
}|k     |S rX   rX   rZ   r
  	min_frames     r7   r]   z=SAM2VideoPredictor._prune_non_cond_memory.<locals>.<listcomp>7  s    TTTa)mm!mmmr8   r  r  c                     g | ]
}|k     |S rX   rX   r&  s     r7   r]   z=SAM2VideoPredictor._prune_non_cond_memory.<locals>.<listcomp><  s    \\\AaR[mmammmr8   )rt  rn  rJ   r  r  rm   r  r  )r3   r{  rn  rx  fr  r'  s         @r7   r  z)SAM2VideoPredictor._prune_non_cond_memory,  s   & 	F)AT-A 
 69c cc	%m4 UTTT[)ABTTT 	? 	?A0155a>>>>  /223H"MMTTVV 	G 	GO\\\\1I!J\\\ G G 89==aFFFFG	G 	Gr8   r4  r5  )NNNr   N)rn  r  ri   r   NN)FFNF)r8  r9  r:  r;  r   r+   r   rs   r  r   r  r  r<  rs  r  ru   r  r  r  r  r  r  r  r  r  r  r  r  r  r=  r>  s   @r7   rk  rk  <  s'        F '$RV ' ' ' ' ' ' '&    Gm Gm Gm GmR    4  15ji ji ji ji jiX H@ H@ H@ H@ H@T T T \T  ' ' \'R4 4 4 4.4 4 4 4 4@ "15L L L L L\'# '# '# '# '#X 15m  m  m  m  m ^& & & & &N 26( ( ( ( (V ]a!> !> !> !> !>FG G G G G, L* L* L* L*\ .> .> .>` 
< 
< 
< 6 6 \6(G G G G G G G Gr8   rk  c                       e Zd ZdZedddfd. fdZ e            	 	 	 	 	 	 d/d0d            Zd1dZ e            	 	 	 	 d2d3d!            Z	d4d%Z
d5d&Zd6d(Z	 	 	 	 d2d7d-Z xZS )8SAM2DynamicInteractivePredictora  SAM2DynamicInteractivePredictor extends SAM2Predictor to support dynamic interactions with video frames or a
    sequence of images.

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

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

    Examples:
            >>> predictor = SAM2DynamicInteractivePredictor(cfg=DEFAULT_CFG)
            >>> predictor(source=support_img1, bboxes=bboxes1, obj_ids=labels1, update_memory=True)
            >>> results1 = predictor(source=query_img1)
            >>> predictor(source=support_img2, bboxes=bboxes2, obj_ids=labels2, update_memory=True)
            >>> results2 = predictor(source=query_img2)
    Nr;   r4   r   r5   r  max_obj_numrJ  r    r!   returnNonec                   t                                          |||           d| _        g | _        t	                      | _        t          t          t          |                              x| _	        | _
        || _        dS )a  Initialize the predictor with configuration and optional overrides.

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

        Args:
            cfg (Any): Configuration dictionary containing default settings.
            overrides (dict[str, Any] | None): Dictionary of values to override default configuration.
            max_obj_num (int): Maximum number of objects to track. Default is 3. This is set to keep fixed feature size
                for the model.
            _callbacks (dict | None): Dictionary of callback functions to customize behavior.
        TN)r*   r+   ro  memory_bankr  obj_idx_setr   r  r  r  r}  _max_obj_num)r3   r4   r5   r/  r    r6   s        r7   r+   z(SAM2DynamicInteractivePredictor.__init__Z  sw    & 	i444!%  552=ikHZHZ>[>[2\2\\T/'r8   Fr.   torch.Tensor | np.ndarrayrd   list[list[float]] | Nonerf    torch.Tensor | np.ndarray | Nonere   rg   list[int] | Noner  update_memorybool!tuple[torch.Tensor, torch.Tensor]c                .   |                      |           |                     | j        | j        d         d         j        dd         ||||          \  }}}|rt          |t                    r|g}|
J d            ||
J d            |ft          j        t          |          ddf| j
        | j                  }t          j        t          |          dft          j        | j                  }|*t          |          t          |          k    s
J d	            t          |          t          |          k    s
J d
            |                     ||||           |                                 }|d         |d         }
}	t          | j                  dk    rt!          d          t#          | j                  }|	|         |
|         }
}	t          j        |
dz  d          }
|	                    dd          |
                    dd          fS )ao  Perform inference on a single image with optional bounding boxes, masks, points and object IDs. It has two
        modes: one is to run inference on a single image without updating the memory, and the other is to update
        the memory with the provided prompts and object IDs. When update_memory is True, it will update the
        memory with the provided prompts and obj_ids. When update_memory is False, it will only run inference on
        the provided image without updating the memory.

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

        Returns:
            res_masks (torch.Tensor): The output masks in shape (C, H, W)
            object_score_logits (torch.Tensor): Quality scores for each mask
        r   r   Nr<   )r   r   re   rd   rg   rf   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   )ru   rv   ra   r'   rw   r=   rJ  r>   r  r`   r   rG   r   r:  r  r4  r  r  r  r   )r3   r.   rd   rf   re   rg   r  r:  r  r   r   r   s               r7   rs   z)SAM2DynamicInteractivePredictor.inferencey  s,   < 	R    $ 5 5jjmA&,RaR0 !6 !
 !
  	?'3'' $")&&(]&&&$(:(:V );(:: ~c'llAq%9AQZ^Zefffc'llA%6ekRVR]^^^ 5zzS\\1113a111v;;#g,,...0_...w>>>oo''"-l";[I^=_K
t  A%%nooo4#$$",S/;s3CK
 l;#3;;;!!!Q'')<)<Q)B)BBBr8   r  c                    t                               | || j                  \  }}}d t          |dd         |dd                   D             | _        || _        || _        || _        dS )zInitialize the image state by processing the input image and extracting features.

        Args:
            img (torch.Tensor | np.ndarray): The input image tensor or numpy array.
        r  c                v    g | ]6\  }} |                     d dd          j        g |j        d d         |R  7S )r   r<   r   N)rS  r   rw   rT  s      r7   r]   zCSAM2DynamicInteractivePredictor.get_im_features.<locals>.<listcomp>  s^     "
 "
 "
i 'DLLAq!!&C
122CCCC"
 "
 "
r8   Nr:   )rk  ru   r5  r   rf  r_  vision_pos_embedsr  )r3   r  r  r  r  s        r7   ru   z/SAM2DynamicInteractivePredictor.get_im_features  s     0B/Q/QRVX[cgct/Q/u/u,	=*"
 "
#&y"~z#2##G#G"
 "
 "

 &!.$r8   torch.Tensor | Nonec           
        ddt          j        | j        d| j        d         dz  | j        d         dz  fd| j        | j                  t          j        | j        | j        j        fd| j        | j                  t          j        | j        dfd| j        | j                  d}t          |          D ]P\  }}|| j        k     sJ | 	                    t          |                    }| j                            |           ||g         ||g         }
}	|||g         d         nd}|	|
J d	            |                     ||	|
|          }||d
         }|j        dd         |d
         j        dd         k    s4J d|d
         j        dd          d|j        dd          d| d            ||d
         ||dz   <   |d         |d         ||dz   <   d|                                v r|d         |d         ||dz   <   Rt!          j        |d
                             | j        | j        j        dk              | j        dd          }| j        j        r| j                            |          }| j                            | j        | j        ||d         d          \  }}||d<   ||d<   | j                            |           dS )a  Append the imgState to the memory_bank and update the memory for the model.

        Args:
            obj_ids (list[int]): List of object IDs corresponding to the prompts.
            points (torch.Tensor | None): Tensor of shape (B, N, 2) representing the input points for N objects.
            labels (torch.Tensor | None): Tensor of shape (B, N) representing the labels for the input points.
            masks (torch.Tensor | None): Optional tensor of shape (N, H, W) representing the input masks for N objects.
        Nr   r      r  r  ir  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  r5  ra   r   rG   rJ   r  r  r  rJ  r4  addr  rw   r  r   r   rF   r  r  r  r  r_  r  r3  r   )r3   r  re   rg   rf   r  rk   rz  r  pointlabelr/  r  obj_maskr  r  r  s                    r7   r:  z-SAM2DynamicInteractivePredictor.update_memory  s   " !%#*'DJqMQ,>
1QR@RS"&{	   z')>?"&{	   $):'+ &{$ $ $
 
2 #7++ 	p 	pIAvD-----))#f++66G  )))!1#;s5E','85!:d##dD$(8(8:c(8(88//'5%>>C|,~bcc*.>|.L.RSUSVSV.WWWW K+;L+I+OPRPSPS+T  K  K_g_mnpnqnq_r  K  K  AH  K  K  K XWW IQ .w1/DEEH^ +Ggk,AB(CHHJJ66UXYnUo$%:;GgPQk<QR\*--dkHX\bHb-cc	
 
 
 :3 	[!ZJJ>ZZN,0J,I,I!%!2 . 01F G! -J -
 -
)/ 0@+,.=*+ 011111r8   r  
int | Nonetorch.Tensorc                   t          | j                  dk    st          |t                    r| j        d         | j        j        z   }nP|                                 \  }}| j                            | j        dd         | j	        dd         ||d          } |
                    ddd          j        | j        | j        j        j        g| j        d         R  S )a  Prepare memory-conditioned features for the current image state.

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

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

        Returns:
            pix_feat_with_mem (torch.Tensor): The memory-conditioned pixel features.
        r   r:   N)currcurr_posmemory
memory_posnum_obj_ptr_tokensr   r<   )r`   r3  r=   rJ  r_  rJ   r\  get_maskmem_encmemory_attentionr@  rS  r   r5  d_modelr  )r3   r  pix_feat_with_memrM  memory_pos_embeds        r7   $_prepare_memory_conditioned_featureszDSAM2DynamicInteractivePredictor._prepare_memory_conditioned_features  s     t  A%%GS)A)A% !% 1" 5
8O O (,';';'='=$F$ $
 ; ;&rss+/4+#$ !< ! ! 7 ((Aq116J'/
 _R 
 
 
 	
r8   c                   g g }}| j         D ]}|                    |d                             d                              ddd                     |d         d                             d                              ddd          }|| j        j        | j        j        dz
           z   }|                    |           t          j        |d          }t          j        |d          }||fS )zfGet memory and positional encoding from memory, which is used to condition the current image features.r  r<   r   r   r  r:   r   )	r3  r   r   rS  rJ   maskmem_tpos_encr  r>   r   )r3   to_cat_memoryto_cat_memory_pos_embedr  maskmem_encrM  rT  s          r7   rP  z/SAM2DynamicInteractivePredictor.get_maskmem_enc@  s    13R. $ 0 	8 	8  !12D!E!M!Ma!P!P!X!XYZ\]_`!a!abbb*+<=bAII!LLTTUVXY[\]]K%
(CDJDZ]^D^(__K#**;7777=a000 9%<!DDD'''r8   rz  c                8    | j                             |d          S )zMap 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  )r3   rz  s     r7   r  z.SAM2DynamicInteractivePredictor._obj_id_to_idxM  s     !%%fd333r8   rE  rF  r/  dict[str, Any]c                   |z| j         j        rn| j        d                             ddd          } |j        d| j         j        j        g| j        d         R  }| j                             |          \  }}}}}}	}
nb| 	                    |          |
dd         n| j         
                    |||dnd|dfd| j        D             	          \  }}}}}}	}
|||	|
d
S )a  Tracking step for the current image state to predict masks.

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

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

        Returns:
            current_out (dict[str, Any]): A dictionary containing the current output with mask predictions and object
                pointers. Keys include 'point_inputs', 'mask_inputs', 'pred_masks', 'pred_masks_high_res',
                'obj_ptr', 'object_score_logits'.
        Nr:   r   r<   r   r  Fc                :    g | ]}|d j         d                  S )Nr   )rw   )rZ   rU  rS  s     r7   r]   z>SAM2DynamicInteractivePredictor.track_step.<locals>.<listcomp>  s-    "i"i"i$4(D*;*A!*D(D#E"i"i"ir8   )backbone_featuresr  r  rq   rf  )r   r  r  r  )rJ   $use_mask_input_as_output_without_samr_  rS  r   rQ  rR  r  _use_mask_as_outputrU  _forward_sam_headsrf  )r3   r  rE  rF  r/  pix_featr^  low_res_masksr  r  r  rS  s              @r7   r  z*SAM2DynamicInteractivePredictor.track_stepX  sD   4 
 O (,44Q1==H$x}R)D)Lct_aObcccHSWS]SqSqrvSwSwPAq!]NG=P=P !% I I' R R9@9L 1"1" 5 5RcSWS]SpSp"3OVObeUKKKhl !&"i"i"i"iRVRh"i"i"i Tq T TPAq!]NG=P (#1#6	
 
 	
r8   )
r4   r   r5   r  r/  rJ  r    r!   r0  r1  r7  )r.   r6  rd   r7  rf   r8  re   r7  rg   r9  r  r9  r:  r;  r0  r<  )r  r6  r0  r1  r5  )
r  r9  re   rA  rg   rA  rf   rA  r0  r1  )r  rH  r0  rI  )r0  r<  )rz  rJ  r0  rH  )
r  rH  rE  rA  rF  rA  r/  rA  r0  r\  )r8  r9  r:  r;  r   r+   r   rs   ru   r:  rU  rP  r  r  r=  r>  s   @r7   r.  r.  @  sc        6 +/"&( ( ( ( ( ( (>  ,026+/#'$(#@C @C @C @C @CD% % % %   %)&*&*%)N2 N2 N2 N2 N2`!
 !
 !
 !
F( ( ( (	4 	4 	4 	4 #%)%)$(1
 1
 1
 1
 1
 1
 1
 1
 1
r8   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.)   rh  )   ri  )H   rj     NTc                l   t                                          ||           t          j        g d                              ddd                              | j                  | _        t          j        g d                              ddd                              | j                  | _        dS )zTSetup the SAM3 model with appropriate mean and standard deviation for preprocessing.)     _@rm  rm  r:   r   N)	r*   r   r>   r   r   rF   rG   rH   rI   )r3   rJ   r   r6   s      r7   r   zSAM3Predictor.setup_model  s    E7+++L!6!6!677<<RAFFII$+VV	< 5 5 566;;B1EEHHUUr8   c                P    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_sam3rq  r,   rJ   rs  )r3   rq  s     r7   r   zSAM3Predictor.get_model  3    666666%%dioty?PQQQQr8   r6  )	r8  r9  r:  r;  rP  r   r   r   r=  r>  s   @r7   rf  rf    sw        ]]  N
 FV V V V V VR R R R R R Rr8   rf  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dS )SAM3SemanticPredictorzGSegment Anything Model 3 (SAM3) Predictor for image segmentation tasks.c                P    ddl m}  || j        j        | j        j                  S )ro  r   )build_sam3_image_modelrr  )rt  ry  r,   rJ   rs  )r3   ry  s     r7   r   zSAM3SemanticPredictor.get_model  ru  r8   c                @    | j         j                            |          S )z2Extract image features using the model's backbone.)rJ   backbonerY  r  s     r7   ru   z%SAM3SemanticPredictor.get_im_features  s     z"00444r8   c                    t          |          dk    s
J d            t          | j        ddd          fd|D             S )rQ   r   rR   FT)rS   rT   
scale_fillc                (    g | ]} |           S rV   rX   rY   s     r7   r]   z7SAM3SemanticPredictor.pre_transform.<locals>.<listcomp>  r^   r8   r_   rb   s     @r7   rB   z#SAM3SemanticPredictor.pre_transform  sQ    , 2ww!|||U|||djuUtTTT	////B////r8   Nc                   |=t          j        || j        | j                  }|j        dk    r|d         n|}t          j        |          }|dddddfxx         |d         z  cc<   |dddddfxx         |d         z  cc<   |!t          j        |j	        dd                   }t          j        |t           j
        | j                  }|j	        d         |j	        d         k    s'J d|j	        d          d	|j	        d          d
            |                    ddd          }|                    dd          }||fS )zRPrepare prompts by normalizing bounding boxes and points to the destination shape.Nr   r   r   r<   r:   r   r   r   r   rC  )r>   r   r   rG   r   r   	xyxy2xywhr@   r   rw   r   r   )r3   r   rd   rg   s       r7   _prepare_geometric_promptsz0SAM3SemanticPredictor._prepare_geometric_prompts  sV   _V43CDKXXXF%+[A%5%5VD\\6F]6**F111add7OOOy|+OOO111add7OOOy|+OOO~crc!233_V5;t{SSSF<#v|B'7777hFL$4hhU[UabdUehhh 877 [[Q**F[[Q''Fv~r8   textlist[str] | Nonec                   |dn)|t          |          nt          | j        j                  }|                     |          }|Ht	          t          |                    D ]&}|                    ||g         ||g                    '|dg}|+| j        j        |k    r| j                            |           | j                            |t          j	        || j
        t          j                  |          }|S )zPRun inference on the extracted features with optional bounding boxes and labels.Nr   visualr  r'  r]  text_idsgeometric_prompt)r`   rJ   r   _get_dummy_promptr  append_boxesset_classesforward_groundingr>   r  rG   long)	r3   r/   rd   rg   r  ncr  rk   outputss	            r7   rx   z)SAM3SemanticPredictor._inference_features  s	    $QQt7G#d)))SQUQ[QaMbMb11"553v;;'' H H --faSk61#;GGGG| z
 0D 8 8J"""---*..!\"T[
KKK- / 
 

 r8   c           
     :   ddl }|d         }|d         }|d         }|                                }|d                                                             d          }	||	z                      d          }t	          j        t          t          |j        d                             |j	        |j
        	          dddf                             |          }
t	          j        ||d
         |
d
         gd          }|| j        j        k    }||         ||         }}t          j        |ddddf                   |ddddf<   |ddddf         | j        j        rdndz  }|ddddf         |z   }|j                            ||dddf         | j        j                  }||         ||         }}t)          | j        dd t          |j        d                   D                       }t-          |t                    st          j        |          }g }t1          |g|g|| j        d                   D ]\  }}}}|j        d         dk    rdt	          j        d|j
                  }}nt7          j        |                                d         |j        dd         d          d         dk    }|dddgfxx         |j        d         z  cc<   |dddgfxx         |j        d         z  cc<   |                    t?          |||||                     |S )NPost-process the predictions to apply non-overlapping constraints if required.r   N
pred_boxespred_logitsr   presence_logit_decr   r:   r   .Nr   rC     r      r   c                ,    g | ]}t          |          S rX   r   rj   s     r7   r]   z5SAM3SemanticPredictor.postprocess.<locals>.<listcomp>	  s    -Z-Z-Zc!ff-Z-Z-Zr8   r   r   r<   r   r%  rO  .r;   r   ) r   sigmoidr+  r   r>   r   r  r  rw   r   rG   	expand_asr   r,   r	  r   	xywh2xyxyagnostic_nmsr   r   r  rJ   r=   r  r   r'   r  r   r   rM   r   r
   )r3   r
  r  r  r   r  r  r   r   presence_scorepred_clsr   c	nms_boxesr   r  rf   r{   r  r  s                       r7   r  z!SAM3SemanticPredictor.postprocess  sU   <(
M*<(
!))++34<<>>HHKK"^3<<R@@<{(+,,--#%
 
 
 !!T'	 9[))	 	
 Y
K	,BHYDWX^`aaa
TY^+!+D!1:d3CJ
M*QQQU*;<<
111bqb5qqq!A#vty'="G!!4Hqqq"1"u%)	""9jA.>	NN!+D!1:d3CJ

G-Z-ZeKDUVWDX>Y>Y-Z-Z-Z[[)T** 	A5i@@I03ZL:,PY[_[efg[h0i0i 	d 	d,E5(H{1~""#U[
@Q%R%R%RuekkmmD&98>"1";MT^___`abehhcAq6k"""hnQ&77"""cAq6k"""hnQ&77"""NN78(%u\abbbccccr8   c                v   | j                             d|          }| j                             d|          }| j                             d|          }| j        |                     |          n| j        }|                     | j        d         d         j        dd         ||          } | j        |g|R d|iS )z:Perform inference on a single image with optional prompts.rd   rg   r  Nr   r   r<   )r0   rm   r/   ru   r  r'   rw   rx   )	r3   r.   rd   rg   r  r,   rr   r/   r0   s	            r7   rs   zSAM3SemanticPredictor.inference	  s    !!(F33!!(F33|--/3}/D4''+++$-11$*Q-2B2H!2LfV\]]'t'F7FFFFFFr8   c                f   ddl }|                     |dd         ||          } | j        |g|R d|i}|d         }	|d         }
|d         }|
                                }|d                                                             d	          }||z                      d
          }t          j        t          t          |j
        d                             |j        |j                  dddf                             |          }t          j        |	|d         |d         gd
          }	|| j        j        k    }||         |	|         }	}t#          j        |	ddddf                   |	ddddf<   |	ddddf         | j        j        rdndz  }|	ddddf         |z   }|j                            ||	dddf         | j        j                  }|	|         ||         }}	|j
        d         dk    rdt          j        d|j                  }	}nt/          j        |                                d         |dd         d          d         dk    }|	dxx         |d	         z  cc<   |	dxx         |d         z  cc<   |	dxx         |d	         z  cc<   |	dxx         |d         z  cc<   ||	fS )aM  Perform prompts preprocessing and inference on provided image features using the SAM model.

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

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

        Notes:
            - The input features is a torch.Tensor of shape (B, C, H, W) if performing on SAM, or a dict[str, Any] if performing on SAM2.
        r   Nr<   r  r  r  r   r  r   r:   r   r  r   rC  r  r   r  r   r   r   r%  rO  ).r   ).r   ).r<   ).r;   )r   r  rx   r  r+  r   r>   r   r  r  rw   r   rG   r  r   r,   r	  r   r  r  r   r   r  r   r   rM   )r3   r/   r   rd   rg   r  r   r0   r
  r  r  r   r   r  r  r   r  r  s                     r7   r3  z(SAM3SemanticPredictor.inference_features$	  s   4 	11)BQB-PP((GGGGG$GG<(
M*<(
!))++34<<>>HHKK"^3<<R@@<{(+,,--#%
 
 
 !!T'	 9[))	 	
 Y
K	,BHYDWX^`aaa
TY^+!+D!1:d3CJ
M*QQQU*;<<
111bqb5qqq!A#vty'="G!!4Hqqq"1"u%)	""9jA.>	NN!+D!1:d3CJ
A!##%)5;vjFW+X+X+X
JJz'7'7'9'9$'?2A2U_```abcfiiJv)A,.v)A,.v)A,.v)A,.:%%r8   c                ,    i | _         i | j        _        dS )z$Reset the prompts for the predictor.N)r0   rJ   text_embeddingsr!  s    r7   reset_promptsz#SAM3SemanticPredictor.reset_promptsb	  s    %'
"""r8   r   c           	         t          t          j        d|d| j                  t          j        |d| j        t          j                            }|S )z-Get a dummy geometric prompt with zero boxes.r   rC  r   r'  )box_embeddingsbox_mask)r   r>   r  rG   r;  )r3   num_promptsr  s      r7   r  z'SAM3SemanticPredictor._get_dummy_promptg	  sQ    ! ;q+qMMM[a5:VVV
 
 
  r8   r+  NNNr  r  r*  )r8  r9  r:  r;  r   r   ru   rB   r  rx   r  rs   r3  r  r  rX   r8   r7   rw  rw    s       QQR R R 5 5 50 0 04   (    && & &PG G G G G 
 !%;& ;& ;& ;& ;&z( ( (
           r8   rw  c                      e Zd ZdZd ZdS )SAM3VideoPredictorzMSegment Anything Model 3 (SAM3) Video Predictor for video segmentation tasks.c                   |}|d         }|d         }|d         }t          |d                   }t          |d                   dk    rt          d          ||d         v r:d}||         |         }	| j        r"| j        s|dk    r|                     |           n]||d	         v rd	}||         |         }	nBd	}|                     |||d
ddd
d|	  	        }	|	||         |<   |                     ||           |                     ||	||           |d                             |           |	d         	                    dd          }
|	d         }||
|fS )a   Perform image segmentation inference based on the given input cues, using the currently loaded image. This
        method leverages SAM's (Segment Anything Model) architecture consisting of image encoder, prompt
        encoder, and mask decoder for real-time and promptable segmentation tasks.

        Args:
            inference_state (dict): The current state of inference, including input cues and previous outputs.
            frame_idx (int): The index of the current frame in the video sequence.
        rx  r  r|  r}  ry  r   r~  r   r  FNT)	rx  r{  r  r  r  r  r  r  rn  r  r  r   r  )
r`   r  rp  rq  r  r  r  r  r   r   )r3   rn  r{  r  rx  r  r|  r  r  r  r   
obj_scoress               r7   propagate_in_videoz%SAM3VideoPredictor.propagate_in_videos	  s    %m4!),"12K"L9::
{/011Q66PQQQ+,@AAA.K%k259K3 =9^ =blpqbqbq55e<<<-.FGGG2K%k259KK2K::'%#(!  $ / ; 
 
K /:K$U+'''OOO 	##E;Ud#eee0188??? .66q!<<
 !67

J..r8   N)r8  r9  r:  r;  r  rX   r8   r7   r  r  p	  s)        WW0/ 0/ 0/ 0/ 0/r8   r  c                      e Zd ZdZdZdZdZdZdZdZ	dZ
g dZd	Zed
d
ddddddddddddddddddddddfdo fdZdp fd	Z fdZed             ZdqdrdZd ZdsdZ e            	 	 	 	 dtd            Zdud Z	 dvdwd0Zedxd2            Zdyd3Zd4 Zd5 Zdzd7Zd{d>Zd|d@Z 	 d}d~dDZ!ddFZ"e	 dddI            Z#	 	 dddNZ$ddPZ%ddVZ&dd]Z'dd`Z(ddcZ)dddZ*de Z+ddhZ,dvddlZ-dm Z.edn             Z/ xZ0S )SAM3VideoSemanticPredictorz9Segment Anything Model 3 (SAM3) Video Semantic Predictor.皙?      $r:   i r   r<   rg  rk  NrO          r   r;      TFr   r    r!   c                T   t                                          |||           || _        || _        || _        || _        || _        |	dk    r|
|	k    sJ ||	k    sJ |	| _        |
| _        || _	        || _
        || _        || _        || _        || _        || _        || _        || _        d| _        d}d}|| _        || _        || _        || _        || _        || _        || _        t5          |          | _        i | _        | j        d                             | j                   dS )zTInitialize the SAM3VideoSemanticPredictor with configuration and optional overrides.r   Ni'  r   )r5   rm  ) 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_alive8suppress_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  trackerrn  rr  r   rs  )r3   r4   r5   r    r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r6   s                              r7   r+   z#SAM3VideoSemanticPredictor.__init__	  sb   \ 	i444)B&, 0$8!, A*n<<<<&.8888,'>$#6 #6 "4"4D 	E /M+:d7,H),  .#6 +F(+F(;f8.L+-J* *I>>>!)*11$/BBBBBr8   c                    t                                          ||           ddlm}  || j        j        d          }| j                            |d           dS )z+Setup the SAM3VideoSemanticPredictor model.r   rp  F)with_backbone)rJ   r   N)r*   r   rt  rq  r,   rJ   r  )r3   rJ   r   rq  r6   s       r7   r   z&SAM3VideoSemanticPredictor.setup_model
  sk    E7+++666666 '&tyeLLL  ue <<<<<r8   c                &    t                                          |            j         j        _         j        j                             j                    fddD              j        _         j        j        j        j        j	         _	        dS )z:Setup the source for the SAM3VideoSemanticPredictor model.c                :    g | ]fd j         D             S )c                D    g | ]}t          |j        z  z            S rX   rI  rK  s     r7   r]   zFSAM3VideoSemanticPredictor.setup_source.<locals>.<listcomp>.<listcomp>
  s,    'W'W'WqAq,A(B(B'W'W'Wr8   rL  rM  s    @r7   r]   z;SAM3VideoSemanticPredictor.setup_source.<locals>.<listcomp>
  s5    &s&s&s\]'W'W'W'W'WDJ'W'W'W&s&s&sr8   rN  N)
r*   r  ra   r  rJ   r  rP  memory_encodermask_downsamplerinterpol_sizer  s   ` r7   r  z'SAM3VideoSemanticPredictor.setup_source
  s~    V$$$!Z$$TZ000&s&s&s&sar&s&s&s#!\/>O]r8   c                    t          | j                  dk    rdS | j        J | j        j        dk    sJ | j        j        }|g i ddg|z  d}|| _        dS )a  Initialize an inference state for the predictor.

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

        Args:
            predictor (SAM3VideoSemanticPredictor): The predictor object for which to initialize the state.
        r   Nr  )r  tracker_inference_statestracker_metadatatext_promptper_frame_geometric_prompt)r`   rn  r  r&   r  )r  r  rn  s      r7   rs  z%SAM3VideoSemanticPredictor.init_state!
  s     y())A--F ,,, %0000&-
$(* "+/&:*=
 
 %4	!!!r8   r  r  c                    | j         j        dz
  }|| j        d<   d| j        vr|                     ||||           |                     |d          S )z<Perform inference on a video sequence with optional prompts.r   r.   r  )r{  r  rd   rg   F)r  )r  r  rn  
add_promptr  )r3   r.   rd   rg   r  r,   rr   r  s           r7   rs   z$SAM3VideoSemanticPredictor.inference:
  s_    "Q&%'T"T111OOe$vfOUUU//u/EEEr8   c           
        d         t                                                    }t          |t                    st	          j        |          }| j        j        dk    r| j        j        ni }t          |          dk    rdt          j
        d| j                  }}nht          j        fd|D             d          }t          j        |                                d         |d         j        dd	         d
          d         dk    }t          j        |t          j        |j                  }t          j        fd|D             |j                  }	t          j        fd|D             |j                  }
|	| j        j        k    |                    d          z  }||         }t-          |          }t          j        |||         dddf         |	|         d         |
|         d         gd          }|j        d         rf|pct/          t1          d t3          |dddf                                                                         dz             D                                 }|j        d         dk    rt          j        fd|D             |j                  |         }|                     |                    d          |                    d          d                              d          dk    }g }t?          |g|g|| j         d                   D ].\  }}}}|!                    tE          |||||                     /|S )r  obj_id_to_maskr  r   N)r      r   c                     g | ]
}|         S rX   rX   )rZ   rz  r  s     r7   r]   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>M
  s    #V#V#VvN6$:#V#V#Vr8   r   r<   r   r%  rO  r   c                ,    g | ]}d          |         S )obj_id_to_scorerX   rZ   rz  r
  s     r7   r]   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>Q
  s$    MMMf()&1MMMr8   c                ,    g | ]}d          |         S )obj_id_to_clsrX   r  s     r7   r]   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>T
  s#    KKKF'/KKKr8   r  r  r:   c              3  4   K   | ]}t          |          V  d S ri   r   rj   s     r7   rl   z9SAM3VideoSemanticPredictor.postprocess.<locals>.<genexpr>]
  s(      /h/h1A/h/h/h/h/h/hr8   r   r   c                D    g | ]}|d          v rd          |         ndS )obj_id_to_tracker_scorer  rX   r  s     r7   r]   z:SAM3VideoSemanticPredictor.postprocess.<locals>.<listcomp>`
  sO        #  &/H)III "";<VDD!$	  r8   )background_valuer   )#sortedr  r=   r  r   r  rJ   r   r`   r>   r  rG   r   r   r   rM   rw   r   r   r,   r	  anyr   r)   r  r  rJ  max._apply_object_wise_non_overlapping_constraintsr+  r   r   r'   r   r
   )r3   r
  r  r  curr_obj_idsr   r   r  pred_idsr   r  r   tracker_scoresr  rf   r{   r  r  r  s    `                @r7   r  z&SAM3VideoSemanticPredictor.postprocessB
  s   /0n113344)T** 	A5i@@I$(J$4$@$@
  b|!!%)5;vdk+R+R+R
JJ#V#V#V#V#V#V#V\]^^^Jz'7'7'9'9$'?1ASTVUVTVAW^hiiijklorrJ|LJL]^^^H,MMMMMMMV`Vg  K |KKKKlKKKT^Te  H  $).0JNNvN4N4NND#D)J,Z88JXd^AAAtG4k$6G	6RT\]aTbclTmntv  J " jii/h/hjQRQRQRTUQUFVFZFZF\F\F`F`FbFbefFf@g@g/h/h/h&h&h!i!i"Q&&!&    '3   &,
" 
" 
" 
" GG",,Q//&0033)* H   gajj
 03ZL:,PY[_[efg[h0i0i 	d 	d,E5(HNN78(%u\abbbccccr8   c                J   |p| j         }|d         }|d         du}|d         |         du}|                     ||d         ||d         |d         |s)|                     t          |d                             n|d         |         ||d	         |p|
	  	        \  }}}	}
}}}|
|d<   ||d	<   |||	|d         |         d}|d         }|d         }||d<   ||d<   | j        r=|d         d         }|| j        k    }|d         |                                         |d<   ng |d<   |S )zBPerform inference on a single frame and get its inference results.r  r  Nr  r  r.   r  r  r  )	r{  r  r  r.   r  r  tracker_states_localtracker_metadata_prevallow_new_detections"obj_id_to_tracker_score_frame_wise)r  r  r  r  metadataremoved_obj_idsframe_statsmasklet_confirmationstatusobj_ids_all_gpuunconfirmed_obj_ids)rn  _det_track_one_framer  r`   r  UNCONFIRMEDtolist)r3   r{  r  rn  r  has_text_prompthas_geometric_promptr  r  r  tracker_states_local_newtracker_metadata_newr  r^  r  r  r  r   is_unconfirmeds                      r7   r  z6SAM3VideoSemanticPredictor._run_single_frame_inferencew
  s   )AT-A./IJ)-8D./KLYW_cc %%&|4t$$Z0 ,N&&3z7R3S3S&TTT$%AB9M!5"12D"E!0!H4H & 
 
	
$ " 7O23.B*+ -.*';<`'abk'l	
 
 (
3"#45!0(M+ 	,45h?F#t'77N)=>O)PQ_)`)g)g)i)iC%&&)+C%&
r8   c                   |p| j         }||
J d            |du}|r|nd}t          |t                    r|gn|}|r|nd|d<   t          |          }t	          j        || j        t          j                  }	|	|d<   |+| j        j	        |k    r| j        
                    |           |                     | j        d         d	         j        dd
         ||          \  }}|du|duk    sJ |                     |          }
|Ct          t          |                    D ]&}|
                    ||g         ||g                    '|
|d         |<   |                     |d|          }||fS )aB  Add text, point or box prompts on a single frame. This method returns the inference outputs only on the
        prompted frame.

        Note that text prompts are NOT associated with a particular frame (i.e. they apply
        to all frames). However, we only run inference on the frame specified in `frame_idx`.
        Nz:at least one type of prompt (text, boxes) must be providedr  r  r'  r  r  r   r   r<   r  r  F)r  rn  )rn  r=   r   r`   r>   r  rG   r  rJ   r   r  r  r'   rw   r  r  r  r  )r3   r{  r  rd   rg   rn  use_text
text_batchnr  r  rk   r  s                r7   r  z%SAM3VideoSemanticPredictor.add_prompt
  s    *AT-A6#5#57s#5#55 t#-ttX)$44>dVV$
19)Ct&
OO<$+UZHHH&.
#
 0D 8 8J"""--- 88Aq9I9OPRQRPR9SU[]cddd"d(:;;;;11a1@@3v;;'' H H --faSk61#;GGGGCS45i@..y%Yh.ii#~r8   c                    t          j        |dk    |d         |          }| j        j                            |          }t          j        |dk    |t          j        ||                    }|S )zhApplies non-overlapping constraints object wise (i.e. only one object can claim the overlapping region).r   ).NN)r  )r>   wherer  rJ   r  clamp)r3   r   r  r  pred_masks_single_score!pixel_level_non_overlapping_maskss         r7   r  zISAM3VideoSemanticPredictor._apply_object_wise_non_overlapping_constraints
  sy     #(+j1nj>Y[k"l"l,0L,>,a,a#-
 -
) [-1K
(8999
 


 r8   r.   rI  r  r{  rJ  r  r  r;  r  r   r  	list[Any]r  r\  r  c
           	        |                      ||||	          }
|i k    r'|                    |                                            |                     |||          \  }}|                     |||
||||          \  }}|                    dt                                }|                     |||
||          }|                     |
||||          }|d         }|d         }t          j
        |d	                   |d
         d}|j        d         dk    rj|                                                                }|d         }|d         |                             t          t          ||                               |||||||fS )a  This function handles one-step inference for the DenseTracking model in an SPMD manner. At a high-level, all
        GPUs execute the same function calls as if it's done on a single GPU, while under the hood, some
        function calls involve distributed computation based on sharded SAM2 states.

        - `input_batch` contains image and other inputs on the entire video; it should be identical across GPUs
        - `tracker_states_local` holds the local masklet information in this GPU shard
        - `tracker_metadata_prev` manages the metadata for SAM2 objects, such as which masklet is hold on which GPUs
          it contains both global and local masklet information
        )r.   r  r  r  )r{  r  r  )r{  r  det_outtracker_low_res_masks_globaltracker_obj_scores_globalr  r  reconditioned_obj_ids)r{  r  r  r  tracker_update_plan)r  r  r  r  r  r  r  num_objnum_obj_dropped_due_to_limit)num_obj_trackednum_obj_droppedr   r  r  )run_backbone_and_detectionr(   _initialize_metadatarun_tracker_propagation!run_tracker_update_planning_phaser  r  "run_tracker_update_execution_phasebuild_outputsr@   r  rw   r  r  r)   r   )r3   r.   r  r{  r  r  r  r  r  r  r  r  r  r  r	  r  r  r  r  r  r  tracker_obj_idss                         r7   r  z/SAM3VideoSemanticPredictor._det_track_one_frame
  s   . 11-!5	 2 
 
 !B&&!(()B)B)D)DEEEBFB^B^!5"7 C_ C
 C
?$&? 594Z4Z)E&?"7!5 5[ 5
 5
11 !4 7 78OQTQVQV W W $(#J#J!!5 3 $K $
 $
  ++)E"7 3"7 , 
 
 //@A,_=  "v&:9&EFF23QR
 

 %*1-11(A(I(I(K(K(R(R(T(T%3I>O !EFyQXXS*CDDEE   $ %
 	
r8   皙?c                    |                      d          \  }}}}||z   dz  }||z   dz  }||k    |d|z
  k     z  ||k    z  |d|z
  k     z  }|S )zSuppress detections too close to image edges (for normalized boxes).

        boxes: (N, 4) in xyxy format, normalized [0,1]
        margin: fraction of image
        r:   r<   r   )unbind)	r{   marginx_miny_minx_maxy_maxx_cy_cr   s	            r7   &_suppress_detections_close_to_boundaryzASAM3VideoSemanticPredictor._suppress_detections_close_to_boundaryP  sn     &+\\"%5%5"ueUu}!u}!fsV|!34fEsU[|I[\r8   c                    |                      |          }| j                            |||          }|                     ||          }|                     |           |S )z.Run backbone and detection for a single frame.r  )ru   rJ   r  _extract_detection_outputs_cache_backbone_features)r3   r.   r  r  r  r/   sam3_image_outr  s           r7   r  z5SAM3VideoSemanticPredictor.run_backbone_and_detection^  sl     ''++55!HGW 6 
 
 11.BVWW%%n555r8   c                   |d                              d                                          }|s|dz
  }t          j        t	          t          |j        d                             |j        |j                  dddf         	                    |          }|d         }|d         }|| j
        k    }||         ||         ||         ||         d	S )
z%Extract and filter detection outputs.r  r:   g    חAr   r   Npred_boxes_xyxyr   )bboxr/  r   r  )r   r  r>   r   r  r  rw   r   rG   r  r  )r3   r4  r  
pred_probsr  r6  r   r   s           r7   r2  z5SAM3VideoSemanticPredictor._extract_detection_outputsj  s    #M2::2>>FFHH
# 	*#c)J<z'*++,,"$
 
 
 !!T'	 9Z((	 	 )):;#L1
D::#D)t$ &D>	
 
 	
r8   c                   | j         j        j        }|d         d         }|                    |d         d                   |                    |d         d                   |d         d         g}|d         |d         |d	}|| j         _        d
S )z'Build and cache SAM2 backbone features.r]  sam2_backbone_outbackbone_fpnr   r   r<   r:   vision_pos_enc)vision_featuresr<  r;  N)r  rJ   rh  conv_s0conv_s1r]  )r3   r4  rh  r`  tracker_backbone_fpntracker_backbone_outs         r7   r3  z3SAM3VideoSemanticPredictor._cache_backbone_features  s    <->~./BC$$U>%:1%=>>$$U>%:1%=>>.!!$ 
  4B7#$450 
  
 %9!!!r8   dict[str, np.ndarray]c                    |                      ||          \  }}}t          j        ||d         k              s$J d                    ||d                               |}|}||fS )zGRun the tracker propagation phase for a single frame in an SPMD manner.r{  r  z{} != {})&_propogate_tracker_one_frame_local_gpur@   rn   r   )	r3   r{  r  r  obj_ids_locallow_res_masks_localobj_scores_locallow_res_masks_globalobj_scores_globals	            r7   r!  z2SAM3VideoSemanticPredictor.run_tracker_propagation  s     @D?j?j I @k @
 @
<*,< vm'<Y'GGHH 	
 	
*J[J[0;K
 K
 	
 	
H  3,#%666r8   r  dict[str, torch.Tensor]trk_id_to_max_iou_high_conf_det	list[int]r  r  c                   |                                 D ]<\  }}|d         ||dz            }	t          j        |	                    d          | j        dd          dk    }
d}t                      }t          j        |d         |k              d                                         }||         }t          |          D ]l\  }}||d         v r]||k    rWt          j        d	| d
| d|d          d           | j                            ||||
           |                    |           m|D ]"}| j                            ||                    #>|S )z=Recondition masklets based on new high-confidence detections.r/  r   r   Fr  r   r  r  zAdding new mask for track 
 at frame z
. Objects z are all reconditioned.rn  r{  rz  rf   )r  r   r   r+  r  r  r@   r  itemr  r   debugr  r  rD  r  )r3   r{  r  rL  r  r  r  
trk_obj_iddet_idxnew_masknew_mask_binaryHIGH_CONF_THRESHreconditioned_states_idxr  	obj_score	state_idxrn  r   s                     r7   _recondition_maskletsz0SAM3VideoSemanticPredictor._recondition_masklets  s    $C#H#H#J#J 	U 	UJvw1'<=Hh0033$:LS]mrsssvww   #'*uu$h/	:jHII!LQQSSG1':I.78L.M.M < <*	?/)"<<< "$444L TZ  T  T9  T  T`opy`z  T  T  T   L00(7"+)-	 1    -00;;;/ U U99:Ns:STTTTU##r8   r  c           
        t          |d                   t          |d                   t          |d                   t          |d                   t          |d                   i t          |d                   d}t                      }	|d         }
|d	                                                                                                         }|d
                                                                                                         }|d         }|                     |
|||d                   \  }}}}}| j        rG|                     ||                   }||                                                                         }t          j	        |d                   }t          |          }d}||z   | j        k    rlt          j        d| j        d|d|           | j        |z
  }||z
  }|                     |||          }t          |          |k    sJ t          |          }|d         dz   t          j        |          z   }t          |d                   }t!          | d          r| j        r |                     |||||||          \  }}nt                      }||d<   ||||||||	d}d}| j        dk    rt          |          dk    r|                                D ]\  }}|d         |         }|d	         |         } 	 t+          |d                                       |          }!n# t.          $ r Y Xw xY w||!         }"|"dk    }#|#	                                                                }$|$dk    rt3          |#                    d                                        d          }%|"j        dd         \  }&}'t;          j        |%d         |'z  |%d         |&z  |%d         |'z  |%d         |&z  g|%j                  }(|                    d          })|(                    d          }*tA          |)|*          d         }+|+| j        k     r"| | j!        k    rd}|	"                    |           | j#        dk    o || j#        z  dk    ot          |          dk    },|,s|r| $                    ||||||           |%                    d          }-|-dk    rTt!          | d          r| j        r%| j&        dk    r| '                    ||||||          }| (                    |||           |d         }.t          |          dk    rt          j)        |.|g          }.t          |          dk    r+t          j*        |.t+          |                    }/|.|/          }.|.|d<   t          |.          |d<   t          |          dk    r|d         +                    tY          |||                              |d         +                    tY          |||                              |d         |         +                    tY          |||                              t[          |d         t          j-        |                    |d<   |D ]:}0d|d         |0<   d|d         |         |0<   |d          .                    |0d           ;d|v sJ | j/        r1| 0                    |d         |d         |d         ||!          }1|1|d<   ||fS )"zKRun the tracker update planning phase for a single frame in an SPMD manner.r  r  r  r  r  
max_obj_id)r  r  r  r  r  obj_id_to_last_occludedr]  r/  r   r  r7  )	det_masksdet_scores_np	trk_maskstrk_obj_idsr   zhitting self.max_num_objects=z with new_det_num=z and prev_obj_num=r   r  _warm_up_complete)r{  r  det_to_matched_trk_obj_idsnew_det_obj_idsempty_trk_obj_idsunmatched_trk_obj_idsr  )new_det_fa_indsre  rg  rd  obj_ids_newly_removedr  rL  r  Fr   Nr<   r;   r   Tr  )rd  g     r^  )r  obj_ids_all_gpu_prevobj_ids_all_gpu_updatedrd  re  )1r   r  rM   r(  r)  _associate_det_trkr  r0  r@   r  r`   r  r   warning_drop_new_det_with_obj_limitr  hasattrrc  _process_hotstartr  r  r  index
ValueErrorrQ  r   r+  r   rw   r>   r   rG   r   r  rD  r  r[  r  r  /_suppress_overlapping_based_on_recent_occlusion_tracker_update_memoriesconcatenateisinr(   r   r  rm   r  "update_masklet_confirmation_status)2r3   r{  r  r  r  r  r  r  r	  r  det_mask_predsr`  
det_cls_npdet_bbox_xyxyrh  rg  rd  rL  rf  r   prev_obj_numnew_det_numr  new_det_num_to_keepre  metadata_newri  r  should_recondition_iourS  rT  det_box	det_scoretrk_idxtracker_maskmask_binary	mask_areatracker_box_pixelsmask_height
mask_widthtracker_box_normalizeddet_box_batchtracker_box_batchr   should_recondition_periodicr  updated_obj_ids_this_gpu
is_removedrz  r  s2                                                     r7   r"  z<SAM3VideoSemanticPredictor.run_tracker_update_planning_phase  s-      5i @AA 5i @AA'(=>O(PQQ%&;O&LMM2:;PQu;v2w2w')"#8#FGG 
  
 !$ (/v$+H$5$;$;$=$=$A$A$C$C$I$I$K$K!(!5!5!7!7!;!;!=!=!C!C!E!E
&-fo ##$'2-i8	 $ 
 
	
!&+ . 	B>>}_?]^^D-dhhjj.>.>.@.@AO v3I>??/**'($+%(<<<Ned&:ee;eeVbeefff"&"6"E+69L+L("??Q^`sttO''+>>>>>o..K 0=ABIkDZDZZ   5j ABBt011 	*T5K 	*262H2H#+E /"3&;% 3I 3 3/!<< %(EE!+7Z(  /.%:*D%:,H/N%:

 

 "' .22s;Z7[7[^_7_7_'F'L'L'N'N $: $:#
G!&/'2#H-g6	"#8#CDDJJ:VVGG!   H  <GD*Q.'OO--2244	>> &99N9Nq9Q9Q%R%R%Z%Z[\%]%]"*6*<RSS*A'Z).*1-
:*1-;*1-
:*1-;	 .4* * *& !( 1 1! 4 4$:$D$DQ$G$G!m->??B<<<dNpApAp-1*)--j999 ,q0 9D<<A9344q8 	$ ' 	*@ 	&&/$%)   266q99
>>4!455 
9O 
PSVVV373g3g!4-,-4 40 ))*>	Yu)vvv $8	#B !##')~7OQ`6a'b'b$$%%))!94@U;V;VWWJ'?'L$*BY'*-.F*G*GY'!## !23::3P]^mPn;o;oppp 188_jYhNi9j9jkkk !EFyQXXO]?%CDD   255I,5WY[Y_`oYpYp1q1q . , 	N 	NF>B !23F;\` !EFyQRXY !:;??MMMM11111+ 	8>>-j9%:9%E(<Y(G+E / ?  H 08 ,"$888s   (L;;
MMr	  ri  set[int]c                    d         }|dk    |                     d          }|dk    rt          |          |k    sJ dt          |           d|             t          j         fd|D             d          }	                     |	|||          }
                    d           }||
z  }|	                                ||<   fdt          |          D             |d	<    j        ||
<   |S )
a#  Suppress overlapping masks based on the most recent occlusion information. If an object is removed by
        hotstart, we always suppress it if it overlaps with any other object.

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

        Returns:
            (torch.Tensor): The updated low-resolution masks with some objects suppressed.
        r  r   zMismatch in number of objects:  vs c                    g | ]S}d                               |t          j        d|vrj        nj        j        t          j                            TS )r^  r*  )r  rG   r   )r  r>   r  NEVER_OCCLUDEDALWAYS_OCCLUDEDrG   r  )rZ   rz  #binary_tracker_low_res_masks_globalri  r3   r  s     r7   r]   z^SAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusion.<locals>.<listcomp>  s         **CDHH
 7=EZ7Z7Z 3 3`d`t#F#M"'*  
 
  r8   r   r:   r   c                2    i | ]\  }}|||d z            S r*  rX   )rZ   r  rz  last_occluded_news      r7   
<dictcomp>z^SAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusion.<locals>.<dictcomp>  s;     ? ? ?ETWf)'GaK*?@? ? ?r8   r^  )	r  r`   r>   r   8_get_objects_to_suppress_based_on_most_recently_occludedr  r  r  NO_OBJ_LOGIT)r3   r{  r  r  r	  ri  r  obj_ids_globalr  last_occluded_prevto_suppressis_obj_occludedis_obj_occluded_or_suppressedr  r  s   `  ` `       @@r7   rs  zJSAM3VideoSemanticPredictor._suppress_overlapping_based_on_recent_occlusion  s   . /y9.JQ.N+166q99
>>~&&*444W#n2E2EWW:WW 544 "'       #1   " " "" WW3" K !D G GH G U UVO,;k,I) 2 8 8 : :?H;<? ? ? ?XabpXqXq? ? ? !:;
 9=8I(5++r8   r  c                .   |d         }|d         }|}|}	|d         }
t          |	          dk    r<t          j        |	          }|d         |         }|                     |||||          }t          |
          dk    r|                     ||
           |S )zEExecute the tracker update plan for a single frame in an SPMD manner.rh  re  ri  r   r/  )r{  r  r  new_obj_masksr  )r`   r>   rE   _tracker_add_new_objects_tracker_remove_objects)r3   r{  r  r  r  r  rh  re  new_det_obj_ids_localnew_det_fa_inds_localri  new_det_fa_inds_local_tnew_det_maskss                r7   r#  z=SAM3VideoSemanticPredictor.run_tracker_update_execution_phase  s     '::K&L&9:K&L,;,;*=>U*V $%%))&+&67L&M&M#*1&/:Q*RM#'#@#@#%1+%9 $A $ $  $%%))(()=?TUUU##r8   r  
set | Nonec                   |d         }|d         }i }|d         }|                     d          }	t          |          t          |	          k    sJ t          ||	          D ]
\  }
}|||
<   t          j        |          }| d         |                              d          }t          |          t          |          k    sJ t          ||          D ]
\  }
}|||
<   |it          |          dk    rV|                    di           }|D ]=}
|                    |
          }|$| d         |                              d          ||
<   >|S )	z-Build the output masks for the current frame.rh  re  r  r   r/  Nr   rL  )r+  r`   r   r>   rE   r  )r  r  r  r  r  rh  re  r  existing_masklet_obj_idsexisting_masklet_binaryrz  r/  new_det_fa_inds_tnew_det_low_res_masksrL  rT  s                   r7   r$  z(SAM3VideoSemanticPredictor.build_outputs  s    '::K&L&9:K&L $9#C ">"H"H"K"K+,,4K0L0LLLLL 8:QRR 	* 	*LFD%)N6"" ",_== '0A B L LQ O O?##s+@'A'AAAAA1FGG 	* 	*LFD%)N6"" !,5J1K1Ka1O1O.A.E.EFgik.l.l+/ S S9==fEE&-4V_W-E-O-OPQ-R-RN6*r8   binary_low_res_maskslast_occludedr  rH  c                   |j         t          j        k    sJ d|j                      t          j        |                    d          |j        t          j                  }t          |          dk    r|S t          |                    d          |                    d                    }|| j	        k    }t          j
        |d          }	|                    d          }
|                    d          }|st          j        nt          j        }|	 ||
|          z  |dk    z  }|	 |||
          z  |
dk    z  }|                    d          |                    d          z  }t          j        d          rT|Q|                                                                }|                                                                }|                                                                }|j        d         }t)          |          D ]Y}t)          |          D ]G}|||f         r;t          j        d	|d
||          d||          d||          d||          
           HZt)          |          D ]Y}t)          |          D ]G}|||f         r;t          j        d	|d
||          d||          d||          d||          
           HZ|S )NzExpected boolean tensor, got r   r'  r   )diagonalr:   r   
   z
frame_idx=z: Suppressing obj z last occluded z in favor of )r   r>   r;  r  r  rG   r`   r   r   r  triur+  gtltr  r   isEnabledForr(  r)  rw   r  rR  )r3   r  r  r  r{  r  r  r   mask_iou_threshoverlapping_pairslast_occ_expanded_ilast_occ_expanded_jcmp_opsuppress_i_masksuppress_j_maskr  rk   js                     r7   r  zSSAM3VideoSemanticPredictor._get_objects_to_suppress_based_on_most_recently_occluded7  s    $)UZ7779uYmYs9u9u777k %%a(('.*
 
 

 w<<1+33A668L8T8TUV8W8WXX !^^!JCCC+55a88+55a88!(6ehf(*=>>?"R') 	 f(*=>>?"R') 	 &))a)00?3F3F13F3M3MM r"" 	y'<-113399;;O-113399;;O)--//5577M ).q1J :&&  z**  A&q!t,  ey  e  eWQZ  e  eXefgXh  e  ew~  @A  xB  e  e  S`  ab  Sc  e  e   :&&  z**  A&q!t,  ey  e  eWQZ  e  eXefgXh  e  ew~  @A  xB  e  e  S`  ab  Sc  e  e   r8   inference_statesc                   g }g }g }|D ]}t          |d                   dk    r| j                            ||          \  }}}	t          |t                    sJ |                    |           |                    |                    d                     |                    |	                    d                     t          |          dk    rBt          j	        |d          }
t          j	        |d          }|
                    d          }
n@t          j
        dg| j        d         R d| j        i}
t          j
        d| j                  }||
|fS )zaInference_states: list of inference states, each state corresponds to a different set of objects.r  r   rD  r   r   rG   r   )r`   r  r  r=   r  extendr   r   r>   r   r  rP  rG   )r3   r  r{  rF  low_res_masks_listobj_scores_listrn  out_obj_idsout_low_res_masksout_obj_scoresrG  rH  s               r7   rE  zASAM3VideoSemanticPredictor._propogate_tracker_one_frame_local_gpu{  s   / 
	> 
	>O?9-..!33=A\=\=\9 >] > >:K*N k400000  ---%%&7&?&?&B&BCCC"">#9#9!#<#<==== !""Q&&"'),>A"F"F"F$ya@@@"5"="=a"@"@"'+a"]$2Ea2H"]"]"]QUQ\"]"]${1T[AAA13CCCr8   r_  r`  
np.ndarrayra  rb  c           	     
   | j         }| j        }| j        }|                                s
J d            |                                s
J d            |                    d          t          |          k    s0J d|                    d           dt          |                       |                    d          dk    rpt          j        |                    d                    }t          j        g t          j	                  }	t          j        g t          j	                  }
i }i }||	|||
fS |                    d          dk    ryt          j        g t          j	                  }|dk    
                    d                                                                          }||         }	||          }
i }i }||	|||
fS |j        dd         |j        dd         k    rt          j        |j        dd                   t          j        |j        dd                   k     rLt          j        |                    d	          |j        dd         d
d                              d	          }nKt          j        |                    d	          |j        dd         d
d                              d	          }|dk    }|dk    }t'          |                    d	                                          |                    d	                                                    }|                                                                }| j        rqddlm} d	|z
  } ||          \  }}t          j        |                    d          t4                    }t7          ||          D ]\  }}|||f         |k    rd||<   n||k    
                    d          }|
                    d                                                                          }t          j        ||           }||         }	||          }
t          j        ||k    t          j        t          j
        ||k    d	                              }t          j        |          d         }i }i }t          j        |d	          }|| j         k    | z  }t          j!        |d	          | j"        k    }tG          t          j        ||z            d                   }tI          |                    d                    D ]D}|||ddf         |k             ||<   ||v r%|||                  %                                }|||<   E||	|||
fS )aj  Match detections on the current frame with the existing masklets.

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

        Returns:
            new_det_fa_inds: array of new object indices.
            unmatched_trk_obj_ids: array of existing masklet object IDs that are not matched to any detections on this
                frame (for unmatched, we only count masklets with >0 area)
            det_to_matched_trk_obj_ids: dict[int, np.ndarray]: mapping from detector's detection indices to the list of
                matched tracklet object IDs
            empty_trk_obj_ids: array of existing masklet object IDs with zero area in SAM2 prediction
        z'float tensor expected (do not binarize)r   z7trk_masks and trk_obj_ids should have the same length, r  r  r   r   Nr   r   Fr  )linear_sum_assignmentr   Tr   )&r  r  r  is_floating_pointr  r`   r@   r  r   int64r  r(  r)  rw   prodr   r   r+  r   r   r   rM   r  scipy.optimizer  r  r;  r   logical_andlogical_notnonzeroargmaxrW  r  HIGH_IOU_THRESHr  r  rQ  ) r3   r_  r`  ra  rb  iou_thresholdiou_threshold_trkr  rh  rg  rf  rd  rL  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_iourS  s                                    r7   rl  z-SAM3VideoSemanticPredictor._associate_det_trk  s   . - 5,**,,WW.WWW,**,,WW.WWW,~~a  C$4$4444oinnUVFWFWoo]`al]m]moo 544 >>!!! i	q(9(9::O$&HR$:$:! "RX 6 6)+&.0+%*/!  ^^A!## hr2844O(1}11f1==AACCIIKKO$/$@! +_,< =)+&.0+%*/!  ?2339?233#777wyrss+,,rwyrss7K/L/LLLM''**"-#"'	  
 '!** 	 M''**"-#"'	  
 '!**  %q=$q=(003399;;=M=U=UVW=X=X=^=^=`=`aa((**""$$, 	H<<<<<< g+K44[AAGWXinnQ&7&7tDDDNGW-- - -11a4=$555(,N1%- &)::??Q?GGN*..6.::>>@@FFHH>/N?KK +,< ='(89 ^^+N26']":CCCDD
 

 *Z003 &("*,'!#7!;!;!;)T-BBzkQ&q111T5II#&rz2B_2T'U'UVW'X#Y#Y y~~a(()) 	@ 	@A,71118V,W&q),,,()?)BCHHJJ
>?/
; !&+
 	
r8   rd  dict[int, np.ndarray]re  rf  rg  r  c                h   |d         |d         }|d         }	|d         }
|d         }t                      }|s
|| j        z
  n	|| j        z   }|D ]}|vr||<   ||	vsJ | j        |	|<   t                      }|                                D ]}|                    |           |D ]#}t          | j        |	|         dz             |	|<   $|D ]>}||                             |           t          | j	        |	|         dz
            |	|<   ?| j
        r&|D ]#}t          | j	        |	|         dz
            |	|<   $|                                D ]\  }}||v s||v rt          |          | j        k    rQ|         |k    r| p|         |k     o|}|r2|                    |           t          j        d| d| d	|            |	|         d
k    r8||vr4||vr0t          j        d| d| d           |                    |           |                                D ]m\  }}t          |          dk     r|st          |fd          nt          |fd          }|D ]'}||k    r||f}|
|                             |           (n|
                                D ]z\  \  }}}||v s||v r|         |k    r|r|         |k     rO|rMt          |          | j        k    r5|                    |           t          j        d| d| d| d|            {|                    |           ||fS )zEHandle hotstart heuristics to remove unmatched or duplicated objects.obj_first_frame_idxunmatched_frame_indstrk_keep_aliveoverlap_pair_to_frame_indsr  r   zRemoving object rO  z# since it is unmatched for frames: r   z, due to being unmatchedr<   c                    |          S ri   rX   r[   r  s    r7   <lambda>z>SAM3VideoSemanticPredictor._process_hotstart.<locals>.<lambda>p  s    7J17M r8   )keyc                    |          S ri   rX   r  s    r7   r  z>SAM3VideoSemanticPredictor._process_hotstart.<locals>.<lambda>r  s    <OPQ<R r8   z& since it overlaps with another track z at frames: )r  r  r  r  r(   r   r  r   r  r  r  r  r`   r  rD  r   rR  r  )r3   r{  r  rd  re  rf  rg  r  r  r  r  r  ri  hotstart_diffrz  matched_trksmatched_trks_per_detframe_indicesis_within_hotstartr^  matched_trk_obj_idsfirst_appear_obj_idr  first_obj_idr  s                           @r7   rp  z,SAM3VideoSemanticPredictor._process_hotstart  s    ''<='(>?!"23%-.J%K""#45 #?Fk	D$777IX\XkLk & 	> 	>F000.7#F+////%)%=N6""uu$>$E$E$G$G 	6 	6  45555" 	^ 	^F%()@.QWBX[\B\%]%]N6""+ 	^ 	^F (//	::: &))@.QWBX[\B\%]%]N6"": 	b+ b b),T-DnU[F\_`F`)a)av&& &:%?%?%A%A 	2 	2!FM((F6K,K,K=!!T%AAA&9&&AM&Q&aZaVa &'/-?KG # & )--f555LM6 M MY M M=JM M  
 v&!++/11"777eee)eeefff%))&111 'A&F&F&H&H 	F 	F"A"&''!++
 T'-M-M-M-MNNNN,2R2R2R2RSSS  
 . F F000.7C.s3::9EEEF 6P5U5U5W5W 	 	1"\6M((F6K,K,K#F+m;;G;#F+m;;;}%%)AAA)--f555Lj6 j jY j j@Lj jZgj j  
 	4555$h..r8   r  rd  c                ,   t          |          dk    rdS t          j        |                    d          | j        dd          }t          | d          r| j        r| j        j        	                    |          }t          j        |dk                        d	          d
d          }d}|}|D ]}t          |d                   }	|	dk    r||	z   }
|||
         }|||
         }|                    d          }| j                            |||d|          }|\  }}|d         }dD ]c}|||         vr|||         |         d<   d |D             ||         |         d<   | j                            ||||         |         |           d||	z  }dS )zHRun Sam2 memory encoder, enforcing non-overlapping constraints globally.r   Nr   r   Fr  rc  r  r   r  r  r  )r  rn  rx  r  r  c                    g | ]}|S rX   rX   )rZ   poss     r7   r]   zGSAM3VideoSemanticPredictor._tracker_update_memories.<locals>.<listcomp>  s    IoIoIoRU#IoIoIor8   r  )rn  r{  r  r  )r`   r   r   r+  r  ro  rc  r  rJ   "_suppress_object_pw_area_shrinkager>   r  r  r  r  r  )r3   r  r{  rd  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_encrx  r  s                      r7   rt  z3SAM3VideoSemanticPredictor._tracker_update_memories  s(    '((A--F##A&&#	
 
 
 t011 	cT5K 	c!\/RRSabbN#k>A+=*B*Bx*B*P*PRVX]^^ '5 "	1 "	1M #M)$< = = A%%+.??M#1/-2O#P (;OM<Y(Z%388;; ,:: $)!& - ;  K =H9"$9'6KO  K$<<<J`K(34FGIoIoYnIoIoIoK(34EF 33$1' +K 8 C +	 4     00OOE"	1 "	1r8   r  r  c                   t          |          dk    r|d         nd}| j                            |          }d|d<   ||                    dd          nd|d<   t          |          |                    d          k    sJ |                                sJ t          j        |                    d          | j	        dd          
                    d          }|dk    }t          ||          D ])\  }}	| j                            ||||	d	         
           *| j                            |           |                    |           |S )z*Add a new object to SAM2 inference states.r   N)r  r.   r]  r   Fr  r+  rP  )r`   r  r  r  r  r  r   r   r+  r  r   r   r  r  r   )
r3   r{  r  r  r  r  prev_tracker_statenew_tracker_state
new_obj_idrU  s
             r7   r  z3SAM3VideoSemanticPredictor._tracker_add_new_objects  s    9<<P8Q8QTU8U8U1!44[_
 !L44
4KK"&$<N<Z"">4888`d 	.) ;=#5#5a#8#88888..00000##A&&#	
 
 

 '!** 	 &) %(]$C$C 	 	 JL(( 1#!z*	 )     	112CDDD##$5666##r8   c                    |sdS g }|D ]R}|D ]}| j                             ||d            t          |d                   dk    r|                    |           S||dd<   dS )zgRemove an object from SAM2 inference states. This would remove the object from all frames in the video.NFr  r  r   )r  r  r`   r   )r3   r  r  active_statesstaterz  s         r7   r  z2SAM3VideoSemanticPredictor._tracker_remove_objects  s     	F) 	, 	,E! H H **5&*GGGG5#$$q(($$U+++ #0QQQr8   c                   t          j        g t           j                  t          j        dt           j                  di i t	          t
                    i d}i t	          t                    t	          t                    t	          t                    t                      d}| j	        rBt          j        g t           j
                  t          j        g t           j
                  d|d<   ||d<   |S )z%Initialize metadata for the masklets.r   r:   )r  r  r]  r  r  r  r^  )r  r  r  r  r  )r   consecutive_det_numr  r  )r@   r   r   r  r   r)   r  rJ  r  r  r  )r3   r  r  s      r7   r   z/SAM3VideoSemanticPredictor._initialize_metadata  s     xBH--x28,,!2=d2C2C')
 
 $&$/$5$5)#..*5d*;*;"uu
 
 + 	 (2rx00 (*xBH'='=0 0H+, (0$r8   rj  rk  c                   |d         }|d         }|d         }|j         |j         k    sJ d|j          d|j                      d t          |          D             t          j        ||          }	||	         }
t          j        fd|
D             t          j                  }| j        }t          j        ||	          }||	         ||<   t          j        |          }||	         ||<   t          j        ||          }|	                                D ]}|t          j        ||          z  }t          j
        ||d
z   d          }|| j        k    }| j        ||<   ||d<   ||d<   |S )zZUpdate the confirmation status of masklets based on the current frame's detection results.r  r   r  zGot r  c                    i | ]\  }}||	S rX   rX   )rZ   r   rz  s      r7   r  zQSAM3VideoSemanticPredictor.update_masklet_confirmation_status.<locals>.<dictcomp>9  s     c c cf c c cr8   c                     g | ]
}|         S rX   rX   )rZ   rz  obj_id_to_updated_idxs     r7   r]   zQSAM3VideoSemanticPredictor.update_masklet_confirmation_status.<locals>.<listcomp>=  s    VVVv"6*VVVr8   r   )r  r   r   )rw   r  r@   rv  r   r  r  	full_like
zeros_liker  r  r  	CONFIRMED)r3   r  rj  rk  rd  re  confirmation_datastatus_prevconsecutive_det_num_prevprev_elem_is_in_updatedprev_elem_obj_ids_in_updatedprev_elem_inds_in_updatedunconfirmed_valr   r  
is_matchedr  change_to_confirmedr  s                     @r7   rw  z=SAM3VideoSemanticPredictor.update_masklet_confirmation_status'  s    %%;< (1#45J#K  $8$>>>>F;$FF*>*DFF ?>> !d c	Ja@b@b c c c"$'*>@W"X"X';<S'T$$&HVVVV9UVVV(%
 %
 %
!
 *5/RRR,78O,P() m,CDD9QRi9j56
 W4oFF
#=#D#D#F#F 	P 	P"'"9;NOOOJJ hz3F3JANN 2T5ee&*n"#&,(#3F/0r8   	ckpt_pathr   r  c                    t          j        |dd          d         }|                     ||          \  }}t          |          dk    st          |          dk    rt	          j        d|d|           d S t	          j        d	           d S )
Nr(  T)map_locationweights_onlyrJ   r  r   zLoaded ckpt with missing_keys=z, unexpected_keys=z;Loaded ckpt successfully without missing or unexpected keys)r>   loadload_state_dictr`   r   rm  info)r3   r"  r  sdmissing_keysunexpected_keyss         r7   _load_checkpointz+SAM3VideoSemanticPredictor._load_checkpointW  s    Z	DIII'R(,(<(<R(<(O(O%o|q  C$8$81$<$<NR|RRRRSSSSSKUVVVVVr8   c                &     | j         j        di |S )NrX   )rJ   _encode_prompt)r3   rr   s     r7   r.  z)SAM3VideoSemanticPredictor._encode_prompt_  s    (tz(226222r8   c                   d|cxk    rt          |           k    sn J |dk    rt          j        g t          j                  S |t          |           k    r| S t          j        ||                    ddd         }| |d|                  } | S )zDrop a few new detections based on the maximum number of objects. We drop new objects based on their
        detection scores, keeping the high-scoring ones and dropping the low-scoring ones.
        r   Nr:   )r`   r@   r   r  argsort)rh  r`  num_to_keepscore_orders       r7   rn  z7SAM3VideoSemanticPredictor._drop_new_det_with_obj_limitb  s    
 K77773#7#7777777!8B)))#o...."" j!?@@2F)+l{l*CDr8   r4  r6  r  r  )FNr5  )r  )T)r.   rI  r  rI  r{  rJ  r  rJ  r  r;  r  r   r  r  r  r\  r  r;  )r&  )r.   rI  r  rI  r  r   r  r;  )r{  rJ  r  r  r  rB  )
r  rK  rL  rM  r  r  r  rB  r  rI  )r{  rJ  r  r;  r  rK  r  rI  r  rI  r  rB  r  r  r,  )r{  rJ  r  rI  r  r\  r	  r\  ri  r  r  r;  )
r{  rJ  r  rJ  r  rK  r  r  r  rB  ri   )
r  rK  r  rI  r  rB  r  rB  r  r  )NF)
r  rI  r  rM  r  rM  r{  rH  r  r;  )r  r  r{  rJ  )r_  rI  r`  r  ra  rI  rb  r  )r{  rJ  r  r;  rd  r  re  r  rf  r  rg  r  r  r\  )r  r  r{  rJ  rd  rI  )
r{  rJ  r  rJ  r  rM  r  rI  r  r  )r  r  r  rM  )
r  r\  rj  r  rk  r  rd  r  re  r  )r"  r   r  r;  )1r8  r9  r:  r;  rW  r  r  r  r  r  r  rP  r   r   r+   r   r  r<  rs  rs   r  r  r   r  r  r  r0  r  r2  r3  r!  r[  r"  rs  r#  r$  r  rE  rl  rp  rt  r  r  r   rw  r,  r.  rn  r=  r>  s   @r7   r  r  	  s
       CCOLNOKI  N
 F "& #&  !  !AD37%*',$&$) 56'*&)WVC VC VC VC VC VC VCp= = = = = =^ ^ ^ ^ ^ 4 4 \40F F F F F3 3 3j4 4 4 4l  % % % %N   4 &*i
 i
 i
 i
 i
V    \
 
 
 

 
 
.9 9 9"7 7 7 7,($ ($ ($ ($TR9 R9 R9 R9v D, D, D, D, D,L"$ "$ "$ "$H  -1$ $ $ $ \$V !%B B B B BHD D D D8C
 C
 C
 C
Jm/ m/ m/ m/^81 81 81 81t*$ *$ *$ *$X0 0 0 0$"  "  " H. . . .`W W W W W3 3 3   \    r8   r  )6r;  
__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   r@  rk  r.  rf  rw  r  r  rX   r8   r7   <module>rA     sL    # " " " " " 0 0 0 0 0 0 0 0             



               . . . . . . 6 6 6 6 6 6 . . . . . . 6 6 6 6 6 6 6 6 6 6 7 7 7 7 7 7 7 7 M M M M M M M M
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 + * * * * *@
' @
' @
' @
' @
' @
' @
' @
'FKC KC KC KC KCI KC KC KC\AG AG AG AG AG AG AG AGH I
 I
 I
 I
 I
m I
 I
 I
X
R R R R RM R R R0I  I  I  I  I M I  I  I X3/ 3/ 3/ 3/ 3/+] 3/ 3/ 3/lJ J J J J!6 J J J J Jr8   