






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







   """simple docstring"""



   def __init__(     self:						List[Any] ,							snake_case__:						Optional[int] ,							snake_case__:						Tuple=13 ,							snake_case__:						Tuple=32 ,							snake_case__:						List[Any]=3 ,							snake_case__:						Union[str, Any]=4 ,							snake_case__:						Tuple=[10, 20, 30, 40] ,							snake_case__:						Tuple=[2, 2, 3, 2] ,							snake_case__:						Optional[Any]=True ,							snake_case__:						Dict=True ,							snake_case__:						Optional[int]=37 ,							snake_case__:						List[Any]="gelu" ,							snake_case__:						int=10 ,							snake_case__:						Optional[int]=0.02 ,							snake_case__:						List[Any]=3 ,							snake_case__:						Union[str, Any]=None ,							)	->		int:


       """simple docstring"""



       _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       SCREAMING_SNAKE_CASE__					(     self:						Optional[int]						)	->		List[str]:


       """simple docstring"""



       _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       SCREAMING_SNAKE_CASE__					(     self:						List[str]						)	->		Optional[int]:


       """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=snake_case__ ,							initializer_range=self.initializer_range ,							)

   def       SCREAMING_SNAKE_CASE__					(     self:						Optional[int] ,							snake_case__:						List[Any] ,							snake_case__:						int ,							snake_case__:						Any						)	->		str:


       """simple docstring"""



       _lowercase     			=						TFConvNextModel(config=snake_case__						)
       _lowercase     			=						model(snake_case__ ,							training=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       SCREAMING_SNAKE_CASE__					(     self:						Dict ,							snake_case__:						int ,							snake_case__:						Union[str, Any] ,							snake_case__:						Optional[int]						)	->		int:


       """simple docstring"""



       _lowercase     			=						self.type_sequence_label_size
       _lowercase     			=						TFConvNextForImageClassification(snake_case__						)
       _lowercase     			=						model(snake_case__ ,							labels=snake_case__ ,							training=snake_case__						)
       self.parent.assertEqual(result.logits.shape ,							(self.batch_size, self.type_sequence_label_size)						)

   def       SCREAMING_SNAKE_CASE__					(     self:						Dict						)	->		Dict:


       """simple docstring"""



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






@require_tf
class        snake_case_				(							lowercase_   ,      lowercase_   ,      unittest.TestCase   ):







   """simple docstring"""



   __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       SCREAMING_SNAKE_CASE__					(     self:						str						)	->		Optional[int]:


       """simple docstring"""



       _lowercase     			=						TFConvNextModelTester(self						)
       _lowercase     			=						ConfigTester(
           self ,							config_class=snake_case__ ,							has_text_modality=snake_case__ ,							hidden_size=37 ,							)

   @unittest.skip(reason='ConvNext does not use inputs_embeds'						)
   def       SCREAMING_SNAKE_CASE__					(     self:						Tuple						)	->		Any:


       """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       SCREAMING_SNAKE_CASE__					(     self:						Optional[int]						)	->		Any:


       """simple docstring"""



       super().test_keras_fit()

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


       """simple docstring"""



       pass

   def       SCREAMING_SNAKE_CASE__					(     self:						List[str]						)	->		Optional[int]:


       """simple docstring"""



       _lowercase			,     _lowercase     			=						self.model_tester.prepare_config_and_inputs_for_common()

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

   def       SCREAMING_SNAKE_CASE__					(     self:						Optional[int]						)	->		Optional[Any]:


       """simple docstring"""



       _lowercase     			=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*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       SCREAMING_SNAKE_CASE__					(     self:						List[Any]						)	->		int:


       """simple docstring"""



       super().test_dataset_conversion()

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


       """simple docstring"""



       def check_hidden_states_output(snake_case__:						List[str] ,							snake_case__:						Optional[int] ,							snake_case__:						int						):
           _lowercase     			=						model_class(snake_case__						)

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

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

       _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(snake_case__ ,							snake_case__ ,							snake_case__						)

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

           check_hidden_states_output(snake_case__ ,							snake_case__ ,							snake_case__						)

   def       SCREAMING_SNAKE_CASE__					(     self:						Optional[int]						)	->		Optional[Any]:


       """simple docstring"""



       _lowercase			,     _lowercase     			=						self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(snake_case__:						int ,							snake_case__:						List[str] ,							snake_case__:						List[str] ,							snake_case__:						Any={}						):
           _lowercase     			=						model(snake_case__ ,							return_dict=snake_case__ ,							**snake_case__						)
           _lowercase     			=						model(snake_case__ ,							return_dict=snake_case__ ,							**snake_case__						).to_tuple()

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

               recursive_check(snake_case__ ,							snake_case__						)

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

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

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

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

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

   def       SCREAMING_SNAKE_CASE__					(     self:						Tuple						)	->		Optional[Any]:


       """simple docstring"""



       _lowercase     			=						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*snake_case__						)

   @slow
   def       SCREAMING_SNAKE_CASE__					(     self:						int						)	->		Optional[int]:


       """simple docstring"""



       _lowercase     			=						TFConvNextModel.from_pretrained('facebook/convnext-tiny-224'						)
       self.assertIsNotNone(snake_case__						)






def 							UpperCAmelCase   ( ):


    '''simple docstring'''



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

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







   """simple docstring"""



   @cached_property
   def       SCREAMING_SNAKE_CASE__					(     self:						Optional[int]						)	->		str:


       """simple docstring"""



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

   @slow
   def       SCREAMING_SNAKE_CASE__					(     self:						Optional[Any]						)	->		Any:


       """simple docstring"""



       _lowercase     			=						TFConvNextForImageClassification.from_pretrained('facebook/convnext-tiny-224'						)

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

       # forward pass
       _lowercase     			=						model(**snake_case__						)

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

       _lowercase     			=						tf.constant([-0.02_60, -0.47_39, 0.19_11]						)

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








from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available


lowerCamelCase					    =	{}

try:
   if not is_sentencepiece_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase					    =	['''MBart50Tokenizer''']

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowerCamelCase					    =	['''MBart50TokenizerFast''']


if TYPE_CHECKING:
   try:
      if not is_sentencepiece_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_mbartaa import MBartaaTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_mbartaa_fast import MBartaaTokenizerFast

else:
   import sys

   lowerCamelCase					    =	_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
