

import numpy as np

from transformers import BatchFeature
from transformers.testing_utils import require_tf, require_torch

from .test_feature_extraction_common import FeatureExtractionSavingTestMixin





class 				__lowerCAmelCase  (      SCREAMING_SNAKE_CASE							):
  # to overwrite at feature extractactor specific tests
  _a		    =						None
  _a		    =						None




  @property
  def 						A__  (       self      )						->				Optional[Any]:
        '''simple docstring'''






        return self.feat_extract_tester.prepare_feat_extract_dict()




  def 						A__  (       self      )						->				str:
        '''simple docstring'''






        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'feature_size'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'sampling_rate'      )      )
        self.assertTrue(hasattr(lowerCAmelCase							,     'padding_value'      )      )




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common()
        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )

        self.assertTrue(all(len(lowerCAmelCase      ) == len(lowerCAmelCase      ) for x, y in zip(lowerCAmelCase							,     processed_features[input_name]      )      )      )

        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCAmelCase      )
        _lowercase			 =BatchFeature({input_name: speech_inputs}							,     tensor_type='np'      )

        _lowercase			 =processed_features[input_name]

        if len(batch_features_input.shape      ) < 3:
              _lowercase			 =batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]      ), self.feat_extract_tester.feature_size)      )




  @require_torch
  def 						A__  (       self      )						->				str:
        '''simple docstring'''






        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCAmelCase      )
        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}							,     tensor_type='pt'      )

        _lowercase			 =processed_features[input_name]

        if len(batch_features_input.shape      ) < 3:
              _lowercase			 =batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]      ), self.feat_extract_tester.feature_size)      )




  @require_tf
  def 						A__  (       self      )						->				Dict:
        '''simple docstring'''






        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCAmelCase      )
        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}							,     tensor_type='tf'      )

        _lowercase			 =processed_features[input_name]

        if len(batch_features_input.shape      ) < 3:
              _lowercase			 =batch_features_input[:, :, None]

        self.assertTrue(
            batch_features_input.shape
            == (self.feat_extract_tester.batch_size, len(speech_inputs[0]      ), self.feat_extract_tester.feature_size)      )




  def 						A__  (       self							,     lowerCAmelCase=False      )						->				Optional[Any]:
        '''simple docstring'''






        def _inputs_have_equal_length(lowerCAmelCase      ):
              _lowercase			 =len(input[0]      )
              for input_slice in input[1:]:
                    if len(lowerCAmelCase      ) != length:
                          return False
              return True

        def _inputs_are_equal(lowerCAmelCase							,     lowerCAmelCase      ):
              if len(lowerCAmelCase      ) != len(lowerCAmelCase      ):
                    return False

              for input_slice_a, input_slice_a in zip(lowerCAmelCase							,     lowerCAmelCase      ):
                    if not np.allclose(np.asarray(lowerCAmelCase      )							,     np.asarray(lowerCAmelCase      )							,     atol=1e-3      ):
                          return False
              return True

        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common(numpify=lowerCAmelCase      )
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )

        _lowercase			 =self.feat_extract_tester.seq_length_diff
        _lowercase			 =self.feat_extract_tester.max_seq_length + pad_diff
        _lowercase			 =self.feat_extract_tester.min_seq_length
        _lowercase			 =self.feat_extract_tester.batch_size
        _lowercase			 =self.feat_extract_tester.feature_size

        # test padding for List[int] + numpy
        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding=lowerCAmelCase      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[-1]      )      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     return_tensors='np'      )
        _lowercase			 =input_a[input_name]

        # max_length parameter has to be provided when setting `padding="max_length"`
        with self.assertRaises(lowerCAmelCase      ):
              feat_extract.pad(lowerCAmelCase							,     padding='max_length'      )[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=lowerCAmelCase							,     return_tensors='np'      )
        _lowercase			 =input_a[input_name]

        self.assertFalse(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(_inputs_are_equal(lowerCAmelCase							,     lowerCAmelCase      )      )
        self.assertTrue(len(input_a[0]      ) == pad_min_length      )
        self.assertTrue(len(input_a[1]      ) == pad_min_length + pad_diff      )
        self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0]      ))      )
        self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length)      )

        if feature_size > 1:
              self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size      )

        # test padding for `pad_to_multiple_of` for List[int] + numpy
        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     pad_to_multiple_of=10      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     pad_to_multiple_of=10      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     pad_to_multiple_of=10							,     max_length=lowerCAmelCase      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     pad_to_multiple_of=10							,     max_length=lowerCAmelCase							,     return_tensors='np'							,     )
        _lowercase			 =input_a[input_name]

        self.assertTrue(all(len(lowerCAmelCase      ) % 10 == 0 for x in input_a      )      )
        self.assertTrue(_inputs_are_equal(lowerCAmelCase							,     lowerCAmelCase      )      )

        _lowercase			 =pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10
        self.assertTrue(all(len(lowerCAmelCase      ) == expected_mult_pad_length for x in input_a      )      )
        self.assertEqual(input_a.shape[:2]							,     (batch_size, expected_mult_pad_length)      )

        if feature_size > 1:
              self.assertTrue(input_a.shape[2] == feature_size      )

        # Check padding value is correct
        _lowercase			 =(np.ones(self.feat_extract_tester.feature_size      ) * feat_extract.padding_value).sum()
        self.assertTrue(
            abs(np.asarray(input_a[0]      )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)      )
            < 1e-3      )
        self.assertTrue(
            abs(
                np.asarray(input_a[1]      )[pad_min_length + pad_diff :].sum()
                - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff)      )
            < 1e-3      )
        self.assertTrue(
            abs(
                np.asarray(input_a[2]      )[pad_min_length + 2 * pad_diff :].sum()
                - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff)      )
            < 1e-3      )
        self.assertTrue(
            abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)      ) < 1e-3      )
        self.assertTrue(
            abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)      )
            < 1e-3      )




  def 						A__  (       self							,     lowerCAmelCase=False      )						->				str:
        '''simple docstring'''






        def _inputs_have_equal_length(lowerCAmelCase      ):
              _lowercase			 =len(input[0]      )
              for input_slice in input[1:]:
                    if len(lowerCAmelCase      ) != length:
                          return False
              return True

        def _inputs_are_equal(lowerCAmelCase							,     lowerCAmelCase      ):
              if len(lowerCAmelCase      ) != len(lowerCAmelCase      ):
                    return False

              for input_slice_a, input_slice_a in zip(lowerCAmelCase							,     lowerCAmelCase      ):
                    if not np.allclose(np.asarray(lowerCAmelCase      )							,     np.asarray(lowerCAmelCase      )							,     atol=1e-3      ):
                          return False
              return True

        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common(numpify=lowerCAmelCase      )
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )

        # truncate to smallest
        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[0]      )							,     truncation=lowerCAmelCase      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[0]      )      )
        _lowercase			 =input_a[input_name]

        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertFalse(_inputs_have_equal_length(lowerCAmelCase      )      )

        # truncate to smallest with np
        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[0]      )							,     return_tensors='np'							,     truncation=lowerCAmelCase							,     )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[0]      )							,     return_tensors='np'      )
        _lowercase			 =input_a[input_name]

        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(input_a.shape[1] == len(speech_inputs[0]      )      )

        # since truncation forces padding to be smaller than longest input
        # function can't return `np.ndarray`, but has to return list
        self.assertFalse(_inputs_have_equal_length(lowerCAmelCase      )      )

        # truncate to middle
        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[1]      )							,     truncation=lowerCAmelCase							,     return_tensors='np'							,     )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[1]      )							,     truncation=lowerCAmelCase      )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[1]      )							,     return_tensors='np'      )
        _lowercase			 =input_a[input_name]

        self.assertTrue(input_a.shape[1] == len(speech_inputs[1]      )      )
        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(_inputs_are_equal(lowerCAmelCase							,     lowerCAmelCase      )      )

        # since truncation forces padding to be smaller than longest input
        # function can't return `np.ndarray`, but has to return list
        self.assertFalse(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertTrue(len(input_a[-1]      ) == len(speech_inputs[-1]      )      )

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(lowerCAmelCase      ):
              feat_extract.pad(lowerCAmelCase							,     truncation=lowerCAmelCase      )[input_name]

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(lowerCAmelCase      ):
              feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     truncation=lowerCAmelCase      )[input_name]

        # padding has to be max_length when setting `truncation=True`
        with self.assertRaises(lowerCAmelCase      ):
              feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     truncation=lowerCAmelCase      )[input_name]

        # max_length parameter has to be provided when setting `truncation=True` and padding="max_length"
        with self.assertRaises(lowerCAmelCase      ):
              feat_extract.pad(lowerCAmelCase							,     padding='max_length'							,     truncation=lowerCAmelCase      )[input_name]

        # test truncation for `pad_to_multiple_of` for List[int] + numpy
        _lowercase			 =12
        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[0]      )							,     pad_to_multiple_of=lowerCAmelCase							,     truncation=lowerCAmelCase							,     )
        _lowercase			 =input_a[input_name]

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=len(speech_inputs[0]      )							,     pad_to_multiple_of=lowerCAmelCase							,     )
        _lowercase			 =input_a[input_name]

        # retrieve expected_length as multiple of pad_to_multiple_of
        _lowercase			 =len(speech_inputs[0]      )
        if expected_length % pad_to_multiple_of != 0:
              _lowercase			 =((len(speech_inputs[0]      ) // pad_to_multiple_of) + 1) * pad_to_multiple_of

        self.assertTrue(len(input_a[0]      ) == expected_length      )
        self.assertTrue(_inputs_have_equal_length(lowerCAmelCase      )      )
        self.assertFalse(_inputs_have_equal_length(lowerCAmelCase      )      )




  def 						A__  (       self      )						->				Optional[int]:
        '''simple docstring'''






        self._check_padding(numpify=lowerCAmelCase      )




  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        self._check_padding(numpify=lowerCAmelCase      )




  def 						A__  (       self      )						->				List[str]:
        '''simple docstring'''






        self._check_truncation(numpify=lowerCAmelCase      )




  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        self._check_truncation(numpify=lowerCAmelCase      )




  @require_torch
  def 						A__  (       self      )						->				Union[str, Any]:
        '''simple docstring'''






        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common()
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     return_tensors='np'      )[input_name]
        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     return_tensors='pt'      )[input_name]

        self.assertTrue(abs(input_np.astype(np.floataa      ).sum() - input_pt.numpy().astype(np.floataa      ).sum()      ) < 1e-2      )




  @require_tf
  def 						A__  (       self      )						->				Any:
        '''simple docstring'''






        _lowercase			 =self.feature_extraction_class(**self.feat_extract_dict      )
        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common()
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     return_tensors='np'      )[input_name]
        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     return_tensors='tf'      )[input_name]

        self.assertTrue(abs(input_np.astype(np.floataa      ).sum() - input_tf.numpy().astype(np.floataa      ).sum()      ) < 1e-2      )




  def 						A__  (       self      )						->				str:
        '''simple docstring'''






        _lowercase			 =self.feat_extract_dict
        _lowercase			 =True
        _lowercase			 =self.feature_extraction_class(**lowerCAmelCase      )
        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common()
        _lowercase			 =[len(lowerCAmelCase      ) for x in speech_inputs]
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )

        _lowercase			 =feat_extract.pad(lowerCAmelCase							,     padding='longest'							,     return_tensors='np'      )
        self.assertIn('attention_mask'							,     lowerCAmelCase      )
        self.assertListEqual(list(processed.attention_mask.shape      )							,     list(processed[input_name].shape[:2]      )      )
        self.assertListEqual(processed.attention_mask.sum(-1      ).tolist()							,     lowerCAmelCase      )




  def 						A__  (       self      )						->				Tuple:
        '''simple docstring'''






        _lowercase			 =self.feat_extract_dict
        _lowercase			 =True
        _lowercase			 =self.feature_extraction_class(**lowerCAmelCase      )
        _lowercase			 =self.feat_extract_tester.prepare_inputs_for_common()
        _lowercase			 =[len(lowerCAmelCase      ) for x in speech_inputs]
        _lowercase			 =feat_extract.model_input_names[0]

        _lowercase			 =BatchFeature({input_name: speech_inputs}      )
        _lowercase			 =min(lowerCAmelCase      )

        _lowercase			 =feat_extract.pad(
            lowerCAmelCase							,     padding='max_length'							,     max_length=lowerCAmelCase							,     truncation=lowerCAmelCase							,     return_tensors='np'      )
        self.assertIn('attention_mask'							,     lowerCAmelCase      )
        self.assertListEqual(
            list(processed_pad.attention_mask.shape      )							,     [processed_pad[input_name].shape[0], max_length]      )
        self.assertListEqual(
            processed_pad.attention_mask[:, :max_length].sum(-1      ).tolist()							,     [max_length for x in speech_inputs]      )





