


'''simple docstring'''




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_  (       A      ):
   '''simple docstring'''





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


def    UpperCAmelCase_  (       A      ):
   '''simple docstring'''





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







class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: List[Any]							  =		"""sigmoid"""
 __lowerCAmelCase						: List[str]							  =		"""softmax"""
 __lowerCAmelCase						: int							  =		"""none"""







@add_end_docstrings(
    snake_case__			,							r"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """			,							)
class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: str							  =		False
 __lowerCAmelCase						: str							  =		ClassificationFunction.NONE




 def __init__(    self		,      **lowerCamelCase_      )      ->    List[Any]:
    super().__init__(**lowerCamelCase_      )

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




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

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

    if isinstance(lowerCamelCase_		,      lowerCamelCase_      ) or top_k is None:
       _a					:  Dict						=  top_k
       _a					:  Optional[int]						=  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					:  Union[str, Any]						=  None
       else:
          _a					:  Union[str, Any]						=  1

    if isinstance(lowerCamelCase_		,      lowerCamelCase_      ):
       _a					:  List[str]						=  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_      )      ->    Union[str, Any]:
    _a					:  Dict						=  super().__call__(*lowerCamelCase_		,      **lowerCamelCase_      )
    # TODO try and retrieve it in a nicer way from _sanitize_parameters.
    _a					:  List[Any]						=  '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   __UpperCamelCase   (    self		,      lowerCamelCase_		,      **lowerCamelCase_      )      ->    Dict[str, GenericTensor]:
    _a					:  List[Any]						=  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   __UpperCamelCase   (    self		,      lowerCamelCase_      )      ->    Tuple:
    return self.model(**lowerCamelCase_      )




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

    _a					:  Optional[int]						=  model_outputs['logits'][0]
    _a					:  Dict						=  outputs.numpy()

    if function_to_apply == ClassificationFunction.SIGMOID:
       _a					:  List[Any]						=  sigmoid(lowerCamelCase_      )
    elif function_to_apply == ClassificationFunction.SOFTMAX:
       _a					:  Tuple						=  softmax(lowerCamelCase_      )
    elif function_to_apply == ClassificationFunction.NONE:
       _a					:  Optional[Any]						=  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					:  str						=  [
        {'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					:  Optional[Any]						=  dict_scores[:top_k]
    return dict_scores






'''simple docstring'''




import warnings
from collections import OrderedDict
from typing import Mapping

from packaging import version

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


UpperCAmelCase_      :		int          =		logging.get_logger(__name__)

UpperCAmelCase_      :		Optional[Any]          =		{
    "nvidia/segformer-b0-finetuned-ade-512-512": (
        "https://huggingface.co/nvidia/segformer-b0-finetuned-ade-512-512/resolve/main/config.json"
    ),
    # See all SegFormer models at https://huggingface.co/models?filter=segformer
}







class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: List[Any]							  =		"""segformer"""




 def __init__(    self		,      lowerCamelCase_=3		,      lowerCamelCase_=4		,      lowerCamelCase_=[2, 2, 2, 2]		,      lowerCamelCase_=[8, 4, 2, 1]		,      lowerCamelCase_=[3_2, 6_4, 1_6_0, 2_5_6]		,      lowerCamelCase_=[7, 3, 3, 3]		,      lowerCamelCase_=[4, 2, 2, 2]		,      lowerCamelCase_=[1, 2, 5, 8]		,      lowerCamelCase_=[4, 4, 4, 4]		,      lowerCamelCase_="gelu"		,      lowerCamelCase_=0.0		,      lowerCamelCase_=0.0		,      lowerCamelCase_=0.1		,      lowerCamelCase_=0.02		,      lowerCamelCase_=0.1		,      lowerCamelCase_=1e-6		,      lowerCamelCase_=2_5_6		,      lowerCamelCase_=2_5_5		,      **lowerCamelCase_		,      )      ->    Union[str, Any]:
    super().__init__(**lowerCamelCase_      )

    if "reshape_last_stage" in kwargs and kwargs["reshape_last_stage"] is False:
       warnings.warn(
           'Reshape_last_stage is set to False in this config. This argument is deprecated and will soon be'
           ' removed, as the behaviour will default to that of reshape_last_stage = True.'		,      lowerCamelCase_		,      )

    _a					:  Union[str, Any]						=  num_channels
    _a					:  Any						=  num_encoder_blocks
    _a					:  Union[str, Any]						=  depths
    _a					:  int						=  sr_ratios
    _a					:  List[str]						=  hidden_sizes
    _a					:  Tuple						=  patch_sizes
    _a					:  Any						=  strides
    _a					:  List[Any]						=  mlp_ratios
    _a					:  str						=  num_attention_heads
    _a					:  str						=  hidden_act
    _a					:  List[Any]						=  hidden_dropout_prob
    _a					:  int						=  attention_probs_dropout_prob
    _a					:  Any						=  classifier_dropout_prob
    _a					:  Optional[Any]						=  initializer_range
    _a					:  int						=  drop_path_rate
    _a					:  int						=  layer_norm_eps
    _a					:  Optional[Any]						=  decoder_hidden_size
    _a					:  int						=  kwargs.get('reshape_last_stage'		,      lowerCamelCase_      )
    _a					:  str						=  semantic_loss_ignore_index







class 					a			(				snake_case__  ):
 '''simple docstring'''




 __lowerCAmelCase						: Any							  =		version.parse("""1.11"""  )




 @property
 def   __UpperCamelCase   (    self      )      ->    Mapping[str, Mapping[int, str]]:
    return OrderedDict(
        [
            ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
        ]      )




 @property
 def   __UpperCamelCase   (    self      )      ->    float:
    return 1e-4




 @property
 def   __UpperCamelCase   (    self      )      ->    int:
    return 1_2


