






"""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   lowerCAmelCase_( SCREAMING_SNAKE_CASE					)					->	Union[str, Any]:
    """simple docstring"""

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







def   lowerCAmelCase_( SCREAMING_SNAKE_CASE					)					->	int:
    """simple docstring"""

    UpperCamelCase__         =    np.max(_outputs ,	axis=-1 ,	keepdims=__UpperCamelCase					)
    UpperCamelCase__         =    np.exp(_outputs - maxes					)
    return shifted_exp / shifted_exp.sum(axis=-1 ,	keepdims=__UpperCamelCase					)
class    __lowerCamelCase    (  SCREAMING_SNAKE_CASE_  ):
   a      :				List[Any] 						="""sigmoid"""
   a      :				Tuple 						="""softmax"""
   a      :				List[str] 						="""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    __lowerCamelCase    (  SCREAMING_SNAKE_CASE_  ):
   a      :				List[str] 						=False
   a      :				Dict 						=ClassificationFunction.NONE

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

       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 ,				snake_case_=None ,				snake_case_=None ,				snake_case_="" ,				**snake_case_      )		->       Dict:
       # Using "" as default argument because we're going to use `top_k=None` in user code to declare
       # "No top_k"
       UpperCamelCase__         =    tokenizer_kwargs

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

       if isinstance(UpperCamelCase__ ,				UpperCamelCase__      ) or top_k is None:
           UpperCamelCase__         =    top_k
           UpperCamelCase__         =    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`.' ,				UpperCamelCase__ ,				)
           if return_all_scores:
               UpperCamelCase__         =    None
           else:
               UpperCamelCase__         =    1

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

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

   def __call__(					self ,				*snake_case_ ,				**snake_case_      )		->       int:
       UpperCamelCase__         =    super().__call__(*UpperCamelCase__ ,				**UpperCamelCase__      )
       # TODO try and retrieve it in a nicer way from _sanitize_parameters.
       UpperCamelCase__         =    '''top_k''' not in kwargs
       if isinstance(args[0] ,				UpperCamelCase__      ) 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 ,				snake_case_ ,				**snake_case_      )		->       Union[str, Any]:
       UpperCamelCase__         =    self.framework
       if isinstance(UpperCamelCase__ ,				UpperCamelCase__      ):
           return self.tokenizer(**UpperCamelCase__ ,				return_tensors=UpperCamelCase__ ,				**UpperCamelCase__      )
       elif isinstance(UpperCamelCase__ ,				UpperCamelCase__      ) and len(UpperCamelCase__      ) == 1 and isinstance(inputs[0] ,				UpperCamelCase__      ) 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=UpperCamelCase__ ,				**UpperCamelCase__      )
       elif isinstance(UpperCamelCase__ ,				UpperCamelCase__      ):
           # 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(UpperCamelCase__ ,				return_tensors=UpperCamelCase__ ,				**UpperCamelCase__      )

   def 						SCREAMING_SNAKE_CASE__ (					self ,				snake_case_      )		->       int:
       return self.model(**UpperCamelCase__      )







   def 						SCREAMING_SNAKE_CASE__ (					self ,				snake_case_ ,				snake_case_=None ,				snake_case_=1 ,				snake_case_=True      )		->       str:
       # `_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__         =    ClassificationFunction.SIGMOID
           elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
               UpperCamelCase__         =    ClassificationFunction.SOFTMAX
           elif hasattr(self.model.config ,				'function_to_apply'      ) and function_to_apply is None:
               UpperCamelCase__         =    self.model.config.function_to_apply
           else:
               UpperCamelCase__         =    ClassificationFunction.NONE

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

       if function_to_apply == ClassificationFunction.SIGMOID:
           UpperCamelCase__         =    sigmoid(UpperCamelCase__      )
       elif function_to_apply == ClassificationFunction.SOFTMAX:
           UpperCamelCase__         =    softmax(UpperCamelCase__      )
       elif function_to_apply == ClassificationFunction.NONE:
           UpperCamelCase__         =    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__         =    [
           {'''label''': self.model.config.idalabel[i], '''score''': score.item()} for i, score in enumerate(UpperCamelCase__      )
       ]
       if not _legacy:
           dict_scores.sort(key=lambda snake_case_      : x["score"] ,				reverse=UpperCamelCase__      )
           if top_k is not None:
               UpperCamelCase__         =    dict_scores[:top_k]
       return dict_scores













"""simple docstring"""





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from packaging import version

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


if TYPE_CHECKING:
  from ...processing_utils import ProcessorMixin
  from ...utils import TensorType


A__					: Any=	logging.get_logger(__name__)

