
    Z j6                         S r SSK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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  S\S\\ \\\4      4S jr! " S S\SS9r"\ " S S\
5      5       r#S/r$g)z!Image processor class for SegGPT.    )UnionN)
functional   )TorchvisionBackend)BatchFeature)group_images_by_shapereorder_images)IMAGENET_DEFAULT_MEANIMAGENET_DEFAULT_STDChannelDimension
ImageInputPILImageResamplingSizeDict)ImagesKwargsUnpack)
TensorTypeauto_docstringrequires_backends
num_labelsreturnc                     [        U S-  5      S-   nSU-  nS/n[        U 5       H@  nXAS-  -  nXAS-  -  U-  nXA-  nSXR-  -
  nSXb-  -
  n	SXr-  -
  n
UR                  XU
45        MB     U$ )NgUUUUUU?      )r   r   r         )intrangeappend)r   basemargin
color_listlocation	num_seq_r	num_seq_g	num_seq_bRGBs              ڃ/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/seggpt/image_processing_seggpt.pybuild_paletter*   '   s    ze$%)DD[F J*%a'	a'D0	O	)$$)$$)$$1)$ &     c                   $    \ rS rSr% Sr\\S'   Srg)SegGptImageProcessorKwargs;   a  
num_labels (`int`, *optional*):
    Number of classes in the segmentation task (excluding the background). If specified, a palette will be
    built, assuming that class_idx 0 is the background, to map the prompt mask from a plain segmentation map
    to a 3-channel RGB image. Not specifying this will result in the prompt mask being duplicated across the
    channel dimension when `do_convert_rgb` is `True`.
r    N)__name__
__module____qualname____firstlineno____doc__r   __annotations____static_attributes__r/   r+   r)   r-   r-   ;   s     Or+   r-   F)totalc                   J  ^  \ rS rSr\r\R                  r\	r
\rSSS.rSrSrSrSrSrS\\   4U 4S jjrS\S	\\\\\4      4S
 jrS'S\R4                  S\\\\\4      S-  S	\R4                  4S jjr\   S(S\S-  S\S-  S\S-  S\\   S	\4
U 4S jjj5       r  S)S\S\S-  S\S-  S\ S\!S\"\#-  S-  S\$\"S4   S-  S\S-  S	\4S jjr%S\S   S\ S\&SSS\ S\'S\ S \'\\'   -  S-  S!\'\\'   -  S-  S"\ S-  S	\S   4S# jr( S)S$\\\\4      S-  S\S-  4S% jjr)S&r*U =r+$ )*SegGptImageProcessorG   i  )heightwidthTNkwargsc                 &   > [         TU ]  " S0 UD6  g )Nr/   )super__init__)selfr=   	__class__s     r)   r@   SegGptImageProcessor.__init__U   s    "6"r+   r   r   c                     [        U5      $ )a  Build a palette to map the prompt mask from a single channel to a 3-channel RGB.

Args:
    num_labels (`int`):
        Number of classes in the segmentation task (excluding the background).

