






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  _lowerCamelCase						(						__lowerCamelCase       ) ->			Tuple:

           '''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.
SCREAMING_SNAKE_CASE__		:							Tuple 				=				(
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)







@is_pipeline_test
@require_torch
@require_vision
class 				UpperCAmelCase_  (		unittest.TestCase		):
     __lowerCamelCase      				=  MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING




     @require_pytesseract
     @require_vision
     def   __UpperCAmelCase  (				self	,						_lowerCAmelCase	,						_lowerCAmelCase	,						_lowerCAmelCase		):
          UpperCAmelCase__      :  Optional[Any]				      =			pipeline(
              """document-question-answering"""	,						model=_lowerCAmelCase	,						tokenizer=_lowerCAmelCase	,						image_processor=_lowerCAmelCase		)

          UpperCAmelCase__      :  Union[str, Any]				      =			INVOICE_URL
          UpperCAmelCase__      :  List[Any]				      =			list(zip(*apply_tesseract(load_image(_lowerCAmelCase		)	,						_lowerCAmelCase	,						""""""		)		)		)
          UpperCAmelCase__      :  List[str]				      =			"""What is the placebo?"""
          UpperCAmelCase__      :  Any				      =			[
              {
                  """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		):
          UpperCAmelCase__      :  Any				      =			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		):
          UpperCAmelCase__      :  List[Any]				      =			pipeline("""document-question-answering"""	,						model="""hf-internal-testing/tiny-random-layoutlmv2"""		)
          UpperCAmelCase__      :  Any				      =			INVOICE_URL
          UpperCAmelCase__      :  Optional[Any]				      =			"""How many cats are there?"""

          UpperCAmelCase__      :  int				      =			[
              {"""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},
          ]
          UpperCAmelCase__      :  List[Any]				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(nested_simplify(_lowerCAmelCase	,						decimals=4		)	,						_lowerCAmelCase		)

          UpperCAmelCase__      :  Optional[Any]				      =			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
          UpperCAmelCase__      :  Union[str, Any]				      =			"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
          UpperCAmelCase__      :  Tuple				      =			dqa_pipeline(image=_lowerCAmelCase	,						question=_lowerCAmelCase	,						top_k=2		)
          self.assertEqual(_lowerCAmelCase	,						[]		)

          # We can optionnally pass directly the words and bounding boxes
          UpperCAmelCase__      :  Optional[Any]				      =			"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
          UpperCAmelCase__      :  List[str]				      =			[]
          UpperCAmelCase__      :  str				      =			[]
          UpperCAmelCase__      :  Tuple				      =			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		):
          UpperCAmelCase__      :  List[Any]				      =			pipeline(
              """document-question-answering"""	,						model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""	,						revision="""9977165"""	,						)
          UpperCAmelCase__      :  List[str]				      =			INVOICE_URL
          UpperCAmelCase__      :  Dict				      =			"""What is the invoice number?"""

          UpperCAmelCase__      :  str				      =			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},
              ]	,						)

          UpperCAmelCase__      :  Union[str, 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},
              ]	,						)

          UpperCAmelCase__      :  Optional[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_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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			pipeline(
              """document-question-answering"""	,						model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""	,						revision="""9977165"""	,						max_seq_len=50	,						)
          UpperCAmelCase__      :  List[Any]				      =			INVOICE_URL
          UpperCAmelCase__      :  Tuple				      =			"""What is the invoice number?"""

          UpperCAmelCase__      :  Union[str, 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},
              ]	,						)

          UpperCAmelCase__      :  Dict				      =			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},
              ]	,						)

          UpperCAmelCase__      :  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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  int				      =			AutoTokenizer.from_pretrained(
              """impira/layoutlm-document-qa"""	,						revision="""3dc6de3"""	,						add_prefix_space=_lowerCAmelCase		)
          UpperCAmelCase__      :  Optional[int]				      =			pipeline(
              """document-question-answering"""	,						model="""impira/layoutlm-document-qa"""	,						tokenizer=_lowerCAmelCase	,						revision="""3dc6de3"""	,						)
          UpperCAmelCase__      :  Dict				      =			INVOICE_URL
          UpperCAmelCase__      :  List[Any]				      =			"""What is the invoice number?"""

          UpperCAmelCase__      :  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},
              ]	,						)

          UpperCAmelCase__      :  Any				      =			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},
              ]	,						)

          UpperCAmelCase__      :  Optional[Any]				      =			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	,						)

          UpperCAmelCase__      :  Dict				      =			list(zip(*apply_tesseract(load_image(_lowerCAmelCase		)	,						_lowerCAmelCase	,						""""""		)		)		)

          # This model should also work if `image` is set to None
          UpperCAmelCase__      :  List[str]				      =			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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[str]				      =			AutoTokenizer.from_pretrained(
              """impira/layoutlm-document-qa"""	,						revision="""3dc6de3"""	,						add_prefix_space=_lowerCAmelCase		)
          UpperCAmelCase__      :  Optional[Any]				      =			pipeline(
              """document-question-answering"""	,						model="""impira/layoutlm-document-qa"""	,						tokenizer=_lowerCAmelCase	,						revision="""3dc6de3"""	,						max_seq_len=50	,						)
          UpperCAmelCase__      :  Any				      =			INVOICE_URL
          UpperCAmelCase__      :  str				      =			"""What is the invoice number?"""

          UpperCAmelCase__      :  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},
              ]	,						)

          UpperCAmelCase__      :  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	,						)

          UpperCAmelCase__      :  List[Any]				      =			list(zip(*apply_tesseract(load_image(_lowerCAmelCase		)	,						_lowerCAmelCase	,						""""""		)		)		)

          # This model should also work if `image` is set to None
          UpperCAmelCase__      :  List[str]				      =			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   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  List[str]				      =			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__      :  List[Any]				      =			INVOICE_URL
          UpperCAmelCase__      :  Optional[int]				      =			"""What is the invoice number?"""
          UpperCAmelCase__      :  List[str]				      =			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














def 		lowercase__  (				_UpperCamelCase       ,							_UpperCamelCase) ->			bool:
      """simple docstring"""

      return numa ^ numa < 0


if __name__ == "__main__":
       import doctest

       doctest.testmod()



