


import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
   from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
   from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING







def SCREAMING_SNAKE_CASE	(			__lowerCAmelCase				)    ->				int:
  return 1.0 / (1.0 + np.exp(-_outputs				))







def SCREAMING_SNAKE_CASE	(			__lowerCAmelCase				)    ->				Any:
  snake_case__						= np.max(_outputs							,   axis=-1							,   keepdims=__lowerCAmelCase				)
  snake_case__						= np.exp(_outputs - maxes				)
  return shifted_exp / shifted_exp.sum(axis=-1							,   keepdims=__lowerCAmelCase				)
class 		__magic_name__						(snake_case_				):





     '''simple docstring'''



     __lowercase				:							Optional[int]	   =       'sigmoid'
     __lowercase				:							int	   =       'softmax'
     __lowercase				:							Optional[Any]	   =       'none'




@add_end_docstrings(
    snake_case_   ,R'\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `"default"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `"sigmoid"`: Applies the sigmoid function on the output.\n            - `"softmax"`: Applies the softmax function on the output.\n            - `"none"`: Does not apply any function on the output.\n    '   ,)
class 		__magic_name__						(snake_case_				):





     '''simple docstring'''



     __lowercase				:							List[str]	   =       False
     __lowercase				:							List[str]	   =       ClassificationFunction.NONE

     def __init__(					self:Optional[Any]     ,		**_a:Union[str, Any]   ):
       super().__init__(**_a   )

       self.check_model_type(
           TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
           if self.framework == '''tf'''
           else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING   )

     def 	SCREAMING_SNAKE_CASE__						(					self:str     ,		_a:int=None     ,		_a:str=None     ,		_a:Union[str, Any]=""     ,		**_a:Tuple   ):
       # Using "" as default argument because we're going to use `top_k=None` in user code to declare
       # "No top_k"
       snake_case__						= tokenizer_kwargs

       snake_case__						= {}
       if hasattr(self.model.config     ,		'''return_all_scores'''   ) and return_all_scores is None:
         snake_case__						= self.model.config.return_all_scores

       if isinstance(_a     ,		_a   ) or top_k is None:
         snake_case__						= top_k
         snake_case__						= False
       elif return_all_scores is not None:
         warnings.warn(
             '''`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of'''
             ''' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.'''     ,		_a     ,		)
         if return_all_scores:
           snake_case__						= None
         else:
           snake_case__						= 1

       if isinstance(_a     ,		_a   ):
         snake_case__						= ClassificationFunction[function_to_apply.upper()]

       if function_to_apply is not None:
         snake_case__						= function_to_apply
       return preprocess_params, {}, postprocess_params

     def __call__(					self:List[str]     ,		*_a:str     ,		**_a:Optional[int]   ):
       snake_case__						= super().__call__(*_a     ,		**_a   )
       # TODO try and retrieve it in a nicer way from _sanitize_parameters.
       snake_case__						= '''top_k''' not in kwargs
       if isinstance(args[0]     ,		_a   ) and _legacy:
         # This pipeline is odd, and return a list when single item is run
         return [result]
       else:
         return result

     def 	SCREAMING_SNAKE_CASE__						(					self:Optional[int]     ,		_a:Optional[int]     ,		**_a:str   ):
       snake_case__						= self.framework
       if isinstance(_a     ,		_a   ):
         return self.tokenizer(**_a     ,		return_tensors=_a     ,		**_a   )
       elif isinstance(_a     ,		_a   ) and len(_a   ) == 1 and isinstance(inputs[0]     ,		_a   ) and len(inputs[0]   ) == 2:
         # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
         return self.tokenizer(
             text=inputs[0][0]     ,		text_pair=inputs[0][1]     ,		return_tensors=_a     ,		**_a   )
       elif isinstance(_a     ,		_a   ):
         # This is likely an invalid usage of the pipeline attempting to pass text pairs.
         raise ValueError(
             '''The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a'''
             ''' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.'''   )
       return self.tokenizer(_a     ,		return_tensors=_a     ,		**_a   )

     def 	SCREAMING_SNAKE_CASE__						(					self:List[str]     ,		_a:Optional[int]   ):
       return self.model(**_a   )







     def 	SCREAMING_SNAKE_CASE__						(					self:Union[str, Any]     ,		_a:List[Any]     ,		_a:List[Any]=None     ,		_a:Tuple=1     ,		_a:Tuple=True   ):
       # `_legacy` is used to determine if we're running the naked pipeline and in backward
       # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
       # the more natural result containing the list.
       # Default value before `set_parameters`
       if function_to_apply is None:
         if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
           snake_case__						= ClassificationFunction.SIGMOID
         elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
           snake_case__						= ClassificationFunction.SOFTMAX
         elif hasattr(self.model.config     ,		'''function_to_apply'''   ) and function_to_apply is None:
           snake_case__						= self.model.config.function_to_apply
         else:
           snake_case__						= ClassificationFunction.NONE

       snake_case__						= model_outputs['''logits'''][0]
       snake_case__						= outputs.numpy()

       if function_to_apply == ClassificationFunction.SIGMOID:
         snake_case__						= sigmoid(_a   )
       elif function_to_apply == ClassificationFunction.SOFTMAX:
         snake_case__						= softmax(_a   )
       elif function_to_apply == ClassificationFunction.NONE:
         snake_case__						= outputs
       else:
         raise ValueError(F"""Unrecognized `function_to_apply` argument: {function_to_apply}"""   )

       if top_k == 1 and _legacy:
         return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

       snake_case__						= [
           {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(_a   )
       ]
       if not _legacy:
         dict_scores.sort(key=lambda _a   : x["score"]     ,		reverse=_a   )
         if top_k is not None:
           snake_case__						= dict_scores[:top_k]
       return dict_scores




'''simple docstring'''

import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer


SCREAMING_SNAKE_CASE							:				int     	=			logging.get_logger(__name__)


SCREAMING_SNAKE_CASE							:				Dict     	=			{"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

# See all BART models at https://huggingface.co/models?filter=bart
SCREAMING_SNAKE_CASE							:				str     	=			{
    "vocab_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
    },
    "merges_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
    },
    "tokenizer_file": {
        "facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json",
        "facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json",
        "facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json",
        "facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json",
        "facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json",
        "yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json",
    },
}

