


'''simple docstring'''

from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
   import tensorflow as tf

   from transformers import (
       TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
       TFTransfoXLForSequenceClassification,
       TFTransfoXLLMHeadModel,
       TFTransfoXLModel,
   )





class 						__SCREAMING_SNAKE_CASE					:






     def __init__(			self     ,							__UpperCamelCase     ,							)       ->    List[str]:
          _a						=		parent
          _a						=		13
          _a						=		7
          _a						=		30
          _a						=		self.seq_length + self.mem_len
          _a						=		15
          _a						=		True
          _a						=		True
          _a						=		99
          _a						=		[10, 50, 80]
          _a						=		32
          _a						=		32
          _a						=		4
          _a						=		8
          _a						=		128
          _a						=		2
          _a						=		2
          _a						=		None
          _a						=		1
          _a						=		0
          _a						=		3
          _a						=		self.vocab_size - 1
          _a						=		0.01






     def  a_					(			self		)       ->    Union[str, Any]:
          _a						=		ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size		)
          _a						=		ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size		)

          _a						=		None
          if self.use_labels:
               _a						=		ids_tensor([self.batch_size, self.seq_length]     ,							self.vocab_size		)

          _a						=		TransfoXLConfig(
              vocab_size=self.vocab_size     ,							mem_len=self.mem_len     ,							clamp_len=self.clamp_len     ,							cutoffs=self.cutoffs     ,							d_model=self.hidden_size     ,							d_embed=self.d_embed     ,							n_head=self.num_attention_heads     ,							d_head=self.d_head     ,							d_inner=self.d_inner     ,							div_val=self.div_val     ,							n_layer=self.num_hidden_layers     ,							eos_token_id=self.eos_token_id     ,							pad_token_id=self.vocab_size - 1     ,							init_range=self.init_range     ,							num_labels=self.num_labels     ,							)

          return (config, input_ids_a, input_ids_a, lm_labels)






     def  a_					(			self		)       ->    Tuple:
          random.seed(self.seed		)
          tf.random.set_seed(self.seed		)






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Tuple:
          _a						=		TFTransfoXLModel(__UpperCamelCase		)

          _a			,			_a						=		model(__UpperCamelCase		).to_tuple()

          _a						=		{"input_ids": input_ids_a, "mems": mems_a}

          _a			,			_a						=		model(__UpperCamelCase		).to_tuple()

          self.parent.assertEqual(hidden_states_a.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)		)
          self.parent.assertEqual(hidden_states_a.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)		)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]     ,							[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,							)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]     ,							[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,							)






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Dict:
          _a						=		TFTransfoXLLMHeadModel(__UpperCamelCase		)

          _a			,			_a						=		model(__UpperCamelCase		).to_tuple()

          _a						=		{"input_ids": input_ids_a, "labels": lm_labels}
          _a			,			_a						=		model(__UpperCamelCase		).to_tuple()

          _a			,			_a						=		model([input_ids_a, mems_a]		).to_tuple()

          _a						=		{"input_ids": input_ids_a, "mems": mems_a, "labels": lm_labels}

          _a			,			_a						=		model(__UpperCamelCase		).to_tuple()

          self.parent.assertEqual(lm_logits_a.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)		)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]     ,							[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,							)

          self.parent.assertEqual(lm_logits_a.shape     ,							(self.batch_size, self.seq_length, self.vocab_size)		)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]     ,							[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers     ,							)






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Optional[int]:
          _a						=		TFTransfoXLForSequenceClassification(__UpperCamelCase		)
          _a						=		model(__UpperCamelCase		)
          self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)		)






     def  a_					(			self		)       ->    Union[str, Any]:
          _a						=		self.prepare_config_and_inputs()
          ((_a)			,			(_a)			,			(_a)			,			(_a))						=		config_and_inputs
          _a						=		{"input_ids": input_ids_a}
          return config, inputs_dict







