


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     __snake_case							:
					def __init__(	self					:	str  ,			_lowerCAmelCase					:	int  ,			_lowerCAmelCase					:	Tuple=False  ,			_lowerCAmelCase					:	Optional[int]=1_3  ,			_lowerCAmelCase					:	Optional[int]=(3_2, 1_2_8)  ,			_lowerCAmelCase					:	Tuple=4  ,			_lowerCAmelCase					:	Dict=3  ,			_lowerCAmelCase					:	List[Any]=2_7  ,			_lowerCAmelCase					:	int=3_8  ,			_lowerCAmelCase					:	Any=9_9  ,			_lowerCAmelCase					:	Optional[int]=9_9  ,			_lowerCAmelCase					:	List[str]=3_2  ,			_lowerCAmelCase					:	Any=5  ,			_lowerCAmelCase					:	int=4  ,			_lowerCAmelCase					:	List[str]=4.0  ,			_lowerCAmelCase					:	Optional[Any]=2_5_7  ,			_lowerCAmelCase					:	List[Any]=None  ,			)       ->				str:



											'''simple docstring'''





											__magic_name__ 		=			parent
											__magic_name__ 		=			is_training
											__magic_name__ 		=			batch_size
											__magic_name__ 		=			image_size
											__magic_name__ 		=			patch_size
											__magic_name__ 		=			num_channels
											__magic_name__ 		=			max_token_length
											__magic_name__ 		=			num_character_labels
											__magic_name__ 		=			num_bpe_labels
											__magic_name__ 		=			num_wordpiece_labels
											__magic_name__ 		=			hidden_size
											__magic_name__ 		=			num_hidden_layers
											__magic_name__ 		=			num_attention_heads
											__magic_name__ 		=			mlp_ratio
											__magic_name__ 		=			patch_embeds_hidden_size
											__magic_name__ 		=			output_hidden_states
					def   a (	self					:	Dict     )       ->				Any:



											'''simple docstring'''





											__magic_name__ 		=			floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]     )
											__magic_name__ 		=			self.get_config()
											return config, pixel_values
					def   a (	self					:	str     )       ->				List[Any]:



											'''simple docstring'''





											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					:	int  ,			_lowerCAmelCase					:	List[str]  ,			_lowerCAmelCase					:	Tuple     )       ->				List[str]:



											'''simple docstring'''





											__magic_name__ 		=			MgpstrForSceneTextRecognition(_lowerCAmelCase     )
											model.to(_lowerCAmelCase     )
											model.eval()
											with torch.no_grad():
																	__magic_name__ 		=			model(_lowerCAmelCase     )
											self.parent.assertEqual(
											    generated_ids[0][0].shape  ,			(self.batch_size, self.max_token_length, self.num_character_labels)     )







					def   a (	self					:	List[str]     )       ->				int:



											'''simple docstring'''





											__magic_name__ 		=			self.prepare_config_and_inputs()
											__magic_name__		,			__magic_name__ 		=			config_and_inputs
											__magic_name__ 		=			{'pixel_values': pixel_values}
											return config, inputs_dict







