






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

lowerCamelCase__       		=  random.Random()






def 	UpperCamelCase	(							snake_case__  : Union[str, Any]						,snake_case__  : Union[str, Any]=1.0						,snake_case__  : Dict=None						,snake_case__  : Any=None	):




     '''simple docstring'''






     if rng is None:
          __snake_case      :Tuple 							=    global_rng

     __snake_case      :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):

       '''simple docstring'''



       def __init__(				self      ,    a__      ,    a__=7      ,    a__=4_00      ,    a__=20_00      ,    a__=20_48      ,    a__=1_28      ,    a__=1      ,    a__=5_12      ,    a__=30      ,    a__=4_41_00      ,    )			->   List[Any]:






            '''simple docstring'''





            __snake_case      :int 							=    parent
            __snake_case      :Any 							=    batch_size
            __snake_case      :List[Any] 							=    min_seq_length
            __snake_case      :Dict 							=    max_seq_length
            __snake_case      :Tuple 							=    (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
            __snake_case      :Any 							=    spectrogram_length
            __snake_case      :Any 							=    feature_size
            __snake_case      :List[str] 							=    num_audio_channels
            __snake_case      :Tuple 							=    hop_length
            __snake_case      :Tuple 							=    chunk_length
            __snake_case      :List[str] 							=    sampling_rate



       def        __lowercase    (				self     )			->   List[str]:






            '''simple docstring'''





            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        __lowercase    (				self      ,    a__=False      ,    a__=False     )			->   List[str]:






            '''simple docstring'''





            def _flatten(a__     ):
                 return list(itertools.chain(*a__     )     )

            if equal_length:
                 __snake_case      :Any 							=    [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      :Optional[Any] 							=    [
                     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      :int 							=    [np.asarray(a__     ) for x in speech_inputs]
            return speech_inputs




@require_torch
@require_torchaudio
class       snake_case__ (				lowercase_						,     unittest.TestCase):

       '''simple docstring'''
       lowerCamelCase				:					Optional[Any]								=			TvltFeatureExtractor



       def        __lowercase    (				self     )			->   str:






            '''simple docstring'''





            __snake_case      :Dict 							=    TvltFeatureExtractionTester(self     )



       def        __lowercase    (				self     )			->   Any:






            '''simple docstring'''





            __snake_case      :int 							=    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        __lowercase    (				self     )			->   Dict:






            '''simple docstring'''





            __snake_case      :Dict 							=    self.feature_extraction_class(**self.feat_extract_dict     )

            with tempfile.TemporaryDirectory() as tmpdirname:
                 __snake_case      :Dict 							=    feat_extract_first.save_pretrained(a__     )[0]
                 check_json_file_has_correct_format(a__     )
                 __snake_case      :Union[str, Any] 							=    self.feature_extraction_class.from_pretrained(a__     )

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



       def        __lowercase    (				self     )			->   List[str]:






            '''simple docstring'''





            __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      :str 							=    self.feature_extraction_class.from_json_file(a__     )

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



       def        __lowercase    (				self     )			->   Any:






            '''simple docstring'''





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

            # create three inputs of length 800, 1000, and 1200
            __snake_case      :Optional[int] 							=    [floats_list((1, x)     )[0] for x in range(8_00      ,    14_00      ,    2_00     )]
            __snake_case      :Optional[int] 							=    [np.asarray(a__     ) for speech_input in speech_inputs]

            # Test not batched input
            __snake_case      :Dict 							=    feature_extractor(np_speech_inputs[0]      ,    return_tensors="""np"""      ,    sampling_rate=4_41_00     ).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      :Dict 							=    feature_extractor(a__      ,    return_tensors="""np"""      ,    sampling_rate=4_41_00     ).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      :Optional[Any] 							=    feature_extractor(
                a__      ,    return_tensors="""np"""      ,    sampling_rate=4_41_00      ,    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      :Dict 							=    [floats_list((1, x)     )[0] for x in (8_00, 8_00, 8_00)]
            __snake_case      :Any 							=    np.asarray(a__     )
            __snake_case      :Dict 							=    feature_extractor(a__      ,    return_tensors="""np"""      ,    sampling_rate=4_41_00     ).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        __lowercase    (				self      ,    a__     )			->   Optional[int]:






            '''simple docstring'''





            __snake_case      :List[Any] 							=    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        __lowercase    (				self     )			->   int:






            '''simple docstring'''





            __snake_case      :Dict 							=    self._load_datasamples(1     )
            __snake_case      :Tuple 							=    TvltFeatureExtractor()
            __snake_case      :str 							=    feature_extractor(a__      ,    return_tensors="""pt"""     ).audio_values

            self.assertEquals(audio_values.shape      ,    (1, 1, 1_92, 1_28)     )

            __snake_case      :int 							=    torch.tensor([[-0.30_32, -0.27_08], [-0.44_34, -0.40_07]]     )
            self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]      ,    a__      ,    atol=1e-4     )     )










def 	UpperCamelCase	(							snake_case__  : int	):




     '''simple docstring'''






     __snake_case      :List[Any] 							=    0
     while num > 0:
          digit_sum += num % 10
          num //= 10
     return digit_sum






def 	UpperCamelCase	(							snake_case__  : int = 100	):




     '''simple docstring'''






     __snake_case      :Tuple 							=    1
     __snake_case      :Dict 							=    2

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

     return sum_digits(snake_case__	)


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


