



"""simple docstring"""




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   :				Dict,  lowerCAmelCase   :				Optional[Any],  lowerCAmelCase   :				Union[str, Any]=13,  lowerCAmelCase   :				str=32,  lowerCAmelCase   :				Union[str, Any]=3,  lowerCAmelCase   :				Dict=4,  lowerCAmelCase   :				List[str]=[10, 20, 30, 40],  lowerCAmelCase   :				Dict=[2, 2, 3, 2],  lowerCAmelCase   :				Dict=True,  lowerCAmelCase   :				Any=True,  lowerCAmelCase   :				Union[str, Any]=37,  lowerCAmelCase   :				Union[str, Any]="gelu",  lowerCAmelCase   :				Any=10,  lowerCAmelCase   :				Dict=0.02,  lowerCAmelCase   :				List[str]=3,  lowerCAmelCase   :				Optional[Any]=None,  )     ->							Optional[int]:
         lowercase	:   Optional[int]											= parent
         lowercase	:   str											= batch_size
         lowercase	:   Optional[int]											= image_size
         lowercase	:   Tuple											= num_channels
         lowercase	:   Union[str, Any]											= num_stages
         lowercase	:   Optional[int]											= hidden_sizes
         lowercase	:   Optional[int]											= depths
         lowercase	:   Union[str, Any]											= is_training
         lowercase	:   Union[str, Any]											= use_labels
         lowercase	:   int											= intermediate_size
         lowercase	:   Union[str, Any]											= hidden_act
         lowercase	:   Dict											= type_sequence_label_size
         lowercase	:   Dict											= initializer_range
         lowercase	:   Optional[int]											= scope


   def 							lowercase					(				self   :				str      )     ->							Tuple:
         lowercase	:   Any											= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

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

         return config, pixel_values, labels


   def 							lowercase					(				self   :				List[str]      )     ->							Optional[int]:
         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 							lowercase					(				self   :				Any,  lowerCAmelCase   :				Tuple,  lowerCAmelCase   :				str,  lowerCAmelCase   :				int      )     ->							Union[str, Any]:
         lowercase	:   int											= TFConvNextModel(config=lowerCAmelCase      )
         lowercase	:   int											= 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 							lowercase					(				self   :				Dict,  lowerCAmelCase   :				str,  lowerCAmelCase   :				Optional[int],  lowerCAmelCase   :				Any      )     ->							Optional[Any]:
         lowercase	:   Dict											= self.type_sequence_label_size
         lowercase	:   Any											= TFConvNextForImageClassification(lowerCAmelCase      )
         lowercase	:   List[str]											= model(lowerCAmelCase,  labels=lowerCAmelCase,  training=lowerCAmelCase      )
         self.parent.assertEqual(result.logits.shape,  (self.batch_size, self.type_sequence_label_size)      )






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




