


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


							"""simple docstring"""

							def __init__(  self						,       UpperCAmelCase						,       UpperCAmelCase=13						,       UpperCAmelCase=32						,       UpperCAmelCase=3						,       UpperCAmelCase=4						,       UpperCAmelCase=[10, 20, 30, 40]						,       UpperCAmelCase=[2, 2, 3, 2]						,       UpperCAmelCase=True						,       UpperCAmelCase=True						,       UpperCAmelCase=37						,       UpperCAmelCase="gelu"						,       UpperCAmelCase=10						,       UpperCAmelCase=0.02						,       UpperCAmelCase=3						,       UpperCAmelCase=None						,       )     ->       Optional[Any]:






								'''simple docstring'''






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




							def 				A__      (  self  )     ->       List[Any]:






								'''simple docstring'''






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

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

								lowercase_			 = self.get_config()

								return config, pixel_values, labels




							def 				A__      (  self  )     ->       int:






								'''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=_lowerCAmelCase						,       initializer_range=self.initializer_range						,       )




							def 				A__      (  self						,       UpperCAmelCase						,       UpperCAmelCase						,       UpperCAmelCase  )     ->       Optional[Any]:






								'''simple docstring'''






								lowercase_			 = TFConvNextModel(config=_lowerCAmelCase  )
								lowercase_			 = model(_lowerCAmelCase						,       training=_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 				A__      (  self						,       UpperCAmelCase						,       UpperCAmelCase						,       UpperCAmelCase  )     ->       int:






								'''simple docstring'''






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




							def 				A__      (  self  )     ->       List[Any]:






								'''simple docstring'''






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







@require_tf
class     __lowerCamelCase     (  snake_case_							,   snake_case_							,   unittest.TestCase     ):


							"""simple docstring"""

							lowerCAmelCase__          =				(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
							lowerCAmelCase__          =				(
							    {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
							    if is_tf_available()
							    else {}
							)

							lowerCAmelCase__          =				False
							lowerCAmelCase__          =				False
							lowerCAmelCase__          =				False
							lowerCAmelCase__          =				False
							lowerCAmelCase__          =				False




							def 				A__      (  self  )     ->       List[Any]:






								'''simple docstring'''






								lowercase_			 = TFConvNextModelTester(self  )
								lowercase_			 = ConfigTester(
								    self						,       config_class=_lowerCAmelCase						,       has_text_modality=_lowerCAmelCase						,       hidden_size=37						,       )




							@unittest.skip(reason="ConvNext does not use inputs_embeds"  )
							def 				A__      (  self  )     ->       Optional[Any]:






								'''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 				A__      (  self  )     ->       List[Any]:






								'''simple docstring'''






								super().test_keras_fit()




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






								'''simple docstring'''






								pass




							def 				A__      (  self  )     ->       Optional[int]:






								'''simple docstring'''






								lowercase_ ,	lowercase_			 = self.model_tester.prepare_config_and_inputs_for_common()

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

									lowercase_			 = ["pixel_values"]
									self.assertListEqual(arg_names[:1]						,       _lowerCAmelCase  )




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






								'''simple docstring'''






								lowercase_			 = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_lowerCAmelCase  )




							@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 				A__      (  self  )     ->       Any:






								'''simple docstring'''






								super().test_dataset_conversion()




							def 				A__      (  self  )     ->       List[Any]:






								'''simple docstring'''






								def check_hidden_states_output(UpperCAmelCase						,       UpperCAmelCase						,       UpperCAmelCase  ):
									lowercase_			 = model_class(_lowerCAmelCase  )

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

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

								lowercase_ ,	lowercase_			 = self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									lowercase_			 = True
									check_hidden_states_output(_lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase  )

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

									check_hidden_states_output(_lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase  )




							def 				A__      (  self  )     ->       Tuple:






								'''simple docstring'''






								lowercase_ ,	lowercase_			 = self.model_tester.prepare_config_and_inputs_for_common()

								def check_equivalence(UpperCAmelCase						,       UpperCAmelCase						,       UpperCAmelCase						,       UpperCAmelCase={}  ):
									lowercase_			 = model(_lowerCAmelCase						,       return_dict=_lowerCAmelCase						,       **_lowerCAmelCase  )
									lowercase_			 = model(_lowerCAmelCase						,       return_dict=_lowerCAmelCase						,       **_lowerCAmelCase  ).to_tuple()

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

										recursive_check(_lowerCAmelCase						,       _lowerCAmelCase  )

								for model_class in self.all_model_classes:
									lowercase_			 = model_class(_lowerCAmelCase  )

									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase  )
									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase  )
									check_equivalence(_lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase  )

									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase						,       return_labels=_lowerCAmelCase  )
									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase						,       return_labels=_lowerCAmelCase  )
									check_equivalence(_lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase  )

									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase  )
									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase  )
									check_equivalence(_lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase						,       {"output_hidden_states": True}  )

									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase						,       return_labels=_lowerCAmelCase  )
									lowercase_			 = self._prepare_for_class(_lowerCAmelCase						,       _lowerCAmelCase						,       return_labels=_lowerCAmelCase  )
									check_equivalence(_lowerCAmelCase						,       _lowerCAmelCase						,       _lowerCAmelCase						,       {"output_hidden_states": True}  )




							def 				A__      (  self  )     ->       Optional[int]:






								'''simple docstring'''






								lowercase_			 = self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase  )




							@slow
							def 				A__      (  self  )     ->       Optional[int]:






								'''simple docstring'''






								lowercase_			 = TFConvNextModel.from_pretrained("facebook/convnext-tiny-224"  )
								self.assertIsNotNone(_lowerCAmelCase  )







