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     _A   :






  def __init__(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_=13   ,				SCREAMING_SNAKE_CASE_=2   ,				SCREAMING_SNAKE_CASE_=24   ,				SCREAMING_SNAKE_CASE_=16   ,				SCREAMING_SNAKE_CASE_=True   ,				SCREAMING_SNAKE_CASE_=True   ,				SCREAMING_SNAKE_CASE_=32   ,				SCREAMING_SNAKE_CASE_=5   ,				SCREAMING_SNAKE_CASE_=4   ,				SCREAMING_SNAKE_CASE_=37   ,				SCREAMING_SNAKE_CASE_="gelu"   ,				SCREAMING_SNAKE_CASE_=0.1   ,				SCREAMING_SNAKE_CASE_=0.1   ,				SCREAMING_SNAKE_CASE_=10   ,				SCREAMING_SNAKE_CASE_=0.02   ,				SCREAMING_SNAKE_CASE_=None   ,				SCREAMING_SNAKE_CASE_=2   ,				SCREAMING_SNAKE_CASE_=2   ,				)		->      List[Any]:





       '''simple docstring'''





       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 		_a					(self	)		->      Any:





       '''simple docstring'''





       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 		_a					(self	)		->      str:





       '''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=SCREAMING_SNAKE_CASE_   ,				initializer_range=self.initializer_range   ,				frequency_stride=self.frequency_stride   ,				time_stride=self.time_stride   ,				)






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      Optional[int]:





       '''simple docstring'''





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






  def 		_a					(self	)		->      int:





       '''simple docstring'''





       UpperCamelCase__										=      self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase__
       )						,       (
           UpperCamelCase__
       )						,       (
           UpperCamelCase__
       )						,       
       )										=      config_and_inputs
       UpperCamelCase__										=      {'''input_values''': input_values}
       return config, inputs_dict



@require_torch
class     _A   (    __UpperCamelCase	, __UpperCamelCase	, unittest.TestCase							):
  SCREAMING_SNAKE_CASE_	:	List[Any]						=(
      (
          ASTModel,
          ASTForAudioClassification,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE_	:	List[str]						=(
      {"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_	:	Dict						=False
  SCREAMING_SNAKE_CASE_	:	Any						=False






  def 		_a					(self   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_   ,				SCREAMING_SNAKE_CASE_	)		->      Union[str, Any]:





       '''simple docstring'''





       if pipeline_test_casse_name == "AudioClassificationPipelineTests":
            return True

       return False






  def 		_a					(self	)		->      Dict:





       '''simple docstring'''





       UpperCamelCase__										=      ASTModelTester(self	)
       UpperCamelCase__										=      ConfigTester(self   ,				config_class=SCREAMING_SNAKE_CASE_   ,				has_text_modality=SCREAMING_SNAKE_CASE_   ,				hidden_size=37	)






  def 		_a					(self	)		->      str:





       '''simple docstring'''





       self.config_tester.run_common_tests()






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





       '''simple docstring'''





       pass






  def 		_a					(self	)		->      Optional[int]:





       '''simple docstring'''





       UpperCamelCase__						,       UpperCamelCase__										=      self.model_tester.prepare_config_and_inputs_for_common()

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






  def 		_a					(self	)		->      Union[str, Any]:





       '''simple docstring'''





       UpperCamelCase__						,       UpperCamelCase__										=      self.model_tester.prepare_config_and_inputs_for_common()

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






  def 		_a					(self	)		->      List[str]:





       '''simple docstring'''





       UpperCamelCase__										=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_	)






  @slow
  def 		_a					(self	)		->      int:





       '''simple docstring'''





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







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

     UpperCamelCase__						,       UpperCamelCase__										=      torchaudio.load(A							)

     return audio, sampling_rate



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






  @cached_property
  def 		_a					(self	)		->      int:





       '''simple docstring'''





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






  @slow
  def 		_a					(self	)		->      List[str]:





       '''simple docstring'''





       UpperCamelCase__										=      self.default_feature_extractor
       UpperCamelCase__										=      ASTForAudioClassification.from_pretrained('''MIT/ast-finetuned-audioset-10-10-0.4593'''	).to(SCREAMING_SNAKE_CASE_	)

       UpperCamelCase__										=      self.default_feature_extractor
       UpperCamelCase__						,       UpperCamelCase__										=      prepare_audio()
       UpperCamelCase__										=      audio.squeeze().numpy()
       UpperCamelCase__										=      feature_extractor(SCREAMING_SNAKE_CASE_   ,				sampling_rate=SCREAMING_SNAKE_CASE_   ,				return_tensors='''pt'''	).to(SCREAMING_SNAKE_CASE_	)

       # forward pass
       with torch.no_grad():
            UpperCamelCase__										=      model(**SCREAMING_SNAKE_CASE_	)

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

       UpperCamelCase__										=      torch.tensor([-0.8760, -7.0042, -8.6602]	).to(SCREAMING_SNAKE_CASE_	)

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




# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position

__magic_name__								='''2.13.1'''

import platform

import pyarrow
from packaging import version


if version.parse(platform.python_version()) < version.parse('''3.7'''):
     raise ImportWarning(
         '''To use `datasets`, Python>=3.7 is required, and the current version of Python doesn\'t match this condition.'''
     )

if version.parse(pyarrow.__version__).major < 8:
     raise ImportWarning(
         '''To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn\'t match this condition.\n'''
         '''If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`.'''
     )

del platform
del pyarrow
del version

from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
    get_dataset_config_info,
    get_dataset_config_names,
    get_dataset_infos,
    get_dataset_split_names,
    inspect_dataset,
    inspect_metric,
    list_datasets,
    list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
    NamedSplit,
    NamedSplitAll,
    Split,
    SplitBase,
    SplitDict,
    SplitGenerator,
    SplitInfo,
    SubSplitInfo,
    percent,
)
from .tasks import *
from .utils import *
from .utils import logging


# deprecated modules
from datasets import arrow_dataset as _arrow_dataset  # isort:skip
from datasets import utils as _utils  # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager  # isort:skip

__magic_name__								=concatenate_datasets
__magic_name__								=DownloadConfig
__magic_name__								=DownloadManager
__magic_name__								=DownloadMode
__magic_name__								=DownloadConfig
__magic_name__								=DownloadMode
__magic_name__								=DownloadManager

del _arrow_dataset, _utils, _deprecated_download_manager



