


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						, ):
       snake_case_			= parent
       snake_case_			= batch_size
       snake_case_			= image_size
       snake_case_			= num_channels
       snake_case_			= num_stages
       snake_case_			= hidden_sizes
       snake_case_			= depths
       snake_case_			= is_training
       snake_case_			= use_labels
       snake_case_			= intermediate_size
       snake_case_			= hidden_act
       snake_case_			= type_sequence_label_size
       snake_case_			= initializer_range
       snake_case_			= scope



 def 		UpperCamelCase__	(      self   ):
       snake_case_			= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

       snake_case_			= self.get_config()

       return config, pixel_values, labels



 def 		UpperCamelCase__	(      self   ):
       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=_UpperCAmelCase						, initializer_range=self.initializer_range						, )



 def 		UpperCamelCase__	(      self						, _UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   ):
       snake_case_			= TFConvNextModel(config=_UpperCAmelCase   )
       snake_case_			= model(_UpperCAmelCase						, training=_UpperCAmelCase   )
       # 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 		UpperCamelCase__	(      self						, _UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   ):
       snake_case_			= self.type_sequence_label_size
       snake_case_			= TFConvNextForImageClassification(_UpperCAmelCase   )
       snake_case_			= model(_UpperCAmelCase						, labels=_UpperCAmelCase						, training=_UpperCAmelCase   )
       self.parent.assertEqual(result.logits.shape						, (self.batch_size, self.type_sequence_label_size)   )





 def 		UpperCamelCase__	(      self   ):
       snake_case_			= self.prepare_config_and_inputs()
       snake_case_			,       snake_case_			,       snake_case_			= config_and_inputs
       snake_case_			= {'''pixel_values''': pixel_values}
       return config, inputs_dict







@require_tf
class lowerCAmelCase_		(					lowerCamelCase__   ,		lowerCamelCase__   ,		unittest.TestCase			):

 '''simple docstring'''

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

 __snake_case				=    False
 __snake_case				=    False
 __snake_case				=    False
 __snake_case				=    False
 __snake_case				=    False



 def 		UpperCamelCase__	(      self   ):
       snake_case_			= TFConvNextModelTester(self   )
       snake_case_			= ConfigTester(
           self						, config_class=_UpperCAmelCase						, has_text_modality=_UpperCAmelCase						, hidden_size=37						, )



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



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



 def 		UpperCamelCase__	(      self   ):
       snake_case_			,       snake_case_			= self.model_tester.prepare_config_and_inputs_for_common()

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

             snake_case_			= ['''pixel_values''']
             self.assertListEqual(arg_names[:1]						, _UpperCAmelCase   )



 def 		UpperCamelCase__	(      self   ):
       snake_case_			= self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase   )



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



 def 		UpperCamelCase__	(      self   ):
       def check_hidden_states_output(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   ):
             snake_case_			= model_class(_UpperCAmelCase   )

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

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

       snake_case_			,       snake_case_			= self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             snake_case_			= True
             check_hidden_states_output(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   )

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

             check_hidden_states_output(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   )



 def 		UpperCamelCase__	(      self   ):
       snake_case_			,       snake_case_			= self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase={}   ):
             snake_case_			= model(_UpperCAmelCase						, return_dict=_UpperCAmelCase						, **_UpperCAmelCase   )
             snake_case_			= model(_UpperCAmelCase						, return_dict=_UpperCAmelCase						, **_UpperCAmelCase   ).to_tuple()

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

                   recursive_check(_UpperCAmelCase						, _UpperCAmelCase   )

       for model_class in self.all_model_classes:
             snake_case_			= model_class(_UpperCAmelCase   )

             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase   )
             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase   )
             check_equivalence(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   )

             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase						, return_labels=_UpperCAmelCase   )
             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase						, return_labels=_UpperCAmelCase   )
             check_equivalence(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase   )

             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase   )
             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase   )
             check_equivalence(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase						, {'''output_hidden_states''': True}   )

             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase						, return_labels=_UpperCAmelCase   )
             snake_case_			= self._prepare_for_class(_UpperCAmelCase						, _UpperCAmelCase						, return_labels=_UpperCAmelCase   )
             check_equivalence(_UpperCAmelCase						, _UpperCAmelCase						, _UpperCAmelCase						, {'''output_hidden_states''': True}   )



 def 		UpperCamelCase__	(      self   ):
       snake_case_			= self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase   )





 @slow
 def 		UpperCamelCase__	(      self   ):
       snake_case_			= TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''   )
       self.assertIsNotNone(_UpperCAmelCase   )






def 			__lowerCAmelCase       ()->    int:




      """simple docstring"""

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







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

 '''simple docstring'''

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





 @slow
 def 		UpperCamelCase__	(      self   ):
       snake_case_			= TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''   )

       snake_case_			= self.default_image_processor
       snake_case_			= prepare_img()
       snake_case_			= image_processor(images=_UpperCAmelCase						, return_tensors='''tf'''   )

       # forward pass
       snake_case_			= model(**_UpperCAmelCase   )

       # verify the logits
       snake_case_			= tf.TensorShape((1, 10_00)   )
       self.assertEqual(outputs.logits.shape						, _UpperCAmelCase   )

       snake_case_			= tf.constant([-0.0_260, -0.4_739, 0.1_911]   )

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



from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available






def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   )->    Union[str, Any]:




      """simple docstring"""

      if is_torch_available():
            import torch

            if isinstance(SCREAMING_SNAKE_CASE   ,   torch.Tensor   ):
                  return True

      return isinstance(SCREAMING_SNAKE_CASE   ,   np.ndarray   )







class lowerCAmelCase_		(					lowerCamelCase__			):

 '''simple docstring'''

 def 		UpperCamelCase__	(      self   ):
       snake_case_			= fields(self   )

       # Safety and consistency checks
       if not len(_UpperCAmelCase   ):
             raise ValueError(F'''{self.__class__.__name__} has no fields.'''   )

       snake_case_			= getattr(self						, class_fields[0].name   )
       snake_case_			= all(getattr(self						, field.name   ) is None for field in class_fields[1:]   )

       if other_fields_are_none and isinstance(_UpperCAmelCase						, _UpperCAmelCase   ):
             for key, value in first_field.items():
                   snake_case_			= value
       else:
             for field in class_fields:
                   snake_case_			= getattr(self						, field.name   )
                   if v is not None:
                         snake_case_			= v



 def __delitem__(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''   )



 def __getitem__(      self						, _UpperCAmelCase   ):
       if isinstance(_UpperCAmelCase						, _UpperCAmelCase   ):
             snake_case_			= dict(self.items()   )
             return inner_dict[k]
       else:
             return self.to_tuple()[k]



 def __setattr__(      self						, _UpperCAmelCase						, _UpperCAmelCase   ):
       if name in self.keys() and value is not None:
             # Don't call self.__setitem__ to avoid recursion errors
             super().__setitem__(_UpperCAmelCase						, _UpperCAmelCase   )
       super().__setattr__(_UpperCAmelCase						, _UpperCAmelCase   )



 def __setitem__(      self						, _UpperCAmelCase						, _UpperCAmelCase   ):
       # Will raise a KeyException if needed
       super().__setitem__(_UpperCAmelCase						, _UpperCAmelCase   )
       # Don't call self.__setattr__ to avoid recursion errors
       super().__setattr__(_UpperCAmelCase						, _UpperCAmelCase   )





 def 		UpperCamelCase__	(      self   ):
       return tuple(self[k] for k in self.keys()   )