





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 UpperCAmelCase_				(      *_A      :      List[str]		,   **_A      :      int	)							->    List[str]:







													"""simple docstring"""


													pass


						def 							SCREAMING_SNAKE_CASE__						(    __a   ):
							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      	=		(
    """https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png"""
)
@is_pipeline_test
@require_torch
@require_vision
class SCREAMING_SNAKE_CASE_						(					unittest.TestCase					):
						__magic_name__:			Any       =       MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING






						@require_pytesseract
						@require_vision
						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      Any		,   _A      :      str		,   _A      :      Any	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	pipeline(
							    'document-question-answering'		,   model=_A		,   tokenizer=_A		,   image_processor=_A	)

							snake_case_		:			int											=	INVOICE_URL
							snake_case_		:			Tuple											=	list(zip(*apply_tesseract(load_image(_A	)		,   _A		,   ''	)	)	)
							snake_case_		:			Any											=	'What is the placebo?'
							snake_case_		:			Union[str, Any]											=	[
							    {
							        '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      :      Optional[Any]		,   _A      :      Union[str, Any]		,   _A      :      Tuple	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Union[str, 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 UpperCAmelCase_				(      self      :      int	)							->    Optional[int]:







							"""simple docstring"""


							snake_case_		:			int											=	pipeline('document-question-answering'		,   model='hf-internal-testing/tiny-random-layoutlmv2'	)
							snake_case_		:			Tuple											=	INVOICE_URL
							snake_case_		:			List[str]											=	'How many cats are there?'

							snake_case_		:			Union[str, Any]											=	[
							    {'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},
							]
							snake_case_		:			int											=	dqa_pipeline(image=_A		,   question=_A		,   top_k=2	)
							self.assertEqual(nested_simplify(_A		,   decimals=4	)		,   _A	)

							snake_case_		:			Optional[int]											=	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
							snake_case_		:			str											=	'./tests/fixtures/tests_samples/COCO/000000039769.png'
							snake_case_		:			Dict											=	dqa_pipeline(image=_A		,   question=_A		,   top_k=2	)
							self.assertEqual(_A		,   []	)

							# We can optionnally pass directly the words and bounding boxes
							snake_case_		:			Optional[Any]											=	'./tests/fixtures/tests_samples/COCO/000000039769.png'
							snake_case_		:			Tuple											=	[]
							snake_case_		:			Tuple											=	[]
							snake_case_		:			Union[str, 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 UpperCAmelCase_				(      self      :      Any	)							->    List[Any]:







							"""simple docstring"""


							snake_case_		:			Tuple											=	pipeline(
							    'document-question-answering'		,   model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'		,   revision='9977165'		,   )
							snake_case_		:			List[str]											=	INVOICE_URL
							snake_case_		:			Any											=	'What is the invoice number?'

							snake_case_		:			str											=	dqa_pipeline(image=_A		,   question=_A		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			Union[str, Any]											=	dqa_pipeline({'image': image, 'question': question}		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			List[str]											=	dqa_pipeline(
							    [{'image': image, 'question': question}, {'image': image, 'question': question}]		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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      :      List[Any]	)							->    str:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	pipeline(
							    'document-question-answering'		,   model='tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'		,   revision='9977165'		,   max_seq_len=50		,   )
							snake_case_		:			Any											=	INVOICE_URL
							snake_case_		:			Union[str, Any]											=	'What is the invoice number?'

							snake_case_		:			Optional[Any]											=	dqa_pipeline(image=_A		,   question=_A		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			Union[str, Any]											=	dqa_pipeline({'image': image, 'question': question}		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			Union[str, Any]											=	dqa_pipeline(
							    [{'image': image, 'question': question}, {'image': image, 'question': question}]		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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      :      Dict	)							->    Dict:







							"""simple docstring"""


							snake_case_		:			Tuple											=	AutoTokenizer.from_pretrained(
							    'impira/layoutlm-document-qa'		,   revision='3dc6de3'		,   add_prefix_space=_A	)
							snake_case_		:			List[Any]											=	pipeline(
							    'document-question-answering'		,   model='impira/layoutlm-document-qa'		,   tokenizer=_A		,   revision='3dc6de3'		,   )
							snake_case_		:			List[str]											=	INVOICE_URL
							snake_case_		:			List[str]											=	'What is the invoice number?'

							snake_case_		:			List[str]											=	dqa_pipeline(image=_A		,   question=_A		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			Tuple											=	dqa_pipeline({'image': image, 'question': question}		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			Optional[int]											=	dqa_pipeline(
							    [{'image': image, 'question': question}, {'image': image, 'question': question}]		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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		,   )

							snake_case_		:			Union[str, Any]											=	list(zip(*apply_tesseract(load_image(_A	)		,   _A		,   ''	)	)	)

							# This model should also work if `image` is set to None
							snake_case_		:			Any											=	dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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      :      Dict	)							->    Optional[Any]:







							"""simple docstring"""


							snake_case_		:			Optional[Any]											=	AutoTokenizer.from_pretrained(
							    'impira/layoutlm-document-qa'		,   revision='3dc6de3'		,   add_prefix_space=_A	)
							snake_case_		:			Dict											=	pipeline(
							    'document-question-answering'		,   model='impira/layoutlm-document-qa'		,   tokenizer=_A		,   revision='3dc6de3'		,   max_seq_len=50		,   )
							snake_case_		:			Dict											=	INVOICE_URL
							snake_case_		:			List[str]											=	'What is the invoice number?'

							snake_case_		:			List[str]											=	dqa_pipeline(image=_A		,   question=_A		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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},
							    ]		,   )

							snake_case_		:			Any											=	dqa_pipeline(
							    [{'image': image, 'question': question}, {'image': image, 'question': question}]		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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		,   )

							snake_case_		:			Union[str, Any]											=	list(zip(*apply_tesseract(load_image(_A	)		,   _A		,   ''	)	)	)

							# This model should also work if `image` is set to None
							snake_case_		:			Tuple											=	dqa_pipeline({'image': None, 'word_boxes': word_boxes, 'question': question}		,   top_k=2	)
							self.assertEqual(
							    nested_simplify(_A		,   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      :      Optional[int]	)							->    Tuple:







							"""simple docstring"""


							snake_case_		:			Union[str, 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'		,   )

							snake_case_		:			Dict											=	INVOICE_URL
							snake_case_		:			Tuple											=	'What is the invoice number?'
							snake_case_		:			Optional[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 UpperCAmelCase_				(      self      :      Dict	)							->    Dict:







							"""simple docstring"""


							pass








from typing import TYPE_CHECKING

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


_SCREAMING_SNAKE_CASE      	=		{"""configuration_swin""": ["""SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SwinConfig""", """SwinOnnxConfig"""]}


try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		[
						    """SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""",
						    """SwinForImageClassification""",
						    """SwinForMaskedImageModeling""",
						    """SwinModel""",
						    """SwinPreTrainedModel""",
						    """SwinBackbone""",
						]

try:
						if not is_tf_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						_SCREAMING_SNAKE_CASE      	=		[
						    """TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST""",
						    """TFSwinForImageClassification""",
						    """TFSwinForMaskedImageModeling""",
						    """TFSwinModel""",
						    """TFSwinPreTrainedModel""",
						]

if TYPE_CHECKING:
						from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_swin import (
												    SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
												    SwinBackbone,
												    SwinForImageClassification,
												    SwinForMaskedImageModeling,
												    SwinModel,
												    SwinPreTrainedModel,
												)

						try:
												if not is_tf_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_tf_swin import (
												    TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
												    TFSwinForImageClassification,
												    TFSwinForMaskedImageModeling,
												    TFSwinModel,
												    TFSwinPreTrainedModel,
												)

else:
						import sys

						_SCREAMING_SNAKE_CASE      	=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)

