



"""simple docstring"""







from typing import Dict, Iterable, List, Optional, 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_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


lowerCAmelCase_   						=   logging.get_logger(__name__)
class        __A       (	A_    ):







		'''simple docstring'''





		lowerCAmelCase			:					Any   	=				["pixel_values"]







		def __init__(	self						:  int			,_snake_case						:  bool = True			,_snake_case						:  Dict[str, int] = None			,_snake_case						:  PILImageResampling = PILImageResampling.BICUBIC			,_snake_case						:  bool = True			,_snake_case						:  Dict[str, int] = None			,_snake_case						:  bool = True			,_snake_case						:  Union[int, float] = 1 / 255			,_snake_case						:  bool = True			,_snake_case						:  Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN			,_snake_case						:  Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD			,**_snake_case						:  Optional[int]			,)					->		None:






				"""simple docstring"""



				super().__init__(**_snake_case						)
				lowercase__   :    List[str]				=			size if size is not None else {'''shortest_edge''': 224}
				lowercase__   :    Union[str, Any]				=			get_size_dict(_snake_case			,default_to_square=_snake_case						)
				lowercase__   :    Dict				=			crop_size if crop_size is not None else {'''height''': 224, '''width''': 224}
				lowercase__   :    int				=			get_size_dict(_snake_case			,param_name='''crop_size'''						)

				lowercase__   :    List[str]				=			do_resize
				lowercase__   :    List[str]				=			size
				lowercase__   :    List[Any]				=			resample
				lowercase__   :    Any				=			do_center_crop
				lowercase__   :    List[str]				=			crop_size
				lowercase__   :    Union[str, Any]				=			do_rescale
				lowercase__   :    List[Any]				=			rescale_factor
				lowercase__   :    Optional[int]				=			do_normalize
				lowercase__   :    Tuple				=			image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
				lowercase__   :    List[str]				=			image_std if image_std is not None else IMAGENET_DEFAULT_STD







		def 					UpperCAmelCase    (	self						:  List[str]			,_snake_case						:  np.ndarray			,_snake_case						:  Dict[str, int]			,_snake_case						:  PILImageResampling = PILImageResampling.BICUBIC			,_snake_case						:  Optional[Union[str, ChannelDimension]] = None			,**_snake_case						:  List[Any]			,)					->		np.ndarray:






				"""simple docstring"""



				lowercase__   :    List[str]				=			get_size_dict(_snake_case			,default_to_square=_snake_case						)
				# size_dict is a dict with either keys "height" and "width" or "shortest_edge"
				if "shortest_edge" in size:
						lowercase__   :    Optional[Any]				=			int((256 / 224) * size['''shortest_edge''']						)
						lowercase__   :    List[str]				=			get_resize_output_image_size(_snake_case			,size=_snake_case			,default_to_square=_snake_case						)
						lowercase__   :    List[str]				=			{'''height''': output_size[0], '''width''': output_size[1]}
				if "height" not in size_dict or "width" not in size_dict:
						raise ValueError(
						    f"""Size dict must have keys 'height' and 'width' or 'shortest_edge'. Got {size_dict.keys()}"""						)
				return resize(
				    _snake_case			,size=(size_dict['''height'''], size_dict['''width'''])			,resample=_snake_case			,data_format=_snake_case			,**_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  np.ndarray			,_snake_case						:  Dict[str, int]			,_snake_case						:  Optional[Union[str, ChannelDimension]] = None			,**_snake_case						:  List[str]			,)					->		np.ndarray:






				"""simple docstring"""



				lowercase__   :    List[str]				=			get_size_dict(_snake_case						)
				if "height" not in size or "width" not in size:
						raise ValueError(f"""Size dict must have keys 'height' and 'width'. Got {size.keys()}"""						)
				return center_crop(_snake_case			,size=(size['''height'''], size['''width'''])			,data_format=_snake_case			,**_snake_case						)







		def 					UpperCAmelCase    (	self						:  Union[str, Any]			,_snake_case						:  np.ndarray			,_snake_case						:  Union[int, float]			,_snake_case						:  Optional[Union[str, ChannelDimension]] = None			,**_snake_case						:  Any			,)					->		np.ndarray:






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  Optional[int]			,_snake_case						:  np.ndarray			,_snake_case						:  Union[float, List[float]]			,_snake_case						:  Union[float, List[float]]			,_snake_case						:  Optional[Union[str, ChannelDimension]] = None			,**_snake_case						:  Tuple			,)					->		np.ndarray:






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  Optional[Any]			,_snake_case						:  ImageInput			,_snake_case						:  Optional[bool] = None			,_snake_case						:  Optional[Dict[str, int]] = None			,_snake_case						:  PILImageResampling = None			,_snake_case						:  Optional[bool] = None			,_snake_case						:  Optional[Dict[str, int]] = None			,_snake_case						:  Optional[bool] = None			,_snake_case						:  Optional[float] = None			,_snake_case						:  Optional[bool] = None			,_snake_case						:  Optional[Union[float, Iterable[float]]] = None			,_snake_case						:  Optional[Union[float, Iterable[float]]] = None			,_snake_case						:  Optional[TensorType] = None			,_snake_case						:  ChannelDimension = ChannelDimension.FIRST			,**_snake_case						:  Dict			,)					->		BatchFeature:






				"""simple docstring"""



				lowercase__   :    Tuple				=			do_resize if do_resize is not None else self.do_resize
				lowercase__   :    str				=			resample if resample is not None else self.resample
				lowercase__   :    List[Any]				=			do_center_crop if do_center_crop is not None else self.do_center_crop
				lowercase__   :    int				=			do_rescale if do_rescale is not None else self.do_rescale
				lowercase__   :    Optional[Any]				=			rescale_factor if rescale_factor is not None else self.rescale_factor
				lowercase__   :    Optional[int]				=			do_normalize if do_normalize is not None else self.do_normalize
				lowercase__   :    str				=			image_mean if image_mean is not None else self.image_mean
				lowercase__   :    Optional[int]				=			image_std if image_std is not None else self.image_std

				lowercase__   :    Optional[Any]				=			size if size is not None else self.size
				lowercase__   :    Tuple				=			get_size_dict(_snake_case			,default_to_square=_snake_case						)
				lowercase__   :    Optional[Any]				=			crop_size if crop_size is not None else self.crop_size
				lowercase__   :    int				=			get_size_dict(_snake_case			,param_name='''crop_size'''						)

				lowercase__   :    Union[str, Any]				=			make_list_of_images(_snake_case						)

				if not valid_images(_snake_case						):
						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.
				lowercase__   :    Tuple				=			[to_numpy_array(_snake_case						) for image in images]

				if do_resize:
						lowercase__   :    Any				=			[self.resize(_snake_case			,_snake_case			,_snake_case						) for image in images]

				if do_center_crop:
						lowercase__   :    Tuple				=			[self.center_crop(_snake_case			,_snake_case						) for image in images]

				if do_rescale:
						lowercase__   :    Dict				=			[self.rescale(_snake_case			,_snake_case						) for image in images]

				if do_normalize:
						lowercase__   :    List[str]				=			[self.normalize(_snake_case			,_snake_case			,_snake_case						) for image in images]

				lowercase__   :    int				=			[to_channel_dimension_format(_snake_case			,_snake_case						) for image in images]

				lowercase__   :    Union[str, Any]				=			{'''pixel_values''': images}
				return BatchFeature(data=_snake_case			,tensor_type=_snake_case						)





