'''simple docstring'''




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


__UpperCAmelCase					=random.Random()






def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__=1.0							,    UpperCamelCase__=None							,    UpperCamelCase__=None							)      ->       Dict:
    if rng is None:
        __lowerCamelCase            =    global_rng

    __lowerCamelCase            =    []
    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        a__ (  unittest.TestCase					):






     def __init__(					self						:						Optional[int]    ,							a						:						int    ,							a						:						List[Any]=7    ,							a						:						Any=4_00    ,							a						:						Dict=20_00    ,							a						:						Tuple=1    ,							a						:						Tuple=0.0    ,							a						:						Optional[Any]=1_60_00    ,							a						:						Tuple=True    ,							a						:						Optional[Any]=80    ,							a						:						List[str]=16    ,							a						:						Union[str, Any]=64    ,							a						:						Dict="hann_window"    ,							a						:						Optional[Any]=80    ,							a						:						Optional[Any]=76_00    ,							a						:						Any=1e-1_0    ,							a						:						Dict=True    ,							):





         """simple docstring"""



         __lowerCamelCase            =    parent
         __lowerCamelCase            =    batch_size
         __lowerCamelCase            =    min_seq_length
         __lowerCamelCase            =    max_seq_length
         __lowerCamelCase            =    (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
         __lowerCamelCase            =    feature_size
         __lowerCamelCase            =    padding_value
         __lowerCamelCase            =    sampling_rate
         __lowerCamelCase            =    do_normalize
         __lowerCamelCase            =    num_mel_bins
         __lowerCamelCase            =    hop_length
         __lowerCamelCase            =    win_length
         __lowerCamelCase            =    win_function
         __lowerCamelCase            =    fmin
         __lowerCamelCase            =    fmax
         __lowerCamelCase            =    mel_floor
         __lowerCamelCase            =    return_attention_mask






     def   SCREAMING_SNAKE_CASE__  (					self						:						Any       ):





         """simple docstring"""



         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						:						int    ,							a						:						Dict=False    ,							a						:						int=False       ):





         """simple docstring"""



         def _flatten(a						:						Dict       ):
             return list(itertools.chain(*a       )       )

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

         return speech_inputs






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Tuple=False    ,							a						:						Any=False       ):





         """simple docstring"""



         if equal_length:
             __lowerCamelCase            =    [floats_list((self.max_seq_length, self.num_mel_bins)       ) for _ in range(self.batch_size       )]
         else:
             # make sure that inputs increase in size
             __lowerCamelCase            =    [
                 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:
             __lowerCamelCase            =    [np.asarray(a       ) for x in speech_inputs]

         return speech_inputs




@require_torch
class        a__ (  UpperCAmelCase__				,  unittest.TestCase					):
     lowerCamelCase    :	Optional[int]				=SpeechTaFeatureExtractor






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    SpeechTaFeatureExtractionTester(self       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple    ,							a						:						Optional[int]       ):





         """simple docstring"""



         self.assertTrue(np.all(np.mean(a    ,							axis=0       ) < 1e-3       )       )
         self.assertTrue(np.all(np.abs(np.var(a    ,							axis=0       ) - 1       ) < 1e-3       )       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         # create three inputs of length 800, 1000, and 1200
         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in range(8_00    ,							14_00    ,							2_00       )]
         __lowerCamelCase            =    [np.asarray(a       ) for speech_input in speech_inputs]

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

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						int       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in range(8_00    ,							14_00    ,							2_00       )]

         __lowerCamelCase            =    ['''longest''', '''max_length''', '''do_not_pad''']
         __lowerCamelCase            =    [None, 16_00, None]
         for max_length, padding in zip(a    ,							a       ):
             __lowerCamelCase            =    feat_extract(a    ,							padding=a    ,							max_length=a    ,							return_tensors='''np'''       )
             __lowerCamelCase            =    processed.input_values

             self._check_zero_mean_unit_variance(input_values[0][:8_00]       )
             self.assertTrue(input_values[0][8_00:].sum() < 1e-6       )
             self._check_zero_mean_unit_variance(input_values[1][:10_00]       )
             self.assertTrue(input_values[0][10_00:].sum() < 1e-6       )
             self._check_zero_mean_unit_variance(input_values[2][:12_00]       )






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





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         __lowerCamelCase            =    range(8_00    ,							14_00    ,							2_00       )
         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in lengths]

         __lowerCamelCase            =    ['''longest''', '''max_length''', '''do_not_pad''']
         __lowerCamelCase            =    [None, 16_00, None]

         for max_length, padding in zip(a    ,							a       ):
             __lowerCamelCase            =    feat_extract(a    ,							max_length=a    ,							padding=a       )
             __lowerCamelCase            =    processed.input_values

             self._check_zero_mean_unit_variance(input_values[0][:8_00]       )
             self._check_zero_mean_unit_variance(input_values[1][:10_00]       )
             self._check_zero_mean_unit_variance(input_values[2][:12_00]       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in range(8_00    ,							14_00    ,							2_00       )]
         __lowerCamelCase            =    feat_extract(
             a    ,							truncation=a    ,							max_length=10_00    ,							padding='''max_length'''    ,							return_tensors='''np'''       )
         __lowerCamelCase            =    processed.input_values

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in range(8_00    ,							14_00    ,							2_00       )]
         __lowerCamelCase            =    feat_extract(
             a    ,							truncation=a    ,							max_length=10_00    ,							padding='''longest'''    ,							return_tensors='''np'''       )
         __lowerCamelCase            =    processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_00]       )
         self._check_zero_mean_unit_variance(input_values[1, :10_00]       )
         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, 10_00)       )

         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in range(8_00    ,							14_00    ,							2_00       )]
         __lowerCamelCase            =    feat_extract(
             a    ,							truncation=a    ,							max_length=20_00    ,							padding='''longest'''    ,							return_tensors='''np'''       )
         __lowerCamelCase            =    processed.input_values

         self._check_zero_mean_unit_variance(input_values[0, :8_00]       )
         self._check_zero_mean_unit_variance(input_values[1, :10_00]       )
         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, 12_00)       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[str]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         __lowerCamelCase            =    np.random.rand(1_00       ).astype(np.floataa       )
         __lowerCamelCase            =    np_speech_inputs.tolist()

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict()       )
         # create three inputs of length 800, 1000, and 1200
         __lowerCamelCase            =    [floats_list((1, x)       )[0] for x in range(8_00    ,							14_00    ,							2_00       )]
         __lowerCamelCase            =    [np.asarray(a       ) for speech_input in speech_inputs]

         # Test feature size
         __lowerCamelCase            =    feature_extractor(audio_target=a    ,							padding=a    ,							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
         __lowerCamelCase            =    feature_extractor(speech_inputs[0]    ,							return_tensors='''np'''       ).input_values
         __lowerCamelCase            =    feature_extractor(np_speech_inputs[0]    ,							return_tensors='''np'''       ).input_values
         self.assertTrue(np.allclose(a    ,							a    ,							atol=1e-3       )       )

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

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[str]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feat_extract_tester.prepare_inputs_for_target()
         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_dict       )
         __lowerCamelCase            =    feat_extract.model_input_names[0]

         __lowerCamelCase            =    BatchFeature({input_name: speech_inputs}       )

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

         __lowerCamelCase            =    self.feat_extract_tester.prepare_inputs_for_target(equal_length=a       )
         __lowerCamelCase            =    BatchFeature({input_name: speech_inputs}    ,							tensor_type='''np'''       )

         __lowerCamelCase            =    processed_features[input_name]

         if len(batch_features_input.shape       ) < 3:
             __lowerCamelCase            =    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						:						Optional[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feat_extract_tester.prepare_inputs_for_target(equal_length=a       )
         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_dict       )
         __lowerCamelCase            =    feat_extract.model_input_names[0]

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

         __lowerCamelCase            =    processed_features[input_name]

         if len(batch_features_input.shape       ) < 3:
             __lowerCamelCase            =    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						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feature_extraction_class(**self.feat_extract_dict       )
         __lowerCamelCase            =    self.feat_extract_tester.prepare_inputs_for_target()
         __lowerCamelCase            =    feat_extract.model_input_names[0]

         __lowerCamelCase            =    BatchFeature({input_name: speech_inputs}       )

         __lowerCamelCase            =    feat_extract.num_mel_bins  # hack!

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





         """simple docstring"""



         __lowerCamelCase            =    self.feat_extract_dict
         __lowerCamelCase            =    True
         __lowerCamelCase            =    self.feature_extraction_class(**a       )
         __lowerCamelCase            =    self.feat_extract_tester.prepare_inputs_for_target()
         __lowerCamelCase            =    [len(a       ) for x in speech_inputs]
         __lowerCamelCase            =    feat_extract.model_input_names[0]

         __lowerCamelCase            =    BatchFeature({input_name: speech_inputs}       )

         __lowerCamelCase            =    feat_extract.num_mel_bins  # hack!

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						Dict       ):





         """simple docstring"""



         __lowerCamelCase            =    self.feat_extract_dict
         __lowerCamelCase            =    True
         __lowerCamelCase            =    self.feature_extraction_class(**a       )
         __lowerCamelCase            =    self.feat_extract_tester.prepare_inputs_for_target()
         __lowerCamelCase            =    [len(a       ) for x in speech_inputs]
         __lowerCamelCase            =    feat_extract.model_input_names[0]

         __lowerCamelCase            =    BatchFeature({input_name: speech_inputs}       )
         __lowerCamelCase            =    min(a       )

         __lowerCamelCase            =    feat_extract.num_mel_bins  # hack!

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





         """simple docstring"""



         from datasets import load_dataset

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

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						Dict       ):





         """simple docstring"""



         __lowerCamelCase            =    torch.tensor(
             [2.3_8_0_4e-0_3, 2.0_7_5_2e-0_3, 1.9_8_3_6e-0_3, 2.1_0_5_7e-0_3, 1.6_1_7_4e-0_3,
              3.0_5_1_8e-0_4, 9.1_5_5_3e-0_5, 3.3_5_6_9e-0_4, 9.7_6_5_6e-0_4, 1.8_3_1_1e-0_3,
              2.0_1_4_2e-0_3, 2.1_0_5_7e-0_3, 1.7_3_9_5e-0_3, 4.5_7_7_6e-0_4, -3.9_6_7_3e-0_4,
              4.5_7_7_6e-0_4, 1.0_0_7_1e-0_3, 9.1_5_5_3e-0_5, 4.8_8_2_8e-0_4, 1.1_5_9_7e-0_3,
              7.3_2_4_2e-0_4, 9.4_6_0_4e-0_4, 1.8_0_0_5e-0_3, 1.8_3_1_1e-0_3, 8.8_5_0_1e-0_4,
              4.2_7_2_5e-0_4, 4.8_8_2_8e-0_4, 7.3_2_4_2e-0_4, 1.0_9_8_6e-0_3, 2.1_0_5_7e-0_3]       )
         # fmt: on

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






     def   SCREAMING_SNAKE_CASE__  (					self						:						Any       ):





         """simple docstring"""



         __lowerCamelCase            =    torch.tensor(
             [-2.68_70, -3.01_04, -3.13_56, -3.53_52, -3.00_44, -3.03_53, -3.47_19, -3.67_77,
              -3.15_20, -2.94_35, -2.65_53, -2.87_95, -2.99_44, -2.59_21, -3.02_79, -3.03_86,
              -3.08_64, -3.12_91, -3.23_53, -2.74_44, -2.68_31, -2.72_87, -3.17_61, -3.15_71,
              -3.27_26, -3.05_82, -3.10_07, -3.45_33, -3.46_95, -3.09_98]       )
         # fmt: on

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

'''simple docstring'''




def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__							)      ->       float:
    if digit_amount > 0:
        return round(number - int(UpperCamelCase__							)							,    UpperCamelCase__							)
    return number - int(UpperCamelCase__							)


if __name__ == "__main__":
  print(decimal_isolate(1.53, 0))
  print(decimal_isolate(35.345, 1))
  print(decimal_isolate(35.345, 2))
  print(decimal_isolate(35.345, 3))
  print(decimal_isolate(-14.789, 3))
  print(decimal_isolate(0, 2))
  print(decimal_isolate(-14.123, 1))
  print(decimal_isolate(-14.123, 2))
  print(decimal_isolate(-14.123, 3))
