



"""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 					a	:



  def __init__(						self :					int       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Any=2       ,		lowerCAmelCase :					Union[str, Any]=3       ,		lowerCAmelCase :					List[Any]=4       ,		lowerCAmelCase :					Tuple=2       ,		lowerCAmelCase :					Union[str, Any]=7       ,		lowerCAmelCase :					List[Any]=True       ,		lowerCAmelCase :					int=True       ,		lowerCAmelCase :					Any=True       ,		lowerCAmelCase :					Dict=True       ,		lowerCAmelCase :					Optional[Any]=99       ,		lowerCAmelCase :					int=36       ,		lowerCAmelCase :					List[Any]=2       ,		lowerCAmelCase :					List[str]=4       ,		lowerCAmelCase :					int=37       ,		lowerCAmelCase :					Union[str, Any]="gelu"       ,		lowerCAmelCase :					Dict=0.1       ,		lowerCAmelCase :					int=0.1       ,		lowerCAmelCase :					Optional[int]=512       ,		lowerCAmelCase :					int=16       ,		lowerCAmelCase :					List[Any]=2       ,		lowerCAmelCase :					List[str]=0.0_2       ,		lowerCAmelCase :					Optional[int]=6       ,		lowerCAmelCase :					str=6       ,		lowerCAmelCase :					str=3       ,		lowerCAmelCase :					Any=4       ,		lowerCAmelCase :					int=None       ,		lowerCAmelCase :					Optional[int]=1000       ,		)     ->					int:


     '''simple docstring'''




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



  def 	lowerCamelCase__       (						self :					int		)     ->					Union[str, Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=ids_tensor([self.batch_size, self.text_seq_length]       ,		self.vocab_size		)

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

     SCREAMING_SNAKE_CASE_: List[Any]     			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

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

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

     SCREAMING_SNAKE_CASE_: List[str]     			=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 	lowerCamelCase__       (						self :					Any       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Optional[int]       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					Optional[int]       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					Union[str, Any]		)     ->					str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=TFLayoutLMvaModel(config=lowerCAmelCase		)

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

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

     # text only
     SCREAMING_SNAKE_CASE_: Tuple     			=model(lowerCAmelCase       ,		training=lowerCAmelCase		)
     self.parent.assertEqual(
         result.last_hidden_state.shape       ,		(self.batch_size, self.text_seq_length, self.hidden_size)		)

     # image only
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=model({"""pixel_values""": pixel_values}       ,		training=lowerCAmelCase		)
     self.parent.assertEqual(
         result.last_hidden_state.shape       ,		(self.batch_size, self.image_seq_length, self.hidden_size)		)



  def 	lowerCamelCase__       (						self :					Optional[int]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					Optional[int]       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					Dict       ,		lowerCAmelCase :					Tuple		)     ->					Optional[int]:


     '''simple docstring'''




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



  def 	lowerCamelCase__       (						self :					List[Any]       ,		lowerCAmelCase :					Tuple       ,		lowerCAmelCase :					List[Any]       ,		lowerCAmelCase :					List[str]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					str		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			=self.num_labels
     SCREAMING_SNAKE_CASE_: Optional[int]     			=TFLayoutLMvaForTokenClassification(config=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Optional[int]     			=model(
         lowerCAmelCase       ,		bbox=lowerCAmelCase       ,		pixel_values=lowerCAmelCase       ,		attention_mask=lowerCAmelCase       ,		token_type_ids=lowerCAmelCase       ,		labels=lowerCAmelCase       ,		training=lowerCAmelCase       ,		)
     self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.text_seq_length, self.num_labels)		)



  def 	lowerCamelCase__       (						self :					Any       ,		lowerCAmelCase :					Tuple       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					List[Any]       ,		lowerCAmelCase :					Dict       ,		lowerCAmelCase :					Optional[Any]		)     ->					Tuple:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			=2
     SCREAMING_SNAKE_CASE_: int     			=TFLayoutLMvaForQuestionAnswering(config=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: int     			=model(
         lowerCAmelCase       ,		bbox=lowerCAmelCase       ,		pixel_values=lowerCAmelCase       ,		attention_mask=lowerCAmelCase       ,		token_type_ids=lowerCAmelCase       ,		start_positions=lowerCAmelCase       ,		end_positions=lowerCAmelCase       ,		training=lowerCAmelCase       ,		)
     self.parent.assertEqual(result.start_logits.shape       ,		(self.batch_size, self.seq_length)		)
     self.parent.assertEqual(result.end_logits.shape       ,		(self.batch_size, self.seq_length)		)





  def 	lowerCamelCase__       (						self :					str		)     ->					List[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: str     			=self.prepare_config_and_inputs()
     (SCREAMING_SNAKE_CASE_): Optional[int]     			=config_and_inputs
     SCREAMING_SNAKE_CASE_: int     			={
         """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       ):
  UpperCamelCase	:				Optional[Any]     						=					(
      (
          TFLayoutLMvaModel,
          TFLayoutLMvaForQuestionAnswering,
          TFLayoutLMvaForSequenceClassification,
          TFLayoutLMvaForTokenClassification,
      )
      if is_tf_available()
      else ()
  )
  UpperCamelCase	:				List[Any]     						=					(
      {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
      if is_tf_available()
      else {}
  )

  UpperCamelCase	:				str     						=					False
  UpperCamelCase	:				Union[str, Any]     						=					False
  UpperCamelCase	:				Dict     						=					False



  def 	lowerCamelCase__       (						self :					List[Any]       ,		lowerCAmelCase :					str       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Any		)     ->					List[Any]:


     '''simple docstring'''




     return True



  def 	lowerCamelCase__       (						self :					Tuple       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Optional[int]=False		)     ->					dict:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=copy.deepcopy(lowerCAmelCase		)

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

     if return_labels:
        if model_class in get_values(lowerCAmelCase		):
           SCREAMING_SNAKE_CASE_: Union[str, Any]     			=tf.ones(self.model_tester.batch_size       ,		dtype=tf.intaa		)
        elif model_class in get_values(lowerCAmelCase		):
           SCREAMING_SNAKE_CASE_: List[Any]     			=tf.zeros(self.model_tester.batch_size       ,		dtype=tf.intaa		)
           SCREAMING_SNAKE_CASE_: Dict     			=tf.zeros(self.model_tester.batch_size       ,		dtype=tf.intaa		)
        elif model_class in get_values(lowerCAmelCase		):
           SCREAMING_SNAKE_CASE_: Union[str, Any]     			=tf.zeros(self.model_tester.batch_size       ,		dtype=tf.intaa		)
        elif model_class in get_values(lowerCAmelCase		):
           SCREAMING_SNAKE_CASE_: Tuple     			=tf.zeros(
               (self.model_tester.batch_size, self.model_tester.text_seq_length)       ,		dtype=tf.intaa		)

     return inputs_dict



  def 	lowerCamelCase__       (						self :					Any		)     ->					Optional[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[str]     			=TFLayoutLMvaModelTester(self		)
     SCREAMING_SNAKE_CASE_: int     			=ConfigTester(self       ,		config_class=lowerCAmelCase       ,		hidden_size=37		)



  def 	lowerCamelCase__       (						self :					Dict		)     ->					str:


     '''simple docstring'''




     self.config_tester.run_common_tests()



  def 	lowerCamelCase__       (						self :					Optional[Any]		)     ->					Union[str, Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=self.model_tester.prepare_config_and_inputs_for_common()
     for model_class in self.all_model_classes:
        SCREAMING_SNAKE_CASE_: str     			=model_class(lowerCAmelCase		)
        if getattr(lowerCAmelCase       ,		"""hf_compute_loss"""       ,		lowerCAmelCase		):
           # The number of elements in the loss should be the same as the number of elements in the label
           SCREAMING_SNAKE_CASE_: Optional[int]     			=self._prepare_for_class(inputs_dict.copy()       ,		lowerCAmelCase       ,		return_labels=lowerCAmelCase		)
           SCREAMING_SNAKE_CASE_: Tuple     			=prepared_for_class[
               sorted(prepared_for_class.keys() - inputs_dict.keys()       ,		reverse=lowerCAmelCase		)[0]
           ]
           SCREAMING_SNAKE_CASE_: Any     			=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()       ,		lowerCAmelCase       ,		return_labels=lowerCAmelCase		)
           SCREAMING_SNAKE_CASE_: Any     			=prepared_for_class.pop("""input_ids"""		)

           SCREAMING_SNAKE_CASE_: Tuple     			=model(lowerCAmelCase       ,		**lowerCAmelCase		)[0]
           self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)

           # Test that model correctly compute the loss when we mask some positions
           SCREAMING_SNAKE_CASE_: List[Any]     			=self._prepare_for_class(inputs_dict.copy()       ,		lowerCAmelCase       ,		return_labels=lowerCAmelCase		)
           SCREAMING_SNAKE_CASE_: Optional[int]     			=prepared_for_class.pop("""input_ids"""		)
           if "labels" in prepared_for_class:
              SCREAMING_SNAKE_CASE_: str     			=prepared_for_class["""labels"""].numpy()
              if len(labels.shape		) > 1 and labels.shape[1] != 1:
                 SCREAMING_SNAKE_CASE_: Dict     			=-100
                 SCREAMING_SNAKE_CASE_: Any     			=tf.convert_to_tensor(lowerCAmelCase		)
                 SCREAMING_SNAKE_CASE_: Optional[Any]     			=model(lowerCAmelCase       ,		**lowerCAmelCase		)[0]
                 self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)
                 self.assertTrue(not np.any(np.isnan(loss.numpy()		)		)		)

                # Test that model correctly compute the loss with a dict
           SCREAMING_SNAKE_CASE_: str     			=self._prepare_for_class(inputs_dict.copy()       ,		lowerCAmelCase       ,		return_labels=lowerCAmelCase		)
           SCREAMING_SNAKE_CASE_: List[str]     			=model(lowerCAmelCase		)[0]
           self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]		)

           # Test that model correctly compute the loss with a tuple
           SCREAMING_SNAKE_CASE_: List[str]     			=self._prepare_for_class(inputs_dict.copy()       ,		lowerCAmelCase       ,		return_labels=lowerCAmelCase		)

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

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

           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_: Any     			=prepared_for_class[value]

           SCREAMING_SNAKE_CASE_: Dict     			=tuple(lowerCAmelCase		)

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

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



  def 	lowerCamelCase__       (						self :					Union[str, Any]		)     ->					Union[str, Any]:


     '''simple docstring'''




     (
         SCREAMING_SNAKE_CASE_		
     ): Union[str, Any]     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)



  def 	lowerCamelCase__       (						self :					Optional[int]		)     ->					Union[str, Any]:


     '''simple docstring'''




     (
         SCREAMING_SNAKE_CASE_		
     ): Tuple     			=self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
        SCREAMING_SNAKE_CASE_: Optional[int]     			=type
        self.model_tester.create_and_check_model(lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)



  def 	lowerCamelCase__       (						self :					List[str]		)     ->					Any:


     '''simple docstring'''




     (
         SCREAMING_SNAKE_CASE_		
     ): str     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(
         lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)



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


     '''simple docstring'''




     (
         SCREAMING_SNAKE_CASE_		
     ): Optional[int]     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_token_classification(
         lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)



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


     '''simple docstring'''




     (
         SCREAMING_SNAKE_CASE_		
     ): Tuple     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(
         lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase       ,		lowerCAmelCase		)





  @slow
  def 	lowerCamelCase__       (						self :					str		)     ->					Optional[int]:


     '''simple docstring'''




     for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        SCREAMING_SNAKE_CASE_: Dict     			=TFLayoutLMvaModel.from_pretrained(lowerCAmelCase		)
        self.assertIsNotNone(lowerCAmelCase		)







