
    ^jq              
          d Z ddlZddlm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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  G d ded      Z 	 	 d$ddde!e"e"f   dz  de"dz  fdZ#de!e$e"f   de%e"e"f   fdZ&de'ejP                     de'e'e"      de%e'ejP                     e'e'e"      f   fdZ)d Z*d%dZ+	 	 	 d&de,de,d e%e"e"f   dz  fd!Z-e G d" d#e	             Z.d#gZ/y)'zImage processor class for EoMT.    N)Union)
functional   )TorchvisionBackend)'SemanticSegmentationPostProcessorOutput)BatchFeature)get_size_with_aspect_ratiogroup_images_by_shapereorder_images)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STDChannelDimension
ImageInputPILImageResamplingSizeDict)ImagesKwargsUnpack)
TensorTypeauto_docstringfilter_out_non_signature_kwargsc                   ,    e Zd ZU dZeed<   edz  ed<   y)EomtImageProcessorKwargsa{  
    do_split_image (`bool`, *optional*, defaults to `self.do_split_image`):
        Whether to split the input images into overlapping patches for semantic segmentation. If set to `True`, the
        input images will be split into patches of size `size["shortest_edge"]` with an overlap between patches.
        Otherwise, the input images will be padded to the target size.
    ignore_index (`int`, *optional*, defaults to `self.ignore_index`):
        Label to be assigned to background pixels in segmentation maps. If provided, segmentation map pixels
        denoted with 0 (background) will be replaced with `ignore_index`.
    do_split_imageNignore_index)__name__
