


import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image

    from transformers import ViltImageProcessor







class       _lowercase			(							unittest.TestCase):


       """simple docstring"""




       def __init__(       self							:      str ,				__lowerCamelCase							:      List[Any] ,				__lowerCamelCase							:      List[str]=7 ,				__lowerCamelCase							:      Union[str, Any]=3 ,				__lowerCamelCase							:      Tuple=18 ,				__lowerCamelCase							:      Optional[Any]=30 ,				__lowerCamelCase							:      Union[str, Any]=400 ,				__lowerCamelCase							:      Optional[int]=True ,				__lowerCamelCase							:      List[Any]=None ,				__lowerCamelCase							:      List[Any]=2 ,				__lowerCamelCase							:      Tuple=True ,				__lowerCamelCase							:      List[str]=[0.5, 0.5, 0.5] ,				__lowerCamelCase							:      List[str]=[0.5, 0.5, 0.5] ,				):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  size if size is not None else {"shortest_edge": 30}
             lowerCamelCase__		:    str   =  parent
             lowerCamelCase__		:    Optional[Any]   =  batch_size
             lowerCamelCase__		:    List[Any]   =  num_channels
             lowerCamelCase__		:    List[str]   =  image_size
             lowerCamelCase__		:    List[Any]   =  min_resolution
             lowerCamelCase__		:    Union[str, Any]   =  max_resolution
             lowerCamelCase__		:    int   =  do_resize
             lowerCamelCase__		:    List[Any]   =  size
             lowerCamelCase__		:    Dict   =  size_divisor
             lowerCamelCase__		:    List[str]   =  do_normalize
             lowerCamelCase__		:    Optional[int]   =  image_mean
             lowerCamelCase__		:    Tuple   =  image_std





       def 						lowerCAmelCase					(       self							:      Tuple	):


             '''simple docstring'''



             return {
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
                 "do_normalize": self.do_normalize,
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "size_divisor": self.size_divisor,
             }





       def 						lowerCAmelCase					(       self							:      Optional[int] ,				__lowerCamelCase							:      List[str] ,				__lowerCamelCase							:      Optional[int]=False	):


             '''simple docstring'''



             if not batched:
                   lowerCamelCase__		:    List[Any]   =  self.size["shortest_edge"]
                   lowerCamelCase__		:    Any   =  image_inputs[0]
                   if isinstance(__lowerCamelCase ,				Image.Image	):
                         lowerCamelCase__   ,       lowerCamelCase__		:    Any   =  image.size
                   else:
                         lowerCamelCase__   ,       lowerCamelCase__		:    List[Any]   =  image.shape[1], image.shape[2]
                   lowerCamelCase__		:    List[str]   =  size / min(__lowerCamelCase ,				__lowerCamelCase	)
                   if h < w:
                         lowerCamelCase__   ,       lowerCamelCase__		:    Tuple   =  size, scale * w
                   else:
                         lowerCamelCase__   ,       lowerCamelCase__		:    int   =  scale * h, size

                   lowerCamelCase__		:    List[str]   =  int((1333 / 800) * size	)
                   if max(__lowerCamelCase ,				__lowerCamelCase	) > max_size:
                         lowerCamelCase__		:    List[Any]   =  max_size / max(__lowerCamelCase ,				__lowerCamelCase	)
                         lowerCamelCase__		:    List[Any]   =  newh * scale
                         lowerCamelCase__		:    Tuple   =  neww * scale

                   lowerCamelCase__   ,       lowerCamelCase__		:    List[Any]   =  int(newh + 0.5	), int(neww + 0.5	)
                   lowerCamelCase__   ,       lowerCamelCase__		:    Any   =  (
                       newh // self.size_divisor * self.size_divisor,
                       neww // self.size_divisor * self.size_divisor,
                   )

             else:
                   lowerCamelCase__		:    Union[str, Any]   =  []
                   for image in image_inputs:
                         lowerCamelCase__   ,       lowerCamelCase__		:    Any   =  self.get_expected_values([image]	)
                         expected_values.append((expected_height, expected_width)	)
                   lowerCamelCase__		:    List[Any]   =  max(__lowerCamelCase ,				key=lambda __lowerCamelCase	: item[0]	)[0]
                   lowerCamelCase__		:    str   =  max(__lowerCamelCase ,				key=lambda __lowerCamelCase	: item[1]	)[1]

             return expected_height, expected_width







