

"""simple docstring"""






import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import ASTForAudioClassification, ASTModel
		from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
		    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
		)


if is_torchaudio_available():
		import torchaudio

		from transformers import ASTFeatureExtractor




class 				__lowercase			:







					'''simple docstring'''




					def __init__(						self	,			_UpperCAmelCase	,			_UpperCAmelCase=13	,			_UpperCAmelCase=2	,			_UpperCAmelCase=24	,			_UpperCAmelCase=16	,			_UpperCAmelCase=True	,			_UpperCAmelCase=True	,			_UpperCAmelCase=32	,			_UpperCAmelCase=5	,			_UpperCAmelCase=4	,			_UpperCAmelCase=37	,			_UpperCAmelCase="gelu"	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=0.1	,			_UpperCAmelCase=10	,			_UpperCAmelCase=0.0_2	,			_UpperCAmelCase=None	,			_UpperCAmelCase=2	,			_UpperCAmelCase=2	,			):
									__a :						Tuple			       =  parent
									__a :						Optional[Any]			       =  batch_size
									__a :						List[Any]			       =  patch_size
									__a :						str			       =  max_length
									__a :						str			       =  num_mel_bins
									__a :						List[Any]			       =  is_training
									__a :						Optional[int]			       =  use_labels
									__a :						Union[str, Any]			       =  hidden_size
									__a :						Optional[Any]			       =  num_hidden_layers
									__a :						Optional[int]			       =  num_attention_heads
									__a :						int			       =  intermediate_size
									__a :						List[Any]			       =  hidden_act
									__a :						Tuple			       =  hidden_dropout_prob
									__a :						Union[str, Any]			       =  attention_probs_dropout_prob
									__a :						List[Any]			       =  type_sequence_label_size
									__a :						Optional[Any]			       =  initializer_range
									__a :						str			       =  scope
									__a :						Optional[int]			       =  frequency_stride
									__a :						Optional[Any]			       =  time_stride

									# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
									__a :						str			       =  (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
									__a :						Tuple			       =  (self.max_length - self.patch_size) // self.time_stride + 1
									__a :						List[Any]			       =  frequency_out_dimension * time_out_dimension
									__a :						Optional[Any]			       =  num_patches + 2







					def  _lowerCamelCase		(						self     ):
									__a :						Optional[Any]			       =  floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]     )

									__a :						Optional[Any]			       =  None
									if self.use_labels:
													__a :						Any			       =  ids_tensor([self.batch_size]	,			self.type_sequence_label_size     )

									__a :						Any			       =  self.get_config()

									return config, input_values, labels







					def  _lowerCamelCase		(						self     ):
									return ASTConfig(
									    patch_size=self.patch_size	,			max_length=self.max_length	,			num_mel_bins=self.num_mel_bins	,			hidden_size=self.hidden_size	,			num_hidden_layers=self.num_hidden_layers	,			num_attention_heads=self.num_attention_heads	,			intermediate_size=self.intermediate_size	,			hidden_act=self.hidden_act	,			hidden_dropout_prob=self.hidden_dropout_prob	,			attention_probs_dropout_prob=self.attention_probs_dropout_prob	,			is_decoder=__UpperCamelCase	,			initializer_range=self.initializer_range	,			frequency_stride=self.frequency_stride	,			time_stride=self.time_stride	,			)







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):
									__a :						Tuple			       =  ASTModel(config=__UpperCamelCase     )
									model.to(__UpperCamelCase     )
									model.eval()
									__a :						Tuple			       =  model(__UpperCamelCase     )
									self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.seq_length, self.hidden_size)     )







					def  _lowerCamelCase		(						self     ):
									__a :						str			       =  self.prepare_config_and_inputs()
									(
									    (
									    __a       
									)       ,						(
									    __a       
									)       ,						(
									    __a       
									)       ,						       
									) :						int			       =  config_and_inputs
									__a :						Optional[Any]			       =  {'''input_values''': input_values}
									return config, inputs_dict






