





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 		UpperCamelCase__ :



     '''simple docstring'''

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




           '''simple docstring'''


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

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		int:




           '''simple docstring'''


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

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

           SCREAMING_SNAKE_CASE		=						self.get_config()

           return config, input_values, labels






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		str:




           '''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=lowerCamelCase__						,initializer_range=self.initializer_range						,frequency_stride=self.frequency_stride						,time_stride=self.time_stride						,)






     def 				SCREAMING_SNAKE_CASE__  (							self						:    int						,lowerCamelCase__						:    int						,lowerCamelCase__						:    Any						,lowerCamelCase__						:    Optional[int]       )     ->		List[Any]:




           '''simple docstring'''


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






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




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.prepare_config_and_inputs()
           (
               (
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					(
               SCREAMING_SNAKE_CASE
           ),					
           )		=						config_and_inputs
           SCREAMING_SNAKE_CASE		=						{"""input_values""": input_values}
           return config, inputs_dict

@require_torch
class 		UpperCamelCase__ (      lowerCAmelCase_							,      lowerCAmelCase_							,      unittest.TestCase   ):



     '''simple docstring'''

     __snake_case    :	Optional[Any]			=			(
         (
             ASTModel,
             ASTForAudioClassification,
         )
         if is_torch_available()
         else ()
     )
     __snake_case    :	Optional[Any]			=			(
         {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
         if is_torch_available()
         else {}
     )
     __snake_case    :	Tuple			=			False
     __snake_case    :	List[str]			=			False
     __snake_case    :	Optional[Any]			=			False
     __snake_case    :	Optional[Any]			=			False






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[Any]						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    Any						,lowerCamelCase__						:    Optional[Any]						,lowerCamelCase__						:    List[Any]						,lowerCamelCase__						:    Any       )     ->		Tuple:




           '''simple docstring'''


           if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                 return True

           return False






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Tuple       )     ->		Tuple:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						ASTModelTester(self       )
           SCREAMING_SNAKE_CASE		=						ConfigTester(self						,config_class=lowerCamelCase__						,has_text_modality=lowerCamelCase__						,hidden_size=37       )






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




           '''simple docstring'''


           self.config_tester.run_common_tests()






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




           '''simple docstring'''


           pass






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		Optional[int]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()

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






     def 				SCREAMING_SNAKE_CASE__  (							self						:    str       )     ->		List[Any]:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs_for_common()

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

                 SCREAMING_SNAKE_CASE		=						["""input_values"""]
                 self.assertListEqual(arg_names[:1]						,lowerCamelCase__       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		str:




           '''simple docstring'''


           SCREAMING_SNAKE_CASE		=						self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*lowerCamelCase__       )






     @slow
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Any       )     ->		Tuple:




           '''simple docstring'''


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



def    __lowercase   (      ) ->   Optional[Any]:


      '''simple docstring'''


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

      SCREAMING_SNAKE_CASE,					SCREAMING_SNAKE_CASE		=						torchaudio.load(_SCREAMING_SNAKE_CASE	)

      return audio, sampling_rate



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



     '''simple docstring'''

     @cached_property
     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		str:




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


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

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

           # forward pass
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE		=						model(**lowerCamelCase__       )

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

           SCREAMING_SNAKE_CASE		=						torch.tensor([-0.8760, -7.0042, -8.6602]       ).to(lowerCamelCase__       )

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









import math
import unittest



def    __lowercase   (      _SCREAMING_SNAKE_CASE	) ->   bool:


      '''simple docstring'''


      assert isinstance(_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE	) and (
          number >= 0
      ), "'number' must been an int and positive"

      if 1 < number < 4:
            # 2 and 3 are primes
            return True
      elif number < 2 or number % 2 == 0 or number % 3 == 0:
            # Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
            return False

      # All primes number are in format of 6k +/- 1
      for i in range(5 ,						int(math.sqrt(_SCREAMING_SNAKE_CASE	) + 1	) ,						6	):
            if number % i == 0 or number % (i + 2) == 0:
                  return False
      return True

class 		UpperCamelCase__ (      unittest.TestCase   ):



     '''simple docstring'''

     def 				SCREAMING_SNAKE_CASE__  (							self						:    Dict       )     ->		Tuple:




           '''simple docstring'''


           self.assertTrue(is_prime(2       )       )
           self.assertTrue(is_prime(3       )       )
           self.assertTrue(is_prime(5       )       )
           self.assertTrue(is_prime(7       )       )
           self.assertTrue(is_prime(11       )       )
           self.assertTrue(is_prime(13       )       )
           self.assertTrue(is_prime(17       )       )
           self.assertTrue(is_prime(19       )       )
           self.assertTrue(is_prime(23       )       )
           self.assertTrue(is_prime(29       )       )






     def 				SCREAMING_SNAKE_CASE__  (							self						:    Optional[int]       )     ->		Tuple:




           '''simple docstring'''


           with self.assertRaises(lowerCamelCase__       ):
                 is_prime(-19       )
           self.assertFalse(
               is_prime(0       )						,"""Zero doesn't have any positive factors, primes must have exactly two."""						,)
           self.assertFalse(
               is_prime(1       )						,"""One only has 1 positive factor, primes must have exactly two."""						,)
           self.assertFalse(is_prime(2 * 2       )       )
           self.assertFalse(is_prime(2 * 3       )       )
           self.assertFalse(is_prime(3 * 3       )       )
           self.assertFalse(is_prime(3 * 5       )       )
           self.assertFalse(is_prime(3 * 5 * 7       )       )


if __name__ == "__main__":
      unittest.main()


