




'''simple docstring'''





import itertools
import os
import random
import tempfile
import unittest

import numpy as np
from datasets import load_dataset

from transformers import is_speech_available
from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
   from transformers import WhisperFeatureExtractor

if is_torch_available():
   import torch

UpperCamelCase_		:     Optional[Any]          =		random.Random()





def       __a      (  _UpperCamelCase:       List[str]   ,		_UpperCamelCase:       Dict=1.0   ,		_UpperCamelCase:       List[str]=None   ,		_UpperCamelCase:       Any=None       )		->					Dict:

     """simple docstring"""




     if rng is None:
          _snake_case				= global_rng

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

     return values

@require_torch
@require_torchaudio
class   _a							(		unittest.TestCase				):






     def __init__(					self   ,_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE=7   ,_SCREAMING_SNAKE_CASE=400   ,_SCREAMING_SNAKE_CASE=2_000   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=160   ,_SCREAMING_SNAKE_CASE=8   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=4_000   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=True   ,)				->     List[Any]:
          _snake_case				= parent
          _snake_case				= batch_size
          _snake_case				= min_seq_length
          _snake_case				= max_seq_length
          _snake_case				= (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
          _snake_case				= padding_value
          _snake_case				= sampling_rate
          _snake_case				= return_attention_mask
          _snake_case				= do_normalize
          _snake_case				= feature_size
          _snake_case				= chunk_length
          _snake_case				= hop_length






     def 							_lowercase      (					self       )				->     List[str]:
          return {
              "feature_size": self.feature_size,
              "hop_length": self.hop_length,
              "chunk_length": self.chunk_length,
              "padding_value": self.padding_value,
              "sampling_rate": self.sampling_rate,
              "return_attention_mask": self.return_attention_mask,
              "do_normalize": self.do_normalize,
          }






     def 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=False       )				->     List[str]:
          def _flatten(_SCREAMING_SNAKE_CASE       ):
               return list(itertools.chain(*_SCREAMING_SNAKE_CASE       )       )

          if equal_length:
               _snake_case				= [floats_list((self.max_seq_length, self.feature_size)       ) for _ in range(self.batch_size       )]
          else:
               # make sure that inputs increase in size
               _snake_case				= [
                   floats_list((x, self.feature_size)       )
                   for x in range(self.min_seq_length   ,self.max_seq_length   ,self.seq_length_diff       )
               ]
          if numpify:
               _snake_case				= [np.asarray(_SCREAMING_SNAKE_CASE       ) for x in speech_inputs]
          return speech_inputs







