





import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
     from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor



class 				_UpperCamelCase       :

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




              """simple docstring"""


              UpperCamelCase_ 							=	parent
              UpperCamelCase_ 							=	batch_size
              UpperCamelCase_ 							=	image_size
              UpperCamelCase_ 							=	num_channels
              UpperCamelCase_ 							=	embeddings_size
              UpperCamelCase_ 							=	hidden_sizes
              UpperCamelCase_ 							=	depths
              UpperCamelCase_ 							=	is_training
              UpperCamelCase_ 							=	use_labels
              UpperCamelCase_ 							=	hidden_act
              UpperCamelCase_ 							=	num_labels
              UpperCamelCase_ 							=	scope
              UpperCamelCase_ 							=	len(__UpperCamelCase		)
              UpperCamelCase_ 							=	out_features
              UpperCamelCase_ 							=	out_indices

       def lowercase			(		self:			List[Any]		)							->			Optional[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

              UpperCamelCase_ 							=	None
              if self.use_labels:
                     UpperCamelCase_ 							=	ids_tensor([self.batch_size]       , self.num_labels		)

              UpperCamelCase_ 							=	self.get_config()

              return config, pixel_values, labels

       def lowercase			(		self:			Optional[Any]		)							->			Dict:




              """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       , out_features=self.out_features       , out_indices=self.out_indices       , )

       def lowercase			(		self:			int       , _SCREAMING_SNAKE_CASE:			Optional[Any]       , _SCREAMING_SNAKE_CASE:			str       , _SCREAMING_SNAKE_CASE:			List[Any]		)							->			Optional[int]:




              """simple docstring"""


              UpperCamelCase_ 							=	ResNetModel(config=__UpperCamelCase		)
              model.to(__UpperCamelCase		)
              model.eval()
              UpperCamelCase_ 							=	model(__UpperCamelCase		)
              # 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 lowercase			(		self:			int       , _SCREAMING_SNAKE_CASE:			Optional[Any]       , _SCREAMING_SNAKE_CASE:			str       , _SCREAMING_SNAKE_CASE:			str		)							->			int:




              """simple docstring"""


              UpperCamelCase_ 							=	self.num_labels
              UpperCamelCase_ 							=	ResNetForImageClassification(__UpperCamelCase		)
              model.to(__UpperCamelCase		)
              model.eval()
              UpperCamelCase_ 							=	model(__UpperCamelCase       , labels=__UpperCamelCase		)
              self.parent.assertEqual(result.logits.shape       , (self.batch_size, self.num_labels)		)

       def lowercase			(		self:			Dict       , _SCREAMING_SNAKE_CASE:			Optional[Any]       , _SCREAMING_SNAKE_CASE:			Optional[int]       , _SCREAMING_SNAKE_CASE:			str		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_ 							=	ResNetBackbone(config=__UpperCamelCase		)
              model.to(__UpperCamelCase		)
              model.eval()
              UpperCamelCase_ 							=	model(__UpperCamelCase		)

              # verify feature maps
              self.parent.assertEqual(len(result.feature_maps		)       , len(config.out_features		)		)
              self.parent.assertListEqual(list(result.feature_maps[0].shape		)       , [self.batch_size, self.hidden_sizes[1], 4, 4]		)

              # verify channels
              self.parent.assertEqual(len(model.channels		)       , len(config.out_features		)		)
              self.parent.assertListEqual(model.channels       , config.hidden_sizes[1:]		)

              # verify backbone works with out_features=None
              UpperCamelCase_ 							=	None
              UpperCamelCase_ 							=	ResNetBackbone(config=__UpperCamelCase		)
              model.to(__UpperCamelCase		)
              model.eval()
              UpperCamelCase_ 							=	model(__UpperCamelCase		)

              # verify feature maps
              self.parent.assertEqual(len(result.feature_maps		)       , 1		)
              self.parent.assertListEqual(list(result.feature_maps[0].shape		)       , [self.batch_size, self.hidden_sizes[-1], 1, 1]		)

              # verify channels
              self.parent.assertEqual(len(model.channels		)       , 1		)
              self.parent.assertListEqual(model.channels       , [config.hidden_sizes[-1]]		)



       def lowercase			(		self:			List[Any]		)							->			int:




              """simple docstring"""


              UpperCamelCase_ 							=	self.prepare_config_and_inputs()
              UpperCamelCase_							,			UpperCamelCase_							,			UpperCamelCase_ 							=	config_and_inputs
              UpperCamelCase_ 							=	{"pixel_values": pixel_values}
              return config, inputs_dict



@require_torch
class 				_UpperCamelCase       (						lowercase_	,    lowercase_	,    unittest.TestCase  ):
       _UpperCamelCase					:       List[Any]       = (
           (
               ResNetModel,
               ResNetForImageClassification,
               ResNetBackbone,
           )
           if is_torch_available()
           else ()
       )
       _UpperCamelCase					:       Optional[int]       = (
           {'''feature-extraction''': ResNetModel, '''image-classification''': ResNetForImageClassification}
           if is_torch_available()
           else {}
       )

       _UpperCamelCase					:       int       = True
       _UpperCamelCase					:       int       = False
       _UpperCamelCase					:       List[str]       = False
       _UpperCamelCase					:       Union[str, Any]       = False
       _UpperCamelCase					:       Any       = False

       def lowercase			(		self:			List[Any]		)							->			Union[str, Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	ResNetModelTester(self		)
              UpperCamelCase_ 							=	ConfigTester(self       , config_class=__UpperCamelCase       , has_text_modality=__UpperCamelCase		)

       def lowercase			(		self:			List[Any]		)							->			int:




              """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 lowercase			(		self:			Union[str, Any]		)							->			List[Any]:




              """simple docstring"""


              return

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




              """simple docstring"""


              pass

       @unittest.skip(reason="ResNet does not support input and output embeddings"		)
       def lowercase			(		self:			Optional[Any]		)							->			List[str]:




              """simple docstring"""


              pass

       def lowercase			(		self:			List[Any]		)							->			Optional[Any]:




              """simple docstring"""


              UpperCamelCase_							,			UpperCamelCase_ 							=	self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     UpperCamelCase_ 							=	model_class(__UpperCamelCase		)
                     UpperCamelCase_ 							=	inspect.signature(model.forward		)
                     # signature.parameters is an OrderedDict => so arg_names order is deterministic
                     UpperCamelCase_ 							=	[*signature.parameters.keys()]

                     UpperCamelCase_ 							=	["pixel_values"]
                     self.assertListEqual(arg_names[:1]       , __UpperCamelCase		)

       def lowercase			(		self:			Tuple		)							->			List[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*__UpperCamelCase		)

       def lowercase			(		self:			Union[str, Any]		)							->			List[str]:




              """simple docstring"""


              UpperCamelCase_ 							=	self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_backbone(*__UpperCamelCase		)

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




              """simple docstring"""


              UpperCamelCase_							,			UpperCamelCase_ 							=	self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     UpperCamelCase_ 							=	model_class(config=__UpperCamelCase		)
                     for name, module in model.named_modules():
                            if isinstance(__UpperCamelCase       , (nn.BatchNormad, nn.GroupNorm)		):
                                   self.assertTrue(
                                       torch.all(module.weight == 1		)       , msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''       , )
                                   self.assertTrue(
                                       torch.all(module.bias == 0		)       , msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''       , )

       def lowercase			(		self:			Optional[Any]		)							->			Optional[Any]:




              """simple docstring"""


              def check_hidden_states_output(_SCREAMING_SNAKE_CASE:			int       , _SCREAMING_SNAKE_CASE:			Any       , _SCREAMING_SNAKE_CASE:			Union[str, Any]		):
                     UpperCamelCase_ 							=	model_class(__UpperCamelCase		)
                     model.to(__UpperCamelCase		)
                     model.eval()

                     with torch.no_grad():
                            UpperCamelCase_ 							=	model(**self._prepare_for_class(__UpperCamelCase       , __UpperCamelCase		)		)

                     UpperCamelCase_ 							=	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                     UpperCamelCase_ 							=	self.model_tester.num_stages
                     self.assertEqual(len(__UpperCamelCase		)       , 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]       , )

              UpperCamelCase_							,			UpperCamelCase_ 							=	self.model_tester.prepare_config_and_inputs_for_common()
              UpperCamelCase_ 							=	["basic", "bottleneck"]
              for model_class in self.all_model_classes:
                     for layer_type in layers_type:
                            UpperCamelCase_ 							=	layer_type
                            UpperCamelCase_ 							=	True
                            check_hidden_states_output(__UpperCamelCase       , __UpperCamelCase       , __UpperCamelCase		)

                            # check that output_hidden_states also work using config
                            del inputs_dict["output_hidden_states"]
                            UpperCamelCase_ 							=	True

                            check_hidden_states_output(__UpperCamelCase       , __UpperCamelCase       , __UpperCamelCase		)

       @unittest.skip(reason="ResNet does not use feedforward chunking"		)
       def lowercase			(		self:			Tuple		)							->			List[Any]:




              """simple docstring"""


              pass

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




              """simple docstring"""


              UpperCamelCase_ 							=	self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase		)



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




              """simple docstring"""


              for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase_ 							=	ResNetModel.from_pretrained(__UpperCamelCase		)
                     self.assertIsNotNone(__UpperCamelCase		)




