o
    oi@                     @  s   d dl mZ d dlmZmZ d dl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 d d	lmZmZmZ d d
lmZ d dlmZ d dlmZ G dd dZdS )    )annotations)AnyOptionalN)LongestMaxSize)AugmentationSequential)PromptsSegmentationResults)Sam	SamConfig)Tensorpadtensor)KORNIA_CHECKKORNIA_CHECK_IS_TENSORKORNIA_CHECK_SHAPE)	normalize)Boxes)	Keypointsc                      s   e Zd ZdZ			dJdK fddZdLdMddZe dLdNddZdOddZ	dPd d!Z
dQd#d$Zdd%dRd+d,Z				dSdTd1d2Ze 					3	3dUdVd8d9ZdWd:d;Zd<d<d=ddd<d>dXdHdIZ  ZS )YVisualPrompteraW  Allow the user to run multiple query with multiple prompts for a model.

    At the moment, we just support the SAM model. The model is loaded based on the given config.

    For default the images are transformed to have their long side with size of the `image_encoder.img_size`. This
    Prompter class ensure to transform the images and the prompts before prediction. Also, the image is passed
    automatically for the method `preprocess_image`, which is responsible for normalize the image and pad it to have
    the right size for the SAM model :math:`(\text{image_encoder.img_size}, \text{image_encoder.img_size})`. For
    default the image is normalized by the mean and standard deviation of the SAM dataset values.

    Args:
        config: A model config to generate the model. Now just the SAM model is supported.
        device: The desired device to use the model.
        dtype: The desired dtype to use the model.

    Example:
        >>> # prompter = VisualPrompter() # Will load the vit h for default
        >>> # You can load a custom SAM type for modifying the config
        >>> prompter = VisualPrompter(SamConfig('vit_b'))
        >>> image = torch.rand(3, 25, 30)
        >>> prompter.set_image(image)
        >>> boxes = Boxes(
        ...    torch.tensor(
        ...         [[[[0, 0], [0, 10], [10, 0], [10, 10]]]],
        ...         device=prompter.device,
        ...         dtype=torch.float32
        ...    ),
        ...    mode='xyxy'
        ... )
        >>> prediction = prompter.predict(boxes=boxes)
        >>> prediction.logits.shape
        torch.Size([1, 3, 256, 256])

    NconfigOptional[SamConfig]deviceOptional[torch.device]dtypeOptional[torch.dtype]returnNonec                   s   t    |d u rtddd}t|tr=t|| _t| jjj	ddf}t
g d||dd | _t
g d	||dd | _nt| jj||d| _t|d
di| _|| _|| _d | _d | _d | _|   d S )Nvit_hT)
model_type
pretrainedg      ?)p)g33333^@gR]@gRY@)r   r      )g(\2M@g(\L@g     L@same_on_batch)super__init__r
   
isinstancer	   from_configmodelr   image_encoderimg_sizer   
pixel_mean	pixel_stdNotImplementedErrortor   
transformsr   r   _original_image_size_input_image_size_input_encoder_sizereset_image)selfr   r   r   r.   	__class__ R/home/ubuntu/.local/lib/python3.10/site-packages/kornia/contrib/visual_prompter.pyr$   G   s"   

zVisualPrompter.__init__xr   meanOptional[Tensor]stdc                 C  s   t |trt |trt|||}nt | jtr%t | jtr%t|| j| j}| jjj}||jd  }||jd  }t	|d|d|f}|S )aa  Normalize and pad a tensor.

        For normalize the tensor: will prioritize the `mean` and `std` passed as argument, if None will use the default
        Sam Dataset values.

        For pad the tensor: Will pad the tensor into the right and bottom to match with the size of
        `self.model.image_encoder.img_size`

        Args:
            x: The image to be preprocessed
            mean: Mean for each channel.
            std: Standard deviations for each channel.

        Returns:
            The image preprocessed (normalized if has mean and str available and padded to encoder size)

        r   )
