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



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



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



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



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



         UpperCAmelCase__								=  self.prepare_config_and_inputs()
         (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			:			Tuple              =      (
       (
           TFLayoutLMvaModel,
           TFLayoutLMvaForQuestionAnswering,
           TFLayoutLMvaForSequenceClassification,
           TFLayoutLMvaForTokenClassification,
       )
       if is_tf_available()
       else ()
   )
   __UpperCAmelCase			:			Dict              =      (
       {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
       if is_tf_available()
       else {}
   )

   __UpperCAmelCase			:			Tuple              =      False
   __UpperCAmelCase			:			str              =      False
   __UpperCAmelCase			:			Union[str, Any]              =      False


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



         return True


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



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



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


   def       lowercase_				(self					:						Dict		)						->    str:
         """simple docstring"""



         self.config_tester.run_common_tests()


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



         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_0_0
                                 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       lowercase_				(self					:						Union[str, Any]		)						->    Any:
         """simple docstring"""



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



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



         (
             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       lowercase_				(self					:						Dict		)						->    str:
         """simple docstring"""



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



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



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




def        lowerCAmelCase_			(					)					->    Optional[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		)						->    Any:
         """simple docstring"""



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





   @slow
   def       lowercase_				(self					:						List[str]		)						->    Dict:
         """simple docstring"""



         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_9_9, 7_6_8)
         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		)		)




import os
import zipfile

import pytest

from datasets.utils.extract import (
    BzipaExtractor,
    Extractor,
    GzipExtractor,
    LzaExtractor,
    SevenZipExtractor,
    TarExtractor,
    XzExtractor,
    ZipExtractor,
    ZstdExtractor,
)

from .utils import require_lza, require_pyazr, require_zstandard




@pytest.mark.parametrize(
    "compression_format, is_archive",  [
        ("7z", True),
        ("bz2", False),
        ("gzip", False),
        ("lz4", False),
        ("tar", True),
        ("xz", False),
        ("zip", True),
        ("zstd", False),
    ],  )
def        lowerCAmelCase_			(					__A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  )					->    Any:







      '''simple docstring'''


      UpperCAmelCase__								=  {
          "7z": (seven_zip_file, SevenZipExtractor),
          "bz2": (bza_file, BzipaExtractor),
          "gzip": (gz_file, GzipExtractor),
          "lz4": (lza_file, LzaExtractor),
          "tar": (tar_file, TarExtractor),
          "xz": (xz_file, XzExtractor),
          "zip": (zip_file, ZipExtractor),
          "zstd": (zstd_file, ZstdExtractor),
      }
      UpperCAmelCase__		,				UpperCAmelCase__								=  input_paths_and_base_extractors[compression_format]
      if input_path is None:
            UpperCAmelCase__								=  f"""for '{compression_format}' compression_format, """
            if compression_format == "7z":
                  reason += require_pyazr.kwargs["reason"]
            elif compression_format == "lz4":
                  reason += require_lza.kwargs["reason"]
            elif compression_format == "zstd":
                  reason += require_zstandard.kwargs["reason"]
            pytest.skip(__A							)
      assert base_extractor.is_extractable(__A							)
      UpperCAmelCase__								=  tmp_path / ("extracted" if is_archive else "extracted.txt")
      base_extractor.extract(__A,  __A							)
      if is_archive:
            assert output_path.is_dir()
            for file_path in output_path.iterdir():
                  assert file_path.name == text_file.name
                  UpperCAmelCase__								=  file_path.read_text(encoding="utf-8"							)
      else:
            UpperCAmelCase__								=  output_path.read_text(encoding="utf-8"							)
      UpperCAmelCase__								=  text_file.read_text(encoding="utf-8"							)
      assert extracted_file_content == expected_file_content




@pytest.mark.parametrize(
    "compression_format, is_archive",  [
        ("7z", True),
        ("bz2", False),
        ("gzip", False),
        ("lz4", False),
        ("tar", True),
        ("xz", False),
        ("zip", True),
        ("zstd", False),
    ],  )
