
from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

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

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


if is_tf_available():
    import tensorflow as tf

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

if is_vision_available():
    from PIL import Image

    from transformers import LayoutLMvaImageProcessor




class 				_lowerCamelCase :





     """simple docstring"""







     def __init__(							self						,						__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=9_9						,						__SCREAMING_SNAKE_CASE=3_6						,						__SCREAMING_SNAKE_CASE=2						,						__SCREAMING_SNAKE_CASE=4						,						__SCREAMING_SNAKE_CASE=3_7						,						__SCREAMING_SNAKE_CASE="gelu"						,						__SCREAMING_SNAKE_CASE=0.1						,						__SCREAMING_SNAKE_CASE=0.1						,						__SCREAMING_SNAKE_CASE=5_1_2						,						__SCREAMING_SNAKE_CASE=1_6						,						__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=1_0_0_0						,						)  ->   List[Any]:




           """simple docstring"""







           UpperCamelCase__    :   int					=				parent
           UpperCamelCase__    :   List[Any]					=				batch_size
           UpperCamelCase__    :   Union[str, Any]					=				num_channels
           UpperCamelCase__    :   int					=				image_size
           UpperCamelCase__    :   Optional[Any]					=				patch_size
           UpperCamelCase__    :   List[str]					=				is_training
           UpperCamelCase__    :   str					=				use_input_mask
           UpperCamelCase__    :   Optional[int]					=				use_token_type_ids
           UpperCamelCase__    :   Any					=				use_labels
           UpperCamelCase__    :   List[Any]					=				vocab_size
           UpperCamelCase__    :   Optional[int]					=				hidden_size
           UpperCamelCase__    :   Optional[int]					=				num_hidden_layers
           UpperCamelCase__    :   str					=				num_attention_heads
           UpperCamelCase__    :   str					=				intermediate_size
           UpperCamelCase__    :   int					=				hidden_act
           UpperCamelCase__    :   Optional[Any]					=				hidden_dropout_prob
           UpperCamelCase__    :   Tuple					=				attention_probs_dropout_prob
           UpperCamelCase__    :   Tuple					=				max_position_embeddings
           UpperCamelCase__    :   List[Any]					=				type_vocab_size
           UpperCamelCase__    :   List[Any]					=				type_sequence_label_size
           UpperCamelCase__    :   Tuple					=				initializer_range
           UpperCamelCase__    :   Union[str, Any]					=				coordinate_size
           UpperCamelCase__    :   Tuple					=				shape_size
           UpperCamelCase__    :   Union[str, Any]					=				num_labels
           UpperCamelCase__    :   Tuple					=				num_choices
           UpperCamelCase__    :   str					=				scope
           UpperCamelCase__    :   Optional[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__    :   Optional[int]					=				(image_size // patch_size) ** 2 + 1
           UpperCamelCase__    :   List[Any]					=				self.text_seq_length + self.image_seq_length






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           UpperCamelCase__    :   List[Any]					=				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__    :   str					=				bbox.numpy()
           # Ensure that bbox is legal
           for i in range(bbox.shape[0]  ):
                 for j in range(bbox.shape[1]  ):
                       if bbox[i, j, 3] < bbox[i, j, 1]:
                             UpperCamelCase__    :   Dict					=				bbox[i, j, 3]
                             UpperCamelCase__    :   Tuple					=				bbox[i, j, 1]
                             UpperCamelCase__    :   int					=				tmp_coordinate
                       if bbox[i, j, 2] < bbox[i, j, 0]:
                             UpperCamelCase__    :   int					=				bbox[i, j, 2]
                             UpperCamelCase__    :   List[str]					=				bbox[i, j, 0]
                             UpperCamelCase__    :   Optional[Any]					=				tmp_coordinate
           UpperCamelCase__    :   Dict					=				tf.constant(lowercase_  )

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

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

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

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

           UpperCamelCase__    :   Optional[int]					=				LayoutLMvaConfig(
               vocab_size=self.vocab_size						,						hidden_size=self.hidden_size						,						num_hidden_layers=self.num_hidden_layers						,						num_attention_heads=self.num_attention_heads						,						intermediate_size=self.intermediate_size						,						hidden_act=self.hidden_act						,						hidden_dropout_prob=self.hidden_dropout_prob						,						attention_probs_dropout_prob=self.attention_probs_dropout_prob						,						max_position_embeddings=self.max_position_embeddings						,						type_vocab_size=self.type_vocab_size						,						initializer_range=self.initializer_range						,						coordinate_size=self.coordinate_size						,						shape_size=self.shape_size						,						input_size=self.image_size						,						patch_size=self.patch_size						,						)

           return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Dict:




           """simple docstring"""







           UpperCamelCase__    :   Dict					=				TFLayoutLMvaModel(config=lowercase_  )

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

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

           # text only
           UpperCamelCase__    :   Optional[Any]					=				model(lowercase_						,						training=lowercase_  )
           self.parent.assertEqual(
               result.last_hidden_state.shape						,						(self.batch_size, self.text_seq_length, self.hidden_size)  )

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






     def    __SCREAMING_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:




           """simple docstring"""







           UpperCamelCase__    :   str					=				self.num_labels
           UpperCamelCase__    :   Any					=				TFLayoutLMvaForSequenceClassification(config=lowercase_  )
           UpperCamelCase__    :   List[str]					=				model(
               lowercase_						,						bbox=lowercase_						,						pixel_values=lowercase_						,						attention_mask=lowercase_						,						token_type_ids=lowercase_						,						labels=lowercase_						,						training=lowercase_						,						)
           self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.num_labels)  )






     def    __SCREAMING_SNAKE_CASE			(							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__    :   Any					=				self.num_labels
           UpperCamelCase__    :   Optional[Any]					=				TFLayoutLMvaForTokenClassification(config=lowercase_  )
           UpperCamelCase__    :   Dict					=				model(
               lowercase_						,						bbox=lowercase_						,						pixel_values=lowercase_						,						attention_mask=lowercase_						,						token_type_ids=lowercase_						,						labels=lowercase_						,						training=lowercase_						,						)
           self.parent.assertEqual(result.logits.shape						,						(self.batch_size, self.text_seq_length, self.num_labels)  )






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Optional[int]:




           """simple docstring"""







           UpperCamelCase__    :   List[Any]					=				2
           UpperCamelCase__    :   str					=				TFLayoutLMvaForQuestionAnswering(config=lowercase_  )
           UpperCamelCase__    :   List[str]					=				model(
               lowercase_						,						bbox=lowercase_						,						pixel_values=lowercase_						,						attention_mask=lowercase_						,						token_type_ids=lowercase_						,						start_positions=lowercase_						,						end_positions=lowercase_						,						training=lowercase_						,						)
           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    __SCREAMING_SNAKE_CASE			(							self  )  ->   str:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				self.prepare_config_and_inputs()
           ((UpperCamelCase__)				,(UpperCamelCase__)				,(UpperCamelCase__)				,(UpperCamelCase__)				,(UpperCamelCase__)				,(UpperCamelCase__)				,(UpperCamelCase__)				,(UpperCamelCase__))    :   List[str]					=				config_and_inputs
           UpperCamelCase__    :   Any					=				{
               '''input_ids''': input_ids,
               '''bbox''': bbox,
               '''pixel_values''': pixel_values,
               '''token_type_ids''': token_type_ids,
               '''attention_mask''': input_mask,
           }
           return config, inputs_dict




@require_tf
class 				_lowerCamelCase (      UpperCamelCase_	,							UpperCamelCase_	,							unittest.TestCase ):





     """simple docstring"""







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

     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False
     SCREAMING_SNAKE_CASE_		   =  False






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE  )  ->   Optional[int]:




           """simple docstring"""







           return True






     def    __SCREAMING_SNAKE_CASE			(							self						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE						,						__SCREAMING_SNAKE_CASE=False  )  ->   dict:




           """simple docstring"""







           UpperCamelCase__    :   Union[str, Any]					=				copy.deepcopy(lowercase_  )

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

           if return_labels:
                 if model_class in get_values(lowercase_  ):
                       UpperCamelCase__    :   str					=				tf.ones(self.model_tester.batch_size						,						dtype=tf.intaa  )
                 elif model_class in get_values(lowercase_  ):
                       UpperCamelCase__    :   Dict					=				tf.zeros(self.model_tester.batch_size						,						dtype=tf.intaa  )
                       UpperCamelCase__    :   str					=				tf.zeros(self.model_tester.batch_size						,						dtype=tf.intaa  )
                 elif model_class in get_values(lowercase_  ):
                       UpperCamelCase__    :   int					=				tf.zeros(self.model_tester.batch_size						,						dtype=tf.intaa  )
                 elif model_class in get_values(lowercase_  ):
                       UpperCamelCase__    :   str					=				tf.zeros(
                           (self.model_tester.batch_size, self.model_tester.text_seq_length)						,						dtype=tf.intaa  )

           return inputs_dict






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Tuple:




           """simple docstring"""







           UpperCamelCase__    :   Tuple					=				TFLayoutLMvaModelTester(self  )
           UpperCamelCase__    :   List[Any]					=				ConfigTester(self						,						config_class=lowercase_						,						hidden_size=3_7  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







           self.config_tester.run_common_tests()






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   List[Any]:




           """simple docstring"""







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

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

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

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

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

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

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

                       UpperCamelCase__    :   Dict					=				tuple(lowercase_  )

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

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






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[int]:




           """simple docstring"""







           (
               (
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,	
           )    :   List[Any]					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Dict:




           """simple docstring"""







           (
               (
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,	
           )    :   List[str]					=				self.model_tester.prepare_config_and_inputs()
           for type in ["absolute", "relative_key", "relative_key_query"]:
                 UpperCamelCase__    :   int					=				type
                 self.model_tester.create_and_check_model(lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[int]:




           """simple docstring"""







           (
               (
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,	
           )    :   Tuple					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_sequence_classification(
               lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[int]:




           """simple docstring"""







           (
               (
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,	
           )    :   Tuple					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_token_classification(
               lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_  )






     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   int:




           """simple docstring"""







           (
               (
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,(
               UpperCamelCase__	
           )				,	
           )    :   Any					=				self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_question_answering(
               lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_						,						lowercase_  )






     @slow
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 UpperCamelCase__    :   Any					=				TFLayoutLMvaModel.from_pretrained(lowercase_  )
                 self.assertIsNotNone(lowercase_  )


def 							SCREAMING_SNAKE_CASE_      (			):
      UpperCamelCase__    :   Tuple					=				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
      return image




@require_tf
class 				_lowerCamelCase (      unittest.TestCase ):





     """simple docstring"""







     @cached_property
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[int]:




           """simple docstring"""







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






     @slow
     def    __SCREAMING_SNAKE_CASE			(							self  )  ->   Optional[Any]:




           """simple docstring"""







           UpperCamelCase__    :   Dict					=				TFLayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base'''  )

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

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

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

           # verify the logits
           UpperCamelCase__    :   Dict					=				(1, 1_9_9, 7_6_8)
           self.assertEqual(outputs.last_hidden_state.shape						,						lowercase_  )

           UpperCamelCase__    :   int					=				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]						,						lowercase_						,						atol=1e-4  )  )







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCamelCase      ={
    "configuration_clipseg": [
        "CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP",
        "CLIPSegConfig",
        "CLIPSegTextConfig",
        "CLIPSegVisionConfig",
    ],
    "processing_clipseg": ["CLIPSegProcessor"],
}

try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowerCamelCase      =[
        "CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST",
        "CLIPSegModel",
        "CLIPSegPreTrainedModel",
        "CLIPSegTextModel",
        "CLIPSegVisionModel",
        "CLIPSegForImageSegmentation",
    ]

if TYPE_CHECKING:
    from .configuration_clipseg import (
        CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP,
        CLIPSegConfig,
        CLIPSegTextConfig,
        CLIPSegVisionConfig,
    )
    from .processing_clipseg import CLIPSegProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_clipseg import (
            CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST,
            CLIPSegForImageSegmentation,
            CLIPSegModel,
            CLIPSegPreTrainedModel,
            CLIPSegTextModel,
            CLIPSegVisionModel,
        )

else:
    import sys

    lowerCamelCase      =_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)


