



'''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 	lowerCAmelCase_:
  '''simple docstring'''




  def __init__(   self  ,__UpperCAmelCase  ,__UpperCAmelCase=13  ,__UpperCAmelCase=2  ,__UpperCAmelCase=24  ,__UpperCAmelCase=16  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=32  ,__UpperCAmelCase=5  ,__UpperCAmelCase=4  ,__UpperCAmelCase=37  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=10  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=None  ,__UpperCAmelCase=2  ,__UpperCAmelCase=2  ,)   ->		List[str]:
      lowerCAmelCase__			:  Union[str, Any]											= parent
      lowerCAmelCase__			:  Union[str, Any]											= batch_size
      lowerCAmelCase__			:  Optional[Any]											= patch_size
      lowerCAmelCase__			:  List[str]											= max_length
      lowerCAmelCase__			:  int											= num_mel_bins
      lowerCAmelCase__			:  Union[str, Any]											= is_training
      lowerCAmelCase__			:  List[Any]											= use_labels
      lowerCAmelCase__			:  Tuple											= hidden_size
      lowerCAmelCase__			:  Dict											= num_hidden_layers
      lowerCAmelCase__			:  str											= num_attention_heads
      lowerCAmelCase__			:  Tuple											= intermediate_size
      lowerCAmelCase__			:  Tuple											= hidden_act
      lowerCAmelCase__			:  List[Any]											= hidden_dropout_prob
      lowerCAmelCase__			:  Dict											= attention_probs_dropout_prob
      lowerCAmelCase__			:  Any											= type_sequence_label_size
      lowerCAmelCase__			:  List[str]											= initializer_range
      lowerCAmelCase__			:  List[str]											= scope
      lowerCAmelCase__			:  int											= frequency_stride
      lowerCAmelCase__			:  int											= time_stride

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




  def 							UpperCAmelCase_     (   self				)   ->		Any:
      lowerCAmelCase__			:  List[str]											= floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]				)

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

      lowerCAmelCase__			:  Any											= self.get_config()

      return config, input_values, labels




  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      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  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Any:
      lowerCAmelCase__			:  Any											= ASTModel(config=__UpperCAmelCase				)
      model.to(__UpperCAmelCase				)
      model.eval()
      lowerCAmelCase__			:  Tuple											= model(__UpperCAmelCase				)
      self.parent.assertEqual(result.last_hidden_state.shape  ,(self.batch_size, self.seq_length, self.hidden_size)				)






  def 							UpperCAmelCase_     (   self				)   ->		str:
      lowerCAmelCase__			:  int											= self.prepare_config_and_inputs()
      (
          (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       
      )			:  str											= config_and_inputs
      lowerCAmelCase__			:  List[Any]											= {"""input_values""": input_values}
      return config, inputs_dict







@require_torch
class 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			unittest.TestCase					):
  '''simple docstring'''




  __lowercase							:				Optional[int]           =				(
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  __lowercase							:				Any           =				(
      {'''audio-classification''': ASTForAudioClassification, '''feature-extraction''': ASTModel}
      if is_torch_available()
      else {}
  )
  __lowercase							:				str           =				False
  __lowercase							:				str           =				False
  __lowercase							:				Dict           =				False
  __lowercase							:				Dict           =				False




  def 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Optional[Any]:
      if pipeline_test_casse_name == "AudioClassificationPipelineTests":
          return True

      return False




  def 							UpperCAmelCase_     (   self				)   ->		str:
      lowerCAmelCase__			:  List[str]											= ASTModelTester(self				)
      lowerCAmelCase__			:  Optional[int]											= ConfigTester(self  ,config_class=__UpperCAmelCase  ,has_text_modality=__UpperCAmelCase  ,hidden_size=37				)




  def 							UpperCAmelCase_     (   self				)   ->		str:
      self.config_tester.run_common_tests()




  @unittest.skip(reason="""AST does not use inputs_embeds"""				)
  def 							UpperCAmelCase_     (   self				)   ->		List[str]:
      pass




  def 							UpperCAmelCase_     (   self				)   ->		Optional[int]:
      lowerCAmelCase__				,       lowerCAmelCase__			:  Union[str, Any]											= self.model_tester.prepare_config_and_inputs_for_common()

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




  def 							UpperCAmelCase_     (   self				)   ->		Union[str, Any]:
      lowerCAmelCase__				,       lowerCAmelCase__			:  int											= self.model_tester.prepare_config_and_inputs_for_common()

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

          lowerCAmelCase__			:  Optional[Any]											= ["""input_values"""]
          self.assertListEqual(arg_names[:1]  ,__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		Optional[int]:
      lowerCAmelCase__			:  Optional[Any]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__UpperCAmelCase				)






  @slow
  def 							UpperCAmelCase_     (   self				)   ->		List[Any]:
      for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase__			:  Optional[int]											= ASTModel.from_pretrained(__UpperCAmelCase				)
          self.assertIsNotNone(__UpperCAmelCase				)







def        _SCREAMING_SNAKE_CASE  (	):



    """simple docstring"""





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

    lowerCAmelCase__				,       lowerCAmelCase__			:  Dict											= torchaudio.load(UpperCamelCase      )

    return audio, sampling_rate






@require_torch
@require_torchaudio
class 	lowerCAmelCase_(    unittest.TestCase					):
  '''simple docstring'''




  @cached_property
  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      return (
          ASTFeatureExtractor.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""				)
          if is_torchaudio_available()
          else None
      )






  @slow
  def 							UpperCAmelCase_     (   self				)   ->		str:
      lowerCAmelCase__			:  Union[str, Any]											= self.default_feature_extractor
      lowerCAmelCase__			:  Union[str, Any]											= ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""				).to(__UpperCAmelCase				)

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

      # forward pass
      with torch.no_grad():
          lowerCAmelCase__			:  Dict											= model(**__UpperCAmelCase				)

      # verify the logits
      lowerCAmelCase__			:  int											= torch.Size((1, 527)				)
      self.assertEqual(outputs.logits.shape  ,__UpperCAmelCase				)

      lowerCAmelCase__			:  Dict											= torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]				).to(__UpperCAmelCase				)

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







'''simple docstring'''





def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase = 1000      ):



    """simple docstring"""





    lowerCAmelCase__			:  Union[str, Any]											= -1
    lowerCAmelCase__			:  Optional[Any]											= 0
    for a in range(1							,   n // 3      ):
        # Solving the two equations a**2+b**2=c**2 and a+b+c=N eliminating c
        lowerCAmelCase__			:  Optional[Any]											= (n * n - 2 * a * n) // (2 * n - 2 * a)
        lowerCAmelCase__			:  Tuple											= n - a - b
        if c * c == (a * a + b * b):
            lowerCAmelCase__			:  int											= a * b * c
            if candidate >= product:
                lowerCAmelCase__			:  Any											= candidate
    return product


if __name__ == "__main__":
 print(F"""{solution() = }""")