def        lowerCAmelCase_			(					__A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  __A,  )					->    List[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  {
          "7z": seven_zip_file,
          "bz2": bza_file,
          "gzip": gz_file,
          "lz4": lza_file,
          "tar": tar_file,
          "xz": xz_file,
          "zip": zip_file,
          "zstd": zstd_file,
      }
      UpperCAmelCase__								=  input_paths[compression_format]
      if input_path is None:
            UpperCAmelCase__								=  f"""for '{compression_format}' compression_format, """
            if compression_format == "7z":
                  reason += require_pyazr.kwargs["reason"]
            elif compression_format == "lz4":
                  reason += require_lza.kwargs["reason"]
            elif compression_format == "zstd":
                  reason += require_zstandard.kwargs["reason"]
            pytest.skip(__A							)
      UpperCAmelCase__								=  Extractor.infer_extractor_format(__A							)
      assert extractor_format is not None
      UpperCAmelCase__								=  tmp_path / ("extracted" if is_archive else "extracted.txt")
      Extractor.extract(__A,  __A,  __A							)
      if is_archive:
            assert output_path.is_dir()
            for file_path in output_path.iterdir():
                  assert file_path.name == text_file.name
                  UpperCAmelCase__								=  file_path.read_text(encoding="utf-8"							)
      else:
            UpperCAmelCase__								=  output_path.read_text(encoding="utf-8"							)
      UpperCAmelCase__								=  text_file.read_text(encoding="utf-8"							)
      assert extracted_file_content == expected_file_content




@pytest.fixture
def        lowerCAmelCase_			(					__A,  __A							)					->    List[str]:







      '''simple docstring'''


      import tarfile

      UpperCAmelCase__								=  tmp_path / "data_dot_dot"
      directory.mkdir()
      UpperCAmelCase__								=  directory / "tar_file_with_dot_dot.tar"
      with tarfile.TarFile(__A,  "w"							) as f:
            f.add(__A,  arcname=os.path.join("..",  text_file.name							)							)
      return path




@pytest.fixture
def        lowerCAmelCase_			(					__A							)					->    Dict:







      '''simple docstring'''


      import tarfile

      UpperCAmelCase__								=  tmp_path / "data_sym_link"
      directory.mkdir()
      UpperCAmelCase__								=  directory / "tar_file_with_sym_link.tar"
      os.symlink("..",  directory / "subdir",  target_is_directory=__A							)
      with tarfile.TarFile(__A,  "w"							) as f:
            f.add(str(directory / "subdir"							),  arcname="subdir"							)  # str required by os.readlink on Windows and Python < 3.8
      return path




@pytest.mark.parametrize(
    "insecure_tar_file, error_log",  [("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")],  )
def        lowerCAmelCase_			(					__A,  __A,  __A,  __A,  __A,  __A							)					->    Dict:







      '''simple docstring'''


      UpperCAmelCase__								=  {
          "tar_file_with_dot_dot": tar_file_with_dot_dot,
          "tar_file_with_sym_link": tar_file_with_sym_link,
      }
      UpperCAmelCase__								=  insecure_tar_files[insecure_tar_file]
      UpperCAmelCase__								=  tmp_path / "extracted"
      TarExtractor.extract(__A,  __A							)
      assert caplog.text
      for record in caplog.records:
            assert record.levelname == "ERROR"
            assert error_log in record.msg







def        lowerCAmelCase_			(					__A							)					->    Any:







      '''simple docstring'''


      UpperCAmelCase__								=  tmpdir / "not_a_zip_file"
      # From: https://github.com/python/cpython/pull/5053
      UpperCAmelCase__								=  (
          B"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"
          B"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I"
          B"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07"
          B"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82"
      )
      with not_a_zip_file.open("wb"							) as f:
            f.write(__A							)
      assert zipfile.is_zipfile(str(__A							)							)  # is a false positive for `zipfile`
      assert not ZipExtractor.is_extractable(__A							)  # but we're right



