


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    :

								"""simple docstring"""







								@staticmethod
								def      _UpperCAmelCase					(						*a__				,   **a__   )	->				Optional[int]:
									pass





				def   _lowerCAmelCase				(   UpperCamelCase__:     List[Any]						) ->   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.
_lowercase       :      Optional[int]	=	(
    "https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"
)






@is_pipeline_test
@require_torch
@require_vision
class       _UpperCamelCase    (					unittest.TestCase				):

				"""simple docstring"""







				lowerCAmelCase 		= MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING

				@require_pytesseract
				@require_vision
				def      _UpperCAmelCase					(						self				,   a__				,   a__				,   a__   )	->				str:
					A								=				pipeline(
					    """document-question-answering"""				,   model=a__				,   tokenizer=a__				,   image_processor=a__   )

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

				def      _UpperCAmelCase					(						self				,   a__				,   a__   )	->				List[Any]:
					A								=				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      _UpperCAmelCase					(						self   )	->				Any:
					A								=				pipeline("""document-question-answering"""				,   model="""hf-internal-testing/tiny-random-layoutlmv2"""   )
					A								=				INVOICE_URL
					A								=				"""How many cats are there?"""

					A								=				[
					    {"""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},
					]
					A								=				dqa_pipeline(image=a__				,   question=a__				,   top_k=2   )
					self.assertEqual(nested_simplify(a__				,   decimals=4   )				,   a__   )

					A								=				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
					A								=				"""./tests/fixtures/tests_samples/COCO/000000039769.png"""
					A								=				dqa_pipeline(image=a__				,   question=a__				,   top_k=2   )
					self.assertEqual(a__				,   []   )

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

				@slow
				@require_torch
				@require_detectrona
				@require_pytesseract
				def      _UpperCAmelCase					(						self   )	->				Optional[int]:
					A								=				pipeline(
					    """document-question-answering"""				,   model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""				,   revision="""9977165"""				,   )
					A								=				INVOICE_URL
					A								=				"""What is the invoice number?"""

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

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

					A								=				dqa_pipeline(
					    [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]				,   top_k=2   )
					self.assertEqual(
					    nested_simplify(a__				,   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      _UpperCAmelCase					(						self   )	->				Any:
					A								=				pipeline(
					    """document-question-answering"""				,   model="""tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa"""				,   revision="""9977165"""				,   max_seq_len=50				,   )
					A								=				INVOICE_URL
					A								=				"""What is the invoice number?"""

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

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

					A								=				dqa_pipeline(
					    [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]				,   top_k=2   )
					self.assertEqual(
					    nested_simplify(a__				,   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      _UpperCAmelCase					(						self   )	->				List[Any]:
					A								=				AutoTokenizer.from_pretrained(
					    """impira/layoutlm-document-qa"""				,   revision="""3dc6de3"""				,   add_prefix_space=a__   )
					A								=				pipeline(
					    """document-question-answering"""				,   model="""impira/layoutlm-document-qa"""				,   tokenizer=a__				,   revision="""3dc6de3"""				,   )
					A								=				INVOICE_URL
					A								=				"""What is the invoice number?"""

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

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

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

					A								=				list(zip(*apply_tesseract(load_image(a__   )				,   a__				,   """"""   )   )   )

					# This model should also work if `image` is set to None
					A								=				dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}				,   top_k=2   )
					self.assertEqual(
					    nested_simplify(a__				,   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      _UpperCAmelCase					(						self   )	->				Union[str, Any]:
					A								=				AutoTokenizer.from_pretrained(
					    """impira/layoutlm-document-qa"""				,   revision="""3dc6de3"""				,   add_prefix_space=a__   )
					A								=				pipeline(
					    """document-question-answering"""				,   model="""impira/layoutlm-document-qa"""				,   tokenizer=a__				,   revision="""3dc6de3"""				,   max_seq_len=50				,   )
					A								=				INVOICE_URL
					A								=				"""What is the invoice number?"""

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

					A								=				dqa_pipeline(
					    [{"""image""": image, """question""": question}, {"""image""": image, """question""": question}]				,   top_k=2   )
					self.assertEqual(
					    nested_simplify(a__				,   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				,   )

					A								=				list(zip(*apply_tesseract(load_image(a__   )				,   a__				,   """"""   )   )   )

					# This model should also work if `image` is set to None
					A								=				dqa_pipeline({"""image""": None, """word_boxes""": word_boxes, """question""": question}				,   top_k=2   )
					self.assertEqual(
					    nested_simplify(a__				,   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      _UpperCAmelCase					(						self   )	->				int:
					A								=				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"""				,   )

					A								=				INVOICE_URL
					A								=				"""What is the invoice number?"""
					A								=				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      _UpperCAmelCase					(						self   )	->				str:
					pass







from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_lowercase       :      Any	=	{
    "configuration_swinv2": ["SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP", "Swinv2Config"],
}


try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				_lowercase       :      Tuple	=	[
				    "SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST",
				    "Swinv2ForImageClassification",
				    "Swinv2ForMaskedImageModeling",
				    "Swinv2Model",
				    "Swinv2PreTrainedModel",
				]


if TYPE_CHECKING:
				from .configuration_swinva import SWINV2_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinvaConfig

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_swinva import (
								    SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST,
								    SwinvaForImageClassification,
								    SwinvaForMaskedImageModeling,
								    SwinvaModel,
								    SwinvaPreTrainedModel,
								)


else:
				import sys

				_lowercase       :      Optional[int]	=	_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



