o
    WhA                    @   s   d Z ddlmZ ddlZddlZddlm  mZ	 ddl
mZ ddlmZ ddl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 deZ"G dd de"Z#G dd de#Z$d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.
    )OrderedDictN)	LetterBox)BasePredictor)Results)DEFAULT_CFGops)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)	build_samc                       s   e Zd ZdZeddf fdd	Zdd Zdd Zd-d
dZd-ddZ	d.ddZ
										d/ddZd0ddZdd Zdd  Z fd!d"Zd#d$ Zd%d& Zd'd( Zd)d* Zed1d+d,Z  ZS )2	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): 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: Prepares input images for model inference.
        pre_transform: Performs initial transformations on the input image.
        inference: Performs segmentation inference based on input prompts.
        prompt_inference: Internal function for prompt-based segmentation inference.
        generate: Generates segmentation masks for an entire image.
        setup_model: Initializes the SAM model for inference.
        get_model: Builds and returns a SAM model.
        postprocess: Post-processes model outputs to generate final results.
        setup_source: Sets up the data source for inference.
        set_image: Sets and preprocesses a single image for inference.
        get_im_features: Extracts image features using the SAM image encoder.
        set_prompts: Sets prompts for subsequent inference.
        reset_image: Resets the current image and its features.
        remove_small_regions: Removes small disconnected regions and holes from masks.

    Examples:
        >>> predictor = Predictor()
        >>> predictor.setup_model(model_path="sam_model.pt")
        >>> predictor.set_image("image.jpg")
        >>> bboxes = [[100, 100, 200, 200]]
        >>> results = predictor(bboxes=bboxes)
    Nc                    sT   |du ri }| tdddd t ||| d| j_d| _d| _i | _d| _	dS )a  
        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.

        Examples:
            >>> predictor_example = Predictor(cfg=DEFAULT_CFG)
            >>> predictor_example_with_imgsz = Predictor(overrides={"imgsz": 640})
            >>> predictor_example_with_callback = Predictor(_callbacks={"on_predict_start": custom_callback})
        Nsegmentpredictr
   )taskmodebatchTF)
updatedictsuper__init__argsretina_masksimfeaturespromptssegment_allselfcfg	overrides
_callbacks	__class__ R/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/models/sam/predict.pyr   P   s   
zPredictor.__init__c                 C   s   | j dur| j S t|tj }|r/t| |}|ddddf d}t|}t	|}|
| j}| jjr=| n| }|rK|| j | j }|S )a  
        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.

        Args:
            im (torch.Tensor | List[np.ndarray]): Input image(s) in BCHW tensor format or list of HWC numpy arrays.

        Returns:
            im (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modelfp16halffloatmeanstd)r&   r!   
not_tensorr,   r,   r-   
preprocessl   s   


zPredictor.preprocessc                    s8   t |dks
J dt| jjddd  fdd|D S )a9  
        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
   z6SAM model does not currently support batched inferenceF)autocenterc                    s   g | ]} |d qS ))imager,   .0x	letterboxr,   r-   
<listcomp>   s    z+Predictor.pre_transform.<locals>.<listcomp>)lenr   r   imgszr&   r!   r,   rJ   r-   r6      s   zPredictor.pre_transformFc           	      O   s|   | j d|}| j d|}| j d|}| j d|}tdd |||fD r4| 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:
            (np.ndarray): The output masks in shape (C, H, W), where C is the number of generated masks.
            (np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
            (np.ndarray): Low-resolution logits of shape (C, H, W) for subsequent inference, where H=W=256.

        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                 s   s    | ]}|d u V  qd S Nr,   rH   ir,   r,   r-   	<genexpr>       z&Predictor.inference.<locals>.<genexpr>)r#   popallgenerateprompt_inference)	r&   r!   rP   rQ   rS   rR   multimask_outputr   kwargsr,   r,   r-   	inference   s   zPredictor.inferencec                 C   s   | j du r
