





"""simple docstring"""




import torch
from torch import nn

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin


class        __UpperCamelCase				(						a__		,       a__						):






							@register_to_config
							def __init__(   self      ,					*,
							    lowerCAmelCase__ = 4      ,					lowerCAmelCase__ = 768      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					)	-> Optional[Any]:
								super().__init__()

								a      :		Tuple	=				nn.Parameter(torch.zeros(lowerCAmelCase__      )      )

								# parameters for additional clip time embeddings
								a      :		str	=				nn.Linear(lowerCAmelCase__      ,					lowerCAmelCase__      )
								a      :		Any	=				nn.Linear(lowerCAmelCase__      ,					lowerCAmelCase__      )

								# parameters for encoder hidden states
								a      :		int	=				clip_extra_context_tokens
								a      :		int	=				nn.Linear(
								    lowerCAmelCase__      ,					self.clip_extra_context_tokens * cross_attention_dim      )
								a      :		Any	=				nn.Linear(lowerCAmelCase__      ,					lowerCAmelCase__      )
								a      :		str	=				nn.LayerNorm(lowerCAmelCase__      )






							def     __a   (   self      ,					*, lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Union[str, Any]:
								if do_classifier_free_guidance:
									# Add the classifier free guidance embeddings to the image embeddings
									a      :		str	=				image_embeddings.shape[0]
									a      :		Optional[int]	=				self.learned_classifier_free_guidance_embeddings.unsqueeze(0      )
									a      :		Any	=				classifier_free_guidance_embeddings.expand(
									    lowerCAmelCase__      ,					-1      )
									a      :		Any	=				torch.cat([classifier_free_guidance_embeddings, image_embeddings]      ,					dim=0      )

								# The image embeddings batch size and the text embeddings batch size are equal
								assert image_embeddings.shape[0] == prompt_embeds.shape[0]

								a      :		List[str]	=				prompt_embeds.shape[0]

								# "Specifically, we modify the architecture described in Nichol et al. (2021) by projecting and
								# adding CLIP embeddings to the existing timestep embedding, ...
								a      :		Dict	=				self.embedding_proj(lowerCAmelCase__      )
								a      :		List[str]	=				self.clip_image_embeddings_project_to_time_embeddings(lowerCAmelCase__      )
								a      :		Dict	=				time_projected_image_embeddings + time_projected_prompt_embeds

								# ... and by projecting CLIP embeddings into four
								# extra tokens of context that are concatenated to the sequence of outputs from the GLIDE text encoder"
								a      :		Union[str, Any]	=				self.clip_extra_context_tokens_proj(lowerCAmelCase__      )
								a      :		List[str]	=				clip_extra_context_tokens.reshape(lowerCAmelCase__      ,					-1      ,					self.clip_extra_context_tokens      )
								a      :		Optional[Any]	=				clip_extra_context_tokens.permute(0      ,					2      ,					1      )

								a      :		Optional[int]	=				self.encoder_hidden_states_proj(lowerCAmelCase__      )
								a      :		str	=				self.text_encoder_hidden_states_norm(lowerCAmelCase__      )
								a      :		List[str]	=				torch.cat([clip_extra_context_tokens, text_encoder_hidden_states]      ,					dim=1      )

								return text_encoder_hidden_states, additive_clip_time_embeddings









"""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     __a   (   *lowerCAmelCase__      ,					**lowerCAmelCase__      )	-> str:
										pass






		def       _SCREAMING_SNAKE_CASE		(	_lowercase						:    Tuple					) ->Dict:






			'''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						: Optional[Any]     	=			(
    '''https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'''
)


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






							@require_pytesseract
							@require_vision
							def     __a   (   self      ,					lowerCAmelCase__      ,					lowerCAmelCase__      ,					lowerCAmelCase__      )	-> Tuple:
								a      :		Tuple	=				pipeline(
								    "document-question-answering"      ,					model=lowerCAmelCase__      ,					tokenizer=lowerCAmelCase__      ,					image_processor=lowerCAmelCase__      )

								a      :		Optional[int]	=				INVOICE_URL
								a      :		str	=				list(zip(*apply_tesseract(load_image(lowerCAmelCase__      )      ,					lowerCAmelCase__      ,					""      )      )      )
								a      :		Union[str, Any]	=				"What is the placebo?"
								a      :		Dict	=				[
								    {
								        "image": load_image(lowerCAmelCase__      ),
								        "question": question,
								    },
								    {
								        "image": image,
								        "question": question,
								    },
								    {
								        "image": image,
								        "question": question,
								        "word_boxes": word_boxes,
								    },
								]
								return dqa_pipeline, examples






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

								a      :		Tuple	=				[
								    {"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},
								]
								a      :		Optional[int]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(nested_simplify(lowerCAmelCase__      ,					decimals=4      )      ,					lowerCAmelCase__      )

								a      :		Optional[int]	=				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
								a      :		List[Any]	=				"./tests/fixtures/tests_samples/COCO/000000039769.png"
								a      :		Any	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(lowerCAmelCase__      ,					[]      )

								# We can optionnally pass directly the words and bounding boxes
								a      :		Optional[int]	=				"./tests/fixtures/tests_samples/COCO/000000039769.png"
								a      :		Tuple	=				[]
								a      :		Optional[int]	=				[]
								a      :		List[str]	=				dqa_pipeline(image=lowerCAmelCase__      ,					question=lowerCAmelCase__      ,					words=lowerCAmelCase__      ,					boxes=lowerCAmelCase__      ,					top_k=2      )
								self.assertEqual(lowerCAmelCase__      ,					[]      )






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

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

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

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

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

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

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

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

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

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

								a      :		Dict	=				list(zip(*apply_tesseract(load_image(lowerCAmelCase__      )      ,					lowerCAmelCase__      ,					""      )      )      )

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

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

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

								a      :		List[Any]	=				list(zip(*apply_tesseract(load_image(lowerCAmelCase__      )      ,					lowerCAmelCase__      ,					""      )      )      )

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

								a      :		Optional[Any]	=				INVOICE_URL
								a      :		Tuple	=				"What is the invoice number?"
								a      :		List[Any]	=				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     __a   (   self      )	-> int:
								pass


