


'''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    UpperCAmelCase_	:
       '''simple docstring'''






       def __init__(     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE=13 ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=24 ,					__SCREAMING_SNAKE_CASE=16 ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=True ,					__SCREAMING_SNAKE_CASE=32 ,					__SCREAMING_SNAKE_CASE=5 ,					__SCREAMING_SNAKE_CASE=4 ,					__SCREAMING_SNAKE_CASE=37 ,					__SCREAMING_SNAKE_CASE="gelu" ,					__SCREAMING_SNAKE_CASE=0.1 ,					__SCREAMING_SNAKE_CASE=0.1 ,					__SCREAMING_SNAKE_CASE=10 ,					__SCREAMING_SNAKE_CASE=0.02 ,					__SCREAMING_SNAKE_CASE=None ,					__SCREAMING_SNAKE_CASE=2 ,					__SCREAMING_SNAKE_CASE=2 ,					):




              """simple docstring"""




              UpperCamelCase    :	Optional[int]   	=		parent
              UpperCamelCase    :	List[Any]   	=		batch_size
              UpperCamelCase    :	List[str]   	=		patch_size
              UpperCamelCase    :	str   	=		max_length
              UpperCamelCase    :	int   	=		num_mel_bins
              UpperCamelCase    :	Any   	=		is_training
              UpperCamelCase    :	int   	=		use_labels
              UpperCamelCase    :	List[str]   	=		hidden_size
              UpperCamelCase    :	Optional[Any]   	=		num_hidden_layers
              UpperCamelCase    :	Dict   	=		num_attention_heads
              UpperCamelCase    :	Any   	=		intermediate_size
              UpperCamelCase    :	Tuple   	=		hidden_act
              UpperCamelCase    :	List[Any]   	=		hidden_dropout_prob
              UpperCamelCase    :	Union[str, Any]   	=		attention_probs_dropout_prob
              UpperCamelCase    :	Union[str, Any]   	=		type_sequence_label_size
              UpperCamelCase    :	int   	=		initializer_range
              UpperCamelCase    :	Optional[int]   	=		scope
              UpperCamelCase    :	Optional[Any]   	=		frequency_stride
              UpperCamelCase    :	Any   	=		time_stride

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






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	List[str]   	=		floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]						)

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

              UpperCamelCase    :	List[Any]   	=		self.get_config()

              return config, input_values, labels






       def  _lowercase   (     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=__SCREAMING_SNAKE_CASE ,					initializer_range=self.initializer_range ,					frequency_stride=self.frequency_stride ,					time_stride=self.time_stride ,					)






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              UpperCamelCase    :	Dict   	=		ASTModel(config=__SCREAMING_SNAKE_CASE						)
              model.to(__SCREAMING_SNAKE_CASE						)
              model.eval()
              UpperCamelCase    :	Optional[int]   	=		model(__SCREAMING_SNAKE_CASE						)
              self.parent.assertEqual(result.last_hidden_state.shape ,					(self.batch_size, self.seq_length, self.hidden_size)						)






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	str   	=		self.prepare_config_and_inputs()
              (
                  (
                  UpperCamelCase       
              )	, (
                  UpperCamelCase       
              )	, (
                  UpperCamelCase       
              )	,        
              )    :	Tuple   	=		config_and_inputs
              UpperCamelCase    :	Optional[int]   	=		{'''input_values''': input_values}
              return config, inputs_dict




@require_torch
class    UpperCAmelCase_	(							_a,     _a,     unittest.TestCase):
       '''simple docstring'''
       __UpperCamelCase      :     List[Any]							=					(
           (
               ASTModel,
               ASTForAudioClassification,
           )
           if is_torch_available()
           else ()
       )
       __UpperCamelCase      :     Any							=					(
           {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
           if is_torch_available()
           else {}
       )
       __UpperCamelCase      :     List[Any]							=					False
       __UpperCamelCase      :     Any							=					False
       __UpperCamelCase      :     Any							=					False
       __UpperCamelCase      :     Any							=					False






       def  _lowercase   (     self ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE ,					__SCREAMING_SNAKE_CASE						):




              """simple docstring"""




              if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                     return True

              return False






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	Tuple   	=		ASTModelTester(self						)
              UpperCamelCase    :	Optional[int]   	=		ConfigTester(self ,					config_class=__SCREAMING_SNAKE_CASE ,					has_text_modality=__SCREAMING_SNAKE_CASE ,					hidden_size=37						)






       def  _lowercase   (     self						):




              """simple docstring"""




              self.config_tester.run_common_tests()






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




              """simple docstring"""




              pass






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase	, UpperCamelCase    :	Optional[int]   	=		self.model_tester.prepare_config_and_inputs_for_common()

              for model_class in self.all_model_classes:
                     UpperCamelCase    :	str   	=		model_class(__SCREAMING_SNAKE_CASE						)
                     self.assertIsInstance(model.get_input_embeddings() ,					(nn.Module)						)
                     UpperCamelCase    :	Optional[Any]   	=		model.get_output_embeddings()
                     self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE ,					nn.Linear						)						)






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase	, UpperCamelCase    :	Dict   	=		self.model_tester.prepare_config_and_inputs_for_common()

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

                     UpperCamelCase    :	Dict   	=		['''input_values''']
                     self.assertListEqual(arg_names[:1] ,					__SCREAMING_SNAKE_CASE						)






       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	List[str]   	=		self.model_tester.prepare_config_and_inputs()
              self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE						)






       @slow
       def  _lowercase   (     self						):




              """simple docstring"""




              for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                     UpperCamelCase    :	Optional[int]   	=		ASTModel.from_pretrained(__SCREAMING_SNAKE_CASE						)
                     self.assertIsNotNone(__SCREAMING_SNAKE_CASE						)




def      a	(							):






       """simple docstring"""





       UpperCamelCase    :	Optional[int]   	=		hf_hub_download(
           repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''							,			filename='''sample_audio.flac'''							,			repo_type='''dataset'''       )

       UpperCamelCase	, UpperCamelCase    :	Optional[Any]   	=		torchaudio.load(SCREAMING_SNAKE_CASE_       )

       return audio, sampling_rate



@require_torch
@require_torchaudio
class    UpperCAmelCase_	(							unittest.TestCase):
       '''simple docstring'''






       @cached_property
       def  _lowercase   (     self						):




              """simple docstring"""




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






       @slow
       def  _lowercase   (     self						):




              """simple docstring"""




              UpperCamelCase    :	List[Any]   	=		self.default_feature_extractor
              UpperCamelCase    :	Any   	=		ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''						).to(__SCREAMING_SNAKE_CASE						)

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

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

              # verify the logits
              UpperCamelCase    :	Union[str, Any]   	=		torch.Size((1, 527)						)
              self.assertEqual(outputs.logits.shape ,					__SCREAMING_SNAKE_CASE						)

              UpperCamelCase    :	List[Any]   	=		torch.tensor([-0.8_760, -7.0_042, -8.6_602]						).to(__SCREAMING_SNAKE_CASE						)

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





from .imports import is_tqdm_available


if is_tqdm_available():
  from tqdm.auto import tqdm as _tqdm

from ..state import PartialState


def      a	(							SCREAMING_SNAKE_CASE_      :		bool = True							,			*SCREAMING_SNAKE_CASE_      :		List[str]							,			**SCREAMING_SNAKE_CASE_      :		Tuple       ):






       """simple docstring"""





       if not is_tqdm_available():
              raise ImportError('''Accelerate\'s `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.'''       )
       UpperCamelCase    :	int   	=		False
       if main_process_only:
              UpperCamelCase    :	int   	=		PartialState().local_process_index == 0
       return _tqdm(*SCREAMING_SNAKE_CASE_							,			**SCREAMING_SNAKE_CASE_							,			disable=SCREAMING_SNAKE_CASE_       )