| |n| j }| |jdd ||||\}}}}|dur'||fnd}| jj|||d\}}	| jj|| jj ||	|d\}
}|
dd|ddfS )aP  
        Performs 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.

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.

        Returns:
            (np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
            (np.ndarray): 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)
        Nr0   rQ   boxesrR   )image_embeddingsimage_pesparse_prompt_embeddingsdense_prompt_embeddingsr]   r   r
   )	r"   get_im_features_prepare_promptsshaper<   prompt_encodermask_decoderget_dense_peflatten)r&   r!   rP   rQ   rS   rR   r]   r"   sparse_embeddingsdense_embeddings
pred_maskspred_scoresr,   r,   r-   r\      s   $


zPredictor.prompt_inferencec                 C   s~  | j d d jdd }| jrdnt|d |d  |d |d  }|durtj|tj| jd}|jdkr9|d n|}|du rIt	
|jdd }tj|tj| jd}|jd |jd ksnJ d	|jd  d
|jd  d||9 }|jdkr|dddddf |dddf }}|durtj|tj| jd}|jdkr|d n|}||9 }|durtj|tj| jdd}||||fS )a  
        Prepares and transforms the input prompts for processing based on the destination shape.

        Args:
            dst_shape (tuple): The target shape (height, width) for the prompts.
            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, Optional): Masks for the objects, where each mask is a 2D array.

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.

        Returns:
            (tuple): A tuple containing transformed bounding boxes, points, labels, and masks.
        r
   r   Nr0   g      ?dtyper;   r.   zNumber of points z should match number of labels .)r   rh   r$   minr2   	as_tensorfloat32r;   ndimr4   onesint32	unsqueeze)r&   	dst_shaperP   rQ   rS   rR   	src_shaperr,   r,   r-   rg      s*   ,
(zPredictor._prepare_promptsr   g?r
       @   )\(?ffffff?ffffff?c           -   	   C   s  ddl }d| _|jdd \}}t||f||\}}|du r$t|||}g g g g f\}}}}t||D ]
\}}|\}}}}|| || }}tj|| |jd}t	
||gg}tj|d||||f ||fddd	}|| | } g g g }!}"}#t|| D ]w\}$| j||$dd
\}%}&tj|%d ||fddd	d }%|&|k}'|%|' |&|' }%}&t|%| jj|
}(|(|	k}'|%|' |&|' }%}&|%| jjk}%t|% })t|)|dd||g }*t|*s|)|* |%|* |&|* })}%}&|!|% |#|) |"|& qt|!}!t|#}#t|"}"|j|#|"| jj}+t|#|+ |}#t|!|+ |||}!|"|+ }"||! ||# ||" ||t|! q3t|}t|}t|}t|}t|dkrtd| },|j||,|}+||+ ||+ ||+ }}}|||fS )aY  
        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   NTr0   r;   .bilinearF)r   align_corners)rQ   r]   r
   ) torchvisionr$   rh   r   r   zipr2   tensorr;   r4   arrayFinterpolater   r\   r   r<   mask_thresholdr   r?   r   rZ   appendcatr   nmsr   iour   r   expandrM   )-r&   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_idxsro   rp   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_bboxesrQ   	pred_mask
pred_scoreidxstability_score	pred_bbox	keep_maskkeepscoresr,   r,   r-   r[   )  sj   +(














zPredictor.generateTc                 C   s   t | jj|d}|du r|  }|  ||| _|| _tg d	ddd|| _
tg d	ddd|| _d| j_d| j_d| j_d| j_d	| _dS )
af  
        Initializes 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@Fr   T)r   r   r;   	get_modelevalr:   r<   r2   r   viewr@   rA   pttritonstrider=   done_warmup)r&   r<   r   r;   r,   r,   r-   setup_model  s     
zPredictor.setup_modelc                 C      t | jjS )zRRetrieves or builds the Segment Anything Model (SAM) for image segmentation tasks.r   r   r<   r&   r,   r,   r-   r        zPredictor.get_modelc              
   C   sh  |dd \}}| j r|d nd}ttdd tt|D }t|ts*t|}g }t	|g|| j
