





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

SCREAMING_SNAKE_CASE_						       =	random.Random()



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE=1.0			,						_SCREAMING_SNAKE_CASE=None			,						_SCREAMING_SNAKE_CASE=None     )			->       Optional[int]:


      '''simple docstring'''


      if rng is None:
            SCREAMING_SNAKE_CASE		=						global_rng

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

      return values

class 		UpperCamelCase__			(				unittest.TestCase       ):



     '''simple docstring'''

     def __init__(							self						:   Tuple						,lowerCamelCase__						:   Dict						,lowerCamelCase__						:   Dict=7						,lowerCamelCase__						:   str=400						,lowerCamelCase__						:   Dict=2000						,lowerCamelCase__						:   Tuple=2048						,lowerCamelCase__						:   List[str]=128						,lowerCamelCase__						:   Optional[Any]=1						,lowerCamelCase__						:   Tuple=512						,lowerCamelCase__						:   Optional[Any]=30						,lowerCamelCase__						:   Tuple=44100						,)					->		Union[str, Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						parent
           SCREAMING_SNAKE_CASE		=						batch_size
           SCREAMING_SNAKE_CASE		=						min_seq_length
           SCREAMING_SNAKE_CASE		=						max_seq_length
           SCREAMING_SNAKE_CASE		=						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
           SCREAMING_SNAKE_CASE		=						spectrogram_length
           SCREAMING_SNAKE_CASE		=						feature_size
           SCREAMING_SNAKE_CASE		=						num_audio_channels
           SCREAMING_SNAKE_CASE		=						hop_length
           SCREAMING_SNAKE_CASE		=						chunk_length
           SCREAMING_SNAKE_CASE		=						sampling_rate






     def     SCREAMING_SNAKE_CASE__  (							self						:   Tuple	)					->		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     SCREAMING_SNAKE_CASE__  (							self						:   Tuple						,lowerCamelCase__						:   Union[str, Any]=False						,lowerCamelCase__						:   Tuple=False	)					->		Optional[int]:




           '''simple docstring'''


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

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

@require_torch
@require_torchaudio
class 		UpperCamelCase__			(				lowerCAmelCase_							,				unittest.TestCase       ):



     '''simple docstring'''

     __snake_case   :     int		     =      TvltFeatureExtractor






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						TvltFeatureExtractionTester(self	)






     def     SCREAMING_SNAKE_CASE__  (							self						:   List[Any]	)					->		Optional[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.feature_extraction_class(**self.feat_extract_dict	)
           self.assertTrue(hasattr(lowerCamelCase__						,"""spectrogram_length"""	)	)
           self.assertTrue(hasattr(lowerCamelCase__						,"""feature_size"""	)	)
           self.assertTrue(hasattr(lowerCamelCase__						,"""num_audio_channels"""	)	)
           self.assertTrue(hasattr(lowerCamelCase__						,"""hop_length"""	)	)
           self.assertTrue(hasattr(lowerCamelCase__						,"""chunk_length"""	)	)
           self.assertTrue(hasattr(lowerCamelCase__						,"""sampling_rate"""	)	)






     def     SCREAMING_SNAKE_CASE__  (							self						:   Dict	)					->		Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.feature_extraction_class(**self.feat_extract_dict	)

           with tempfile.TemporaryDirectory() as tmpdirname:
                 SCREAMING_SNAKE_CASE		=						feat_extract_first.save_pretrained(lowerCamelCase__	)[0]
                 check_json_file_has_correct_format(lowerCamelCase__	)
                 SCREAMING_SNAKE_CASE		=						self.feature_extraction_class.from_pretrained(lowerCamelCase__	)

           SCREAMING_SNAKE_CASE		=						feat_extract_first.to_dict()
           SCREAMING_SNAKE_CASE		=						feat_extract_second.to_dict()
           SCREAMING_SNAKE_CASE		=						dict_first.pop("""mel_filters"""	)
           SCREAMING_SNAKE_CASE		=						dict_second.pop("""mel_filters"""	)
           self.assertTrue(np.allclose(lowerCamelCase__						,lowerCamelCase__	)	)
           self.assertEqual(lowerCamelCase__						,lowerCamelCase__	)






     def     SCREAMING_SNAKE_CASE__  (							self						:   int	)					->		Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.feature_extraction_class(**self.feat_extract_dict	)

           with tempfile.TemporaryDirectory() as tmpdirname:
                 SCREAMING_SNAKE_CASE		=						os.path.join(lowerCamelCase__						,"""feat_extract.json"""	)
                 feat_extract_first.to_json_file(lowerCamelCase__	)
                 SCREAMING_SNAKE_CASE		=						self.feature_extraction_class.from_json_file(lowerCamelCase__	)

           SCREAMING_SNAKE_CASE		=						feat_extract_first.to_dict()
           SCREAMING_SNAKE_CASE		=						feat_extract_second.to_dict()
           SCREAMING_SNAKE_CASE		=						dict_first.pop("""mel_filters"""	)
           SCREAMING_SNAKE_CASE		=						dict_second.pop("""mel_filters"""	)
           self.assertTrue(np.allclose(lowerCamelCase__						,lowerCamelCase__	)	)
           self.assertEqual(lowerCamelCase__						,lowerCamelCase__	)






     def     SCREAMING_SNAKE_CASE__  (							self						:   int	)					->		Any:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.feature_extraction_class(**self.feat_extract_dict	)

           # create three inputs of length 800, 1000, and 1200
           SCREAMING_SNAKE_CASE		=						[floats_list((1, x)	)[0] for x in range(800						,1400						,200	)]
           SCREAMING_SNAKE_CASE		=						[np.asarray(lowerCamelCase__	) for speech_input in speech_inputs]

           # Test not batched input
           SCREAMING_SNAKE_CASE		=						feature_extractor(np_speech_inputs[0]						,return_tensors="""np"""						,sampling_rate=44100	).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
           SCREAMING_SNAKE_CASE		=						feature_extractor(lowerCamelCase__						,return_tensors="""np"""						,sampling_rate=44100	).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
           SCREAMING_SNAKE_CASE		=						feature_extractor(
               lowerCamelCase__						,return_tensors="""np"""						,sampling_rate=44100						,mask_audio=lowerCamelCase__	).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.
           SCREAMING_SNAKE_CASE		=						[floats_list((1, x)	)[0] for x in (800, 800, 800)]
           SCREAMING_SNAKE_CASE		=						np.asarray(lowerCamelCase__	)
           SCREAMING_SNAKE_CASE		=						feature_extractor(lowerCamelCase__						,return_tensors="""np"""						,sampling_rate=44100	).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     SCREAMING_SNAKE_CASE__  (							self						:   List[str]						,lowerCamelCase__						:   str	)					->		Dict:




           '''simple docstring'''


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

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






     def     SCREAMING_SNAKE_CASE__  (							self						:   Tuple	)					->		Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self._load_datasamples(1	)
           SCREAMING_SNAKE_CASE		=						TvltFeatureExtractor()
           SCREAMING_SNAKE_CASE		=						feature_extractor(lowerCamelCase__						,return_tensors="""pt"""	).audio_values

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

           SCREAMING_SNAKE_CASE		=						torch.tensor([[-0.3032, -0.2708], [-0.4434, -0.4007]]	)
           self.assertTrue(torch.allclose(audio_values[0, 0, :2, :2]						,lowerCamelCase__						,atol=1e-4	)	)









from __future__ import annotations



def        __lowercase       (				_SCREAMING_SNAKE_CASE			,						_SCREAMING_SNAKE_CASE     )			->       list[int]:


      '''simple docstring'''


      SCREAMING_SNAKE_CASE		=						0
      SCREAMING_SNAKE_CASE		=						len(_SCREAMING_SNAKE_CASE     ) - 1

      while i < j:
            if nums[i] + nums[j] == target:
                  return [i, j]
            elif nums[i] + nums[j] < target:
                  SCREAMING_SNAKE_CASE		=						i + 1
            else:
                  SCREAMING_SNAKE_CASE		=						j - 1

      return []


if __name__ == "__main__":
      import doctest

      doctest.testmod()
      print(F'''{two_pointer([2, 7, 1_1, 1_5], 9) = }''')


