




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






	def __init__(	self				,     lowerCamelCase				,     lowerCamelCase=False				,     lowerCamelCase=13				,     lowerCamelCase=(32, 128)				,     lowerCamelCase=4				,     lowerCamelCase=3				,     lowerCamelCase=27				,     lowerCamelCase=38				,     lowerCamelCase=99				,     lowerCamelCase=99				,     lowerCamelCase=32				,     lowerCamelCase=5				,     lowerCamelCase=4				,     lowerCamelCase=4.0				,     lowerCamelCase=257				,     lowerCamelCase=None				,     )      ->   Tuple:




						"""simple docstring"""






						__magic_name__					:							str		   =							parent
						__magic_name__					:							Optional[int]		   =							is_training
						__magic_name__					:							Tuple		   =							batch_size
						__magic_name__					:							Any		   =							image_size
						__magic_name__					:							Any		   =							patch_size
						__magic_name__					:							Optional[Any]		   =							num_channels
						__magic_name__					:							int		   =							max_token_length
						__magic_name__					:							Union[str, Any]		   =							num_character_labels
						__magic_name__					:							Dict		   =							num_bpe_labels
						__magic_name__					:							Optional[int]		   =							num_wordpiece_labels
						__magic_name__					:							int		   =							hidden_size
						__magic_name__					:							int		   =							num_hidden_layers
						__magic_name__					:							Any		   =							num_attention_heads
						__magic_name__					:							Optional[int]		   =							mlp_ratio
						__magic_name__					:							Optional[Any]		   =							patch_embeds_hidden_size
						__magic_name__					:							List[Any]		   =							output_hidden_states






	def  lowercase      (	self						)      ->   Optional[int]:




						"""simple docstring"""






						__magic_name__					:							Dict		   =							floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]						)
						__magic_name__					:							int		   =							self.get_config()
						return config, pixel_values






	def  lowercase      (	self						)      ->   Dict:




						"""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  lowercase      (	self				,     lowerCamelCase				,     lowerCamelCase						)      ->   List[str]:




						"""simple docstring"""






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






	def  lowercase      (	self						)      ->   Tuple:




						"""simple docstring"""






						__magic_name__					:							List[Any]		   =							self.prepare_config_and_inputs()
						__magic_name__   , __magic_name__					:							List[Any]		   =							config_and_inputs
						__magic_name__					:							Union[str, Any]		   =							{'''pixel_values''': pixel_values}
						return config, inputs_dict





@require_torch
class 		A__				(   __SCREAMING_SNAKE_CASE		,     __SCREAMING_SNAKE_CASE		,     unittest.TestCase ):
	lowerCamelCase__		: int				    =(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
	lowerCamelCase__		: str				    ={"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
	lowerCamelCase__		: Dict				    =False

	lowerCamelCase__		: List[Any]				    =False
	lowerCamelCase__		: Dict				    =False
	lowerCamelCase__		: str				    =False
	lowerCamelCase__		: List[str]				    =False






	def  lowercase      (	self						)      ->   Optional[Any]:




						"""simple docstring"""






						__magic_name__					:							str		   =							MgpstrModelTester(self						)
						__magic_name__					:							Union[str, Any]		   =							ConfigTester(self				,     config_class=lowerCamelCase				,     has_text_modality=lowerCamelCase						)






	def  lowercase      (	self						)      ->   Dict:




						"""simple docstring"""






						self.config_tester.run_common_tests()






	def  lowercase      (	self						)      ->   int:




						"""simple docstring"""






						__magic_name__					:							int		   =							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  lowercase      (	self						)      ->   Optional[Any]:




						"""simple docstring"""






						pass






	def  lowercase      (	self						)      ->   Optional[Any]:




						"""simple docstring"""






						__magic_name__   , __magic_name__					:							Optional[Any]		   =							self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__magic_name__					:							Union[str, Any]		   =							model_class(lowerCamelCase						)
											self.assertIsInstance(model.get_input_embeddings()				,     (nn.Module)						)
											__magic_name__					:							Tuple		   =							model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(lowerCamelCase				,     nn.Linear						)						)






	def  lowercase      (	self						)      ->   Tuple:




						"""simple docstring"""






						__magic_name__   , __magic_name__					:							Any		   =							self.model_tester.prepare_config_and_inputs_for_common()

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

											__magic_name__					:							int		   =							['''pixel_values''']
											self.assertListEqual(arg_names[:1]				,     lowerCamelCase						)






	@unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''						)
	def  lowercase      (	self						)      ->   Dict:




						"""simple docstring"""






						pass






	def  lowercase      (	self						)      ->   Any:




						"""simple docstring"""






						__magic_name__   , __magic_name__					:							Optional[int]		   =							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__					:							str		   =							True
											__magic_name__					:							List[str]		   =							model_class(lowerCamelCase						)
											self.assertTrue(model.is_gradient_checkpointing						)






	def  lowercase      (	self						)      ->   Optional[int]:




						"""simple docstring"""






						def check_hidden_states_output(lowerCamelCase				,     lowerCamelCase				,     lowerCamelCase						):
											__magic_name__					:							Optional[Any]		   =							model_class(lowerCamelCase						)
											model.to(lowerCamelCase						)
											model.eval()

											with torch.no_grad():
																__magic_name__					:							List[Any]		   =							model(**self._prepare_for_class(lowerCamelCase				,     lowerCamelCase						)						)

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

											__magic_name__					:							Union[str, Any]		   =							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__					:							List[str]		   =							self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
											__magic_name__					:							Union[str, Any]		   =							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__					:							Dict		   =							True

											check_hidden_states_output(lowerCamelCase				,     lowerCamelCase				,     lowerCamelCase						)






	def  lowercase      (	self						)      ->   Union[str, Any]:




						"""simple docstring"""






						__magic_name__   , __magic_name__					:							Optional[Any]		   =							self.model_tester.prepare_config_and_inputs_for_common()

						__magic_name__					:							Optional[int]		   =							_config_zero_init(lowerCamelCase						)
						for model_class in self.all_model_classes:
											__magic_name__					:							int		   =							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  lowercase      (	self						)      ->   Optional[int]:




						"""simple docstring"""






						pass







def  lowerCAmelCase  (	)  ->Tuple:






					"""simple docstring"""






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





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






	@slow
	def  lowercase      (	self						)      ->   List[Any]:




						"""simple docstring"""






						__magic_name__					:							Optional[Any]		   =							'''alibaba-damo/mgp-str-base'''
						__magic_name__					:							List[Any]		   =							MgpstrForSceneTextRecognition.from_pretrained(lowerCamelCase						).to(lowerCamelCase						)
						__magic_name__					:							Optional[int]		   =							MgpstrProcessor.from_pretrained(lowerCamelCase						)

						__magic_name__					:							Any		   =							prepare_img()
						__magic_name__					:							Tuple		   =							processor(images=lowerCamelCase				,     return_tensors='''pt'''						).pixel_values.to(lowerCamelCase						)

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

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

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

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

						__magic_name__					:							Dict		   =							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						)						)









from typing import Any





class 		A__				:






	def __init__(	self						)      ->   int:




						"""simple docstring"""






						__magic_name__					:							List[str]		   =							[]
						__magic_name__					:							str		   =							0






	def __str__(	self						)      ->   Union[str, Any]:




						"""simple docstring"""






						__magic_name__					:							str		   =							'''<''' + str(self.stack						)[1:-1] + '''>'''
						return printed






	def  lowercase      (	self				,     lowerCamelCase						)      ->   None:




						"""simple docstring"""






						self.stack.append(lowerCamelCase						)
						__magic_name__					:							Tuple		   =							self.length + 1






	def  lowercase      (	self						)      ->   Any:




						"""simple docstring"""






						self.rotate(1						)
						__magic_name__					:							Union[str, Any]		   =							self.stack[self.length - 1]
						__magic_name__					:							Union[str, Any]		   =							self.stack[:-1]
						self.rotate(self.length - 1						)
						__magic_name__					:							List[Any]		   =							self.length - 1
						return dequeued






	def  lowercase      (	self				,     lowerCamelCase						)      ->   None:




						"""simple docstring"""






						for _ in range(lowerCamelCase						):
											__magic_name__					:							str		   =							self.stack[0]
											__magic_name__					:							Optional[Any]		   =							self.stack[1:]
											self.put(lowerCamelCase						)
											__magic_name__					:							List[Any]		   =							self.length - 1






	def  lowercase      (	self						)      ->   Any:




						"""simple docstring"""






						__magic_name__					:							Optional[int]		   =							self.get()
						self.put(lowerCamelCase						)
						self.rotate(self.length - 1						)
						return front






	def  lowercase      (	self						)      ->   int:




						"""simple docstring"""






						return self.length



