


'''simple docstring'''

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    a__					(			unittest.TestCase   ):







				"""simple docstring"""



				def __init__(self							,      __lowercase							,      __lowercase=7							,      __lowercase=3							,      __lowercase=30							,      __lowercase=4_00							,      __lowercase=True							,      __lowercase=None							,      __lowercase=True							,      __lowercase=[0.5, 0.5, 0.5]							,      __lowercase=[0.5, 0.5, 0.5]							,      __lowercase=False							,      ):
										__lowerCAmelCase											=					size if size is not None else {'''height''': 30, '''width''': 30}
										__lowerCAmelCase											=					parent
										__lowerCAmelCase											=					batch_size
										__lowerCAmelCase											=					num_channels
										__lowerCAmelCase											=					min_resolution
										__lowerCAmelCase											=					max_resolution
										__lowerCAmelCase											=					do_resize
										__lowerCAmelCase											=					size
										__lowerCAmelCase											=					do_normalize
										__lowerCAmelCase											=					image_mean
										__lowerCAmelCase											=					image_std
										__lowerCAmelCase											=					do_reduce_labels




				def        _snake_case	(self		):
										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 				__magic_name__(    ):
						__lowerCAmelCase											=					load_dataset('''hf-internal-testing/fixtures_ade20k''',					split='''test''')

						__lowerCAmelCase											=					Image.open(dataset[0]['''file'''])
						__lowerCAmelCase											=					Image.open(dataset[1]['''file'''])

						return image, map

def 				__magic_name__(    ):
						__lowerCAmelCase											=					load_dataset('''hf-internal-testing/fixtures_ade20k''',					split='''test''')

						__lowerCAmelCase											=					Image.open(dataset[0]['''file'''])
						__lowerCAmelCase											=					Image.open(dataset[1]['''file'''])
						__lowerCAmelCase											=					Image.open(dataset[2]['''file'''])
						__lowerCAmelCase											=					Image.open(dataset[3]['''file'''])

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




