


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






       def __init__(      self  ,							snake_case  ,							snake_case=1_3  ,							snake_case=2  ,							snake_case=2_4  ,							snake_case=1_6  ,							snake_case=True  ,							snake_case=True  ,							snake_case=3_2  ,							snake_case=5  ,							snake_case=4  ,							snake_case=3_7  ,							snake_case="gelu"  ,							snake_case=0.1  ,							snake_case=0.1  ,							snake_case=1_0  ,							snake_case=0.02  ,							snake_case=None  ,							snake_case=2  ,							snake_case=2  ,							)						->  Union[str, Any]:




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

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






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




          '''simple docstring'''
          _UpperCAmelCase       :       List[Any]							   =floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])

          _UpperCAmelCase       :       List[Any]							   =None
          if self.use_labels:
             _UpperCAmelCase       :       Optional[Any]							   =ids_tensor([self.batch_size]  ,							self.type_sequence_label_size)

          _UpperCAmelCase       :       str							   =self.get_config()

          return config, input_values, labels






       def       lowerCAmelCase		(      self)						->  Any:




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






       def       lowerCAmelCase		(      self  ,							snake_case  ,							snake_case  ,							snake_case)						->  Optional[int]:




          '''simple docstring'''
          _UpperCAmelCase       :       Any							   =ASTModel(config=snake_case)
          model.to(snake_case)
          model.eval()
          _UpperCAmelCase       :       Any							   =model(snake_case)
          self.parent.assertEqual(result.last_hidden_state.shape  ,							(self.batch_size, self.seq_length, self.hidden_size))






       def       lowerCAmelCase		(      self)						->  Tuple:




          '''simple docstring'''
          _UpperCAmelCase       :       List[Any]							   =self.prepare_config_and_inputs()
          (
              _UpperCAmelCase      
          )       :       Dict							   =config_and_inputs
          _UpperCAmelCase       :       Union[str, Any]							   ={'input_values': input_values}
          return config, inputs_dict






@require_torch
class  __magic_name__							(		SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,unittest.TestCase    ):
       UpperCAmelCase										=(
           (
               ASTModel,
               ASTForAudioClassification,
           )
           if is_torch_available()
           else ()
       )
       UpperCAmelCase										=(
           {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
           if is_torch_available()
           else {}
       )
       UpperCAmelCase										=False
       UpperCAmelCase										=False
       UpperCAmelCase										=False
       UpperCAmelCase										=False






       def       lowerCAmelCase		(      self  ,							snake_case  ,							snake_case  ,							snake_case  ,							snake_case  ,							snake_case)						->  Tuple:




          '''simple docstring'''
          if pipeline_test_casse_name == "AudioClassificationPipelineTests":
             return True

          return False






       def       lowerCAmelCase		(      self)						->  Dict:




          '''simple docstring'''
          _UpperCAmelCase       :       List[Any]							   =ASTModelTester(self)
          _UpperCAmelCase       :       Any							   =ConfigTester(self  ,							config_class=snake_case  ,							has_text_modality=snake_case  ,							hidden_size=3_7)






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




          '''simple docstring'''
          self.config_tester.run_common_tests()






       @unittest.skip(reason='AST does not use inputs_embeds')
       def       lowerCAmelCase		(      self)						->  List[Any]:




          '''simple docstring'''
          pass






       def       lowerCAmelCase		(      self)						->  List[str]:




          '''simple docstring'''
          _UpperCAmelCase       :       int							   =self.model_tester.prepare_config_and_inputs_for_common()

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






       def       lowerCAmelCase		(      self)						->  Optional[Any]:




          '''simple docstring'''
          _UpperCAmelCase       :       List[str]							   =self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
             _UpperCAmelCase       :       Optional[int]							   =model_class(snake_case)
             _UpperCAmelCase       :       Optional[Any]							   =inspect.signature(model.forward)
             # signature.parameters is an OrderedDict => so arg_names order is deterministic
             _UpperCAmelCase       :       List[Any]							   =[*signature.parameters.keys()]

             _UpperCAmelCase       :       str							   =['input_values']
             self.assertListEqual(arg_names[:1]  ,							snake_case)






       def       lowerCAmelCase		(      self)						->  Tuple:




          '''simple docstring'''
          _UpperCAmelCase       :       List[Any]							   =self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case)






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




          '''simple docstring'''
          for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _UpperCAmelCase       :       Dict							   =ASTModel.from_pretrained(snake_case)
             self.assertIsNotNone(snake_case)






