

'''simple docstring'''







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__     (   UpperCAmelCase__,							UpperCAmelCase__=1.0,							UpperCAmelCase__=None,							UpperCAmelCase__=None					)      ->      str:
       if rng is None:
              A_						       =   global_rng

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

       return values


class        A__   (   unittest.TestCase      ):



    def __init__(       self		,					UpperCamelCase__		,					UpperCamelCase__=7		,					UpperCamelCase__=400		,					UpperCamelCase__=2000		,					UpperCamelCase__=2048		,					UpperCamelCase__=128		,					UpperCamelCase__=1		,					UpperCamelCase__=512		,					UpperCamelCase__=30		,					UpperCamelCase__=44100		,					)    ->   List[str]:





           '''simple docstring'''
           A_						       =   parent
           A_						       =   batch_size
           A_						       =   min_seq_length
           A_						       =   max_seq_length
           A_						       =   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
           A_						       =   spectrogram_length
           A_						       =   feature_size
           A_						       =   num_audio_channels
           A_						       =   hop_length
           A_						       =   chunk_length
           A_						       =   sampling_rate



    def        snake_case_      (       self							)    ->   List[Any]:





           '''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        snake_case_      (       self		,					UpperCamelCase__=False		,					UpperCamelCase__=False							)    ->   List[Any]:





           '''simple docstring'''
           def _flatten(UpperCamelCase__							):
                  return list(itertools.chain(*UpperCamelCase__							)							)

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


@require_torch
@require_torchaudio
class        A__   (   _snake_case    ,    unittest.TestCase      ):
    lowercase						       =		TvltFeatureExtractor



    def        snake_case_      (       self							)    ->   Optional[Any]:





           '''simple docstring'''
           A_						       =   TvltFeatureExtractionTester(self							)



    def        snake_case_      (       self							)    ->   List[Any]:





           '''simple docstring'''
           A_						       =   self.feature_extraction_class(**self.feat_extract_dict							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""spectrogram_length"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""feature_size"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""num_audio_channels"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""hop_length"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""chunk_length"""							)							)
           self.assertTrue(hasattr(UpperCamelCase__		,					"""sampling_rate"""							)							)



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





           '''simple docstring'''
           A_						       =   self.feature_extraction_class(**self.feat_extract_dict							)

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

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



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   self.feature_extraction_class(**self.feat_extract_dict							)

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

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



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           # Initialize feature_extractor
           A_						       =   self.feature_extraction_class(**self.feat_extract_dict							)

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

           # Test not batched input
           A_						       =   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
           A_						       =   feature_extractor(UpperCamelCase__		,					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
           A_						       =   feature_extractor(
               UpperCamelCase__		,					return_tensors="""np"""		,					sampling_rate=44100		,					mask_audio=UpperCamelCase__							).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.
           A_						       =   [floats_list((1, x)							)[0] for x in (800, 800, 800)]
           A_						       =   np.asarray(UpperCamelCase__							)
           A_						       =   feature_extractor(UpperCamelCase__		,					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        snake_case_      (       self		,					UpperCamelCase__							)    ->   Tuple:





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

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







    def        snake_case_      (       self							)    ->   Any:





           '''simple docstring'''
           A_						       =   self._load_datasamples(1							)
           A_						       =   TvltFeatureExtractor()
           A_						       =   feature_extractor(UpperCamelCase__		,					return_tensors="""pt"""							).audio_values

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

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



'''simple docstring'''







import os
import sys
import unittest


__lowerCamelCase									=     os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, '''utils'''))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__lowerCamelCase									=     os.path.join(git_repo_path, '''src''', '''transformers''')

__lowerCamelCase									=     '''
{0} = None
'''

__lowerCamelCase									=     '''
class {0}(metaclass=DummyObject):
    _backends = {1}

    def __init__(self, *args, **kwargs):
        requires_backends(self, {1})
'''


__lowerCamelCase									=     '''
def {0}(*args, **kwargs):
    requires_backends({0}, {1})
'''


class        A__   (   unittest.TestCase      ):



    def        snake_case_      (       self							)    ->   Dict:





           '''simple docstring'''
           A_						       =   find_backend("""    _import_structure[\"models.albert\"].append(\"AlbertTokenizerFast\")"""							)
           self.assertIsNone(UpperCamelCase__							)

           A_						       =   find_backend("""    if not is_tokenizers_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tokenizers"""							)

           A_						       =   find_backend("""    if not is_tensorflow_text_available():"""							)
           self.assertEqual(UpperCamelCase__		,					"""tensorflow_text"""							)

           A_						       =   find_backend("""    if not (is_sentencepiece_available() and is_tokenizers_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tensorflow_text"""							)

           A_						       =   find_backend(
               """    if not (is_sentencepiece_available() and is_tokenizers_available() and is_vision_available()):"""							)
           self.assertEqual(UpperCamelCase__		,					"""sentencepiece_and_tokenizers_and_vision"""							)



    def        snake_case_      (       self							)    ->   int:





           '''simple docstring'''
           A_						       =   read_init()
           # We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
           self.assertIn("""torch"""		,					UpperCamelCase__							)
           self.assertIn("""tensorflow_text"""		,					UpperCamelCase__							)
           self.assertIn("""sentencepiece_and_tokenizers"""		,					UpperCamelCase__							)

           # Likewise, we can't assert on the exact content of a key
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertModel"""		,					objects["""tf"""]							)
           self.assertIn("""FlaxBertModel"""		,					objects["""flax"""]							)
           self.assertIn("""BertModel"""		,					objects["""torch"""]							)
           self.assertIn("""TFBertTokenizer"""		,					objects["""tensorflow_text"""]							)
           self.assertIn("""convert_slow_tokenizer"""		,					objects["""sentencepiece_and_tokenizers"""]							)



    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   create_dummy_object("""CONSTANT"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					"""\nCONSTANT = None\n"""							)

           A_						       =   create_dummy_object("""function"""		,					"""'torch'"""							)
           self.assertEqual(
               UpperCamelCase__		,					"""\ndef function(*args, **kwargs):\n    requires_backends(function, 'torch')\n"""							)

           A_						       =   """
class FakeClass(metaclass=DummyObject):
    _backends = 'torch'

    def __init__(self, *args, **kwargs):
        requires_backends(self, 'torch')
"""
           A_						       =   create_dummy_object("""FakeClass"""		,					"""'torch'"""							)
           self.assertEqual(UpperCamelCase__		,					UpperCamelCase__							)







    def        snake_case_      (       self							)    ->   str:





           '''simple docstring'''
           A_						       =   """# This file is autogenerated by the command `make fix-copies`, do not edit.
from ..utils import DummyObject, requires_backends


CONSTANT = None


def function(*args, **kwargs):
    requires_backends(function, [\"torch\"])


class FakeClass(metaclass=DummyObject):
    _backends = [\"torch\"]

    def __init__(self, *args, **kwargs):
        requires_backends(self, [\"torch\"])
"""
           A_						       =   create_dummy_files({"""torch""": ["""CONSTANT""", """function""", """FakeClass"""]}							)
           self.assertEqual(dummy_files["""torch"""]		,					UpperCamelCase__							)
