




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     :
     """simple docstring"""

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




     def 	__snake_case				(      self					:				Optional[int]		,					A__					:				Union[str, Any]		,					A__					:				List[str]		,					A__					:				List[Any]     )			->    Optional[Any]:
           lowerCamelCase__ 					=			TFConvNextModel(config=A__     )
           lowerCamelCase__ 					=			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 // 3_2, self.image_size // 3_2)		,					)




     def 	__snake_case				(      self					:				Optional[int]		,					A__					:				Union[str, Any]		,					A__					:				Any		,					A__					:				str     )			->    int:
           lowerCamelCase__ 					=			self.type_sequence_label_size
           lowerCamelCase__ 					=			TFConvNextForImageClassification(A__     )
           lowerCamelCase__ 					=			model(A__		,					labels=A__		,					training=A__     )
           self.parent.assertEqual(result.logits.shape		,					(self.batch_size, self.type_sequence_label_size)     )




     def 	__snake_case				(      self					:				Optional[int]     )			->    List[str]:
           lowerCamelCase__ 					=			self.prepare_config_and_inputs()
           lowerCamelCase__					,						lowerCamelCase__					,						lowerCamelCase__ 					=			config_and_inputs
           lowerCamelCase__ 					=			{'pixel_values': pixel_values}
           return config, inputs_dict






@require_tf
class      A     (						_lowerCAmelCase     ,  _lowerCAmelCase     ,  unittest.TestCase						):
     """simple docstring"""

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

     _snake_case:		Dict       =False
     _snake_case:		Optional[Any]       =False
     _snake_case:		Any       =False
     _snake_case:		Any       =False
     _snake_case:		Any       =False




     def 	__snake_case				(      self					:				str     )			->    str:
           lowerCamelCase__ 					=			TFConvNextModelTester(self     )
           lowerCamelCase__ 					=			ConfigTester(
               self		,					config_class=A__		,					has_text_modality=A__		,					hidden_size=3_7		,					)




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




     @unittest.skip(reason='ConvNext does not support input and output embeddings'     )
     def 	__snake_case				(      self					:				Any     )			->    List[str]:
           pass




     def 	__snake_case				(      self					:				int     )			->    str:
           lowerCamelCase__					,						lowerCamelCase__ 					=			self.model_tester.prepare_config_and_inputs_for_common()

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




     def 	__snake_case				(      self					:				Dict     )			->    Optional[Any]:
           lowerCamelCase__ 					=			self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*A__     )




     @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 	__snake_case				(      self					:				Union[str, Any]     )			->    Optional[Any]:
           super().test_dataset_conversion()




     def 	__snake_case				(      self					:				int     )			->    Optional[int]:
           def check_hidden_states_output(A__					:				List[Any]		,					A__					:				Any		,					A__					:				Optional[int]     ):
                 lowerCamelCase__ 					=			model_class(A__     )

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

                 lowerCamelCase__ 					=			self.model_tester.num_stages
                 self.assertEqual(len(A__     )		,					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__					,						lowerCamelCase__ 					=			self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 lowerCamelCase__ 					=			True
                 check_hidden_states_output(A__		,					A__		,					A__     )

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

                 check_hidden_states_output(A__		,					A__		,					A__     )




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

           def check_equivalence(A__					:				str		,					A__					:				Union[str, Any]		,					A__					:				str		,					A__					:				Optional[int]={}     ):
                 lowerCamelCase__ 					=			model(A__		,					return_dict=A__		,					**A__     )
                 lowerCamelCase__ 					=			model(A__		,					return_dict=A__		,					**A__     ).to_tuple()

                 def recursive_check(A__					:				Any		,					A__					:				Tuple     ):
                       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__ 					=			model_class(A__     )

                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__     )
                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__     )
                 check_equivalence(A__		,					A__		,					A__     )

                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__		,					return_labels=A__     )
                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__		,					return_labels=A__     )
                 check_equivalence(A__		,					A__		,					A__     )

                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__     )
                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__     )
                 check_equivalence(A__		,					A__		,					A__		,					{'output_hidden_states': True}     )

                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__		,					return_labels=A__     )
                 lowerCamelCase__ 					=			self._prepare_for_class(A__		,					A__		,					return_labels=A__     )
                 check_equivalence(A__		,					A__		,					A__		,					{'output_hidden_states': True}     )




     def 	__snake_case				(      self					:				Union[str, Any]     )			->    str:
           lowerCamelCase__ 					=			self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*A__     )




     @slow
     def 	__snake_case				(      self					:				Any     )			->    Union[str, Any]:
           lowerCamelCase__ 					=			TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'     )
           self.assertIsNotNone(A__     )

def      lowerCAmelCase_     (					)   ->     str:


      '''simple docstring'''




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






@require_tf
@require_vision
class      A     (						unittest.TestCase						):
     """simple docstring"""

     @cached_property
     def 	__snake_case				(      self					:				Optional[int]     )			->    int:
           return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'     ) if is_vision_available() else None




     @slow
     def 	__snake_case				(      self					:				Tuple     )			->    List[str]:
           lowerCamelCase__ 					=			TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'     )

           lowerCamelCase__ 					=			self.default_image_processor
           lowerCamelCase__ 					=			prepare_img()
           lowerCamelCase__ 					=			image_processor(images=A__		,					return_tensors='tf'     )

           # forward pass
           lowerCamelCase__ 					=			model(**A__     )

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

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

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





from __future__ import annotations

def      lowerCAmelCase_     (					lowerCamelCase:    list[int | float]  )   ->     int | float:


      '''simple docstring'''




      if len(lowerCamelCase  ) == 0:
            raise ValueError('find_max() arg is an empty sequence'  )
      lowerCamelCase__ 					=			nums[0]
      for x in nums:
            if x > max_num:
                  lowerCamelCase__ 					=			x
      return max_num


if __name__ == "__main__":
      import doctest

      doctest.testmod(verbose=True)