




from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
					from PIL import Image

					from transformers import ConvNextImageProcessor
class      a__       :






						def __init__(  self						,     _A						,     _A=1_3						,     _A=3_2						,     _A=3						,     _A=4						,     _A=[1_0, 2_0, 3_0, 4_0]						,     _A=[2, 2, 3, 2]						,     _A=True						,     _A=True						,     _A=3_7						,     _A="gelu"						,     _A=1_0						,     _A=0.02						,     _A=3						,     _A=None						,     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			parent
											__lowerCAmelCase							  =			batch_size
											__lowerCAmelCase							  =			image_size
											__lowerCAmelCase							  =			num_channels
											__lowerCAmelCase							  =			num_stages
											__lowerCAmelCase							  =			hidden_sizes
											__lowerCAmelCase							  =			depths
											__lowerCAmelCase							  =			is_training
											__lowerCAmelCase							  =			use_labels
											__lowerCAmelCase							  =			intermediate_size
											__lowerCAmelCase							  =			hidden_act
											__lowerCAmelCase							  =			type_sequence_label_size
											__lowerCAmelCase							  =			initializer_range
											__lowerCAmelCase							  =			scope






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



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

											__lowerCAmelCase							  =			None
											if self.use_labels:
																__lowerCAmelCase							  =			ids_tensor([self.batch_size]						,     self.type_sequence_label_size     )

											__lowerCAmelCase							  =			self.get_config()

											return config, pixel_values, labels






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											return ConvNextConfig(
											    num_channels=self.num_channels						,     hidden_sizes=self.hidden_sizes						,     depths=self.depths						,     num_stages=self.num_stages						,     hidden_act=self.hidden_act						,     is_decoder=_snake_case						,     initializer_range=self.initializer_range						,     )






						def 							__SCREAMING_SNAKE_CASE(  self						,     _A						,     _A						,     _A     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			TFConvNextModel(config=_snake_case     )
											__lowerCAmelCase							  =			model(_snake_case						,     training=_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 							__SCREAMING_SNAKE_CASE(  self						,     _A						,     _A						,     _A     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			self.type_sequence_label_size
											__lowerCAmelCase							  =			TFConvNextForImageClassification(_snake_case     )
											__lowerCAmelCase							  =			model(_snake_case						,     labels=_snake_case						,     training=_snake_case     )
											self.parent.assertEqual(result.logits.shape						,     (self.batch_size, self.type_sequence_label_size)     )






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			self.prepare_config_and_inputs()
											__lowerCAmelCase							  =			config_and_inputs
											__lowerCAmelCase							  =			{'pixel_values': pixel_values}
											return config, inputs_dict






@require_tf
class      a__       (   snake_case__					,							snake_case__					,							unittest.TestCase ):
						_a				:       Optional[int]   =       (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
						_a				:       List[Any]   =       (
						    {'feature-extraction': TFConvNextModel, 'image-classification': TFConvNextForImageClassification}
						    if is_tf_available()
						    else {}
						)

						_a				:       str   =       False
						_a				:       str   =       False
						_a				:       int   =       False
						_a				:       str   =       False
						_a				:       Any   =       False






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			TFConvNextModelTester(self     )
											__lowerCAmelCase							  =			ConfigTester(
											    self						,     config_class=_snake_case						,     has_text_modality=_snake_case						,     hidden_size=3_7						,     )






						@unittest.skip(reason="ConvNext does not use inputs_embeds"     )
						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											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 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											super().test_keras_fit()






						@unittest.skip(reason="ConvNext does not support input and output embeddings"     )
						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											pass






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			self.model_tester.prepare_config_and_inputs_for_common()

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

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






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_snake_case     )






						@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."						,     )
						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											super().test_dataset_conversion()






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											def check_hidden_states_output(_A						,     _A						,     _A     ):
																__lowerCAmelCase							  =			model_class(_snake_case     )

																__lowerCAmelCase							  =			model(**self._prepare_for_class(_snake_case						,     _snake_case     )     )
																__lowerCAmelCase							  =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																__lowerCAmelCase							  =			self.model_tester.num_stages
																self.assertEqual(len(_snake_case     )						,     expected_num_stages + 1     )

																# ConvNext'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]						,     )

											__lowerCAmelCase							  =			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__lowerCAmelCase							  =			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"]
																__lowerCAmelCase							  =			True

																check_hidden_states_output(_snake_case						,     _snake_case						,     _snake_case     )






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			self.model_tester.prepare_config_and_inputs_for_common()

											def check_equivalence(_A						,     _A						,     _A						,     _A={}     ):
																__lowerCAmelCase							  =			model(_snake_case						,     return_dict=_snake_case						,     **_snake_case     )
																__lowerCAmelCase							  =			model(_snake_case						,     return_dict=_snake_case						,     **_snake_case     ).to_tuple()

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

																					recursive_check(_snake_case						,     _snake_case     )

											for model_class in self.all_model_classes:
																__lowerCAmelCase							  =			model_class(_snake_case     )

																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case     )
																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case     )
																check_equivalence(_snake_case						,     _snake_case						,     _snake_case     )

																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case						,     return_labels=_snake_case     )
																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case						,     return_labels=_snake_case     )
																check_equivalence(_snake_case						,     _snake_case						,     _snake_case     )

																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case     )
																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case     )
																check_equivalence(_snake_case						,     _snake_case						,     _snake_case						,     {"output_hidden_states": True}     )

																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case						,     return_labels=_snake_case     )
																__lowerCAmelCase							  =			self._prepare_for_class(_snake_case						,     _snake_case						,     return_labels=_snake_case     )
																check_equivalence(_snake_case						,     _snake_case						,     _snake_case						,     {"output_hidden_states": True}     )






						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_snake_case     )






						@slow
						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"     )
											self.assertIsNotNone(_snake_case     )