def SCREAMING_SNAKE_CASE_  (				):







	'''simple docstring'''



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







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


							"""simple docstring"""

							@cached_property
							def 				A__      (  self  )     ->       Any:






								'''simple docstring'''






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




							@slow
							def 				A__      (  self  )     ->       Optional[int]:






								'''simple docstring'''






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

								lowercase_			 = self.default_image_processor
								lowercase_			 = prepare_img()
								lowercase_			 = image_processor(images=_lowerCAmelCase						,       return_tensors="tf"  )

								# forward pass
								lowercase_			 = model(**_lowerCAmelCase  )

								# verify the logits
								lowercase_			 = tf.TensorShape((1, 1000)  )
								self.assertEqual(outputs.logits.shape						,       _lowerCAmelCase  )

								lowercase_			 = tf.constant([-0.0260, -0.4739, 0.1911]  )

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



import abc
import copy
import dataclasses
from dataclasses import dataclass
from typing import ClassVar, Dict, Type, TypeVar

from ..features import Features


_UpperCamelCase:					List[Any]     =TypeVar('T', bound='TaskTemplate')





@dataclass(frozen=SCREAMING_SNAKE_CASE   )
class 						__lowercase(     abc.ABC   ):


       """simple docstring"""







       UpperCamelCase_				 =							42
       UpperCamelCase_				 =							42
       UpperCamelCase_				 =							42



       def SCREAMING_SNAKE_CASE_				(     self					:			T  ,      _lowerCAmelCase					:			Features       )					->   T:
         return copy.deepcopy(self       )



       @property
       def SCREAMING_SNAKE_CASE_				(     self					:			str       )					->   Features:
         return Features(**self.input_schema  ,      **self.label_schema       )



       @property
       @abc.abstractmethod
       def SCREAMING_SNAKE_CASE_				(     self					:			Dict       )					->   Dict[str, str]:
         raise NotImplementedError






       @classmethod
       def SCREAMING_SNAKE_CASE_				(     cls					:			Type[T]  ,      _lowerCAmelCase					:			dict       )					->   T:
         _lowerCAmelCase						=		{f.name for f in dataclasses.fields(cls       )}
         return cls(**{k: v for k, v in template_dict.items() if k in field_names}       )
