





'''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  UpperCAmelCase     :




            @staticmethod
            def 				lowercase__    (			*__snake_case			: int			,			**__snake_case			: str  )				->      Dict:
                  pass




      def    UpperCamelCase__      (		lowerCAmelCase  ):





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




@is_pipeline_test
@require_torch
@require_vision
class  UpperCAmelCase     (			unittest.TestCase   ):
      _lowercase:			Optional[Any]						     =   MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING




      @require_pytesseract
      @require_vision
      def 				lowercase__    (			self			: Dict			,			__snake_case			: Optional[int]			,			__snake_case			: int			,			__snake_case			: Union[str, Any]  )				->      List[Any]:
            _lowerCAmelCase							     =							pipeline(
                """document-question-answering"""			,			model=__snake_case			,			tokenizer=__snake_case			,			image_processor=__snake_case  )

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




      def 				lowercase__    (			self			: str			,			__snake_case			: Dict			,			__snake_case			: Any  )				->      Dict:
            _lowerCAmelCase							     =							dqa_pipeline(__snake_case			,			top_k=2  )
            self.assertEqual(
                __snake_case			,			[
                    [
                        {"""score""": ANY(__snake_case  ), """answer""": ANY(__snake_case  ), """start""": ANY(__snake_case  ), """end""": ANY(__snake_case  )},
                        {"""score""": ANY(__snake_case  ), """answer""": ANY(__snake_case  ), """start""": ANY(__snake_case  ), """end""": ANY(__snake_case  )},
                    ]
                ]
                * 3			,			)




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

            _lowerCAmelCase							     =							[
                {"""score""": 0.00_01, """answer""": """oy 2312/2019""", """start""": 38, """end""": 39},
                {"""score""": 0.00_01, """answer""": """oy 2312/2019 DUE""", """start""": 38, """end""": 40},
            ]
            _lowerCAmelCase							     =							dqa_pipeline(image=__snake_case			,			question=__snake_case			,			top_k=2  )
            self.assertEqual(nested_simplify(__snake_case			,			decimals=4  )			,			__snake_case  )

            _lowerCAmelCase							     =							dqa_pipeline({"""image""": image, """question""": question}			,			top_k=2  )
            self.assertEqual(nested_simplify(__snake_case			,			decimals=4  )			,			__snake_case  )

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

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




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

            _lowerCAmelCase							     =							dqa_pipeline(image=__snake_case			,			question=__snake_case			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.99_44, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.00_09, """answer""": """us-001""", """start""": 16, """end""": 16},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline({"""image""": image, """question""": question}			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.99_44, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.00_09, """answer""": """us-001""", """start""": 16, """end""": 16},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline(
                [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    [
                        {"""score""": 0.99_44, """answer""": """us-001""", """start""": 16, """end""": 16},
                        {"""score""": 0.00_09, """answer""": """us-001""", """start""": 16, """end""": 16},
                    ],
                ]
                * 2			,			)




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

            _lowerCAmelCase							     =							dqa_pipeline(image=__snake_case			,			question=__snake_case			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.99_74, """answer""": """1110212019""", """start""": 23, """end""": 23},
                    {"""score""": 0.99_48, """answer""": """us-001""", """start""": 16, """end""": 16},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline({"""image""": image, """question""": question}			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.99_74, """answer""": """1110212019""", """start""": 23, """end""": 23},
                    {"""score""": 0.99_48, """answer""": """us-001""", """start""": 16, """end""": 16},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline(
                [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    [
                        {"""score""": 0.99_74, """answer""": """1110212019""", """start""": 23, """end""": 23},
                        {"""score""": 0.99_48, """answer""": """us-001""", """start""": 16, """end""": 16},
                    ]
                ]
                * 2			,			)




      @slow
      @require_torch
      @require_pytesseract
      @require_vision
      def 				lowercase__    (			self			: Tuple  )				->      Union[str, Any]:
            _lowerCAmelCase							     =							AutoTokenizer.from_pretrained(
                """impira/layoutlm-document-qa"""			,			revision="""3dc6de3"""			,			add_prefix_space=__snake_case  )
            _lowerCAmelCase							     =							pipeline(
                """document-question-answering"""			,			model="""impira/layoutlm-document-qa"""			,			tokenizer=__snake_case			,			revision="""3dc6de3"""			,			)
            _lowerCAmelCase							     =							INVOICE_URL
            _lowerCAmelCase							     =							"""What is the invoice number?"""

            _lowerCAmelCase							     =							dqa_pipeline(image=__snake_case			,			question=__snake_case			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.42_51, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 23, """end""": 23},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline({"""image""": image, """question""": question}			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.42_51, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 23, """end""": 23},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline(
                [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    [
                        {"""score""": 0.42_51, """answer""": """us-001""", """start""": 16, """end""": 16},
                        {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 23, """end""": 23},
                    ]
                ]
                * 2			,			)

            _lowerCAmelCase							     =							list(zip(*apply_tesseract(load_image(__snake_case  )			,			__snake_case			,			""""""  )  )  )

            # This model should also work if `image` is set to None
            _lowerCAmelCase							     =							dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.42_51, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.08_19, """answer""": """1110212019""", """start""": 23, """end""": 23},
                ]			,			)




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

            _lowerCAmelCase							     =							dqa_pipeline(image=__snake_case			,			question=__snake_case			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.99_99, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.99_98, """answer""": """us-001""", """start""": 16, """end""": 16},
                ]			,			)

            _lowerCAmelCase							     =							dqa_pipeline(
                [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    [
                        {"""score""": 0.99_99, """answer""": """us-001""", """start""": 16, """end""": 16},
                        {"""score""": 0.99_98, """answer""": """us-001""", """start""": 16, """end""": 16},
                    ]
                ]
                * 2			,			)

            _lowerCAmelCase							     =							list(zip(*apply_tesseract(load_image(__snake_case  )			,			__snake_case			,			""""""  )  )  )

            # This model should also work if `image` is set to None
            _lowerCAmelCase							     =							dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}			,			top_k=2  )
            self.assertEqual(
                nested_simplify(__snake_case			,			decimals=4  )			,			[
                    {"""score""": 0.99_99, """answer""": """us-001""", """start""": 16, """end""": 16},
                    {"""score""": 0.99_98, """answer""": """us-001""", """start""": 16, """end""": 16},
                ]			,			)




      @slow
      @require_torch
      def 				lowercase__    (			self			: Dict  )				->      Optional[int]:
            _lowerCAmelCase							     =							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"""			,			)

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




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











"""simple docstring"""
import inspect
import warnings
from typing import Any, Dict, Optional, Union

from packaging import version

def       _snake_case						(						*UpperCamelCase						:		str			,		UpperCamelCase						:		Optional[Union[Dict, Any]] = None			,		UpperCamelCase						:		Tuple=True			,		UpperCamelCase						:		Optional[int]=2						):
 from .. import __version__

 UpperCAmelCase	:					Tuple	=	take_from
 UpperCAmelCase	:					Optional[Any]	=	()
 if not isinstance(args[0]			,		UpperCamelCase						):
  UpperCAmelCase	:					List[str]	=	(args,)

 for attribute, version_name, message in args:
  if version.parse(version.parse(UpperCamelCase						).base_version						) >= version.parse(UpperCamelCase						):
   raise ValueError(
       F"The deprecation tuple {(attribute, version_name, message)} should be removed since diffusers'"
       F" version {__version__} is >= {version_name}"						)

  UpperCAmelCase	:					Optional[int]	=	None
  if isinstance(UpperCamelCase			,		UpperCamelCase						) and attribute in deprecated_kwargs:
   values += (deprecated_kwargs.pop(UpperCamelCase						),)
   UpperCAmelCase	:					List[str]	=	F"The `{attribute}` argument is deprecated and will be removed in version {version_name}."
  elif hasattr(UpperCamelCase			,		UpperCamelCase						):
   values += (getattr(UpperCamelCase			,		UpperCamelCase						),)
   UpperCAmelCase	:					List[Any]	=	F"The `{attribute}` attribute is deprecated and will be removed in version {version_name}."
  elif deprecated_kwargs is None:
   UpperCAmelCase	:					int	=	F"`{attribute}` is deprecated and will be removed in version {version_name}."

  if warning is not None:
   UpperCAmelCase	:					Optional[Any]	=	warning + """ """ if standard_warn else """"""
   warnings.warn(warning + message			,		UpperCamelCase			,		stacklevel=UpperCamelCase						)

 if isinstance(UpperCamelCase			,		UpperCamelCase						) and len(UpperCamelCase						) > 0:
  UpperCAmelCase	:					Optional[int]	=	inspect.getouterframes(inspect.currentframe()						)[1]
  UpperCAmelCase	:					Union[str, Any]	=	call_frame.filename
  UpperCAmelCase	:					List[Any]	=	call_frame.lineno
  UpperCAmelCase	:					List[str]	=	call_frame.function
  UpperCAmelCase	,		UpperCAmelCase	:					Optional[int]	=	next(iter(deprecated_kwargs.items()						)						)
  raise TypeError(F"{function} in {filename} line {line_number-1} got an unexpected keyword argument `{key}`"						)

 if len(UpperCamelCase						) == 0:
  return
 elif len(UpperCamelCase						) == 1:
  return values[0]
 return values