__module____qualname____doc__bool__annotations__int     y/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/eomt/image_processing_eomt.pyr   r   *   s     *r#   r   F)totalsegmentation_maptorch.Tensorinstance_id_to_semantic_idr   c                 r   |t        j                  | dk(  || dz
        } t        j                  |       }||||k7     }|D cg c]  }| |k(  	 }}|rt        j                  |d      }n/t        j                  dg| j
                  | j                        }|vt        j                  |j
                  d   | j                        }t        |      D ]9  \  }}|||j                         dz   n|j                            }||dz
  n|||<   ; n|}|j                         |j                         fS c c}w )Nr      dimdevice)torchwhereuniquestackzerosshaper.   	enumerateitemfloatlong)	r&   r(   r   
all_labelsibinary_maskslabelslabelclass_ids	            r$   -convert_segmentation_map_to_binary_masks_fastr?   :   sE   
  ;;'71'<lL\_`L`a./J
l :;
5?@%*@L@{{<Q7{{A#?(8(>(>#?HXH_H_` "-Z--a09I9P9PQ!*- 	OHAu1|G_5::<!3CejeoeoeqsH(4(@1hF1I	O .. As   D4	size_dictreturnc                 &    | d   }| d   xs |}||fS )z.Returns the height and width from a size dict.shortest_edgelongest_edger"   )r@   target_heighttarget_widths      r$   get_target_sizerG   Y   s&    o.M^,=L,&&r#   patchesoffsetsc                     t        t        ||             }|j                  d        t        | \  }}t        |      t        |      fS )z@Sorts patches and offsets according to the original image index.c                     | d   d   S )Nr   r"   )xs    r$   <lambda>z-reorder_patches_and_offsets.<locals>.<lambda>g   s    !Q r#   )key)listzipsort)rH   rI   combinedsorted_offsetssorted_patchess        r$   reorder_patches_and_offsetsrU   a   sG    
 C)*HMM'M(%((^"NNn!555r#   c                     | j                   d   |j                   d   cxk(  r|j                   d   k(  st        d       t        d      |j                  |      ||kD  z  }| |   ||   ||   fS )a	  
    Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
    `labels`.

    Args:
        masks (`torch.Tensor`):
            A tensor of shape `(num_queries, height, width)`.
        scores (`torch.Tensor`):
            A tensor of shape `(num_queries)`.
        labels (`torch.Tensor`):
            A tensor of shape `(num_queries)`.
        object_mask_threshold (`float`):
            A number between 0 and 1 used to binarize the masks.
    Raises:
        `ValueError`: Raised when the first dimension doesn't match in all input tensors.
    Returns:
        `tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
        < `object_mask_threshold`.
    r   z1mask, scores and labels must have the same shape!)r4   
ValueErrorne)masksscoresr<   object_mask_threshold
num_labelsto_keeps         r$   remove_low_and_no_objectsr^   m   sy    ( KKNfll1o@a@LMM ALMMii
#v0E'EFG>6'?F7O;;r#   c                     | |k(  }|j                         }||   |k\  }|j                         }||z  }	|	j                         }
|dkD  xr |dkD  xr |
dkD  }|r||z  }|j                         |kD  sd}||	fS )Nr   F)sumr6   )mask_labels
mask_probskmask_thresholdoverlap_mask_area_thresholdmask_kmask_k_areaoriginal_maskoriginal_area
final_maskfinal_mask_areamask_exists
area_ratios                r$   check_segment_validityrn      s    AF**,K qM^3M!%%'M-'J nn&O/Oma&7OOa<OK =0
 #>>K
""r#   rd   re   target_sizec                 b   || j                   d   n|d   }|| j                   d   n|d   }t        j                  ||ft        j                  | j                        dz
  }	g }
| j                         } |d d d d f   | z  j                  d      }d}i }t        |j                   d         D ]~  }||   j                         }t        || |||      \  }}|s+|r||v r||v r	||   |	|<   >|||<   ||	|<   t        ||   j                         d      }|
j                  |||d       |dz  } |	|
fS )Nr*   r      )dtyper.      idlabel_idscore)r4   r/   r3   r8   r.   sigmoidargmaxranger6   rn   roundappend)rb   pred_scorespred_labelsstuff_classesrd   re   ro   heightwidthsegmentationsegmentsra   current_segment_idstuff_memory_listrc   
pred_classrl   rj   segment_scores                      r$   compute_segmentsr      s    %0$7Za [^F#.#6JQKNE;;ejjIZIZ[^__LH ##%Jq$}-
:BB1EK (*;$$Q'(   ^((*
 #9Q8S#
Z Z=8..+<Z+HZ(0B!*-#5Z k!n113Q7(&&	
 	a7 8 !!r#   c                       e Zd ZeZej                  ZeZ	e
ZdddZdZdZdZdZdZdZdZdee   f fdZdej.                  d	ed
ee   deeef   fdZdej.                  d	edej.                  fdZe	 	 d2dedeej.                     dz  de eef   dz  dee   de!f
 fd       Z"	 d3dededz  de eef   dz  de#de$de%e&z  dz  de'e%df   dz  dee   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  fd#Z*d$ej.                  d%eeeeef      d&eeeef      d	e e%ef   deej.                     f
d'Z+d$ej.                  d&eeeef      d	e e%ef   deej.                     fd(Z,	 	 d4d&eeeef      d	e e%ef   dz  d)e#dd*fd+Z-	 	 	 	 	 d5d&eeeef      d,e)d-e)d.e)d/ee   dz  d	e e%ef   dz  fd0Z. e/       	 	 d6d&eeeef      d,e)d	e e%ef   dz  fd1       Z0 xZ1S )7EomtImageProcessori  rC   rD   FTNkwargsc                 $    t        |   di | y )Nr"   )super__init__)selfr   	__class__s     r$   r   zEomtImageProcessor.__init__   s    "6"r#   imagessizeimage_indicesrA   c                    g g }}|j                   \  }}}}|j                  }	t        ||      }
t        j                  |
|	z        }||	z  |
z
  }|dkD  r||dz
  z  nd}t        |      D ]  }t        ||	|z
  z        }||	z   }||kD  r|dddd||ddf   }n|dddddd||f   }t        t        j                  |d            D ]-  \  }}|j                  |       |j                  ||   ||g       /  ||fS )zCSlices an image into overlapping patches for semantic segmentation.r*   r   Nr+   )r4   rC   maxmathceilrz   r!   r5   r/   unbindr|   )r   r   r   r   rH   patch_offsets_r   r   
patch_sizelonger_sidenum_patchestotal_overlapoverlap_per_patchr:   startendbatch_patch	batch_idxsingles                       r$   _split_imagezEomtImageProcessor._split_image   s3    "$R$ll1fe''
&%(iij 89#j0;>ALqM[1_=VW{# 	MAZ*;;<=E*$C~$Q59a%78$Q1eCi%78%.u||KQ/O%P M!	6v&$$mI&>s%KLM	M %%r#   c                 0   |j                   \  }}}}t        |j                  |j                  xs |j                  d      \  }}t	        d||z
        }t	        d||z
        }	d|	d|f}
t
        j                  j                  j                  ||
dd      }|S )z5Pads the image to the target size using zero padding.r   r   constantg        )modevalue)	r4   rG   rC   rD   r   r/   nnr   pad)r   r   r   r   r   r   rE   rF   pad_hpad_wpaddingpadded_imagess               r$   _padzEomtImageProcessor._pad  s    $ll1fe&5"00$BSBSBiW[WiWij'
#| A}v-.A|e+,eQ&++//jX[/\r#   segmentation_mapsr(   c                 (    t        |   |||fi |S )a'  
        segmentation_maps (`ImageInput`, *optional*):
            The segmentation maps to preprocess for corresponding images.
        instance_id_to_semantic_id (`list[dict[int, int]]` or `dict[int, int]`, *optional*):
            A mapping between object instance ids and class ids.
        )r   
preprocess)r   r   r   r(   r   r   s        r$   r   zEomtImageProcessor.preprocess  s!     w!&*;=Wb[abbr#   do_convert_rgbinput_data_formatreturn_tensorsr.   ztorch.devicec                 f   | j                  ||||      }|j                  dd      }	|j                         }
i } | j                  |fi |
\  }}||d<   ||d<   || j                  |ddt        j
                        }|j                         }|j                  ddt        j                  d	        | j                  dd
|i|\  }}|D cg c]0  }|j                  d      j                  t        j                        2 }}g g }}t        |      D ]P  \  }}t        |t              r||   }n|}t!        |||	      \  }}|j#                  |       |j#                  |       R ||d<   ||d<   |r&|D cg c]  }t        j$                  |       c}|d<   t'        ||g d      S c c}w c c}w )z/
        Preprocess image-like inputs.
        )r   r   r   r.   r   Npixel_valuesr   rq   F)r   expected_ndimsr   r   )do_normalize
do_rescaleresampler   r   )r   ra   class_labels)r   ra   r   )datatensor_typeskip_tensor_conversionr"   )_prepare_image_like_inputspopcopy_preprocessr   FIRSTupdater   NEARESTsqueezetor/   int64r5   
isinstancerO   r?   r|   tensorr   )r   r   r   r(   r   r   r   r.   r   r   images_kwargsr   processed_imagesr   processed_segmentation_mapssegmentation_maps_kwargsr   r&   ra   r   idxinstance_idrY   classesrI   s                            r$   _preprocess_image_like_inputsz0EomtImageProcessor._preprocess_image_like_inputs!  s    00.L]fl 1 
 zz.$7*:$*:*:6*S]*S'-/^ -_(*.*I*I( $"2"8"8	 +J +' (.{{}$$++$)"' 2 : :	 .>T-=-= .2.6N.*' Up+@P ((+..u{{;+' + )+BK)23N)O -%%8$?"<S"AK"<K!N$!-"w ""5)##G,-  #.D#/D JW$XwU\\'%:$XD!&#S
 	
7+2 %Ys   5F)7F.r'   	do_resizer   z7PILImageResampling | tvF.InterpolationMode | int | Noner   rescale_factorr   r   do_pad
image_mean	image_stddisable_groupingc           	      R   g }t        ||      \  }}i }|j                         D ]   \  }}|r| j                  |||      }|||<   " t        ||      }|rt        ||      \  }}g g }}|j                         D ]j  \  }}|j                         D cg c]  \  }\  }}||k(  s| }}}}| j	                  |||      \  }}|j                  |       |j                  |       l t        ||      \  }}|	rOt        ||      \  }}|j                         D ci c]  \  }}|| j                  ||       }}}t        ||      }t        ||      \  }}i }|j                         D ]   \  }}| j                  |||||
|      }|||<   " t        ||      }||fS c c}}}w c c}}w )z4Preprocesses the input images and masks if provided.)r   )imager   r   )	r
   itemsresizer   r   extendrU   r   rescale_and_normalize)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   grouped_imagesgrouped_images_indexresized_images_groupedr4   stacked_imagesrH   original_idx	img_shaper   original_indicessplit_patchesrI   padded_groupedprocessed_images_groupedr   s                                 r$   r   zEomtImageProcessor._preprocesso  s   " /DV^n/o,,!#%3%9%9%; 	;!E>!%>W_!`,:"5)	;   68LM3Hbr3s0N0%']G)7)=)=)? .%~EYE_E_Ea$ $%A\>IqenrwewL$  $ *.):):>4Qa)b&w}-$$W-. %@$W!FM3Hbr3s0N0TbThThTj;P5.tyy66N  $N4HIF/DV^n/o,,#% %3%9%9%; 	=!E>!77
NL*V_N /=$U+		=
 **BDXY..1$s   F
%F
F#segmentation_logitsr   target_sizesc                 T   |j                   d   }g }g }|D ]~  }t        ||d   |d         \  }	}
|j                  t        j                  ||	|
f|j
                               |j                  t        j                  ||	|
f|j
                                t        |      D ]  \  }\  }}}||   d   ||   d   kD  r6||   dd||ddfxx   ||   z  cc<   ||   dd||ddfxx   dz  cc<   Q||   dddd||fxx   ||   z  cc<   ||   dddd||fxx   dz  cc<    g }t        t        ||            D ]d  \  }\  }}||j                  d      z  }t        j                  j                  j                  |d   ||   d	d
      d   }|j                  |       f |S )a  
        Reconstructs full-size semantic segmentation logits from patch predictions.

        Args:
            segmentation_logits (`torch.Tensor`):
                A tensor of shape `(num_patches, num_classes, patch_height, patch_width)` representing predicted logits
                for each image patch.
            patch_offsets (`list[tuple[int, int, int]]`):
                A list of tuples where each tuple contains:
                - `image_index` (int): Index of the original image this patch belongs to.
                - `start` (int): Start pixel index of the patch along the long dimension (height or width).
                - `end` (int): End pixel index of the patch along the long dimension.
            target_sizes (`list[tuple[int, int]]`):
                list of original (height, width) dimensions for each image before preprocessing.
            size (`dict[str, int]`):
                A size dict which was used to resize.
        r*   rC   rD   r-   r   N)minN.bilinearFr   r   align_corners)r4   r	   r|   r/   r3   r.   r5   rP   clampr   r   interpolate)r   r   r   r   r   num_classesaggregated_logitspatch_counts
