


import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


__UpperCamelCase     :    List[Any] 	=				logging.get_logger(__name__)

# General docstring
__UpperCamelCase     :    Optional[Any] 	=				'PoolFormerConfig'

# Base docstring
__UpperCamelCase     :    Tuple 	=				'sail/poolformer_s12'
__UpperCamelCase     :    int 	=				[1, 512, 7, 7]

# Image classification docstring
__UpperCamelCase     :    Optional[Any] 	=				'sail/poolformer_s12'
__UpperCamelCase     :    int 	=				'tabby, tabby cat'

__UpperCamelCase     :    Tuple 	=				[
    'sail/poolformer_s12',
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]





def 	_UpperCAmelCase							(  UpperCAmelCase   :      List[str]    ,						UpperCAmelCase   :      int = 0.0    ,						UpperCAmelCase   :      List[Any] = False   ):
      """simple docstring"""




      if drop_prob == 0.0 or not training:
            return input
      __lowerCamelCase  :   List[Any]							    =    1 - drop_prob
      __lowerCamelCase  :   int							    =    (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
      __lowerCamelCase  :   Optional[int]							    =    keep_prob + torch.rand(UpperCAmelCase    ,						dtype=input.dtype    ,						device=input.device   )
      random_tensor.floor_()  # binarize
      __lowerCamelCase  :   List[str]							    =    input.div(UpperCAmelCase   ) * random_tensor
      return output



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			int							,	_lowerCamelCase	:			Optional[float] = None				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   List[str]							    =    drop_prob

   def 	_snake_case     (	self	:			str							,	_lowerCamelCase	:			torch.Tensor				):






         '''simple docstring'''



         return drop_path(_lowerCamelCase							,	self.drop_prob							,	self.training				)


   def 	_snake_case     (	self	:			int				):






         '''simple docstring'''



         return "p={}".format(self.drop_prob				)



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			Dict							,	_lowerCamelCase	:			int							,	_lowerCamelCase	:			List[str]							,	_lowerCamelCase	:			Optional[int]							,	_lowerCamelCase	:			str							,	_lowerCamelCase	:			Optional[Any]							,	_lowerCamelCase	:			List[Any]=None				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   Union[str, Any]							    =    patch_size if isinstance(_lowerCamelCase							,	collections.abc.Iterable				) else (patch_size, patch_size)
         __lowerCamelCase  :   str							    =    stride if isinstance(_lowerCamelCase							,	collections.abc.Iterable				) else (stride, stride)
         __lowerCamelCase  :   List[str]							    =    padding if isinstance(_lowerCamelCase							,	collections.abc.Iterable				) else (padding, padding)

         __lowerCamelCase  :   Dict							    =    nn.Convad(_lowerCamelCase							,	_lowerCamelCase							,	kernel_size=_lowerCamelCase							,	stride=_lowerCamelCase							,	padding=_lowerCamelCase				)
         __lowerCamelCase  :   Dict							    =    norm_layer(_lowerCamelCase				) if norm_layer else nn.Identity()


   def 	_snake_case     (	self	:			Union[str, Any]							,	_lowerCamelCase	:			Dict				):






         '''simple docstring'''



         __lowerCamelCase  :   str							    =    self.projection(_lowerCamelCase				)
         __lowerCamelCase  :   List[str]							    =    self.norm(_lowerCamelCase				)
         return embeddings



class 				_UpperCamelCase			(    nn.GroupNorm    ):

   '''simple docstring'''







   def __init__(	self	:			str							,	_lowerCamelCase	:			Optional[Any]							,	**_lowerCamelCase	:			Optional[Any]				):






         '''simple docstring'''



         super().__init__(1							,	_lowerCamelCase							,	**_lowerCamelCase				)



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			Union[str, Any]							,	_lowerCamelCase	:			Any				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   Tuple							    =    nn.AvgPoolad(_lowerCamelCase							,	stride=1							,	padding=pool_size // 2							,	count_include_pad=_lowerCamelCase				)


   def 	_snake_case     (	self	:			str							,	_lowerCamelCase	:			Tuple				):






         '''simple docstring'''



         return self.pool(_lowerCamelCase				) - hidden_states



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			Tuple							,	_lowerCamelCase	:			Dict							,	_lowerCamelCase	:			Union[str, Any]							,	_lowerCamelCase	:			Any							,	_lowerCamelCase	:			int				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   Any							    =    nn.Convad(_lowerCamelCase							,	_lowerCamelCase							,	1				)
         __lowerCamelCase  :   List[Any]							    =    nn.Convad(_lowerCamelCase							,	_lowerCamelCase							,	1				)
         __lowerCamelCase  :   Union[str, Any]							    =    PoolFormerDropPath(_lowerCamelCase				)
         if isinstance(config.hidden_act							,	_lowerCamelCase				):
               __lowerCamelCase  :   List[str]							    =    ACTaFN[config.hidden_act]
         else:
               __lowerCamelCase  :   Tuple							    =    config.hidden_act


   def 	_snake_case     (	self	:			Tuple							,	_lowerCamelCase	:			List[Any]				):






         '''simple docstring'''



         __lowerCamelCase  :   Optional[Any]							    =    self.conva(_lowerCamelCase				)
         __lowerCamelCase  :   Dict							    =    self.act_fn(_lowerCamelCase				)
         __lowerCamelCase  :   Optional[int]							    =    self.drop(_lowerCamelCase				)
         __lowerCamelCase  :   Any							    =    self.conva(_lowerCamelCase				)
         __lowerCamelCase  :   int							    =    self.drop(_lowerCamelCase				)

         return hidden_states



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			int							,	_lowerCamelCase	:			Any							,	_lowerCamelCase	:			Any							,	_lowerCamelCase	:			Optional[Any]							,	_lowerCamelCase	:			Tuple							,	_lowerCamelCase	:			str							,	_lowerCamelCase	:			Tuple				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   Tuple							    =    PoolFormerPooling(_lowerCamelCase				)
         __lowerCamelCase  :   Any							    =    PoolFormerOutput(_lowerCamelCase							,	_lowerCamelCase							,	_lowerCamelCase							,	_lowerCamelCase				)
         __lowerCamelCase  :   Any							    =    PoolFormerGroupNorm(_lowerCamelCase				)
         __lowerCamelCase  :   Union[str, Any]							    =    PoolFormerGroupNorm(_lowerCamelCase				)

         # Useful for training neural nets
         __lowerCamelCase  :   str							    =    PoolFormerDropPath(_lowerCamelCase				) if drop_path > 0.0 else nn.Identity()
         __lowerCamelCase  :   Union[str, Any]							    =    config.use_layer_scale
         if config.use_layer_scale:
               __lowerCamelCase  :   Optional[int]							    =    nn.Parameter(
                   config.layer_scale_init_value * torch.ones((_lowerCamelCase)				)							,	requires_grad=_lowerCamelCase				)
               __lowerCamelCase  :   Dict							    =    nn.Parameter(
                   config.layer_scale_init_value * torch.ones((_lowerCamelCase)				)							,	requires_grad=_lowerCamelCase				)


   def 	_snake_case     (	self	:			Union[str, Any]							,	_lowerCamelCase	:			Union[str, Any]				):






         '''simple docstring'''



         if self.use_layer_scale:
               __lowerCamelCase  :   int							    =    self.pooling(self.before_norm(_lowerCamelCase				)				)
               __lowerCamelCase  :   Optional[Any]							    =    self.layer_scale_a.unsqueeze(-1				).unsqueeze(-1				) * pooling_output
               # First residual connection
               __lowerCamelCase  :   Optional[Any]							    =    hidden_states + self.drop_path(_lowerCamelCase				)
               __lowerCamelCase  :   Dict							    =    ()

               __lowerCamelCase  :   int							    =    self.output(self.after_norm(_lowerCamelCase				)				)
               __lowerCamelCase  :   Any							    =    self.layer_scale_a.unsqueeze(-1				).unsqueeze(-1				) * layer_output
               # Second residual connection
               __lowerCamelCase  :   Optional[int]							    =    hidden_states + self.drop_path(_lowerCamelCase				)

               __lowerCamelCase  :   List[Any]							    =    (output,) + outputs
               return outputs

         else:
               __lowerCamelCase  :   Dict							    =    self.drop_path(self.pooling(self.before_norm(_lowerCamelCase				)				)				)
               # First residual connection
               __lowerCamelCase  :   Dict							    =    pooling_output + hidden_states
               __lowerCamelCase  :   Any							    =    ()

               # Second residual connection inside the PoolFormerOutput block
               __lowerCamelCase  :   Dict							    =    self.drop_path(self.output(self.after_norm(_lowerCamelCase				)				)				)
               __lowerCamelCase  :   Tuple							    =    hidden_states + layer_output

               __lowerCamelCase  :   Optional[Any]							    =    (output,) + outputs
               return outputs



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			Union[str, Any]							,	_lowerCamelCase	:			Union[str, Any]				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   str							    =    config
         # stochastic depth decay rule
         __lowerCamelCase  :   int							    =    [x.item() for x in torch.linspace(0							,	config.drop_path_rate							,	sum(config.depths				)				)]

         # patch embeddings
         __lowerCamelCase  :   Tuple							    =    []
         for i in range(config.num_encoder_blocks				):
               embeddings.append(
                   PoolFormerEmbeddings(
                       patch_size=config.patch_sizes[i]							,	stride=config.strides[i]							,	padding=config.padding[i]							,	num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1]							,	hidden_size=config.hidden_sizes[i]							,	)				)
         __lowerCamelCase  :   Optional[int]							    =    nn.ModuleList(_lowerCamelCase				)

         # Transformer blocks
         __lowerCamelCase  :   Union[str, Any]							    =    []
         __lowerCamelCase  :   List[str]							    =    0
         for i in range(config.num_encoder_blocks				):
               # each block consists of layers
               __lowerCamelCase  :   Dict							    =    []
               if i != 0:
                     cur += config.depths[i - 1]
               for j in range(config.depths[i]				):
                     layers.append(
                         PoolFormerLayer(
                             _lowerCamelCase							,	num_channels=config.hidden_sizes[i]							,	pool_size=config.pool_size							,	hidden_size=config.hidden_sizes[i]							,	intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio				)							,	drop_path=dpr[cur + j]							,	)				)
               blocks.append(nn.ModuleList(_lowerCamelCase				)				)

         __lowerCamelCase  :   int							    =    nn.ModuleList(_lowerCamelCase				)


   def 	_snake_case     (	self	:			List[Any]							,	_lowerCamelCase	:			Dict							,	_lowerCamelCase	:			List[Any]=False							,	_lowerCamelCase	:			Optional[Any]=True				):






         '''simple docstring'''



         __lowerCamelCase  :   Optional[Any]							    =    () if output_hidden_states else None

         __lowerCamelCase  :   Any							    =    pixel_values
         for idx, layers in enumerate(zip(self.patch_embeddings							,	self.block				)				):
               __lowerCamelCase  :   Tuple							    =    layers
               # Get patch embeddings from hidden_states
               __lowerCamelCase  :   Union[str, Any]							    =    embedding_layer(_lowerCamelCase				)
               # Send the embeddings through the blocks
               for _, blk in enumerate(_lowerCamelCase				):
                     __lowerCamelCase  :   str							    =    blk(_lowerCamelCase				)
                     __lowerCamelCase  :   Union[str, Any]							    =    layer_outputs[0]

               if output_hidden_states:
                     __lowerCamelCase  :   str							    =    all_hidden_states + (hidden_states,)

         if not return_dict:
               return tuple(v for v in [hidden_states, all_hidden_states] if v is not None				)

         return BaseModelOutputWithNoAttention(last_hidden_state=_lowerCamelCase							,	hidden_states=_lowerCamelCase				)



