



import inspect
import unittest

from transformers import YolosConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import YolosForObjectDetection, YolosModel
					from transformers.models.yolos.modeling_yolos import YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor


class     __SCREAMING_SNAKE_CASE					:






						def __init__(	self     ,						_UpperCamelCase     ,						_UpperCamelCase=13     ,						_UpperCamelCase=[30, 30]     ,						_UpperCamelCase=2     ,						_UpperCamelCase=3     ,						_UpperCamelCase=True     ,						_UpperCamelCase=True     ,						_UpperCamelCase=32     ,						_UpperCamelCase=5     ,						_UpperCamelCase=4     ,						_UpperCamelCase=37     ,						_UpperCamelCase="gelu"     ,						_UpperCamelCase=0.1     ,						_UpperCamelCase=0.1     ,						_UpperCamelCase=10     ,						_UpperCamelCase=0.02     ,						_UpperCamelCase=3     ,						_UpperCamelCase=None     ,						_UpperCamelCase=8     ,						_UpperCamelCase=10     ,						):






												"""simple docstring"""
												lowerCAmelCase__    						=						parent
												lowerCAmelCase__    						=						batch_size
												lowerCAmelCase__    						=						image_size
												lowerCAmelCase__    						=						patch_size
												lowerCAmelCase__    						=						num_channels
												lowerCAmelCase__    						=						is_training
												lowerCAmelCase__    						=						use_labels
												lowerCAmelCase__    						=						hidden_size
												lowerCAmelCase__    						=						num_hidden_layers
												lowerCAmelCase__    						=						num_attention_heads
												lowerCAmelCase__    						=						intermediate_size
												lowerCAmelCase__    						=						hidden_act
												lowerCAmelCase__    						=						hidden_dropout_prob
												lowerCAmelCase__    						=						attention_probs_dropout_prob
												lowerCAmelCase__    						=						type_sequence_label_size
												lowerCAmelCase__    						=						initializer_range
												lowerCAmelCase__    						=						num_labels
												lowerCAmelCase__    						=						scope
												lowerCAmelCase__    						=						n_targets
												lowerCAmelCase__    						=						num_detection_tokens
												# we set the expected sequence length (which is used in several tests)
												# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token) + num_detection_tokens
												lowerCAmelCase__    						=						(image_size[1] // patch_size) * (image_size[0] // patch_size)
												lowerCAmelCase__    						=						num_patches + 1 + self.num_detection_tokens






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]   )

												lowerCAmelCase__    						=						None
												if self.use_labels:
																		# labels is a list of Dict (each Dict being the labels for a given example in the batch)
																		lowerCAmelCase__    						=						[]
																		for i in range(self.batch_size   ):
																								lowerCAmelCase__    						=						{}
																								lowerCAmelCase__    						=						torch.randint(
																								    high=self.num_labels     ,						size=(self.n_targets,)     ,						device=_UpperCamelCase   )
																								lowerCAmelCase__    						=						torch.rand(self.n_targets     ,						4     ,						device=_UpperCamelCase   )
																								labels.append(_UpperCamelCase   )

												lowerCAmelCase__    						=						self.get_config()

												return config, pixel_values, labels






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												return YolosConfig(
												    image_size=self.image_size     ,						patch_size=self.patch_size     ,						num_channels=self.num_channels     ,						hidden_size=self.hidden_size     ,						num_hidden_layers=self.num_hidden_layers     ,						num_attention_heads=self.num_attention_heads     ,						intermediate_size=self.intermediate_size     ,						hidden_act=self.hidden_act     ,						hidden_dropout_prob=self.hidden_dropout_prob     ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,						is_decoder=_UpperCamelCase     ,						initializer_range=self.initializer_range     ,						num_detection_tokens=self.num_detection_tokens     ,						num_labels=self.num_labels     ,						)






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosModel(config=_UpperCamelCase   )
												model.to(_UpperCamelCase   )
												model.eval()
												lowerCAmelCase__    						=						model(_UpperCamelCase   )
												self.parent.assertEqual(
												    result.last_hidden_state.shape     ,						(self.batch_size, self.expected_seq_len, self.hidden_size)   )






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosForObjectDetection(_UpperCamelCase   )
												model.to(_UpperCamelCase   )
												model.eval()

												lowerCAmelCase__    						=						model(pixel_values=_UpperCamelCase   )
												lowerCAmelCase__    						=						model(_UpperCamelCase   )

												self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_detection_tokens, self.num_labels + 1)   )
												self.parent.assertEqual(result.pred_boxes.shape     ,						(self.batch_size, self.num_detection_tokens, 4)   )

												lowerCAmelCase__    						=						model(pixel_values=_UpperCamelCase     ,						labels=_UpperCamelCase   )

												self.parent.assertEqual(result.loss.shape     ,						()   )
												self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_detection_tokens, self.num_labels + 1)   )
												self.parent.assertEqual(result.pred_boxes.shape     ,						(self.batch_size, self.num_detection_tokens, 4)   )







						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.prepare_config_and_inputs()
												lowerCAmelCase__						,       lowerCAmelCase__						,       lowerCAmelCase__    						=						config_and_inputs
												lowerCAmelCase__    						=						{'pixel_values': pixel_values}
												return config, inputs_dict