@require_torch
@require_torchaudio
class   _a							(		__lowerCAmelCase   ,   unittest.TestCase				):
     SCREAMING_SNAKE_CASE_				:       Union[str, Any]       							=		WhisperFeatureExtractor if is_speech_available() else None






     def 							_lowercase      (					self       )				->     int:
          _snake_case				= WhisperFeatureExtractionTester(self       )






     def 							_lowercase      (					self       )				->     List[Any]:
          _snake_case				= self.feature_extraction_class(**self.feat_extract_dict       )

          with tempfile.TemporaryDirectory() as tmpdirname:
               _snake_case				= feat_extract_first.save_pretrained(_SCREAMING_SNAKE_CASE       )[0]
               check_json_file_has_correct_format(_SCREAMING_SNAKE_CASE       )
               _snake_case				= self.feature_extraction_class.from_pretrained(_SCREAMING_SNAKE_CASE       )

          _snake_case				= feat_extract_first.to_dict()
          _snake_case				= feat_extract_second.to_dict()
          _snake_case				= feat_extract_first.mel_filters
          _snake_case				= feat_extract_second.mel_filters
          self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       )       )
          self.assertEqual(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       )






     def 							_lowercase      (					self       )				->     Tuple:
          _snake_case				= self.feature_extraction_class(**self.feat_extract_dict       )

          with tempfile.TemporaryDirectory() as tmpdirname:
               _snake_case				= os.path.join(_SCREAMING_SNAKE_CASE   ,"feat_extract.json"       )
               feat_extract_first.to_json_file(_SCREAMING_SNAKE_CASE       )
               _snake_case				= self.feature_extraction_class.from_json_file(_SCREAMING_SNAKE_CASE       )

          _snake_case				= feat_extract_first.to_dict()
          _snake_case				= feat_extract_second.to_dict()
          _snake_case				= feat_extract_first.mel_filters
          _snake_case				= feat_extract_second.mel_filters
          self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       )       )
          self.assertEqual(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       )






     def 							_lowercase      (					self       )				->     Any:
          # Tests that all call wrap to encode_plus and batch_encode_plus
          _snake_case				= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
          # create three inputs of length 800, 1000, and 1200
          _snake_case				= [floats_list((1, x)       )[0] for x in range(800   ,1_400   ,200       )]
          _snake_case				= [np.asarray(_SCREAMING_SNAKE_CASE       ) for speech_input in speech_inputs]

          # Test feature size
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,padding="max_length"   ,return_tensors="np"       ).input_features
          self.assertTrue(input_features.ndim == 3       )
          self.assertTrue(input_features.shape[-1] == feature_extractor.nb_max_frames       )
          self.assertTrue(input_features.shape[-2] == feature_extractor.feature_size       )

          # Test not batched input
          _snake_case				= feature_extractor(speech_inputs[0]   ,return_tensors="np"       ).input_features
          _snake_case				= feature_extractor(np_speech_inputs[0]   ,return_tensors="np"       ).input_features
          self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE   ,atol=1e-3       )       )

          # Test batched
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="np"       ).input_features
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="np"       ).input_features
          for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ):
               self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE   ,atol=1e-3       )       )

          # Test 2-D numpy arrays are batched.
          _snake_case				= [floats_list((1, x)       )[0] for x in (800, 800, 800)]
          _snake_case				= np.asarray(_SCREAMING_SNAKE_CASE       )
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="np"       ).input_features
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="np"       ).input_features
          for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ):
               self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE   ,atol=1e-3       )       )

          # Test truncation required
          _snake_case				= [floats_list((1, x)       )[0] for x in range(200   ,(feature_extractor.n_samples + 500)   ,200       )]
          _snake_case				= [np.asarray(_SCREAMING_SNAKE_CASE       ) for speech_input in speech_inputs]

          _snake_case				= [x[: feature_extractor.n_samples] for x in speech_inputs]
          _snake_case				= [np.asarray(_SCREAMING_SNAKE_CASE       ) for speech_input in speech_inputs_truncated]

          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="np"       ).input_features
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="np"       ).input_features
          for enc_seq_a, enc_seq_a in zip(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE       ):
               self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE   ,_SCREAMING_SNAKE_CASE   ,atol=1e-3       )       )






     def 							_lowercase      (					self       )				->     List[str]:
          import torch

          _snake_case				= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
          _snake_case				= np.random.rand(100   ,32       ).astype(np.floataa       )
          _snake_case				= np_speech_inputs.tolist()

          for inputs in [py_speech_inputs, np_speech_inputs]:
               _snake_case				= feature_extractor.pad([{"input_features": inputs}]   ,return_tensors="np"       )
               self.assertTrue(np_processed.input_features.dtype == np.floataa       )
               _snake_case				= feature_extractor.pad([{"input_features": inputs}]   ,return_tensors="pt"       )
               self.assertTrue(pt_processed.input_features.dtype == torch.floataa       )






     def 							_lowercase      (					self   ,_SCREAMING_SNAKE_CASE       )				->     List[str]:
          _snake_case				= load_dataset("hf-internal-testing/librispeech_asr_dummy"   ,"clean"   ,split="validation"       )
          # automatic decoding with librispeech
          _snake_case				= ds.sort("id"       ).select(range(_SCREAMING_SNAKE_CASE       )       )[:num_samples]["audio"]

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






     def 							_lowercase      (					self       )				->     Optional[int]:
          # fmt: off
          _snake_case				= torch.tensor(
              [
                  0.1_1_9_3, -0.0_9_4_6, -0.1_0_9_8, -0.0_1_9_6, 0.0_2_2_5, -0.0_6_9_0, -0.1_7_3_6, 0.0_9_5_1,
                  0.0_9_7_1, -0.0_8_1_7, -0.0_7_0_2, 0.0_1_6_2, 0.0_2_6_0, 0.0_0_1_7, -0.0_1_9_2, -0.1_6_7_8,
                  0.0_7_0_9, -0.1_8_6_7, -0.0_6_5_5, -0.0_2_7_4, -0.0_2_3_4, -0.1_8_8_4, -0.0_5_1_6, -0.0_5_5_4,
                  -0.0_2_7_4, -0.1_4_2_5, -0.1_4_2_3, 0.0_8_3_7, 0.0_3_7_7, -0.0_8_5_4
              ]       )
          # fmt: on

          _snake_case				= self._load_datasamples(1       )
          _snake_case				= WhisperFeatureExtractor()
          _snake_case				= feature_extractor(_SCREAMING_SNAKE_CASE   ,return_tensors="pt"       ).input_features
          self.assertEqual(input_features.shape   ,(1, 80, 3_000)       )
          self.assertTrue(torch.allclose(input_features[0, 0, :30]   ,_SCREAMING_SNAKE_CASE   ,atol=1e-4       )       )






     def 							_lowercase      (					self       )				->     Tuple:
          _snake_case				= self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
          _snake_case				= self._load_datasamples(1       )[0]
          _snake_case				= ((audio - audio.min()) / (audio.max() - audio.min())) * 65_535  # Rescale to [0, 65535] to show issue
          _snake_case				= feat_extract.zero_mean_unit_var_norm([audio]   ,attention_mask=_SCREAMING_SNAKE_CASE       )[0]

          self.assertTrue(np.all(np.mean(_SCREAMING_SNAKE_CASE       ) < 1e-3       )       )
          self.assertTrue(np.all(np.abs(np.var(_SCREAMING_SNAKE_CASE       ) - 1       ) < 1e-3       )       )








