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






   '''simple docstring'''







   def __init__(			self ,   lowerCamelCase__ ,   lowerCamelCase__=1_3 ,   lowerCamelCase__=2 ,   lowerCamelCase__=2_4 ,   lowerCamelCase__=1_6 ,   lowerCamelCase__=True ,   lowerCamelCase__=True ,   lowerCamelCase__=3_2 ,   lowerCamelCase__=5 ,   lowerCamelCase__=4 ,   lowerCamelCase__=3_7 ,   lowerCamelCase__="gelu" ,   lowerCamelCase__=0.1 ,   lowerCamelCase__=0.1 ,   lowerCamelCase__=1_0 ,   lowerCamelCase__=0.02 ,   lowerCamelCase__=None ,   lowerCamelCase__=2 ,   lowerCamelCase__=2 ,   ):

      '''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       UpperCAmelCase				(			self   ):

      '''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       UpperCAmelCase				(			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       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







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







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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




@require_torch
class 						lowercase__	(  __snake_case,					__snake_case,					unittest.TestCase   ):






   '''simple docstring'''







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







   def       UpperCAmelCase				(			self ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__ ,   lowerCamelCase__   ):

      '''simple docstring'''







      if pipeline_test_casse_name == "AudioClassificationPipelineTests":
         return True

      return False







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  ASTModelTester(self   )
      UpperCamelCase       =  ConfigTester(self ,   config_class=__UpperCamelCase ,   has_text_modality=__UpperCamelCase ,   hidden_size=3_7   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      self.config_tester.run_common_tests()







   @unittest.skip(reason='''AST does not use inputs_embeds'''   )
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      pass







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase     , UpperCamelCase       =  self.model_tester.prepare_config_and_inputs_for_common()

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







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase     , UpperCamelCase       =  self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
         UpperCamelCase       =  model_class(__UpperCamelCase   )
         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] ,   __UpperCamelCase   )







   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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







   @slow
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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




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

   UpperCamelCase     , UpperCamelCase       =  torchaudio.load(lowercase__)

   return audio, sampling_rate


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






   '''simple docstring'''







   @cached_property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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







   @slow
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







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

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

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

      # verify the logits
      UpperCamelCase       =  torch.Size((1, 5_2_7)   )
      self.assertEqual(outputs.logits.shape ,   __UpperCamelCase   )

      UpperCamelCase       =  torch.tensor([-0.8760, -7.0042, -8.6602]   ).to(__UpperCamelCase   )

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







'''simple docstring'''


import math
from typing import Optional

import numpy as np

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case_ :  Dict     =					logging.get_logger(__name__)

snake_case_ :  Union[str, Any]     =					{
    'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json',
    'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json',
}


class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							'''encodec'''







   def __init__(			self ,   lowerCamelCase__=[1.5, 3.0, 6.0, 12.0, 24.0] ,   lowerCamelCase__=2_4_0_0_0 ,   lowerCamelCase__=1 ,   lowerCamelCase__=False ,   lowerCamelCase__=None ,   lowerCamelCase__=None ,   lowerCamelCase__=1_2_8 ,   lowerCamelCase__=3_2 ,   lowerCamelCase__=1 ,   lowerCamelCase__=[8, 5, 4, 2] ,   lowerCamelCase__="weight_norm" ,   lowerCamelCase__=7 ,   lowerCamelCase__=7 ,   lowerCamelCase__=3 ,   lowerCamelCase__=2 ,   lowerCamelCase__=True ,   lowerCamelCase__="reflect" ,   lowerCamelCase__=2 ,   lowerCamelCase__=2 ,   lowerCamelCase__=1.0 ,   lowerCamelCase__=1_0_2_4 ,   lowerCamelCase__=None ,   lowerCamelCase__=True ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      UpperCamelCase       =  target_bandwidths
      UpperCamelCase       =  sampling_rate
      UpperCamelCase       =  audio_channels
      UpperCamelCase       =  normalize
      UpperCamelCase       =  chunk_length_s
      UpperCamelCase       =  overlap
      UpperCamelCase       =  hidden_size
      UpperCamelCase       =  num_filters
      UpperCamelCase       =  num_residual_layers
      UpperCamelCase       =  upsampling_ratios
      UpperCamelCase       =  norm_type
      UpperCamelCase       =  kernel_size
      UpperCamelCase       =  last_kernel_size
      UpperCamelCase       =  residual_kernel_size
      UpperCamelCase       =  dilation_growth_rate
      UpperCamelCase       =  use_causal_conv
      UpperCamelCase       =  pad_mode
      UpperCamelCase       =  compress
      UpperCamelCase       =  num_lstm_layers
      UpperCamelCase       =  trim_right_ratio
      UpperCamelCase       =  codebook_size
      UpperCamelCase       =  codebook_dim if codebook_dim is not None else hidden_size
      UpperCamelCase       =  use_conv_shortcut

      if self.norm_type not in ["weight_norm", "time_group_norm"]:
         raise ValueError(
             f'self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}'   )

      super().__init__(**lowerCamelCase__   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if self.chunk_length_s is None:
         return None
      else:
         return int(self.chunk_length_s * self.sampling_rate   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if self.chunk_length_s is None or self.overlap is None:
         return None
      else:
         return max(1 ,   int((1.0 - self.overlap) * self.chunk_length   )   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  np.prod(self.upsampling_ratios   )
      return math.ceil(self.sampling_rate / hop_length   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return int(1_0_0_0 * self.target_bandwidths[-1] // (self.frame_rate * 1_0)   )





