

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		:	str			,     __lowerCamelCase		:	str			,     __lowerCamelCase		:	Any=13			,     __lowerCamelCase		:	List[str]=2			,     __lowerCamelCase		:	Union[str, Any]=24			,     __lowerCamelCase		:	Union[str, Any]=16			,     __lowerCamelCase		:	Optional[int]=True			,     __lowerCamelCase		:	Union[str, Any]=True			,     __lowerCamelCase		:	List[Any]=32			,     __lowerCamelCase		:	str=5			,     __lowerCamelCase		:	List[Any]=4			,     __lowerCamelCase		:	Optional[int]=37			,     __lowerCamelCase		:	Tuple="gelu"			,     __lowerCamelCase		:	Any=0.1			,     __lowerCamelCase		:	Optional[Any]=0.1			,     __lowerCamelCase		:	Tuple=10			,     __lowerCamelCase		:	Optional[int]=0.02			,     __lowerCamelCase		:	Optional[Any]=None			,     __lowerCamelCase		:	List[Any]=2			,     __lowerCamelCase		:	Optional[Any]=2			,     )	->							Optional[int]:
       SCREAMING_SNAKE_CASE__					=					parent
       SCREAMING_SNAKE_CASE__					=					batch_size
       SCREAMING_SNAKE_CASE__					=					patch_size
       SCREAMING_SNAKE_CASE__					=					max_length
       SCREAMING_SNAKE_CASE__					=					num_mel_bins
       SCREAMING_SNAKE_CASE__					=					is_training
       SCREAMING_SNAKE_CASE__					=					use_labels
       SCREAMING_SNAKE_CASE__					=					hidden_size
       SCREAMING_SNAKE_CASE__					=					num_hidden_layers
       SCREAMING_SNAKE_CASE__					=					num_attention_heads
       SCREAMING_SNAKE_CASE__					=					intermediate_size
       SCREAMING_SNAKE_CASE__					=					hidden_act
       SCREAMING_SNAKE_CASE__					=					hidden_dropout_prob
       SCREAMING_SNAKE_CASE__					=					attention_probs_dropout_prob
       SCREAMING_SNAKE_CASE__					=					type_sequence_label_size
       SCREAMING_SNAKE_CASE__					=					initializer_range
       SCREAMING_SNAKE_CASE__					=					scope
       SCREAMING_SNAKE_CASE__					=					frequency_stride
       SCREAMING_SNAKE_CASE__					=					time_stride

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






  def    lowercase_	(							self		:	Union[str, Any]      )	->							str:
       SCREAMING_SNAKE_CASE__					=					floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

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

       SCREAMING_SNAKE_CASE__					=					self.get_config()

       return config, input_values, labels






  def    lowercase_	(							self		:	List[str]      )	->							Union[str, Any]:
       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    lowercase_	(							self		:	List[str]			,     __lowerCamelCase		:	Any			,     __lowerCamelCase		:	Any			,     __lowerCamelCase		:	Union[str, Any]      )	->							Tuple:
       SCREAMING_SNAKE_CASE__					=					ASTModel(config=__lowerCamelCase      )
       model.to(__lowerCamelCase      )
       model.eval()
       SCREAMING_SNAKE_CASE__					=					model(__lowerCamelCase      )
       self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)      )







  def    lowercase_	(							self		:	Optional[int]      )	->							Any:
       SCREAMING_SNAKE_CASE__					=					self.prepare_config_and_inputs()
       (
           (
           SCREAMING_SNAKE_CASE__
       ),(
           SCREAMING_SNAKE_CASE__
       ),(
           SCREAMING_SNAKE_CASE__
       ),
       )					=					config_and_inputs
       SCREAMING_SNAKE_CASE__					=					{'''input_values''': input_values}
       return config, inputs_dict






