
import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
 from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import AutoImageProcessor


class 						__lowerCAmelCase	:



      """simple docstring"""







      def __init__(      self		:       Optional[Any]				,       _snake_case		:       Tuple				,       _snake_case		:       Tuple=13				,       _snake_case		:       Optional[Any]=32				,       _snake_case		:       Dict=3				,       _snake_case		:       Any=4				,       _snake_case		:       Optional[Any]=[10, 20, 30, 40]				,       _snake_case		:       Dict=[2, 2, 3, 2]				,       _snake_case		:       Union[str, Any]=True				,       _snake_case		:       List[str]=True				,       _snake_case		:       Optional[int]=37				,       _snake_case		:       str="gelu"				,       _snake_case		:       int=10				,       _snake_case		:       Optional[int]=0.02				,       _snake_case		:       Optional[int]=["stage2", "stage3", "stage4"]				,       _snake_case		:       Optional[Any]=[2, 3, 4]				,       _snake_case		:       Union[str, Any]=None				,       ):
          __lowercase		:			int	    =       parent
          __lowercase		:			Optional[Any]	    =       batch_size
          __lowercase		:			Optional[int]	    =       image_size
          __lowercase		:			Tuple	    =       num_channels
          __lowercase		:			int	    =       num_stages
          __lowercase		:			Optional[int]	    =       hidden_sizes
          __lowercase		:			List[Any]	    =       depths
          __lowercase		:			List[str]	    =       is_training
          __lowercase		:			Tuple	    =       use_labels
          __lowercase		:			List[str]	    =       intermediate_size
          __lowercase		:			str	    =       hidden_act
          __lowercase		:			Any	    =       num_labels
          __lowercase		:			Dict	    =       initializer_range
          __lowercase		:			Optional[int]	    =       out_features
          __lowercase		:			List[Any]	    =       out_indices
          __lowercase		:			List[str]	    =       scope




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			Dict	    =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

          __lowercase		:			Union[str, Any]	    =       None
          if self.use_labels:
              __lowercase		:			List[Any]	    =       ids_tensor([self.batch_size]				,       self.num_labels				)

          __lowercase		:			List[Any]	    =       self.get_config()
          return config, pixel_values, labels




      def 		snake_case_			(      self		:       List[Any]				):
          return ConvNextConfig(
              num_channels=self.num_channels				,       hidden_sizes=self.hidden_sizes				,       depths=self.depths				,       num_stages=self.num_stages				,       hidden_act=self.hidden_act				,       is_decoder=_snake_case				,       initializer_range=self.initializer_range				,       out_features=self.out_features				,       out_indices=self.out_indices				,       num_labels=self.num_labels				,       )




      def 		snake_case_			(      self		:       Optional[int]				,       _snake_case		:       Union[str, Any]				,       _snake_case		:       List[Any]				,       _snake_case		:       List[Any]				):
          __lowercase		:			List[str]	    =       ConvNextModel(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			List[Any]	    =       model(_snake_case				)
          # expected last hidden states: B, C, H // 32, W // 32
          self.parent.assertEqual(
              result.last_hidden_state.shape				,       (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)				,       )




      def 		snake_case_			(      self		:       str				,       _snake_case		:       Tuple				,       _snake_case		:       List[str]				,       _snake_case		:       Union[str, Any]				):
          __lowercase		:			Any	    =       ConvNextForImageClassification(_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			str	    =       model(_snake_case				,       labels=_snake_case				)
          self.parent.assertEqual(result.logits.shape				,       (self.batch_size, self.num_labels)				)




      def 		snake_case_			(      self		:       Tuple				,       _snake_case		:       str				,       _snake_case		:       Optional[int]				,       _snake_case		:       Tuple				):
          __lowercase		:			Optional[Any]	    =       ConvNextBackbone(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			Dict	    =       model(_snake_case				)

          # verify hidden states
          self.parent.assertEqual(len(result.feature_maps				)				,       len(config.out_features				)				)
          self.parent.assertListEqual(list(result.feature_maps[0].shape				)				,       [self.batch_size, self.hidden_sizes[1], 4, 4]				)

          # verify channels
          self.parent.assertEqual(len(model.channels				)				,       len(config.out_features				)				)
          self.parent.assertListEqual(model.channels				,       config.hidden_sizes[1:]				)

          # verify backbone works with out_features=None
          __lowercase		:			Tuple	    =       None
          __lowercase		:			List[Any]	    =       ConvNextBackbone(config=_snake_case				)
          model.to(_snake_case				)
          model.eval()
          __lowercase		:			Dict	    =       model(_snake_case				)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps				)				,       1				)
          self.parent.assertListEqual(list(result.feature_maps[0].shape				)				,       [self.batch_size, self.hidden_sizes[-1], 1, 1]				)

          # verify channels
          self.parent.assertEqual(len(model.channels				)				,       1				)
          self.parent.assertListEqual(model.channels				,       [config.hidden_sizes[-1]]				)




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			Any	    =       self.prepare_config_and_inputs()
          __lowercase		:			List[Any]	    =       config_and_inputs
          __lowercase		:			Tuple	    =       {'''pixel_values''': pixel_values}
          return config, inputs_dict






@require_torch
class 						__lowerCAmelCase	(	lowerCAmelCase_ , lowerCAmelCase_ , unittest.TestCase      ):



      """simple docstring"""







      A__	:			List[str]        =    (
          (
              ConvNextModel,
              ConvNextForImageClassification,
              ConvNextBackbone,
          )
          if is_torch_available()
          else ()
      )
      A__	:			Optional[Any]        =    (
          {'''feature-extraction''': ConvNextModel, '''image-classification''': ConvNextForImageClassification}
          if is_torch_available()
          else {}
      )

      A__	:			Optional[Any]        =    True
      A__	:			Optional[int]        =    False
      A__	:			str        =    False
      A__	:			Dict        =    False
      A__	:			str        =    False




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			Optional[int]	    =       ConvNextModelTester(self				)
          __lowercase		:			Tuple	    =       ConfigTester(self				,       config_class=_snake_case				,       has_text_modality=_snake_case				,       hidden_size=37				)




      def 		snake_case_			(      self		:       Tuple				):
          self.create_and_test_config_common_properties()
          self.config_tester.create_and_test_config_to_json_string()
          self.config_tester.create_and_test_config_to_json_file()
          self.config_tester.create_and_test_config_from_and_save_pretrained()
          self.config_tester.create_and_test_config_with_num_labels()
          self.config_tester.check_config_can_be_init_without_params()
          self.config_tester.check_config_arguments_init()




      def 		snake_case_			(      self		:       List[str]				):
          return




      @unittest.skip(reason='''ConvNext does not use inputs_embeds'''				)
      def 		snake_case_			(      self		:       Tuple				):
          pass




      @unittest.skip(reason='''ConvNext does not support input and output embeddings'''				)
      def 		snake_case_			(      self		:       Union[str, Any]				):
          pass




      @unittest.skip(reason='''ConvNext does not use feedforward chunking'''				)
      def 		snake_case_			(      self		:       Tuple				):
          pass




      def 		snake_case_			(      self		:       Dict				):
          __lowercase		:			Tuple	    =       self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __lowercase		:			List[str]	    =       model_class(_snake_case				)
              __lowercase		:			int	    =       inspect.signature(model.forward				)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __lowercase		:			Any	    =       [*signature.parameters.keys()]

              __lowercase		:			Dict	    =       ['''pixel_values''']
              self.assertListEqual(arg_names[:1]				,       _snake_case				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          __lowercase		:			int	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*_snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			List[str]	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*_snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          def check_hidden_states_output(_snake_case		:       Any				,       _snake_case		:       List[str]				,       _snake_case		:       str				):
              __lowercase		:			int	    =       model_class(_snake_case				)
              model.to(_snake_case				)
              model.eval()

              with torch.no_grad():
                  __lowercase		:			Optional[int]	    =       model(**self._prepare_for_class(_snake_case				,       _snake_case				)				)

              __lowercase		:			Dict	    =       outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

              __lowercase		:			List[Any]	    =       self.model_tester.num_stages
              self.assertEqual(len(_snake_case				)				,       expected_num_stages + 1				)

              # ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
              self.assertListEqual(
                  list(hidden_states[0].shape[-2:]				)				,       [self.model_tester.image_size // 4, self.model_tester.image_size // 4]				,       )

          __lowercase		:			str	    =       self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
              __lowercase		:			Any	    =       True
              check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case				)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              __lowercase		:			Any	    =       True

              check_hidden_states_output(_snake_case				,       _snake_case				,       _snake_case				)




      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			int	    =       self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*_snake_case				)




      @slow
      def 		snake_case_			(      self		:       Optional[int]				):
          for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              __lowercase		:			List[str]	    =       ConvNextModel.from_pretrained(_snake_case				)
              self.assertIsNotNone(_snake_case				)






def     UpperCAmelCase_  (						) ->						Tuple:
    __lowercase		:			str	    =       Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
    return image


@require_torch
@require_vision
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      @cached_property
      def 		snake_case_			(      self		:       int				):
          return AutoImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''				) if is_vision_available() else None




      @slow
      def 		snake_case_			(      self		:       Union[str, Any]				):
          __lowercase		:			Any	    =       ConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''				).to(_snake_case				)

          __lowercase		:			Any	    =       self.default_image_processor
          __lowercase		:			Any	    =       prepare_img()
          __lowercase		:			Optional[int]	    =       image_processor(images=_snake_case				,       return_tensors='''pt'''				).to(_snake_case				)

          # forward pass
          with torch.no_grad():
              __lowercase		:			Tuple	    =       model(**_snake_case				)

          # verify the logits
          __lowercase		:			Dict	    =       torch.Size((1, 1000)				)
          self.assertEqual(outputs.logits.shape				,       _snake_case				)

          __lowercase		:			Optional[Any]	    =       torch.tensor([-0.02_60, -0.47_39, 0.19_11]				).to(_snake_case				)

          self.assertTrue(torch.allclose(outputs.logits[0, :3]				,       _snake_case				,       atol=1E-4				)				)






