
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:

  """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_=5_12	,      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_=10_00	,      ):
       UpperCamelCase__				=    parent
       UpperCamelCase__				=    batch_size
       UpperCamelCase__				=    num_channels
       UpperCamelCase__				=    image_size
       UpperCamelCase__				=    patch_size
       UpperCamelCase__				=    is_training
       UpperCamelCase__				=    use_input_mask
       UpperCamelCase__				=    use_token_type_ids
       UpperCamelCase__				=    use_labels
       UpperCamelCase__				=    vocab_size
       UpperCamelCase__				=    hidden_size
       UpperCamelCase__				=    num_hidden_layers
       UpperCamelCase__				=    num_attention_heads
       UpperCamelCase__				=    intermediate_size
       UpperCamelCase__				=    hidden_act
       UpperCamelCase__				=    hidden_dropout_prob
       UpperCamelCase__				=    attention_probs_dropout_prob
       UpperCamelCase__				=    max_position_embeddings
       UpperCamelCase__				=    type_vocab_size
       UpperCamelCase__				=    type_sequence_label_size
       UpperCamelCase__				=    initializer_range
       UpperCamelCase__				=    coordinate_size
       UpperCamelCase__				=    shape_size
       UpperCamelCase__				=    num_labels
       UpperCamelCase__				=    num_choices
       UpperCamelCase__				=    scope
       UpperCamelCase__				=    range_bbox

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







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    ids_tensor([self.batch_size, self.text_seq_length]	,      self.vocab_size						)

       UpperCamelCase__				=    ids_tensor([self.batch_size, self.text_seq_length, 4]	,      self.range_bbox						)
       UpperCamelCase__				=    bbox.numpy()
       # Ensure that bbox is legal
       for i in range(bbox.shape[0]						):
            for j in range(bbox.shape[1]						):
                 if bbox[i, j, 3] < bbox[i, j, 1]:
                      UpperCamelCase__				=    bbox[i, j, 3]
                      UpperCamelCase__				=    bbox[i, j, 1]
                      UpperCamelCase__				=    tmp_coordinate
                 if bbox[i, j, 2] < bbox[i, j, 0]:
                      UpperCamelCase__				=    bbox[i, j, 2]
                      UpperCamelCase__				=    bbox[i, j, 0]
                      UpperCamelCase__				=    tmp_coordinate
       UpperCamelCase__				=    tf.constant(SCREAMING_SNAKE_CASE_						)

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

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

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

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

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

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







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    TFLayoutLMvaModel(config=SCREAMING_SNAKE_CASE_						)

       # text + image
       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_	,      pixel_values=SCREAMING_SNAKE_CASE_	,      training=SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    model(
           SCREAMING_SNAKE_CASE_	,      bbox=SCREAMING_SNAKE_CASE_	,      pixel_values=SCREAMING_SNAKE_CASE_	,      attention_mask=SCREAMING_SNAKE_CASE_	,      token_type_ids=SCREAMING_SNAKE_CASE_	,      training=SCREAMING_SNAKE_CASE_	,      )
       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_	,      bbox=SCREAMING_SNAKE_CASE_	,      pixel_values=SCREAMING_SNAKE_CASE_	,      training=SCREAMING_SNAKE_CASE_						)

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

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

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







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    self.num_labels
       UpperCamelCase__				=    TFLayoutLMvaForSequenceClassification(config=SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    model(
           SCREAMING_SNAKE_CASE_	,      bbox=SCREAMING_SNAKE_CASE_	,      pixel_values=SCREAMING_SNAKE_CASE_	,      attention_mask=SCREAMING_SNAKE_CASE_	,      token_type_ids=SCREAMING_SNAKE_CASE_	,      labels=SCREAMING_SNAKE_CASE_	,      training=SCREAMING_SNAKE_CASE_	,      )
       self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.num_labels)						)







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    self.num_labels
       UpperCamelCase__				=    TFLayoutLMvaForTokenClassification(config=SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    model(
           SCREAMING_SNAKE_CASE_	,      bbox=SCREAMING_SNAKE_CASE_	,      pixel_values=SCREAMING_SNAKE_CASE_	,      attention_mask=SCREAMING_SNAKE_CASE_	,      token_type_ids=SCREAMING_SNAKE_CASE_	,      labels=SCREAMING_SNAKE_CASE_	,      training=SCREAMING_SNAKE_CASE_	,      )
       self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.text_seq_length, self.num_labels)						)







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







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.prepare_config_and_inputs()
       ((UpperCamelCase__)		,	(UpperCamelCase__)		,	(UpperCamelCase__)		,	(UpperCamelCase__)		,	(UpperCamelCase__)		,	(UpperCamelCase__)		,	(UpperCamelCase__)		,	(UpperCamelCase__))				=    config_and_inputs
       UpperCamelCase__				=    {
           """input_ids""": input_ids,
           """bbox""": bbox,
           """pixel_values""": pixel_values,
           """token_type_ids""": token_type_ids,
           """attention_mask""": input_mask,
       }
       return config, inputs_dict






@require_tf
class      __A(    __lowerCamelCase    ,				__lowerCamelCase    ,				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 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       return True







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_=False						):
       UpperCamelCase__				=    copy.deepcopy(SCREAMING_SNAKE_CASE_						)

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

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

       return inputs_dict







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    TFLayoutLMvaModelTester(self						)
       UpperCamelCase__				=    ConfigTester(self	,      config_class=SCREAMING_SNAKE_CASE_	,      hidden_size=37						)







  def 	UpperCAmelCase_ (self						):
       self.config_tester.run_common_tests()







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

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

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

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

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

                 # Test that model correctly compute the loss with a tuple
                 UpperCamelCase__				=    self._prepare_for_class(inputs_dict.copy()	,      SCREAMING_SNAKE_CASE_	,      return_labels=SCREAMING_SNAKE_CASE_						)

                 # Get keys that were added with the _prepare_for_class function
                 UpperCamelCase__				=    prepared_for_class.keys() - inputs_dict.keys()
                 UpperCamelCase__				=    inspect.signature(model.call						).parameters
                 UpperCamelCase__				=    list(signature.keys()						)

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

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

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

                 UpperCamelCase__				=    tuple(SCREAMING_SNAKE_CASE_						)

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

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







  def 	UpperCAmelCase_ (self						):
       (
           (
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	
       )				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       (
           (
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	
       )				=    self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
            UpperCamelCase__				=    type
            self.model_tester.create_and_check_model(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       (
           (
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	
       )				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(
           SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       (
           (
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	
       )				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(
           SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       (
           (
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	(
           UpperCamelCase__
       )		,	
       )				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(
           SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)







  @slow
  def 	UpperCAmelCase_ (self						):
       for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCamelCase__				=    TFLayoutLMvaModel.from_pretrained(SCREAMING_SNAKE_CASE_						)
            self.assertIsNotNone(SCREAMING_SNAKE_CASE_						)






def 						__magic_name__			(   ):



     '''simple docstring'''




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




@require_tf
class      __A(    unittest.TestCase			):

  """simple docstring"""







  @cached_property
  def 	UpperCAmelCase_ (self						):
       return LayoutLMvaImageProcessor(apply_ocr=SCREAMING_SNAKE_CASE_						) if is_vision_available() else None







  @slow
  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""						)

       UpperCamelCase__				=    self.default_image_processor
       UpperCamelCase__				=    prepare_img()
       UpperCamelCase__				=    image_processor(images=SCREAMING_SNAKE_CASE_	,      return_tensors="""tf"""						).pixel_values

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

       # forward pass
       UpperCamelCase__				=    model(input_ids=SCREAMING_SNAKE_CASE_	,      bbox=SCREAMING_SNAKE_CASE_	,      pixel_values=SCREAMING_SNAKE_CASE_	,      training=SCREAMING_SNAKE_CASE_						)

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

       UpperCamelCase__				=    tf.constant(
           [[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]]						)

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







from pathlib import Path
from typing import List

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText


if is_torch_available():
    import torch

if is_vision_available():
    from PIL import Image


lowerCamelCase_						     =					['''text''', '''image''', '''audio''']






def 						__magic_name__			(   __a      :	List[str]						):



     '''simple docstring'''




     UpperCamelCase__				=    []

     for input_type in input_types:
          if input_type == "text":
               inputs.append("""Text input"""						)
          elif input_type == "image":
               inputs.append(
                   Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO"""						)						) / """000000039769.png"""						).resize((512, 512)						)						)
          elif input_type == "audio":
               inputs.append(torch.ones(3_000						)						)
          elif isinstance(__a	,		__a						):
               inputs.append(create_inputs(__a						)						)
          else:
               raise ValueError(f"Invalid type requested: {input_type}"						)

     return inputs






