

from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


snake_case_        =			logging.get_logger(__name__)


class 				SCREAMING_SNAKE_CASE__ (__SCREAMING_SNAKE_CASE					):





    def 				snake_case_    (				self						,       a):







         if isinstance(UpperCamelCase__						,       UpperCamelCase__):
              lowercase__   :       Any				=	[label.strip() for label in labels.split(',') if label.strip()]
         return labels





    def __call__(				self						,       a						,       a						,       a):







         if len(UpperCamelCase__) == 0 or len(UpperCamelCase__) == 0:
              raise ValueError('You must include at least one label and at least one sequence.')
         if hypothesis_template.format(labels[0]) == hypothesis_template:
              raise ValueError(
                  (
                      'The provided hypothesis_template "{}" was not able to be formatted with the target labels. '
                      'Make sure the passed template includes formatting syntax such as {{}} where the label should go.'
                  ).format(UpperCamelCase__))

         if isinstance(UpperCamelCase__						,       UpperCamelCase__):
              lowercase__   :       List[Any]				=	[sequences]

         lowercase__   :       List[Any]				=	[]
         for sequence in sequences:
              sequence_pairs.extend([[sequence, hypothesis_template.format(UpperCamelCase__)] for label in labels])

         return sequence_pairs, sequences



@add_end_docstrings(__SCREAMING_SNAKE_CASE					)
class 				SCREAMING_SNAKE_CASE__ (__SCREAMING_SNAKE_CASE					):





    def __init__(				self						,       a=ZeroShotClassificationArgumentHandler()						,       *a						,       **a):
         lowercase__   :       Any				=	args_parser
         super().__init__(*UpperCamelCase__						,       **UpperCamelCase__)
         if self.entailment_id == -1:
              logger.warning(
                  'Failed to determine \'entailment\' label id from the label2id mapping in the model config. Setting to '
                  '-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.')





    @property
    def 				snake_case_    (				self):







         for label, ind in self.model.config.labelaid.items():
              if label.lower().startswith('entail'):
                   return ind
         return -1





    def 				snake_case_    (				self						,       a						,       a=True						,       a=True						,       a=TruncationStrategy.ONLY_FIRST						,       **a):
         lowercase__   :       int				=	self.framework
         if self.tokenizer.pad_token is None:
              # Override for tokenizers not supporting padding
              logger.error(
                  'Tokenizer was not supporting padding necessary for zero-shot, attempting to use '
                  ' `pad_token=eos_token`')
              lowercase__   :       List[Any]				=	self.tokenizer.eos_token
         try:
              lowercase__   :       Optional[Any]				=	self.tokenizer(
                  UpperCamelCase__						,       add_special_tokens=UpperCamelCase__						,       return_tensors=UpperCamelCase__						,       padding=UpperCamelCase__						,       truncation=UpperCamelCase__						,       )
         except Exception as e:
              if "too short" in str(UpperCamelCase__):
                   # tokenizers might yell that we want to truncate
                   # to a value that is not even reached by the input.
                   # In that case we don't want to truncate.
                   # It seems there's not a really better way to catch that
                   # exception.

                   lowercase__   :       Tuple				=	self.tokenizer(
                       UpperCamelCase__						,       add_special_tokens=UpperCamelCase__						,       return_tensors=UpperCamelCase__						,       padding=UpperCamelCase__						,       truncation=TruncationStrategy.DO_NOT_TRUNCATE						,       )
              else:
                   raise e

         return inputs





    def 				snake_case_    (				self						,       **a):







         if kwargs.get('multi_class'						,       UpperCamelCase__) is not None:
              lowercase__   :       Union[str, Any]				=	kwargs['''multi_class''']
              logger.warning(
                  'The `multi_class` argument has been deprecated and renamed to `multi_label`. '
                  '`multi_class` will be removed in a future version of Transformers.')
         lowercase__   :       Union[str, Any]				=	{}
         if "candidate_labels" in kwargs:
              lowercase__   :       Tuple				=	self._args_parser._parse_labels(kwargs['candidate_labels'])
         if "hypothesis_template" in kwargs:
              lowercase__   :       Optional[int]				=	kwargs['''hypothesis_template''']

         lowercase__   :       int				=	{}
         if "multi_label" in kwargs:
              lowercase__   :       List[str]				=	kwargs['''multi_label''']
         return preprocess_params, {}, postprocess_params





    def __call__(				self						,       a						,       *a						,       **a						,       ):







         if len(UpperCamelCase__) == 0:
              pass
         elif len(UpperCamelCase__) == 1 and "candidate_labels" not in kwargs:
              lowercase__   :       List[str]				=	args[0]
         else:
              raise ValueError(f"""Unable to understand extra arguments {args}""")

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





    def 				snake_case_    (				self						,       a						,       a=None						,       a="This example is {}."):
         lowercase__   :       Dict				=	self._args_parser(UpperCamelCase__						,       UpperCamelCase__						,       UpperCamelCase__)

         for i, (candidate_label, sequence_pair) in enumerate(zip(UpperCamelCase__						,       UpperCamelCase__)):
              lowercase__   :       str				=	self._parse_and_tokenize([sequence_pair])

              yield {
                  "candidate_label": candidate_label,
                  "sequence": sequences[0],
                  "is_last": i == len(UpperCamelCase__) - 1,
                  **model_input,
              }





    def 				snake_case_    (				self						,       a):
         lowercase__   :       int				=	inputs['''candidate_label''']
         lowercase__   :       Tuple				=	inputs['''sequence''']
         lowercase__   :       Union[str, Any]				=	{k: inputs[k] for k in self.tokenizer.model_input_names}
         lowercase__   :       str				=	self.model(**UpperCamelCase__)

         lowercase__   :       Optional[Any]				=	{
             '''candidate_label''': candidate_label,
             '''sequence''': sequence,
             '''is_last''': inputs['''is_last'''],
             **outputs,
         }
         return model_outputs





    def 				snake_case_    (				self						,       a						,       a=False):
         lowercase__   :       int				=	[outputs['''candidate_label'''] for outputs in model_outputs]
         lowercase__   :       Union[str, Any]				=	[outputs['''sequence'''] for outputs in model_outputs]
         lowercase__   :       str				=	np.concatenate([output['logits'].numpy() for output in model_outputs])
         lowercase__   :       Optional[int]				=	logits.shape[0]
         lowercase__   :       str				=	len(UpperCamelCase__)
         lowercase__   :       List[str]				=	N // n
         lowercase__   :       str				=	logits.reshape((num_sequences, n, -1))

         if multi_label or len(UpperCamelCase__) == 1:
              # softmax over the entailment vs. contradiction dim for each label independently
              lowercase__   :       Optional[Any]				=	self.entailment_id
              lowercase__   :       Tuple				=	-1 if entailment_id == 0 else 0
              lowercase__   :       Optional[int]				=	reshaped_outputs[..., [contradiction_id, entailment_id]]
              lowercase__   :       Any				=	np.exp(UpperCamelCase__) / np.exp(UpperCamelCase__).sum(-1						,       keepdims=UpperCamelCase__)
              lowercase__   :       str				=	scores[..., 1]
         else:
              # softmax the "entailment" logits over all candidate labels
              lowercase__   :       Dict				=	reshaped_outputs[..., self.entailment_id]
              lowercase__   :       Optional[int]				=	np.exp(UpperCamelCase__) / np.exp(UpperCamelCase__).sum(-1						,       keepdims=UpperCamelCase__)

         lowercase__   :       List[Any]				=	list(reversed(scores[0].argsort()))
         return {
             "sequence": sequences[0],
             "labels": [candidate_labels[i] for i in top_inds],
             "scores": scores[0, top_inds].tolist(),
         }




