


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

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


				def 		__magic_name__(       self			:Tuple	)		->			Any:
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]	)

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

										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		self.get_config()

										return config, input_values, labels


				def 		__magic_name__(       self			:Tuple	)		->			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=lowercase_			,			initializer_range=self.initializer_range			,			frequency_stride=self.frequency_stride			,			time_stride=self.time_stride			,			)


				def 		__magic_name__(       self			:Any			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:Dict			,			lowerCAmelCase__			:str	)		->			Union[str, Any]:
										__SCREAMING_SNAKE_CASE						:     Dict					=		ASTModel(config=lowercase_	)
										model.to(lowercase_	)
										model.eval()
										__SCREAMING_SNAKE_CASE						:     str					=		model(lowercase_	)
										self.parent.assertEqual(result.last_hidden_state.shape			,			(self.batch_size, self.seq_length, self.hidden_size)	)



				def 		__magic_name__(       self			:str	)		->			List[Any]:
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		self.prepare_config_and_inputs()
										(
										    __SCREAMING_SNAKE_CASE   
										)						:     Optional[int]					=		config_and_inputs
										__SCREAMING_SNAKE_CASE						:     str					=		{"input_values": input_values}
										return config, inputs_dict




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






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			int						=		(
				    (
				        ASTModel,
				        ASTForAudioClassification,
				    )
				    if is_torch_available()
				    else ()
				)
				SCREAMING_SNAKE_CASE__				:			Dict						=		(
				    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
				    if is_torch_available()
				    else {}
				)
				SCREAMING_SNAKE_CASE__				:			Optional[int]						=		False
				SCREAMING_SNAKE_CASE__				:			Tuple						=		False
				SCREAMING_SNAKE_CASE__				:			Optional[Any]						=		False
				SCREAMING_SNAKE_CASE__				:			Tuple						=		False


				def 		__magic_name__(       self			:str			,			lowerCAmelCase__			:int			,			lowerCAmelCase__			:Optional[int]			,			lowerCAmelCase__			:List[Any]			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:Any	)		->			Optional[int]:
										if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																return True

										return False


				def 		__magic_name__(       self			:Dict	)		->			Optional[int]:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		ASTModelTester(self	)
										__SCREAMING_SNAKE_CASE						:     Tuple					=		ConfigTester(self			,			config_class=lowercase_			,			has_text_modality=lowercase_			,			hidden_size=37	)


				def 		__magic_name__(       self			:Optional[int]	)		->			Any:
										self.config_tester.run_common_tests()


				@unittest.skip(reason='''AST does not use inputs_embeds'''	)
				def 		__magic_name__(       self			:str	)		->			Any:
										pass


				def 		__magic_name__(       self			:List[Any]	)		->			str:
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		self.model_tester.prepare_config_and_inputs_for_common()

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


				def 		__magic_name__(       self			:Any	)		->			str:
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		self.model_tester.prepare_config_and_inputs_for_common()

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

																__SCREAMING_SNAKE_CASE						:     List[Any]					=		["input_values"]
																self.assertListEqual(arg_names[:1]			,			lowercase_	)


				def 		__magic_name__(       self			:int	)		->			Dict:
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*lowercase_	)



				@slow
				def 		__magic_name__(       self			:Dict	)		->			Tuple:
										for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		ASTModel.from_pretrained(lowercase_	)
																self.assertIsNotNone(lowercase_	)




def        _UpperCamelCase							(      ):
						__SCREAMING_SNAKE_CASE						:     Any					=		hf_hub_download(
						    repo_id='''nielsr/audio-spectogram-transformer-checkpoint'''    ,       filename='''sample_audio.flac'''    ,       repo_type='''dataset'''      )

						__SCREAMING_SNAKE_CASE						:     Any					=		torchaudio.load(__lowerCamelCase      )

						return audio, sampling_rate
@require_torch
@require_torchaudio
class        _lowercase      (			unittest.TestCase       ):






				'''simple docstring'''



				@cached_property
				def 		__magic_name__(       self			:str	)		->			Tuple:
										return (
										    ASTFeatureExtractor.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''	)
										    if is_torchaudio_available()
										    else None
										)



				@slow
				def 		__magic_name__(       self			:str	)		->			Dict:
										__SCREAMING_SNAKE_CASE						:     str					=		self.default_feature_extractor
										__SCREAMING_SNAKE_CASE						:     str					=		ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''	).to(lowercase_	)

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

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

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

										__SCREAMING_SNAKE_CASE						:     List[Any]					=		torch.tensor([-0.8760, -7.0042, -8.6602]	).to(lowercase_	)

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


"""simple docstring"""





import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
_a		       =							'src/diffusers'

# Matches is_xxx_available()
_a		       =							re.compile(R'is\_([a-z_]*)_available\(\)')
# Matches from xxx import bla
_a		       =							re.compile(R'\s+from\s+\S*\s+import\s+([^\(\s].*)\n')


_a		       =							'\n{0} = None\n'

_a		       =							'\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, {1})\n'


_a		       =							'\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n'