def 			lowerCAmelCase_			(				)  ->		Dict:
       UpperCamelCase_ 							=	Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
       return image



@require_torch
@require_vision
class 				_UpperCamelCase       (						unittest.TestCase  ):

       @cached_property
       def lowercase			(		self:			List[Any]		)							->			Any:




              """simple docstring"""


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



       @slow
       def lowercase			(		self:			Dict		)							->			Dict:




              """simple docstring"""


              UpperCamelCase_ 							=	ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(__UpperCamelCase		)

              UpperCamelCase_ 							=	self.default_image_processor
              UpperCamelCase_ 							=	prepare_img()
              UpperCamelCase_ 							=	image_processor(images=__UpperCamelCase       , return_tensors="pt"		).to(__UpperCamelCase		)

              # forward pass
              with torch.no_grad():
                     UpperCamelCase_ 							=	model(**__UpperCamelCase		)

              # verify the logits
              UpperCamelCase_ 							=	torch.Size((1, 1000)		)
              self.assertEqual(outputs.logits.shape       , __UpperCamelCase		)

              UpperCamelCase_ 							=	torch.tensor([-11.10_69, -9.78_77, -8.37_77]		).to(__UpperCamelCase		)

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



@require_torch
class 				_UpperCamelCase       (						lowercase_	,    unittest.TestCase  ):
       _UpperCamelCase					:       Union[str, Any]       = (ResNetBackbone,) if is_torch_available() else ()
       _UpperCamelCase					:       Optional[int]       = False
       _UpperCamelCase					:       List[Any]       = ResNetConfig

       def lowercase			(		self:			Dict		)							->			Optional[Any]:




              """simple docstring"""


              UpperCamelCase_ 							=	ResNetModelTester(self		)








