


"""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,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


A				:   Dict		= logging.get_logger(__name__)


if is_vision_available():
    import PIL







class       _lowercase			(							lowercase__):


       """simple docstring"""




       A__ 						=      ["pixel_values"]





       def __init__(       self							:      List[Any] ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Dict[str, int] = None ,				__lowerCamelCase							:      PILImageResampling = PILImageResampling.BICUBIC ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Dict[str, int] = None ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Union[int, float] = 1 / 255 ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Optional[Union[float, List[float]]] = None ,				__lowerCamelCase							:      Optional[Union[float, List[float]]] = None ,				__lowerCamelCase							:      bool = True ,				**__lowerCamelCase							:      Any ,				):


             '''simple docstring'''



             super().__init__(**__lowerCamelCase	)
             lowerCamelCase__		:    Any   =  size if size is not None else {"shortest_edge": 224}
             lowerCamelCase__		:    List[str]   =  get_size_dict(__lowerCamelCase ,				default_to_square=__lowerCamelCase	)
             lowerCamelCase__		:    List[Any]   =  crop_size if crop_size is not None else {"height": 224, "width": 224}
             lowerCamelCase__		:    Union[str, Any]   =  get_size_dict(__lowerCamelCase	)

             lowerCamelCase__		:    List[Any]   =  do_resize
             lowerCamelCase__		:    Any   =  size
             lowerCamelCase__		:    int   =  resample
             lowerCamelCase__		:    Dict   =  do_center_crop
             lowerCamelCase__		:    Optional[int]   =  crop_size
             lowerCamelCase__		:    List[Any]   =  do_rescale
             lowerCamelCase__		:    Optional[Any]   =  rescale_factor
             lowerCamelCase__		:    Dict   =  do_normalize
             lowerCamelCase__		:    Dict   =  image_mean if image_mean is not None else OPENAI_CLIP_MEAN
             lowerCamelCase__		:    List[Any]   =  image_std if image_std is not None else OPENAI_CLIP_STD
             lowerCamelCase__		:    Any   =  do_convert_rgb





       def 						lowerCAmelCase					(       self							:      Any ,				__lowerCamelCase							:      np.ndarray ,				__lowerCamelCase							:      Dict[str, int] ,				__lowerCamelCase							:      PILImageResampling = PILImageResampling.BICUBIC ,				__lowerCamelCase							:      Optional[Union[str, ChannelDimension]] = None ,				**__lowerCamelCase							:      Optional[Any] ,				):


             '''simple docstring'''



             lowerCamelCase__		:    List[str]   =  get_size_dict(__lowerCamelCase ,				default_to_square=__lowerCamelCase	)
             lowerCamelCase__		:    List[Any]   =  get_resize_output_image_size(
                 __lowerCamelCase ,				size=(size["height"], size["width"]) ,				default_to_square=__lowerCamelCase	)
             return resize(__lowerCamelCase ,				size=__lowerCamelCase ,				resample=__lowerCamelCase ,				data_format=__lowerCamelCase ,				**__lowerCamelCase	)





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


             '''simple docstring'''



             lowerCamelCase__		:    List[str]   =  get_size_dict(__lowerCamelCase	)
             return center_crop(__lowerCamelCase ,				size=(size["height"], size["width"]) ,				data_format=__lowerCamelCase ,				**__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      int ,				__lowerCamelCase							:      np.ndarray ,				__lowerCamelCase							:      Union[int, float] ,				__lowerCamelCase							:      Optional[Union[str, ChannelDimension]] = None ,				**__lowerCamelCase							:      Optional[int] ,				):


             '''simple docstring'''



             return rescale(__lowerCamelCase ,				scale=__lowerCamelCase ,				data_format=__lowerCamelCase ,				**__lowerCamelCase	)





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


             '''simple docstring'''



             return normalize(__lowerCamelCase ,				mean=__lowerCamelCase ,				std=__lowerCamelCase ,				data_format=__lowerCamelCase ,				**__lowerCamelCase	)





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


             '''simple docstring'''



             lowerCamelCase__		:    Tuple   =  do_resize if do_resize is not None else self.do_resize
             lowerCamelCase__		:    Union[str, Any]   =  size if size is not None else self.size
             lowerCamelCase__		:    Tuple   =  get_size_dict(__lowerCamelCase ,				default_to_square=__lowerCamelCase	)
             lowerCamelCase__		:    Dict   =  resample if resample is not None else self.resample
             lowerCamelCase__		:    List[Any]   =  do_center_crop if do_center_crop is not None else self.do_center_crop
             lowerCamelCase__		:    str   =  crop_size if crop_size is not None else self.crop_size
             lowerCamelCase__		:    Optional[Any]   =  get_size_dict(__lowerCamelCase	)
             lowerCamelCase__		:    Dict   =  do_rescale if do_rescale is not None else self.do_rescale
             lowerCamelCase__		:    List[Any]   =  rescale_factor if rescale_factor is not None else self.rescale_factor
             lowerCamelCase__		:    int   =  do_normalize if do_normalize is not None else self.do_normalize
             lowerCamelCase__		:    List[Any]   =  image_mean if image_mean is not None else self.image_mean
             lowerCamelCase__		:    List[Any]   =  image_std if image_std is not None else self.image_std
             lowerCamelCase__		:    List[Any]   =  do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

             lowerCamelCase__		:    Dict   =  make_list_of_images(__lowerCamelCase	)

             if not valid_images(__lowerCamelCase	):
                   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:
                   raise ValueError("Size 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."	)

             # PIL RGBA images are converted to RGB
             if do_convert_rgb:
                   lowerCamelCase__		:    int   =  [convert_to_rgb(__lowerCamelCase	) for image in images]

             # All transformations expect numpy arrays.
             lowerCamelCase__		:    Union[str, Any]   =  [to_numpy_array(__lowerCamelCase	) for image in images]

             if do_resize:
                   lowerCamelCase__		:    Any   =  [self.resize(image=__lowerCamelCase ,				size=__lowerCamelCase ,				resample=__lowerCamelCase	) for image in images]

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

             if do_rescale:
                   lowerCamelCase__		:    Tuple   =  [self.rescale(image=__lowerCamelCase ,				scale=__lowerCamelCase	) for image in images]

             if do_normalize:
                   lowerCamelCase__		:    Any   =  [self.normalize(image=__lowerCamelCase ,				mean=__lowerCamelCase ,				std=__lowerCamelCase	) for image in images]

             lowerCamelCase__		:    Optional[int]   =  [to_channel_dimension_format(__lowerCamelCase ,				__lowerCamelCase	) for image in images]

             lowerCamelCase__		:    Union[str, Any]   =  {"pixel_values": images}
             return BatchFeature(data=__lowerCamelCase ,				tensor_type=__lowerCamelCase	)






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


A				:   int		= logging.get_logger(__name__)

A				:   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       _lowercase			(							lowercase__):


       """simple docstring"""




       A__ 						=      "layoutlmv2"





       def __init__(       self							:      Union[str, Any] ,				__lowerCamelCase							:      int=30522 ,				__lowerCamelCase							:      List[Any]=768 ,				__lowerCamelCase							:      Any=12 ,				__lowerCamelCase							:      List[Any]=12 ,				__lowerCamelCase							:      Optional[Any]=3072 ,				__lowerCamelCase							:      List[Any]="gelu" ,				__lowerCamelCase							:      Any=0.1 ,				__lowerCamelCase							:      Union[str, Any]=0.1 ,				__lowerCamelCase							:      int=512 ,				__lowerCamelCase							:      str=2 ,				__lowerCamelCase							:      Any=0.0_2 ,				__lowerCamelCase							:      List[Any]=1E-1_2 ,				__lowerCamelCase							:      List[str]=0 ,				__lowerCamelCase							:      Union[str, Any]=1024 ,				__lowerCamelCase							:      Tuple=128 ,				__lowerCamelCase							:      Tuple=32 ,				__lowerCamelCase							:      Union[str, Any]=True ,				__lowerCamelCase							:      List[Any]=256 ,				__lowerCamelCase							:      Dict=64 ,				__lowerCamelCase							:      List[Any]=True ,				__lowerCamelCase							:      Union[str, Any]=[7, 7, 256] ,				__lowerCamelCase							:      str=128 ,				__lowerCamelCase							:      Dict=128 ,				__lowerCamelCase							:      Dict=True ,				__lowerCamelCase							:      int=True ,				__lowerCamelCase							:      str=False ,				__lowerCamelCase							:      Tuple=None ,				**__lowerCamelCase							:      str ,				):


             '''simple docstring'''



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





       @classmethod
       def 						lowerCAmelCase					(       self							:      List[Any]	):


             '''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": 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 						lowerCAmelCase					(       self							:      List[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  detectrona.config.get_cfg()
             for k, v in self.detectrona_config_args.items():
                   lowerCamelCase__		:    List[Any]   =  k.split("."	)
                   lowerCamelCase__		:    int   =  detectrona_config
                   for attribute in attributes[:-1]:
                         lowerCamelCase__		:    Any   =  getattr(__lowerCamelCase ,				__lowerCamelCase	)
                   setattr(__lowerCamelCase ,				attributes[-1] ,				__lowerCamelCase	)

             return detectrona_config


