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


lowercase__				:				int						=      logging.get_logger(__name__)

lowercase__				:				List[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 							SCREAMING_SNAKE_CASE__     (				SCREAMING_SNAKE_CASE_     ):

							"""simple docstring"""






							_snake_case  		=	'layoutlmv2'



							def __init__(	self  ,						SCREAMING_SNAKE_CASE_=30522  ,						SCREAMING_SNAKE_CASE_=768  ,						SCREAMING_SNAKE_CASE_=12  ,						SCREAMING_SNAKE_CASE_=12  ,						SCREAMING_SNAKE_CASE_=3072  ,						SCREAMING_SNAKE_CASE_="gelu"  ,						SCREAMING_SNAKE_CASE_=0.1  ,						SCREAMING_SNAKE_CASE_=0.1  ,						SCREAMING_SNAKE_CASE_=512  ,						SCREAMING_SNAKE_CASE_=2  ,						SCREAMING_SNAKE_CASE_=0.0_2  ,						SCREAMING_SNAKE_CASE_=1E-12  ,						SCREAMING_SNAKE_CASE_=0  ,						SCREAMING_SNAKE_CASE_=1024  ,						SCREAMING_SNAKE_CASE_=128  ,						SCREAMING_SNAKE_CASE_=32  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=256  ,						SCREAMING_SNAKE_CASE_=64  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=[7, 7, 256]  ,						SCREAMING_SNAKE_CASE_=128  ,						SCREAMING_SNAKE_CASE_=128  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=True  ,						SCREAMING_SNAKE_CASE_=False  ,						SCREAMING_SNAKE_CASE_=None  ,						**SCREAMING_SNAKE_CASE_  ,						)-> int:





													'''simple docstring'''






													super().__init__(
													    vocab_size=SCREAMING_SNAKE_CASE_  ,						hidden_size=SCREAMING_SNAKE_CASE_  ,						num_hidden_layers=SCREAMING_SNAKE_CASE_  ,						num_attention_heads=SCREAMING_SNAKE_CASE_  ,						intermediate_size=SCREAMING_SNAKE_CASE_  ,						hidden_act=SCREAMING_SNAKE_CASE_  ,						hidden_dropout_prob=SCREAMING_SNAKE_CASE_  ,						attention_probs_dropout_prob=SCREAMING_SNAKE_CASE_  ,						max_position_embeddings=SCREAMING_SNAKE_CASE_  ,						type_vocab_size=SCREAMING_SNAKE_CASE_  ,						initializer_range=SCREAMING_SNAKE_CASE_  ,						layer_norm_eps=SCREAMING_SNAKE_CASE_  ,						pad_token_id=SCREAMING_SNAKE_CASE_  ,						**SCREAMING_SNAKE_CASE_  ,						)
													__UpperCamelCase  	=      max_ad_position_embeddings
													__UpperCamelCase  	=      max_rel_pos
													__UpperCamelCase  	=      rel_pos_bins
													__UpperCamelCase  	=      fast_qkv
													__UpperCamelCase  	=      max_rel_ad_pos
													__UpperCamelCase  	=      rel_ad_pos_bins
													__UpperCamelCase  	=      convert_sync_batchnorm
													__UpperCamelCase  	=      image_feature_pool_shape
													__UpperCamelCase  	=      coordinate_size
													__UpperCamelCase  	=      shape_size
													__UpperCamelCase  	=      has_relative_attention_bias
													__UpperCamelCase  	=      has_spatial_attention_bias
													__UpperCamelCase  	=      has_visual_segment_embedding
													__UpperCamelCase  	=      (
													    detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
													)



							@classmethod
							def      A__		(	self      )-> Optional[int]:





													'''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      A__		(	self      )-> Optional[int]:





													'''simple docstring'''






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

													return detectrona_config









import unittest

import numpy as np
from datasets import load_dataset

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 SegformerImageProcessor




class 				lowerCAmelCase__	(						unittest.TestCase    ):







					def __init__(							self   :  int      ,		_A   :  Optional[Any]      ,		_A   :  Optional[int]=7      ,		_A   :  str=3      ,		_A   :  Optional[int]=30      ,		_A   :  List[str]=400      ,		_A   :  Tuple=True      ,		_A   :  List[Any]=None      ,		_A   :  Dict=True      ,		_A   :  Tuple=[0.5, 0.5, 0.5]      ,		_A   :  List[str]=[0.5, 0.5, 0.5]      ,		_A   :  int=False      ,		):
											A__						:				Tuple         =			size if size is not None else {"height": 30, "width": 30}
											A__						:				Tuple         =			parent
											A__						:				str         =			batch_size
											A__						:				int         =			num_channels
											A__						:				Union[str, Any]         =			min_resolution
											A__						:				List[str]         =			max_resolution
											A__						:				int         =			do_resize
											A__						:				Tuple         =			size
											A__						:				Union[str, Any]         =			do_normalize
											A__						:				Optional[int]         =			image_mean
											A__						:				List[Any]         =			image_std
											A__						:				Dict         =			do_reduce_labels







					def 			_lowercase      (							self   :  Optional[int]):
											return {
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "do_normalize": self.do_normalize,
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_reduce_labels": self.do_reduce_labels,
											}




def 						snake_case__							(       )		->		Tuple:







						"""simple docstring"""

						A__						:				Union[str, Any]         =			load_dataset("hf-internal-testing/fixtures_ade20k"				,  split="test"							)

						A__						:				Any         =			Image.open(dataset[0]["file"]							)
						A__						:				Any         =			Image.open(dataset[1]["file"]							)

						return image, map
def 						snake_case__							(       )		->		List[str]:







						"""simple docstring"""

						A__						:				Tuple         =			load_dataset("hf-internal-testing/fixtures_ade20k"				,  split="test"							)

						A__						:				Tuple         =			Image.open(dataset[0]["file"]							)
						A__						:				int         =			Image.open(dataset[1]["file"]							)
						A__						:				str         =			Image.open(dataset[2]["file"]							)
						A__						:				List[Any]         =			Image.open(dataset[3]["file"]							)

						return [imagea, imagea], [mapa, mapa]




@require_torch
@require_vision
class 				lowerCAmelCase__	(						UpperCamelCase       ,				unittest.TestCase    ):
					__A  :     int     =    SegformerImageProcessor if is_vision_available() else None







					def 			_lowercase      (							self   :  int):
											A__						:				int         =			SegformerImageProcessingTester(self)







					@property
					def 			_lowercase      (							self   :  str):
											return self.image_processor_tester.prepare_image_processor_dict()







					def 			_lowercase      (							self   :  Optional[Any]):
											A__						:				Any         =			self.image_processing_class(**self.image_processor_dict)
											self.assertTrue(hasattr(_A      ,		"do_resize"))
											self.assertTrue(hasattr(_A      ,		"size"))
											self.assertTrue(hasattr(_A      ,		"do_normalize"))
											self.assertTrue(hasattr(_A      ,		"image_mean"))
											self.assertTrue(hasattr(_A      ,		"image_std"))
											self.assertTrue(hasattr(_A      ,		"do_reduce_labels"))







					def 			_lowercase      (							self   :  Tuple):
											A__						:				Union[str, Any]         =			self.image_processing_class.from_dict(self.image_processor_dict)
											self.assertEqual(image_processor.size      ,		{"height": 30, "width": 30})
											self.assertEqual(image_processor.do_reduce_labels      ,		_A)

											A__						:				Union[str, Any]         =			self.image_processing_class.from_dict(self.image_processor_dict      ,		size=42      ,		reduce_labels=_A)
											self.assertEqual(image_processor.size      ,		{"height": 42, "width": 42})
											self.assertEqual(image_processor.do_reduce_labels      ,		_A)







					def 			_lowercase      (							self   :  Union[str, Any]):
											pass







					def 			_lowercase      (							self   :  Dict):
											# Initialize image_processing
											A__						:				Tuple         =			self.image_processing_class(**self.image_processor_dict)
											# create random PIL images
											A__						:				Union[str, Any]         =			prepare_image_inputs(self.image_processor_tester      ,		equal_resolution=_A)
											for image in image_inputs:
																	self.assertIsInstance(_A      ,		Image.Image)

											# Test not batched input
											A__						:				Dict         =			image_processing(image_inputs[0]      ,		return_tensors="pt").pixel_values
											self.assertEqual(
											    encoded_images.shape      ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)

											# Test batched
											A__						:				List[Any]         =			image_processing(_A      ,		return_tensors="pt").pixel_values
											self.assertEqual(
											    encoded_images.shape      ,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)







					def 			_lowercase      (							self   :  Optional[int]):
											# Initialize image_processing
											A__						:				Tuple         =			self.image_processing_class(**self.image_processor_dict)
											# create random numpy tensors
											A__						:				Tuple         =			prepare_image_inputs(self.image_processor_tester      ,		equal_resolution=_A      ,		numpify=_A)
											for image in image_inputs:
																	self.assertIsInstance(_A      ,		np.ndarray)

											# Test not batched input
											A__						:				Optional[Any]         =			image_processing(image_inputs[0]      ,		return_tensors="pt").pixel_values
											self.assertEqual(
											    encoded_images.shape      ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)

											# Test batched
											A__						:				Optional[int]         =			image_processing(_A      ,		return_tensors="pt").pixel_values
											self.assertEqual(
											    encoded_images.shape      ,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)







					def 			_lowercase      (							self   :  Tuple):
											# Initialize image_processing
											A__						:				str         =			self.image_processing_class(**self.image_processor_dict)
											# create random PyTorch tensors
											A__						:				str         =			prepare_image_inputs(self.image_processor_tester      ,		equal_resolution=_A      ,		torchify=_A)
											for image in image_inputs:
																	self.assertIsInstance(_A      ,		torch.Tensor)

											# Test not batched input
											A__						:				int         =			image_processing(image_inputs[0]      ,		return_tensors="pt").pixel_values
											self.assertEqual(
											    encoded_images.shape      ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)

											# Test batched
											A__						:				List[str]         =			image_processing(_A      ,		return_tensors="pt").pixel_values
											self.assertEqual(
											    encoded_images.shape      ,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)







					def 			_lowercase      (							self   :  Optional[int]):
											# Initialize image_processing
											A__						:				str         =			self.image_processing_class(**self.image_processor_dict)
											# create random PyTorch tensors
											A__						:				Optional[Any]         =			prepare_image_inputs(self.image_processor_tester      ,		equal_resolution=_A      ,		torchify=_A)
											A__						:				List[str]         =			[]
											for image in image_inputs:
																	self.assertIsInstance(_A      ,		torch.Tensor)
																	maps.append(torch.zeros(image.shape[-2:]).long())

											# Test not batched input
											A__						:				Any         =			image_processing(image_inputs[0]      ,		maps[0]      ,		return_tensors="pt")
											self.assertEqual(
											    encoding["pixel_values"].shape      ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(
											    encoding["labels"].shape      ,		(
											        1,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(encoding["labels"].dtype      ,		torch.long)
											self.assertTrue(encoding["labels"].min().item() >= 0)
											self.assertTrue(encoding["labels"].max().item() <= 255)

											# Test batched
											A__						:				int         =			image_processing(_A      ,		_A      ,		return_tensors="pt")
											self.assertEqual(
											    encoding["pixel_values"].shape      ,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(
											    encoding["labels"].shape      ,		(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(encoding["labels"].dtype      ,		torch.long)
											self.assertTrue(encoding["labels"].min().item() >= 0)
											self.assertTrue(encoding["labels"].max().item() <= 255)

											# Test not batched input (PIL images)
											A__     ,							A__						:				List[str]         =			prepare_semantic_single_inputs()

											A__						:				Any         =			image_processing(_A      ,		_A      ,		return_tensors="pt")
											self.assertEqual(
											    encoding["pixel_values"].shape      ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(
											    encoding["labels"].shape      ,		(
											        1,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(encoding["labels"].dtype      ,		torch.long)
											self.assertTrue(encoding["labels"].min().item() >= 0)
											self.assertTrue(encoding["labels"].max().item() <= 255)

											# Test batched input (PIL images)
											A__     ,							A__						:				Union[str, Any]         =			prepare_semantic_batch_inputs()

											A__						:				str         =			image_processing(_A      ,		_A      ,		return_tensors="pt")
											self.assertEqual(
											    encoding["pixel_values"].shape      ,		(
											        2,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(
											    encoding["labels"].shape      ,		(
											        2,
											        self.image_processor_tester.size["height"],
											        self.image_processor_tester.size["width"],
											    )      ,		)
											self.assertEqual(encoding["labels"].dtype      ,		torch.long)
											self.assertTrue(encoding["labels"].min().item() >= 0)
											self.assertTrue(encoding["labels"].max().item() <= 255)







					def 			_lowercase      (							self   :  Union[str, Any]):
											# Initialize image_processing
											A__						:				List[str]         =			self.image_processing_class(**self.image_processor_dict)

											# ADE20k has 150 classes, and the background is included, so labels should be between 0 and 150
											A__     ,							A__						:				Tuple         =			prepare_semantic_single_inputs()
											A__						:				Dict         =			image_processing(_A      ,		_A      ,		return_tensors="pt")
											self.assertTrue(encoding["labels"].min().item() >= 0)
											self.assertTrue(encoding["labels"].max().item() <= 150)

											A__						:				str         =			True
											A__						:				int         =			image_processing(_A      ,		_A      ,		return_tensors="pt")
											self.assertTrue(encoding["labels"].min().item() >= 0)
											self.assertTrue(encoding["labels"].max().item() <= 255)