
from ...configuration_utils import PretrainedConfig
from ...utils import is_detectrona_available, logging


__lowerCAmelCase      :					int   	=       logging.get_logger(__name__)

__lowerCAmelCase      :					Union[str, Any]   	=       {
    "layoutlmv2-base-uncased": "https://huggingface.co/microsoft/layoutlmv2-base-uncased/resolve/main/config.json",
    "layoutlmv2-large-uncased": "https://huggingface.co/microsoft/layoutlmv2-large-uncased/resolve/main/config.json",
    # See all LayoutLMv2 models at https://huggingface.co/models?filter=layoutlmv2
}

# soft dependency
if is_detectrona_available():
				import detectrona




class 	UpperCAmelCase_      (			lowerCAmelCase_					):


		'''simple docstring'''







		a__   	=		"""layoutlmv2"""
		def __init__(			self      :			int      ,							UpperCamelCase__      :			Optional[Any]=3_0522      ,							UpperCamelCase__      :			Union[str, Any]=768      ,							UpperCamelCase__      :			str=12      ,							UpperCamelCase__      :			Dict=12      ,							UpperCamelCase__      :			int=3072      ,							UpperCamelCase__      :			List[str]="gelu"      ,							UpperCamelCase__      :			Union[str, Any]=0.1      ,							UpperCamelCase__      :			List[str]=0.1      ,							UpperCamelCase__      :			Union[str, Any]=512      ,							UpperCamelCase__      :			str=2      ,							UpperCamelCase__      :			Any=0.02      ,							UpperCamelCase__      :			Optional[Any]=1E-12      ,							UpperCamelCase__      :			Optional[Any]=0      ,							UpperCamelCase__      :			str=1024      ,							UpperCamelCase__      :			Union[str, Any]=128      ,							UpperCamelCase__      :			int=32      ,							UpperCamelCase__      :			int=True      ,							UpperCamelCase__      :			Optional[Any]=256      ,							UpperCamelCase__      :			List[Any]=64      ,							UpperCamelCase__      :			int=True      ,							UpperCamelCase__      :			Any=[7, 7, 256]      ,							UpperCamelCase__      :			Union[str, Any]=128      ,							UpperCamelCase__      :			Dict=128      ,							UpperCamelCase__      :			Union[str, Any]=True      ,							UpperCamelCase__      :			List[str]=True      ,							UpperCamelCase__      :			Union[str, Any]=False      ,							UpperCamelCase__      :			Optional[int]=None      ,							**UpperCamelCase__      :			Optional[int]      ,							)      ->     List[Any]:







				"""simple docstring"""






				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      ,							**_snake_case      ,							)
				__magic_name__    					=	max_ad_position_embeddings
				__magic_name__    					=	max_rel_pos
				__magic_name__    					=	rel_pos_bins
				__magic_name__    					=	fast_qkv
				__magic_name__    					=	max_rel_ad_pos
				__magic_name__    					=	rel_ad_pos_bins
				__magic_name__    					=	convert_sync_batchnorm
				__magic_name__    					=	image_feature_pool_shape
				__magic_name__    					=	coordinate_size
				__magic_name__    					=	shape_size
				__magic_name__    					=	has_relative_attention_bias
				__magic_name__    					=	has_spatial_attention_bias
				__magic_name__    					=	has_visual_segment_embedding
				__magic_name__    					=	(
				    detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
				)
		@classmethod
		def 							_lowercase							(			self      :			Any   )      ->     Any:







				"""simple docstring"""






				return {
				    "MODEL.MASK_ON": True,
				    "MODEL.PIXEL_STD": [57.375, 57.120, 58.395],
				    "MODEL.BACKBONE.NAME": "build_resnet_fpn_backbone",
				    "MODEL.FPN.IN_FEATURES": ["res2", "res3", "res4", "res5"],
				    "MODEL.ANCHOR_GENERATOR.SIZES": [[32], [64], [128], [256], [512]],
				    "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
				    "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 2000,
				    "MODEL.RPN.PRE_NMS_TOPK_TEST": 1000,
				    "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1000,
				    "MODEL.POST_NMS_TOPK_TEST": 1000,
				    "MODEL.ROI_HEADS.NAME": "StandardROIHeads",
				    "MODEL.ROI_HEADS.NUM_CLASSES": 5,
				    "MODEL.ROI_HEADS.IN_FEATURES": ["p2", "p3", "p4", "p5"],
				    "MODEL.ROI_BOX_HEAD.NAME": "FastRCNNConvFCHead",
				    "MODEL.ROI_BOX_HEAD.NUM_FC": 2,
				    "MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION": 14,
				    "MODEL.ROI_MASK_HEAD.NAME": "MaskRCNNConvUpsampleHead",
				    "MODEL.ROI_MASK_HEAD.NUM_CONV": 4,
				    "MODEL.ROI_MASK_HEAD.POOLER_RESOLUTION": 7,
				    "MODEL.RESNETS.DEPTH": 101,
				    "MODEL.RESNETS.SIZES": [[32], [64], [128], [256], [512]],
				    "MODEL.RESNETS.ASPECT_RATIOS": [[0.5, 1.0, 2.0]],
				    "MODEL.RESNETS.OUT_FEATURES": ["res2", "res3", "res4", "res5"],
				    "MODEL.RESNETS.NUM_GROUPS": 32,
				    "MODEL.RESNETS.WIDTH_PER_GROUP": 8,
				    "MODEL.RESNETS.STRIDE_IN_1X1": False,
				}





		def 							_lowercase							(			self      :			List[str]   )      ->     Any:







				"""simple docstring"""






				__magic_name__    					=	detectrona.config.get_cfg()
				for k, v in self.detectrona_config_args.items():
						__magic_name__    					=	k.split("""."""   )
						__magic_name__    					=	detectrona_config
						for attribute in attributes[:-1]:
								__magic_name__    					=	getattr(_snake_case      ,							_snake_case   )
						setattr(_snake_case      ,							attributes[-1]      ,							_snake_case   )

				return detectrona_config



