





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 					__A    :

			'''simple docstring'''







			def __init__(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase=1_3       ,  __lowerCAmelCase=2       ,  __lowerCAmelCase=2_4       ,  __lowerCAmelCase=1_6       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=True       ,  __lowerCAmelCase=3_2       ,  __lowerCAmelCase=5       ,  __lowerCAmelCase=4       ,  __lowerCAmelCase=3_7       ,  __lowerCAmelCase="gelu"       ,  __lowerCAmelCase=0.1       ,  __lowerCAmelCase=0.1       ,  __lowerCAmelCase=1_0       ,  __lowerCAmelCase=0.02       ,  __lowerCAmelCase=None       ,  __lowerCAmelCase=2       ,  __lowerCAmelCase=2       ,  ):



				'''simple docstring'''







				lowerCamelCase__								=		parent
				lowerCamelCase__								=		batch_size
				lowerCamelCase__								=		patch_size
				lowerCamelCase__								=		max_length
				lowerCamelCase__								=		num_mel_bins
				lowerCamelCase__								=		is_training
				lowerCamelCase__								=		use_labels
				lowerCamelCase__								=		hidden_size
				lowerCamelCase__								=		num_hidden_layers
				lowerCamelCase__								=		num_attention_heads
				lowerCamelCase__								=		intermediate_size
				lowerCamelCase__								=		hidden_act
				lowerCamelCase__								=		hidden_dropout_prob
				lowerCamelCase__								=		attention_probs_dropout_prob
				lowerCamelCase__								=		type_sequence_label_size
				lowerCamelCase__								=		initializer_range
				lowerCamelCase__								=		scope
				lowerCamelCase__								=		frequency_stride
				lowerCamelCase__								=		time_stride

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





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]							)

				lowerCamelCase__								=		None
				if self.use_labels:
					lowerCamelCase__								=		ids_tensor([self.batch_size]       ,  self.type_sequence_label_size							)

				lowerCamelCase__								=		self.get_config()

				return config, input_values, labels





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				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=__lowerCAmelCase       ,  initializer_range=self.initializer_range       ,  frequency_stride=self.frequency_stride       ,  time_stride=self.time_stride       ,  )





			def 		__lowerCamelCase				(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				lowerCamelCase__								=		ASTModel(config=__lowerCAmelCase							)
				model.to(__lowerCAmelCase							)
				model.eval()
				lowerCamelCase__								=		model(__lowerCAmelCase							)
				self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size)							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.prepare_config_and_inputs()
				(
				    (
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	(
				    lowerCamelCase__
				)				,	
				)								=		config_and_inputs
				lowerCamelCase__								=		{'''input_values''': input_values}
				return config, inputs_dict






@require_torch
class 					__A    (    lowerCAmelCase			,				lowerCAmelCase			,				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       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				if pipeline_test_casse_name == "AudioClassificationPipelineTests":
					return True

				return False





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		ASTModelTester(self							)
				lowerCamelCase__								=		ConfigTester(self       ,  config_class=__lowerCAmelCase       ,  has_text_modality=__lowerCAmelCase       ,  hidden_size=3_7							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				self.config_tester.run_common_tests()





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



				'''simple docstring'''







				pass





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__				,	lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs_for_common()

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





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__				,	lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					lowerCamelCase__								=		model_class(__lowerCAmelCase							)
					lowerCamelCase__								=		inspect.signature(model.forward							)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					lowerCamelCase__								=		[*signature.parameters.keys()]

					lowerCamelCase__								=		['''input_values''']
					self.assertListEqual(arg_names[:1]       ,  __lowerCAmelCase							)





			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__lowerCAmelCase							)





			@slow
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					lowerCamelCase__								=		ASTModel.from_pretrained(__lowerCAmelCase							)
					self.assertIsNotNone(__lowerCAmelCase							)





def lowerCAmelCase__()				->      Dict:







	'''simple docstring'''







	lowerCamelCase__								=		hf_hub_download(
	    repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''       ,filename='''sample_audio.flac'''       ,repo_type='''dataset'''							)

	lowerCamelCase__				,	lowerCamelCase__								=		torchaudio.load(__snake_case							)

	return audio, sampling_rate






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

			'''simple docstring'''







			@cached_property
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				return (
				    ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''							)
				    if is_torchaudio_available()
				    else None
				)





			@slow
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				lowerCamelCase__								=		self.default_feature_extractor
				lowerCamelCase__								=		ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''							).to(__lowerCAmelCase							)

				lowerCamelCase__								=		self.default_feature_extractor
				lowerCamelCase__				,	lowerCamelCase__								=		prepare_audio()
				lowerCamelCase__								=		audio.squeeze().numpy()
				lowerCamelCase__								=		feature_extractor(__lowerCAmelCase       ,  sampling_rate=__lowerCAmelCase       ,  return_tensors='''pt'''							).to(__lowerCAmelCase							)

				# forward pass
				with torch.no_grad():
					lowerCamelCase__								=		model(**__lowerCAmelCase							)

				# verify the logits
				lowerCamelCase__								=		torch.Size((1, 5_2_7)							)
				self.assertEqual(outputs.logits.shape       ,  __lowerCAmelCase							)

				lowerCamelCase__								=		torch.tensor([-0.8760, -7.0042, -8.6602]							).to(__lowerCAmelCase							)

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










