





'''simple docstring'''




import inspect
import unittest

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

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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
  from transformers.models.mobilevitva.modeling_mobilevitva import (
      MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
      make_divisible,
  )


if is_vision_available():
  from PIL import Image

  from transformers import MobileViTImageProcessor


class 					SCREAMING_SNAKE_CASE       (SCREAMING_SNAKE_CASE_				):


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Union[str, Any]						=			self.config_class(**self.inputs_dict)
          self.parent.assertTrue(hasattr(snake_case__		,      'width_multiplier'))




class 					SCREAMING_SNAKE_CASE       :


     def __init__(		self		,      _UpperCAmelCase		,      _UpperCAmelCase=13		,      _UpperCAmelCase=64		,      _UpperCAmelCase=2		,      _UpperCAmelCase=3		,      _UpperCAmelCase="swish"		,      _UpperCAmelCase=3		,      _UpperCAmelCase=32		,      _UpperCAmelCase=0.1		,      _UpperCAmelCase=0.02		,      _UpperCAmelCase=True		,      _UpperCAmelCase=True		,      _UpperCAmelCase=10		,      _UpperCAmelCase=None		,      _UpperCAmelCase=0.25		,      _UpperCAmelCase=0.0		,      _UpperCAmelCase=0.0		,      ):

          '''simple docstring'''






          __A		:					int						=			parent
          __A		:					str						=			batch_size
          __A		:					str						=			image_size
          __A		:					List[Any]						=			patch_size
          __A		:					Dict						=			num_channels
          __A		:					Optional[int]						=			make_divisible(512 * width_multiplier		,      divisor=8)
          __A		:					Tuple						=			hidden_act
          __A		:					str						=			conv_kernel_size
          __A		:					Any						=			output_stride
          __A		:					Any						=			classifier_dropout_prob
          __A		:					Optional[int]						=			use_labels
          __A		:					Tuple						=			is_training
          __A		:					Any						=			num_labels
          __A		:					Tuple						=			initializer_range
          __A		:					List[Any]						=			scope
          __A		:					List[Any]						=			width_multiplier
          __A		:					Any						=			ffn_dropout
          __A		:					Dict						=			attn_dropout


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Tuple						=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

          __A		:					Any						=			self.get_config()

          return config, pixel_values, labels, pixel_labels


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return MobileViTVaConfig(
              image_size=self.image_size		,      patch_size=self.patch_size		,      num_channels=self.num_channels		,      hidden_act=self.hidden_act		,      conv_kernel_size=self.conv_kernel_size		,      output_stride=self.output_stride		,      classifier_dropout_prob=self.classifier_dropout_prob		,      initializer_range=self.initializer_range		,      width_multiplier=self.width_multiplier		,      ffn_dropout=self.ffn_dropout_prob		,      attn_dropout=self.attn_dropout_prob		,      )


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					Dict						=			MobileViTVaModel(config=snake_case__)
          model.to(snake_case__)
          model.eval()
          __A		:					List[Any]						=			model(snake_case__)
          self.parent.assertEqual(
              result.last_hidden_state.shape		,      (
                  self.batch_size,
                  self.last_hidden_size,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              )		,      )


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					int						=			self.num_labels
          __A		:					Optional[int]						=			MobileViTVaForImageClassification(snake_case__)
          model.to(snake_case__)
          model.eval()
          __A		:					Optional[Any]						=			model(snake_case__		,      labels=snake_case__)
          self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels))


     def 				SCREAMING_SNAKE_CASE    (		self		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):

          '''simple docstring'''






          __A		:					List[str]						=			self.num_labels
          __A		:					Optional[Any]						=			MobileViTVaForSemanticSegmentation(snake_case__)
          model.to(snake_case__)
          model.eval()
          __A		:					Any						=			model(snake_case__)
          self.parent.assertEqual(
              result.logits.shape		,      (
                  self.batch_size,
                  self.num_labels,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              )		,      )
          __A		:					Dict						=			model(snake_case__		,      labels=snake_case__)
          self.parent.assertEqual(
              result.logits.shape		,      (
                  self.batch_size,
                  self.num_labels,
                  self.image_size // self.output_stride,
                  self.image_size // self.output_stride,
              )		,      )


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Dict						=			self.prepare_config_and_inputs()
          __A					,__A					,__A					,__A		:					int						=			config_and_inputs
          __A		:					Union[str, Any]						=			{'pixel_values': pixel_values}
          return config, inputs_dict