import math

import tensorflow as tf
from packaging import version
def   a   (    A__			:     Tuple  )					->   List[Any]:





      """simple docstring"""



      _lowercase			 =tf.convert_to_tensor(A__  )
      _lowercase			 =0.5 * (1.0 + tf.math.erf(x / tf.cast(tf.sqrt(2.0  )   ,     x.dtype  )  ))

      return x * cdf
def   a   (    A__			:     Any  )					->   int:





      """simple docstring"""



      _lowercase			 =tf.convert_to_tensor(A__  )
      _lowercase			 =tf.cast(math.pi   ,     x.dtype  )
      _lowercase			 =tf.cast(0.044715   ,     x.dtype  )
      _lowercase			 =0.5 * (1.0 + tf.tanh(tf.sqrt(2.0 / pi  ) * (x + coeff * tf.pow(A__   ,     3  ))  ))

      return x * cdf
def   a   (    A__			:     Optional[int]  )					->   int:





      """simple docstring"""



      _lowercase			 =tf.convert_to_tensor(A__  )

      return x * tf.tanh(tf.math.softplus(A__  )  )
def   a   (    A__			:     Tuple  )					->   List[str]:





      """simple docstring"""



      _lowercase			 =tf.convert_to_tensor(A__  )
      _lowercase			 =tf.cast(0.044715   ,     x.dtype  )
      _lowercase			 =tf.cast(0.7978845608   ,     x.dtype  )

      return 0.5 * x * (1.0 + tf.tanh(x * coeffa * (1.0 + coeffa * x * x)  ))
