





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
					from ... import FeatureExtractionMixin, PreTrainedTokenizerBase, TensorType


A    :					Optional[int] =      logging.get_logger(__name__)

A    :					Any =      {
    '''microsoft/deberta-v2-xlarge''': '''https://huggingface.co/microsoft/deberta-v2-xlarge/resolve/main/config.json''',
    '''microsoft/deberta-v2-xxlarge''': '''https://huggingface.co/microsoft/deberta-v2-xxlarge/resolve/main/config.json''',
    '''microsoft/deberta-v2-xlarge-mnli''': (
        '''https://huggingface.co/microsoft/deberta-v2-xlarge-mnli/resolve/main/config.json'''
    ),
    '''microsoft/deberta-v2-xxlarge-mnli''': (
        '''https://huggingface.co/microsoft/deberta-v2-xxlarge-mnli/resolve/main/config.json'''
    ),
}


class   A			(__UpperCamelCase    ):
			'''simple docstring'''




			__lowerCamelCase	:       Optional[int]							=    'deberta-v2'






			def __init__(			self   :    Optional[int]							,	__lowerCAmelCase   :    Any=12_81_00							,	__lowerCAmelCase   :    Dict=15_36							,	__lowerCAmelCase   :    Optional[Any]=24							,	__lowerCAmelCase   :    Tuple=24							,	__lowerCAmelCase   :    Optional[Any]=61_44							,	__lowerCAmelCase   :    str="gelu"							,	__lowerCAmelCase   :    str=0.1							,	__lowerCAmelCase   :    str=0.1							,	__lowerCAmelCase   :    Tuple=5_12							,	__lowerCAmelCase   :    Optional[int]=0							,	__lowerCAmelCase   :    Tuple=0.0_2							,	__lowerCAmelCase   :    Optional[int]=1e-7							,	__lowerCAmelCase   :    Union[str, Any]=False							,	__lowerCAmelCase   :    Optional[Any]=-1							,	__lowerCAmelCase   :    Optional[Any]=0							,	__lowerCAmelCase   :    Union[str, Any]=True							,	__lowerCAmelCase   :    List[Any]=None							,	__lowerCAmelCase   :    Tuple=0							,	__lowerCAmelCase   :    Union[str, Any]="gelu"							,	**__lowerCAmelCase   :    Dict							,	)	->	Optional[Any]:







					"""simple docstring"""






					super().__init__(**lowerCAmelCase__   )

					A__        =   hidden_size
					A__        =   num_hidden_layers
					A__        =   num_attention_heads
					A__        =   intermediate_size
					A__        =   hidden_act
					A__        =   hidden_dropout_prob
					A__        =   attention_probs_dropout_prob
					A__        =   max_position_embeddings
					A__        =   type_vocab_size
					A__        =   initializer_range
					A__        =   relative_attention
					A__        =   max_relative_positions
					A__        =   pad_token_id
					A__        =   position_biased_input

					# Backwards compatibility
					if type(lowerCAmelCase__   ) == str:
							A__        =   [x.strip() for x in pos_att_type.lower().split("""|"""   )]

					A__        =   pos_att_type
					A__        =   vocab_size
					A__        =   layer_norm_eps

					A__        =   kwargs.get("""pooler_hidden_size"""							,	lowerCAmelCase__   )
					A__        =   pooler_dropout
					A__        =   pooler_hidden_act