@require_torch
class  UpperCAmelCase__	( A__		,  A__		,  unittest.TestCase ):






  """simple docstring"""


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






  def    lowercase_	(							self		:	Union[str, Any]			,     __lowerCamelCase		:	Tuple			,     __lowerCamelCase		:	Optional[Any]			,     __lowerCamelCase		:	int			,     __lowerCamelCase		:	Optional[int]			,     __lowerCamelCase		:	List[Any]      )	->							Dict:
       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
            return True

       return False






  def    lowercase_	(							self		:	str      )	->							Union[str, Any]:
       SCREAMING_SNAKE_CASE__					=					ASTModelTester(self      )
       SCREAMING_SNAKE_CASE__					=					ConfigTester(self			,     config_class=__lowerCamelCase			,     has_text_modality=__lowerCamelCase			,     hidden_size=37      )






  def    lowercase_	(							self		:	Dict      )	->							List[str]:
       self.config_tester.run_common_tests()






  @unittest.skip(reason='''AST does not use inputs_embeds'''      )
  def    lowercase_	(							self		:	List[str]      )	->							str:
       pass






  def    lowercase_	(							self		:	Any      )	->							int:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()

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






  def    lowercase_	(							self		:	str      )	->							str:
       SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs_for_common()

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

            SCREAMING_SNAKE_CASE__					=					['''input_values''']
            self.assertListEqual(arg_names[:1]			,     __lowerCamelCase      )






  def    lowercase_	(							self		:	str      )	->							Optional[Any]:
       SCREAMING_SNAKE_CASE__					=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__lowerCamelCase      )







  @slow
  def    lowercase_	(							self		:	List[str]      )	->							List[str]:
       for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            SCREAMING_SNAKE_CASE__					=					ASTModel.from_pretrained(__lowerCamelCase      )
            self.assertIsNotNone(__lowerCamelCase      )



def        UpperCAmelCase_     (		):





     '''simple docstring'''




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

     SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					torchaudio.load(_A       )

     return audio, sampling_rate







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






  """simple docstring"""


  @cached_property
  def    lowercase_	(							self		:	List[Any]      )	->							Any:
       return (
           ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      )
           if is_torchaudio_available()
           else None
       )







  @slow
  def    lowercase_	(							self		:	List[str]      )	->							Optional[int]:
       SCREAMING_SNAKE_CASE__					=					self.default_feature_extractor
       SCREAMING_SNAKE_CASE__					=					ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      ).to(__lowerCamelCase      )

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

       # forward pass
       with torch.no_grad():
            SCREAMING_SNAKE_CASE__					=					model(**__lowerCamelCase      )

       # verify the logits
       SCREAMING_SNAKE_CASE__					=					torch.Size((1, 527)      )
       self.assertEqual(outputs.logits.shape			,     __lowerCamelCase      )

       SCREAMING_SNAKE_CASE__					=					torch.tensor([-0.8760, -7.0042, -8.6602]      ).to(__lowerCamelCase      )

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





import random
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					a[left_index]
     SCREAMING_SNAKE_CASE__					=					left_index + 1
     for j in range(left_index + 1   ,	_A       ):
          if a[j] < pivot:
               SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					a[i], a[j]
               i += 1
     SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					a[i - 1], a[left_index]
     return i - 1
def        UpperCAmelCase_     (		_A   ,	_A   ,	_A       ):





     '''simple docstring'''




     if left < right:
          SCREAMING_SNAKE_CASE__					=					random.randint(_A   ,	right - 1       )
          SCREAMING_SNAKE_CASE__,SCREAMING_SNAKE_CASE__					=					(
              a[left],
              a[pivot],
          )  # switches the pivot with the left most bound
          SCREAMING_SNAKE_CASE__					=					partition(_A   ,	_A   ,	_A       )
          quick_sort_random(
              _A   ,	_A   ,	_A       )  # recursive quicksort to the left of the pivot point
          quick_sort_random(
              _A   ,	pivot_index + 1   ,	_A       )  # recursive quicksort to the right of the pivot point
def        UpperCAmelCase_     (		):





     '''simple docstring'''




     SCREAMING_SNAKE_CASE__					=					input('''Enter numbers separated by a comma:\n'''       ).strip()
     SCREAMING_SNAKE_CASE__					=					[int(_A       ) for item in user_input.split(''','''       )]

     quick_sort_random(_A   ,	0   ,	len(_A       )       )

     print(_A       )


if __name__ == "__main__":
       main()


