


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


    def __init__(  self      :							Tuple				,							SCREAMING_SNAKE_CASE      :							Tuple				,							SCREAMING_SNAKE_CASE      :							Any=13				,							SCREAMING_SNAKE_CASE      :							Optional[int]=2				,							SCREAMING_SNAKE_CASE      :							List[str]=24				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=16				,							SCREAMING_SNAKE_CASE      :							Tuple=True				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=True				,							SCREAMING_SNAKE_CASE      :							Dict=32				,							SCREAMING_SNAKE_CASE      :							List[Any]=5				,							SCREAMING_SNAKE_CASE      :							List[str]=4				,							SCREAMING_SNAKE_CASE      :							Optional[int]=37				,							SCREAMING_SNAKE_CASE      :							Any="gelu"				,							SCREAMING_SNAKE_CASE      :							Optional[int]=0.1				,							SCREAMING_SNAKE_CASE      :							Optional[int]=0.1				,							SCREAMING_SNAKE_CASE      :							Optional[Any]=10				,							SCREAMING_SNAKE_CASE      :							Any=0.02				,							SCREAMING_SNAKE_CASE      :							int=None				,							SCREAMING_SNAKE_CASE      :							List[str]=2				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=2				,							):
           _A					:     Any     = parent
           _A					:     str     = batch_size
           _A					:     List[str]     = patch_size
           _A					:     Union[str, Any]     = max_length
           _A					:     Union[str, Any]     = num_mel_bins
           _A					:     Optional[Any]     = is_training
           _A					:     Any     = use_labels
           _A					:     Optional[Any]     = hidden_size
           _A					:     List[str]     = num_hidden_layers
           _A					:     List[str]     = num_attention_heads
           _A					:     Union[str, Any]     = intermediate_size
           _A					:     str     = hidden_act
           _A					:     Union[str, Any]     = hidden_dropout_prob
           _A					:     str     = attention_probs_dropout_prob
           _A					:     Optional[Any]     = type_sequence_label_size
           _A					:     List[Any]     = initializer_range
           _A					:     int     = scope
           _A					:     Union[str, Any]     = frequency_stride
           _A					:     Union[str, Any]     = time_stride

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


    def        A   (  self      :							str):
           _A					:     str     = floats_tensor([self.batch_size, self.max_length, self.num_mel_bins])

           _A					:     int     = None
           if self.use_labels:
                  _A					:     Tuple     = ids_tensor([self.batch_size]				,							self.type_sequence_label_size)

           _A					:     str     = self.get_config()

           return config, input_values, labels


    def        A   (  self      :							Tuple):
           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      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Dict				,							SCREAMING_SNAKE_CASE      :							Optional[Any]):
           _A					:     int     = ASTModel(config=SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           _A					:     Dict     = model(SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(result.last_hidden_state.shape				,							(self.batch_size, self.seq_length, self.hidden_size))


    def        A   (  self      :							Tuple):
           _A					:     Any     = self.prepare_config_and_inputs()
           (
               (
               _A
           )  ,			(
               _A
           )  ,			(
               _A
           )  ,			
           )					:     Optional[Any]     = config_and_inputs
           _A					:     Dict     = {'input_values': input_values}
           return config, inputs_dict




@require_torch
class 			__lowerCamelCase			(	a_    , a_    , 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        A   (  self      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							int				,							SCREAMING_SNAKE_CASE      :							Any				,							SCREAMING_SNAKE_CASE      :							Dict):
           if pipeline_test_casse_name == "AudioClassificationPipelineTests":
                  return True

           return False


    def        A   (  self      :							Tuple):
           _A					:     Optional[Any]     = ASTModelTester(self)
           _A					:     List[str]     = ConfigTester(self				,							config_class=SCREAMING_SNAKE_CASE				,							has_text_modality=SCREAMING_SNAKE_CASE				,							hidden_size=37)


    def        A   (  self      :							List[str]):
           self.config_tester.run_common_tests()


    @unittest.skip(reason='AST does not use inputs_embeds')
    def        A   (  self      :							List[str]):
           pass


    def        A   (  self      :							Optional[Any]):
           _A  ,			_A					:     List[Any]     = self.model_tester.prepare_config_and_inputs_for_common()

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


    def        A   (  self      :							Optional[Any]):
           _A  ,			_A					:     Tuple     = self.model_tester.prepare_config_and_inputs_for_common()

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

                  _A					:     Any     = ['input_values']
                  self.assertListEqual(arg_names[:1]				,							SCREAMING_SNAKE_CASE)


    def        A   (  self      :							str):
           _A					:     Union[str, Any]     = self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE)


    @slow
    def        A   (  self      :							Tuple):
           for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _A					:     Dict     = ASTModel.from_pretrained(SCREAMING_SNAKE_CASE)
                  self.assertIsNotNone(SCREAMING_SNAKE_CASE)






def 				lowerCAmelCase__	(    ):
       _A					:     List[str]     = hf_hub_download(
           repo_id='nielsr/audio-spectogram-transformer-checkpoint'  ,filename='sample_audio.flac'  ,repo_type='dataset'       )

       _A  ,			_A					:     Dict     = torchaudio.load(lowerCamelCase       )

       return audio, sampling_rate


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


    @cached_property
    def        A   (  self      :							Optional[Any]):
           return (
               ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593')
               if is_torchaudio_available()
               else None
           )


    @slow
    def        A   (  self      :							Tuple):
           _A					:     Optional[Any]     = self.default_feature_extractor
           _A					:     Tuple     = ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593').to(SCREAMING_SNAKE_CASE)

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

           # forward pass
           with torch.no_grad():
                  _A					:     Tuple     = model(**SCREAMING_SNAKE_CASE)

           # verify the logits
           _A					:     Optional[Any]     = torch.Size((1, 527))
           self.assertEqual(outputs.logits.shape				,							SCREAMING_SNAKE_CASE)

           _A					:     Union[str, Any]     = 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))