def 	__a     (		__lowerCamelCase  ):
   UpperCAmelCase_					:					int			     =    _re_backend.findall(__lowerCamelCase  )
   if len(__lowerCamelCase  ) == 0:
      return None

   return "_and_".join(__lowerCamelCase  )







def 	__a     (		):
   with open(os.path.join(__lowerCamelCase,		"__init__.py"  ),		"r",		encoding="utf-8",		newline="\n"  ) as f:
      UpperCAmelCase_					:					Optional[int]			     =    f.readlines()

   # Get to the point we do the actual imports for type checking
   UpperCAmelCase_					:					Union[str, Any]			     =    0
   UpperCAmelCase_					:					Optional[int]			     =    {}
   # Go through the end of the file
   while line_index < len(__lowerCamelCase  ):
      # If the line contains is_backend_available, we grab all objects associated with the `else` block
      UpperCAmelCase_					:					Union[str, Any]			     =    find_backend(lines[line_index]  )
      if backend is not None:
         while not lines[line_index].startswith("else:"  ):
            line_index += 1
         line_index += 1
         UpperCAmelCase_					:					List[str]			     =    []
         # Until we unindent, add backend objects to the list
         while line_index < len(__lowerCamelCase  ) and len(lines[line_index]  ) > 1:
            UpperCAmelCase_					:					Union[str, Any]			     =    lines[line_index]
            UpperCAmelCase_					:					Optional[Any]			     =    _re_single_line_import.search(__lowerCamelCase  )
            if single_line_import_search is not None:
               objects.extend(single_line_import_search.groups()[0].split(", "  )  )
            elif line.startswith(" " * 8  ):
               objects.append(line[8:-2]  )
            line_index += 1

         if len(__lowerCamelCase  ) > 0:
            UpperCAmelCase_					:					Optional[int]			     =    objects
      else:
         line_index += 1

   return backend_specific_objects







def 	__a     (		__lowerCamelCase,		__lowerCamelCase  ):
   if name.isupper():
      return DUMMY_CONSTANT.format(__lowerCamelCase  )
   elif name.islower():
      return DUMMY_FUNCTION.format(__lowerCamelCase,		__lowerCamelCase  )
   else:
      return DUMMY_CLASS.format(__lowerCamelCase,		__lowerCamelCase  )







def 	__a     (		__lowerCamelCase=None  ):
   if backend_specific_objects is None:
      UpperCAmelCase_					:					Tuple			     =    read_init()
   # For special correspondence backend to module name as used in the function requires_modulename
   UpperCAmelCase_					:					str			     =    {}

   for backend, objects in backend_specific_objects.items():
      UpperCAmelCase_					:					int			     =    "[" + ", ".join(f"""\"{b}\"""" for b in backend.split("_and_"  )  ) + "]"
      UpperCAmelCase_					:					Dict			     =    "# This file is autogenerated by the command `make fix-copies`, do not edit.\n"
      dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
      dummy_file += "\n".join([create_dummy_object(__lowerCamelCase,		__lowerCamelCase  ) for o in objects]  )
      UpperCAmelCase_					:					int			     =    dummy_file

   return dummy_files







def 	__a     (		__lowerCamelCase=False  ):
   UpperCAmelCase_					:					Optional[Any]			     =    create_dummy_files()
   # For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
   UpperCAmelCase_					:					Union[str, Any]			     =    {"torch": "pt"}

   # Locate actual dummy modules and read their content.
   UpperCAmelCase_					:					List[str]			     =    os.path.join(__lowerCamelCase,		"utils"  )
   UpperCAmelCase_					:					Optional[int]			     =    {
       backend: os.path.join(__lowerCamelCase,		f"""dummy_{short_names.get(__lowerCamelCase,		__lowerCamelCase  )}_objects.py"""  )
       for backend in dummy_files.keys()
   }

   UpperCAmelCase_					:					Any			     =    {}
   for backend, file_path in dummy_file_paths.items():
      if os.path.isfile(__lowerCamelCase  ):
         with open(__lowerCamelCase,		"r",		encoding="utf-8",		newline="\n"  ) as f:
            UpperCAmelCase_					:					Optional[int]			     =    f.read()
      else:
         UpperCAmelCase_					:					Any			     =    ""

   for backend in dummy_files.keys():
      if dummy_files[backend] != actual_dummies[backend]:
         if overwrite:
            print(
                f"""Updating diffusers.utils.dummy_{short_names.get(__lowerCamelCase,		__lowerCamelCase  )}_objects.py as the main """
                "__init__ has new objects."  )
            with open(dummy_file_paths[backend],		"w",		encoding="utf-8",		newline="\n"  ) as f:
               f.write(dummy_files[backend]  )
         else:
            raise ValueError(
                "The main __init__ has objects that are not present in "
                f"""diffusers.utils.dummy_{short_names.get(__lowerCamelCase,		__lowerCamelCase  )}_objects.py. Run `make fix-copies` """
                "to fix this."  )


if __name__ == "__main__":
    _a		       =							argparse.ArgumentParser()
    parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
    _a		       =							parser.parse_args()

    check_dummies(args.fix_and_overwrite)


