
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 :			Optional[int])					->    str:






							'''simple docstring'''





							return 1.0 / (1.0 + np.exp(-_outputs))




def 	_SCREAMING_SNAKE_CASE					(		_lowerCamelCase :			int)					->    List[Any]:






							'''simple docstring'''





							__UpperCamelCase	:   List[str]			   =					np.max(_outputs						,  axis=-1						,  keepdims=_lowerCamelCase)
							__UpperCamelCase	:   List[Any]			   =					np.exp(_outputs - maxes)
							return shifted_exp / shifted_exp.sum(axis=-1						,  keepdims=_lowerCamelCase)




class  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	_A								=     'sigmoid'
	_A								=     'softmax'
	_A								=     'none'




@add_end_docstrings(
    __lowercase     ,						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  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	_A								=     False
	_A								=     ClassificationFunction.NONE







	def __init__(					self		:str     ,   **a		:List[Any]						)		-> Optional[int]:
								super().__init__(**a						)

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







	def    _lowerCamelCase				(					self		:int     ,   a		:Optional[int]=None     ,   a		:int=None     ,   a		:Optional[int]=""     ,   **a		:List[Any]						)		-> List[str]:
								# Using "" as default argument because we're going to use `top_k=None` in user code to declare
								# "No top_k"
								__UpperCamelCase	:   Dict			   =					tokenizer_kwargs

								__UpperCamelCase	:   List[str]			   =					{}
								if hasattr(self.model.config     ,   "return_all_scores"						) and return_all_scores is None:
															__UpperCamelCase	:   Union[str, Any]			   =					self.model.config.return_all_scores

								if isinstance(a     ,   a						) or top_k is None:
															__UpperCamelCase	:   Tuple			   =					top_k
															__UpperCamelCase	:   List[Any]			   =					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:
																						__UpperCamelCase	:   List[str]			   =					None
															else:
																						__UpperCamelCase	:   Union[str, Any]			   =					1

								if isinstance(a     ,   a						):
															__UpperCamelCase	:   Dict			   =					ClassificationFunction[function_to_apply.upper()]

								if function_to_apply is not None:
															__UpperCamelCase	:   List[Any]			   =					function_to_apply
								return preprocess_params, {}, postprocess_params







	def __call__(					self		:Tuple     ,   *a		:List[Any]     ,   **a		:Optional[Any]						)		-> Optional[Any]:
								__UpperCamelCase	:   Dict			   =					super().__call__(*a     ,   **a						)
								# TODO try and retrieve it in a nicer way from _sanitize_parameters.
								__UpperCamelCase	:   List[str]			   =					"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    _lowerCamelCase				(					self		:Dict     ,   a		:List[Any]     ,   **a		:int						)		-> Dict[str, GenericTensor]:
								__UpperCamelCase	:   Optional[Any]			   =					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    _lowerCamelCase				(					self		:Tuple     ,   a		:Dict						)		-> Any:
								return self.model(**a						)







	def    _lowerCamelCase				(					self		:Optional[int]     ,   a		:str     ,   a		:Any=None     ,   a		:int=1     ,   a		:int=True						)		-> Optional[int]:
								# `_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:
																						__UpperCamelCase	:   Union[str, Any]			   =					ClassificationFunction.SIGMOID
															elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																						__UpperCamelCase	:   Union[str, Any]			   =					ClassificationFunction.SOFTMAX
															elif hasattr(self.model.config     ,   "function_to_apply"						) and function_to_apply is None:
																						__UpperCamelCase	:   Tuple			   =					self.model.config.function_to_apply
															else:
																						__UpperCamelCase	:   Union[str, Any]			   =					ClassificationFunction.NONE

								__UpperCamelCase	:   List[Any]			   =					model_outputs["logits"][0]
								__UpperCamelCase	:   Optional[int]			   =					outputs.numpy()

								if function_to_apply == ClassificationFunction.SIGMOID:
															__UpperCamelCase	:   Optional[Any]			   =					sigmoid(a						)
								elif function_to_apply == ClassificationFunction.SOFTMAX:
															__UpperCamelCase	:   int			   =					softmax(a						)
								elif function_to_apply == ClassificationFunction.NONE:
															__UpperCamelCase	:   Tuple			   =					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()}

								__UpperCamelCase	:   List[str]			   =					[
								    {"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:
																						__UpperCamelCase	:   Union[str, Any]			   =					dict_scores[:top_k]
								return dict_scores

import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


lowercase  :					int													=       logging.get_logger(__name__)


lowercase  :					Union[str, Any]													=       '▁'

lowercase  :					Tuple													=       {'vocab_file': 'spiece.model'}

lowercase  :					Dict													=       {
    'vocab_file': {
        'google/reformer-crime-and-punishment': (
            'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model'
        )
    }
}

lowercase  :					Any													=       {
    'google/reformer-crime-and-punishment': 524288,
}




class  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	_A								=     VOCAB_FILES_NAMES
	_A								=     PRETRAINED_VOCAB_FILES_MAP
	_A								=     PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
	_A								=     ['input_ids', 'attention_mask']







	def __init__(					self		:int     ,   a		:List[Any]     ,   a		:Tuple="</s>"     ,   a		:str="<unk>"     ,   a		:Dict=[]     ,   a		:Optional[Dict[str, Any]] = None     ,   **a		:Union[str, Any]     ,   )		-> None:
								__UpperCamelCase	:   str			   =					{} if sp_model_kwargs is None else sp_model_kwargs

								super().__init__(
								    eos_token=a     ,   unk_token=a     ,   additional_special_tokens=a     ,   sp_model_kwargs=self.sp_model_kwargs     ,   **a     ,   )

								__UpperCamelCase	:   Optional[Any]			   =					vocab_file
								__UpperCamelCase	:   Dict			   =					spm.SentencePieceProcessor(**self.sp_model_kwargs						)
								self.sp_model.Load(a						)







	@property
	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> Any:
								return self.sp_model.get_piece_size()







	def    _lowerCamelCase				(					self		:Optional[int]						)		-> Dict[str, int]:
								__UpperCamelCase	:   str			   =					{self.convert_ids_to_tokens(a						): i for i in range(self.vocab_size						)}
								vocab.update(self.added_tokens_encoder						)
								return vocab







	def __getstate__(					self		:str						)		-> List[str]:
								__UpperCamelCase	:   Union[str, Any]			   =					self.__dict__.copy()
								__UpperCamelCase	:   Optional[Any]			   =					None
								return state







	def __setstate__(					self		:int     ,   a		:List[str]						)		-> int:
								__UpperCamelCase	:   Union[str, Any]			   =					d

								# for backward compatibility
								if not hasattr(self     ,   "sp_model_kwargs"						):
															__UpperCamelCase	:   int			   =					{}

								__UpperCamelCase	:   Any			   =					spm.SentencePieceProcessor(**self.sp_model_kwargs						)
								self.sp_model.Load(self.vocab_file						)







	def    _lowerCamelCase				(					self		:List[Any]     ,   a		:str						)		-> List[str]:
								return self.sp_model.encode(a     ,   out_type=a						)







	def    _lowerCamelCase				(					self		:Optional[int]     ,   a		:Optional[Any]						)		-> str:
								return self.sp_model.piece_to_id(a						)







	def    _lowerCamelCase				(					self		:Dict     ,   a		:Union[str, Any]						)		-> Optional[int]:
								if index < self.sp_model.get_piece_size():
															__UpperCamelCase	:   Optional[int]			   =					self.sp_model.IdToPiece(a						)
								return token







	def    _lowerCamelCase				(					self		:Dict     ,   a		:List[Any]						)		-> Dict:
								__UpperCamelCase	:   Optional[int]			   =					[]
								__UpperCamelCase	:   str			   =					""
								for token in tokens:
															# make sure that special tokens are not decoded using sentencepiece model
															if token in self.all_special_tokens:
																						out_string += self.sp_model.decode(a						) + token
																						__UpperCamelCase	:   List[Any]			   =					[]
															else:
																						current_sub_tokens.append(a						)
								out_string += self.sp_model.decode(a						)
								return out_string.strip()







	def    _lowerCamelCase				(					self		:Optional[Any]     ,   a		:str     ,   a		:Optional[str] = None						)		-> Tuple[str]:
								if not os.path.isdir(a						):
															logger.error(f'Vocabulary path ({save_directory}) should be a directory'						)
															return
								__UpperCamelCase	:   List[Any]			   =					os.path.join(
								    a     ,   (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]						)

								if os.path.abspath(self.vocab_file						) != os.path.abspath(a						) and os.path.isfile(self.vocab_file						):
															copyfile(self.vocab_file     ,   a						)
								elif not os.path.isfile(self.vocab_file						):
															with open(a     ,   "wb"						) as fi:
																						__UpperCamelCase	:   int			   =					self.sp_model.serialized_model_proto()
																						fi.write(a						)

								return (out_vocab_file,)