


'''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 						UpperCamelCase__       :



     """simple docstring"""






     def __init__(			self   ,						snake_case__   ,						snake_case__=2   ,						snake_case__=3   ,						snake_case__=4   ,						snake_case__=2   ,						snake_case__=7   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=True   ,						snake_case__=99   ,						snake_case__=36   ,						snake_case__=2   ,						snake_case__=4   ,						snake_case__=37   ,						snake_case__="gelu"   ,						snake_case__=0.1   ,						snake_case__=0.1   ,						snake_case__=512   ,						snake_case__=16   ,						snake_case__=2   ,						snake_case__=0.02   ,						snake_case__=6   ,						snake_case__=6   ,						snake_case__=3   ,						snake_case__=4   ,						snake_case__=None   ,						snake_case__=1000   ,						):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							parent
            _lowerCAmelCase     :				Dict       =							batch_size
            _lowerCAmelCase     :				Optional[int]       =							num_channels
            _lowerCAmelCase     :				List[str]       =							image_size
            _lowerCAmelCase     :				Optional[int]       =							patch_size
            _lowerCAmelCase     :				int       =							is_training
            _lowerCAmelCase     :				str       =							use_input_mask
            _lowerCAmelCase     :				Dict       =							use_token_type_ids
            _lowerCAmelCase     :				Optional[int]       =							use_labels
            _lowerCAmelCase     :				List[str]       =							vocab_size
            _lowerCAmelCase     :				Union[str, Any]       =							hidden_size
            _lowerCAmelCase     :				int       =							num_hidden_layers
            _lowerCAmelCase     :				Optional[Any]       =							num_attention_heads
            _lowerCAmelCase     :				Any       =							intermediate_size
            _lowerCAmelCase     :				List[Any]       =							hidden_act
            _lowerCAmelCase     :				Optional[int]       =							hidden_dropout_prob
            _lowerCAmelCase     :				List[Any]       =							attention_probs_dropout_prob
            _lowerCAmelCase     :				Optional[Any]       =							max_position_embeddings
            _lowerCAmelCase     :				Dict       =							type_vocab_size
            _lowerCAmelCase     :				List[str]       =							type_sequence_label_size
            _lowerCAmelCase     :				Union[str, Any]       =							initializer_range
            _lowerCAmelCase     :				Optional[int]       =							coordinate_size
            _lowerCAmelCase     :				Optional[int]       =							shape_size
            _lowerCAmelCase     :				int       =							num_labels
            _lowerCAmelCase     :				Any       =							num_choices
            _lowerCAmelCase     :				str       =							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     :				Optional[Any]       =							text_seq_length
            _lowerCAmelCase     :				str       =							(image_size // patch_size) ** 2 + 1
            _lowerCAmelCase     :				Optional[Any]       =							self.text_seq_length + self.image_seq_length







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[Any]       =							ids_tensor([self.batch_size, self.text_seq_length]   ,						self.vocab_size )

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

            _lowerCAmelCase     :				Union[str, Any]       =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

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

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

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

            _lowerCAmelCase     :				List[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 a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							TFLayoutLMvaModel(config=_lowerCamelCase )

            # text + image
            _lowerCAmelCase     :				int       =							model(_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						training=_lowerCamelCase )
            _lowerCAmelCase     :				Tuple       =							model(
                _lowerCamelCase   ,						bbox=_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						attention_mask=_lowerCamelCase   ,						token_type_ids=_lowerCamelCase   ,						training=_lowerCamelCase   ,						)
            _lowerCAmelCase     :				Dict       =							model(_lowerCamelCase   ,						bbox=_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						training=_lowerCamelCase )

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

            # text only
            _lowerCAmelCase     :				str       =							model(_lowerCamelCase   ,						training=_lowerCamelCase )
            self.parent.assertEqual(
                result.last_hidden_state.shape   ,						(self.batch_size, self.text_seq_length, self.hidden_size) )

            # image only
            _lowerCAmelCase     :				List[Any]       =							model({'pixel_values': pixel_values}   ,						training=_lowerCamelCase )
            self.parent.assertEqual(
                result.last_hidden_state.shape   ,						(self.batch_size, self.image_seq_length, self.hidden_size) )







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Tuple       =							self.num_labels
            _lowerCAmelCase     :				int       =							TFLayoutLMvaForSequenceClassification(config=_lowerCamelCase )
            _lowerCAmelCase     :				int       =							model(
                _lowerCamelCase   ,						bbox=_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						attention_mask=_lowerCamelCase   ,						token_type_ids=_lowerCamelCase   ,						labels=_lowerCamelCase   ,						training=_lowerCamelCase   ,						)
            self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.num_labels) )







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				Any       =							self.num_labels
            _lowerCAmelCase     :				int       =							TFLayoutLMvaForTokenClassification(config=_lowerCamelCase )
            _lowerCAmelCase     :				Optional[Any]       =							model(
                _lowerCamelCase   ,						bbox=_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						attention_mask=_lowerCamelCase   ,						token_type_ids=_lowerCamelCase   ,						labels=_lowerCamelCase   ,						training=_lowerCamelCase   ,						)
            self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.text_seq_length, self.num_labels) )







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							2
            _lowerCAmelCase     :				List[str]       =							TFLayoutLMvaForQuestionAnswering(config=_lowerCamelCase )
            _lowerCAmelCase     :				Optional[int]       =							model(
                _lowerCamelCase   ,						bbox=_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						attention_mask=_lowerCamelCase   ,						token_type_ids=_lowerCamelCase   ,						start_positions=_lowerCamelCase   ,						end_positions=_lowerCamelCase   ,						training=_lowerCamelCase   ,						)
            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 a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				List[str]       =							self.prepare_config_and_inputs()
            ((_lowerCAmelCase)      ,  (_lowerCAmelCase)      ,  (_lowerCAmelCase)      ,  (_lowerCAmelCase)      ,  (_lowerCAmelCase)      ,  (_lowerCAmelCase)      ,  (_lowerCAmelCase)      ,  (_lowerCAmelCase))     :				str       =							config_and_inputs
            _lowerCAmelCase     :				List[Any]       =							{
                '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 						UpperCamelCase__       (			__a     ,       __a     ,       unittest.TestCase						):



     """simple docstring"""






     __magic_name__           =     (
         (
             TFLayoutLMvaModel,
             TFLayoutLMvaForQuestionAnswering,
             TFLayoutLMvaForSequenceClassification,
             TFLayoutLMvaForTokenClassification,
         )
         if is_tf_available()
         else ()
     )
     __magic_name__           =     (
         {'document-question-answering': TFLayoutLMvaForQuestionAnswering, 'feature-extraction': TFLayoutLMvaModel}
         if is_tf_available()
         else {}
     )

     __magic_name__           =     False
     __magic_name__           =     False
     __magic_name__           =     False







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__   ,						snake_case__ ):

            '''simple docstring'''

            return True







     def a						(			self   ,						snake_case__   ,						snake_case__   ,						snake_case__=False ):

            '''simple docstring'''

            _lowerCAmelCase     :				Optional[Any]       =							copy.deepcopy(_lowerCamelCase )

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

            if return_labels:
                   if model_class in get_values(_lowerCamelCase ):
                          _lowerCAmelCase     :				List[Any]       =							tf.ones(self.model_tester.batch_size   ,						dtype=tf.intaa )
                   elif model_class in get_values(_lowerCamelCase ):
                          _lowerCAmelCase     :				Optional[int]       =							tf.zeros(self.model_tester.batch_size   ,						dtype=tf.intaa )
                          _lowerCAmelCase     :				int       =							tf.zeros(self.model_tester.batch_size   ,						dtype=tf.intaa )
                   elif model_class in get_values(_lowerCamelCase ):
                          _lowerCAmelCase     :				List[Any]       =							tf.zeros(self.model_tester.batch_size   ,						dtype=tf.intaa )
                   elif model_class in get_values(_lowerCamelCase ):
                          _lowerCAmelCase     :				Optional[Any]       =							tf.zeros(
                              (self.model_tester.batch_size, self.model_tester.text_seq_length)   ,						dtype=tf.intaa )

            return inputs_dict







     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				str       =							TFLayoutLMvaModelTester(self )
            _lowerCAmelCase     :				Optional[int]       =							ConfigTester(self   ,						config_class=_lowerCamelCase   ,						hidden_size=37 )







     def a						(			self ):

            '''simple docstring'''

            self.config_tester.run_common_tests()







     def a						(			self ):

            '''simple docstring'''

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

                          # Test that model correctly compute the loss with kwargs
                          _lowerCAmelCase     :				Dict       =							self._prepare_for_class(inputs_dict.copy()   ,						_lowerCamelCase   ,						return_labels=_lowerCamelCase )
                          _lowerCAmelCase     :				Optional[Any]       =							prepared_for_class.pop('input_ids' )

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

                          # Get keys that were added with the _prepare_for_class function
                          _lowerCAmelCase     :				Any       =							prepared_for_class.keys() - inputs_dict.keys()
                          _lowerCAmelCase     :				List[Any]       =							inspect.signature(model.call ).parameters
                          _lowerCAmelCase     :				Union[str, Any]       =							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     :				Union[str, Any]       =							signature_names.index(_lowerCamelCase )
                                 _lowerCAmelCase     :				List[str]       =							label_key
                          _lowerCAmelCase     :				int       =							sorted(tuple_index_mapping.items() )
                          # Initialize a list with their default values, update the values and convert to a tuple
                          _lowerCAmelCase     :				Any       =							[]

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

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

                          _lowerCAmelCase     :				Optional[int]       =							tuple(_lowerCamelCase )

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

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







     def a						(			self ):

            '''simple docstring'''

            (
                (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  
            )     :				List[str]       =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            (
                (
                _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     :				Optional[Any]       =							type
                   self.model_tester.create_and_check_model(_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            (
                (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  
            )     :				Tuple       =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(
                _lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            (
                (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  
            )     :				List[str]       =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(
                _lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase )







     def a						(			self ):

            '''simple docstring'''

            (
                (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  (
                _lowerCAmelCase
            )      ,  
            )     :				Optional[int]       =							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(
                _lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase   ,						_lowerCamelCase )







     @slow
     def a						(			self ):

            '''simple docstring'''

            for model_name in TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   _lowerCAmelCase     :				Optional[int]       =							TFLayoutLMvaModel.from_pretrained(_lowerCamelCase )
                   self.assertIsNotNone(_lowerCamelCase )






def       lowercase					():







       """simple docstring"""







       _lowerCAmelCase     :				Optional[Any]       =							Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
       return image
@require_tf
class 						UpperCamelCase__       (			unittest.TestCase						):



     """simple docstring"""






     @cached_property
     def a						(			self ):

            '''simple docstring'''

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







     @slow
     def a						(			self ):

            '''simple docstring'''

            _lowerCAmelCase     :				Union[str, Any]       =							TFLayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base' )

            _lowerCAmelCase     :				List[str]       =							self.default_image_processor
            _lowerCAmelCase     :				Any       =							prepare_img()
            _lowerCAmelCase     :				str       =							image_processor(images=_lowerCamelCase   ,						return_tensors='tf' ).pixel_values

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

            # forward pass
            _lowerCAmelCase     :				int       =							model(input_ids=_lowerCamelCase   ,						bbox=_lowerCamelCase   ,						pixel_values=_lowerCamelCase   ,						training=_lowerCamelCase )

            # verify the logits
            _lowerCAmelCase     :				List[Any]       =							(1, 199, 768)
            self.assertEqual(outputs.last_hidden_state.shape   ,						_lowerCamelCase )

            _lowerCAmelCase     :				List[str]       =							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]   ,						_lowerCamelCase   ,						atol=1E-4 ) )


'''simple docstring'''

import unittest

from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
    is_pipeline_test,
    nested_simplify,
    require_detectrona,
    require_pytesseract,
    require_tf,
    require_torch,
    require_vision,
    slow,
)

from .test_pipelines_common import ANY


if is_vision_available():
 from PIL import Image

 from transformers.image_utils import load_image
else:


 class     __UpperCAmelCase       :





   @staticmethod
   def 						UpperCAmelCase_	(	*_lowerCamelCase    ,     **_lowerCamelCase ):
      pass






 def snake_case_      (					__snake_case  :							int)			->					Union[str, Any]:
    return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
A_     :						Any    							=(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


@is_pipeline_test
@require_torch
@require_vision
class     __UpperCAmelCase       ( unittest.TestCase		):
  __A :				Union[str, Any]											= MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING





  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model=_lowerCamelCase    ,     tokenizer=_lowerCamelCase    ,     image_processor=_lowerCamelCase )

     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )
     lowerCAmelCase_			=      '''What is the placebo?'''
     lowerCAmelCase_			=      [
         {
             '''image''': load_image(_lowerCamelCase ),
             '''question''': question,
         },
         {
             '''image''': image,
             '''question''': question,
         },
         {
             '''image''': image,
             '''question''': question,
             '''word_boxes''': word_boxes,
         },
     ]
     return dqa_pipeline, examples





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      dqa_pipeline(_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         _lowerCamelCase    ,     [
             [
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
             ]
         ]
         * 3    ,     )





  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline('''document-question-answering'''    ,     model='''hf-internal-testing/tiny-random-layoutlmv2''' )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''How many cats are there?'''

     lowerCAmelCase_			=      [
         {'''score''': 0.00_01, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39},
         {'''score''': 0.00_01, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40},
     ]
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     _lowerCamelCase )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     _lowerCamelCase )

     # This image does not detect ANY text in it, meaning layoutlmv2 should fail.
     # Empty answer probably
     lowerCAmelCase_			=      '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(_lowerCamelCase    ,     [] )

     # We can optionnally pass directly the words and bounding boxes
     lowerCAmelCase_			=      '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
     lowerCAmelCase_			=      []
     lowerCAmelCase_			=      []
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     words=_lowerCamelCase    ,     boxes=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(_lowerCamelCase    ,     [] )





  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ],
         ]
         * 2    ,     )





  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     max_seq_len=50    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
                 {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ]
         ]
         * 2    ,     )





  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''    ,     revision='''3dc6de3'''    ,     add_prefix_space=_lowerCamelCase )
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''impira/layoutlm-document-qa'''    ,     tokenizer=_lowerCamelCase    ,     revision='''3dc6de3'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             ]
         ]
         * 2    ,     )

     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )





  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''    ,     revision='''3dc6de3'''    ,     add_prefix_space=_lowerCamelCase )
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''impira/layoutlm-document-qa'''    ,     tokenizer=_lowerCamelCase    ,     revision='''3dc6de3'''    ,     max_seq_len=50    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ]
         ]
         * 2    ,     )

     lowerCAmelCase_			=      list(zip(*apply_tesseract(load_image(_lowerCamelCase )    ,     _lowerCamelCase    ,     '''''' ) ) )

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )





  @slow
  @require_torch
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''naver-clova-ix/donut-base-finetuned-docvqa'''    ,     tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' )    ,     feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa'''    ,     )

     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [{'''answer''': '''us-001'''}] )







  @require_tf
  @unittest.skip('''Document question answering not implemented in TF''' )
  def 						UpperCAmelCase_	(	self ):
     pass





