



from typing import Optional, Union

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

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, 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_mobilenet_va import MobileNetVaConfig


__snake_case       :	Tuple            =logging.get_logger(__name__)


# General docstring
__snake_case       :	str            ='MobileNetV1Config'

# Base docstring
__snake_case       :	List[Any]            ='google/mobilenet_v1_1.0_224'
__snake_case       :	List[Any]            =[1, 1_0_2_4, 7, 7]

# Image classification docstring
__snake_case       :	Tuple            ='google/mobilenet_v1_1.0_224'
__snake_case       :	Dict            ='tabby, tabby cat'


__snake_case       :	Dict            =[
    'google/mobilenet_v1_1.0_224',
    'google/mobilenet_v1_0.75_192',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]






def 			lowerCAmelCase__	(					lowerCamelCase_	:	str ,lowerCamelCase_	:	Any ,lowerCamelCase_	:	List[str]=None):





				'''simple docstring'''

				lowerCAmelCase__  :       int				=  {}

				if isinstance(lowerCamelCase_ ,lowerCamelCase_):
								lowerCAmelCase__  :       Tuple				=  model.mobilenet_va
				else:
								lowerCAmelCase__  :       str				=  model

				lowerCAmelCase__  :       int				=  '''MobilenetV1/Conv2d_0/'''
				lowerCAmelCase__  :       Optional[int]				=  backbone.conv_stem.convolution.weight
				lowerCAmelCase__  :       Dict				=  backbone.conv_stem.normalization.bias
				lowerCAmelCase__  :       Any				=  backbone.conv_stem.normalization.weight
				lowerCAmelCase__  :       Optional[int]				=  backbone.conv_stem.normalization.running_mean
				lowerCAmelCase__  :       int				=  backbone.conv_stem.normalization.running_var

				for i in range(13):
								lowerCAmelCase__  :       Union[str, Any]				=  i + 1
								lowerCAmelCase__  :       Any				=  i * 2

								lowerCAmelCase__  :       List[Any]				=  backbone.layer[pt_index]
								lowerCAmelCase__  :       List[Any]				=  f"""MobilenetV1/Conv2d_{tf_index}_depthwise/"""
								lowerCAmelCase__  :       Union[str, Any]				=  pointer.convolution.weight
								lowerCAmelCase__  :       Dict				=  pointer.normalization.bias
								lowerCAmelCase__  :       Tuple				=  pointer.normalization.weight
								lowerCAmelCase__  :       int				=  pointer.normalization.running_mean
								lowerCAmelCase__  :       List[Any]				=  pointer.normalization.running_var

								lowerCAmelCase__  :       Optional[Any]				=  backbone.layer[pt_index + 1]
								lowerCAmelCase__  :       Dict				=  f"""MobilenetV1/Conv2d_{tf_index}_pointwise/"""
								lowerCAmelCase__  :       Any				=  pointer.convolution.weight
								lowerCAmelCase__  :       Dict				=  pointer.normalization.bias
								lowerCAmelCase__  :       Optional[int]				=  pointer.normalization.weight
								lowerCAmelCase__  :       int				=  pointer.normalization.running_mean
								lowerCAmelCase__  :       Dict				=  pointer.normalization.running_var

				if isinstance(lowerCamelCase_ ,lowerCamelCase_):
								lowerCAmelCase__  :       Optional[Any]				=  '''MobilenetV1/Logits/Conv2d_1c_1x1/'''
								lowerCAmelCase__  :       Optional[int]				=  model.classifier.weight
								lowerCAmelCase__  :       Optional[int]				=  model.classifier.bias

				return tf_to_pt_map






