






'''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

__A	:	str     =     random.Random()





def      UpperCAmelCase      (		lowerCamelCase_  :Any				,      lowerCamelCase_  :Any=1.0				,      lowerCamelCase_  :str=None				,      lowerCamelCase_  :Dict=None ):







		'''simple docstring'''
		if rng is None:
				snake_case_		:							Any			       =						global_rng

		snake_case_		:							int			       =						[]
		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							):





							def __init__(  self		:Union[str, Any]  ,_UpperCamelCase		:Tuple  ,_UpperCamelCase		:str=7  ,_UpperCamelCase		:Tuple=4_0_0  ,_UpperCamelCase		:Any=2_0_0_0  ,_UpperCamelCase		:int=2_0_4_8  ,_UpperCamelCase		:Optional[int]=1_2_8  ,_UpperCamelCase		:Tuple=1  ,_UpperCamelCase		:Dict=5_1_2  ,_UpperCamelCase		:Union[str, Any]=3_0  ,_UpperCamelCase		:Optional[int]=4_4_1_0_0  ,):
									snake_case_		:							Union[str, Any]			       =						parent
									snake_case_		:							Optional[int]			       =						batch_size
									snake_case_		:							Tuple			       =						min_seq_length
									snake_case_		:							Optional[Any]			       =						max_seq_length
									snake_case_		:							Dict			       =						(self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
									snake_case_		:							int			       =						spectrogram_length
									snake_case_		:							Dict			       =						feature_size
									snake_case_		:							Union[str, Any]			       =						num_audio_channels
									snake_case_		:							Optional[int]			       =						hop_length
									snake_case_		:							List[Any]			       =						chunk_length
									snake_case_		:							Union[str, Any]			       =						sampling_rate





							def 		a__   (  self		:Tuple			):
									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 		a__   (  self		:Optional[int]  ,_UpperCamelCase		:int=False  ,_UpperCamelCase		:Tuple=False			):
									def _flatten(_UpperCamelCase		:Any			):
											return list(itertools.chain(*__UpperCamelCase			)			)

									if equal_length:
											snake_case_		:							int			       =						[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_		:							int			       =						[
											    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_		:							List[str]			       =						[np.asarray(__UpperCamelCase			) for x in speech_inputs]
									return speech_inputs





@require_torch
@require_torchaudio
class 						__UpperCamelCase	(						lowercase__						,  unittest.TestCase							):
							lowercase			:		Optional[Any]   		=  TvltFeatureExtractor





							def 		a__   (  self		:Union[str, Any]			):
									snake_case_		:							Optional[int]			       =						TvltFeatureExtractionTester(self			)





							def 		a__   (  self		:Union[str, Any]			):
									snake_case_		:							List[Any]			       =						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 		a__   (  self		:Any			):
									snake_case_		:							int			       =						self.feature_extraction_class(**self.feat_extract_dict			)

									with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_		:							List[Any]			       =						feat_extract_first.save_pretrained(__UpperCamelCase			)[0]
											check_json_file_has_correct_format(__UpperCamelCase			)
											snake_case_		:							Optional[int]			       =						self.feature_extraction_class.from_pretrained(__UpperCamelCase			)

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





							def 		a__   (  self		:Optional[int]			):
									snake_case_		:							str			       =						self.feature_extraction_class(**self.feat_extract_dict			)

									with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_		:							Optional[int]			       =						os.path.join(__UpperCamelCase  ,"""feat_extract.json"""			)
											feat_extract_first.to_json_file(__UpperCamelCase			)
											snake_case_		:							List[str]			       =						self.feature_extraction_class.from_json_file(__UpperCamelCase			)

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





							def 		a__   (  self		:int			):
									# Initialize feature_extractor
									snake_case_		:							List[str]			       =						self.feature_extraction_class(**self.feat_extract_dict			)

									# create three inputs of length 800, 1000, and 1200
									snake_case_		:							Any			       =						[floats_list((1, x)			)[0] for x in range(8_0_0  ,1_4_0_0  ,2_0_0			)]
									snake_case_		:							Any			       =						[np.asarray(__UpperCamelCase			) 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_4_1_0_0			).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_		:							List[str]			       =						feature_extractor(__UpperCamelCase  ,return_tensors="""np"""  ,sampling_rate=4_4_1_0_0			).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_		:							str			       =						feature_extractor(
									    __UpperCamelCase  ,return_tensors="""np"""  ,sampling_rate=4_4_1_0_0  ,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.
									snake_case_		:							int			       =						[floats_list((1, x)			)[0] for x in (8_0_0, 8_0_0, 8_0_0)]
									snake_case_		:							str			       =						np.asarray(__UpperCamelCase			)
									snake_case_		:							Union[str, Any]			       =						feature_extractor(__UpperCamelCase  ,return_tensors="""np"""  ,sampling_rate=4_4_1_0_0			).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 		a__   (  self		:Dict  ,_UpperCamelCase		:Optional[Any]			):
									snake_case_		:							Optional[int]			       =						load_dataset("""hf-internal-testing/librispeech_asr_dummy"""  ,"""clean"""  ,split="""validation"""			)
									# automatic decoding with librispeech
									snake_case_		:							Any			       =						ds.sort("""id"""			).select(range(__UpperCamelCase			)			)[:num_samples]["""audio"""]

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





							def 		a__   (  self		:Dict			):
									snake_case_		:							int			       =						self._load_datasamples(1			)
									snake_case_		:							Optional[Any]			       =						TvltFeatureExtractor()
									snake_case_		:							Dict			       =						feature_extractor(__UpperCamelCase  ,return_tensors="""pt"""			).audio_values

									self.assertEquals(audio_values.shape  ,(1, 1, 1_9_2, 1_2_8)			)

									snake_case_		:							Optional[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]  ,__UpperCamelCase  ,atol=1E-4			)			)



'''simple docstring'''






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_speech_available, is_torch_available


__A	:	Tuple     =     {
    'configuration_audio_spectrogram_transformer': [
        'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'ASTConfig',
    ]
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__A	:	Tuple     =     [
							    'AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
							    'ASTForAudioClassification',
							    'ASTModel',
							    'ASTPreTrainedModel',
							]

try:
							if not is_speech_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							__A	:	int     =     ['ASTFeatureExtractor']

if TYPE_CHECKING:
							from .configuration_audio_spectrogram_transformer import (
							    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
							    ASTConfig,
							)

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_audio_spectrogram_transformer import (
														    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
														    ASTForAudioClassification,
														    ASTModel,
														    ASTPreTrainedModel,
														)

							try:
														if not is_speech_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .feature_extraction_audio_spectrogram_transformer import ASTFeatureExtractor


else:
							import sys

							__A	:	Union[str, Any]     =     _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)