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

						def __init__(					self		:			Optional[int]	,						_lowerCamelCase		:			int	,						_lowerCamelCase		:			List[str]=False	,						_lowerCamelCase		:			List[Any]=13	,						_lowerCamelCase		:			Optional[int]=(32, 1_28)	,						_lowerCamelCase		:			Union[str, Any]=4	,						_lowerCamelCase		:			Dict=3	,						_lowerCamelCase		:			Tuple=27	,						_lowerCamelCase		:			Any=38	,						_lowerCamelCase		:			List[str]=99	,						_lowerCamelCase		:			str=99	,						_lowerCamelCase		:			List[Any]=32	,						_lowerCamelCase		:			Any=5	,						_lowerCamelCase		:			Tuple=4	,						_lowerCamelCase		:			Any=4.0	,						_lowerCamelCase		:			List[Any]=2_57	,						_lowerCamelCase		:			int=None	,						):
													_UpperCAmelCase  :			Dict	       =		parent
													_UpperCAmelCase  :			Dict	       =		is_training
													_UpperCAmelCase  :			Optional[int]	       =		batch_size
													_UpperCAmelCase  :			int	       =		image_size
													_UpperCAmelCase  :			Union[str, Any]	       =		patch_size
													_UpperCAmelCase  :			Dict	       =		num_channels
													_UpperCAmelCase  :			List[Any]	       =		max_token_length
													_UpperCAmelCase  :			Optional[int]	       =		num_character_labels
													_UpperCAmelCase  :			List[str]	       =		num_bpe_labels
													_UpperCAmelCase  :			Tuple	       =		num_wordpiece_labels
													_UpperCAmelCase  :			Optional[int]	       =		hidden_size
													_UpperCAmelCase  :			List[Any]	       =		num_hidden_layers
													_UpperCAmelCase  :			Optional[int]	       =		num_attention_heads
													_UpperCAmelCase  :			Optional[Any]	       =		mlp_ratio
													_UpperCAmelCase  :			Dict	       =		patch_embeds_hidden_size
													_UpperCAmelCase  :			Optional[Any]	       =		output_hidden_states

						def 						a__ (					self		:			Any			):
													_UpperCAmelCase  :			Dict	       =		floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]			)
													_UpperCAmelCase  :			Dict	       =		self.get_config()
													return config, pixel_values

						def 						a__ (					self		:			Any			):
													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		:			Union[str, Any]	,						_lowerCamelCase		:			Optional[int]	,						_lowerCamelCase		:			Union[str, Any]			):
													_UpperCAmelCase  :			int	       =		MgpstrForSceneTextRecognition(_UpperCAmelCase			)
													model.to(_UpperCAmelCase			)
													model.eval()
													with torch.no_grad():
																				_UpperCAmelCase  :			List[Any]	       =		model(_UpperCAmelCase			)
													self.parent.assertEqual(
													    generated_ids[0][0].shape	,						(self.batch_size, self.max_token_length, self.num_character_labels)			)






						def 						a__ (					self		:			Optional[Any]			):
													_UpperCAmelCase  :			str	       =		self.prepare_config_and_inputs()
													_UpperCAmelCase       ,_UpperCAmelCase  :			str	       =		config_and_inputs
													_UpperCAmelCase  :			Any	       =		{"pixel_values": pixel_values}
													return config, inputs_dict







