





"""simple docstring"""
import inspect
import unittest
from typing import List

import numpy as np

from transformers import EfficientFormerConfig
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 (
       TFEfficientFormerForImageClassification,
       TFEfficientFormerForImageClassificationWithTeacher,
       TFEfficientFormerModel,
   )
   from transformers.models.efficientformer.modeling_tf_efficientformer import (
       TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
   )


if is_vision_available():
   from PIL import Image

   from transformers import EfficientFormerImageProcessor
class lowerCamelCase__	:



   def __init__(							self   , snake_case   , snake_case = 1_3   , snake_case = 6_4   , snake_case = 2   , snake_case = 3   , snake_case = 3   , snake_case = True   , snake_case = True   , snake_case = 1_2_8   , snake_case=[1_6, 3_2, 6_4, 1_2_8]   , snake_case = 7   , snake_case = 4   , snake_case = 3_7   , snake_case = "gelu"   , snake_case = 0.1   , snake_case = 0.1   , snake_case = 1_0   , snake_case = 0.02   , snake_case = 2   , snake_case = 1   , snake_case = 1_2_8   , snake_case = [2, 2, 2, 2]   , snake_case = 2   , snake_case = 2   , )			->     List[Any]:







      """simple docstring"""
      lowercase     :      int	=							parent
      lowercase     :      Union[str, Any]	=							batch_size
      lowercase     :      Any	=							image_size
      lowercase     :      List[str]	=							patch_size
      lowercase     :      Dict	=							num_channels
      lowercase     :      Dict	=							is_training
      lowercase     :      Optional[Any]	=							use_labels
      lowercase     :      List[str]	=							hidden_size
      lowercase     :      List[Any]	=							num_hidden_layers
      lowercase     :      Dict	=							num_attention_heads
      lowercase     :      str	=							intermediate_size
      lowercase     :      Dict	=							hidden_act
      lowercase     :      str	=							hidden_dropout_prob
      lowercase     :      Dict	=							attention_probs_dropout_prob
      lowercase     :      Tuple	=							type_sequence_label_size
      lowercase     :      List[Any]	=							initializer_range
      lowercase     :      int	=							encoder_stride
      lowercase     :      List[str]	=							num_attention_outputs
      lowercase     :      int	=							embed_dim
      lowercase     :      List[str]	=							embed_dim + 1
      lowercase     :      Union[str, Any]	=							resolution
      lowercase     :      Dict	=							depths
      lowercase     :      Dict	=							hidden_sizes
      lowercase     :      Any	=							dim
      lowercase     :      List[str]	=							mlp_expansion_ratio



   def  _UpperCAmelCase						(							self						)			->     str:







      """simple docstring"""
      lowercase     :      int	=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

      lowercase     :      str	=							self.get_config()

      return config, pixel_values, labels



   def  _UpperCAmelCase						(							self						)			->     List[str]:







      """simple docstring"""
      return EfficientFormerConfig(
          image_size=self.image_size   , patch_size=self.patch_size   , num_channels=self.num_channels   , hidden_size=self.hidden_size   , num_hidden_layers=self.num_hidden_layers   , num_attention_heads=self.num_attention_heads   , intermediate_size=self.intermediate_size   , hidden_act=self.hidden_act   , hidden_dropout_prob=self.hidden_dropout_prob   , attention_probs_dropout_prob=self.attention_probs_dropout_prob   , is_decoder=__a   , initializer_range=self.initializer_range   , encoder_stride=self.encoder_stride   , resolution=self.resolution   , depths=self.depths   , hidden_sizes=self.hidden_sizes   , dim=self.dim   , mlp_expansion_ratio=self.mlp_expansion_ratio   , )



   def  _UpperCAmelCase						(							self   , snake_case   , snake_case   , snake_case						)			->     Optional[int]:







      """simple docstring"""
      lowercase     :      List[Any]	=							TFEfficientFormerModel(config=__a						)
      lowercase     :      List[Any]	=							model(__a   , training=__a						)
      self.parent.assertEqual(result.last_hidden_state.shape   , (self.batch_size, self.seq_length, self.hidden_size)						)



   def  _UpperCAmelCase						(							self   , snake_case   , snake_case   , snake_case						)			->     str:







      """simple docstring"""
      lowercase     :      Optional[Any]	=							self.type_sequence_label_size
      lowercase     :      int	=							TFEfficientFormerForImageClassification(__a						)
      lowercase     :      List[str]	=							model(__a   , labels=__a   , training=__a						)
      self.parent.assertEqual(result.logits.shape   , (self.batch_size, self.type_sequence_label_size)						)

      # test greyscale images
      lowercase     :      Dict	=							1
      lowercase     :      Tuple	=							TFEfficientFormerForImageClassification(__a						)

      lowercase     :      List[Any]	=							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
      lowercase     :      Any	=							model(__a   , labels=__a						)
      self.parent.assertEqual(result.logits.shape   , (self.batch_size, self.type_sequence_label_size)						)





   def  _UpperCAmelCase						(							self						)			->     int:







      """simple docstring"""
      lowercase     :      Optional[Any]	=							self.prepare_config_and_inputs()
      lowercase	,       lowercase	,       lowercase     :      Tuple	=							config_and_inputs
      lowercase     :      Optional[Any]	=							{"""pixel_values""": pixel_values}
      return config, inputs_dict




