


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.02     ,       _SCREAMING_SNAKE_CASE=6     ,       _SCREAMING_SNAKE_CASE=6     ,       _SCREAMING_SNAKE_CASE=3     ,       _SCREAMING_SNAKE_CASE=4     ,       _SCREAMING_SNAKE_CASE=None     ,       _SCREAMING_SNAKE_CASE=1000     ,       )					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     parent
									_UpperCAmelCase											=     batch_size
									_UpperCAmelCase											=     num_channels
									_UpperCAmelCase											=     image_size
									_UpperCAmelCase											=     patch_size
									_UpperCAmelCase											=     is_training
									_UpperCAmelCase											=     use_input_mask
									_UpperCAmelCase											=     use_token_type_ids
									_UpperCAmelCase											=     use_labels
									_UpperCAmelCase											=     vocab_size
									_UpperCAmelCase											=     hidden_size
									_UpperCAmelCase											=     num_hidden_layers
									_UpperCAmelCase											=     num_attention_heads
									_UpperCAmelCase											=     intermediate_size
									_UpperCAmelCase											=     hidden_act
									_UpperCAmelCase											=     hidden_dropout_prob
									_UpperCAmelCase											=     attention_probs_dropout_prob
									_UpperCAmelCase											=     max_position_embeddings
									_UpperCAmelCase											=     type_vocab_size
									_UpperCAmelCase											=     type_sequence_label_size
									_UpperCAmelCase											=     initializer_range
									_UpperCAmelCase											=     coordinate_size
									_UpperCAmelCase											=     shape_size
									_UpperCAmelCase											=     num_labels
									_UpperCAmelCase											=     num_choices
									_UpperCAmelCase											=     scope
									_UpperCAmelCase											=     range_bbox

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




									"""simple docstring"""





									_UpperCAmelCase											=     ids_tensor([self.batch_size, self.text_seq_length]     ,       self.vocab_size		)

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

									_UpperCAmelCase											=     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

									_UpperCAmelCase											=     None
									if self.use_input_mask:
																_UpperCAmelCase											=     random_attention_mask([self.batch_size, self.text_seq_length]		)

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

									_UpperCAmelCase											=     None
									_UpperCAmelCase											=     None
									if self.use_labels:
																_UpperCAmelCase											=     ids_tensor([self.batch_size]     ,       self.type_sequence_label_size		)
																_UpperCAmelCase											=     ids_tensor([self.batch_size, self.text_seq_length]     ,       self.num_labels		)

									_UpperCAmelCase											=     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     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			List[str]:




									"""simple docstring"""





									_UpperCAmelCase											=     TFLayoutLMvaModel(config=_SCREAMING_SNAKE_CASE		)

									# text + image
									_UpperCAmelCase											=     model(_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       training=_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     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											=     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											=     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											=     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       UpperCAmelCase__							(     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]:




									"""simple docstring"""





									_UpperCAmelCase											=     self.num_labels
									_UpperCAmelCase											=     TFLayoutLMvaForSequenceClassification(config=_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     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       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     self.num_labels
									_UpperCAmelCase											=     TFLayoutLMvaForTokenClassification(config=_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     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       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase											=     2
									_UpperCAmelCase											=     TFLayoutLMvaForQuestionAnswering(config=_SCREAMING_SNAKE_CASE		)
									_UpperCAmelCase											=     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       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





									_UpperCAmelCase											=     self.prepare_config_and_inputs()
									((_UpperCAmelCase)						,			(_UpperCAmelCase)						,			(_UpperCAmelCase)						,			(_UpperCAmelCase)						,			(_UpperCAmelCase)						,			(_UpperCAmelCase)						,			(_UpperCAmelCase)						,			(_UpperCAmelCase))											=     config_and_inputs
									_UpperCAmelCase											=     {
									    '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 (							UpperCAmelCase       , UpperCAmelCase       , unittest.TestCase     ):
		_a      :    Optional[Any]           =      (
		    (
		        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      :    Any           =      False
		_a      :    Any           =      False
		_a      :    Dict           =      False
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE		)					->			Tuple:




									"""simple docstring"""





									return True
		def       UpperCAmelCase__							(     self     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE=False		)					->			dict:




									"""simple docstring"""





									_UpperCAmelCase											=     copy.deepcopy(_SCREAMING_SNAKE_CASE		)

									if model_class in get_values(_SCREAMING_SNAKE_CASE		):
																_UpperCAmelCase											=     {
																    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											=     tf.ones(self.model_tester.batch_size     ,       dtype=tf.intaa		)
																elif model_class in get_values(_SCREAMING_SNAKE_CASE		):
																							_UpperCAmelCase											=     tf.zeros(self.model_tester.batch_size     ,       dtype=tf.intaa		)
																							_UpperCAmelCase											=     tf.zeros(self.model_tester.batch_size     ,       dtype=tf.intaa		)
																elif model_class in get_values(_SCREAMING_SNAKE_CASE		):
																							_UpperCAmelCase											=     tf.zeros(self.model_tester.batch_size     ,       dtype=tf.intaa		)
																elif model_class in get_values(_SCREAMING_SNAKE_CASE		):
																							_UpperCAmelCase											=     tf.zeros(
																							    (self.model_tester.batch_size, self.model_tester.text_seq_length)     ,       dtype=tf.intaa		)

									return inputs_dict
		def       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									_UpperCAmelCase											=     TFLayoutLMvaModelTester(self		)
									_UpperCAmelCase											=     ConfigTester(self     ,       config_class=_SCREAMING_SNAKE_CASE     ,       hidden_size=37		)
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									self.config_tester.run_common_tests()
		def       UpperCAmelCase__							(     self		)					->			List[str]:




									"""simple docstring"""





									_UpperCAmelCase						,			_UpperCAmelCase											=     self.model_tester.prepare_config_and_inputs_for_common()
									for model_class in self.all_model_classes:
																_UpperCAmelCase											=     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											=     self._prepare_for_class(inputs_dict.copy()     ,       _SCREAMING_SNAKE_CASE     ,       return_labels=_SCREAMING_SNAKE_CASE		)
																							_UpperCAmelCase											=     prepared_for_class[
																							    sorted(prepared_for_class.keys() - inputs_dict.keys()     ,       reverse=_SCREAMING_SNAKE_CASE		)[0]
																							]
																							_UpperCAmelCase											=     added_label.shape.as_list()[:1]

																							# Test that model correctly compute the loss with kwargs
																							_UpperCAmelCase											=     self._prepare_for_class(inputs_dict.copy()     ,       _SCREAMING_SNAKE_CASE     ,       return_labels=_SCREAMING_SNAKE_CASE		)
																							_UpperCAmelCase											=     prepared_for_class.pop('input_ids'		)

																							_UpperCAmelCase											=     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											=     self._prepare_for_class(inputs_dict.copy()     ,       _SCREAMING_SNAKE_CASE     ,       return_labels=_SCREAMING_SNAKE_CASE		)
																							_UpperCAmelCase											=     prepared_for_class.pop('input_ids'		)
																							if "labels" in prepared_for_class:
																														_UpperCAmelCase											=     prepared_for_class['labels'].numpy()
																														if len(labels.shape		) > 1 and labels.shape[1] != 1:
																																					_UpperCAmelCase											=     -100
																																					_UpperCAmelCase											=     tf.convert_to_tensor(_SCREAMING_SNAKE_CASE		)
																																					_UpperCAmelCase											=     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											=     self._prepare_for_class(inputs_dict.copy()     ,       _SCREAMING_SNAKE_CASE     ,       return_labels=_SCREAMING_SNAKE_CASE		)
																							_UpperCAmelCase											=     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											=     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											=     prepared_for_class.keys() - inputs_dict.keys()
																							_UpperCAmelCase											=     inspect.signature(model.call		).parameters
																							_UpperCAmelCase											=     list(signature.keys()		)

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

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

																							for index, value in sorted_tuple_index_mapping:
																														_UpperCAmelCase											=     prepared_for_class[value]

																							_UpperCAmelCase											=     tuple(_SCREAMING_SNAKE_CASE		)

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

																							self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)
		def       UpperCAmelCase__							(     self		)					->			Any:




									"""simple docstring"""





									(
									    (
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,									
									)											=     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       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									(
									    (
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,									
									)											=     self.model_tester.prepare_config_and_inputs()
									for type in ["absolute", "relative_key", "relative_key_query"]:
																_UpperCAmelCase											=     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       UpperCAmelCase__							(     self		)					->			Optional[Any]:




									"""simple docstring"""





									(
									    (
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,									
									)											=     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       UpperCAmelCase__							(     self		)					->			int:




									"""simple docstring"""





									(
									    (
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,									
									)											=     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       UpperCAmelCase__							(     self		)					->			Dict:




									"""simple docstring"""





									(
									    (
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,			(
									    _UpperCAmelCase						
									)						,									
									)											=     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       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





									for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																_UpperCAmelCase											=     TFLayoutLMvaModel.from_pretrained(_SCREAMING_SNAKE_CASE		)
																self.assertIsNotNone(_SCREAMING_SNAKE_CASE		)



def 			lowerCAmelCase__					(     )    ->						Tuple:


							'''simple docstring'''





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







@require_tf
class 						__a (							unittest.TestCase     ):
		@cached_property
		def       UpperCAmelCase__							(     self		)					->			Tuple:




									"""simple docstring"""





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






		@slow
		def       UpperCAmelCase__							(     self		)					->			str:




									"""simple docstring"""





									_UpperCAmelCase											=     TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'		)

									_UpperCAmelCase											=     self.default_image_processor
									_UpperCAmelCase											=     prepare_img()
									_UpperCAmelCase											=     image_processor(images=_SCREAMING_SNAKE_CASE     ,       return_tensors='tf'		).pixel_values

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

									# forward pass
									_UpperCAmelCase											=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       bbox=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       training=_SCREAMING_SNAKE_CASE		)

									# verify the logits
									_UpperCAmelCase											=     (1, 199, 768)
									self.assertEqual(outputs.last_hidden_state.shape     ,       _SCREAMING_SNAKE_CASE		)

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





from sklearn.metrics import matthews_corrcoef

import datasets


a__   :					Any 						=      "\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

a__   :					Any 						=      "\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

a__   :					str 						=      "\\n@article{scikit-learn,\n  title={Scikit-learn: Machine Learning in {P}ython},\n  author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n  journal={Journal of Machine Learning Research},\n  volume={12},\n  pages={2825--2830},\n  year={2011}\n}\n"



@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION  ,				_KWARGS_DESCRIPTION						)
class    UpperCAmelCase__(				datasets.Metric						):

   '''simple docstring'''




   def       UpperCAmelCase		(    self	:      List[Any])						->					int:




         """simple docstring"""

         return datasets.MetricInfo(
             description=_DESCRIPTION      ,					citation=_CITATION      ,					inputs_description=_KWARGS_DESCRIPTION      ,					features=datasets.Features(
                 {
                     'predictions': datasets.Value('int32'),
                     'references': datasets.Value('int32'),
                 })      ,					reference_urls=[
                 'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'
             ]      ,					)



   def       UpperCAmelCase		(    self	:      Dict      ,					lowerCAmelCase	:      Dict      ,					lowerCAmelCase	:      Optional[int]      ,					lowerCAmelCase	:      Union[str, Any]=None)						->					Any:




         """simple docstring"""

         return {
             "matthews_correlation": float(matthews_corrcoef(lowerCAmelCase      ,					lowerCAmelCase      ,					sample_weight=lowerCAmelCase)),
         }
