"""simple docstring"""




import copy
import unittest

from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
				import torch

				from transformers import (
				    MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
				    MODEL_FOR_QUESTION_ANSWERING_MAPPING,
				    MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
				    MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
				    LayoutLMvaConfig,
				    LayoutLMvaForQuestionAnswering,
				    LayoutLMvaForSequenceClassification,
				    LayoutLMvaForTokenClassification,
				    LayoutLMvaModel,
				)
				from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
				from PIL import Image

				from transformers import LayoutLMvaImageProcessor
class     UpperCamelCase__:





						def __init__(       self		,__UpperCAmelCase		,__UpperCAmelCase=2		,__UpperCAmelCase=3		,__UpperCAmelCase=4		,__UpperCAmelCase=2		,__UpperCAmelCase=7		,__UpperCAmelCase=True		,__UpperCAmelCase=True		,__UpperCAmelCase=True		,__UpperCAmelCase=True		,__UpperCAmelCase=99		,__UpperCAmelCase=36		,__UpperCAmelCase=3		,__UpperCAmelCase=4		,__UpperCAmelCase=37		,__UpperCAmelCase="gelu"		,__UpperCAmelCase=0.1		,__UpperCAmelCase=0.1		,__UpperCAmelCase=5_12		,__UpperCAmelCase=16		,__UpperCAmelCase=2		,__UpperCAmelCase=0.0_2		,__UpperCAmelCase=6		,__UpperCAmelCase=6		,__UpperCAmelCase=3		,__UpperCAmelCase=4		,__UpperCAmelCase=None		,__UpperCAmelCase=10_00		,)					->				Any:
													A__	     =							parent
													A__	     =							batch_size
													A__	     =							num_channels
													A__	     =							image_size
													A__	     =							patch_size
													A__	     =							text_seq_length
													A__	     =							is_training
													A__	     =							use_input_mask
													A__	     =							use_token_type_ids
													A__	     =							use_labels
													A__	     =							vocab_size
													A__	     =							hidden_size
													A__	     =							num_hidden_layers
													A__	     =							num_attention_heads
													A__	     =							intermediate_size
													A__	     =							hidden_act
													A__	     =							hidden_dropout_prob
													A__	     =							attention_probs_dropout_prob
													A__	     =							max_position_embeddings
													A__	     =							type_vocab_size
													A__	     =							type_sequence_label_size
													A__	     =							initializer_range
													A__	     =							coordinate_size
													A__	     =							shape_size
													A__	     =							num_labels
													A__	     =							num_choices
													A__	     =							scope
													A__	     =							range_bbox

													# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
													A__	     =							text_seq_length
													A__	     =							(image_size // patch_size) ** 2 + 1
													A__	     =							self.text_seq_length + self.image_seq_length





						def 				snake_case__	(       self     )					->				List[str]:
													A__	     =							ids_tensor([self.batch_size, self.text_seq_length]		,self.vocab_size     )

													A__	     =							ids_tensor([self.batch_size, self.text_seq_length, 4]		,self.range_bbox     )
													# Ensure that bbox is legal
													for i in range(bbox.shape[0]     ):
																				for j in range(bbox.shape[1]     ):
																											if bbox[i, j, 3] < bbox[i, j, 1]:
																																		A__	     =							bbox[i, j, 3]
																																		A__	     =							bbox[i, j, 1]
																																		A__	     =							t
																											if bbox[i, j, 2] < bbox[i, j, 0]:
																																		A__	     =							bbox[i, j, 2]
																																		A__	     =							bbox[i, j, 0]
																																		A__	     =							t

													A__	     =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

													A__	     =							None
													if self.use_input_mask:
																				A__	     =							random_attention_mask([self.batch_size, self.text_seq_length]     )

													A__	     =							None
													if self.use_token_type_ids:
																				A__	     =							ids_tensor([self.batch_size, self.text_seq_length]		,self.type_vocab_size     )

													A__	     =							None
													A__	     =							None
													if self.use_labels:
																				A__	     =							ids_tensor([self.batch_size]		,self.type_sequence_label_size     )
																				A__	     =							ids_tensor([self.batch_size, self.text_seq_length]		,self.num_labels     )

													A__	     =							LayoutLMvaConfig(
													    vocab_size=self.vocab_size		,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		,max_position_embeddings=self.max_position_embeddings		,type_vocab_size=self.type_vocab_size		,initializer_range=self.initializer_range		,coordinate_size=self.coordinate_size		,shape_size=self.shape_size		,input_size=self.image_size		,patch_size=self.patch_size		,)

													return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels





						def 				snake_case__	(       self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase     )					->				Tuple:
													A__	     =							LayoutLMvaModel(config=__UpperCAmelCase     )
													model.to(__UpperCAmelCase     )
													model.eval()

													# text + image
													A__	     =							model(__UpperCAmelCase		,pixel_values=__UpperCAmelCase     )
													A__	     =							model(
													    __UpperCAmelCase		,bbox=__UpperCAmelCase		,pixel_values=__UpperCAmelCase		,attention_mask=__UpperCAmelCase		,token_type_ids=__UpperCAmelCase     )
													A__	     =							model(__UpperCAmelCase		,bbox=__UpperCAmelCase		,pixel_values=__UpperCAmelCase		,token_type_ids=__UpperCAmelCase     )
													A__	     =							model(__UpperCAmelCase		,bbox=__UpperCAmelCase		,pixel_values=__UpperCAmelCase     )

													self.parent.assertEqual(result.last_hidden_state.shape		,(self.batch_size, self.seq_length, self.hidden_size)     )

													# text only
													A__	     =							model(__UpperCAmelCase     )
													self.parent.assertEqual(
													    result.last_hidden_state.shape		,(self.batch_size, self.text_seq_length, self.hidden_size)     )

													# image only
													A__	     =							model(pixel_values=__UpperCAmelCase     )
													self.parent.assertEqual(
													    result.last_hidden_state.shape		,(self.batch_size, self.image_seq_length, self.hidden_size)     )





						def 				snake_case__	(       self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase     )					->				Tuple:
													A__	     =							self.num_labels
													A__	     =							LayoutLMvaForSequenceClassification(__UpperCAmelCase     )
													model.to(__UpperCAmelCase     )
													model.eval()
													A__	     =							model(
													    __UpperCAmelCase		,bbox=__UpperCAmelCase		,pixel_values=__UpperCAmelCase		,attention_mask=__UpperCAmelCase		,token_type_ids=__UpperCAmelCase		,labels=__UpperCAmelCase		,)
													self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.num_labels)     )





						def 				snake_case__	(       self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase     )					->				Dict:
													A__	     =							self.num_labels
													A__	     =							LayoutLMvaForTokenClassification(config=__UpperCAmelCase     )
													model.to(__UpperCAmelCase     )
													model.eval()
													A__	     =							model(
													    __UpperCAmelCase		,bbox=__UpperCAmelCase		,pixel_values=__UpperCAmelCase		,attention_mask=__UpperCAmelCase		,token_type_ids=__UpperCAmelCase		,labels=__UpperCAmelCase		,)
													self.parent.assertEqual(result.logits.shape		,(self.batch_size, self.text_seq_length, self.num_labels)     )





						def 				snake_case__	(       self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase     )					->				Any:
													A__	     =							LayoutLMvaForQuestionAnswering(config=__UpperCAmelCase     )
													model.to(__UpperCAmelCase     )
													model.eval()
													A__	     =							model(
													    __UpperCAmelCase		,bbox=__UpperCAmelCase		,pixel_values=__UpperCAmelCase		,attention_mask=__UpperCAmelCase		,token_type_ids=__UpperCAmelCase		,start_positions=__UpperCAmelCase		,end_positions=__UpperCAmelCase		,)
													self.parent.assertEqual(result.start_logits.shape		,(self.batch_size, self.seq_length)     )
													self.parent.assertEqual(result.end_logits.shape		,(self.batch_size, self.seq_length)     )





						def 				snake_case__	(       self     )					->				Union[str, Any]:
													A__	     =							self.prepare_config_and_inputs()
													(
													    (
													    A__
													)     ,  (
													    A__
													)     ,  (
													    A__
													)     ,  (
													    A__
													)     ,  (
													    A__
													)     ,  (
													    A__
													)     ,  (
													    A__
													)     ,  (
													    A__
													)     ,  
													)	     =							config_and_inputs
													A__	     =							{
													    'input_ids': input_ids,
													    'bbox': bbox,
													    'pixel_values': pixel_values,
													    'token_type_ids': token_type_ids,
													    'attention_mask': input_mask,
													}
													return config, inputs_dict






