


from dataclasses import dataclass
from typing import Dict, Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder
@dataclass
class        _lowercase      (			A__       ):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			"DiagonalGaussianDistribution"




class        _lowercase      (			A__						,			A__       ):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			Dict						=		True


				@register_to_config
				def __init__(       self			:str			,			lowerCAmelCase__			:int = 3			,			lowerCAmelCase__			:int = 3			,			lowerCAmelCase__			:Tuple[str] = ("DownEncoderBlock2D",)			,			lowerCAmelCase__			:Tuple[str] = ("UpDecoderBlock2D",)			,			lowerCAmelCase__			:Tuple[int] = (64,)			,			lowerCAmelCase__			:int = 1			,			lowerCAmelCase__			:str = "silu"			,			lowerCAmelCase__			:int = 4			,			lowerCAmelCase__			:int = 32			,			lowerCAmelCase__			:int = 32			,			lowerCAmelCase__			:float = 0.1_8215			,			)		->			str:
										super().__init__()

										# pass init params to Encoder
										__SCREAMING_SNAKE_CASE						:     int					=		Encoder(
										    in_channels=lowerCAmelCase__			,			out_channels=lowerCAmelCase__			,			down_block_types=lowerCAmelCase__			,			block_out_channels=lowerCAmelCase__			,			layers_per_block=lowerCAmelCase__			,			act_fn=lowerCAmelCase__			,			norm_num_groups=lowerCAmelCase__			,			double_z=lowerCAmelCase__			,			)

										# pass init params to Decoder
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		Decoder(
										    in_channels=lowerCAmelCase__			,			out_channels=lowerCAmelCase__			,			up_block_types=lowerCAmelCase__			,			block_out_channels=lowerCAmelCase__			,			layers_per_block=lowerCAmelCase__			,			norm_num_groups=lowerCAmelCase__			,			act_fn=lowerCAmelCase__			,			)

										__SCREAMING_SNAKE_CASE						:     str					=		nn.Convad(2 * latent_channels			,			2 * latent_channels			,			1	)
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		nn.Convad(lowerCAmelCase__			,			lowerCAmelCase__			,			1	)

										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		False
										__SCREAMING_SNAKE_CASE						:     str					=		False

										# only relevant if vae tiling is enabled
										__SCREAMING_SNAKE_CASE						:     Any					=		self.config.sample_size
										__SCREAMING_SNAKE_CASE						:     Tuple					=		(
										    self.config.sample_size[0]
										    if isinstance(self.config.sample_size			,			(list, tuple)	)
										    else self.config.sample_size
										)
										__SCREAMING_SNAKE_CASE						:     str					=		int(sample_size / (2 ** (len(self.config.block_out_channels	) - 1))	)
										__SCREAMING_SNAKE_CASE						:     int					=		0.25


				def 		__magic_name__(       self			:Union[str, Any]			,			lowerCAmelCase__			:List[str]			,			lowerCAmelCase__			:Optional[int]=False	)		->			List[str]:
										if isinstance(lowerCAmelCase__			,			(Encoder, Decoder)	):
																__SCREAMING_SNAKE_CASE						:     List[str]					=		value


				def 		__magic_name__(       self			:Optional[Any]			,			lowerCAmelCase__			:bool = True	)		->			Union[str, Any]:
										__SCREAMING_SNAKE_CASE						:     Tuple					=		use_tiling


				def 		__magic_name__(       self			:Union[str, Any]	)		->			int:
										self.enable_tiling(lowerCAmelCase__	)


				def 		__magic_name__(       self			:Tuple	)		->			Tuple:
										__SCREAMING_SNAKE_CASE						:     Any					=		True


				def 		__magic_name__(       self			:Optional[Any]	)		->			int:
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		False


				@property
				# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
				def 		__magic_name__(       self			:Tuple	)		->			Dict[str, AttentionProcessor]:
										__SCREAMING_SNAKE_CASE						:     Dict					=		{}

										def fn_recursive_add_processors(lowerCAmelCase__			:str			,			lowerCAmelCase__			:torch.nn.Module			,			lowerCAmelCase__			:Dict[str, AttentionProcessor]	):
																if hasattr(lowerCAmelCase__			,			'''set_processor'''	):
																						__SCREAMING_SNAKE_CASE						:     Optional[int]					=		module.processor

																for sub_name, child in module.named_children():
																						fn_recursive_add_processors(f'''{name}.{sub_name}'''			,			lowerCAmelCase__			,			lowerCAmelCase__	)

																return processors

										for name, module in self.named_children():
																fn_recursive_add_processors(lowerCAmelCase__			,			lowerCAmelCase__			,			lowerCAmelCase__	)

										return processors


				def 		__magic_name__(       self			:Union[str, Any]			,			lowerCAmelCase__			:Union[AttentionProcessor, Dict[str, AttentionProcessor]]	)		->			Optional[int]:
										__SCREAMING_SNAKE_CASE						:     Tuple					=		len(self.attn_processors.keys()	)

										if isinstance(lowerCAmelCase__			,			lowerCAmelCase__	) and len(lowerCAmelCase__	) != count:
																raise ValueError(
																    f'''A dict of processors was passed, but the number of processors {len(lowerCAmelCase__	)} does not match the'''
																    f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.'''	)

										def fn_recursive_attn_processor(lowerCAmelCase__			:str			,			lowerCAmelCase__			:torch.nn.Module			,			lowerCAmelCase__			:Tuple	):
																if hasattr(lowerCAmelCase__			,			'''set_processor'''	):
																						if not isinstance(lowerCAmelCase__			,			lowerCAmelCase__	):
																												module.set_processor(lowerCAmelCase__	)
																						else:
																												module.set_processor(processor.pop(f'''{name}.processor'''	)	)

																for sub_name, child in module.named_children():
																						fn_recursive_attn_processor(f'''{name}.{sub_name}'''			,			lowerCAmelCase__			,			lowerCAmelCase__	)

										for name, module in self.named_children():
																fn_recursive_attn_processor(lowerCAmelCase__			,			lowerCAmelCase__			,			lowerCAmelCase__	)


				def 		__magic_name__(       self			:Dict	)		->			List[Any]:
										self.set_attn_processor(AttnProcessor()	)


				@apply_forward_hook
				def 		__magic_name__(       self			:Optional[int]			,			lowerCAmelCase__			:torch.FloatTensor			,			lowerCAmelCase__			:bool = True	)		->			AutoencoderKLOutput:
										if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
																return self.tiled_encode(lowerCAmelCase__			,			return_dict=lowerCAmelCase__	)

										if self.use_slicing and x.shape[0] > 1:
																__SCREAMING_SNAKE_CASE						:     List[Any]					=		[self.encoder(lowerCAmelCase__	) for x_slice in x.split(1	)]
																__SCREAMING_SNAKE_CASE						:     Tuple					=		torch.cat(lowerCAmelCase__	)
										else:
																__SCREAMING_SNAKE_CASE						:     str					=		self.encoder(lowerCAmelCase__	)

										__SCREAMING_SNAKE_CASE						:     List[str]					=		self.quant_conv(lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		DiagonalGaussianDistribution(lowerCAmelCase__	)

										if not return_dict:
																return (posterior,)

										return AutoencoderKLOutput(latent_dist=lowerCAmelCase__	)


				def 		__magic_name__(       self			:str			,			lowerCAmelCase__			:torch.FloatTensor			,			lowerCAmelCase__			:bool = True	)		->			Union[DecoderOutput, torch.FloatTensor]:
										if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
																return self.tiled_decode(lowerCAmelCase__			,			return_dict=lowerCAmelCase__	)

										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		self.post_quant_conv(lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     int					=		self.decoder(lowerCAmelCase__	)

										if not return_dict:
																return (dec,)

										return DecoderOutput(sample=lowerCAmelCase__	)


				@apply_forward_hook
				def 		__magic_name__(       self			:Union[str, Any]			,			lowerCAmelCase__			:torch.FloatTensor			,			lowerCAmelCase__			:bool = True	)		->			Union[DecoderOutput, torch.FloatTensor]:
										if self.use_slicing and z.shape[0] > 1:
																__SCREAMING_SNAKE_CASE						:     Optional[int]					=		[self._decode(lowerCAmelCase__	).sample for z_slice in z.split(1	)]
																__SCREAMING_SNAKE_CASE						:     str					=		torch.cat(lowerCAmelCase__	)
										else:
																__SCREAMING_SNAKE_CASE						:     Tuple					=		self._decode(lowerCAmelCase__	).sample

										if not return_dict:
																return (decoded,)

										return DecoderOutput(sample=lowerCAmelCase__	)


				def 		__magic_name__(       self			:Dict			,			lowerCAmelCase__			:Optional[int]			,			lowerCAmelCase__			:List[str]			,			lowerCAmelCase__			:Any	)		->			Any:
										__SCREAMING_SNAKE_CASE						:     Tuple					=		min(a.shape[2]			,			b.shape[2]			,			lowerCAmelCase__	)
										for y in range(lowerCAmelCase__	):
																__SCREAMING_SNAKE_CASE						:     Any					=		a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
										return b


				def 		__magic_name__(       self			:Dict			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:str			,			lowerCAmelCase__			:str	)		->			List[Any]:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		min(a.shape[3]			,			b.shape[3]			,			lowerCAmelCase__	)
										for x in range(lowerCAmelCase__	):
																__SCREAMING_SNAKE_CASE						:     str					=		a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
										return b


				def 		__magic_name__(       self			:Union[str, Any]			,			lowerCAmelCase__			:torch.FloatTensor			,			lowerCAmelCase__			:bool = True	)		->			AutoencoderKLOutput:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)	)
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		int(self.tile_latent_min_size * self.tile_overlap_factor	)
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		self.tile_latent_min_size - blend_extent

										# Split the image into 512x512 tiles and encode them separately.
										__SCREAMING_SNAKE_CASE						:     str					=		[]
										for i in range(0			,			x.shape[2]			,			lowerCAmelCase__	):
																__SCREAMING_SNAKE_CASE						:     Dict					=		[]
																for j in range(0			,			x.shape[3]			,			lowerCAmelCase__	):
																						__SCREAMING_SNAKE_CASE						:     Dict					=		x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
																						__SCREAMING_SNAKE_CASE						:     Any					=		self.encoder(lowerCAmelCase__	)
																						__SCREAMING_SNAKE_CASE						:     str					=		self.quant_conv(lowerCAmelCase__	)
																						row.append(lowerCAmelCase__	)
																rows.append(lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     Any					=		[]
										for i, row in enumerate(lowerCAmelCase__	):
																__SCREAMING_SNAKE_CASE						:     str					=		[]
																for j, tile in enumerate(lowerCAmelCase__	):
																						# blend the above tile and the left tile
																						# to the current tile and add the current tile to the result row
																						if i > 0:
																												__SCREAMING_SNAKE_CASE						:     int					=		self.blend_v(rows[i - 1][j]			,			lowerCAmelCase__			,			lowerCAmelCase__	)
																						if j > 0:
																												__SCREAMING_SNAKE_CASE						:     Optional[int]					=		self.blend_h(row[j - 1]			,			lowerCAmelCase__			,			lowerCAmelCase__	)
																						result_row.append(tile[:, :, :row_limit, :row_limit]	)
																result_rows.append(torch.cat(lowerCAmelCase__			,			dim=3	)	)

										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		torch.cat(lowerCAmelCase__			,			dim=2	)
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		DiagonalGaussianDistribution(lowerCAmelCase__	)

										if not return_dict:
																return (posterior,)

										return AutoencoderKLOutput(latent_dist=lowerCAmelCase__	)


				def 		__magic_name__(       self			:Union[str, Any]			,			lowerCAmelCase__			:torch.FloatTensor			,			lowerCAmelCase__			:bool = True	)		->			Union[DecoderOutput, torch.FloatTensor]:
										__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)	)
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		int(self.tile_sample_min_size * self.tile_overlap_factor	)
										__SCREAMING_SNAKE_CASE						:     int					=		self.tile_sample_min_size - blend_extent

										# Split z into overlapping 64x64 tiles and decode them separately.
										# The tiles have an overlap to avoid seams between tiles.
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		[]
										for i in range(0			,			z.shape[2]			,			lowerCAmelCase__	):
																__SCREAMING_SNAKE_CASE						:     str					=		[]
																for j in range(0			,			z.shape[3]			,			lowerCAmelCase__	):
																						__SCREAMING_SNAKE_CASE						:     Dict					=		z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
																						__SCREAMING_SNAKE_CASE						:     List[Any]					=		self.post_quant_conv(lowerCAmelCase__	)
																						__SCREAMING_SNAKE_CASE						:     List[str]					=		self.decoder(lowerCAmelCase__	)
																						row.append(lowerCAmelCase__	)
																rows.append(lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		[]
										for i, row in enumerate(lowerCAmelCase__	):
																__SCREAMING_SNAKE_CASE						:     Tuple					=		[]
																for j, tile in enumerate(lowerCAmelCase__	):
																						# blend the above tile and the left tile
																						# to the current tile and add the current tile to the result row
																						if i > 0:
																												__SCREAMING_SNAKE_CASE						:     Optional[Any]					=		self.blend_v(rows[i - 1][j]			,			lowerCAmelCase__			,			lowerCAmelCase__	)
																						if j > 0:
																												__SCREAMING_SNAKE_CASE						:     List[Any]					=		self.blend_h(row[j - 1]			,			lowerCAmelCase__			,			lowerCAmelCase__	)
																						result_row.append(tile[:, :, :row_limit, :row_limit]	)
																result_rows.append(torch.cat(lowerCAmelCase__			,			dim=3	)	)

										__SCREAMING_SNAKE_CASE						:     str					=		torch.cat(lowerCAmelCase__			,			dim=2	)
										if not return_dict:
																return (dec,)

										return DecoderOutput(sample=lowerCAmelCase__	)



				def 		__magic_name__(       self			:int			,			lowerCAmelCase__			:torch.FloatTensor			,			lowerCAmelCase__			:bool = False			,			lowerCAmelCase__			:bool = True			,			lowerCAmelCase__			:Optional[torch.Generator] = None			,			)		->			Union[DecoderOutput, torch.FloatTensor]:
										__SCREAMING_SNAKE_CASE						:     str					=		sample
										__SCREAMING_SNAKE_CASE						:     str					=		self.encode(lowerCAmelCase__	).latent_dist
										if sample_posterior:
																__SCREAMING_SNAKE_CASE						:     List[str]					=		posterior.sample(generator=lowerCAmelCase__	)
										else:
																__SCREAMING_SNAKE_CASE						:     int					=		posterior.mode()
										__SCREAMING_SNAKE_CASE						:     str					=		self.decode(lowerCAmelCase__	).sample

										if not return_dict:
																return (dec,)

										return DecoderOutput(sample=lowerCAmelCase__	)




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        _lowercase      :






										'''simple docstring'''



										@staticmethod
										def 		__magic_name__(       *lowerCAmelCase__			:Union[str, Any]			,			**lowerCAmelCase__			:str	)		->			Union[str, Any]:
																pass




						def        _UpperCamelCase							(      lowercase__      ):
												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.
__lowerCAmelCase	: str  				=(
    'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)
@is_pipeline_test
@require_torch
@require_vision
class        _lowercase      (			unittest.TestCase       ):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE__				:			Tuple						=		MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING


				@require_pytesseract
				@require_vision
				def 		__magic_name__(       self			:Any			,			lowerCAmelCase__			:List[str]			,			lowerCAmelCase__			:Optional[Any]			,			lowerCAmelCase__			:Any	)		->			Any:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		pipeline(
										    '''document-question-answering'''			,			model=lowerCAmelCase__			,			tokenizer=lowerCAmelCase__			,			image_processor=lowerCAmelCase__	)

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


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

										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		[
										    {'''score''': 0.0001, '''answer''': '''oy 2312/2019''', '''start''': 38, '''end''': 39},
										    {'''score''': 0.0001, '''answer''': '''oy 2312/2019 DUE''', '''start''': 38, '''end''': 40},
										]
										__SCREAMING_SNAKE_CASE						:     Tuple					=		dqa_pipeline(image=lowerCAmelCase__			,			question=lowerCAmelCase__			,			top_k=2	)
										self.assertEqual(nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			lowerCAmelCase__	)

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

										# We can optionnally pass directly the words and bounding boxes
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		'''./tests/fixtures/tests_samples/COCO/000000039769.png'''
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		[]
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		[]
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		dqa_pipeline(image=lowerCAmelCase__			,			question=lowerCAmelCase__			,			words=lowerCAmelCase__			,			boxes=lowerCAmelCase__			,			top_k=2	)
										self.assertEqual(lowerCAmelCase__			,			[]	)


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

										__SCREAMING_SNAKE_CASE						:     Any					=		dqa_pipeline(image=lowerCAmelCase__			,			question=lowerCAmelCase__			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     Tuple					=		dqa_pipeline({'''image''': image, '''question''': question}			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     List[Any]					=		dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        [
										            {'''score''': 0.9944, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										            {'''score''': 0.0009, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        ],
										    ]
										    * 2			,			)


				@slow
				@require_torch
				@require_detectrona
				@require_pytesseract
				def 		__magic_name__(       self			:Optional[Any]	)		->			Any:
										__SCREAMING_SNAKE_CASE						:     int					=		pipeline(
										    '''document-question-answering'''			,			model='''tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa'''			,			revision='''9977165'''			,			max_seq_len=50			,			)
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		INVOICE_URL
										__SCREAMING_SNAKE_CASE						:     Tuple					=		'''What is the invoice number?'''

										__SCREAMING_SNAKE_CASE						:     List[str]					=		dqa_pipeline(image=lowerCAmelCase__			,			question=lowerCAmelCase__			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										        {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     int					=		dqa_pipeline({'''image''': image, '''question''': question}			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										        {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     str					=		dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        [
										            {'''score''': 0.9974, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										            {'''score''': 0.9948, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        ]
										    ]
										    * 2			,			)


				@slow
				@require_torch
				@require_pytesseract
				@require_vision
				def 		__magic_name__(       self			:int	)		->			List[Any]:
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		AutoTokenizer.from_pretrained(
										    '''impira/layoutlm-document-qa'''			,			revision='''3dc6de3'''			,			add_prefix_space=lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     Dict					=		pipeline(
										    '''document-question-answering'''			,			model='''impira/layoutlm-document-qa'''			,			tokenizer=lowerCAmelCase__			,			revision='''3dc6de3'''			,			)
										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		INVOICE_URL
										__SCREAMING_SNAKE_CASE						:     str					=		'''What is the invoice number?'''

										__SCREAMING_SNAKE_CASE						:     Dict					=		dqa_pipeline(image=lowerCAmelCase__			,			question=lowerCAmelCase__			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		dqa_pipeline({'''image''': image, '''question''': question}			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        [
										            {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										            {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										        ]
										    ]
										    * 2			,			)

										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		list(zip(*apply_tesseract(load_image(lowerCAmelCase__	)			,			lowerCAmelCase__			,			''''''	)	)	)

										# This model should also work if `image` is set to None
										__SCREAMING_SNAKE_CASE						:     str					=		dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.4251, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.0819, '''answer''': '''1110212019''', '''start''': 23, '''end''': 23},
										    ]			,			)


				@slow
				@require_torch
				@require_pytesseract
				@require_vision
				def 		__magic_name__(       self			:str	)		->			Dict:
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		AutoTokenizer.from_pretrained(
										    '''impira/layoutlm-document-qa'''			,			revision='''3dc6de3'''			,			add_prefix_space=lowerCAmelCase__	)
										__SCREAMING_SNAKE_CASE						:     Tuple					=		pipeline(
										    '''document-question-answering'''			,			model='''impira/layoutlm-document-qa'''			,			tokenizer=lowerCAmelCase__			,			revision='''3dc6de3'''			,			max_seq_len=50			,			)
										__SCREAMING_SNAKE_CASE						:     List[str]					=		INVOICE_URL
										__SCREAMING_SNAKE_CASE						:     Dict					=		'''What is the invoice number?'''

										__SCREAMING_SNAKE_CASE						:     List[Any]					=		dqa_pipeline(image=lowerCAmelCase__			,			question=lowerCAmelCase__			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]			,			)

										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		dqa_pipeline(
										    [{'''image''': image, '''question''': question}, {'''image''': image, '''question''': question}]			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        [
										            {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										            {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        ]
										    ]
										    * 2			,			)

										__SCREAMING_SNAKE_CASE						:     List[str]					=		list(zip(*apply_tesseract(load_image(lowerCAmelCase__	)			,			lowerCAmelCase__			,			''''''	)	)	)

										# This model should also work if `image` is set to None
										__SCREAMING_SNAKE_CASE						:     List[Any]					=		dqa_pipeline({'''image''': None, '''word_boxes''': word_boxes, '''question''': question}			,			top_k=2	)
										self.assertEqual(
										    nested_simplify(lowerCAmelCase__			,			decimals=4	)			,			[
										        {'''score''': 0.9999, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										        {'''score''': 0.9998, '''answer''': '''us-001''', '''start''': 16, '''end''': 16},
										    ]			,			)


				@slow
				@require_torch
				def 		__magic_name__(       self			:Union[str, Any]	)		->			Tuple:
										__SCREAMING_SNAKE_CASE						:     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'''			,			)

										__SCREAMING_SNAKE_CASE						:     Union[str, Any]					=		INVOICE_URL
										__SCREAMING_SNAKE_CASE						:     Optional[int]					=		'''What is the invoice number?'''
										__SCREAMING_SNAKE_CASE						:     Tuple					=		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 		__magic_name__(       self			:Union[str, Any]	)		->			Tuple:
										pass
