



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      __UpperCamelCase     (  _lowerCAmelCase		)	->  Optional[Any]:



    """simple docstring"""






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




def      __UpperCamelCase     (  _lowerCAmelCase		)	->  Union[str, Any]:



    """simple docstring"""






    A			:	List[str]										=       np.max(_outputs				,					axis=-1				,					keepdims=_lowerCAmelCase		)
    A			:	int										=       np.exp(_outputs - maxes		)
    return shifted_exp / shifted_exp.sum(axis=-1				,					keepdims=_lowerCAmelCase		)






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			str =				"sigmoid"
    __lowerCamelCase      :			int =				"softmax"
    __lowerCamelCase      :			Optional[int] =				"none"






@add_end_docstrings(
    SCREAMING_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 SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			str =				False
    __lowerCamelCase      :			str =				ClassificationFunction.NONE






    def __init__(	self,		**lowerCamelCase__		):
        super().__init__(**lowerCamelCase__		)

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






    def       _lowerCAmelCase (	self,		lowerCamelCase__=None,		lowerCamelCase__=None,		lowerCamelCase__="",		**lowerCamelCase__		):
        # Using "" as default argument because we're going to use `top_k=None` in user code to declare
        # "No top_k"
        A			:	Any										=       tokenizer_kwargs

        A			:	Dict										=       {}
        if hasattr(self.model.config,		"""return_all_scores"""		) and return_all_scores is None:
            A			:	Any										=       self.model.config.return_all_scores

        if isinstance(lowerCamelCase__,		lowerCamelCase__		) or top_k is None:
            A			:	List[str]										=       top_k
            A			:	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`.""",		lowerCamelCase__,		)
            if return_all_scores:
                A			:	Dict										=       None
            else:
                A			:	Optional[Any]										=       1

        if isinstance(lowerCamelCase__,		lowerCamelCase__		):
            A			:	List[Any]										=       ClassificationFunction[function_to_apply.upper()]

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






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






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		**lowerCamelCase__		):
        A			:	str										=       self.framework
        if isinstance(lowerCamelCase__,		lowerCamelCase__		):
            return self.tokenizer(**lowerCamelCase__,		return_tensors=lowerCamelCase__,		**lowerCamelCase__		)
        elif isinstance(lowerCamelCase__,		lowerCamelCase__		) and len(lowerCamelCase__		) == 1 and isinstance(inputs[0],		lowerCamelCase__		) 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=lowerCamelCase__,		**lowerCamelCase__		)
        elif isinstance(lowerCamelCase__,		lowerCamelCase__		):
            # 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(lowerCamelCase__,		return_tensors=lowerCamelCase__,		**lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__		):
        return self.model(**lowerCamelCase__		)






    def       _lowerCAmelCase (	self,		lowerCamelCase__,		lowerCamelCase__=None,		lowerCamelCase__=1,		lowerCamelCase__=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:
                A			:	List[Any]										=       ClassificationFunction.SIGMOID
            elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                A			:	Dict										=       ClassificationFunction.SOFTMAX
            elif hasattr(self.model.config,		"""function_to_apply"""		) and function_to_apply is None:
                A			:	Optional[Any]										=       self.model.config.function_to_apply
            else:
                A			:	Any										=       ClassificationFunction.NONE

        A			:	Dict										=       model_outputs["""logits"""][0]
        A			:	Optional[int]										=       outputs.numpy()

        if function_to_apply == ClassificationFunction.SIGMOID:
            A			:	Dict										=       sigmoid(lowerCamelCase__		)
        elif function_to_apply == ClassificationFunction.SOFTMAX:
            A			:	List[Any]										=       softmax(lowerCamelCase__		)
        elif function_to_apply == ClassificationFunction.NONE:
            A			:	int										=       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()}

        A			:	Union[str, Any]										=       [
            {"""label""": self.model.config.idalabel[i], """score""": score.item()} for i, score in enumerate(lowerCamelCase__		)
        ]
        if not _legacy:
            dict_scores.sort(key=lambda lowerCamelCase__		: x["score"],		reverse=lowerCamelCase__		)
            if top_k is not None:
                A			:	List[Any]										=       dict_scores[:top_k]
        return dict_scores







from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


SCREAMING_SNAKE_CASE_:int					=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_:Any					=						{
    """roberta-base""": """https://huggingface.co/roberta-base/resolve/main/config.json""",
    """roberta-large""": """https://huggingface.co/roberta-large/resolve/main/config.json""",
    """roberta-large-mnli""": """https://huggingface.co/roberta-large-mnli/resolve/main/config.json""",
    """distilroberta-base""": """https://huggingface.co/distilroberta-base/resolve/main/config.json""",
    """roberta-base-openai-detector""": """https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json""",
    """roberta-large-openai-detector""": """https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json""",
}






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    __lowerCamelCase      :			Any =				"roberta"






    def __init__(	self,		lowerCamelCase__=5_0265,		lowerCamelCase__=768,		lowerCamelCase__=12,		lowerCamelCase__=12,		lowerCamelCase__=3072,		lowerCamelCase__="gelu",		lowerCamelCase__=0.1,		lowerCamelCase__=0.1,		lowerCamelCase__=512,		lowerCamelCase__=2,		lowerCamelCase__=0.02,		lowerCamelCase__=1e-12,		lowerCamelCase__=1,		lowerCamelCase__=0,		lowerCamelCase__=2,		lowerCamelCase__="absolute",		lowerCamelCase__=True,		lowerCamelCase__=None,		**lowerCamelCase__,		):
        super().__init__(pad_token_id=lowerCamelCase__,		bos_token_id=lowerCamelCase__,		eos_token_id=lowerCamelCase__,		**lowerCamelCase__		)

        A			:	List[str]										=       vocab_size
        A			:	List[Any]										=       hidden_size
        A			:	List[Any]										=       num_hidden_layers
        A			:	Optional[Any]										=       num_attention_heads
        A			:	Union[str, Any]										=       hidden_act
        A			:	Union[str, Any]										=       intermediate_size
        A			:	Optional[int]										=       hidden_dropout_prob
        A			:	List[str]										=       attention_probs_dropout_prob
        A			:	int										=       max_position_embeddings
        A			:	List[str]										=       type_vocab_size
        A			:	List[str]										=       initializer_range
        A			:	Dict										=       layer_norm_eps
        A			:	Optional[int]										=       position_embedding_type
        A			:	Any										=       use_cache
        A			:	Optional[int]										=       classifier_dropout






class SCREAMING_SNAKE_CASE__					(		SCREAMING_SNAKE_CASE__   ):




    '''simple docstring'''






    @property
    def       _lowerCAmelCase (	self		):
        if self.task == "multiple-choice":
            A			:	Optional[Any]										=       {0: """batch""", 1: """choice""", 2: """sequence"""}
        else:
            A			:	int										=       {0: """batch""", 1: """sequence"""}
        return OrderedDict(
            [
                ("""input_ids""", dynamic_axis),
                ("""attention_mask""", dynamic_axis),
            ]		)


