






'''simple docstring'''



import inspect
import unittest

from transformers import YolosConfig
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
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch
       from torch import nn

       from transformers import YolosForObjectDetection, YolosModel
       from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import AutoImageProcessor
class UpperCAmelCase_					:




      """simple docstring"""




      def __init__( self			:		Dict     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		Optional[int]=13     ,      UpperCAmelCase			:		Dict=[30, 30]     ,      UpperCAmelCase			:		Tuple=2     ,      UpperCAmelCase			:		Any=3     ,      UpperCAmelCase			:		Optional[Any]=True     ,      UpperCAmelCase			:		List[Any]=True     ,      UpperCAmelCase			:		int=32     ,      UpperCAmelCase			:		Any=5     ,      UpperCAmelCase			:		Optional[Any]=4     ,      UpperCAmelCase			:		str=37     ,      UpperCAmelCase			:		Optional[Any]="gelu"     ,      UpperCAmelCase			:		str=0.1     ,      UpperCAmelCase			:		Optional[int]=0.1     ,      UpperCAmelCase			:		str=10     ,      UpperCAmelCase			:		Optional[int]=0.0_2     ,      UpperCAmelCase			:		Dict=3     ,      UpperCAmelCase			:		Union[str, Any]=None     ,      UpperCAmelCase			:		Optional[int]=8     ,      UpperCAmelCase			:		Union[str, Any]=10     ,      )  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   int				  =parent
       lowercase					:   str				  =batch_size
       lowercase					:   List[Any]				  =image_size
       lowercase					:   Tuple				  =patch_size
       lowercase					:   str				  =num_channels
       lowercase					:   int				  =is_training
       lowercase					:   Dict				  =use_labels
       lowercase					:   Dict				  =hidden_size
       lowercase					:   Any				  =num_hidden_layers
       lowercase					:   Optional[Any]				  =num_attention_heads
       lowercase					:   Optional[int]				  =intermediate_size
       lowercase					:   int				  =hidden_act
       lowercase					:   Dict				  =hidden_dropout_prob
       lowercase					:   int				  =attention_probs_dropout_prob
       lowercase					:   List[str]				  =type_sequence_label_size
       lowercase					:   Any				  =initializer_range
       lowercase					:   str				  =num_labels
       lowercase					:   str				  =scope
       lowercase					:   Dict				  =n_targets
       lowercase					:   Any				  =num_detection_tokens
       # we set the expected sequence length (which is used in several tests)
       # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
       lowercase					:   int				  =(image_size[1] // patch_size) * (image_size[0] // patch_size)
       lowercase					:   Tuple				  =num_patches + 1 + self.num_detection_tokens






      def 				A__      ( self			:		Tuple		)  ->  List[str]:


       '''simple docstring'''

       lowercase					:   List[Any]				  =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]		)

       lowercase					:   Dict				  =None
       if self.use_labels:
        # labels is a list of Dict (each Dict being the labels for a given example in the batch)
        lowercase					:   Union[str, Any]				  =[]
        for i in range(self.batch_size		):
         lowercase					:   Tuple				  ={}
         lowercase					:   str				  =torch.randint(
             high=self.num_labels     ,      size=(self.n_targets,)     ,      device=UpperCAmelCase		)
         lowercase					:   List[Any]				  =torch.rand(self.n_targets     ,      4     ,      device=UpperCAmelCase		)
         labels.append(UpperCAmelCase		)

       lowercase					:   Any				  =self.get_config()

       return config, pixel_values, labels






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


       '''simple docstring'''

       return YolosConfig(
           image_size=self.image_size     ,      patch_size=self.patch_size     ,      num_channels=self.num_channels     ,      hidden_size=self.hidden_size     ,      num_hidden_layers=self.num_hidden_layers     ,      num_attention_heads=self.num_attention_heads     ,      intermediate_size=self.intermediate_size     ,      hidden_act=self.hidden_act     ,      hidden_dropout_prob=self.hidden_dropout_prob     ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,      is_decoder=UpperCAmelCase     ,      initializer_range=self.initializer_range     ,      num_detection_tokens=self.num_detection_tokens     ,      num_labels=self.num_labels     ,      )






      def 				A__      ( self			:		str     ,      UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		List[str]		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   Optional[Any]				  =YolosModel(config=UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()
       lowercase					:   Dict				  =model(UpperCAmelCase		)
       self.parent.assertEqual(
           result.last_hidden_state.shape     ,      (self.batch_size, self.expected_seq_len, self.hidden_size)		)






      def 				A__      ( self			:		Optional[Any]     ,      UpperCAmelCase			:		List[Any]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		Dict		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Tuple				  =YolosForObjectDetection(UpperCAmelCase		)
       model.to(UpperCAmelCase		)
       model.eval()

       lowercase					:   Tuple				  =model(pixel_values=UpperCAmelCase		)
       lowercase					:   str				  =model(UpperCAmelCase		)

       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_detection_tokens, self.num_labels + 1)		)
       self.parent.assertEqual(result.pred_boxes.shape     ,      (self.batch_size, self.num_detection_tokens, 4)		)

       lowercase					:   str				  =model(pixel_values=UpperCAmelCase     ,      labels=UpperCAmelCase		)

       self.parent.assertEqual(result.loss.shape     ,      ()		)
       self.parent.assertEqual(result.logits.shape     ,      (self.batch_size, self.num_detection_tokens, self.num_labels + 1)		)
       self.parent.assertEqual(result.pred_boxes.shape     ,      (self.batch_size, self.num_detection_tokens, 4)		)






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


       '''simple docstring'''

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





@require_torch
class UpperCAmelCase_					(    __A				,       __A				,       unittest.TestCase				):




      """simple docstring"""




      UpperCamelCase_								=			(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
      UpperCamelCase_								=			(
          {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
      )

      UpperCamelCase_								=			False
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False
      UpperCamelCase_								=			False






      def 				A__      ( self			:		Union[str, Any]     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		Any     ,      UpperCAmelCase			:		int=False		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Dict				  =super()._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase     ,      return_labels=UpperCAmelCase		)

       if return_labels:
        if model_class.__name__ == "YolosForObjectDetection":
         lowercase					:   Any				  =[]
         for i in range(self.model_tester.batch_size		):
          lowercase					:   Optional[Any]				  ={}
          lowercase					:   int				  =torch.ones(
              size=(self.model_tester.n_targets,)     ,      device=UpperCAmelCase     ,      dtype=torch.long		)
          lowercase					:   Tuple				  =torch.ones(
              self.model_tester.n_targets     ,      4     ,      device=UpperCAmelCase     ,      dtype=torch.float		)
          labels.append(UpperCAmelCase		)
         lowercase					:   int				  =labels

       return inputs_dict






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


       '''simple docstring'''

       lowercase					:   List[str]				  =YolosModelTester(self		)
       lowercase					:   Optional[Any]				  =ConfigTester(self     ,      config_class=UpperCAmelCase     ,      has_text_modality=UpperCAmelCase     ,      hidden_size=37		)






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


       '''simple docstring'''

       self.config_tester.run_common_tests()






      def 				A__      ( self			:		Dict		)  ->  List[str]:


       '''simple docstring'''

       pass






      def 				A__      ( self			:		Union[str, Any]		)  ->  List[Any]:


       '''simple docstring'''

       lowercase					:   Tuple				  =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowercase					:   Optional[int]				  =model_class(UpperCAmelCase		)
        self.assertIsInstance(model.get_input_embeddings()     ,      (nn.Module)		)
        lowercase					:   List[Any]				  =model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(UpperCAmelCase     ,      nn.Linear		)		)






      def 				A__      ( self			:		List[Any]		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Any				  =self.model_tester.prepare_config_and_inputs_for_common()

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

        lowercase					:   Optional[int]				  =['''pixel_values''']
        self.assertListEqual(arg_names[:1]     ,      UpperCAmelCase		)






      def 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

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






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


       '''simple docstring'''

       lowercase					:   Tuple				  =self.model_tester.prepare_config_and_inputs_for_common()
       lowercase					:   Any				  =True

       # in YOLOS, the seq_len is different
       lowercase					:   Union[str, Any]				  =self.model_tester.expected_seq_len
       for model_class in self.all_model_classes:
        lowercase					:   Optional[int]				  =True
        lowercase					:   int				  =False
        lowercase					:   Any				  =True
        lowercase					:   Optional[Any]				  =model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()
        with torch.no_grad():
         lowercase					:   Optional[int]				  =model(**self._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase		)		)
        lowercase					:   List[Any]				  =outputs.attentions
        self.assertEqual(len(UpperCAmelCase		)     ,      self.model_tester.num_hidden_layers		)

        # check that output_attentions also work using config
        del inputs_dict["output_attentions"]
        lowercase					:   Dict				  =True
        lowercase					:   List[Any]				  =model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()
        with torch.no_grad():
         lowercase					:   List[str]				  =model(**self._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase		)		)
        lowercase					:   int				  =outputs.attentions
        self.assertEqual(len(UpperCAmelCase		)     ,      self.model_tester.num_hidden_layers		)

        self.assertListEqual(
            list(attentions[0].shape[-3:]		)     ,      [self.model_tester.num_attention_heads, seq_len, seq_len]     ,      )
        lowercase					:   Dict				  =len(UpperCAmelCase		)

        # Check attention is always last and order is fine
        lowercase					:   Optional[int]				  =True
        lowercase					:   Tuple				  =True
        lowercase					:   Dict				  =model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()
        with torch.no_grad():
         lowercase					:   Tuple				  =model(**self._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase		)		)

        lowercase					:   Optional[int]				  =1
        self.assertEqual(out_len + added_hidden_states     ,      len(UpperCAmelCase		)		)

        lowercase					:   Optional[int]				  =outputs.attentions

        self.assertEqual(len(UpperCAmelCase		)     ,      self.model_tester.num_hidden_layers		)
        self.assertListEqual(
            list(self_attentions[0].shape[-3:]		)     ,      [self.model_tester.num_attention_heads, seq_len, seq_len]     ,      )






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


       '''simple docstring'''

       def check_hidden_states_output(UpperCAmelCase			:		List[str]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		Optional[int]		):
        lowercase					:   List[Any]				  =model_class(UpperCAmelCase		)
        model.to(UpperCAmelCase		)
        model.eval()

        with torch.no_grad():
         lowercase					:   Dict				  =model(**self._prepare_for_class(UpperCAmelCase     ,      UpperCAmelCase		)		)

        lowercase					:   Optional[Any]				  =outputs.hidden_states

        lowercase					:   Any				  =getattr(
            self.model_tester     ,      '''expected_num_hidden_layers'''     ,      self.model_tester.num_hidden_layers + 1		)
        self.assertEqual(len(UpperCAmelCase		)     ,      UpperCAmelCase		)

        # YOLOS has a different seq_length
        lowercase					:   int				  =self.model_tester.expected_seq_len

        self.assertListEqual(
            list(hidden_states[0].shape[-2:]		)     ,      [seq_length, self.model_tester.hidden_size]     ,      )

       lowercase					:   int				  =self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowercase					:   Optional[Any]				  =True
        check_hidden_states_output(UpperCAmelCase     ,      UpperCAmelCase     ,      UpperCAmelCase		)

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

        check_hidden_states_output(UpperCAmelCase     ,      UpperCAmelCase     ,      UpperCAmelCase		)






      def 				A__      ( self			:		int		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   List[Any]				  =self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_object_detection(*UpperCAmelCase		)






      @slow
      def 				A__      ( self			:		Any		)  ->  int:


       '''simple docstring'''

       for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowercase					:   str				  =YolosModel.from_pretrained(UpperCAmelCase		)
        self.assertIsNotNone(UpperCAmelCase		)





def 							lowercase_				(    )       ->      List[str]:



 """simple docstring"""




 lowercase					:   Optional[int]				  =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
 return image





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




      """simple docstring"""




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


       '''simple docstring'''

       return AutoImageProcessor.from_pretrained('''hustvl/yolos-small'''		) if is_vision_available() else None






      @slow
      def 				A__      ( self			:		Tuple		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   Optional[Any]				  =YolosForObjectDetection.from_pretrained('''hustvl/yolos-small'''		).to(UpperCAmelCase		)

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

       # forward pass
       with torch.no_grad():
        lowercase					:   Optional[Any]				  =model(inputs.pixel_values		)

       # verify outputs
       lowercase					:   Dict				  =torch.Size((1, 100, 92)		)
       self.assertEqual(outputs.logits.shape     ,      UpperCAmelCase		)

       lowercase					:   Optional[int]				  =torch.tensor(
           [[-24.0248, -10.3024, -14.8290], [-42.0392, -16.8200, -27.4334], [-27.2743, -11.8154, -18.7148]]     ,      device=UpperCAmelCase     ,      )
       lowercase					:   str				  =torch.tensor(
           [[0.2_5_5_9, 0.5_4_5_5, 0.4_7_0_6], [0.2_9_8_9, 0.7_2_7_9, 0.1_8_7_5], [0.7_7_3_2, 0.4_0_1_7, 0.4_4_6_2]]     ,      device=UpperCAmelCase		)
       self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]     ,      UpperCAmelCase     ,      atol=1e-4		)		)
       self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]     ,      UpperCAmelCase     ,      atol=1e-4		)		)

       # verify postprocessing
       lowercase					:   int				  =image_processor.post_process_object_detection(
           UpperCAmelCase     ,      threshold=0.3     ,      target_sizes=[image.size[::-1]]		)[0]
       lowercase					:   Union[str, Any]				  =torch.tensor([0.9_9_9_4, 0.9_7_9_0, 0.9_9_6_4, 0.9_9_7_2, 0.9_8_6_1]		).to(UpperCAmelCase		)
       lowercase					:   List[Any]				  =[75, 75, 17, 63, 17]
       lowercase					:   Union[str, Any]				  =torch.tensor([335.0609, 79.3848, 375.4216, 187.2495]		).to(UpperCAmelCase		)

       self.assertEqual(len(results['''scores''']		)     ,      5		)
       self.assertTrue(torch.allclose(results['''scores''']     ,      UpperCAmelCase     ,      atol=1e-4		)		)
       self.assertSequenceEqual(results['''labels'''].tolist()     ,      UpperCAmelCase		)
       self.assertTrue(torch.allclose(results['''boxes'''][0, :]     ,      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_					:




            """simple docstring"""




            @staticmethod
            def 				A__      ( *UpperCAmelCase			:		Union[str, Any]     ,      **UpperCAmelCase			:		Optional[int]		)  ->  Any:


             '''simple docstring'''

             pass





      def 							lowercase_				(    __A :       Union[str, Any]			)       ->      List[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.
SCREAMING_SNAKE_CASE						=	(
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)
@is_pipeline_test
@require_torch
@require_vision
class UpperCAmelCase_					(    unittest.TestCase				):




      """simple docstring"""




      UpperCamelCase_								=			MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING






      @require_pytesseract
      @require_vision
      def 				A__      ( self			:		Union[str, Any]     ,      UpperCAmelCase			:		Dict     ,      UpperCAmelCase			:		str     ,      UpperCAmelCase			:		List[str]		)  ->  Tuple:


       '''simple docstring'''

       lowercase					:   Dict				  =pipeline(
           '''document-question-answering'''     ,      model=UpperCAmelCase     ,      tokenizer=UpperCAmelCase     ,      image_processor=UpperCAmelCase		)

       lowercase					:   Optional[Any]				  =INVOICE_URL
       lowercase					:   Any				  =list(zip(*apply_tesseract(load_image(UpperCAmelCase		)     ,      UpperCAmelCase     ,      ''''''		)		)		)
       lowercase					:   Dict				  ='''What is the placebo?'''
       lowercase					:   Optional[Any]				  =[
           {
               '''image''': load_image(UpperCAmelCase		),
               '''question''': question,
           },
           {
               '''image''': image,
               '''question''': question,
           },
           {
               '''image''': image,
               '''question''': question,
               '''word_boxes''': word_boxes,
           },
       ]
       return dqa_pipeline, examples






      def 				A__      ( self			:		Any     ,      UpperCAmelCase			:		Optional[int]     ,      UpperCAmelCase			:		int		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   Dict				  =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 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Dict				  =pipeline('''document-question-answering'''     ,      model='''hf-internal-testing/tiny-random-layoutlmv2'''		)
       lowercase					:   Union[str, Any]				  =INVOICE_URL
       lowercase					:   Tuple				  ='''How many cats are there?'''

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

       lowercase					:   List[str]				  =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					:   Optional[Any]				  ='''./tests/fixtures/tests_samples/COCO/000000039769.png'''
       lowercase					:   Any				  =dqa_pipeline(image=UpperCAmelCase     ,      question=UpperCAmelCase     ,      top_k=2		)
       self.assertEqual(UpperCAmelCase     ,      []		)

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






      @slow
      @require_torch
      @require_detectrona
      @require_pytesseract
      def 				A__      ( self			:		int		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Union[str, Any]				  =pipeline(
           '''document-question-answering'''     ,      model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''     ,      revision='''9977165'''     ,      )
       lowercase					:   Dict				  =INVOICE_URL
       lowercase					:   str				  ='''What is the invoice number?'''

       lowercase					:   List[str]				  =dqa_pipeline(image=UpperCAmelCase     ,      question=UpperCAmelCase     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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},
           ]     ,      )

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

       lowercase					:   List[Any]				  =dqa_pipeline(
           [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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 				A__      ( self			:		Dict		)  ->  List[str]:


       '''simple docstring'''

       lowercase					:   str				  =pipeline(
           '''document-question-answering'''     ,      model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''     ,      revision='''9977165'''     ,      max_seq_len=50     ,      )
       lowercase					:   Dict				  =INVOICE_URL
       lowercase					:   Any				  ='''What is the invoice number?'''

       lowercase					:   Union[str, Any]				  =dqa_pipeline(image=UpperCAmelCase     ,      question=UpperCAmelCase     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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},
           ]     ,      )

       lowercase					:   int				  =dqa_pipeline({'''image''': image, '''question''': question}     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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},
           ]     ,      )

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


       '''simple docstring'''

       lowercase					:   Any				  =AutoTokenizer.from_pretrained(
           '''impira/layoutlm-document-qa'''     ,      revision='''3dc6de3'''     ,      add_prefix_space=UpperCAmelCase		)
       lowercase					:   Tuple				  =pipeline(
           '''document-question-answering'''     ,      model='''impira/layoutlm-document-qa'''     ,      tokenizer=UpperCAmelCase     ,      revision='''3dc6de3'''     ,      )
       lowercase					:   Tuple				  =INVOICE_URL
       lowercase					:   Any				  ='''What is the invoice number?'''

       lowercase					:   Dict				  =dqa_pipeline(image=UpperCAmelCase     ,      question=UpperCAmelCase     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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},
           ]     ,      )

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

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

       lowercase					:   Tuple				  =list(zip(*apply_tesseract(load_image(UpperCAmelCase		)     ,      UpperCAmelCase     ,      ''''''		)		)		)

       # This model should also work if `image` is set to None
       lowercase					:   Dict				  =dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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 				A__      ( self			:		Dict		)  ->  Any:


       '''simple docstring'''

       lowercase					:   Dict				  =AutoTokenizer.from_pretrained(
           '''impira/layoutlm-document-qa'''     ,      revision='''3dc6de3'''     ,      add_prefix_space=UpperCAmelCase		)
       lowercase					:   List[Any]				  =pipeline(
           '''document-question-answering'''     ,      model='''impira/layoutlm-document-qa'''     ,      tokenizer=UpperCAmelCase     ,      revision='''3dc6de3'''     ,      max_seq_len=50     ,      )
       lowercase					:   str				  =INVOICE_URL
       lowercase					:   int				  ='''What is the invoice number?'''

       lowercase					:   Tuple				  =dqa_pipeline(image=UpperCAmelCase     ,      question=UpperCAmelCase     ,      top_k=2		)
       self.assertEqual(
           nested_simplify(UpperCAmelCase     ,      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},
           ]     ,      )

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

       lowercase					:   List[str]				  =list(zip(*apply_tesseract(load_image(UpperCAmelCase		)     ,      UpperCAmelCase     ,      ''''''		)		)		)

       # 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(UpperCAmelCase     ,      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 				A__      ( self			:		List[Any]		)  ->  Optional[int]:


       '''simple docstring'''

       lowercase					:   str				  =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					:   Any				  =INVOICE_URL
       lowercase					:   Union[str, Any]				  ='''What is the invoice number?'''
       lowercase					:   int				  =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 				A__      ( self			:		Any		)  ->  Any:


       '''simple docstring'''

       pass