import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType




class 	UpperCAmelCase_      (			_A					):


  '''simple docstring'''







  a__   	=		["""image_processor""", """tokenizer"""]
  a__   	=		"""LayoutLMv2ImageProcessor"""
  a__   	=		("""LayoutLMv2Tokenizer""", """LayoutLMv2TokenizerFast""")
  def __init__(			self      :			int      ,							UpperCamelCase__      :			Dict=None      ,							UpperCamelCase__      :			int=None      ,							**UpperCamelCase__      :			str   )      ->     Union[str, Any]:







    """simple docstring"""






    __magic_name__    					=	None
    if "feature_extractor" in kwargs:
      warnings.warn(
          """The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
          """ instead."""      ,							UpperCamelCase__      ,							)
      __magic_name__    					=	kwargs.pop("""feature_extractor"""   )

    __magic_name__    					=	image_processor if image_processor is not None else feature_extractor
    if image_processor is None:
      raise ValueError("""You need to specify an `image_processor`."""   )
    if tokenizer is None:
      raise ValueError("""You need to specify a `tokenizer`."""   )

    super().__init__(UpperCamelCase__      ,							UpperCamelCase__   )
  def __call__(			self      :			List[str]      ,							UpperCamelCase__      :			Union[str, Any]      ,							UpperCamelCase__      :			Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None      ,							UpperCamelCase__      :			Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None      ,							UpperCamelCase__      :			Union[List[List[int]], List[List[List[int]]]] = None      ,							UpperCamelCase__      :			Optional[Union[List[int], List[List[int]]]] = None      ,							UpperCamelCase__      :			bool = True      ,							UpperCamelCase__      :			Union[bool, str, PaddingStrategy] = False      ,							UpperCamelCase__      :			Union[bool, str, TruncationStrategy] = False      ,							UpperCamelCase__      :			Optional[int] = None      ,							UpperCamelCase__      :			int = 0      ,							UpperCamelCase__      :			Optional[int] = None      ,							UpperCamelCase__      :			Optional[bool] = None      ,							UpperCamelCase__      :			Optional[bool] = None      ,							UpperCamelCase__      :			bool = False      ,							UpperCamelCase__      :			bool = False      ,							UpperCamelCase__      :			bool = False      ,							UpperCamelCase__      :			bool = False      ,							UpperCamelCase__      :			bool = True      ,							UpperCamelCase__      :			Optional[Union[str, TensorType]] = None      ,							**UpperCamelCase__      :			Union[str, Any]      ,							)      ->     BatchEncoding:







    """simple docstring"""






    if self.image_processor.apply_ocr and (boxes is not None):
      raise ValueError(
          """You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True."""   )

    if self.image_processor.apply_ocr and (word_labels is not None):
      raise ValueError(
          """You cannot provide word labels if you initialized the image processor with apply_ocr set to True."""   )

    if return_overflowing_tokens is True and return_offsets_mapping is False:
      raise ValueError("""You cannot return overflowing tokens without returning the offsets mapping."""   )

    # first, apply the image processor
    __magic_name__    					=	self.image_processor(images=UpperCamelCase__      ,							return_tensors=UpperCamelCase__   )

    # second, apply the tokenizer
    if text is not None and self.image_processor.apply_ocr and text_pair is None:
      if isinstance(UpperCamelCase__      ,							UpperCamelCase__   ):
        __magic_name__    					=	[text]  # add batch dimension (as the image processor always adds a batch dimension)
      __magic_name__    					=	features["""words"""]

    __magic_name__    					=	self.tokenizer(
        text=text if text is not None else features["""words"""]      ,							text_pair=text_pair if text_pair is not None else None      ,							boxes=boxes if boxes is not None else features["""boxes"""]      ,							word_labels=UpperCamelCase__      ,							add_special_tokens=UpperCamelCase__      ,							padding=UpperCamelCase__      ,							truncation=UpperCamelCase__      ,							max_length=UpperCamelCase__      ,							stride=UpperCamelCase__      ,							pad_to_multiple_of=UpperCamelCase__      ,							return_token_type_ids=UpperCamelCase__      ,							return_attention_mask=UpperCamelCase__      ,							return_overflowing_tokens=UpperCamelCase__      ,							return_special_tokens_mask=UpperCamelCase__      ,							return_offsets_mapping=UpperCamelCase__      ,							return_length=UpperCamelCase__      ,							verbose=UpperCamelCase__      ,							return_tensors=UpperCamelCase__      ,							**UpperCamelCase__      ,							)

    # add pixel values
    __magic_name__    					=	features.pop("""pixel_values"""   )
    if return_overflowing_tokens is True:
      __magic_name__    					=	self.get_overflowing_images(UpperCamelCase__      ,							encoded_inputs["""overflow_to_sample_mapping"""]   )
    __magic_name__    					=	images

    return encoded_inputs
  def 							_lowercase							(			self      :			Optional[int]      ,							UpperCamelCase__      :			Tuple      ,							UpperCamelCase__      :			Optional[int]   )      ->     Any:







    """simple docstring"""






    __magic_name__    					=	[]
    for sample_idx in overflow_to_sample_mapping:
      images_with_overflow.append(images[sample_idx]   )

    if len(UpperCamelCase__   ) != len(UpperCamelCase__   ):
      raise ValueError(
          """Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got"""
          F''' {len(UpperCamelCase__   )} and {len(UpperCamelCase__   )}'''   )

    return images_with_overflow
  def 							_lowercase							(			self      :			Optional[int]      ,							*UpperCamelCase__      :			str      ,							**UpperCamelCase__      :			int   )      ->     Union[str, Any]:







    """simple docstring"""






    return self.tokenizer.batch_decode(*UpperCamelCase__      ,							**UpperCamelCase__   )
  def 							_lowercase							(			self      :			Dict      ,							*UpperCamelCase__      :			Optional[int]      ,							**UpperCamelCase__      :			str   )      ->     str:







    """simple docstring"""






    return self.tokenizer.decode(*UpperCamelCase__      ,							**UpperCamelCase__   )
  @property
  def 							_lowercase							(			self      :			Optional[Any]   )      ->     Optional[int]:







    """simple docstring"""






    return ["input_ids", "bbox", "token_type_ids", "attention_mask", "image"]
  @property
  def 							_lowercase							(			self      :			Union[str, Any]   )      ->     Optional[int]:







    """simple docstring"""






    warnings.warn(
        """`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."""      ,							UpperCamelCase__      ,							)
    return self.image_processor_class





  @property
  def 							_lowercase							(			self      :			Union[str, Any]   )      ->     Dict:







    """simple docstring"""






    warnings.warn(
        """`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."""      ,							UpperCamelCase__      ,							)
    return self.image_processor

