




"""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_	   =    logging.get_logger(__name__)

a_	   =    {
    'microsoft/layoutlmv3-base': 'https://huggingface.co/microsoft/layoutlmv3-base/resolve/main/config.json',
}

class    UpperCAmelCase_  (       snake_case						):
		UpperCamelCase						 ="layoutlmv3"
		def __init__(		self							,		UpperCamelCase_=5_02_65							,		UpperCamelCase_=7_68							,		UpperCamelCase_=12							,		UpperCamelCase_=12							,		UpperCamelCase_=30_72							,		UpperCamelCase_="gelu"							,		UpperCamelCase_=0.1							,		UpperCamelCase_=0.1							,		UpperCamelCase_=5_12							,		UpperCamelCase_=2							,		UpperCamelCase_=0.0_2							,		UpperCamelCase_=1E-5							,		UpperCamelCase_=1							,		UpperCamelCase_=0							,		UpperCamelCase_=2							,		UpperCamelCase_=10_24							,		UpperCamelCase_=1_28							,		UpperCamelCase_=1_28							,		UpperCamelCase_=True							,		UpperCamelCase_=32							,		UpperCamelCase_=1_28							,		UpperCamelCase_=64							,		UpperCamelCase_=2_56							,		UpperCamelCase_=True							,		UpperCamelCase_=True							,		UpperCamelCase_=True							,		UpperCamelCase_=2_24							,		UpperCamelCase_=3							,		UpperCamelCase_=16							,		UpperCamelCase_=None							,		**UpperCamelCase_							,		)		->    int:
					super().__init__(
					    vocab_size=UpperCamelCase_							,		hidden_size=UpperCamelCase_							,		num_hidden_layers=UpperCamelCase_							,		num_attention_heads=UpperCamelCase_							,		intermediate_size=UpperCamelCase_							,		hidden_act=UpperCamelCase_							,		hidden_dropout_prob=UpperCamelCase_							,		attention_probs_dropout_prob=UpperCamelCase_							,		max_position_embeddings=UpperCamelCase_							,		type_vocab_size=UpperCamelCase_							,		initializer_range=UpperCamelCase_							,		layer_norm_eps=UpperCamelCase_							,		pad_token_id=UpperCamelCase_							,		bos_token_id=UpperCamelCase_							,		eos_token_id=UpperCamelCase_							,		**UpperCamelCase_							,		)
					__lowercase       :   str        =    max_ad_position_embeddings
					__lowercase       :   List[str]        =    coordinate_size
					__lowercase       :   Tuple        =    shape_size
					__lowercase       :   List[Any]        =    has_relative_attention_bias
					__lowercase       :   int        =    rel_pos_bins
					__lowercase       :   Tuple        =    max_rel_pos
					__lowercase       :   int        =    has_spatial_attention_bias
					__lowercase       :   List[str]        =    rel_ad_pos_bins
					__lowercase       :   List[Any]        =    max_rel_ad_pos
					__lowercase       :   Tuple        =    text_embed
					__lowercase       :   Dict        =    visual_embed
					__lowercase       :   Any        =    input_size
					__lowercase       :   List[str]        =    num_channels
					__lowercase       :   Any        =    patch_size
					__lowercase       :   int        =    classifier_dropout


class    UpperCAmelCase_  (       snake_case						):
		UpperCamelCase						 =version.parse("1.12"						)
		@property
		def      _lowerCamelCase				(		self    )		->    List[str]:







					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      _lowerCamelCase				(		self    )		->    Union[str, Any]:
					return 1E-5
		@property
		def      _lowerCamelCase				(		self    )		->    Dict:
					return 12
		def      _lowerCamelCase				(		self							,		UpperCamelCase_							,		UpperCamelCase_ = -1							,		UpperCamelCase_ = -1							,		UpperCamelCase_ = False							,		UpperCamelCase_ = None							,		UpperCamelCase_ = 3							,		UpperCamelCase_ = 40							,		UpperCamelCase_ = 40							,		)		->    str:
					setattr(processor.image_processor							,		'''apply_ocr'''							,		UpperCamelCase_    )

					# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
					__lowercase       :   Optional[int]        =    compute_effective_axis_dimension(
					    UpperCamelCase_							,		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
					__lowercase       :   List[Any]        =    processor.tokenizer.num_special_tokens_to_add(UpperCamelCase_    )
					__lowercase       :   Dict        =    compute_effective_axis_dimension(
					    UpperCamelCase_							,		fixed_dimension=OnnxConfig.default_fixed_sequence							,		num_token_to_add=UpperCamelCase_    )
					# Generate dummy inputs according to compute batch and sequence
					__lowercase       :   List[str]        =    [[' '.join([processor.tokenizer.unk_token]    ) * seq_length]] * batch_size

					# Generate dummy bounding boxes
					__lowercase       :   Tuple        =    [[[48, 84, 73, 1_28]]] * 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)
					__lowercase       :   Dict        =    self._generate_dummy_images(UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_							,		UpperCamelCase_    )

					__lowercase       :   int        =    dict(
					    processor(
					        UpperCamelCase_							,		text=UpperCamelCase_							,		boxes=UpperCamelCase_							,		return_tensors=UpperCamelCase_							,		)    )

					return inputs





from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
					from PIL import Image

					from ..image_utils import load_image

if is_tf_available():
					import tensorflow as tf

					from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
					from ..tf_utils import stable_softmax

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

lowerCamelCase__          =		logging.get_logger(__name__)







@add_end_docstrings(__magic_name__	)
class      A__							(     __magic_name__	):






				def __init__(						self					:      int    ,     *a					:      Dict    ,     **a					:      Union[str, Any]   ):






							'''simple docstring'''







							super().__init__(*a    ,     **a   )
							requires_backends(self    ,     'vision'   )
							self.check_model_type(
							    TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
							    if self.framework == 'tf'
							    else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING   )






				def 							_lowerCamelCase		(						self					:      Dict    ,     a					:      List[str]=None   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Any         =		{}
							if top_k is not None:
										lowerCAmelCase__      :      Tuple         =		top_k
							return {}, {}, postprocess_params






				def __call__(						self					:      Any    ,     a					:      Union[str, List[str], "Image.Image", List["Image.Image"]]    ,     **a					:      List[Any]   ):






							'''simple docstring'''







							return super().__call__(a    ,     **a   )






				def 							_lowerCamelCase		(						self					:      Any    ,     a					:      Optional[Any]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[Any]         =		load_image(a   )
							lowerCAmelCase__      :      Optional[int]         =		self.image_processor(images=a    ,     return_tensors=self.framework   )
							return model_inputs






				def 							_lowerCamelCase		(						self					:      Optional[int]    ,     a					:      List[str]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Optional[Any]         =		self.model(**a   )
							return model_outputs






				def 							_lowerCamelCase		(						self					:      Optional[Any]    ,     a					:      List[Any]    ,     a					:      List[Any]=5   ):






							'''simple docstring'''







							if top_k > self.model.config.num_labels:
										lowerCAmelCase__      :      Optional[int]         =		self.model.config.num_labels

							if self.framework == "pt":
										lowerCAmelCase__      :      List[Any]         =		model_outputs.logits.softmax(-1   )[0]
										lowerCAmelCase__      ,				lowerCAmelCase__      :      Optional[int]         =		probs.topk(a   )
							elif self.framework == "tf":
										lowerCAmelCase__      :      Any         =		stable_softmax(model_outputs.logits    ,     axis=-1   )[0]
										lowerCAmelCase__      :      Any         =		tf.math.top_k(a    ,     k=a   )
										lowerCAmelCase__      ,				lowerCAmelCase__      :      int         =		topk.values.numpy(), topk.indices.numpy()
							else:
										raise ValueError(f'''Unsupported framework: {self.framework}'''   )

							lowerCAmelCase__      :      List[Any]         =		scores.tolist()
							lowerCAmelCase__      :      List[str]         =		ids.tolist()
							return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(a    ,     a   )]