


import itertools
import random
import unittest

import numpy as np

from transformers import BatchFeature, SpeechTaFeatureExtractor
from transformers.testing_utils import require_torch
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_torch_available():
     import torch


snake_case    :   int	    =					random.Random()
def     __lowerCamelCase						(			UpperCAmelCase_						:		Optional[int]			,  UpperCAmelCase_						:		Any=1.0			,  UpperCAmelCase_						:		Dict=None			,  UpperCAmelCase_						:		List[str]=None						):




      """simple docstring"""





      if rng is None:
            a						:Tuple										=	global_rng

      a						:str										=	[]
      for batch_idx in range(shape[0]						):
            values.append([]						)
            for _ in range(shape[1]						):
                  values[-1].append(rng.random() * scale						)

      return values







@require_torch
class 						_snake_case  (				unittest.TestCase							):




 def __init__(		self ,  _lowerCamelCase ,  _lowerCamelCase=7 ,  _lowerCamelCase=400 ,  _lowerCamelCase=2000 ,  _lowerCamelCase=1 ,  _lowerCamelCase=0.0 ,  _lowerCamelCase=1_6000 ,  _lowerCamelCase=True ,  _lowerCamelCase=80 ,  _lowerCamelCase=16 ,  _lowerCamelCase=64 ,  _lowerCamelCase="hann_window" ,  _lowerCamelCase=80 ,  _lowerCamelCase=7600 ,  _lowerCamelCase=1e-10 ,  _lowerCamelCase=True ,  ):
       a						:Optional[int]										=	parent
       a						:str										=	batch_size
       a						:List[str]										=	min_seq_length
       a						:Optional[Any]										=	max_seq_length
       a						:str										=	(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
       a						:Tuple										=	feature_size
       a						:List[str]										=	padding_value
       a						:List[str]										=	sampling_rate
       a						:Union[str, Any]										=	do_normalize
       a						:Optional[Any]										=	num_mel_bins
       a						:int										=	hop_length
       a						:Optional[Any]										=	win_length
       a						:Tuple										=	win_function
       a						:Any										=	fmin
       a						:str										=	fmax
       a						:str										=	mel_floor
       a						:Any										=	return_attention_mask




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return {
           "feature_size": self.feature_size,
           "padding_value": self.padding_value,
           "sampling_rate": self.sampling_rate,
           "do_normalize": self.do_normalize,
           "num_mel_bins": self.num_mel_bins,
           "hop_length": self.hop_length,
           "win_length": self.win_length,
           "win_function": self.win_function,
           "fmin": self.fmin,
           "fmax": self.fmax,
           "mel_floor": self.mel_floor,
           "return_attention_mask": self.return_attention_mask,
       }




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase=False ,  _lowerCamelCase=False   ):
       def _flatten(_lowerCamelCase   ):
             return list(itertools.chain(*lowercase_   )   )

       if equal_length:
             a						:List[Any]										=	floats_list((self.batch_size, self.max_seq_length)   )
       else:
             # make sure that inputs increase in size
             a						:Optional[int]										=	[
                 _flatten(floats_list((x, self.feature_size)   )   )
                 for x in range(self.min_seq_length ,  self.max_seq_length ,  self.seq_length_diff   )
             ]

       if numpify:
             a						:Optional[Any]										=	[np.asarray(lowercase_   ) for x in speech_inputs]

       return speech_inputs




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase=False ,  _lowerCamelCase=False   ):
       if equal_length:
             a						:Optional[Any]										=	[floats_list((self.max_seq_length, self.num_mel_bins)   ) for _ in range(self.batch_size   )]
       else:
             # make sure that inputs increase in size
             a						:Union[str, Any]										=	[
                 floats_list((x, self.num_mel_bins)   )
                 for x in range(self.min_seq_length ,  self.max_seq_length ,  self.seq_length_diff   )
             ]

       if numpify:
             a						:Tuple										=	[np.asarray(lowercase_   ) for x in speech_inputs]

       return speech_inputs