image_sizer   r   	patch_idx	image_idxpatch_start	patch_endreconstructed_logitsr   	logit_sumcountaveraged_logitsresized_logitss                        r$   merge_image_patchesz&EomtImageProcessor.merge_image_patches  s	   0 *//2& 	nJ6z4CXZ^_mZnoMFE$$U[[+vu1MViVpVp%qr[&%,HQdQkQk lm	n ?H>V 	J:I:	;	I&q)L,CA,FF!),QI0Eq-HIM`ajMkkIY';y+@!(CDID!),Q;y3H-HIM`ajMkkIY'1k).C(CDID	J  "'05F1U'V 		8#C#)U'%++!+*<<O"XX00<<	*!#&#	 = 
 N !''7		8 $#r#   c                    g }t        |      D ]p  \  }}t        ||d   |d         \  }}||   ddd|d|f   }	t        j                  j                  j                  |	d   |dd      d   }
|j                  |
       r |S )	zJRestores panoptic segmentation logits to their original image resolutions.rC   rD   Nr   r   Fr   r   )r5   r	   r/   r   r   r   r|   )r   r   r   r   r  r   original_sizerE   rF   cropped_logitsupsampled_logitss              r$   unpad_imagezEomtImageProcessor.unpad_image  s     "+L"9 	4C*DtO4d>6J+'M< 15a-,6VWN$xx22>>y)J^c  ?    !!"23	4 r#   return_segmentation_scoreszBlist[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]c                    ||n| j                   }|j                  }|j                  }|j                  }t	        |      }t
        j                  j                  j                  ||d      }|j                  d      dddf   }	|j                         }
