





import inspect
import unittest

from transformers import MobileViTConfig
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_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 MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
     from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import MobileViTImageProcessor



class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''

 def 				SCREAMING_SNAKE_CASE_   (self							:  Tuple)			->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__: List[str]         =self.config_class(**self.inputs_dict)
   self.parent.assertTrue(hasattr(UpperCAmelCase_			,					"hidden_sizes"))
   self.parent.assertTrue(hasattr(UpperCAmelCase_			,					"neck_hidden_sizes"))
   self.parent.assertTrue(hasattr(UpperCAmelCase_			,					"num_attention_heads"))



class   _SCREAMING_SNAKE_CASE		:







 '''simple docstring'''

 def __init__(self							:  Dict			,					UpperCAmelCase_							:  Any			,					UpperCAmelCase_							:  List[Any]=13			,					UpperCAmelCase_							:  Optional[int]=32			,					UpperCAmelCase_							:  Optional[int]=2			,					UpperCAmelCase_							:  Any=3			,					UpperCAmelCase_							:  int=640			,					UpperCAmelCase_							:  str=4			,					UpperCAmelCase_							:  Dict="silu"			,					UpperCAmelCase_							:  Dict=3			,					UpperCAmelCase_							:  Union[str, Any]=32			,					UpperCAmelCase_							:  int=0.1			,					UpperCAmelCase_							:  Tuple=0.1			,					UpperCAmelCase_							:  Any=0.1			,					UpperCAmelCase_							:  str=0.02			,					UpperCAmelCase_							:  List[str]=True			,					UpperCAmelCase_							:  List[str]=True			,					UpperCAmelCase_							:  Optional[Any]=10			,					UpperCAmelCase_							:  Union[str, Any]=None			,					)			->Dict:



   '''simple docstring'''



   lowerCamelCase__: Optional[int]         =parent
   lowerCamelCase__: int         =batch_size
   lowerCamelCase__: int         =image_size
   lowerCamelCase__: str         =patch_size
   lowerCamelCase__: Optional[int]         =num_channels
   lowerCamelCase__: Dict         =last_hidden_size
   lowerCamelCase__: Dict         =num_attention_heads
   lowerCamelCase__: Any         =hidden_act
   lowerCamelCase__: Union[str, Any]         =conv_kernel_size
   lowerCamelCase__: int         =output_stride
   lowerCamelCase__: Optional[int]         =hidden_dropout_prob
   lowerCamelCase__: int         =attention_probs_dropout_prob
   lowerCamelCase__: List[Any]         =classifier_dropout_prob
   lowerCamelCase__: List[Any]         =use_labels
   lowerCamelCase__: int         =is_training
   lowerCamelCase__: Any         =num_labels
   lowerCamelCase__: Any         =initializer_range
   lowerCamelCase__: Optional[int]         =scope

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[Any])			->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__: Dict         =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

   lowerCamelCase__: Optional[int]         =None
   lowerCamelCase__: int         =None
   if self.use_labels:
     lowerCamelCase__: str         =ids_tensor([self.batch_size]			,					self.num_labels)
     lowerCamelCase__: Union[str, Any]         =ids_tensor([self.batch_size, self.image_size, self.image_size]			,					self.num_labels)

   lowerCamelCase__: List[str]         =self.get_config()

   return config, pixel_values, labels, pixel_labels

 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[Any])			->Any:



   '''simple docstring'''



   return MobileViTConfig(
       image_size=self.image_size			,					patch_size=self.patch_size			,					num_channels=self.num_channels			,					num_attention_heads=self.num_attention_heads			,					hidden_act=self.hidden_act			,					conv_kernel_size=self.conv_kernel_size			,					output_stride=self.output_stride			,					hidden_dropout_prob=self.hidden_dropout_prob			,					attention_probs_dropout_prob=self.attention_probs_dropout_prob			,					classifier_dropout_prob=self.classifier_dropout_prob			,					initializer_range=self.initializer_range			,					)

 def 				SCREAMING_SNAKE_CASE_   (self							:  Tuple			,					UpperCAmelCase_							:  List[str]			,					UpperCAmelCase_							:  List[Any]			,					UpperCAmelCase_							:  Optional[Any]			,					UpperCAmelCase_							:  str)			->Tuple:



   '''simple docstring'''



   lowerCamelCase__: Union[str, Any]         =MobileViTModel(config=UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__: Optional[Any]         =model(UpperCAmelCase_)
   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							:  str			,					UpperCAmelCase_							:  Union[str, Any]			,					UpperCAmelCase_							:  Dict			,					UpperCAmelCase_							:  int			,					UpperCAmelCase_							:  str)			->Any:



   '''simple docstring'''



   lowerCamelCase__: Union[str, Any]         =self.num_labels
   lowerCamelCase__: Optional[int]         =MobileViTForImageClassification(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__: Union[str, Any]         =model(UpperCAmelCase_			,					labels=UpperCAmelCase_)
   self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.num_labels))

 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[Any]			,					UpperCAmelCase_							:  Union[str, Any]			,					UpperCAmelCase_							:  Dict			,					UpperCAmelCase_							:  Tuple			,					UpperCAmelCase_							:  Any)			->Any:



   '''simple docstring'''



   lowerCamelCase__: Optional[int]         =self.num_labels
   lowerCamelCase__: Union[str, Any]         =MobileViTForSemanticSegmentation(UpperCAmelCase_)
   model.to(UpperCAmelCase_)
   model.eval()
   lowerCamelCase__: str         =model(UpperCAmelCase_)
   self.parent.assertEqual(
       result.logits.shape			,					(
           self.batch_size,
           self.num_labels,
           self.image_size // self.output_stride,
           self.image_size // self.output_stride,
       )			,					)
   lowerCamelCase__: Dict         =model(UpperCAmelCase_			,					labels=UpperCAmelCase_)
   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							:  List[Any])			->List[Any]:



   '''simple docstring'''



   lowerCamelCase__: Optional[Any]         =self.prepare_config_and_inputs()
   lowerCamelCase__    ,   lowerCamelCase__    ,   lowerCamelCase__    ,   lowerCamelCase__: str         =config_and_inputs
   lowerCamelCase__: 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       ):







 '''simple docstring'''
 lowercase_						=     (
     (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
     if is_torch_available()
     else ()
 )
 lowercase_						=     (
     {
         "feature-extraction": MobileViTModel,
         "image-classification": MobileViTForImageClassification,
         "image-segmentation": MobileViTForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 lowercase_						=     False
 lowercase_						=     False
 lowercase_						=     False
 lowercase_						=     False

 def 				SCREAMING_SNAKE_CASE_   (self							:  Any)			->List[str]:



   '''simple docstring'''



   lowerCamelCase__: Optional[Any]         =MobileViTModelTester(self)
   lowerCamelCase__: Union[str, Any]         =MobileViTConfigTester(self			,					config_class=UpperCAmelCase_			,					has_text_modality=UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[Any])			->Optional[int]:



   '''simple docstring'''



   self.config_tester.run_common_tests()

 @unittest.skip(reason="MobileViT does not use inputs_embeds")
 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->str:



   '''simple docstring'''



   pass

 @unittest.skip(reason="MobileViT does not support input and output embeddings")
 def 				SCREAMING_SNAKE_CASE_   (self							:  Any)			->List[Any]:



   '''simple docstring'''



   pass

 @unittest.skip(reason="MobileViT does not output attentions")
 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[int])			->str:



   '''simple docstring'''



   pass

 def 				SCREAMING_SNAKE_CASE_   (self							:  Dict)			->List[Any]:



   '''simple docstring'''



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

   for model_class in self.all_model_classes:
     lowerCamelCase__: Tuple         =model_class(UpperCAmelCase_)
     lowerCamelCase__: int         =inspect.signature(model.forward)
     # signature.parameters is an OrderedDict => so arg_names order is deterministic
     lowerCamelCase__: Tuple         =[*signature.parameters.keys()]

     lowerCamelCase__: int         =["pixel_values"]
     self.assertListEqual(arg_names[:1]			,					UpperCAmelCase_)

 @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests.")
 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->Tuple:



   '''simple docstring'''



   pass

 def 				SCREAMING_SNAKE_CASE_   (self							:  Optional[int])			->Dict:



   '''simple docstring'''



   lowerCamelCase__: List[Any]         =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->List[Any]:



   '''simple docstring'''



   def check_hidden_states_output(UpperCAmelCase_							:  Union[str, Any]			,					UpperCAmelCase_							:  Any			,					UpperCAmelCase_							:  List[Any]):
     lowerCamelCase__: List[Any]         =model_class(UpperCAmelCase_)
     model.to(UpperCAmelCase_)
     model.eval()

     with torch.no_grad():
       lowerCamelCase__: List[Any]         =model(**self._prepare_for_class(UpperCAmelCase_			,					UpperCAmelCase_))

     lowerCamelCase__: List[str]         =outputs.hidden_states

     lowerCamelCase__: List[str]         =5
     self.assertEqual(len(UpperCAmelCase_)			,					UpperCAmelCase_)

     # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
     # with the width and height being successively divided by 2.
     lowerCamelCase__: Optional[int]         =2
     for i in range(len(UpperCAmelCase_)):
       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)

   lowerCamelCase__    ,   lowerCamelCase__: Dict         =self.model_tester.prepare_config_and_inputs_for_common()

   for model_class in self.all_model_classes:
     lowerCamelCase__: List[Any]         =True
     check_hidden_states_output(UpperCAmelCase_			,					UpperCAmelCase_			,					UpperCAmelCase_)

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

     check_hidden_states_output(UpperCAmelCase_			,					UpperCAmelCase_			,					UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[str])			->Optional[int]:



   '''simple docstring'''



   lowerCamelCase__: List[Any]         =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_)

 def 				SCREAMING_SNAKE_CASE_   (self							:  List[Any])			->Optional[Any]:



   '''simple docstring'''



   lowerCamelCase__: Any         =self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase_)







 @slow
 def 				SCREAMING_SNAKE_CASE_   (self							:  int)			->int:



   '''simple docstring'''



   for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     lowerCamelCase__: int         =MobileViTModel.from_pretrained(UpperCAmelCase_)
     self.assertIsNotNone(UpperCAmelCase_)





