import json
import pathlib
import unittest

import numpy as np

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

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
      import torch

if is_vision_available():
      from PIL import Image

      from transformers import DeformableDetrImageProcessor



class   snake_case_       (		unittest.TestCase       ):






   def __init__(      self				:     Optional[int]	,						lowercase_				:     str	,						lowercase_				:     Optional[Any]=7	,						lowercase_				:     List[str]=3	,						lowercase_				:     int=30	,						lowercase_				:     List[Any]=4_00	,						lowercase_				:     Dict=True	,						lowercase_				:     Optional[int]=None	,						lowercase_				:     Any=True	,						lowercase_				:     List[str]=[0.5, 0.5, 0.5]	,						lowercase_				:     List[str]=[0.5, 0.5, 0.5]	,						lowercase_				:     Any=True	,						lowercase_				:     Optional[int]=1 / 2_55	,						lowercase_				:     str=True	,						)					->						Tuple:
       # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p
       lowercase__ :   Optional[int]    					=				size if size is not None else {"shortest_edge": 18, "longest_edge": 13_33}
       lowercase__ :   List[str]    					=				parent
       lowercase__ :   str    					=				batch_size
       lowercase__ :   Optional[Any]    					=				num_channels
       lowercase__ :   List[str]    					=				min_resolution
       lowercase__ :   str    					=				max_resolution
       lowercase__ :   Optional[Any]    					=				do_resize
       lowercase__ :   List[Any]    					=				size
       lowercase__ :   int    					=				do_normalize
       lowercase__ :   List[Any]    					=				image_mean
       lowercase__ :   List[str]    					=				image_std
       lowercase__ :   Optional[Any]    					=				do_rescale
       lowercase__ :   Dict    					=				rescale_factor
       lowercase__ :   Union[str, Any]    					=				do_pad






   def       __UpperCamelCase     (      self				:     Any  )					->						Dict:
       return {
           "do_resize": self.do_resize,
           "size": self.size,
           "do_normalize": self.do_normalize,
           "image_mean": self.image_mean,
           "image_std": self.image_std,
           "do_rescale": self.do_rescale,
           "rescale_factor": self.rescale_factor,
           "do_pad": self.do_pad,
       }







   def       __UpperCamelCase     (      self				:     str	,						lowercase_				:     Optional[Any]	,						lowercase_				:     Optional[Any]=False  )					->						Any:
       if not batched:
           lowercase__ :   Dict    					=				image_inputs[0]
           if isinstance(lowercase_	,						Image.Image  ):
               lowercase__					,   lowercase__ :   List[Any]    					=				image.size
           else:
               lowercase__					,   lowercase__ :   List[str]    					=				image.shape[1], image.shape[2]
           if w < h:
               lowercase__ :   Any    					=				int(self.size["shortest_edge"] * h / w  )
               lowercase__ :   Union[str, Any]    					=				self.size["shortest_edge"]
           elif w > h:
               lowercase__ :   str    					=				self.size["shortest_edge"]
               lowercase__ :   Tuple    					=				int(self.size["shortest_edge"] * w / h  )
           else:
               lowercase__ :   Any    					=				self.size["shortest_edge"]
               lowercase__ :   Tuple    					=				self.size["shortest_edge"]

       else:
           lowercase__ :   int    					=				[]
           for image in image_inputs:
               lowercase__					,   lowercase__ :   Tuple    					=				self.get_expected_values([image]  )
               expected_values.append((expected_height, expected_width)  )
           lowercase__ :   Union[str, Any]    					=				max(lowercase_	,						key=lambda lowercase_  : item[0]  )[0]
           lowercase__ :   Any    					=				max(lowercase_	,						key=lambda lowercase_  : item[1]  )[1]

       return expected_height, expected_width