t        j                  d|	|
      }|r| j                  ||||      }nrg }t        t        |            D ]Y  }t
        j                  j                  j                  ||   j                  d      ||   dd	
      }|j!                  |d          [ |D cg c]!  }t#        |j%                  d      |d      # }}|s|D cg c]  }|j&                   }}|S c c}w c c}w )a@  
        Converts the output of [`EomtForUniversalSegmentation`] into semantic segmentation maps.

        Args:
            outputs ([`EomtForUniversalSegmentation`]):
                Raw outputs of the model.
            target_sizes (`list[tuple[int, int]]`):
                A list of tuples (`tuple[int, int]`) containing the target size (height, width) of each image in the
                batch.
            size (`dict[str, int]`, *optional*):
                The size to which the intermediate masks are interpolated. Defaults to `self.size`.
            return_segmentation_scores (`bool`, *optional*, defaults to `False`):
                Whether to return segmentation scores alongside the segmentation map. When `True`, each element of
                the returned list is a [`SemanticSegmentationPostProcessorOutput`] with fields `segmentation`
                (class IDs, shape `(height, width)`) and `segmentation_scores` (shape `(num_classes, height, width)`).

        Returns:
            `list[torch.Tensor]` or `list[SemanticSegmentationPostProcessorOutput]`: When
            `return_segmentation_scores=False` (default), a list of length `batch_size` where each item is a
            segmentation map of shape `(height, width)` with class IDs. When `return_segmentation_scores=True`,
            a list of [`SemanticSegmentationPostProcessorOutput`] with fields `segmentation` (class IDs, shape
            `(height, width)`) and `segmentation_scores` (shape `(num_classes, height, width)`). In both cases,
            `(height, width)` corresponds to the target size.
        Nr   r   r   r+   .zbqc, bqhw -> bchwr   Fr   )r   segmentation_scores)r   )r   masks_queries_logitsclass_queries_logitsr   rG   r/   r   r   r   softmaxrx   einsumr  rz   len	unsqueezer|   r   ry   r   )r   outputsr   r   r	  r  r  r   output_sizemasks_classesmasks_probsr   output_logitsr   r  logitsemantic_segmentationr6   s                     r$   "post_process_semantic_segmentationz5EomtImageProcessor.post_process_semantic_segmentation  s   > 'tTYY&;;&;;--%d+$xx22>>   ?  
 -444<S#2#XF*224#ll+>{[ 445H-YegklMMS!456 8!&!4!4!@!@',6616=%c*#"'	 "A " $$^A%678 '	!
  4&+llql&9RWX!
 !
 *CX$Y4T%6%6$Y!$Y$$!
 %Zs   9&E>'F	thresholdrd   re   r   c                    ||n| j                   }|j                  }|j                  }	|	j                  d   }