@require_torch
class 						_snake_case  (				_UpperCAmelCase						,   unittest.TestCase							):
 SCREAMING_SNAKE_CASE__				=	SpeechTaFeatureExtractor




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Optional[Any]										=	SpeechTaFeatureExtractionTester(self   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       self.assertTrue(np.all(np.mean(lowercase_ ,  axis=0   ) < 1e-3   )   )
       self.assertTrue(np.all(np.abs(np.var(lowercase_ ,  axis=0   ) - 1   ) < 1e-3   )   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       # Tests that all call wrap to encode_plus and batch_encode_plus
       a						:Union[str, Any]										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       # create three inputs of length 800, 1000, and 1200
       a						:int										=	[floats_list((1, x)   )[0] for x in range(800 ,  1400 ,  200   )]
       a						:Any										=	[np.asarray(lowercase_   ) for speech_input in speech_inputs]

       # Test not batched input
       a						:Optional[int]										=	feat_extract(speech_inputs[0] ,  return_tensors='''np'''   ).input_values
       a						:Any										=	feat_extract(np_speech_inputs[0] ,  return_tensors='''np'''   ).input_values
       self.assertTrue(np.allclose(lowercase_ ,  lowercase_ ,  atol=1e-3   )   )

       # Test batched
       a						:Dict										=	feat_extract(lowercase_ ,  return_tensors='''np'''   ).input_values
       a						:Optional[Any]										=	feat_extract(lowercase_ ,  return_tensors='''np'''   ).input_values
       for enc_seq_a, enc_seq_a in zip(lowercase_ ,  lowercase_   ):
             self.assertTrue(np.allclose(lowercase_ ,  lowercase_ ,  atol=1e-3   )   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Any										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       a						:int										=	[floats_list((1, x)   )[0] for x in range(800 ,  1400 ,  200   )]

       a						:List[Any]										=	["""longest""", """max_length""", """do_not_pad"""]
       a						:int										=	[None, 1600, None]
       for max_length, padding in zip(lowercase_ ,  lowercase_   ):
             a						:Any										=	feat_extract(lowercase_ ,  padding=lowercase_ ,  max_length=lowercase_ ,  return_tensors='''np'''   )
             a						:Optional[Any]										=	processed.input_values

             self._check_zero_mean_unit_variance(input_values[0][:800]   )
             self.assertTrue(input_values[0][800:].sum() < 1e-6   )
             self._check_zero_mean_unit_variance(input_values[1][:1000]   )
             self.assertTrue(input_values[0][1000:].sum() < 1e-6   )
             self._check_zero_mean_unit_variance(input_values[2][:1200]   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Union[str, Any]										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       a						:Any										=	range(800 ,  1400 ,  200   )
       a						:int										=	[floats_list((1, x)   )[0] for x in lengths]

       a						:int										=	["""longest""", """max_length""", """do_not_pad"""]
       a						:str										=	[None, 1600, None]

       for max_length, padding in zip(lowercase_ ,  lowercase_   ):
             a						:Tuple										=	feat_extract(lowercase_ ,  max_length=lowercase_ ,  padding=lowercase_   )
             a						:Optional[int]										=	processed.input_values

             self._check_zero_mean_unit_variance(input_values[0][:800]   )
             self._check_zero_mean_unit_variance(input_values[1][:1000]   )
             self._check_zero_mean_unit_variance(input_values[2][:1200]   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Optional[Any]										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       a						:List[Any]										=	[floats_list((1, x)   )[0] for x in range(800 ,  1400 ,  200   )]
       a						:int										=	feat_extract(
           lowercase_ ,  truncation=lowercase_ ,  max_length=1000 ,  padding='''max_length''' ,  return_tensors='''np'''   )
       a						:int										=	processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]   )
       self._check_zero_mean_unit_variance(input_values[1]   )
       self._check_zero_mean_unit_variance(input_values[2]   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Dict										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       a						:Optional[Any]										=	[floats_list((1, x)   )[0] for x in range(800 ,  1400 ,  200   )]
       a						:str										=	feat_extract(
           lowercase_ ,  truncation=lowercase_ ,  max_length=1000 ,  padding='''longest''' ,  return_tensors='''np'''   )
       a						:List[str]										=	processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]   )
       self._check_zero_mean_unit_variance(input_values[1, :1000]   )
       self._check_zero_mean_unit_variance(input_values[2]   )

       # make sure that if max_length < longest -> then pad to max_length
       self.assertTrue(input_values.shape == (3, 1000)   )

       a						:List[str]										=	[floats_list((1, x)   )[0] for x in range(800 ,  1400 ,  200   )]
       a						:Optional[int]										=	feat_extract(
           lowercase_ ,  truncation=lowercase_ ,  max_length=2000 ,  padding='''longest''' ,  return_tensors='''np'''   )
       a						:int										=	processed.input_values

       self._check_zero_mean_unit_variance(input_values[0, :800]   )
       self._check_zero_mean_unit_variance(input_values[1, :1000]   )
       self._check_zero_mean_unit_variance(input_values[2]   )

       # make sure that if max_length > longest -> then pad to longest
       self.assertTrue(input_values.shape == (3, 1200)   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:str										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       a						:Tuple										=	np.random.rand(100   ).astype(np.floataa   )
       a						:Any										=	np_speech_inputs.tolist()

       for inputs in [py_speech_inputs, np_speech_inputs]:
             a						:List[Any]										=	feature_extractor.pad([{'''input_values''': inputs}] ,  return_tensors='''np'''   )
             self.assertTrue(np_processed.input_values.dtype == np.floataa   )
             a						:Any										=	feature_extractor.pad([{'''input_values''': inputs}] ,  return_tensors='''pt'''   )
             self.assertTrue(pt_processed.input_values.dtype == torch.floataa   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       # Tests that all call wrap to encode_plus and batch_encode_plus
       a						:Optional[int]										=	self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()   )
       # create three inputs of length 800, 1000, and 1200
       a						:List[Any]										=	[floats_list((1, x)   )[0] for x in range(800 ,  1400 ,  200   )]
       a						:Tuple										=	[np.asarray(lowercase_   ) for speech_input in speech_inputs]

       # Test feature size
       a						:Dict										=	feature_extractor(audio_target=lowercase_ ,  padding=lowercase_ ,  return_tensors='''np'''   ).input_values
       self.assertTrue(input_values.ndim == 3   )
       self.assertTrue(input_values.shape[-1] == feature_extractor.num_mel_bins   )

       # Test not batched input
       a						:Optional[int]										=	feature_extractor(speech_inputs[0] ,  return_tensors='''np'''   ).input_values
       a						:Any										=	feature_extractor(np_speech_inputs[0] ,  return_tensors='''np'''   ).input_values
       self.assertTrue(np.allclose(lowercase_ ,  lowercase_ ,  atol=1e-3   )   )

       # Test batched
       a						:Dict										=	feature_extractor(lowercase_ ,  return_tensors='''np'''   ).input_values
       a						:int										=	feature_extractor(lowercase_ ,  return_tensors='''np'''   ).input_values
       for enc_seq_a, enc_seq_a in zip(lowercase_ ,  lowercase_   ):
             self.assertTrue(np.allclose(lowercase_ ,  lowercase_ ,  atol=1e-3   )   )

       # Test 2-D numpy arrays are batched.
       a						:str										=	[floats_list((1, x)   )[0] for x in (800, 800, 800)]
       a						:str										=	np.asarray(lowercase_   )
       a						:Any										=	feature_extractor(lowercase_ ,  return_tensors='''np'''   ).input_values
       a						:Dict										=	feature_extractor(lowercase_ ,  return_tensors='''np'''   ).input_values
       for enc_seq_a, enc_seq_a in zip(lowercase_ ,  lowercase_   ):
             self.assertTrue(np.allclose(lowercase_ ,  lowercase_ ,  atol=1e-3   )   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Tuple										=	self.feat_extract_tester.prepare_inputs_for_target()
       a						:List[Any]										=	self.feature_extraction_class(**self.feat_extract_dict   )
       a						:List[str]										=	feat_extract.model_input_names[0]

       a						:Dict										=	BatchFeature({input_name: speech_inputs}   )

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

       a						:List[Any]										=	self.feat_extract_tester.prepare_inputs_for_target(equal_length=lowercase_   )
       a						:List[str]										=	BatchFeature({input_name: speech_inputs} ,  tensor_type='''np'''   )

       a						:List[Any]										=	processed_features[input_name]

       if len(batch_features_input.shape   ) < 3:
             a						:List[Any]										=	batch_features_input[:, :, None]

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




 @require_torch
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:List[Any]										=	self.feat_extract_tester.prepare_inputs_for_target(equal_length=lowercase_   )
       a						:Union[str, Any]										=	self.feature_extraction_class(**self.feat_extract_dict   )
       a						:Union[str, Any]										=	feat_extract.model_input_names[0]

       a						:List[Any]										=	BatchFeature({input_name: speech_inputs} ,  tensor_type='''pt'''   )

       a						:Union[str, Any]										=	processed_features[input_name]

       if len(batch_features_input.shape   ) < 3:
             a						:List[Any]										=	batch_features_input[:, :, None]

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




 @require_torch
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Dict										=	self.feature_extraction_class(**self.feat_extract_dict   )
       a						:List[str]										=	self.feat_extract_tester.prepare_inputs_for_target()
       a						:List[str]										=	feat_extract.model_input_names[0]

       a						:Tuple										=	BatchFeature({input_name: speech_inputs}   )

       a						:str										=	feat_extract.num_mel_bins  # hack!

       a						:Optional[int]										=	feat_extract.pad(lowercase_ ,  padding='''longest''' ,  return_tensors='''np'''   )[input_name]
       a						:Dict										=	feat_extract.pad(lowercase_ ,  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   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Optional[Any]										=	self.feat_extract_dict
       a						:str										=	True
       a						:Optional[Any]										=	self.feature_extraction_class(**lowercase_   )
       a						:str										=	self.feat_extract_tester.prepare_inputs_for_target()
       a						:Any										=	[len(lowercase_   ) for x in speech_inputs]
       a						:List[str]										=	feat_extract.model_input_names[0]

       a						:Any										=	BatchFeature({input_name: speech_inputs}   )

       a						:Union[str, Any]										=	feat_extract.num_mel_bins  # hack!

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




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       a						:Dict										=	self.feat_extract_dict
       a						:Tuple										=	True
       a						:int										=	self.feature_extraction_class(**lowercase_   )
       a						:int										=	self.feat_extract_tester.prepare_inputs_for_target()
       a						:List[Any]										=	[len(lowercase_   ) for x in speech_inputs]
       a						:Dict										=	feat_extract.model_input_names[0]

       a						:List[str]										=	BatchFeature({input_name: speech_inputs}   )
       a						:List[Any]										=	min(lowercase_   )

       a						:str										=	feat_extract.num_mel_bins  # hack!

       a						:Union[str, Any]										=	feat_extract.pad(
           lowercase_ ,  padding='''max_length''' ,  max_length=lowercase_ ,  truncation=lowercase_ ,  return_tensors='''np'''   )
       self.assertIn('''attention_mask''' ,  lowercase_   )
       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]   )




 def 	SCREAMING_SNAKE_CASE__    (		self ,  _lowerCamelCase   ):
       from datasets import load_dataset

       a						:Tuple										=	load_dataset('''hf-internal-testing/librispeech_asr_dummy''' ,  '''clean''' ,  split='''validation'''   )
       # automatic decoding with librispeech
       a						:Optional[Any]										=	ds.sort('''id'''   ).select(range(lowercase_   )   )[:num_samples]["""audio"""]

       return [x["array"] for x in speech_samples]




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       # fmt: off
       a						:int										=	torch.tensor(
           [2.38_04e-03, 2.07_52e-03, 1.98_36e-03, 2.10_57e-03, 1.61_74e-03,
            3.05_18e-04, 9.15_53e-05, 3.35_69e-04, 9.76_56e-04, 1.83_11e-03,
            2.01_42e-03, 2.10_57e-03, 1.73_95e-03, 4.57_76e-04, -3.96_73e-04,
            4.57_76e-04, 1.00_71e-03, 9.15_53e-05, 4.88_28e-04, 1.15_97e-03,
            7.32_42e-04, 9.46_04e-04, 1.80_05e-03, 1.83_11e-03, 8.85_01e-04,
            4.27_25e-04, 4.88_28e-04, 7.32_42e-04, 1.09_86e-03, 2.10_57e-03]   )
       # fmt: on

       a						:List[str]										=	self._load_datasamples(1   )
       a						:str										=	SpeechTaFeatureExtractor()
       a						:int										=	feature_extractor(lowercase_ ,  return_tensors='''pt'''   ).input_values
       self.assertEquals(input_values.shape ,  (1, 9_3680)   )
       self.assertTrue(torch.allclose(input_values[0, :30] ,  lowercase_ ,  atol=1e-6   )   )




 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       # fmt: off
       a						:int										=	torch.tensor(
           [-2.6870, -3.0104, -3.1356, -3.5352, -3.0044, -3.0353, -3.4719, -3.6777,
            -3.1520, -2.9435, -2.6553, -2.8795, -2.9944, -2.5921, -3.0279, -3.0386,
            -3.0864, -3.1291, -3.2353, -2.7444, -2.6831, -2.7287, -3.1761, -3.1571,
            -3.2726, -3.0582, -3.1007, -3.4533, -3.4695, -3.0998]   )
       # fmt: on

       a						:str										=	self._load_datasamples(1   )
       a						:str										=	SpeechTaFeatureExtractor()
       a						:int										=	feature_extractor(audio_target=lowercase_ ,  return_tensors='''pt'''   ).input_values
       self.assertEquals(input_values.shape ,  (1, 366, 80)   )
       self.assertTrue(torch.allclose(input_values[0, 0, :30] ,  lowercase_ ,  atol=1e-4   )   )









from collections import OrderedDict
from typing import List, Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


snake_case    :   Union[str, Any]	    =					logging.get_logger(__name__)

snake_case    :   List[str]	    =					{
    '''google/efficientnet-b7''': '''https://huggingface.co/google/efficientnet-b7/resolve/main/config.json''',
}







class 		_snake_case  (				_snake_case							):
 SCREAMING_SNAKE_CASE__				=	'efficientnet'




 def __init__(		self ,  _lowerCamelCase = 3 ,  _lowerCamelCase = 600 ,  _lowerCamelCase = 2.0 ,  _lowerCamelCase = 3.1 ,  _lowerCamelCase = 8 ,  _lowerCamelCase = [3, 3, 5, 3, 5, 5, 3] ,  _lowerCamelCase = [32, 16, 24, 40, 80, 112, 192] ,  _lowerCamelCase = [16, 24, 40, 80, 112, 192, 320] ,  _lowerCamelCase = [] ,  _lowerCamelCase = [1, 2, 2, 2, 1, 2, 1] ,  _lowerCamelCase = [1, 2, 2, 3, 3, 4, 1] ,  _lowerCamelCase = [1, 6, 6, 6, 6, 6, 6] ,  _lowerCamelCase = 0.25 ,  _lowerCamelCase = "swish" ,  _lowerCamelCase = 2560 ,  _lowerCamelCase = "mean" ,  _lowerCamelCase = 0.02 ,  _lowerCamelCase = 0.001 ,  _lowerCamelCase = 0.99 ,  _lowerCamelCase = 0.5 ,  _lowerCamelCase = 0.2 ,  **_lowerCamelCase ,  ):
       super().__init__(**_lowerCamelCase   )

       a						:Optional[int]										=	num_channels
       a						:List[str]										=	image_size
       a						:int										=	width_coefficient
       a						:Optional[Any]										=	depth_coefficient
       a						:Any										=	depth_divisor
       a						:Any										=	kernel_sizes
       a						:Tuple										=	in_channels
       a						:Union[str, Any]										=	out_channels
       a						:Any										=	depthwise_padding
       a						:Any										=	strides
       a						:Optional[Any]										=	num_block_repeats
       a						:Tuple										=	expand_ratios
       a						:Dict										=	squeeze_expansion_ratio
       a						:int										=	hidden_act
       a						:Dict										=	hidden_dim
       a						:Tuple										=	pooling_type
       a						:Any										=	initializer_range
       a						:Tuple										=	batch_norm_eps
       a						:Optional[int]										=	batch_norm_momentum
       a						:List[Any]										=	dropout_rate
       a						:Optional[int]										=	drop_connect_rate
       a						:Tuple										=	sum(_lowerCamelCase   ) * 4







class 		_snake_case  (				_snake_case							):
 SCREAMING_SNAKE_CASE__				=	version.parse('1.11'							)




 @property
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return OrderedDict(
           [
               ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
           ]   )




 @property
 def 	SCREAMING_SNAKE_CASE__    (		self   ):
       return 1e-5