def       _a (		):
					__lowerCAmelCase							  =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
					return image


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






						@cached_property
						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											return ConvNextImageProcessor.from_pretrained("facebook/convnext-tiny-224"     ) if is_vision_available() else None






						@slow
						def 							__SCREAMING_SNAKE_CASE(  self     ):




											"""simple docstring"""



											__lowerCAmelCase							  =			TFConvNextForImageClassification.from_pretrained("facebook/convnext-tiny-224"     )

											__lowerCAmelCase							  =			self.default_image_processor
											__lowerCAmelCase							  =			prepare_img()
											__lowerCAmelCase							  =			image_processor(images=_snake_case						,     return_tensors="tf"     )

											# forward pass
											__lowerCAmelCase							  =			model(**_snake_case     )

											# verify the logits
											__lowerCAmelCase							  =			tf.TensorShape((1, 1_0_0_0)     )
											self.assertEqual(outputs.logits.shape						,     _snake_case     )

											__lowerCAmelCase							  =			tf.constant([-0.02_60, -0.47_39, 0.19_11]     )

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












from collections import namedtuple

UpperCamelCase											=      namedtuple('''from_to''', '''from_ to''')

UpperCamelCase											=      {
    '''millimeter''': '''mm''',
    '''centimeter''': '''cm''',
    '''meter''': '''m''',
    '''kilometer''': '''km''',
    '''inch''': '''in''',
    '''inche''': '''in''',  # Trailing 's' has been stripped off
    '''feet''': '''ft''',
    '''foot''': '''ft''',
    '''yard''': '''yd''',
    '''mile''': '''mi''',
}

UpperCamelCase											=      {
    '''mm''': from_to(0.001, 1_0_0_0),
    '''cm''': from_to(0.01, 1_0_0),
    '''m''': from_to(1, 1),
    '''km''': from_to(1_0_0_0, 0.001),
    '''in''': from_to(0.0254, 39.3701),
    '''ft''': from_to(0.3048, 3.2_8084),
    '''yd''': from_to(0.9144, 1.0_9361),
    '''mi''': from_to(1609.34, 0.0_0062_1371),
}




def       _a   (							lowerCamelCase__ ,			lowerCamelCase__ ,			lowerCamelCase__				)  ->      float:
 lowerCamelCase_							:    List[Any]							=     from_type.lower().rstrip('s'				)
 lowerCamelCase_							:    Optional[Any]							=     TYPE_CONVERSION.get(lowerCamelCase__ ,			lowerCamelCase__				)
 lowerCamelCase_							:    List[Any]							=     to_type.lower().rstrip('s'				)
 lowerCamelCase_							:    Optional[int]							=     TYPE_CONVERSION.get(lowerCamelCase__ ,			lowerCamelCase__				)
 if new_from not in METRIC_CONVERSION:
  lowerCamelCase_							:    List[Any]							=     (
      F'Invalid \'from_type\' value: {from_type!r}.\n'
      F'Conversion abbreviations are: {", ".join(lowerCamelCase__				)}'
  )
  raise ValueError(lowerCamelCase__				)
 if new_to not in METRIC_CONVERSION:
  lowerCamelCase_							:    List[str]							=     (
      F'Invalid \'to_type\' value: {to_type!r}.\n'
      F'Conversion abbreviations are: {", ".join(lowerCamelCase__				)}'
  )
  raise ValueError(lowerCamelCase__				)
 return value * METRIC_CONVERSION[new_from].from_ * METRIC_CONVERSION[new_to].to


if __name__ == "__main__":
       import doctest

       doctest.testmod()
