ó
    qyüi‡{  ã                   ó¶  • S r SSKrSSKJr  SSKJr  SSKJr  SSKJ	r	J
r
Jr  SSKrSSKrSSKJr  SSKJr  SSKJr  S	S
KJr  S	SKJrJr  S	SKJrJr  S	SKJrJ r J!r!J"r"J#r#J$r$  S	SK%J&r&J'r'  S	SK(J)r)J*r*J+r+  \+" 5       (       a  SSK,r, " S S\&SS9r-\* " S S\5      5       r.SSS\/S\04S jr1S3S jr2S4S jr3S\4\0   S\0S\04S  jr5    S5S!\0S"\0S#\/S$\0S-  S%\4\0   S-  S&\6\4\4\0      \4\0   4   4S' jjr7S( r8S)\0S&\Rr                  4S* jr: S6S+ jr; S7S!\0S,\Rr                  S-\6\0\04   S&\Rr                  4S. jjr<S/\=\>\	4   S&\Rr                  4S0 jr?S8S1 jr@S9S2 jrAS/rBg):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                   óB   • \ rS rSr% Sr\\\4   \S'   \\\4   \S'   Sr	g)ÚSamImageProcessorKwargsé/   a>  
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_size© N)
Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__ÚdictÚstrÚintÚ__annotations__Ú__static_attributes__r!   ó    Úi/home/mande/repo/quber/.venv/lib/python3.13/site-packages/transformers/models/sam/image_processing_sam.pyr   r   /   s%   ‡ ñð �C˜�H‰~ÓØ˜˜S˜‘>Ö!r,   r   F)Útotalc            #       óä  ^ • \ rS rSr\r\R                  r\	r
\rSS0rSS0rSrSrSrSrSrSSS.rSSS.rS\\   4U 4S jjr\ S5S
\S\S	-  S\\   S\4U 4S jjj5       r  S6S\\\   -  \\\4   -  \ -  S	-  S\\\   -  \\\4   -  \ -  S	-  S\4U 4S jjjr!S\"\\4   S\4S jr# S5SSS\ SSSS4U 4S jjjr$ S5S
\S\S	-  S\%S\&S\\'-  S	-  S\(\S4   S	-  S\4S jjr)S
\*S   S\%S\ SSS \%S!\ S"\%S#\+S$\%S%\+\*\+   -  S	-  S&\+\*\+   -  S	-  S'\%S	-  S(\ S	-  S)\%S	-  S\"\*S   \*\"\\4      4   4S* jr,     S7SS+S,\S-\+S.\S	-  S/\*\   S	-  S\-S   4S0 jjr.    S8S1 jr/   S9S2 jr0S3 r1S4r2U =r3$ ):ÚSamImageProcessoré<   Úlongest_edgei   é   T©ÚheightÚwidthÚkwargsc                 ó&   >• [         TU ]  " S0 UD6  g )Nr!   )ÚsuperÚ__init__)Úselfr7   Ú	__class__s     €r-   r:   ÚSamImageProcessor.__init__L   s   ø€ Ü‰ÒÑ"˜6Ó"r,   NÚimagesÚsegmentation_mapsÚreturnc                 ó&   >• [         TU ]  " X40 UD6$ )zX
segmentation_maps (`ImageInput`, *optional*):
    The segmentation maps to preprocess.
)r9   Ú
preprocess)r;   r>   r?   r7   r<   s       €r-   rB   ÚSamImageProcessor.preprocessO   s   ø€ ô ‰wÒ! &ÑF¸vÑFÐFr,   r   r    c           	      óä   >• [         TU ]  " S0 UD6nUb(  [        U[        5      (       d  [        S0 [	        USS9D6nUb(  [        U[        5      (       d  [        S0 [	        USS9D6nXS'   X#S'   U$ )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!   )r9   Ú_standardize_kwargsÚ
isinstancer   r   )r;   r   r    r7   r<   s       €r-   rF   Ú%SamImageProcessor._standardize_kwargs\   sx   ø€ ô ‘Ò,Ñ6¨vÑ6ˆØÑ ¬°I¼x×)HÑ)HÜ ÑT¤=°À{Ñ#SÑTˆIØÑ$¬Z¸Äx×-PÑ-PÜ$Ñ`¤}°]ÈÑ'_Ñ`ˆMà'ˆ{ÑØ"/ˆÑàˆr,   Ú	old_shapec                 óx   • Uu  p4US-  [        X45      -  nX5-  XE-  pv[        US-   5      n[        US-   5      nXg4$ )zG
Compute the output size given input size and target long side length.
ç      ð?ç      à?)Úmaxr)   )r;   rI   r2   ÚoldhÚoldwÚscaleÚnewhÚnewws           r-   Ú_get_preprocess_shapeÚ'SamImageProcessor._get_preprocess_shapeq   sK   € ð ‰
ˆØ˜sÑ"¤S¨£_Ñ4ˆØ‘\ 4¡<ˆdÜ�4˜#‘:‹ˆÜ�4˜#‘:‹ˆØˆ|Ðr,   Úimageútorch.TensorÚsizeÚresamplez7PILImageResampling | tvF.InterpolationMode | int | Nonec                 óì   >• UR                   (       d  [        SUR                  5        35      eUR                  SS nU R	                  XRR                   5      u  pg[
        TU ]  " U4[        XgS9US.UD6$ )aE  
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 éþÿÿÿNr4   )rW   rX   )r2   Ú
ValueErrorÚkeysÚshaperS   r9   Úresizer   )	r;   rU   rW   rX   r7   Ú
input_sizeÚoutput_heightÚoutput_widthr<   s	           €r-   r^   ÚSamImageProcessor.resize|   s�   ø€ ð. × × ÜÐ^Ð_c×_hÑ_hÓ_jÐ^kÐlÓmÐmØ—[‘[  Ð%ˆ
Ø&*×&@Ñ&@À×M^ÑM^Ó&_Ñ#ˆÜ‰wŠ~Øð
Ü ¨ÑJÐU]ñ
Øagñ
ð 	
r,   Údo_convert_rgbÚinput_data_formatÚreturn_tensorsÚdeviceztorch.devicec           	      óx  • U R                  XXFS9nU Vs/ s H  oˆR                  SS PM     n	nUR                  5       n
U R                  " U40 U
D6u  p¼UU	US.nUbÌ  U R                  USS[        R
                  S9nUR                  5       nUR                  SS[        R                  UR                  S5      UR                  S	5      S
.5        U R                  " SSU0UD6u  nnU Vs/ s H1  nUR                  S5      R                  [        R                  5      PM3     snUS'   [        XÕS9$ s  snf s  snf )z
Preprocess image-like inputs.
)r>   rc   rd   rf   rZ   N)Úpixel_valuesÚoriginal_sizesÚreshaped_input_sizesé   F)r>   Úexpected_ndimsrc   rd   r   r    )Údo_normalizeÚ
do_rescalerX   rW   Úpad_sizer>   r   Úlabels)ÚdataÚtensor_typer!   )Ú_prepare_image_like_inputsr]   ÚcopyÚ_preprocessr   ÚFIRSTÚupdater   ÚNEARESTÚpopÚsqueezeÚtoÚtorchÚint64r   )r;   r>   r?   rc   rd   re   rf   r7   rU   ri   Úimages_kwargsrh   rj   rq   Úprocessed_segmentation_mapsÚsegmentation_maps_kwargsÚ_Úms                     r-   Ú_preprocess_image_like_inputsÚ/SamImageProcessor._preprocess_image_like_inputs›   sa  € ð ×0Ñ0ØÐL]ð 1ð 
ˆñ 9?Ó?º¨uŸ+™+ b cÓ*¹ˆÐ?ØŸ™›ˆØ-1×-=Ò-=¸fÑ-VÈÑ-VÑ*ˆà(Ø,Ø$8ñ
ˆð Ñ(Ø*.×*IÑ*IØ(Ø Ø$Ü"2×"8Ñ"8ð	 +Jð +Ð'ð (.§{¡{£}Ð$Ø$×+Ñ+à$)Ø"'Ü 2× :Ñ :Ø4×8Ñ8¸ÓEØ 8× <Ñ <¸_Ó Mñôð .2×-=Ò-=ñ .Ø2ð.Ø6Nñ.Ñ*Ð'¨ñ E`Ó`ÒD_¸q˜aŸi™i¨›lŸo™o¬e¯k©kÖ:ÑD_Ñ`ˆD�‰Nä ÑBÐBùòA @ùò< as   •D2Ã+8D7Ú	do_resizeÚdo_center_cropÚ	crop_sizern   Úrescale_factorrm   Ú
image_meanÚ	image_stdÚdo_padro   Údisable_groupingc           	      óî  • [        XS9u  nn0 nUR                  5        H"  u  nnU(       a  U R                  UX4S9nUUU'   M$     [        UU5      nU Vs/ s H  nUR                  SS  PM     nn[        UUS9u  nn0 nUR                  5        H8  u  nnU(       a  U R                  UU5      nU R                  UXxXšU5      nUUU'   M:     [        UU5      nU(       a  U R                  UXÞS9nUU4$ s  snf )N)rŒ   )rU   rW   rX   rZ   )ro   rŒ   )r   Úitemsr^   r   r]   Úcenter_cropÚrescale_and_normalizeÚpad)r;   r>   r…   rW   rX   r†   r‡   rn   rˆ   rm   r‰   rŠ   r‹   ro   rŒ   r7   Úgrouped_imagesÚgrouped_images_indexÚresized_images_groupedr]   Ústacked_imagesÚresized_imagesrU   rj   Úprocessed_images_groupedÚprocessed_imagess                             r-   ru   ÚSamImageProcessor._preprocessÍ   s-  € ô& 0EÀVÑ/oÑ,ˆÐ,Ø!#ÐØ%3×%9Ñ%9Ö%;Ñ!ˆE�>ÞØ!%§¡°>È Ð!`�Ø,:Ð" 5Ó)ñ &<ô (Ð(>Ð@TÓUˆÙ>LÓMºn°U §¡¨B¨CÓ 0¹nÐÐMô 0EÀ^ÐfvÑ/wÑ,ˆÐ,Ø#%Ð Ø%3×%9Ñ%9Ö%;Ñ!ˆE�>ÞØ!%×!1Ñ!1°.À)Ó!L�à!×7Ñ7Ø 
¸LÐV_óˆNð /=Ð$ UÓ+ñ &<ô *Ð*BÐDXÓYÐæØ#Ÿx™xÐ(8À8˜xÐoÐàÐ!5Ð5Ð5ùò'  Ns   ÁC2z+np.ndarray | PIL.Image.Image | torch.TensorÚcrop_n_layersÚoverlap_ratioÚpoints_per_cropÚcrop_n_points_downscale_factorc                 óê   • U R                  U5      n[        UUUUUU5      u  p…pšUc  [        R                  " S5      nUR	                  U5      nUR	                  U5      nU
R	                  U5      n
X…Xš4$ )an  
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_boxesr|   rf   r{   )r;   rU   Útarget_sizerš   r›   rœ   r�   rf   Ú
crop_boxesÚcropped_imagesÚinput_labelss              r-   Úgenerate_crop_boxesÚ%SamImageProcessor.generate_crop_boxesü   s‚   € ð> ×"Ñ" 5Ó)ˆÜDXØØØØØØ*óE
ÑAˆ
 ^ð ‰>Ü—\’\ %Ó(ˆFØ—]‘] 6Ó*ˆ