@require_torch
class 				__lowercase			(			__snake_case   ,      __snake_case   ,      unittest.TestCase							):







					'''simple docstring'''




					__lowerCAmelCase  =  (
					    (
					        ASTModel,
					        ASTForAudioClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					__lowerCAmelCase  =  (
					    {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
					    if is_torch_available()
					    else {}
					)
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False
					__lowerCAmelCase  =  False







					def  _lowerCamelCase		(						self	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase	,			_UpperCAmelCase     ):


									if pipeline_test_casse_name == "AudioClassificationPipelineTests":
													return True

									return False







					def  _lowerCamelCase		(						self     ):
									__a :						str			       =  ASTModelTester(self     )
									__a :						Tuple			       =  ConfigTester(self	,			config_class=__UpperCamelCase	,			has_text_modality=__UpperCamelCase	,			hidden_size=37     )







					def  _lowerCamelCase		(						self     ):
									self.config_tester.run_common_tests()







					@unittest.skip(reason='''AST does not use inputs_embeds'''     )
					def  _lowerCamelCase		(						self     ):
									pass







					def  _lowerCamelCase		(						self     ):
									__a       ,						__a :						List[Any]			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						str			       =  model_class(__UpperCamelCase     )
													self.assertIsInstance(model.get_input_embeddings()	,			(nn.Module)     )
													__a :						int			       =  model.get_output_embeddings()
													self.assertTrue(x is None or isinstance(__UpperCamelCase	,			nn.Linear     )     )







					def  _lowerCamelCase		(						self     ):
									__a       ,						__a :						Any			       =  self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
													__a :						str			       =  model_class(__UpperCamelCase     )
													__a :						Optional[Any]			       =  inspect.signature(model.forward     )
													# signature.parameters is an OrderedDict => so arg_names order is deterministic
													__a :						Optional[int]			       =  [*signature.parameters.keys()]

													__a :						Optional[Any]			       =  ['''input_values''']
													self.assertListEqual(arg_names[:1]	,			__UpperCamelCase     )







					def  _lowerCamelCase		(						self     ):
									__a :						List[Any]			       =  self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__UpperCamelCase     )







					@slow
					def  _lowerCamelCase		(						self     ):


									for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__a :						Dict			       =  ASTModel.from_pretrained(__UpperCamelCase     )
													self.assertIsNotNone(__UpperCamelCase     )






def     __A      (			)		->		List[str]:
				__a :						int			       =  hf_hub_download(
				    repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''   ,       filename='''sample_audio.flac'''   ,       repo_type='''dataset''')

				__a       ,						__a :						Optional[Any]			       =  torchaudio.load(lowercase__)

				return audio, sampling_rate






@require_torch
@require_torchaudio
class 				__lowercase			(			unittest.TestCase							):







					'''simple docstring'''




					@cached_property
					def  _lowerCamelCase		(						self     ):
									return (
									    ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''     )
									    if is_torchaudio_available()
									    else None
									)







					@slow
					def  _lowerCamelCase		(						self     ):
									__a :						Union[str, Any]			       =  self.default_feature_extractor
									__a :						List[str]			       =  ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''     ).to(__UpperCamelCase     )

									__a :						List[Any]			       =  self.default_feature_extractor
									__a       ,						__a :						Union[str, Any]			       =  prepare_audio()
									__a :						str			       =  audio.squeeze().numpy()
									__a :						Optional[Any]			       =  feature_extractor(__UpperCamelCase	,			sampling_rate=__UpperCamelCase	,			return_tensors='''pt'''     ).to(__UpperCamelCase     )

									# forward pass
									with torch.no_grad():
													__a :						Union[str, Any]			       =  model(**__UpperCamelCase     )

									# verify the logits
									__a :						Any			       =  torch.Size((1, 527)     )
									self.assertEqual(outputs.logits.shape	,			__UpperCamelCase     )

									__a :						Optional[int]			       =  torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]     ).to(__UpperCamelCase     )

									self.assertTrue(torch.allclose(outputs.logits[0, :3]	,			__UpperCamelCase	,			atol=1e-4     )     )






"""simple docstring"""






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


A 			=  {
    '''configuration_jukebox''': [
        '''JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''JukeboxConfig''',
        '''JukeboxPriorConfig''',
        '''JukeboxVQVAEConfig''',
    ],
    '''tokenization_jukebox''': ['''JukeboxTokenizer'''],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		A 			=  [
		    '''JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''JukeboxModel''',
		    '''JukeboxPreTrainedModel''',
		    '''JukeboxVQVAE''',
		    '''JukeboxPrior''',
		]

if TYPE_CHECKING:
		from .configuration_jukebox import (
		    JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP,
		    JukeboxConfig,
		    JukeboxPriorConfig,
		    JukeboxVQVAEConfig,
		)
		from .tokenization_jukebox import JukeboxTokenizer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_jukebox import (
				    JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST,
				    JukeboxModel,
				    JukeboxPreTrainedModel,
				    JukeboxPrior,
				    JukeboxVQVAE,
				)

else:
		import sys

		A 			=  _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)