






'''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			,		_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.0_2			,		_SCREAMING_SNAKE_CASE=None			,		_SCREAMING_SNAKE_CASE=2			,		_SCREAMING_SNAKE_CASE=2			,		)  ->      Union[str, Any]:



        """simple docstring"""






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

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

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



        """simple docstring"""






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

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

        UpperCamelCase				  =					self.get_config()

        return config, input_values, labels

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

  def   A__						(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE      )  ->      List[Any]:



        """simple docstring"""






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


  def   A__						(      self      )  ->      List[str]:



        """simple docstring"""






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






@require_torch
class 				a_						(			lowerCamelCase	,       lowerCamelCase	,       unittest.TestCase				):
  lowercase     		=      (
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  lowercase     		=      (
      {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
      if is_torch_available()
      else {}
  )
  lowercase     		=      False
  lowercase     		=      False
  lowercase     		=      False
  lowercase     		=      False

  def   A__						(      self			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE			,		_SCREAMING_SNAKE_CASE      )  ->      Optional[Any]:



        """simple docstring"""






        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

        return False

  def   A__						(      self      )  ->      Optional[int]:



        """simple docstring"""






        UpperCamelCase				  =					ASTModelTester(self      )
        UpperCamelCase				  =					ConfigTester(self			,		config_class=_SCREAMING_SNAKE_CASE			,		has_text_modality=_SCREAMING_SNAKE_CASE			,		hidden_size=37      )

  def   A__						(      self      )  ->      Any:



        """simple docstring"""






        self.config_tester.run_common_tests()

  @unittest.skip(reason="""AST does not use inputs_embeds"""      )
  def   A__						(      self      )  ->      Optional[Any]:



        """simple docstring"""






        pass

  def   A__						(      self      )  ->      int:



        """simple docstring"""






        UpperCamelCase				  =					self.model_tester.prepare_config_and_inputs_for_common()

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

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



        """simple docstring"""






        UpperCamelCase				  =					self.model_tester.prepare_config_and_inputs_for_common()

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

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

  def   A__						(      self      )  ->      Dict:



        """simple docstring"""






        UpperCamelCase				  =					self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE      )


  @slow
  def   A__						(      self      )  ->      List[Any]:



        """simple docstring"""






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







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

      UpperCamelCase				  =					torchaudio.load(lowercase__    )

      return audio, sampling_rate






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

  @cached_property
  def   A__						(      self      )  ->      List[str]:



        """simple docstring"""






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


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



        """simple docstring"""






        UpperCamelCase				  =					self.default_feature_extractor
        UpperCamelCase				  =					ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""      ).to(_SCREAMING_SNAKE_CASE      )

        UpperCamelCase				  =					self.default_feature_extractor
        UpperCamelCase				  =					prepare_audio()
        UpperCamelCase				  =					audio.squeeze().numpy()
        UpperCamelCase				  =					feature_extractor(_SCREAMING_SNAKE_CASE			,		sampling_rate=_SCREAMING_SNAKE_CASE			,		return_tensors="""pt"""      ).to(_SCREAMING_SNAKE_CASE      )

        # forward pass
        with torch.no_grad():
              UpperCamelCase				  =					model(**_SCREAMING_SNAKE_CASE      )

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

        UpperCamelCase				  =					torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]      ).to(_SCREAMING_SNAKE_CASE      )

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






"""simple docstring"""






# Imports
import numpy as np






class lowerCAmelCase__	:






			'''simple docstring'''



			def __init__(  self  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ):
							self.set_matricies(red=lowercase  ,      green=lowercase  ,      blue=lowercase  ,      red_edge=lowercase  ,      nir=lowercase  )
			def 					A_    (  self  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ):
							if red is not None:
											_lowerCamelCase     :			Optional[int]    =    red
							if green is not None:
											_lowerCamelCase     :			Optional[Any]    =    green
							if blue is not None:
											_lowerCamelCase     :			Tuple    =    blue
							if red_edge is not None:
											_lowerCamelCase     :			Optional[Any]    =    red_edge
							if nir is not None:
											_lowerCamelCase     :			Union[str, Any]    =    nir
							return True
			def 					A_    (  self  ,      lowercase=""  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ,      lowercase=None  ):
							self.set_matricies(red=lowercase  ,      green=lowercase  ,      blue=lowercase  ,      red_edge=lowercase  ,      nir=lowercase  )
							_lowerCamelCase     :			str    =    {
							    'ARVI2': self.arvaa,
							    'CCCI': self.ccci,
							    'CVI': self.cvi,
							    'GLI': self.gli,
							    'NDVI': self.ndvi,
							    'BNDVI': self.bndvi,
							    'redEdgeNDVI': self.red_edge_ndvi,
							    'GNDVI': self.gndvi,
							    'GBNDVI': self.gbndvi,
							    'GRNDVI': self.grndvi,
							    'RBNDVI': self.rbndvi,
							    'PNDVI': self.pndvi,
							    'ATSAVI': self.atsavi,
							    'BWDRVI': self.bwdrvi,
							    'CIgreen': self.ci_green,
							    'CIrededge': self.ci_rededge,
							    'CI': self.ci,
							    'CTVI': self.ctvi,
							    'GDVI': self.gdvi,
							    'EVI': self.evi,
							    'GEMI': self.gemi,
							    'GOSAVI': self.gosavi,
							    'GSAVI': self.gsavi,
							    'Hue': self.hue,
							    'IVI': self.ivi,
							    'IPVI': self.ipvi,
							    'I': self.i,
							    'RVI': self.rvi,
							    'MRVI': self.mrvi,
							    'MSAVI': self.m_savi,
							    'NormG': self.norm_g,
							    'NormNIR': self.norm_nir,
							    'NormR': self.norm_r,
							    'NGRDI': self.ngrdi,
							    'RI': self.ri,
							    'S': self.s,
							    'IF': self._if,
							    'DVI': self.dvi,
							    'TVI': self.tvi,
							    'NDRE': self.ndre,
							}

							try:
											return funcs[index]()
							except KeyError:
											print('Index not in the list!'  )
											return False
			def 					A_    (  self  ):
							return -0.18 + (1.17 * ((self.nir - self.red) / (self.nir + self.red)))
			def 					A_    (  self  ):
							return ((self.nir - self.redEdge) / (self.nir + self.redEdge)) / (
							    (self.nir - self.red) / (self.nir + self.red)
							)
			def 					A_    (  self  ):
							return self.nir * (self.red / (self.green**2))
			def 					A_    (  self  ):
							return (2 * self.green - self.red - self.blue) / (
							    2 * self.green + self.red + self.blue
							)
			def 					A_    (  self  ):
							return (self.nir - self.red) / (self.nir + self.red)
			def 					A_    (  self  ):
							return (self.nir - self.blue) / (self.nir + self.blue)
			def 					A_    (  self  ):
							return (self.redEdge - self.red) / (self.redEdge + self.red)
			def 					A_    (  self  ):
							return (self.nir - self.green) / (self.nir + self.green)
			def 					A_    (  self  ):
							return (self.nir - (self.green + self.blue)) / (
							    self.nir + (self.green + self.blue)
							)
			def 					A_    (  self  ):
							return (self.nir - (self.green + self.red)) / (
							    self.nir + (self.green + self.red)
							)
			def 					A_    (  self  ):
							return (self.nir - (self.blue + self.red)) / (self.nir + (self.blue + self.red))
			def 					A_    (  self  ):
							return (self.nir - (self.green + self.red + self.blue)) / (
							    self.nir + (self.green + self.red + self.blue)
							)
			def 					A_    (  self  ,      lowercase=0.08  ,      lowercase=1.22  ,      lowercase=0.03  ):
							return a * (
							    (self.nir - a * self.red - b)
							    / (a * self.nir + self.red - a * b + x * (1 + a**2))
							)
			def 					A_    (  self  ):
							return (0.1 * self.nir - self.blue) / (0.1 * self.nir + self.blue)
			def 					A_    (  self  ):
							return (self.nir / self.green) - 1
			def 					A_    (  self  ):
							return (self.nir / self.redEdge) - 1
			def 					A_    (  self  ):
							return (self.red - self.blue) / self.red
			def 					A_    (  self  ):
							_lowerCamelCase     :			Any    =    self.ndvi()
							return ((ndvi + 0.5) / (abs(ndvi + 0.5  ))) * (abs(ndvi + 0.5  ) ** (1 / 2))
			def 					A_    (  self  ):
							return self.nir - self.green
			def 					A_    (  self  ):
							return 2.5 * (
							    (self.nir - self.red) / (self.nir + 6 * self.red - 7.5 * self.blue + 1)
							)
			def 					A_    (  self  ):
							_lowerCamelCase     :			Any    =    (2 * (self.nir**2 - self.red**2) + 1.5 * self.nir + 0.5 * self.red) / (
							    self.nir + self.red + 0.5
							)
							return n * (1 - 0.25 * n) - (self.red - 0.1_25) / (1 - self.red)
			def 					A_    (  self  ,      lowercase=0.16  ):
							return (self.nir - self.green) / (self.nir + self.green + y)
			def 					A_    (  self  ,      lowercase=0.5  ):
							return ((self.nir - self.green) / (self.nir + self.green + n)) * (1 + n)
			def 					A_    (  self  ):
							return np.arctan(
							    ((2 * self.red - self.green - self.blue) / 30.5) * (self.green - self.blue)  )
			def 					A_    (  self  ,      lowercase=None  ,      lowercase=None  ):
							return (self.nir - b) / (a * self.red)
			def 					A_    (  self  ):
							return (self.nir / ((self.nir + self.red) / 2)) * (self.ndvi() + 1)
			def 					A_    (  self  ):
							return (self.red + self.green + self.blue) / 30.5
			def 					A_    (  self  ):
							return self.nir / self.red
			def 					A_    (  self  ):
							return (self.rvi() - 1) / (self.rvi() + 1)
			def 					A_    (  self  ):
							return (
							    (2 * self.nir + 1)
							    - ((2 * self.nir + 1) ** 2 - 8 * (self.nir - self.red)) ** (1 / 2)
							) / 2
			def 					A_    (  self  ):
							return self.green / (self.nir + self.red + self.green)
			def 					A_    (  self  ):
							return self.nir / (self.nir + self.red + self.green)
			def 					A_    (  self  ):
							return self.red / (self.nir + self.red + self.green)
			def 					A_    (  self  ):
							return (self.green - self.red) / (self.green + self.red)
			def 					A_    (  self  ):
							return (self.red - self.green) / (self.red + self.green)
			def 					A_    (  self  ):
							_lowerCamelCase     :			Union[str, Any]    =    np.max([np.max(self.red  ), np.max(self.green  ), np.max(self.blue  )]  )
							_lowerCamelCase     :			Dict    =    np.min([np.min(self.red  ), np.min(self.green  ), np.min(self.blue  )]  )
							return (max_value - min_value) / max_value
			def 					A_    (  self  ):
							return (2 * self.red - self.green - self.blue) / (self.green - self.blue)
			def 					A_    (  self  ):
							return self.nir / self.red
			def 					A_    (  self  ):
							return (self.ndvi() + 0.5) ** (1 / 2)






			def 					A_    (  self  ):
							return (self.nir - self.redEdge) / (self.nir + self.redEdge)