@require_torch
class 						__lowerCAmelCase	(	unittest.TestCase , lowerCAmelCase_      ):



      """simple docstring"""







      A__	:			List[str]        =    (ConvNextBackbone,) if is_torch_available() else ()
      A__	:			int        =    ConvNextConfig

      A__	:			str        =    False




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			Any	    =       ConvNextModelTester(self				)




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 						__lowerCAmelCase	:



       """simple docstring"""







       @staticmethod
       def 		snake_case_			(      *_snake_case		:       Union[str, Any]				,       **_snake_case		:       str				):
           pass






 def     UpperCAmelCase_  (						__lowerCAmelCase	) ->						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.
__lowerCAmelCase					:			Dict			      =		(
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)


@is_pipeline_test
@require_torch
@require_vision
class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      A__	:			int        =    MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING




      @require_pytesseract
      @require_vision
      def 		snake_case_			(      self		:       List[Any]				,       _snake_case		:       Any				,       _snake_case		:       Dict				,       _snake_case		:       Any				):
          __lowercase		:			List[str]	    =       pipeline(
              '''document-question-answering'''				,       model=_snake_case				,       tokenizer=_snake_case				,       image_processor=_snake_case				)

          __lowercase		:			int	    =       INVOICE_URL
          __lowercase		:			Optional[int]	    =       list(zip(*apply_tesseract(load_image(_snake_case				)				,       _snake_case				,       ''''''				)				)				)
          __lowercase		:			List[str]	    =       '''What is the placebo?'''
          __lowercase		:			Tuple	    =       [
              {
                  '''image''': load_image(_snake_case				),
                  '''question''': question,
              },
              {
                  '''image''': image,
                  '''question''': question,
              },
              {
                  '''image''': image,
                  '''question''': question,
                  '''word_boxes''': word_boxes,
              },
          ]
          return dqa_pipeline, examples




      def 		snake_case_			(      self		:       List[str]				,       _snake_case		:       int				,       _snake_case		:       List[Any]				):
          __lowercase		:			Optional[Any]	    =       dqa_pipeline(_snake_case				,       top_k=2				)
          self.assertEqual(
              _snake_case				,       [
                  [
                      {'''score''': ANY(_snake_case				), '''answer''': ANY(_snake_case				), '''start''': ANY(_snake_case				), '''end''': ANY(_snake_case				)},
                      {'''score''': ANY(_snake_case				), '''answer''': ANY(_snake_case				), '''start''': ANY(_snake_case				), '''end''': ANY(_snake_case				)},
                  ]
              ]
              * 3				,       )




      @require_torch
      @require_detectrona
      @require_pytesseract
      def 		snake_case_			(      self		:       Optional[int]				):
          __lowercase		:			List[str]	    =       pipeline('''document-question-answering'''				,       model='''hf-internal-testing/tiny-random-layoutlmv2'''				)
          __lowercase		:			Any	    =       INVOICE_URL
          __lowercase		:			str	    =       '''How many cats are there?'''

          __lowercase		:			Optional[int]	    =       [
              {'''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},
          ]
          __lowercase		:			Optional[Any]	    =       dqa_pipeline(image=_snake_case				,       question=_snake_case				,       top_k=2				)
          self.assertEqual(nested_simplify(_snake_case				,       decimals=4				)				,       _snake_case				)

          __lowercase		:			Optional[Any]	    =       dqa_pipeline({'''image''': image, '''question''': question}				,       top_k=2				)
          self.assertEqual(nested_simplify(_snake_case				,       decimals=4				)				,       _snake_case				)

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

          # We can optionnally pass directly the words and bounding boxes
          __lowercase		:			List[Any]	    =       '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
          __lowercase		:			Dict	    =       []
          __lowercase		:			List[str]	    =       []
          __lowercase		:			Tuple	    =       dqa_pipeline(image=_snake_case				,       question=_snake_case				,       words=_snake_case				,       boxes=_snake_case				,       top_k=2				)
          self.assertEqual(_snake_case				,       []				)




      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def 		snake_case_			(      self		:       int				):
          __lowercase		:			List[Any]	    =       pipeline(
              '''document-question-answering'''				,       model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''				,       revision='''9977165'''				,       )
          __lowercase		:			List[str]	    =       INVOICE_URL
          __lowercase		:			Optional[Any]	    =       '''What is the invoice number?'''

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

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

          __lowercase		:			List[str]	    =       dqa_pipeline(
              [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]				,       top_k=2				)
          self.assertEqual(
              nested_simplify(_snake_case				,       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 		snake_case_			(      self		:       int				):
          __lowercase		:			Optional[Any]	    =       pipeline(
              '''document-question-answering'''				,       model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''				,       revision='''9977165'''				,       max_seq_len=50				,       )
          __lowercase		:			Union[str, Any]	    =       INVOICE_URL
          __lowercase		:			Any	    =       '''What is the invoice number?'''

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

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

          __lowercase		:			List[Any]	    =       dqa_pipeline(
              [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]				,       top_k=2				)
          self.assertEqual(
              nested_simplify(_snake_case				,       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 		snake_case_			(      self		:       str				):
          __lowercase		:			List[Any]	    =       AutoTokenizer.from_pretrained(
              '''impira/layoutlm-document-qa'''				,       revision='''3dc6de3'''				,       add_prefix_space=_snake_case				)
          __lowercase		:			Union[str, Any]	    =       pipeline(
              '''document-question-answering'''				,       model='''impira/layoutlm-document-qa'''				,       tokenizer=_snake_case				,       revision='''3dc6de3'''				,       )
          __lowercase		:			Tuple	    =       INVOICE_URL
          __lowercase		:			Any	    =       '''What is the invoice number?'''

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

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

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

          __lowercase		:			Union[str, Any]	    =       list(zip(*apply_tesseract(load_image(_snake_case				)				,       _snake_case				,       ''''''				)				)				)

          # This model should also work if `image` is set to None
          __lowercase		:			Union[str, Any]	    =       dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}				,       top_k=2				)
          self.assertEqual(
              nested_simplify(_snake_case				,       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 		snake_case_			(      self		:       List[str]				):
          __lowercase		:			Optional[int]	    =       AutoTokenizer.from_pretrained(
              '''impira/layoutlm-document-qa'''				,       revision='''3dc6de3'''				,       add_prefix_space=_snake_case				)
          __lowercase		:			List[str]	    =       pipeline(
              '''document-question-answering'''				,       model='''impira/layoutlm-document-qa'''				,       tokenizer=_snake_case				,       revision='''3dc6de3'''				,       max_seq_len=50				,       )
          __lowercase		:			Tuple	    =       INVOICE_URL
          __lowercase		:			Optional[int]	    =       '''What is the invoice number?'''

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

          __lowercase		:			Any	    =       dqa_pipeline(
              [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]				,       top_k=2				)
          self.assertEqual(
              nested_simplify(_snake_case				,       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				,       )

          __lowercase		:			int	    =       list(zip(*apply_tesseract(load_image(_snake_case				)				,       _snake_case				,       ''''''				)				)				)

          # This model should also work if `image` is set to None
          __lowercase		:			Tuple	    =       dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}				,       top_k=2				)
          self.assertEqual(
              nested_simplify(_snake_case				,       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 		snake_case_			(      self		:       List[Any]				):
          __lowercase		:			int	    =       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'''				,       )

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




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