@require_tf
class 						__SCREAMING_SNAKE_CASE					(      lowerCamelCase__ ,			lowerCamelCase__ ,			unittest.TestCase ):
     UpperCAmelCase 					=				(
         (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
     )
     UpperCAmelCase 					=				() if is_tf_available() else ()
     UpperCAmelCase 					=				(
         {
             '''feature-extraction''': TFTransfoXLModel,
             '''text-classification''': TFTransfoXLForSequenceClassification,
             '''text-generation''': TFTransfoXLLMHeadModel,
             '''zero-shot''': TFTransfoXLForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False
     UpperCAmelCase 					=				False






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Any:
          if pipeline_test_casse_name == "TextGenerationPipelineTests":
               # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
               # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
               # tokenizer.
               return True

          return False






     def  a_					(			self		)       ->    Tuple:
          _a						=		TFTransfoXLModelTester(self		)
          _a						=		ConfigTester(self     ,							config_class=__UpperCamelCase     ,							d_embed=37		)






     def  a_					(			self		)       ->    Tuple:
          self.config_tester.run_common_tests()






     def  a_					(			self		)       ->    str:
          self.model_tester.set_seed()
          _a						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_transfo_xl_model(*__UpperCamelCase		)






     def  a_					(			self		)       ->    Dict:
          self.model_tester.set_seed()
          _a						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_transfo_xl_lm_head(*__UpperCamelCase		)






     def  a_					(			self		)       ->    str:
          _a						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*__UpperCamelCase		)






     def  a_					(			self		)       ->    Union[str, Any]:
          _a			,			_a						=		self.model_tester.prepare_config_and_inputs_for_common()
          _a						=		[TFTransfoXLForSequenceClassification]

          for model_class in self.all_model_classes:
               _a						=		model_class(__UpperCamelCase		)
               assert isinstance(model.get_input_embeddings()     ,							tf.keras.layers.Layer		)
               if model_class in list_other_models_with_output_ebd:
                    _a						=		model.get_output_embeddings()
                    assert isinstance(__UpperCamelCase     ,							tf.keras.layers.Layer		)
                    _a						=		model.get_bias()
                    assert name is None
               else:
                    _a						=		model.get_output_embeddings()
                    assert x is None
                    _a						=		model.get_bias()
                    assert name is None






     def  a_					(			self		)       ->    str:
          # TODO JP: Make TransfoXL XLA compliant
          pass






     @slow
     def  a_					(			self		)       ->    List[Any]:
          for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _a						=		TFTransfoXLModel.from_pretrained(__UpperCamelCase		)
               self.assertIsNotNone(__UpperCamelCase		)






     @unittest.skip(reason="This model doesn't play well with fit() due to not returning a single loss."		)
     def  a_					(			self		)       ->    int:
          pass







@require_tf
class 						__SCREAMING_SNAKE_CASE					(      unittest.TestCase ):






     @unittest.skip("Skip test until #12651 is resolved."		)
     @slow
     def  a_					(			self		)       ->    List[Any]:
          _a						=		TFTransfoXLLMHeadModel.from_pretrained("transfo-xl-wt103"		)
          # fmt: off
          _a						=		tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]]     ,							dtype=tf.intaa		)  # noqa: E231
          # fmt: on
          #  In 1991 , the remains of Russian Tsar Nicholas II and his family
          #  ( except for Alexei and Maria ) are discovered .
          #  The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
          #  remainder of the story . 1883 Western Siberia ,
          #  a young Grigori Rasputin is asked by his father and a group of men to perform magic .
          #  Rasputin has a vision and denounces one of the men as a horse thief . Although his
          #  father initially slaps him for making such an accusation , Rasputin watches as the
          #  man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
          #  the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
          #  with people , even a bishop , begging for his blessing . <eod> </s> <eos>

          # fmt: off
          _a						=		[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0]  # noqa: E231
          # fmt: on
          #  In 1991, the remains of Russian Tsar Nicholas II and his family (
          #  except for Alexei and Maria ) are discovered. The voice of young son,
          #  Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
          #  1883 Western Siberia, a young Grigori Rasputin is asked by his father
          #  and a group of men to perform magic. Rasputin has a vision and
          #  denounces one of the men as a horse thief. Although his father initially
          #  slaps him for making such an accusation, Rasputin watches as the man
          #  is chased outside and beaten. Twenty years later, Rasputin sees a vision
          #  of the Virgin Mary, prompting him to become a priest.
          #  Rasputin quickly becomes famous, with people, even a bishop, begging for
          #  his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
          # Nicholas II and his family were discovered. The voice of <unk> young son,
          # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

          _a						=		model.generate(__UpperCamelCase     ,							max_length=200     ,							do_sample=__UpperCamelCase		)
          self.assertListEqual(output_ids[0].numpy().tolist()     ,							__UpperCamelCase		)





