






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 	snake_case__ :
	def __init__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=32      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=10      ,       lowerCAmelCase__=[10, 20, 30, 40]      ,       lowerCAmelCase__=[1, 1, 2, 1]      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__="relu"      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=None      ,       )							->				Tuple:
							__magic_name__      :       List[Any]       						= parent
							__magic_name__      :       Optional[int]       						= batch_size
							__magic_name__      :       str       						= image_size
							__magic_name__      :       Tuple       						= num_channels
							__magic_name__      :       Dict       						= embeddings_size
							__magic_name__      :       Tuple       						= hidden_sizes
							__magic_name__      :       str       						= depths
							__magic_name__      :       Optional[int]       						= is_training
							__magic_name__      :       Tuple       						= use_labels
							__magic_name__      :       Any       						= hidden_act
							__magic_name__      :       List[Any]       						= num_labels
							__magic_name__      :       Any       						= scope
							__magic_name__      :       Tuple       						= len(lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Tuple:
							__magic_name__      :       List[Any]       						= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

							__magic_name__      :       Dict       						= None
							if self.use_labels:
													__magic_name__      :       List[Any]       						= ids_tensor([self.batch_size]      ,       self.num_labels			)

							__magic_name__      :       Union[str, Any]       						= self.get_config()

							return config, pixel_values, labels
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Any:
							__magic_name__      :       Union[str, Any]       						= TFResNetModel(config=lowerCAmelCase__			)
							__magic_name__      :       Optional[Any]       						= model(lowerCAmelCase__			)
							# 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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Any:
							__magic_name__      :       List[str]       						= self.num_labels
							__magic_name__      :       str       						= TFResNetForImageClassification(lowerCAmelCase__			)
							__magic_name__      :       Any       						= model(lowerCAmelCase__      ,       labels=lowerCAmelCase__			)
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.num_labels)			)







	def       __magic_name__    (    self			)							->				Tuple:
							__magic_name__      :       Any       						= self.prepare_config_and_inputs()
							__magic_name__      :       str       						= config_and_inputs
							__magic_name__      :       Union[str, Any]       						= {"""pixel_values""": pixel_values}
							return config, inputs_dict





