Ë
    ÜÓ^j‡{  ã                   ó˜  — d Z ddl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ZddlZddl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$ d	dl%m&Z&m'Z' d	dl(m)Z)m*Z*m+Z+  e+«       rddl,Z, G d„ de&d¬«      Z-e* G d„ de«      «       Z.ddde/de0fd„Z1d3d„Z2d4d„Z3de4e0   de0de0fd „Z5	 	 	 	 d5d!e0d"e0d#e/d$e0dz  d%e4e0   dz  d&e6e4e4e0      e4e0   f   fd'„Z7d(„ Z8d)e0d&ejr                  fd*„Z:	 d6d+„Z;	 d7d!e0d,ejr                  d-e6e0e0f   d&ejr                  fd.„Z<d/e=e>e	f   d&ejr                  fd0„Z?d8d1„Z@d9d2„ZAdgZBy):zImage processor class for SAM.é    N)ÚIterable)Údeepcopy)Úproduct)ÚAnyÚOptionalÚUnion)Ú
functional)Úbatched_nmsé   )ÚTorchvisionBackend)ÚBatchFeatureÚget_size_dict)Úgroup_images_by_shapeÚreorder_images)ÚIMAGENET_DEFAULT_MEANÚIMAGENET_DEFAULT_STDÚChannelDimensionÚ
ImageInputÚPILImageResamplingÚSizeDict)ÚImagesKwargsÚUnpack)Ú
TensorTypeÚauto_docstringÚis_vision_availablec                   ó:   — e Zd ZU dZeeef   ed<   eeef   ed<   y)ÚSamImageProcessorKwargsaV  
    mask_size (`dict[str, int]`, *optional*):
        The size `{"longest_edge": int}` to resize the segmentation maps to.
    mask_pad_size (`dict[str, int]`, *optional*):
        The size `{"height": int, "width": int}` to pad the segmentation maps to. Must be larger than any segmentation
        map size provided for preprocessing.
    Ú	mask_sizeÚmask_pad_sizeN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚdictÚstrÚintÚ__annotations__© ó    úw/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/sam/image_processing_sam.pyr   r   /   s%   … ñð �C˜�H‰~ÓØ˜˜S˜‘>Ô!r)   r   F)Útotalc            #       ó¶  ‡ — e Zd ZeZej                  ZeZ	e
ZddiZddiZdZdZdZdZdZdddœZdddœZdee   fˆ fd„Ze	 d3d	ed
edz  dee   defˆ fd„«       Z	 	 d4deee   z  eeef   z  ez  dz  deee   z  eeef   z  ez  dz  defˆ fd„Z de!eef   defd„Z"	 d3dddeddddfˆ fd„Z#	 d3d	ed
edz  de$de%dee&z  dz  de'edf   dz  defd„Z(d	e)d   de$deddde$d ed!e$d"e*d#e$d$e*e)e*   z  dz  d%e*e)e*   z  dz  d&e$dz  d'edz  d(e$dz  de!e)d   e)e!eef      f   fd)„Z+	 	 	 	 	 d5dd*d+ed,e*d-edz  d.e)e   dz  de,d   fd/„Z-	 	 	 	 d6d0„Z.	 	 	 d7d1„Z/d2„ Z0ˆ xZ1S )8ÚSamImageProcessorÚlongest_edgei   é   T©ÚheightÚwidthÚkwargsc                 ó$   •— t        ‰| �  di |¤Ž y )Nr(   )ÚsuperÚ__init__)Úselfr3   Ú	__class__s     €r*   r6   zSamImageProcessor.__init__L   s   ø€ Ü‰ÑÑ"˜6Ó"r)   NÚimagesÚsegmentation_mapsÚreturnc                 ó&   •— t        ‰| �  ||fi |¤ŽS )zp
        segmentation_maps (`ImageInput`, *optional*):
            The segmentation maps to preprocess.
        )r5   Ú
preprocess)r7   r9   r:   r3   r8   s       €r*   r=   zSamImageProcessor.preprocessO   s   ø€ ô ‰wÑ! &Ð*;ÑF¸vÑFÐFr)   r   r   c                 óÚ   •— t        ‰| �  di |¤Ž}|�&t        |t        «      st        di t	        |d¬«      ¤Ž}|�&t        |t        «      st        di t	        |d¬«      ¤Ž}||d<   ||d<   |S )z¢
        Update kwargs that need further processing before being validated
        Can be overridden by subclasses to customize the processing of kwargs.
        r   )Ú
param_namer   r(   )r5   Ú_standardize_kwargsÚ
isinstancer   r   )r7   r   r   r3   r8   s       €r*   r@   z%SamImageProcessor._standardize_kwargs\   sv   ø€ ô ‘Ñ,Ñ6¨vÑ6ˆØÐ ¬°I¼xÔ)HÜ ÑT¤=°À{Ô#SÑTˆIØÐ$¬Z¸ÄxÔ-PÜ$Ñ`¤}°]ÈÔ'_Ñ`ˆMà'ˆˆ{ÑØ"/ˆˆÑàˆr)   Ú	old_shapec                 ó„   — |\  }}|dz  t        ||«      z  }||z  ||z  }}t        |dz   «      }t        |dz   «      }||fS )zW
        Compute the output size given input size and target long side length.
        ç      ð?ç      à?)Úmaxr&   )r7   rB   r.   ÚoldhÚoldwÚscaleÚnewhÚnewws           r*   Ú_get_preprocess_shapez'SamImageProcessor._get_preprocess_shapeq   sW   € ð ‰