@require_torch
@require_vision
class       _lowercase			(							lowercase__							,  unittest.TestCase):


       """simple docstring"""




       A__ 						=      ViltImageProcessor if is_vision_available() else None





       def 						lowerCAmelCase					(       self							:      List[str]	):


             '''simple docstring'''



             lowerCamelCase__		:    Dict   =  ViltImageProcessingTester(self	)





       @property
       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



             return self.image_processor_tester.prepare_image_processor_dict()





       def 						lowerCAmelCase					(       self							:      List[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  self.image_processing_class(**self.image_processor_dict	)
             self.assertTrue(hasattr(__lowerCamelCase ,				"image_mean"	)	)
             self.assertTrue(hasattr(__lowerCamelCase ,				"image_std"	)	)
             self.assertTrue(hasattr(__lowerCamelCase ,				"do_normalize"	)	)
             self.assertTrue(hasattr(__lowerCamelCase ,				"do_resize"	)	)
             self.assertTrue(hasattr(__lowerCamelCase ,				"size"	)	)
             self.assertTrue(hasattr(__lowerCamelCase ,				"size_divisor"	)	)





       def 						lowerCAmelCase					(       self							:      int	):


             '''simple docstring'''



             lowerCamelCase__		:    str   =  self.image_processing_class.from_dict(self.image_processor_dict	)
             self.assertEqual(image_processor.size ,				{"shortest_edge": 30}	)

             lowerCamelCase__		:    int   =  self.image_processing_class.from_dict(self.image_processor_dict ,				size=42	)
             self.assertEqual(image_processor.size ,				{"shortest_edge": 42}	)





       def 						lowerCAmelCase					(       self							:      int	):


             '''simple docstring'''



             pass





       def 						lowerCAmelCase					(       self							:      int	):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  self.image_processing_class(**self.image_processor_dict	)
             # create random PIL images
             lowerCamelCase__		:    List[str]   =  prepare_image_inputs(self.image_processor_tester ,				equal_resolution=__lowerCamelCase	)
             for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase ,				Image.Image	)

             # Test not batched input
             lowerCamelCase__		:    str   =  image_processing(image_inputs[0] ,				return_tensors="pt"	).pixel_values

             lowerCamelCase__   ,       lowerCamelCase__		:    Any   =  self.image_processor_tester.get_expected_values(__lowerCamelCase	)
             self.assertEqual(
                 encoded_images.shape ,				(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,				)

             # Test batched
             lowerCamelCase__		:    Dict   =  image_processing(__lowerCamelCase ,				return_tensors="pt"	).pixel_values

             lowerCamelCase__   ,       lowerCamelCase__		:    Optional[Any]   =  self.image_processor_tester.get_expected_values(__lowerCamelCase ,				batched=__lowerCamelCase	)
             self.assertEqual(
                 encoded_images.shape ,				(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     expected_height,
                     expected_width,
                 ) ,				)





       def 						lowerCAmelCase					(       self							:      Any	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  self.image_processing_class(**self.image_processor_dict	)
             # create random numpy tensors
             lowerCamelCase__		:    Union[str, Any]   =  prepare_image_inputs(self.image_processor_tester ,				equal_resolution=__lowerCamelCase ,				numpify=__lowerCamelCase	)
             for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase ,				np.ndarray	)

             # Test not batched input
             lowerCamelCase__		:    Optional[Any]   =  image_processing(image_inputs[0] ,				return_tensors="pt"	).pixel_values

             lowerCamelCase__   ,       lowerCamelCase__		:    Tuple   =  self.image_processor_tester.get_expected_values(__lowerCamelCase	)
             self.assertEqual(
                 encoded_images.shape ,				(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,				)

             # Test batched
             lowerCamelCase__		:    str   =  image_processing(__lowerCamelCase ,				return_tensors="pt"	).pixel_values

             lowerCamelCase__   ,       lowerCamelCase__		:    Union[str, Any]   =  self.image_processor_tester.get_expected_values(__lowerCamelCase ,				batched=__lowerCamelCase	)
             self.assertEqual(
                 encoded_images.shape ,				(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     expected_height,
                     expected_width,
                 ) ,				)





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



             lowerCamelCase__		:    List[str]   =  self.image_processing_class(**self.image_processor_dict	)
             # create random PyTorch tensors
             lowerCamelCase__		:    str   =  prepare_image_inputs(self.image_processor_tester ,				equal_resolution=__lowerCamelCase ,				torchify=__lowerCamelCase	)
             for image in image_inputs:
                   self.assertIsInstance(__lowerCamelCase ,				torch.Tensor	)

             # Test not batched input
             lowerCamelCase__		:    Optional[Any]   =  image_processing(image_inputs[0] ,				return_tensors="pt"	).pixel_values

             lowerCamelCase__   ,       lowerCamelCase__		:    Any   =  self.image_processor_tester.get_expected_values(__lowerCamelCase	)
             self.assertEqual(
                 encoded_images.shape ,				(1, self.image_processor_tester.num_channels, expected_height, expected_width) ,				)

             # Test batched
             lowerCamelCase__		:    Optional[int]   =  image_processing(__lowerCamelCase ,				return_tensors="pt"	).pixel_values

             lowerCamelCase__   ,       lowerCamelCase__		:    Any   =  self.image_processor_tester.get_expected_values(__lowerCamelCase ,				batched=__lowerCamelCase	)
             self.assertEqual(
                 encoded_images.shape ,				(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_channels,
                     expected_height,
                     expected_width,
                 ) ,				)






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


