



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		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE=1_3		,				SCREAMING_SNAKE_CASE=2		,				SCREAMING_SNAKE_CASE=2_4		,				SCREAMING_SNAKE_CASE=1_6		,				SCREAMING_SNAKE_CASE=True		,				SCREAMING_SNAKE_CASE=True		,				SCREAMING_SNAKE_CASE=3_2		,				SCREAMING_SNAKE_CASE=5		,				SCREAMING_SNAKE_CASE=4		,				SCREAMING_SNAKE_CASE=3_7		,				SCREAMING_SNAKE_CASE="gelu"		,				SCREAMING_SNAKE_CASE=0.1		,				SCREAMING_SNAKE_CASE=0.1		,				SCREAMING_SNAKE_CASE=1_0		,				SCREAMING_SNAKE_CASE=0.02		,				SCREAMING_SNAKE_CASE=None		,				SCREAMING_SNAKE_CASE=2		,				SCREAMING_SNAKE_CASE=2		,				) ->			List[str]:
  a__												= parent
  a__												= batch_size
  a__												= patch_size
  a__												= max_length
  a__												= num_mel_bins
  a__												= is_training
  a__												= use_labels
  a__												= hidden_size
  a__												= num_hidden_layers
  a__												= num_attention_heads
  a__												= intermediate_size
  a__												= hidden_act
  a__												= hidden_dropout_prob
  a__												= attention_probs_dropout_prob
  a__												= type_sequence_label_size
  a__												= initializer_range
  a__												= scope
  a__												= frequency_stride
  a__												= time_stride

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

 def 						_UpperCAmelCase       (	self      ) ->			Tuple:
  a__												= floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

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

  a__												= self.get_config()

  return config, input_values, labels

 def 						_UpperCAmelCase       (	self      ) ->			Any:
  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=SCREAMING_SNAKE_CASE		,				initializer_range=self.initializer_range		,				frequency_stride=self.frequency_stride		,				time_stride=self.time_stride		,				)

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      ) ->			Union[str, Any]:
  a__												= ASTModel(config=SCREAMING_SNAKE_CASE      )
  model.to(SCREAMING_SNAKE_CASE      )
  model.eval()
  a__												= model(SCREAMING_SNAKE_CASE      )
  self.parent.assertEqual(result.last_hidden_state.shape		,				(self.batch_size, self.seq_length, self.hidden_size)      )



 def 						_UpperCAmelCase       (	self      ) ->			str:
  a__												= self.prepare_config_and_inputs()
  (
      (
      a__
  )							,			(
      a__
  )							,			(
      a__
  )							,			
  )												= config_and_inputs
  a__												= {'''input_values''': input_values}
  return config, inputs_dict





@require_torch
class    __UpperCamelCase			(       _lowercase	,	_lowercase	,	unittest.TestCase				):

 """simple docstring"""



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

 def 						_UpperCAmelCase       (	self		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE		,				SCREAMING_SNAKE_CASE      ) ->			List[Any]:
  if pipeline_test_casse_name == "AudioClassificationPipelineTests":
   return True

  return False

 def 						_UpperCAmelCase       (	self      ) ->			Tuple:
  a__												= ASTModelTester(self      )
  a__												= ConfigTester(self		,				config_class=SCREAMING_SNAKE_CASE		,				has_text_modality=SCREAMING_SNAKE_CASE		,				hidden_size=3_7      )

 def 						_UpperCAmelCase       (	self      ) ->			List[Any]:
  self.config_tester.run_common_tests()

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

 def 						_UpperCAmelCase       (	self      ) ->			Dict:
  a__							,			a__												= self.model_tester.prepare_config_and_inputs_for_common()

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

 def 						_UpperCAmelCase       (	self      ) ->			str:
  a__							,			a__												= self.model_tester.prepare_config_and_inputs_for_common()

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

   a__												= ['''input_values''']
   self.assertListEqual(arg_names[:1]		,				SCREAMING_SNAKE_CASE      )

 def 						_UpperCAmelCase       (	self      ) ->			List[Any]:
  a__												= self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE      )



 @slow
 def 						_UpperCAmelCase       (	self      ) ->			List[str]:
  for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   a__												= ASTModel.from_pretrained(SCREAMING_SNAKE_CASE      )
   self.assertIsNotNone(SCREAMING_SNAKE_CASE      )






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

 a__							,			a__												= torchaudio.load(__UpperCAmelCase       )

 return audio, sampling_rate

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

 """simple docstring"""



 @cached_property
 def 						_UpperCAmelCase       (	self      ) ->			List[Any]:
  return (
      ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      )
      if is_torchaudio_available()
      else None
  )



 @slow
 def 						_UpperCAmelCase       (	self      ) ->			Optional[int]:
  a__												= self.default_feature_extractor
  a__												= ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''      ).to(SCREAMING_SNAKE_CASE      )

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

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

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

  a__												= torch.tensor([-0.87_60, -7.00_42, -8.66_02]      ).to(SCREAMING_SNAKE_CASE      )

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










import math
from collections.abc import Iterator
from itertools import takewhile






def     __a					(		__UpperCAmelCase       ):

 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(__UpperCAmelCase       ) + 1       )							,  6       ):
  if number % i == 0 or number % (i + 2) == 0:
   return False
 return True






def     __a					(		):
 a__												= 2
 while True:
  if is_prime(__UpperCAmelCase       ):
   yield num
  num += 1






def     __a					(		__UpperCAmelCase = 200_0000       ):
 return sum(takewhile(lambda __UpperCAmelCase       : x < n							,  prime_generator()       )       )


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