import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin






class 					__A    (    lowerCAmelCase ):

			'''simple docstring'''







			lowerCAmelCase_							     =						"""Speech2TextFeatureExtractor"""
			lowerCAmelCase_							     =						"""Speech2TextTokenizer"""





			def __init__(    self       ,  __lowerCAmelCase       ,  __lowerCAmelCase							):



				'''simple docstring'''







				super().__init__(__lowerCAmelCase       ,  __lowerCAmelCase							)
				lowerCamelCase__								=		self.feature_extractor
				lowerCamelCase__								=		False





			def __call__(    self       ,  *__lowerCAmelCase       ,  **__lowerCAmelCase							):



				'''simple docstring'''







				if self._in_target_context_manager:
					return self.current_processor(*__lowerCAmelCase       ,  **__lowerCAmelCase							)

				if "raw_speech" in kwargs:
					warnings.warn('''Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead.'''							)
					lowerCamelCase__								=		kwargs.pop('''raw_speech'''							)
				else:
					lowerCamelCase__								=		kwargs.pop('''audio'''       ,  __lowerCAmelCase							)
				lowerCamelCase__								=		kwargs.pop('''sampling_rate'''       ,  __lowerCAmelCase							)
				lowerCamelCase__								=		kwargs.pop('''text'''       ,  __lowerCAmelCase							)
				if len(__lowerCAmelCase							) > 0:
					lowerCamelCase__								=		args[0]
					lowerCamelCase__								=		args[1:]

				if audio is None and text is None:
					raise ValueError('''You need to specify either an `audio` or `text` input to process.'''							)

				if audio is not None:
					lowerCamelCase__								=		self.feature_extractor(__lowerCAmelCase       ,  *__lowerCAmelCase       ,  sampling_rate=__lowerCAmelCase       ,  **__lowerCAmelCase							)
				if text is not None:
					lowerCamelCase__								=		self.tokenizer(__lowerCAmelCase       ,  **__lowerCAmelCase							)

				if text is None:
					return inputs
				elif audio is None:
					return encodings
				else:
					lowerCamelCase__								=		encodings['''input_ids''']
					return inputs





			def 		__lowerCamelCase				(    self       ,  *__lowerCAmelCase       ,  **__lowerCAmelCase							):



				'''simple docstring'''







				return self.tokenizer.batch_decode(*__lowerCAmelCase       ,  **__lowerCAmelCase							)





			def 		__lowerCamelCase				(    self       ,  *__lowerCAmelCase       ,  **__lowerCAmelCase							):



				'''simple docstring'''







				return self.tokenizer.decode(*__lowerCAmelCase       ,  **__lowerCAmelCase							)





			@contextmanager
			def 		__lowerCamelCase				(    self							):



				'''simple docstring'''







				warnings.warn(
				    '''`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your '''
				    '''labels by using the argument `text` of the regular `__call__` method (either in the same call as '''
				    '''your audio inputs, or in a separate call.'''							)
				lowerCamelCase__								=		True
				lowerCamelCase__								=		self.tokenizer
				yield
				lowerCamelCase__								=		self.feature_extractor
				lowerCamelCase__								=		False



