



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

   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.02   ,  _SCREAMING_SNAKE_CASE=None   ,  _SCREAMING_SNAKE_CASE=2   ,  _SCREAMING_SNAKE_CASE=2   ,  )						->   Optional[Any]:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			parent
    UpperCAmelCase			:      Any			=			batch_size
    UpperCAmelCase			:      Optional[Any]			=			patch_size
    UpperCAmelCase			:      Dict			=			max_length
    UpperCAmelCase			:      int			=			num_mel_bins
    UpperCAmelCase			:      Dict			=			is_training
    UpperCAmelCase			:      int			=			use_labels
    UpperCAmelCase			:      Optional[Any]			=			hidden_size
    UpperCAmelCase			:      str			=			num_hidden_layers
    UpperCAmelCase			:      Dict			=			num_attention_heads
    UpperCAmelCase			:      Tuple			=			intermediate_size
    UpperCAmelCase			:      List[str]			=			hidden_act
    UpperCAmelCase			:      List[Any]			=			hidden_dropout_prob
    UpperCAmelCase			:      Dict			=			attention_probs_dropout_prob
    UpperCAmelCase			:      List[Any]			=			type_sequence_label_size
    UpperCAmelCase			:      Dict			=			initializer_range
    UpperCAmelCase			:      str			=			scope
    UpperCAmelCase			:      List[str]			=			frequency_stride
    UpperCAmelCase			:      Optional[int]			=			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			:      Optional[int]			=			(self.max_length - self.patch_size) // self.time_stride + 1
    UpperCAmelCase			:      Optional[Any]			=			frequency_out_dimension * time_out_dimension
    UpperCAmelCase			:      Optional[int]			=			num_patches + 2

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




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

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

    UpperCAmelCase			:      List[str]			=			self.get_config()

    return config, input_values, labels

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Optional[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   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE   ,  _SCREAMING_SNAKE_CASE		)						->   Dict:





    '''simple docstring'''




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




   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




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