Ø)×,Ñ,¨VÓ4ˆà#—‘ vÓ.ˆà¨NÐHÐHr,   c	                 ót  • Uu  pšUR                  SS5      nUR                  SS5      nUR                  S   UR                  S   :w  a  [        S5      eUR                  UR                  :w  a  UR	                  UR                  5      nUR                  S   n[
        R                  " U[
        R                  UR                  S9nUS:”  a  XÂU:„  -  nUS:”  a  [        XU5      nXÍU:„  -  nX,   nX   nX:„  n[        U5      n[        XôSSX©/5      ) nXì   nX   nXü   n[        XXš5      n[        U5      nXU4$ )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.©Údtyperf   ç        )Úflattenr]   r[   rf   r{   r|   ÚonesÚboolÚ_compute_stability_scoreÚ_batched_mask_to_boxÚ_is_box_near_crop_edgeÚ
_pad_masksÚ_mask_to_rle)r;   Ú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_masksÚSamImageProcessor.filter_masks-  sV  € ðF +8Ñ'ˆØ×'Ñ'¨¨1Ó-ˆ
Ø—‘˜a Ó#ˆà�;‰;�q‰>˜Z×-Ñ-¨aÑ0Ó0ÜÐRÓSÐSà�<‰<˜:×,Ñ,Ó,Ø#Ÿ™ u§|¡|Ó4ˆJà—[‘[ ‘^ˆ
ä—J’J˜z´·±ÀEÇLÁLÑQˆ	à˜SÓ Ø!°/Ñ%AÑBˆIð " CÓ'Ü7¸ÐOeÓfÐØ!Ð8NÑ%NÑOˆIàÑ&ˆØÑ ˆð Ñ&ˆÜ.¨uÓ5ˆä+Ø°°A°~Ð0Wó
ð 
ˆ	ð Ñ"ˆØÑ ˆØ)Ñ4ˆä˜5°_ÓUˆä˜UÓ#ˆà˜oÐ-Ð-r,   c                 óö  • Uc  U R                   OUnUS   US   4n[        U[        R                  [        R
                  45      (       a  UR                  5       n[        U[        R                  [        R
                  45      (       a  UR                  5       n/ n[        U5       HÎ  u  pš[        X   [        R
                  5      (       a  [        R                  " X   5      X'   O,[        X   [        R                  5      (       d  [        S5      e[        R                  " X   USSS9nUSSX9   S	   2SX9   S
   24   n[        R                  " XºSSS9nU(       a  X´:„  nUR                  U5        MÐ     U$ )a¦  
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.
Nr5   r6   zIInput masks should be a list of `torch.tensors` or a list of `np.ndarray`ÚbilinearF)ÚmodeÚalign_corners.r   r©   )ro   rG   r|   ÚTensorÚnpÚndarrayÚtolistÚ	enumerateÚ
from_numpyÚ	TypeErrorÚFÚinterpolateÚappend)r;   rµ   ri   rj   r»   Úbinarizero   Útarget_image_sizeÚoutput_masksÚir·   Úinterpolated_masks               r-   Úpost_process_masksÚ$SamImageProcessor.post_process_masks{  s]  € ð> %-Ñ$4�4—=’=¸(ˆØ% hÑ/°¸'Ñ1BÐCÐÜ�n¤u§|¡|´R·Z±ZÐ&@×AÑAØ+×2Ñ2Ó4ˆNÜÐ*¬U¯\©\¼2¿:¹:Ð,F×GÑGØ#7×#>Ñ#>Ó#@Ð àˆÜ )¨.Ö 9ÑˆAÜ˜%™(¤B§J¡J×/Ñ/Ü ×+Ò+¨E©HÓ5�’Ü ¡¬%¯,©,×7Ñ7ÜÐ kÓlÐlÜ !§¢¨e©hÐ8IÐPZÐjoÑ pÐØ 1°#Ð7SÐ9MÑ9PÐQRÑ9SÐ7SÐUqÐWkÑWnÐopÑWqÐUqÐ2qÑ rÐÜ !§¢Ð.?ÐU_ÐotÑ uÐÞØ$5Ñ$FÐ!Ø×ÑÐ 1Ö2ñ !:ð Ðr,   c                 ó   • [        XX45      $ )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)r;   Ú	all_masksÚ
all_scoresÚ	all_boxesÚcrops_nms_threshs        r-   Ú post_process_for_mask_generationÚ2SamImageProcessor.post_process_for_mask_generation°  s   € ô 1°È	ÓdÐdr,   r!   ©N)NN)r   ç¥âìÃgØÕ?é    r©   N)g)\�Âõ(ì?gffffffî?r   r©   )r¬   TN)4r"   r#   r$   r%   r   Úvalid_kwargsr   ÚBILINEARrX   r   r‰   r   rŠ   rW   r   r…   rn   rm   rc   r‹   ro   r    r   r:   r   r   r   rB   r)   r   r'   r(   r   rF   ÚtuplerS   r^   r¯   r   r   r   rƒ   ÚlistÚfloatru   r   r¦   rÄ   rÙ   rá   r+   Ú__classcell__)r<   s   @r-   r0   r0   <   sy  ø† à*€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ð er,   r0   rµ   rV   r»   r¼   c                 ó
  • XU-   :„  R                  S[        R                  S9R                  S[        R                  S9nXU-
  :„  R                  S[        R                  S9R                  S[        R                  S9nX4-  nU$ )Néÿÿÿÿ©r«   )Úsumr|   Ú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Ø$Ñ-ÐØÐr,   c                 ó.  • [         R                  " U 5      S:X  a2  [         R                  " / U R                  SS QSP7SU R                  06$ U R                  nUSS u  p#[         R
                  " U SS9u  pEU[         R                  " X$R                  S9SSS24   -  n[         R
                  " USS9u  puXbU) -  -   n[         R                  " USS9u  p…[         R
                  " U SS9u  p•U	[         R                  " X9R                  S9SSS24   -  n
[         R
                  " U
SS9u  pµX£U	) -  -   n
[         R                  " U
SS9u  pÅX¼:  Xx:  -  n[         R                  " XÈX·/SS9nXí) R                  S5      -  nUR                  " / USS QSP76 nU$ )	a   
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   NrZ   é   rf   rí   ©Údim©rf   )r|   ÚnumelÚzerosr]   rf   rM   ÚarangeÚminÚstackÚ	unsqueezeÚreshape)rµ   r]   r5   r6   Ú	in_heightr�   Ú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ô —9’9˜U¨Ñ+�L€IØ ¤5§<¢<°×?OÑ?OÑ#PÐQUÒWXÐQXÑ#YÑYÐÜ—i’iÐ 0°bÑ9�O€LØ'°Y°JÑ*?Ñ?ÐÜ—9’9Ð-°2Ñ6�L€Iô —)’)˜E rÑ*�K€HØ¤§¢¨e¿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¨kÐHÈbÑ
Q€CØ
�×)Ñ)¨"Ó-Ñ
-€Cð �+Š+Ð
%�u˜S˜b�zÐ
% 1Ò
%€CØ€Jr,   c                 óN  • [         R                  " U[         R                  U R                  S9n[         R                  " U[         R                  U R                  S9nUu  pg  n[         R                  " XgXg//U R                  S9n	[        U R                  5      S:X  a  U	R                  S5      n	X	-   R                  5       n [         R                  " XSSS24   USS9n
[         R                  " XSSS24   USS9n[         R                  " X«) 5      n
[         R                  " U
SS9$ )	zNFilter masks at the edge of a crop, but not at the edge of the original image.rª   rø   r   r©   Nr   )ÚatolÚrtolrö   )r|   Ú	as_tensorrê   rf   ÚtensorÚlenr]   rþ   ÚiscloseÚlogical_andÚany)ÚboxesÚcrop_boxÚorig_boxr  Úcrop_box_torchÚorig_box_torchÚleftÚtopr�   ÚoffsetÚnear_crop_edgeÚnear_image_edges               r-   r²   r²   ý  sê   € ä—_’_ X´U·[±[ÈÏÉÑV€NÜ—_’_ X´U·[±[ÈÏÉÑV€Nà�O€Dˆq�!Ü�\Š\˜D tÐ1Ð2¸5¿<¹<ÑH€Fä
ˆ5�;‰;Ó˜1ÓØ×!Ñ! !Ó$ˆØ‰^×"Ñ"Ó$€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                 óº   • Uu  pEpgUS:X  a  US:X  a  Xc:X  a  Xr:X  a  U $ X6U-
  -
  X'U-
  -
  p˜XHU-
  XYU-
  4n
[         R                  R                  R                  X
SS9$ )Nr   )Úvalue)r|   Únnr	   r‘   )rµ   r  r  r  r  r  ÚrightÚbottomÚpad_xÚpad_yr‘   s              r-   r³   r³     so   € Ø'Ñ€DˆuØˆqƒy�S˜A“X %Ó"5¸&Ó:OØˆà¨¡Ñ.°È¹|Ñ0Lˆ5Ø˜‘˜s¨C¡KÐ
0€CÜ�8‰8×Ñ×"Ñ" 5°QÐ"Ð7Ð7r,   r¢   rš   r›   rœ   r�   r@   c                 ón  • [        U [        5      (       a  [        S5      eU R                  SS n/ n[	        US-   5       H-  n[        XEU-  -  5      n	UR                  [        U	5      5        M/     [        X#U5      u  p«[        X X{X5      u  pÍ[        R                  " U
5      n
U
R                  5       n
[        R                  " U5      nUR                  S5      R                  SSSS5      n[        R                  " U5      n[        R                   " USS2SS2SS2S4   [        R"                  S9nX¤XÎ4$ )	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.rZ   Nr©   r   rk   r   rî   )rG   ré   r[   r]   Úranger)   rÓ   Ú_build_point_gridÚ_generate_per_layer_cropsÚ_generate_crop_imagesr|   r  rê   rý   rþ   ÚpermuteÚ	ones_liker}   )rU   r¢   rš   r›   rœ   r�   r·   Úpoints_gridr×   Ún_pointsr£   Ú
layer_idxsr¤   Úpoint_grid_per_cropr¥   s                  r-   r¡   r¡     s  € ô8 �%œ×ÑÜÐIÓJÐJØ—K‘K  Ð$€Mà€KÜ�= 1Ñ$Ö%ˆÜ�È!Ñ*KÑLÓMˆØ×ÑÔ,¨XÓ6Ö7ñ &ô 7°}ÐUbÓcÑ€Jä*?Ø˜;°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           	      óè  • / / pCUu  pV[        XV5      nUR                  SSXe/5        UR                  S5        [        U 5       GH  nSUS-   -  n	[        X-  SU	-  -  5      n
[        [        R
                  " X©S-
  -  U-   U	-  5      5      n[        [        R
                  " X©S-
  -  U-   U	-  5      5      n[        U	5       Vs/ s H  n[        Xº-
  U-  5      PM     nn[        U	5       Vs/ s H  n[        XÊ-
  U-  5      PM     nn[        Xï5       HK  u  nnUU[        UU-   U5      [        UU-   U5      /nUR                  U5        UR                  US-   5        MM     GM"     X44$ s  snf s  snf )aU  
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   rk   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„  € ð   �
Ø'Ñ€IÜ�YÓ)€Jð ×Ñ�q˜!˜XÐ1Ô2Ø×Ñ�aÔÜ˜×'ˆØ ¨1¡Ñ-ÐÜ�mÑ0°AÐ8HÑ4HÑIÓJˆäœŸš GÀ!Ñ/CÑ$DÀxÑ$OÐScÑ#cÓdÓeˆ
Üœ$Ÿ)š) WÀ1Ñ0DÑ%EÈ	Ñ%QÐUeÑ$eÓfÓgˆä@EÐFVÔ@WÓXÒ@W¸1”s˜JÑ0°AÑ5Ö6Ñ@WˆÐXÜAFÐGWÔAXÓYÒAX¸A”s˜KÑ1°QÑ6Ö7ÑAXˆÐYä  Ö:‰IˆD�#Ø˜œc $¨Ñ"3°XÓ>ÄÀCÈ+ÑDUÐW`Ó@aÐbˆCØ×Ñ˜cÔ"Ø×Ñ˜g¨™kÖ*ô ;ñ (ð Ð!Ð!ùò YùÚYs   ÃE*Ã,E/Ú
n_per_sidec                 ó  • SSU -  -  n[         R                  " USU-
  U 5      n[         R                  " USSS24   U S45      n[         R                  " USS2S4   SU 45      n[         R                  " X4/SS9R	                  SS5      nU$ )z;Generates a 2D grid of points evenly spaced in [0,1]x[0,1].r©   rk   Nrí   rö   )r|   ÚlinspaceÚtilerý   rÿ   )r?  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Ü�[Š[˜(Ð-°2Ñ6×>Ñ>¸rÀ1ÓE€FØ€Mr,   c                 óN  • / n/ n[        U 5       H�  u  pšU
u  p¼pÞUSS2XÎ2X½24   nUR                  U5        UR                  SS n[        R                  " U5      R                  SS9R                  S5      nX#U	      U-  n[        UUU5      nUR                  U5        M’     Xx4$ )z�
Takes as an input bounding boxes that are used to crop the image. Based in the crops, the corresponding points are
also passed.
NrZ   )r   )Údimsr   )rÎ   rÓ   r]   r|   r  Úfliprþ   Ú_normalize_coordinates)r£   rU   r-  r/  r¢   r·   rd   r¤   Útotal_points_per_cropr×   r  r  r  r"  r#  Ú
cropped_imÚcropped_im_sizeÚpoints_scalerF  Únormalized_pointss                       r-   r*  r*  z  sÀ   € ð €NØÐÜ  Ö,‰ˆØ#+Ñ ˆ�5Øš1˜c˜j¨$¨*Ð4Ñ5ˆ
à×Ñ˜jÔ)à$×*Ñ*¨2¨3Ð/ˆÜ—|’| OÓ4×9Ñ9¸tÐ9ÐD×NÑNÈqÓQˆà¨™]Ñ+¨lÑ:ˆÜ2°;ÀÈÓVÐØ×$Ñ$Ð%6Ö7ñ -ð Ð0Ð0r,   Úcoordsr·   c                 óB  • Uu  pEU S-  [        XE5      -  nXF-  XV-  p‡[        US-   5      n[        US-   5      n[        U5      R                  5       nU(       a  UR	                  SSS5      nUS   X…-  -  US'   US   Xt-  -  US'   U(       a  UR	                  SS5      nU$ )zw
Expects a numpy array of length 2 in the final dimension. Requires the original image size in (height, width)
format.
rK   rL   rí   rk   ).r   ).r©   rõ   )rM   r)   r   rê   rÿ   )	r¢   rP  r·   Úis_bounding_boxÚ
old_heightÚ	old_widthrP   Ú
new_heightÚ	new_widths	            r-   rJ  rJ  “  s´   € ð *Ñ€Jà˜#Ñ¤ JÓ :Ñ:€EØ&Ñ.°	Ñ0A�	Ü�I ‘OÓ$€IÜ�Z #Ñ%Ó&€Jä�fÓ×#Ñ#Ó%€FæØ—‘  A qÓ)ˆà˜F‘^ yÑ'<Ñ=€Fˆ6�NØ˜F‘^ zÑ'>Ñ?€Fˆ6�NæØ—‘  AÓ&ˆà€Mr,   Úrlec                 óÎ   • U S   u  p[         R                  " X-  [        S9nSnSnU S    H  nXSXDU-   & XF-  nU(       + nM     UR                  X!5      nUR	                  SS5      $ )z/Compute a binary mask from an uncompressed RLE.rW   rî   r   FÚcountsr©   )r|   Úemptyr¯   rÿ   Ú	transpose)rW  r5   r6   ÚmaskÚidxÚparityÚcounts          r-   Ú_rle_to_maskr`  ¯  sr   € à˜‘K�M€FÜ�;Š;�v‘~¬TÑ2€DØ
€CØ€FØ�X”ˆØ"(ˆS˜‘;ÐØ‰ˆØ”Šñ ð �<‰<˜Ó&€DØ�>‰>˜!˜QÓÐr,   c                 ó  • [        UR                  5       U[        R                  " UR                  S   5      US9nX   nU Vs/ s H  oPU   PM	     n nX$   nU  Vs/ s H  n[        U5      PM     nnXqX4$ s  snf s  snf )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ê   r|   rú   r]   r`  )Ú	rle_masksr¶   Ú
mask_boxesÚamg_crops_nms_threshÚkeep_by_nmsr×   rW  rµ   s           r-   rÜ   rÜ   ½  s‹   € ô Ø×ÑÓ ØÜ�[Š[˜×)Ñ)¨!Ñ,Ó-Ø*ñ	€Kð Ñ(€JÙ'2Ó3¢{ !˜1”¡{€IÐ3ØÑ(€JÙ*3Ó4ª) 3Œ\˜#Ö©)€EÐ4à˜iÐ3Ð3ùò	 4ùâ4s   ÁA7ÁA<c                 ó~  • U R                   u  pnU R                  SSS5      R                  S5      n U SS2SS24   U SS2SS24   -  nUR                  5       n/ n[	        U5       HÓ  nXUSS2S4   U:H  S4   S-   n[        U5      S:X  a>  XS4   S:X  a  UR                  X#/X#-  /S.5        OUR                  X#/SX#-  /S.5        Mc  USS USS -
  n	XS4   S:X  a  / OS/n
X¨S   R                  5       /U	R                  5       -   X#-  US   R                  5       -
  /-   -  n
UR                  X#/U
S.5        MÕ     U$ )zV
Encodes masks the run-length encoding (RLE), in the format expected by pycoco tools.
r   rk   r©   Nrí   )rW   rY  )	r]   r+  r­   Únonzeror'  r  rÓ   ÚitemrÍ   )Ú
input_maskr¿   r5   r6   ÚdiffÚchange_indicesr	  r×   Úcur_idxsÚbtw_idxsrY  s              r-   r´   r´   Ú  sr  € ð
 !+× 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 OÀÁÐ?OÑPÕQà—
‘
 V OÀÀ6Á>Ð?RÑSÔTÙØ˜A˜B�< (¨3¨B -Ñ/ˆØ! Q $Ñ'¨1Ó,‘°1°#ˆØ˜A‘;×#Ñ#Ó%Ð&¨¯©Ó):Ñ:¸f¹nÈxÐXZÉ|×O`ÑO`ÓObÑ>bÐ=cÑcÑcˆØ�
‰
˜V˜O°vÑ>Ö?ñ ð €Jr,   )rµ   rV   )g      4@)r   rä   rå   r©   rã   )F)gffffffæ?)rk  rV   )Cr&   r2  Úcollections.abcr   rt   r   Ú	itertoolsr   Útypingr   r   r   ÚnumpyrË   r|   Ú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   r0   rê   r)   r°   r±   r²   ré   r³   rè   r¡   r)  rÊ   r(  r*  rJ  r'   r(   r`  rÜ   r´   Ú__all__r!   r,   r-   Ú<module>r€     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,   