class 				_UpperCamelCase			(    A    ):

   '''simple docstring'''







   a_					:				Any     =			PoolFormerConfig
   a_					:				Optional[Any]     =			"""poolformer"""
   a_					:				List[str]     =			"""pixel_values"""
   a_					:				str     =			True

   def 	_snake_case     (	self	:			Optional[int]							,	_lowerCamelCase	:			Optional[Any]				):






         '''simple docstring'''



         if isinstance(_lowerCamelCase							,	(nn.Linear, nn.Convad)				):
               module.weight.data.normal_(mean=0.0							,	std=self.config.initializer_range				)
               if module.bias is not None:
                     module.bias.data.zero_()
         elif isinstance(_lowerCamelCase							,	nn.LayerNorm				):
               module.bias.data.zero_()
               module.weight.data.fill_(1.0				)


   def 	_snake_case     (	self	:			Optional[Any]							,	_lowerCamelCase	:			Union[str, Any]							,	_lowerCamelCase	:			str=False				):






         '''simple docstring'''



         if isinstance(_lowerCamelCase							,	_lowerCamelCase				):
               __lowerCamelCase  :   str							    =    value

__UpperCamelCase     :    str 	=				R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

__UpperCamelCase     :    str 	=				R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`PoolFormerImageProcessor.__call__`] for details.\n'