from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case_        =			logging.get_logger(__name__)

snake_case_        =			{
    '''facebook/s2t-wav2vec2-large-en-de''': (
        '''https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json'''
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}


class 				SCREAMING_SNAKE_CASE__ (__snake_case					):
    __lowerCamelCase						:	List[Any]														=					"""speech_to_text_2"""
    __lowerCamelCase						:	str														=					["""past_key_values"""]
    __lowerCamelCase						:	List[Any]														=					{"""num_attention_heads""": """decoder_attention_heads""", """hidden_size""": """d_model"""}





    def __init__(				self						,       a=1_0000						,       a=6						,       a=2048						,       a=4						,       a=0.0						,       a=True						,       a="relu"						,       a=256						,       a=0.1						,       a=0.0						,       a=0.0						,       a=0.02						,       a=2						,       a=True						,       a=1						,       a=0						,       a=2						,       a=1024						,       **a						,       ):
         lowercase__   :       Optional[int]				=	vocab_size
         lowercase__   :       List[str]				=	d_model
         lowercase__   :       int				=	decoder_ffn_dim
         lowercase__   :       Optional[Any]				=	decoder_layers
         lowercase__   :       int				=	decoder_attention_heads
         lowercase__   :       Dict				=	dropout
         lowercase__   :       Optional[int]				=	attention_dropout
         lowercase__   :       Optional[int]				=	activation_dropout
         lowercase__   :       Optional[int]				=	activation_function
         lowercase__   :       Dict				=	init_std
         lowercase__   :       List[Any]				=	decoder_layerdrop
         lowercase__   :       int				=	use_cache
         lowercase__   :       Any				=	decoder_layers
         lowercase__   :       Optional[int]				=	scale_embedding  # scale factor will be sqrt(d_model) if True
         lowercase__   :       Tuple				=	max_target_positions

         super().__init__(
             pad_token_id=a						,       bos_token_id=a						,       eos_token_id=a						,       decoder_start_token_id=a						,       **a						,       )