ˆˆdØ˜sÑ"¤S¨¨t£_Ñ4ˆØ˜E‘\ 4¨%¡<ˆdˆÜ�4˜#‘:‹ˆÜ�4˜#‘:‹ˆØ�dˆ|Ðr)   Úimageútorch.TensorÚsizeÚresamplez7PILImageResampling | tvF.InterpolationMode | int | Nonec                 óì   •— |j                   st        d|j                  «       › �«      ‚|j                  dd }| j	                  ||j                   «      \  }}t        ‰| �  |ft        ||¬«      |dœ|¤ŽS )a­  
        Resize an image to `(size["height"], size["width"])`.

        Args:
            image (`torch.Tensor`):
                Image to resize.
            size (`SizeDict`):
                Dictionary in the format `{"longest_edge": int}` specifying the size of the output image. The longest
                edge of the image will be resized to the specified size, while the other edge will be resized to
                maintain the aspect ratio.
            resample (`PILImageResampling | tvF.InterpolationMode | int | None`, *optional*):
                Resampling filter to use when resizing the image.

        Returns:
            `torch.Tensor`: The resized image.
        z?The `size` dictionary must contain the key `longest_edge`. Got éþÿÿÿNr0   )rO   rP   )r.   Ú
ValueErrorÚkeysÚshaperL   r5   Úresizer   )	r7   rM   rO   rP   r3   Ú
input_sizeÚoutput_heightÚoutput_widthr8   s	           €r*   rV   zSamImageProcessor.resize|   s‡   ø€ ð. × Ò ÜÐ^Ð_c×_hÑ_hÓ_jÐ^kÐlÓmÐmØ—[‘[  Ð%ˆ
Ø&*×&@Ñ&@ÀÈT×M^ÑM^Ó&_Ñ#ˆ�|Ü‰w‰~Øð
Ü ¨¸\ÔJÐU]ñ
Øagñ
ð 	
r)   Údo_convert_rgbÚinput_data_formatÚreturn_tensorsÚdeviceztorch.devicec           	      ó†  — | j                  ||||¬«      }|D �cg c]  }|j                  dd ‘Œ }	}|j                  «       }
 | j                  |fi |
¤Ž\  }}||	|dœ}|�Ì| j                  |ddt        j
                  ¬«      }|j                  «       }|j                  ddt        j                  |j                  d«      |j                  d	«      d
œ«        | j                  dd|i|¤Ž\  }}|D �cg c]0  }|j                  d«      j                  t        j                  «      ‘Œ2 c}|d<   t        ||¬«      S c c}w c c}w )z/
        Preprocess image-like inputs.
        )r9   rZ   r[   r]   rR   N)Úpixel_valuesÚoriginal_sizesÚreshaped_input_sizesé   F)r9   Úexpected_ndimsrZ   r[   r   r   )Údo_normalizeÚ
do_rescalerP   rO   Úpad_sizer9   r   Úlabels)ÚdataÚtensor_typer(   )Ú_prepare_image_like_inputsrU   ÚcopyÚ_preprocessr   ÚFIRSTÚupdater   ÚNEARESTÚpopÚsqueezeÚtoÚtorchÚint64r   )r7   r9   r:   rZ   r[   r\   r]   r3   rM   r`   Úimages_kwargsr_   ra   rh   Úprocessed_segmentation_mapsÚsegmentation_maps_kwargsÚ_Úms                     r*   Ú_preprocess_image_like_inputsz/SamImageProcessor._preprocess_image_like_inputs›   sj  € ð ×0Ñ0Ø¨.ÐL]Ðflð 1ó 
ˆð 9?Ö?¨u˜%Ÿ+™+ b cÒ*Ð?ˆÐ?ØŸ™›ˆØ-=¨T×-=Ñ-=¸fÑ-VÈÑ-VÑ*ˆÐ*à(Ø,Ø$8ñ
ˆð Ð(Ø*.×*IÑ*IØ(Ø Ø$Ü"2×"8Ñ"8ð	 +Jó +Ð'ð (.§{¡{£}Ð$Ø$×+Ñ+à$)Ø"'Ü 2× :Ñ :Ø4×8Ñ8¸ÓEØ 8× <Ñ <¸_Ó Mñôð .>¨T×-=Ñ-=ñ .Ø2ð.Ø6Nñ.Ñ*Ð'¨ð E`Ö`¸q˜aŸi™i¨›lŸo™o¬e¯k©kÕ:Ò`ˆD�‰Nä °>ÔBÐBùòA @ùò< as   šD9Ã15D>Ú	do_resizeÚdo_center_cropÚ	crop_sizere   Úrescale_factorrd   Ú
image_meanÚ	image_stdÚdo_padrf   Údisable_groupingc           	      óä  — t        ||¬«      \  }}i }|j                  «       D ]   \  }}|r| j                  |||¬«      }|||<   Œ" t        ||«      }|D �cg c]  }|j                  dd  ‘Œ }}t        ||¬«      \  }}i }|j                  «       D ]4  \  }}|r| j                  ||«      }| j                  ||||	|
|«      }|||<   Œ6 t        ||«      }|r| j                  |||¬«      }||fS c c}w )N)r‚   )rM   rO   rP   rR   )rf   r‚   )r   ÚitemsrV   r   rU   Úcenter_cropÚrescale_and_normalizeÚpad)r7   r9   r{   rO   rP   r|   r}   re   r~   rd   r   r€   r�   rf   r‚   r3   Úgrouped_imagesÚgrouped_images_indexÚresized_images_groupedrU   Ústacked_imagesÚresized_imagesrM   ra   Úprocessed_images_groupedÚprocessed_imagess                             r*   rl   zSamImageProcessor._preprocessÍ   sC  € ô& 0EÀVÐ^nÔ/oÑ,ˆÐ,Ø!#ÐØ%3×%9Ñ%9Ó%;ò 	;Ñ!ˆE�>ÙØ!%§¡°>ÈÐW_ Ó!`�Ø,:Ð" 5Ò)ð	;ô (Ð(>Ð@TÓUˆØ>LÖM°U §¡¨B¨CÒ 0ÐMÐÐMô 0EÀ^ÐfvÔ/wÑ,ˆÐ,Ø#%Ð Ø%3×%9Ñ%9Ó%;ò 	=Ñ!ˆE�>ÙØ!%×!1Ñ!1°.À)Ó!L�à!×7Ñ7Ø 
¨N¸LÈ*ÐV_óˆNð /=Ð$ UÒ+ð	=ô *Ð*BÐDXÓYÐáØ#Ÿx™xÐ(8À8Ð^n˜xÓoÐàÐ!5Ð5Ð5ùò'  Ns   ÁC-z+np.ndarray | PIL.Image.Image | torch.TensorÚcrop_n_layersÚoverlap_ratioÚpoints_per_cropÚcrop_n_points_downscale_factorc                 óî   — | j                  |«      }t        ||||||«      \  }}}	}
|€t        j                  d«      }|j	                  |«      }|j	                  |«      }|
j	                  |«      }
|||	|
fS )a  
        Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

        Args:
            image (`torch.Tensor`):
                Input original image
            target_size (`int`):
                Target size of the resized image
            crop_n_layers (`int`, *optional*, defaults to 0):
                If >0, mask prediction will be run again on crops of the image. Sets the number of layers to run, where
                each layer has 2**i_layer number of image crops.
            overlap_ratio (`float`, *optional*, defaults to 512/1500):
                Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of
                the image length. Later layers with more crops scale down this overlap.
            points_per_crop (`int`, *optional*, defaults to 32):
                Number of points to sample from each crop.
            crop_n_points_downscale_factor (`list[int]`, *optional*, defaults to 1):
                The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
            device (`torch.device`, *optional*, defaults to None):
                Device to use for the computation. If None, cpu will be used.
        Úcpu)Úprocess_imageÚ_generate_crop_boxesrs   r]   rr   )r7   rM   Útarget_sizer�   r�   r‘   r’   r]   Ú
