


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





     def __init__(self		,					UpperCAmelCase		,					UpperCAmelCase=1_3		,					UpperCAmelCase=3_2		,					UpperCAmelCase=3		,					UpperCAmelCase=4		,					UpperCAmelCase=[1_0, 2_0, 3_0, 4_0]		,					UpperCAmelCase=[2, 2, 3, 2]		,					UpperCAmelCase=True		,					UpperCAmelCase=True		,					UpperCAmelCase=3_7		,					UpperCAmelCase="gelu"		,					UpperCAmelCase=1_0		,					UpperCAmelCase=0.02		,					UpperCAmelCase=3		,					UpperCAmelCase=None		,					)					->       Optional[int]:
      _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	)					->       str:
      _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	)					->       Optional[Any]:
      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=lowercase_		,					initializer_range=self.initializer_range		,					)





     def 					__A (self		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase	)					->       Tuple:
      _lowercase											=TFConvNextModel(config=lowercase_	)
      _lowercase											=model(lowercase_		,					training=lowercase_	)
      # 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		,					UpperCAmelCase		,					UpperCAmelCase		,					UpperCAmelCase	)					->       List[Any]:
      _lowercase											=self.type_sequence_label_size
      _lowercase											=TFConvNextForImageClassification(lowercase_	)
      _lowercase											=model(lowercase_		,					labels=lowercase_		,					training=lowercase_	)
      self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)	)





     def 					__A (self	)					->       Any:
      _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__       (	lowerCamelCase__       ,							lowerCamelCase__       ,							unittest.TestCase):
     SCREAMING_SNAKE_CASE__				      =      (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE__				      =      (
         {'feature-extraction': TFConvNextModel, 'image-classification': TFConvNextForImageClassification}
         if is_tf_available()
         else {}
     )

     SCREAMING_SNAKE_CASE__				      =      False
     SCREAMING_SNAKE_CASE__				      =      False
     SCREAMING_SNAKE_CASE__				      =      False
     SCREAMING_SNAKE_CASE__				      =      False
     SCREAMING_SNAKE_CASE__				      =      False





     def 					__A (self	)					->       Optional[int]:
      _lowercase											=TFConvNextModelTester(self	)
      _lowercase											=ConfigTester(
          self		,					config_class=lowercase_		,					has_text_modality=lowercase_		,					hidden_size=3_7		,					)





     @unittest.skip(reason='''ConvNext does not use inputs_embeds'''	)
     def 					__A (self	)					->       Dict:
      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	)					->       Optional[Any]:
      super().test_keras_fit()





     @unittest.skip(reason='''ConvNext does not support input and output embeddings'''	)
     def 					__A (self	)					->       Dict:
      pass





     def 					__A (self	)					->       Optional[Any]:
      _lowercase				,   _lowercase											=self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
       _lowercase											=model_class(lowercase_	)
       _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]		,					lowercase_	)





     def 					__A (self	)					->       int:
      _lowercase											=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowercase_	)





     @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	)					->       str:
      super().test_dataset_conversion()





     def 					__A (self	)					->       Union[str, Any]:






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

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

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

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

       check_hidden_states_output(lowercase_		,					lowercase_		,					lowercase_	)





     def 					__A (self	)					->       Optional[Any]:
      _lowercase				,   _lowercase											=self.model_tester.prepare_config_and_inputs_for_common()

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

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

        recursive_check(lowercase_		,					lowercase_	)

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

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

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

       _lowercase											=self._prepare_for_class(lowercase_		,					lowercase_	)
       _lowercase											=self._prepare_for_class(lowercase_		,					lowercase_	)
       check_equivalence(lowercase_		,					lowercase_		,					lowercase_		,					{'''output_hidden_states''': True}	)

       _lowercase											=self._prepare_for_class(lowercase_		,					lowercase_		,					return_labels=lowercase_	)
       _lowercase											=self._prepare_for_class(lowercase_		,					lowercase_		,					return_labels=lowercase_	)
       check_equivalence(lowercase_		,					lowercase_		,					lowercase_		,					{'''output_hidden_states''': True}	)





     def 					__A (self	)					->       int:
      _lowercase											=self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*lowercase_	)





     @slow
     def 					__A (self	)					->       str:
      _lowercase											=TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''	)
      self.assertIsNotNone(lowercase_	)



def     UpperCAmelCase_ (							)					->      Dict:







 """simple docstring"""


 _lowercase											=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
 return image







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





     @cached_property
     def 					__A (self	)					->       Any:
      return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''	) if is_vision_available() else None





     @slow
     def 					__A (self	)					->       int:
      _lowercase											=TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''	)

      _lowercase											=self.default_image_processor
      _lowercase											=prepare_img()
      _lowercase											=image_processor(images=lowercase_		,					return_tensors='''tf'''	)

      # forward pass
      _lowercase											=model(**lowercase_	)

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

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

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





def     UpperCAmelCase_ (							__snake_case						)					->      str:







 """simple docstring"""


 return " ".join(sorted(set(sentence.split()						)						)						)


if __name__ == "__main__":
  import doctest

  doctest.testmod()

