


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  UpperCAmelCase_						:
       '''simple docstring'''






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




              """simple docstring"""




              UpperCamelCase     :						Union[str, Any] 						=		parent
              UpperCamelCase     :						Union[str, Any] 						=		batch_size
              UpperCamelCase     :						List[Any] 						=		image_size
              UpperCamelCase     :						List[str] 						=		num_channels
              UpperCamelCase     :						Optional[Any] 						=		num_stages
              UpperCamelCase     :						Any 						=		hidden_sizes
              UpperCamelCase     :						str 						=		depths
              UpperCamelCase     :						Optional[Any] 						=		is_training
              UpperCamelCase     :						Optional[Any] 						=		use_labels
              UpperCamelCase     :						str 						=		intermediate_size
              UpperCamelCase     :						Tuple 						=		hidden_act
              UpperCamelCase     :						Union[str, Any] 						=		type_sequence_label_size
              UpperCamelCase     :						List[str] 						=		initializer_range
              UpperCamelCase     :						str 						=		scope






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						List[Any] 						=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

              UpperCamelCase     :						Optional[Any] 						=		self.get_config()

              return config, pixel_values, labels






       def 			_lowercase (  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=__SCREAMING_SNAKE_CASE			,       initializer_range=self.initializer_range			,       )






       def 			_lowercase (  self			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    ):




              """simple docstring"""




              UpperCamelCase     :						List[str] 						=		TFConvNextModel(config=__SCREAMING_SNAKE_CASE    )
              UpperCamelCase     :						List[Any] 						=		model(__SCREAMING_SNAKE_CASE			,       training=__SCREAMING_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 // 32, self.image_size // 32)			,       )






       def 			_lowercase (  self			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    ):




              """simple docstring"""




              UpperCamelCase     :						Dict 						=		self.type_sequence_label_size
              UpperCamelCase     :						List[str] 						=		TFConvNextForImageClassification(__SCREAMING_SNAKE_CASE    )
              UpperCamelCase     :						List[Any] 						=		model(__SCREAMING_SNAKE_CASE			,       labels=__SCREAMING_SNAKE_CASE			,       training=__SCREAMING_SNAKE_CASE    )
              self.parent.assertEqual(result.logits.shape			,       (self.batch_size, self.type_sequence_label_size)    )






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						Optional[Any] 						=		self.prepare_config_and_inputs()
              UpperCamelCase						,			UpperCamelCase						,			UpperCamelCase     :						List[str] 						=		config_and_inputs
              UpperCamelCase     :						List[Any] 						=		{'''pixel_values''': pixel_values}
              return config, inputs_dict




@require_tf
class  UpperCAmelCase_						(				_a,  _a,  unittest.TestCase):
       '''simple docstring'''
       __UpperCamelCase   :  int				=       (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
       __UpperCamelCase   :  List[Any]				=       (
           {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
           if is_tf_available()
           else {}
       )

       __UpperCamelCase   :  List[Any]				=       False
       __UpperCamelCase   :  List[str]				=       False
       __UpperCamelCase   :  str				=       False
       __UpperCamelCase   :  Dict				=       False
       __UpperCamelCase   :  int				=       False






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						Optional[Any] 						=		TFConvNextModelTester(self    )
              UpperCamelCase     :						Tuple 						=		ConfigTester(
                  self			,       config_class=__SCREAMING_SNAKE_CASE			,       has_text_modality=__SCREAMING_SNAKE_CASE			,       hidden_size=37			,       )






       @unittest.skip(reason='''ConvNext does not use inputs_embeds'''    )
       def 			_lowercase (  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 			_lowercase (  self    ):




              """simple docstring"""




              super().test_keras_fit()






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




              """simple docstring"""




              pass






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase						,			UpperCamelCase     :						Optional[Any] 						=		self.model_tester.prepare_config_and_inputs_for_common()

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

                     UpperCamelCase     :						str 						=		['''pixel_values''']
                     self.assertListEqual(arg_names[:1]			,       __SCREAMING_SNAKE_CASE    )






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						Dict 						=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*__SCREAMING_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 			_lowercase (  self    ):




              """simple docstring"""




              super().test_dataset_conversion()






       def 			_lowercase (  self    ):




              """simple docstring"""




              def check_hidden_states_output(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    ):
                     UpperCamelCase     :						Optional[Any] 						=		model_class(__SCREAMING_SNAKE_CASE    )

                     UpperCamelCase     :						List[Any] 						=		model(**self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )    )
                     UpperCamelCase     :						List[str] 						=		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                     UpperCamelCase     :						Union[str, Any] 						=		self.model_tester.num_stages
                     self.assertEqual(len(__SCREAMING_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]			,       )

              UpperCamelCase						,			UpperCamelCase     :						int 						=		self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     UpperCamelCase     :						Any 						=		True
                     check_hidden_states_output(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )

                     # check that output_hidden_states also work using config
                     del inputs_dict["output_hidden_states"]
                     UpperCamelCase     :						List[Any] 						=		True

                     check_hidden_states_output(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase						,			UpperCamelCase     :						Any 						=		self.model_tester.prepare_config_and_inputs_for_common()

              def check_equivalence(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE={}    ):
                     UpperCamelCase     :						Tuple 						=		model(__SCREAMING_SNAKE_CASE			,       return_dict=__SCREAMING_SNAKE_CASE			,       **__SCREAMING_SNAKE_CASE    )
                     UpperCamelCase     :						Dict 						=		model(__SCREAMING_SNAKE_CASE			,       return_dict=__SCREAMING_SNAKE_CASE			,       **__SCREAMING_SNAKE_CASE    ).to_tuple()

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

                            recursive_check(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )

              for model_class in self.all_model_classes:
                     UpperCamelCase     :						str 						=		model_class(__SCREAMING_SNAKE_CASE    )

                     UpperCamelCase     :						Dict 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )
                     UpperCamelCase     :						Dict 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )
                     check_equivalence(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )

                     UpperCamelCase     :						str 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       return_labels=__SCREAMING_SNAKE_CASE    )
                     UpperCamelCase     :						Dict 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       return_labels=__SCREAMING_SNAKE_CASE    )
                     check_equivalence(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )

                     UpperCamelCase     :						Any 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )
                     UpperCamelCase     :						List[Any] 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE    )
                     check_equivalence(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       {'''output_hidden_states''': True}    )

                     UpperCamelCase     :						str 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       return_labels=__SCREAMING_SNAKE_CASE    )
                     UpperCamelCase     :						Optional[int] 						=		self._prepare_for_class(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       return_labels=__SCREAMING_SNAKE_CASE    )
                     check_equivalence(__SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       __SCREAMING_SNAKE_CASE			,       {'''output_hidden_states''': True}    )






       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						Tuple 						=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE    )






       @slow
       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						Union[str, Any] 						=		TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''    )
              self.assertIsNotNone(__SCREAMING_SNAKE_CASE    )