crop_boxesÚcropped_imagesÚinput_labelss              r*   Úgenerate_crop_boxesz%SamImageProcessor.generate_crop_boxesü   sŠ   € ð> ×"Ñ" 5Ó)ˆÜDXØØØØØØ*óE
ÑAˆ
�O ^°\ð ˆ>Ü—\‘\ %Ó(ˆFØ—]‘] 6Ó*ˆ
Ø)×,Ñ,¨VÓ4ˆà#—‘ vÓ.ˆà˜?¨N¸LÐHÐHr)   c	                 óŽ  — |\  }	}
|j                  dd«      }|j                  dd«      }|j                  d   |j                  d   k7  rt        d«      ‚|j                  |j                  k7  r|j	                  |j                  «      }|j                  d   }t        j                  |t
        j                  |j                  ¬«      }|dkD  r|||kD  z  }|dkD  rt        |||«      }|||kD  z  }||   }||   }||kD  }t        |«      }t        ||dd|
|	g«       }||   }||   }||   }t        |||	|
«      }t        |«      }|||fS )a  
        Filters the predicted masks by selecting only the ones that meets several criteria. The first criterion being
        that the iou scores needs to be greater than `pred_iou_thresh`. The second criterion is that the stability
        score needs to be greater than `stability_score_thresh`. The method also converts the predicted masks to
        bounding boxes and pad the predicted masks if necessary.

        Args:
            masks (`torch.Tensor`):
                Input masks.
            iou_scores (`torch.Tensor`):
                List of IoU scores.
            original_size (`tuple[int,int]`):
                Size of the original image.
            cropped_box_image (`torch.Tensor`):
                The cropped image.
            pred_iou_thresh (`float`, *optional*, defaults to 0.88):
                The threshold for the iou scores.
            stability_score_thresh (`float`, *optional*, defaults to 0.95):
                The threshold for the stability score.
            mask_threshold (`float`, *optional*, defaults to 0):
                The threshold for the predicted masks.
            stability_score_offset (`float`, *optional*, defaults to 1):
                The offset for the stability score used in the `_compute_stability_score` method.
        r   é   z3masks and iou_scores must have the same batch size.©Údtyper]   ç        )ÚflattenrU   rS   r]   rr   rs   ÚonesÚboolÚ_compute_stability_scoreÚ_batched_mask_to_boxÚ_is_box_near_crop_edgeÚ
_pad_masksÚ_mask_to_rle)r7   ÚmasksÚ
iou_scoresÚoriginal_sizeÚcropped_box_imageÚpred_iou_threshÚstability_score_threshÚmask_thresholdÚstability_score_offsetÚoriginal_heightÚoriginal_widthÚ
batch_sizeÚ	keep_maskÚstability_scoresÚscoresÚconverted_boxess                   r*   Úfilter_maskszSamImageProcessor.filter_masks-  sw  € ðF +8Ñ'ˆ˜Ø×'Ñ'¨¨1Ó-ˆ
Ø—‘˜a Ó#ˆà�;‰;�q‰>˜Z×-Ñ-¨aÑ0Ò0ÜÐRÓSÐSà�<‰<˜:×,Ñ,Ò,Ø#Ÿ™ u§|¡|Ó4ˆJà—[‘[ ‘^ˆ
ä—J‘J˜z´·±ÀEÇLÁLÔQˆ	à˜SÒ Ø! Z°/Ñ%AÑBˆIð " CÒ'Ü7¸¸~ÐOeÓfÐØ!Ð%5Ð8NÑ%NÑOˆIà˜IÑ&ˆØ�iÑ ˆð ˜Ñ&ˆÜ.¨uÓ5ˆä+ØÐ.°°A°~ÀÐ0Wó
ð 
ˆ	ð ˜	Ñ"ˆØ�iÑ ˆØ)¨)Ñ4ˆä˜5Ð"3°_ÀnÓUˆä˜UÓ#ˆà�f˜oÐ-Ð-r)   c                 óØ  — |€| j                   n|}|d   |d   f}t        |t        j                  t        j
                  f«      r|j                  «       }t        |t        j                  t        j
                  f«      r|j                  «       }g }t        |«      D ]Ë  \  }	}