@require_torch
@require_vision
class   snake_case_       (		__A  ,unittest.TestCase       ):
   __A	:		str         =				DeformableDetrImageProcessor if is_vision_available() else None






   def       __UpperCamelCase     (      self				:     List[Any]  )					->						Any:
       lowercase__ :   Optional[Any]    					=				DeformableDetrImageProcessingTester(self  )






   @property
   def       __UpperCamelCase     (      self				:     Optional[Any]  )					->						Union[str, Any]:
       return self.image_processor_tester.prepare_image_processor_dict()






   def       __UpperCamelCase     (      self				:     int  )					->						int:
       lowercase__ :   Tuple    					=				self.image_processing_class(**self.image_processor_dict  )
       self.assertTrue(hasattr(lowercase_	,						"image_mean"  )  )
       self.assertTrue(hasattr(lowercase_	,						"image_std"  )  )
       self.assertTrue(hasattr(lowercase_	,						"do_normalize"  )  )
       self.assertTrue(hasattr(lowercase_	,						"do_resize"  )  )
       self.assertTrue(hasattr(lowercase_	,						"do_rescale"  )  )
       self.assertTrue(hasattr(lowercase_	,						"do_pad"  )  )
       self.assertTrue(hasattr(lowercase_	,						"size"  )  )






   def       __UpperCamelCase     (      self				:     Tuple  )					->						Optional[int]:
       lowercase__ :   List[str]    					=				self.image_processing_class.from_dict(self.image_processor_dict  )
       self.assertEqual(image_processor.size	,						{"shortest_edge": 18, "longest_edge": 13_33}  )
       self.assertEqual(image_processor.do_pad	,						lowercase_  )

       lowercase__ :   int    					=				self.image_processing_class.from_dict(
           self.image_processor_dict	,						size=42	,						max_size=84	,						pad_and_return_pixel_mask=lowercase_  )
       self.assertEqual(image_processor.size	,						{"shortest_edge": 42, "longest_edge": 84}  )
       self.assertEqual(image_processor.do_pad	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     Dict  )					->						str:
       pass






   def       __UpperCamelCase     (      self				:     List[str]  )					->						Any:
       # Initialize image_processing
       lowercase__ :   Union[str, Any]    					=				self.image_processing_class(**self.image_processor_dict  )
       # create random PIL images
       lowercase__ :   Dict    					=				prepare_image_inputs(self.image_processor_tester	,						equal_resolution=lowercase_  )
       for image in image_inputs:
           self.assertIsInstance(lowercase_	,						Image.Image  )

       # Test not batched input
       lowercase__ :   str    					=				image_processing(image_inputs[0]	,						return_tensors="pt"  ).pixel_values

       lowercase__					,   lowercase__ :   Tuple    					=				self.image_processor_tester.get_expected_values(lowercase_  )

       self.assertEqual(
           encoded_images.shape	,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)	,						)

       # Test batched
       lowercase__					,   lowercase__ :   Optional[Any]    					=				self.image_processor_tester.get_expected_values(lowercase_	,						batched=lowercase_  )

       lowercase__ :   str    					=				image_processing(lowercase_	,						return_tensors="pt"  ).pixel_values
       self.assertEqual(
           encoded_images.shape	,						(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               expected_height,
               expected_width,
           )	,						)






   def       __UpperCamelCase     (      self				:     List[str]  )					->						int:
       # Initialize image_processing
       lowercase__ :   str    					=				self.image_processing_class(**self.image_processor_dict  )
       # create random numpy tensors
       lowercase__ :   Tuple    					=				prepare_image_inputs(self.image_processor_tester	,						equal_resolution=lowercase_	,						numpify=lowercase_  )
       for image in image_inputs:
           self.assertIsInstance(lowercase_	,						np.ndarray  )

       # Test not batched input
       lowercase__ :   int    					=				image_processing(image_inputs[0]	,						return_tensors="pt"  ).pixel_values

       lowercase__					,   lowercase__ :   List[str]    					=				self.image_processor_tester.get_expected_values(lowercase_  )

       self.assertEqual(
           encoded_images.shape	,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)	,						)

       # Test batched
       lowercase__ :   Tuple    					=				image_processing(lowercase_	,						return_tensors="pt"  ).pixel_values

       lowercase__					,   lowercase__ :   Any    					=				self.image_processor_tester.get_expected_values(lowercase_	,						batched=lowercase_  )

       self.assertEqual(
           encoded_images.shape	,						(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               expected_height,
               expected_width,
           )	,						)






   def       __UpperCamelCase     (      self				:     str  )					->						int:
       # Initialize image_processing
       lowercase__ :   Optional[Any]    					=				self.image_processing_class(**self.image_processor_dict  )
       # create random PyTorch tensors
       lowercase__ :   str    					=				prepare_image_inputs(self.image_processor_tester	,						equal_resolution=lowercase_	,						torchify=lowercase_  )
       for image in image_inputs:
           self.assertIsInstance(lowercase_	,						torch.Tensor  )

       # Test not batched input
       lowercase__ :   List[str]    					=				image_processing(image_inputs[0]	,						return_tensors="pt"  ).pixel_values

       lowercase__					,   lowercase__ :   int    					=				self.image_processor_tester.get_expected_values(lowercase_  )

       self.assertEqual(
           encoded_images.shape	,						(1, self.image_processor_tester.num_channels, expected_height, expected_width)	,						)

       # Test batched
       lowercase__ :   Union[str, Any]    					=				image_processing(lowercase_	,						return_tensors="pt"  ).pixel_values

       lowercase__					,   lowercase__ :   Tuple    					=				self.image_processor_tester.get_expected_values(lowercase_	,						batched=lowercase_  )

       self.assertEqual(
           encoded_images.shape	,						(
               self.image_processor_tester.batch_size,
               self.image_processor_tester.num_channels,
               expected_height,
               expected_width,
           )	,						)






   @slow
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Tuple:
       # prepare image and target
       lowercase__ :   List[str]    					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
       with open("./tests/fixtures/tests_samples/COCO/coco_annotations.txt"	,						"r"  ) as f:
           lowercase__ :   List[Any]    					=				json.loads(f.read()  )

       lowercase__ :   Dict    					=				{"image_id": 3_97_69, "annotations": target}

       # encode them
       lowercase__ :   List[str]    					=				DeformableDetrImageProcessor()
       lowercase__ :   Optional[int]    					=				image_processing(images=lowercase_	,						annotations=lowercase_	,						return_tensors="pt"  )

       # verify pixel values
       lowercase__ :   Union[str, Any]    					=				torch.Size([1, 3, 8_00, 10_66]  )
       self.assertEqual(encoding["pixel_values"].shape	,						lowercase_  )

       lowercase__ :   Dict    					=				torch.tensor([0.27_96, 0.31_38, 0.34_81]  )
       self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]	,						lowercase_	,						atol=1E-4  )  )

       # verify area
       lowercase__ :   Union[str, Any]    					=				torch.tensor([58_87.96_00, 1_12_50.20_61, 48_93_53.84_38, 83_71_22.75_00, 14_79_67.51_56, 16_57_32.34_38]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["area"]	,						lowercase_  )  )
       # verify boxes
       lowercase__ :   Optional[Any]    					=				torch.Size([6, 4]  )
       self.assertEqual(encoding["labels"][0]["boxes"].shape	,						lowercase_  )
       lowercase__ :   Optional[Any]    					=				torch.tensor([0.55_03, 0.27_65, 0.06_04, 0.22_15]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]	,						lowercase_	,						atol=1E-3  )  )
       # verify image_id
       lowercase__ :   Dict    					=				torch.tensor([3_97_69]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]	,						lowercase_  )  )
       # verify is_crowd
       lowercase__ :   Optional[int]    					=				torch.tensor([0, 0, 0, 0, 0, 0]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]	,						lowercase_  )  )
       # verify class_labels
       lowercase__ :   Optional[int]    					=				torch.tensor([75, 75, 63, 65, 17, 17]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]	,						lowercase_  )  )
       # verify orig_size
       lowercase__ :   Tuple    					=				torch.tensor([4_80, 6_40]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]	,						lowercase_  )  )
       # verify size
       lowercase__ :   List[str]    					=				torch.tensor([8_00, 10_66]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["size"]	,						lowercase_  )  )







   @slow
   def       __UpperCamelCase     (      self				:     str  )					->						Tuple:
       # prepare image, target and masks_path
       lowercase__ :   Union[str, Any]    					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"  )
       with open("./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt"	,						"r"  ) as f:
           lowercase__ :   Optional[Any]    					=				json.loads(f.read()  )

       lowercase__ :   Union[str, Any]    					=				{"file_name": "000000039769.png", "image_id": 3_97_69, "segments_info": target}

       lowercase__ :   Optional[int]    					=				pathlib.Path("./tests/fixtures/tests_samples/COCO/coco_panoptic"  )

       # encode them
       lowercase__ :   Dict    					=				DeformableDetrImageProcessor(format="coco_panoptic"  )
       lowercase__ :   Optional[Any]    					=				image_processing(images=lowercase_	,						annotations=lowercase_	,						masks_path=lowercase_	,						return_tensors="pt"  )

       # verify pixel values
       lowercase__ :   Tuple    					=				torch.Size([1, 3, 8_00, 10_66]  )
       self.assertEqual(encoding["pixel_values"].shape	,						lowercase_  )

       lowercase__ :   int    					=				torch.tensor([0.27_96, 0.31_38, 0.34_81]  )
       self.assertTrue(torch.allclose(encoding["pixel_values"][0, 0, 0, :3]	,						lowercase_	,						atol=1E-4  )  )

       # verify area
       lowercase__ :   Tuple    					=				torch.tensor([14_79_79.68_75, 16_55_27.04_69, 48_46_38.59_38, 1_12_92.93_75, 58_79.65_62, 76_34.11_47]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["area"]	,						lowercase_  )  )
       # verify boxes
       lowercase__ :   Tuple    					=				torch.Size([6, 4]  )
       self.assertEqual(encoding["labels"][0]["boxes"].shape	,						lowercase_  )
       lowercase__ :   Dict    					=				torch.tensor([0.26_25, 0.54_37, 0.46_88, 0.86_25]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["boxes"][0]	,						lowercase_	,						atol=1E-3  )  )
       # verify image_id
       lowercase__ :   List[str]    					=				torch.tensor([3_97_69]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["image_id"]	,						lowercase_  )  )
       # verify is_crowd
       lowercase__ :   Optional[int]    					=				torch.tensor([0, 0, 0, 0, 0, 0]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["iscrowd"]	,						lowercase_  )  )
       # verify class_labels
       lowercase__ :   Any    					=				torch.tensor([17, 17, 63, 75, 75, 93]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["class_labels"]	,						lowercase_  )  )
       # verify masks
       lowercase__ :   str    					=				82_28_73
       self.assertEqual(encoding["labels"][0]["masks"].sum().item()	,						lowercase_  )
       # verify orig_size
       lowercase__ :   Dict    					=				torch.tensor([4_80, 6_40]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["orig_size"]	,						lowercase_  )  )
       # verify size
       lowercase__ :   str    					=				torch.tensor([8_00, 10_66]  )
       self.assertTrue(torch.allclose(encoding["labels"][0]["size"]	,						lowercase_  )  )






