




from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


UpperCamelCase								=     logging.get_logger(__name__)

# General docstring
UpperCamelCase								=     """ResNetConfig"""

# Base docstring
UpperCamelCase								=     """microsoft/resnet-50"""
UpperCamelCase								=     [1, 2048, 7, 7]

# Image classification docstring
UpperCamelCase								=     """microsoft/resnet-50"""
UpperCamelCase								=     """tiger cat"""

UpperCamelCase								=     [
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]





class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     List[str]   ,	SCREAMING_SNAKE_CASE__     :     List[str]   ,	SCREAMING_SNAKE_CASE__     :     List[str] = 3   ,	SCREAMING_SNAKE_CASE__     :     Any = 1   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any] = "relu"   ,	**SCREAMING_SNAKE_CASE__     :     Any   )      ->       List[str]:
         super().__init__(**snake_case__   )
         lowerCAmelCase__		= kernel_size // 2
         lowerCAmelCase__		= tf.keras.layers.ConvaD(
             snake_case__   ,	kernel_size=snake_case__   ,	strides=snake_case__   ,	padding="valid"   ,	use_bias=snake_case__   ,	name="convolution"   )
         # Use same default momentum and epsilon as PyTorch equivalent
         lowerCAmelCase__		= tf.keras.layers.BatchNormalization(epsilon=1e-5   ,	momentum=0.9   ,	name="normalization"   )
         lowerCAmelCase__		= ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("linear"   )


    def    a      (       self     :     Any   ,	SCREAMING_SNAKE_CASE__     :     int   )      ->       Optional[int]:
         lowerCAmelCase__		= (self.pad_value, self.pad_value)
         lowerCAmelCase__		= tf.pad(snake_case__   ,	[(0, 0), height_pad, width_pad, (0, 0)]   )
         lowerCAmelCase__		= self.conv(snake_case__   )
         return hidden_state


    def    a      (       self     :     Optional[int]   ,	SCREAMING_SNAKE_CASE__     :     Any   ,	SCREAMING_SNAKE_CASE__     :     Optional[int] = False   )      ->       Union[str, Any]:
         lowerCAmelCase__		= self.convolution(snake_case__   )
         lowerCAmelCase__		= self.normalization(snake_case__   ,	training=snake_case__   )
         lowerCAmelCase__		= self.activation(snake_case__   )
         return hidden_state






class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     Union[str, Any]   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any]   ,	**SCREAMING_SNAKE_CASE__     :     Any   )      ->       str:
         super().__init__(**snake_case__   )
         lowerCAmelCase__		= TFResNetConvLayer(
             config.embedding_size   ,	kernel_size=7   ,	stride=2   ,	activation=config.hidden_act   ,	name="embedder"   ,	)
         lowerCAmelCase__		= tf.keras.layers.MaxPoolaD(pool_size=3   ,	strides=2   ,	padding="valid"   ,	name="pooler"   )
         lowerCAmelCase__		= config.num_channels


    def    a      (       self     :     int   ,	SCREAMING_SNAKE_CASE__     :     Dict   ,	SCREAMING_SNAKE_CASE__     :     Union[str, Any] = False   )      ->       Union[str, Any]:
         lowerCAmelCase__		= shape_list(snake_case__   )
         if tf.executing_eagerly() and num_channels != self.num_channels:
              raise ValueError(
                  "Make sure that the channel dimension of the pixel values match with the one set in the configuration."   )
         lowerCAmelCase__		= pixel_values
         lowerCAmelCase__		= self.embedder(snake_case__   )
         lowerCAmelCase__		= tf.pad(snake_case__   ,	[[0, 0], [1, 1], [1, 1], [0, 0]]   )
         lowerCAmelCase__		= self.pooler(snake_case__   )
         return hidden_state






class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     Optional[int]   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     Any = 2   ,	**SCREAMING_SNAKE_CASE__     :     Optional[Any]   )      ->       Optional[int]:
         super().__init__(**snake_case__   )
         lowerCAmelCase__		= tf.keras.layers.ConvaD(
             snake_case__   ,	kernel_size=1   ,	strides=snake_case__   ,	use_bias=snake_case__   ,	name="convolution"   )
         # Use same default momentum and epsilon as PyTorch equivalent
         lowerCAmelCase__		= tf.keras.layers.BatchNormalization(epsilon=1e-5   ,	momentum=0.9   ,	name="normalization"   )


    def    a      (       self     :     Optional[int]   ,	SCREAMING_SNAKE_CASE__     :     Any   ,	SCREAMING_SNAKE_CASE__     :     Any = False   )      ->       Union[str, Any]:
         lowerCAmelCase__		= x
         lowerCAmelCase__		= self.convolution(snake_case__   )
         lowerCAmelCase__		= self.normalization(snake_case__   ,	training=snake_case__   )
         return hidden_state