def 			lowerCAmelCase__	(					lowerCamelCase_	:	List[Any] ,lowerCamelCase_	:	Optional[int] ,lowerCamelCase_	:	Optional[Any]):





				'''simple docstring'''

				try:
								import numpy as np
								import tensorflow as tf
				except ImportError:
								logger.error(
								    '''Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '''
								    '''https://www.tensorflow.org/install/ for installation instructions.''')
								raise

				# Load weights from TF model
				lowerCAmelCase__  :       str				=  tf.train.list_variables(lowerCamelCase_)
				lowerCAmelCase__  :       Union[str, Any]				=  {}
				for name, shape in init_vars:
								logger.info(f"""Loading TF weight {name} with shape {shape}""")
								lowerCAmelCase__  :       Optional[Any]				=  tf.train.load_variable(lowerCamelCase_ ,lowerCamelCase_)
								lowerCAmelCase__  :       Union[str, Any]				=  array

				# Build TF to PyTorch weights loading map
				lowerCAmelCase__  :       List[str]				=  _build_tf_to_pytorch_map(lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_)

				for name, pointer in tf_to_pt_map.items():
								logger.info(f"""Importing {name}""")
								if name not in tf_weights:
												logger.info(f"""{name} not in tf pre-trained weights, skipping""")
												continue

								lowerCAmelCase__  :       Dict				=  tf_weights[name]

								if "depthwise_weights" in name:
												logger.info('''Transposing depthwise''')
												lowerCAmelCase__  :       List[str]				=  np.transpose(lowerCamelCase_ ,(2, 3, 0, 1))
								elif "weights" in name:
												logger.info('''Transposing''')
												if len(pointer.shape) == 2:  # copying into linear layer
																lowerCAmelCase__  :       Any				=  array.squeeze().transpose()
												else:
																lowerCAmelCase__  :       Optional[Any]				=  np.transpose(lowerCamelCase_ ,(3, 2, 0, 1))

								if pointer.shape != array.shape:
												raise ValueError(f"""Pointer shape {pointer.shape} and array shape {array.shape} mismatched""")

								logger.info(f"""Initialize PyTorch weight {name} {array.shape}""")
								lowerCAmelCase__  :       Optional[int]				=  torch.from_numpy(lowerCamelCase_)

								tf_weights.pop(lowerCamelCase_ ,lowerCamelCase_)
								tf_weights.pop(name + '''/RMSProp''' ,lowerCamelCase_)
								tf_weights.pop(name + '''/RMSProp_1''' ,lowerCamelCase_)
								tf_weights.pop(name + '''/ExponentialMovingAverage''' ,lowerCamelCase_)

				logger.info(f"""Weights not copied to PyTorch model: {', '.join(tf_weights.keys())}""")
				return model






def 			lowerCAmelCase__	(					lowerCamelCase_	:	torch.Tensor ,lowerCamelCase_	:	nn.Convad):





				'''simple docstring'''

				lowerCAmelCase__		,	lowerCAmelCase__  :       List[str]				=  features.shape[-2:]
				lowerCAmelCase__		,	lowerCAmelCase__  :       List[str]				=  conv_layer.stride
				lowerCAmelCase__		,	lowerCAmelCase__  :       Tuple				=  conv_layer.kernel_size

				if in_height % stride_height == 0:
								lowerCAmelCase__  :       List[Any]				=  max(kernel_height - stride_height ,0)
				else:
								lowerCAmelCase__  :       List[Any]				=  max(kernel_height - (in_height % stride_height) ,0)

				if in_width % stride_width == 0:
								lowerCAmelCase__  :       str				=  max(kernel_width - stride_width ,0)
				else:
								lowerCAmelCase__  :       Dict				=  max(kernel_width - (in_width % stride_width) ,0)

				lowerCAmelCase__  :       Union[str, Any]				=  pad_along_width // 2
				lowerCAmelCase__  :       List[str]				=  pad_along_width - pad_left
				lowerCAmelCase__  :       Union[str, Any]				=  pad_along_height // 2
				lowerCAmelCase__  :       Tuple				=  pad_along_height - pad_top

				lowerCAmelCase__  :       str				=  (pad_left, pad_right, pad_top, pad_bottom)
				return nn.functional.pad(lowerCamelCase_ ,lowerCamelCase_ ,'''constant''' ,0.0)



