






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


      '''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=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		,				) ->				List[Any]:
        snake_case_				:							int						 =       parent
        snake_case_				:							Dict						 =       batch_size
        snake_case_				:							str						 =       num_channels
        snake_case_				:							Optional[Any]						 =       image_size
        snake_case_				:							Tuple						 =       patch_size
        snake_case_				:							Optional[int]						 =       is_training
        snake_case_				:							List[Any]						 =       use_input_mask
        snake_case_				:							Optional[Any]						 =       use_token_type_ids
        snake_case_				:							Optional[int]						 =       use_labels
        snake_case_				:							List[str]						 =       vocab_size
        snake_case_				:							int						 =       hidden_size
        snake_case_				:							List[Any]						 =       num_hidden_layers
        snake_case_				:							List[Any]						 =       num_attention_heads
        snake_case_				:							int						 =       intermediate_size
        snake_case_				:							str						 =       hidden_act
        snake_case_				:							List[Any]						 =       hidden_dropout_prob
        snake_case_				:							str						 =       attention_probs_dropout_prob
        snake_case_				:							Union[str, Any]						 =       max_position_embeddings
        snake_case_				:							Union[str, Any]						 =       type_vocab_size
        snake_case_				:							str						 =       type_sequence_label_size
        snake_case_				:							List[Any]						 =       initializer_range
        snake_case_				:							Optional[int]						 =       coordinate_size
        snake_case_				:							List[str]						 =       shape_size
        snake_case_				:							Tuple						 =       num_labels
        snake_case_				:							List[str]						 =       num_choices
        snake_case_				:							Dict						 =       scope
        snake_case_				:							Tuple						 =       range_bbox

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






      def       _lowerCAmelCase       (	self				) ->				int:
        snake_case_				:							int						 =       ids_tensor([self.batch_size, self.text_seq_length]		,				self.vocab_size				)

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

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

        snake_case_				:							Dict						 =       None
        if self.use_input_mask:
          snake_case_				:							str						 =       random_attention_mask([self.batch_size, self.text_seq_length]				)

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

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

        snake_case_				:							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		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Any:
        snake_case_				:							Optional[Any]						 =       TFLayoutLMvaModel(config=UpperCamelCase_				)

        # text + image
        snake_case_				:							Optional[Any]						 =       model(UpperCamelCase_		,				pixel_values=UpperCamelCase_		,				training=UpperCamelCase_				)
        snake_case_				:							str						 =       model(
            UpperCamelCase_		,				bbox=UpperCamelCase_		,				pixel_values=UpperCamelCase_		,				attention_mask=UpperCamelCase_		,				token_type_ids=UpperCamelCase_		,				training=UpperCamelCase_		,				)
        snake_case_				:							List[str]						 =       model(UpperCamelCase_		,				bbox=UpperCamelCase_		,				pixel_values=UpperCamelCase_		,				training=UpperCamelCase_				)

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

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

        # image only
        snake_case_				:							int						 =       model({"pixel_values": pixel_values}		,				training=UpperCamelCase_				)
        self.parent.assertEqual(
            result.last_hidden_state.shape		,				(self.batch_size, self.image_seq_length, self.hidden_size)				)






      def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				List[Any]:
        snake_case_				:							List[str]						 =       self.num_labels
        snake_case_				:							List[Any]						 =       TFLayoutLMvaForSequenceClassification(config=UpperCamelCase_				)
        snake_case_				:							Any						 =       model(
            UpperCamelCase_		,				bbox=UpperCamelCase_		,				pixel_values=UpperCamelCase_		,				attention_mask=UpperCamelCase_		,				token_type_ids=UpperCamelCase_		,				labels=UpperCamelCase_		,				training=UpperCamelCase_		,				)
        self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)				)






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






      def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Any:
        snake_case_				:							int						 =       2
        snake_case_				:							Tuple						 =       TFLayoutLMvaForQuestionAnswering(config=UpperCamelCase_				)
        snake_case_				:							Union[str, Any]						 =       model(
            UpperCamelCase_		,				bbox=UpperCamelCase_		,				pixel_values=UpperCamelCase_		,				attention_mask=UpperCamelCase_		,				token_type_ids=UpperCamelCase_		,				start_positions=UpperCamelCase_		,				end_positions=UpperCamelCase_		,				training=UpperCamelCase_		,				)
        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				) ->				List[Any]:
        snake_case_				:							Optional[Any]						 =       self.prepare_config_and_inputs()
        (snake_case_)				:							Tuple						 =       config_and_inputs
        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 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					,  SCREAMING_SNAKE_CASE__					,  unittest.TestCase					):


      '''simple docstring'''




      A     :   str						=					(
          (
              TFLayoutLMvaModel,
              TFLayoutLMvaForQuestionAnswering,
              TFLayoutLMvaForSequenceClassification,
              TFLayoutLMvaForTokenClassification,
          )
          if is_tf_available()
          else ()
      )
      A     :   Union[str, Any]						=					(
          {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
          if is_tf_available()
          else {}
      )

      A     :   int						=					False
      A     :   str						=					False
      A     :   Optional[int]						=					False






      def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				) ->				Dict:
        return True






      def       _lowerCAmelCase       (	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE=False				) ->				dict:
        snake_case_				:							Dict						 =       copy.deepcopy(UpperCamelCase_				)

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

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

        return inputs_dict






      def       _lowerCAmelCase       (	self				) ->				Optional[int]:
        snake_case_				:							str						 =       TFLayoutLMvaModelTester(self				)
        snake_case_				:							Optional[Any]						 =       ConfigTester(self		,				config_class=UpperCamelCase_		,				hidden_size=37				)






      def       _lowerCAmelCase       (	self				) ->				Dict:
        self.config_tester.run_common_tests()






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

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

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

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

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

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

            for index, value in sorted_tuple_index_mapping:
              snake_case_				:							int						 =       prepared_for_class[value]

            snake_case_				:							Any						 =       tuple(UpperCamelCase_				)

            # Send to model
            snake_case_				:							List[str]						 =       model(tuple_input[:-1]				)[0]

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






      def       _lowerCAmelCase       (	self				) ->				int:
        (
            snake_case_    
        )				:							int						 =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_				)






      def       _lowerCAmelCase       (	self				) ->				int:
        (
            snake_case_    
        )				:							Tuple						 =       self.model_tester.prepare_config_and_inputs()
        for type in ["absolute", "relative_key", "relative_key_query"]:
          snake_case_				:							Dict						 =       type
          self.model_tester.create_and_check_model(UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_				)






      def       _lowerCAmelCase       (	self				) ->				str:
        (
            snake_case_    
        )				:							Union[str, Any]						 =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(
            UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_				)






      def       _lowerCAmelCase       (	self				) ->				Tuple:
        (
            snake_case_    
        )				:							Optional[Any]						 =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(
            UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_				)






      def       _lowerCAmelCase       (	self				) ->				Any:
        (
            snake_case_    
        )				:							List[Any]						 =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(
            UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_		,				UpperCamelCase_				)






      @slow
      def       _lowerCAmelCase       (	self				) ->				Tuple:





        for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          snake_case_				:							Optional[int]						 =       TFLayoutLMvaModel.from_pretrained(UpperCamelCase_				)
          self.assertIsNotNone(UpperCamelCase_				)




def      lowerCAmelCase__	(    ):
  snake_case_				:							List[str]						 =       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
  return image




@require_tf
class 		UpperCAmelCase_						(	unittest.TestCase					):


      '''simple docstring'''




      @cached_property
      def       _lowerCAmelCase       (	self				) ->				Optional[Any]:
        return LayoutLMvaImageProcessor(apply_ocr=UpperCamelCase_				) if is_vision_available() else None






      @slow
      def       _lowerCAmelCase       (	self				) ->				List[str]:
        snake_case_				:							Optional[int]						 =       TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base"				)

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

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

        # forward pass
        snake_case_				:							Optional[int]						 =       model(input_ids=UpperCamelCase_		,				bbox=UpperCamelCase_		,				pixel_values=UpperCamelCase_		,				training=UpperCamelCase_				)

        # verify the logits
        snake_case_				:							Any						 =       (1, 199, 768)
        self.assertEqual(outputs.last_hidden_state.shape		,				UpperCamelCase_				)

        snake_case_				:							Union[str, Any]						 =       tf.constant(
            [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]				)

        self.assertTrue(np.allclose(outputs.last_hidden_state[0, :3, :3]		,				UpperCamelCase_		,				atol=1e-4				)				)








import warnings
from typing import List, Optional, Union

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   Tuple						=					['image_processor', 'tokenizer']
						A     :   List[Any]						=					'ViltImageProcessor'
						A     :   Optional[Any]						=					('BertTokenizer', 'BertTokenizerFast')






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=None		,				**_SCREAMING_SNAKE_CASE				) ->				int:
								snake_case_				:							str						 =       None
								if "feature_extractor" in kwargs:
										warnings.warn(
										    "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
										    " instead."		,				_SCREAMING_SNAKE_CASE		,				)
										snake_case_				:							str						 =       kwargs.pop("feature_extractor"				)

								snake_case_				:							Tuple						 =       image_processor if image_processor is not None else feature_extractor
								if image_processor is None:
										raise ValueError("You need to specify an `image_processor`."				)
								if tokenizer is None:
										raise ValueError("You need to specify a `tokenizer`."				)

								super().__init__(_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE				)
								snake_case_				:							str						 =       self.image_processor






						def __call__(	self		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = True		,				_SCREAMING_SNAKE_CASE = False		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = 0		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = None		,				_SCREAMING_SNAKE_CASE = False		,				_SCREAMING_SNAKE_CASE = False		,				_SCREAMING_SNAKE_CASE = False		,				_SCREAMING_SNAKE_CASE = False		,				_SCREAMING_SNAKE_CASE = True		,				_SCREAMING_SNAKE_CASE = None		,				**_SCREAMING_SNAKE_CASE		,				) ->				BatchEncoding:
								snake_case_				:							List[Any]						 =       self.tokenizer(
								    text=_SCREAMING_SNAKE_CASE		,				add_special_tokens=_SCREAMING_SNAKE_CASE		,				padding=_SCREAMING_SNAKE_CASE		,				truncation=_SCREAMING_SNAKE_CASE		,				max_length=_SCREAMING_SNAKE_CASE		,				stride=_SCREAMING_SNAKE_CASE		,				pad_to_multiple_of=_SCREAMING_SNAKE_CASE		,				return_token_type_ids=_SCREAMING_SNAKE_CASE		,				return_attention_mask=_SCREAMING_SNAKE_CASE		,				return_overflowing_tokens=_SCREAMING_SNAKE_CASE		,				return_special_tokens_mask=_SCREAMING_SNAKE_CASE		,				return_offsets_mapping=_SCREAMING_SNAKE_CASE		,				return_length=_SCREAMING_SNAKE_CASE		,				verbose=_SCREAMING_SNAKE_CASE		,				return_tensors=_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE		,				)
								# add pixel_values + pixel_mask
								snake_case_				:							str						 =       self.image_processor(_SCREAMING_SNAKE_CASE		,				return_tensors=_SCREAMING_SNAKE_CASE				)
								encoding.update(_SCREAMING_SNAKE_CASE				)

								return encoding






						def       _lowerCAmelCase       (	self		,				*_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				List[str]:
								return self.tokenizer.batch_decode(*_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self		,				*_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				Dict:
								return self.tokenizer.decode(*_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)






						@property
						def       _lowerCAmelCase       (	self				) ->				Tuple:
								snake_case_				:							List[Any]						 =       self.tokenizer.model_input_names
								snake_case_				:							Tuple						 =       self.image_processor.model_input_names
								return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names				)				)






						@property
						def       _lowerCAmelCase       (	self				) ->				Optional[Any]:
								warnings.warn(
								    "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead."		,				_SCREAMING_SNAKE_CASE		,				)
								return self.image_processor_class






						@property
						def       _lowerCAmelCase       (	self				) ->				Optional[int]:
								warnings.warn(
								    "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead."		,				_SCREAMING_SNAKE_CASE		,				)
								return self.image_processor
