
    ^j,                        d 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 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mZ  ej>                  e       Z! G d ded      Z"e G d de             Z#dgZ$y)z$Image processor class for MobileViT.    )UnionN)
functional   )TorchvisionBackend)'SemanticSegmentationPostProcessorOutput)BatchFeature)group_images_by_shapereorder_images)IMAGENET_STANDARD_MEANIMAGENET_STANDARD_STDChannelDimension
ImageInputPILImageResamplingSizeDict)ImagesKwargsUnpack)
TensorTypeauto_docstringloggingrequires_backendsc                   &    e Zd ZU dZeed<   eed<   y)MobileVitImageProcessorKwargsa  
    do_flip_channel_order (`bool`, *optional*, defaults to `self.do_flip_channel_order`):
        Whether to flip the color channels from RGB to BGR or vice versa.
    do_reduce_labels (`bool`, *optional*, defaults to `self.do_reduce_labels`):
        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0
        is used for background, and background itself is not included in all classes of a dataset (e.g.
        ADE20k). The background label will be replaced by 255.
    do_flip_channel_orderdo_reduce_labelsN)__name__
__module____qualname____doc__bool__annotations__     /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/mobilevit/image_processing_mobilevit.pyr   r   -   s      r"   r   F)totalc                       e Zd ZdZeZej                  Ze	Z
eZddiZd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e	 d)dededz  d	ee   def fd       Z	 d)d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   fdZ$d*dZ%	 	 d+de#d   dede&dddede&ded e'd!edz  d"ed#ede#d   fd$Z(	 	 d,d%e#e)e*e*f      dz  d&edd'fd(Z+ xZ,S )-MobileViTImageProcessorzSTorchvision backend for MobileViT with flip_channel_order and reduce_label support.shortest_edge   F   )heightwidthTNkwargsc                 $    t        |   di | y )Nr!   )super__init__)selfr,   	__class__s     r#   r/   z MobileViTImageProcessor.__init__O   s    "6"r"   imagessegmentation_mapsreturnc                 &    t        |   ||fi |S )zp
        segmentation_maps (`ImageInput`, *optional*):
            The segmentation maps to preprocess.
        )r.   
preprocess)r0   r2   r3   r,   r1   s       r#   r6   z"MobileViTImageProcessor.preprocessR   s     w!&*;FvFFr"   do_convert_rgbinput_data_formatreturn_tensorsdeviceztorch.devicec                    | j                  ||||      }|j                         }d|d<   i }	 | j                  |fi ||	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 }
}|
|	d
<   t        |	|      S c c}w )z"Handle extra inputs beyond images.)r2   r7   r8   r:   Fr   pixel_values   )r2   expected_ndimsr7   r8   )
do_rescaler   resampler2   r   labels)datatensor_typer!   )_prepare_image_like_inputscopy_preprocessr   FIRSTupdater   NEARESTsqueezetotorchint64r   )r0   r2   r3   r7   r8   r9   r:   r,   images_kwargsrB   processed_segmentation_mapssegmentation_maps_kwargsprocessed_segmentation_maps                r#   _preprocess_image_like_inputsz5MobileViTImageProcessor._preprocess_image_like_inputs_   s9    00.L]fl 1 
 ,1()/t//H-H^(*.*I*I( $"2"8"8	 +J +' (.{{}$$++"'-2 2 : :	 +;$*:*: +2+6N+' 3N+. +221588E+' + 9DN>BB+s   35C<rA   torch.Tensorc           	      f   t        t        |            D ]  }||   }t        j                  |dk(  t        j                  d|j
                  |j                        |      }|dz
  }t        j                  |dk(  t        j                  d|j
                  |j                        |      }|||<    |S )z/Reduce label values by 1, replacing 0 with 255.r      )dtyper:         )rangelenrL   wheretensorrV   r:   )r0   rA   idxlabels       r#   reduce_labelz$MobileViTImageProcessor.reduce_label   s    V% 	 C3KEKK
