


'''simple docstring'''
import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
		    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
		    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
		    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
		    LayoutLMvaConfig,
		    LayoutLMvaForQuestionAnswering,
		    LayoutLMvaForSequenceClassification,
		    LayoutLMvaForTokenClassification,
		    LayoutLMvaModel,
		)
		from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
		from PIL import Image

		from transformers import LayoutLMvaImageProcessor
class    lowercase	:

		"""simple docstring"""

		def __init__(		self    ,   UpperCamelCase_    ,   UpperCamelCase_=2    ,   UpperCamelCase_=3    ,   UpperCamelCase_=4    ,   UpperCamelCase_=2    ,   UpperCamelCase_=7    ,   UpperCamelCase_=True    ,   UpperCamelCase_=True    ,   UpperCamelCase_=True    ,   UpperCamelCase_=True    ,   UpperCamelCase_=99    ,   UpperCamelCase_=36    ,   UpperCamelCase_=3    ,   UpperCamelCase_=4    ,   UpperCamelCase_=37    ,   UpperCamelCase_="gelu"    ,   UpperCamelCase_=0.1    ,   UpperCamelCase_=0.1    ,   UpperCamelCase_=512    ,   UpperCamelCase_=16    ,   UpperCamelCase_=2    ,   UpperCamelCase_=0.02    ,   UpperCamelCase_=6    ,   UpperCamelCase_=6    ,   UpperCamelCase_=3    ,   UpperCamelCase_=4    ,   UpperCamelCase_=None    ,   UpperCamelCase_=1000    ,   ):

							'''simple docstring'''


							UpperCamelCase__   :List[str]												= parent
							UpperCamelCase__   :Dict												= batch_size
							UpperCamelCase__   :List[Any]												= num_channels
							UpperCamelCase__   :int												= image_size
							UpperCamelCase__   :str												= patch_size
							UpperCamelCase__   :Optional[Any]												= text_seq_length
							UpperCamelCase__   :str												= is_training
							UpperCamelCase__   :List[str]												= use_input_mask
							UpperCamelCase__   :Any												= use_token_type_ids
							UpperCamelCase__   :List[Any]												= use_labels
							UpperCamelCase__   :List[Any]												= vocab_size
							UpperCamelCase__   :List[Any]												= hidden_size
							UpperCamelCase__   :Any												= num_hidden_layers
							UpperCamelCase__   :List[str]												= num_attention_heads
							UpperCamelCase__   :Tuple												= intermediate_size
							UpperCamelCase__   :Any												= hidden_act
							UpperCamelCase__   :Optional[int]												= hidden_dropout_prob
							UpperCamelCase__   :Optional[int]												= attention_probs_dropout_prob
							UpperCamelCase__   :List[Any]												= max_position_embeddings
							UpperCamelCase__   :Dict												= type_vocab_size
							UpperCamelCase__   :Optional[int]												= type_sequence_label_size
							UpperCamelCase__   :List[Any]												= initializer_range
							UpperCamelCase__   :Any												= coordinate_size
							UpperCamelCase__   :Optional[Any]												= shape_size
							UpperCamelCase__   :Any												= num_labels
							UpperCamelCase__   :Union[str, Any]												= num_choices
							UpperCamelCase__   :Any												= scope
							UpperCamelCase__   :List[Any]												= range_bbox

							# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
							UpperCamelCase__   :Optional[int]												= text_seq_length
							UpperCamelCase__   :str												= (image_size // patch_size) ** 2 + 1
							UpperCamelCase__   :Optional[int]												= self.text_seq_length + self.image_seq_length




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :str												= ids_tensor([self.batch_size, self.text_seq_length]    ,   self.vocab_size							)

							UpperCamelCase__   :Any												= ids_tensor([self.batch_size, self.text_seq_length, 4]    ,   self.range_bbox							)
							# Ensure that bbox is legal
							for i in range(bbox.shape[0]							):
												for j in range(bbox.shape[1]							):
																	if bbox[i, j, 3] < bbox[i, j, 1]:
																						UpperCamelCase__   :int												= bbox[i, j, 3]
																						UpperCamelCase__   :Union[str, Any]												= bbox[i, j, 1]
																						UpperCamelCase__   :List[str]												= t
																	if bbox[i, j, 2] < bbox[i, j, 0]:
																						UpperCamelCase__   :List[str]												= bbox[i, j, 2]
																						UpperCamelCase__   :Union[str, Any]												= bbox[i, j, 0]
																						UpperCamelCase__   :List[Any]												= t

							UpperCamelCase__   :Tuple												= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

							UpperCamelCase__   :List[Any]												= None
							if self.use_input_mask:
												UpperCamelCase__   :Optional[Any]												= random_attention_mask([self.batch_size, self.text_seq_length]							)

							UpperCamelCase__   :Any												= None
							if self.use_token_type_ids:
												UpperCamelCase__   :int												= ids_tensor([self.batch_size, self.text_seq_length]    ,   self.type_vocab_size							)

							UpperCamelCase__   :Union[str, Any]												= None
							UpperCamelCase__   :Tuple												= None
							if self.use_labels:
												UpperCamelCase__   :List[str]												= ids_tensor([self.batch_size]    ,   self.type_sequence_label_size							)
												UpperCamelCase__   :str												= ids_tensor([self.batch_size, self.text_seq_length]    ,   self.num_labels							)

							UpperCamelCase__   :Tuple												= LayoutLMvaConfig(
							    vocab_size=self.vocab_size    ,   hidden_size=self.hidden_size    ,   num_hidden_layers=self.num_hidden_layers    ,   num_attention_heads=self.num_attention_heads    ,   intermediate_size=self.intermediate_size    ,   hidden_act=self.hidden_act    ,   hidden_dropout_prob=self.hidden_dropout_prob    ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,   max_position_embeddings=self.max_position_embeddings    ,   type_vocab_size=self.type_vocab_size    ,   initializer_range=self.initializer_range    ,   coordinate_size=self.coordinate_size    ,   shape_size=self.shape_size    ,   input_size=self.image_size    ,   patch_size=self.patch_size    ,   )

							return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Union[str, Any]												= LayoutLMvaModel(config=UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()

							# text + image
							UpperCamelCase__   :List[str]												= model(UpperCamelCase_    ,   pixel_values=UpperCamelCase_							)
							UpperCamelCase__   :int												= model(
							    UpperCamelCase_    ,   bbox=UpperCamelCase_    ,   pixel_values=UpperCamelCase_    ,   attention_mask=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_							)
							UpperCamelCase__   :Union[str, Any]												= model(UpperCamelCase_    ,   bbox=UpperCamelCase_    ,   pixel_values=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_							)
							UpperCamelCase__   :str												= model(UpperCamelCase_    ,   bbox=UpperCamelCase_    ,   pixel_values=UpperCamelCase_							)

							self.parent.assertEqual(result.last_hidden_state.shape    ,   (self.batch_size, self.seq_length, self.hidden_size)							)

							# text only
							UpperCamelCase__   :Dict												= model(UpperCamelCase_							)
							self.parent.assertEqual(
							    result.last_hidden_state.shape    ,   (self.batch_size, self.text_seq_length, self.hidden_size)							)

							# image only
							UpperCamelCase__   :List[str]												= model(pixel_values=UpperCamelCase_							)
							self.parent.assertEqual(
							    result.last_hidden_state.shape    ,   (self.batch_size, self.image_seq_length, self.hidden_size)							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[Any]												= self.num_labels
							UpperCamelCase__   :Tuple												= LayoutLMvaForSequenceClassification(UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()
							UpperCamelCase__   :int												= model(
							    UpperCamelCase_    ,   bbox=UpperCamelCase_    ,   pixel_values=UpperCamelCase_    ,   attention_mask=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_    ,   labels=UpperCamelCase_    ,   )
							self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.num_labels)							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Union[str, Any]												= self.num_labels
							UpperCamelCase__   :int												= LayoutLMvaForTokenClassification(config=UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()
							UpperCamelCase__   :Tuple												= model(
							    UpperCamelCase_    ,   bbox=UpperCamelCase_    ,   pixel_values=UpperCamelCase_    ,   attention_mask=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_    ,   labels=UpperCamelCase_    ,   )
							self.parent.assertEqual(result.logits.shape    ,   (self.batch_size, self.text_seq_length, self.num_labels)							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[int]												= LayoutLMvaForQuestionAnswering(config=UpperCamelCase_							)
							model.to(UpperCamelCase_							)
							model.eval()
							UpperCamelCase__   :int												= model(
							    UpperCamelCase_    ,   bbox=UpperCamelCase_    ,   pixel_values=UpperCamelCase_    ,   attention_mask=UpperCamelCase_    ,   token_type_ids=UpperCamelCase_    ,   start_positions=UpperCamelCase_    ,   end_positions=UpperCamelCase_    ,   )
							self.parent.assertEqual(result.start_logits.shape    ,   (self.batch_size, self.seq_length)							)
							self.parent.assertEqual(result.end_logits.shape    ,   (self.batch_size, self.seq_length)							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Tuple												= self.prepare_config_and_inputs()
							(
							    (
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				(
							    UpperCamelCase__
							)					,				
							)   :Any												= config_and_inputs
							UpperCamelCase__   :Optional[int]												= {
							    '''input_ids''': input_ids,
							    '''bbox''': bbox,
							    '''pixel_values''': pixel_values,
							    '''token_type_ids''': token_type_ids,
							    '''attention_mask''': input_mask,
							}
							return config, inputs_dict



@require_torch
class    lowercase	(							A__	,		A__	,		unittest.TestCase					):

		"""simple docstring"""

		_a     =				False
		_a     =				False
		_a     =				False

		_a     =				(
		    (
		        LayoutLMvaModel,
		        LayoutLMvaForSequenceClassification,
		        LayoutLMvaForTokenClassification,
		        LayoutLMvaForQuestionAnswering,
		    )
		    if is_torch_available()
		    else ()
		)
		_a     =				(
		    {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel}
		    if is_torch_available()
		    else {}
		)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_							):

							'''simple docstring'''


							return True




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :str												= LayoutLMvaModelTester(self							)
							UpperCamelCase__   :Optional[Any]												= ConfigTester(self    ,   config_class=UpperCamelCase_    ,   hidden_size=37							)




		def     lowerCAmelCase__				(		self    ,   UpperCamelCase_    ,   UpperCamelCase_    ,   UpperCamelCase_=False							):

							'''simple docstring'''


							UpperCamelCase__   :int												= copy.deepcopy(UpperCamelCase_							)
							if model_class in get_values(UpperCamelCase_							):
												UpperCamelCase__   :Dict												= {
												    k: v.unsqueeze(1							).expand(-1    ,   self.model_tester.num_choices    ,   -1							).contiguous()
												    if isinstance(UpperCamelCase_    ,   torch.Tensor							) and v.ndim > 1
												    else v
												    for k, v in inputs_dict.items()
												}
							if return_labels:
												if model_class in get_values(UpperCamelCase_							):
																	UpperCamelCase__   :Optional[int]												= torch.ones(self.model_tester.batch_size    ,   dtype=torch.long    ,   device=UpperCamelCase_							)
												elif model_class in get_values(UpperCamelCase_							):
																	UpperCamelCase__   :int												= torch.zeros(
																	    self.model_tester.batch_size    ,   dtype=torch.long    ,   device=UpperCamelCase_							)
																	UpperCamelCase__   :int												= torch.zeros(
																	    self.model_tester.batch_size    ,   dtype=torch.long    ,   device=UpperCamelCase_							)
												elif model_class in [
												    *get_values(UpperCamelCase_							),
												]:
																	UpperCamelCase__   :Union[str, Any]												= torch.zeros(
																	    self.model_tester.batch_size    ,   dtype=torch.long    ,   device=UpperCamelCase_							)
												elif model_class in [
												    *get_values(UpperCamelCase_							),
												]:
																	UpperCamelCase__   :int												= torch.zeros(
																	    (self.model_tester.batch_size, self.model_tester.text_seq_length)    ,   dtype=torch.long    ,   device=UpperCamelCase_    ,   )

							return inputs_dict




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							self.config_tester.run_common_tests()




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Union[str, Any]												= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*UpperCamelCase_							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Dict												= self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
												UpperCamelCase__   :Optional[Any]												= type
												self.model_tester.create_and_check_model(*UpperCamelCase_							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :List[str]												= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase_							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[int]												= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(*UpperCamelCase_							)




		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :Optional[Any]												= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(*UpperCamelCase_							)




		@slow
		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												UpperCamelCase__   :Optional[Any]												= LayoutLMvaModel.from_pretrained(UpperCamelCase_							)
												self.assertIsNotNone(UpperCamelCase_							)



def 			a      (			)  ->	str:



					'''simple docstring'''






					UpperCamelCase__   :str												= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
					return image







@require_torch
class    lowercase	(							unittest.TestCase					):

		"""simple docstring"""

		@cached_property
		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							return LayoutLMvaImageProcessor(apply_ocr=UpperCamelCase_							) if is_vision_available() else None




		@slow
		def     lowerCAmelCase__				(		self							):

							'''simple docstring'''


							UpperCamelCase__   :List[Any]												= LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''							).to(UpperCamelCase_							)

							UpperCamelCase__   :List[str]												= self.default_image_processor
							UpperCamelCase__   :Optional[Any]												= prepare_img()
							UpperCamelCase__   :List[str]												= image_processor(images=UpperCamelCase_    ,   return_tensors='''pt'''							).pixel_values.to(UpperCamelCase_							)

							UpperCamelCase__   :List[str]												= torch.tensor([[1, 2]]							)
							UpperCamelCase__   :Optional[Any]												= torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]							).unsqueeze(0							)

							# forward pass
							UpperCamelCase__   :str												= model(
							    input_ids=input_ids.to(UpperCamelCase_							)    ,   bbox=bbox.to(UpperCamelCase_							)    ,   pixel_values=pixel_values.to(UpperCamelCase_							)    ,   )

							# verify the logits
							UpperCamelCase__   :Tuple												= torch.Size((1, 199, 768)							)
							self.assertEqual(outputs.last_hidden_state.shape    ,   UpperCamelCase_							)

							UpperCamelCase__   :Tuple												= torch.tensor(
							    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]							).to(UpperCamelCase_							)

							self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]    ,   UpperCamelCase_    ,   atol=1e-4							)							)



'''simple docstring'''
from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable


__snake_case							      =     {'''configuration_dpt''': ['''DPT_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''DPTConfig''']}

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__snake_case							      =     ['''DPTFeatureExtractor''']
		__snake_case							      =     ['''DPTImageProcessor''']

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		__snake_case							      =     [
		    '''DPT_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''DPTForDepthEstimation''',
		    '''DPTForSemanticSegmentation''',
		    '''DPTModel''',
		    '''DPTPreTrainedModel''',
		]


if TYPE_CHECKING:
		from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_dpt import DPTFeatureExtractor
				from .image_processing_dpt import DPTImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_dpt import (
				    DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    DPTForDepthEstimation,
				    DPTForSemanticSegmentation,
				    DPTModel,
				    DPTPreTrainedModel,
				)


else:
		import sys

		__snake_case							      =     _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)