



"""simple docstring"""






import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowerCAmelCase__              =							random.Random()

if is_torch_available():
   import torch






def 			snake_case_    ( A_   :						Tuple,							A_   :						List[Any]=1.0,							A_   :						Optional[Any]=None,							A_   :						Optional[int]=None		):


       '''simple docstring'''





       if rng is None:
              _lowerCamelCase		:							Dict            =					global_rng

       _lowerCamelCase		:							Any            =					[]
       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):




  def __init__(					self	:		int		,   __lowerCAmelCase	:		Tuple		,   __lowerCAmelCase	:		List[Any]=7		,   __lowerCAmelCase	:		int=4_0_0		,   __lowerCAmelCase	:		List[str]=2_0_0_0		,   __lowerCAmelCase	:		str=1		,   __lowerCAmelCase	:		Tuple=0.0		,   __lowerCAmelCase	:		Dict=1_6_0_0_0		,   __lowerCAmelCase	:		Dict=True		,   __lowerCAmelCase	:		Any=True		,   ):






         """simple docstring"""






         _lowerCamelCase		:							int            =					parent
         _lowerCamelCase		:							Optional[Any]            =					batch_size
         _lowerCamelCase		:							int            =					min_seq_length
         _lowerCamelCase		:							Any            =					max_seq_length
         _lowerCamelCase		:							int            =					(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         _lowerCamelCase		:							Dict            =					feature_size
         _lowerCamelCase		:							int            =					padding_value
         _lowerCamelCase		:							Tuple            =					sampling_rate
         _lowerCamelCase		:							Optional[int]            =					return_attention_mask
         _lowerCamelCase		:							List[str]            =					do_normalize




  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[int]						):






         """simple docstring"""






         return {
             "feature_size": self.feature_size,
             "padding_value": self.padding_value,
             "sampling_rate": self.sampling_rate,
             "return_attention_mask": self.return_attention_mask,
             "do_normalize": self.do_normalize,
         }




  def 		SCREAMING_SNAKE_CASE							(					self	:		Dict		,   __lowerCAmelCase	:		Any=False		,   __lowerCAmelCase	:		int=False						):






         """simple docstring"""






         def _flatten(__lowerCAmelCase	:		int						):
                return list(itertools.chain(*__lowerCAmelCase						)						)

         if equal_length:
                _lowerCamelCase		:							str            =					floats_list((self.batch_size, self.max_seq_length)						)
         else:
                # make sure that inputs increase in size
                _lowerCamelCase		:							Optional[Any]            =					[
                    _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:
                _lowerCamelCase		:							Dict            =					[np.asarray(__lowerCAmelCase						) for x in speech_inputs]

         return speech_inputs






@require_torch
@require_torchaudio
class 			__snake_case			(      _lowercase    ,	unittest.TestCase):
  snake_case__							:  List[str]         =		ASTFeatureExtractor




  def 		SCREAMING_SNAKE_CASE							(					self	:		Union[str, Any]						):






         """simple docstring"""






         _lowerCamelCase		:							Union[str, Any]            =					ASTFeatureExtractionTester(self						)




  def 		SCREAMING_SNAKE_CASE							(					self	:		Dict						):






         """simple docstring"""






         _lowerCamelCase		:							Tuple            =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
         # create three inputs of length 800, 1000, and 1200
         _lowerCamelCase		:							List[str]            =					[floats_list((1, x)						)[0] for x in range(8_0_0		,   1_4_0_0		,   2_0_0						)]
         _lowerCamelCase		:							Tuple            =					[np.asarray(__lowerCAmelCase						) for speech_input in speech_inputs]

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

         # Test batched
         _lowerCamelCase		:							Optional[Any]            =					feat_extract(__lowerCAmelCase		,   padding=__lowerCAmelCase		,   return_tensors='''np'''						).input_values
         _lowerCamelCase		:							Optional[Any]            =					feat_extract(__lowerCAmelCase		,   padding=__lowerCAmelCase		,   return_tensors='''np'''						).input_values
         for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase		,   __lowerCAmelCase						):
                self.assertTrue(np.allclose(__lowerCAmelCase		,   __lowerCAmelCase		,   atol=1E-3						)						)

         # Test 2-D numpy arrays are batched.
         _lowerCamelCase		:							str            =					[floats_list((1, x)						)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
         _lowerCamelCase		:							Any            =					np.asarray(__lowerCAmelCase						)
         _lowerCamelCase		:							Dict            =					feat_extract(__lowerCAmelCase		,   return_tensors='''np'''						).input_values
         _lowerCamelCase		:							List[Any]            =					feat_extract(__lowerCAmelCase		,   return_tensors='''np'''						).input_values
         for enc_seq_a, enc_seq_a in zip(__lowerCAmelCase		,   __lowerCAmelCase						):
                self.assertTrue(np.allclose(__lowerCAmelCase		,   __lowerCAmelCase		,   atol=1E-3						)						)




  @require_torch
  def 		SCREAMING_SNAKE_CASE							(					self	:		Union[str, Any]						):






         """simple docstring"""






         import torch

         _lowerCamelCase		:							Any            =					self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()						)
         _lowerCamelCase		:							Any            =					np.random.rand(1_0_0						).astype(np.floataa						)
         _lowerCamelCase		:							int            =					np_speech_inputs.tolist()

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




  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[Any]		,   __lowerCAmelCase	:		List[str]						):






         """simple docstring"""






         from datasets import load_dataset

         _lowerCamelCase		:							str            =					load_dataset('''hf-internal-testing/librispeech_asr_dummy'''		,   '''clean'''		,   split='''validation'''						)
         # automatic decoding with librispeech
         _lowerCamelCase		:							int            =					ds.sort('''id'''						).select(range(__lowerCAmelCase						)						)[:num_samples]['''audio''']

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




  @require_torch
  def 		SCREAMING_SNAKE_CASE							(					self	:		Optional[int]						):






         """simple docstring"""






         _lowerCamelCase		:							Optional[int]            =					torch.tensor(
             [-0.98_94, -1.27_76, -0.90_66, -1.27_76, -0.93_49, -1.26_09, -1.03_86, -1.27_76,
              -1.15_61, -1.27_76, -1.20_52, -1.27_23, -1.21_90, -1.21_32, -1.27_76, -1.11_33,
              -1.19_53, -1.13_43, -1.15_84, -1.22_03, -1.17_70, -1.24_74, -1.23_81, -1.19_36,
              -0.92_70, -0.83_17, -0.80_49, -0.77_06, -0.75_65, -0.78_69]						)
         # fmt: on

         _lowerCamelCase		:							Optional[Any]            =					self._load_datasamples(1						)
         _lowerCamelCase		:							int            =					ASTFeatureExtractor()
         _lowerCamelCase		:							Tuple            =					feature_extractor(__lowerCAmelCase		,   return_tensors='''pt'''						).input_values
         self.assertEquals(input_values.shape		,   (1, 1_0_2_4, 1_2_8)						)
         self.assertTrue(torch.allclose(input_values[0, 0, :3_0]		,   __lowerCAmelCase		,   atol=1E-4						)						)






A				:       Any      =  '\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n'

A				:       Optional[int]      =  [{'type': 'code', 'content': INSTALL_CONTENT}]
A				:       Optional[int]      =  {
    '{processor_class}': 'FakeProcessorClass',
    '{model_class}': 'FakeModelClass',
    '{object_class}': 'FakeObjectClass',
}





