
import inspect
import unittest

import requests

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

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


if is_torch_available():
		import torch
		from torch import nn

		from transformers import MgpstrForSceneTextRecognition


if is_vision_available():
		from PIL import Image

		from transformers import MgpstrProcessor


class 						__magic_name__				:





		def __init__(							self      :		List[Any]  ,					lowerCamelCase__      :		int  ,					lowerCamelCase__      :		List[str]=False  ,					lowerCamelCase__      :		str=1_3  ,					lowerCamelCase__      :		Optional[Any]=(3_2, 1_2_8)  ,					lowerCamelCase__      :		int=4  ,					lowerCamelCase__      :		str=3  ,					lowerCamelCase__      :		Any=2_7  ,					lowerCamelCase__      :		List[Any]=3_8  ,					lowerCamelCase__      :		Optional[Any]=9_9  ,					lowerCamelCase__      :		Optional[int]=9_9  ,					lowerCamelCase__      :		Dict=3_2  ,					lowerCamelCase__      :		Any=5  ,					lowerCamelCase__      :		Optional[int]=4  ,					lowerCamelCase__      :		List[Any]=4.0  ,					lowerCamelCase__      :		Union[str, Any]=2_5_7  ,					lowerCamelCase__      :		List[str]=None  ,					):
							lowerCAmelCase						:   Optional[Any]							=       parent
							lowerCAmelCase						:   List[Any]							=       is_training
							lowerCAmelCase						:   Optional[int]							=       batch_size
							lowerCAmelCase						:   List[Any]							=       image_size
							lowerCAmelCase						:   int							=       patch_size
							lowerCAmelCase						:   Any							=       num_channels
							lowerCAmelCase						:   List[str]							=       max_token_length
							lowerCAmelCase						:   Any							=       num_character_labels
							lowerCAmelCase						:   Dict							=       num_bpe_labels
							lowerCAmelCase						:   str							=       num_wordpiece_labels
							lowerCAmelCase						:   List[str]							=       hidden_size
							lowerCAmelCase						:   Dict							=       num_hidden_layers
							lowerCAmelCase						:   Dict							=       num_attention_heads
							lowerCAmelCase						:   str							=       mlp_ratio
							lowerCAmelCase						:   Any							=       patch_embeds_hidden_size
							lowerCAmelCase						:   List[Any]							=       output_hidden_states





		def  _A							(							self      :		Dict			):
							lowerCAmelCase						:   Any							=       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]			)
							lowerCAmelCase						:   List[str]							=       self.get_config()
							return config, pixel_values





		def  _A							(							self      :		Dict			):
							return MgpstrConfig(
							    image_size=self.image_size  ,					patch_size=self.patch_size  ,					num_channels=self.num_channels  ,					max_token_length=self.max_token_length  ,					num_character_labels=self.num_character_labels  ,					num_bpe_labels=self.num_bpe_labels  ,					num_wordpiece_labels=self.num_wordpiece_labels  ,					hidden_size=self.hidden_size  ,					num_hidden_layers=self.num_hidden_layers  ,					num_attention_heads=self.num_attention_heads  ,					mlp_ratio=self.mlp_ratio  ,					output_hidden_states=self.output_hidden_states  ,					)





		def  _A							(							self      :		str  ,					lowerCamelCase__      :		Any  ,					lowerCamelCase__      :		Any			):
							lowerCAmelCase						:   str							=       MgpstrForSceneTextRecognition(lowerCamelCase__			)
							model.to(lowerCamelCase__			)
							model.eval()
							with torch.no_grad():
												lowerCAmelCase						:   Optional[int]							=       model(lowerCamelCase__			)
							self.parent.assertEqual(
							    generated_ids[0][0].shape  ,					(self.batch_size, self.max_token_length, self.num_character_labels)			)





		def  _A							(							self      :		Tuple			):
							lowerCAmelCase						:   int							=       self.prepare_config_and_inputs()
							lowerCAmelCase		,							lowerCAmelCase						:   Tuple							=       config_and_inputs
							lowerCAmelCase						:   int							=       {'''pixel_values''': pixel_values}
							return config, inputs_dict



