'''simple docstring'''

import inspect
import unittest

from transformers import MobileNetVaConfig
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 MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation, MobileNetVaModel
 from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
 from PIL import Image

 from transformers import MobileNetVaImageProcessor


class     __UpperCAmelCase       ( __a		):





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.config_class(**self.inputs_dict )
     self.parent.assertTrue(hasattr(_lowerCamelCase    ,     '''tf_padding''' ) )
     self.parent.assertTrue(hasattr(_lowerCamelCase    ,     '''depth_multiplier''' ) )






class     __UpperCAmelCase       :





  def __init__(	self    ,     _lowerCamelCase    ,     _lowerCamelCase=13    ,     _lowerCamelCase=3    ,     _lowerCamelCase=32    ,     _lowerCamelCase=0.25    ,     _lowerCamelCase=8    ,     _lowerCamelCase=8    ,     _lowerCamelCase=6    ,     _lowerCamelCase=32    ,     _lowerCamelCase=True    ,     _lowerCamelCase=True    ,     _lowerCamelCase=True    ,     _lowerCamelCase="relu6"    ,     _lowerCamelCase=1280    ,     _lowerCamelCase=0.1    ,     _lowerCamelCase=0.02    ,     _lowerCamelCase=True    ,     _lowerCamelCase=True    ,     _lowerCamelCase=10    ,     _lowerCamelCase=None    ,     ):
     lowerCAmelCase_			=      parent
     lowerCAmelCase_			=      batch_size
     lowerCAmelCase_			=      num_channels
     lowerCAmelCase_			=      image_size
     lowerCAmelCase_			=      depth_multiplier
     lowerCAmelCase_			=      depth_divisible_by
     lowerCAmelCase_			=      min_depth
     lowerCAmelCase_			=      expand_ratio
     lowerCAmelCase_			=      tf_padding
     lowerCAmelCase_			=      output_stride
     lowerCAmelCase_			=      first_layer_is_expansion
     lowerCAmelCase_			=      finegrained_output
     lowerCAmelCase_			=      hidden_act
     lowerCAmelCase_			=      last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier )
     lowerCAmelCase_			=      classifier_dropout_prob
     lowerCAmelCase_			=      use_labels
     lowerCAmelCase_			=      is_training
     lowerCAmelCase_			=      num_labels
     lowerCAmelCase_			=      initializer_range
     lowerCAmelCase_			=      scope





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

     lowerCAmelCase_			=      None
     lowerCAmelCase_			=      None
     if self.use_labels:
        lowerCAmelCase_			=      ids_tensor([self.batch_size]    ,     self.num_labels )
        lowerCAmelCase_			=      ids_tensor([self.batch_size, self.image_size, self.image_size]    ,     self.num_labels )

     lowerCAmelCase_			=      self.get_config()

     return config, pixel_values, labels, pixel_labels





  def 						UpperCAmelCase_	(	self ):
     return MobileNetVaConfig(
         num_channels=self.num_channels    ,     image_size=self.image_size    ,     depth_multiplier=self.depth_multiplier    ,     depth_divisible_by=self.depth_divisible_by    ,     min_depth=self.min_depth    ,     expand_ratio=self.expand_ratio    ,     output_stride=self.output_stride    ,     first_layer_is_expansion=self.first_layer_is_expansion    ,     finegrained_output=self.finegrained_output    ,     hidden_act=self.hidden_act    ,     tf_padding=self.tf_padding    ,     classifier_dropout_prob=self.classifier_dropout_prob    ,     initializer_range=self.initializer_range    ,     )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      MobileNetVaModel(config=_lowerCamelCase )
     model.to(_lowerCamelCase )
     model.eval()
     lowerCAmelCase_			=      model(_lowerCamelCase )
     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,
         )    ,     )
     self.parent.assertEqual(
         result.pooler_output.shape    ,     (self.batch_size, self.last_hidden_size)    ,     )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      self.num_labels
     lowerCAmelCase_			=      MobileNetVaForImageClassification(_lowerCamelCase )
     model.to(_lowerCamelCase )
     model.eval()
     lowerCAmelCase_			=      model(_lowerCamelCase    ,     labels=_lowerCamelCase )
     self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels) )





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      self.num_labels
     lowerCAmelCase_			=      MobileNetVaForSemanticSegmentation(_lowerCamelCase )
     model.to(_lowerCamelCase )
     model.eval()
     lowerCAmelCase_			=      model(_lowerCamelCase )
     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_			=      model(_lowerCamelCase    ,     labels=_lowerCamelCase )
     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 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.prepare_config_and_inputs()
     lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_	,lowerCAmelCase_			=      config_and_inputs
     lowerCAmelCase_			=      {'''pixel_values''': pixel_values}
     return config, inputs_dict