class  lowerCamelCase__    (							nn.Module):




		'''simple docstring'''



		def __init__(self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = 1	,__lowerCamelCase = 1	,__lowerCamelCase = False	,__lowerCamelCase = True	,__lowerCamelCase = True	,)  ->    None:

						"""simple docstring"""






						super().__init__()
						lowerCAmelCase__  :       int				=  config

						if in_channels % groups != 0:
										raise ValueError(f"""Input channels ({in_channels}) are not divisible by {groups} groups."""				)
						if out_channels % groups != 0:
										raise ValueError(f"""Output channels ({out_channels}) are not divisible by {groups} groups."""				)

						lowerCAmelCase__  :       Union[str, Any]				=  0 if config.tf_padding else int((kernel_size - 1) / 2				)

						lowerCAmelCase__  :       List[Any]				=  nn.Convad(
						    in_channels=__lowerCamelCase	,out_channels=__lowerCamelCase	,kernel_size=__lowerCamelCase	,stride=__lowerCamelCase	,padding=__lowerCamelCase	,groups=__lowerCamelCase	,bias=__lowerCamelCase	,padding_mode='''zeros'''	,)

						if use_normalization:
										lowerCAmelCase__  :       Optional[int]				=  nn.BatchNormad(
										    num_features=__lowerCamelCase	,eps=config.layer_norm_eps	,momentum=0.9997	,affine=__lowerCamelCase	,track_running_stats=__lowerCamelCase	,)
						else:
										lowerCAmelCase__  :       List[str]				=  None

						if use_activation:
										if isinstance(__lowerCamelCase	,__lowerCamelCase				):
														lowerCAmelCase__  :       Any				=  ACTaFN[use_activation]
										elif isinstance(config.hidden_act	,__lowerCamelCase				):
														lowerCAmelCase__  :       Dict				=  ACTaFN[config.hidden_act]
										else:
														lowerCAmelCase__  :       Optional[int]				=  config.hidden_act
						else:
										lowerCAmelCase__  :       Union[str, Any]				=  None



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    torch.Tensor:

						"""simple docstring"""






						if self.config.tf_padding:
										lowerCAmelCase__  :       int				=  apply_tf_padding(__lowerCamelCase	,self.convolution				)
						lowerCAmelCase__  :       List[Any]				=  self.convolution(__lowerCamelCase				)
						if self.normalization is not None:
										lowerCAmelCase__  :       Optional[int]				=  self.normalization(__lowerCamelCase				)
						if self.activation is not None:
										lowerCAmelCase__  :       Any				=  self.activation(__lowerCamelCase				)
						return features