@require_torch
class 						__magic_name__				(  snake_case,			snake_case,			unittest.TestCase      ):
		_lowerCAmelCase						=		(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
		_lowerCAmelCase						=		{"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
		_lowerCAmelCase						=		False

		_lowerCAmelCase						=		False
		_lowerCAmelCase						=		False
		_lowerCAmelCase						=		False
		_lowerCAmelCase						=		False





		def  _A							(							self      :		Tuple			):
							lowerCAmelCase						:   Tuple							=       MgpstrModelTester(self			)
							lowerCAmelCase						:   Optional[Any]							=       ConfigTester(self  ,					config_class=lowerCamelCase__  ,					has_text_modality=lowerCamelCase__			)





		def  _A							(							self      :		Optional[Any]			):
							self.config_tester.run_common_tests()





		def  _A							(							self      :		List[Any]			):
							lowerCAmelCase						:   Dict							=       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*lowerCamelCase__			)





		@unittest.skip(reason='''MgpstrModel does not use inputs_embeds'''			)
		def  _A							(							self      :		Optional[Any]			):
							pass





		def  _A							(							self      :		Any			):
							lowerCAmelCase		,							lowerCAmelCase						:   List[Any]							=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												lowerCAmelCase						:   Optional[int]							=       model_class(lowerCamelCase__			)
												self.assertIsInstance(model.get_input_embeddings()  ,					(nn.Module)			)
												lowerCAmelCase						:   int							=       model.get_output_embeddings()
												self.assertTrue(x is None or isinstance(lowerCamelCase__  ,					nn.Linear			)			)





		def  _A							(							self      :		Tuple			):
							lowerCAmelCase		,							lowerCAmelCase						:   Optional[Any]							=       self.model_tester.prepare_config_and_inputs_for_common()

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

												lowerCAmelCase						:   Optional[Any]							=       ['''pixel_values''']
												self.assertListEqual(arg_names[:1]  ,					lowerCamelCase__			)





		@unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''			)
		def  _A							(							self      :		Optional[int]			):
							pass





		def  _A							(							self      :		List[Any]			):
							lowerCAmelCase		,							lowerCAmelCase						:   Tuple							=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												if not model_class.supports_gradient_checkpointing:
																	continue

												lowerCAmelCase						:   Union[str, Any]							=       True
												lowerCAmelCase						:   List[str]							=       model_class(lowerCamelCase__			)
												self.assertTrue(model.is_gradient_checkpointing			)





		def  _A							(							self      :		Tuple			):
							def check_hidden_states_output(lowerCamelCase__      :		Dict  ,					lowerCamelCase__      :		Union[str, Any]  ,					lowerCamelCase__      :		Dict			):
												lowerCAmelCase						:   Dict							=       model_class(lowerCamelCase__			)
												model.to(lowerCamelCase__			)
												model.eval()

												with torch.no_grad():
																	lowerCAmelCase						:   Tuple							=       model(**self._prepare_for_class(lowerCamelCase__  ,					lowerCamelCase__			)			)

												lowerCAmelCase						:   Tuple							=       outputs.hidden_states

												lowerCAmelCase						:   Optional[int]							=       getattr(
												    self.model_tester  ,					'''expected_num_hidden_layers'''  ,					self.model_tester.num_hidden_layers + 1			)
												self.assertEqual(len(lowerCamelCase__			)  ,					lowerCamelCase__			)

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

							lowerCAmelCase		,							lowerCAmelCase						:   List[Any]							=       self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
												lowerCAmelCase						:   str							=       True
												check_hidden_states_output(lowerCamelCase__  ,					lowerCamelCase__  ,					lowerCamelCase__			)

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												lowerCAmelCase						:   List[Any]							=       True

												check_hidden_states_output(lowerCamelCase__  ,					lowerCamelCase__  ,					lowerCamelCase__			)





		def  _A							(							self      :		List[Any]			):
							lowerCAmelCase		,							lowerCAmelCase						:   Tuple							=       self.model_tester.prepare_config_and_inputs_for_common()

							lowerCAmelCase						:   str							=       _config_zero_init(lowerCamelCase__			)
							for model_class in self.all_model_classes:
												lowerCAmelCase						:   Tuple							=       model_class(config=lowerCamelCase__			)
												for name, param in model.named_parameters():
																	if isinstance(lowerCamelCase__  ,					(nn.Linear, nn.Convad, nn.LayerNorm)			):
																						if param.requires_grad:
																											self.assertIn(
																											    ((param.data.mean() * 1E9).round() / 1E9).item()  ,					[0.0, 1.0]  ,					msg=f'''Parameter {name} of model {model_class} seems not properly initialized'''  ,					)





		@unittest.skip(reason='''Retain_grad is tested in individual model tests'''			)
		def  _A							(							self      :		Union[str, Any]			):
							pass