@require_torch
class     __UpperCAmelCase       ( __a						,       __a						,       unittest.TestCase		):
  __A :				int											= (
      (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
      if is_torch_available()
      else ()
  )
  __A :				Tuple											= (
      {
          'feature-extraction': MobileNetVaModel,
          'image-classification': MobileNetVaForImageClassification,
          'image-segmentation': MobileNetVaForSemanticSegmentation,
      }
      if is_torch_available()
      else {}
  )

  __A :				Any											= False
  __A :				Tuple											= False
  __A :				Optional[int]											= False
  __A :				int											= False





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      MobileNetVaModelTester(self )
     lowerCAmelCase_			=      MobileNetVaConfigTester(self    ,     config_class=_lowerCamelCase    ,     has_text_modality=_lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     self.config_tester.run_common_tests()





  @unittest.skip(reason='''MobileNetV2 does not use inputs_embeds''' )
  def 						UpperCAmelCase_	(	self ):
     pass





  @unittest.skip(reason='''MobileNetV2 does not support input and output embeddings''' )
  def 						UpperCAmelCase_	(	self ):
     pass





  @unittest.skip(reason='''MobileNetV2 does not output attentions''' )
  def 						UpperCAmelCase_	(	self ):
     pass





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_	,lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCAmelCase_			=      ['''pixel_values''']
        self.assertListEqual(arg_names[:1]    ,     _lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     def check_hidden_states_output(_lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
        lowerCAmelCase_			=      model_class(_lowerCamelCase )
        model.to(_lowerCamelCase )
        model.eval()

        with torch.no_grad():
           lowerCAmelCase_			=      model(**self._prepare_for_class(_lowerCamelCase    ,     _lowerCamelCase ) )

        lowerCAmelCase_			=      outputs.hidden_states

        lowerCAmelCase_			=      16
        self.assertEqual(len(_lowerCamelCase )    ,     _lowerCamelCase )

     lowerCAmelCase_	,lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        lowerCAmelCase_			=      True
        check_hidden_states_output(_lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase )

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCAmelCase_			=      True

        check_hidden_states_output(_lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_lowerCamelCase )





  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*_lowerCamelCase )







  @slow
  def 						UpperCAmelCase_	(	self ):
     for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCAmelCase_			=      MobileNetVaModel.from_pretrained(_lowerCamelCase )
        self.assertIsNotNone(_lowerCamelCase )






def snake_case_      (					)			->					Optional[Any]:
   lowerCAmelCase_			=      Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''')
   return image






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





  @cached_property
  def 						UpperCAmelCase_	(	self ):
     return (
         MobileNetVaImageProcessor.from_pretrained('''google/mobilenet_v2_1.0_224''' ) if is_vision_available() else None
     )





  @slow
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      MobileNetVaForImageClassification.from_pretrained('''google/mobilenet_v2_1.0_224''' ).to(_lowerCamelCase )

     lowerCAmelCase_			=      self.default_image_processor
     lowerCAmelCase_			=      prepare_img()
     lowerCAmelCase_			=      image_processor(images=_lowerCamelCase    ,     return_tensors='''pt''' ).to(_lowerCamelCase )

     # forward pass
     with torch.no_grad():
        lowerCAmelCase_			=      model(**_lowerCamelCase )

     # verify the logits
     lowerCAmelCase_			=      torch.Size((1, 1001) )
     self.assertEqual(outputs.logits.shape    ,     _lowerCamelCase )

     lowerCAmelCase_			=      torch.tensor([0.24_45, -1.19_93, 0.19_05] ).to(_lowerCamelCase )

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







  @slow
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      MobileNetVaForSemanticSegmentation.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )
     lowerCAmelCase_			=      model.to(_lowerCamelCase )

     lowerCAmelCase_			=      MobileNetVaImageProcessor.from_pretrained('''google/deeplabv3_mobilenet_v2_1.0_513''' )

     lowerCAmelCase_			=      prepare_img()
     lowerCAmelCase_			=      image_processor(images=_lowerCamelCase    ,     return_tensors='''pt''' ).to(_lowerCamelCase )

     # forward pass
     with torch.no_grad():
        lowerCAmelCase_			=      model(**_lowerCamelCase )
     lowerCAmelCase_			=      outputs.logits

     # verify the logits
     lowerCAmelCase_			=      torch.Size((1, 21, 65, 65) )
     self.assertEqual(logits.shape    ,     _lowerCamelCase )

     lowerCAmelCase_			=      torch.tensor(
         [
             [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
             [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
             [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
         ]    ,     device=_lowerCamelCase    ,     )

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






'''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_	(	*_lowerCamelCase    ,     **_lowerCamelCase ):
      pass






 def snake_case_      (					__snake_case  :							int)			->					Union[str, Any]:
    return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
A_     :						Any    							=(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


@is_pipeline_test
@require_torch
@require_vision
class     __UpperCAmelCase       ( unittest.TestCase		):
  __A :				Union[str, Any]											= MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING





  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model=_lowerCamelCase    ,     tokenizer=_lowerCamelCase    ,     image_processor=_lowerCamelCase )

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





  def 						UpperCAmelCase_	(	self    ,     _lowerCamelCase    ,     _lowerCamelCase ):
     lowerCAmelCase_			=      dqa_pipeline(_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         _lowerCamelCase    ,     [
             [
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
                 {'''score''': ANY(_lowerCamelCase ), '''answer''': ANY(_lowerCamelCase ), '''start''': ANY(_lowerCamelCase ), '''end''': ANY(_lowerCamelCase )},
             ]
         ]
         * 3    ,     )





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

     lowerCAmelCase_			=      [
         {'''score''': 0.00_01, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39},
         {'''score''': 0.00_01, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40},
     ]
     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     _lowerCamelCase )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     _lowerCamelCase )

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

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





  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_44, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.00_09, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ],
         ]
         * 2    ,     )





  @slow
  @require_torch
  @require_detectrona
  @require_pytesseract
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''    ,     revision='''9977165'''    ,     max_seq_len=50    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_74, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
                 {'''score''': 0.99_48, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ]
         ]
         * 2    ,     )





  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''    ,     revision='''3dc6de3'''    ,     add_prefix_space=_lowerCamelCase )
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''impira/layoutlm-document-qa'''    ,     tokenizer=_lowerCamelCase    ,     revision='''3dc6de3'''    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline({'''image''': image, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
             ]
         ]
         * 2    ,     )

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

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.42_51, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.08_19, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
         ]    ,     )





  @slow
  @require_torch
  @require_pytesseract
  @require_vision
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      AutoTokenizer.from_pretrained(
         '''impira/layoutlm-document-qa'''    ,     revision='''3dc6de3'''    ,     add_prefix_space=_lowerCamelCase )
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''impira/layoutlm-document-qa'''    ,     tokenizer=_lowerCamelCase    ,     revision='''3dc6de3'''    ,     max_seq_len=50    ,     )
     lowerCAmelCase_			=      INVOICE_URL
     lowerCAmelCase_			=      '''What is the invoice number?'''

     lowerCAmelCase_			=      dqa_pipeline(image=_lowerCamelCase    ,     question=_lowerCamelCase    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )

     lowerCAmelCase_			=      dqa_pipeline(
         [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             [
                 {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
                 {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             ]
         ]
         * 2    ,     )

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

     # This model should also work if `image` is set to None
     lowerCAmelCase_			=      dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}    ,     top_k=2 )
     self.assertEqual(
         nested_simplify(_lowerCamelCase    ,     decimals=4 )    ,     [
             {'''score''': 0.99_99, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
             {'''score''': 0.99_98, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
         ]    ,     )





  @slow
  @require_torch
  def 						UpperCAmelCase_	(	self ):
     lowerCAmelCase_			=      pipeline(
         '''document-question-answering'''    ,     model='''naver-clova-ix/donut-base-finetuned-docvqa'''    ,     tokenizer=AutoTokenizer.from_pretrained('''naver-clova-ix/donut-base-finetuned-docvqa''' )    ,     feature_extractor='''naver-clova-ix/donut-base-finetuned-docvqa'''    ,     )

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







  @require_tf
  @unittest.skip('''Document question answering not implemented in TF''' )
  def 						UpperCAmelCase_	(	self ):
     pass