r%   r   r   r*   r+   r'   r(   r)   shaper   )r3   r8   r9   r;   encoder_im_sizepad_hpad_wr6   r6   r7   preprocess_imagec   s   
zVisualPrompter.preprocess_imageimagec                 C  s   t |g d |   |jd |jd f| _| j|dgd}| jj| _|jd |jd f| _| |||}|jd |jd f| _	| j
|| _d| _dS )aE  Set the embeddings from the given image with `image_decoder` of the model.

        Prepare the given image with the selected transforms and the preprocess method.

        Args:
            image: RGB image. Normally images with range of [0-1], the model preprocess normalize the
                   pixel values with the mean and std defined in its initialization. Expected to be into a float32
                   dtype. Shape :math:`(3, H, W)`.
            mean: mean value of dataset for normalization.
            std: standard deviation of dataset for normalization.

        )3HWr<   r=   input	data_keysTN)r   r2   r>   r/   r.   _params_tfs_paramsr0   rB   r1   r'   r(   image_embeddingsis_image_set)r3   rC   r9   r;   r6   r6   r7   	set_image   s   

zVisualPrompter.set_image	keypointsKeypoints | Tensorlabelsr   c                 C  sR   t |jg d t |jddg t|jd |jd kd t|tr't|}|S )z:Validate the keypoints shape and ensure to be a Keypoints.)KN2rR   rS   r   z8The keypoints and labels should have the same batch size)r   datar   r>   r%   r   r   from_tensor)r3   rO   rQ   r6   r6   r7   _valid_keypoints   s   

zVisualPrompter._valid_keypointsboxesBoxes | Tensorr   c                 C  sP   t |trt|jddg t|dd}|jdkr|}|S t|jdddd}|S )zAValidate the boxes shape and ensure to be a Boxes into xyxy mode.rR   4xyxymode)r%   r   r   rU   r   r]   	to_tensor)r3   rX   
boxes_xyxyr6   r6   r7   _valid_boxes   s   

zVisualPrompter._valid_boxesmasksc                 C  s   t |g d |S )zValidate the input masks shape.)rR   1256rc   )r   )r3   ra   r6   r6   r7   _valid_masks   s   zVisualPrompter._valid_masksrH   promptsTensor | Boxes | KeypointsrI   Optional[list[str]]%dict[str, Tensor | Boxes | Keypoints]c                  sJ   | j ||| jd |d u rg }t ttfs g  fddt|D S )N)rI   paramsc                   s   i | ]	\}}| | qS r6   r6   ).0idxkeytransformed_promptsr6   r7   
<dictcomp>   s    z5VisualPrompter._transform_prompts.<locals>.<dictcomp>)r.   rK   r%   listtuple	enumerate)r3   rI   re   r6   rm   r7   _transform_prompts   s   z!VisualPrompter._transform_promptsOptional[Keypoints | Tensor]keypoints_labelsOptional[Boxes | Tensor]r   c                 C  s  g }g }t |ttfr t |tr | ||}|d || t |ttfr6| | |d || t |tr@| | | j|d|i}d|v rft |d trf|d 	 }t
|ret
|re||f}	nd}	d|v rt |d tr|d j	dd}
t
|
r|
}nd}t|	||dS )zMValidate and preprocess the given prompts to be aligned with the input image.rO   	bbox_xyxyrI   Nr[   r\   pointsrX   ra   )r%   r   r   rW   appendr   r`   rd   rs   r^   r   r   )r3   rO   ru   rX   ra   rI   to_transformrU   kpts_tensorry   _bboxbboxr6   r6   r7   preprocess_prompts   s4   






z!VisualPrompter.preprocess_promptsTmultimask_outputbooloutput_original_sizer   c                 C  s   t | jd | ||||}| jj|j|j|jd\}}	~| jj| j	| jj
 ||	|d\}
}t|
|}|rLt| jtrLt| jtrL|| j| j| j |S )as  Predict masks for the given image based on the input prompts.

        Args:
            keypoints: Point prompts to the model. Each point is in (X,Y) in pixels. Shape :math:`(K, N, 2)`. Where
                       `N` is the number of points and `K` the number of prompts.
            keypoints_labels: Labels for the point prompts. 1 indicates a foreground point and 0 indicates a background
                             point. Shape :math:`(K, N)`. Where `N` is the number of points, and `K` the number of
                             prompts.
            boxes: A box prompt to the model. If a tensor, should be in a xyxy mode. Shape :math:`(K, 4)`
            masks: A low resolution mask input to the model, typically coming from a previous prediction
                   iteration. Has shape :math:`(K, 1, H, W)`, where for SAM, H=W=256.
            multimask_output: If true, the model will return three masks. For ambiguous input prompts (such as a
                              single click), this will often produce better masks than a single prediction. If only
                              a single mask is needed, the model's predicted quality score can be used to select the
                              best mask. For non-ambiguous prompts, such as multiple input prompts,
                              multimask_output=False can give better results.
            output_original_size: If true, the logits of `SegmentationResults` will be post-process to match the
                                  original input image size.

        Returns:
            A prediction with the logits and scores (IoU of each predicted mask)

        zKAn image must be set with `self.set_image(...)` before `predict` be called!rx   )rL   image_pesparse_prompt_embeddingsdense_prompt_embeddingsr   )r   rM   r   r'   prompt_encoderry   rX   ra   mask_decoderrL   get_dense_per   r%   r0   rq   r/   original_res_logitsr1   )r3   rO   ru   rX   ra   r   r   re   sparse_embeddingsdense_embeddingslogitsscoresresultsr6   r6   r7   predict   s,   !





zVisualPrompter.predictc                 C  s6   d | _ d | _d | _d | _t| dr| `d | _d| _d S )NrL   F)rK   r/   r0   r1   hasattrrL   rM   )r3   r6   r6   r7   r2   2  s   