'''simple docstring'''





import functools
import operator

from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_		:     Optional[Any]          =		logging.get_logger(__name__)

UpperCamelCase_		:     Any          =		{
    '''microsoft/unispeech-sat-base-100h-libri-ft''': (
        '''https://huggingface.co/microsoft/unispeech-sat-base-100h-libri-ft/resolve/main/config.json'''
    ),
    # See all UniSpeechSat models at https://huggingface.co/models?filter=unispeech_sat
}

class   _a							(		__lowerCAmelCase				):
     SCREAMING_SNAKE_CASE_				:       str       							=		"""unispeech-sat"""






     def __init__(					self   ,_SCREAMING_SNAKE_CASE=32   ,_SCREAMING_SNAKE_CASE=768   ,_SCREAMING_SNAKE_CASE=12   ,_SCREAMING_SNAKE_CASE=12   ,_SCREAMING_SNAKE_CASE=3_072   ,_SCREAMING_SNAKE_CASE="gelu"   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=0.0_2   ,_SCREAMING_SNAKE_CASE=1e-5   ,_SCREAMING_SNAKE_CASE="group"   ,_SCREAMING_SNAKE_CASE="gelu"   ,_SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 512, 512, 512)   ,_SCREAMING_SNAKE_CASE=(5, 2, 2, 2, 2, 2, 2)   ,_SCREAMING_SNAKE_CASE=(10, 3, 3, 3, 3, 2, 2)   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=128   ,_SCREAMING_SNAKE_CASE=16   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=True   ,_SCREAMING_SNAKE_CASE=0.0_5   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=0.0   ,_SCREAMING_SNAKE_CASE=10   ,_SCREAMING_SNAKE_CASE=0   ,_SCREAMING_SNAKE_CASE=320   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE=100   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=0.1   ,_SCREAMING_SNAKE_CASE="mean"   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=False   ,_SCREAMING_SNAKE_CASE=256   ,_SCREAMING_SNAKE_CASE=(512, 512, 512, 512, 1_500)   ,_SCREAMING_SNAKE_CASE=(5, 3, 3, 1, 1)   ,_SCREAMING_SNAKE_CASE=(1, 2, 3, 1, 1)   ,_SCREAMING_SNAKE_CASE=512   ,_SCREAMING_SNAKE_CASE=0   ,_SCREAMING_SNAKE_CASE=1   ,_SCREAMING_SNAKE_CASE=2   ,_SCREAMING_SNAKE_CASE=504   ,**_SCREAMING_SNAKE_CASE   ,)				->     Any:
          super().__init__(**_SCREAMING_SNAKE_CASE   ,pad_token_id=_SCREAMING_SNAKE_CASE   ,bos_token_id=_SCREAMING_SNAKE_CASE   ,eos_token_id=_SCREAMING_SNAKE_CASE       )
          _snake_case				= hidden_size
          _snake_case				= feat_extract_norm
          _snake_case				= feat_extract_activation
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= conv_bias
          _snake_case				= num_conv_pos_embeddings
          _snake_case				= num_conv_pos_embedding_groups
          _snake_case				= len(self.conv_dim       )
          _snake_case				= num_hidden_layers
          _snake_case				= intermediate_size
          _snake_case				= hidden_act
          _snake_case				= num_attention_heads
          _snake_case				= hidden_dropout
          _snake_case				= attention_dropout
          _snake_case				= activation_dropout
          _snake_case				= feat_proj_dropout
          _snake_case				= final_dropout
          _snake_case				= layerdrop
          _snake_case				= layer_norm_eps
          _snake_case				= initializer_range
          _snake_case				= vocab_size
          _snake_case				= num_clusters
          _snake_case				= do_stable_layer_norm
          _snake_case				= use_weighted_layer_sum

          if (
              (len(self.conv_stride       ) != self.num_feat_extract_layers)
              or (len(self.conv_kernel       ) != self.num_feat_extract_layers)
              or (len(self.conv_dim       ) != self.num_feat_extract_layers)
          ):
               raise ValueError(
                   "Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =="
                   " `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ="
                   f""" {len(self.conv_dim       )}`, `len(config.conv_stride) = {len(self.conv_stride       )}`,"""
                   f""" `len(config.conv_kernel) = {len(self.conv_kernel       )}`."""       )

          # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
          _snake_case				= apply_spec_augment
          _snake_case				= mask_time_prob
          _snake_case				= mask_time_length
          _snake_case				= mask_time_min_masks
          _snake_case				= mask_feature_prob
          _snake_case				= mask_feature_length
          _snake_case				= mask_feature_min_masks

          # parameters for pretraining with codevector quantized representations
          _snake_case				= num_codevectors_per_group
          _snake_case				= num_codevector_groups
          _snake_case				= contrastive_logits_temperature
          _snake_case				= feat_quantizer_dropout
          _snake_case				= num_negatives
          _snake_case				= codevector_dim
          _snake_case				= proj_codevector_dim
          _snake_case				= diversity_loss_weight

          # ctc loss
          _snake_case				= ctc_loss_reduction
          _snake_case				= ctc_zero_infinity

          # SequenceClassification-specific parameter. Feel free to ignore for other classes.
          _snake_case				= classifier_proj_size

          # XVector-specific parameters. Feel free to ignore for other classes.
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= list(_SCREAMING_SNAKE_CASE       )
          _snake_case				= xvector_output_dim






     @property
     def 							_lowercase      (					self       )				->     List[str]:
          return functools.reduce(operator.mul   ,self.conv_stride   ,1       )


