



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		,       lowerCamelCase_		,       lowerCamelCase_=13		,       lowerCamelCase_=2		,       lowerCamelCase_=24		,       lowerCamelCase_=16		,       lowerCamelCase_=True		,       lowerCamelCase_=True		,       lowerCamelCase_=32		,       lowerCamelCase_=5		,       lowerCamelCase_=4		,       lowerCamelCase_=37		,       lowerCamelCase_="gelu"		,       lowerCamelCase_=0.1		,       lowerCamelCase_=0.1		,       lowerCamelCase_=10		,       lowerCamelCase_=0.02		,       lowerCamelCase_=None		,       lowerCamelCase_=2		,       lowerCamelCase_=2		,       ):
						"""simple docstring"""

						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      UpperCamelCase_       (self		):
						"""simple docstring"""

						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      UpperCamelCase_       (self		):
						"""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      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		):
						"""simple docstring"""

						a					     =   ASTModel(config=lowerCamelCase_		)
						model.to(lowerCamelCase_		)
						model.eval()
						a					     =   model(lowerCamelCase_		)
						self.parent.assertEqual(result.last_hidden_state.shape		,       (self.batch_size, self.seq_length, self.hidden_size)		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.prepare_config_and_inputs()
						(
						    (
						    a
						)     ,				(
						    a
						)     ,				(
						    a
						)     ,				
						)					     =   config_and_inputs
						a					     =   {"input_values": input_values}
						return config, inputs_dict




@require_torch
class 	_lowercase							(   lowerCAmelCase,      lowerCAmelCase,      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      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		,       lowerCamelCase_		):
						"""simple docstring"""

						if pipeline_test_casse_name == "AudioClassificationPipelineTests":
											return True

						return False




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   ASTModelTester(self		)
						a					     =   ConfigTester(self		,       config_class=lowerCamelCase_		,       has_text_modality=lowerCamelCase_		,       hidden_size=37		)




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						self.config_tester.run_common_tests()




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

						pass




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a     ,				a					     =   self.model_tester.prepare_config_and_inputs_for_common()

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




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a     ,				a					     =   self.model_tester.prepare_config_and_inputs_for_common()

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




	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*lowerCamelCase_		)




	@slow
	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											a					     =   ASTModel.from_pretrained(lowerCamelCase_		)
											self.assertIsNotNone(lowerCamelCase_		)






def     a(      )		->       Optional[int]:
					"""simple docstring"""





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

					a     ,				a					     =   torchaudio.load(A       )

					return audio, sampling_rate







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





	"""simple docstring"""




	@cached_property
	def      UpperCamelCase_       (self		):
						"""simple docstring"""

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




	@slow
	def      UpperCamelCase_       (self		):
						"""simple docstring"""

						a					     =   self.default_feature_extractor
						a					     =   ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"		).to(lowerCamelCase_		)

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

						# forward pass
						with torch.no_grad():
											a					     =   model(**lowerCamelCase_		)

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

						a					     =   torch.tensor([-0.8760, -7.0042, -8.6602]		).to(lowerCamelCase_		)

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





from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
				from PIL import Image

				from ..image_utils import load_image

if is_tf_available():
				from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_VISION_2_SEQ_MAPPING

if is_torch_available():
				import torch

				from ..models.auto.modeling_auto import MODEL_FOR_VISION_2_SEQ_MAPPING

_lowercase: Union[str, Any]      			=		logging.get_logger(__name__)



@add_end_docstrings(lowerCAmelCase	)
class 	_lowercase							(   lowerCAmelCase	):





	"""simple docstring"""




	def __init__(self		,       *lowerCamelCase_		,       **lowerCamelCase_		):
						"""simple docstring"""

						super().__init__(*lowerCamelCase_		,       **lowerCamelCase_		)
						requires_backends(self		,       "vision"		)
						self.check_model_type(
						    TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == "tf" else MODEL_FOR_VISION_2_SEQ_MAPPING		)




	def      UpperCamelCase_       (self		,       lowerCamelCase_=None		,       lowerCamelCase_=None		,       lowerCamelCase_=None		):
						"""simple docstring"""

						a					     =   {}
						a					     =   {}

						if prompt is not None:
											a					     =   prompt

						if generate_kwargs is not None:
											a					     =   generate_kwargs
						if max_new_tokens is not None:
											if "generate_kwargs" not in forward_kwargs:
																a					     =   {}
											if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
																raise ValueError(
																    "'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"
																    " please use only one"		)
											a					     =   max_new_tokens
						return preprocess_params, forward_kwargs, {}




	def __call__(self		,       lowerCamelCase_		,       **lowerCamelCase_		):
						"""simple docstring"""

						return super().__call__(lowerCamelCase_		,       **lowerCamelCase_		)




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_=None		):
						"""simple docstring"""

						a					     =   load_image(lowerCamelCase_		)

						if prompt is not None:
											if not isinstance(lowerCamelCase_		,       lowerCamelCase_		):
																raise ValueError(
																    F'''Received an invalid text input, got - {type(lowerCamelCase_		)} - but expected a single string. '''
																    "Note also that one single text can be provided for conditional image to text generation."		)

											a					     =   self.model.config.model_type

											if model_type == "git":
																a					     =   self.image_processor(images=lowerCamelCase_		,       return_tensors=self.framework		)
																a					     =   self.tokenizer(text=lowerCamelCase_		,       add_special_tokens=lowerCamelCase_		).input_ids
																a					     =   [self.tokenizer.cls_token_id] + input_ids
																a					     =   torch.tensor(lowerCamelCase_		).unsqueeze(0		)
																model_inputs.update({"input_ids": input_ids}		)

											elif model_type == "pix2struct":
																a					     =   self.image_processor(images=lowerCamelCase_		,       header_text=lowerCamelCase_		,       return_tensors=self.framework		)

											elif model_type != "vision-encoder-decoder":
																# vision-encoder-decoder does not support conditional generation
																a					     =   self.image_processor(images=lowerCamelCase_		,       return_tensors=self.framework		)
																a					     =   self.tokenizer(lowerCamelCase_		,       return_tensors=self.framework		)
																model_inputs.update(lowerCamelCase_		)

											else:
																raise ValueError(F'''Model type {model_type} does not support conditional text generation'''		)

						else:
											a					     =   self.image_processor(images=lowerCamelCase_		,       return_tensors=self.framework		)

						if self.model.config.model_type == "git" and prompt is None:
											a					     =   None

						return model_inputs




	def      UpperCamelCase_       (self		,       lowerCamelCase_		,       lowerCamelCase_=None		):
						"""simple docstring"""

						if (
						    "input_ids" in model_inputs
						    and isinstance(model_inputs["input_ids"]		,       lowerCamelCase_		)
						    and all(x is None for x in model_inputs["input_ids"]		)
						):
											a					     =   None

						if generate_kwargs is None:
											a					     =   {}
						# FIXME: We need to pop here due to a difference in how `generation.py` and `generation.tf_utils.py`
						#  parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
						#  the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
						#  in the `_prepare_model_inputs` method.
						a					     =   model_inputs.pop(self.model.main_input_name		)
						a					     =   self.model.generate(lowerCamelCase_		,       **lowerCamelCase_		,       **lowerCamelCase_		)
						return model_outputs




	def      UpperCamelCase_       (self		,       lowerCamelCase_		):
						"""simple docstring"""

						a					     =   []
						for output_ids in model_outputs:
											a					     =   {
											    "generated_text": self.tokenizer.decode(
											        lowerCamelCase_		,       skip_special_tokens=lowerCamelCase_		,       )
											}
											records.append(lowerCamelCase_		)
						return records