@add_start_docstrings(
    "The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.",A,)
class 				_UpperCamelCase			(    A    ):

   '''simple docstring'''







   def __init__(	self	:			int							,	_lowerCamelCase	:			List[str]				):






         '''simple docstring'''



         super().__init__(_lowerCamelCase				)
         __lowerCamelCase  :   str							    =    config

         __lowerCamelCase  :   Tuple							    =    PoolFormerEncoder(_lowerCamelCase				)

         # Initialize weights and apply final processing
         self.post_init()

   def 	_snake_case     (	self	:			int				):






         '''simple docstring'''



         return self.embeddings.patch_embeddings


   @add_start_docstrings_to_model_forward(_lowerCamelCase				)
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC							,	output_type=_lowerCamelCase							,	config_class=_CONFIG_FOR_DOC							,	modality="""vision"""							,	expected_output=_EXPECTED_OUTPUT_SHAPE							,	)
   def 	_snake_case     (	self	:			Optional[int]							,	_lowerCamelCase	:			Optional[torch.FloatTensor] = None							,	_lowerCamelCase	:			Optional[bool] = None							,	_lowerCamelCase	:			Optional[bool] = None							,	):






         '''simple docstring'''



         __lowerCamelCase  :   List[str]							    =    (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         __lowerCamelCase  :   Optional[Any]							    =    return_dict if return_dict is not None else self.config.use_return_dict

         if pixel_values is None:
               raise ValueError("""You have to specify pixel_values"""				)

         __lowerCamelCase  :   Dict							    =    self.encoder(
             _lowerCamelCase							,	output_hidden_states=_lowerCamelCase							,	return_dict=_lowerCamelCase							,	)
         __lowerCamelCase  :   Tuple							    =    encoder_outputs[0]

         if not return_dict:
               return (sequence_output, None) + encoder_outputs[1:]

         return BaseModelOutputWithNoAttention(
             last_hidden_state=_lowerCamelCase							,	hidden_states=encoder_outputs.hidden_states							,	)



class 				_UpperCamelCase			(    nn.Module    ):

   '''simple docstring'''







   def __init__(	self	:			Any							,	_lowerCamelCase	:			Optional[int]				):






         '''simple docstring'''



         super().__init__()
         __lowerCamelCase  :   Any							    =    nn.Linear(config.hidden_size							,	config.hidden_size				)


   def 	_snake_case     (	self	:			Tuple							,	_lowerCamelCase	:			str				):






         '''simple docstring'''



         __lowerCamelCase  :   str							    =    self.dense(_lowerCamelCase				)
         return output



@add_start_docstrings(
    "\n    PoolFormer Model transformer with an image classification head on top\n    ",A,)
class 				_UpperCamelCase			(    A    ):

   '''simple docstring'''







   def __init__(	self	:			List[str]							,	_lowerCamelCase	:			Optional[Any]				):






         '''simple docstring'''



         super().__init__(_lowerCamelCase				)
         __lowerCamelCase  :   Union[str, Any]							    =    config.num_labels
         __lowerCamelCase  :   Union[str, Any]							    =    PoolFormerModel(_lowerCamelCase				)

         # Final norm
         __lowerCamelCase  :   Any							    =    PoolFormerGroupNorm(config.hidden_sizes[-1]				)
         # Classifier head
         __lowerCamelCase  :   int							    =    (
             nn.Linear(config.hidden_sizes[-1]							,	config.num_labels				) if config.num_labels > 0 else nn.Identity()
         )

         # Initialize weights and apply final processing
         self.post_init()


   @add_start_docstrings_to_model_forward(_lowerCamelCase				)
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT							,	output_type=_lowerCamelCase							,	config_class=_CONFIG_FOR_DOC							,	expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,	)
   def 	_snake_case     (	self	:			Tuple							,	_lowerCamelCase	:			Optional[torch.FloatTensor] = None							,	_lowerCamelCase	:			Optional[torch.LongTensor] = None							,	_lowerCamelCase	:			Optional[bool] = None							,	_lowerCamelCase	:			Optional[bool] = None							,	):






         '''simple docstring'''



         __lowerCamelCase  :   Optional[int]							    =    return_dict if return_dict is not None else self.config.use_return_dict

         __lowerCamelCase  :   Any							    =    self.poolformer(
             _lowerCamelCase							,	output_hidden_states=_lowerCamelCase							,	return_dict=_lowerCamelCase							,	)

         __lowerCamelCase  :   Optional[int]							    =    outputs[0]

         __lowerCamelCase  :   int							    =    self.classifier(self.norm(_lowerCamelCase				).mean([-2, -1]				)				)

         __lowerCamelCase  :   Tuple							    =    None
         if labels is not None:
               if self.config.problem_type is None:
                     if self.num_labels == 1:
                           __lowerCamelCase  :   Union[str, Any]							    =    "regression"
                     elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                           __lowerCamelCase  :   Dict							    =    "single_label_classification"
                     else:
                           __lowerCamelCase  :   List[str]							    =    "multi_label_classification"

               if self.config.problem_type == "regression":
                     __lowerCamelCase  :   Optional[Any]							    =    MSELoss()
                     if self.num_labels == 1:
                           __lowerCamelCase  :   Union[str, Any]							    =    loss_fct(logits.squeeze()							,	labels.squeeze()				)
                     else:
                           __lowerCamelCase  :   List[Any]							    =    loss_fct(_lowerCamelCase							,	_lowerCamelCase				)
               elif self.config.problem_type == "single_label_classification":
                     __lowerCamelCase  :   Any							    =    CrossEntropyLoss()
                     __lowerCamelCase  :   Union[str, Any]							    =    loss_fct(logits.view(-1							,	self.num_labels				)							,	labels.view(-1				)				)
               elif self.config.problem_type == "multi_label_classification":
                     __lowerCamelCase  :   List[Any]							    =    BCEWithLogitsLoss()
                     __lowerCamelCase  :   Any							    =    loss_fct(_lowerCamelCase							,	_lowerCamelCase				)

         if not return_dict:
               __lowerCamelCase  :   Union[str, Any]							    =    (logits,) + outputs[2:]
               return ((loss,) + output) if loss is not None else output

         return ImageClassifierOutputWithNoAttention(loss=_lowerCamelCase							,	logits=_lowerCamelCase							,	hidden_states=outputs.hidden_states				)







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import rescale, resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
		import PIL