t        ||	   t        j
                  «      rt        j                  ||	   «      ||	<   n(t        ||	   t        j                  «      st        d«      ‚t        j                  ||	   |dd¬«      }|dd||	   d	   …d||	   d
   …f   }t        j                  ||
dd¬«      }|r||kD  }|j                  |«       ŒÍ |S )aF  
        Remove padding and upscale masks to the original image size.

        Args:
            masks (`Union[List[torch.Tensor], List[np.ndarray]]`):
                Batched masks from the mask_decoder in (batch_size, num_channels, height, width) format.
            original_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
                The original sizes of each image before it was resized to the model's expected input shape, in (height,
                width) format.
            reshaped_input_sizes (`Union[torch.Tensor, List[Tuple[int,int]]]`):
                The size of each image as it is fed to the model, in (height, width) format. Used to remove padding.
            mask_threshold (`float`, *optional*, defaults to 0.0):
                The threshold to use for binarizing the masks.
            binarize (`bool`, *optional*, defaults to `True`):
                Whether to binarize the masks.
            pad_size (`int`, *optional*, defaults to `self.pad_size`):
                The target size the images were padded to before being passed to the model. If None, the target size is
                assumed to be the processor's `pad_size`.
        Returns:
            (`torch.Tensor`): Batched masks in batch_size, num_channels, height, width) format, where (height, width)
            is given by original_size.
        Nr1   r2   zIInput masks should be a list of `torch.tensors` or a list of `np.ndarray`ÚbilinearF)ÚmodeÚalign_corners.r   r�   )rf   rA   rs   ÚTensorÚnpÚndarrayÚtolistÚ	enumerateÚ
from_numpyÚ	TypeErrorÚFÚinterpolateÚappend)r7   r©   r`   ra   r¯   Úbinarizerf   Útarget_image_sizeÚoutput_masksÚir«   Úinterpolated_masks               r*   Úpost_process_masksz$SamImageProcessor.post_process_masks{  sk  € ð> %-Ð$4�4—=’=¸(ˆØ% hÑ/°¸'Ñ1BÐCÐÜ�n¤u§|¡|´R·Z±ZÐ&@ÔAØ+×2Ñ2Ó4ˆNÜÐ*¬U¯\©\¼2¿:¹:Ð,FÔGØ#7×#>Ñ#>Ó#@Ð àˆÜ )¨.Ó 9ò 
	3ÑˆAˆ}Ü˜% ™(¤B§J¡JÔ/Ü ×+Ñ+¨E°!©HÓ5��a’Ü  a¡¬%¯,©,Ô7ÜÐ kÓlÐlÜ !§¡¨e°A©hÐ8IÐPZÐjoÔ pÐØ 1°#Ð7SÐ9MÈaÑ9PÐQRÑ9SÐ7SÐUqÐWkÐlmÑWnÐopÑWqÐUqÐ2qÑ rÐÜ !§¡Ð.?ÀÐU_ÐotÔ uÐÙØ$5¸Ñ$FÐ!Ø×ÑÐ 1Õ2ð
	3ð Ðr)   c                 ó   — t        ||||«      S )a$  
        Post processes mask that are generated by calling the Non Maximum Suppression algorithm on the predicted masks.

        Args:
            all_masks (`torch.Tensor`):
                List of all predicted segmentation masks
            all_scores (`torch.Tensor`):
                List of all predicted iou scores
            all_boxes (`torch.Tensor`):
                List of all bounding boxes of the predicted masks
            crops_nms_thresh (`float`):
                Threshold for NMS (Non Maximum Suppression) algorithm.
        )Ú!_post_process_for_mask_generation)r7   Ú	all_masksÚ
all_scoresÚ	all_boxesÚcrops_nms_threshs        r*   Ú post_process_for_mask_generationz2SamImageProcessor.post_process_for_mask_generation°  s   € ô 1°¸JÈ	ÐScÓdÐdr)   ©N)NN)r   ç¥âìÃgØÕ?é    r�   N)g)\�Âõ(ì?gffffffî?r   r�   )r    TN)2r    r!   r"   r   Úvalid_kwargsr   ÚBILINEARrP   r   r   r   r€   rO   r   r{   re   rd   rZ   r�   rf   r   r   r6   r   r   r   r=   r&   r   r$   r%   r   r@   ÚtuplerL   rV   r£   r   r   r   rz   ÚlistÚfloatrl   r   r›   r¸   rÌ   rÓ   Ú__classcell__)r8   s   @r*   r-   r-   <   si  ø„ à*€LØ!×*Ñ*€HØ&€JØ$€IØ˜DÐ!€DØ Ð%€IØ€IØ€JØ€LØ€NØ€FØ¨Ñ.€HØ"¨SÑ1€Mð# Ð(?Ñ!@õ #ð ð 04ñ
Gàð
Gð &¨Ñ,ð
Gð Ð0Ñ1ð	
Gð
 
ô
Gó ð
Gð MQØPTñà˜ #™Ñ&¨¨c°3¨h©Ñ7¸(ÑBÀTÑIðð ˜X c™]Ñ*¨T°#°s°(©^Ñ;¸hÑFÈÑMðð
 
õð*	¨u°S¸#°X©ð 	Ècó 	ð OSñ	
àð
ð ð
ð Lð	
ð 
õ
ðL 59ñ0Càð0Cð &¨Ñ,ð0Cð ð	0Cð
 ,ð0Cð ˜jÑ(¨4Ñ/ð0Cð �c˜>Ð)Ñ*¨TÑ1ð0Cð 
ó0Cðd-6à�^Ñ$ð-6ð ð-6ð ð	-6ð
 Lð-6ð ð-6ð ð-6ð ð-6ð ð-6ð ð-6ð ˜D ™KÑ'¨$Ñ.ð-6ð ˜4 ™;Ñ&¨Ñ-ð-6ð �t‘ð-6ð ˜T‘/ð-6ð  ™+ð-6ð" 
ˆt�NÑ# T¨%°°S°©/Ñ%:Ð:Ñ	;ó#-6ðf Ø)Ø&(Ø;<Ø+/ñ/Ià<ð/Ið ð	/Ið
 ð/Ið ˜t™ð/Ið )-¨S©	°DÑ(8ð/Ið ˜Ñ(ó/Iðn Ø#ØØ óL.ðf ØØó3öjer)   r-   r©   rN   r¯   r°   c                 ó(  — | ||z   kD  j                  dt        j                  ¬«      j                  dt        j                  ¬«      }| ||z
  kD  j                  dt        j                  ¬«      j                  dt        j                  ¬«      }||z  }|S )Néÿÿÿÿ©rŸ   )Úsumrs   Úint16Úint32)r©   r¯   r°   ÚintersectionsÚunionsrµ   s         r*   r¤   r¤   Á  s’   € ð 
�.Ð#9Ñ9Ñ	:×?Ñ?ÀÌ%Ï+É+Ð?ÓV×ZÑZÐ[]Ôej×epÑepÐZÓqð ð �~Ð(>Ñ>Ñ?×DÑDÀRÌuÏ{É{ÐDÓ[×_Ñ_Ð`bÔjo×juÑjuÐ_Óv€FØ$ vÑ-ÐØÐr)   c                 ól  — t        j                  | «      dk(  r1t        j                  g | j                  dd ¢d‘­d| j                  iŽS | j                  }|dd \  }}t        j
                  | d¬«      \  }}|t        j                  ||j                  ¬«      ddd…f   z  }t        j
                  |d¬«      \  }}||| z  z   }t        j                  |d¬«      \  }}t        j
                  | d¬«      \  }	}|	t        j                  ||	j                  ¬«      ddd…f   z  }
