
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   :




	'''simple docstring'''





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






	def        UpperCamelCase_						( self      :				List[Any]				):
					__A         =				floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]				)
					__A         =				self.get_config()
					return config, pixel_values






	def        UpperCamelCase_						( self      :				Optional[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        UpperCamelCase_						( self      :				Tuple							,A      :				Tuple							,A      :				str				):
					__A         =				MgpstrForSceneTextRecognition(A				)
					model.to(A				)
					model.eval()
					with torch.no_grad():
									__A         =				model(A				)
					self.parent.assertEqual(
					    generated_ids[0][0].shape							,(self.batch_size, self.max_token_length, self.num_character_labels)				)







	def        UpperCamelCase_						( self      :				Union[str, Any]				):
					__A         =				self.prepare_config_and_inputs()
					__A    ,							__A         =				config_and_inputs
					__A         =				{"pixel_values": pixel_values}
					return config, inputs_dict





@require_torch
class 							UpperCAmelCase   (						__SCREAMING_SNAKE_CASE    ,    __SCREAMING_SNAKE_CASE    ,    unittest.TestCase						):




	'''simple docstring'''





	snake_case_      					=  (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
	snake_case_      					=  {"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
	snake_case_      					=  False

	snake_case_      					=  False
	snake_case_      					=  False
	snake_case_      					=  False
	snake_case_      					=  False






	def        UpperCamelCase_						( self      :				Optional[int]				):
					__A         =				MgpstrModelTester(self				)
					__A         =				ConfigTester(self							,config_class=A							,has_text_modality=A				)






	def        UpperCamelCase_						( self      :				int				):
					self.config_tester.run_common_tests()






	def        UpperCamelCase_						( self      :				Optional[Any]				):
					__A         =				self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*A				)






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






	def        UpperCamelCase_						( self      :				Tuple				):
					__A    ,							__A         =				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									__A         =				model_class(A				)
									self.assertIsInstance(model.get_input_embeddings()							,(nn.Module)				)
									__A         =				model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(A							,nn.Linear				)				)






	def        UpperCamelCase_						( self      :				Tuple				):
					__A    ,							__A         =				self.model_tester.prepare_config_and_inputs_for_common()

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

									__A         =				["pixel_values"]
									self.assertListEqual(arg_names[:1]							,A				)






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






	def        UpperCamelCase_						( self      :				Tuple				):
					__A    ,							__A         =				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

									__A         =				True
									__A         =				model_class(A				)
									self.assertTrue(model.is_gradient_checkpointing				)






	def        UpperCamelCase_						( self      :				Any				):
					def check_hidden_states_output(A      :				Tuple							,A      :				Any							,A      :				List[str]				):
									__A         =				model_class(A				)
									model.to(A				)
									model.eval()

									with torch.no_grad():
													__A         =				model(**self._prepare_for_class(A							,A				)				)

									__A         =				outputs.hidden_states

									__A         =				getattr(
									    self.model_tester							,"expected_num_hidden_layers"							,self.model_tester.num_hidden_layers + 1				)
									self.assertEqual(len(A				)							,A				)

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

					__A    ,							__A         =				self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
									__A         =				True
									check_hidden_states_output(A							,A							,A				)

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

									check_hidden_states_output(A							,A							,A				)






	def        UpperCamelCase_						( self      :				str				):
					__A    ,							__A         =				self.model_tester.prepare_config_and_inputs_for_common()

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





def 		UpperCAmelCase    (			)	->			List[Any]:







				"""simple docstring"""



				__A         =				"https://i.postimg.cc/ZKwLg2Gw/367-14.png"
				__A         =				Image.open(requests.get(a_	,     stream=a_		).raw		).convert("RGB"		)
				return im





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




	'''simple docstring'''





	@slow
	def        UpperCamelCase_						( self      :				List[Any]				):
					__A         =				"alibaba-damo/mgp-str-base"
					__A         =				MgpstrForSceneTextRecognition.from_pretrained(A				).to(A				)
					__A         =				MgpstrProcessor.from_pretrained(A				)

					__A         =				prepare_img()
					__A         =				processor(images=A							,return_tensors="pt"				).pixel_values.to(A				)

					# forward pass
					with torch.no_grad():
									__A         =				model(A				)

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

					__A         =				processor.batch_decode(outputs.logits				)
					__A         =				"ticket"

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

					__A         =				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=A							,)

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


def 		UpperCAmelCase    (			a_		)	->			int:







				"""simple docstring"""



				__A         =				str(a_		).strip()
				if not oct_string:
								raise ValueError("Empty string was passed to the function"		)
				__A         =				oct_string[0] == "-"
				if is_negative:
								__A         =				oct_string[1:]
				if not oct_string.isdigit() or not all(0 <= int(a_		) <= 7 for char in oct_string		):
								raise ValueError("Non-octal value was passed to the function"		)
				__A         =				0
				for char in oct_string:
								__A         =				8 * decimal_number + int(a_		)
				if is_negative:
								__A         =				-decimal_number
				return decimal_number


if __name__ == "__main__":
					from doctest import testmod

					testmod()