d D ]x\}	}
}t|	dkrMdtjd|jd}	}nUtj|	d  |
jdd dd	d }	|	| jjk}	|dur|tj|jdd | |
jdd	}nt|	}tjt|tj|jd
}tj||dddf |dddf gdd}|t|
|||	|d q6d| _ |S )a  
        Post-processes 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[torch.Tensor]): 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:
            results (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)
        Nr0   c                 s   s    | ]}t |V  qd S rT   )strrU   r,   r,   r-   rW     rX   z(Predictor.postprocess.<locals>.<genexpr>r   )r      r   F)paddingrq   r.   dim)pathnamesrR   ra   )r$   r   	enumeraterangerM   r1   listr   convert_torch2numpy_batchr   r   r2   zerosr;   scale_masksr?   rh   r<   r   scale_boxesr   arangerz   r   r   r   )r&   predsimg	orig_imgsro   rp   r   r   resultsrR   orig_imgimg_pathclsr,   r,   r-   postprocess  s&   

&$,zPredictor.postprocessc                    s   |durt  | dS dS )a  
        Sets up the data source for inference.

        This method configures the data source from which images will be fetched for inference. It supports
        various input types such as image files, directories, video files, and other compatible data sources.

        Args:
            source (str | Path | None): The path or identifier for the image data source. Can be a file path,
                directory path, URL, or other supported source types.

        Examples:
            >>> predictor = Predictor()
            >>> predictor.setup_source("path/to/images")
            >>> predictor.setup_source("video.mp4")
            >>> predictor.setup_source(None)  # Uses default source if available

        Notes:
            - If source is None, the method may use a default source if configured.
            - The method adapts to different source types and prepares them for subsequent inference steps.
            - Supported source types may include local files, directories, URLs, and video streams.
        N)r   setup_source)r&   sourcer*   r,   r-   r     s   zPredictor.setup_sourcec                 C   d   | j du r| jdd | | t| jdksJ d| jD ]}| |d }| || _ dS dS )a  
        Preprocesses and sets 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.

        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.
        Nr<   r
   ,`set_image` only supports setting one image!r<   r   r   rM   datasetrC   rf   r"   r&   rF   r   r!   r,   r,   r-   	set_image  s   


zPredictor.set_imagec                 C   sP   t | jttfr| jd | jd ksJ d| j d| j| j | j|S )z[Extracts image features using the SAM model's image encoder for subsequent mask prediction.r   r
   z3SAM models only support square image size, but got rt   )r1   rN   tupler   r<   	set_imgszimage_encoderrO   r,   r,   r-   rf   )  s
   &zPredictor.get_im_featuresc                 C   s
   || _ dS )z1Sets prompts for subsequent inference operations.N)r#   )r&   r#   r,   r,   r-   set_prompts1  s   
zPredictor.set_promptsc                 C   s   d| _ d| _dS )zRResets the current image and its features, clearing them for subsequent inference.N)r!   r"   r   r,   r,   r-   reset_image5  s   
zPredictor.reset_imagec                 C   s   ddl }t| dkr| S g }g }| D ]8}|  tj}t||dd\}}| }t||dd\}}|o7| }|t	
|d |t| qt	j|dd}t|}	|j|	 t	
||}
||
 j| j| jd|