@require_torch
class    _UpperCamelCase(   lowerCAmelCase__		,						lowerCAmelCase__		,						unittest.TestCase				):
						__A:						List[str]				   =      (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
						__A:						str				   =      {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
						__A:						Dict				   =      False

						__A:						List[str]				   =      False
						__A:						Optional[int]				   =      False
						__A:						List[Any]				   =      False
						__A:						Any				   =      False

						def 						a__ (					self		:			Dict			):
													_UpperCAmelCase  :			str	       =		MgpstrModelTester(self			)
													_UpperCAmelCase  :			str	       =		ConfigTester(self	,						config_class=_UpperCAmelCase	,						has_text_modality=_UpperCAmelCase			)

						def 						a__ (					self		:			List[str]			):
													self.config_tester.run_common_tests()

						def 						a__ (					self		:			str			):
													_UpperCAmelCase  :			str	       =		self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*_UpperCAmelCase			)

						@unittest.skip(reason="MgpstrModel does not use inputs_embeds"			)
						def 						a__ (					self		:			Tuple			):
													pass

						def 						a__ (					self		:			Optional[int]			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			int	       =		self.model_tester.prepare_config_and_inputs_for_common()

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

						def 						a__ (					self		:			List[str]			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			Optional[int]	       =		self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				_UpperCAmelCase  :			Union[str, Any]	       =		model_class(_UpperCAmelCase			)
																				_UpperCAmelCase  :			Tuple	       =		inspect.signature(model.forward			)
																				# signature.parameters is an OrderedDict => so arg_names order is deterministic
																				_UpperCAmelCase  :			int	       =		[*signature.parameters.keys()]

																				_UpperCAmelCase  :			List[str]	       =		["pixel_values"]
																				self.assertListEqual(arg_names[:1]	,						_UpperCAmelCase			)

						@unittest.skip(reason="MgpstrModel does not support feedforward chunking"			)
						def 						a__ (					self		:			int			):
													pass

						def 						a__ (					self		:			List[str]			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			Union[str, Any]	       =		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

																				_UpperCAmelCase  :			Tuple	       =		True
																				_UpperCAmelCase  :			List[Any]	       =		model_class(_UpperCAmelCase			)
																				self.assertTrue(model.is_gradient_checkpointing			)

						def 						a__ (					self		:			List[str]			):


													def check_hidden_states_output(_lowerCamelCase		:			Any	,						_lowerCamelCase		:			Optional[int]	,						_lowerCamelCase		:			Tuple			):
																				_UpperCAmelCase  :			Dict	       =		model_class(_UpperCAmelCase			)
																				model.to(_UpperCAmelCase			)
																				model.eval()

																				with torch.no_grad():
																											_UpperCAmelCase  :			Optional[int]	       =		model(**self._prepare_for_class(_UpperCAmelCase	,						_UpperCAmelCase			)			)

																				_UpperCAmelCase  :			Union[str, Any]	       =		outputs.hidden_states

																				_UpperCAmelCase  :			List[str]	       =		getattr(
																				    self.model_tester	,						"expected_num_hidden_layers"	,						self.model_tester.num_hidden_layers + 1			)
																				self.assertEqual(len(_UpperCAmelCase			)	,						_UpperCAmelCase			)

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

													_UpperCAmelCase       ,_UpperCAmelCase  :			List[str]	       =		self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				_UpperCAmelCase  :			Dict	       =		True
																				check_hidden_states_output(_UpperCAmelCase	,						_UpperCAmelCase	,						_UpperCAmelCase			)

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

																				check_hidden_states_output(_UpperCAmelCase	,						_UpperCAmelCase	,						_UpperCAmelCase			)

						def 						a__ (					self		:			int			):
													_UpperCAmelCase       ,_UpperCAmelCase  :			Union[str, Any]	       =		self.model_tester.prepare_config_and_inputs_for_common()

													_UpperCAmelCase  :			Optional[Any]	       =		_config_zero_init(_UpperCAmelCase			)
													for model_class in self.all_model_classes:
																				_UpperCAmelCase  :			List[Any]	       =		model_class(config=_UpperCAmelCase			)
																				for name, param in model.named_parameters():
																											if isinstance(_UpperCAmelCase	,						(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[int]			):
													pass







def 		lowerCAmelCase_     (     )   ->      Dict:

							"""simple docstring"""






							_UpperCAmelCase  :			Optional[Any]	       =		"https://i.postimg.cc/ZKwLg2Gw/367-14.png"
							_UpperCAmelCase  :			Tuple	       =		Image.open(requests.get(_SCREAMING_SNAKE_CASE      ,	stream=_SCREAMING_SNAKE_CASE  ).raw  ).convert("RGB"  )
							return im


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

						@slow
						def 						a__ (					self		:			List[Any]			):
													_UpperCAmelCase  :			Union[str, Any]	       =		"alibaba-damo/mgp-str-base"
													_UpperCAmelCase  :			List[str]	       =		MgpstrForSceneTextRecognition.from_pretrained(_UpperCAmelCase			).to(_UpperCAmelCase			)
													_UpperCAmelCase  :			Dict	       =		MgpstrProcessor.from_pretrained(_UpperCAmelCase			)

													_UpperCAmelCase  :			Dict	       =		prepare_img()
													_UpperCAmelCase  :			Optional[int]	       =		processor(images=_UpperCAmelCase	,						return_tensors="pt"			).pixel_values.to(_UpperCAmelCase			)

													# forward pass
													with torch.no_grad():
																				_UpperCAmelCase  :			int	       =		model(_UpperCAmelCase			)

													# verify the logits
													self.assertEqual(outputs.logits[0].shape	,						torch.Size((1, 27, 38)			)			)

													_UpperCAmelCase  :			List[Any]	       =		processor.batch_decode(outputs.logits			)
													_UpperCAmelCase  :			Any	       =		"ticket"

													self.assertEqual(out_strs["generated_text"][0]	,						_UpperCAmelCase			)

													_UpperCAmelCase  :			Union[str, Any]	       =		torch.tensor(
													    [[[-39.53_97, -44.40_24, -36.18_44], [-61.47_09, -63.86_39, -58.34_54], [-74.02_25, -68.54_94, -71.21_64]]]	,						device=_UpperCAmelCase	,						)

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






def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: Union[str, Any]       ,				SCREAMING_SNAKE_CASE			: Any     )	->		Tuple:
				# "Simpson Rule"
				# int(f) = delta_x/2 * (b-a)/3*(f1 + 4f2 + 2f_3 + ... + fn)
				__lowercase								=   (boundary[1] - boundary[0]) / steps
				__lowercase								=   boundary[0]
				__lowercase								=   boundary[1]
				__lowercase								=   make_points(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE     )
				__lowercase								=   0.0
				y += (h / 3.0) * f(SCREAMING_SNAKE_CASE     )
				__lowercase								=   2
				for i in x_i:
								y += (h / 3) * (4 - 2 * (cnt % 2)) * f(SCREAMING_SNAKE_CASE     )
								cnt += 1
				y += (h / 3.0) * f(SCREAMING_SNAKE_CASE     )
				return y




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: List[Any]       ,				SCREAMING_SNAKE_CASE			: Dict       ,				SCREAMING_SNAKE_CASE			: int     )	->		Any:
				__lowercase								=   a + h
				while x < (b - h):
								yield x
								__lowercase								=   x + h




def 				__SCREAMING_SNAKE_CASE  (						SCREAMING_SNAKE_CASE			: Any     )	->		List[Any]:  # enter your function here
				__lowercase								=   (x - 0) * (x - 0)
				return y




def 				__SCREAMING_SNAKE_CASE  (						)	->		List[str]:
				__lowercase								=   0.0  # Lower bound of integration
				__lowercase								=   1.0  # Upper bound of integration
				__lowercase								=   10.0  # define number of steps or resolution
				__lowercase								=   [a, b]  # define boundary of integration
				__lowercase								=   method_a(SCREAMING_SNAKE_CASE       ,				SCREAMING_SNAKE_CASE     )
				print(F"""y = {y}"""     )


if __name__ == "__main__":
							main()





