



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

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

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

			def 			__snake_case    (self )    ->					Union[str, Any]:
						UpperCAmelCase_:						Dict					=			ids_tensor([self.batch_size, self.text_seq_length],					self.vocab_size )

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

						UpperCAmelCase_:						Dict					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

						UpperCAmelCase_:						Optional[int]					=			None
						if self.use_input_mask:
									UpperCAmelCase_:						Tuple					=			random_attention_mask([self.batch_size, self.text_seq_length] )

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

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

						UpperCAmelCase_:						List[Any]					=			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 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_ )    ->					Optional[int]:
						UpperCAmelCase_:						List[str]					=			TFLayoutLMvaModel(config=SCREAMING_SNAKE_CASE__ )

						# text + image
						UpperCAmelCase_:						Tuple					=			model(SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_:						Optional[int]					=			model(
						    SCREAMING_SNAKE_CASE__,					bbox=SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					attention_mask=SCREAMING_SNAKE_CASE__,					token_type_ids=SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__,					)
						UpperCAmelCase_:						Dict					=			model(SCREAMING_SNAKE_CASE__,					bbox=SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__ )

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

						# text only
						UpperCAmelCase_:						Any					=			model(SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__ )
						self.parent.assertEqual(
						    result.last_hidden_state.shape,					(self.batch_size, self.text_seq_length, self.hidden_size) )

						# image only
						UpperCAmelCase_:						List[str]					=			model({"""pixel_values""": pixel_values},					training=SCREAMING_SNAKE_CASE__ )
						self.parent.assertEqual(
						    result.last_hidden_state.shape,					(self.batch_size, self.image_seq_length, self.hidden_size) )

			def 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_ )    ->					Union[str, Any]:
						UpperCAmelCase_:						Any					=			self.num_labels
						UpperCAmelCase_:						List[str]					=			TFLayoutLMvaForSequenceClassification(config=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_:						List[Any]					=			model(
						    SCREAMING_SNAKE_CASE__,					bbox=SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					attention_mask=SCREAMING_SNAKE_CASE__,					token_type_ids=SCREAMING_SNAKE_CASE__,					labels=SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__,					)
						self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.num_labels) )

			def 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_ )    ->					Dict:
						UpperCAmelCase_:						str					=			self.num_labels
						UpperCAmelCase_:						Tuple					=			TFLayoutLMvaForTokenClassification(config=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_:						Optional[Any]					=			model(
						    SCREAMING_SNAKE_CASE__,					bbox=SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					attention_mask=SCREAMING_SNAKE_CASE__,					token_type_ids=SCREAMING_SNAKE_CASE__,					labels=SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__,					)
						self.parent.assertEqual(result.logits.shape,					(self.batch_size, self.text_seq_length, self.num_labels) )

			def 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_ )    ->					List[Any]:
						UpperCAmelCase_:						List[Any]					=			2
						UpperCAmelCase_:						List[str]					=			TFLayoutLMvaForQuestionAnswering(config=SCREAMING_SNAKE_CASE__ )
						UpperCAmelCase_:						List[str]					=			model(
						    SCREAMING_SNAKE_CASE__,					bbox=SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					attention_mask=SCREAMING_SNAKE_CASE__,					token_type_ids=SCREAMING_SNAKE_CASE__,					start_positions=SCREAMING_SNAKE_CASE__,					end_positions=SCREAMING_SNAKE_CASE__,					training=SCREAMING_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 			__snake_case    (self )    ->					Tuple:
						UpperCAmelCase_:						int					=			self.prepare_config_and_inputs()
						(UpperCAmelCase_):						Optional[int]					=			config_and_inputs
						UpperCAmelCase_:						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 							_a							(					a__      ,						a__      ,						unittest.TestCase ):
			A							=     (
			    (
			        TFLayoutLMvaModel,
			        TFLayoutLMvaForQuestionAnswering,
			        TFLayoutLMvaForSequenceClassification,
			        TFLayoutLMvaForTokenClassification,
			    )
			    if is_tf_available()
			    else ()
			)
			A							=     (
			    {'''document-question-answering''': TFLayoutLMvaForQuestionAnswering, '''feature-extraction''': TFLayoutLMvaModel}
			    if is_tf_available()
			    else {}
			)

			A							=     False
			A							=     False
			A							=     False

			def 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_ )    ->					List[str]:
						return True

			def 			__snake_case    (self,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_,					SCREAMING_SNAKE_CASE_=False )    ->					dict:
						UpperCAmelCase_:						Dict					=			copy.deepcopy(SCREAMING_SNAKE_CASE__ )

						if model_class in get_values(SCREAMING_SNAKE_CASE__ ):
									UpperCAmelCase_:						List[Any]					=			{
									    k: tf.tile(tf.expand_dims(SCREAMING_SNAKE_CASE__,					1 ),					(1, self.model_tester.num_choices) + (1,) * (v.ndim - 1) )
									    if isinstance(SCREAMING_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(SCREAMING_SNAKE_CASE__ ):
												UpperCAmelCase_:						Union[str, Any]					=			tf.ones(self.model_tester.batch_size,					dtype=tf.intaa )
									elif model_class in get_values(SCREAMING_SNAKE_CASE__ ):
												UpperCAmelCase_:						Tuple					=			tf.zeros(self.model_tester.batch_size,					dtype=tf.intaa )
												UpperCAmelCase_:						Dict					=			tf.zeros(self.model_tester.batch_size,					dtype=tf.intaa )
									elif model_class in get_values(SCREAMING_SNAKE_CASE__ ):
												UpperCAmelCase_:						List[str]					=			tf.zeros(self.model_tester.batch_size,					dtype=tf.intaa )
									elif model_class in get_values(SCREAMING_SNAKE_CASE__ ):
												UpperCAmelCase_:						Any					=			tf.zeros(
												    (self.model_tester.batch_size, self.model_tester.text_seq_length),					dtype=tf.intaa )

						return inputs_dict

			def 			__snake_case    (self )    ->					Tuple:
						UpperCAmelCase_:						List[str]					=			TFLayoutLMvaModelTester(self )
						UpperCAmelCase_:						Tuple					=			ConfigTester(self,					config_class=SCREAMING_SNAKE_CASE__,					hidden_size=37 )

			def 			__snake_case    (self )    ->					Union[str, Any]:
						self.config_tester.run_common_tests()

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

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

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

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

												# Create a dictionary holding the location of the tensors in the tuple
												UpperCAmelCase_:						int					=			{0: """input_ids"""}
												for label_key in label_keys:
															UpperCAmelCase_:						str					=			signature_names.index(SCREAMING_SNAKE_CASE__ )
															UpperCAmelCase_:						Union[str, Any]					=			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_:						int					=			[]

												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_:						int					=			tuple(SCREAMING_SNAKE_CASE__ )

												# Send to model
												UpperCAmelCase_:						Optional[int]					=			model(tuple_input[:-1] )[0]

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

			def 			__snake_case    (self )    ->					int:
						(
						    UpperCAmelCase_      
						):						Optional[int]					=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__ )

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

			def 			__snake_case    (self )    ->					Tuple:
						(
						    UpperCAmelCase_      
						):						Union[str, Any]					=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(
						    SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__ )

			def 			__snake_case    (self )    ->					Union[str, Any]:
						(
						    UpperCAmelCase_      
						):						Optional[Any]					=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(
						    SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__ )

			def 			__snake_case    (self )    ->					Optional[int]:
						(
						    UpperCAmelCase_      
						):						Optional[int]					=			self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(
						    SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__,					SCREAMING_SNAKE_CASE__ )

			@slow
			def 			__snake_case    (self )    ->					int:




						for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									UpperCAmelCase_:						Tuple					=			TFLayoutLMvaModel.from_pretrained(SCREAMING_SNAKE_CASE__ )
									self.assertIsNotNone(SCREAMING_SNAKE_CASE__ )







def       lowerCAmelCase_     ():





			"""simple docstring"""


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







@require_tf
class 							_a							(					unittest.TestCase ):

			@cached_property
			def 			__snake_case    (self )    ->					Optional[int]:
						return LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE__ ) if is_vision_available() else None

			@slow
			def 			__snake_case    (self )    ->					List[str]:
						UpperCAmelCase_:						Optional[Any]					=			TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base""" )

						UpperCAmelCase_:						List[str]					=			self.default_image_processor
						UpperCAmelCase_:						Tuple					=			prepare_img()
						UpperCAmelCase_:						str					=			image_processor(images=SCREAMING_SNAKE_CASE__,					return_tensors="""tf""" ).pixel_values

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

						# forward pass
						UpperCAmelCase_:						Union[str, Any]					=			model(input_ids=SCREAMING_SNAKE_CASE__,					bbox=SCREAMING_SNAKE_CASE__,					pixel_values=SCREAMING_SNAKE_CASE__,					training=SCREAMING_SNAKE_CASE__ )

						# verify the logits
						UpperCAmelCase_:						Optional[int]					=			(1, 199, 768)
						self.assertEqual(outputs.last_hidden_state.shape,					SCREAMING_SNAKE_CASE__ )

						UpperCAmelCase_:						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],					SCREAMING_SNAKE_CASE__,					atol=1E-4 ) )








"""simple docstring"""




def lowercase_  (   _snake_case   ,_snake_case						):

							if not (isinstance(_snake_case   ,_snake_case						) and isinstance(_snake_case   ,_snake_case						)):
														raise ValueError("""longest_common_substring() takes two strings for inputs"""						)

							SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   len(_snake_case						)
							SCREAMING_SNAKE_CASE__						:       int           =   len(_snake_case						)

							SCREAMING_SNAKE_CASE__						:       Dict           =   [[0] * (texta_length + 1) for _ in range(texta_length + 1						)]
							SCREAMING_SNAKE_CASE__						:       List[Any]           =   0
							SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   0

							for i in range(1   ,texta_length + 1						):
														for j in range(1   ,texta_length + 1						):
																					if texta[i - 1] == texta[j - 1]:
																												SCREAMING_SNAKE_CASE__						:       int           =   1 + dp[i - 1][j - 1]
																												if dp[i][j] > ans_length:
																																			SCREAMING_SNAKE_CASE__						:       List[Any]           =   i
																																			SCREAMING_SNAKE_CASE__						:       List[str]           =   dp[i][j]

							return texta[ans_index - ans_length : ans_index]


if __name__ == "__main__":
					import doctest

					doctest.testmod()