@require_torch
class     UpperCamelCase__(			__A		,						__A		,						unittest.TestCase ):
						lowerCAmelCase__  :						int													=		False
						lowerCAmelCase__  :						List[str]													=		False
						lowerCAmelCase__  :						Optional[Any]													=		False

						lowerCAmelCase__  :						int													=		(
						    (
						        LayoutLMvaModel,
						        LayoutLMvaForSequenceClassification,
						        LayoutLMvaForTokenClassification,
						        LayoutLMvaForQuestionAnswering,
						    )
						    if is_torch_available()
						    else ()
						)
						lowerCAmelCase__  :						List[Any]													=		(
						    {'document-question-answering': LayoutLMvaForQuestionAnswering, 'feature-extraction': LayoutLMvaModel}
						    if is_torch_available()
						    else {}
						)





						def 				snake_case__	(       self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase     )					->				Dict:
													# `DocumentQuestionAnsweringPipeline` is expected to work with this model, but it combines the text and visual
													# embedding along the sequence dimension (dim 1), which causes an error during post-processing as `p_mask` has
													# the sequence dimension of the text embedding only.
													# (see the line `embedding_output = torch.cat([embedding_output, visual_embeddings], dim=1)`)
													return True





						def 				snake_case__	(       self     )					->				Optional[int]:
													A__	     =							LayoutLMvaModelTester(self     )
													A__	     =							ConfigTester(self		,config_class=__UpperCAmelCase		,hidden_size=37     )





						def 				snake_case__	(       self		,__UpperCAmelCase		,__UpperCAmelCase		,__UpperCAmelCase=False     )					->				Dict:
													A__	     =							copy.deepcopy(__UpperCAmelCase     )
													if model_class in get_values(__UpperCAmelCase     ):
																				A__	     =							{
																				    k: v.unsqueeze(1     ).expand(-1		,self.model_tester.num_choices		,-1     ).contiguous()
																				    if isinstance(__UpperCAmelCase		,torch.Tensor     ) and v.ndim > 1
																				    else v
																				    for k, v in inputs_dict.items()
																				}
													if return_labels:
																				if model_class in get_values(__UpperCAmelCase     ):
																											A__	     =							torch.ones(self.model_tester.batch_size		,dtype=torch.long		,device=__UpperCAmelCase     )
																				elif model_class in get_values(__UpperCAmelCase     ):
																											A__	     =							torch.zeros(
																											    self.model_tester.batch_size		,dtype=torch.long		,device=__UpperCAmelCase     )
																											A__	     =							torch.zeros(
																											    self.model_tester.batch_size		,dtype=torch.long		,device=__UpperCAmelCase     )
																				elif model_class in [
																				    *get_values(__UpperCAmelCase     ),
																				]:
																											A__	     =							torch.zeros(
																											    self.model_tester.batch_size		,dtype=torch.long		,device=__UpperCAmelCase     )
																				elif model_class in [
																				    *get_values(__UpperCAmelCase     ),
																				]:
																											A__	     =							torch.zeros(
																											    (self.model_tester.batch_size, self.model_tester.text_seq_length)		,dtype=torch.long		,device=__UpperCAmelCase		,)

													return inputs_dict





						def 				snake_case__	(       self     )					->				Tuple:
													self.config_tester.run_common_tests()





						def 				snake_case__	(       self     )					->				Optional[Any]:
													A__	     =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*__UpperCAmelCase     )





						def 				snake_case__	(       self     )					->				int:
													A__	     =							self.model_tester.prepare_config_and_inputs()
													for type in ["absolute", "relative_key", "relative_key_query"]:
																				A__	     =							type
																				self.model_tester.create_and_check_model(*__UpperCAmelCase     )





						def 				snake_case__	(       self     )					->				Union[str, Any]:
													A__	     =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase     )





						def 				snake_case__	(       self     )					->				Optional[Any]:
													A__	     =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase     )





						def 				snake_case__	(       self     )					->				int:
													A__	     =							self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase     )





						@slow
						def 				snake_case__	(       self     )					->				Optional[Any]:
													for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				A__	     =							LayoutLMvaModel.from_pretrained(__UpperCAmelCase     )
																				self.assertIsNotNone(__UpperCAmelCase     )






