





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

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


if TYPE_CHECKING:
      from ...feature_extraction_utils import FeatureExtractionMixin
      from ...tokenization_utils_base import PreTrainedTokenizerBase
      from ...utils import TensorType

__UpperCAmelCase	:       List[Any]    	=							logging.get_logger(__name__)

__UpperCAmelCase	:       Optional[Any]    	=							{
    'openai/whisper-base': 'https://huggingface.co/openai/whisper-base/resolve/main/config.json',
}

# fmt: off
__UpperCAmelCase	:       Optional[Any]    	=							[
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
    705, 796, 930, 1_058, 1_220, 1_267, 1_279, 1_303, 1_343, 1_377,
    1_391, 1_635, 1_782, 1_875, 2_162, 2_361, 2_488, 3_467, 4_008, 4_211,
    4_600, 4_808, 5_299, 5_855, 6_329, 7_203, 9_609, 9_959, 10_563, 10_786,
    11_420, 11_709, 11_907, 13_163, 13_697, 13_700, 14_808, 15_306, 16_410, 16_791,
    17_992, 19_203, 19_510, 20_724, 22_305, 22_935, 27_007, 30_109, 30_420, 33_409,
    34_949, 40_283, 40_493, 40_549, 47_282, 49_146, 50_257, 50_359, 50_360, 50_361
]
__UpperCAmelCase	:       List[str]    	=							[
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
    893, 902, 918, 922, 931, 1_350, 1_853, 1_982, 2_460, 2_627,
    3_246, 3_253, 3_268, 3_536, 3_846, 3_961, 4_183, 4_667, 6_585, 6_647,
    7_273, 9_061, 9_383, 10_428, 10_929, 11_938, 12_033, 12_331, 12_562, 13_793,
    14_157, 14_635, 15_265, 15_618, 16_553, 16_604, 18_362, 18_956, 20_075, 21_675,
    22_520, 26_130, 26_161, 26_435, 28_279, 29_464, 31_650, 32_302, 32_470, 36_865,
    42_863, 47_425, 49_870, 50_254, 50_258, 50_360, 50_361, 50_362
]