Returns:
    `list[tuple[int, int, int]]`: Palette to map the prompt mask to RGB.
)r*   )rA   r   s     r)   get_palette SegGptImageProcessor.get_paletteX   s     Z((r+   maskpalettec                    UR                   S:X  a  UR                  S5      nUR                  u  p4UGb  [        R                  " SX44[        R
                  S9n[        R                  " U5      nU H  nX'   nX:H  R                  [        R
                  5      n	[        R                  " U[        R
                  S9R                  SSS5      n
U[        R                  " U	S5      U
-  R                  [        R
                  5      -  nM     [        R                  " USS5      R                  [        R
                  5      nU$ [        R                  " U[        R                  S4   SSS9nU$ )a  Converts a segmentation map to RGB format.

Args:
    mask (`np.ndarray`):
        Segmentation map with shape `(height, width)` or `(1, height, width)` where pixel values
        represent the class index.
    palette (`list[tuple[int, int, int]]`, *optional*):
        Palette to use to convert the mask to RGB format. If unset, the mask is duplicated across
        the channel dimension.

Returns:
    `np.ndarray`: The mask in RGB format with shape `(3, height, width)`.
r   r   )dtyper   r   .)axis)ndimsqueezeshapenpzerosuint8uniqueastypearrayreshapeexpand_dimscliprepeatnewaxis)rA   rG   rH   r;   r<   rgb_maskclasses_in_mask	class_idx	rgb_value
class_mask	class_rgbs              r)   mask_to_rgb SegGptImageProcessor.mask_to_rgbd   s    99><<?D

xxF 2"((CH iioO,	#.	"/77A
HHYbhh?GG1aP	R^^J:YFNNrxxXX	 -
 wwxC077AH  yybjj#o!6BHr+   imagesprompt_imagesprompt_masksc                 ~   > [        S XU4 5       5      (       a  [        S5      eUb  UO/ n[        TU ]  " XRU40 UD6$ )a  
prompt_images (`ImageInput`, *optional*):
    Prompt images to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255.
prompt_masks (`ImageInput`, *optional*):
    Prompt masks to preprocess. Can be in the format of segmentation maps (no channels) or RGB images.
    If in the format of RGB images, `do_convert_rgb` should be set to `False`. If in the format of
    segmentation maps, specifying `num_labels` is recommended to build a palette to map the prompt mask
    from a single channel to a 3-channel RGB. If `num_labels` is not specified, the prompt mask will be
    duplicated across the channel dimension.
c              3   (   #    U  H  oS L v   M
     g 7fNr/   ).0vs     r)   	<genexpr>2SegGptImageProcessor.preprocess.<locals>.<genexpr>   s     H"GQDy"Gs   zFAt least one of images, prompt_images, prompt_masks must be specified.)all
ValueErrorr?   
preprocess)rA   rb   rc   rd   r=   _images_inputrB   s         r)   rn   SegGptImageProcessor.preprocess   sM    $ H6,"GHHHeff #)"4"w!-WPVWWr+   do_convert_rgbinput_data_formatreturn_tensorsdeviceztorch.devicec	                 ,   0 n
[        U[        5      =(       a    [        U5      S:H  (       + nU(       a'  U R                  USXWS9nU R                  " U40 U	D6U
S'   Ub'  U R                  USXWS9nU R                  " U40 U	D6U
S'   UGb  U(       a  U R                  USS[
        R                  US9nUb  U R                  U5      OS n/ nU Ht  nUR                  S5      R                  5       nU R                  UUS9nUR                  [        R                  " UR                  [        R                   5      5      5        Mv     UnOU R                  US	SUUS9n[#        U	5      n[$        R&                  US
'   U R                  " U40 UD6U
S'   [)        XS9$ )Nr   F)rb   rq   rr   rt   pixel_valuesprompt_pixel_valuesr   )rb   expected_ndimsrq   rr   rt   )rH   r   resamplerd   )datatensor_type)
isinstancelistlen_prepare_image_like_inputs_preprocessr   FIRSTrE   rM   numpyr`   r   torch
from_numpyrS   rO   float32dictr   NEARESTr   )rA   rb   rc   rd   rq   rr   rs   rt   r   r=   rz   _images_providedprepared_imagesprepared_prompt_imagesprepared_masksrH   	convertedmask_tensormask_nprgb_npmasks_kwargss                        r)   _preprocess_image_like_inputs2SegGptImageProcessor._preprocess_image_like_inputs   s     !+64 8 MS[A=MN"==eGX > O $(#3#3O#Nv#ND  $%)%D%D$UN_ &E &" +/*:*:;Q*\U[*\D&' #!%!@!@'#$#(&6&<&<! "A " ;E:P$**:6VZ	#1K)11!4::<G!--gw-GF$$U%5%5fmmBJJ6O%PQ $2 "+ "&!@!@'#$#(&7! "A "  <L'9'A'AL$#'#3#3N#Sl#SD BBr+   ztorch.Tensor	do_resizesizery   z7PILImageResampling | tvF.InterpolationMode | int | None
do_rescalerescale_factordo_normalize
image_mean	image_stddisable_groupingc           	      :   [        XS9u  p0 nUR                  5        H#  u  nnU(       a  U R                  UX45      nUX'   M%     [        X5      n[        UU
S9u  p0 nUR                  5        H  u  nnU R	                  UXVXxU	5      nUUU'   M!     [        UU5      $ )N)r   )r   itemsresizer	   rescale_and_normalize)rA   rb   r   r   ry   r   r   r   r   r   r   r=   grouped_imagesgrouped_images_indexresized_images_groupedrN   stacked_imagesresized_imagesprocessed_images_groupeds                      r)   r    SegGptImageProcessor._preprocess   s     0EV/o,!#%3%9%9%;!E>!%^T!L,:") &< ((>U/D^fv/w,#% %3%9%9%;!E>!77
LV_N /=$U+	 &< 68LMMr+   target_sizesc                    [        U S/5        UR                  nUSS2SS2UR                  S   S-  S2SS24   n[        R                  " U R
                  5      R                  UR                  5      n[        R                  " U R                  5      R                  UR                  5      nUR                  SSSS5      U-  U-   nUR                  SSSS5      n[        R                  " US-  SS5      n/ nSnUb  U R                  U5      OSn	U	bc  [        R                  " U	5      R                  UR                  [        R                  S9nUR                  u  p  n
UR                  SSUS-   U5      n[        U5       H  u  pUb=  [        R                  R                   R#                  UR%                  S5      X,   S	S
9S   nUbu  UR                  u  pnUR                  SSS5      R                  UUSU5      nUU-
  n[        R&                  " US5      n[        R(                  " USS9nUR+                  SS9nOUR-                  SS9R/                  5       nUR1                  U5        M     U$ )a  
Converts the output of [`SegGptImageSegmentationOutput`] into segmentation maps. Only supports PyTorch.

Args:
    outputs ([`SegGptImageSegmentationOutput`]):
        Raw outputs of the model.
    target_sizes (`list[tuple[int, int]]`, *optional*):
        List of length `batch_size`, where each item corresponds to the requested final size `(height, width)`
        of each prediction. If left to `None`, predictions will not be resized.
    num_labels (`int`, *optional*):
        Number of classes in the segmentation task (excluding the background). If specified, a palette will be
        built to map prediction masks from RGB values back to class indices. Should match the value used during
        preprocessing.

Returns:
    `list[torch.Tensor]` of length `batch_size`, where each item is a semantic segmentation map of shape
    `(height, width)`. Each entry corresponds to a semantic class id.
r   Nr   r   r   r   r   )rt   rJ   nearest)r   mode)dim)r   
pred_masksrN   r   tensorr   tort   r   permuterW   rE   floatview	enumeratennr   interpolate	unsqueezepowsumargminmeanr   r   )rA   outputsr   r   masksstdr   semantic_segmentationpalette_tensorrH   _num_channelsidxrG   channelsr;   r<   distpreds                      r)   "post_process_semantic_segmentation7SegGptImageProcessor.post_process_semantic_segmentation   s@   , 	$	* "" aEKKNa/1145 ll4>>*--ell;||DOO,//=aAq)C/$6aAq)

53;3/ "2<2H$"":.d"\\'255U\\QVQ\Q\5]N$)KK!AQ+00AzA~|TN"5)IC'xx**66NN1%%*" 7  	 %*.**'%||Aq!,11&%HMn,yyq)yy2.{{r{*yyQy'++-!((.% *( %$r+   r/   rg   )NNN)NN),r0   r1   r2   r3   r-   valid_kwargsr   BICUBICry   r
   r   r   r   r   r   r   r   rq   r   r   r@   r   r}   tuplerE   rO   ndarrayr`   r   r   r   rn   boolr   strr   r   r   r   r   r   r   r6   __classcell__)rB   s   @r)   r9   r9   G   s   -L!))H&J$IC(DIJLNJ#(B!C #
)c 
)d5c33G.H 
)

 T%S#:N5ORV5V bdblbl B  %)+/*.	XT!X "D(X !4'	X
 34X 
X X@ 59!%>C>C "D(>C !4'	>C
 >C ,>C j(4/>C c>)*T1>C $J>C 
>C@N^$N N 	N
 LN N N N DK'$.N 4;&-N +N 
n	NB dhC%%)%S/%:T%AC%VY\`V`C% C%r+   r9   )%r4   typingr   r   rO   r   torchvision.transforms.v2r   tvFimage_processing_backendsr   image_processing_utilsr   image_transformsr   r	   image_utilsr
   r   r   r   r   r   processing_utilsr   r   utilsr   r   r   r   r}   r   r*   r-   r9   __all__r/   r+   r)   <module>r      s    (    7 ; 2 E  5 B B
c d5c3+?&@ (	U 	 y%- y% y%x "
"r+   