fS )a`  
        Remove small disconnected regions and holes from segmentation masks.

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

        Args:
            masks (torch.Tensor): Segmentation masks to be processed, with shape (N, H, W) where N is the number of
                masks, H is height, and W is width.
            min_area (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   )r;   rr   )r   rM   cpunumpyastyper4   uint8r   r   r2   rv   r{   r?   r   r   r   r   r:   r;   rr   )rR   min_area
nms_threshr   	new_masksr   maskchanged	unchangedra   r   r,   r,   r-   r   :  s"   
zPredictor.remove_small_regions)NNNNFNNNN)
r   r   r
   Nr   r   r   r   r   r   )NT)r   r   )__name__
__module____qualname____doc__r   r   rC   r6   r_   r\   rg   r[   r   r   r   r   r   rf   r   r   staticmethodr   __classcell__r,   r,   r*   r-   r   %   s:    *!

'
0-

p3!r   c                       sX   e Zd ZdZg dZdd Z						ddd	Zd fd
d	Zdd Zdd Z	  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[int, int]]): 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[str, torch.Tensor]): Cached image features for efficient inference.
        segment_all (bool): Flag to indicate if all segments should be predicted.
        prompts (dict): Dictionary to store various types of prompts for inference.

    Methods:
        get_model: Retrieves and initializes the SAM2 model.
        prompt_inference: Performs image segmentation inference based on various prompts.
        set_image: Preprocesses and sets a single image for inference.
        get_im_features: Extracts and processes image features using SAM2's image encoder.

    Examples:
        >>> predictor = SAM2Predictor(cfg)
        >>> predictor.set_image("path/to/image.jpg")
        >>> bboxes = [[100, 100, 200, 200]]
        >>> result = predictor(bboxes=bboxes)[0]
        >>> print(f"Predicted {len(result.masks)} masks with average score {result.boxes.conf.mean():.2f}")
    ))   r  )   r  )r   r   c                 C   r   )z[Retrieves and initializes the Segment Anything Model 2 (SAM2) for image segmentation tasks.r   r   r,   r,   r-   r     r   zSAM2Predictor.get_modelNFr.   c              	      s   | j du r
| |n| j }| |jdd ||||\}}}|dur&||fnd}| jj|d|d\}	}
|duo?|d jd dk} fdd|d D }| jj|d	   d| jj |	|
|||d
\}}}}|	dd|	ddfS )a  
        Performs image segmentation inference based on various prompts using SAM2 architecture.

        This method leverages the Segment Anything Model 2 (SAM2) to generate segmentation masks for input images
        based on provided prompts such as bounding boxes, points, or existing masks. It supports both single and
        multi-object prediction scenarios.

        Args:
            im (torch.Tensor): Preprocessed input image tensor with shape (N, C, H, W).
            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 (np.ndarray | None): Low-resolution masks from previous predictions with shape (N, H, W).
            multimask_output (bool): Flag to return multiple masks for ambiguous prompts.
            img_idx (int): Index of the image in the batch to process.

        Returns:
            (np.ndarray): Output masks with shape (C, H, W), where C is the number of generated masks.
            (np.ndarray): Quality scores for each mask, with length C.

        Examples:
            >>> predictor = SAM2Predictor(cfg)
            >>> image = torch.rand(1, 3, 640, 640)
            >>> bboxes = [[100, 100, 200, 200]]
            >>> result = predictor(image, bboxes=bboxes)[0]
            >>> print(f"Generated {result.masks.shape[0]} masks with average score {result.boxes.conf.mean():.2f}")

        Notes:
            - The method supports batched inference for multiple objects when points or bboxes are provided.
            - Input prompts (bboxes, points) are automatically scaled to match the input image dimensions.
            - When both bboxes and points are provided, they are merged into a single 'points' input for the model.
        Nr0   r`   r   r
   c                    s   g | ]	}|   d qS )r   )r{   )rH   
feat_levelimg_idxr,   r-   rL     s    z2SAM2Predictor.prompt_inference.<locals>.<listcomp>high_res_featsimage_embed)rb   rc   rd   re   r]   repeat_imagehigh_res_features)
r"   rf   rg   rh   r<   sam_prompt_encodersam_mask_decoderr{   rk   rl   )r&   r!   rP   rQ   rS   rR   r]   r  r"   rm   rn   batched_moder	  ro   rp   _r,   r  r-   r\     s(   *"

zSAM2Predictor.prompt_inferencec                    s   t  |||||\}}}}|durH|ddd}tjddggtj|jdt|d}|durCtj	||gdd}tj	||gdd}n||}}|||fS )a  
        Prepares and transforms the input prompts for processing based on the destination shape.

        Args:
            dst_shape (tuple): The target shape (height, width) for the prompts.
            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, Optional): Masks for the objects, where each mask is a 2D array.

        Raises:
            AssertionError: If the number of points don't match the number of labels, in case labels were passed.

        Returns:
            (tuple): A tuple containing transformed points, labels, and masks.
        Nr.   r0   r/   rq   r
   r   )
r   rg   r   r2   r   rz   r;   r   rM   r   )r&   r|   rP   rQ   rS   rR   bbox_labelsr*   r,   r-   rg     s   &