'''simple docstring'''







import uuid
from typing import Any, Dict, List, Optional, Union

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


if is_tf_available():
   import tensorflow as tf

if is_torch_available():
   import torch


A				:					Any    						=			logging.get_logger(__name__)


class 			__lowerCamelCase			:
    """simple docstring"""


    def __init__(  self      :							Dict				,							SCREAMING_SNAKE_CASE      :							str = None				,							SCREAMING_SNAKE_CASE      :							uuid.UUID = None				,							SCREAMING_SNAKE_CASE      :							List[Any]=None				,							SCREAMING_SNAKE_CASE      :							Optional[int]=None):
           if not conversation_id:
                  _A					:     str     = uuid.uuida()
           if past_user_inputs is None:
                  _A					:     List[Any]     = []
           if generated_responses is None:
                  _A					:     Union[str, Any]     = []

           _A					:     uuid.UUID     = conversation_id
           _A					:     List[str]     = past_user_inputs
           _A					:     List[str]     = generated_responses
           _A					:     Optional[str]     = text


    def __eq__(  self      :							List[str]				,							SCREAMING_SNAKE_CASE      :							Optional[int]):
           if not isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                  return False
           if self.uuid == other.uuid:
                  return True
           return (
               self.new_user_input == other.new_user_input
               and self.past_user_inputs == other.past_user_inputs
               and self.generated_responses == other.generated_responses
           )


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							bool = False):
           if self.new_user_input:
                  if overwrite:
                         logger.warning(
                             F'User input added while unprocessed input was existing: "{self.new_user_input}" was overwritten '
                             F'with: "{text}".')
                         _A					:     Optional[Any]     = text
                  else:
                         logger.warning(
                             F'User input added while unprocessed input was existing: "{self.new_user_input}" new input '
                             F'ignored: "{text}". Set `overwrite` to True to overwrite unprocessed user input')
           else:
                  _A					:     Optional[Any]     = text


    def        A   (  self      :							Optional[int]):
           if self.new_user_input:
                  self.past_user_inputs.append(self.new_user_input)
           _A					:     Optional[Any]     = None


    def        A   (  self      :							List[Any]				,							SCREAMING_SNAKE_CASE      :							str):
           self.generated_responses.append(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							str):
           for user_input, generated_response in zip(self.past_user_inputs				,							self.generated_responses):
                  yield True, user_input
                  yield False, generated_response
           if self.new_user_input:
                  yield True, self.new_user_input


    def __repr__(  self      :							Dict):
           _A					:     Any     = F'Conversation id: {self.uuid} \n'
           for is_user, text in self.iter_texts():
                  _A					:     Optional[int]     = 'user' if is_user else 'bot'
                  output += F'{name} >> {text} \n'
           return output




@add_end_docstrings(
    a_    , R"\n        min_length_for_response (`int`, *optional*, defaults to 32):\n            The minimum length (in number of tokens) for a response.\n        minimum_tokens (`int`, *optional*, defaults to 10):\n            The minimum length of tokens to leave for a response.\n    "    , )
