






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					:
					'''simple docstring'''






					def __init__(self					:		str   ,      _UpperCAmelCase					:		Dict   ,      _UpperCAmelCase					:		int=False   ,      _UpperCAmelCase					:		List[Any]=13   ,      _UpperCAmelCase					:		str=(32, 128)   ,      _UpperCAmelCase					:		List[Any]=4   ,      _UpperCAmelCase					:		List[Any]=3   ,      _UpperCAmelCase					:		Optional[int]=27   ,      _UpperCAmelCase					:		str=38   ,      _UpperCAmelCase					:		List[Any]=99   ,      _UpperCAmelCase					:		Union[str, Any]=99   ,      _UpperCAmelCase					:		Union[str, Any]=32   ,      _UpperCAmelCase					:		str=5   ,      _UpperCAmelCase					:		Any=4   ,      _UpperCAmelCase					:		List[Any]=4.0   ,      _UpperCAmelCase					:		Any=257   ,      _UpperCAmelCase					:		Tuple=None   ,      )		->     Optional[int]:




							"""simple docstring"""


							lowercase__      =	parent
							lowercase__      =	is_training
							lowercase__      =	batch_size
							lowercase__      =	image_size
							lowercase__      =	patch_size
							lowercase__      =	num_channels
							lowercase__      =	max_token_length
							lowercase__      =	num_character_labels
							lowercase__      =	num_bpe_labels
							lowercase__      =	num_wordpiece_labels
							lowercase__      =	hidden_size
							lowercase__      =	num_hidden_layers
							lowercase__      =	num_attention_heads
							lowercase__      =	mlp_ratio
							lowercase__      =	patch_embeds_hidden_size
							lowercase__      =	output_hidden_states

					def 						lowerCamelCase__  (self					:		List[Any]	)		->     Dict:




							"""simple docstring"""


							lowercase__      =	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]	)
							lowercase__      =	self.get_config()
							return config, pixel_values

					def 						lowerCamelCase__  (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 						lowerCamelCase__  (self					:		int   ,      _UpperCAmelCase					:		Optional[Any]   ,      _UpperCAmelCase					:		Optional[int]	)		->     Any:




							"""simple docstring"""


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


					def 						lowerCamelCase__  (self					:		Optional[Any]	)		->     List[Any]:




							"""simple docstring"""


							lowercase__      =	self.prepare_config_and_inputs()
							lowercase__    ,			lowercase__      =	config_and_inputs
							lowercase__      =	{"""pixel_values""": pixel_values}
							return config, inputs_dict






@require_torch
class 							A					( UpperCAmelCase__				,						UpperCAmelCase__				,						unittest.TestCase							):
					'''simple docstring'''






					A__    =				(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
					A__    =				{'''feature-extraction''': MgpstrForSceneTextRecognition} if is_torch_available() else {}
					A__    =				False

					A__    =				False
					A__    =				False
					A__    =				False
					A__    =				False

					def 						lowerCamelCase__  (self					:		Dict	)		->     Tuple:




							"""simple docstring"""


							lowercase__      =	MgpstrModelTester(self	)
							lowercase__      =	ConfigTester(self   ,      config_class=_UpperCAmelCase   ,      has_text_modality=_UpperCAmelCase	)

					def 						lowerCamelCase__  (self					:		str	)		->     Tuple:




							"""simple docstring"""


							self.config_tester.run_common_tests()

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




							"""simple docstring"""


							lowercase__      =	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 						lowerCamelCase__  (self					:		List[Any]	)		->     List[Any]:




							"""simple docstring"""


							pass

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




							"""simple docstring"""


							lowercase__    ,			lowercase__      =	self.model_tester.prepare_config_and_inputs_for_common()

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

					def 						lowerCamelCase__  (self					:		Optional[int]	)		->     Union[str, Any]:




							"""simple docstring"""


							lowercase__    ,			lowercase__      =	self.model_tester.prepare_config_and_inputs_for_common()

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

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

					@unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""	)
					def 						lowerCamelCase__  (self					:		Optional[int]	)		->     Union[str, Any]:




							"""simple docstring"""


							pass

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




							"""simple docstring"""


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

									lowercase__      =	True
									lowercase__      =	model_class(_UpperCAmelCase	)
									self.assertTrue(model.is_gradient_checkpointing	)

					def 						lowerCamelCase__  (self					:		Dict	)		->     Any:




							"""simple docstring"""


							def check_hidden_states_output(_UpperCAmelCase					:		str   ,      _UpperCAmelCase					:		str   ,      _UpperCAmelCase					:		int	):
									lowercase__      =	model_class(_UpperCAmelCase	)
									model.to(_UpperCAmelCase	)
									model.eval()

									with torch.no_grad():
											lowercase__      =	model(**self._prepare_for_class(_UpperCAmelCase   ,      _UpperCAmelCase	)	)

									lowercase__      =	outputs.hidden_states

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

							lowercase__    ,			lowercase__      =	self.model_tester.prepare_config_and_inputs_for_common()

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

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

									check_hidden_states_output(_UpperCAmelCase   ,      _UpperCAmelCase   ,      _UpperCAmelCase	)

					def 						lowerCamelCase__  (self					:		Dict	)		->     Dict:




							"""simple docstring"""


							lowercase__    ,			lowercase__      =	self.model_tester.prepare_config_and_inputs_for_common()

							lowercase__      =	_config_zero_init(_UpperCAmelCase	)
							for model_class in self.all_model_classes:
									lowercase__      =	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 						lowerCamelCase__  (self					:		str	)		->     Dict:




							"""simple docstring"""


							pass






def 				UpperCamelCase      (			)     ->						Union[str, Any]:
		"""simple docstring"""




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







@require_vision
@require_torch
class 							A					( unittest.TestCase							):
					'''simple docstring'''






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




							"""simple docstring"""


							lowercase__      =	"""alibaba-damo/mgp-str-base"""
							lowercase__      =	MgpstrForSceneTextRecognition.from_pretrained(_UpperCAmelCase	).to(_UpperCAmelCase	)
							lowercase__      =	MgpstrProcessor.from_pretrained(_UpperCAmelCase	)

							lowercase__      =	prepare_img()
							lowercase__      =	processor(images=_UpperCAmelCase   ,      return_tensors="""pt"""	).pixel_values.to(_UpperCAmelCase	)

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

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

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

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

							lowercase__      =	torch.tensor(
							    [[[-39.5_397, -44.4_024, -36.1_844], [-61.4_709, -63.8_639, -58.3_454], [-74.0_225, -68.5_494, -71.2_164]]]   ,      device=_UpperCAmelCase   ,      )

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





import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging


A :	Optional[Any]												=     logging.get_logger(__name__)

A :	Union[str, Any]												=     {
    'facebook/sam-vit-huge': 'https://huggingface.co/facebook/sam-vit-huge/resolve/main/config.json',
    'facebook/sam-vit-large': 'https://huggingface.co/facebook/sam-vit-large/resolve/main/config.json',
    'facebook/sam-vit-base': 'https://huggingface.co/facebook/sam-vit-base/resolve/main/config.json',
}



class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		Dict   ,      _UpperCAmelCase					:		List[str]=256   ,      _UpperCAmelCase					:		Tuple=1024   ,      _UpperCAmelCase					:		List[str]=16   ,      _UpperCAmelCase					:		Optional[Any]=16   ,      _UpperCAmelCase					:		Union[str, Any]=4   ,      _UpperCAmelCase					:		str="gelu"   ,      _UpperCAmelCase					:		List[str]=1E-6   ,      **_UpperCAmelCase					:		List[Any]   ,      )		->     Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)
							lowercase__      =	hidden_size
							lowercase__      =	image_size
							lowercase__      =	patch_size
							lowercase__      =	image_size // patch_size
							lowercase__      =	mask_input_channels
							lowercase__      =	num_point_embeddings
							lowercase__      =	hidden_act
							lowercase__      =	layer_norm_eps






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		List[str]   ,      _UpperCAmelCase					:		Optional[int]=256   ,      _UpperCAmelCase					:		int="relu"   ,      _UpperCAmelCase					:		Union[str, Any]=2048   ,      _UpperCAmelCase					:		int=2   ,      _UpperCAmelCase					:		Optional[Any]=8   ,      _UpperCAmelCase					:		Any=2   ,      _UpperCAmelCase					:		Tuple=3   ,      _UpperCAmelCase					:		List[str]=3   ,      _UpperCAmelCase					:		List[str]=256   ,      _UpperCAmelCase					:		Tuple=1E-6   ,      **_UpperCAmelCase					:		int   ,      )		->     Tuple:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)
							lowercase__      =	hidden_size
							lowercase__      =	hidden_act
							lowercase__      =	mlp_dim
							lowercase__      =	num_hidden_layers
							lowercase__      =	num_attention_heads
							lowercase__      =	attention_downsample_rate
							lowercase__      =	num_multimask_outputs
							lowercase__      =	iou_head_depth
							lowercase__      =	iou_head_hidden_dim
							lowercase__      =	layer_norm_eps






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					def __init__(self					:		Optional[int]   ,      _UpperCAmelCase					:		List[Any]=768   ,      _UpperCAmelCase					:		Union[str, Any]=256   ,      _UpperCAmelCase					:		Union[str, Any]=12   ,      _UpperCAmelCase					:		Optional[Any]=12   ,      _UpperCAmelCase					:		Tuple=3   ,      _UpperCAmelCase					:		Optional[int]=1024   ,      _UpperCAmelCase					:		str=16   ,      _UpperCAmelCase					:		Tuple="gelu"   ,      _UpperCAmelCase					:		Any=1E-0_6   ,      _UpperCAmelCase					:		Any=0.0   ,      _UpperCAmelCase					:		str=1E-1_0   ,      _UpperCAmelCase					:		Tuple=True   ,      _UpperCAmelCase					:		Tuple=4.0   ,      _UpperCAmelCase					:		Optional[Any]=True   ,      _UpperCAmelCase					:		Optional[int]=True   ,      _UpperCAmelCase					:		Optional[Any]=14   ,      _UpperCAmelCase					:		Optional[int]=[2, 5, 8, 11]   ,      _UpperCAmelCase					:		List[Any]=128   ,      _UpperCAmelCase					:		int=None   ,      **_UpperCAmelCase					:		int   ,      )		->     Dict:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)

							lowercase__      =	hidden_size
							lowercase__      =	output_channels
							lowercase__      =	num_hidden_layers
							lowercase__      =	num_attention_heads
							lowercase__      =	num_channels
							lowercase__      =	image_size
							lowercase__      =	patch_size
							lowercase__      =	hidden_act
							lowercase__      =	layer_norm_eps
							lowercase__      =	attention_dropout
							lowercase__      =	initializer_range
							lowercase__      =	qkv_bias
							lowercase__      =	mlp_ratio
							lowercase__      =	use_abs_pos
							lowercase__      =	use_rel_pos
							lowercase__      =	window_size
							lowercase__      =	global_attn_indexes
							lowercase__      =	num_pos_feats
							lowercase__      =	int(hidden_size * mlp_ratio	) if mlp_dim is None else mlp_dim