zSAM2Predictor._prepare_promptsc                 C   r   )a#  
        Preprocesses and sets a single image for inference using the SAM2 model.

        This method initializes the model if not already done, configures the data source to the specified image,
        and preprocesses the image for feature extraction. It supports setting only one image at a time.

        Args:
            image (str | np.ndarray): Path to the image file as a string, or a numpy array representing the image.

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

        Examples:
            >>> predictor = SAM2Predictor()
            >>> predictor.set_image("path/to/image.jpg")
            >>> predictor.set_image(np.array([...]))  # Using a numpy array

        Notes:
            - This method must be called before performing any inference on a new image.
            - The method caches the extracted features for efficient subsequent inferences on the same image.
            - Only one image can be set at a time. To process multiple images, call this method for each new image.
        Nr   r
   r   r   r   r,   r,   r-   r     s   


zSAM2Predictor.set_imagec                    s   t  jttfr jd  jd ksJ d j d j j  fdddD  _ j|} j|\}}}} jj	rJ|d  jj
 |d< d	d t|d
d
d  jd
d
d D d
d
d }|d |d
d dS )zMExtracts image features from the SAM image encoder for subsequent processing.r   r
   z5SAM 2 models only support square image size, but got rt   c                    s    g | ]  fd dj D qS )c                    s   g | ]}|d    qS )   r,   rG   rV   r,   r-   rL     s    z<SAM2Predictor.get_im_features.<locals>.<listcomp>.<listcomp>)rN   )rH   r   r  r-   rL     s     z1SAM2Predictor.get_im_features.<locals>.<listcomp>)r
   r0   r  r.   c                 S   s.   g | ]\}}| d ddjd dg|R  qS )r
   r0   r   r.   )permuter   )rH   feat	feat_sizer,   r,   r-   rL   %  s    N)r  r  )r1   rN   r   r   r<   r   _bb_feat_sizesforward_image_prepare_backbone_featuresdirectly_add_no_mem_embedno_mem_embedr   )r&   r!   backbone_outr  vision_featsfeatsr,   r   r-   rf     s   &zSAM2Predictor.get_im_features)NNNNFr.   r   )r   r   r   r   r  r   r\   rg   r   rf   r   r,   r,   r*   r-   r   o  s    
D r   c                       s   e Zd ZdZeddf fdd	Z fddZd&ddZ fd	d
Ze	 				d'ddZ
e	 dd Zedd Zd(ddZdd Z	d)ddZdd Z		d*ddZdd Zd d! Zd"d# Zd$d% Z  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.

    Args:
        cfg (dict, Optional): Configuration settings for the predictor. Defaults to DEFAULT_CFG.
        overrides (dict, Optional): Additional configuration overrides. Defaults to None.
        _callbacks (list, Optional): Custom callbacks to be added. Defaults to None.

    Note:
        The `fill_hole_area` attribute is defined but not used in the current implementation.
    Nc                    s>   t  ||| i | _d| _d| _d| _| jd | j dS )a  
        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.

        Examples:
            >>> predictor = SAM2VideoPredictor(cfg=DEFAULT_CFG)
            >>> predictor_example_with_imgsz = SAM2VideoPredictor(overrides={"imgsz": 640})
            >>> predictor_example_with_callback = SAM2VideoPredictor(_callbacks={"on_predict_start": custom_callback})
        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_stater%   r*   r,   r-   r   F  s   zSAM2VideoPredictor.__init__c                    s   t   }|d |S )z
        Retrieves and configures the model with binarization enabled.

        Note:
            This method overrides the base class implementation to set the binarize flag to True.
        T)r   r   set_binarize)r&   r<   r*   r,   r-   r   _  s   

zSAM2VideoPredictor.get_modelc              
   C   s  | j d|}| j d|}| j d|}| jj}|| jd< | jd }t|d dkrq| |jdd	 ||||\}}}|d	urYtt|D ]}| j	|||g ||g |d
 qFn|d	urqtt|D ]}| j	|||g |d qc| 
  | jd }	t| jd }
