




"""simple docstring"""
from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor

class __lowercase:




					'''simple docstring'''


					def __init__(    self						,	__a						,	__a=3						,	__a=32						,	__a=3						,	__a=10						,	__a=[10, 20, 30, 40]						,	__a=[1, 1, 2, 1]						,	__a=True						,	__a=True						,	__a="relu"						,	__a=3						,	__a=None						,	):
								__lowerCamelCase					:	List[Any]	       =				parent
								__lowerCamelCase					:	List[Any]	       =				batch_size
								__lowerCamelCase					:	Any	       =				image_size
								__lowerCamelCase					:	Tuple	       =				num_channels
								__lowerCamelCase					:	Tuple	       =				embeddings_size
								__lowerCamelCase					:	Optional[int]	       =				hidden_sizes
								__lowerCamelCase					:	Dict	       =				depths
								__lowerCamelCase					:	str	       =				is_training
								__lowerCamelCase					:	str	       =				use_labels
								__lowerCamelCase					:	Any	       =				hidden_act
								__lowerCamelCase					:	Union[str, Any]	       =				num_labels
								__lowerCamelCase					:	Optional[Any]	       =				scope
								__lowerCamelCase					:	List[str]	       =				len(__a     )
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	str	       =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

								__lowerCamelCase					:	Optional[Any]	       =				self.get_config()
								return config, pixel_values, labels
					def     snake_case_				(    self     ):
								return RegNetConfig(
								    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						,	)
					def     snake_case_				(    self						,	__a						,	__a						,	__a     ):
								__lowerCamelCase					:	List[str]	       =				TFRegNetModel(config=__a     )
								__lowerCamelCase					:	Optional[int]	       =				model(__a						,	training=__a     )
								# 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     snake_case_				(    self						,	__a						,	__a						,	__a     ):
								__lowerCamelCase					:	Optional[int]	       =				self.num_labels
								__lowerCamelCase					:	List[str]	       =				TFRegNetForImageClassification(__a     )
								__lowerCamelCase					:	Any	       =				model(__a						,	labels=__a						,	training=__a     )
								self.parent.assertEqual(result.logits.shape						,	(self.batch_size, self.num_labels)     )





					def     snake_case_				(    self     ):
								__lowerCamelCase					:	int	       =				self.prepare_config_and_inputs()
								__lowerCamelCase       ,      __lowerCamelCase       ,      __lowerCamelCase					:	List[str]	       =				config_and_inputs
								__lowerCamelCase					:	Tuple	       =				{'pixel_values': pixel_values}
								return config, inputs_dict



