





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						:







 '''simple docstring'''

 def __init__(self    :       List[Any]	,			UpperCAmelCase_    :       Optional[int]	,			UpperCAmelCase_    :       Union[str, Any]=13	,			UpperCAmelCase_    :       List[Any]=2	,			UpperCAmelCase_    :       Union[str, Any]=24	,			UpperCAmelCase_    :       Optional[int]=16	,			UpperCAmelCase_    :       List[Any]=True	,			UpperCAmelCase_    :       Optional[Any]=True	,			UpperCAmelCase_    :       Optional[int]=32	,			UpperCAmelCase_    :       Any=5	,			UpperCAmelCase_    :       Dict=4	,			UpperCAmelCase_    :       Union[str, Any]=37	,			UpperCAmelCase_    :       Optional[Any]="gelu"	,			UpperCAmelCase_    :       Optional[Any]=0.1	,			UpperCAmelCase_    :       int=0.1	,			UpperCAmelCase_    :       List[Any]=10	,			UpperCAmelCase_    :       Optional[Any]=0.02	,			UpperCAmelCase_    :       List[str]=None	,			UpperCAmelCase_    :       Union[str, Any]=2	,			UpperCAmelCase_    :       Tuple=2	,			)	->int:



   '''simple docstring'''



   lowerCamelCase__:				Optional[int]        =parent
   lowerCamelCase__:				List[Any]        =batch_size
   lowerCamelCase__:				str        =patch_size
   lowerCamelCase__:				List[str]        =max_length
   lowerCamelCase__:				List[str]        =num_mel_bins
   lowerCamelCase__:				Any        =is_training
   lowerCamelCase__:				Dict        =use_labels
   lowerCamelCase__:				str        =hidden_size
   lowerCamelCase__:				Optional[Any]        =num_hidden_layers
   lowerCamelCase__:				str        =num_attention_heads
   lowerCamelCase__:				Tuple        =intermediate_size
   lowerCamelCase__:				int        =hidden_act
   lowerCamelCase__:				Tuple        =hidden_dropout_prob
   lowerCamelCase__:				str        =attention_probs_dropout_prob
   lowerCamelCase__:				Optional[Any]        =type_sequence_label_size
   lowerCamelCase__:				List[str]        =initializer_range
   lowerCamelCase__:				List[Any]        =scope
   lowerCamelCase__:				Optional[int]        =frequency_stride
   lowerCamelCase__:				str        =time_stride

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

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[str])	->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])

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

   lowerCamelCase__:				str        =self.get_config()

   return config, input_values, labels

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



   '''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    :       str	,			UpperCAmelCase_    :       Any	,			UpperCAmelCase_    :       Any	,			UpperCAmelCase_    :       int)	->str:



   '''simple docstring'''



   lowerCamelCase__:				int        =ASTModel(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__:				Dict        =model(UpperCAmelCase_)
   self.parent.assertEqual(result.last_hidden_state.shape	,			(self.batch_size, self.seq_length, self.hidden_size))







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



   '''simple docstring'''



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



@require_torch
class        _SCREAMING_SNAKE_CASE						(     __SCREAMING_SNAKE_CASE   ,							__SCREAMING_SNAKE_CASE   ,							unittest.TestCase   ):







 '''simple docstring'''
 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 							SCREAMING_SNAKE_CASE_ (self    :       List[Any]	,			UpperCAmelCase_    :       Union[str, Any]	,			UpperCAmelCase_    :       int	,			UpperCAmelCase_    :       List[str]	,			UpperCAmelCase_    :       Dict	,			UpperCAmelCase_    :       int)	->int:



   '''simple docstring'''



   if pipeline_test_casse_name == "AudioClassificationPipelineTests":
     return True

   return False

 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->Any:



   '''simple docstring'''



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

 def 							SCREAMING_SNAKE_CASE_ (self    :       int)	->List[str]:



   '''simple docstring'''



   self.config_tester.run_common_tests()

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



   '''simple docstring'''



   pass

 def 							SCREAMING_SNAKE_CASE_ (self    :       Any)	->Tuple:



   '''simple docstring'''



   lowerCamelCase__  , lowerCamelCase__:				List[str]        =self.model_tester.prepare_config_and_inputs_for_common()

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

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



   '''simple docstring'''



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

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

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

 def 							SCREAMING_SNAKE_CASE_ (self    :       List[Any])	->Dict:



   '''simple docstring'''



   lowerCamelCase__:				List[str]        =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)







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



   '''simple docstring'''



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





def 					lowerCAmelCase_			(	)					->		Dict:







  """simple docstring"""





  lowerCamelCase__:				int        =hf_hub_download(
      repo_id="nielsr/audio-spectogram-transformer-checkpoint"     ,   filename="sample_audio.flac"     ,   repo_type="dataset"		)

  lowerCamelCase__  , lowerCamelCase__:				List[str]        =torchaudio.load(__a		)

  return audio, sampling_rate






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







 '''simple docstring'''

 @cached_property
 def 							SCREAMING_SNAKE_CASE_ (self    :       Tuple)	->Tuple:



   '''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    :       str)	->List[Any]:



   '''simple docstring'''



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

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

   # forward pass
   with torch.no_grad():
     lowerCamelCase__:				List[Any]        =model(**UpperCAmelCase_)

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

   lowerCamelCase__:				List[Any]        =torch.tensor([-0.8760, -7.0042, -8.6602]).to(UpperCAmelCase_)

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








from math import pow





def 					lowerCAmelCase_			(	__a     ,   __a     ,   __a     ,   __a     ,   __a     ,   )					->		tuple[int, int]:







  """simple docstring"""





  if current_sum == needed_sum:
    # If the sum of the powers is equal to needed_sum, then we have a solution.
    solutions_count += 1
    return current_sum, solutions_count

  lowerCamelCase__:				Optional[Any]        =int(pow(__a     ,   __a		)		)
  if current_sum + i_to_n <= needed_sum:
    # If the sum of the powers is less than needed_sum, then continue adding powers.
    current_sum += i_to_n
    lowerCamelCase__  , lowerCamelCase__:				int        =backtrack(
        __a     ,   __a     ,   current_number + 1     ,   __a     ,   __a		)
    current_sum -= i_to_n
  if i_to_n < needed_sum:
    # If the power of i is less than needed_sum, then try with the next power.
    lowerCamelCase__  , lowerCamelCase__:				Dict        =backtrack(
        __a     ,   __a     ,   current_number + 1     ,   __a     ,   __a		)
  return current_sum, solutions_count





def 					lowerCAmelCase_			(	__a     ,   __a		)					->		int:







  """simple docstring"""





  if not (1 <= needed_sum <= 1000 and 2 <= power <= 10):
    raise ValueError(
        "Invalid input\n"
        "needed_sum must be between 1 and 1000, power between 2 and 10."		)

  return backtrack(__a     ,   __a     ,   1     ,   0     ,   0		)[1]  # Return the solutions_count


if __name__ == "__main__":
     import doctest

     doctest.testmod()