|	j                  d   dz
  }t	        |      }t
        j                  j                  j                  ||d      }| j                  |||      }|	j                  d      j                  d      \  }}g }t        |
      D ]  }t        ||   ||   ||   ||      \  }}}|j                  d   dk  rH|||   n|j                  dd \  }}t        j                  ||f      dz
  }|j                  |g d       yt!        |||||||||   nd	      \  }}|j                  ||d        |S )
zIPost-processes model outputs into final panoptic segmentation prediction.Nr   r  r*   r   r  r+   r   segments_info)rb   r}   r~   r   rd   re   ro   )r   r  r  r4   rG   r/   r   r   r   r  r  r   rz   r^   r3   r|   r   )r   r  r   r  rd   re   r   r   r  r  
batch_sizer\   r  mask_probs_batchpred_scores_batchpred_labels_batchresultsr:   rb   r}   r~   r   r   r   r   s                            r$   "post_process_panoptic_segmentationz5EomtImageProcessor.post_process_panoptic_segmentationB  s    'tTYY&;;&;;)//2
)//3a7
%d+$xx22>>   ?  
  ++,@,PTU/C/K/KPR/K/S/W/WXZ/[,,z" 	VA3L #%6q%9;LQ;OQZ\f40J[
 "a'3?3KQQ[QaQabcbdQe${{FE?;a?rRS%5%''+-,G/;/GLOT&"L( NNL8TU-	V. r#   c           
      h   ||n| j                   }|j                  }|j                  }t        |      }t        j
                  j                  j                  ||d      }| j                  |||      }|j                  }	|j                  d   }