class   A			(__UpperCamelCase    ):
			'''simple docstring'''




			@property
			def    a_       (			self   :    List[Any]   )	->	Mapping[str, Mapping[int, str]]:







					"""simple docstring"""






					if self.task == "multiple-choice":
							A__        =   {0: 'batch', 1: 'choice', 2: 'sequence'}
					else:
							A__        =   {0: 'batch', 1: 'sequence'}
					if self._config.type_vocab_size > 0:
							return OrderedDict(
							    [("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis), ("""token_type_ids""", dynamic_axis)]   )
					else:
							return OrderedDict([("""input_ids""", dynamic_axis), ("""attention_mask""", dynamic_axis)]   )






			@property
			def    a_       (			self   :    Optional[Any]   )	->	int:







					"""simple docstring"""






					return 12







			def    a_       (			self   :    str							,	__lowerCAmelCase   :    Union[str, Any]							,	__lowerCAmelCase   :    Union[str, Any] = -1							,	__lowerCAmelCase   :    Tuple = -1							,	__lowerCAmelCase   :    int = -1							,	__lowerCAmelCase   :    Union[str, Any] = False							,	__lowerCAmelCase   :    str = None							,	__lowerCAmelCase   :    int = 3							,	__lowerCAmelCase   :    List[Any] = 40							,	__lowerCAmelCase   :    str = 40							,	__lowerCAmelCase   :    List[str] = None							,	)	->	Mapping[str, Any]:







					"""simple docstring"""






					A__        =   super().generate_dummy_inputs(preprocessor=lowerCAmelCase__							,	framework=lowerCAmelCase__   )
					if self._config.type_vocab_size == 0 and "token_type_ids" in dummy_inputs:
							del dummy_inputs["token_type_ids"]
					return dummy_inputs







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			:
  @staticmethod
  def 		SCREAMING_SNAKE_CASE__   (   *lowerCAmelCase__				, **lowerCAmelCase__ )					->				List[str]:




         '''simple docstring'''
         pass





 def    snake_case_     (  snake_case     )  ->				Optional[Any]:
        return None


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





@is_pipeline_test
@require_torch
@require_vision
class   __a			(    unittest.TestCase      ):
 __lowercase :							Dict        = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
 @require_pytesseract
 @require_vision
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   pipeline(
            'document-question-answering'				, model=lowerCAmelCase__				, tokenizer=lowerCAmelCase__				, image_processor=lowerCAmelCase__ )

        lowercase__:   int  			=   INVOICE_URL
        lowercase__:   Dict  			=   list(zip(*apply_tesseract(load_image(lowerCAmelCase__ )				, lowerCAmelCase__				, '' ) ) )
        lowercase__:   str  			=   'What is the placebo?'
        lowercase__:   Any  			=   [
            {
                'image': load_image(lowerCAmelCase__ ),
                'question': question,
            },
            {
                'image': image,
                'question': question,
            },
            {
                'image': image,
                'question': question,
                'word_boxes': word_boxes,
            },
        ]
        return dqa_pipeline, examples
 def 		SCREAMING_SNAKE_CASE__   (   self				, lowerCAmelCase__				, lowerCAmelCase__ )					->				int:




        '''simple docstring'''
        lowercase__:   str  			=   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 		SCREAMING_SNAKE_CASE__   (   self )					->				Dict:




        '''simple docstring'''
        lowercase__:   Union[str, Any]  			=   pipeline('document-question-answering'				, model='hf-internal-testing/tiny-random-layoutlmv2' )
        lowercase__:   Optional[Any]  			=   INVOICE_URL
        lowercase__:   int  			=   'How many cats are there?'

        lowercase__:   List[str]  			=   [
            {'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__:   Dict  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(nested_simplify(lowerCAmelCase__				, decimals=4 )				, lowerCAmelCase__ )

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

        # We can optionnally pass directly the words and bounding boxes
        lowercase__:   int  			=   './tests/fixtures/tests_samples/COCO/000000039769.png'
        lowercase__:   List[Any]  			=   []
        lowercase__:   Optional[int]  			=   []
        lowercase__:   Any  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, words=lowerCAmelCase__				, boxes=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(lowerCAmelCase__				, [] )
 @slow
 @require_torch
 @require_detectrona
 @require_pytesseract
 def 		SCREAMING_SNAKE_CASE__   (   self )					->				Any:




        '''simple docstring'''
        lowercase__:   List[str]  			=   pipeline(
            'document-question-answering'				, model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'				, revision='9977165'				, )
        lowercase__:   int  			=   INVOICE_URL
        lowercase__:   str  			=   'What is the invoice number?'

        lowercase__:   Union[str, Any]  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Any  			=   dqa_pipeline({'image': image, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Optional[int]  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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 		SCREAMING_SNAKE_CASE__   (   self )					->				str:




        '''simple docstring'''
        lowercase__:   Any  			=   pipeline(
            'document-question-answering'				, model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'				, revision='9977165'				, max_seq_len=50				, )
        lowercase__:   Optional[int]  			=   INVOICE_URL
        lowercase__:   Union[str, Any]  			=   'What is the invoice number?'

        lowercase__:   Optional[Any]  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Tuple  			=   dqa_pipeline({'image': image, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Dict  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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 		SCREAMING_SNAKE_CASE__   (   self )					->				str:




        '''simple docstring'''
        lowercase__:   Optional[Any]  			=   AutoTokenizer.from_pretrained(
            'impira/layoutlm-document-qa'				, revision='3dc6de3'				, add_prefix_space=lowerCAmelCase__ )
        lowercase__:   Optional[Any]  			=   pipeline(
            'document-question-answering'				, model='impira/layoutlm-document-qa'				, tokenizer=lowerCAmelCase__				, revision='3dc6de3'				, )
        lowercase__:   List[str]  			=   INVOICE_URL
        lowercase__:   Union[str, Any]  			=   'What is the invoice number?'

        lowercase__:   Dict  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   List[str]  			=   dqa_pipeline({'image': image, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   int  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Any  			=   list(zip(*apply_tesseract(load_image(lowerCAmelCase__ )				, lowerCAmelCase__				, '' ) ) )

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




        '''simple docstring'''
        lowercase__:   Any  			=   AutoTokenizer.from_pretrained(
            'impira/layoutlm-document-qa'				, revision='3dc6de3'				, add_prefix_space=lowerCAmelCase__ )
        lowercase__:   str  			=   pipeline(
            'document-question-answering'				, model='impira/layoutlm-document-qa'				, tokenizer=lowerCAmelCase__				, revision='3dc6de3'				, max_seq_len=50				, )
        lowercase__:   Optional[Any]  			=   INVOICE_URL
        lowercase__:   Optional[Any]  			=   'What is the invoice number?'

        lowercase__:   Optional[int]  			=   dqa_pipeline(image=lowerCAmelCase__				, question=lowerCAmelCase__				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Any  			=   dqa_pipeline(
            [{'image': image, 'question': question}, {'image': image, 'question': question}]				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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__:   Optional[int]  			=   list(zip(*apply_tesseract(load_image(lowerCAmelCase__ )				, lowerCAmelCase__				, '' ) ) )

        # This model should also work if `image` is set to None
        lowercase__:   Tuple  			=   dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}				, top_k=2 )
        self.assertEqual(
            nested_simplify(lowerCAmelCase__				, 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 		SCREAMING_SNAKE_CASE__   (   self )					->				Optional[Any]:




        '''simple docstring'''
        lowercase__:   List[Any]  			=   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__:   int  			=   INVOICE_URL
        lowercase__:   int  			=   'What is the invoice number?'
        lowercase__:   Union[str, Any]  			=   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 		SCREAMING_SNAKE_CASE__   (   self )					->				List[str]:




        '''simple docstring'''
        pass


