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			:   List[Any]  ,				__SCREAMING_SNAKE_CASE			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Dict=2  ,				__SCREAMING_SNAKE_CASE			:   int=3  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=4  ,				__SCREAMING_SNAKE_CASE			:   Tuple=2  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]=7  ,				__SCREAMING_SNAKE_CASE			:   Any=True  ,				__SCREAMING_SNAKE_CASE			:   str=True  ,				__SCREAMING_SNAKE_CASE			:   List[Any]=True  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]=True  ,				__SCREAMING_SNAKE_CASE			:   int=99  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]=36  ,				__SCREAMING_SNAKE_CASE			:   int=2  ,				__SCREAMING_SNAKE_CASE			:   Any=4  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]=37  ,				__SCREAMING_SNAKE_CASE			:   str="gelu"  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=0.1  ,				__SCREAMING_SNAKE_CASE			:   int=0.1  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=5_12  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=16  ,				__SCREAMING_SNAKE_CASE			:   Tuple=2  ,				__SCREAMING_SNAKE_CASE			:   Dict=0.02  ,				__SCREAMING_SNAKE_CASE			:   Dict=6  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]=6  ,				__SCREAMING_SNAKE_CASE			:   List[str]=3  ,				__SCREAMING_SNAKE_CASE			:   int=4  ,				__SCREAMING_SNAKE_CASE			:   Dict=None  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]=10_00  ,				):
   __a							=	parent
   __a							=	batch_size
   __a							=	num_channels
   __a							=	image_size
   __a							=	patch_size
   __a							=	is_training
   __a							=	use_input_mask
   __a							=	use_token_type_ids
   __a							=	use_labels
   __a							=	vocab_size
   __a							=	hidden_size
   __a							=	num_hidden_layers
   __a							=	num_attention_heads
   __a							=	intermediate_size
   __a							=	hidden_act
   __a							=	hidden_dropout_prob
   __a							=	attention_probs_dropout_prob
   __a							=	max_position_embeddings
   __a							=	type_vocab_size
   __a							=	type_sequence_label_size
   __a							=	initializer_range
   __a							=	coordinate_size
   __a							=	shape_size
   __a							=	num_labels
   __a							=	num_choices
   __a							=	scope
   __a							=	range_bbox

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

  def 		_UpperCAmelCase (		self			:   List[Any]							):
   __a							=	ids_tensor([self.batch_size, self.text_seq_length]  ,				self.vocab_size							)

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

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

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

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

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

   __a							=	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			:   int  ,				__SCREAMING_SNAKE_CASE			:   List[str]  ,				__SCREAMING_SNAKE_CASE			:   Any  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]  ,				__SCREAMING_SNAKE_CASE			:   List[str]  ,				__SCREAMING_SNAKE_CASE			:   int  ,				__SCREAMING_SNAKE_CASE			:   List[str]							):
   __a							=	TFLayoutLMvaModel(config=__SCREAMING_SNAKE_CASE							)

   # text + image
   __a							=	model(__SCREAMING_SNAKE_CASE  ,				pixel_values=__SCREAMING_SNAKE_CASE  ,				training=__SCREAMING_SNAKE_CASE							)
   __a							=	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  ,				)
   __a							=	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
   __a							=	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
   __a							=	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			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Any  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]  ,				__SCREAMING_SNAKE_CASE			:   List[Any]  ,				__SCREAMING_SNAKE_CASE			:   int  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]  ,				__SCREAMING_SNAKE_CASE			:   Any							):
   __a							=	self.num_labels
   __a							=	TFLayoutLMvaForSequenceClassification(config=__SCREAMING_SNAKE_CASE							)
   __a							=	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			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]  ,				__SCREAMING_SNAKE_CASE			:   List[str]  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Union[str, Any]							):
   __a							=	self.num_labels
   __a							=	TFLayoutLMvaForTokenClassification(config=__SCREAMING_SNAKE_CASE							)
   __a							=	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			:   Union[str, Any]  ,				__SCREAMING_SNAKE_CASE			:   List[str]  ,				__SCREAMING_SNAKE_CASE			:   int  ,				__SCREAMING_SNAKE_CASE			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   List[str]  ,				__SCREAMING_SNAKE_CASE			:   List[Any]  ,				__SCREAMING_SNAKE_CASE			:   Any							):
   __a							=	2
   __a							=	TFLayoutLMvaForQuestionAnswering(config=__SCREAMING_SNAKE_CASE							)
   __a							=	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			:   Optional[Any]							):
   __a							=	self.prepare_config_and_inputs()
   ((__a)							,  (__a)							,  (__a)							,  (__a)							,  (__a)							,  (__a)							,  (__a)							,  (__a))							=	config_and_inputs
   __a							=	{
       "input_ids": input_ids,
       "bbox": bbox,
       "pixel_values": pixel_values,
       "token_type_ids": token_type_ids,
       "attention_mask": input_mask,
   }
   return config, inputs_dict
