




from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...file_utils import TensorType, is_torch_available
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import logging


UpperCamelCase								=					logging.get_logger(__name__)

UpperCamelCase								=					{
    'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/config.json',
    # See all BlenderbotSmall models at https://huggingface.co/models?filter=blenderbot_small
}





class 			__lowerCamelCase	(   UpperCamelCase__   ):




    """simple docstring"""

    snake_case__ =				"blenderbot-small"
    snake_case__ =				["past_key_values"]
    snake_case__ =				{"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}


    def __init__(	self					:					List[str]       ,     SCREAMING_SNAKE_CASE__					:					int=50_265       ,     SCREAMING_SNAKE_CASE__					:					str=512       ,     SCREAMING_SNAKE_CASE__					:					Any=8       ,     SCREAMING_SNAKE_CASE__					:					Any=2_048       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]=16       ,     SCREAMING_SNAKE_CASE__					:					Any=8       ,     SCREAMING_SNAKE_CASE__					:					Tuple=2_048       ,     SCREAMING_SNAKE_CASE__					:					str=16       ,     SCREAMING_SNAKE_CASE__					:					str=0.0       ,     SCREAMING_SNAKE_CASE__					:					List[str]=0.0       ,     SCREAMING_SNAKE_CASE__					:					Tuple=True       ,     SCREAMING_SNAKE_CASE__					:					Tuple=True       ,     SCREAMING_SNAKE_CASE__					:					List[str]="gelu"       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]=512       ,     SCREAMING_SNAKE_CASE__					:					Dict=0.1       ,     SCREAMING_SNAKE_CASE__					:					Dict=0.0       ,     SCREAMING_SNAKE_CASE__					:					List[Any]=0.0       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]=0.02       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]=1       ,     SCREAMING_SNAKE_CASE__					:					str=False       ,     SCREAMING_SNAKE_CASE__					:					str=0       ,     SCREAMING_SNAKE_CASE__					:					Dict=1       ,     SCREAMING_SNAKE_CASE__					:					Any=2       ,     SCREAMING_SNAKE_CASE__					:					int=2       ,     **SCREAMING_SNAKE_CASE__					:					Union[str, Any]       ,     )				->	int:
         lowerCAmelCase__          =			vocab_size
         lowerCAmelCase__          =			max_position_embeddings
         lowerCAmelCase__          =			d_model
         lowerCAmelCase__          =			encoder_ffn_dim
         lowerCAmelCase__          =			encoder_layers
         lowerCAmelCase__          =			encoder_attention_heads
         lowerCAmelCase__          =			decoder_ffn_dim
         lowerCAmelCase__          =			decoder_layers
         lowerCAmelCase__          =			decoder_attention_heads
         lowerCAmelCase__          =			dropout
         lowerCAmelCase__          =			attention_dropout
         lowerCAmelCase__          =			activation_dropout
         lowerCAmelCase__          =			activation_function
         lowerCAmelCase__          =			init_std
         lowerCAmelCase__          =			encoder_layerdrop
         lowerCAmelCase__          =			decoder_layerdrop
         lowerCAmelCase__          =			use_cache
         lowerCAmelCase__          =			encoder_layers
         lowerCAmelCase__          =			scale_embedding  # scale factor will be sqrt(d_model) if True

         super().__init__(
             pad_token_id=SCREAMING_SNAKE_CASE__       ,     bos_token_id=SCREAMING_SNAKE_CASE__       ,     eos_token_id=SCREAMING_SNAKE_CASE__       ,     is_encoder_decoder=SCREAMING_SNAKE_CASE__       ,     decoder_start_token_id=SCREAMING_SNAKE_CASE__       ,     forced_eos_token_id=SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       ,     )