class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     List[Any]   ,	SCREAMING_SNAKE_CASE__     :     int   ,	SCREAMING_SNAKE_CASE__     :     Union[str, Any] = 1   ,	SCREAMING_SNAKE_CASE__     :     int = "relu"   ,	**SCREAMING_SNAKE_CASE__     :     Dict   )      ->       Optional[int]:
         super().__init__(**snake_case__   )
         lowerCAmelCase__		= in_channels != out_channels or stride != 1
         lowerCAmelCase__		= TFResNetConvLayer(snake_case__   ,	stride=snake_case__   ,	name="layer.0"   )
         lowerCAmelCase__		= TFResNetConvLayer(snake_case__   ,	activation=snake_case__   ,	name="layer.1"   )
         lowerCAmelCase__		= (
             TFResNetShortCut(snake_case__   ,	stride=snake_case__   ,	name="shortcut"   )
             if should_apply_shortcut
             else tf.keras.layers.Activation("linear"   ,	name="shortcut"   )
         )
         lowerCAmelCase__		= ACTaFN[activation]


    def    a      (       self     :     Union[str, Any]   ,	SCREAMING_SNAKE_CASE__     :     List[str]   ,	SCREAMING_SNAKE_CASE__     :     Tuple = False   )      ->       List[str]:
         lowerCAmelCase__		= hidden_state
         lowerCAmelCase__		= self.conva(snake_case__   ,	training=snake_case__   )
         lowerCAmelCase__		= self.conva(snake_case__   ,	training=snake_case__   )
         lowerCAmelCase__		= self.shortcut(snake_case__   ,	training=snake_case__   )
         hidden_state += residual
         lowerCAmelCase__		= self.activation(snake_case__   )
         return hidden_state






class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     Union[str, Any]   ,	SCREAMING_SNAKE_CASE__     :     Dict   ,	SCREAMING_SNAKE_CASE__     :     Tuple   ,	SCREAMING_SNAKE_CASE__     :     str = 1   ,	SCREAMING_SNAKE_CASE__     :     Any = "relu"   ,	SCREAMING_SNAKE_CASE__     :     Dict = 4   ,	**SCREAMING_SNAKE_CASE__     :     str   ,	)      ->       Any:
         super().__init__(**snake_case__   )
         lowerCAmelCase__		= in_channels != out_channels or stride != 1
         lowerCAmelCase__		= out_channels // reduction
         lowerCAmelCase__		= TFResNetConvLayer(snake_case__   ,	kernel_size=1   ,	name="layer.0"   )
         lowerCAmelCase__		= TFResNetConvLayer(snake_case__   ,	stride=snake_case__   ,	name="layer.1"   )
         lowerCAmelCase__		= TFResNetConvLayer(snake_case__   ,	kernel_size=1   ,	activation=snake_case__   ,	name="layer.2"   )
         lowerCAmelCase__		= (
             TFResNetShortCut(snake_case__   ,	stride=snake_case__   ,	name="shortcut"   )
             if should_apply_shortcut
             else tf.keras.layers.Activation("linear"   ,	name="shortcut"   )
         )
         lowerCAmelCase__		= ACTaFN[activation]


    def    a      (       self     :     Dict   ,	SCREAMING_SNAKE_CASE__     :     Any   ,	SCREAMING_SNAKE_CASE__     :     Union[str, Any] = False   )      ->       Dict:
         lowerCAmelCase__		= hidden_state
         lowerCAmelCase__		= self.conva(snake_case__   ,	training=snake_case__   )
         lowerCAmelCase__		= self.conva(snake_case__   ,	training=snake_case__   )
         lowerCAmelCase__		= self.conva(snake_case__   ,	training=snake_case__   )
         lowerCAmelCase__		= self.shortcut(snake_case__   ,	training=snake_case__   )
         hidden_state += residual
         lowerCAmelCase__		= self.activation(snake_case__   )
         return hidden_state