@require_torch
class     __SCREAMING_SNAKE_CASE					(   __lowercase		,					__lowercase		,					unittest.TestCase):
						_SCREAMING_SNAKE_CASE	:       Tuple   =					(YolosModel, YolosForObjectDetection) if is_torch_available() else ()
						_SCREAMING_SNAKE_CASE	:       int   =					(
						    {'''feature-extraction''': YolosModel, '''object-detection''': YolosForObjectDetection} if is_torch_available() else {}
						)

						_SCREAMING_SNAKE_CASE	:       int   =					False
						_SCREAMING_SNAKE_CASE	:       List[str]   =					False
						_SCREAMING_SNAKE_CASE	:       Union[str, Any]   =					False
						_SCREAMING_SNAKE_CASE	:       Any   =					False






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase=False   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						super()._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase     ,						return_labels=_UpperCamelCase   )

												if return_labels:
																		if model_class.__name__ == "YolosForObjectDetection":
																								lowerCAmelCase__    						=						[]
																								for i in range(self.model_tester.batch_size   ):
																														lowerCAmelCase__    						=						{}
																														lowerCAmelCase__    						=						torch.ones(
																														    size=(self.model_tester.n_targets,)     ,						device=_UpperCamelCase     ,						dtype=torch.long   )
																														lowerCAmelCase__    						=						torch.ones(
																														    self.model_tester.n_targets     ,						4     ,						device=_UpperCamelCase     ,						dtype=torch.float   )
																														labels.append(_UpperCamelCase   )
																								lowerCAmelCase__    						=						labels

												return inputs_dict






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosModelTester(self   )
												lowerCAmelCase__    						=						ConfigTester(self     ,						config_class=_UpperCamelCase     ,						has_text_modality=_UpperCamelCase     ,						hidden_size=37   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												self.config_tester.run_common_tests()






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												pass






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		self.assertIsInstance(model.get_input_embeddings()     ,						(nn.Module)   )
																		lowerCAmelCase__    						=						model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(_UpperCamelCase     ,						nn.Linear   )   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		lowerCAmelCase__    						=						inspect.signature(model.forward   )
																		# signature.parameters is an OrderedDict => so arg_names order is deterministic
																		lowerCAmelCase__    						=						[*signature.parameters.keys()]

																		lowerCAmelCase__    						=						['pixel_values']
																		self.assertListEqual(arg_names[:1]     ,						_UpperCamelCase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*_UpperCamelCase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()
												lowerCAmelCase__    						=						True

												# in YOLOS, the seq_len is different
												lowerCAmelCase__    						=						self.model_tester.expected_seq_len
												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						False
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()
																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )
																		lowerCAmelCase__    						=						outputs.attentions
																		self.assertEqual(len(_UpperCamelCase   )     ,						self.model_tester.num_hidden_layers   )

																		# check that output_attentions also work using config
																		del inputs_dict["output_attentions"]
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()
																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )
																		lowerCAmelCase__    						=						outputs.attentions
																		self.assertEqual(len(_UpperCamelCase   )     ,						self.model_tester.num_hidden_layers   )

																		self.assertListEqual(
																		    list(attentions[0].shape[-3:]   )     ,						[self.model_tester.num_attention_heads, seq_len, seq_len]     ,						)
																		lowerCAmelCase__    						=						len(_UpperCamelCase   )

																		# Check attention is always last and order is fine
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						True
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()
																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )

																		lowerCAmelCase__    						=						1
																		self.assertEqual(out_len + added_hidden_states     ,						len(_UpperCamelCase   )   )

																		lowerCAmelCase__    						=						outputs.attentions

																		self.assertEqual(len(_UpperCamelCase   )     ,						self.model_tester.num_hidden_layers   )
																		self.assertListEqual(
																		    list(self_attentions[0].shape[-3:]   )     ,						[self.model_tester.num_attention_heads, seq_len, seq_len]     ,						)






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												def check_hidden_states_output(_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):
																		lowerCAmelCase__    						=						model_class(_UpperCamelCase   )
																		model.to(_UpperCamelCase   )
																		model.eval()

																		with torch.no_grad():
																								lowerCAmelCase__    						=						model(**self._prepare_for_class(_UpperCamelCase     ,						_UpperCamelCase   )   )

																		lowerCAmelCase__    						=						outputs.hidden_states

																		lowerCAmelCase__    						=						getattr(
																		    self.model_tester     ,						'expected_num_hidden_layers'     ,						self.model_tester.num_hidden_layers + 1   )
																		self.assertEqual(len(_UpperCamelCase   )     ,						_UpperCamelCase   )

																		# YOLOS has a different seq_length
																		lowerCAmelCase__    						=						self.model_tester.expected_seq_len

																		self.assertListEqual(
																		    list(hidden_states[0].shape[-2:]   )     ,						[seq_length, self.model_tester.hidden_size]     ,						)

												lowerCAmelCase__						,       lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																		lowerCAmelCase__    						=						True
																		check_hidden_states_output(_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   )

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		lowerCAmelCase__    						=						True

																		check_hidden_states_output(_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   )






						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_object_detection(*_UpperCamelCase   )







						@slow
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												for model_name in YOLOS_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		lowerCAmelCase__    						=						YolosModel.from_pretrained(_UpperCamelCase   )
																		self.assertIsNotNone(_UpperCamelCase   )