def      __magic_name__				(							):
   SCREAMING_SNAKE_CASE_: Union[str, Any]     			=Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
   return image





@require_tf
class 					a	(  unittest.TestCase       ):



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


     '''simple docstring'''




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





  @slow
  def 	lowerCamelCase__       (						self :					Dict		)     ->					str:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""		)

     SCREAMING_SNAKE_CASE_: str     			=self.default_image_processor
     SCREAMING_SNAKE_CASE_: Dict     			=prepare_img()
     SCREAMING_SNAKE_CASE_: List[str]     			=image_processor(images=lowerCAmelCase       ,		return_tensors="""tf"""		).pixel_values

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

     # forward pass
     SCREAMING_SNAKE_CASE_: Tuple     			=model(input_ids=lowerCAmelCase       ,		bbox=lowerCAmelCase       ,		pixel_values=lowerCAmelCase       ,		training=lowerCAmelCase		)

     # verify the logits
     SCREAMING_SNAKE_CASE_: List[Any]     			=(1, 199, 768)
     self.assertEqual(outputs.last_hidden_state.shape       ,		lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Optional[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]       ,		lowerCAmelCase       ,		atol=1E-4		)		)








"""simple docstring"""
def      __magic_name__				(							lowercase							,			lowercase ):
   return int((input_a, input_a).count(0 ) == 0 )





def      __magic_name__				(							):
   assert and_gate(0							,			0 ) == 0
   assert and_gate(0							,			1 ) == 0
   assert and_gate(1							,			0 ) == 0
   assert and_gate(1							,			1 ) == 1


if __name__ == "__main__":
   test_and_gate()
   print(and_gate(1, 0))
   print(and_gate(0, 0))
   print(and_gate(0, 1))
   print(and_gate(1, 1))



