




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   :			Tuple      ,				UpperCAmelCase__   :			str      ,				UpperCAmelCase__   :			str=13      ,				UpperCAmelCase__   :			List[str]=2      ,				UpperCAmelCase__   :			Optional[int]=24      ,				UpperCAmelCase__   :			Any=16      ,				UpperCAmelCase__   :			Any=True      ,				UpperCAmelCase__   :			int=True      ,				UpperCAmelCase__   :			str=32      ,				UpperCAmelCase__   :			int=5      ,				UpperCAmelCase__   :			str=4      ,				UpperCAmelCase__   :			Optional[Any]=37      ,				UpperCAmelCase__   :			int="gelu"      ,				UpperCAmelCase__   :			Optional[int]=0.1      ,				UpperCAmelCase__   :			List[Any]=0.1      ,				UpperCAmelCase__   :			List[Any]=10      ,				UpperCAmelCase__   :			Optional[int]=0.02      ,				UpperCAmelCase__   :			Any=None      ,				UpperCAmelCase__   :			Optional[Any]=2      ,				UpperCAmelCase__   :			Tuple=2      ,				)		->str:





           '''simple docstring'''

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

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


    def  SCREAMING_SNAKE_CASE							(    self   :			str)		->str:





           '''simple docstring'''

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

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

           A__   				=					self.get_config()

           return config, input_values, labels


    def  SCREAMING_SNAKE_CASE							(    self   :			Tuple)		->Union[str, Any]:





           '''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  SCREAMING_SNAKE_CASE							(    self   :			Union[str, Any]      ,				UpperCAmelCase__   :			List[Any]      ,				UpperCAmelCase__   :			Dict      ,				UpperCAmelCase__   :			List[str])		->List[str]:





           '''simple docstring'''

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





    def  SCREAMING_SNAKE_CASE							(    self   :			Any)		->Any:





           '''simple docstring'''

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


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

    '''simple docstring'''






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


    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[int]      ,				UpperCAmelCase__   :			int      ,				UpperCAmelCase__   :			List[str]      ,				UpperCAmelCase__   :			List[str]      ,				UpperCAmelCase__   :			Tuple      ,				UpperCAmelCase__   :			str)		->Union[str, Any]:





           '''simple docstring'''

           if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                  return True

           return False


    def  SCREAMING_SNAKE_CASE							(    self   :			Tuple)		->Dict:





           '''simple docstring'''

           A__   				=					ASTModelTester(self)
           A__   				=					ConfigTester(self      ,				config_class=UpperCAmelCase__      ,				has_text_modality=UpperCAmelCase__      ,				hidden_size=37)


    def  SCREAMING_SNAKE_CASE							(    self   :			Union[str, Any])		->Optional[int]:





           '''simple docstring'''

           self.config_tester.run_common_tests()


    @unittest.skip(reason='''AST does not use inputs_embeds''')
    def  SCREAMING_SNAKE_CASE							(    self   :			Union[str, Any])		->Tuple:





           '''simple docstring'''

           pass


    def  SCREAMING_SNAKE_CASE							(    self   :			Union[str, Any])		->Union[str, Any]:





           '''simple docstring'''

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

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


    def  SCREAMING_SNAKE_CASE							(    self   :			Any)		->List[Any]:





           '''simple docstring'''

           A__				,							A__   				=					self.model_tester.prepare_config_and_inputs_for_common()

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

                  A__   				=					['''input_values''']
                  self.assertListEqual(arg_names[:1]      ,				UpperCAmelCase__)


    def  SCREAMING_SNAKE_CASE							(    self   :			str)		->str:





           '''simple docstring'''

           A__   				=					self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*UpperCAmelCase__)





    @slow
    def  SCREAMING_SNAKE_CASE							(    self   :			List[str])		->Dict:





           '''simple docstring'''

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







def SCREAMING_SNAKE_CASE       ( )     -> Tuple:



       """simple docstring"""

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

       A__				,							A__   				=					torchaudio.load(lowercase_		)

       return audio, sampling_rate


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

    '''simple docstring'''






    @cached_property
    def  SCREAMING_SNAKE_CASE							(    self   :			Optional[int])		->Optional[int]:





           '''simple docstring'''

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





    @slow
    def  SCREAMING_SNAKE_CASE							(    self   :			List[Any])		->Optional[int]:





           '''simple docstring'''

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

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

           # forward pass
           with torch.no_grad():
                  A__   				=					model(**UpperCAmelCase__)

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

           A__   				=					torch.tensor([-0.8760, -7.0042, -8.6602]).to(UpperCAmelCase__)

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







from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable


_lowerCamelCase			:	Union[str, Any]							 =     {"""configuration_dpt""": ["""DPT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """DPTConfig"""]}

try:
  if not is_vision_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _lowerCamelCase			:	Optional[Any]							 =     ["""DPTFeatureExtractor"""]
  _lowerCamelCase			:	int							 =     ["""DPTImageProcessor"""]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  _lowerCamelCase			:	Optional[int]							 =     [
      """DPT_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """DPTForDepthEstimation""",
      """DPTForSemanticSegmentation""",
      """DPTModel""",
      """DPTPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig

  try:
    if not is_vision_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .feature_extraction_dpt import DPTFeatureExtractor
    from .image_processing_dpt import DPTImageProcessor

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_dpt import (
        DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPTForDepthEstimation,
        DPTForSemanticSegmentation,
        DPTModel,
        DPTPreTrainedModel,
    )


else:
  import sys

  _lowerCamelCase			:	Any							 =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)


