






from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
		    TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
		    TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
		    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
		    TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
		    LayoutLMvaConfig,
		    TFLayoutLMvaForQuestionAnswering,
		    TFLayoutLMvaForSequenceClassification,
		    TFLayoutLMvaForTokenClassification,
		    TFLayoutLMvaModel,
		)

if is_vision_available():
		from PIL import Image

		from transformers import LayoutLMvaImageProcessor





class 	snake_case__ :
	def __init__(    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=7      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=True      ,       lowerCAmelCase__=99      ,       lowerCAmelCase__=36      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=37      ,       lowerCAmelCase__="gelu"      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=0.1      ,       lowerCAmelCase__=5_12      ,       lowerCAmelCase__=16      ,       lowerCAmelCase__=2      ,       lowerCAmelCase__=0.0_2      ,       lowerCAmelCase__=6      ,       lowerCAmelCase__=6      ,       lowerCAmelCase__=3      ,       lowerCAmelCase__=4      ,       lowerCAmelCase__=None      ,       lowerCAmelCase__=10_00      ,       )							->				Tuple:
							__magic_name__      :       int       						= parent
							__magic_name__      :       int       						= batch_size
							__magic_name__      :       Dict       						= num_channels
							__magic_name__      :       Optional[int]       						= image_size
							__magic_name__      :       List[Any]       						= patch_size
							__magic_name__      :       Optional[Any]       						= is_training
							__magic_name__      :       Dict       						= use_input_mask
							__magic_name__      :       Optional[int]       						= use_token_type_ids
							__magic_name__      :       str       						= use_labels
							__magic_name__      :       Any       						= vocab_size
							__magic_name__      :       int       						= hidden_size
							__magic_name__      :       int       						= num_hidden_layers
							__magic_name__      :       Union[str, Any]       						= num_attention_heads
							__magic_name__      :       Any       						= intermediate_size
							__magic_name__      :       Dict       						= hidden_act
							__magic_name__      :       List[Any]       						= hidden_dropout_prob
							__magic_name__      :       Optional[Any]       						= attention_probs_dropout_prob
							__magic_name__      :       List[Any]       						= max_position_embeddings
							__magic_name__      :       Optional[int]       						= type_vocab_size
							__magic_name__      :       Optional[int]       						= type_sequence_label_size
							__magic_name__      :       List[Any]       						= initializer_range
							__magic_name__      :       Any       						= coordinate_size
							__magic_name__      :       Dict       						= shape_size
							__magic_name__      :       Optional[int]       						= num_labels
							__magic_name__      :       int       						= num_choices
							__magic_name__      :       List[Any]       						= scope
							__magic_name__      :       str       						= range_bbox

							# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
							__magic_name__      :       Optional[Any]       						= text_seq_length
							__magic_name__      :       Tuple       						= (image_size // patch_size) ** 2 + 1
							__magic_name__      :       Any       						= self.text_seq_length + self.image_seq_length
	def       __magic_name__    (    self			)							->				str:
							__magic_name__      :       Any       						= ids_tensor([self.batch_size, self.text_seq_length]      ,       self.vocab_size			)

							__magic_name__      :       Optional[int]       						= ids_tensor([self.batch_size, self.text_seq_length, 4]      ,       self.range_bbox			)
							__magic_name__      :       Optional[Any]       						= bbox.numpy()
							# 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]:
																									__magic_name__      :       Tuple       						= bbox[i, j, 3]
																									__magic_name__      :       Union[str, Any]       						= bbox[i, j, 1]
																									__magic_name__      :       int       						= tmp_coordinate
																			if bbox[i, j, 2] < bbox[i, j, 0]:
																									__magic_name__      :       Union[str, Any]       						= bbox[i, j, 2]
																									__magic_name__      :       Tuple       						= bbox[i, j, 0]
																									__magic_name__      :       int       						= tmp_coordinate
							__magic_name__      :       List[str]       						= tf.constant(lowerCAmelCase__			)

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

							__magic_name__      :       Dict       						= None
							if self.use_input_mask:
													__magic_name__      :       Any       						= random_attention_mask([self.batch_size, self.text_seq_length]			)

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

							__magic_name__      :       Optional[int]       						= None
							__magic_name__      :       int       						= None
							if self.use_labels:
													__magic_name__      :       Optional[Any]       						= ids_tensor([self.batch_size]      ,       self.type_sequence_label_size			)
													__magic_name__      :       Tuple       						= ids_tensor([self.batch_size, self.text_seq_length]      ,       self.num_labels			)

							__magic_name__      :       Optional[int]       						= 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       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Union[str, Any]:
							__magic_name__      :       str       						= TFLayoutLMvaModel(config=lowerCAmelCase__			)

							# text + image
							__magic_name__      :       Dict       						= model(lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       training=lowerCAmelCase__			)
							__magic_name__      :       Union[str, Any]       						= model(
							    lowerCAmelCase__      ,       bbox=lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__      ,       training=lowerCAmelCase__      ,       )
							__magic_name__      :       List[str]       						= model(lowerCAmelCase__      ,       bbox=lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       training=lowerCAmelCase__			)

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

							# text only
							__magic_name__      :       List[str]       						= model(lowerCAmelCase__      ,       training=lowerCAmelCase__			)
							self.parent.assertEqual(
							    result.last_hidden_state.shape      ,       (self.batch_size, self.text_seq_length, self.hidden_size)			)

							# image only
							__magic_name__      :       Union[str, Any]       						= model({"""pixel_values""": pixel_values}      ,       training=lowerCAmelCase__			)
							self.parent.assertEqual(
							    result.last_hidden_state.shape      ,       (self.batch_size, self.image_seq_length, self.hidden_size)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Optional[Any]:
							__magic_name__      :       Tuple       						= self.num_labels
							__magic_name__      :       Any       						= TFLayoutLMvaForSequenceClassification(config=lowerCAmelCase__			)
							__magic_name__      :       Any       						= model(
							    lowerCAmelCase__      ,       bbox=lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__      ,       labels=lowerCAmelCase__      ,       training=lowerCAmelCase__      ,       )
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.num_labels)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				List[Any]:
							__magic_name__      :       Any       						= self.num_labels
							__magic_name__      :       Optional[int]       						= TFLayoutLMvaForTokenClassification(config=lowerCAmelCase__			)
							__magic_name__      :       Union[str, Any]       						= model(
							    lowerCAmelCase__      ,       bbox=lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__      ,       labels=lowerCAmelCase__      ,       training=lowerCAmelCase__      ,       )
							self.parent.assertEqual(result.logits.shape      ,       (self.batch_size, self.text_seq_length, self.num_labels)			)
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Any:
							__magic_name__      :       Any       						= 2
							__magic_name__      :       Any       						= TFLayoutLMvaForQuestionAnswering(config=lowerCAmelCase__			)
							__magic_name__      :       Optional[int]       						= model(
							    lowerCAmelCase__      ,       bbox=lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       attention_mask=lowerCAmelCase__      ,       token_type_ids=lowerCAmelCase__      ,       start_positions=lowerCAmelCase__      ,       end_positions=lowerCAmelCase__      ,       training=lowerCAmelCase__      ,       )
							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       __magic_name__    (    self			)							->				str:
							__magic_name__      :       Optional[int]       						= self.prepare_config_and_inputs()
							((__magic_name__)						,(__magic_name__)						,(__magic_name__)						,(__magic_name__)						,(__magic_name__)						,(__magic_name__)						,(__magic_name__)						,(__magic_name__))      :       str       						= config_and_inputs
							__magic_name__      :       Dict       						= {
							    """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_tf
class 	snake_case__ (							_lowerCAmelCase						,  _lowerCAmelCase						,  unittest.TestCase				):
	lowercase__						:					Optional[Any]											=   (
	    (
	        TFLayoutLMvaModel,
	        TFLayoutLMvaForQuestionAnswering,
	        TFLayoutLMvaForSequenceClassification,
	        TFLayoutLMvaForTokenClassification,
	    )
	    if is_tf_available()
	    else ()
	)
	lowercase__						:					Optional[Any]											=   (
	    {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
	    if is_tf_available()
	    else {}
	)

	lowercase__						:					Union[str, Any]											=   False
	lowercase__						:					Optional[int]											=   False
	lowercase__						:					Optional[Any]											=   False
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)							->				Optional[Any]:
							return True
	def       __magic_name__    (    self      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__=False			)							->				dict:
							__magic_name__      :       Dict       						= copy.deepcopy(lowerCAmelCase__			)

							if model_class in get_values(lowerCAmelCase__			):
													__magic_name__      :       Dict       						= {
													    k: tf.tile(tf.expand_dims(lowerCAmelCase__      ,       1			)      ,       (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)			)
													    if isinstance(lowerCAmelCase__      ,       tf.Tensor			) and v.ndim > 0
													    else v
													    for k, v in inputs_dict.items()
													}

							if return_labels:
													if model_class in get_values(lowerCAmelCase__			):
																			__magic_name__      :       Optional[int]       						= tf.ones(self.model_tester.batch_size      ,       dtype=tf.intaa			)
													elif model_class in get_values(lowerCAmelCase__			):
																			__magic_name__      :       Optional[Any]       						= tf.zeros(self.model_tester.batch_size      ,       dtype=tf.intaa			)
																			__magic_name__      :       List[str]       						= tf.zeros(self.model_tester.batch_size      ,       dtype=tf.intaa			)
													elif model_class in get_values(lowerCAmelCase__			):
																			__magic_name__      :       List[str]       						= tf.zeros(self.model_tester.batch_size      ,       dtype=tf.intaa			)
													elif model_class in get_values(lowerCAmelCase__			):
																			__magic_name__      :       Union[str, Any]       						= tf.zeros(
																			    (self.model_tester.batch_size, self.model_tester.text_seq_length)      ,       dtype=tf.intaa			)

							return inputs_dict
	def       __magic_name__    (    self			)							->				Any:
							__magic_name__      :       Tuple       						= TFLayoutLMvaModelTester(self			)
							__magic_name__      :       List[str]       						= ConfigTester(self      ,       config_class=lowerCAmelCase__      ,       hidden_size=37			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							self.config_tester.run_common_tests()
	def       __magic_name__    (    self			)							->				Tuple:
							__magic_name__						,__magic_name__      :       List[Any]       						= self.model_tester.prepare_config_and_inputs_for_common()
							for model_class in self.all_model_classes:
													__magic_name__      :       Optional[Any]       						= model_class(lowerCAmelCase__			)
													if getattr(lowerCAmelCase__      ,       """hf_compute_loss"""      ,       lowerCAmelCase__			):
																			# The number of elements in the loss should be the same as the number of elements in the label
																			__magic_name__      :       List[Any]       						= self._prepare_for_class(inputs_dict.copy()      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)
																			__magic_name__      :       Tuple       						= prepared_for_class[
																			    sorted(prepared_for_class.keys() - inputs_dict.keys()      ,       reverse=lowerCAmelCase__			)[0]
																			]
																			__magic_name__      :       Union[str, Any]       						= added_label.shape.as_list()[:1]

																			# Test that model correctly compute the loss with kwargs
																			__magic_name__      :       Any       						= self._prepare_for_class(inputs_dict.copy()      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)
																			__magic_name__      :       int       						= prepared_for_class.pop("""input_ids"""			)

																			__magic_name__      :       Optional[Any]       						= model(lowerCAmelCase__      ,       **lowerCAmelCase__			)[0]
																			self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

																			# Test that model correctly compute the loss when we mask some positions
																			__magic_name__      :       Union[str, Any]       						= self._prepare_for_class(inputs_dict.copy()      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)
																			__magic_name__      :       List[Any]       						= prepared_for_class.pop("""input_ids"""			)
																			if "labels" in prepared_for_class:
																									__magic_name__      :       List[Any]       						= prepared_for_class["""labels"""].numpy()
																									if len(labels.shape			) > 1 and labels.shape[1] != 1:
																															__magic_name__      :       Optional[int]       						= -1_00
																															__magic_name__      :       int       						= tf.convert_to_tensor(lowerCAmelCase__			)
																															__magic_name__      :       str       						= model(lowerCAmelCase__      ,       **lowerCAmelCase__			)[0]
																															self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)
																															self.assertTrue(not np.any(np.isnan(loss.numpy()			)			)			)

                # Test that model correctly compute the loss with a dict
																			__magic_name__      :       List[Any]       						= self._prepare_for_class(inputs_dict.copy()      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)
																			__magic_name__      :       Any       						= model(lowerCAmelCase__			)[0]
																			self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

																			# Test that model correctly compute the loss with a tuple
																			__magic_name__      :       Optional[Any]       						= self._prepare_for_class(inputs_dict.copy()      ,       lowerCAmelCase__      ,       return_labels=lowerCAmelCase__			)

																			# Get keys that were added with the _prepare_for_class function
																			__magic_name__      :       Union[str, Any]       						= prepared_for_class.keys() - inputs_dict.keys()
																			__magic_name__      :       Union[str, Any]       						= inspect.signature(model.call			).parameters
																			__magic_name__      :       List[str]       						= list(signature.keys()			)

																			# Create a dictionary holding the location of the tensors in the tuple
																			__magic_name__      :       Optional[int]       						= {0: """input_ids"""}
																			for label_key in label_keys:
																									__magic_name__      :       str       						= signature_names.index(lowerCAmelCase__			)
																									__magic_name__      :       Any       						= label_key
																			__magic_name__      :       Optional[int]       						= sorted(tuple_index_mapping.items()			)
																			# Initialize a list with their default values, update the values and convert to a tuple
																			__magic_name__      :       List[str]       						= []

																			for name in signature_names:
																									if name != "kwargs":
																															list_input.append(signature[name].default			)

																			for index, value in sorted_tuple_index_mapping:
																									__magic_name__      :       Tuple       						= prepared_for_class[value]

																			__magic_name__      :       Union[str, Any]       						= tuple(lowerCAmelCase__			)

																			# Send to model
																			__magic_name__      :       Tuple       						= model(tuple_input[:-1]			)[0]

																			self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)
	def       __magic_name__    (    self			)							->				Optional[Any]:
							(
							    (
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,
							)      :       Optional[int]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Tuple:
							(
							    (
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,
							)      :       Dict       						= self.model_tester.prepare_config_and_inputs()
							for type in ["absolute", "relative_key", "relative_key_query"]:
													__magic_name__      :       Any       						= type
													self.model_tester.create_and_check_model(lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Dict:
							(
							    (
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,
							)      :       int       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_sequence_classification(
							    lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Optional[int]:
							(
							    (
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,
							)      :       List[Any]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_token_classification(
							    lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)
	def       __magic_name__    (    self			)							->				Any:
							(
							    (
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,(
							    __magic_name__
							)						,
							)      :       Optional[int]       						= self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_question_answering(
							    lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__      ,       lowerCAmelCase__			)







	@slow
	def       __magic_name__    (    self			)							->				List[str]:
							for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__magic_name__      :       Optional[int]       						= TFLayoutLMvaModel.from_pretrained(lowerCAmelCase__			)
													self.assertIsNotNone(lowerCAmelCase__			)



def    UpperCamelCase						(	):






						"""simple docstring"""







						__magic_name__      :       int       						= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""			)
						return image





@require_tf
class 	snake_case__ (							unittest.TestCase				):
	@cached_property
	def       __magic_name__    (    self			)							->				List[str]:
							return LayoutLMvaImageProcessor(apply_ocr=lowerCAmelCase__			) if is_vision_available() else None







	@slow
	def       __magic_name__    (    self			)							->				int:
							__magic_name__      :       Union[str, Any]       						= TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""			)

							__magic_name__      :       Optional[int]       						= self.default_image_processor
							__magic_name__      :       Any       						= prepare_img()
							__magic_name__      :       Dict       						= image_processor(images=lowerCAmelCase__      ,       return_tensors="""tf"""			).pixel_values

							__magic_name__      :       Tuple       						= tf.constant([[1, 2]]			)
							__magic_name__      :       Dict       						= tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]			)      ,       axis=0			)

							# forward pass
							__magic_name__      :       Dict       						= model(input_ids=lowerCAmelCase__      ,       bbox=lowerCAmelCase__      ,       pixel_values=lowerCAmelCase__      ,       training=lowerCAmelCase__			)

							# verify the logits
							__magic_name__      :       Dict       						= (1, 1_99, 7_68)
							self.assertEqual(outputs.last_hidden_state.shape      ,       lowerCAmelCase__			)

							__magic_name__      :       Union[str, Any]       						= tf.constant(
							    [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]			)

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








import os
from pathlib import Path

def    UpperCamelCase						(	):






						"""simple docstring"""







						from torch.utils.cpp_extension import load

						__magic_name__      :       Dict       						= Path(_A			).resolve().parent.parent.parent / """kernels""" / """deformable_detr"""
						__magic_name__      :       Optional[int]       						= [
						    root / filename
						    for filename in [
						        """vision.cpp""",
						        os.path.join("""cpu""",   """ms_deform_attn_cpu.cpp"""			),
						        os.path.join("""cuda""",   """ms_deform_attn_cuda.cu"""			),
						    ]
						]

						load(
						    """MultiScaleDeformableAttention""",   _A,   with_cuda=_A,   extra_include_paths=[str(_A			)],   extra_cflags=["""-DWITH_CUDA=1"""],   extra_cuda_cflags=[
						        """-DCUDA_HAS_FP16=1""",
						        """-D__CUDA_NO_HALF_OPERATORS__""",
						        """-D__CUDA_NO_HALF_CONVERSIONS__""",
						        """-D__CUDA_NO_HALF2_OPERATORS__""",
						    ],   )

						import MultiScaleDeformableAttention as MSDA

						return MSDA
