






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 				lowerCAmelCase_	:


				def __init__(					self ,						_lowerCAmelCase ,						_lowerCAmelCase=3 ,						_lowerCAmelCase=3_2 ,						_lowerCAmelCase=3 ,						_lowerCAmelCase=1_0 ,						_lowerCAmelCase=[1_0, 2_0, 3_0, 4_0] ,						_lowerCAmelCase=[1, 1, 2, 1] ,						_lowerCAmelCase=True ,						_lowerCAmelCase=True ,						_lowerCAmelCase="relu" ,						_lowerCAmelCase=3 ,						_lowerCAmelCase=None ,						):
											_lowercase							:   str 							=   parent
											_lowercase							:   Any 							=   batch_size
											_lowercase							:   Any 							=   image_size
											_lowercase							:   List[str] 							=   num_channels
											_lowercase							:   Tuple 							=   embeddings_size
											_lowercase							:   Optional[Any] 							=   hidden_sizes
											_lowercase							:   Optional[int] 							=   depths
											_lowercase							:   Tuple 							=   is_training
											_lowercase							:   Any 							=   use_labels
											_lowercase							:   List[str] 							=   hidden_act
											_lowercase							:   Tuple 							=   num_labels
											_lowercase							:   Any 							=   scope
											_lowercase							:   List[Any] 							=   len(snake_case__      )


				def 						__a					(					self      ):
											_lowercase							:   Optional[Any] 							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

											_lowercase							:   Optional[Any] 							=   self.get_config()

											return config, pixel_values, labels


				def 						__a					(					self      ):
											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 						__a					(					self ,						_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
											_lowercase							:   Union[str, Any] 							=   TFResNetModel(config=snake_case__      )
											_lowercase							:   Union[str, Any] 							=   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 // 3_2, self.image_size // 3_2) ,						)


				def 						__a					(					self ,						_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
											_lowercase							:   int 							=   self.num_labels
											_lowercase							:   int 							=   TFResNetForImageClassification(snake_case__      )
											_lowercase							:   Optional[Any] 							=   model(snake_case__ ,						labels=snake_case__      )
											self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.num_labels)      )


				def 						__a					(					self      ):
											_lowercase							:   Optional[Any] 							=   self.prepare_config_and_inputs()
											_lowercase							,							_lowercase							,							_lowercase							:   str 							=   config_and_inputs
											_lowercase							:   List[str] 							=   {'pixel_values': pixel_values}
											return config, inputs_dict




@require_tf
class 				lowerCAmelCase_	(		SCREAMING_SNAKE_CASE__   ,		SCREAMING_SNAKE_CASE__   ,		unittest.TestCase			):
				_UpperCamelCase					:       Optional[int]							       = (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
				_UpperCamelCase					:       Any							       = (
				    {"feature-extraction": TFResNetModel, "image-classification": TFResNetForImageClassification}
				    if is_tf_available()
				    else {}
				)

				_UpperCamelCase					:       Optional[Any]							       = False
				_UpperCamelCase					:       int							       = False
				_UpperCamelCase					:       List[str]							       = False
				_UpperCamelCase					:       Any							       = False
				_UpperCamelCase					:       Optional[Any]							       = False


				def 						__a					(					self      ):
											_lowercase							:   str 							=   TFResNetModelTester(self      )
											_lowercase							:   Dict 							=   ConfigTester(self ,						config_class=snake_case__ ,						has_text_modality=snake_case__      )


				def 						__a					(					self      ):
											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 						__a					(					self      ):
											return


				@unittest.skip(reason='ResNet does not use inputs_embeds'      )
				def 						__a					(					self      ):
											pass


				@unittest.skip(reason='ResNet does not support input and output embeddings'      )
				def 						__a					(					self      ):
											pass


				def 						__a					(					self      ):
											_lowercase							,							_lowercase							:   Optional[int] 							=   self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		_lowercase							:   Optional[Any] 							=   model_class(snake_case__      )
																		_lowercase							:   str 							=   inspect.signature(model.call      )
																		# signature.parameters is an OrderedDict => so arg_names order is deterministic
																		_lowercase							:   Union[str, Any] 							=   [*signature.parameters.keys()]

																		_lowercase							:   int 							=   ['pixel_values']
																		self.assertListEqual(arg_names[:1] ,						snake_case__      )


				def 						__a					(					self      ):
											_lowercase							:   Dict 							=   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*snake_case__      )


				def 						__a					(					self      ):

											def check_hidden_states_output(_lowerCAmelCase ,						_lowerCAmelCase ,						_lowerCAmelCase      ):
																		_lowercase							:   Optional[Any] 							=   model_class(snake_case__      )
																		_lowercase							:   Optional[int] 							=   model(**self._prepare_for_class(snake_case__ ,						snake_case__      )      )

																		_lowercase							:   str 							=   outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																		_lowercase							:   Optional[int] 							=   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							:   Optional[Any] 							=   self.model_tester.prepare_config_and_inputs_for_common()
											_lowercase							:   Optional[Any] 							=   ['basic', 'bottleneck']
											for model_class in self.all_model_classes:
																		for layer_type in layers_type:
																									_lowercase							:   Dict 							=   layer_type
																									_lowercase							:   Tuple 							=   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							:   Any 							=   True

																									check_hidden_states_output(snake_case__ ,						snake_case__ ,						snake_case__      )


				def 						__a					(					self      ):
											_lowercase							:   Dict 							=   self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*snake_case__      )


				@slow
				def 						__a					(					self      ):

											for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		_lowercase							:   Dict 							=   TFResNetModel.from_pretrained(snake_case__      )
																		self.assertIsNotNone(snake_case__      )






def    __magic_name__    (	)     ->    Tuple:
							_lowercase							:   Union[str, Any] 							=   Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
							return image






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


				@cached_property
				def 						__a					(					self      ):
											return (
											    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )
											    if is_vision_available()
											    else None
											)


				@slow
				def 						__a					(					self      ):
											_lowercase							:   Any 							=   TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]      )

											_lowercase							:   Dict 							=   self.default_image_processor
											_lowercase							:   List[str] 							=   prepare_img()
											_lowercase							:   int 							=   image_processor(images=snake_case__ ,						return_tensors='tf'      )

											# forward pass
											_lowercase							:   Optional[Any] 							=   model(**snake_case__      )

											# verify the logits
											_lowercase							:   Optional[int] 							=   tf.TensorShape((1, 1_0_0_0)      )
											self.assertEqual(outputs.logits.shape ,						snake_case__      )

											_lowercase							:   Union[str, Any] 							=   tf.constant([-11.10_69, -9.78_77, -8.37_77]      )

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










def 					_a							(					lowerCAmelCase    ,						lowerCAmelCase )->	List[str]:
		SCREAMING_SNAKE_CASE_					      =							[1]
		for i in range(2    ,						lowerCAmelCase ):
				factorials.append(factorials[-1] * i )
		assert 0 <= k < factorials[-1] * n, "k out of bounds"

		SCREAMING_SNAKE_CASE_					      =							[]
		SCREAMING_SNAKE_CASE_					      =							list(range(lowerCAmelCase ) )

		# Find permutation
		while factorials:
				SCREAMING_SNAKE_CASE_					      =							factorials.pop()
				SCREAMING_SNAKE_CASE_      ,				SCREAMING_SNAKE_CASE_					      =							divmod(lowerCAmelCase    ,						lowerCAmelCase )
				permutation.append(elements[number] )
				elements.remove(elements[number] )
		permutation.append(elements[0] )

		return permutation


if __name__ == "__main__":
						import doctest

						doctest.testmod()