zVisualPrompter.reset_imageFinductor	fullgraphdynamicbackendr]   optionsdisabler   r   r   strr]   Optional[str]r   Optional[dict[Any, Any]]r   c             	   C  sd   t j| jj||||||d| j_t j| jj||||||d| j_t j| jj||||||d| j_dS )uF  Apply `torch.compile(...)`/dynamo API into the VisualPrompter API.

        .. note:: For more information about the dynamo API check the official docs
                  https://pytorch.org/docs/stable/generated/torch.compile.html

        Args:
            fullgraph: Whether it is ok to break model into several subgraphs
            dynamic: Use dynamic shape tracing
            backend: backend to be used
            mode: Can be either “default”, “reduce-overhead” or “max-autotune”
            options: A dictionary of options to pass to the backend.
            disable: Turn torch.compile() into a no-op for testing

        Example:
            >>> # prompter = VisualPrompter()
            >>> # prompter.compile() # You should have torch >= 2.0.0 installed
            >>> # Use the prompter methods ...

        r   N)torchcompiler'   r(   r   r   )r3   r   r   r   r]   r   r   r6   r6   r7   r   >  s6   '

	zVisualPrompter.compile)NNN)r   r   r   r   r   r   r   r   )NN)r8   r   r9   r:   r;   r:   r   r   )rC   r   r9   r:   r;   r:   r   r   )rO   rP   rQ   r   r   r   )rX   rY   r   r   )ra   r   r   r   )re   rf   rI   rg   r   rh   )NNNN)
rO   rt   ru   r:   rX   rv   ra   r:   r   r   )NNNNTT)rO   rt   ru   r:   rX   rv   ra   r:   r   r   r   r   r   r   )r   r   )r   r   r   r   r   r   r]   r   r   r   r   r   r   r   )__name__
__module____qualname____doc__r$   rB   r   no_gradrN   rW   r`   rd   rs   r   r   r2   r   __classcell__r6   r6   r4   r7   r   #   sF    %


*
>r   )
__future__r   typingr   r   r   kornia.augmentationr   %kornia.augmentation.container.augmentr   kornia.contrib.modelsr   r   kornia.contrib.models.samr	   r
   kornia.corer   r   r   kornia.core.checkr   r   r   kornia.enhancer   kornia.geometry.boxesr   kornia.geometry.keypointsr   r   r6   r6   r6   r7   <module>   s   