class 							A					( UpperCAmelCase__							):
					'''simple docstring'''






					A__    =				'''sam'''
					A__    =				True

					def __init__(self					:		List[str]   ,      _UpperCAmelCase					:		Any=None   ,      _UpperCAmelCase					:		List[Any]=None   ,      _UpperCAmelCase					:		List[Any]=None   ,      _UpperCAmelCase					:		List[Any]=0.02   ,      **_UpperCAmelCase					:		Optional[Any]   ,      )		->     Dict:




							"""simple docstring"""


							super().__init__(**_UpperCAmelCase	)
							lowercase__      =	vision_config if vision_config is not None else {}
							lowercase__      =	prompt_encoder_config if prompt_encoder_config is not None else {}
							lowercase__      =	mask_decoder_config if mask_decoder_config is not None else {}

							if isinstance(_UpperCAmelCase   ,      _UpperCAmelCase	):
									lowercase__      =	vision_config.to_dict()
							if isinstance(_UpperCAmelCase   ,      _UpperCAmelCase	):
									lowercase__      =	prompt_encoder_config.to_dict()
							if isinstance(_UpperCAmelCase   ,      _UpperCAmelCase	):
									lowercase__      =	mask_decoder_config.to_dict()

							lowercase__      =	SamVisionConfig(**_UpperCAmelCase	)
							lowercase__      =	SamPromptEncoderConfig(**_UpperCAmelCase	)
							lowercase__      =	SamMaskDecoderConfig(**_UpperCAmelCase	)
							lowercase__      =	initializer_range


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




							"""simple docstring"""


							lowercase__      =	copy.deepcopy(self.__dict__	)
							lowercase__      =	self.vision_config.to_dict()
							lowercase__      =	self.prompt_encoder_config.to_dict()
							lowercase__      =	self.mask_decoder_config.to_dict()
							lowercase__      =	self.__class__.model_type
							return output