"""simple docstring"""







from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
							import tensorflow as tf

							from transformers import TFResNetForImageClassification, TFResNetModel
							from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor
class        __A       :







		'''simple docstring'''





		def __init__(	self						:  str			,_snake_case						:  List[Any]			,_snake_case						:  Optional[int]=3			,_snake_case						:  Optional[int]=32			,_snake_case						:  Union[str, Any]=3			,_snake_case						:  int=10			,_snake_case						:  List[str]=[10, 20, 30, 40]			,_snake_case						:  Any=[1, 1, 2, 1]			,_snake_case						:  int=True			,_snake_case						:  Optional[Any]=True			,_snake_case						:  Union[str, Any]="relu"			,_snake_case						:  Dict=3			,_snake_case						:  Any=None			,)					->		str:






				"""simple docstring"""



				lowercase__   :    int				=			parent
				lowercase__   :    Optional[Any]				=			batch_size
				lowercase__   :    Optional[Any]				=			image_size
				lowercase__   :    Optional[Any]				=			num_channels
				lowercase__   :    Optional[Any]				=			embeddings_size
				lowercase__   :    Optional[Any]				=			hidden_sizes
				lowercase__   :    str				=			depths
				lowercase__   :    Tuple				=			is_training
				lowercase__   :    List[Any]				=			use_labels
				lowercase__   :    Union[str, Any]				=			hidden_act
				lowercase__   :    Union[str, Any]				=			num_labels
				lowercase__   :    Tuple				=			scope
				lowercase__   :    Optional[Any]				=			len(_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

				lowercase__   :    Tuple				=			None
				if self.use_labels:
						lowercase__   :    Dict				=			ids_tensor([self.batch_size]			,self.num_labels						)

				lowercase__   :    int				=			self.get_config()

				return config, pixel_values, labels







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[Any]:






				"""simple docstring"""



				return ResNetConfig(
				    num_channels=self.num_channels			,embeddings_size=self.embeddings_size			,hidden_sizes=self.hidden_sizes			,depths=self.depths			,hidden_act=self.hidden_act			,num_labels=self.num_labels			,image_size=self.image_size			,)







		def 					UpperCAmelCase    (	self						:  List[str]			,_snake_case						:  Optional[int]			,_snake_case						:  int			,_snake_case						:  Tuple						)					->		List[Any]:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			TFResNetModel(config=_snake_case						)
				lowercase__   :    List[str]				=			model(_snake_case						)
				# expected last hidden states: B, C, H // 32, W // 32
				self.parent.assertEqual(
				    result.last_hidden_state.shape			,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)			,)







		def 					UpperCAmelCase    (	self						:  Optional[int]			,_snake_case						:  Optional[Any]			,_snake_case						:  int			,_snake_case						:  Any						)					->		Tuple:






				"""simple docstring"""



				lowercase__   :    Tuple				=			self.num_labels
				lowercase__   :    Union[str, Any]				=			TFResNetForImageClassification(_snake_case						)
				lowercase__   :    List[str]				=			model(_snake_case			,labels=_snake_case						)
				self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)						)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		str:






				"""simple docstring"""



				lowercase__   :    Dict				=			self.prepare_config_and_inputs()
				lowercase__		,			lowercase__		,			lowercase__   :    Union[str, Any]				=			config_and_inputs
				lowercase__   :    Dict				=			{'''pixel_values''': pixel_values}
				return config, inputs_dict





