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       ,  __UpperCAmelCase     :						Any       ,  __UpperCAmelCase     :						str=2       ,  __UpperCAmelCase     :						str=3       ,  __UpperCAmelCase     :						Tuple=4       ,  __UpperCAmelCase     :						List[Any]=2       ,  __UpperCAmelCase     :						int=7       ,  __UpperCAmelCase     :						Dict=True       ,  __UpperCAmelCase     :						List[Any]=True       ,  __UpperCAmelCase     :						Tuple=True       ,  __UpperCAmelCase     :						Union[str, Any]=True       ,  __UpperCAmelCase     :						Dict=9_9       ,  __UpperCAmelCase     :						List[str]=3_6       ,  __UpperCAmelCase     :						Optional[Any]=2       ,  __UpperCAmelCase     :						int=4       ,  __UpperCAmelCase     :						Optional[Any]=3_7       ,  __UpperCAmelCase     :						List[str]="gelu"       ,  __UpperCAmelCase     :						Dict=0.1       ,  __UpperCAmelCase     :						Any=0.1       ,  __UpperCAmelCase     :						int=5_1_2       ,  __UpperCAmelCase     :						str=1_6       ,  __UpperCAmelCase     :						str=2       ,  __UpperCAmelCase     :						Any=0.02       ,  __UpperCAmelCase     :						str=6       ,  __UpperCAmelCase     :						str=6       ,  __UpperCAmelCase     :						Any=3       ,  __UpperCAmelCase     :						List[Any]=4       ,  __UpperCAmelCase     :						Dict=None       ,  __UpperCAmelCase     :						List[Any]=1_0_0_0       ,  )						->				Optional[Any]:
         """simple docstring"""



         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 			lowercase_      (self     :						Optional[int]		)						->				List[str]:
         """simple docstring"""



         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(__UpperCAmelCase		)

         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 			lowercase_      (self     :						int       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						Optional[Any]		)						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFLayoutLMvaModel(config=__UpperCAmelCase		)

         # text + image
         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  pixel_values=__UpperCAmelCase       ,  training=__UpperCAmelCase		)
         UpperCAmelCase__								=  model(
             __UpperCAmelCase       ,  bbox=__UpperCAmelCase       ,  pixel_values=__UpperCAmelCase       ,  attention_mask=__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  training=__UpperCAmelCase       ,  )
         UpperCAmelCase__								=  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
         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  training=__UpperCAmelCase		)
         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=__UpperCAmelCase		)
         self.parent.assertEqual(
             result.last_hidden_state.shape       ,  (self.batch_size, self.image_seq_length, self.hidden_size)		)


   def 			lowercase_      (self     :						List[Any]       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						Optional[int]       ,  __UpperCAmelCase     :						List[str]       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						List[Any]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  TFLayoutLMvaForSequenceClassification(config=__UpperCAmelCase		)
         UpperCAmelCase__								=  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 			lowercase_      (self     :						Optional[Any]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Union[str, Any]		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  TFLayoutLMvaForTokenClassification(config=__UpperCAmelCase		)
         UpperCAmelCase__								=  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 			lowercase_      (self     :						str       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Tuple       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						List[str]       ,  __UpperCAmelCase     :						Optional[int]       ,  __UpperCAmelCase     :						Optional[Any]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  2
         UpperCAmelCase__								=  TFLayoutLMvaForQuestionAnswering(config=__UpperCAmelCase		)
         UpperCAmelCase__								=  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 			lowercase_      (self     :						Tuple		)						->				str:
         """simple docstring"""



         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							(				UpperCAmelCase_		,				UpperCAmelCase_		,				unittest.TestCase     ):
   __UpperCAmelCase : Optional[Any]      =			(
       (
           TFLayoutLMvaModel,
           TFLayoutLMvaForQuestionAnswering,
           TFLayoutLMvaForSequenceClassification,
           TFLayoutLMvaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   __UpperCAmelCase : Tuple      =			(
       {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
       if is_tf_available()
       else {}
   )

   __UpperCAmelCase : Union[str, Any]      =			False
   __UpperCAmelCase : Optional[int]      =			False
   __UpperCAmelCase : int      =			False


   def 			lowercase_      (self     :						int       ,  __UpperCAmelCase     :						Any       ,  __UpperCAmelCase     :						Tuple       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						int		)						->				List[str]:
         """simple docstring"""



         return True


   def 			lowercase_      (self     :						str       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						List[str]=False		)						->				dict:
         """simple docstring"""



         UpperCAmelCase__								=  copy.deepcopy(__UpperCAmelCase		)

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

         return inputs_dict


   def 			lowercase_      (self     :						int		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  TFLayoutLMvaModelTester(self		)
         UpperCAmelCase__								=  ConfigTester(self       ,  config_class=__UpperCAmelCase       ,  hidden_size=3_7		)


   def 			lowercase_      (self     :						Tuple		)						->				Optional[int]:
         """simple docstring"""



         self.config_tester.run_common_tests()


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Dict:
         """simple docstring"""



         UpperCAmelCase__		,      UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs_for_common()
         for model_class in self.all_model_classes:
               UpperCAmelCase__								=  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
                     UpperCAmelCase__								=  self._prepare_for_class(inputs_dict.copy()       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)
                     UpperCAmelCase__								=  prepared_for_class[
                         sorted(prepared_for_class.keys() - inputs_dict.keys()       ,  reverse=__UpperCAmelCase		)[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()       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)
                     UpperCAmelCase__								=  prepared_for_class.pop("input_ids"		)

                     UpperCAmelCase__								=  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
                     UpperCAmelCase__								=  self._prepare_for_class(inputs_dict.copy()       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)
                     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_0_0
                                 UpperCAmelCase__								=  tf.convert_to_tensor(__UpperCAmelCase		)
                                 UpperCAmelCase__								=  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
                     UpperCAmelCase__								=  self._prepare_for_class(inputs_dict.copy()       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)
                     UpperCAmelCase__								=  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
                     UpperCAmelCase__								=  self._prepare_for_class(inputs_dict.copy()       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)

                     # 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(__UpperCAmelCase		)
                           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(__UpperCAmelCase		)

                     # 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 			lowercase_      (self     :						Optional[int]		)						->				Optional[Any]:
         """simple docstring"""



         (
             (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      
         )								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				str:
         """simple docstring"""



         (
             (
             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(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)


   def 			lowercase_      (self     :						Optional[int]		)						->				List[Any]:
         """simple docstring"""



         (
             (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      
         )								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_sequence_classification(
             __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)


   def 			lowercase_      (self     :						List[Any]		)						->				List[Any]:
         """simple docstring"""



         (
             (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      
         )								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_token_classification(
             __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)


   def 			lowercase_      (self     :						int		)						->				List[Any]:
         """simple docstring"""



         (
             (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      
         )								=  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 			lowercase_      (self     :						Any		)						->				str:
         """simple docstring"""



         for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__								=  TFLayoutLMvaModel.from_pretrained(__UpperCAmelCase		)
               self.assertIsNotNone(__UpperCAmelCase		)




def    lowerCAmelCase_ (     )     ->				int:







      '''simple docstring'''


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







@require_tf
class      A							(				unittest.TestCase     ):


   @cached_property
   def 			lowercase_      (self     :						int		)						->				int:
         """simple docstring"""



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





   @slow
   def 			lowercase_      (self     :						Tuple		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  TFLayoutLMvaModel.from_pretrained("microsoft/layoutlmv3-base"		)

         UpperCAmelCase__								=  self.default_image_processor
         UpperCAmelCase__								=  prepare_img()
         UpperCAmelCase__								=  image_processor(images=__UpperCAmelCase       ,  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=__UpperCAmelCase       ,  bbox=__UpperCAmelCase       ,  pixel_values=__UpperCAmelCase       ,  training=__UpperCAmelCase		)

         # verify the logits
         UpperCAmelCase__								=  (1, 1_9_9, 7_6_8)
         self.assertEqual(outputs.last_hidden_state.shape       ,  __UpperCAmelCase		)

         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]       ,  __UpperCAmelCase       ,  atol=1E-4		)		)




import warnings
from typing import Any, Dict, List, Optional, Union

import numpy as np

from ...audio_utils import mel_filter_bank, optimal_fft_length, spectrogram, window_function
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging


UpperCamelCase__											=					logging.get_logger(__name__)





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : int      =			['input_values', 'attention_mask']


   def __init__(self     :						Any       ,  __UpperCAmelCase     :						int = 1       ,  __UpperCAmelCase     :						int = 1_6_0_0_0       ,  __UpperCAmelCase     :						float = 0.0       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						int = 8_0       ,  __UpperCAmelCase     :						int = 1_6       ,  __UpperCAmelCase     :						int = 6_4       ,  __UpperCAmelCase     :						str = "hann_window"       ,  __UpperCAmelCase     :						float = 1.0       ,  __UpperCAmelCase     :						float = 8_0       ,  __UpperCAmelCase     :						float = 7_6_0_0       ,  __UpperCAmelCase     :						float = 1E-10       ,  __UpperCAmelCase     :						int = 2       ,  __UpperCAmelCase     :						bool = True       ,  **__UpperCAmelCase     :						Any       ,  )						->				str:
         """simple docstring"""



         super().__init__(feature_size=__UpperCAmelCase       ,  sampling_rate=__UpperCAmelCase       ,  padding_value=__UpperCAmelCase       ,  **__UpperCAmelCase		)
         UpperCAmelCase__								=  do_normalize
         UpperCAmelCase__								=  return_attention_mask

         UpperCAmelCase__								=  num_mel_bins
         UpperCAmelCase__								=  hop_length
         UpperCAmelCase__								=  win_length
         UpperCAmelCase__								=  win_function
         UpperCAmelCase__								=  frame_signal_scale
         UpperCAmelCase__								=  fmin
         UpperCAmelCase__								=  fmax
         UpperCAmelCase__								=  mel_floor
         UpperCAmelCase__								=  reduction_factor

         UpperCAmelCase__								=  win_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  hop_length * sampling_rate // 1_0_0_0
         UpperCAmelCase__								=  optimal_fft_length(self.sample_size		)
         UpperCAmelCase__								=  (self.n_fft // 2) + 1

         UpperCAmelCase__								=  window_function(window_length=self.sample_size       ,  name=self.win_function       ,  periodic=__UpperCAmelCase		)

         UpperCAmelCase__								=  mel_filter_bank(
             num_frequency_bins=self.n_freqs       ,  num_mel_filters=self.num_mel_bins       ,  min_frequency=self.fmin       ,  max_frequency=self.fmax       ,  sampling_rate=self.sampling_rate       ,  norm="slaney"       ,  mel_scale="slaney"       ,  )

         if frame_signal_scale != 1.0:
               warnings.warn(
                   "The argument `frame_signal_scale` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )
         if reduction_factor != 2.0:
               warnings.warn(
                   "The argument `reduction_factor` is deprecated and will be removed in version 4.30.0 of Transformers"       ,  __UpperCAmelCase       ,  )


   @staticmethod
   # Copied from transformers.models.wav2vec2.feature_extraction_wav2vec2.Wav2Vec2FeatureExtractor.zero_mean_unit_var_norm
   def 			lowercase_      (__UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						List[np.ndarray]       ,  __UpperCAmelCase     :						float = 0.0		)						->				List[np.ndarray]:
         """simple docstring"""



         if attention_mask is not None:
               UpperCAmelCase__								=  np.array(__UpperCAmelCase       ,  np.intaa		)
               UpperCAmelCase__								=  []

               for vector, length in zip(__UpperCAmelCase       ,  attention_mask.sum(-1		)		):
                     UpperCAmelCase__								=  (vector - vector[:length].mean()) / np.sqrt(vector[:length].var() + 1E-7		)
                     if length < normed_slice.shape[0]:
                           UpperCAmelCase__								=  padding_value

                     normed_input_values.append(__UpperCAmelCase		)
         else:
               UpperCAmelCase__								=  [(x - x.mean()) / np.sqrt(x.var() + 1E-7		) for x in input_values]

         return normed_input_values


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						np.ndarray       ,  )						->				np.ndarray:
         """simple docstring"""



         UpperCAmelCase__								=  spectrogram(
             __UpperCAmelCase       ,  window=self.window       ,  frame_length=self.sample_size       ,  hop_length=self.sample_stride       ,  fft_length=self.n_fft       ,  mel_filters=self.mel_filters       ,  mel_floor=self.mel_floor       ,  log_mel="log10"       ,  )
         return log_mel_spec.T


   def __call__(self     :						Any       ,  __UpperCAmelCase     :						Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None       ,  __UpperCAmelCase     :						Optional[Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]] = None       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  __UpperCAmelCase     :						Optional[int] = None       ,  **__UpperCAmelCase     :						str       ,  )						->				BatchFeature:
         """simple docstring"""



         if audio is None and audio_target is None:
               raise ValueError("You must provide either `audio` or `audio_target` values."		)

         if sampling_rate is not None:
               if sampling_rate != self.sampling_rate:
                     raise ValueError(
                         f"""The model corresponding to this feature extractor: {self} was trained using a sampling rate of"""
                         f""" {self.sampling_rate}. Please make sure that the provided audio input was sampled with"""
                         f""" {self.sampling_rate} and not {sampling_rate}."""		)
         else:
               logger.warning(
                   "It is strongly recommended to pass the ``sampling_rate`` argument to this function. "
                   "Failing to do so can result in silent errors that might be hard to debug."		)

         if audio is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )
         else:
               UpperCAmelCase__								=  None

         if audio_target is not None:
               UpperCAmelCase__								=  self._process_audio(
                   __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

               if inputs is None:
                     return inputs_target
               else:
                     UpperCAmelCase__								=  inputs_target["input_values"]
                     UpperCAmelCase__								=  inputs_target.get("attention_mask"		)
                     if decoder_attention_mask is not None:
                           UpperCAmelCase__								=  decoder_attention_mask

         return inputs


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]]       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Union[bool, str, PaddingStrategy] = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						bool = False       ,  __UpperCAmelCase     :						Optional[int] = None       ,  __UpperCAmelCase     :						Optional[bool] = None       ,  __UpperCAmelCase     :						Optional[Union[str, TensorType]] = None       ,  **__UpperCAmelCase     :						Any       ,  )						->				BatchFeature:
         """simple docstring"""



         UpperCAmelCase__								=  isinstance(__UpperCAmelCase       ,  np.ndarray		) and len(speech.shape		) > 1
         if is_batched_numpy and len(speech.shape		) > 2:
               raise ValueError(f"""Only mono-channel audio is supported for input to {self}"""		)
         UpperCAmelCase__								=  is_batched_numpy or (
             isinstance(__UpperCAmelCase       ,  (list, tuple)		) and (isinstance(speech[0]       ,  (np.ndarray, tuple, list)		))
         )

         if is_batched:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for speech in speech]
         elif not is_batched and not isinstance(__UpperCAmelCase       ,  np.ndarray		):
               UpperCAmelCase__								=  np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		)
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and speech.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  speech.astype(np.floataa		)

         # always return batch
         if not is_batched:
               UpperCAmelCase__								=  [speech]

         # needed to make pad() work on spectrogram inputs
         UpperCAmelCase__								=  self.feature_size

         # convert into correct format for padding
         if is_target:
               UpperCAmelCase__								=  [self._extract_mel_features(__UpperCAmelCase		) for waveform in speech]
               UpperCAmelCase__								=  BatchFeature({"input_values": features}		)
               UpperCAmelCase__								=  self.num_mel_bins
         else:
               UpperCAmelCase__								=  BatchFeature({"input_values": speech}		)

         UpperCAmelCase__								=  self.pad(
             __UpperCAmelCase       ,  padding=__UpperCAmelCase       ,  max_length=__UpperCAmelCase       ,  truncation=__UpperCAmelCase       ,  pad_to_multiple_of=__UpperCAmelCase       ,  return_attention_mask=__UpperCAmelCase       ,  **__UpperCAmelCase       ,  )

         UpperCAmelCase__								=  feature_size_hack

         # convert input values to correct format
         UpperCAmelCase__								=  padded_inputs["input_values"]
         if not isinstance(input_values[0]       ,  np.ndarray		):
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.floataa		) for array in input_values]
         elif (
             not isinstance(__UpperCAmelCase       ,  np.ndarray		)
             and isinstance(input_values[0]       ,  np.ndarray		)
             and input_values[0].dtype is np.dtype(np.floataa		)
         ):
               UpperCAmelCase__								=  [array.astype(np.floataa		) for array in input_values]
         elif isinstance(__UpperCAmelCase       ,  np.ndarray		) and input_values.dtype is np.dtype(np.floataa		):
               UpperCAmelCase__								=  input_values.astype(np.floataa		)

         # convert attention_mask to correct format
         UpperCAmelCase__								=  padded_inputs.get("attention_mask"		)
         if attention_mask is not None:
               UpperCAmelCase__								=  [np.asarray(__UpperCAmelCase       ,  dtype=np.intaa		) for array in attention_mask]

         # zero-mean and unit-variance normalization
         if not is_target and self.do_normalize:
               UpperCAmelCase__								=  (
                   attention_mask
                   if self._get_padding_strategies(__UpperCAmelCase       ,  max_length=__UpperCAmelCase		) is not PaddingStrategy.DO_NOT_PAD
                   else None
               )
               UpperCAmelCase__								=  self.zero_mean_unit_var_norm(
                   padded_inputs["input_values"]       ,  attention_mask=__UpperCAmelCase       ,  padding_value=self.padding_value		)

         if return_tensors is not None:
               UpperCAmelCase__								=  padded_inputs.convert_to_tensors(__UpperCAmelCase		)

         return padded_inputs





   def 			lowercase_      (self     :						Tuple		)						->				Dict[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super().to_dict()

         # Don't serialize these as they are derived from the other properties.
         UpperCAmelCase__								=  ["window", "mel_filters", "sample_size", "sample_stride", "n_fft", "n_freqs"]
         for name in names:
               if name in output:
                     del output[name]

         return output