class 			__lowerCamelCase			(	a_	):
    """simple docstring"""


    def __init__(  self      :							Optional[int]				,							*SCREAMING_SNAKE_CASE      :							Any				,							**SCREAMING_SNAKE_CASE      :							str):
           super().__init__(*SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if self.tokenizer.pad_token_id is None:
                  _A					:     Any     = self.tokenizer.eos_token


    def        A   (  self      :							Optional[Any]				,							SCREAMING_SNAKE_CASE      :							List[Any]=None				,							SCREAMING_SNAKE_CASE      :							Optional[int]=None				,							SCREAMING_SNAKE_CASE      :							Optional[Any]=None				,							**SCREAMING_SNAKE_CASE      :							str):
           _A					:     str     = {}
           _A					:     Union[str, Any]     = {}
           _A					:     List[str]     = {}

           if min_length_for_response is not None:
                  _A					:     Optional[Any]     = min_length_for_response
           if minimum_tokens is not None:
                  _A					:     Tuple     = minimum_tokens

           if "max_length" in generate_kwargs:
                  _A					:     List[Any]     = generate_kwargs['max_length']
                  # self.max_length = generate_kwargs.get("max_length", self.model.config.max_length)
           if clean_up_tokenization_spaces is not None:
                  _A					:     List[str]     = clean_up_tokenization_spaces

           if generate_kwargs:
                  forward_params.update(SCREAMING_SNAKE_CASE)
           return preprocess_params, forward_params, postprocess_params


    def __call__(  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Union[Conversation, List[Conversation]]				,							SCREAMING_SNAKE_CASE      :							Any=0				,							**SCREAMING_SNAKE_CASE      :							Tuple):
           _A					:     Any     = super().__call__(SCREAMING_SNAKE_CASE				,							num_workers=SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE) and len(SCREAMING_SNAKE_CASE) == 1:
                  return outputs[0]
           return outputs


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							Conversation				,							SCREAMING_SNAKE_CASE      :							Union[str, Any]=32):
           if not isinstance(SCREAMING_SNAKE_CASE				,							SCREAMING_SNAKE_CASE):
                  raise ValueError('ConversationalPipeline, expects Conversation as inputs')
           if conversation.new_user_input is None:
                  raise ValueError(
                      F'Conversation with UUID {type(conversation.uuid)} does not contain new user input to process. '
                      'Add user inputs with the conversation\'s `add_user_input` method')
           if hasattr(self.tokenizer				,							'_build_conversation_input_ids'):
                  _A					:     Optional[Any]     = self.tokenizer._build_conversation_input_ids(SCREAMING_SNAKE_CASE)
           else:
                  # If the tokenizer cannot handle conversations, we default to only the old version
                  _A					:     Dict     = self._legacy_parse_and_tokenize(SCREAMING_SNAKE_CASE)

           if self.framework == "pt":
                  _A					:     Union[str, Any]     = torch.LongTensor([input_ids])
           elif self.framework == "tf":
                  _A					:     Optional[Any]     = tf.constant([input_ids])
           return {"input_ids": input_ids, "conversation": conversation}


    def        A   (  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							Dict				,							SCREAMING_SNAKE_CASE      :							List[str]=10				,							**SCREAMING_SNAKE_CASE      :							Tuple):
           _A					:     str     = generate_kwargs.get('max_length'				,							self.model.config.max_length)

           _A					:     Any     = model_inputs['input_ids'].shape[1]
           if max_length - minimum_tokens < n:
                  logger.warning(F'Conversation input is to long ({n}), trimming it to ({max_length} - {minimum_tokens})')
                  _A					:     Dict     = max_length - minimum_tokens
                  _A					:     int     = model_inputs['input_ids'][:, -trim:]
                  if "attention_mask" in model_inputs:
                         _A					:     str     = model_inputs['attention_mask'][:, -trim:]
           _A					:     Any     = model_inputs.pop('conversation')
           _A					:     Optional[Any]     = max_length
           _A					:     int     = self.model.generate(**SCREAMING_SNAKE_CASE				,							**SCREAMING_SNAKE_CASE)
           if self.model.config.is_encoder_decoder:
                  _A					:     int     = 1
           else:
                  _A					:     List[Any]     = n
           return {"output_ids": output_ids[:, start_position:], "conversation": conversation}


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							str				,							SCREAMING_SNAKE_CASE      :							List[Any]=True):
           _A					:     Optional[Any]     = model_outputs['output_ids']
           _A					:     Optional[int]     = self.tokenizer.decode(
               output_ids[0]				,							skip_special_tokens=SCREAMING_SNAKE_CASE				,							clean_up_tokenization_spaces=SCREAMING_SNAKE_CASE				,							)
           _A					:     Any     = model_outputs['conversation']
           conversation.mark_processed()
           conversation.append_response(SCREAMING_SNAKE_CASE)
           return conversation


    def        A   (  self      :							str				,							SCREAMING_SNAKE_CASE      :							Conversation):
           _A					:     Optional[Any]     = self.tokenizer.eos_token_id
           _A					:     List[Any]     = []
           for is_user, text in conversation.iter_texts():
                  if eos_token_id is not None:
                         input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE				,							add_special_tokens=SCREAMING_SNAKE_CASE) + [eos_token_id])
                  else:
                         input_ids.extend(self.tokenizer.encode(SCREAMING_SNAKE_CASE				,							add_special_tokens=SCREAMING_SNAKE_CASE))

           if len(SCREAMING_SNAKE_CASE) > self.tokenizer.model_max_length:
                  _A					:     Dict     = input_ids[-self.tokenizer.model_max_length :]
           return input_ids






