"""simple docstring"""







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


__SCREAMING_SNAKE_CASE    	=logging.get_logger(__name__)







class        UpperCamelCase		(			lowercase_  ):
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      Union[str, Any]:


        '''simple docstring'''


        if isinstance(__UpperCamelCase     ,__UpperCamelCase			):
             lowercase_	:				Dict													=	[label.strip() for label in labels.split(','			) if label.strip()]
        return labels







   def __call__(			self     ,__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)	->      List[str]:


        '''simple docstring'''


        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_	:				Tuple													=	[sequences]

        lowercase_	:				str													=	[]
        for sequence in sequences:
             sequence_pairs.extend([[sequence, hypothesis_template.format(__UpperCamelCase			)] for label in labels]			)

        return sequence_pairs, sequences







@add_end_docstrings(lowercase_  )
class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,__UpperCamelCase=ZeroShotClassificationArgumentHandler()     ,*__UpperCamelCase     ,**__UpperCamelCase			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				List[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 			_UpperCAmelCase   (			self			)	->      int:


        '''simple docstring'''


        for label, ind in self.model.config.labelaid.items():
             if label.lower().startswith('entail'			):
                  return ind
        return -1
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase=True     ,__UpperCamelCase=True     ,__UpperCamelCase=TruncationStrategy.ONLY_FIRST     ,**__UpperCamelCase			)	->      Optional[Any]:


        '''simple docstring'''


        lowercase_	:				List[Any]													=	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_	:				Union[str, Any]													=	self.tokenizer.eos_token
        try:
             lowercase_	:				Union[str, 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 			_UpperCAmelCase   (			self     ,**__UpperCamelCase			)	->      int:


        '''simple docstring'''


        if kwargs.get('multi_class'     ,__UpperCamelCase			) is not None:
             lowercase_	:				int													=	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_	:				List[Any]													=	{}
        if "candidate_labels" in kwargs:
             lowercase_	:				Tuple													=	self._args_parser._parse_labels(kwargs['candidate_labels']			)
        if "hypothesis_template" in kwargs:
             lowercase_	:				Any													=	kwargs['hypothesis_template']

        lowercase_	:				List[str]													=	{}
        if "multi_label" in kwargs:
             lowercase_	:				List[str]													=	kwargs['multi_label']
        return preprocess_params, {}, postprocess_params
   def __call__(			self     ,__UpperCamelCase     ,*__UpperCamelCase     ,**__UpperCamelCase     ,)	->      Any:


        '''simple docstring'''


        if len(__UpperCamelCase			) == 0:
             pass
        elif len(__UpperCamelCase			) == 1 and "candidate_labels" not in kwargs:
             lowercase_	:				Optional[Any]													=	args[0]
        else:
             raise ValueError(f'''Unable to understand extra arguments {args}'''			)

        return super().__call__(__UpperCamelCase     ,**__UpperCamelCase			)
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase=None     ,__UpperCamelCase="This example is {}."			)	->      List[str]:


        '''simple docstring'''


        lowercase_							,  lowercase_	:				Optional[int]													=	self._args_parser(__UpperCamelCase     ,__UpperCamelCase     ,__UpperCamelCase			)

        for i, (candidate_label, sequence_pair) in enumerate(zip(__UpperCamelCase     ,__UpperCamelCase			)			):
             lowercase_	:				Union[str, Any]													=	self._parse_and_tokenize([sequence_pair]			)

             yield {
                 "candidate_label": candidate_label,
                 "sequence": sequences[0],
                 "is_last": i == len(__UpperCamelCase			) - 1,
                 **model_input,
             }
   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase			)	->      List[Any]:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	inputs['candidate_label']
        lowercase_	:				Optional[int]													=	inputs['sequence']
        lowercase_	:				Union[str, Any]													=	{k: inputs[k] for k in self.tokenizer.model_input_names}
        lowercase_	:				List[str]													=	self.model(**__UpperCamelCase			)

        lowercase_	:				str													=	{
            'candidate_label': candidate_label,
            'sequence': sequence,
            'is_last': inputs['is_last'],
            **outputs,
        }
        return model_outputs







   def 			_UpperCAmelCase   (			self     ,__UpperCamelCase     ,__UpperCamelCase=False			)	->      Tuple:


        '''simple docstring'''


        lowercase_	:				Optional[int]													=	[outputs['candidate_label'] for outputs in model_outputs]
        lowercase_	:				str													=	[outputs['sequence'] for outputs in model_outputs]
        lowercase_	:				List[str]													=	np.concatenate([output['logits'].numpy() for output in model_outputs]			)
        lowercase_	:				str													=	logits.shape[0]
        lowercase_	:				Optional[int]													=	len(__UpperCamelCase			)
        lowercase_	:				Union[str, Any]													=	N // n
        lowercase_	:				Optional[int]													=	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_	:				Union[str, Any]													=	self.entailment_id
             lowercase_	:				List[str]													=	-1 if entailment_id == 0 else 0
             lowercase_	:				int													=	reshaped_outputs[..., [contradiction_id, entailment_id]]
             lowercase_	:				Optional[Any]													=	np.exp(__UpperCamelCase			) / np.exp(__UpperCamelCase			).sum(-1     ,keepdims=__UpperCamelCase			)
             lowercase_	:				Optional[Any]													=	scores[..., 1]
        else:
             # softmax the "entailment" logits over all candidate labels
             lowercase_	:				Any													=	reshaped_outputs[..., self.entailment_id]
             lowercase_	:				Optional[int]													=	np.exp(__UpperCamelCase			) / np.exp(__UpperCamelCase			).sum(-1     ,keepdims=__UpperCamelCase			)

        lowercase_	:				Union[str, 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(),
        }


"""simple docstring"""







import warnings

from ...utils import logging
from .image_processing_beit import BeitImageProcessor


__SCREAMING_SNAKE_CASE    	=logging.get_logger(__name__)







class        UpperCamelCase		(			lowercase_  ):
   def __init__(			self     ,*__UpperCamelCase     ,**__UpperCamelCase			)	->      None:


        '''simple docstring'''


        warnings.warn(
            'The class BeitFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please'
            ' use BeitImageProcessor instead.'     ,__UpperCamelCase     ,)
        super().__init__(*__UpperCamelCase     ,**__UpperCamelCase			)