class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_			=MobileNetVaConfig
		snake_case_			=load_tf_weights_in_mobilenet_va
		snake_case_			="""mobilenet_v1"""
		snake_case_			="""pixel_values"""
		snake_case_			=False



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    None:

						"""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.BatchNormad				):
										module.bias.data.zero_()
										module.weight.data.fill_(1.0				)


__snake_case       :	Tuple            =R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    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 ([`MobileNetV1Config`]): 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'

__snake_case       :	Optional[int]            =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            [`MobileNetV1ImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'



@add_start_docstrings(
    """The bare MobileNetV1 model outputting raw hidden-states without any specific head on top."""   ,       lowerCamelCase__   ,       )
class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self	,__lowerCamelCase	,__lowerCamelCase = True				)  ->    List[str]:

						"""simple docstring"""






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

						lowerCAmelCase__  :       List[Any]				=  32
						lowerCAmelCase__  :       Dict				=  max(int(depth * config.depth_multiplier				)	,config.min_depth				)

						lowerCAmelCase__  :       List[Any]				=  MobileNetVaConvLayer(
						    __lowerCamelCase	,in_channels=config.num_channels	,out_channels=__lowerCamelCase	,kernel_size=3	,stride=2	,)

						lowerCAmelCase__  :       Tuple				=  [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]

						lowerCAmelCase__  :       str				=  nn.ModuleList()
						for i in range(13				):
										lowerCAmelCase__  :       Optional[int]				=  out_channels

										if strides[i] == 2 or i == 0:
														depth *= 2
														lowerCAmelCase__  :       Optional[Any]				=  max(int(depth * config.depth_multiplier				)	,config.min_depth				)

										self.layer.append(
										    MobileNetVaConvLayer(
										        __lowerCamelCase	,in_channels=__lowerCamelCase	,out_channels=__lowerCamelCase	,kernel_size=3	,stride=strides[i]	,groups=__lowerCamelCase	,)				)

										self.layer.append(
										    MobileNetVaConvLayer(
										        __lowerCamelCase	,in_channels=__lowerCamelCase	,out_channels=__lowerCamelCase	,kernel_size=1	,)				)

						lowerCAmelCase__  :       Optional[int]				=  nn.AdaptiveAvgPoolad((1, 1)				) if add_pooling_layer else None

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



		def 	lowerCAmelCase__   (self	,__lowerCamelCase				)  ->    Any:

						"""simple docstring"""






						raise NotImplementedError



		@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 	lowerCAmelCase__   (self	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,)  ->    Union[tuple, BaseModelOutputWithPoolingAndNoAttention]:

						"""simple docstring"""






						lowerCAmelCase__  :       str				=  (
						    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
						)
						lowerCAmelCase__  :       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__  :       Any				=  self.conv_stem(__lowerCamelCase				)

						lowerCAmelCase__  :       int				=  () if output_hidden_states else None

						for i, layer_module in enumerate(self.layer				):
										lowerCAmelCase__  :       Any				=  layer_module(__lowerCamelCase				)

										if output_hidden_states:
														lowerCAmelCase__  :       Union[str, Any]				=  all_hidden_states + (hidden_states,)

						lowerCAmelCase__  :       List[str]				=  hidden_states

						if self.pooler is not None:
										lowerCAmelCase__  :       List[Any]				=  torch.flatten(self.pooler(__lowerCamelCase				)	,start_dim=1				)
						else:
										lowerCAmelCase__  :       int				=  None

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

						return BaseModelOutputWithPoolingAndNoAttention(
						    last_hidden_state=__lowerCamelCase	,pooler_output=__lowerCamelCase	,hidden_states=__lowerCamelCase	,)



@add_start_docstrings(
    """
    MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """   ,       lowerCamelCase__   ,       )
class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		def __init__(self	,__lowerCamelCase				)  ->    None:

						"""simple docstring"""






						super().__init__(__lowerCamelCase				)

						lowerCAmelCase__  :       List[str]				=  config.num_labels
						lowerCAmelCase__  :       Optional[Any]				=  MobileNetVaModel(__lowerCamelCase				)

						lowerCAmelCase__  :       Tuple				=  self.mobilenet_va.layer[-1].convolution.out_channels

						# Classifier head
						lowerCAmelCase__  :       Any				=  nn.Dropout(config.classifier_dropout_prob	,inplace=__lowerCamelCase				)
						lowerCAmelCase__  :       Dict				=  nn.Linear(__lowerCamelCase	,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 	lowerCAmelCase__   (self	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,)  ->    Union[tuple, ImageClassifierOutputWithNoAttention]:

						"""simple docstring"""






						lowerCAmelCase__  :       Union[str, Any]				=  return_dict if return_dict is not None else self.config.use_return_dict

						lowerCAmelCase__  :       Dict				=  self.mobilenet_va(__lowerCamelCase	,output_hidden_states=__lowerCamelCase	,return_dict=__lowerCamelCase				)

						lowerCAmelCase__  :       Optional[Any]				=  outputs.pooler_output if return_dict else outputs[1]

						lowerCAmelCase__  :       Optional[int]				=  self.classifier(self.dropout(__lowerCamelCase				)				)

						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__  :       Optional[int]				=  '''single_label_classification'''
														else:
																		lowerCAmelCase__  :       Dict				=  '''multi_label_classification'''

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

						if not return_dict:
										lowerCAmelCase__  :       str				=  (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, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, logging


if is_torch_available():
							import torch


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



class  lowerCamelCase__    (							lowerCamelCase__):




		'''simple docstring'''



		snake_case_			=["""pixel_values"""]



		def __init__(self	,__lowerCamelCase = True	,__lowerCamelCase = None	,__lowerCamelCase = PILImageResampling.BILINEAR	,__lowerCamelCase = True	,__lowerCamelCase = None	,__lowerCamelCase = True	,__lowerCamelCase = 1 / 2_55	,__lowerCamelCase = True	,__lowerCamelCase = None	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    None:

						"""simple docstring"""






						super().__init__(**__lowerCamelCase				)
						lowerCAmelCase__  :       List[Any]				=  size if size is not None else {'''shortest_edge''': 2_56}
						lowerCAmelCase__  :       Any				=  get_size_dict(__lowerCamelCase	,default_to_square=__lowerCamelCase				)
						lowerCAmelCase__  :       Optional[Any]				=  crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24}
						lowerCAmelCase__  :       Any				=  get_size_dict(__lowerCamelCase	,param_name='''crop_size'''				)
						lowerCAmelCase__  :       Dict				=  do_resize
						lowerCAmelCase__  :       str				=  size
						lowerCAmelCase__  :       Tuple				=  resample
						lowerCAmelCase__  :       List[Any]				=  do_center_crop
						lowerCAmelCase__  :       Dict				=  crop_size
						lowerCAmelCase__  :       Optional[int]				=  do_rescale
						lowerCAmelCase__  :       List[str]				=  rescale_factor
						lowerCAmelCase__  :       List[Any]				=  do_normalize
						lowerCAmelCase__  :       Optional[Any]				=  image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
						lowerCAmelCase__  :       str				=  image_std if image_std is not None else IMAGENET_STANDARD_STD



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = PILImageResampling.BICUBIC	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    np.ndarray:

						"""simple docstring"""






						lowerCAmelCase__  :       Dict				=  get_size_dict(__lowerCamelCase	,default_to_square=__lowerCamelCase				)
						if "shortest_edge" not in size:
										raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""				)
						lowerCAmelCase__  :       str				=  get_resize_output_image_size(__lowerCamelCase	,size=size['''shortest_edge''']	,default_to_square=__lowerCamelCase				)
						return resize(__lowerCamelCase	,size=__lowerCamelCase	,resample=__lowerCamelCase	,data_format=__lowerCamelCase	,**__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    np.ndarray:

						"""simple docstring"""






						lowerCAmelCase__  :       Union[str, Any]				=  get_size_dict(__lowerCamelCase				)
						if "height" not in size or "width" not in size:
										raise ValueError(f"""The `size` parameter must contain the keys `height` and `width`. Got {size.keys()}"""				)
						return center_crop(__lowerCamelCase	,size=(size['''height'''], size['''width'''])	,data_format=__lowerCamelCase	,**__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = None	,**__lowerCamelCase				)  ->    np.ndarray:

						"""simple docstring"""






						return rescale(__lowerCamelCase	,scale=__lowerCamelCase	,data_format=__lowerCamelCase	,**__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase	,__lowerCamelCase = None	,**__lowerCamelCase	,)  ->    np.ndarray:

						"""simple docstring"""






						return normalize(__lowerCamelCase	,mean=__lowerCamelCase	,std=__lowerCamelCase	,data_format=__lowerCamelCase	,**__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = None	,__lowerCamelCase = ChannelDimension.FIRST	,**__lowerCamelCase	,)  ->    Optional[Any]:

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[int]				=  do_resize if do_resize is not None else self.do_resize
						lowerCAmelCase__  :       Optional[int]				=  size if size is not None else self.size
						lowerCAmelCase__  :       Union[str, Any]				=  get_size_dict(__lowerCamelCase	,default_to_square=__lowerCamelCase				)
						lowerCAmelCase__  :       Dict				=  resample if resample is not None else self.resample
						lowerCAmelCase__  :       Union[str, Any]				=  do_center_crop if do_center_crop is not None else self.do_center_crop
						lowerCAmelCase__  :       Any				=  crop_size if crop_size is not None else self.crop_size
						lowerCAmelCase__  :       List[str]				=  get_size_dict(__lowerCamelCase	,param_name='''crop_size'''				)
						lowerCAmelCase__  :       List[str]				=  do_rescale if do_rescale is not None else self.do_rescale
						lowerCAmelCase__  :       str				=  rescale_factor if rescale_factor is not None else self.rescale_factor
						lowerCAmelCase__  :       int				=  do_normalize if do_normalize is not None else self.do_normalize
						lowerCAmelCase__  :       Optional[Any]				=  image_mean if image_mean is not None else self.image_mean
						lowerCAmelCase__  :       List[Any]				=  image_std if image_std is not None else self.image_std

						lowerCAmelCase__  :       Any				=  make_list_of_images(__lowerCamelCase				)

						if not valid_images(__lowerCamelCase				):
										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:
										raise ValueError('''Size must be specified if do_resize is True.'''				)

						if do_center_crop and crop_size is None:
										raise ValueError('''Crop size must be specified if do_center_crop is True.'''				)

						if do_rescale and rescale_factor is None:
										raise ValueError('''Rescale factor must be specified if do_rescale is True.'''				)

						if do_normalize and (image_mean is None or image_std is None):
										raise ValueError('''Image mean and std must be specified if do_normalize is True.'''				)

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

						if do_resize:
										lowerCAmelCase__  :       str				=  [self.resize(image=__lowerCamelCase	,size=__lowerCamelCase	,resample=__lowerCamelCase				) for image in images]

						if do_center_crop:
										lowerCAmelCase__  :       List[Any]				=  [self.center_crop(image=__lowerCamelCase	,size=__lowerCamelCase				) for image in images]

						if do_rescale:
										lowerCAmelCase__  :       Any				=  [self.rescale(image=__lowerCamelCase	,scale=__lowerCamelCase				) for image in images]

						if do_normalize:
										lowerCAmelCase__  :       Tuple				=  [self.normalize(image=__lowerCamelCase	,mean=__lowerCamelCase	,std=__lowerCamelCase				) for image in images]

						lowerCAmelCase__  :       int				=  [to_channel_dimension_format(__lowerCamelCase	,__lowerCamelCase				) for image in images]

						lowerCAmelCase__  :       int				=  {'''pixel_values''': images}
						return BatchFeature(data=__lowerCamelCase	,tensor_type=__lowerCamelCase				)



		def 	lowerCAmelCase__   (self	,__lowerCamelCase	,__lowerCamelCase = None				)  ->    Union[str, Any]:

						"""simple docstring"""






						lowerCAmelCase__  :       Optional[int]				=  outputs.logits

						# Resize logits and compute semantic segmentation maps
						if target_sizes is not None:
										if len(__lowerCamelCase				) != len(__lowerCamelCase				):
														raise ValueError(
														    '''Make sure that you pass in as many target sizes as the batch dimension of the logits'''				)

										if is_torch_tensor(__lowerCamelCase				):
														lowerCAmelCase__  :       str				=  target_sizes.numpy()

										lowerCAmelCase__  :       Optional[Any]				=  []

										for idx in range(len(__lowerCamelCase				)				):
														lowerCAmelCase__  :       Optional[int]				=  torch.nn.functional.interpolate(
														    logits[idx].unsqueeze(dim=0				)	,size=target_sizes[idx]	,mode='''bilinear'''	,align_corners=__lowerCamelCase				)
														lowerCAmelCase__  :       Optional[Any]				=  resized_logits[0].argmax(dim=0				)
														semantic_segmentation.append(__lowerCamelCase				)
						else:
										lowerCAmelCase__  :       Optional[Any]				=  logits.argmax(dim=1				)
										lowerCAmelCase__  :       int				=  [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]				)]

						return semantic_segmentation