@require_torch
@require_vision
class    a__					(			__A				,    unittest.TestCase   ):







				"""simple docstring"""



				__UpperCamelCase     :		Dict						=						SegformerImageProcessor if is_vision_available() else None




				def        _snake_case	(self		):
										__lowerCAmelCase											=					SegformerImageProcessingTester(self		)




				@property
				def        _snake_case	(self		):
										return self.image_processor_tester.prepare_image_processor_dict()




				def        _snake_case	(self		):
										__lowerCAmelCase											=					self.image_processing_class(**self.image_processor_dict		)
										self.assertTrue(hasattr(__lowercase							,      '''do_resize'''		)		)
										self.assertTrue(hasattr(__lowercase							,      '''size'''		)		)
										self.assertTrue(hasattr(__lowercase							,      '''do_normalize'''		)		)
										self.assertTrue(hasattr(__lowercase							,      '''image_mean'''		)		)
										self.assertTrue(hasattr(__lowercase							,      '''image_std'''		)		)
										self.assertTrue(hasattr(__lowercase							,      '''do_reduce_labels'''		)		)




				def        _snake_case	(self		):
										__lowerCAmelCase											=					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							,      __lowercase		)

										__lowerCAmelCase											=					self.image_processing_class.from_dict(self.image_processor_dict							,      size=42							,      reduce_labels=__lowercase		)
										self.assertEqual(image_processor.size							,      {'''height''': 42, '''width''': 42}		)
										self.assertEqual(image_processor.do_reduce_labels							,      __lowercase		)




				def        _snake_case	(self		):
										pass




				def        _snake_case	(self		):
										# Initialize image_processing
										__lowerCAmelCase											=					self.image_processing_class(**self.image_processor_dict		)
										# create random PIL images
										__lowerCAmelCase											=					prepare_image_inputs(self.image_processor_tester							,      equal_resolution=__lowercase		)
										for image in image_inputs:
																self.assertIsInstance(__lowercase							,      Image.Image		)

										# Test not batched input
										__lowerCAmelCase											=					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
										__lowerCAmelCase											=					image_processing(__lowercase							,      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        _snake_case	(self		):
										# Initialize image_processing
										__lowerCAmelCase											=					self.image_processing_class(**self.image_processor_dict		)
										# create random numpy tensors
										__lowerCAmelCase											=					prepare_image_inputs(self.image_processor_tester							,      equal_resolution=__lowercase							,      numpify=__lowercase		)
										for image in image_inputs:
																self.assertIsInstance(__lowercase							,      np.ndarray		)

										# Test not batched input
										__lowerCAmelCase											=					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
										__lowerCAmelCase											=					image_processing(__lowercase							,      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        _snake_case	(self		):
										# Initialize image_processing
										__lowerCAmelCase											=					self.image_processing_class(**self.image_processor_dict		)
										# create random PyTorch tensors
										__lowerCAmelCase											=					prepare_image_inputs(self.image_processor_tester							,      equal_resolution=__lowercase							,      torchify=__lowercase		)
										for image in image_inputs:
																self.assertIsInstance(__lowercase							,      torch.Tensor		)

										# Test not batched input
										__lowerCAmelCase											=					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
										__lowerCAmelCase											=					image_processing(__lowercase							,      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        _snake_case	(self		):
										# Initialize image_processing
										__lowerCAmelCase											=					self.image_processing_class(**self.image_processor_dict		)
										# create random PyTorch tensors
										__lowerCAmelCase											=					prepare_image_inputs(self.image_processor_tester							,      equal_resolution=__lowercase							,      torchify=__lowercase		)
										__lowerCAmelCase											=					[]
										for image in image_inputs:
																self.assertIsInstance(__lowercase							,      torch.Tensor		)
																maps.append(torch.zeros(image.shape[-2:]		).long()		)

										# Test not batched input
										__lowerCAmelCase											=					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() <= 2_55		)

										# Test batched
										__lowerCAmelCase											=					image_processing(__lowercase							,      __lowercase							,      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() <= 2_55		)

										# Test not batched input (PIL images)
										__lowerCAmelCase							,       __lowerCAmelCase											=					prepare_semantic_single_inputs()

										__lowerCAmelCase											=					image_processing(__lowercase							,      __lowercase							,      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() <= 2_55		)

										# Test batched input (PIL images)
										__lowerCAmelCase							,       __lowerCAmelCase											=					prepare_semantic_batch_inputs()

										__lowerCAmelCase											=					image_processing(__lowercase							,      __lowercase							,      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() <= 2_55		)




				def        _snake_case	(self		):
										# Initialize image_processing
										__lowerCAmelCase											=					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
										__lowerCAmelCase							,       __lowerCAmelCase											=					prepare_semantic_single_inputs()
										__lowerCAmelCase											=					image_processing(__lowercase							,      __lowercase							,      return_tensors='''pt'''		)
										self.assertTrue(encoding['''labels'''].min().item() >= 0		)
										self.assertTrue(encoding['''labels'''].max().item() <= 1_50		)

										__lowerCAmelCase											=					True
										__lowerCAmelCase											=					image_processing(__lowercase							,      __lowercase							,      return_tensors='''pt'''		)
										self.assertTrue(encoding['''labels'''].min().item() >= 0		)
										self.assertTrue(encoding['''labels'''].max().item() <= 2_55		)





'''simple docstring'''

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


_UpperCAmelCase					:			Optional[int]				     =					logging.get_logger(__name__)

_UpperCAmelCase					:			str				     =					{
    """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    a__					(			__A   ):







				"""simple docstring"""



				__UpperCamelCase     :		List[Any]						=						'layoutlmv2'




				def __init__(self							,      __lowercase=3_05_22							,      __lowercase=7_68							,      __lowercase=12							,      __lowercase=12							,      __lowercase=30_72							,      __lowercase="gelu"							,      __lowercase=0.1							,      __lowercase=0.1							,      __lowercase=5_12							,      __lowercase=2							,      __lowercase=0.0_2							,      __lowercase=1e-12							,      __lowercase=0							,      __lowercase=10_24							,      __lowercase=1_28							,      __lowercase=32							,      __lowercase=True							,      __lowercase=2_56							,      __lowercase=64							,      __lowercase=True							,      __lowercase=[7, 7, 2_56]							,      __lowercase=1_28							,      __lowercase=1_28							,      __lowercase=True							,      __lowercase=True							,      __lowercase=False							,      __lowercase=None							,      **__lowercase							,      ):
										super().__init__(
										    vocab_size=__lowercase							,      hidden_size=__lowercase							,      num_hidden_layers=__lowercase							,      num_attention_heads=__lowercase							,      intermediate_size=__lowercase							,      hidden_act=__lowercase							,      hidden_dropout_prob=__lowercase							,      attention_probs_dropout_prob=__lowercase							,      max_position_embeddings=__lowercase							,      type_vocab_size=__lowercase							,      initializer_range=__lowercase							,      layer_norm_eps=__lowercase							,      pad_token_id=__lowercase							,      **__lowercase							,      )
										__lowerCAmelCase											=					max_ad_position_embeddings
										__lowerCAmelCase											=					max_rel_pos
										__lowerCAmelCase											=					rel_pos_bins
										__lowerCAmelCase											=					fast_qkv
										__lowerCAmelCase											=					max_rel_ad_pos
										__lowerCAmelCase											=					rel_ad_pos_bins
										__lowerCAmelCase											=					convert_sync_batchnorm
										__lowerCAmelCase											=					image_feature_pool_shape
										__lowerCAmelCase											=					coordinate_size
										__lowerCAmelCase											=					shape_size
										__lowerCAmelCase											=					has_relative_attention_bias
										__lowerCAmelCase											=					has_spatial_attention_bias
										__lowerCAmelCase											=					has_visual_segment_embedding
										__lowerCAmelCase											=					(
										    detectrona_config_args if detectrona_config_args is not None else self.get_default_detectrona_config()
										)




				@classmethod
				def        _snake_case	(self		):
										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], [1_28], [2_56], [5_12]],
										    "MODEL.RPN.IN_FEATURES": ["p2", "p3", "p4", "p5", "p6"],
										    "MODEL.RPN.PRE_NMS_TOPK_TRAIN": 20_00,
										    "MODEL.RPN.PRE_NMS_TOPK_TEST": 10_00,
										    "MODEL.RPN.POST_NMS_TOPK_TRAIN": 10_00,
										    "MODEL.POST_NMS_TOPK_TEST": 10_00,
										    "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": 1_01,
										    "MODEL.RESNETS.SIZES": [[32], [64], [1_28], [2_56], [5_12]],
										    "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        _snake_case	(self		):
										__lowerCAmelCase											=					detectrona.config.get_cfg()
										for k, v in self.detectrona_config_args.items():
																__lowerCAmelCase											=					k.split('''.'''		)
																__lowerCAmelCase											=					detectrona_config
																for attribute in attributes[:-1]:
																						__lowerCAmelCase											=					getattr(__lowercase							,      __lowercase		)
																setattr(__lowercase							,      attributes[-1]							,      __lowercase		)

										return detectrona_config