t        j
                  |
d¬«      \  }}|
||	 z  z   }
t        j                  |
d¬«      \  }}||k  ||k  z  }t        j                  ||||gd¬«      }|| j                  d«      z  } |j                  g |dd ¢d‘­Ž }|S )	aL  
    Computes the bounding boxes around the given input masks. The bounding boxes are in the XYXY format which
    corresponds the following required indices:
        - LEFT: left hand side of the bounding box
        - TOP: top of the bounding box
        - RIGHT: right of the bounding box
        - BOTTOM: bottom of the bounding box

    Return [0,0,0,0] for an empty mask. For input shape channel_1 x channel_2 x ... x height x width, the output shape
    is channel_1 x channel_2 x ... x 4.

    Args:
        - masks (`torch.Tensor` of shape `(batch, nb_mask, height, width)`)
    r   NrR   é   r]   rÞ   ©Údim©r]   )rs   ÚnumelÚzerosrU   r]   rF   ÚarangeÚminÚstackÚ	unsqueezeÚreshape)r©   rU   r1   r2   Ú	in_heightrx   Úin_height_coordsÚbottom_edgesÚ	top_edgesÚin_widthÚin_width_coordsÚright_edgesÚ
left_edgesÚempty_filterÚouts                  r*   r¥   r¥   Ì  s±  € ô" ‡{�{�5Ó˜QÒÜ�{‰{ÐE˜EŸK™K¨¨Ð,ÐE¨aÒE¸¿¹ÑEÐEð �K‰K€EØ˜"˜#�J�M€FˆEô —9‘9˜U¨Ô+�L€IˆqØ ¤5§<¡<°¸y×?OÑ?OÔ#PÐQUÒWXÐQXÑ#YÑYÐÜ—i‘iÐ 0°bÔ9�O€L�!Ø'¨&°Y°JÑ*?Ñ?ÐÜ—9‘9Ð-°2Ô6�L€Iˆqô —)‘)˜E rÔ*�K€HˆaØ¤§¡¨e¸H¿O¹OÔ!LÈTÒSTÈWÑ!UÑU€OÜ—Y‘Y˜°BÔ7�N€K�Ø%¨°(°Ñ(;Ñ;€OÜ—I‘I˜o°2Ô6�M€J�ð   *Ñ,°À	Ñ1IÑJ€LÜ
�+‰+�z 9¨k¸<ÐHÈbÔ
Q€CØ
�,�×)Ñ)¨"Ó-Ñ
-€Cð ˆ#�+‰+Ð
%�u˜S˜b�zÐ
% 1Ò
%€CØ€Jr)   c                 óp  — t        j                  |t         j                  | j                  ¬«      }t        j                  |t         j                  | j                  ¬«      }|\  }}}}t        j                  ||||gg| j                  ¬«      }	t        | j                  «      dk(  r|	j                  d«      }	| |	z   j                  «       } t        j                  | |ddd…f   |d¬«      }
t        j                  | |ddd…f   |d¬«      }t        j                  |
| «      }
t        j                  |
d¬«      S )	zNFilter masks at the edge of a crop, but not at the edge of the original image.rž   ré   r   r�   Nr   )ÚatolÚrtolrç   )rs   Ú	as_tensorrÛ   r]   ÚtensorÚlenrU   rï   ÚiscloseÚlogical_andÚany)ÚboxesÚcrop_boxÚorig_boxrü   Úcrop_box_torchÚorig_box_torchÚleftÚtoprx   ÚoffsetÚnear_crop_edgeÚnear_image_edges               r*   r¦   r¦   ý  sø   € ä—_‘_ X´U·[±[ÈÏÉÔV€NÜ—_‘_ X´U·[±[ÈÏÉÔV€Nà�O€Dˆ#ˆq�!Ü�\‰\˜D # t¨SÐ1Ð2¸5¿<¹<ÔH€Fä
ˆ5�;‰;Ó˜1ÒØ×!Ñ! !Ó$ˆØ�V‰^×"Ñ"Ó$€Eä—]‘] 5¨.¸ºq¸Ñ*AÈÐSTÔU€NÜ—m‘m E¨>¸$Â¸'Ñ+BÈÐTUÔV€OÜ×&Ñ& ~¸Ð7GÓH€NÜ�9‰9�^¨Ô+Ð+r)   r  Úorig_heightÚ
orig_widthc                 óÌ   — |\  }}}}|dk(  r|dk(  r||k(  r||k(  r| S |||z
  z
  |||z
  z
  }	}|||z
  ||	|z
  f}
t         j                  j                  j                  | |
d¬«      S )Nr   )Úvalue)rs   Únnr	   r‡   )r©   r  r  r  r	  r
  ÚrightÚbottomÚpad_xÚpad_yr‡   s              r*   r§   r§     sƒ   € Ø'Ñ€Dˆ#ˆu�fØˆq‚y�S˜A’X %¨:Ò"5¸&ÀKÒ:OØˆà ¨¡Ñ.°¸vÈ¹|Ñ0Lˆ5€EØ�˜‘˜s E¨C¡KÐ