class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     str   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     Union[str, Any]   ,	SCREAMING_SNAKE_CASE__     :     str   ,	SCREAMING_SNAKE_CASE__     :     Optional[int] = 2   ,	SCREAMING_SNAKE_CASE__     :     Union[str, Any] = 2   ,	**SCREAMING_SNAKE_CASE__     :     Tuple   )      ->       Union[str, Any]:
         super().__init__(**snake_case__   )

         lowerCAmelCase__		= TFResNetBottleNeckLayer if config.layer_type == "bottleneck" else TFResNetBasicLayer

         lowerCAmelCase__		= [layer(snake_case__   ,	snake_case__   ,	stride=snake_case__   ,	activation=config.hidden_act   ,	name="layers.0"   )]
         layers += [
             layer(snake_case__   ,	snake_case__   ,	activation=config.hidden_act   ,	name=f'layers.{i + 1}'   )
             for i in range(depth - 1   )
         ]
         lowerCAmelCase__		= layers


    def    a      (       self     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any] = False   )      ->       Union[str, Any]:
         for layer in self.stage_layers:
              lowerCAmelCase__		= layer(snake_case__   ,	training=snake_case__   )
         return hidden_state






class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    def __init__(       self     :     Tuple   ,	SCREAMING_SNAKE_CASE__     :     int   ,	**SCREAMING_SNAKE_CASE__     :     List[Any]   )      ->       int:
         super().__init__(**snake_case__   )
         # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
         lowerCAmelCase__		= [
             TFResNetStage(
                 snake_case__   ,	config.embedding_size   ,	config.hidden_sizes[0]   ,	stride=2 if config.downsample_in_first_stage else 1   ,	depth=config.depths[0]   ,	name="stages.0"   ,	)
         ]
         for i, (in_channels, out_channels, depth) in enumerate(
             zip(config.hidden_sizes   ,	config.hidden_sizes[1:]   ,	config.depths[1:]   )   ):
              self.stages.append(TFResNetStage(snake_case__   ,	snake_case__   ,	snake_case__   ,	depth=snake_case__   ,	name=f'stages.{i + 1}'   )   )


    def    a      (       self     :     Tuple   ,	SCREAMING_SNAKE_CASE__     :     Any   ,	SCREAMING_SNAKE_CASE__     :     Dict = False   ,	SCREAMING_SNAKE_CASE__     :     List[str] = True   ,	SCREAMING_SNAKE_CASE__     :     Any = False   ,	)      ->       Dict:
         lowerCAmelCase__		= () if output_hidden_states else None

         for stage_module in self.stages:
              if output_hidden_states:
                   lowerCAmelCase__		= hidden_states + (hidden_state,)

              lowerCAmelCase__		= stage_module(snake_case__   ,	training=snake_case__   )

         if output_hidden_states:
              lowerCAmelCase__		= hidden_states + (hidden_state,)

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

         return TFBaseModelOutputWithNoAttention(last_hidden_state=snake_case__   ,	hidden_states=snake_case__   )






class  __lowerCamelCase       (    SCREAMING_SNAKE_CASE__    ):




    """simple docstring"""

    snake_case__					=      ResNetConfig
    snake_case__					=      "resnet"
    snake_case__					=      "pixel_values"


    @property
    def    a      (       self     :     List[Any]   )      ->       List[str]:
         return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224)   ,	dtype=tf.floataa   )}