@require_tf
class        __A       (	A_     ,A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Optional[int]   	=				(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
		lowerCAmelCase			:					Any   	=				(
		    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
		    if is_tf_available()
		    else {}
		)

		lowerCAmelCase			:					List[Any]   	=				False
		lowerCAmelCase			:					List[Any]   	=				False
		lowerCAmelCase			:					int   	=				False
		lowerCAmelCase			:					Union[str, Any]   	=				False
		lowerCAmelCase			:					List[str]   	=				False







		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			TFResNetModelTester(self						)
				lowercase__   :    int				=			ConfigTester(self			,config_class=_snake_case			,has_text_modality=_snake_case						)







		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		str:






				"""simple docstring"""



				self.create_and_test_config_common_properties()
				self.config_tester.create_and_test_config_to_json_string()
				self.config_tester.create_and_test_config_to_json_file()
				self.config_tester.create_and_test_config_from_and_save_pretrained()
				self.config_tester.create_and_test_config_with_num_labels()
				self.config_tester.check_config_can_be_init_without_params()
				self.config_tester.check_config_arguments_init()







		def 					UpperCAmelCase    (	self						:  List[Any]						)					->		List[str]:






				"""simple docstring"""



				return







		@unittest.skip(reason='''ResNet does not use inputs_embeds'''						)
		def 					UpperCAmelCase    (	self						:  Optional[int]						)					->		Dict:






				"""simple docstring"""



				pass







		@unittest.skip(reason='''ResNet does not support input and output embeddings'''						)
		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Optional[Any]:






				"""simple docstring"""



				pass







		def 					UpperCAmelCase    (	self						:  int						)					->		Union[str, Any]:






				"""simple docstring"""



				lowercase__		,			lowercase__   :    Dict				=			self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
						lowercase__   :    str				=			model_class(_snake_case						)
						lowercase__   :    Dict				=			inspect.signature(model.call						)
						# signature.parameters is an OrderedDict => so arg_names order is deterministic
						lowercase__   :    Optional[int]				=			[*signature.parameters.keys()]

						lowercase__   :    Any				=			['''pixel_values''']
						self.assertListEqual(arg_names[:1]			,_snake_case						)







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Optional[int]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		List[str]:






				"""simple docstring"""



				def check_hidden_states_output(_snake_case						:  Optional[int]			,_snake_case						:  List[str]			,_snake_case						:  Optional[Any]						):
						lowercase__   :    str				=			model_class(_snake_case						)
						lowercase__   :    Union[str, Any]				=			model(**self._prepare_for_class(_snake_case			,_snake_case						)						)

						lowercase__   :    List[Any]				=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

						lowercase__   :    Tuple				=			self.model_tester.num_stages
						self.assertEqual(len(_snake_case						)			,expected_num_stages + 1						)

						# ResNet's feature maps are of shape (batch_size, num_channels, height, width)
						self.assertListEqual(
						    list(hidden_states[0].shape[-2:]						)			,[self.model_tester.image_size // 4, self.model_tester.image_size // 4]			,)

				lowercase__		,			lowercase__   :    int				=			self.model_tester.prepare_config_and_inputs_for_common()
				lowercase__   :    List[Any]				=			['''basic''', '''bottleneck''']
				for model_class in self.all_model_classes:
						for layer_type in layers_type:
								lowercase__   :    List[Any]				=			layer_type
								lowercase__   :    Dict				=			True
								check_hidden_states_output(_snake_case			,_snake_case			,_snake_case						)

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								lowercase__   :    Dict				=			True

								check_hidden_states_output(_snake_case			,_snake_case			,_snake_case						)







		def 					UpperCAmelCase    (	self						:  Dict						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*_snake_case						)







		@slow
		def 					UpperCAmelCase    (	self						:  Optional[Any]						)					->		int:






				"""simple docstring"""



				for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						lowercase__   :    Optional[Any]				=			TFResNetModel.from_pretrained(_snake_case						)
						self.assertIsNotNone(_snake_case						)





def      __UpperCAmelCase      (    )							->      Dict:
		lowercase__   :    List[str]				=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
		return image





@require_tf
@require_vision
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





		@cached_property
		def 					UpperCAmelCase    (	self						:  str						)					->		Any:






				"""simple docstring"""



				return (
				    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
				    if is_vision_available()
				    else None
				)







		@slow
		def 					UpperCAmelCase    (	self						:  Union[str, Any]						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    Tuple				=			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

				lowercase__   :    Any				=			self.default_image_processor
				lowercase__   :    int				=			prepare_img()
				lowercase__   :    Tuple				=			image_processor(images=_snake_case			,return_tensors='''tf'''						)

				# forward pass
				lowercase__   :    Dict				=			model(**_snake_case						)

				# verify the logits
				lowercase__   :    List[str]				=			tf.TensorShape((1, 1_000)						)
				self.assertEqual(outputs.logits.shape			,_snake_case						)

				lowercase__   :    Any				=			tf.constant([-11.1069, -9.7877, -8.3777]						)

				self.assertTrue(np.allclose(outputs.logits[0, :3].numpy()			,_snake_case			,atol=1e-4						)						)