0€CÜ�8‰8×Ñ×"Ñ" 5¨#°QÐ"Ó7Ð7r)   r—   r�   r�   r‘   r’   r;   c                 óp  — t        | t        «      rt        d«      ‚| j                  dd }g }t	        |dz   «      D ]-  }t        |||z  z  «      }	|j                  t        |	«      «       Œ/ t        |||«      \  }
}t        |
| ||||«      \  }}t        j                  |
«      }
|
j                  «       }
t        j                  |«      }|j                  d«      j                  dddd«      }t        j                  |«      }t        j                   |dd…dd…dd…df   t        j"                  ¬«      }|
|||fS )	añ  
    Generates a list of crop boxes of different sizes. Each layer has (2**i)**2 boxes for the ith layer.

    Args:
        image (`torch.Tensor`):
            Image to generate crops for.
        target_size (`int`):
            Size of the smallest crop.
        crop_n_layers (`int`, *optional*):
            If `crops_n_layers>0`, mask prediction will be run again on crops of the image. Sets the number of layers
            to run, where each layer has 2**i_layer number of image crops.
        overlap_ratio (`int`, *optional*):
            Sets the degree to which crops overlap. In the first crop layer, crops will overlap by this fraction of the
            image length. Later layers with more crops scale down this overlap.
        points_per_crop (`int`, *optional*):
            Number of points to sample per crop.
        crop_n_points_downscale_factor (`int`, *optional*):
            The number of points-per-side sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
    z.Only one image is allowed for crop generation.rR   Nr�   r   rb   r   rß   )rA   rÚ   rS   rU   Úranger&   rÆ   Ú_build_point_gridÚ_generate_per_layer_cropsÚ_generate_crop_imagesrs   rÿ   rÛ   rî   rï   ÚpermuteÚ	ones_likert   )rM   r—   r�   r�   r‘   r’   r«   Úpoints_gridrÊ   Ún_pointsr˜   Ú
layer_idxsr™   Úpoint_grid_per_croprš   s                  r*   r–   r–     s0  € ô8 �%œÔÜÐIÓJÐJØ—K‘K  Ð$€Mà€KÜ�= 1Ñ$Ó%ò 8ˆÜ�Ð*HÈ!Ñ*KÑLÓMˆØ×ÑÔ,¨XÓ6Õ7ð8ô 7°}ÀmÐUbÓcÑ€J�
ä*?Ø�E˜;¨
°KÀó+Ñ'€NÐ'ô —‘˜jÓ)€JØ×!Ñ!Ó#€JÜ—k‘kÐ"5Ó6€OØ%×/Ñ/°Ó2×:Ñ:¸1¸aÀÀAÓF€OÜ—[‘[ Ó0€Nä—?‘? ?²1²aº¸A°:Ñ#>ÄeÇkÁkÔR€Là�¨¸ÐDÐDr)   c           	      óæ  — g g }}|\  }}t        ||«      }|j                  dd||g«       |j                  d«       t        | «      D �]  }d|dz   z  }	t        ||z  d|	z  z  «      }
t        t	        j
                  |
|	dz
  z  |z   |	z  «      «      }t        t	        j
                  |
|	dz
  z  |z   |	z  «      «      }t        |	«      D �cg c]  }t        ||
z
  |z  «      ‘Œ }}t        |	«      D �cg c]  }t        ||
z
  |z  «      ‘Œ }}t        ||«      D ]J  \  }}||t        ||z   |«      t        ||z   |«      g}|j                  |«       |j                  |dz   «       ŒL �Œ ||fS c c}w c c}w )aq  
    Generates 2 ** (layers idx + 1) crops for each crop_n_layers. Crops are in the XYWH format : The XYWH format
    consists of the following required indices:
        - X: X coordinate of the top left of the bounding box
        - Y: Y coordinate of the top left of the bounding box
        - W: width of the bounding box
        - H: height of the bounding box
    r   rb   r�   )rí   rÆ   r  r&   ÚmathÚceilr   )r�   r�   r«   r˜   r   Ú	im_heightÚim_widthÚ