@require_torch
class     __snake_case							(      _UpperCAmelCase  ,			_UpperCAmelCase  ,			unittest.TestCase):
					SCREAMING_SNAKE_CASE_		:					Tuple 				= (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
					SCREAMING_SNAKE_CASE_		:					Union[str, Any] 				= {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
					SCREAMING_SNAKE_CASE_		:					List[str] 				= False

					SCREAMING_SNAKE_CASE_		:					List[str] 				= False
					SCREAMING_SNAKE_CASE_		:					Optional[int] 				= False
					SCREAMING_SNAKE_CASE_		:					Tuple 				= False
					SCREAMING_SNAKE_CASE_		:					Union[str, Any] 				= False
					def   a (	self					:	int     )       ->				Optional[int]:



											'''simple docstring'''





											__magic_name__ 		=			MgpstrModelTester(self     )
											__magic_name__ 		=			ConfigTester(self  ,			config_class=_lowerCAmelCase  ,			has_text_modality=_lowerCAmelCase     )
					def   a (	self					:	Tuple     )       ->				Optional[int]:



											'''simple docstring'''





											self.config_tester.run_common_tests()
					def   a (	self					:	Dict     )       ->				Optional[Any]:



											'''simple docstring'''





											__magic_name__ 		=			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					:	List[str]     )       ->				List[Any]:



											'''simple docstring'''





											pass
					def   a (	self					:	Tuple     )       ->				Tuple:



											'''simple docstring'''





											__magic_name__		,			__magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__ 		=			model_class(_lowerCAmelCase     )
																	self.assertIsInstance(model.get_input_embeddings()  ,			(nn.Module)     )
																	__magic_name__ 		=			model.get_output_embeddings()
																	self.assertTrue(x is None or isinstance(_lowerCAmelCase  ,			nn.Linear     )     )
					def   a (	self					:	int     )       ->				List[Any]:



											'''simple docstring'''





											__magic_name__		,			__magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

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

																	__magic_name__ 		=			['pixel_values']
																	self.assertListEqual(arg_names[:1]  ,			_lowerCAmelCase     )
					@unittest.skip(reason='MgpstrModel does not support feedforward chunking'     )
					def   a (	self					:	Union[str, Any]     )       ->				Tuple:



											'''simple docstring'''





											pass
					def   a (	self					:	Tuple     )       ->				str:



											'''simple docstring'''





											__magic_name__		,			__magic_name__ 		=			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

																	__magic_name__ 		=			True
																	__magic_name__ 		=			model_class(_lowerCAmelCase     )
																	self.assertTrue(model.is_gradient_checkpointing     )
					def   a (	self					:	str     )       ->				List[Any]:



											'''simple docstring'''





											def check_hidden_states_output(_lowerCAmelCase					:	str  ,			_lowerCAmelCase					:	Tuple  ,			_lowerCAmelCase					:	Tuple     ):
																	__magic_name__ 		=			model_class(_lowerCAmelCase     )
																	model.to(_lowerCAmelCase     )
																	model.eval()

																	with torch.no_grad():
																							__magic_name__ 		=			model(**self._prepare_for_class(_lowerCAmelCase  ,			_lowerCAmelCase     )     )

																	__magic_name__ 		=			outputs.hidden_states

																	__magic_name__ 		=			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]  ,			)

											__magic_name__		,			__magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	__magic_name__ 		=			True
																	check_hidden_states_output(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )

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

																	check_hidden_states_output(_lowerCAmelCase  ,			_lowerCAmelCase  ,			_lowerCAmelCase     )
					def   a (	self					:	List[Any]     )       ->				Optional[Any]:



											'''simple docstring'''





											__magic_name__		,			__magic_name__ 		=			self.model_tester.prepare_config_and_inputs_for_common()

											__magic_name__ 		=			_config_zero_init(_lowerCAmelCase     )
											for model_class in self.all_model_classes:
																	__magic_name__ 		=			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					:	Optional[Any]     )       ->				Tuple:



											'''simple docstring'''





											pass







def 							UpperCamelCase_  (				)->      List[str]:




						'''simple docstring'''
						__magic_name__ 		=			'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
						__magic_name__ 		=			Image.open(requests.get(__snake_case	,			stream=__snake_case     ).raw     ).convert('RGB'     )
						return im




@require_vision
@require_torch
class     __snake_case							(      unittest.TestCase):
					@slow
					def   a (	self					:	int     )       ->				Dict:



											'''simple docstring'''





											__magic_name__ 		=			'alibaba-damo/mgp-str-base'
											__magic_name__ 		=			MgpstrForSceneTextRecognition.from_pretrained(_lowerCAmelCase     ).to(_lowerCAmelCase     )
											__magic_name__ 		=			MgpstrProcessor.from_pretrained(_lowerCAmelCase     )

											__magic_name__ 		=			prepare_img()
											__magic_name__ 		=			processor(images=_lowerCAmelCase  ,			return_tensors='pt'     ).pixel_values.to(_lowerCAmelCase     )

											# forward pass
											with torch.no_grad():
																	__magic_name__ 		=			model(_lowerCAmelCase     )

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

											__magic_name__ 		=			processor.batch_decode(outputs.logits     )
											__magic_name__ 		=			'ticket'

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

											__magic_name__ 		=			torch.tensor(
											    [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]  ,			device=_lowerCAmelCase  ,			)

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





def 							UpperCamelCase_  (				__snake_case			:						int     )->      bool:




						'''simple docstring'''
						if not isinstance(__snake_case	,			__snake_case     ):
												__magic_name__ 		=			F'''Input value of [number={number}] must be an integer'''
												raise TypeError(__snake_case     )
						if number < 0 or number % 2 == 1:
												return False
						__magic_name__ 		=			int(number**0.5     )
						return number == number_sqrt * (number_sqrt + 1)


if __name__ == "__main__":
					import doctest

					doctest.testmod()