def 	lowerCAmelCase_					(			)	->						Optional[Any]:







  """simple docstring"""





  lowerCamelCase__: List[Any]         =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
  return image






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







 '''simple docstring'''

 @cached_property
 def 				SCREAMING_SNAKE_CASE_   (self							:  Union[str, Any])			->Any:



   '''simple docstring'''



   return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small") if is_vision_available() else None

 @slow
 def 				SCREAMING_SNAKE_CASE_   (self							:  Any)			->Any:



   '''simple docstring'''



   lowerCamelCase__: Optional[int]         =MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small").to(UpperCAmelCase_)

   lowerCamelCase__: Optional[int]         =self.default_image_processor
   lowerCamelCase__: str         =prepare_img()
   lowerCamelCase__: Dict         =image_processor(images=UpperCAmelCase_			,					return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__: Union[str, Any]         =model(**UpperCAmelCase_)

   # verify the logits
   lowerCamelCase__: Union[str, Any]         =torch.Size((1, 1_000))
   self.assertEqual(outputs.logits.shape			,					UpperCAmelCase_)

   lowerCamelCase__: Union[str, Any]         =torch.tensor([-1.9364, -1.2327, -0.4653]).to(UpperCAmelCase_)

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

 @slow
 def 				SCREAMING_SNAKE_CASE_   (self							:  str)			->List[Any]:



   '''simple docstring'''



   lowerCamelCase__: Union[str, Any]         =MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")
   lowerCamelCase__: str         =model.to(UpperCAmelCase_)

   lowerCamelCase__: Optional[Any]         =MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

   lowerCamelCase__: Optional[Any]         =prepare_img()
   lowerCamelCase__: List[str]         =image_processor(images=UpperCAmelCase_			,					return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__: List[str]         =model(**UpperCAmelCase_)
   lowerCamelCase__: Tuple         =outputs.logits

   # verify the logits
   lowerCamelCase__: int         =torch.Size((1, 21, 32, 32))
   self.assertEqual(logits.shape			,					UpperCAmelCase_)

   lowerCamelCase__: Any         =torch.tensor(
       [
           [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
           [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
           [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
       ]			,					device=UpperCAmelCase_			,					)

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







 @slow
 def 				SCREAMING_SNAKE_CASE_   (self							:  Any)			->Union[str, Any]:



   '''simple docstring'''



   lowerCamelCase__: int         =MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small")
   lowerCamelCase__: Dict         =model.to(UpperCAmelCase_)

   lowerCamelCase__: Optional[Any]         =MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small")

   lowerCamelCase__: str         =prepare_img()
   lowerCamelCase__: List[Any]         =image_processor(images=UpperCAmelCase_			,					return_tensors="pt").to(UpperCAmelCase_)

   # forward pass
   with torch.no_grad():
     lowerCamelCase__: Union[str, Any]         =model(**UpperCAmelCase_)

   lowerCamelCase__: Optional[Any]         =outputs.logits.detach().cpu()

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

   lowerCamelCase__: Optional[Any]         =image_processor.post_process_semantic_segmentation(outputs=UpperCAmelCase_)
   lowerCamelCase__: int         =torch.Size((32, 32))
   self.assertEqual(segmentation[0].shape			,					UpperCAmelCase_)








'''simple docstring'''

import unittest

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

from .test_pipelines_common import ANY


if is_vision_available():
  from PIL import Image

  from transformers.image_utils import load_image
else:






  class   UpperCAmelCase      :
   @staticmethod
   def 	UpperCAmelCase_				(							*lowercase_ :Optional[Any]		,			**lowercase_ :List[Any]				)->				Optional[int]:
       pass





  def 		UpperCamelCase							(				_lowerCamelCase   :   List[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				:      int						      =(
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)






@is_pipeline_test
@require_torch
@require_vision
class   UpperCAmelCase      (			unittest.TestCase							):
 __lowercase  						=							MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
 @require_pytesseract
 @require_vision
 def 	UpperCAmelCase_				(							self :int		,			lowercase_ :Optional[Any]		,			lowercase_ :Optional[Any]		,			lowercase_ :Dict				)->				int:
     A__							=     pipeline(
         "document-question-answering"		,			model=lowercase_		,			tokenizer=lowercase_		,			image_processor=lowercase_				)

     A__							=     INVOICE_URL
     A__							=     list(zip(*apply_tesseract(load_image(lowercase_				)		,			lowercase_		,			""				)				)				)
     A__							=     "What is the placebo?"
     A__							=     [
         {
             "image": load_image(lowercase_				),
             "question": question,
         },
         {
             "image": image,
             "question": question,
         },
         {
             "image": image,
             "question": question,
             "word_boxes": word_boxes,
         },
     ]
     return dqa_pipeline, examples
 def 	UpperCAmelCase_				(							self :str		,			lowercase_ :List[Any]		,			lowercase_ :List[str]				)->				List[str]:
     A__							=     dqa_pipeline(lowercase_		,			top_k=2				)
     self.assertEqual(
         lowercase_		,			[
             [
                 {"score": ANY(lowercase_				), "answer": ANY(lowercase_				), "start": ANY(lowercase_				), "end": ANY(lowercase_				)},
                 {"score": ANY(lowercase_				), "answer": ANY(lowercase_				), "start": ANY(lowercase_				), "end": ANY(lowercase_				)},
             ]
         ]
         * 3		,			)
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 	UpperCAmelCase_				(							self :Dict				)->				Optional[Any]:
     A__							=     pipeline("document-question-answering"		,			model="hf-internal-testing/tiny-random-layoutlmv2"				)
     A__							=     INVOICE_URL
     A__							=     "How many cats are there?"

     A__							=     [
         {"score": 0.0_0_0_1, "answer": "oy 2312/2019", "start": 38, "end": 39},
         {"score": 0.0_0_0_1, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
     ]
     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(nested_simplify(lowercase_		,			decimals=4				)		,			lowercase_				)

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

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

     # We can optionnally pass directly the words and bounding boxes
     A__							=     "./tests/fixtures/tests_samples/COCO/000000039769.png"
     A__							=     []
     A__							=     []
     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			words=lowercase_		,			boxes=lowercase_		,			top_k=2				)
     self.assertEqual(lowercase_		,			[]				)
 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 	UpperCAmelCase_				(							self :Optional[Any]				)->				Tuple:
     A__							=     pipeline(
         "document-question-answering"		,			model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"		,			revision="9977165"		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.9_9_4_4, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.0_0_0_9, "answer": "us-001", "start": 16, "end": 16},
         ]		,			)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.9_9_4_4, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.0_0_0_9, "answer": "us-001", "start": 16, "end": 16},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             [
                 {"score": 0.9_9_4_4, "answer": "us-001", "start": 16, "end": 16},
                 {"score": 0.0_0_0_9, "answer": "us-001", "start": 16, "end": 16},
             ],
         ]
         * 2		,			)
 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 	UpperCAmelCase_				(							self :Tuple				)->				Optional[Any]:
     A__							=     pipeline(
         "document-question-answering"		,			model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"		,			revision="9977165"		,			max_seq_len=50		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.9_9_7_4, "answer": "1110212019", "start": 23, "end": 23},
             {"score": 0.9_9_4_8, "answer": "us-001", "start": 16, "end": 16},
         ]		,			)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.9_9_7_4, "answer": "1110212019", "start": 23, "end": 23},
             {"score": 0.9_9_4_8, "answer": "us-001", "start": 16, "end": 16},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             [
                 {"score": 0.9_9_7_4, "answer": "1110212019", "start": 23, "end": 23},
                 {"score": 0.9_9_4_8, "answer": "us-001", "start": 16, "end": 16},
             ]
         ]
         * 2		,			)
 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 	UpperCAmelCase_				(							self :List[Any]				)->				Any:
     A__							=     AutoTokenizer.from_pretrained(
         "impira/layoutlm-document-qa"		,			revision="3dc6de3"		,			add_prefix_space=lowercase_				)
     A__							=     pipeline(
         "document-question-answering"		,			model="impira/layoutlm-document-qa"		,			tokenizer=lowercase_		,			revision="3dc6de3"		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
         ]		,			)

     A__							=     dqa_pipeline({"image": image, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             [
                 {"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
                 {"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
             ]
         ]
         * 2		,			)

     A__							=     list(zip(*apply_tesseract(load_image(lowercase_				)		,			lowercase_		,			""				)				)				)

     # This model should also work if `image` is set to None
     A__							=     dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
         ]		,			)
 @slow
 @require_torch
 @require_pytesseract
 @require_vision
 def 	UpperCAmelCase_				(							self :Optional[int]				)->				Union[str, Any]:
     A__							=     AutoTokenizer.from_pretrained(
         "impira/layoutlm-document-qa"		,			revision="3dc6de3"		,			add_prefix_space=lowercase_				)
     A__							=     pipeline(
         "document-question-answering"		,			model="impira/layoutlm-document-qa"		,			tokenizer=lowercase_		,			revision="3dc6de3"		,			max_seq_len=50		,			)
     A__							=     INVOICE_URL
     A__							=     "What is the invoice number?"

     A__							=     dqa_pipeline(image=lowercase_		,			question=lowercase_		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.9_9_9_9, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.9_9_9_8, "answer": "us-001", "start": 16, "end": 16},
         ]		,			)

     A__							=     dqa_pipeline(
         [{"image": image, "question": question}, {"image": image, "question": question}]		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             [
                 {"score": 0.9_9_9_9, "answer": "us-001", "start": 16, "end": 16},
                 {"score": 0.9_9_9_8, "answer": "us-001", "start": 16, "end": 16},
             ]
         ]
         * 2		,			)

     A__							=     list(zip(*apply_tesseract(load_image(lowercase_				)		,			lowercase_		,			""				)				)				)

     # This model should also work if `image` is set to None
     A__							=     dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question}		,			top_k=2				)
     self.assertEqual(
         nested_simplify(lowercase_		,			decimals=4				)		,			[
             {"score": 0.9_9_9_9, "answer": "us-001", "start": 16, "end": 16},
             {"score": 0.9_9_9_8, "answer": "us-001", "start": 16, "end": 16},
         ]		,			)
 @slow
 @require_torch
 def 	UpperCAmelCase_				(							self :Optional[int]				)->				Tuple:
     A__							=     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"		,			)

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



 @require_tf
 @unittest.skip("Document question answering not implemented in TF"				)
 def 	UpperCAmelCase_				(							self :Optional[Any]				)->				List[str]:
     pass



