

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


   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      ,    ):





      """simple docstring"""





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

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


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





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

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

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


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       ASTModel(config=_UpperCamelCase  )
      model.to(_UpperCamelCase  )
      model.eval()
      _lowercase      :				Tuple      					=       model(_UpperCamelCase  )
      self.parent.assertEqual(result.last_hidden_state.shape      ,    (self.batch_size, self.seq_length, self.hidden_size)  )






   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       self.prepare_config_and_inputs()
      (
          (
          _lowercase
      )					,				(
          _lowercase
      )					,				(
          _lowercase
      )					,				
      )      :				Optional[Any]      					=       config_and_inputs
      _lowercase      :				str      					=       {"input_values": input_values}
      return config, inputs_dict




@require_torch
class        a__  (							lowerCamelCase_  ,				lowerCamelCase_  ,				unittest.TestCase  ):
   _SCREAMING_SNAKE_CASE   :					Any     	=							(
       (
           ASTModel,
           ASTForAudioClassification,
       )
       if is_torch_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE   :					str     	=							(
       {'audio-classification': ASTForAudioClassification, 'feature-extraction': ASTModel}
       if is_torch_available()
       else {}
   )
   _SCREAMING_SNAKE_CASE   :					Optional[int]     	=							False
   _SCREAMING_SNAKE_CASE   :					str     	=							False
   _SCREAMING_SNAKE_CASE   :					Tuple     	=							False
   _SCREAMING_SNAKE_CASE   :					Optional[Any]     	=							False


   def 						_lowerCamelCase       (			self      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase      ,    _UpperCamelCase  ):





      """simple docstring"""





      if pipeline_test_casse_name == "AudioClassificationPipelineTests":
         return True

      return False


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				List[str]      					=       ASTModelTester(self  )
      _lowercase      :				int      					=       ConfigTester(self      ,    config_class=_UpperCamelCase      ,    has_text_modality=_UpperCamelCase      ,    hidden_size=37  )


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





      _lowercase					,				_lowercase      :				List[str]      					=       self.model_tester.prepare_config_and_inputs_for_common()

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


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase					,				_lowercase      :				List[Any]      					=       self.model_tester.prepare_config_and_inputs_for_common()

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

         _lowercase      :				List[Any]      					=       ["input_values"]
         self.assertListEqual(arg_names[:1]      ,    _UpperCamelCase  )


   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      _lowercase      :				Optional[Any]      					=       self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_UpperCamelCase  )






   @slow
   def 						_lowerCamelCase       (			self  ):





      """simple docstring"""





      for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _lowercase      :				Optional[Any]      					=       ASTModel.from_pretrained(_UpperCamelCase  )
         self.assertIsNotNone(_UpperCamelCase  )







def  _A		(     )      ->     Any:
   _lowercase      :				Optional[Any]      					=       hf_hub_download(
       repo_id="nielsr/audio-spectogram-transformer-checkpoint"		,							filename="sample_audio.flac"		,							repo_type="dataset"					)

   _lowercase					,				_lowercase      :				List[str]      					=       torchaudio.load(snake_case					)

   return audio, sampling_rate


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


   @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"""





      _lowercase      :				List[Any]      					=       self.default_feature_extractor
      _lowercase      :				Tuple      					=       ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"  ).to(_UpperCamelCase  )

      _lowercase      :				str      					=       self.default_feature_extractor
      _lowercase					,				_lowercase      :				List[Any]      					=       prepare_audio()
      _lowercase      :				Optional[Any]      					=       audio.squeeze().numpy()
      _lowercase      :				Optional[Any]      					=       feature_extractor(_UpperCamelCase      ,    sampling_rate=_UpperCamelCase      ,    return_tensors="pt"  ).to(_UpperCamelCase  )

      # forward pass
      with torch.no_grad():
         _lowercase      :				Optional[int]      					=       model(**_UpperCamelCase  )

      # verify the logits
      _lowercase      :				Tuple      					=       torch.Size((1, 527)  )
      self.assertEqual(outputs.logits.shape      ,    _UpperCamelCase  )

      _lowercase      :				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 __future__ import annotations







def  _A		(     snake_case		,							snake_case = None		,							snake_case = None					)      ->     None:
   if start is None:
      _lowercase      :				Dict      					=       0

   if end is None:
      _lowercase      :				List[Any]      					=       len(snake_case					) - 1

   if start >= end:
      return

   _lowercase      :				int      					=       (start + end) // 2

   slowsort(snake_case		,							snake_case		,							snake_case					)
   slowsort(snake_case		,							mid + 1		,							snake_case					)

   if sequence[end] < sequence[mid]:
      _lowercase					,				_lowercase      :				Any      					=       sequence[mid], sequence[end]

   slowsort(snake_case		,							snake_case		,							end - 1					)


if __name__ == "__main__":
    from doctest import testmod

    testmod()