@require_tf
class 	snake_case__ (							_lowerCAmelCase						,  _lowerCAmelCase						,  unittest.TestCase				):
	lowercase__						:					Any											=   (TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
	lowercase__						:					Optional[Any]											=   (
	    {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	lowercase__						:					int											=   False
	lowercase__						:					Union[str, Any]											=   False
	lowercase__						:					Tuple											=   False
	lowercase__						:					Optional[int]											=   False
	lowercase__						:					Optional[int]											=   False
	def       __magic_name__    (    self			)							->				Dict:
							__magic_name__      :       List[str]       						= TFResNetModelTester(self			)
							__magic_name__      :       Union[str, Any]       						= ConfigTester(self      ,       config_class=lowerCAmelCase__      ,       has_text_modality=lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							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       __magic_name__    (    self			)							->				Any:
							return
	@unittest.skip(reason="""ResNet does not use inputs_embeds"""			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							pass
	@unittest.skip(reason="""ResNet does not support input and output embeddings"""			)
	def       __magic_name__    (    self			)							->				List[str]:
							pass
	def       __magic_name__    (    self			)							->				Optional[Any]:
							__magic_name__      :       Optional[int]       						= self.model_tester.prepare_config_and_inputs_for_common()

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

													__magic_name__      :       List[Any]       						= ["""pixel_values"""]
													self.assertListEqual(arg_names[:1]      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							__magic_name__      :       Union[str, Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				List[Any]:
							def check_hidden_states_output(lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			):
													__magic_name__      :       Optional[int]       						= model_class(lowerCAmelCase__			)
													__magic_name__      :       Optional[int]       						= model(**self._prepare_for_class(lowerCAmelCase__      ,       lowerCAmelCase__			)			)

													__magic_name__      :       Tuple       						= outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

													__magic_name__      :       Union[str, Any]       						= self.model_tester.num_stages
													self.assertEqual(len(lowerCAmelCase__			)      ,       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]      ,       )

							__magic_name__      :       Any       						= self.model_tester.prepare_config_and_inputs_for_common()
							__magic_name__      :       Optional[Any]       						= ["""basic""", """bottleneck"""]
							for model_class in self.all_model_classes:
													for layer_type in layers_type:
																			__magic_name__      :       Optional[int]       						= layer_type
																			__magic_name__      :       Optional[int]       						= True
																			check_hidden_states_output(lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)

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

																			check_hidden_states_output(lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				str:
							__magic_name__      :       Optional[int]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__			)







	@slow
	def       __magic_name__    (    self			)							->				Union[str, Any]:
							for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__      :       Union[str, Any]       						= TFResNetModel.from_pretrained(lowerCAmelCase__			)
													self.assertIsNotNone(lowerCAmelCase__			)



def    UpperCamelCase						(	):






						"""simple docstring"""







						__magic_name__      :       int       						= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
						return image





@require_tf
@require_vision
class 	snake_case__ (							unittest.TestCase				):
	@cached_property
	def       __magic_name__    (    self			)							->				Optional[Any]:
							return (
							    AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)
							    if is_vision_available()
							    else None
							)







	@slow
	def       __magic_name__    (    self			)							->				Optional[int]:
							__magic_name__      :       List[str]       						= TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]			)

							__magic_name__      :       List[str]       						= self.default_image_processor
							__magic_name__      :       str       						= prepare_img()
							__magic_name__      :       Any       						= image_processor(images=lowerCAmelCase__      ,       return_tensors="""tf"""			)

							# forward pass
							__magic_name__      :       str       						= model(**lowerCAmelCase__			)

							# verify the logits
							__magic_name__      :       Optional[int]       						= tf.TensorShape((1, 10_00)			)
							self.assertEqual(outputs.logits.shape      ,       lowerCAmelCase__			)

							__magic_name__      :       Any       						= tf.constant([-11.10_69, -9.7_8_7_7, -8.3_7_7_7]			)

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








from __future__ import annotations

import math

import numpy as np
from numpy.linalg import norm

def    UpperCamelCase						(	_A,   _A			):






						"""simple docstring"""







						return math.sqrt(sum(pow(a - b,   2			) for a, b in zip(_A,   _A			)			)			)

def    UpperCamelCase						(	_A,   _A			):






						"""simple docstring"""







						if dataset.ndim != value_array.ndim:
												__magic_name__      :       str       						= (
												    """Wrong input data's dimensions... """
												    f'dataset : {dataset.ndim}, value_array : {value_array.ndim}'
												)
												raise ValueError(_A			)

						try:
												if dataset.shape[1] != value_array.shape[1]:
																		__magic_name__      :       Optional[Any]       						= (
																		    """Wrong input data's shape... """
																		    f'dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}'
																		)
																		raise ValueError(_A			)
						except IndexError:
												if dataset.ndim != value_array.ndim:
																		raise TypeError("""Wrong shape"""			)

						if dataset.dtype != value_array.dtype:
												__magic_name__      :       List[Any]       						= (
												    """Input data have different datatype... """
												    f'dataset : {dataset.dtype}, value_array : {value_array.dtype}'
												)
												raise TypeError(_A			)

						__magic_name__      :       Dict       						= []

						for value in value_array:
												__magic_name__      :       Tuple       						= euclidean(_A,   dataset[0]			)
												__magic_name__      :       Any       						= dataset[0].tolist()

												for dataset_value in dataset[1:]:
																		__magic_name__      :       Any       						= euclidean(_A,   _A			)

																		if dist > temp_dist:
																								__magic_name__      :       Dict       						= temp_dist
																								__magic_name__      :       Any       						= dataset_value.tolist()

												answer.append([vector, dist]			)

						return answer

def    UpperCamelCase						(	_A,   _A			):






						"""simple docstring"""







						return np.dot(_A,   _A			) / (norm(_A			) * norm(_A			))


if __name__ == "__main__":
		import doctest

		doctest.testmod()