"""simple docstring"""





import unittest

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

from .test_pipelines_common import ANY


if is_vision_available():
   from PIL import Image

   from transformers.image_utils import load_image
else:




   class 					_lowerCAmelCase  :







    """simple docstring"""







    @staticmethod
    def 					_lowercase (			*UpperCAmelCase__							:			Tuple,					**UpperCAmelCase__							:			List[Any]	):
       pass







   def   _A  (  UpperCamelCase_     :       Union[str, Any])	->						Any:
      '''simple docstring'''


      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"""







 __UpperCAmelCase	:					Tuple   		=	MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING


 @require_pytesseract
 @require_vision
 def 					_lowercase (			self							:			Optional[Any],					UpperCAmelCase__							:			Optional[Any],					UpperCAmelCase__							:			Dict,					UpperCAmelCase__							:			Optional[Any]	):
    __lowercase								=						pipeline(
        "document-question-answering",					model=UpperCAmelCase__,					tokenizer=UpperCAmelCase__,					image_processor=UpperCAmelCase__	)

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


 def 					_lowercase (			self							:			int,					UpperCAmelCase__							:			Tuple,					UpperCAmelCase__							:			Any	):
    __lowercase								=						dqa_pipeline(UpperCAmelCase__,					top_k=2	)
    self.assertEqual(
        UpperCAmelCase__,					[
            [
                {"score": ANY(UpperCAmelCase__	), "answer": ANY(UpperCAmelCase__	), "start": ANY(UpperCAmelCase__	), "end": ANY(UpperCAmelCase__	)},
                {"score": ANY(UpperCAmelCase__	), "answer": ANY(UpperCAmelCase__	), "start": ANY(UpperCAmelCase__	), "end": ANY(UpperCAmelCase__	)},
            ]
        ]
        * 3,					)


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

    __lowercase								=						[
        {"score": 0.0_001, "answer": "oy 2312/2019", "start": 3_8, "end": 3_9},
        {"score": 0.0_001, "answer": "oy 2312/2019 DUE", "start": 3_8, "end": 4_0},
    ]
    __lowercase								=						dqa_pipeline(image=UpperCAmelCase__,					question=UpperCAmelCase__,					top_k=2	)
    self.assertEqual(nested_simplify(UpperCAmelCase__,					decimals=4	),					UpperCAmelCase__	)

    __lowercase								=						dqa_pipeline({"image": image, "question": question},					top_k=2	)
    self.assertEqual(nested_simplify(UpperCAmelCase__,					decimals=4	),					UpperCAmelCase__	)

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

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


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

    __lowercase								=						dqa_pipeline(image=UpperCAmelCase__,					question=UpperCAmelCase__,					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.9_944, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.0_009, "answer": "us-001", "start": 1_6, "end": 1_6},
        ],					)

    __lowercase								=						dqa_pipeline({"image": image, "question": question},					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.9_944, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.0_009, "answer": "us-001", "start": 1_6, "end": 1_6},
        ],					)

    __lowercase								=						dqa_pipeline(
        [{"image": image, "question": question}, {"image": image, "question": question}],					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            [
                {"score": 0.9_944, "answer": "us-001", "start": 1_6, "end": 1_6},
                {"score": 0.0_009, "answer": "us-001", "start": 1_6, "end": 1_6},
            ],
        ]
        * 2,					)


 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						pipeline(
        "document-question-answering",					model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa",					revision="9977165",					max_seq_len=5_0,					)
    __lowercase								=						INVOICE_URL
    __lowercase								=						"What is the invoice number?"

    __lowercase								=						dqa_pipeline(image=UpperCAmelCase__,					question=UpperCAmelCase__,					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.9_974, "answer": "1110212019", "start": 2_3, "end": 2_3},
            {"score": 0.9_948, "answer": "us-001", "start": 1_6, "end": 1_6},
        ],					)

    __lowercase								=						dqa_pipeline({"image": image, "question": question},					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.9_974, "answer": "1110212019", "start": 2_3, "end": 2_3},
            {"score": 0.9_948, "answer": "us-001", "start": 1_6, "end": 1_6},
        ],					)

    __lowercase								=						dqa_pipeline(
        [{"image": image, "question": question}, {"image": image, "question": question}],					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            [
                {"score": 0.9_974, "answer": "1110212019", "start": 2_3, "end": 2_3},
                {"score": 0.9_948, "answer": "us-001", "start": 1_6, "end": 1_6},
            ]
        ]
        * 2,					)


 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 					_lowercase (			self							:			Optional[Any]	):
    __lowercase								=						AutoTokenizer.from_pretrained(
        "impira/layoutlm-document-qa",					revision="3dc6de3",					add_prefix_space=UpperCAmelCase__	)
    __lowercase								=						pipeline(
        "document-question-answering",					model="impira/layoutlm-document-qa",					tokenizer=UpperCAmelCase__,					revision="3dc6de3",					)
    __lowercase								=						INVOICE_URL
    __lowercase								=						"What is the invoice number?"

    __lowercase								=						dqa_pipeline(image=UpperCAmelCase__,					question=UpperCAmelCase__,					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.4_251, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.0_819, "answer": "1110212019", "start": 2_3, "end": 2_3},
        ],					)

    __lowercase								=						dqa_pipeline({"image": image, "question": question},					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.4_251, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.0_819, "answer": "1110212019", "start": 2_3, "end": 2_3},
        ],					)

    __lowercase								=						dqa_pipeline(
        [{"image": image, "question": question}, {"image": image, "question": question}],					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            [
                {"score": 0.4_251, "answer": "us-001", "start": 1_6, "end": 1_6},
                {"score": 0.0_819, "answer": "1110212019", "start": 2_3, "end": 2_3},
            ]
        ]
        * 2,					)

    __lowercase								=						list(zip(*apply_tesseract(load_image(UpperCAmelCase__	),					UpperCAmelCase__,					""	)	)	)

    # This model should also work if `image` is set to None
    __lowercase								=						dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question},					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.4_251, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.0_819, "answer": "1110212019", "start": 2_3, "end": 2_3},
        ],					)


 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 					_lowercase (			self							:			Union[str, Any]	):
    __lowercase								=						AutoTokenizer.from_pretrained(
        "impira/layoutlm-document-qa",					revision="3dc6de3",					add_prefix_space=UpperCAmelCase__	)
    __lowercase								=						pipeline(
        "document-question-answering",					model="impira/layoutlm-document-qa",					tokenizer=UpperCAmelCase__,					revision="3dc6de3",					max_seq_len=5_0,					)
    __lowercase								=						INVOICE_URL
    __lowercase								=						"What is the invoice number?"

    __lowercase								=						dqa_pipeline(image=UpperCAmelCase__,					question=UpperCAmelCase__,					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.9_999, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.9_998, "answer": "us-001", "start": 1_6, "end": 1_6},
        ],					)

    __lowercase								=						dqa_pipeline(
        [{"image": image, "question": question}, {"image": image, "question": question}],					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            [
                {"score": 0.9_999, "answer": "us-001", "start": 1_6, "end": 1_6},
                {"score": 0.9_998, "answer": "us-001", "start": 1_6, "end": 1_6},
            ]
        ]
        * 2,					)

    __lowercase								=						list(zip(*apply_tesseract(load_image(UpperCAmelCase__	),					UpperCAmelCase__,					""	)	)	)

    # This model should also work if `image` is set to None
    __lowercase								=						dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question},					top_k=2	)
    self.assertEqual(
        nested_simplify(UpperCAmelCase__,					decimals=4	),					[
            {"score": 0.9_999, "answer": "us-001", "start": 1_6, "end": 1_6},
            {"score": 0.9_998, "answer": "us-001", "start": 1_6, "end": 1_6},
        ],					)


 @slow
 @require_torch
 def 					_lowercase (			self							:			Dict	):
    __lowercase								=						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								=						INVOICE_URL
    __lowercase								=						"What is the invoice number?"
    __lowercase								=						dqa_pipeline(image=UpperCAmelCase__,					question=UpperCAmelCase__,					top_k=2	)
    self.assertEqual(nested_simplify(UpperCAmelCase__,					decimals=4	),					[{"answer": "us-001"}]	)



 @require_tf
 @unittest.skip("Document question answering not implemented in TF"	)
 def 					_lowercase (			self							:			List[Any]	):
    pass




