



'''simple docstring'''





from __future__ import annotations

import copy
import inspect
import unittest

import numpy as np

from transformers import is_tf_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers import (
     TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
     TF_MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
     TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
     TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
     TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
     LayoutLMvaConfig,
     TFLayoutLMvaForQuestionAnswering,
     TFLayoutLMvaForSequenceClassification,
     TFLayoutLMvaForTokenClassification,
     TFLayoutLMvaModel,
 )

if is_vision_available():
 from PIL import Image

 from transformers import LayoutLMvaImageProcessor






class 	lowerCAmelCase_:
  '''simple docstring'''




  def __init__(   self  ,__UpperCAmelCase  ,__UpperCAmelCase=2  ,__UpperCAmelCase=3  ,__UpperCAmelCase=4  ,__UpperCAmelCase=2  ,__UpperCAmelCase=7  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=True  ,__UpperCAmelCase=99  ,__UpperCAmelCase=36  ,__UpperCAmelCase=2  ,__UpperCAmelCase=4  ,__UpperCAmelCase=37  ,__UpperCAmelCase="gelu"  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=0.1  ,__UpperCAmelCase=512  ,__UpperCAmelCase=16  ,__UpperCAmelCase=2  ,__UpperCAmelCase=0.0_2  ,__UpperCAmelCase=6  ,__UpperCAmelCase=6  ,__UpperCAmelCase=3  ,__UpperCAmelCase=4  ,__UpperCAmelCase=None  ,__UpperCAmelCase=1000  ,)   ->		str:
      lowerCAmelCase__			:  Optional[int]											= parent
      lowerCAmelCase__			:  List[str]											= batch_size
      lowerCAmelCase__			:  Optional[Any]											= num_channels
      lowerCAmelCase__			:  str											= image_size
      lowerCAmelCase__			:  Dict											= patch_size
      lowerCAmelCase__			:  int											= is_training
      lowerCAmelCase__			:  List[str]											= use_input_mask
      lowerCAmelCase__			:  str											= use_token_type_ids
      lowerCAmelCase__			:  int											= use_labels
      lowerCAmelCase__			:  List[str]											= vocab_size
      lowerCAmelCase__			:  List[Any]											= hidden_size
      lowerCAmelCase__			:  str											= num_hidden_layers
      lowerCAmelCase__			:  Union[str, Any]											= num_attention_heads
      lowerCAmelCase__			:  Optional[Any]											= intermediate_size
      lowerCAmelCase__			:  List[str]											= hidden_act
      lowerCAmelCase__			:  List[str]											= hidden_dropout_prob
      lowerCAmelCase__			:  Dict											= attention_probs_dropout_prob
      lowerCAmelCase__			:  Optional[int]											= max_position_embeddings
      lowerCAmelCase__			:  Union[str, Any]											= type_vocab_size
      lowerCAmelCase__			:  Optional[Any]											= type_sequence_label_size
      lowerCAmelCase__			:  str											= initializer_range
      lowerCAmelCase__			:  int											= coordinate_size
      lowerCAmelCase__			:  List[str]											= shape_size
      lowerCAmelCase__			:  Optional[Any]											= num_labels
      lowerCAmelCase__			:  List[str]											= num_choices
      lowerCAmelCase__			:  Optional[int]											= scope
      lowerCAmelCase__			:  Dict											= range_bbox

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




  def 							UpperCAmelCase_     (   self				)   ->		Optional[int]:
      lowerCAmelCase__			:  Union[str, Any]											= ids_tensor([self.batch_size, self.text_seq_length]  ,self.vocab_size				)

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

      lowerCAmelCase__			:  List[str]											= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

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

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

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

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

      # text + image
      lowerCAmelCase__			:  str											= model(__UpperCAmelCase  ,pixel_values=__UpperCAmelCase  ,training=__UpperCAmelCase				)
      lowerCAmelCase__			:  List[str]											= model(
          __UpperCAmelCase  ,bbox=__UpperCAmelCase  ,pixel_values=__UpperCAmelCase  ,attention_mask=__UpperCAmelCase  ,token_type_ids=__UpperCAmelCase  ,training=__UpperCAmelCase  ,)
      lowerCAmelCase__			:  List[Any]											= 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
      lowerCAmelCase__			:  int											= model(__UpperCAmelCase  ,training=__UpperCAmelCase				)
      self.parent.assertEqual(
          result.last_hidden_state.shape  ,(self.batch_size, self.text_seq_length, self.hidden_size)				)

      # image only
      lowerCAmelCase__			:  Tuple											= 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 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Dict:
      lowerCAmelCase__			:  Dict											= self.num_labels
      lowerCAmelCase__			:  Tuple											= TFLayoutLMvaForSequenceClassification(config=__UpperCAmelCase				)
      lowerCAmelCase__			:  Optional[int]											= 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 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		List[Any]:
      lowerCAmelCase__			:  Any											= self.num_labels
      lowerCAmelCase__			:  Any											= TFLayoutLMvaForTokenClassification(config=__UpperCAmelCase				)
      lowerCAmelCase__			:  str											= 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 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Optional[Any]:
      lowerCAmelCase__			:  Union[str, Any]											= 2
      lowerCAmelCase__			:  int											= TFLayoutLMvaForQuestionAnswering(config=__UpperCAmelCase				)
      lowerCAmelCase__			:  Dict											= 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 							UpperCAmelCase_     (   self				)   ->		List[str]:
      lowerCAmelCase__			:  Union[str, Any]											= self.prepare_config_and_inputs()
      ((lowerCAmelCase__)				,       (lowerCAmelCase__)				,       (lowerCAmelCase__)				,       (lowerCAmelCase__)				,       (lowerCAmelCase__)				,       (lowerCAmelCase__)				,       (lowerCAmelCase__)				,       (lowerCAmelCase__))			:  str											= config_and_inputs
      lowerCAmelCase__			:  List[str]											= {
          """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 	lowerCAmelCase_(    SCREAMING_SNAKE_CASE_						,			SCREAMING_SNAKE_CASE_						,			unittest.TestCase					):
  '''simple docstring'''




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

  __lowercase							:				Optional[Any]           =				False
  __lowercase							:				Union[str, Any]           =				False
  __lowercase							:				Dict           =				False




  def 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)   ->		Any:
      return True




  def 							UpperCAmelCase_     (   self  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase=False				)   ->		dict:
      lowerCAmelCase__			:  str											= copy.deepcopy(__UpperCAmelCase				)

      if model_class in get_values(__UpperCAmelCase				):
          lowerCAmelCase__			:  List[Any]											= {
              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				):
              lowerCAmelCase__			:  str											= tf.ones(self.model_tester.batch_size  ,dtype=tf.intaa				)
          elif model_class in get_values(__UpperCAmelCase				):
              lowerCAmelCase__			:  Union[str, Any]											= tf.zeros(self.model_tester.batch_size  ,dtype=tf.intaa				)
              lowerCAmelCase__			:  Tuple											= tf.zeros(self.model_tester.batch_size  ,dtype=tf.intaa				)
          elif model_class in get_values(__UpperCAmelCase				):
              lowerCAmelCase__			:  Dict											= tf.zeros(self.model_tester.batch_size  ,dtype=tf.intaa				)
          elif model_class in get_values(__UpperCAmelCase				):
              lowerCAmelCase__			:  List[Any]											= tf.zeros(
                  (self.model_tester.batch_size, self.model_tester.text_seq_length)  ,dtype=tf.intaa				)

      return inputs_dict




  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      lowerCAmelCase__			:  Any											= TFLayoutLMvaModelTester(self				)
      lowerCAmelCase__			:  Dict											= ConfigTester(self  ,config_class=__UpperCAmelCase  ,hidden_size=37				)




  def 							UpperCAmelCase_     (   self				)   ->		List[str]:
      self.config_tester.run_common_tests()




  def 							UpperCAmelCase_     (   self				)   ->		int:
      lowerCAmelCase__				,       lowerCAmelCase__			:  str											= self.model_tester.prepare_config_and_inputs_for_common()
      for model_class in self.all_model_classes:
          lowerCAmelCase__			:  Dict											= 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
              lowerCAmelCase__			:  Dict											= self._prepare_for_class(inputs_dict.copy()  ,__UpperCAmelCase  ,return_labels=__UpperCAmelCase				)
              lowerCAmelCase__			:  Dict											= prepared_for_class[
                  sorted(prepared_for_class.keys() - inputs_dict.keys()  ,reverse=__UpperCAmelCase				)[0]
              ]
              lowerCAmelCase__			:  Tuple											= added_label.shape.as_list()[:1]

              # Test that model correctly compute the loss with kwargs
              lowerCAmelCase__			:  str											= self._prepare_for_class(inputs_dict.copy()  ,__UpperCAmelCase  ,return_labels=__UpperCAmelCase				)
              lowerCAmelCase__			:  Any											= prepared_for_class.pop("""input_ids"""				)

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

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

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

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

              for index, value in sorted_tuple_index_mapping:
                  lowerCAmelCase__			:  Any											= prepared_for_class[value]

              lowerCAmelCase__			:  Optional[Any]											= tuple(__UpperCAmelCase				)

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

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




  def 							UpperCAmelCase_     (   self				)   ->		Union[str, Any]:
      (
          (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       
      )			:  List[Any]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		Optional[int]:
      (
          (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       
      )			:  Dict											= self.model_tester.prepare_config_and_inputs()
      for type in ["absolute", "relative_key", "relative_key_query"]:
          lowerCAmelCase__			:  int											= type
          self.model_tester.create_and_check_model(__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		Any:
      (
          (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       
      )			:  Union[str, Any]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(
          __UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      (
          (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       
      )			:  Union[str, Any]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(
          __UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)




  def 							UpperCAmelCase_     (   self				)   ->		Optional[Any]:
      (
          (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       (
          lowerCAmelCase__
      )				,       
      )			:  Union[str, Any]											= self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(
          __UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase  ,__UpperCAmelCase				)






  @slow
  def 							UpperCAmelCase_     (   self				)   ->		List[Any]:
      for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
          lowerCAmelCase__			:  List[str]											= TFLayoutLMvaModel.from_pretrained(__UpperCAmelCase				)
          self.assertIsNotNone(__UpperCAmelCase				)







def        _SCREAMING_SNAKE_CASE  (	):



    """simple docstring"""





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






@require_tf
class 	lowerCAmelCase_(    unittest.TestCase					):
  '''simple docstring'''




  @cached_property
  def 							UpperCAmelCase_     (   self				)   ->		Dict:
      return LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase				) if is_vision_available() else None






  @slow
  def 							UpperCAmelCase_     (   self				)   ->		Any:
      lowerCAmelCase__			:  Dict											= TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""				)

      lowerCAmelCase__			:  str											= self.default_image_processor
      lowerCAmelCase__			:  Union[str, Any]											= prepare_img()
      lowerCAmelCase__			:  List[Any]											= image_processor(images=__UpperCAmelCase  ,return_tensors="""tf"""				).pixel_values

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

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

      # verify the logits
      lowerCAmelCase__			:  List[str]											= (1, 199, 768)
      self.assertEqual(outputs.last_hidden_state.shape  ,__UpperCAmelCase				)

      lowerCAmelCase__			:  List[Any]											= tf.constant(
          [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]				)

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







'''simple docstring'''





def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase							,   UpperCamelCase      ):



    """simple docstring"""





    def count_of_possible_combinations(UpperCamelCase      ) -> int:
        if target < 0:
            return 0
        if target == 0:
            return 1
        return sum(count_of_possible_combinations(target - item      ) for item in array      )

    return count_of_possible_combinations(UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase							,   UpperCamelCase      ):



    """simple docstring"""





    def count_of_possible_combinations_with_dp_array(
        UpperCamelCase							,   UpperCamelCase      ) -> int:
        if target < 0:
            return 0
        if target == 0:
            return 1
        if dp_array[target] != -1:
            return dp_array[target]
        lowerCAmelCase__			:  Any											= sum(
            count_of_possible_combinations_with_dp_array(target - item							,   UpperCamelCase      )
            for item in array      )
        lowerCAmelCase__			:  Tuple											= answer
        return answer

    lowerCAmelCase__			:  Optional[int]											= [-1] * (target + 1)
    return count_of_possible_combinations_with_dp_array(UpperCamelCase							,   UpperCamelCase      )
def        _SCREAMING_SNAKE_CASE  (	UpperCamelCase							,   UpperCamelCase							,   UpperCamelCase      ):



    """simple docstring"""





    lowerCAmelCase__			:  str											= [0] * (target + 1)
    lowerCAmelCase__			:  List[Any]											= 1

    for i in range(1							,   target + 1      ):
        for j in range(UpperCamelCase      ):
            if i - array[j] >= 0:
                dp_array[i] += dp_array[i - array[j]]

    return dp_array[target]


if __name__ == "__main__":
 import doctest

 doctest.testmod()
 _lowerCAmelCase										=     3
 _lowerCAmelCase										=     5
 _lowerCAmelCase										=     [1, 2, 5]
 print(combination_sum_iv(n, array, target))


