




"""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  lowercase:







 '''simple docstring'''





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




   '''simple docstring'''



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

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


 def 			UpperCamelCase_       (    self:		List[Any]		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]		)

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

   _snake_case							:		int								=  self.get_config()

   return config, input_values, labels


 def 			UpperCamelCase_       (    self:		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=a_,				initializer_range=self.initializer_range,				frequency_stride=self.frequency_stride,				time_stride=self.time_stride,				)


 def 			UpperCamelCase_       (    self:		Tuple,				a_:		str,				a_:		Dict,				a_:		Tuple		):




   '''simple docstring'''



   _snake_case							:		Union[str, Any]								=  ASTModel(config=a_		)
   model.to(a_		)
   model.eval()
   _snake_case							:		int								=  model(a_		)
   self.parent.assertEqual(result.last_hidden_state.shape,				(self.batch_size, self.seq_length, self.hidden_size)		)


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



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







@require_torch
class  lowercase(					__a	,      __a	,      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 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		str,				a_:		str,				a_:		int,				a_:		List[Any],				a_:		Tuple		):




   '''simple docstring'''



   if pipeline_test_casse_name == "AudioClassificationPipelineTests":
     return True

   return False


 def 			UpperCamelCase_       (    self:		List[str]		):




   '''simple docstring'''



   _snake_case							:		List[Any]								=  ASTModelTester(self		)
   _snake_case							:		Dict								=  ConfigTester(self,				config_class=a_,				has_text_modality=a_,				hidden_size=37		)


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   self.config_tester.run_common_tests()


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




   '''simple docstring'''



   pass


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		int								=  self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     _snake_case							:		List[str]								=  model_class(a_		)
     self.assertIsInstance(model.get_input_embeddings(),				(nn.Module)		)
     _snake_case							:		Union[str, Any]								=  model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(a_,				nn.Linear		)		)


 def 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   _snake_case							:		Any								=  self.model_tester.prepare_config_and_inputs_for_common()

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

     _snake_case							:		List[str]								=  ["""input_values"""]
     self.assertListEqual(arg_names[:1],				a_		)


 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   _snake_case							:		Optional[Any]								=  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*a_		)


 @slow
 def 			UpperCamelCase_       (    self:		str		):




   '''simple docstring'''



   for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     _snake_case							:		Dict								=  ASTModel.from_pretrained(a_		)
     self.assertIsNotNone(a_		)







def  UpperCAmelCase__	():
  """simple docstring"""

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

  _snake_case							:		List[Any]								=  torchaudio.load(snake_case__   )

  return audio, sampling_rate






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







 '''simple docstring'''





 @cached_property
 def 			UpperCamelCase_       (    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 			UpperCamelCase_       (    self:		Any		):




   '''simple docstring'''



   _snake_case							:		Dict								=  self.default_feature_extractor
   _snake_case							:		List[Any]								=  ASTForAudioClassification.from_pretrained("""MIT/ast-finetuned-audioset-10-10-0.4593"""		).to(a_		)

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

   # forward pass
   with torch.no_grad():
     _snake_case							:		Optional[int]								=  model(**a_		)

   # verify the logits
   _snake_case							:		Optional[Any]								=  torch.Size((1, 527)		)
   self.assertEqual(outputs.logits.shape,				a_		)

   _snake_case							:		Any								=  torch.tensor([-0.8_760, -7.0_042, -8.6_602]		).to(a_		)

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








"""simple docstring"""


from collections.abc import Generator
from math import sin


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) != 32:
    raise ValueError("""Input must be of length 32"""   )

  _snake_case							:		Optional[int]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[Any]								=  format(snake_case__		,       """08x"""   )[-8:]
  _snake_case							:		Optional[Any]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8"""   )
  return little_endian_hex


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Union[str, Any]								=  B""""""
  for char in message:
    bit_string += format(snake_case__		,       """08b"""   ).encode("""utf-8"""   )
  _snake_case							:		List[Any]								=  format(len(snake_case__   )		,       """064b"""   ).encode("""utf-8"""   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(snake_case__   ) % 5_12 != 4_48:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) % 5_12 != 0:
    raise ValueError("""Input must have length that's a multiple of 512"""   )

  for pos in range(0		,       len(snake_case__   )		,       5_12   ):
    _snake_case							:		List[str]								=  bit_string[pos : pos + 5_12]
    _snake_case							:		List[str]								=  []
    for i in range(0		,       5_12		,       32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   )		,       2   )   )
    yield block_words


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[int]								=  format(snake_case__		,       """032b"""   )
  _snake_case							:		str								=  """"""
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(snake_case__		,       2   )


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  return (a + b) % 2**32


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )
  if shift < 0:
    raise ValueError("""Shift must be non-negative"""   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Any								=  preprocess(snake_case__   )

  _snake_case							:		Optional[Any]								=  [int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  _snake_case							:		Union[str, Any]								=  0x6745_2301
  _snake_case							:		List[Any]								=  0xEFCD_AB89
  _snake_case							:		Optional[Any]								=  0x98BA_DCFE
  _snake_case							:		Optional[int]								=  0x1032_5476

  _snake_case							:		Tuple								=  [
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(snake_case__   ):
    _snake_case							:		Tuple								=  aa
    _snake_case							:		str								=  ba
    _snake_case							:		int								=  ca
    _snake_case							:		Dict								=  da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        _snake_case							:		int								=  d ^ (b & (c ^ d))
        _snake_case							:		Dict								=  i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        _snake_case							:		Tuple								=  c ^ (d & (b ^ c))
        _snake_case							:		int								=  (5 * i + 1) % 16
      elif i <= 47:
        _snake_case							:		List[Any]								=  b ^ c ^ d
        _snake_case							:		Union[str, Any]								=  (3 * i + 5) % 16
      else:
        _snake_case							:		Tuple								=  c ^ (b | not_aa(snake_case__   ))
        _snake_case							:		Optional[int]								=  (7 * i) % 16
      _snake_case							:		Dict								=  (f + a + added_consts[i] + block_words[g]) % 2**32
      _snake_case							:		List[str]								=  d
      _snake_case							:		List[Any]								=  c
      _snake_case							:		str								=  b
      _snake_case							:		List[str]								=  sum_aa(snake_case__		,       left_rotate_aa(snake_case__		,       shift_amounts[i]   )   )

    # Add hashed chunk to running total
    _snake_case							:		Union[str, Any]								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		str								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		Any								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		List[str]								=  sum_aa(snake_case__		,       snake_case__   )

  _snake_case							:		Any								=  reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()


