


'''simple docstring'''





import itertools
import random
import unittest

import numpy as np

from transformers import is_speech_available
from transformers.testing_utils import require_torch, require_torchaudio

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


if is_speech_available():
    from transformers import SpeechaTextFeatureExtractor

__lowerCamelCase												=						random.Random()


def        a__     (					UpperCamelCase_						:      Optional[Any],   UpperCamelCase_						:      Dict=1.0,   UpperCamelCase_						:      Tuple=None,   UpperCamelCase_						:      Union[str, Any]=None						):
   if rng is None:
      UpperCAmelCase__	:Optional[int]      =      global_rng

   UpperCAmelCase__	:int      =      []
   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 				UpperCAmelCase			(			unittest.TestCase						):


 def __init__(      self							:	Tuple			,       __lowerCamelCase							:	Any			,       __lowerCamelCase							:	Any=7			,       __lowerCamelCase							:	List[str]=4_0_0			,       __lowerCamelCase							:	Tuple=2_0_0_0			,       __lowerCamelCase							:	Tuple=2_4			,       __lowerCamelCase							:	Any=2_4			,       __lowerCamelCase							:	Optional[Any]=0.0			,       __lowerCamelCase							:	Any=1_6_0_0_0			,       __lowerCamelCase							:	List[str]=True			,       __lowerCamelCase							:	Dict=True			,       ):
    UpperCAmelCase__	:List[Any]      =      parent
    UpperCAmelCase__	:Optional[int]      =      batch_size
    UpperCAmelCase__	:Optional[int]      =      min_seq_length
    UpperCAmelCase__	:Tuple      =      max_seq_length
    UpperCAmelCase__	:Optional[Any]      =      (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
    UpperCAmelCase__	:Any      =      feature_size
    UpperCAmelCase__	:Optional[Any]      =      num_mel_bins
    UpperCAmelCase__	:List[Any]      =      padding_value
    UpperCAmelCase__	:Optional[int]      =      sampling_rate
    UpperCAmelCase__	:str      =      return_attention_mask
    UpperCAmelCase__	:Optional[Any]      =      do_normalize


 def        __SCREAMING_SNAKE_CASE					(      self							:	List[Any] ):
    return {
        "feature_size": self.feature_size,
        "num_mel_bins": self.num_mel_bins,
        "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							:	Any			,       __lowerCamelCase							:	int=False			,       __lowerCamelCase							:	str=False ):
    def _flatten(__lowerCamelCase							:	Dict ):
       return list(itertools.chain(*__lowerCamelCase ) )

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




@require_torch
@require_torchaudio
class 				UpperCAmelCase			(			__snake_case						, unittest.TestCase						):
 UpperCAmelCase				=					SpeechaTextFeatureExtractor if is_speech_available() else None


 def        __SCREAMING_SNAKE_CASE					(      self							:	List[Any] ):
    UpperCAmelCase__	:Union[str, Any]      =      SpeechaTextFeatureExtractionTester(self )


 def        __SCREAMING_SNAKE_CASE					(      self							:	Dict			,       __lowerCamelCase							:	str ):
    self.assertTrue(np.all(np.mean(__lowerCamelCase			,       axis=0 ) < 1e-3 ) )
    self.assertTrue(np.all(np.abs(np.var(__lowerCamelCase			,       axis=0 ) - 1 ) < 1e-3 ) )


 def        __SCREAMING_SNAKE_CASE					(      self							:	str ):
    # Tests that all call wrap to encode_plus and batch_encode_plus
    UpperCAmelCase__	:List[str]      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    # create three inputs of length 800, 1000, and 1200
    UpperCAmelCase__	:Union[str, Any]      =      [floats_list((1, x) )[0] for x in range(8_0_0			,       1_4_0_0			,       2_0_0 )]
    UpperCAmelCase__	:Optional[int]      =      [np.asarray(__lowerCamelCase ) for speech_input in speech_inputs]

    # Test feature size
    UpperCAmelCase__	:int      =      feature_extractor(__lowerCamelCase			,       padding=__lowerCamelCase			,       return_tensors='''np''' ).input_features
    self.assertTrue(input_features.ndim == 3 )
    self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size )

    # Test not batched input
    UpperCAmelCase__	:Dict      =      feature_extractor(speech_inputs[0]			,       return_tensors='''np''' ).input_features
    UpperCAmelCase__	:List[Any]      =      feature_extractor(np_speech_inputs[0]			,       return_tensors='''np''' ).input_features
    self.assertTrue(np.allclose(__lowerCamelCase			,       __lowerCamelCase			,       atol=1e-3 ) )

    # Test batched
    UpperCAmelCase__	:Dict      =      feature_extractor(__lowerCamelCase			,       return_tensors='''np''' ).input_features
    UpperCAmelCase__	:Optional[int]      =      feature_extractor(__lowerCamelCase			,       return_tensors='''np''' ).input_features
    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.
    UpperCAmelCase__	:List[Any]      =      [floats_list((1, x) )[0] for x in (8_0_0, 8_0_0, 8_0_0)]
    UpperCAmelCase__	:Any      =      np.asarray(__lowerCamelCase )
    UpperCAmelCase__	:int      =      feature_extractor(__lowerCamelCase			,       return_tensors='''np''' ).input_features
    UpperCAmelCase__	:int      =      feature_extractor(__lowerCamelCase			,       return_tensors='''np''' ).input_features
    for enc_seq_a, enc_seq_a in zip(__lowerCamelCase			,       __lowerCamelCase ):
       self.assertTrue(np.allclose(__lowerCamelCase			,       __lowerCamelCase			,       atol=1e-3 ) )


 def        __SCREAMING_SNAKE_CASE					(      self							:	Any ):
    UpperCAmelCase__	:Optional[int]      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    UpperCAmelCase__	:Optional[int]      =      [floats_list((1, x) )[0] for x in range(8_0_0			,       1_4_0_0			,       2_0_0 )]

    UpperCAmelCase__	:Optional[int]      =      ["""longest""", """max_length""", """do_not_pad"""]
    UpperCAmelCase__	:Union[str, Any]      =      [None, 1_6, None]
    for max_length, padding in zip(__lowerCamelCase			,       __lowerCamelCase ):
       UpperCAmelCase__	:Any      =      feature_extractor(
           __lowerCamelCase			,       padding=__lowerCamelCase			,       max_length=__lowerCamelCase			,       return_attention_mask=__lowerCamelCase )
       UpperCAmelCase__	:Dict      =      inputs.input_features
       UpperCAmelCase__	:Tuple      =      inputs.attention_mask
       UpperCAmelCase__	:Any      =      [np.sum(__lowerCamelCase ) for x in attention_mask]

       self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] )
       self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] )
       self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] )


 def        __SCREAMING_SNAKE_CASE					(      self							:	Any ):
    UpperCAmelCase__	:Tuple      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    UpperCAmelCase__	:Tuple      =      [floats_list((1, x) )[0] for x in range(8_0_0			,       1_4_0_0			,       2_0_0 )]

    UpperCAmelCase__	:Optional[int]      =      ["""longest""", """max_length""", """do_not_pad"""]
    UpperCAmelCase__	:Optional[Any]      =      [None, 1_6, None]
    for max_length, padding in zip(__lowerCamelCase			,       __lowerCamelCase ):
       UpperCAmelCase__	:List[Any]      =      feature_extractor(
           __lowerCamelCase			,       max_length=__lowerCamelCase			,       padding=__lowerCamelCase			,       return_tensors='''np'''			,       return_attention_mask=__lowerCamelCase )
       UpperCAmelCase__	:str      =      inputs.input_features
       UpperCAmelCase__	:str      =      inputs.attention_mask
       UpperCAmelCase__	:Optional[int]      =      [np.sum(__lowerCamelCase ) for x in attention_mask]

       self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] )
       self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6 )
       self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] )
       self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6 )
       self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] )


 def        __SCREAMING_SNAKE_CASE					(      self							:	List[str] ):
    UpperCAmelCase__	:Tuple      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    UpperCAmelCase__	:int      =      [floats_list((1, x) )[0] for x in range(8_0_0			,       1_4_0_0			,       2_0_0 )]
    UpperCAmelCase__	:str      =      feature_extractor(
        __lowerCamelCase			,       padding='''max_length'''			,       max_length=4			,       truncation=__lowerCamelCase			,       return_tensors='''np'''			,       return_attention_mask=__lowerCamelCase			,       )
    UpperCAmelCase__	:str      =      inputs.input_features
    UpperCAmelCase__	:List[Any]      =      inputs.attention_mask
    UpperCAmelCase__	:str      =      np.sum(attention_mask == 1			,       axis=1 )

    self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] )
    self._check_zero_mean_unit_variance(input_features[1] )
    self._check_zero_mean_unit_variance(input_features[2] )


 def        __SCREAMING_SNAKE_CASE					(      self							:	Optional[int] ):
    UpperCAmelCase__	:Any      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    UpperCAmelCase__	:Tuple      =      [floats_list((1, x) )[0] for x in range(8_0_0			,       1_4_0_0			,       2_0_0 )]
    UpperCAmelCase__	:Optional[int]      =      feature_extractor(
        __lowerCamelCase			,       padding='''longest'''			,       max_length=4			,       truncation=__lowerCamelCase			,       return_tensors='''np'''			,       return_attention_mask=__lowerCamelCase			,       )
    UpperCAmelCase__	:List[Any]      =      inputs.input_features
    UpperCAmelCase__	:Dict      =      inputs.attention_mask
    UpperCAmelCase__	:int      =      np.sum(attention_mask == 1			,       axis=1 )

    self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] )
    self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] )
    self._check_zero_mean_unit_variance(input_features[2] )

    # make sure that if max_length < longest -> then pad to max_length
    self.assertEqual(input_features.shape			,       (3, 4, 2_4) )

    UpperCAmelCase__	:Optional[int]      =      [floats_list((1, x) )[0] for x in range(8_0_0			,       1_4_0_0			,       2_0_0 )]
    UpperCAmelCase__	:str      =      feature_extractor(
        __lowerCamelCase			,       padding='''longest'''			,       max_length=1_6			,       truncation=__lowerCamelCase			,       return_tensors='''np'''			,       return_attention_mask=__lowerCamelCase			,       )
    UpperCAmelCase__	:Dict      =      inputs.input_features
    UpperCAmelCase__	:Any      =      inputs.attention_mask
    UpperCAmelCase__	:Optional[Any]      =      np.sum(attention_mask == 1			,       axis=1 )

    self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] )
    self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] )
    self._check_zero_mean_unit_variance(input_features[2] )

    # make sure that if max_length < longest -> then pad to max_length
    self.assertEqual(input_features.shape			,       (3, 6, 2_4) )


 def        __SCREAMING_SNAKE_CASE					(      self							:	Union[str, Any] ):
    import torch

    UpperCAmelCase__	:str      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    UpperCAmelCase__	:int      =      np.random.rand(1_0_0			,       3_2 ).astype(np.floataa )
    UpperCAmelCase__	:Optional[int]      =      np_speech_inputs.tolist()

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


 def        __SCREAMING_SNAKE_CASE					(      self							:	str			,       __lowerCamelCase							:	List[Any] ):
    from datasets import load_dataset

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

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





 def        __SCREAMING_SNAKE_CASE					(      self							:	Optional[Any] ):
    # fmt: off
    UpperCAmelCase__	:List[Any]      =      np.array([
        -1.57_45, -1.77_13, -1.70_20, -1.60_69, -1.22_50, -1.11_05, -0.90_72, -0.82_41,
        -1.23_10, -0.80_98, -0.33_20, -0.41_01, -0.79_85, -0.49_96, -0.82_13, -0.91_28,
        -1.04_20, -1.12_86, -1.04_40, -0.79_99, -0.84_05, -1.22_75, -1.54_43, -1.46_25,
    ] )
    # fmt: on

    UpperCAmelCase__	:Optional[Any]      =      self._load_datasamples(1 )
    UpperCAmelCase__	:Dict      =      self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
    UpperCAmelCase__	:Optional[int]      =      feature_extractor(__lowerCamelCase			,       return_tensors='''pt''' ).input_features
    self.assertEquals(input_features.shape			,       (1, 5_8_4, 2_4) )
    self.assertTrue(np.allclose(input_features[0, 0, :3_0]			,       __lowerCamelCase			,       atol=1e-4 ) )











"""simple docstring"""







def      UpperCamelCase       ( _A )     ->       int:
				lowercase    :      Dict       = 0
				while num > 0:
								digit_sum += num % 10
								num //= 10
				return digit_sum


def      UpperCamelCase       ( _A = 100 )     ->       int:
				lowercase    :      Union[str, Any]       = 1
				lowercase    :      Tuple       = 2

				for i in range(2  ,				max_n + 1 ):
								lowercase    :      Any       = pre_numerator
								lowercase    :      Dict       = 2 * i // 3 if i % 3 == 0 else 1
								lowercase    :      Optional[Any]       = cur_numerator
								lowercase    :      str       = e_cont * pre_numerator + temp

				return sum_digits(_A )


if __name__ == "__main__":
				print(F'{solution() = }')
