






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  _lowercase   :
      def __init__(     self				,			a				,			a=2				,			a=3				,			a=4				,			a=2				,			a=7				,			a=True				,			a=True				,			a=True				,			a=True				,			a=9_9				,			a=3_6				,			a=2				,			a=4				,			a=3_7				,			a="gelu"				,			a=0.1				,			a=0.1				,			a=5_1_2				,			a=1_6				,			a=2				,			a=0.02				,			a=6				,			a=6				,			a=3				,			a=4				,			a=None				,			a=1_0_0_0				,			):
       snake_case__  :    List[Any]							       =parent
       snake_case__  :    Tuple							       =batch_size
       snake_case__  :    Tuple							       =num_channels
       snake_case__  :    List[Any]							       =image_size
       snake_case__  :    List[str]							       =patch_size
       snake_case__  :    Dict							       =is_training
       snake_case__  :    int							       =use_input_mask
       snake_case__  :    Tuple							       =use_token_type_ids
       snake_case__  :    Tuple							       =use_labels
       snake_case__  :    int							       =vocab_size
       snake_case__  :    int							       =hidden_size
       snake_case__  :    str							       =num_hidden_layers
       snake_case__  :    Optional[Any]							       =num_attention_heads
       snake_case__  :    Dict							       =intermediate_size
       snake_case__  :    Dict							       =hidden_act
       snake_case__  :    Optional[Any]							       =hidden_dropout_prob
       snake_case__  :    Dict							       =attention_probs_dropout_prob
       snake_case__  :    Union[str, Any]							       =max_position_embeddings
       snake_case__  :    Union[str, Any]							       =type_vocab_size
       snake_case__  :    Optional[Any]							       =type_sequence_label_size
       snake_case__  :    str							       =initializer_range
       snake_case__  :    Union[str, Any]							       =coordinate_size
       snake_case__  :    Any							       =shape_size
       snake_case__  :    str							       =num_labels
       snake_case__  :    Optional[int]							       =num_choices
       snake_case__  :    Optional[Any]							       =scope
       snake_case__  :    int							       =range_bbox

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

       snake_case__  :    int							       =ids_tensor([self.batch_size, self.text_seq_length, 4]				,			self.range_bbox   )
       snake_case__  :    str							       =bbox.numpy()
       # Ensure that bbox is legal
       for i in range(bbox.shape[0]   ):
        for j in range(bbox.shape[1]   ):
         if bbox[i, j, 3] < bbox[i, j, 1]:
          snake_case__  :    Tuple							       =bbox[i, j, 3]
          snake_case__  :    int							       =bbox[i, j, 1]
          snake_case__  :    Optional[int]							       =tmp_coordinate
         if bbox[i, j, 2] < bbox[i, j, 0]:
          snake_case__  :    str							       =bbox[i, j, 2]
          snake_case__  :    List[Any]							       =bbox[i, j, 0]
          snake_case__  :    str							       =tmp_coordinate
       snake_case__  :    str							       =tf.constant(_lowercase   )

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

       snake_case__  :    Optional[Any]							       =None
       if self.use_input_mask:
        snake_case__  :    Union[str, Any]							       =random_attention_mask([self.batch_size, self.text_seq_length]   )

       snake_case__  :    str							       =None
       if self.use_token_type_ids:
        snake_case__  :    Optional[int]							       =ids_tensor([self.batch_size, self.text_seq_length]				,			self.type_vocab_size   )

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

       snake_case__  :    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 						lowercase__					(     self				,			a				,			a				,			a				,			a				,			a				,			a   ):
       snake_case__  :    Optional[Any]							       =TFLayoutLMvaModel(config=_lowercase   )

       # text + image
       snake_case__  :    List[Any]							       =model(_lowercase				,			pixel_values=_lowercase				,			training=_lowercase   )
       snake_case__  :    List[str]							       =model(
           _lowercase				,			bbox=_lowercase				,			pixel_values=_lowercase				,			attention_mask=_lowercase				,			token_type_ids=_lowercase				,			training=_lowercase				,			)
       snake_case__  :    Dict							       =model(_lowercase				,			bbox=_lowercase				,			pixel_values=_lowercase				,			training=_lowercase   )

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

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

       # image only
       snake_case__  :    Union[str, Any]							       =model({"""pixel_values""": pixel_values}				,			training=_lowercase   )
       self.parent.assertEqual(
           result.last_hidden_state.shape				,			(self.batch_size, self.image_seq_length, self.hidden_size)   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a				,			a				,			a				,			a   ):
       snake_case__  :    List[str]							       =self.num_labels
       snake_case__  :    Any							       =TFLayoutLMvaForSequenceClassification(config=_lowercase   )
       snake_case__  :    Union[str, Any]							       =model(
           _lowercase				,			bbox=_lowercase				,			pixel_values=_lowercase				,			attention_mask=_lowercase				,			token_type_ids=_lowercase				,			labels=_lowercase				,			training=_lowercase				,			)
       self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.num_labels)   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a				,			a				,			a				,			a   ):
       snake_case__  :    int							       =self.num_labels
       snake_case__  :    Tuple							       =TFLayoutLMvaForTokenClassification(config=_lowercase   )
       snake_case__  :    Optional[int]							       =model(
           _lowercase				,			bbox=_lowercase				,			pixel_values=_lowercase				,			attention_mask=_lowercase				,			token_type_ids=_lowercase				,			labels=_lowercase				,			training=_lowercase				,			)
       self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.text_seq_length, self.num_labels)   )
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a				,			a				,			a				,			a   ):
       snake_case__  :    str							       =2
       snake_case__  :    str							       =TFLayoutLMvaForQuestionAnswering(config=_lowercase   )
       snake_case__  :    List[Any]							       =model(
           _lowercase				,			bbox=_lowercase				,			pixel_values=_lowercase				,			attention_mask=_lowercase				,			token_type_ids=_lowercase				,			start_positions=_lowercase				,			end_positions=_lowercase				,			training=_lowercase				,			)
       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   ):
       snake_case__  :    List[Any]							       =self.prepare_config_and_inputs()
       ((snake_case__)       ,   (snake_case__)       ,   (snake_case__)       ,   (snake_case__)       ,   (snake_case__)       ,   (snake_case__)       ,   (snake_case__)       ,   (snake_case__))  :    List[Any]							       =config_and_inputs
       snake_case__  :    Optional[int]							       ={
           """input_ids""": input_ids,
           """bbox""": bbox,
           """pixel_values""": pixel_values,
           """token_type_ids""": token_type_ids,
           """attention_mask""": input_mask,
       }
       return config, inputs_dict