def 						__magic_name__			(   __a      :	List						):



     '''simple docstring'''




     UpperCamelCase__				=    []

     for output in outputs:
          if isinstance(__a	,		(str, AgentText)						):
               output_types.append("""text"""						)
          elif isinstance(__a	,		(Image.Image, AgentImage)						):
               output_types.append("""image"""						)
          elif isinstance(__a	,		(torch.Tensor, AgentAudio)						):
               output_types.append("""audio"""						)
          else:
               raise ValueError(f"Invalid output: {output}"						)

     return output_types




@is_tool_test
class      __A:

  """simple docstring"""







  def 	UpperCAmelCase_ (self						):
       self.assertTrue(hasattr(self.tool	,      """inputs"""						)						)
       self.assertTrue(hasattr(self.tool	,      """outputs"""						)						)

       UpperCamelCase__				=    self.tool.inputs
       for _input in inputs:
            if isinstance(_input	,      SCREAMING_SNAKE_CASE_						):
                 for __input in _input:
                      self.assertTrue(__input in authorized_types						)
            else:
                 self.assertTrue(_input in authorized_types						)

       UpperCamelCase__				=    self.tool.outputs
       for _output in outputs:
            self.assertTrue(_output in authorized_types						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    create_inputs(self.tool.inputs						)
       UpperCamelCase__				=    self.tool(*SCREAMING_SNAKE_CASE_						)

       # There is a single output
       if len(self.tool.outputs						) == 1:
            UpperCamelCase__				=    [outputs]

       self.assertListEqual(output_types(SCREAMING_SNAKE_CASE_						)	,      self.tool.outputs						)







  def 	UpperCAmelCase_ (self						):
       self.assertTrue(hasattr(self.tool	,      """description"""						)						)
       self.assertTrue(hasattr(self.tool	,      """default_checkpoint"""						)						)
       self.assertTrue(self.tool.description.startswith("""This is a tool that"""						)						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    create_inputs(self.tool.inputs						)
       UpperCamelCase__				=    self.tool(*SCREAMING_SNAKE_CASE_						)

       if not isinstance(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
            UpperCamelCase__				=    [outputs]

       self.assertEqual(len(SCREAMING_SNAKE_CASE_						)	,      len(self.tool.outputs						)						)

       for output, output_type in zip(SCREAMING_SNAKE_CASE_	,      self.tool.outputs						):
            UpperCamelCase__				=    AGENT_TYPE_MAPPING[output_type]
            self.assertTrue(isinstance(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    create_inputs(self.tool.inputs						)

       UpperCamelCase__				=    []

       for _input, input_type in zip(SCREAMING_SNAKE_CASE_	,      self.tool.inputs						):
            if isinstance(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
                 _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input						) for _input_type in input_type]						)
            else:
                 _inputs.append(AGENT_TYPE_MAPPING[input_type](_input						)						)

        # Should not raise an error
       UpperCamelCase__				=    self.tool(*SCREAMING_SNAKE_CASE_						)

       if not isinstance(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
            UpperCamelCase__				=    [outputs]

       self.assertEqual(len(SCREAMING_SNAKE_CASE_						)	,      len(self.tool.outputs						)						)