SCREAMING_SNAKE_CASE__     					=			logging.get_logger(__name__)


def     lowercase	(    a     , a ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:Dict				     =						b.T
		SCREAMING_SNAKE_CASE_				:str				     =						np.sum(np.square(a )     , axis=1 )
		SCREAMING_SNAKE_CASE_				:List[Any]				     =						np.sum(np.square(a )     , axis=0 )
		SCREAMING_SNAKE_CASE_				:Optional[int]				     =						np.matmul(a     , a )
		SCREAMING_SNAKE_CASE_				:Any				     =						aa[:, None] - 2 * ab + ba[None, :]
		return d


def     lowercase	(    a     , a ):



		'''simple docstring'''




		SCREAMING_SNAKE_CASE_				:str				     =						x.reshape(-1     , 3 )
		SCREAMING_SNAKE_CASE_				:str				     =						squared_euclidean_distance(a     , a )
		return np.argmin(a     , axis=1 )



class 						_UpperCAmelCase      (     lowercase							):
		lowerCamelCase_	:			List[str]       			=  ["""pixel_values"""]






		def __init__(						self				:     Dict   ,  UpperCAmelCase				:     Optional[Union[List[List[int]], np.ndarray]] = None   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     Dict[str, int] = None   ,  UpperCAmelCase				:     PILImageResampling = PILImageResampling.BILINEAR   ,  UpperCAmelCase				:     bool = True   ,  UpperCAmelCase				:     bool = True   ,  **UpperCAmelCase				:     Union[str, Any]   ,  ):
				super().__init__(**UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						size if size is not None else {"height": 2_56, "width": 2_56}
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						get_size_dict(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:int				     =						np.array(UpperCAmelCase) if clusters is not None else None
				SCREAMING_SNAKE_CASE_				:List[Any]				     =						do_resize
				SCREAMING_SNAKE_CASE_				:Dict				     =						size
				SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						resample
				SCREAMING_SNAKE_CASE_				:Dict				     =						do_normalize
				SCREAMING_SNAKE_CASE_				:Tuple				     =						do_color_quantize






		def _snake_case		(						self				:     Union[str, Any]   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Dict[str, int]   ,  UpperCAmelCase				:     PILImageResampling = PILImageResampling.BILINEAR   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  **UpperCAmelCase				:     List[Any]   ,  ):
				SCREAMING_SNAKE_CASE_				:str				     =						get_size_dict(UpperCAmelCase)
				if "height" not in size or "width" not in size:
						raise ValueError(F"Size dictionary must contain both height and width keys. Got {size.keys()}")
				return resize(
				    UpperCAmelCase   ,  size=(size["height"], size["width"])   ,  resample=UpperCAmelCase   ,  data_format=UpperCAmelCase   ,  **UpperCAmelCase)






		def _snake_case		(						self				:     Union[str, Any]   ,  UpperCAmelCase				:     np.ndarray   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = None   ,  ):
				SCREAMING_SNAKE_CASE_				:int				     =						rescale(image=UpperCAmelCase   ,  scale=1 / 127.5   ,  data_format=UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:List[str]				     =						image - 1
				return image







		def _snake_case		(						self				:     List[str]   ,  UpperCAmelCase				:     ImageInput   ,  UpperCAmelCase				:     bool = None   ,  UpperCAmelCase				:     Dict[str, int] = None   ,  UpperCAmelCase				:     PILImageResampling = None   ,  UpperCAmelCase				:     bool = None   ,  UpperCAmelCase				:     Optional[bool] = None   ,  UpperCAmelCase				:     Optional[Union[List[List[int]], np.ndarray]] = None   ,  UpperCAmelCase				:     Optional[Union[str, TensorType]] = None   ,  UpperCAmelCase				:     Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST   ,  **UpperCAmelCase				:     Optional[Any]   ,  ):
				SCREAMING_SNAKE_CASE_				:Any				     =						do_resize if do_resize is not None else self.do_resize
				SCREAMING_SNAKE_CASE_				:Dict				     =						size if size is not None else self.size
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						get_size_dict(UpperCAmelCase)
				SCREAMING_SNAKE_CASE_				:Optional[int]				     =						resample if resample is not None else self.resample
				SCREAMING_SNAKE_CASE_				:Dict				     =						do_normalize if do_normalize is not None else self.do_normalize
				SCREAMING_SNAKE_CASE_				:List[str]				     =						do_color_quantize if do_color_quantize is not None else self.do_color_quantize
				SCREAMING_SNAKE_CASE_				:Tuple				     =						clusters if clusters is not None else self.clusters
				SCREAMING_SNAKE_CASE_				:Tuple				     =						np.array(UpperCAmelCase)

				SCREAMING_SNAKE_CASE_				:Dict				     =						make_list_of_images(UpperCAmelCase)

				if not valid_images(UpperCAmelCase):
						raise ValueError(
						    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
						    "torch.Tensor, tf.Tensor or jax.ndarray.")

				if do_resize and size is None or resample is None:
						raise ValueError("Size and resample must be specified if do_resize is True.")

				if do_color_quantize and clusters is None:
						raise ValueError("Clusters must be specified if do_color_quantize is True.")

				# All transformations expect numpy arrays.
				SCREAMING_SNAKE_CASE_				:Union[str, Any]				     =						[to_numpy_array(UpperCAmelCase) for image in images]

				if do_resize:
						SCREAMING_SNAKE_CASE_				:Tuple				     =						[self.resize(image=UpperCAmelCase   ,  size=UpperCAmelCase   ,  resample=UpperCAmelCase) for image in images]

				if do_normalize:
						SCREAMING_SNAKE_CASE_				:int				     =						[self.normalize(image=UpperCAmelCase) for image in images]

				if do_color_quantize:
						SCREAMING_SNAKE_CASE_				:Optional[Any]				     =						[to_channel_dimension_format(UpperCAmelCase   ,  ChannelDimension.LAST) for image in images]
						# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
						SCREAMING_SNAKE_CASE_				:Optional[int]				     =						np.array(UpperCAmelCase)
						SCREAMING_SNAKE_CASE_				:Tuple				     =						color_quantize(UpperCAmelCase   ,  UpperCAmelCase).reshape(images.shape[:-1])

						# flatten to (batch_size, height*width)
						SCREAMING_SNAKE_CASE_				:Any				     =						images.shape[0]
						SCREAMING_SNAKE_CASE_				:Dict				     =						images.reshape(UpperCAmelCase   ,  -1)

						# We need to convert back to a list of images to keep consistent behaviour across processors.
						SCREAMING_SNAKE_CASE_				:Any				     =						list(UpperCAmelCase)
				else:
						SCREAMING_SNAKE_CASE_				:List[Any]				     =						[to_channel_dimension_format(UpperCAmelCase   ,  UpperCAmelCase) for image in images]

				SCREAMING_SNAKE_CASE_				:str				     =						{"input_ids": images}
				return BatchFeature(data=UpperCAmelCase   ,  tensor_type=UpperCAmelCase)






