






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        lowerCAmelCase_				:







				"""simple docstring"""




				def __init__( self     :Union[str, Any]  ,     lowerCamelCase__     :Tuple  ,     lowerCamelCase__     :List[str]=2  ,     lowerCamelCase__     :List[str]=3  ,     lowerCamelCase__     :List[str]=4  ,     lowerCamelCase__     :str=2  ,     lowerCamelCase__     :Optional[int]=7  ,     lowerCamelCase__     :List[Any]=True  ,     lowerCamelCase__     :Optional[Any]=True  ,     lowerCamelCase__     :Union[str, Any]=True  ,     lowerCamelCase__     :Any=True  ,     lowerCamelCase__     :Dict=99  ,     lowerCamelCase__     :Optional[Any]=36  ,     lowerCamelCase__     :str=2  ,     lowerCamelCase__     :List[Any]=4  ,     lowerCamelCase__     :Optional[Any]=37  ,     lowerCamelCase__     :Optional[int]="gelu"  ,     lowerCamelCase__     :Any=0.1  ,     lowerCamelCase__     :List[Any]=0.1  ,     lowerCamelCase__     :List[Any]=5_12  ,     lowerCamelCase__     :str=16  ,     lowerCamelCase__     :Tuple=2  ,     lowerCamelCase__     :int=0.02  ,     lowerCamelCase__     :List[Any]=6  ,     lowerCamelCase__     :List[str]=6  ,     lowerCamelCase__     :Optional[int]=3  ,     lowerCamelCase__     :Optional[int]=4  ,     lowerCamelCase__     :int=None  ,     lowerCamelCase__     :Optional[Any]=10_00  ,     ):
					UpperCamelCase__ :Any						=      parent
					UpperCamelCase__ :Union[str, Any]						=      batch_size
					UpperCamelCase__ :Dict						=      num_channels
					UpperCamelCase__ :Optional[Any]						=      image_size
					UpperCamelCase__ :Union[str, Any]						=      patch_size
					UpperCamelCase__ :Union[str, Any]						=      is_training
					UpperCamelCase__ :str						=      use_input_mask
					UpperCamelCase__ :int						=      use_token_type_ids
					UpperCamelCase__ :int						=      use_labels
					UpperCamelCase__ :List[Any]						=      vocab_size
					UpperCamelCase__ :List[str]						=      hidden_size
					UpperCamelCase__ :List[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__ :Tuple						=      attention_probs_dropout_prob
					UpperCamelCase__ :Dict						=      max_position_embeddings
					UpperCamelCase__ :Tuple						=      type_vocab_size
					UpperCamelCase__ :Union[str, Any]						=      type_sequence_label_size
					UpperCamelCase__ :int						=      initializer_range
					UpperCamelCase__ :List[Any]						=      coordinate_size
					UpperCamelCase__ :Tuple						=      shape_size
					UpperCamelCase__ :Dict						=      num_labels
					UpperCamelCase__ :str						=      num_choices
					UpperCamelCase__ :Tuple						=      scope
					UpperCamelCase__ :str						=      range_bbox

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







				def 				__a   ( self     :Tuple     ):
					UpperCamelCase__ :Optional[int]						=      ids_tensor([self.batch_size, self.text_seq_length]  ,     self.vocab_size     )

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

					UpperCamelCase__ :Union[str, Any]						=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

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

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

					UpperCamelCase__ :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 				__a   ( self     :List[Any]  ,     lowerCamelCase__     :str  ,     lowerCamelCase__     :Optional[int]  ,     lowerCamelCase__     :Dict  ,     lowerCamelCase__     :str  ,     lowerCamelCase__     :int  ,     lowerCamelCase__     :Any     ):
					UpperCamelCase__ :Dict						=      TFLayoutLMvaModel(config=lowerCamelCase__     )

					# text + image
					UpperCamelCase__ :Tuple						=      model(lowerCamelCase__  ,     pixel_values=lowerCamelCase__  ,     training=lowerCamelCase__     )
					UpperCamelCase__ :Tuple						=      model(
					    lowerCamelCase__  ,     bbox=lowerCamelCase__  ,     pixel_values=lowerCamelCase__  ,     attention_mask=lowerCamelCase__  ,     token_type_ids=lowerCamelCase__  ,     training=lowerCamelCase__  ,     )
					UpperCamelCase__ :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
					UpperCamelCase__ :Optional[int]						=      model(lowerCamelCase__  ,     training=lowerCamelCase__     )
					self.parent.assertEqual(
					    result.last_hidden_state.shape  ,     (self.batch_size, self.text_seq_length, self.hidden_size)     )

					# image only
					UpperCamelCase__ :Tuple						=      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 				__a   ( self     :Dict  ,     lowerCamelCase__     :str  ,     lowerCamelCase__     :Union[str, Any]  ,     lowerCamelCase__     :Dict  ,     lowerCamelCase__     :Union[str, Any]  ,     lowerCamelCase__     :str  ,     lowerCamelCase__     :Optional[Any]  ,     lowerCamelCase__     :str     ):
					UpperCamelCase__ :Optional[Any]						=      self.num_labels
					UpperCamelCase__ :List[Any]						=      TFLayoutLMvaForSequenceClassification(config=lowerCamelCase__     )
					UpperCamelCase__ :List[str]						=      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 				__a   ( self     :List[str]  ,     lowerCamelCase__     :List[str]  ,     lowerCamelCase__     :Union[str, Any]  ,     lowerCamelCase__     :Dict  ,     lowerCamelCase__     :List[Any]  ,     lowerCamelCase__     :Optional[int]  ,     lowerCamelCase__     :Tuple  ,     lowerCamelCase__     :List[str]     ):
					UpperCamelCase__ :Union[str, Any]						=      self.num_labels
					UpperCamelCase__ :Dict						=      TFLayoutLMvaForTokenClassification(config=lowerCamelCase__     )
					UpperCamelCase__ :Optional[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 				__a   ( self     :int  ,     lowerCamelCase__     :Dict  ,     lowerCamelCase__     :Optional[Any]  ,     lowerCamelCase__     :Optional[Any]  ,     lowerCamelCase__     :Any  ,     lowerCamelCase__     :Dict  ,     lowerCamelCase__     :Tuple  ,     lowerCamelCase__     :Tuple     ):
					UpperCamelCase__ :Dict						=      2
					UpperCamelCase__ :Tuple						=      TFLayoutLMvaForQuestionAnswering(config=lowerCamelCase__     )
					UpperCamelCase__ :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 				__a   ( self     :List[Any]     ):
					UpperCamelCase__ :Union[str, Any]						=      self.prepare_config_and_inputs()
					((UpperCamelCase__)				,		(UpperCamelCase__)				,		(UpperCamelCase__)				,		(UpperCamelCase__)				,		(UpperCamelCase__)				,		(UpperCamelCase__)				,		(UpperCamelCase__)				,		(UpperCamelCase__)) :Any						=      config_and_inputs
					UpperCamelCase__ :List[str]						=      {
					    """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        lowerCAmelCase_				(      lowercase						,      lowercase						,      unittest.TestCase	):







				"""simple docstring"""




				_snake_case				:   Dict        =			(
				    (
				        TFLayoutLMvaModel,
				        TFLayoutLMvaForQuestionAnswering,
				        TFLayoutLMvaForSequenceClassification,
				        TFLayoutLMvaForTokenClassification,
				    )
				    if is_tf_available()
				    else ()
				)
				_snake_case				:   Dict        =			(
				    {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel}
				    if is_tf_available()
				    else {}
				)

				_snake_case				:   Optional[int]        =			False
				_snake_case				:   List[str]        =			False
				_snake_case				:   Tuple        =			False







				def 				__a   ( self     :str  ,     lowerCamelCase__     :Optional[int]  ,     lowerCamelCase__     :Union[str, Any]  ,     lowerCamelCase__     :Optional[Any]  ,     lowerCamelCase__     :Tuple  ,     lowerCamelCase__     :int     ):
					return True







				def 				__a   ( self     :Optional[int]  ,     lowerCamelCase__     :int  ,     lowerCamelCase__     :List[str]  ,     lowerCamelCase__     :Optional[int]=False     ):
					UpperCamelCase__ :List[str]						=      copy.deepcopy(lowerCamelCase__     )

					if model_class in get_values(lowerCamelCase__     ):
						UpperCamelCase__ :Optional[int]						=      {
						    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__     ):
							UpperCamelCase__ :str						=      tf.ones(self.model_tester.batch_size  ,     dtype=tf.intaa     )
						elif model_class in get_values(lowerCamelCase__     ):
							UpperCamelCase__ :List[str]						=      tf.zeros(self.model_tester.batch_size  ,     dtype=tf.intaa     )
							UpperCamelCase__ :Union[str, Any]						=      tf.zeros(self.model_tester.batch_size  ,     dtype=tf.intaa     )
						elif model_class in get_values(lowerCamelCase__     ):
							UpperCamelCase__ :Optional[Any]						=      tf.zeros(self.model_tester.batch_size  ,     dtype=tf.intaa     )
						elif model_class in get_values(lowerCamelCase__     ):
							UpperCamelCase__ :Tuple						=      tf.zeros(
							    (self.model_tester.batch_size, self.model_tester.text_seq_length)  ,     dtype=tf.intaa     )

					return inputs_dict







				def 				__a   ( self     :Dict     ):
					UpperCamelCase__ :List[Any]						=      TFLayoutLMvaModelTester(self     )
					UpperCamelCase__ :Optional[int]						=      ConfigTester(self  ,     config_class=lowerCamelCase__  ,     hidden_size=37     )







				def 				__a   ( self     :Any     ):
					self.config_tester.run_common_tests()







				def 				__a   ( self     :Optional[int]     ):
					UpperCamelCase__				,		UpperCamelCase__ :Any						=      self.model_tester.prepare_config_and_inputs_for_common()
					for model_class in self.all_model_classes:
						UpperCamelCase__ :Optional[int]						=      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
							UpperCamelCase__ :Union[str, Any]						=      self._prepare_for_class(inputs_dict.copy()  ,     lowerCamelCase__  ,     return_labels=lowerCamelCase__     )
							UpperCamelCase__ :int						=      prepared_for_class[
							    sorted(prepared_for_class.keys() - inputs_dict.keys()  ,     reverse=lowerCamelCase__     )[0]
							]
							UpperCamelCase__ :Union[str, Any]						=      added_label.shape.as_list()[:1]

							# Test that model correctly compute the loss with kwargs
							UpperCamelCase__ :List[Any]						=      self._prepare_for_class(inputs_dict.copy()  ,     lowerCamelCase__  ,     return_labels=lowerCamelCase__     )
							UpperCamelCase__ :Optional[Any]						=      prepared_for_class.pop("""input_ids"""     )

							UpperCamelCase__ :List[str]						=      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
							UpperCamelCase__ :Union[str, Any]						=      self._prepare_for_class(inputs_dict.copy()  ,     lowerCamelCase__  ,     return_labels=lowerCamelCase__     )
							UpperCamelCase__ :Optional[Any]						=      prepared_for_class.pop("""input_ids"""     )
							if "labels" in prepared_for_class:
								UpperCamelCase__ :List[str]						=      prepared_for_class["""labels"""].numpy()
								if len(labels.shape     ) > 1 and labels.shape[1] != 1:
									UpperCamelCase__ :Optional[Any]						=      -1_00
									UpperCamelCase__ :Union[str, Any]						=      tf.convert_to_tensor(lowerCamelCase__     )
									UpperCamelCase__ :Tuple						=      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
							UpperCamelCase__ :Optional[Any]						=      self._prepare_for_class(inputs_dict.copy()  ,     lowerCamelCase__  ,     return_labels=lowerCamelCase__     )
							UpperCamelCase__ :Union[str, 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
							UpperCamelCase__ :Dict						=      self._prepare_for_class(inputs_dict.copy()  ,     lowerCamelCase__  ,     return_labels=lowerCamelCase__     )

							# Get keys that were added with the _prepare_for_class function
							UpperCamelCase__ :str						=      prepared_for_class.keys() - inputs_dict.keys()
							UpperCamelCase__ :Tuple						=      inspect.signature(model.call     ).parameters
							UpperCamelCase__ :str						=      list(signature.keys()     )

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

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

							for index, value in sorted_tuple_index_mapping:
								UpperCamelCase__ :List[str]						=      prepared_for_class[value]

							UpperCamelCase__ :Union[str, Any]						=      tuple(lowerCamelCase__     )

							# Send to model
							UpperCamelCase__ :str						=      model(tuple_input[:-1]     )[0]

							self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]     )







				def 				__a   ( self     :Optional[int]     ):
					(
					    (
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		
					) :Any						=      self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__     )







				def 				__a   ( self     :Any     ):
					(
					    (
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		
					) :List[Any]						=      self.model_tester.prepare_config_and_inputs()
					for type in ["absolute", "relative_key", "relative_key_query"]:
						UpperCamelCase__ :Dict						=      type
						self.model_tester.create_and_check_model(lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__  ,     lowerCamelCase__     )







				def 				__a   ( self     :Tuple     ):
					(
					    (
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		
					) :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 				__a   ( self     :Optional[int]     ):
					(
					    (
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		
					) :Union[str, 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 				__a   ( self     :List[str]     ):
					(
					    (
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		(
					    UpperCamelCase__
					)				,		
					) :Tuple						=      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 				__a   ( self     :Optional[int]     ):
					for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
						UpperCamelCase__ :Dict						=      TFLayoutLMvaModel.from_pretrained(lowerCamelCase__     )
						self.assertIsNotNone(lowerCamelCase__     )




def 				A		(					)		-> List[str]:
	UpperCamelCase__ :List[Any]						=      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
	return image




@require_tf
class        lowerCAmelCase_				(      unittest.TestCase	):







				"""simple docstring"""




				@cached_property
				def 				__a   ( self     :Optional[Any]     ):
					return LayoutLMvaImageProcessor(apply_ocr=lowerCamelCase__     ) if is_vision_available() else None







				@slow
				def 				__a   ( self     :Dict     ):
					UpperCamelCase__ :List[str]						=      TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""     )

					UpperCamelCase__ :List[Any]						=      self.default_image_processor
					UpperCamelCase__ :str						=      prepare_img()
					UpperCamelCase__ :Any						=      image_processor(images=lowerCamelCase__  ,     return_tensors="""tf"""     ).pixel_values

					UpperCamelCase__ :str						=      tf.constant([[1, 2]]     )
					UpperCamelCase__ :Any						=      tf.expand_dims(tf.constant([[1, 2, 3, 4], [5, 6, 7, 8]]     )  ,     axis=0     )

					# forward pass
					UpperCamelCase__ :Dict						=      model(input_ids=lowerCamelCase__  ,     bbox=lowerCamelCase__  ,     pixel_values=lowerCamelCase__  ,     training=lowerCamelCase__     )

					# verify the logits
					UpperCamelCase__ :int						=      (1, 1_99, 7_68)
					self.assertEqual(outputs.last_hidden_state.shape  ,     lowerCamelCase__     )

					UpperCamelCase__ :List[Any]						=      tf.constant(
					    [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]     )

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

"""simple docstring"""


import copy
import re







class 					lowerCAmelCase_					:



						'''simple docstring'''


						_lowerCamelCase:     str   =     '''hp'''
						_lowerCamelCase:     List[Any]   =     {}
						_lowerCamelCase:     List[Any]   =     None


						@classmethod
						def     _SCREAMING_SNAKE_CASE   (			cls  :   List[Any]	,A_  :   List[str]	,A_  :   Optional[Any]   )  -> Tuple:
							A     = prefix
							A     = defaults
							cls.build_naming_info()


						@staticmethod
						def     _SCREAMING_SNAKE_CASE   (			A_  :   Any	,A_  :   List[Any]   )  -> int:
							if len(A_   ) == 0:
								return ""
							A     = None
							if any(char.isdigit() for char in word   ):
								raise Exception(F'Parameters should not contain numbers: \'{word}\' contains a number'   )
							if word in info["short_word"]:
								return info["short_word"][word]
							for prefix_len in range(1	,len(A_   ) + 1   ):
								A     = word[:prefix_len]
								if prefix in info["reverse_short_word"]:
									continue
								else:
									A     = prefix
									break

							if short_word is None:
								# Paranoid fallback
								def int_to_alphabetic(A_  :   Optional[Any]   ):
									A     = ''
									while integer != 0:
										A     = chr(ord('A'   ) + integer % 10   ) + s
										integer //= 10
									return s

								A     = 0
								while True:
									A     = word + '#' + int_to_alphabetic(A_   )
									if sword in info["reverse_short_word"]:
										continue
									else:
										A     = sword
										break

							A     = short_word
							A     = word
							return short_word


						@staticmethod
						def     _SCREAMING_SNAKE_CASE   (			A_  :   List[Any]	,A_  :   Union[str, Any]   )  -> Union[str, Any]:
							A     = param_name.split('_'   )

							A     = [TrialShortNamer.shortname_for_word(A_	,A_   ) for word in words]

							# We try to create a separatorless short name, but if there is a collision we have to fallback
							# to a separated short name
							A     = ['', '_']

							for separator in separators:
								A     = separator.join(A_   )
								if shortname not in info["reverse_short_param"]:
									A     = shortname
									A     = param_name
									return shortname

							return param_name


						@staticmethod
						def     _SCREAMING_SNAKE_CASE   (			A_  :   List[Any]	,A_  :   Any   )  -> Tuple:
							A     = TrialShortNamer.shortname_for_key(A_	,A_   )
							A     = short_name
							A     = param_name


						@classmethod
						def     _SCREAMING_SNAKE_CASE   (			cls  :   Dict   )  -> List[Any]:
							if cls.NAMING_INFO is not None:
								return

							A     = {
							    'short_word': {},
							    'reverse_short_word': {},
							    'short_param': {},
							    'reverse_short_param': {},
							}

							A     = list(cls.DEFAULTS.keys()   )

							for k in field_keys:
								cls.add_new_param_name(A_	,A_   )

							A     = info


						@classmethod
						def     _SCREAMING_SNAKE_CASE   (			cls  :   List[Any]	,A_  :   Union[str, Any]   )  -> Union[str, Any]:
							cls.build_naming_info()
							assert cls.PREFIX is not None
							A     = [copy.copy(cls.PREFIX   )]

							for k, v in params.items():
								if k not in cls.DEFAULTS:
									raise Exception(F'You should provide a default value for the param name {k} with value {v}'   )
								if v == cls.DEFAULTS[k]:
									# The default value is not added to the name
									continue

								A     = cls.NAMING_INFO['short_param'][k]

								if isinstance(A_	,A_   ):
									A     = 1 if v else 0

								A     = '' if isinstance(A_	,(int, float)   ) else '-'
								A     = F'{key}{sep}{v}'
								name.append(A_   )

							return "_".join(A_   )




						@classmethod
						def     _SCREAMING_SNAKE_CASE   (			cls  :   List[str]	,A_  :   Any   )  -> int:
							A     = repr[len(cls.PREFIX   ) + 1 :]
							if repr == "":
								A     = []
							else:
								A     = repr.split('_'   )

							A     = {}

							for value in values:
								if "-" in value:
									A ,   A     = value.split('-'   )
								else:
									A     = re.sub('[0-9.]'	,''	,A_   )
									A     = float(re.sub('[^0-9.]'	,''	,A_   )   )

								A     = cls.NAMING_INFO['reverse_short_param'][p_k]

								A     = p_v

							for k in cls.DEFAULTS:
								if k not in parameters:
									A     = cls.DEFAULTS[k]

							return parameters