|j                  d   }g }t        |
      D ]  }||   }||   }|j                  d      dddf   j                  d      \  }}|dkD  j                         }|j                         j!                  d	      |j!                  d	      z  j#                  d	      |j!                  d	      j#                  d	      d
z   z  }||z  }t	        j$                  ||   |	      d	z
  }g g }}d}t        |      D ]  }||   j'                         }t	        j(                  ||   dk(        r2||k\  s8||||   d	k(  <   |j+                  |||   j'                         t-        |d      d       |d	z  }|j+                  ||           |j+                  ||d        |S )zDPost-processes model outputs into Instance Segmentation Predictions.Nr   r  r   r  r+   .r*   gư>r-   rs   rt   r  )r   r  r  rG   r/   r   r   r   r  r.   r4   rz   r  r   r7   rx   flattenr`   r3   r6   allr|   r{   )r   r  r   r  r   r  r  r  r!  r.   r   num_queriesr$  r:   	mask_pred
mask_classrZ   pred_classes
pred_masksmask_scoresr}   r   instance_mapsr   r   jrw   s                              r$   "post_process_instance_segmentationz5EomtImageProcessor.post_process_instance_segmentation{  sa    'tTYY&;;&;;%d+$xx22>>   ?  
  ++,@,PTU%,,)//2
*004z" !	VA(+I-a0J $.#5#5"#5#=c3B3h#G#K#KB#O FL#a-..0J %,,.66q9J<N<Nq<QQVVWXY""1%))!,t3K !;.K ;;|AvFJL&("8M!";' 8#A++-yyA!!34)9K7ILA!!34OO"4(4Q(<(<(>%*5!_ '!+&!((A78 NNL8TUC!	VD r#   NN)N)NF)皙?      ?r4  NN)r4  N)2r   r   r   r   valid_kwargsr   BILINEARr   r   r   r   r   r   default_to_squarer   r   r   r   r   r   r   r   r/   Tensorr   rO   r!   tupler   r   r   r   dictr   r   r   r   strr   r   r   r7   r   r  r  r  r%  r   r2  __classcell__)r   s   @r$   r   r      sD   +L!**H&J$I #6DIJLNFL#(@!A #&5<< &x &PTUXPY &^cdhjndn^o &85<< x ELL   8<<@	cc  -4c %)cNT$9	c
 12c 
c c. 59L
L
 &,L
 %)cNT$9	L

 L
 ,L
 j(4/L
 c>)*T1L
 12L
 
L
\7/^$7/ 7/ 	7/
 L7/ 7/ 7/ 7/ 7/ 7/ DK'$.7/ 4;&-7/ +7/r7$"\\7$ E#sC-017$ 5c?+	7$
 38n7$ 
ell	7$r"\\ 5c?+ 38n	
 
ell	2 '++0J% 5c?+J% 38nt#	J%
 %)J% 
NJ%`  #-0*.&*7 5c?+7 	7
 7 &+7 Cy4'7 38nt#7r %&
 &*? 5c?+? 	?
 38nt#? '?r#   r   r3  )r5  r4  )r5  r4  N)0r   r   typingr   r/   torchvision.transforms.v2r   tvFimage_processing_backendsr   image_processing_outputsr   image_processing_utilsr   image_transformsr	   r
   r   image_utilsr   r   r   r   r   r   processing_utilsr   r   utilsr   r   r   r   r;  r!   r?   r<  r:  rG   rO   r9  rU   r^   rn   r7   r   r   __all__r"   r#   r$   <module>rI     s`   &    7 ; O 2 a a  5 |5 $ 9=#/$/ $S#X 5/ */>'tCH~ '%S/ '	6%,,	6*.tCy/	6
4tDI./	6<8#6  ),*.3"
 3" "'3" sCx4'3"l e+ e eP  
 r#   