




'''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 			_UpperCamelCase      :
      def __init__(			self   :Any ,      lowerCamelCase   :List[str] ,      lowerCamelCase   :Optional[int]=13 ,      lowerCamelCase   :Optional[Any]=2 ,      lowerCamelCase   :Any=24 ,      lowerCamelCase   :Union[str, Any]=16 ,      lowerCamelCase   :Any=True ,      lowerCamelCase   :int=True ,      lowerCamelCase   :Optional[Any]=32 ,      lowerCamelCase   :Union[str, Any]=5 ,      lowerCamelCase   :Tuple=4 ,      lowerCamelCase   :Optional[Any]=37 ,      lowerCamelCase   :Optional[Any]="gelu" ,      lowerCamelCase   :int=0.1 ,      lowerCamelCase   :Tuple=0.1 ,      lowerCamelCase   :List[str]=10 ,      lowerCamelCase   :Optional[Any]=0.02 ,      lowerCamelCase   :Optional[int]=None ,      lowerCamelCase   :Optional[Any]=2 ,      lowerCamelCase   :List[Any]=2 ,      )     ->			Union[str, Any]:
       UpperCAmelCase__							 =						parent
       UpperCAmelCase__							 =						batch_size
       UpperCAmelCase__							 =						patch_size
       UpperCAmelCase__							 =						max_length
       UpperCAmelCase__							 =						num_mel_bins
       UpperCAmelCase__							 =						is_training
       UpperCAmelCase__							 =						use_labels
       UpperCAmelCase__							 =						hidden_size
       UpperCAmelCase__							 =						num_hidden_layers
       UpperCAmelCase__							 =						num_attention_heads
       UpperCAmelCase__							 =						intermediate_size
       UpperCAmelCase__							 =						hidden_act
       UpperCAmelCase__							 =						hidden_dropout_prob
       UpperCAmelCase__							 =						attention_probs_dropout_prob
       UpperCAmelCase__							 =						type_sequence_label_size
       UpperCAmelCase__							 =						initializer_range
       UpperCAmelCase__							 =						scope
       UpperCAmelCase__							 =						frequency_stride
       UpperCAmelCase__							 =						time_stride

       # in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
       UpperCAmelCase__							 =						(self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
       UpperCAmelCase__							 =						(self.max_length - self.patch_size) // self.time_stride + 1
       UpperCAmelCase__							 =						frequency_out_dimension * time_out_dimension
       UpperCAmelCase__							 =						num_patches + 2
      def 	UpperCAmelCase_						(			self   :int      )     ->			List[str]:
       UpperCAmelCase__							 =						floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

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

       UpperCAmelCase__							 =						self.get_config()

       return config, input_values, labels
      def 	UpperCAmelCase_						(			self   :List[Any]      )     ->			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=lowerCamelCase ,      initializer_range=self.initializer_range ,      frequency_stride=self.frequency_stride ,      time_stride=self.time_stride ,      )
      def 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :List[str] ,      lowerCamelCase   :List[str] ,      lowerCamelCase   :List[str]      )     ->			Optional[Any]:
       UpperCAmelCase__							 =						ASTModel(config=lowerCamelCase      )
       model.to(lowerCamelCase      )
       model.eval()
       UpperCAmelCase__							 =						model(lowerCamelCase      )
       self.parent.assertEqual(result.last_hidden_state.shape ,      (self.batch_size, self.seq_length, self.hidden_size)      )







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



@require_torch
class 			_UpperCamelCase      (				lowerCAmelCase	,       lowerCAmelCase	,       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 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :Optional[int] ,      lowerCamelCase   :List[Any] ,      lowerCamelCase   :str ,      lowerCamelCase   :List[Any] ,      lowerCamelCase   :int      )     ->			str:
       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
        return True

       return False
      def 	UpperCAmelCase_						(			self   :List[str]      )     ->			int:
       UpperCAmelCase__							 =						ASTModelTester(self      )
       UpperCAmelCase__							 =						ConfigTester(self ,      config_class=lowerCamelCase ,      has_text_modality=lowerCamelCase ,      hidden_size=37      )
      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			str:
       self.config_tester.run_common_tests()
      @unittest.skip(reason="AST does not use inputs_embeds"      )
      def 	UpperCAmelCase_						(			self   :List[str]      )     ->			Optional[Any]:
       pass
      def 	UpperCAmelCase_						(			self   :Optional[int]      )     ->			Any:
       UpperCAmelCase__ , UpperCAmelCase__							 =						self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        UpperCAmelCase__							 =						model_class(lowerCamelCase      )
        self.assertIsInstance(model.get_input_embeddings() ,      (nn.Module)      )
        UpperCAmelCase__							 =						model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(lowerCamelCase ,      nn.Linear      )      )
      def 	UpperCAmelCase_						(			self   :Tuple      )     ->			List[str]:
       UpperCAmelCase__ , UpperCAmelCase__							 =						self.model_tester.prepare_config_and_inputs_for_common()

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

        UpperCAmelCase__							 =						["input_values"]
        self.assertListEqual(arg_names[:1] ,      lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :int      )     ->			Any:
       UpperCAmelCase__							 =						self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase      )







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



def 						lowerCAmelCase		(		):




 """simple docstring"""







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

 UpperCAmelCase__ , UpperCAmelCase__							 =						torchaudio.load(_lowerCAmelCase	)

 return audio, sampling_rate


@require_torch
@require_torchaudio
class 			_UpperCamelCase      (				unittest.TestCase		):
      @cached_property
      def 	UpperCAmelCase_						(			self   :str      )     ->			Dict:
       return (
           ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      )
           if is_torchaudio_available()
           else None
       )







      @slow
      def 	UpperCAmelCase_						(			self   :str      )     ->			Optional[int]:
       UpperCAmelCase__							 =						self.default_feature_extractor
       UpperCAmelCase__							 =						ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      ).to(lowerCamelCase      )

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

       # forward pass
       with torch.no_grad():
        UpperCAmelCase__							 =						model(**lowerCamelCase      )

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

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

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











import json
from typing import TYPE_CHECKING, List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging


if TYPE_CHECKING:
  from transformers.pipelines.conversational import Conversation


_lowerCAmelCase						:   str		=   logging.get_logger(__name__)

_lowerCAmelCase						:   List[Any]		=   {"tokenizer_file": "tokenizer.json"}

_lowerCAmelCase						:   Tuple		=   {
    "tokenizer_file": {
        "bigscience/tokenizer": "https://huggingface.co/bigscience/tokenizer/blob/main/tokenizer.json",
        "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/tokenizer.json",
        "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/tokenizer.json",
        "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/tokenizer.json",
        "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/tokenizer.json",
        "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/tokenizer.json",
        "bigscience/bloom": "https://huggingface.co/bigscience/bloom/blob/main/tokenizer.json",
    },
}
class 			_UpperCamelCase      (				lowerCAmelCase		):
      UpperCAmelCase_        =		VOCAB_FILES_NAMES
      UpperCAmelCase_        =		PRETRAINED_VOCAB_FILES_MAP
      UpperCAmelCase_        =		["""input_ids""", """attention_mask"""]
      UpperCAmelCase_        =		None
      def __init__(			self   :List[Any] ,      lowerCamelCase   :Union[str, Any]=None ,      lowerCamelCase   :Optional[Any]=None ,      lowerCamelCase   :List[Any]=None ,      lowerCamelCase   :Union[str, Any]="<unk>" ,      lowerCamelCase   :Union[str, Any]="<s>" ,      lowerCamelCase   :Union[str, Any]="</s>" ,      lowerCamelCase   :str="<pad>" ,      lowerCamelCase   :Any=False ,      lowerCamelCase   :Optional[Any]=False ,      **lowerCamelCase   :Optional[Any] ,      )     ->			Any:
       super().__init__(
           lowerCamelCase ,      lowerCamelCase ,      tokenizer_file=lowerCamelCase ,      unk_token=lowerCamelCase ,      bos_token=lowerCamelCase ,      eos_token=lowerCamelCase ,      pad_token=lowerCamelCase ,      add_prefix_space=lowerCamelCase ,      clean_up_tokenization_spaces=lowerCamelCase ,      **lowerCamelCase ,      )
       UpperCAmelCase__							 =						json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()      )
       if pre_tok_state.get("add_prefix_space" ,      lowerCamelCase      ) != add_prefix_space:
        UpperCAmelCase__							 =						getattr(lowerCamelCase ,      pre_tok_state.pop("type"      )      )
        UpperCAmelCase__							 =						add_prefix_space
        UpperCAmelCase__							 =						pre_tok_class(**lowerCamelCase      )

       UpperCAmelCase__							 =						add_prefix_space
      def 	UpperCAmelCase_						(			self   :int ,      *lowerCamelCase   :Any ,      **lowerCamelCase   :int      )     ->			BatchEncoding:
       UpperCAmelCase__							 =						kwargs.get("is_split_into_words" ,      lowerCamelCase      )
       if not (self.add_prefix_space or not is_split_into_words):
        raise Exception(
            f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with'''
            " pretokenized inputs."      )

       return super()._batch_encode_plus(*lowerCamelCase ,      **lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :Any ,      *lowerCamelCase   :List[Any] ,      **lowerCamelCase   :Union[str, Any]      )     ->			BatchEncoding:
       UpperCAmelCase__							 =						kwargs.get("is_split_into_words" ,      lowerCamelCase      )

       if not (self.add_prefix_space or not is_split_into_words):
        raise Exception(
            f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True to use it with'''
            " pretokenized inputs."      )

       return super()._encode_plus(*lowerCamelCase ,      **lowerCamelCase      )
      def 	UpperCAmelCase_						(			self   :Tuple ,      lowerCamelCase   :str ,      lowerCamelCase   :Optional[str] = None      )     ->			Tuple[str]:
       UpperCAmelCase__							 =						self._tokenizer.model.save(lowerCamelCase ,      name=lowerCamelCase      )
       return tuple(lowerCamelCase      )







      def 	UpperCAmelCase_						(			self   :List[str] ,      lowerCamelCase   :"Conversation"      )     ->			List[int]:
       UpperCAmelCase__							 =						[]
       for is_user, text in conversation.iter_texts():
        input_ids.extend(self.encode(lowerCamelCase ,      add_special_tokens=lowerCamelCase      ) + [self.eos_token_id]      )

       if len(lowerCamelCase      ) > self.model_max_length:
        UpperCAmelCase__							 =						input_ids[-self.model_max_length :]
       return input_ids