@require_torch
class    SCREAMING_SNAKE_CASE__						(      __UpperCAmelCase   ,    __UpperCAmelCase   ,    unittest.TestCase				):
   __lowerCAmelCase						:     List[str]		=		(
       (
           ASTModel,
           ASTForAudioClassification,
       )
       if is_torch_available()
       else ()
   )
   __lowerCAmelCase						:     Dict		=		(
       {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
       if is_torch_available()
       else {}
   )
   __lowerCAmelCase						:     str		=		False
   __lowerCAmelCase						:     Union[str, Any]		=		False
   __lowerCAmelCase						:     Optional[int]		=		False
   __lowerCAmelCase						:     Any		=		False

   def 			SCREAMING_SNAKE_CASE  (     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 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''simple docstring'''




    UpperCAmelCase			:      Optional[Any]			=			ASTModelTester(self		)
    UpperCAmelCase			:      Optional[int]			=			ConfigTester(self   ,  config_class=UpperCAmelCase_   ,  has_text_modality=UpperCAmelCase_   ,  hidden_size=37		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   int:





    '''simple docstring'''




    self.config_tester.run_common_tests()

   @unittest.skip(reason="""AST does not use inputs_embeds"""		)
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   str:





    '''simple docstring'''




    pass

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





    '''simple docstring'''




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

    for model_class in self.all_model_classes:
     UpperCAmelCase			:      List[str]			=			model_class(UpperCAmelCase_		)
     self.assertIsInstance(model.get_input_embeddings()   ,  (nn.Module)		)
     UpperCAmelCase			:      List[str]			=			model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(UpperCAmelCase_   ,  nn.Linear		)		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Tuple:





    '''simple docstring'''




    UpperCAmelCase			,	UpperCAmelCase			:      int			=			self.model_tester.prepare_config_and_inputs_for_common()

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

     UpperCAmelCase			:      Union[str, Any]			=			["""input_values"""]
     self.assertListEqual(arg_names[:1]   ,  UpperCAmelCase_		)

   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Any:





    '''simple docstring'''




    UpperCAmelCase			:      int			=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCAmelCase_		)




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





    '''simple docstring'''




    for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase			:      List[Any]			=			ASTModel.from_pretrained(UpperCAmelCase_		)
     self.assertIsNotNone(UpperCAmelCase_		)

def    _snake_case		(		):
 UpperCAmelCase			:      Tuple			=			hf_hub_download(
     repo_id="""nielsr/audio-spectogram-transformer-checkpoint"""    ,	filename="""sample_audio.flac"""    ,	repo_type="""dataset"""		)

 UpperCAmelCase			,	UpperCAmelCase			:      str			=			torchaudio.load(_snake_case		)

 return audio, sampling_rate



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

   @cached_property
   def 			SCREAMING_SNAKE_CASE  (     self		)						->   Dict:





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





    '''simple docstring'''




    UpperCAmelCase			:      Union[str, Any]			=			self.default_feature_extractor
    UpperCAmelCase			:      str			=			ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		).to(UpperCAmelCase_		)

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

    # forward pass
    with torch.no_grad():
     UpperCAmelCase			:      Any			=			model(**UpperCAmelCase_		)

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

    UpperCAmelCase			:      Tuple			=			torch.tensor([-0.8760, -7.0042, -8.6602]		).to(UpperCAmelCase_		)

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





"""simple docstring"""
from __future__ import annotations

from decimal import Decimal

from numpy import array

def    _snake_case		(		UpperCamelCase		:	list[list[float]]		):
 UpperCAmelCase			:      str			=			Decimal

 # Check if the provided matrix has 2 rows and 2 columns
 # since this implementation only works for 2x2 matrices
 if len(UpperCamelCase		) == 2 and len(matrix[0]		) == 2 and len(matrix[1]		) == 2:
  # Calculate the determinant of the matrix
  UpperCAmelCase			:      Optional[int]			=			float(
      d(matrix[0][0]		) * d(matrix[1][1]		) - d(matrix[1][0]		) * d(matrix[0][1]		)		)
  if determinant == 0:
   raise ValueError("""This matrix has no inverse."""		)

  # Creates a copy of the matrix with swapped positions of the elements
  UpperCAmelCase			:      Optional[Any]			=			[[0.0, 0.0], [0.0, 0.0]]
  UpperCAmelCase			,	UpperCAmelCase			:      Any			=			matrix[1][1], matrix[0][0]
  UpperCAmelCase			,	UpperCAmelCase			:      Union[str, Any]			=			-matrix[1][0], -matrix[0][1]

  # Calculate the inverse of the matrix
  return [
      [(float(d(UpperCamelCase		)		) / determinant) or 0.0 for n in row] for row in swapped_matrix
  ]
 elif (
     len(UpperCamelCase		) == 3
     and len(matrix[0]		) == 3
     and len(matrix[1]		) == 3
     and len(matrix[2]		) == 3
 ):
  # Calculate the determinant of the matrix using Sarrus rule
  UpperCAmelCase			:      str			=			float(
      (
          (d(matrix[0][0]		) * d(matrix[1][1]		) * d(matrix[2][2]		))
          + (d(matrix[0][1]		) * d(matrix[1][2]		) * d(matrix[2][0]		))
          + (d(matrix[0][2]		) * d(matrix[1][0]		) * d(matrix[2][1]		))
      )
      - (
          (d(matrix[0][2]		) * d(matrix[1][1]		) * d(matrix[2][0]		))
          + (d(matrix[0][1]		) * d(matrix[1][0]		) * d(matrix[2][2]		))
          + (d(matrix[0][0]		) * d(matrix[1][2]		) * d(matrix[2][1]		))
      )		)
  if determinant == 0:
   raise ValueError("""This matrix has no inverse."""		)

  # Creating cofactor matrix
  UpperCAmelCase			:      Optional[int]			=			[
      [d(0.0		), d(0.0		), d(0.0		)],
      [d(0.0		), d(0.0		), d(0.0		)],
      [d(0.0		), d(0.0		), d(0.0		)],
  ]
  UpperCAmelCase			:      str			=			(d(matrix[1][1]		) * d(matrix[2][2]		)) - (
      d(matrix[1][2]		) * d(matrix[2][1]		)
  )
  UpperCAmelCase			:      List[str]			=			-(
      (d(matrix[1][0]		) * d(matrix[2][2]		)) - (d(matrix[1][2]		) * d(matrix[2][0]		))
  )
  UpperCAmelCase			:      Optional[int]			=			(d(matrix[1][0]		) * d(matrix[2][1]		)) - (
      d(matrix[1][1]		) * d(matrix[2][0]		)
  )
  UpperCAmelCase			:      Optional[int]			=			-(
      (d(matrix[0][1]		) * d(matrix[2][2]		)) - (d(matrix[0][2]		) * d(matrix[2][1]		))
  )
  UpperCAmelCase			:      str			=			(d(matrix[0][0]		) * d(matrix[2][2]		)) - (
      d(matrix[0][2]		) * d(matrix[2][0]		)
  )
  UpperCAmelCase			:      Union[str, Any]			=			-(
      (d(matrix[0][0]		) * d(matrix[2][1]		)) - (d(matrix[0][1]		) * d(matrix[2][0]		))
  )
  UpperCAmelCase			:      Dict			=			(d(matrix[0][1]		) * d(matrix[1][2]		)) - (
      d(matrix[0][2]		) * d(matrix[1][1]		)
  )
  UpperCAmelCase			:      Optional[Any]			=			-(
      (d(matrix[0][0]		) * d(matrix[1][2]		)) - (d(matrix[0][2]		) * d(matrix[1][0]		))
  )
  UpperCAmelCase			:      str			=			(d(matrix[0][0]		) * d(matrix[1][1]		)) - (
      d(matrix[0][1]		) * d(matrix[1][0]		)
  )

  # Transpose the cofactor matrix (Adjoint matrix)
  UpperCAmelCase			:      str			=			array(UpperCamelCase		)
  for i in range(3		):
   for j in range(3		):
    UpperCAmelCase			:      Any			=			cofactor_matrix[j][i]

        # Inverse of the matrix using the formula (1/determinant) * adjoint matrix
  UpperCAmelCase			:      Tuple			=			array(UpperCamelCase		)
  for i in range(3		):
   for j in range(3		):
    inverse_matrix[i][j] /= d(UpperCamelCase		)

        # Calculate the inverse of the matrix
  return [[float(d(UpperCamelCase		)		) or 0.0 for n in row] for row in inverse_matrix]
 raise ValueError("""Please provide a matrix of size 2x2 or 3x3."""		)
