
"""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


UpperCamelCase     :    Union[str, Any]       =			logging.get_logger(__name__)

class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):





     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase				):

      '''simple docstring'''




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







     def __call__(     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				):

      '''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				):
       __UpperCamelCase      =	[sequences]

      __UpperCamelCase      =	[]
      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 __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):





     def __init__(     self     ,					__UpperCAmelCase=ZeroShotClassificationArgumentHandler()     ,					*__UpperCAmelCase     ,					**__UpperCAmelCase				):

      '''simple docstring'''




      __UpperCamelCase      =	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				):

      '''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				):

      '''simple docstring'''




      __UpperCamelCase      =	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`'				)
       __UpperCamelCase      =	self.tokenizer.eos_token
      try:
       __UpperCamelCase      =	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.

        __UpperCamelCase      =	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				):

      '''simple docstring'''




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

      __UpperCamelCase      =	{}
      if "multi_label" in kwargs:
       __UpperCamelCase      =	kwargs['multi_label']
      return preprocess_params, {}, postprocess_params





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

      '''simple docstring'''




      if len(__UpperCAmelCase				) == 0:
       pass
      elif len(__UpperCAmelCase				) == 1 and "candidate_labels" not in kwargs:
       __UpperCamelCase      =	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 {}."				):

      '''simple docstring'''




      __UpperCamelCase  ,     __UpperCamelCase      =	self._args_parser(__UpperCAmelCase     ,					__UpperCAmelCase     ,					__UpperCAmelCase				)

      for i, (candidate_label, sequence_pair) in enumerate(zip(__UpperCAmelCase     ,					__UpperCAmelCase				)				):
       __UpperCamelCase      =	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				):

      '''simple docstring'''




      __UpperCamelCase      =	inputs['candidate_label']
      __UpperCamelCase      =	inputs['sequence']
      __UpperCamelCase      =	{k: inputs[k] for k in self.tokenizer.model_input_names}
      __UpperCamelCase      =	self.model(**__UpperCAmelCase				)

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







     def 						UpperCAmelCase (     self     ,					__UpperCAmelCase     ,					__UpperCAmelCase=False				):

      '''simple docstring'''




      __UpperCamelCase      =	[outputs['candidate_label'] for outputs in model_outputs]
      __UpperCamelCase      =	[outputs['sequence'] for outputs in model_outputs]
      __UpperCamelCase      =	np.concatenate([output['logits'].numpy() for output in model_outputs]				)
      __UpperCamelCase      =	logits.shape[0]
      __UpperCamelCase      =	len(__UpperCAmelCase				)
      __UpperCamelCase      =	N // n
      __UpperCamelCase      =	logits.reshape((num_sequences, n, -1)				)

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

      __UpperCamelCase      =	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_donut import DonutImageProcessor


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

class __lowerCAmelCase		(				__SCREAMING_SNAKE_CASE      ):





     def __init__(     self     ,					*__UpperCAmelCase     ,					**__UpperCAmelCase				):

      '''simple docstring'''




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



