


'''simple docstring'''


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





							'''simple docstring'''


							def __init__(       self       ,   __snake_case       ,   __snake_case=2       ,   __snake_case=3       ,   __snake_case=4       ,   __snake_case=2       ,   __snake_case=7       ,   __snake_case=True       ,   __snake_case=True       ,   __snake_case=True       ,   __snake_case=True       ,   __snake_case=99       ,   __snake_case=36       ,   __snake_case=2       ,   __snake_case=4       ,   __snake_case=37       ,   __snake_case="gelu"       ,   __snake_case=0.1       ,   __snake_case=0.1       ,   __snake_case=512       ,   __snake_case=16       ,   __snake_case=2       ,   __snake_case=0.02       ,   __snake_case=6       ,   __snake_case=6       ,   __snake_case=3       ,   __snake_case=4       ,   __snake_case=None       ,   __snake_case=1000       ,   ):
											_SCREAMING_SNAKE_CASE					:			int							= parent
											_SCREAMING_SNAKE_CASE					:			Tuple							= batch_size
											_SCREAMING_SNAKE_CASE					:			List[Any]							= num_channels
											_SCREAMING_SNAKE_CASE					:			str							= image_size
											_SCREAMING_SNAKE_CASE					:			Tuple							= patch_size
											_SCREAMING_SNAKE_CASE					:			Tuple							= is_training
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= use_input_mask
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= use_token_type_ids
											_SCREAMING_SNAKE_CASE					:			Dict							= use_labels
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= vocab_size
											_SCREAMING_SNAKE_CASE					:			str							= hidden_size
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= num_hidden_layers
											_SCREAMING_SNAKE_CASE					:			str							= num_attention_heads
											_SCREAMING_SNAKE_CASE					:			int							= intermediate_size
											_SCREAMING_SNAKE_CASE					:			List[str]							= hidden_act
											_SCREAMING_SNAKE_CASE					:			Tuple							= hidden_dropout_prob
											_SCREAMING_SNAKE_CASE					:			int							= attention_probs_dropout_prob
											_SCREAMING_SNAKE_CASE					:			int							= max_position_embeddings
											_SCREAMING_SNAKE_CASE					:			Tuple							= type_vocab_size
											_SCREAMING_SNAKE_CASE					:			str							= type_sequence_label_size
											_SCREAMING_SNAKE_CASE					:			Dict							= initializer_range
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= coordinate_size
											_SCREAMING_SNAKE_CASE					:			List[str]							= shape_size
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= num_labels
											_SCREAMING_SNAKE_CASE					:			Dict							= num_choices
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= scope
											_SCREAMING_SNAKE_CASE					:			int							= range_bbox

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






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Dict							= ids_tensor([self.batch_size, self.text_seq_length]       ,   self.vocab_size    )

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

											_SCREAMING_SNAKE_CASE					:			int							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

											_SCREAMING_SNAKE_CASE					:			List[Any]							= None
											if self.use_input_mask:
															_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= random_attention_mask([self.batch_size, self.text_seq_length]    )

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

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

											_SCREAMING_SNAKE_CASE					:			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 UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			Any							= TFLayoutLMvaModel(config=__snake_case    )

											# text + image
											_SCREAMING_SNAKE_CASE					:			List[Any]							= model(__snake_case       ,   pixel_values=__snake_case       ,   training=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= model(
											    __snake_case       ,   bbox=__snake_case       ,   pixel_values=__snake_case       ,   attention_mask=__snake_case       ,   token_type_ids=__snake_case       ,   training=__snake_case       ,   )
											_SCREAMING_SNAKE_CASE					:			Dict							= model(__snake_case       ,   bbox=__snake_case       ,   pixel_values=__snake_case       ,   training=__snake_case    )

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

											# text only
											_SCREAMING_SNAKE_CASE					:			int							= model(__snake_case       ,   training=__snake_case    )
											self.parent.assertEqual(
											    result.last_hidden_state.shape       ,   (self.batch_size, self.text_seq_length, self.hidden_size)    )

											# image only
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= model({"""pixel_values""": pixel_values}       ,   training=__snake_case    )
											self.parent.assertEqual(
											    result.last_hidden_state.shape       ,   (self.batch_size, self.image_seq_length, self.hidden_size)    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= self.num_labels
											_SCREAMING_SNAKE_CASE					:			Tuple							= TFLayoutLMvaForSequenceClassification(config=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			int							= model(
											    __snake_case       ,   bbox=__snake_case       ,   pixel_values=__snake_case       ,   attention_mask=__snake_case       ,   token_type_ids=__snake_case       ,   labels=__snake_case       ,   training=__snake_case       ,   )
											self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.num_labels)    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			List[Any]							= self.num_labels
											_SCREAMING_SNAKE_CASE					:			str							= TFLayoutLMvaForTokenClassification(config=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= model(
											    __snake_case       ,   bbox=__snake_case       ,   pixel_values=__snake_case       ,   attention_mask=__snake_case       ,   token_type_ids=__snake_case       ,   labels=__snake_case       ,   training=__snake_case       ,   )
											self.parent.assertEqual(result.logits.shape       ,   (self.batch_size, self.text_seq_length, self.num_labels)    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= 2
											_SCREAMING_SNAKE_CASE					:			Tuple							= TFLayoutLMvaForQuestionAnswering(config=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Any							= model(
											    __snake_case       ,   bbox=__snake_case       ,   pixel_values=__snake_case       ,   attention_mask=__snake_case       ,   token_type_ids=__snake_case       ,   start_positions=__snake_case       ,   end_positions=__snake_case       ,   training=__snake_case       ,   )
											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 UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= self.prepare_config_and_inputs()
											((_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE)						,			(_SCREAMING_SNAKE_CASE))					:			Any							= config_and_inputs
											_SCREAMING_SNAKE_CASE					:			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        lowercase__    (		_snake_case	,	_snake_case	,	unittest.TestCase   ):





							'''simple docstring'''


							A_				: int       =    (
							    (
							        TFLayoutLMvaModel,
							        TFLayoutLMvaForQuestionAnswering,
							        TFLayoutLMvaForSequenceClassification,
							        TFLayoutLMvaForTokenClassification,
							    )
							    if is_tf_available()
							    else ()
							)
							A_				: List[Any]       =    (
							    {"""document-question-answering""": TFLayoutLMvaForQuestionAnswering, """feature-extraction""": TFLayoutLMvaModel}
							    if is_tf_available()
							    else {}
							)

							A_				: Dict       =    False
							A_				: List[Any]       =    False
							A_				: Union[str, Any]       =    False






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    ):
											return True






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case=False    ):
											_SCREAMING_SNAKE_CASE					:			Any							= copy.deepcopy(__snake_case    )

											if model_class in get_values(__snake_case    ):
															_SCREAMING_SNAKE_CASE					:			Optional[int]							= {
															    k: tf.tile(tf.expand_dims(__snake_case       ,   1    )       ,   (1, self.model_tester.num_choices) + (1,) * (v.ndim - 1)    )
															    if isinstance(__snake_case       ,   tf.Tensor    ) and v.ndim > 0
															    else v
															    for k, v in inputs_dict.items()
															}

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

											return inputs_dict






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= TFLayoutLMvaModelTester(self    )
											_SCREAMING_SNAKE_CASE					:			Dict							= ConfigTester(self       ,   config_class=__snake_case       ,   hidden_size=37    )






							def UpperCAmelCase_      (       self    ):
											self.config_tester.run_common_tests()






							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE						,			_SCREAMING_SNAKE_CASE					:			List[str]							= self.model_tester.prepare_config_and_inputs_for_common()
											for model_class in self.all_model_classes:
															_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= model_class(__snake_case    )
															if getattr(__snake_case       ,   """hf_compute_loss"""       ,   __snake_case    ):
																			# The number of elements in the loss should be the same as the number of elements in the label
																			_SCREAMING_SNAKE_CASE					:			List[str]							= self._prepare_for_class(inputs_dict.copy()       ,   __snake_case       ,   return_labels=__snake_case    )
																			_SCREAMING_SNAKE_CASE					:			str							= prepared_for_class[
																			    sorted(prepared_for_class.keys() - inputs_dict.keys()       ,   reverse=__snake_case    )[0]
																			]
																			_SCREAMING_SNAKE_CASE					:			List[str]							= added_label.shape.as_list()[:1]

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

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

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

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

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

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

																			_SCREAMING_SNAKE_CASE					:			Dict							= tuple(__snake_case    )

																			# Send to model
																			_SCREAMING_SNAKE_CASE					:			List[Any]							= model(tuple_input[:-1]    )[0]

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






							def UpperCAmelCase_      (       self    ):
											(
											    (
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			
											)					:			Optional[Any]							= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(__snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    )






							def UpperCAmelCase_      (       self    ):
											(
											    (
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			
											)					:			Any							= self.model_tester.prepare_config_and_inputs()
											for type in ["absolute", "relative_key", "relative_key_query"]:
															_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= type
															self.model_tester.create_and_check_model(__snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    )






							def UpperCAmelCase_      (       self    ):
											(
											    (
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			
											)					:			Any							= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_sequence_classification(
											    __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    )






							def UpperCAmelCase_      (       self    ):
											(
											    (
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			
											)					:			List[str]							= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_token_classification(
											    __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    )






							def UpperCAmelCase_      (       self    ):
											(
											    (
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			(
											    _SCREAMING_SNAKE_CASE
											)						,			
											)					:			Optional[Any]							= self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_question_answering(
											    __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case    )






							@slow
							def UpperCAmelCase_      (       self    ):
											for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															_SCREAMING_SNAKE_CASE					:			Optional[int]							= TFLayoutLMvaModel.from_pretrained(__snake_case    )
															self.assertIsNotNone(__snake_case    )







def      snake_case_  (    ):







				"""simple docstring"""





				_SCREAMING_SNAKE_CASE					:			Optional[Any]							= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
				return image







@require_tf
class        lowercase__    (		unittest.TestCase   ):





							'''simple docstring'''


							@cached_property
							def UpperCAmelCase_      (       self    ):
											return LayoutLMvaImageProcessor(apply_ocr=__snake_case    ) if is_vision_available() else None






							@slow
							def UpperCAmelCase_      (       self    ):
											_SCREAMING_SNAKE_CASE					:			Any							= TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""    )

											_SCREAMING_SNAKE_CASE					:			Tuple							= self.default_image_processor
											_SCREAMING_SNAKE_CASE					:			Any							= prepare_img()
											_SCREAMING_SNAKE_CASE					:			int							= image_processor(images=__snake_case       ,   return_tensors="""tf"""    ).pixel_values

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

											# forward pass
											_SCREAMING_SNAKE_CASE					:			Dict							= model(input_ids=__snake_case       ,   bbox=__snake_case       ,   pixel_values=__snake_case       ,   training=__snake_case    )

											# verify the logits
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= (1, 199, 768)
											self.assertEqual(outputs.last_hidden_state.shape       ,   __snake_case    )

											_SCREAMING_SNAKE_CASE					:			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]       ,   __snake_case       ,   atol=1e-4    )    )








'''simple docstring'''


from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


UpperCAmelCase_						:  int				  =						logging.get_logger(__name__)


if is_vision_available():
				import PIL





class        lowercase__    (		_snake_case   ):





							'''simple docstring'''


							A_				: int       =    ["""pixel_values"""]






							def __init__(       self       ,   __snake_case = True       ,   __snake_case = None       ,   __snake_case = PILImageResampling.BICUBIC       ,   __snake_case = True       ,   __snake_case = None       ,   __snake_case = True       ,   __snake_case = 1 / 255       ,   __snake_case = True       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = True       ,   **__snake_case       ,   ):
											super().__init__(**__snake_case    )
											_SCREAMING_SNAKE_CASE					:			int							= size if size is not None else {"""shortest_edge""": 224}
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= get_size_dict(__snake_case       ,   default_to_square=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= crop_size if crop_size is not None else {"""height""": 224, """width""": 224}
											_SCREAMING_SNAKE_CASE					:			Any							= get_size_dict(__snake_case       ,   default_to_square=__snake_case       ,   param_name="""crop_size"""    )

											_SCREAMING_SNAKE_CASE					:			str							= do_resize
											_SCREAMING_SNAKE_CASE					:			Union[str, Any]							= size
											_SCREAMING_SNAKE_CASE					:			List[str]							= resample
											_SCREAMING_SNAKE_CASE					:			str							= do_center_crop
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= crop_size
											_SCREAMING_SNAKE_CASE					:			Tuple							= do_rescale
											_SCREAMING_SNAKE_CASE					:			Dict							= rescale_factor
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= do_normalize
											_SCREAMING_SNAKE_CASE					:			List[Any]							= image_mean if image_mean is not None else OPENAI_CLIP_MEAN
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= image_std if image_std is not None else OPENAI_CLIP_STD
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= do_convert_rgb






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case = PILImageResampling.BICUBIC       ,   __snake_case = None       ,   **__snake_case       ,   ):
											_SCREAMING_SNAKE_CASE					:			int							= get_size_dict(__snake_case       ,   default_to_square=__snake_case    )
											if "shortest_edge" not in size:
															raise ValueError(f"""The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}"""    )
											_SCREAMING_SNAKE_CASE					:			Any							= get_resize_output_image_size(__snake_case       ,   size=size["""shortest_edge"""]       ,   default_to_square=__snake_case    )
											return resize(__snake_case       ,   size=__snake_case       ,   resample=__snake_case       ,   data_format=__snake_case       ,   **__snake_case    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case = None       ,   **__snake_case       ,   ):
											_SCREAMING_SNAKE_CASE					:			List[str]							= get_size_dict(__snake_case    )
											if "height" not in size or "width" not in size:
															raise ValueError(f"""The `size` parameter must contain the keys (height, width). Got {size.keys()}"""    )
											return center_crop(__snake_case       ,   size=(size["""height"""], size["""width"""])       ,   data_format=__snake_case       ,   **__snake_case    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case = None       ,   **__snake_case       ,   ):
											return rescale(__snake_case       ,   scale=__snake_case       ,   data_format=__snake_case       ,   **__snake_case    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case       ,   __snake_case       ,   __snake_case = None       ,   **__snake_case       ,   ):
											return normalize(__snake_case       ,   mean=__snake_case       ,   std=__snake_case       ,   data_format=__snake_case       ,   **__snake_case    )






							def UpperCAmelCase_      (       self       ,   __snake_case       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = None       ,   __snake_case = ChannelDimension.FIRST       ,   **__snake_case       ,   ):
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= do_resize if do_resize is not None else self.do_resize
											_SCREAMING_SNAKE_CASE					:			Any							= size if size is not None else self.size
											_SCREAMING_SNAKE_CASE					:			List[str]							= get_size_dict(__snake_case       ,   param_name="""size"""       ,   default_to_square=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Any							= resample if resample is not None else self.resample
											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= do_center_crop if do_center_crop is not None else self.do_center_crop
											_SCREAMING_SNAKE_CASE					:			str							= crop_size if crop_size is not None else self.crop_size
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= get_size_dict(__snake_case       ,   param_name="""crop_size"""       ,   default_to_square=__snake_case    )
											_SCREAMING_SNAKE_CASE					:			Optional[int]							= do_rescale if do_rescale is not None else self.do_rescale
											_SCREAMING_SNAKE_CASE					:			int							= rescale_factor if rescale_factor is not None else self.rescale_factor
											_SCREAMING_SNAKE_CASE					:			Tuple							= do_normalize if do_normalize is not None else self.do_normalize
											_SCREAMING_SNAKE_CASE					:			List[str]							= image_mean if image_mean is not None else self.image_mean
											_SCREAMING_SNAKE_CASE					:			List[Any]							= image_std if image_std is not None else self.image_std
											_SCREAMING_SNAKE_CASE					:			Any							= do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

											_SCREAMING_SNAKE_CASE					:			Optional[Any]							= make_list_of_images(__snake_case    )

											if not valid_images(__snake_case    ):
															raise ValueError(
															    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
															    """torch.Tensor, tf.Tensor or jax.ndarray."""    )

											if do_resize and size is None:
															raise ValueError("""Size must be specified if do_resize is True."""    )

											if do_center_crop and crop_size is None:
															raise ValueError("""Crop size must be specified if do_center_crop is True."""    )

											if do_rescale and rescale_factor is None:
															raise ValueError("""Rescale factor must be specified if do_rescale is True."""    )

											if do_normalize and (image_mean is None or image_std is None):
															raise ValueError("""Image mean and std must be specified if do_normalize is True."""    )

											# PIL RGBA images are converted to RGB
											if do_convert_rgb:
															_SCREAMING_SNAKE_CASE					:			Optional[int]							= [convert_to_rgb(__snake_case    ) for image in images]

											# All transformations expect numpy arrays.
											_SCREAMING_SNAKE_CASE					:			str							= [to_numpy_array(__snake_case    ) for image in images]

											if do_resize:
															_SCREAMING_SNAKE_CASE					:			Optional[Any]							= [self.resize(image=__snake_case       ,   size=__snake_case       ,   resample=__snake_case    ) for image in images]

											if do_center_crop:
															_SCREAMING_SNAKE_CASE					:			Tuple							= [self.center_crop(image=__snake_case       ,   size=__snake_case    ) for image in images]

											if do_rescale:
															_SCREAMING_SNAKE_CASE					:			List[Any]							= [self.rescale(image=__snake_case       ,   scale=__snake_case    ) for image in images]

											if do_normalize:
															_SCREAMING_SNAKE_CASE					:			Dict							= [self.normalize(image=__snake_case       ,   mean=__snake_case       ,   std=__snake_case    ) for image in images]

											_SCREAMING_SNAKE_CASE					:			str							= [to_channel_dimension_format(__snake_case       ,   __snake_case    ) for image in images]

											_SCREAMING_SNAKE_CASE					:			int							= {"""pixel_values""": images}
											return BatchFeature(data=__snake_case       ,   tensor_type=__snake_case    )