"""simple docstring"""
from typing import List, Optional, Union

import numpy as np

from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


_snake_case	:						List[str]					=					logging.get_logger(__name__)






class    _UpperCAmelCase  (      lowercase_					):
					UpperCamelCase						=				['''input_values''', '''attention_mask''']


					def __init__(   self     :str	,			__UpperCamelCase     :List[str]=1	,			__UpperCamelCase     :Tuple=1_60_00	,			__UpperCamelCase     :Optional[int]=0.0	,			__UpperCamelCase     :Optional[int]=False	,			__UpperCamelCase     :Optional[Any]=True	,			**__UpperCamelCase     :Optional[Any]	,			):
												super().__init__(feature_size=__UpperCamelCase	,			sampling_rate=__UpperCamelCase	,			padding_value=__UpperCamelCase	,			**__UpperCamelCase						)
												A						=    return_attention_mask
												A						=    do_normalize


					@staticmethod
					def       lowerCamelCase			(   __UpperCamelCase     :List[np.ndarray]	,			__UpperCamelCase     :List[np.ndarray]	,			__UpperCamelCase     :float = 0.0						):
												if attention_mask is not None:
																			A						=    np.array(__UpperCamelCase	,			np.intaa						)
																			A						=    []

																			for vector, length in zip(__UpperCamelCase	,			attention_mask.sum(-1						)						):
																										A						=    (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1e-7						)
																										if length < normed_slice.shape[0]:
																																	A						=    padding_value

																										normed_input_values.append(__UpperCamelCase						)
												else:
																			A						=    [(x - x.mean()) / np.sqrt(x.var() + 1e-7						) for x in input_values]

												return normed_input_values


					def __call__(   self     :Tuple	,			__UpperCamelCase     :Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]	,			__UpperCamelCase     :Union[bool, str, PaddingStrategy] = False	,			__UpperCamelCase     :Optional[int] = None	,			__UpperCamelCase     :bool = False	,			__UpperCamelCase     :Optional[int] = None	,			__UpperCamelCase     :Optional[bool] = None	,			__UpperCamelCase     :Optional[Union[str, TensorType]] = None	,			__UpperCamelCase     :Optional[int] = None	,			**__UpperCamelCase     :List[str]	,			):

												if sampling_rate is not None:
																			if sampling_rate != self.sampling_rate:
																										raise ValueError(
																										    f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
																										    f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
																										    f" {self.sampling_rate} and not {sampling_rate}."						)
												else:
																			logger.warning(
																			    "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
																			    "Failing to do so can result in silent errors that might be hard to debug."						)

												A						=    isinstance(__UpperCamelCase	,			np.ndarray						) and len(raw_speech.shape						) > 1
												if is_batched_numpy and len(raw_speech.shape						) > 2:
																			raise ValueError(f"Only mono-channel audio is supported for input to {self}"						)
												A						=    is_batched_numpy or (
												    isinstance(__UpperCamelCase	,			(list, tuple)						) and (isinstance(raw_speech[0]	,			(np.ndarray, tuple, list)						))
												)

												# always return batch
												if not is_batched:
																			A						=    [raw_speech]

												# convert into correct format for padding
												A						=    BatchFeature({"input_values": raw_speech}						)

												A						=    self.pad(
												    __UpperCamelCase	,			padding=__UpperCamelCase	,			max_length=__UpperCamelCase	,			truncation=__UpperCamelCase	,			pad_to_multiple_of=__UpperCamelCase	,			return_attention_mask=__UpperCamelCase	,			)

												# convert input values to correct format
												A						=    padded_inputs["input_values"]
												if not isinstance(input_values[0]	,			np.ndarray						):
																			A						=    [np.asarray(__UpperCamelCase	,			dtype=np.floataa						) for array in input_values]
												elif (
												    not isinstance(__UpperCamelCase	,			np.ndarray						)
												    and isinstance(input_values[0]	,			np.ndarray						)
												    and input_values[0].dtype is np.dtype(np.floataa						)
												):
																			A						=    [array.astype(np.floataa						) for array in input_values]
												elif isinstance(__UpperCamelCase	,			np.ndarray						) and input_values.dtype is np.dtype(np.floataa						):
																			A						=    input_values.astype(np.floataa						)

												# convert attention_mask to correct format
												A						=    padded_inputs.get("attention_mask"						)
												if attention_mask is not None:
																			A						=    [np.asarray(__UpperCamelCase	,			dtype=np.intaa						) for array in attention_mask]

												# zero-mean and unit-variance normalization
												if self.do_normalize:
																			A						=    (
																			    attention_mask
																			    if self._get_padding_strategies(__UpperCamelCase	,			max_length=__UpperCamelCase						) is not PaddingStrategy.DO_NOT_PAD
																			    else None
																			)
																			A						=    self.zero_mean_unit_var_norm(
																			    padded_inputs["input_values"]	,			attention_mask=__UpperCamelCase	,			padding_value=self.padding_value						)

												if return_tensors is not None:
																			A						=    padded_inputs.convert_to_tensors(__UpperCamelCase						)

												return padded_inputs