A__					: str=	{
    """microsoft/layoutlmv3-base""": """https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json""",
}
class    __lowerCamelCase    (  _a  ):
   a      :				List[str] 						="""layoutlmv3"""

   def __init__(					self ,				snake_case_=5_0265 ,				snake_case_=768 ,				snake_case_=12 ,				snake_case_=12 ,				snake_case_=3072 ,				snake_case_="gelu" ,				snake_case_=0.1 ,				snake_case_=0.1 ,				snake_case_=512 ,				snake_case_=2 ,				snake_case_=0.02 ,				snake_case_=1E-5 ,				snake_case_=1 ,				snake_case_=0 ,				snake_case_=2 ,				snake_case_=1024 ,				snake_case_=128 ,				snake_case_=128 ,				snake_case_=True ,				snake_case_=32 ,				snake_case_=128 ,				snake_case_=64 ,				snake_case_=256 ,				snake_case_=True ,				snake_case_=True ,				snake_case_=True ,				snake_case_=224 ,				snake_case_=3 ,				snake_case_=16 ,				snake_case_=None ,				**snake_case_ ,				)		->       Union[str, Any]:
       super().__init__(
           vocab_size=snake_case_ ,				hidden_size=snake_case_ ,				num_hidden_layers=snake_case_ ,				num_attention_heads=snake_case_ ,				intermediate_size=snake_case_ ,				hidden_act=snake_case_ ,				hidden_dropout_prob=snake_case_ ,				attention_probs_dropout_prob=snake_case_ ,				max_position_embeddings=snake_case_ ,				type_vocab_size=snake_case_ ,				initializer_range=snake_case_ ,				layer_norm_eps=snake_case_ ,				pad_token_id=snake_case_ ,				bos_token_id=snake_case_ ,				eos_token_id=snake_case_ ,				**snake_case_ ,				)
       UpperCamelCase__         =    max_ad_position_embeddings
       UpperCamelCase__         =    coordinate_size
       UpperCamelCase__         =    shape_size
       UpperCamelCase__         =    has_relative_attention_bias
       UpperCamelCase__         =    rel_pos_bins
       UpperCamelCase__         =    max_rel_pos
       UpperCamelCase__         =    has_spatial_attention_bias
       UpperCamelCase__         =    rel_ad_pos_bins
       UpperCamelCase__         =    max_rel_ad_pos
       UpperCamelCase__         =    text_embed
       UpperCamelCase__         =    visual_embed
       UpperCamelCase__         =    input_size
       UpperCamelCase__         =    num_channels
       UpperCamelCase__         =    patch_size
       UpperCamelCase__         =    classifier_dropout







class    __lowerCamelCase    (  _a  ):
   a      :				Tuple 						=version.parse("""1.12"""  )

   @property
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       Mapping[str, Mapping[int, str]]:
       # The order of inputs is different for question answering and sequence classification
       if self.task in ["question-answering", "sequence-classification"]:
           return OrderedDict(
               [
                   ('input_ids', {0: 'batch', 1: 'sequence'}),
                   ('attention_mask', {0: 'batch', 1: 'sequence'}),
                   ('bbox', {0: 'batch', 1: 'sequence'}),
                   ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
               ]      )
       else:
           return OrderedDict(
               [
                   ('input_ids', {0: 'batch', 1: 'sequence'}),
                   ('bbox', {0: 'batch', 1: 'sequence'}),
                   ('attention_mask', {0: 'batch', 1: 'sequence'}),
                   ('pixel_values', {0: 'batch', 1: 'num_channels'}),
               ]      )

   @property
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       float:
       return 1E-5

   @property
   def 						SCREAMING_SNAKE_CASE__ (					self      )		->       int:
       return 12







   def 						SCREAMING_SNAKE_CASE__ (					self ,				snake_case_ ,				snake_case_ = -1 ,				snake_case_ = -1 ,				snake_case_ = False ,				snake_case_ = None ,				snake_case_ = 3 ,				snake_case_ = 40 ,				snake_case_ = 40 ,				)		->       Mapping[str, Any]:
       setattr(processor.image_processor ,				'apply_ocr' ,				snake_case_      )

       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       UpperCamelCase__         =    compute_effective_axis_dimension(
           snake_case_ ,				fixed_dimension=OnnxConfig.default_fixed_batch ,				num_token_to_add=0      )
       # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
       UpperCamelCase__         =    processor.tokenizer.num_special_tokens_to_add(snake_case_      )
       UpperCamelCase__         =    compute_effective_axis_dimension(
           snake_case_ ,				fixed_dimension=OnnxConfig.default_fixed_sequence ,				num_token_to_add=snake_case_      )
       # Generate dummy inputs according to compute batch and sequence
       UpperCamelCase__         =    [[' '.join([processor.tokenizer.unk_token]      ) * seq_length]] * batch_size

       # Generate dummy bounding boxes
       UpperCamelCase__         =    [[[48, 84, 73, 128]]] * batch_size

       # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
       # batch_size = compute_effective_axis_dimension(batch_size, fixed_dimension=OnnxConfig.default_fixed_batch)
       UpperCamelCase__         =    self._generate_dummy_images(snake_case_ ,				snake_case_ ,				snake_case_ ,				snake_case_      )

       UpperCamelCase__         =    dict(
           processor(
               snake_case_ ,				text=snake_case_ ,				boxes=snake_case_ ,				return_tensors=snake_case_ ,				)      )

       return inputs