SCREAMING_SNAKE_CASE							:				Union[str, Any]     	=			{
    "facebook/bart-base": 1024,
    "facebook/bart-large": 1024,
    "facebook/bart-large-mnli": 1024,
    "facebook/bart-large-cnn": 1024,
    "facebook/bart-large-xsum": 1024,
    "yjernite/bart_eli5": 1024,
}






class    snake_case     (      lowercase_		):






				"""simple docstring"""
				_a    	=     VOCAB_FILES_NAMES
				_a    	=     PRETRAINED_VOCAB_FILES_MAP
				_a    	=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
				_a    	=     ["""input_ids""", """attention_mask"""]
				_a    	=     BartTokenizer



				def __init__(    self,     _lowercase=None,     _lowercase=None,     _lowercase=None,     _lowercase="replace",     _lowercase="<s>",     _lowercase="</s>",     _lowercase="</s>",     _lowercase="<s>",     _lowercase="<unk>",     _lowercase="<pad>",     _lowercase="<mask>",     _lowercase=False,     _lowercase=True,     **_lowercase,     )     ->							Dict:
											super().__init__(
											    _lowercase,     _lowercase,     tokenizer_file=_lowercase,     errors=_lowercase,     bos_token=_lowercase,     eos_token=_lowercase,     sep_token=_lowercase,     cls_token=_lowercase,     unk_token=_lowercase,     pad_token=_lowercase,     mask_token=_lowercase,     add_prefix_space=_lowercase,     trim_offsets=_lowercase,     **_lowercase,     )

											SCREAMING_SNAKE_CASE_				=				json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()       )
											if pre_tok_state.get('add_prefix_space',     _lowercase       ) != add_prefix_space:
																		SCREAMING_SNAKE_CASE_				=				getattr(_lowercase,     pre_tok_state.pop('type'       )       )
																		SCREAMING_SNAKE_CASE_				=				add_prefix_space
																		SCREAMING_SNAKE_CASE_				=				pre_tok_class(**_lowercase       )

											SCREAMING_SNAKE_CASE_				=				add_prefix_space

											# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
											SCREAMING_SNAKE_CASE_				=				'post_processor'
											SCREAMING_SNAKE_CASE_				=				getattr(self.backend_tokenizer,     _lowercase,     _lowercase       )
											if tokenizer_component_instance:
																		SCREAMING_SNAKE_CASE_				=				json.loads(tokenizer_component_instance.__getstate__()       )

																		# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
																		if "sep" in state:
																									SCREAMING_SNAKE_CASE_				=				tuple(state['sep']       )
																		if "cls" in state:
																									SCREAMING_SNAKE_CASE_				=				tuple(state['cls']       )

																		SCREAMING_SNAKE_CASE_				=				False

																		if state.get('add_prefix_space',     _lowercase       ) != add_prefix_space:
																									SCREAMING_SNAKE_CASE_				=				add_prefix_space
																									SCREAMING_SNAKE_CASE_				=				True

																		if state.get('trim_offsets',     _lowercase       ) != trim_offsets:
																									SCREAMING_SNAKE_CASE_				=				trim_offsets
																									SCREAMING_SNAKE_CASE_				=				True

																		if changes_to_apply:
																									SCREAMING_SNAKE_CASE_				=				getattr(_lowercase,     state.pop('type'       )       )
																									SCREAMING_SNAKE_CASE_				=				component_class(**_lowercase       )
																									setattr(self.backend_tokenizer,     _lowercase,     _lowercase       )



				@property
				def   a__					(    self       )     ->							str:
											if self._mask_token is None:
																		if self.verbose:
																									logger.error('Using mask_token, but it is not set yet.'       )
																		return None
											return str(self._mask_token       )



				@mask_token.setter
				def   a__					(    self,     _lowercase       )     ->							Dict:
											SCREAMING_SNAKE_CASE_				=				AddedToken(_lowercase,     lstrip=_lowercase,     rstrip=_lowercase       ) if isinstance(_lowercase,     _lowercase       ) else value
											SCREAMING_SNAKE_CASE_				=				value



				def   a__					(    self,     *_lowercase,     **_lowercase       )     ->							BatchEncoding:
											SCREAMING_SNAKE_CASE_				=				kwargs.get('is_split_into_words',     _lowercase       )

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.'       )

											return super()._batch_encode_plus(*_lowercase,     **_lowercase       )



				def   a__					(    self,     *_lowercase,     **_lowercase       )     ->							BatchEncoding:
											SCREAMING_SNAKE_CASE_				=				kwargs.get('is_split_into_words',     _lowercase       )

											if is_split_into_words and not self.add_prefix_space:
																		raise ValueError(
																		    f"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """
																		    'to use it with pretokenized inputs.'       )

											return super()._encode_plus(*_lowercase,     **_lowercase       )



				def   a__					(    self,     _lowercase,     _lowercase = None       )     ->							Tuple[str]:
											SCREAMING_SNAKE_CASE_				=				self._tokenizer.model.save(_lowercase,     name=_lowercase       )
											return tuple(_lowercase       )



				def   a__					(    self,     _lowercase,     _lowercase=None       )     ->							Optional[Any]:
											SCREAMING_SNAKE_CASE_				=				[self.bos_token_id] + token_ids_a + [self.eos_token_id]
											if token_ids_a is None:
																		return output

											return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]





				def   a__					(    self,     _lowercase,     _lowercase = None       )     ->							List[int]:
											SCREAMING_SNAKE_CASE_				=				[self.sep_token_id]
											SCREAMING_SNAKE_CASE_				=				[self.cls_token_id]

											if token_ids_a is None:
																		return len(cls + token_ids_a + sep       ) * [0]
											return len(cls + token_ids_a + sep + sep + token_ids_a + sep       ) * [0]





