from typing import Dict

import numpy as np

from ..utils import add_end_docstrings, is_tf_available, is_torch_available, logging
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline, PipelineException


if is_tf_available():
      import tensorflow as tf

      from ..tf_utils import stable_softmax


if is_torch_available():
      import torch


A   :     Optional[int]       =				logging.get_logger(__name__)


@add_end_docstrings(
    SCREAMING_SNAKE_CASE__     ,					r'''
        top_k (`int`, defaults to 5):
            The number of predictions to return.
        targets (`str` or `List[str]`, *optional*):
            When passed, the model will limit the scores to the passed targets instead of looking up in the whole
            vocab. If the provided targets are not in the model vocab, they will be tokenized and the first resulting
            token will be used (with a warning, and that might be slower).

    '''     ,					)
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__    ):
  """simple docstring"""







  def       __A   (							self       :				Any     ,   __magic_name__       :				GenericTensor      )     ->		np.ndarray:
        if self.framework == "tf":
              SCREAMING_SNAKE_CASE_      =     tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()
        elif self.framework == "pt":
              SCREAMING_SNAKE_CASE_      =     torch.nonzero(input_ids == self.tokenizer.mask_token_id     ,   as_tuple=__magic_name__      )
        else:
              raise ValueError("Unsupported framework"      )
        return masked_index







  def       __A   (							self       :				Optional[int]     ,   __magic_name__       :				GenericTensor      )     ->		np.ndarray:
        SCREAMING_SNAKE_CASE_      =     self.get_masked_index(__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     np.prod(masked_index.shape      )
        if numel < 1:
              raise PipelineException(
                  "fill-mask"     ,   self.model.base_model_prefix     ,   F'''No mask_token ({self.tokenizer.mask_token}) found on the input'''     ,   )







  def       __A   (							self       :				str     ,   __magic_name__       :				GenericTensor      )     ->		Optional[int]:
        if isinstance(__magic_name__     ,   __magic_name__      ):
              for model_input in model_inputs:
                    self._ensure_exactly_one_mask_token(model_input["input_ids"][0]      )
        else:
              for input_ids in model_inputs["input_ids"]:
                    self._ensure_exactly_one_mask_token(__magic_name__      )







  def       __A   (							self       :				Optional[Any]     ,   __magic_name__       :				List[str]     ,   __magic_name__       :				Any=None     ,   **__magic_name__       :				List[Any]      )     ->		Dict[str, GenericTensor]:
        if return_tensors is None:
              SCREAMING_SNAKE_CASE_      =     self.framework
        SCREAMING_SNAKE_CASE_      =     self.tokenizer(__magic_name__     ,   return_tensors=__magic_name__      )
        self.ensure_exactly_one_mask_token(__magic_name__      )
        return model_inputs







  def       __A   (							self       :				Optional[Any]     ,   __magic_name__       :				Tuple      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     self.model(**__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     model_inputs["input_ids"]
        return model_outputs







  def       __A   (							self       :				Optional[int]     ,   __magic_name__       :				Optional[int]     ,   __magic_name__       :				Union[str, Any]=5     ,   __magic_name__       :				str=None      )     ->		Any:
        # Cap top_k if there are targets
        if target_ids is not None and target_ids.shape[0] < top_k:
              SCREAMING_SNAKE_CASE_      =     target_ids.shape[0]
        SCREAMING_SNAKE_CASE_      =     model_outputs["input_ids"][0]
        SCREAMING_SNAKE_CASE_      =     model_outputs["logits"]

        if self.framework == "tf":
              SCREAMING_SNAKE_CASE_      =     tf.where(input_ids == self.tokenizer.mask_token_id      ).numpy()[:, 0]

              SCREAMING_SNAKE_CASE_      =     outputs.numpy()

              SCREAMING_SNAKE_CASE_      =     outputs[0, masked_index, :]
              SCREAMING_SNAKE_CASE_      =     stable_softmax(__magic_name__     ,   axis=-1      )
              if target_ids is not None:
                    SCREAMING_SNAKE_CASE_      =     tf.gather_nd(tf.squeeze(__magic_name__     ,   0      )     ,   target_ids.reshape(-1     ,   1      )      )
                    SCREAMING_SNAKE_CASE_      =     tf.expand_dims(__magic_name__     ,   0      )

              SCREAMING_SNAKE_CASE_      =     tf.math.top_k(__magic_name__     ,   k=__magic_name__      )
              SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     topk.values.numpy(), topk.indices.numpy()
        else:
              SCREAMING_SNAKE_CASE_      =     torch.nonzero(input_ids == self.tokenizer.mask_token_id     ,   as_tuple=__magic_name__      ).squeeze(-1      )
              # Fill mask pipeline supports only one ${mask_token} per sample

              SCREAMING_SNAKE_CASE_      =     outputs[0, masked_index, :]
              SCREAMING_SNAKE_CASE_      =     logits.softmax(dim=-1      )
              if target_ids is not None:
                    SCREAMING_SNAKE_CASE_      =     probs[..., target_ids]

              SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     probs.topk(__magic_name__      )

        SCREAMING_SNAKE_CASE_      =     []
        SCREAMING_SNAKE_CASE_      =     values.shape[0] == 1
        for i, (_values, _predictions) in enumerate(zip(values.tolist()     ,   predictions.tolist()      )      ):
              SCREAMING_SNAKE_CASE_      =     []
              for v, p in zip(_values     ,   _predictions      ):
                    # Copy is important since we're going to modify this array in place
                    SCREAMING_SNAKE_CASE_      =     input_ids.numpy().copy()
                    if target_ids is not None:
                          SCREAMING_SNAKE_CASE_      =     target_ids[p].tolist()

                    SCREAMING_SNAKE_CASE_      =     p
                    # Filter padding out:
                    SCREAMING_SNAKE_CASE_      =     tokens[np.where(tokens != self.tokenizer.pad_token_id      )]
                    # Originally we skip special tokens to give readable output.
                    # For multi masks though, the other [MASK] would be removed otherwise
                    # making the output look odd, so we add them back
                    SCREAMING_SNAKE_CASE_      =     self.tokenizer.decode(__magic_name__     ,   skip_special_tokens=__magic_name__      )
                    SCREAMING_SNAKE_CASE_      =     {"score": v, "token": p, "token_str": self.tokenizer.decode([p]      ), "sequence": sequence}
                    row.append(__magic_name__      )
              result.append(__magic_name__      )
        if single_mask:
              return result[0]
        return result







  def       __A   (							self       :				List[Any]     ,   __magic_name__       :				str     ,   __magic_name__       :				List[str]=None      )     ->		Optional[Any]:
        if isinstance(__magic_name__     ,   __magic_name__      ):
              SCREAMING_SNAKE_CASE_      =     [targets]
        try:
              SCREAMING_SNAKE_CASE_      =     self.tokenizer.get_vocab()
        except Exception:
              SCREAMING_SNAKE_CASE_      =     {}
        SCREAMING_SNAKE_CASE_      =     []
        for target in targets:
              SCREAMING_SNAKE_CASE_      =     vocab.get(__magic_name__     ,   __magic_name__      )
              if id_ is None:
                    SCREAMING_SNAKE_CASE_      =     self.tokenizer(
                        __magic_name__     ,   add_special_tokens=__magic_name__     ,   return_attention_mask=__magic_name__     ,   return_token_type_ids=__magic_name__     ,   max_length=1     ,   truncation=__magic_name__     ,   )["input_ids"]
                    if len(__magic_name__      ) == 0:
                          logger.warning(
                              F'''The specified target token `{target}` does not exist in the model vocabulary. '''
                              "We cannot replace it with anything meaningful, ignoring it"      )
                          continue
                    SCREAMING_SNAKE_CASE_      =     input_ids[0]
                    # XXX: If users encounter this pass
                    # it becomes pretty slow, so let's make sure
                    # The warning enables them to fix the input to
                    # get faster performance.
                    logger.warning(
                        F'''The specified target token `{target}` does not exist in the model vocabulary. '''
                        F'''Replacing with `{self.tokenizer.convert_ids_to_tokens(id_      )}`.'''      )
              target_ids.append(id_      )
        SCREAMING_SNAKE_CASE_      =     list(set(__magic_name__      )      )
        if len(__magic_name__      ) == 0:
              raise ValueError("At least one target must be provided when passed."      )
        SCREAMING_SNAKE_CASE_      =     np.array(__magic_name__      )
        return target_ids







  def       __A   (							self       :				Any     ,   __magic_name__       :				Any=None     ,   __magic_name__       :				Any=None      )     ->		Optional[Any]:
        SCREAMING_SNAKE_CASE_      =     {}

        if targets is not None:
              SCREAMING_SNAKE_CASE_      =     self.get_target_ids(__magic_name__     ,   __magic_name__      )
              SCREAMING_SNAKE_CASE_      =     target_ids

        if top_k is not None:
              SCREAMING_SNAKE_CASE_      =     top_k

        if self.tokenizer.mask_token_id is None:
              raise PipelineException(
                  "fill-mask"     ,   self.model.base_model_prefix     ,   "The tokenizer does not define a `mask_token`."      )
        return {}, {}, postprocess_params







  def __call__(							self       :				str     ,   __magic_name__       :				int     ,   *__magic_name__       :				Dict     ,   **__magic_name__       :				Union[str, Any]      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     super().__call__(__magic_name__     ,   **__magic_name__      )
        if isinstance(__magic_name__     ,   __magic_name__      ) and len(__magic_name__      ) == 1:
              return outputs[0]
        return outputs



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      lowerCamelCase    :
  """simple docstring"""







  def __init__(							self       :				List[Any]     ,   __magic_name__       :				Any     ,   __magic_name__       :				List[Any]=13     ,   __magic_name__       :				List[Any]=2     ,   __magic_name__       :				Tuple=24     ,   __magic_name__       :				List[str]=16     ,   __magic_name__       :				Dict=True     ,   __magic_name__       :				List[Any]=True     ,   __magic_name__       :				Optional[int]=32     ,   __magic_name__       :				Tuple=5     ,   __magic_name__       :				int=4     ,   __magic_name__       :				Tuple=37     ,   __magic_name__       :				List[str]="gelu"     ,   __magic_name__       :				Tuple=0.1     ,   __magic_name__       :				Tuple=0.1     ,   __magic_name__       :				Union[str, Any]=10     ,   __magic_name__       :				Tuple=0.02     ,   __magic_name__       :				Tuple=None     ,   __magic_name__       :				Any=2     ,   __magic_name__       :				Dict=2     ,   )     ->		int:
        SCREAMING_SNAKE_CASE_      =     parent
        SCREAMING_SNAKE_CASE_      =     batch_size
        SCREAMING_SNAKE_CASE_      =     patch_size
        SCREAMING_SNAKE_CASE_      =     max_length
        SCREAMING_SNAKE_CASE_      =     num_mel_bins
        SCREAMING_SNAKE_CASE_      =     is_training
        SCREAMING_SNAKE_CASE_      =     use_labels
        SCREAMING_SNAKE_CASE_      =     hidden_size
        SCREAMING_SNAKE_CASE_      =     num_hidden_layers
        SCREAMING_SNAKE_CASE_      =     num_attention_heads
        SCREAMING_SNAKE_CASE_      =     intermediate_size
        SCREAMING_SNAKE_CASE_      =     hidden_act
        SCREAMING_SNAKE_CASE_      =     hidden_dropout_prob
        SCREAMING_SNAKE_CASE_      =     attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE_      =     type_sequence_label_size
        SCREAMING_SNAKE_CASE_      =     initializer_range
        SCREAMING_SNAKE_CASE_      =     scope
        SCREAMING_SNAKE_CASE_      =     frequency_stride
        SCREAMING_SNAKE_CASE_      =     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_      =     (self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
        SCREAMING_SNAKE_CASE_      =     (self.max_length - self.patch_size) // self.time_stride + 1
        SCREAMING_SNAKE_CASE_      =     frequency_out_dimension * time_out_dimension
        SCREAMING_SNAKE_CASE_      =     num_patches + 2







  def       __A   (							self       :				Any      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]      )

        SCREAMING_SNAKE_CASE_      =     None
        if self.use_labels:
              SCREAMING_SNAKE_CASE_      =     ids_tensor([self.batch_size]     ,   self.type_sequence_label_size      )

        SCREAMING_SNAKE_CASE_      =     self.get_config()

        return config, input_values, labels







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







  def       __A   (							self       :				List[Any]     ,   __magic_name__       :				List[str]     ,   __magic_name__       :				str     ,   __magic_name__       :				List[str]      )     ->		Union[str, Any]:
        SCREAMING_SNAKE_CASE_      =     ASTModel(config=__magic_name__      )
        model.to(__magic_name__      )
        model.eval()
        SCREAMING_SNAKE_CASE_      =     model(__magic_name__      )
        self.parent.assertEqual(result.last_hidden_state.shape     ,   (self.batch_size, self.seq_length, self.hidden_size)      )







  def       __A   (							self       :				Tuple      )     ->		str:
        SCREAMING_SNAKE_CASE_      =     self.prepare_config_and_inputs()
        (
            (
            SCREAMING_SNAKE_CASE_
        )   ,       (
            SCREAMING_SNAKE_CASE_
        )   ,       (
            SCREAMING_SNAKE_CASE_
        )   ,       
        )      =     config_and_inputs
        SCREAMING_SNAKE_CASE_      =     {"input_values": input_values}
        return config, inputs_dict



@require_torch
class      lowerCamelCase    (SCREAMING_SNAKE_CASE__     ,					SCREAMING_SNAKE_CASE__     ,					unittest.TestCase    ):
  """simple docstring"""







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







  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Union[str, Any]     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				Dict     ,   __magic_name__       :				Optional[int]     ,   __magic_name__       :				Tuple      )     ->		Tuple:
        if pipeline_test_casse_name == "AudioClassificationPipelineTests":
              return True

        return False







  def       __A   (							self       :				Optional[Any]      )     ->		Optional[Any]:
        SCREAMING_SNAKE_CASE_      =     ASTModelTester(self      )
        SCREAMING_SNAKE_CASE_      =     ConfigTester(self     ,   config_class=__magic_name__     ,   has_text_modality=__magic_name__     ,   hidden_size=37      )







  def       __A   (							self       :				Union[str, Any]      )     ->		Dict:
        self.config_tester.run_common_tests()







  @unittest.skip(reason="AST does not use inputs_embeds"      )
  def       __A   (							self       :				Optional[Any]      )     ->		Tuple:
        pass







  def       __A   (							self       :				int      )     ->		int:
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs_for_common()

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







  def       __A   (							self       :				List[Any]      )     ->		str:
        SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_      =     ["input_values"]
              self.assertListEqual(arg_names[:1]     ,   __magic_name__      )







  def       __A   (							self       :				int      )     ->		Any:
        SCREAMING_SNAKE_CASE_      =     self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*__magic_name__      )







  @slow
  def       __A   (							self       :				int      )     ->		int:
        for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE_      =     ASTModel.from_pretrained(__magic_name__      )
              self.assertIsNotNone(__magic_name__      )



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

      SCREAMING_SNAKE_CASE_   ,       SCREAMING_SNAKE_CASE_      =     torchaudio.load(__UpperCamelCase )

      return audio, sampling_rate





@require_torch
@require_torchaudio
class      lowerCamelCase    (unittest.TestCase    ):
  """simple docstring"""







  @cached_property
  def       __A   (							self       :				List[Any]      )     ->		List[Any]:
        return (
            ASTFeatureExtractor.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      )
            if is_torchaudio_available()
            else None
        )







  @slow
  def       __A   (							self       :				Union[str, Any]      )     ->		Optional[int]:
        SCREAMING_SNAKE_CASE_      =     self.default_feature_extractor
        SCREAMING_SNAKE_CASE_      =     ASTForAudioClassification.from_pretrained("MIT/ast-finetuned-audioset-10-10-0.4593"      ).to(__magic_name__      )

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

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

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

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

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