def       UpperCAmelCase__							(    ):


					'''simple docstring'''

					lowerCAmelCase						:   List[Any]							=       '''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
					lowerCAmelCase						:   Any							=       Image.open(requests.get(__magic_name__							,					stream=__magic_name__					).raw					).convert('''RGB'''					)
					return im


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





		@slow
		def  _A							(							self      :		List[str]			):
							lowerCAmelCase						:   Union[str, Any]							=       '''alibaba-damo/mgp-str-base'''
							lowerCAmelCase						:   str							=       MgpstrForSceneTextRecognition.from_pretrained(lowerCamelCase__			).to(lowerCamelCase__			)
							lowerCAmelCase						:   str							=       MgpstrProcessor.from_pretrained(lowerCamelCase__			)

							lowerCAmelCase						:   Union[str, Any]							=       prepare_img()
							lowerCAmelCase						:   Optional[int]							=       processor(images=lowerCamelCase__  ,					return_tensors='''pt'''			).pixel_values.to(lowerCamelCase__			)

							# forward pass
							with torch.no_grad():
												lowerCAmelCase						:   Union[str, Any]							=       model(lowerCamelCase__			)

							# verify the logits
							self.assertEqual(outputs.logits[0].shape  ,					torch.Size((1, 2_7, 3_8)			)			)

							lowerCAmelCase						:   Any							=       processor.batch_decode(outputs.logits			)
							lowerCAmelCase						:   Any							=       '''ticket'''

							self.assertEqual(out_strs['''generated_text'''][0]  ,					lowerCamelCase__			)

							lowerCAmelCase						:   Any							=       torch.tensor(
							    [[[-3_9.5_3_9_7, -4_4.4_0_2_4, -3_6.1_8_4_4], [-6_1.4_7_0_9, -6_3.8_6_3_9, -5_8.3_4_5_4], [-7_4.0_2_2_5, -6_8.5_4_9_4, -7_1.2_1_6_4]]]  ,					device=lowerCamelCase__  ,					)

							self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4]  ,					lowerCamelCase__  ,					atol=1E-4			)			)


import gc
import unittest

import numpy as np
import torch

from diffusers import RePaintPipeline, RePaintScheduler, UNetaDModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_image,
    load_numpy,
    nightly,
    require_torch_gpu,
    skip_mps,
    torch_device,
)

from ..pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class 						__magic_name__				(  snake_case,			unittest.TestCase      ):
		_lowerCAmelCase						=		RePaintPipeline
		_lowerCAmelCase						=		IMAGE_INPAINTING_PARAMS - {"width", "height", "guidance_scale"}
		_lowerCAmelCase						=		PipelineTesterMixin.required_optional_params - {
		    "latents",
		    "num_images_per_prompt",
		    "callback",
		    "callback_steps",
		}
		_lowerCAmelCase						=		IMAGE_INPAINTING_BATCH_PARAMS
		_lowerCAmelCase						=		False





		def  _A							(							self      :		Optional[int]			):
							torch.manual_seed(0			)
							torch.manual_seed(0			)
							lowerCAmelCase						:   Dict							=       UNetaDModel(
							    block_out_channels=(3_2, 6_4)  ,					layers_per_block=2  ,					sample_size=3_2  ,					in_channels=3  ,					out_channels=3  ,					down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')  ,					up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')  ,					)
							lowerCAmelCase						:   List[Any]							=       RePaintScheduler()
							lowerCAmelCase						:   Tuple							=       {'''unet''': unet, '''scheduler''': scheduler}
							return components





		def  _A							(							self      :		Any  ,					lowerCamelCase__      :		Any  ,					lowerCamelCase__      :		int=0			):
							if str(lowerCamelCase__			).startswith('''mps'''			):
												lowerCAmelCase						:   Union[str, Any]							=       torch.manual_seed(lowerCamelCase__			)
							else:
												lowerCAmelCase						:   Optional[Any]							=       torch.Generator(device=lowerCamelCase__			).manual_seed(lowerCamelCase__			)
							lowerCAmelCase						:   List[str]							=       np.random.RandomState(lowerCamelCase__			).standard_normal((1, 3, 3_2, 3_2)			)
							lowerCAmelCase						:   Tuple							=       torch.from_numpy(lowerCamelCase__			).to(device=lowerCamelCase__  ,					dtype=torch.floataa			)
							lowerCAmelCase						:   Tuple							=       (image > 0).to(device=lowerCamelCase__  ,					dtype=torch.floataa			)
							lowerCAmelCase						:   List[Any]							=       {
							    '''image''': image,
							    '''mask_image''': mask,
							    '''generator''': generator,
							    '''num_inference_steps''': 5,
							    '''eta''': 0.0,
							    '''jump_length''': 2,
							    '''jump_n_sample''': 2,
							    '''output_type''': '''numpy''',
							}
							return inputs





		def  _A							(							self      :		Union[str, Any]			):
							lowerCAmelCase						:   List[str]							=       '''cpu'''  # ensure determinism for the device-dependent torch.Generator
							lowerCAmelCase						:   Dict							=       self.get_dummy_components()
							lowerCAmelCase						:   str							=       RePaintPipeline(**lowerCamelCase__			)
							lowerCAmelCase						:   Union[str, Any]							=       sd_pipe.to(lowerCamelCase__			)
							sd_pipe.set_progress_bar_config(disable=lowerCamelCase__			)

							lowerCAmelCase						:   List[Any]							=       self.get_dummy_inputs(lowerCamelCase__			)
							lowerCAmelCase						:   int							=       sd_pipe(**lowerCamelCase__			).images
							lowerCAmelCase						:   Dict							=       image[0, -3:, -3:, -1]

							assert image.shape == (1, 3_2, 3_2, 3)
							lowerCAmelCase						:   List[str]							=       np.array([1.0_0_0_0, 0.5_4_2_6, 0.5_4_9_7, 0.2_2_0_0, 1.0_0_0_0, 1.0_0_0_0, 0.5_6_2_3, 1.0_0_0_0, 0.6_2_7_4]			)

							assert np.abs(image_slice.flatten() - expected_slice			).max() < 1E-3





		@skip_mps
		def  _A							(							self      :		Optional[Any]			):
							return super().test_save_load_local()





		@unittest.skip('''non-deterministic pipeline'''			)
		def  _A							(							self      :		Any			):
							return super().test_inference_batch_single_identical()





		@skip_mps
		def  _A							(							self      :		List[Any]			):
							return super().test_dict_tuple_outputs_equivalent()





		@skip_mps
		def  _A							(							self      :		Dict			):
							return super().test_save_load_optional_components()





		@skip_mps
		def  _A							(							self      :		Tuple			):
							return super().test_attention_slicing_forward_pass()



@nightly
@require_torch_gpu
class 						__magic_name__				(  unittest.TestCase      ):





		def  _A							(							self      :		Optional[Any]			):
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()





		def  _A							(							self      :		Union[str, Any]			):
							lowerCAmelCase						:   str							=       load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/'''
							    '''repaint/celeba_hq_256.png'''			)
							lowerCAmelCase						:   Tuple							=       load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png'''			)
							lowerCAmelCase						:   int							=       load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/'''
							    '''repaint/celeba_hq_256_result.npy'''			)

							lowerCAmelCase						:   List[str]							=       '''google/ddpm-ema-celebahq-256'''
							lowerCAmelCase						:   List[str]							=       UNetaDModel.from_pretrained(lowerCamelCase__			)
							lowerCAmelCase						:   str							=       RePaintScheduler.from_pretrained(lowerCamelCase__			)

							lowerCAmelCase						:   Optional[int]							=       RePaintPipeline(unet=lowerCamelCase__  ,					scheduler=lowerCamelCase__			).to(lowerCamelCase__			)
							repaint.set_progress_bar_config(disable=lowerCamelCase__			)
							repaint.enable_attention_slicing()

							lowerCAmelCase						:   str							=       torch.manual_seed(0			)
							lowerCAmelCase						:   Dict							=       repaint(
							    lowerCamelCase__  ,					lowerCamelCase__  ,					num_inference_steps=2_5_0  ,					eta=0.0  ,					jump_length=1_0  ,					jump_n_sample=1_0  ,					generator=lowerCamelCase__  ,					output_type='''np'''  ,					)
							lowerCAmelCase						:   str							=       output.images[0]

							assert image.shape == (2_5_6, 2_5_6, 3)
							assert np.abs(expected_image - image			).mean() < 1E-2