@require_tf
class lowerCamelCase__	(     lowerCAmelCase__	,					lowerCAmelCase__	,					unittest.TestCase					):
   __UpperCAmelCase										=       (
       (
           TFEfficientFormerModel,
           TFEfficientFormerForImageClassificationWithTeacher,
           TFEfficientFormerForImageClassification,
       )
       if is_tf_available()
       else ()
   )
   __UpperCAmelCase										=       (
       {
           """feature-extraction""": TFEfficientFormerModel,
           """image-classification""": (
               TFEfficientFormerForImageClassification,
               TFEfficientFormerForImageClassificationWithTeacher,
           ),
       }
       if is_tf_available()
       else {}
   )

   __UpperCAmelCase										=       False

   __UpperCAmelCase										=       False
   __UpperCAmelCase										=       False
   __UpperCAmelCase										=       False
   __UpperCAmelCase										=       False



   def  _UpperCAmelCase						(							self						)			->     str:







      """simple docstring"""
      lowercase     :      Union[str, Any]	=							TFEfficientFormerModelTester(self						)
      lowercase     :      Optional[Any]	=							ConfigTester(
          self   , config_class=__a   , has_text_modality=__a   , hidden_size=3_7						)



   def  _UpperCAmelCase						(							self						)			->     Tuple:







      """simple docstring"""
      self.config_tester.run_common_tests()



   @unittest.skip(reason="""EfficientFormer does not use inputs_embeds"""						)
   def  _UpperCAmelCase						(							self						)			->     Union[str, Any]:







      """simple docstring"""
      pass



   @unittest.skip(reason="""EfficientFormer does not support input and output embeddings"""						)
   def  _UpperCAmelCase						(							self						)			->     str:







      """simple docstring"""
      pass



   def  _UpperCAmelCase						(							self						)			->     Optional[Any]:







      """simple docstring"""
      lowercase	,       lowercase     :      str	=							self.model_tester.prepare_config_and_inputs_for_common()

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

         lowercase     :      Union[str, Any]	=							["""pixel_values"""]
         self.assertListEqual(arg_names[:1]   , __a						)



   def  _UpperCAmelCase						(							self						)			->     List[Any]:







      """simple docstring"""
      def check_hidden_states_output(snake_case   , snake_case   , snake_case						):
         lowercase     :      Any	=							model_class(__a						)

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

         lowercase     :      Dict	=							getattr(
             self.model_tester   , """expected_num_hidden_layers"""   , self.model_tester.num_hidden_layers + 1						)
         self.assertEqual(len(__a						)   , __a						)

         if hasattr(self.model_tester   , """encoder_seq_length"""						):
            lowercase     :      Union[str, Any]	=							self.model_tester.encoder_seq_length
            if hasattr(self.model_tester   , """chunk_length"""						) and self.model_tester.chunk_length > 1:
               lowercase     :      Dict	=							seq_length * self.model_tester.chunk_length
         else:
            lowercase     :      Optional[int]	=							self.model_tester.seq_length

         self.assertListEqual(
             list(hidden_states[-1].shape[-2:]						)   , [seq_length, self.model_tester.hidden_size]   , )

         if config.is_encoder_decoder:
            lowercase     :      Union[str, Any]	=							outputs.decoder_hidden_states

            self.asseretIsInstance(__a   , (list, tuple)						)
            self.assertEqual(len(__a						)   , __a						)
            lowercase     :      Tuple	=							getattr(self.model_tester   , """seq_length"""   , __a						)
            lowercase     :      int	=							getattr(self.model_tester   , """decoder_seq_length"""   , __a						)

            self.assertListEqual(
                list(hidden_states[-1].shape[-2:]						)   , [decoder_seq_length, self.model_tester.hidden_size]   , )

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

      for model_class in self.all_model_classes:
         lowercase     :      Dict	=							True
         check_hidden_states_output(__a   , __a   , __a						)

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

         check_hidden_states_output(__a   , __a   , __a						)



   def  _UpperCAmelCase						(							self   , snake_case   , snake_case   , snake_case=False						)			->     Any:







      """simple docstring"""
      lowercase     :      Dict	=							super()._prepare_for_class(__a   , __a   , return_labels=__a						)

      if return_labels:
         if model_class.__name__ == "TFEfficientFormerForImageClassificationWithTeacher":
            del inputs_dict["labels"]

      return inputs_dict



   def  _UpperCAmelCase						(							self						)			->     Dict:







      """simple docstring"""
      lowercase     :      List[str]	=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__a						)



   @unittest.skip(reason="""EfficientFormer does not implement masked image modeling yet"""						)
   def  _UpperCAmelCase						(							self						)			->     Dict:







      """simple docstring"""
      lowercase     :      Optional[int]	=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_masked_image_modeling(*__a						)



   def  _UpperCAmelCase						(							self						)			->     List[str]:







      """simple docstring"""
      lowercase     :      Union[str, Any]	=							self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__a						)



   @slow
   def  _UpperCAmelCase						(							self						)			->     Union[str, Any]:







      """simple docstring"""
      for model_name in TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         lowercase     :      List[Any]	=							TFEfficientFormerModel.from_pretrained(__a						)
         self.assertIsNotNone(__a						)



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







      """simple docstring"""
      lowercase	,       lowercase     :      Tuple	=							self.model_tester.prepare_config_and_inputs_for_common()
      lowercase     :      str	=							True

      lowercase     :      Union[str, Any]	=							getattr(self.model_tester   , """seq_length"""   , __a						)
      lowercase     :      Dict	=							getattr(self.model_tester   , """encoder_seq_length"""   , __a						)
      lowercase     :      int	=							getattr(self.model_tester   , """key_length"""   , __a						)
      lowercase     :      List[Any]	=							getattr(self.model_tester   , """chunk_length"""   , __a						)

      if chunk_length is not None and hasattr(self.model_tester   , """num_hashes"""						):
         lowercase     :      int	=							encoder_seq_length * self.model_tester.num_hashes

      for model_class in self.all_model_classes:
         lowercase     :      int	=							True
         lowercase     :      int	=							False
         lowercase     :      List[Any]	=							True
         lowercase     :      Optional[int]	=							model_class(__a						)

         lowercase     :      int	=							model(**self._prepare_for_class(__a   , __a						)   , training=__a						)
         lowercase     :      Dict	=							outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
         self.assertEqual(len(__a						)   , self.model_tester.num_attention_outputs						)

         # check that output_attentions also work using config
         del inputs_dict["output_attentions"]
         lowercase     :      List[str]	=							True
         lowercase     :      int	=							model_class(__a						)
         lowercase     :      Any	=							model(**self._prepare_for_class(__a   , __a						)   , training=__a						)

         lowercase     :      Tuple	=							outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
         self.assertEqual(len(__a						)   , self.model_tester.num_attention_outputs						)

         if chunk_length is not None:
            self.assertListEqual(
                list(attentions[0].shape[-4:]						)   , [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length]   , )
         else:
            self.assertListEqual(
                list(attentions[0].shape[-3:]						)   , [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length]   , )





   def  _UpperCAmelCase						(							self						)			->     str:







      """simple docstring"""
      # We use a simplified version of this test for EfficientFormer because it requires training=False
      # and Keras refuses to let us force that during functional construction
      lowercase	,       lowercase     :      Any	=							self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         # Prepare our model
         lowercase     :      str	=							model_class(__a						)
         # These are maximally general inputs for the model, with multiple None dimensions
         # Hopefully this will catch any conditionals that fail for flexible shapes
         lowercase     :      Tuple	=							{
             key: tf.keras.Input(shape=val.shape[1:]   , dtype=val.dtype   , name=__a						)
             for key, val in model.input_signature.items()
             if key in model.dummy_inputs
         }
         lowercase     :      Dict	=							model(__a						)
         self.assertTrue(outputs_dict is not None						)