short_sideÚi_layerÚn_crops_per_sideÚoverlapÚ
crop_widthÚcrop_heightrÊ   Úcrop_box_x0Úcrop_box_y0r	  r
  Úboxs                      r*   r  r  N  s   € ð   �
€JØ'Ñ€IˆxÜ�Y Ó)€Jð ×Ñ�q˜!˜X yÐ1Ô2Ø×Ñ�aÔÜ˜Ó'ó +ˆØ ¨1¡Ñ-ÐÜ�m jÑ0°AÐ8HÑ4HÑIÓJˆäœŸ™ GÐ/?À!Ñ/CÑ$DÀxÑ$OÐScÑ#cÓdÓeˆ
Üœ$Ÿ)™) WÐ0@À1Ñ0DÑ%EÈ	Ñ%QÐUeÑ$eÓfÓgˆä@EÐFVÓ@WÖX¸1”s˜J¨Ñ0°AÑ5Õ6ÐXˆÐXÜAFÐGWÓAXÖY¸A”s˜K¨'Ñ1°QÑ6Õ7ÐYˆÐYä  ¨kÓ:ò 	+‰IˆD�#Ø˜œc $¨Ñ"3°XÓ>ÄÀCÈ+ÑDUÐW`Ó@aÐbˆCØ×Ñ˜cÔ"Ø×Ñ˜g¨™kÕ*ò	+ð+ð �zÐ!Ð!ùò YùÚYs   ÃE)Ã/E.Ú
n_per_sidec                 ó  — dd| z  z  }t        j                  |d|z
  | «      }t        j                  |ddd…f   | df«      }t        j                  |dd…df   d| f«      }t        j                  ||gd¬«      j	                  dd«      }|S )z;Generates a 2D grid of points evenly spaced in [0,1]x[0,1].r�   rb   NrÞ   rç   )rs   ÚlinspaceÚtilerî   rð   )r0  r  Úpoints_one_sideÚpoints_xÚpoints_yÚpointss         r*   r  r  p  s‡   € à�!�j‘.Ñ!€FÜ—n‘n V¨Q°©Z¸ÓD€OÜ�z‰z˜/¨$²¨'Ñ2°ZÀ°OÓD€HÜ�z‰z˜/ª!¨T¨'Ñ2°Q¸
°OÓD€HÜ�[‰[˜( HÐ-°2Ô6×>Ñ>¸rÀ1ÓE€FØ€Mr)   c                 ó\  — g }g }t        | «      D ]—  \  }	}
|
\  }}}}|dd…||…||…f   }|j                  |«       |j                  dd }t        j                  |«      j                  d¬«      j                  d«      }|||	      |z  }t        |||«      }|j                  |«       Œ™ ||fS )z�
    Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are
    also passed.
    NrR   )r   )Údimsr   )rÁ   rÆ   rU   rs   rÿ   Úfliprï   Ú_normalize_coordinates)r˜   rM   r  r   r—   r«   r[   r™   Útotal_points_per_croprÊ   r  r	  r
  r  r  Ú
cropped_imÚcropped_im_sizeÚpoints_scaler7  Únormalized_pointss                       r*   r  r  z  sÔ   € ð €NØÐÜ  Ó,ò 8‰ˆˆ8Ø#+Ñ ˆˆc�5˜&Øš1˜c &˜j¨$¨u¨*Ð4Ñ5ˆ
à×Ñ˜jÔ)à$×*Ñ*¨2¨3Ð/ˆÜ—|‘| OÓ4×9Ñ9¸tÐ9ÓD×NÑNÈqÓQˆà˜Z¨™]Ñ+¨lÑ:ˆÜ2°;ÀÈÓVÐØ×$Ñ$Ð%6Õ7ð8ð Ð0Ð0Ð0r)   Úcoordsr«   c                 ó<  — |\  }}| dz  t        ||«      z  }||z  ||z  }}t        |dz   «      }t        |dz   «      }t        |«      j                  «       }|r|j	                  ddd«      }|d   ||z  z  |d<   |d   ||z  z  |d<   |r|j	                  dd«      }|S )zƒ
    Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
    format.
    rD   rE   rÞ   rb   ).r   ).r�   ræ   )rF   r&   r   rÛ   rð   )	r—   rA  r«   Úis_bounding_boxÚ