class 			__lowerCamelCase	(   UpperCamelCase__   ):




    """simple docstring"""

    @property
    def        a				(	self					:					Any       )				->	Mapping[str, Mapping[int, str]]:
         if self.task in ["default", "seq2seq-lm"]:
              lowerCAmelCase__          =			OrderedDict(
                  [
                      ("input_ids", {0: "batch", 1: "encoder_sequence"}),
                      ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
                  ]       )

              if self.use_past:
                   lowerCAmelCase__          =			{0: "batch"}
                   lowerCAmelCase__          =			{0: "batch", 1: "past_decoder_sequence + sequence"}
              else:
                   lowerCAmelCase__          =			{0: "batch", 1: "decoder_sequence"}
                   lowerCAmelCase__          =			{0: "batch", 1: "decoder_sequence"}

              if self.use_past:
                   self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__       ,     direction="inputs"       )
         elif self.task == "causal-lm":
              # TODO: figure this case out.
              lowerCAmelCase__          =			OrderedDict(
                  [
                      ("input_ids", {0: "batch", 1: "encoder_sequence"}),
                      ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
                  ]       )
              if self.use_past:
                   lowerCAmelCase__     ,		lowerCAmelCase__          =			self.num_layers
                   for i in range(SCREAMING_SNAKE_CASE__       ):
                        lowerCAmelCase__          =			{0: "batch", 2: "past_sequence + sequence"}
                        lowerCAmelCase__          =			{0: "batch", 2: "past_sequence + sequence"}
         else:
              lowerCAmelCase__          =			OrderedDict(
                  [
                      ("input_ids", {0: "batch", 1: "encoder_sequence"}),
                      ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
                      ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
                      ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
                  ]       )

         return common_inputs


    @property
    def        a				(	self					:					List[str]       )				->	Mapping[str, Mapping[int, str]]:
         if self.task in ["default", "seq2seq-lm"]:
              lowerCAmelCase__          =			super().outputs
         else:
              lowerCAmelCase__          =			super(SCREAMING_SNAKE_CASE__       ,     self       ).outputs
              if self.use_past:
                   lowerCAmelCase__     ,		lowerCAmelCase__          =			self.num_layers
                   for i in range(SCREAMING_SNAKE_CASE__       ):
                        lowerCAmelCase__          =			{0: "batch", 2: "past_sequence + sequence"}
                        lowerCAmelCase__          =			{0: "batch", 2: "past_sequence + sequence"}
         return common_outputs


    def        a				(	self					:					str       ,     SCREAMING_SNAKE_CASE__					:					PreTrainedTokenizer       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					bool = False       ,     SCREAMING_SNAKE_CASE__					:					Optional[TensorType] = None       ,     )				->	Mapping[str, Any]:
         lowerCAmelCase__          =			self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )

         # Generate decoder inputs
         lowerCAmelCase__          =			seq_length if not self.use_past else 1
         lowerCAmelCase__          =			self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			{f'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
         lowerCAmelCase__          =			dict(**SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if self.use_past:
              if not is_torch_available():
                   raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."       )
              else:
                   import torch
              lowerCAmelCase__     ,		lowerCAmelCase__          =			common_inputs["input_ids"].shape
              lowerCAmelCase__          =			common_inputs["decoder_input_ids"].shape[1]
              lowerCAmelCase__     ,		lowerCAmelCase__          =			self.num_attention_heads
              lowerCAmelCase__          =			(
                  batch,
                  num_encoder_attention_heads,
                  encoder_seq_length,
                  self._config.hidden_size // num_encoder_attention_heads,
              )
              lowerCAmelCase__          =			decoder_seq_length + 3
              lowerCAmelCase__          =			(
                  batch,
                  num_decoder_attention_heads,
                  decoder_past_length,
                  self._config.hidden_size // num_decoder_attention_heads,
              )

              lowerCAmelCase__          =			torch.cat(
                  [common_inputs["decoder_attention_mask"], torch.ones(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )]       ,     dim=1       )

              lowerCAmelCase__          =			[]
              # If the number of encoder and decoder layers are present in the model configuration, both are considered
              lowerCAmelCase__     ,		lowerCAmelCase__          =			self.num_layers
              lowerCAmelCase__          =			min(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
              lowerCAmelCase__          =			max(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ) - min_num_layers
              lowerCAmelCase__          =			"encoder" if num_encoder_layers > num_decoder_layers else "decoder"

              for _ in range(SCREAMING_SNAKE_CASE__       ):
                   common_inputs["past_key_values"].append(
                       (
                           torch.zeros(SCREAMING_SNAKE_CASE__       ),
                           torch.zeros(SCREAMING_SNAKE_CASE__       ),
                           torch.zeros(SCREAMING_SNAKE_CASE__       ),
                           torch.zeros(SCREAMING_SNAKE_CASE__       ),
                       )       )
              # TODO: test this.
              lowerCAmelCase__          =			encoder_shape if remaining_side_name == "encoder" else decoder_shape
              for _ in range(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ):
                   common_inputs["past_key_values"].append((torch.zeros(SCREAMING_SNAKE_CASE__       ), torch.zeros(SCREAMING_SNAKE_CASE__       ))       )
         return common_inputs


    def        a				(	self					:					Any       ,     SCREAMING_SNAKE_CASE__					:					PreTrainedTokenizer       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					bool = False       ,     SCREAMING_SNAKE_CASE__					:					Optional[TensorType] = None       ,     )				->	Mapping[str, Any]:
         lowerCAmelCase__          =			self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )

         if self.use_past:
              if not is_torch_available():
                   raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed."       )
              else:
                   import torch
              lowerCAmelCase__     ,		lowerCAmelCase__          =			common_inputs["input_ids"].shape
              # Not using the same length for past_key_values
              lowerCAmelCase__          =			seqlen + 2
              lowerCAmelCase__     ,		lowerCAmelCase__          =			self.num_layers
              lowerCAmelCase__     ,		lowerCAmelCase__          =			self.num_attention_heads
              lowerCAmelCase__          =			(
                  batch,
                  num_encoder_attention_heads,
                  past_key_values_length,
                  self._config.hidden_size // num_encoder_attention_heads,
              )

              lowerCAmelCase__          =			common_inputs["attention_mask"].dtype
              lowerCAmelCase__          =			torch.cat(
                  [common_inputs["attention_mask"], torch.ones(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     dtype=SCREAMING_SNAKE_CASE__       )]       ,     dim=1       )
              lowerCAmelCase__          =			[
                  (torch.zeros(SCREAMING_SNAKE_CASE__       ), torch.zeros(SCREAMING_SNAKE_CASE__       )) for _ in range(SCREAMING_SNAKE_CASE__       )
              ]
         return common_inputs


    def        a				(	self					:					str       ,     SCREAMING_SNAKE_CASE__					:					PreTrainedTokenizer       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					bool = False       ,     SCREAMING_SNAKE_CASE__					:					Optional[TensorType] = None       ,     )				->	Mapping[str, Any]:
         # Copied from OnnxConfig.generate_dummy_inputs
         # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
         # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
         lowerCAmelCase__          =			compute_effective_axis_dimension(
             SCREAMING_SNAKE_CASE__       ,     fixed_dimension=OnnxConfig.default_fixed_batch       ,     num_token_to_add=0       )

         # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
         lowerCAmelCase__          =			tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			compute_effective_axis_dimension(
             SCREAMING_SNAKE_CASE__       ,     fixed_dimension=OnnxConfig.default_fixed_sequence       ,     num_token_to_add=SCREAMING_SNAKE_CASE__       )

         # Generate dummy inputs according to compute batch and sequence
         lowerCAmelCase__          =			[" ".join([tokenizer.unk_token]       ) * seq_length] * batch_size
         lowerCAmelCase__          =			dict(tokenizer(SCREAMING_SNAKE_CASE__       ,     return_tensors=SCREAMING_SNAKE_CASE__       )       )
         return common_inputs


    def        a				(	self					:					List[str]       ,     SCREAMING_SNAKE_CASE__					:					PreTrainedTokenizer       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					int = -1       ,     SCREAMING_SNAKE_CASE__					:					bool = False       ,     SCREAMING_SNAKE_CASE__					:					Optional[TensorType] = None       ,     )				->	Mapping[str, Any]:
         if self.task in ["default", "seq2seq-lm"]:
              lowerCAmelCase__          =			self._generate_dummy_inputs_for_default_and_seqaseq_lm(
                  SCREAMING_SNAKE_CASE__       ,     batch_size=SCREAMING_SNAKE_CASE__       ,     seq_length=SCREAMING_SNAKE_CASE__       ,     is_pair=SCREAMING_SNAKE_CASE__       ,     framework=SCREAMING_SNAKE_CASE__       )

         elif self.task == "causal-lm":
              lowerCAmelCase__          =			self._generate_dummy_inputs_for_causal_lm(
                  SCREAMING_SNAKE_CASE__       ,     batch_size=SCREAMING_SNAKE_CASE__       ,     seq_length=SCREAMING_SNAKE_CASE__       ,     is_pair=SCREAMING_SNAKE_CASE__       ,     framework=SCREAMING_SNAKE_CASE__       )
         else:
              lowerCAmelCase__          =			self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
                  SCREAMING_SNAKE_CASE__       ,     batch_size=SCREAMING_SNAKE_CASE__       ,     seq_length=SCREAMING_SNAKE_CASE__       ,     is_pair=SCREAMING_SNAKE_CASE__       ,     framework=SCREAMING_SNAKE_CASE__       )

         return common_inputs


    def        a				(	self					:					str       ,     SCREAMING_SNAKE_CASE__					:					List[Any]       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]       ,     SCREAMING_SNAKE_CASE__					:					int       ,     SCREAMING_SNAKE_CASE__					:					Optional[int]       )				->	List[Any]:
         if self.task in ["default", "seq2seq-lm"]:
              lowerCAmelCase__          =			super()._flatten_past_key_values_(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
         else:
              lowerCAmelCase__          =			super(SCREAMING_SNAKE_CASE__       ,     self       )._flatten_past_key_values_(
                  SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin





class 			__lowerCamelCase	(   UpperCamelCase__   ):




    """simple docstring"""

    snake_case__ =				"Speech2TextFeatureExtractor"
    snake_case__ =				"Speech2TextTokenizer"


    def __init__(	self					:					int       ,     SCREAMING_SNAKE_CASE__					:					Dict       ,     SCREAMING_SNAKE_CASE__					:					Tuple       )				->	Optional[Any]:
         super().__init__(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			self.feature_extractor
         lowerCAmelCase__          =			False


    def __call__(	self					:					str       ,     *SCREAMING_SNAKE_CASE__					:					int       ,     **SCREAMING_SNAKE_CASE__					:					int       )				->	Optional[Any]:
         # For backward compatibility
         if self._in_target_context_manager:
              return self.current_processor(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if "raw_speech" in kwargs:
              warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."       )
              lowerCAmelCase__          =			kwargs.pop("raw_speech"       )
         else:
              lowerCAmelCase__          =			kwargs.pop("audio"       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			kwargs.pop("sampling_rate"       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			kwargs.pop("text"       ,     SCREAMING_SNAKE_CASE__       )
         if len(SCREAMING_SNAKE_CASE__       ) > 0:
              lowerCAmelCase__          =			args[0]
              lowerCAmelCase__          =			args[1:]

         if audio is None and text is None:
              raise ValueError("You need to specify either an `audio` or `text` input to process."       )

         if audio is not None:
              lowerCAmelCase__          =			self.feature_extractor(SCREAMING_SNAKE_CASE__       ,     *SCREAMING_SNAKE_CASE__       ,     sampling_rate=SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )
         if text is not None:
              lowerCAmelCase__          =			self.tokenizer(SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if text is None:
              return inputs
         elif audio is None:
              return encodings
         else:
              lowerCAmelCase__          =			encodings["input_ids"]
              return inputs


    def        a				(	self					:					str       ,     *SCREAMING_SNAKE_CASE__					:					Dict       ,     **SCREAMING_SNAKE_CASE__					:					int       )				->	Union[str, Any]:
         return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					Dict       ,     *SCREAMING_SNAKE_CASE__					:					Optional[int]       ,     **SCREAMING_SNAKE_CASE__					:					Optional[int]       )				->	Optional[Any]:
         return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )


    @contextmanager
    def        a				(	self					:					Union[str, Any]       )				->	Any:
         warnings.warn(
             "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
             "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
             "your audio inputs, or in a separate call."       )
         lowerCAmelCase__          =			True
         lowerCAmelCase__          =			self.tokenizer
         yield
         lowerCAmelCase__          =			self.feature_extractor
         lowerCAmelCase__          =			False