@require_torch
class 					SCREAMING_SNAKE_CASE       (SCREAMING_SNAKE_CASE_   ,						SCREAMING_SNAKE_CASE_   ,						unittest.TestCase				):
     lowerCAmelCase						     =			(
         (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )

     lowerCAmelCase						     =			(
         {
             '''feature-extraction''': MobileViTVaModel,
             '''image-classification''': MobileViTVaForImageClassification,
             '''image-segmentation''': MobileViTVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False
     lowerCAmelCase						     =			False


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Dict						=			MobileViTVaModelTester(self)
          __A		:					List[str]						=			MobileViTVaConfigTester(self		,      config_class=snake_case__		,      has_text_modality=snake_case__)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          self.config_tester.run_common_tests()


     @unittest.skip(reason='MobileViTV2 does not use inputs_embeds')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     @unittest.skip(reason='MobileViTV2 does not support input and output embeddings')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     @unittest.skip(reason='MobileViTV2 does not output attentions')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     @require_torch_multi_gpu
     @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.')
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          pass


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A					,__A		:					int						=			self.model_tester.prepare_config_and_inputs_for_common()

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

               __A		:					Dict						=			['pixel_values']
               self.assertListEqual(arg_names[:1]		,      snake_case__)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Union[str, Any]						=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*snake_case__)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          def check_hidden_states_output(_UpperCAmelCase		,      _UpperCAmelCase		,      _UpperCAmelCase):
               __A		:					str						=			model_class(snake_case__)
               model.to(snake_case__)
               model.eval()

               with torch.no_grad():
                    __A		:					Any						=			model(**self._prepare_for_class(snake_case__		,      snake_case__))

               __A		:					List[str]						=			outputs.hidden_states

               __A		:					Optional[Any]						=			5
               self.assertEqual(len(snake_case__)		,      snake_case__)

               # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
               # with the width and height being successively divided by 2.
               __A		:					Any						=			2
               for i in range(len(snake_case__)):
                    self.assertListEqual(
                        list(hidden_states[i].shape[-2:])		,      [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]		,      )
                    divisor *= 2

               self.assertEqual(self.model_tester.output_stride		,      divisor // 2)

          __A					,__A		:					Any						=			self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
               __A		:					str						=			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"]
               __A		:					str						=			True

               check_hidden_states_output(snake_case__		,      snake_case__		,      snake_case__)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					List[Any]						=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*snake_case__)


     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Dict						=			self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_semantic_segmentation(*snake_case__)


     @slow
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __A		:					Dict						=			MobileViTVaModel.from_pretrained(snake_case__)
               self.assertIsNotNone(snake_case__)






def 			_lowerCAmelCase     (    )	->	int:
     __A		:					str						=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
     return image







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


     @cached_property
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          return (
              MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256')
              if is_vision_available()
              else None
          )


     @slow
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Tuple						=			MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256').to(
              snake_case__)

          __A		:					List[str]						=			self.default_image_processor
          __A		:					str						=			prepare_img()
          __A		:					int						=			image_processor(images=snake_case__		,      return_tensors='pt').to(snake_case__)

          # forward pass
          with torch.no_grad():
               __A		:					int						=			model(**snake_case__)

          # verify the logits
          __A		:					Optional[int]						=			torch.Size((1, 1000))
          self.assertEqual(outputs.logits.shape		,      snake_case__)

          __A		:					Dict						=			torch.tensor([-1.6_3_3_6e0_0, -7.3_2_0_4e-0_2, -5.1_8_8_3e-0_1]).to(snake_case__)

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


     @slow
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					Optional[Any]						=			MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')
          __A		:					Optional[Any]						=			model.to(snake_case__)

          __A		:					Optional[Any]						=			MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')

          __A		:					List[str]						=			prepare_img()
          __A		:					Optional[Any]						=			image_processor(images=snake_case__		,      return_tensors='pt').to(snake_case__)

          # forward pass
          with torch.no_grad():
               __A		:					Dict						=			model(**snake_case__)
          __A		:					int						=			outputs.logits

          # verify the logits
          __A		:					Union[str, Any]						=			torch.Size((1, 21, 32, 32))
          self.assertEqual(logits.shape		,      snake_case__)

          __A		:					Any						=			torch.tensor(
              [
                  [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
                  [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
                  [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
              ]		,      device=snake_case__		,      )

          self.assertTrue(torch.allclose(logits[0, :3, :3, :3]		,      snake_case__		,      atol=1e-4))


     @slow
     def 				SCREAMING_SNAKE_CASE    (		self):

          '''simple docstring'''






          __A		:					str						=			MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')
          __A		:					Optional[int]						=			model.to(snake_case__)

          __A		:					str						=			MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3')

          __A		:					Union[str, Any]						=			prepare_img()
          __A		:					Optional[Any]						=			image_processor(images=snake_case__		,      return_tensors='pt').to(snake_case__)

          # forward pass
          with torch.no_grad():
               __A		:					Optional[int]						=			model(**snake_case__)

          __A		:					List[str]						=			outputs.logits.detach().cpu()

          __A		:					Union[str, Any]						=			image_processor.post_process_semantic_segmentation(outputs=snake_case__		,      target_sizes=[(50, 60)])
          __A		:					Optional[Any]						=			torch.Size((50, 60))
          self.assertEqual(segmentation[0].shape		,      snake_case__)

          __A		:					Tuple						=			image_processor.post_process_semantic_segmentation(outputs=snake_case__)
          __A		:					Dict						=			torch.Size((32, 32))
          self.assertEqual(segmentation[0].shape		,      snake_case__)
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__     :     Optional[int]     ,  **snake_case__     :     Tuple		)      ->	Optional[Any]:
								pass



				def 	lowerCamelCase					(	UpperCamelCase     :				str							)   ->    Tuple:
						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						=			(
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)





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


		'''simple docstring'''






		lowerCAmelCase_     =   MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
		@require_pytesseract
		@require_vision
		def   _snake_case       (       self     :     str     ,  snake_case__     :     Optional[Any]     ,  snake_case__     :     Any     ,  snake_case__     :     Union[str, Any]		)      ->	Dict:
				_lowerCamelCase				   =  pipeline(
				    'document-question-answering'     ,  model=snake_case__     ,  tokenizer=snake_case__     ,  image_processor=snake_case__		)

				_lowerCamelCase				   =  INVOICE_URL
				_lowerCamelCase				   =  list(zip(*apply_tesseract(load_image(snake_case__		)     ,  snake_case__     ,  ''		)		)		)
				_lowerCamelCase				   =  'What is the placebo?'
				_lowerCamelCase				   =  [
				    {
				        '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     :     Union[str, Any]     ,  snake_case__     :     Union[str, Any]     ,  snake_case__     :     List[Any]		)      ->	Tuple:
				_lowerCamelCase				   =  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     :     Union[str, Any]		)      ->	Optional[int]:
				_lowerCamelCase				   =  pipeline('document-question-answering'     ,  model='hf-internal-testing/tiny-random-layoutlmv2'		)
				_lowerCamelCase				   =  INVOICE_URL
				_lowerCamelCase				   =  'How many cats are there?'

				_lowerCamelCase				   =  [
				    {'score': 0.0001, 'answer': 'oy 2312/2019', 'start': 3_8, 'end': 3_9},
				    {'score': 0.0001, 'answer': 'oy 2312/2019 DUE', 'start': 3_8, 'end': 4_0},
				]
				_lowerCamelCase				   =  dqa_pipeline(image=snake_case__     ,  question=snake_case__     ,  top_k=2		)
				self.assertEqual(nested_simplify(snake_case__     ,  decimals=4		)     ,  snake_case__		)

				_lowerCamelCase				   =  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
				_lowerCamelCase				   =  './tests/fixtures/tests_samples/COCO/000000039769.png'
				_lowerCamelCase				   =  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
				_lowerCamelCase				   =  './tests/fixtures/tests_samples/COCO/000000039769.png'
				_lowerCamelCase				   =  []
				_lowerCamelCase				   =  []
				_lowerCamelCase				   =  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     :     Optional[int]		)      ->	List[Any]:
				_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=snake_case__     ,  question=snake_case__     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.9944, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.0009, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline({'image': image, 'question': question}     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.9944, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.0009, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline(
				    [{'image': image, 'question': question}, {'image': image, 'question': question}]     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        [
				            {'score': 0.9944, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				            {'score': 0.0009, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        ],
				    ]
				    * 2     ,  )
		@slow
		@require_torch
		@require_detectrona
		@require_pytesseract
		def   _snake_case       (       self     :     int		)      ->	Optional[Any]:
				_lowerCamelCase				   =  pipeline(
				    'document-question-answering'     ,  model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'     ,  revision='9977165'     ,  max_seq_len=5_0     ,  )
				_lowerCamelCase				   =  INVOICE_URL
				_lowerCamelCase				   =  'What is the invoice number?'

				_lowerCamelCase				   =  dqa_pipeline(image=snake_case__     ,  question=snake_case__     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.9974, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				        {'score': 0.9948, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline({'image': image, 'question': question}     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.9974, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				        {'score': 0.9948, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline(
				    [{'image': image, 'question': question}, {'image': image, 'question': question}]     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        [
				            {'score': 0.9974, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				            {'score': 0.9948, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        ]
				    ]
				    * 2     ,  )
		@slow
		@require_torch
		@require_pytesseract
		@require_vision
		def   _snake_case       (       self     :     int		)      ->	List[Any]:
				_lowerCamelCase				   =  AutoTokenizer.from_pretrained(
				    'impira/layoutlm-document-qa'     ,  revision='3dc6de3'     ,  add_prefix_space=snake_case__		)
				_lowerCamelCase				   =  pipeline(
				    'document-question-answering'     ,  model='impira/layoutlm-document-qa'     ,  tokenizer=snake_case__     ,  revision='3dc6de3'     ,  )
				_lowerCamelCase				   =  INVOICE_URL
				_lowerCamelCase				   =  'What is the invoice number?'

				_lowerCamelCase				   =  dqa_pipeline(image=snake_case__     ,  question=snake_case__     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.4251, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.0819, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline({'image': image, 'question': question}     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.4251, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.0819, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline(
				    [{'image': image, 'question': question}, {'image': image, 'question': question}]     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        [
				            {'score': 0.4251, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				            {'score': 0.0819, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				        ]
				    ]
				    * 2     ,  )

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

				# 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(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.4251, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.0819, 'answer': '1110212019', 'start': 2_3, 'end': 2_3},
				    ]     ,  )
		@slow
		@require_torch
		@require_pytesseract
		@require_vision
		def   _snake_case       (       self     :     Dict		)      ->	List[str]:
				_lowerCamelCase				   =  AutoTokenizer.from_pretrained(
				    'impira/layoutlm-document-qa'     ,  revision='3dc6de3'     ,  add_prefix_space=snake_case__		)
				_lowerCamelCase				   =  pipeline(
				    'document-question-answering'     ,  model='impira/layoutlm-document-qa'     ,  tokenizer=snake_case__     ,  revision='3dc6de3'     ,  max_seq_len=5_0     ,  )
				_lowerCamelCase				   =  INVOICE_URL
				_lowerCamelCase				   =  'What is the invoice number?'

				_lowerCamelCase				   =  dqa_pipeline(image=snake_case__     ,  question=snake_case__     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.9999, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.9998, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				    ]     ,  )

				_lowerCamelCase				   =  dqa_pipeline(
				    [{'image': image, 'question': question}, {'image': image, 'question': question}]     ,  top_k=2		)
				self.assertEqual(
				    nested_simplify(snake_case__     ,  decimals=4		)     ,  [
				        [
				            {'score': 0.9999, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				            {'score': 0.9998, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        ]
				    ]
				    * 2     ,  )

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

				# 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(snake_case__     ,  decimals=4		)     ,  [
				        {'score': 0.9999, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				        {'score': 0.9998, 'answer': 'us-001', 'start': 1_6, 'end': 1_6},
				    ]     ,  )
		@slow
		@require_torch
		def   _snake_case       (       self     :     Dict		)      ->	int:
				_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=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     :     Optional[Any]		)      ->	Any:
				pass