UpperCamelCase								=     r"""
    This model is a TensorFlow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""


UpperCamelCase								=     r"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""





@keras_serializable
class  __lowerCamelCase       (    tf.keras.layers.Layer    ):




    """simple docstring"""

    snake_case__					=      ResNetConfig


    def __init__(       self     :     int   ,	SCREAMING_SNAKE_CASE__     :     int   ,	**SCREAMING_SNAKE_CASE__     :     int   )      ->       int:
         super().__init__(**snake_case__   )
         lowerCAmelCase__		= config
         lowerCAmelCase__		= TFResNetEmbeddings(snake_case__   ,	name="embedder"   )
         lowerCAmelCase__		= TFResNetEncoder(snake_case__   ,	name="encoder"   )
         lowerCAmelCase__		= tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case__   )


    @unpack_inputs
    def    a      (       self     :     Any   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     Optional[int] = None   ,	SCREAMING_SNAKE_CASE__     :     Union[str, Any] = None   ,	SCREAMING_SNAKE_CASE__     :     int = False   ,	)      ->       Optional[Any]:
         lowerCAmelCase__		= (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         lowerCAmelCase__		= return_dict if return_dict is not None else self.config.use_return_dict

         # TF 2.0 image layers can't use NCHW format when running on CPU.
         # We transpose to NHWC format and then transpose back after the full forward pass.
         # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
         lowerCAmelCase__		= tf.transpose(snake_case__   ,	perm=[0, 2, 3, 1]   )
         lowerCAmelCase__		= self.embedder(snake_case__   ,	training=snake_case__   )

         lowerCAmelCase__		= self.encoder(
             snake_case__   ,	output_hidden_states=snake_case__   ,	return_dict=snake_case__   ,	training=snake_case__   )

         lowerCAmelCase__		= encoder_outputs[0]

         lowerCAmelCase__		= self.pooler(snake_case__   )

         # Transpose all the outputs to the NCHW format
         # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
         lowerCAmelCase__		= tf.transpose(snake_case__   ,	(0, 3, 1, 2)   )
         lowerCAmelCase__		= tf.transpose(snake_case__   ,	(0, 3, 1, 2)   )
         lowerCAmelCase__		= ()
         for hidden_state in encoder_outputs[1:]:
              lowerCAmelCase__		= hidden_states + tuple(tf.transpose(snake_case__   ,	(0, 3, 1, 2)   ) for h in hidden_state   )

         if not return_dict:
              return (last_hidden_state, pooled_output) + hidden_states

         lowerCAmelCase__		= hidden_states if output_hidden_states else None

         return TFBaseModelOutputWithPoolingAndNoAttention(
             last_hidden_state=snake_case__   ,	pooler_output=snake_case__   ,	hidden_states=snake_case__   ,	)






@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."	,				SCREAMING_SNAKE_CASE__	,				)
class  __lowerCamelCase       (    SCREAMING_SNAKE_CASE__    ):




    """simple docstring"""

    def __init__(       self     :     Optional[Any]   ,	SCREAMING_SNAKE_CASE__     :     Tuple   ,	**SCREAMING_SNAKE_CASE__     :     Union[str, Any]   )      ->       Optional[Any]:
         super().__init__(snake_case__   ,	**snake_case__   )
         lowerCAmelCase__		= TFResNetMainLayer(config=snake_case__   ,	name="resnet"   )


    @add_start_docstrings_to_model_forward(snake_case__   )
    @add_code_sample_docstrings(
        checkpoint=_CHECKPOINT_FOR_DOC   ,	output_type=snake_case__   ,	config_class=_CONFIG_FOR_DOC   ,	modality="vision"   ,	expected_output=_EXPECTED_OUTPUT_SHAPE   ,	)
    @unpack_inputs
    def    a      (       self     :     Tuple   ,	SCREAMING_SNAKE_CASE__     :     List[Any]   ,	SCREAMING_SNAKE_CASE__     :     Dict = None   ,	SCREAMING_SNAKE_CASE__     :     Dict = None   ,	SCREAMING_SNAKE_CASE__     :     Optional[int] = False   ,	)      ->       Dict:
         lowerCAmelCase__		= (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         lowerCAmelCase__		= return_dict if return_dict is not None else self.config.use_return_dict

         lowerCAmelCase__		= self.resnet(
             pixel_values=snake_case__   ,	output_hidden_states=snake_case__   ,	return_dict=snake_case__   ,	training=snake_case__   ,	)
         return resnet_outputs






@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "	,				SCREAMING_SNAKE_CASE__	,				)
class  __lowerCamelCase       (    SCREAMING_SNAKE_CASE__	,				SCREAMING_SNAKE_CASE__    ):




    """simple docstring"""

    def __init__(       self     :     List[Any]   ,	SCREAMING_SNAKE_CASE__     :     List[str]   ,	**SCREAMING_SNAKE_CASE__     :     Optional[int]   )      ->       List[str]:
         super().__init__(snake_case__   ,	**snake_case__   )
         lowerCAmelCase__		= config.num_labels
         lowerCAmelCase__		= TFResNetMainLayer(snake_case__   ,	name="resnet"   )
         # classification head
         lowerCAmelCase__		= (
             tf.keras.layers.Dense(config.num_labels   ,	name="classifier.1"   )
             if config.num_labels > 0
             else tf.keras.layers.Activation("linear"   ,	name="classifier.1"   )
         )


    def    a      (       self     :     int   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any]   )      ->       Union[str, Any]:
         lowerCAmelCase__		= tf.keras.layers.Flatten()(snake_case__   )
         lowerCAmelCase__		= self.classifier_layer(snake_case__   )
         return logits


    @add_start_docstrings_to_model_forward(snake_case__   )
    @add_code_sample_docstrings(
        checkpoint=_IMAGE_CLASS_CHECKPOINT   ,	output_type=snake_case__   ,	config_class=_CONFIG_FOR_DOC   ,	expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT   ,	)
    @unpack_inputs
    def    a      (       self     :     str   ,	SCREAMING_SNAKE_CASE__     :     Optional[int] = None   ,	SCREAMING_SNAKE_CASE__     :     Optional[Any] = None   ,	SCREAMING_SNAKE_CASE__     :     Optional[int] = None   ,	SCREAMING_SNAKE_CASE__     :     Dict = None   ,	SCREAMING_SNAKE_CASE__     :     List[str] = False   ,	)      ->       Union[str, Any]:
         lowerCAmelCase__		= return_dict if return_dict is not None else self.config.use_return_dict

         lowerCAmelCase__		= self.resnet(
             snake_case__   ,	output_hidden_states=snake_case__   ,	return_dict=snake_case__   ,	training=snake_case__   )

         lowerCAmelCase__		= outputs.pooler_output if return_dict else outputs[1]

         lowerCAmelCase__		= self.classifier(snake_case__   )

         lowerCAmelCase__		= None if labels is None else self.hf_compute_loss(snake_case__   ,	snake_case__   )

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

         return TFImageClassifierOutputWithNoAttention(loss=snake_case__   ,	logits=snake_case__   ,	hidden_states=outputs.hidden_states   )








"""simple docstring"""







import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
			import torch

if is_vision_available():
			from PIL import Image

			from transformers import CLIPImageProcessor


class     __UpperCAmelCase(   unittest.TestCase							):




						"""simple docstring"""




						def __init__(   self       ,  snake_case__       ,  snake_case__=7       ,  snake_case__=3       ,  snake_case__=18       ,  snake_case__=30       ,  snake_case__=400       ,  snake_case__=True       ,  snake_case__=None       ,  snake_case__=True       ,  snake_case__=None       ,  snake_case__=True       ,  snake_case__=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]       ,  snake_case__=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]       ,  snake_case__=True       ,  ):
												'''simple docstring'''
												lowercase__				:      int=       size if size is not None else {"shortest_edge": 20}
												lowercase__				:      int=       crop_size if crop_size is not None else {"height": 18, "width": 18}
												lowercase__				:      Union[str, Any]=       parent
												lowercase__				:      Optional[Any]=       batch_size
												lowercase__				:      List[str]=       num_channels
												lowercase__				:      str=       image_size
												lowercase__				:      Optional[int]=       min_resolution
												lowercase__				:      Union[str, Any]=       max_resolution
												lowercase__				:      List[Any]=       do_resize
												lowercase__				:      Any=       size
												lowercase__				:      Optional[Any]=       do_center_crop
												lowercase__				:      List[str]=       crop_size
												lowercase__				:      List[Any]=       do_normalize
												lowercase__				:      Optional[Any]=       image_mean
												lowercase__				:      Dict=       image_std
												lowercase__				:      Dict=       do_convert_rgb




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return {
												    "do_resize": self.do_resize,
												    "size": self.size,
												    "do_center_crop": self.do_center_crop,
												    "crop_size": self.crop_size,
												    "do_normalize": self.do_normalize,
												    "image_mean": self.image_mean,
												    "image_std": self.image_std,
												    "do_convert_rgb": self.do_convert_rgb,
												}




						def 		UpperCAmelCase_       (   self       ,  snake_case__=False       ,  snake_case__=False       ,  snake_case__=False			):
												'''simple docstring'''
												assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

												if equal_resolution:
																		lowercase__				:      Optional[Any]=       []
																		for i in range(self.batch_size			):
																								image_inputs.append(
																								    np.random.randint(
																								        255       ,  size=(self.num_channels, self.max_resolution, self.max_resolution)       ,  dtype=np.uinta			)			)
												else:
																		lowercase__				:      Optional[Any]=       []
																		for i in range(self.batch_size			):
																								lowercase__,	lowercase__				:      str=       np.random.choice(np.arange(self.min_resolution       ,  self.max_resolution			)       ,  2			)
																								image_inputs.append(np.random.randint(255       ,  size=(self.num_channels, width, height)       ,  dtype=np.uinta			)			)

												if not numpify and not torchify:
																		# PIL expects the channel dimension as last dimension
																		lowercase__				:      Dict=       [Image.fromarray(np.moveaxis(snake_case__       ,  0       ,  -1			)			) for x in image_inputs]

												if torchify:
																		lowercase__				:      Tuple=       [torch.from_numpy(snake_case__			) for x in image_inputs]

												return image_inputs


@require_torch
@require_vision
class     __UpperCAmelCase(   SCREAMING_SNAKE_CASE__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase				       =					CLIPImageProcessor if is_vision_available() else None




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[Any]=       CLIPImageProcessingTester(self			)




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return self.image_processor_tester.prepare_image_processor_dict()




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Dict=       self.image_processing_class(**self.image_processor_dict			)
												self.assertTrue(hasattr(snake_case__       ,  "do_resize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "size"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_normalize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_mean"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_std"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_convert_rgb"			)			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[str]=       self.image_processing_class.from_dict(self.image_processor_dict			)
												self.assertEqual(image_processor.size       ,  {"shortest_edge": 20}			)
												self.assertEqual(image_processor.crop_size       ,  {"height": 18, "width": 18}			)

												lowercase__				:      Dict=       self.image_processing_class.from_dict(self.image_processor_dict       ,  size=42       ,  crop_size=84			)
												self.assertEqual(image_processor.size       ,  {"shortest_edge": 42}			)
												self.assertEqual(image_processor.crop_size       ,  {"height": 84, "width": 84}			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												pass




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      int=       self.image_processing_class(**self.image_processor_dict			)
												# create random PIL images
												lowercase__				:      Optional[Any]=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  Image.Image			)

												# Test not batched input
												lowercase__				:      List[str]=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      Dict=       image_processing(snake_case__       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      Any=       self.image_processing_class(**self.image_processor_dict			)
												# create random numpy tensors
												lowercase__				:      Tuple=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__       ,  numpify=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  np.ndarray			)

												# Test not batched input
												lowercase__				:      Dict=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      int=       image_processing(snake_case__       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      Optional[Any]=       self.image_processing_class(**self.image_processor_dict			)
												# create random PyTorch tensors
												lowercase__				:      Union[str, Any]=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__       ,  torchify=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  torch.Tensor			)

												# Test not batched input
												lowercase__				:      Any=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      Union[str, Any]=       image_processing(snake_case__       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.image_processor_tester.num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )


@require_torch
@require_vision
class     __UpperCAmelCase(   SCREAMING_SNAKE_CASE__  ,  unittest.TestCase							):




						"""simple docstring"""




						__lowerCamelCase				       =					CLIPImageProcessor if is_vision_available() else None




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      Optional[int]=       CLIPImageProcessingTester(self       ,  num_channels=4			)
												lowercase__				:      Optional[Any]=       3




						@property
						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												return self.image_processor_tester.prepare_image_processor_dict()




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												lowercase__				:      List[str]=       self.image_processing_class(**self.image_processor_dict			)
												self.assertTrue(hasattr(snake_case__       ,  "do_resize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "size"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "center_crop"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_normalize"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_mean"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "image_std"			)			)
												self.assertTrue(hasattr(snake_case__       ,  "do_convert_rgb"			)			)




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												pass




						def 		UpperCAmelCase_       (   self			):
												'''simple docstring'''
												# Initialize image_processing
												lowercase__				:      int=       self.image_processing_class(**self.image_processor_dict			)
												# create random PIL images
												lowercase__				:      int=       self.image_processor_tester.prepare_inputs(equal_resolution=snake_case__			)
												for image in image_inputs:
																		self.assertIsInstance(snake_case__       ,  Image.Image			)

												# Test not batched input
												lowercase__				:      Optional[int]=       image_processing(image_inputs[0]       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        1,
												        self.expected_encoded_image_num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )

												# Test batched
												lowercase__				:      Any=       image_processing(snake_case__       ,  return_tensors="pt"			).pixel_values
												self.assertEqual(
												    encoded_images.shape       ,  (
												        self.image_processor_tester.batch_size,
												        self.expected_encoded_image_num_channels,
												        self.image_processor_tester.crop_size["height"],
												        self.image_processor_tester.crop_size["width"],
												    )       ,  )






