
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
 import torch

if is_vision_available():
 from PIL import Image

 from transformers import ChineseCLIPImageProcessor


class 						__lowerCAmelCase	(	unittest.TestCase      ):



      """simple docstring"""







      def __init__(      self		:       str				,       _snake_case		:       Union[str, Any]				,       _snake_case		:       Optional[int]=7				,       _snake_case		:       Optional[int]=3				,       _snake_case		:       Any=18				,       _snake_case		:       str=30				,       _snake_case		:       Optional[Any]=400				,       _snake_case		:       Tuple=True				,       _snake_case		:       str=None				,       _snake_case		:       List[Any]=True				,       _snake_case		:       Union[str, Any]=None				,       _snake_case		:       int=True				,       _snake_case		:       Union[str, Any]=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]				,       _snake_case		:       Tuple=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]				,       _snake_case		:       Dict=True				,       ):
          __lowercase		:			List[str]	    =       size if size is not None else {'''height''': 224, '''width''': 224}
          __lowercase		:			Optional[int]	    =       crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
          __lowercase		:			Optional[Any]	    =       parent
          __lowercase		:			List[str]	    =       batch_size
          __lowercase		:			Dict	    =       num_channels
          __lowercase		:			Optional[Any]	    =       image_size
          __lowercase		:			Optional[int]	    =       min_resolution
          __lowercase		:			Dict	    =       max_resolution
          __lowercase		:			str	    =       do_resize
          __lowercase		:			Optional[Any]	    =       size
          __lowercase		:			Optional[Any]	    =       do_center_crop
          __lowercase		:			Any	    =       crop_size
          __lowercase		:			str	    =       do_normalize
          __lowercase		:			Any	    =       image_mean
          __lowercase		:			Tuple	    =       image_std
          __lowercase		:			Optional[int]	    =       do_convert_rgb




      def 		snake_case_			(      self		:       List[str]				):
          return {
              "do_resize": self.do_resize,
              "size": self.size,
              "do_center_crop": self.do_center_crop,
              "crop_size": self.crop_size,
              "do_normalize": self.do_normalize,
              "image_mean": self.image_mean,
              "image_std": self.image_std,
              "do_convert_rgb": self.do_convert_rgb,
          }




      def 		snake_case_			(      self		:       Any				,       _snake_case		:       Dict=False				,       _snake_case		:       Optional[Any]=False				,       _snake_case		:       List[Any]=False				):
          assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

          if equal_resolution:
              __lowercase		:			Any	    =       []
              for i in range(self.batch_size				):
                  image_inputs.append(
                      np.random.randint(
                          255				,       size=(self.num_channels, self.max_resolution, self.max_resolution)				,       dtype=np.uinta				)				)
          else:
              __lowercase		:			Any	    =       []
              for i in range(self.batch_size				):
                  __lowercase    ,      __lowercase		:			Tuple	    =       np.random.choice(np.arange(self.min_resolution				,       self.max_resolution				)				,       2				)
                  image_inputs.append(np.random.randint(255				,       size=(self.num_channels, width, height)				,       dtype=np.uinta				)				)

          if not numpify and not torchify:
              # PIL expects the channel dimension as last dimension
              __lowercase		:			Optional[int]	    =       [Image.fromarray(np.moveaxis(_snake_case				,       0				,       -1				)				) for x in image_inputs]

          if torchify:
              __lowercase		:			Dict	    =       [torch.from_numpy(_snake_case				) for x in image_inputs]

          return image_inputs






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



      """simple docstring"""







      A__	:			Tuple        =    ChineseCLIPImageProcessor if is_vision_available() else None




      def 		snake_case_			(      self		:       List[str]				):
          __lowercase		:			Optional[Any]	    =       ChineseCLIPImageProcessingTester(self				,       do_center_crop=_snake_case				)




      @property
      def 		snake_case_			(      self		:       List[Any]				):
          return self.image_processor_tester.prepare_image_processor_dict()




      def 		snake_case_			(      self		:       str				):
          __lowercase		:			Optional[Any]	    =       self.image_processing_class(**self.image_processor_dict				)
          self.assertTrue(hasattr(_snake_case				,       '''do_resize'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''size'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''do_center_crop'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''center_crop'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''do_normalize'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''image_mean'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''image_std'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''do_convert_rgb'''				)				)




      def 		snake_case_			(      self		:       str				):
          __lowercase		:			Any	    =       self.image_processing_class.from_dict(self.image_processor_dict				)
          self.assertEqual(image_processor.size				,       {'''height''': 224, '''width''': 224}				)
          self.assertEqual(image_processor.crop_size				,       {'''height''': 18, '''width''': 18}				)

          __lowercase		:			Any	    =       self.image_processing_class.from_dict(self.image_processor_dict				,       size=42				,       crop_size=84				)
          self.assertEqual(image_processor.size				,       {'''shortest_edge''': 42}				)
          self.assertEqual(image_processor.crop_size				,       {'''height''': 84, '''width''': 84}				)




      def 		snake_case_			(      self		:       Union[str, Any]				):
          pass




      def 		snake_case_			(      self		:       List[str]				):
          # Initialize image_processing
          __lowercase		:			Any	    =       self.image_processing_class(**self.image_processor_dict				)
          # create random PIL images
          __lowercase		:			Dict	    =       self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case				)
          for image in image_inputs:
              self.assertIsInstance(_snake_case				,       Image.Image				)

          # Test not batched input
          __lowercase		:			List[Any]	    =       image_processing(image_inputs[0]				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )

          # Test batched
          __lowercase		:			Optional[int]	    =       image_processing(_snake_case				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )




      def 		snake_case_			(      self		:       Any				):
          # Initialize image_processing
          __lowercase		:			Optional[int]	    =       self.image_processing_class(**self.image_processor_dict				)
          # create random numpy tensors
          __lowercase		:			str	    =       self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case				,       numpify=_snake_case				)
          for image in image_inputs:
              self.assertIsInstance(_snake_case				,       np.ndarray				)

          # Test not batched input
          __lowercase		:			List[Any]	    =       image_processing(image_inputs[0]				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )

          # Test batched
          __lowercase		:			List[str]	    =       image_processing(_snake_case				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )




      def 		snake_case_			(      self		:       List[Any]				):
          # Initialize image_processing
          __lowercase		:			Any	    =       self.image_processing_class(**self.image_processor_dict				)
          # create random PyTorch tensors
          __lowercase		:			Optional[int]	    =       self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case				,       torchify=_snake_case				)
          for image in image_inputs:
              self.assertIsInstance(_snake_case				,       torch.Tensor				)

          # Test not batched input
          __lowercase		:			List[str]	    =       image_processing(image_inputs[0]				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  1,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )

          # Test batched
          __lowercase		:			List[str]	    =       image_processing(_snake_case				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  self.image_processor_tester.batch_size,
                  self.image_processor_tester.num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )






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



      """simple docstring"""







      A__	:			int        =    ChineseCLIPImageProcessor if is_vision_available() else None




      def 		snake_case_			(      self		:       Tuple				):
          __lowercase		:			List[Any]	    =       ChineseCLIPImageProcessingTester(self				,       num_channels=4				,       do_center_crop=_snake_case				)
          __lowercase		:			List[str]	    =       3




      @property
      def 		snake_case_			(      self		:       Union[str, Any]				):
          return self.image_processor_tester.prepare_image_processor_dict()




      def 		snake_case_			(      self		:       Dict				):
          __lowercase		:			Optional[int]	    =       self.image_processing_class(**self.image_processor_dict				)
          self.assertTrue(hasattr(_snake_case				,       '''do_resize'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''size'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''do_center_crop'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''center_crop'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''do_normalize'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''image_mean'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''image_std'''				)				)
          self.assertTrue(hasattr(_snake_case				,       '''do_convert_rgb'''				)				)




      def 		snake_case_			(      self		:       Optional[Any]				):
          pass




      def 		snake_case_			(      self		:       str				):
          # Initialize image_processing
          __lowercase		:			Dict	    =       self.image_processing_class(**self.image_processor_dict				)
          # create random PIL images
          __lowercase		:			str	    =       self.image_processor_tester.prepare_inputs(equal_resolution=_snake_case				)
          for image in image_inputs:
              self.assertIsInstance(_snake_case				,       Image.Image				)

          # Test not batched input
          __lowercase		:			List[Any]	    =       image_processing(image_inputs[0]				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  1,
                  self.expected_encoded_image_num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )

          # Test batched
          __lowercase		:			Dict	    =       image_processing(_snake_case				,       return_tensors='''pt'''				).pixel_values
          self.assertEqual(
              encoded_images.shape				,       (
                  self.image_processor_tester.batch_size,
                  self.expected_encoded_image_num_channels,
                  self.image_processor_tester.crop_size['''height'''],
                  self.image_processor_tester.crop_size['''width'''],
              )				,       )




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