def 	_UpperCamelCase   (    )  ->   List[Any]:

						"""simple docstring"""



						lowerCAmelCase__    						=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
						return image


@require_torch
@require_vision
class     __SCREAMING_SNAKE_CASE					(   unittest.TestCase):






						@cached_property
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												return AutoImageProcessor.from_pretrained('hustvl/yolos-small'   ) if is_vision_available() else None







						@slow
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						YolosForObjectDetection.from_pretrained('hustvl/yolos-small'   ).to(_UpperCamelCase   )

												lowerCAmelCase__    						=						self.default_image_processor
												lowerCAmelCase__    						=						prepare_img()
												lowerCAmelCase__    						=						image_processor(images=_UpperCamelCase     ,						return_tensors='pt'   ).to(_UpperCamelCase   )

												# forward pass
												with torch.no_grad():
																		lowerCAmelCase__    						=						model(inputs.pixel_values   )

												# verify outputs
												lowerCAmelCase__    						=						torch.Size((1, 1_00, 92)   )
												self.assertEqual(outputs.logits.shape     ,						_UpperCamelCase   )

												lowerCAmelCase__    						=						torch.tensor(
												    [[-24.02_48, -10.30_24, -14.82_90], [-42.03_92, -16.82_00, -27.43_34], [-27.27_43, -11.81_54, -18.71_48]]     ,						device=_UpperCamelCase     ,						)
												lowerCAmelCase__    						=						torch.tensor(
												    [[0.25_59, 0.54_55, 0.47_06], [0.29_89, 0.72_79, 0.18_75], [0.77_32, 0.40_17, 0.44_62]]     ,						device=_UpperCamelCase   )
												self.assertTrue(torch.allclose(outputs.logits[0, :3, :3]     ,						_UpperCamelCase     ,						atol=1E-4   )   )
												self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3]     ,						_UpperCamelCase     ,						atol=1E-4   )   )

												# verify postprocessing
												lowerCAmelCase__    						=						image_processor.post_process_object_detection(
												    _UpperCamelCase     ,						threshold=0.3     ,						target_sizes=[image.size[::-1]]   )[0]
												lowerCAmelCase__    						=						torch.tensor([0.99_94, 0.97_90, 0.99_64, 0.99_72, 0.98_61]   ).to(_UpperCamelCase   )
												lowerCAmelCase__    						=						[75, 75, 17, 63, 17]
												lowerCAmelCase__    						=						torch.tensor([3_35.06_09, 79.38_48, 3_75.42_16, 1_87.24_95]   ).to(_UpperCamelCase   )

												self.assertEqual(len(results['scores']   )     ,						5   )
												self.assertTrue(torch.allclose(results['scores']     ,						_UpperCamelCase     ,						atol=1E-4   )   )
												self.assertSequenceEqual(results['labels'].tolist()     ,						_UpperCamelCase   )
												self.assertTrue(torch.allclose(results['boxes'][0, :]     ,						_UpperCamelCase   )   )













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__      (	*_UpperCamelCase     ,						**_UpperCamelCase   ):






																	"""simple docstring"""
																	pass







					def 	_UpperCamelCase   (    UpperCamelCase_       :					Tuple		)  ->   Any:

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


