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



  """simple docstring"""







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

    '''simple docstring'''







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

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







  def  lowercase_	(				self       ):

    '''simple docstring'''







    __UpperCAmelCase:       Union[str, Any]		=			floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]       )

    __UpperCAmelCase:       Dict		=			None
    if self.use_labels:
      __UpperCAmelCase:       str		=			ids_tensor([self.batch_size] ,     self.type_sequence_label_size       )

    __UpperCAmelCase:       int		=			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=snake_case_ ,     initializer_range=self.initializer_range ,     frequency_stride=self.frequency_stride ,     time_stride=self.time_stride ,     )







  def  lowercase_	(				self ,     snake_case_ ,     snake_case_ ,     snake_case_       ):

    '''simple docstring'''







    __UpperCAmelCase:       List[Any]		=			ASTModel(config=snake_case_       )
    model.to(snake_case_       )
    model.eval()
    __UpperCAmelCase:       Union[str, Any]		=			model(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:       List[Any]		=			self.prepare_config_and_inputs()
    (
        __UpperCAmelCase      
    ):       str		=			config_and_inputs
    __UpperCAmelCase:       Optional[int]		=			{'input_values': input_values}
    return config, inputs_dict




@require_torch
class  a			(							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  lowercase_	(				self ,     snake_case_ ,     snake_case_ ,     snake_case_ ,     snake_case_ ,     snake_case_       ):

    '''simple docstring'''







    if pipeline_test_casse_name == "AudioClassificationPipelineTests":
      return True

    return False







  def  lowercase_	(				self       ):

    '''simple docstring'''







    __UpperCAmelCase:       Optional[Any]		=			ASTModelTester(self       )
    __UpperCAmelCase:       Dict		=			ConfigTester(self ,     config_class=snake_case_ ,     has_text_modality=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:       int		=			self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __UpperCAmelCase:       List[Any]		=			model_class(snake_case_       )
      self.assertIsInstance(model.get_input_embeddings() ,     (nn.Module)       )
      __UpperCAmelCase:       int		=			model.get_output_embeddings()
      self.assertTrue(x is None or isinstance(snake_case_ ,     nn.Linear       )       )







  def  lowercase_	(				self       ):

    '''simple docstring'''







    __UpperCAmelCase:       Any		=			self.model_tester.prepare_config_and_inputs_for_common()

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

      __UpperCAmelCase:       List[Any]		=			['input_values']
      self.assertListEqual(arg_names[:1] ,     snake_case_       )







  def  lowercase_	(				self       ):

    '''simple docstring'''







    __UpperCAmelCase:       List[str]		=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*snake_case_       )







  @slow
  def  lowercase_	(				self       ):

    '''simple docstring'''







    for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __UpperCAmelCase:       int		=			ASTModel.from_pretrained(snake_case_       )
      self.assertIsNotNone(snake_case_       )






def 			UpperCamelCase__       (       )				->						str:
  __UpperCAmelCase:       List[Any]		=			hf_hub_download(
      repo_id="""nielsr/audio-spectogram-transformer-checkpoint""" ,     filename="""sample_audio.flac""" ,     repo_type="""dataset"""  )

  __UpperCAmelCase:       List[str]		=			torchaudio.load(lowerCAmelCase__  )

  return audio, sampling_rate







@require_torch
@require_torchaudio
class  a			(							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:       Optional[Any]		=			self.default_feature_extractor
    __UpperCAmelCase:       List[Any]		=			ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""       ).to(snake_case_       )

    __UpperCAmelCase:       Union[str, Any]		=			self.default_feature_extractor
    __UpperCAmelCase:       Union[str, Any]		=			prepare_audio()
    __UpperCAmelCase:       Any		=			audio.squeeze().numpy()
    __UpperCAmelCase:       Optional[int]		=			feature_extractor(snake_case_ ,     sampling_rate=snake_case_ ,     return_tensors="""pt"""       ).to(snake_case_       )

    # forward pass
    with torch.no_grad():
      __UpperCAmelCase:       Tuple		=			model(**snake_case_       )

    # verify the logits
    __UpperCAmelCase:       str		=			torch.Size((1, 527)       )
    self.assertEqual(outputs.logits.shape ,     snake_case_       )

    __UpperCAmelCase:       List[str]		=			torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]       ).to(snake_case_       )

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






import warnings

from ...utils import logging
from .image_processing_yolos import YolosImageProcessor


_lowercase		:  int			       =logging.get_logger(__name__)






class 						UpperCamelCase_  (  snake_case__							):



					def __init__(		self     :     Tuple       ,      *lowerCamelCase     :     List[Any]       ,      **lowerCamelCase     :     Union[str, Any]						):
							warnings.warn(
							    'The class YolosFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
							    ' use YolosImageProcessor instead.'       ,      lowerCamelCase       ,      )
							super().__init__(*lowerCamelCase       ,      **lowerCamelCase						)