'''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 						__SCREAMING_SNAKE_CASE					:






     def __init__(			self     ,							__UpperCamelCase     ,							__UpperCamelCase=13     ,							__UpperCamelCase=2     ,							__UpperCamelCase=24     ,							__UpperCamelCase=16     ,							__UpperCamelCase=True     ,							__UpperCamelCase=True     ,							__UpperCamelCase=32     ,							__UpperCamelCase=5     ,							__UpperCamelCase=4     ,							__UpperCamelCase=37     ,							__UpperCamelCase="gelu"     ,							__UpperCamelCase=0.1     ,							__UpperCamelCase=0.1     ,							__UpperCamelCase=10     ,							__UpperCamelCase=0.02     ,							__UpperCamelCase=None     ,							__UpperCamelCase=2     ,							__UpperCamelCase=2     ,							)       ->    Optional[int]:
          _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  a_					(			self		)       ->    List[str]:
          _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  a_					(			self		)       ->    Optional[int]:
          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=__UpperCamelCase     ,							initializer_range=self.initializer_range     ,							frequency_stride=self.frequency_stride     ,							time_stride=self.time_stride     ,							)






     def  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    Optional[Any]:
          _a						=		ASTModel(config=__UpperCamelCase		)
          model.to(__UpperCamelCase		)
          model.eval()
          _a						=		model(__UpperCamelCase		)
          self.parent.assertEqual(result.last_hidden_state.shape     ,							(self.batch_size, self.seq_length, self.hidden_size)		)






     def  a_					(			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 						__SCREAMING_SNAKE_CASE					(      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  a_					(			self     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase     ,							__UpperCamelCase		)       ->    List[str]:
          if pipeline_test_casse_name == "AudioClassificationPipelineTests":
               return True

          return False






     def  a_					(			self		)       ->    int:
          _a						=		ASTModelTester(self		)
          _a						=		ConfigTester(self     ,							config_class=__UpperCamelCase     ,							has_text_modality=__UpperCamelCase     ,							hidden_size=37		)






     def  a_					(			self		)       ->    str:
          self.config_tester.run_common_tests()






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






     def  a_					(			self		)       ->    List[Any]:
          _a			,			_a						=		self.model_tester.prepare_config_and_inputs_for_common()

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






     def  a_					(			self		)       ->    Any:
          _a			,			_a						=		self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               _a						=		model_class(__UpperCamelCase		)
               _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]     ,							__UpperCamelCase		)






     def  a_					(			self		)       ->    int:
          _a						=		self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__UpperCamelCase		)






     @slow
     def  a_					(			self		)       ->    Optional[Any]:
          for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               _a						=		ASTModel.from_pretrained(__UpperCamelCase		)
               self.assertIsNotNone(__UpperCamelCase		)







def __UpperCamelCase   (			)      ->     Dict:







     '''simple docstring'''






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

     _a			,			_a						=		torchaudio.load(__lowerCamelCase				)

     return audio, sampling_rate






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






     @cached_property
     def  a_					(			self		)       ->    int:
          return (
              ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"		)
              if is_torchaudio_available()
              else None
          )






     @slow
     def  a_					(			self		)       ->    Dict:
          _a						=		self.default_feature_extractor
          _a						=		ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"		).to(__UpperCamelCase		)

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

          # forward pass
          with torch.no_grad():
               _a						=		model(**__UpperCamelCase		)

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

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

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