@require_tf
class  _lowercase   (   UpperCAmelCase_						,				UpperCAmelCase_						,				unittest.TestCase						):
      _a							:						Tuple										=							(
          (
              TFLayoutLMvaModel,
              TFLayoutLMvaForQuestionAnswering,
              TFLayoutLMvaForSequenceClassification,
              TFLayoutLMvaForTokenClassification,
          )
          if is_tf_available()
          else ()
      )
      _a							:						Tuple										=							(
          {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
          if is_tf_available()
          else {}
      )

      _a							:						int										=							False
      _a							:						str										=							False
      _a							:						int										=							False
      def 						lowercase__					(     self				,			a				,			a				,			a				,			a				,			a   ):
       return True
      def 						lowercase__					(     self				,			a				,			a				,			a=False   ):
       snake_case__  :    Dict							       =copy.deepcopy(_lowercase   )

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

       if return_labels:
        if model_class in get_values(_lowercase   ):
         snake_case__  :    int							       =tf.ones(self.model_tester.batch_size				,			dtype=tf.intaa   )
        elif model_class in get_values(_lowercase   ):
         snake_case__  :    str							       =tf.zeros(self.model_tester.batch_size				,			dtype=tf.intaa   )
         snake_case__  :    int							       =tf.zeros(self.model_tester.batch_size				,			dtype=tf.intaa   )
        elif model_class in get_values(_lowercase   ):
         snake_case__  :    Any							       =tf.zeros(self.model_tester.batch_size				,			dtype=tf.intaa   )
        elif model_class in get_values(_lowercase   ):
         snake_case__  :    Union[str, Any]							       =tf.zeros(
             (self.model_tester.batch_size, self.model_tester.text_seq_length)				,			dtype=tf.intaa   )

       return inputs_dict
      def 						lowercase__					(     self   ):
       snake_case__  :    Any							       =TFLayoutLMvaModelTester(self   )
       snake_case__  :    str							       =ConfigTester(self				,			config_class=_lowercase				,			hidden_size=3_7   )
      def 						lowercase__					(     self   ):
       self.config_tester.run_common_tests()
      def 						lowercase__					(     self   ):
       snake_case__       ,   snake_case__  :    Tuple							       =self.model_tester.prepare_config_and_inputs_for_common()
       for model_class in self.all_model_classes:
        snake_case__  :    Optional[Any]							       =model_class(_lowercase   )
        if getattr(_lowercase				,			"""hf_compute_loss"""				,			_lowercase   ):
         # The number of elements in the loss should be the same as the number of elements in the label
         snake_case__  :    List[Any]							       =self._prepare_for_class(inputs_dict.copy()				,			_lowercase				,			return_labels=_lowercase   )
         snake_case__  :    List[str]							       =prepared_for_class[
             sorted(prepared_for_class.keys() - inputs_dict.keys()				,			reverse=_lowercase   )[0]
         ]
         snake_case__  :    Union[str, Any]							       =added_label.shape.as_list()[:1]

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

         snake_case__  :    Optional[Any]							       =model(_lowercase				,			**_lowercase   )[0]
         self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

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

                # Test that model correctly compute the loss with a dict
         snake_case__  :    Optional[int]							       =self._prepare_for_class(inputs_dict.copy()				,			_lowercase				,			return_labels=_lowercase   )
         snake_case__  :    str							       =model(_lowercase   )[0]
         self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )

         # Test that model correctly compute the loss with a tuple
         snake_case__  :    str							       =self._prepare_for_class(inputs_dict.copy()				,			_lowercase				,			return_labels=_lowercase   )

         # Get keys that were added with the _prepare_for_class function
         snake_case__  :    Any							       =prepared_for_class.keys() - inputs_dict.keys()
         snake_case__  :    Tuple							       =inspect.signature(model.call   ).parameters
         snake_case__  :    List[Any]							       =list(signature.keys()   )

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

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

         for index, value in sorted_tuple_index_mapping:
          snake_case__  :    List[str]							       =prepared_for_class[value]

         snake_case__  :    Dict							       =tuple(_lowercase   )

         # Send to model
         snake_case__  :    Optional[int]							       =model(tuple_input[:-1]   )[0]

         self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]   )
      def 						lowercase__					(     self   ):
       (
           (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,    
       )  :    Union[str, Any]							       =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase   )
      def 						lowercase__					(     self   ):
       (
           (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,    
       )  :    Optional[Any]							       =self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
        snake_case__  :    Union[str, Any]							       =type
        self.model_tester.create_and_check_model(_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase   )
      def 						lowercase__					(     self   ):
       (
           (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,    
       )  :    Any							       =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(
           _lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase   )
      def 						lowercase__					(     self   ):
       (
           (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,    
       )  :    int							       =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(
           _lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase   )
      def 						lowercase__					(     self   ):
       (
           (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,   (
           snake_case__ 
       )       ,    
       )  :    str							       =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(
           _lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase				,			_lowercase   )



      @slow
      def 						lowercase__					(     self   ):
       for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        snake_case__  :    List[str]							       =TFLayoutLMvaModel.from_pretrained(_lowercase   )
        self.assertIsNotNone(_lowercase   )







def 			A__							(      ):





 '''simple docstring'''







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







@require_tf
class  _lowercase   (   unittest.TestCase						):
      @cached_property
      def 						lowercase__					(     self   ):
       return LayoutLMvaImageProcessor(apply_ocr=_lowercase   ) if is_vision_available() else None



      @slow
      def 						lowercase__					(     self   ):
       snake_case__  :    Tuple							       =TFLayoutLMvaModel.from_pretrained("""microsoft/layoutlmv3-base"""   )

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

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

       # forward pass
       snake_case__  :    Any							       =model(input_ids=_lowercase				,			bbox=_lowercase				,			pixel_values=_lowercase				,			training=_lowercase   )

       # verify the logits
       snake_case__  :    str							       =(1, 1_9_9, 7_6_8)
       self.assertEqual(outputs.last_hidden_state.shape				,			_lowercase   )

       snake_case__  :    Optional[int]							       =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]				,			_lowercase				,			atol=1e-4   )   )













def 			A__							(      _a  :					list	):





 '''simple docstring'''







 if len(_a	) <= 1:
  return [tuple(_a	)]

 snake_case__  :    Optional[int]							       =[]

 def generate(_a  :					int		,  _a  :					list	):
  if k == 1:
   res.append(tuple(arr[:]	)	)
   return

  generate(k - 1		,  _a	)

  for i in range(k - 1	):
   if k % 2 == 0:  # k is even
    snake_case__       ,   snake_case__  :    Dict							       =arr[k - 1], arr[i]
   else:  # k is odd
    snake_case__       ,   snake_case__  :    int							       =arr[k - 1], arr[0]
   generate(k - 1		,  _a	)

 generate(len(_a	)		,  _a	)
 return res


if __name__ == "__main__":
       __lowerCamelCase	:		Optional[int]										=   input("""Enter numbers separated by a comma:\n""").strip()
       __lowerCamelCase	:		Any										=   [int(item) for item in user_input.split(""",""")]
       print(heaps(arr))