t|d dkrtd||	d v rd}|| | }| jr| js|
dkr| | n$||	d v rd}|| | }nd}| j|||
dd	d	ddd}||| |< | ||| | jd | |d dd}||| jjkddk }|tjt||j|j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:
            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:
            (np.ndarray): The output masks in shape CxHxW, where C is the number of generated masks.
            (np.ndarray): An array of length C containing quality scores predicted by the model for each mask.
        rP   rQ   rR   r!   output_dictcond_frame_outputsr   r0   N)obj_idrQ   rS   	frame_idx)r'  rR   r(  consolidated_frame_indsobj_idx_to_idz/No points are provided; please add points firstr
   non_cond_frame_outputsFT)r%  r(  
batch_sizeis_init_cond_framepoint_inputsmask_inputsreverserun_mem_encoderframes_already_trackedro   )r
   r0   rq   )r#   rY   r   framer  rM   rg   rh   r   add_new_promptspropagate_in_video_preflightRuntimeErrorr   r!   _clear_non_cond_mem_around_input_run_single_frame_inference_add_output_per_objectr   rl   r<   r   sumr2   ry   rr   r;   )r&   r!   rP   rQ   rS   rR   r3  r%  rV   r)  r,  storage_keycurrent_outro   r,   r,   r-   r_   j  s\   

" 


zSAM2VideoPredictor.inferencec                    s\   t  |||}| jr,|D ]}|jdu st|jdkrq| j|jjdd |j_q|S )a(  
        Post-processes 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]): The predictions from the model.
            img (torch.Tensor): The processed image tensor.
            orig_imgs (List[np.ndarray]): The original images before processing.

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

        Note:
            If `non_overlap_masks` is True, the method applies constraints to ensure non-overlapping masks.
        Nr   )	r   r   r  rR   rM   r<   "_apply_non_overlapping_constraintsdatar{   )r&   r   r   r   r   resultr*   r,   r-   r     s    zSAM2VideoPredictor.postprocessr   c                 C   s  |du |du A sJ d|  |}d}d}|dur)||d}|| jd | |< d}|| jd | |< | j| | |d || jd v}	| jd | }
| jd | }|	pW| jj}|r\d	nd
}d}|dur|| |px|
d	 |px|
d
 |}|dur|ddur|d j| jdd}|dd | j	|
|d|	||dd|d	}||| |< | j
||dd}|d dd}|ddtjd|j|jdfS )a  
        Adds 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. Defaults to None.
            labels (torch.Tensor, Optional): The labels corresponding to the points. Defaults to None.
            masks (torch.Tensor, optional): Binary masks for the object. Defaults to None.
            frame_idx (int, optional): The index of the frame to which the prompts are applied. Defaults to 0.

        Returns:
            (tuple): A tuple containing the flattened predicted masks and a tensor of ones indicating the number of objects.

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

        Note:
            - 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_objr2  output_dict_per_objtemp_output_dict_per_objr&  r+  ro   T)r;   non_blockingg      @g      @@r
   F)	r%  r(  r,  r-  r.  r/  r0  r1  prev_sam_mask_logitsis_condr1  r   rq   )_obj_id_to_idxr  rY   r<   !add_all_frames_to_correct_as_condgetr:   r;   clamp_r8  #_consolidate_temp_output_across_objrl   r2   ry   rr   )r&   r'  rQ   rS   rR   r(  obj_idxr.  pop_keyr-  obj_output_dictobj_temp_output_dictrI  r;  rG  prev_outr<  consolidated_outro   r,   r,   r-   r4    sX   #

 z"SAM2VideoPredictor.add_new_promptsc                 C   s  d| j d< t| j d }| j d }| j d }| j d }dD ]X}|r#dnd	}t }| D ]}|||   q,|| | |D ]&}	| j|	|dd
}
|
|| |	< | |	|
| | jrg| j	sb|dkrg| 
|	 qA| D ]}||   qlq|d D ]
}	|d	 |	d qz| j d  D ]}|d D ]
}	|d	 |	d qq|d D ]}	|	|d v sJ |d	 |	 q|d |d	 B }t }| j d  D ]	}||  q| j d  D ]	}||  q||ksJ dS )a  
        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.
        Ttracking_has_startedr*  rE  r%  r)  >   FTr&  r+  rH  r
   NrD  r@  rC  )r  rM   setvaluesr   keysrN  r9  r   r!  r7  clearrY   discard)r&   r,  rE  r%  r)  rI  r;  temp_frame_indsrR  r(  rT  rQ  all_consolidated_frame_indsinput_frames_indspoint_inputs_per_framemask_inputs_per_framer,   r,   r-   r5  1  sP   




z/SAM2VideoPredictor.propagate_in_video_preflightc                 C   sr   t | jdkr	dS | jdusJ | jjdksJ | jji i i t t g i i di i t t ddg 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 (SAM2VideoPredictor): The predictor object for which to initialize the state.
        r   Nvideor&  r+  F)
