





from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


A    :					Union[str, Any] =      {
    '''configuration_graphormer''': ['''GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GraphormerConfig'''],
}

try:
					if not is_torch_available():
										raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
					pass
else:
					A    :					Optional[Any] =      [
					    '''GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
					    '''GraphormerForGraphClassification''',
					    '''GraphormerModel''',
					    '''GraphormerPreTrainedModel''',
					]


if TYPE_CHECKING:
					from .configuration_graphormer import GRAPHORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, GraphormerConfig

					try:
										if not is_torch_available():
															raise OptionalDependencyNotAvailable()
					except OptionalDependencyNotAvailable:
										pass
					else:
										from .modeling_graphormer import (
										    GRAPHORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
										    GraphormerForGraphClassification,
										    GraphormerModel,
										    GraphormerPreTrainedModel,
										)


else:
					import sys

					A    :					Any =      _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)







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