def   UpperCAmelCase					(	):






							"""simple docstring"""





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


@require_torch
class     UpperCamelCase__(			unittest.TestCase ):





						@cached_property
						def 				snake_case__	(       self     )					->				Optional[Any]:
													return LayoutLMvaImageProcessor(apply_ocr=__UpperCAmelCase     ) if is_vision_available() else None





						@slow
						def 				snake_case__	(       self     )					->				Any:
													A__	     =							LayoutLMvaModel.from_pretrained('microsoft/layoutlmv3-base'     ).to(__UpperCAmelCase     )

													A__	     =							self.default_image_processor
													A__	     =							prepare_img()
													A__	     =							image_processor(images=__UpperCAmelCase		,return_tensors='pt'     ).pixel_values.to(__UpperCAmelCase     )

													A__	     =							torch.tensor([[1, 2]]     )
													A__	     =							torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]]     ).unsqueeze(0     )

													# forward pass
													A__	     =							model(
													    input_ids=input_ids.to(__UpperCAmelCase     )		,bbox=bbox.to(__UpperCAmelCase     )		,pixel_values=pixel_values.to(__UpperCAmelCase     )		,)

													# verify the logits
													A__	     =							torch.Size((1, 1_99, 7_68)     )
													self.assertEqual(outputs.last_hidden_state.shape		,__UpperCAmelCase     )

													A__	     =							torch.tensor(
													    [[-0.0_5_2_9, 0.3_6_1_8, 0.1_6_3_2], [-0.1_5_8_7, -0.1_6_6_7, -0.0_4_0_0], [-0.1_5_5_7, -0.1_6_7_1, -0.0_5_0_5]]     ).to(__UpperCAmelCase     )

													self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]		,__UpperCAmelCase		,atol=1e-4     )     )