num_framesr@  rC  	constantsobj_id_to_idxr*  obj_idsr%  rD  rE  r)  rU  r2  )rM   r  r   r   framesr   rV  )	predictorr  r,   r,   r-   r#  x  s.   
zSAM2VideoPredictor.init_stater
   c                 C   s   | j |}|dkr:t|d D ]\}}||ddd|d |< qt|d D ]\}}||ddd}||d |< q'| j |\}}}	}
||	|
fS )a8  
        Extracts and processes 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. Defaults to 1.

        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[int])): A list containing the sizes of the extracted features.

        Note:
            - 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
   backbone_fpnr.   vision_pos_enc)r<   r  r   r   r  )r&   r!   r   r  rV   r  posr  	vis_featsvis_pos_embed
feat_sizesr,   r,   r-   rf     s   
z"SAM2VideoPredictor.get_im_featuresc                 C   s   | j d |d}|dur|S | j d  }|rZt| j d }|| j d |< || j d |< t| j d | j d< i | j d |< i | j d |< i i d| j d	 |< i i d| j d
 |< |S td| d| j d  d)a5  
        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.

        Returns:
            obj_idx (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.

        Note:
            - 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.
        rd  NrU  r*  re  r@  rC  ra  rD  rE  zCannot add new object id z1 after tracking starts. All existing object ids: z4. Please call 'reset_state' to restart from scratch.)r  rL  rM   r   r6  )r&   r'  rO  allow_new_objectr,   r,   r-   rJ    s.   z!SAM2VideoPredictor._obj_id_to_idxc
                 C   s   |  | jd |\}
}}|du s|du sJ | jj|||
|||||| jd |||	d}|d }|dur?|jtj| jdd|d< | |d |d< |S )	ah  
        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, Optional): Input points and their labels. Defaults to None.
            mask_inputs (torch.Tensor, Optional): Input binary masks. Defaults to None.
            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, Optional): Previous mask logits for the current object. Defaults to None.

        Returns:
            current_out (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, or neither is provided.

        Note:
            - 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!   Nrb  r(  r-  current_vision_featscurrent_vision_pos_embedsrm  r.  r/  r%  rb  track_in_reverser1  rG  maskmem_featuresTrr   r;   rF  maskmem_pos_enc)	rf   r  r<   
track_stepr:   r2   float16r;   _get_maskmem_pos_enc)r&   r%  r(  r,  r-  r.  r/  r0  r1  rG  rp  rq  rm  r<  rs  r,   r,   r-   r8    s2   '




z.SAM2VideoPredictor._run_single_frame_inferencec                    st   | j d }|dur8d|vr t|tsJ dd |D }||d< n|d }|d d  dkr8 fdd|D }|S )	aD  
        Caches and manages 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] or None): The positional encoding for mask memory.
                Should be a list of tensors or None.

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

        Note:
            - 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.
        rc  Nru  c                 S   s   g | ]
}|d d   qS )Nr
   )clonerG   r,   r,   r-   rL   `      z;SAM2VideoPredictor._get_maskmem_pos_enc.<locals>.<listcomp>r   r
   c                    s   g | ]
}|  d d d qS )r.   )r   rG   r,  r,   r-   rL   g  rz  )r  r1   r   size)r&   out_maskmem_pos_encmodel_constantsru  r,   r{  r-   rx  B  s   

z'SAM2VideoPredictor._get_maskmem_pos_encFc              
   C   s  t | jd }|rdnd}ddtj|d| jd d | jd d fdtj| jd	tj|| jjfdtj| jd	tj|dfd
tj| jd	d}t	|D ]Q}| jd | }| jd | }	|| 
|pl|	d 
|pl|	d 
|}
|
du r|r| ||d ||d < qH|
d |d ||d < |
d |d ||d < qH|rtj|d | jddd}| jjr| j|}| j||d|d d\|d< |d< |S )a  
        Consolidates 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.
                Defaults to False.
            run_mem_encoder (bool, Optional): Specifies whether to run the memory encoder after
                consolidating the outputs. Defaults to False.

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

        Note:
            - The method initializes the consolidated output with placeholder values for missing objects.
            - It searches for outputs in both the temporary and main output dictionaries.
            - If `run_mem_encoder` is True, it applies non-overlapping constraints and re-runs the memory encoder.
            - The `maskmem_features` and `maskmem_pos_enc` are only populated when `run_mem_encoder` is True.
        r*  r&  r+  Nr
   r   r  g      )r|  
fill_valuerr   r;   g      $@)rs  ru  ro   obj_ptrobject_score_logitsrE  rD  r  ro   r   F)r|  r   r   Tr  )r,  high_res_masksis_mask_from_ptsr  rs  ru  )rM   r  r2   fullrN   rw   r;   r<   
hidden_dimr   rL  _get_empty_mask_ptrr   r   non_overlap_masks_for_mem_encr=  _run_memory_encoder)r&   r(  rI  r1  r,  r;  rT  rO  rR  rQ  outr  r,   r,   r-   rN  j  sj   
z6SAM2VideoPredictor._consolidate_temp_output_across_objc                 C   sd   |  | jd \}}}| jj|d|||dtjddg| jR tj| jdi | jd dddd}|d	 S )
aP  
        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.

        Returns:
            (torch.Tensor): A tensor representing the dummy object pointer generated from the empty mask.
        r!   TNr
   rq   rb  Fro  r  )	rf   r  r<   rv  r2   r   rN   rw   r;   )r&   r(  rp  rq  rm  r<  r,   r,   r-   r    s    z&SAM2VideoPredictor._get_empty_mask_ptrc           
      C   sT   |  | jd |\}}}| jj|||||d\}}	| |	}	|jtj| jdd|	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.

        Returns:
            (tuple[torch.Tensor, torch.Tensor]): A tuple containing the encoded mask features and positional encoding.
        r!   )rp  rm  pred_masks_high_resr  r  Trt  )	rf   r  r<   _encode_new_memoryrx  r:   r2   rw  r;   )
r&   r,  r  r  r  rp  r  rm  rs  ru  r,   r,   r-   r    s   

	z&SAM2VideoPredictor._run_memory_encoderc           	         s   |d }|du st |tjsJ |d }|du st |tsJ | jd  D ]9\}}t||d  dd|d   |d   d}|durJ|  |d< |durY fd	d
|D |d< ||| |< q&dS )a  
        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.
        rs  Nru  rD  r
   ro   r  )rs  ru  ro   r  c                    s   g | ]}|  qS r,   r,   rG   	obj_slicer,   r-   rL   .  s    z=SAM2VideoPredictor._add_output_per_object.<locals>.<listcomp>)r1   r2   r3   r   r  itemsslice)	r&   r(  r<  r;  rs  ru  rO  rQ  obj_outr,   r  r-   r9    s"   

z)SAM2VideoPredictor._add_output_per_objectc                 C   sz   | j j}||| j j  }||| j j  }t||d D ]}| jd d |d | jd  D ]
}|d |d q/q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.
        r
   r%  r+  NrD  )r<   memory_temporal_stride_for_evalnum_maskmemr   r  rY   rW  )r&   r(  r~   frame_idx_beginframe_idx_endtrQ  r,   r,   r-   r7  1  s   z3SAM2VideoPredictor._clear_non_cond_mem_around_inputr   )NNNr   )r
   rT   )FF)r   r   r   r   r   r   r   r_   r   r	   r4  r5  r   r#  rf   rJ  r8  rx  rN  r  r  r9  r7  r   r,   r,   r*   r-   r  ,  s8    
Gd
F

/>
K+
kr  )%r   collectionsr   r   r4   r2   torch.nn.functionalnn
functionalr   ultralytics.data.augmentr   ultralytics.engine.predictorr   ultralytics.engine.resultsr   ultralytics.utilsr   r   ultralytics.utils.torch_utilsr   r	   amgr   r   r   r   r   r   r   r   r   buildr   r   r   r  r,   r,   r,   r-   <module>   s(   	,    N >