@require_tf
class __lowercase(      lowercase__	,	lowercase__	,	unittest.TestCase				):




					'''simple docstring'''


					__a						:						Union[str, Any]     		= (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
					__a						:						int     		= (
					    {'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
					    if is_tf_available()
					    else {}
					)

					__a						:						Optional[int]     		= False
					__a						:						Union[str, Any]     		= False
					__a						:						Dict     		= False
					__a						:						int     		= False
					__a						:						List[str]     		= False
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	Optional[Any]	       =				TFRegNetModelTester(self     )
								__lowerCamelCase					:	Dict	       =				ConfigTester(self						,	config_class=__a						,	has_text_modality=__a     )
					def     snake_case_				(    self     ):
								return
					@unittest.skip(reason='RegNet does not use inputs_embeds'     )
					def     snake_case_				(    self     ):
								pass
					@unittest.skipIf(
					    not is_tf_available() or len(tf.config.list_physical_devices('GPU'     )     ) == 0						,	reason='TF does not support backprop for grouped convolutions on CPU.'						,	)
					@slow
					def     snake_case_				(    self     ):
								super().test_keras_fit()
					@unittest.skip(reason='RegNet does not support input and output embeddings'     )
					def     snake_case_				(    self     ):
								pass
					def     snake_case_				(    self     ):
								__lowerCamelCase       ,      __lowerCamelCase					:	Dict	       =				self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
											__lowerCamelCase					:	List[Any]	       =				model_class(__a     )
											__lowerCamelCase					:	str	       =				inspect.signature(model.call     )
											# signature.parameters is an OrderedDict => so arg_names order is deterministic
											__lowerCamelCase					:	Tuple	       =				[*signature.parameters.keys()]

											__lowerCamelCase					:	List[str]	       =				['pixel_values']
											self.assertListEqual(arg_names[:1]						,	__a     )
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	int	       =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*__a     )
					def     snake_case_				(    self     ):
								def check_hidden_states_output(__a						,	__a						,	__a     ):
											__lowerCamelCase					:	Dict	       =				model_class(__a     )
											__lowerCamelCase					:	Any	       =				model(**self._prepare_for_class(__a						,	__a     )						,	training=__a     )

											__lowerCamelCase					:	List[str]	       =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

											__lowerCamelCase					:	str	       =				self.model_tester.num_stages
											self.assertEqual(len(__a     )						,	expected_num_stages + 1     )

											# RegNet'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 // 2, self.model_tester.image_size // 2]						,	)

								__lowerCamelCase       ,      __lowerCamelCase					:	List[str]	       =				self.model_tester.prepare_config_and_inputs_for_common()
								__lowerCamelCase					:	Optional[int]	       =				['basic', 'bottleneck']
								for model_class in self.all_model_classes:
											for layer_type in layers_type:
														__lowerCamelCase					:	Union[str, Any]	       =				layer_type
														__lowerCamelCase					:	Optional[int]	       =				True
														check_hidden_states_output(__a						,	__a						,	__a     )

														# check that output_hidden_states also work using config
														del inputs_dict["output_hidden_states"]
														__lowerCamelCase					:	Union[str, Any]	       =				True

														check_hidden_states_output(__a						,	__a						,	__a     )
					def     snake_case_				(    self     ):
								__lowerCamelCase       ,      __lowerCamelCase					:	List[Any]	       =				self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(__a						,	__a						,	__a						,	__a={}     ):
											__lowerCamelCase					:	List[Any]	       =				model(__a						,	return_dict=__a						,	**__a     )
											__lowerCamelCase					:	Dict	       =				model(__a						,	return_dict=__a						,	**__a     ).to_tuple()

											def recursive_check(__a						,	__a     ):
														if isinstance(__a						,	(List, Tuple)     ):
																	for tuple_iterable_value, dict_iterable_value in zip(__a						,	__a     ):
																				recursive_check(__a						,	__a     )
														elif tuple_object is None:
																	return
														else:
																	self.assertTrue(
																	    all(tf.equal(__a						,	__a     )     )						,	msg=(
																	        'Tuple and dict output are not equal. Difference:'
																	        f''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object     )     )}'''
																	    )						,	)

														recursive_check(__a						,	__a     )

								for model_class in self.all_model_classes:
											__lowerCamelCase					:	Optional[int]	       =				model_class(__a     )

											__lowerCamelCase					:	Dict	       =				self._prepare_for_class(__a						,	__a     )
											__lowerCamelCase					:	Optional[int]	       =				self._prepare_for_class(__a						,	__a     )
											check_equivalence(__a						,	__a						,	__a     )

											__lowerCamelCase					:	str	       =				self._prepare_for_class(__a						,	__a						,	return_labels=__a     )
											__lowerCamelCase					:	str	       =				self._prepare_for_class(__a						,	__a						,	return_labels=__a     )
											check_equivalence(__a						,	__a						,	__a     )

											__lowerCamelCase					:	Optional[Any]	       =				self._prepare_for_class(__a						,	__a     )
											__lowerCamelCase					:	Dict	       =				self._prepare_for_class(__a						,	__a     )
											check_equivalence(__a						,	__a						,	__a						,	{'output_hidden_states': True}     )

											__lowerCamelCase					:	Optional[Any]	       =				self._prepare_for_class(__a						,	__a						,	return_labels=__a     )
											__lowerCamelCase					:	Optional[int]	       =				self._prepare_for_class(__a						,	__a						,	return_labels=__a     )
											check_equivalence(__a						,	__a						,	__a						,	{'output_hidden_states': True}     )
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	str	       =				self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*__a     )





					@slow
					def     snake_case_				(    self     ):
								for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCamelCase					:	Optional[Any]	       =				TFRegNetModel.from_pretrained(__a     )
											self.assertIsNotNone(__a     )





def 						UpperCAmelCase				(			)  ->     Optional[Any]:
			__lowerCamelCase					:	str	       =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
			return image






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




					'''simple docstring'''


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





					@slow
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	Dict	       =				TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]     )

								__lowerCamelCase					:	Any	       =				self.default_image_processor
								__lowerCamelCase					:	Optional[int]	       =				prepare_img()
								__lowerCamelCase					:	Optional[Any]	       =				image_processor(images=__a						,	return_tensors='tf'     )

								# forward pass
								__lowerCamelCase					:	Dict	       =				model(**__a						,	training=__a     )

								# verify the logits
								__lowerCamelCase					:	str	       =				tf.TensorShape((1, 1000)     )
								self.assertEqual(outputs.logits.shape						,	__a     )

								__lowerCamelCase					:	Tuple	       =				tf.constant([-0.4_180, -1.5_051, -3.4_836]     )

								tf.debugging.assert_near(outputs.logits[0, :3]						,	__a						,	atol=1E-4     )









"""simple docstring"""
a_				:    Dict										=     {
    '''meter''': '''m''',
    '''kilometer''': '''km''',
    '''megametre''': '''Mm''',
    '''gigametre''': '''Gm''',
    '''terametre''': '''Tm''',
    '''petametre''': '''Pm''',
    '''exametre''': '''Em''',
    '''zettametre''': '''Zm''',
    '''yottametre''': '''Ym''',
}
# Exponent of the factor(meter)
a_				:    Optional[int]										=     {
    '''m''': 0,
    '''km''': 3,
    '''Mm''': 6,
    '''Gm''': 9,
    '''Tm''': 12,
    '''Pm''': 15,
    '''Em''': 18,
    '''Zm''': 21,
    '''Ym''': 24,
}





def 						UpperCAmelCase				(			A__:    float							,				A__:    str							,				A__:    str     )  ->     float:
			__lowerCamelCase					:	List[Any]	       =				from_type.lower().strip('s'     )
			__lowerCamelCase					:	Optional[int]	       =				to_type.lower().strip('s'     )

			__lowerCamelCase					:	int	       =				UNIT_SYMBOL.get(A__							,				A__     )
			__lowerCamelCase					:	Dict	       =				UNIT_SYMBOL.get(A__							,				A__     )

			if from_sanitized not in METRIC_CONVERSION:
						__lowerCamelCase					:	Dict	       =				(
						    f'''Invalid \'from_type\' value: {from_type!r}.\n'''
						    f'''Conversion abbreviations are: {", ".join(A__     )}'''
						)
						raise ValueError(A__     )
			if to_sanitized not in METRIC_CONVERSION:
						__lowerCamelCase					:	Any	       =				(
						    f'''Invalid \'to_type\' value: {to_type!r}.\n'''
						    f'''Conversion abbreviations are: {", ".join(A__     )}'''
						)
						raise ValueError(A__     )
			__lowerCamelCase					:	Any	       =				METRIC_CONVERSION[from_sanitized]
			__lowerCamelCase					:	Tuple	       =				METRIC_CONVERSION[to_sanitized]
			__lowerCamelCase					:	Any	       =				1

			if from_exponent > to_exponent:
						__lowerCamelCase					:	Union[str, Any]	       =				from_exponent - to_exponent
			else:
						__lowerCamelCase					:	List[Any]	       =				-(to_exponent - from_exponent)

			return value * pow(10							,				A__     )


if __name__ == "__main__":
					from doctest import testmod

					testmod()



