

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 				SCREAMING_SNAKE_CASE__ :





           @staticmethod
           def 				snake_case_    (				*a						,       **a):
                pass



       def      snake_case__      (   SCREAMING_SNAKE_CASE_		:   List[Any]      ):



            '''simple docstring'''





            return None


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


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





    @require_pytesseract
    @require_vision
    def 				snake_case_    (				self						,       a						,       a						,       a):
         lowercase__   :       Dict				=	pipeline(
             'document-question-answering'						,       model=a						,       tokenizer=a						,       image_processor=a)

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





    def 				snake_case_    (				self						,       a						,       a):
         lowercase__   :       List[Any]				=	dqa_pipeline(a						,       top_k=2)
         self.assertEqual(
             a						,       [
                 [
                     {'score': ANY(a), 'answer': ANY(a), 'start': ANY(a), 'end': ANY(a)},
                     {'score': ANY(a), 'answer': ANY(a), 'start': ANY(a), 'end': ANY(a)},
                 ]
             ]
             * 3						,       )





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

         lowercase__   :       Optional[Any]				=	[
             {'score': 0.0_001, 'answer': 'oy 2312/2019', 'start': 38, 'end': 39},
             {'score': 0.0_001, 'answer': 'oy 2312/2019 DUE', 'start': 38, 'end': 40},
         ]
         lowercase__   :       List[Any]				=	dqa_pipeline(image=a						,       question=a						,       top_k=2)
         self.assertEqual(nested_simplify(a						,       decimals=4)						,       a)

         lowercase__   :       str				=	dqa_pipeline({'image': image, 'question': question}						,       top_k=2)
         self.assertEqual(nested_simplify(a						,       decimals=4)						,       a)

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

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





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

         lowercase__   :       List[str]				=	dqa_pipeline(image=a						,       question=a						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.9_944, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_009, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]						,       )

         lowercase__   :       Tuple				=	dqa_pipeline({'image': image, 'question': question}						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.9_944, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_009, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]						,       )

         lowercase__   :       Tuple				=	dqa_pipeline(
             [{'image': image, 'question': question}, {'image': image, 'question': question}]						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 [
                     {'score': 0.9_944, 'answer': 'us-001', 'start': 16, 'end': 16},
                     {'score': 0.0_009, 'answer': 'us-001', 'start': 16, 'end': 16},
                 ],
             ]
             * 2						,       )





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

         lowercase__   :       int				=	dqa_pipeline(image=a						,       question=a						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.9_974, 'answer': '1110212019', 'start': 23, 'end': 23},
                 {'score': 0.9_948, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]						,       )

         lowercase__   :       Optional[int]				=	dqa_pipeline({'image': image, 'question': question}						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.9_974, 'answer': '1110212019', 'start': 23, 'end': 23},
                 {'score': 0.9_948, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]						,       )

         lowercase__   :       Optional[Any]				=	dqa_pipeline(
             [{'image': image, 'question': question}, {'image': image, 'question': question}]						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 [
                     {'score': 0.9_974, 'answer': '1110212019', 'start': 23, 'end': 23},
                     {'score': 0.9_948, 'answer': 'us-001', 'start': 16, 'end': 16},
                 ]
             ]
             * 2						,       )





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

         lowercase__   :       List[Any]				=	dqa_pipeline(image=a						,       question=a						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23},
             ]						,       )

         lowercase__   :       str				=	dqa_pipeline({'image': image, 'question': question}						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23},
             ]						,       )

         lowercase__   :       List[str]				=	dqa_pipeline(
             [{'image': image, 'question': question}, {'image': image, 'question': question}]						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 [
                     {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16},
                     {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23},
                 ]
             ]
             * 2						,       )

         lowercase__   :       Optional[Any]				=	list(zip(*apply_tesseract(load_image(a)						,       a						,       '')))

         # This model should also work if `image` is set to None
         lowercase__   :       int				=	dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.4_251, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.0_819, 'answer': '1110212019', 'start': 23, 'end': 23},
             ]						,       )





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

         lowercase__   :       List[Any]				=	dqa_pipeline(image=a						,       question=a						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.9_999, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.9_998, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]						,       )

         lowercase__   :       int				=	dqa_pipeline(
             [{'image': image, 'question': question}, {'image': image, 'question': question}]						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 [
                     {'score': 0.9_999, 'answer': 'us-001', 'start': 16, 'end': 16},
                     {'score': 0.9_998, 'answer': 'us-001', 'start': 16, 'end': 16},
                 ]
             ]
             * 2						,       )

         lowercase__   :       Any				=	list(zip(*apply_tesseract(load_image(a)						,       a						,       '')))

         # This model should also work if `image` is set to None
         lowercase__   :       int				=	dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}						,       top_k=2)
         self.assertEqual(
             nested_simplify(a						,       decimals=4)						,       [
                 {'score': 0.9_999, 'answer': 'us-001', 'start': 16, 'end': 16},
                 {'score': 0.9_998, 'answer': 'us-001', 'start': 16, 'end': 16},
             ]						,       )





    @slow
    @require_torch
    def 				snake_case_    (				self):
         lowercase__   :       Tuple				=	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__   :       str				=	INVOICE_URL
         lowercase__   :       Any				=	'What is the invoice number?'
         lowercase__   :       Union[str, Any]				=	dqa_pipeline(image=a						,       question=a						,       top_k=2)
         self.assertEqual(nested_simplify(a						,       decimals=4)						,       [{'answer': 'us-001'}])





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




import numpy as np

def      snake_case__      (   SCREAMING_SNAKE_CASE_		:   str     ,					SCREAMING_SNAKE_CASE_		:   Optional[int]     ,					SCREAMING_SNAKE_CASE_		:   Optional[int]     ,					SCREAMING_SNAKE_CASE_		:   Union[str, Any]     ,					SCREAMING_SNAKE_CASE_		:   List[Any]      ):



     '''simple docstring'''





     lowercase__   :       List[Any]				=	int(np.ceil((x_end - xa) / h      )      )
     lowercase__   :       Dict				=	np.zeros((n + 1,)      )
     lowercase__   :       Dict				=	ya
     lowercase__   :       Union[str, Any]				=	xa

     for k in range(SCREAMING_SNAKE_CASE_      ):
          lowercase__   :       Optional[int]				=	f(SCREAMING_SNAKE_CASE_     ,					y[k]      )
          lowercase__   :       Dict				=	f(x + 0.5 * h     ,					y[k] + 0.5 * h * ka      )
          lowercase__   :       Any				=	f(x + 0.5 * h     ,					y[k] + 0.5 * h * ka      )
          lowercase__   :       List[Any]				=	f(x + h     ,					y[k] + h * ka      )
          lowercase__   :       Tuple				=	y[k] + (1 / 6) * h * (ka + 2 * ka + 2 * ka + ka)
          x += h

     return y


if __name__ == "__main__":
       import doctest

       doctest.testmod()