def   a						(				):






       """simple docstring"""





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



@require_tf
@require_vision
class  UpperCAmelCase_						(				unittest.TestCase):
       '''simple docstring'''






       @cached_property
       def 			_lowercase (  self    ):




              """simple docstring"""




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






       @slow
       def 			_lowercase (  self    ):




              """simple docstring"""




              UpperCamelCase     :						Tuple 						=		TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''    )

              UpperCamelCase     :						Any 						=		self.default_image_processor
              UpperCamelCase     :						Any 						=		prepare_img()
              UpperCamelCase     :						List[str] 						=		image_processor(images=__SCREAMING_SNAKE_CASE			,       return_tensors='''tf'''    )

              # forward pass
              UpperCamelCase     :						Any 						=		model(**__SCREAMING_SNAKE_CASE    )

              # verify the logits
              UpperCamelCase     :						Dict 						=		tf.TensorShape((1, 1_000)    )
              self.assertEqual(outputs.logits.shape			,       __SCREAMING_SNAKE_CASE    )

              UpperCamelCase     :						Optional[Any] 						=		tf.constant([-0.0_260, -0.4_739, 0.1_911]    )

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





def   a						(				SCREAMING_SNAKE_CASE_   :		int							):






       """simple docstring"""





       UpperCamelCase     :						Tuple 						=		[True for i in range(n + 1							)]
       UpperCamelCase     :						Tuple 						=		[i - 1 for i in range(n + 1							)]
       UpperCamelCase     :						Optional[Any] 						=		[]
       for i in range(2				,      n + 1							):
              if is_prime[i]:
                     primes.append(SCREAMING_SNAKE_CASE_							)
              for j in range(0				,      len(SCREAMING_SNAKE_CASE_							)							):
                     if i * primes[j] >= n:
                            break
                     UpperCamelCase     :						Any 						=		False

                     if i % primes[j] == 0:
                            UpperCamelCase     :						int 						=		totients[i] * primes[j]
                            break

                     UpperCamelCase     :						Dict 						=		totients[i] * (primes[j] - 1)

       return totients


if __name__ == "__main__":
  import doctest

  doctest.testmod()