class    __snake_case	(							_A      ):





       '''simple docstring'''







       lowerCAmelCase__						=					"""whisper"""
       lowerCAmelCase__						=					["""past_key_values"""]
       lowerCAmelCase__						=					{"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




       def __init__(  self			:   Optional[Any]							,    A			:   Optional[Any]=51_865							,    A			:   Tuple=80							,    A			:   Optional[Any]=6							,    A			:   Dict=4							,    A			:   List[Any]=6							,    A			:   Tuple=4							,    A			:   Any=1_536							,    A			:   Optional[int]=1_536							,    A			:   Any=0.0							,    A			:   List[str]=0.0							,    A			:   List[str]=50_257							,    A			:   Optional[int]=True							,    A			:   int=True							,    A			:   List[Any]="gelu"							,    A			:   List[Any]=256							,    A			:   List[Any]=0.0							,    A			:   int=0.0							,    A			:   Any=0.0							,    A			:   Any=0.02							,    A			:   Dict=False							,    A			:   int=1_500							,    A			:   Optional[Any]=448							,    A			:   Tuple=50_256							,    A			:   Optional[int]=50_256							,    A			:   Any=50_256							,    A			:   Optional[Any]=None							,    A			:   int=[220, 50_256]							,    A			:   Tuple=False							,    A			:   Dict=256							,    A			:   List[Any]=False							,    A			:   Optional[Any]=0.05							,    A			:   List[str]=10							,    A			:   List[Any]=2							,    A			:   Union[str, Any]=0.0							,    A			:   Optional[int]=10							,    A			:   str=0							,    A			:   Any=7							,    **A			:   List[Any]							,    ):
         __snake_case:						str			  =						vocab_size
         __snake_case:						Union[str, Any]			  =						num_mel_bins
         __snake_case:						Tuple			  =						d_model
         __snake_case:						List[str]			  =						encoder_layers
         __snake_case:						Union[str, Any]			  =						encoder_attention_heads
         __snake_case:						Tuple			  =						decoder_layers
         __snake_case:						str			  =						decoder_attention_heads
         __snake_case:						int			  =						decoder_ffn_dim
         __snake_case:						Optional[Any]			  =						encoder_ffn_dim
         __snake_case:						List[str]			  =						dropout
         __snake_case:						Dict			  =						attention_dropout
         __snake_case:						str			  =						activation_dropout
         __snake_case:						Optional[int]			  =						activation_function
         __snake_case:						Any			  =						init_std
         __snake_case:						Dict			  =						encoder_layerdrop
         __snake_case:						str			  =						decoder_layerdrop
         __snake_case:						List[str]			  =						use_cache
         __snake_case:						Any			  =						encoder_layers
         __snake_case:						Optional[int]			  =						scale_embedding  # scale factor will be sqrt(d_model) if True
         __snake_case:						Dict			  =						max_source_positions
         __snake_case:						Any			  =						max_target_positions

         # Audio Classification-specific parameters. Feel free to ignore for other classes.
         __snake_case:						Union[str, Any]			  =						classifier_proj_size
         __snake_case:						str			  =						use_weighted_layer_sum

         # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
         __snake_case:						int			  =						apply_spec_augment
         __snake_case:						Tuple			  =						mask_time_prob
         __snake_case:						Optional[Any]			  =						mask_time_length
         __snake_case:						Optional[Any]			  =						mask_time_min_masks
         __snake_case:						str			  =						mask_feature_prob
         __snake_case:						Dict			  =						mask_feature_length
         __snake_case:						Tuple			  =						mask_feature_min_masks

         __snake_case:						Union[str, Any]			  =						median_filter_width

         super().__init__(
             pad_token_id=__SCREAMING_SNAKE_CASE							,    bos_token_id=__SCREAMING_SNAKE_CASE							,    eos_token_id=__SCREAMING_SNAKE_CASE							,    is_encoder_decoder=__SCREAMING_SNAKE_CASE							,    decoder_start_token_id=__SCREAMING_SNAKE_CASE							,    suppress_tokens=__SCREAMING_SNAKE_CASE							,    begin_suppress_tokens=__SCREAMING_SNAKE_CASE							,    **__SCREAMING_SNAKE_CASE							,    )







class    __snake_case	(							_A      ):





       '''simple docstring'''







       @property
       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         __snake_case:						List[Any]			  =						OrderedDict(
             [
                 ("""input_features""", {0: """batch""", 1: """feature_size""", 2: """encoder_sequence"""}),
             ]		)
         if self.use_past:
           __snake_case:						List[Any]			  =						{0: """batch"""}
         else:
           __snake_case:						Dict			  =						{0: """batch""", 1: """decoder_sequence"""}

         if self.use_past:
           self.fill_with_past_key_values_(__SCREAMING_SNAKE_CASE							,    direction="""inputs"""		)

         return common_inputs




       def 							UpperCAmelCase__			(  self			:   List[Any]							,    A			:   Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"]							,    A			:   int = -1							,    A			:   int = -1							,    A			:   bool = False							,    A			:   Optional["TensorType"] = None							,    A			:   int = 22_050							,    A			:   float = 5.0							,    A			:   int = 220							,    ):
         __snake_case:						List[str]			  =						OrderedDict()
         __snake_case:						Union[str, Any]			  =						OnnxConfig.generate_dummy_inputs(
             self							,    preprocessor=preprocessor.feature_extractor							,    batch_size=__SCREAMING_SNAKE_CASE							,    framework=__SCREAMING_SNAKE_CASE							,    sampling_rate=__SCREAMING_SNAKE_CASE							,    time_duration=__SCREAMING_SNAKE_CASE							,    frequency=__SCREAMING_SNAKE_CASE							,    )
         __snake_case:						int			  =						encoder_inputs["""input_features"""].shape[2]
         __snake_case:						Any			  =						encoder_sequence_length // 2 if self.use_past else seq_length

         __snake_case:						int			  =						super().generate_dummy_inputs(
             preprocessor.tokenizer							,    __SCREAMING_SNAKE_CASE							,    __SCREAMING_SNAKE_CASE							,    __SCREAMING_SNAKE_CASE							,    __SCREAMING_SNAKE_CASE		)

         __snake_case:						List[Any]			  =						encoder_inputs.pop("""input_features"""		)
         __snake_case:						str			  =						decoder_inputs.pop("""decoder_input_ids"""		)

         if "past_key_values" in decoder_inputs:
           __snake_case:						Any			  =						decoder_inputs.pop("""past_key_values"""		)

         return dummy_inputs






       @property
       def 							UpperCAmelCase__			(  self			:   str		):
         return 1E-3








import itertools
import os
import random
import tempfile
import unittest

import numpy as np

from transformers import TvltFeatureExtractor, is_datasets_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_torch_available():
      import torch

if is_datasets_available():
      from datasets import load_dataset

__UpperCAmelCase	:       Any    	=							random.Random()







def       A__							(   SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=1.0 , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None)       ->   Any:
  if rng is None:
    __snake_case:						Dict			  =						global_rng

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

  return values







class    __snake_case	(							unittest.TestCase      ):





       '''simple docstring'''







       def __init__(  self			:   int							,    A			:   List[str]							,    A			:   List[Any]=7							,    A			:   Optional[int]=400							,    A			:   List[Any]=2_000							,    A			:   Dict=2_048							,    A			:   Tuple=128							,    A			:   List[Any]=1							,    A			:   Tuple=512							,    A			:   str=30							,    A			:   Optional[Any]=44_100							,    ):
         __snake_case:						Dict			  =						parent
         __snake_case:						Optional[Any]			  =						batch_size
         __snake_case:						Optional[int]			  =						min_seq_length
         __snake_case:						Optional[Any]			  =						max_seq_length
         __snake_case:						List[str]			  =						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         __snake_case:						Any			  =						spectrogram_length
         __snake_case:						Any			  =						feature_size
         __snake_case:						Union[str, Any]			  =						num_audio_channels
         __snake_case:						Any			  =						hop_length
         __snake_case:						List[str]			  =						chunk_length
         __snake_case:						Any			  =						sampling_rate




       def 							UpperCAmelCase__			(  self			:   List[Any]		):
         return {
             "spectrogram_length": self.spectrogram_length,
             "feature_size": self.feature_size,
             "num_audio_channels": self.num_audio_channels,
             "hop_length": self.hop_length,
             "chunk_length": self.chunk_length,
             "sampling_rate": self.sampling_rate,
         }






       def 							UpperCAmelCase__			(  self			:   List[str]							,    A			:   str=False							,    A			:   int=False		):
         def _flatten(A			:   Dict		):
           return list(itertools.chain(*A		)		)

         if equal_length:
           __snake_case:						List[str]			  =						[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:						int			  =						[
               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:						Tuple			  =						[np.asarray(A		) for x in speech_inputs]
         return speech_inputs







@require_torch
@require_torchaudio
class    __snake_case	(							__lowerCamelCase       ,      unittest.TestCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					TvltFeatureExtractor




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         __snake_case:						str			  =						TvltFeatureExtractionTester(self		)




       def 							UpperCAmelCase__			(  self			:   int		):
         __snake_case:						Tuple			  =						self.feature_extraction_class(**self.feat_extract_dict		)
         self.assertTrue(hasattr(A							,    """spectrogram_length"""		)		)
         self.assertTrue(hasattr(A							,    """feature_size"""		)		)
         self.assertTrue(hasattr(A							,    """num_audio_channels"""		)		)
         self.assertTrue(hasattr(A							,    """hop_length"""		)		)
         self.assertTrue(hasattr(A							,    """chunk_length"""		)		)
         self.assertTrue(hasattr(A							,    """sampling_rate"""		)		)




       def 							UpperCAmelCase__			(  self			:   Any		):
         __snake_case:						Optional[Any]			  =						self.feature_extraction_class(**self.feat_extract_dict		)

         with tempfile.TemporaryDirectory() as tmpdirname:
           __snake_case:						Tuple			  =						feat_extract_first.save_pretrained(A		)[0]
           check_json_file_has_correct_format(A		)
           __snake_case:						int			  =						self.feature_extraction_class.from_pretrained(A		)

         __snake_case:						List[str]			  =						feat_extract_first.to_dict()
         __snake_case:						str			  =						feat_extract_second.to_dict()
         __snake_case:						List[Any]			  =						dict_first.pop("""mel_filters"""		)
         __snake_case:						str			  =						dict_second.pop("""mel_filters"""		)
         self.assertTrue(np.allclose(A							,    A		)		)
         self.assertEqual(A							,    A		)




       def 							UpperCAmelCase__			(  self			:   Optional[Any]		):
         __snake_case:						str			  =						self.feature_extraction_class(**self.feat_extract_dict		)

         with tempfile.TemporaryDirectory() as tmpdirname:
           __snake_case:						str			  =						os.path.join(A							,    """feat_extract.json"""		)
           feat_extract_first.to_json_file(A		)
           __snake_case:						List[Any]			  =						self.feature_extraction_class.from_json_file(A		)

         __snake_case:						Dict			  =						feat_extract_first.to_dict()
         __snake_case:						Any			  =						feat_extract_second.to_dict()
         __snake_case:						int			  =						dict_first.pop("""mel_filters"""		)
         __snake_case:						int			  =						dict_second.pop("""mel_filters"""		)
         self.assertTrue(np.allclose(A							,    A		)		)
         self.assertEqual(A							,    A		)




       def 							UpperCAmelCase__			(  self			:   Any		):
         # Initialize feature_extractor
         __snake_case:						Union[str, Any]			  =						self.feature_extraction_class(**self.feat_extract_dict		)

         # create three inputs of length 800, 1000, and 1200
         __snake_case:						Dict			  =						[floats_list((1, x)		)[0] for x in range(800							,    1_400							,    200		)]
         __snake_case:						str			  =						[np.asarray(A		) for speech_input in speech_inputs]

         # Test not batched input
         __snake_case:						int			  =						feature_extractor(np_speech_inputs[0]							,    return_tensors="""np"""							,    sampling_rate=44_100		).audio_values

         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

         # Test batched
         __snake_case:						Optional[int]			  =						feature_extractor(A							,    return_tensors="""np"""							,    sampling_rate=44_100		).audio_values

         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

         # Test audio masking
         __snake_case:						Union[str, Any]			  =						feature_extractor(
             A							,    return_tensors="""np"""							,    sampling_rate=44_100							,    mask_audio=A		).audio_values

         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)

         # Test 2-D numpy arrays are batched.
         __snake_case:						Any			  =						[floats_list((1, x)		)[0] for x in (800, 800, 800)]
         __snake_case:						Union[str, Any]			  =						np.asarray(A		)
         __snake_case:						List[Any]			  =						feature_extractor(A							,    return_tensors="""np"""							,    sampling_rate=44_100		).audio_values
         self.assertTrue(encoded_audios.ndim == 4		)
         self.assertTrue(encoded_audios.shape[-1] == feature_extractor.feature_size		)
         self.assertTrue(encoded_audios.shape[-2] <= feature_extractor.spectrogram_length		)
         self.assertTrue(encoded_audios.shape[-3] == feature_extractor.num_channels		)




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]							,    A			:   List[str]		):
         __snake_case:						Tuple			  =						load_dataset("""hf-internal-testing/librispeech_asr_dummy"""							,    """clean"""							,    split="""validation"""		)
         # automatic decoding with librispeech
         __snake_case:						List[Any]			  =						ds.sort("""id"""		).select(range(A		)		)[:num_samples]["""audio"""]

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






       def 							UpperCAmelCase__			(  self			:   Optional[int]		):
         __snake_case:						Dict			  =						self._load_datasamples(1		)
         __snake_case:						Optional[int]			  =						TvltFeatureExtractor()
         __snake_case:						Optional[Any]			  =						feature_extractor(A							,    return_tensors="""pt"""		).audio_values

         self.assertEquals(audio_values.shape							,    (1, 1, 192, 128)		)

         __snake_case:						str			  =						torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]]		)
         self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]							,    A							,    atol=1E-4		)		)