def       __snake_case    (   )		->					Dict:
   lowercase     :      Tuple	=							Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
   return image







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



   @cached_property
   def  _UpperCAmelCase						(							self						)			->     List[str]:







      """simple docstring"""
      return (
          EfficientFormerImageProcessor.from_pretrained("""snap-research/efficientformer-l1-300"""						)
          if is_vision_available()
          else None
      )



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







      """simple docstring"""
      lowercase     :      List[str]	=							TFEfficientFormerForImageClassification.from_pretrained("""snap-research/efficientformer-l1-300"""						)
      lowercase     :      Optional[Any]	=							self.default_image_processor
      lowercase     :      int	=							prepare_img()
      lowercase     :      Optional[int]	=							image_processor(images=__a   , return_tensors="""tf"""						)
      # forward pass
      lowercase     :      Dict	=							model(**__a   , training=__a						)
      # verify the logits
      lowercase     :      Dict	=							tf.TensorShape((1, 1_0_0_0)						)
      self.assertEqual(outputs.logits.shape   , __a						)
      lowercase     :      int	=							tf.constant([-0.05_55, 0.48_25, -0.08_52]						)
      self.assertTrue(np.allclose(outputs.logits[0, :3]   , __a   , atol=1E-4						)						)





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







      """simple docstring"""
      lowercase     :      int	=							TFEfficientFormerForImageClassificationWithTeacher.from_pretrained(
          """snap-research/efficientformer-l1-300"""						)
      lowercase     :      Optional[Any]	=							self.default_image_processor
      lowercase     :      str	=							prepare_img()
      lowercase     :      List[Any]	=							image_processor(images=__a   , return_tensors="""tf"""						)
      # forward pass
      lowercase     :      str	=							model(**__a   , training=__a						)
      # verify the logits
      lowercase     :      Dict	=							tf.TensorShape((1, 1_0_0_0)						)
      self.assertEqual(outputs.logits.shape   , __a						)
      lowercase     :      Optional[Any]	=							tf.constant([-0.13_12, 0.43_53, -1.04_99]						)
      self.assertTrue(np.allclose(outputs.logits[0, :3]   , __a   , atol=1E-4						)						)






