

"""simple docstring"""




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


__UpperCAmelCase	=			logging.get_logger(__name__)

__UpperCAmelCase	=			{
    '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        __lowercase     (      __lowerCamelCase   ):
  snake_case_			    =    """layoutlmv2"""

  def __init__(					self						:     int   ,A						:     Tuple=30_522   ,A						:     Any=768   ,A						:     Union[str, Any]=12   ,A						:     Optional[int]=12   ,A						:     List[str]=3_072   ,A						:     Optional[int]="gelu"   ,A						:     Dict=0.1   ,A						:     Union[str, Any]=0.1   ,A						:     List[Any]=512   ,A						:     List[Any]=2   ,A						:     int=0.0_2   ,A						:     Any=1e-12   ,A						:     Tuple=0   ,A						:     List[str]=1_024   ,A						:     Union[str, Any]=128   ,A						:     Union[str, Any]=32   ,A						:     Any=True   ,A						:     Optional[Any]=256   ,A						:     Any=64   ,A						:     Optional[int]=True   ,A						:     Tuple=[7, 7, 256]   ,A						:     List[Any]=128   ,A						:     str=128   ,A						:     Tuple=True   ,A						:     Tuple=True   ,A						:     List[Any]=False   ,A						:     str=None   ,**A						:     Optional[Any]   ,):






   '''simple docstring'''
   super().__init__(
       vocab_size=A   ,hidden_size=A   ,num_hidden_layers=A   ,num_attention_heads=A   ,intermediate_size=A   ,hidden_act=A   ,hidden_dropout_prob=A   ,attention_probs_dropout_prob=A   ,max_position_embeddings=A   ,type_vocab_size=A   ,initializer_range=A   ,layer_norm_eps=A   ,pad_token_id=A   ,**A   ,)
   UpperCAmelCase__   :					Tuple   				=   max_ad_position_embeddings
   UpperCAmelCase__   :					str   				=   max_rel_pos
   UpperCAmelCase__   :					List[Any]   				=   rel_pos_bins
   UpperCAmelCase__   :					List[str]   				=   fast_qkv
   UpperCAmelCase__   :					Dict   				=   max_rel_ad_pos
   UpperCAmelCase__   :					Union[str, Any]   				=   rel_ad_pos_bins
   UpperCAmelCase__   :					Dict   				=   convert_sync_batchnorm
   UpperCAmelCase__   :					Tuple   				=   image_feature_pool_shape
   UpperCAmelCase__   :					Union[str, Any]   				=   coordinate_size
   UpperCAmelCase__   :					Dict   				=   shape_size
   UpperCAmelCase__   :					Optional[Any]   				=   has_relative_attention_bias
   UpperCAmelCase__   :					Any   				=   has_spatial_attention_bias
   UpperCAmelCase__   :					Any   				=   has_visual_segment_embedding
   UpperCAmelCase__   :					Any   				=   (
       detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
   )

  @classmethod
  def 				__lowercase    (					self						:     Dict      ):






   '''simple docstring'''
   return {
       "MODEL.MASK_ON": True,
       "MODEL.PIXEL_STD": [5_7.3_7_5, 5_7.1_2_0, 5_8.3_9_5],
       "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": 2_000,
       "MODEL.RPN.PRE_NMS_TOPK_TEST": 1_000,
       "MODEL.RPN.POST_NMS_TOPK_TRAIN": 1_000,
       "MODEL.POST_NMS_TOPK_TEST": 1_000,
       "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]      ):






   '''simple docstring'''
   UpperCAmelCase__   :					Optional[Any]   				=   detectrona.config.get_cfg()
   for k, v in self.detectrona_config_args.items():
    UpperCAmelCase__   :					Optional[int]   				=   k.split("""."""      )
    UpperCAmelCase__   :					str   				=   detectrona_config
    for attribute in attributes[:-1]:
     UpperCAmelCase__   :					Optional[Any]   				=   getattr(A   ,A      )
    setattr(A   ,attributes[-1]   ,A      )

   return detectrona_config








"""simple docstring"""




from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import center_crop, normalize, rescale, resize, to_channel_dimension_format
from ...image_utils import (
    IMAGENET_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
      import PIL


__UpperCAmelCase	=			logging.get_logger(__name__)







class        __lowercase     (      __lowerCamelCase   ):
  snake_case_			    =    ["""pixel_values"""]

  def __init__(					self						:     Tuple   ,A						:     bool = True   ,A						:     Dict[str, int] = None   ,A						:     PILImageResampling = PIL.Image.NEAREST   ,A						:     bool = False   ,A						:     Dict[str, int] = None   ,A						:     Union[int, float] = 1 / 255   ,A						:     bool = False   ,A						:     bool = True   ,A						:     bool = True   ,A						:     Optional[Union[float, List[float]]] = None   ,A						:     Optional[Union[float, List[float]]] = None   ,A						:     bool = True   ,**A						:     List[str]   ,):






   '''simple docstring'''
   super().__init__(**A      )
   UpperCAmelCase__   :					Optional[Any]   				=   size if size is not None else {"""height""": 346, """width""": 346}
   UpperCAmelCase__   :					Union[str, Any]   				=   get_size_dict(A      )
   UpperCAmelCase__   :					Union[str, Any]   				=   crop_size if crop_size is not None else {"""height""": 289, """width""": 289}
   UpperCAmelCase__   :					Optional[Any]   				=   get_size_dict(A   ,param_name="""crop_size"""      )

   UpperCAmelCase__   :					Optional[int]   				=   do_resize
   UpperCAmelCase__   :					Optional[int]   				=   size
   UpperCAmelCase__   :					Optional[int]   				=   resample
   UpperCAmelCase__   :					List[str]   				=   do_center_crop
   UpperCAmelCase__   :					int   				=   crop_size
   UpperCAmelCase__   :					List[Any]   				=   do_rescale
   UpperCAmelCase__   :					List[str]   				=   rescale_factor
   UpperCAmelCase__   :					List[str]   				=   rescale_offset
   UpperCAmelCase__   :					Any   				=   do_normalize
   UpperCAmelCase__   :					Tuple   				=   image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
   UpperCAmelCase__   :					int   				=   image_std if image_std is not None else IMAGENET_STANDARD_STD
   UpperCAmelCase__   :					Optional[int]   				=   include_top

  def 				__lowercase    (					self						:     Tuple   ,A						:     np.ndarray   ,A						:     Dict[str, int]   ,A						:     PILImageResampling = PIL.Image.NEAREST   ,A						:     Optional[Union[str, ChannelDimension]] = None   ,**A						:     Optional[int]   ,):






   '''simple docstring'''
   UpperCAmelCase__   :					List[Any]   				=   get_size_dict(A      )
   if "height" not in size or "width" not in size:
    raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"      )
   return resize(
       A   ,size=(size["""height"""], size["""width"""])   ,resample=A   ,data_format=A   ,**A      )

  def 				__lowercase    (					self						:     Union[str, Any]   ,A						:     np.ndarray   ,A						:     Dict[str, int]   ,A						:     Optional[Union[str, ChannelDimension]] = None   ,**A						:     Union[str, Any]   ,):






   '''simple docstring'''
   UpperCAmelCase__   :					Optional[Any]   				=   get_size_dict(A      )
   if "height" not in size or "width" not in size:
    raise ValueError(f"The size dictionary must have keys 'height' and 'width'. Got {size.keys()}"      )
   return center_crop(A   ,size=(size["""height"""], size["""width"""])   ,data_format=A   ,**A      )

  def 				__lowercase    (					self						:     List[Any]   ,A						:     np.ndarray   ,A						:     Union[int, float]   ,A						:     bool = True   ,A						:     Optional[Union[str, ChannelDimension]] = None   ,**A						:     Any   ,):






   '''simple docstring'''
   if offset:
    UpperCAmelCase__   :					Tuple   				=   (image - 1_2_7.5) * scale
    if data_format is not None:
     UpperCAmelCase__   :					Any   				=   to_channel_dimension_format(A   ,A      )
    UpperCAmelCase__   :					Union[str, Any]   				=   rescaled_image.astype(np.floataa      )
   else:
    UpperCAmelCase__   :					List[str]   				=   rescale(A   ,scale=A   ,data_format=A   ,**A      )
   return rescaled_image

  def 				__lowercase    (					self						:     Optional[Any]   ,A						:     np.ndarray   ,A						:     Union[float, List[float]]   ,A						:     Union[float, List[float]]   ,A						:     Optional[Union[str, ChannelDimension]] = None   ,**A						:     List[Any]   ,):






   '''simple docstring'''
   return normalize(A   ,mean=A   ,std=A   ,data_format=A   ,**A      )




  def 				__lowercase    (					self						:     Optional[int]   ,A						:     ImageInput   ,A						:     bool = None   ,A						:     Dict[str, int] = None   ,A						:     str=None   ,A						:     bool = None   ,A						:     Dict[str, int] = None   ,A						:     bool = None   ,A						:     float = None   ,A						:     bool = None   ,A						:     bool = None   ,A						:     Optional[Union[float, List[float]]] = None   ,A						:     Optional[Union[float, List[float]]] = None   ,A						:     bool = None   ,A						:     Optional[Union[str, TensorType]] = None   ,A						:     ChannelDimension = ChannelDimension.FIRST   ,**A						:     Optional[int]   ,):






   '''simple docstring'''
   UpperCAmelCase__   :					List[str]   				=   do_resize if do_resize is not None else self.do_resize
   UpperCAmelCase__   :					Optional[int]   				=   resample if resample is not None else self.resample
   UpperCAmelCase__   :					List[str]   				=   do_center_crop if do_center_crop is not None else self.do_center_crop
   UpperCAmelCase__   :					List[str]   				=   do_rescale if do_rescale is not None else self.do_rescale
   UpperCAmelCase__   :					Any   				=   rescale_factor if rescale_factor is not None else self.rescale_factor
   UpperCAmelCase__   :					str   				=   rescale_offset if rescale_offset is not None else self.rescale_offset
   UpperCAmelCase__   :					Union[str, Any]   				=   do_normalize if do_normalize is not None else self.do_normalize
   UpperCAmelCase__   :					int   				=   image_mean if image_mean is not None else self.image_mean
   UpperCAmelCase__   :					Any   				=   image_std if image_std is not None else self.image_std
   UpperCAmelCase__   :					List[Any]   				=   include_top if include_top is not None else self.include_top

   UpperCAmelCase__   :					List[Any]   				=   size if size is not None else self.size
   UpperCAmelCase__   :					int   				=   get_size_dict(A      )
   UpperCAmelCase__   :					Any   				=   crop_size if crop_size is not None else self.crop_size
   UpperCAmelCase__   :					str   				=   get_size_dict(A   ,param_name="""crop_size"""      )

   UpperCAmelCase__   :					Any   				=   make_list_of_images(A      )

   if not valid_images(A      ):
    raise ValueError(
        """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
        """torch.Tensor, tf.Tensor or jax.ndarray."""      )

   if do_resize and size is None or resample is None:
    raise ValueError("""Size and resample must be specified if do_resize is True."""      )

   if do_center_crop and crop_size is None:
    raise ValueError("""Crop size must be specified if do_center_crop is True."""      )

   if do_rescale and rescale_factor is None:
    raise ValueError("""Rescale factor must be specified if do_rescale is True."""      )

   if do_normalize and (image_mean is None or image_std is None):
    raise ValueError("""Image mean and std must be specified if do_normalize is True."""      )

   # All transformations expect numpy arrays.
   UpperCAmelCase__   :					List[str]   				=   [to_numpy_array(A      ) for image in images]

   if do_resize:
    UpperCAmelCase__   :					str   				=   [self.resize(image=A   ,size=A   ,resample=A      ) for image in images]

   if do_center_crop:
    UpperCAmelCase__   :					Tuple   				=   [self.center_crop(image=A   ,size=A      ) for image in images]

   if do_rescale:
    UpperCAmelCase__   :					int   				=   [self.rescale(image=A   ,scale=A   ,offset=A      ) for image in images]

   if do_normalize:
    UpperCAmelCase__   :					int   				=   [self.normalize(image=A   ,mean=A   ,std=A      ) for image in images]

   if include_top:
    UpperCAmelCase__   :					Dict   				=   [self.normalize(image=A   ,mean=[0, 0, 0]   ,std=A      ) for image in images]

   UpperCAmelCase__   :					Optional[Any]   				=   [to_channel_dimension_format(A   ,A      ) for image in images]

   UpperCAmelCase__   :					Dict   				=   {"""pixel_values""": images}
   return BatchFeature(data=A   ,tensor_type=A      )