@is_pipeline_test
@require_torch
@require_vision
class     __SCREAMING_SNAKE_CASE					(   unittest.TestCase):
						_SCREAMING_SNAKE_CASE	:       Dict   =					MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING






						@require_pytesseract
						@require_vision
						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						pipeline(
												    'document-question-answering'     ,						model=_UpperCamelCase     ,						tokenizer=_UpperCamelCase     ,						image_processor=_UpperCamelCase   )

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






						def       UpperCamelCase__      (	self     ,						_UpperCamelCase     ,						_UpperCamelCase   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						dqa_pipeline(_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(
												    _UpperCamelCase     ,						[
												        [
												            {'score': ANY(_UpperCamelCase   ), 'answer': ANY(_UpperCamelCase   ), 'start': ANY(_UpperCamelCase   ), 'end': ANY(_UpperCamelCase   )},
												            {'score': ANY(_UpperCamelCase   ), 'answer': ANY(_UpperCamelCase   ), 'start': ANY(_UpperCamelCase   ), 'end': ANY(_UpperCamelCase   )},
												        ]
												    ]
												    * 3     ,						)






						@require_torch
						@require_detectrona
						@require_pytesseract
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												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=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(nested_simplify(_UpperCamelCase     ,						decimals=4   )     ,						_UpperCamelCase   )

												lowerCAmelCase__    						=						dqa_pipeline({'image': image, 'question': question}     ,						top_k=2   )
												self.assertEqual(nested_simplify(_UpperCamelCase     ,						decimals=4   )     ,						_UpperCamelCase   )

												# 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=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(_UpperCamelCase     ,						[]   )

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






						@slow
						@require_torch
						@require_detectrona
						@require_pytesseract
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												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=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(
												    nested_simplify(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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   ):






												"""simple docstring"""
												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=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(
												    nested_simplify(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AutoTokenizer.from_pretrained(
												    'impira/layoutlm-document-qa'     ,						revision='3dc6de3'     ,						add_prefix_space=_UpperCamelCase   )
												lowerCAmelCase__    						=						pipeline(
												    'document-question-answering'     ,						model='impira/layoutlm-document-qa'     ,						tokenizer=_UpperCamelCase     ,						revision='3dc6de3'     ,						)
												lowerCAmelCase__    						=						INVOICE_URL
												lowerCAmelCase__    						=						'What is the invoice number?'

												lowerCAmelCase__    						=						dqa_pipeline(image=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(
												    nested_simplify(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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(_UpperCamelCase   )     ,						_UpperCamelCase     ,						''   )   )   )

												# 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(_UpperCamelCase     ,						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   ):






												"""simple docstring"""
												lowerCAmelCase__    						=						AutoTokenizer.from_pretrained(
												    'impira/layoutlm-document-qa'     ,						revision='3dc6de3'     ,						add_prefix_space=_UpperCamelCase   )
												lowerCAmelCase__    						=						pipeline(
												    'document-question-answering'     ,						model='impira/layoutlm-document-qa'     ,						tokenizer=_UpperCamelCase     ,						revision='3dc6de3'     ,						max_seq_len=50     ,						)
												lowerCAmelCase__    						=						INVOICE_URL
												lowerCAmelCase__    						=						'What is the invoice number?'

												lowerCAmelCase__    						=						dqa_pipeline(image=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(
												    nested_simplify(_UpperCamelCase     ,						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(_UpperCamelCase     ,						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(_UpperCamelCase   )     ,						_UpperCamelCase     ,						''   )   )   )

												# 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(_UpperCamelCase     ,						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   ):






												"""simple docstring"""
												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=_UpperCamelCase     ,						question=_UpperCamelCase     ,						top_k=2   )
												self.assertEqual(nested_simplify(_UpperCamelCase     ,						decimals=4   )     ,						[{'answer': 'us-001'}]   )







						@require_tf
						@unittest.skip('Document question answering not implemented in TF'   )
						def       UpperCamelCase__      (	self   ):






												"""simple docstring"""
												pass