def lowerCamelCase__      (						):







   '''simple docstring'''




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

   _UpperCAmelCase       :       List[str]							   =torchaudio.load(_UpperCAmelCase							)

   return audio, sampling_rate






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






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




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






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




          '''simple docstring'''
          _UpperCAmelCase       :       List[str]							   =self.default_feature_extractor
          _UpperCAmelCase       :       Tuple							   =ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593').to(snake_case)

          _UpperCAmelCase       :       List[str]							   =self.default_feature_extractor
          _UpperCAmelCase       :       Optional[int]							   =prepare_audio()
          _UpperCAmelCase       :       List[str]							   =audio.squeeze().numpy()
          _UpperCAmelCase       :       List[Any]							   =feature_extractor(snake_case  ,							sampling_rate=snake_case  ,							return_tensors='pt').to(snake_case)

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

          # verify the logits
          _UpperCAmelCase       :       Union[str, Any]							   =torch.Size((1, 5_2_7))
          self.assertEqual(outputs.logits.shape  ,							snake_case)

          _UpperCAmelCase       :       Any							   =torch.tensor([-0.87_60, -7.00_42, -8.66_02]).to(snake_case)

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





'''simple docstring'''






from __future__ import annotations

import bisect





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int	,   __lowerCamelCase	:							int = 0	,   __lowerCamelCase	:							int = -1							):







   '''simple docstring'''




   if hi < 0:
      _UpperCAmelCase       :       int							   =len(__lowerCamelCase							)

   while lo < hi:
      _UpperCAmelCase       :       Dict							   =lo + (hi - lo) // 2
      if sorted_collection[mid] < item:
         _UpperCAmelCase       :       int							   =mid + 1
      else:
         _UpperCAmelCase       :       Union[str, Any]							   =mid

   return lo





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int	,   __lowerCamelCase	:							int = 0	,   __lowerCamelCase	:							int = -1							):







   '''simple docstring'''




   if hi < 0:
      _UpperCAmelCase       :       str							   =len(__lowerCamelCase							)

   while lo < hi:
      _UpperCAmelCase       :       List[Any]							   =lo + (hi - lo) // 2
      if sorted_collection[mid] <= item:
         _UpperCAmelCase       :       Dict							   =mid + 1
      else:
         _UpperCAmelCase       :       Tuple							   =mid

   return lo





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int	,   __lowerCamelCase	:							int = 0	,   __lowerCamelCase	:							int = -1							):







   '''simple docstring'''




   sorted_collection.insert(bisect_left(__lowerCamelCase	,   __lowerCamelCase	,   __lowerCamelCase	,   __lowerCamelCase							)	,   __lowerCamelCase							)





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int	,   __lowerCamelCase	:							int = 0	,   __lowerCamelCase	:							int = -1							):







   '''simple docstring'''




   sorted_collection.insert(bisect_right(__lowerCamelCase	,   __lowerCamelCase	,   __lowerCamelCase	,   __lowerCamelCase							)	,   __lowerCamelCase							)





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int							):







   '''simple docstring'''




   _UpperCAmelCase       :       Optional[int]							   =0
   _UpperCAmelCase       :       Any							   =len(__lowerCamelCase							) - 1

   while left <= right:
      _UpperCAmelCase       :       int							   =left + (right - left) // 2
      _UpperCAmelCase       :       Union[str, Any]							   =sorted_collection[midpoint]
      if current_item == item:
         return midpoint
      elif item < current_item:
         _UpperCAmelCase       :       Optional[Any]							   =midpoint - 1
      else:
         _UpperCAmelCase       :       int							   =midpoint + 1
   return None





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int							):







   '''simple docstring'''




   _UpperCAmelCase       :       Any							   =bisect.bisect_left(__lowerCamelCase	,   __lowerCamelCase							)
   if index != len(__lowerCamelCase							) and sorted_collection[index] == item:
      return index
   return None





def lowerCamelCase__      (						__lowerCamelCase	:							list[int]	,   __lowerCamelCase	:							int	,   __lowerCamelCase	:							int	,   __lowerCamelCase	:							int							):







   '''simple docstring'''




   if right < left:
      return None

   _UpperCAmelCase       :       str							   =left + (right - left) // 2

   if sorted_collection[midpoint] == item:
      return midpoint
   elif sorted_collection[midpoint] > item:
      return binary_search_by_recursion(__lowerCamelCase	,   __lowerCamelCase	,   __lowerCamelCase	,   midpoint - 1							)
   else:
      return binary_search_by_recursion(__lowerCamelCase	,   __lowerCamelCase	,   midpoint + 1	,   __lowerCamelCase							)


if __name__ == "__main__":
 lowercase							=input('Enter numbers separated by comma:\n').strip()
 lowercase							=sorted(int(item) for item in user_input.split(','))
 lowercase							=int(input('Enter a single number to be found in the list:\n'))
 lowercase							=binary_search(collection, target)
 if result is None:
  print(F"""{target} was not found in {collection}.""")
 else:
  print(F"""{target} was found at position {result} in {collection}.""")