"""simple docstring"""




import unittest

import numpy as np

from diffusers import OnnxStableDiffusionInpaintPipelineLegacy
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    load_numpy,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)


if is_onnx_available():
				import onnxruntime as ort
@nightly
@require_onnxruntime
@require_torch_gpu
class     UpperCamelCase__(			unittest.TestCase ):





						@property
						def 				snake_case__	(       self     )					->				int:
													return (
													    "CUDAExecutionProvider",
													    {
													        "gpu_mem_limit": "15000000000",  # 15GB
													        "arena_extend_strategy": "kSameAsRequested",
													    },
													)





						@property
						def 				snake_case__	(       self     )					->				Union[str, Any]:
													A__	     =							ort.SessionOptions()
													A__	     =							False
													return options





						def 				snake_case__	(       self     )					->				str:
													A__	     =							load_image(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/in_paint/overture-creations-5sI6fQgYIuo.png'     )
													A__	     =							load_image(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/in_paint/overture-creations-5sI6fQgYIuo_mask.png'     )
													A__	     =							load_numpy(
													    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
													    '/in_paint/red_cat_sitting_on_a_park_bench_onnx.npy'     )

													# using the PNDM scheduler by default
													A__	     =							OnnxStableDiffusionInpaintPipelineLegacy.from_pretrained(
													    'CompVis/stable-diffusion-v1-4'		,revision='onnx'		,safety_checker=__UpperCAmelCase		,feature_extractor=__UpperCAmelCase		,provider=self.gpu_provider		,sess_options=self.gpu_options		,)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase     )

													A__	     =							'A red cat sitting on a park bench'

													A__	     =							np.random.RandomState(0     )
													A__	     =							pipe(
													    prompt=__UpperCAmelCase		,image=__UpperCAmelCase		,mask_image=__UpperCAmelCase		,strength=0.7_5		,guidance_scale=7.5		,num_inference_steps=15		,generator=__UpperCAmelCase		,output_type='np'		,)

													A__	     =							output.images[0]

													assert image.shape == (5_12, 5_12, 3)
													assert np.abs(expected_image - image     ).max() < 1e-2