"""simple docstring"""


import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin
class     _UpperCamelCase    (  lowerCAmelCase__						):
							'''simple docstring'''







							__UpperCAmelCase		:       List[str]							 ="""Speech2TextFeatureExtractor"""
							__UpperCAmelCase		:       Union[str, Any]							 ="""Speech2TextTokenizer"""

							def __init__(	self       ,  __a       ,  __a      ):
										super().__init__(__a       ,  __a      )
										__lowerCAmelCase							       =     self.feature_extractor
										__lowerCAmelCase							       =     False

							def __call__(	self       ,  *__a       ,  **__a      ):
										# For backward compatibility
										if self._in_target_context_manager:
													return self.current_processor(*__a       ,  **__a      )

										if "raw_speech" in kwargs:
													warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."      )
													__lowerCAmelCase							       =     kwargs.pop("raw_speech"      )
										else:
													__lowerCAmelCase							       =     kwargs.pop("audio"       ,  __a      )
										__lowerCAmelCase							       =     kwargs.pop("sampling_rate"       ,  __a      )
										__lowerCAmelCase							       =     kwargs.pop("text"       ,  __a      )
										if len(__a      ) > 0:
													__lowerCAmelCase							       =     args[0]
													__lowerCAmelCase							       =     args[1:]

										if audio is None and text is None:
													raise ValueError("You need to specify either an `audio` or `text` input to process."      )

										if audio is not None:
													__lowerCAmelCase							       =     self.feature_extractor(__a       ,  *__a       ,  sampling_rate=__a       ,  **__a      )
										if text is not None:
													__lowerCAmelCase							       =     self.tokenizer(__a       ,  **__a      )

										if text is None:
													return inputs
										elif audio is None:
													return encodings
										else:
													__lowerCAmelCase							       =     encodings["input_ids"]
													return inputs

							def      snake_case							(	self       ,  *__a       ,  **__a      ):
										return self.tokenizer.batch_decode(*__a       ,  **__a      )

							def      snake_case							(	self       ,  *__a       ,  **__a      ):
										return self.tokenizer.decode(*__a       ,  **__a      )



							@contextmanager
							def      snake_case							(	self      ):
										warnings.warn(
										    "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
										    "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
										    "your audio inputs, or in a separate call."      )
										__lowerCAmelCase							       =     True
										__lowerCAmelCase							       =     self.tokenizer
										yield
										__lowerCAmelCase							       =     self.feature_extractor
										__lowerCAmelCase							       =     False