def   a   (    A__			:     int  )					->   Any:





      """simple docstring"""



      _lowercase			 =tf.convert_to_tensor(A__  )
      _lowercase			 =tf.cast(1.702   ,     x.dtype  )
      return x * tf.math.sigmoid(coeff * x  )
def   a   (    A__			:     int  )					->   Dict:





      """simple docstring"""



      return tf.clip_by_value(_gelu(A__  )   ,     -10   ,     10  )
def   a   (    A__			:     Optional[int]   ,     A__			:     int=-1  )					->   Optional[Any]:





      """simple docstring"""



      _lowercase , _lowercase			 =tf.split(A__   ,     2   ,     axis=A__  )
      return a * tf.math.sigmoid(A__  )


if version.parse(tf.version.VERSION) >= version.parse('2.4'):
  def   a   (    A__			:     Any  )					->   Dict:





        """simple docstring"""



        return tf.keras.activations.gelu(A__   ,     approximate=A__  )

  lowercase_             =     tf.keras.activations.gelu







  lowercase_             =     approximate_gelu_wrap
else:
  lowercase_             =     _gelu
  lowercase_             =     _gelu_new


lowercase_             =     {
    'gelu': gelu,
    'gelu_10': gelu_aa,
    'gelu_fast': gelu_fast,
    'gelu_new': gelu_new,
    'glu': glu,
    'mish': mish,
    'quick_gelu': quick_gelu,
    'relu': tf.keras.activations.relu,
    'sigmoid': tf.keras.activations.sigmoid,
    'silu': tf.keras.activations.swish,
    'swish': tf.keras.activations.swish,
    'tanh': tf.keras.activations.tanh,
}







def   a   (    A__			:     Optional[int]  )					->   str:





      """simple docstring"""



      if activation_string in ACTaFN:
            return ACTaFN[activation_string]
      else:
            raise KeyError(F'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()  )}'''  )


