



"""simple docstring"""


import unittest

from transformers import DebertaVaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch

					from transformers import (
					    DebertaVaForMaskedLM,
					    DebertaVaForMultipleChoice,
					    DebertaVaForQuestionAnswering,
					    DebertaVaForSequenceClassification,
					    DebertaVaForTokenClassification,
					    DebertaVaModel,
					)
					from transformers.models.deberta_va.modeling_deberta_va import DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST
class 			_a (					lowerCAmelCase):
			"""simple docstring"""



			def __init__(		self     :    Optional[int]				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    List[str]=1_3				,   __UpperCamelCase     :    str=7				,   __UpperCamelCase     :    Any=True				,   __UpperCamelCase     :    Optional[Any]=True				,   __UpperCamelCase     :    Optional[Any]=True				,   __UpperCamelCase     :    Any=True				,   __UpperCamelCase     :    Optional[int]=9_9				,   __UpperCamelCase     :    Any=3_2				,   __UpperCamelCase     :    Union[str, Any]=5				,   __UpperCamelCase     :    Dict=4				,   __UpperCamelCase     :    Union[str, Any]=3_7				,   __UpperCamelCase     :    List[Any]="gelu"				,   __UpperCamelCase     :    str=0.1				,   __UpperCamelCase     :    List[Any]=0.1				,   __UpperCamelCase     :    List[Any]=5_1_2				,   __UpperCamelCase     :    str=1_6				,   __UpperCamelCase     :    Union[str, Any]=2				,   __UpperCamelCase     :    List[Any]=0.0_2				,   __UpperCamelCase     :    int=False				,   __UpperCamelCase     :    Union[str, Any]=True				,   __UpperCamelCase     :    Tuple="None"				,   __UpperCamelCase     :    Any=3				,   __UpperCamelCase     :    Any=4				,   __UpperCamelCase     :    int=None				,   )->Optional[int]:
							_UpperCAmelCase					=    parent
							_UpperCAmelCase					=    batch_size
							_UpperCAmelCase					=    seq_length
							_UpperCAmelCase					=    is_training
							_UpperCAmelCase					=    use_input_mask
							_UpperCAmelCase					=    use_token_type_ids
							_UpperCAmelCase					=    use_labels
							_UpperCAmelCase					=    vocab_size
							_UpperCAmelCase					=    hidden_size
							_UpperCAmelCase					=    num_hidden_layers
							_UpperCAmelCase					=    num_attention_heads
							_UpperCAmelCase					=    intermediate_size
							_UpperCAmelCase					=    hidden_act
							_UpperCAmelCase					=    hidden_dropout_prob
							_UpperCAmelCase					=    attention_probs_dropout_prob
							_UpperCAmelCase					=    max_position_embeddings
							_UpperCAmelCase					=    type_vocab_size
							_UpperCAmelCase					=    type_sequence_label_size
							_UpperCAmelCase					=    initializer_range
							_UpperCAmelCase					=    num_labels
							_UpperCAmelCase					=    num_choices
							_UpperCAmelCase					=    relative_attention
							_UpperCAmelCase					=    position_biased_input
							_UpperCAmelCase					=    pos_att_type
							_UpperCAmelCase					=    scope



			def  lowercase__						(		self     :    Optional[int]   )->int:
							_UpperCAmelCase					=    ids_tensor([self.batch_size, self.seq_length]				,   self.vocab_size   )

							_UpperCAmelCase					=    None
							if self.use_input_mask:
											_UpperCAmelCase					=    ids_tensor([self.batch_size, self.seq_length]				,   vocab_size=2   )

							_UpperCAmelCase					=    None
							if self.use_token_type_ids:
											_UpperCAmelCase					=    ids_tensor([self.batch_size, self.seq_length]				,   self.type_vocab_size   )

							_UpperCAmelCase					=    None
							_UpperCAmelCase					=    None
							_UpperCAmelCase					=    None
							if self.use_labels:
											_UpperCAmelCase					=    ids_tensor([self.batch_size]				,   self.type_sequence_label_size   )
											_UpperCAmelCase					=    ids_tensor([self.batch_size, self.seq_length]				,   self.num_labels   )
											_UpperCAmelCase					=    ids_tensor([self.batch_size]				,   self.num_choices   )

							_UpperCAmelCase					=    self.get_config()

							return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



			def  lowercase__						(		self     :    Any   )->Dict:
							return DebertaVaConfig(
							    vocab_size=self.vocab_size				,   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				,   max_position_embeddings=self.max_position_embeddings				,   type_vocab_size=self.type_vocab_size				,   initializer_range=self.initializer_range				,   relative_attention=self.relative_attention				,   position_biased_input=self.position_biased_input				,   pos_att_type=self.pos_att_type				,   )



			def  lowercase__						(		self     :    List[str]				,   __UpperCamelCase     :    Dict   )->Union[str, Any]:
							self.parent.assertListEqual(list(result.loss.size()   )				,   []   )



			def  lowercase__						(		self     :    Union[str, Any]				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    List[str]				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Optional[Any]   )->Tuple:
							_UpperCAmelCase					=    DebertaVaModel(config=__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(__UpperCamelCase				,   attention_mask=__UpperCamelCase				,   token_type_ids=__UpperCamelCase   )[0]
							_UpperCAmelCase					=    model(__UpperCamelCase				,   token_type_ids=__UpperCamelCase   )[0]
							_UpperCAmelCase					=    model(__UpperCamelCase   )[0]

							self.parent.assertListEqual(list(sequence_output.size()   )				,   [self.batch_size, self.seq_length, self.hidden_size]   )



			def  lowercase__						(		self     :    List[Any]				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    List[Any]				,   __UpperCamelCase     :    Optional[Any]				,   __UpperCamelCase     :    Optional[Any]   )->Tuple:
							_UpperCAmelCase					=    DebertaVaForMaskedLM(config=__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(__UpperCamelCase				,   attention_mask=__UpperCamelCase				,   token_type_ids=__UpperCamelCase				,   labels=__UpperCamelCase   )

							self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.seq_length, self.vocab_size)   )



			def  lowercase__						(		self     :    str				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    List[Any]				,   __UpperCamelCase     :    List[str]   )->str:
							_UpperCAmelCase					=    self.num_labels
							_UpperCAmelCase					=    DebertaVaForSequenceClassification(__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(__UpperCamelCase				,   attention_mask=__UpperCamelCase				,   token_type_ids=__UpperCamelCase				,   labels=__UpperCamelCase   )
							self.parent.assertListEqual(list(result.logits.size()   )				,   [self.batch_size, self.num_labels]   )
							self.check_loss_output(__UpperCamelCase   )



			def  lowercase__						(		self     :    List[Any]				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    int				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    List[str]				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    List[Any]   )->Dict:
							_UpperCAmelCase					=    self.num_labels
							_UpperCAmelCase					=    DebertaVaForTokenClassification(config=__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(__UpperCamelCase				,   attention_mask=__UpperCamelCase				,   token_type_ids=__UpperCamelCase				,   labels=__UpperCamelCase   )
							self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.seq_length, self.num_labels)   )



			def  lowercase__						(		self     :    int				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    str				,   __UpperCamelCase     :    str   )->Dict:
							_UpperCAmelCase					=    DebertaVaForQuestionAnswering(config=__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    model(
							    __UpperCamelCase				,   attention_mask=__UpperCamelCase				,   token_type_ids=__UpperCamelCase				,   start_positions=__UpperCamelCase				,   end_positions=__UpperCamelCase				,   )
							self.parent.assertEqual(result.start_logits.shape				,   (self.batch_size, self.seq_length)   )
							self.parent.assertEqual(result.end_logits.shape				,   (self.batch_size, self.seq_length)   )



			def  lowercase__						(		self     :    Union[str, Any]				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    Optional[int]				,   __UpperCamelCase     :    Optional[Any]				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    Union[str, Any]				,   __UpperCamelCase     :    List[Any]				,   __UpperCamelCase     :    Optional[int]   )->Tuple:
							_UpperCAmelCase					=    DebertaVaForMultipleChoice(config=__UpperCamelCase   )
							model.to(__UpperCamelCase   )
							model.eval()
							_UpperCAmelCase					=    input_ids.unsqueeze(1   ).expand(-1				,   self.num_choices				,   -1   ).contiguous()
							_UpperCAmelCase					=    token_type_ids.unsqueeze(1   ).expand(-1				,   self.num_choices				,   -1   ).contiguous()
							_UpperCAmelCase					=    input_mask.unsqueeze(1   ).expand(-1				,   self.num_choices				,   -1   ).contiguous()
							_UpperCAmelCase					=    model(
							    __UpperCamelCase				,   attention_mask=__UpperCamelCase				,   token_type_ids=__UpperCamelCase				,   labels=__UpperCamelCase				,   )
							self.parent.assertEqual(result.logits.shape				,   (self.batch_size, self.num_choices)   )



			def  lowercase__						(		self     :    Any   )->List[str]:
							_UpperCAmelCase					=    self.prepare_config_and_inputs()
							(
							    (
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						(
							    _UpperCAmelCase
							)		,						
							)					=    config_and_inputs
							_UpperCAmelCase					=    {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
							return config, inputs_dict



@require_torch
class 			_a (					lowerCAmelCase			,							lowerCAmelCase			,							unittest.TestCase):
			"""simple docstring"""
			UpperCamelCase__			      =	(
			    (
			        DebertaVaModel,
			        DebertaVaForMaskedLM,
			        DebertaVaForSequenceClassification,
			        DebertaVaForTokenClassification,
			        DebertaVaForQuestionAnswering,
			        DebertaVaForMultipleChoice,
			    )
			    if is_torch_available()
			    else ()
			)
			UpperCamelCase__			      =	(
			    {
			        """feature-extraction""": DebertaVaModel,
			        """fill-mask""": DebertaVaForMaskedLM,
			        """question-answering""": DebertaVaForQuestionAnswering,
			        """text-classification""": DebertaVaForSequenceClassification,
			        """token-classification""": DebertaVaForTokenClassification,
			        """zero-shot""": DebertaVaForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase__			      =	True
			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False
			UpperCamelCase__			      =	False



			def  lowercase__						(		self     :    str   )->str:
							_UpperCAmelCase					=    DebertaVaModelTester(self   )
							_UpperCAmelCase					=    ConfigTester(self				,   config_class=__UpperCamelCase				,   hidden_size=3_7   )



			def  lowercase__						(		self     :    Any   )->List[str]:
							self.config_tester.run_common_tests()



			def  lowercase__						(		self     :    List[Any]   )->Tuple:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_model(*__UpperCamelCase   )



			def  lowercase__						(		self     :    List[Any]   )->Optional[Any]:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_sequence_classification(*__UpperCamelCase   )



			def  lowercase__						(		self     :    Tuple   )->Any:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_masked_lm(*__UpperCamelCase   )



			def  lowercase__						(		self     :    Dict   )->Optional[Any]:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_question_answering(*__UpperCamelCase   )



			def  lowercase__						(		self     :    str   )->str:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_token_classification(*__UpperCamelCase   )



			def  lowercase__						(		self     :    Optional[int]   )->Any:
							_UpperCAmelCase					=    self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_deberta_for_multiple_choice(*__UpperCamelCase   )



			@slow
			def  lowercase__						(		self     :    Union[str, Any]   )->Union[str, Any]:
							for model_name in DEBERTA_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											_UpperCAmelCase					=    DebertaVaModel.from_pretrained(__UpperCamelCase   )
											self.assertIsNotNone(__UpperCamelCase   )



@require_torch
@require_sentencepiece
@require_tokenizers
class 			_a (					unittest.TestCase):
			"""simple docstring"""



			@unittest.skip(reason='''Model not available yet'''   )
			def  lowercase__						(		self     :    int   )->Any:
							pass



			@slow
			def  lowercase__						(		self     :    Any   )->Union[str, Any]:
							_UpperCAmelCase					=    DebertaVaModel.from_pretrained('''microsoft/deberta-v2-xlarge'''   )

							_UpperCAmelCase					=    torch.tensor([[0, 3_1_4_1_4, 2_3_2, 3_2_8, 7_4_0, 1_1_4_0, 1_2_6_9_5, 6_9, 4_6_0_7_8, 1_5_8_8, 2]]   )
							_UpperCAmelCase					=    torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]   )
							with torch.no_grad():
											_UpperCAmelCase					=    model(__UpperCamelCase				,   attention_mask=__UpperCamelCase   )[0]
							# compare the actual values for a slice.
							_UpperCAmelCase					=    torch.tensor(
							    [[[0.2_3_5_6, 0.1_9_4_8, 0.0_3_6_9], [-0.1_0_6_3, 0.3_5_8_6, -0.5_1_5_2], [-0.6_3_9_9, -0.0_2_5_9, -0.2_5_2_5]]]   )
							self.assertTrue(torch.allclose(output[:, 1:4, 1:4]				,   __UpperCamelCase				,   atol=1e-4   )				,   F'{output[:, 1:4, 1: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 			_a :
								"""simple docstring"""



								@staticmethod
								def  lowercase__						(		*__UpperCamelCase     :    Dict				,   **__UpperCamelCase     :    Optional[Any]   )->List[str]:
												pass







					def  lowercase	(      _SCREAMING_SNAKE_CASE   :						Union[str, Any]				):






									'''simple docstring'''



									return None


# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
__A   :							Dict										=   (
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)
@is_pipeline_test
@require_torch
@require_vision
class 			_a (					unittest.TestCase):
			"""simple docstring"""
			UpperCamelCase__			      =	MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING



			@require_pytesseract
			@require_vision
			def  lowercase__						(		self     :    List[str]				,   __UpperCamelCase     :    Tuple				,   __UpperCamelCase     :    Any				,   __UpperCamelCase     :    str   )->Tuple:
							_UpperCAmelCase					=    pipeline(
							    '''document-question-answering'''				,   model=__UpperCamelCase				,   tokenizer=__UpperCamelCase				,   image_processor=__UpperCamelCase   )

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



			def  lowercase__						(		self     :    str				,   __UpperCamelCase     :    List[Any]				,   __UpperCamelCase     :    Optional[int]   )->Any:
							_UpperCAmelCase					=    dqa_pipeline(__UpperCamelCase				,   top_k=2   )
							self.assertEqual(
							    __UpperCamelCase				,   [
							        [
							            {'''score''': ANY(__UpperCamelCase   ), '''answer''': ANY(__UpperCamelCase   ), '''start''': ANY(__UpperCamelCase   ), '''end''': ANY(__UpperCamelCase   )},
							            {'''score''': ANY(__UpperCamelCase   ), '''answer''': ANY(__UpperCamelCase   ), '''start''': ANY(__UpperCamelCase   ), '''end''': ANY(__UpperCamelCase   )},
							        ]
							    ]
							    * 3				,   )



			@require_torch
			@require_detectrona
			@require_pytesseract
			def  lowercase__						(		self     :    str   )->Union[str, Any]:
							_UpperCAmelCase					=    pipeline('''document-question-answering'''				,   model='''hf-internal-testing/tiny-random-layoutlmv2'''   )
							_UpperCAmelCase					=    INVOICE_URL
							_UpperCAmelCase					=    '''How many cats are there?'''

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

							_UpperCAmelCase					=    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
							_UpperCAmelCase					=    '''./tests/fixtures/tests_samples/COCO/000000039769.png'''
							_UpperCAmelCase					=    dqa_pipeline(image=__UpperCamelCase				,   question=__UpperCamelCase				,   top_k=2   )
							self.assertEqual(__UpperCamelCase				,   []   )

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



			@slow
			@require_torch
			@require_detectrona
			@require_pytesseract
			def  lowercase__						(		self     :    Union[str, Any]   )->Optional[Any]:
							_UpperCAmelCase					=    pipeline(
							    '''document-question-answering'''				,   model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''				,   revision='''9977165'''				,   )
							_UpperCAmelCase					=    INVOICE_URL
							_UpperCAmelCase					=    '''What is the invoice number?'''

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							    ]				,   )

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							    ]				,   )

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							            {'''score''': 0.0_0_0_9, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							        ],
							    ]
							    * 2				,   )



			@slow
			@require_torch
			@require_detectrona
			@require_pytesseract
			def  lowercase__						(		self     :    int   )->Optional[int]:
							_UpperCAmelCase					=    pipeline(
							    '''document-question-answering'''				,   model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''				,   revision='''9977165'''				,   max_seq_len=5_0				,   )
							_UpperCAmelCase					=    INVOICE_URL
							_UpperCAmelCase					=    '''What is the invoice number?'''

							_UpperCAmelCase					=    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''': 2_3, '''end''': 2_3},
							        {'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							    ]				,   )

							_UpperCAmelCase					=    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''': 2_3, '''end''': 2_3},
							        {'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							    ]				,   )

							_UpperCAmelCase					=    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''': 2_3, '''end''': 2_3},
							            {'''score''': 0.9_9_4_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							        ]
							    ]
							    * 2				,   )



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

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
							    ]				,   )

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
							    ]				,   )

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							            {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
							        ]
							    ]
							    * 2				,   )

							_UpperCAmelCase					=    list(zip(*apply_tesseract(load_image(__UpperCamelCase   )				,   __UpperCamelCase				,   ''''''   )   )   )

							# This model should also work if `image` is set to None
							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.0_8_1_9, '''answer''': '''1110212019''', '''start''': 2_3, '''end''': 2_3},
							    ]				,   )



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

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							    ]				,   )

							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							            {'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							        ]
							    ]
							    * 2				,   )

							_UpperCAmelCase					=    list(zip(*apply_tesseract(load_image(__UpperCamelCase   )				,   __UpperCamelCase				,   ''''''   )   )   )

							# This model should also work if `image` is set to None
							_UpperCAmelCase					=    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''': 1_6, '''end''': 1_6},
							        {'''score''': 0.9_9_9_8, '''answer''': '''us-001''', '''start''': 1_6, '''end''': 1_6},
							    ]				,   )



			@slow
			@require_torch
			def  lowercase__						(		self     :    int   )->str:
							_UpperCAmelCase					=    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'''				,   )

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



			@require_tf
			@unittest.skip('''Document question answering not implemented in TF'''   )
			def  lowercase__						(		self     :    Tuple   )->Union[str, Any]:
							pass