@require_tf
class 	a__		(    SCREAMING_SNAKE_CASE__,	SCREAMING_SNAKE_CASE__,	unittest.TestCase  ):
   _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 							lowercase					(				self   :				Optional[int]      )     ->							int:
         lowercase	:   str											= TFConvNextModelTester(self      )
         lowercase	:   int											= ConfigTester(
             self,  config_class=lowerCAmelCase,  has_text_modality=lowerCAmelCase,  hidden_size=37,  )


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


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


   def 							lowercase					(				self   :				Union[str, Any]      )     ->							List[Any]:
         lowercase						,     lowercase	:   Dict											= self.model_tester.prepare_config_and_inputs_for_common()

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

               lowercase	:   Optional[Any]											= ['pixel_values']
               self.assertListEqual(arg_names[:1],  lowerCAmelCase      )


   def 							lowercase					(				self   :				List[Any]      )     ->							List[Any]:
         lowercase	:   str											= 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 							lowercase					(				self   :				int      )     ->							List[Any]:
         super().test_dataset_conversion()


   def 							lowercase					(				self   :				Any      )     ->							Dict:
         def check_hidden_states_output(lowerCAmelCase   :				Dict,  lowerCAmelCase   :				Dict,  lowerCAmelCase   :				Optional[int]      ):
               lowercase	:   Any											= model_class(lowerCAmelCase      )

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

               lowercase	:   Any											= 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	:   Optional[Any]											= self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
               lowercase	:   Optional[Any]											= True
               check_hidden_states_output(lowerCAmelCase,  lowerCAmelCase,  lowerCAmelCase      )

               # check that output_hidden_states also work using config
               del inputs_dict["output_hidden_states"]
               lowercase	:   Dict											= True

               check_hidden_states_output(lowerCAmelCase,  lowerCAmelCase,  lowerCAmelCase      )


   def 							lowercase					(				self   :				Dict      )     ->							List[Any]:
         lowercase						,     lowercase	:   int											= self.model_tester.prepare_config_and_inputs_for_common()

         def check_equivalence(lowerCAmelCase   :				Optional[int],  lowerCAmelCase   :				List[Any],  lowerCAmelCase   :				Union[str, Any],  lowerCAmelCase   :				Any={}      ):
               lowercase	:   Dict											= model(lowerCAmelCase,  return_dict=lowerCAmelCase,  **lowerCAmelCase      )
               lowercase	:   List[str]											= model(lowerCAmelCase,  return_dict=lowerCAmelCase,  **lowerCAmelCase      ).to_tuple()

               def recursive_check(lowerCAmelCase   :				Optional[int],  lowerCAmelCase   :				Tuple      ):
                     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	:   List[Any]											= model_class(lowerCAmelCase      )

               lowercase	:   Optional[Any]											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase      )
               lowercase	:   Any											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase      )
               check_equivalence(lowerCAmelCase,  lowerCAmelCase,  lowerCAmelCase      )

               lowercase	:   List[str]											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase,  return_labels=lowerCAmelCase      )
               lowercase	:   Optional[Any]											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase,  return_labels=lowerCAmelCase      )
               check_equivalence(lowerCAmelCase,  lowerCAmelCase,  lowerCAmelCase      )

               lowercase	:   Optional[int]											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase      )
               lowercase	:   int											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase      )
               check_equivalence(lowerCAmelCase,  lowerCAmelCase,  lowerCAmelCase,  {'output_hidden_states': True}      )

               lowercase	:   Tuple											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase,  return_labels=lowerCAmelCase      )
               lowercase	:   int											= self._prepare_for_class(lowerCAmelCase,  lowerCAmelCase,  return_labels=lowerCAmelCase      )
               check_equivalence(lowerCAmelCase,  lowerCAmelCase,  lowerCAmelCase,  {'output_hidden_states': True}      )


   def 							lowercase					(				self   :				Tuple      )     ->							str:
         lowercase	:   List[Any]											= self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase      )






   @slow
   def 							lowercase					(				self   :				Union[str, Any]      )     ->							Dict:
         lowercase	:   int											= TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'      )
         self.assertIsNotNone(lowerCAmelCase      )




def 	lowercase__  (      )  ->      Dict:






      '''simple docstring'''


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





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


   @cached_property
   def 							lowercase					(				self   :				Union[str, Any]      )     ->							Union[str, Any]:
         return ConvNextImageProcessor.from_pretrained('facebook/convnext-tiny-224'      ) if is_vision_available() else None






   @slow
   def 							lowercase					(				self   :				int      )     ->							Tuple:
         lowercase	:   Optional[int]											= TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'      )

         lowercase	:   Union[str, Any]											= self.default_image_processor
         lowercase	:   List[str]											= prepare_img()
         lowercase	:   List[Any]											= image_processor(images=lowerCAmelCase,  return_tensors='tf'      )

         # forward pass
         lowercase	:   Any											= model(**lowerCAmelCase      )

         # verify the logits
         lowercase	:   List[str]											= tf.TensorShape((1, 1000)      )
         self.assertEqual(outputs.logits.shape,  lowerCAmelCase      )

         lowercase	:   List[Any]											= tf.constant([-0.0260, -0.4739, 0.1911]      )

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





"""simple docstring"""




from __future__ import annotations


def 	lowercase__  (      _UpperCAmelCase					)  ->      list[int]:






      '''simple docstring'''


      lowercase	:   Optional[Any]											= [0] * max_one

      for i in range(0						,   _UpperCAmelCase					):
            lowercase	:   List[Any]											= i

      for i in range(2						,   _UpperCAmelCase					):
            if totients[i] == i:
                  for j in range(_UpperCAmelCase						,   _UpperCAmelCase						,   _UpperCAmelCase					):
                        totients[j] -= totients[j] // i

      return totients


def 	lowercase__  (      _UpperCAmelCase						,   _UpperCAmelCase					)  ->      bool:






      '''simple docstring'''


      return sorted(str(_UpperCAmelCase					)					) == sorted(str(_UpperCAmelCase					)					)


def 	lowercase__  (      _UpperCAmelCase = 10_00_00_00					)  ->      int:






      '''simple docstring'''


      lowercase	:   Union[str, Any]											= 1  # i
      lowercase	:   Any											= 0  # φ(i)
      lowercase	:   int											= get_totients(max_n + 1					)

      for i in range(2						,   max_n + 1					):
            lowercase	:   Any											= totients[i]

            if i * min_denominator < min_numerator * t and has_same_digits(_UpperCAmelCase						,   _UpperCAmelCase					):
                  lowercase	:   List[Any]											= i
                  lowercase	:   Optional[Any]											= t

      return min_numerator


if __name__ == "__main__":
     print(f'''{solution() = }''')
