


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							:			Any					,      __lowerCamelCase							:			List[Any]					,      __lowerCamelCase							:			Dict=13					,      __lowerCamelCase							:			Union[str, Any]=2					,      __lowerCamelCase							:			str=24					,      __lowerCamelCase							:			int=16					,      __lowerCamelCase							:			str=True					,      __lowerCamelCase							:			int=True					,      __lowerCamelCase							:			List[str]=32					,      __lowerCamelCase							:			Union[str, Any]=5					,      __lowerCamelCase							:			Dict=4					,      __lowerCamelCase							:			Union[str, Any]=37					,      __lowerCamelCase							:			List[str]="gelu"					,      __lowerCamelCase							:			str=0.1					,      __lowerCamelCase							:			int=0.1					,      __lowerCamelCase							:			Dict=10					,      __lowerCamelCase							:			str=0.0_2					,      __lowerCamelCase							:			Optional[Any]=None					,      __lowerCamelCase							:			Optional[Any]=2					,      __lowerCamelCase							:			List[Any]=2					,      ):


             '''simple docstring'''



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

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





       def 						lowerCAmelCase     (   self							:			Any       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]       )

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

             lowerCamelCase__		:				str    =  self.get_config()

             return config, input_values, labels





       def 						lowerCAmelCase     (   self							:			Optional[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=__lowerCamelCase					,      initializer_range=self.initializer_range					,      frequency_stride=self.frequency_stride					,      time_stride=self.time_stride					,      )





       def 						lowerCAmelCase     (   self							:			Tuple					,      __lowerCamelCase							:			Optional[int]					,      __lowerCamelCase							:			int					,      __lowerCamelCase							:			List[str]       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  ASTModel(config=__lowerCamelCase       )
             model.to(__lowerCamelCase       )
             model.eval()
             lowerCamelCase__		:				List[str]    =  model(__lowerCamelCase       )
             self.parent.assertEqual(result.last_hidden_state.shape					,      (self.batch_size, self.seq_length, self.hidden_size)       )





       def 						lowerCAmelCase     (   self							:			Optional[int]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  self.prepare_config_and_inputs()
             (
                 (
                 lowerCamelCase__
             )    ,   (
                 lowerCamelCase__
             )    ,   (
                 lowerCamelCase__
             )    ,   
             )		:				Dict    =  config_and_inputs
             lowerCamelCase__		:				str    =  {"input_values": input_values}
             return config, inputs_dict







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


       """simple docstring"""




       A__											=			(
           (
               ASTModel,
               ASTForAudioClassification,
           )
           if is_torch_available()
           else ()
       )
       A__											=			(
           {"audio-classification": ASTForAudioClassification, "feature-extraction": ASTModel}
           if is_torch_available()
           else {}
       )
       A__											=			False
       A__											=			False
       A__											=			False
       A__											=			False





       def 						lowerCAmelCase     (   self							:			List[Any]					,      __lowerCamelCase							:			Union[str, Any]					,      __lowerCamelCase							:			str					,      __lowerCamelCase							:			str					,      __lowerCamelCase							:			Dict					,      __lowerCamelCase							:			Tuple       ):


             '''simple docstring'''



             if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                   return True

             return False





       def 						lowerCAmelCase     (   self							:			Optional[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Any    =  ASTModelTester(self       )
             lowerCamelCase__		:				Optional[int]    =  ConfigTester(self					,      config_class=__lowerCamelCase					,      has_text_modality=__lowerCamelCase					,      hidden_size=37       )





       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							:			Optional[Any]       ):


             '''simple docstring'''



             pass





       def 						lowerCAmelCase     (   self							:			Tuple       ):


             '''simple docstring'''



             lowerCamelCase__    ,   lowerCamelCase__		:				List[str]    =  self.model_tester.prepare_config_and_inputs_for_common()

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





       def 						lowerCAmelCase     (   self							:			Tuple       ):


             '''simple docstring'''



             lowerCamelCase__    ,   lowerCamelCase__		:				Optional[Any]    =  self.model_tester.prepare_config_and_inputs_for_common()

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

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





       def 						lowerCAmelCase     (   self							:			Optional[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				List[str]    =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*__lowerCamelCase       )





       @slow
       def 						lowerCAmelCase     (   self							:			Tuple       ):


             '''simple docstring'''



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



def       lowercase_		(		):

      """simple docstring"""




      lowerCamelCase__		:				List[Any]    =  hf_hub_download(
          repo_id="nielsr/audio-spectogram-transformer-checkpoint"    ,					filename="sample_audio.flac"    ,					repo_type="dataset"						)

      lowerCamelCase__    ,   lowerCamelCase__		:				Optional[Any]    =  torchaudio.load(_A						)

      return audio, sampling_rate







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


       """simple docstring"""




       @cached_property
       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



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





       @slow
       def 						lowerCAmelCase     (   self							:			Tuple       ):


             '''simple docstring'''



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

             lowerCamelCase__		:				Tuple    =  self.default_feature_extractor
             lowerCamelCase__    ,   lowerCamelCase__		:				str    =  prepare_audio()
             lowerCamelCase__		:				Optional[Any]    =  audio.squeeze().numpy()
             lowerCamelCase__		:				Optional[Any]    =  feature_extractor(__lowerCamelCase					,      sampling_rate=__lowerCamelCase					,      return_tensors="pt"       ).to(__lowerCamelCase       )

             # forward pass
             with torch.no_grad():
                   lowerCamelCase__		:				Optional[Any]    =  model(**__lowerCamelCase       )

             # verify the logits
             lowerCamelCase__		:				List[Any]    =  torch.Size((1, 527)       )
             self.assertEqual(outputs.logits.shape					,      __lowerCamelCase       )

             lowerCamelCase__		:				Tuple    =  torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]       ).to(__lowerCamelCase       )

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






import unittest

from transformers import (
    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
    TextClassificationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, nested_simplify, require_tf, require_torch, slow

from .test_pipelines_common import ANY


# These 2 model types require different inputs than those of the usual text models.
A      :    Union[str, Any]		=					{"LayoutLMv2Config", "LayoutLMv3Config"}







@is_pipeline_test
class 			_lowercase (							unittest.TestCase):


       """simple docstring"""




       A__											=			MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
       A__											=			TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

       if model_mapping is not None:
              A__											=			{config: model for config, model in model_mapping.items() if config.__name__ not in _TO_SKIP}
       if tf_model_mapping is not None:
              A__											=			{
                  config: model for config, model in tf_model_mapping.items() if config.__name__ not in _TO_SKIP
              }





       @require_torch
       def 						lowerCAmelCase     (   self							:			List[str]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  pipeline(
                 task="text-classification"					,      model="hf-internal-testing/tiny-random-distilbert"					,      framework="pt"       )

             lowerCamelCase__		:				Dict    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )

             lowerCamelCase__		:				List[str]    =  text_classifier("This is great !"					,      top_k=2       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}]       )

             lowerCamelCase__		:				Optional[int]    =  text_classifier(["This is great !", "This is bad"]					,      top_k=2       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                 ]					,      )

             lowerCamelCase__		:				Any    =  text_classifier("This is great !"					,      top_k=1       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )

             # Legacy behavior
             lowerCamelCase__		:				Dict    =  text_classifier("This is great !"					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )

             lowerCamelCase__		:				str    =  text_classifier("This is great !"					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [[{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}]]       )

             lowerCamelCase__		:				Optional[Any]    =  text_classifier(["This is great !", "Something else"]					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                     [{"label": "LABEL_0", "score": 0.5_0_4}, {"label": "LABEL_1", "score": 0.4_9_6}],
                 ]					,      )

             lowerCamelCase__		:				Any    =  text_classifier(["This is great !", "Something else"]					,      return_all_scores=__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [
                     {"label": "LABEL_0", "score": 0.5_0_4},
                     {"label": "LABEL_0", "score": 0.5_0_4},
                 ]					,      )





       @require_torch
       def 						lowerCAmelCase     (   self							:			str       ):


             '''simple docstring'''



             import torch

             lowerCamelCase__		:				int    =  pipeline(
                 task="text-classification"					,      model="hf-internal-testing/tiny-random-distilbert"					,      framework="pt"					,      device=torch.device("cpu"       )					,      )

             lowerCamelCase__		:				Any    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )





       @require_tf
       def 						lowerCAmelCase     (   self							:			int       ):


             '''simple docstring'''



             lowerCamelCase__		:				List[str]    =  pipeline(
                 task="text-classification"					,      model="hf-internal-testing/tiny-random-distilbert"					,      framework="tf"       )

             lowerCamelCase__		:				List[str]    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "LABEL_0", "score": 0.5_0_4}]       )





       @slow
       @require_torch
       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Optional[Any]    =  pipeline("text-classification"       )

             lowerCamelCase__		:				List[str]    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Optional[int]    =  text_classifier("This is bad !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "NEGATIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Tuple    =  text_classifier("Birds are a type of animal"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 0.9_8_8}]       )





       @slow
       @require_tf
       def 						lowerCAmelCase     (   self							:			List[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				str    =  pipeline("text-classification"					,      framework="tf"       )

             lowerCamelCase__		:				Optional[int]    =  text_classifier("This is great !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Optional[Any]    =  text_classifier("This is bad !"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "NEGATIVE", "score": 1.0}]       )
             lowerCamelCase__		:				Dict    =  text_classifier("Birds are a type of animal"       )
             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": "POSITIVE", "score": 0.9_8_8}]       )





       def 						lowerCAmelCase     (   self							:			Tuple					,      __lowerCamelCase							:			Any					,      __lowerCamelCase							:			str					,      __lowerCamelCase							:			Optional[Any]       ):


             '''simple docstring'''



             lowerCamelCase__		:				Tuple    =  TextClassificationPipeline(model=__lowerCamelCase					,      tokenizer=__lowerCamelCase       )
             return text_classifier, ["HuggingFace is in", "This is another test"]





       def 						lowerCAmelCase     (   self							:			Optional[Any]					,      __lowerCamelCase							:			Tuple					,      __lowerCamelCase							:			Any       ):


             '''simple docstring'''



             lowerCamelCase__		:				int    =  text_classifier.model
             # Small inputs because BartTokenizer tiny has maximum position embeddings = 22
             lowerCamelCase__		:				List[Any]    =  "HuggingFace is in"
             lowerCamelCase__		:				Tuple    =  text_classifier(__lowerCamelCase       )

             self.assertEqual(nested_simplify(__lowerCamelCase       )					,      [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}]       )
             self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )

             lowerCamelCase__		:				Optional[int]    =  ["HuggingFace is in ", "Paris is in France"]
             lowerCamelCase__		:				Dict    =  text_classifier(__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}, {"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}]					,      )
             self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )
             self.assertTrue(outputs[1]["label"] in model.config.idalabel.values()       )

             # Forcing to get all results with `top_k=None`
             # This is NOT the legacy format
             lowerCamelCase__		:				List[Any]    =  text_classifier(__lowerCamelCase					,      top_k=__lowerCamelCase       )
             lowerCamelCase__		:				Union[str, Any]    =  len(model.config.idalabel.values()       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [[{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}] * N, [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}] * N]					,      )

             lowerCamelCase__		:				Optional[int]    =  {"text": "HuggingFace is in ", "text_pair": "Paris is in France"}
             lowerCamelCase__		:				List[Any]    =  text_classifier(__lowerCamelCase       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      {"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}					,      )
             self.assertTrue(outputs["label"] in model.config.idalabel.values()       )

             # This might be used a text pair, but tokenizer + pipe interaction
             # makes it hard to understand that it's not using the pair properly
             # https://github.com/huggingface/transformers/issues/17305
             # We disabled this usage instead as it was outputting wrong outputs.
             lowerCamelCase__		:				Any    =  [["HuggingFace is in ", "Paris is in France"]]
             with self.assertRaises(__lowerCamelCase       ):
                   text_classifier(__lowerCamelCase       )

             # This used to be valid for doing text pairs
             # We're keeping it working because of backward compatibility
             lowerCamelCase__		:				int    =  text_classifier([[["HuggingFace is in ", "Paris is in France"]]]       )
             self.assertEqual(
                 nested_simplify(__lowerCamelCase       )					,      [{"label": ANY(__lowerCamelCase       ), "score": ANY(__lowerCamelCase       )}]					,      )
             self.assertTrue(outputs[0]["label"] in model.config.idalabel.values()       )