ELLEKKX]XdXd,eglmEAIEKKell3ekkZ_ZfZf.ginoEF3K	  r"   c                     |j                   dk(  r|j                         }|g d   |dd |S |j                   dk(  r&|j                         }|ddg df   |ddddf<   |S |S )zFlip RGB to BGR or vice versa.r   )r=   rW   r   r      N)ndimclone)r0   r2   flippeds      r#   flip_channel_orderz*MobileViTImageProcessor.flip_channel_order   si    ;;!llnG!),GAaLN[[AllnG$Q	\2GAqsFONr"   	do_resizesizer@   z7PILImageResampling | tvF.InterpolationMode | int | Nonedo_center_crop	crop_sizer?   rescale_factordisable_groupingr   r   c                    |
r| j                  |      }t        ||	      \  }}i }|j                         D ]  \  }}|r| j                  |||      }|||<   ! t	        ||      }t        ||	      \  }}i }|j                         D ]E  \  }}|r| j                  ||      }|r| j                  ||      }|r| j                  |      }|||<   G t	        ||      }|S )z#Custom preprocessing for MobileViT.)rk   )r_   r	   itemsresizer
   center_croprescalere   )r0   r2   rf   rg   r@   rh   ri   r?   rj   rk   r   r   r,   grouped_imagesgrouped_images_indexresized_images_groupedshapestacked_imagesresized_imagesprocessed_images_groupedprocessed_imagess                        r#   rF   z#MobileViTImageProcessor._preprocess   s     &&v.F/DV^n/o,,!#%3%9%9%; 	;!E>!%^T8!L,:"5)	; ((>@TU/D^fv/w,,#% %3%9%9%; 	=!E>!%!1!1.)!L!%nn!M$!%!8!8!H.<$U+	= **BDXYr"   target_sizesreturn_segmentation_scoreszBlist[torch.Tensor] | list[SemanticSegmentationPostProcessorOutput]c                    t        | d       |j                  }t        |      }|t        |      t        |      k7  rt        d      t	        |t
        j                        r|j                         }g }t        |      D ]y  }t
        j                  j                  j                  ||   j                  d      ||   dd      }|j                  t        |d   j                  d      |d   d	             { n;t        |      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 [`MobileViTForSemanticSegmentation`] into semantic segmentation maps.

        Args:
            outputs ([`MobileViTForSemanticSegmentation`]):
                Raw outputs of the model.
            target_sizes (`list[tuple[int, int]]`, *optional*):
                List of tuples corresponding to the requested final size (height, width) of each prediction.
            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 (if `target_sizes` is specified).
        rL   zTMake sure that you pass in as many target sizes as the batch dimension of the logitsr   )dimbilinearF)rg   modealign_corners)segmentationsegmentation_scores)rB   )r   logitsrZ   
ValueError
isinstancerL   TensortolistrY   nnr   interpolate	unsqueezeappendr   argmaxr   )r0   outputsry   rz   r   
batch_sizesemantic_segmentationr]   resized_logitsiitems              r#   "post_process_semantic_segmentationz:MobileViTImageProcessor.post_process_semantic_segmentation   sx   6 	$([
#6{c,// j  ,5+224$&!Z( !&!4!4!@!@3K))a)0|C7Hzin "A " &,,;,:1,=,D,D,D,K3A!3D	" z*	%  8*0)*:*:q*:*AZ`abZcd%! % *CX$Y4T%6%6$Y!$Y$$% %Zs   	,E=E)N)r2   rS   r4   rS   )FT)NF)-r   r   r   r   r   valid_kwargsr   BICUBICr@   r   
image_meanr   	image_stdrg   default_to_squareri   rf   rh   r?   do_normalizer7   r   r   r   r/   r   r   r   r6   r   r   strr   r   rR   listr_   re   r   floatrF   tupleintr   __classcell__)r1   s   @r#   r&   r&   ;   s)   ]0L!))H'J%IS!D-IINJLN #(E!F #  04
G
G &,
G 67	
G
 

G 
G& 59/C/C &,/C 	/C
 ,/C j(4//C c>)*T1/C 
/Cb4#7 D<P 2 "'&*& ^$&  &  	& 
 L&  &  &  &  &  +&  &   $&  
n	& V 6:+0	=% 5c?+d2=% %)	=%
 
N=%r"   r&   )%r   typingr   rL   torchvision.transforms.v2r   tvFimage_processing_backendsr   image_processing_outputsr   image_processing_utilsr   image_transformsr	   r
   image_utilsr   r   r   r   r   r   processing_utilsr   r   utilsr   r   r   r   
get_loggerr   loggerr   r&   __all__r!   r"   r#   <module>r      s    +   7 ; O 2 E  5  
		H	%L  Q%0 Q% Q%h %
%r"   