@require_tf
class  A_			(							a_      ,							a_      ,							unittest.TestCase			):
  _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 		_UpperCAmelCase (		self			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   str  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   Optional[int]  ,				__SCREAMING_SNAKE_CASE			:   Any  ,				__SCREAMING_SNAKE_CASE			:   List[Any]							):
   return True

  def 		_UpperCAmelCase (		self			:   Tuple  ,				__SCREAMING_SNAKE_CASE			:   Dict  ,				__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				__SCREAMING_SNAKE_CASE			:   str=False							):
   __a							=	copy.deepcopy(__SCREAMING_SNAKE_CASE							)

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

   return inputs_dict

  def 		_UpperCAmelCase (		self			:   Dict							):
   __a							=	TFLayoutLMvaModelTester(self							)
   __a							=	ConfigTester(self  ,				config_class=__SCREAMING_SNAKE_CASE  ,				hidden_size=37							)

  def 		_UpperCAmelCase (		self			:   Union[str, Any]							):
   self.config_tester.run_common_tests()

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

     # Test that model correctly compute the loss with kwargs
     __a							=	self._prepare_for_class(inputs_dict.copy()  ,				__SCREAMING_SNAKE_CASE  ,				return_labels=__SCREAMING_SNAKE_CASE							)
     __a							=	prepared_for_class.pop("input_ids"							)

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

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

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

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

     __a							=	tuple(__SCREAMING_SNAKE_CASE							)

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

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

  def 		_UpperCAmelCase (		self			:   Optional[Any]							):
   (
       (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  
   )							=	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			:   Dict							):
   (
       (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  
   )							=	self.model_tester.prepare_config_and_inputs()
   for type in ["absolute", "relative_key", "relative_key_query"]:
    __a							=	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			:   Dict							):
   (
       (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  
   )							=	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							):
   (
       (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  
   )							=	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			:   Union[str, Any]							):
   (
       (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  (
       __a
   )							,  
   )							=	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			:   Optional[int]							):
   for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
    __a							=	TFLayoutLMvaModel.from_pretrained(__SCREAMING_SNAKE_CASE							)
    self.assertIsNotNone(__SCREAMING_SNAKE_CASE							)



def 	__A		(      ):



 """simple docstring"""


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






@require_tf
class  A_			(							unittest.TestCase			):

  @cached_property
  def 		_UpperCAmelCase (		self			:   Dict							):
   return LayoutLMvaImageProcessor(apply_ocr=__SCREAMING_SNAKE_CASE							) if is_vision_available() else None

  @slow
  def 		_UpperCAmelCase (		self			:   Optional[int]							):
   __a							=	TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base"							)

   __a							=	self.default_image_processor
   __a							=	prepare_img()
   __a							=	image_processor(images=__SCREAMING_SNAKE_CASE  ,				return_tensors="tf"							).pixel_values

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

   # forward pass
   __a							=	model(input_ids=__SCREAMING_SNAKE_CASE  ,				bbox=__SCREAMING_SNAKE_CASE  ,				pixel_values=__SCREAMING_SNAKE_CASE  ,				training=__SCREAMING_SNAKE_CASE							)

   # verify the logits
   __a							=	(1, 1_99, 7_68)
   self.assertEqual(outputs.last_hidden_state.shape  ,				__SCREAMING_SNAKE_CASE							)

   __a							=	tf.constant(
       [[-0.05_29, 0.36_18, 0.16_32], [-0.15_87, -0.16_67, -0.04_00], [-0.15_57, -0.16_71, -0.05_05]]							)

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



import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding
class  A_			(							a_			):
  _SCREAMING_SNAKE_CASE     					=      ["""image_processor""", """tokenizer"""]
  _SCREAMING_SNAKE_CASE     					=      """ChineseCLIPImageProcessor"""
  _SCREAMING_SNAKE_CASE     					=      ("""BertTokenizer""", """BertTokenizerFast""")

  def __init__(		self			:   List[str]  ,				__SCREAMING_SNAKE_CASE			:   Any=None  ,				__SCREAMING_SNAKE_CASE			:   Tuple=None  ,				**__SCREAMING_SNAKE_CASE			:   List[Any]							):
   __a							=	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  ,				)
    __a							=	kwargs.pop("feature_extractor"							)

   __a							=	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							)
   __a							=	self.image_processor

  def __call__(		self			:   Optional[int]  ,				__SCREAMING_SNAKE_CASE			:   Dict=None  ,				__SCREAMING_SNAKE_CASE			:   Dict=None  ,				__SCREAMING_SNAKE_CASE			:   Tuple=None  ,				**__SCREAMING_SNAKE_CASE			:   List[Any]							):

   if text is None and images is None:
    raise ValueError("You have to specify either text or images. Both cannot be none."							)

   if text is not None:
    __a							=	self.tokenizer(__SCREAMING_SNAKE_CASE  ,				return_tensors=__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE							)

   if images is not None:
    __a							=	self.image_processor(__SCREAMING_SNAKE_CASE  ,				return_tensors=__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE							)

   if text is not None and images is not None:
    __a							=	image_features.pixel_values
    return encoding
   elif text is not None:
    return encoding
   else:
    return BatchEncoding(data=dict(**__SCREAMING_SNAKE_CASE							)  ,				tensor_type=__SCREAMING_SNAKE_CASE							)

  def 		_UpperCAmelCase (		self			:   int  ,				*__SCREAMING_SNAKE_CASE			:   Optional[Any]  ,				**__SCREAMING_SNAKE_CASE			:   str							):
   return self.tokenizer.batch_decode(*__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE							)

  def 		_UpperCAmelCase (		self			:   List[Any]  ,				*__SCREAMING_SNAKE_CASE			:   Optional[int]  ,				**__SCREAMING_SNAKE_CASE			:   Optional[int]							):
   return self.tokenizer.decode(*__SCREAMING_SNAKE_CASE  ,				**__SCREAMING_SNAKE_CASE							)

  @property
  def 		_UpperCAmelCase (		self			:   Union[str, Any]							):
   __a							=	self.tokenizer.model_input_names
   __a							=	self.image_processor.model_input_names
   return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names							)							)

  @property
  def 		_UpperCAmelCase (		self			:   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