old_heightÚ	old_widthrI   Ú
new_heightÚ	new_widths	            r*   r;  r;  “  sÂ   € ð *Ñ€J�	à˜#Ñ¤ J°	Ó :Ñ:€EØ&¨Ñ.°	¸EÑ0A�	€JÜ�I ‘OÓ$€IÜ�Z #Ñ%Ó&€Jä�fÓ×#Ñ#Ó%€FáØ—‘  A qÓ)ˆà˜F‘^ y°9Ñ'<Ñ=€Fˆ6�NØ˜F‘^ z°JÑ'>Ñ?€Fˆ6�NáØ—‘  AÓ&ˆà€Mr)   Úrlec                 óÒ   — | d   \  }}t        j                  ||z  t        ¬«      }d}d}| d   D ]  }|||||z    ||z  }| }Œ |j                  ||«      }|j	                  dd«      S )z/Compute a binary mask from an uncompressed RLE.rO   rß   r   FÚcountsr�   )rs   Úemptyr£   rð   Ú	transpose)rH  r1   r2   ÚmaskÚidxÚparityÚcounts          r*   Ú_rle_to_maskrQ  ¯  sƒ   € à˜‘K�M€FˆEÜ�;‰;�v ‘~¬TÔ2€DØ
€CØ€FØ�X‘ò ˆØ"(ˆˆS�3˜‘;ÐØˆu‰ˆØ�‰ðð �<‰<˜˜vÓ&€DØ�>‰>˜!˜QÓÐr)   c                 ó  — t        |j                  «       |t        j                  |j                  d   «      |¬«      }||   }|D �cg c]  }| |   ‘Œ	 } }||   }| D �cg c]  }t        |«      ‘Œ }}||| |fS c c}w c c}w )aë  
    Perform NMS (Non Maximum Suppression) on the outputs.

    Args:
            rle_masks (`torch.Tensor`):
                binary masks in the RLE format
            iou_scores (`torch.Tensor` of shape (nb_masks, 1)):
                iou_scores predicted by the model
            mask_boxes (`torch.Tensor`):
                The bounding boxes corresponding to segmentation masks
            amg_crops_nms_thresh (`float`, *optional*, defaults to 0.7):
                NMS threshold.
    r   )r  r¶   ÚidxsÚiou_threshold)r
   rÛ   rs   rë   rU   rQ  )Ú	rle_masksrª   Ú
mask_boxesÚamg_crops_nms_threshÚkeep_by_nmsrÊ   rH  r©   s           r*   rÎ   rÎ   ½  s“   € ô Ø×ÑÓ ØÜ�[‰[˜×)Ñ)¨!Ñ,Ó-Ø*ô	€Kð ˜KÑ(€JØ'2Ö3 !�˜1“Ð3€IÐ3Ø˜KÑ(€JØ*3Ö4 3Œ\˜#ÕÐ4€EÐ4à�*˜i¨Ð3Ð3ùò	 4ùâ4s   ÁA8ÁA=c                 óˆ  — | j                   \  }}}| j                  ddd«      j                  d«      } | dd…dd…f   | dd…dd…f   z  }|j                  «       }g }t	        |«      D ]Ø  }||dd…df   |k(  df   dz   }t        |«      dk(  rA| |df   dk(  r|j                  ||g||z  gdœ«       n|j                  ||gd||z  gdœ«       Œf|dd |dd z
  }	| |df   dk(  rg ndg}
|
|d   j                  «       g|	j                  «       z   ||z  |d   j                  «       z
  gz   z  }
|j                  ||g|
dœ«       ŒÚ |S )z^
    Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
    r   rb   r�   NrÞ   )rO   rJ  )	rU   r  r¡   Únonzeror  r   rÆ   ÚitemrÀ   )Ú
input_maskr³   r1   r2   ÚdiffÚchange_indicesrú   rÊ   Úcur_idxsÚbtw_idxsrJ  s              r*   r¨   r¨   Ú  s�  € ð
 !+× 0Ñ 0Ñ€J�˜Ø×#Ñ# A q¨!Ó,×4Ñ4°QÓ7€Jð ’a˜™�eÑ˜zª!¨S¨b¨S¨&Ñ1Ñ1€DØ—\‘\“^€Nð €CÜ�:Óò @ˆØ! .²°A°Ñ"6¸!Ñ";¸QÐ">Ñ?À!ÑCˆÜˆx‹=˜AÒð ˜!˜Q˜$Ñ 1Ò$Ø—
‘
 V¨U OÀÈÁÐ?OÑPÕQà—
‘
 V¨U OÀÀ6ÈEÁ>Ð?RÑSÔTØØ˜A˜B�< (¨3¨B -Ñ/ˆØ! ! Q $Ñ'¨1Ò,‘°1°#ˆØ�8˜A‘;×#Ñ#Ó%Ð&¨¯©Ó):Ñ:¸fÀu¹nÈxÐXZÉ|×O`ÑO`ÓObÑ>bÐ=cÑcÑcˆØ�
‰
˜V U˜O°vÑ>Õ?ð@ð €Jr)   )r©   rN   )g      4@)r   rÕ   rÖ   r�   rÔ   )F)gffffffæ?)r\  rN   )Cr#   r#  Úcollections.abcr   rk   r   Ú	itertoolsr   Útypingr   r   r   Únumpyr¾   rs   Útorch.nnr	   rÄ   Útorchvision.ops.boxesr
   Útorchvision.transforms.v2ÚtvFÚimage_processing_backendsr   Úimage_processing_utilsr   r   Úimage_transformsr   r   Úimage_utilsr   r   r   r   r   r   Úprocessing_utilsr   r   Úutilsr   r   r   ÚPILr   r-   rÛ   r&   r¤   r¥   r¦   rÚ   r§   rÙ   r–   r  r½   r  r  r;  r$   r%   rQ  rÎ   r¨   Ú__all__r(   r)   r*   ú<module>rq     sÙ  ðñ %ã Ý $Ý Ý ß 'Ñ 'ã Û Ý $Ý -Ý 7å ;ß Aß E÷÷ ÷ 5ß DÑ Dñ ÔÛô
"˜l°%õ 
"ð ôAeÐ*ó Aeó ðAeðH Nð ÀEð Ðcfó ó.ób,ð$8  S¡	ð 8¸ð 8Èó 8ð Ø%Ø"$Ø78ñ2Eàð2Eð ð2Eð ð	2Eð
 ˜4‘Zð2Eð %)¨¡I°Ñ$4ð2Eð ˆ4��S‘	‰?˜D ™IÐ%Ñ&ó2Eòj"ðD #ð ¨%¯,©,ó ð _có1ð4 ]bñØðØ#Ÿl™lðØ;@ÀÀcÀ¹?ðà
‡\�\óð8 �d˜3 ˜8‘nð  ¨¯©ó  ó4ó:ð> Ð
�r)   