


'''simple docstring'''




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  _lowercase   :
   def __init__(	self					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			List[str]=False					,      SCREAMING_SNAKE_CASE_					:			str=13					,      SCREAMING_SNAKE_CASE_					:			List[Any]=(32, 128)					,      SCREAMING_SNAKE_CASE_					:			Tuple=4					,      SCREAMING_SNAKE_CASE_					:			Any=3					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=27					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=38					,      SCREAMING_SNAKE_CASE_					:			int=99					,      SCREAMING_SNAKE_CASE_					:			int=99					,      SCREAMING_SNAKE_CASE_					:			str=32					,      SCREAMING_SNAKE_CASE_					:			List[Any]=5					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=4					,      SCREAMING_SNAKE_CASE_					:			List[Any]=4.0					,      SCREAMING_SNAKE_CASE_					:			List[Any]=257					,      SCREAMING_SNAKE_CASE_					:			int=None					,      )   ->       int:
        __snake_case    			=	parent
        __snake_case    			=	is_training
        __snake_case    			=	batch_size
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	num_channels
        __snake_case    			=	max_token_length
        __snake_case    			=	num_character_labels
        __snake_case    			=	num_bpe_labels
        __snake_case    			=	num_wordpiece_labels
        __snake_case    			=	hidden_size
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	mlp_ratio
        __snake_case    			=	patch_embeds_hidden_size
        __snake_case    			=	output_hidden_states
   def a     (	self					:			Any			)   ->       Any:
        __snake_case    			=	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]			)
        __snake_case    			=	self.get_config()
        return config, pixel_values
   def a     (	self					:			Optional[int]			)   ->       Tuple:
        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					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			List[str]					,      SCREAMING_SNAKE_CASE_					:			str			)   ->       Union[str, Any]:
        __snake_case    			=	MgpstrForSceneTextRecognition(SCREAMING_SNAKE_CASE_			)
        model.to(SCREAMING_SNAKE_CASE_			)
        model.eval()
        with torch.no_grad():
             __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(
            generated_ids[0][0].shape					,      (self.batch_size, self.max_token_length, self.num_character_labels)			)





   def a     (	self					:			str			)   ->       Dict:
        __snake_case    			=	self.prepare_config_and_inputs()
        __snake_case			,					__snake_case    			=	config_and_inputs
        __snake_case    			=	{'pixel_values': pixel_values}
        return config, inputs_dict




@require_torch
class  _lowercase   (  __lowercase	,				__lowercase	,				unittest.TestCase       ):
   _SCREAMING_SNAKE_CASE     :     str									=  (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     :     Any									=  False
   _SCREAMING_SNAKE_CASE     :     Optional[Any]									=  False
   _SCREAMING_SNAKE_CASE     :     int									=  False
   _SCREAMING_SNAKE_CASE     :     Optional[Any]									=  False
   def a     (	self					:			Dict			)   ->       Union[str, Any]:
        __snake_case    			=	MgpstrModelTester(self			)
        __snake_case    			=	ConfigTester(self					,      config_class=SCREAMING_SNAKE_CASE_					,      has_text_modality=SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			List[str]			)   ->       List[str]:
        self.config_tester.run_common_tests()
   def a     (	self					:			Optional[int]			)   ->       List[str]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)
   @unittest.skip(reason='MgpstrModel does not use inputs_embeds'			)
   def a     (	self					:			List[Any]			)   ->       Dict:
        pass
   def a     (	self					:			Dict			)   ->       Optional[Any]:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             self.assertIsInstance(model.get_input_embeddings()					,      (nn.Module)			)
             __snake_case    			=	model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_					,      nn.Linear			)			)
   def a     (	self					:			str			)   ->       Optional[Any]:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

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

             __snake_case    			=	['pixel_values']
             self.assertListEqual(arg_names[:1]					,      SCREAMING_SNAKE_CASE_			)
   @unittest.skip(reason='MgpstrModel does not support feedforward chunking'			)
   def a     (	self					:			Tuple			)   ->       Optional[int]:
        pass
   def a     (	self					:			Optional[int]			)   ->       List[Any]:
        __snake_case			,					__snake_case    			=	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

             __snake_case    			=	True
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             self.assertTrue(model.is_gradient_checkpointing			)
   def a     (	self					:			Optional[int]			)   ->       Optional[Any]:
        def check_hidden_states_output(SCREAMING_SNAKE_CASE_					:			Dict					,      SCREAMING_SNAKE_CASE_					:			Tuple					,      SCREAMING_SNAKE_CASE_					:			str			):
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             model.to(SCREAMING_SNAKE_CASE_			)
             model.eval()

             with torch.no_grad():
                  __snake_case    			=	model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)			)

             __snake_case    			=	outputs.hidden_states

             __snake_case    			=	getattr(
                 self.model_tester					,      'expected_num_hidden_layers'					,      self.model_tester.num_hidden_layers + 1			)
             self.assertEqual(len(SCREAMING_SNAKE_CASE_			)					,      SCREAMING_SNAKE_CASE_			)

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

        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             __snake_case    			=	True
             check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)

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

             check_hidden_states_output(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			Tuple			)   ->       Tuple:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

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





def      _a		() -> Optional[Any]:






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




@require_vision
@require_torch
class  _lowercase   (  unittest.TestCase       ):
   @slow
   def a     (	self					:			Dict			)   ->       str:
        __snake_case    			=	'alibaba-damo/mgp-str-base'
        __snake_case    			=	MgpstrForSceneTextRecognition.from_pretrained(SCREAMING_SNAKE_CASE_			).to(SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	MgpstrProcessor.from_pretrained(SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	prepare_img()
        __snake_case    			=	processor(images=SCREAMING_SNAKE_CASE_					,      return_tensors='pt'			).pixel_values.to(SCREAMING_SNAKE_CASE_			)

        # forward pass
        with torch.no_grad():
             __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)

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

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

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

        __snake_case    			=	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=SCREAMING_SNAKE_CASE_					,      )

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








'''simple docstring'''




import copy

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


_a      :      List[str]       				=      logging.get_logger(__name__)

_a      :      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  _lowercase   (  __lowercase       ):
   def __init__(	self					:			int					,      SCREAMING_SNAKE_CASE_					:			List[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=1024					,      SCREAMING_SNAKE_CASE_					:			Any=16					,      SCREAMING_SNAKE_CASE_					:			int=16					,      SCREAMING_SNAKE_CASE_					:			List[Any]=4					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Tuple=1e-6					,      **SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      )   ->       Tuple:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	hidden_size
        __snake_case    			=	image_size
        __snake_case    			=	patch_size
        __snake_case    			=	image_size // patch_size
        __snake_case    			=	mask_input_channels
        __snake_case    			=	num_point_embeddings
        __snake_case    			=	hidden_act
        __snake_case    			=	layer_norm_eps




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			List[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Dict="relu"					,      SCREAMING_SNAKE_CASE_					:			Any=2048					,      SCREAMING_SNAKE_CASE_					:			int=2					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=8					,      SCREAMING_SNAKE_CASE_					:			int=2					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=3					,      SCREAMING_SNAKE_CASE_					:			str=3					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=256					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1e-6					,      **SCREAMING_SNAKE_CASE_					:			int					,      )   ->       str:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	hidden_size
        __snake_case    			=	hidden_act
        __snake_case    			=	mlp_dim
        __snake_case    			=	num_hidden_layers
        __snake_case    			=	num_attention_heads
        __snake_case    			=	attention_downsample_rate
        __snake_case    			=	num_multimask_outputs
        __snake_case    			=	iou_head_depth
        __snake_case    			=	iou_head_hidden_dim
        __snake_case    			=	layer_norm_eps




class  _lowercase   (  __lowercase       ):
   def __init__(	self					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			int=768					,      SCREAMING_SNAKE_CASE_					:			int=256					,      SCREAMING_SNAKE_CASE_					:			str=12					,      SCREAMING_SNAKE_CASE_					:			Tuple=12					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=3					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1024					,      SCREAMING_SNAKE_CASE_					:			List[str]=16					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]="gelu"					,      SCREAMING_SNAKE_CASE_					:			Any=1e-06					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=0.0					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=1e-10					,      SCREAMING_SNAKE_CASE_					:			List[Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=4.0					,      SCREAMING_SNAKE_CASE_					:			List[Any]=True					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=True					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]=14					,      SCREAMING_SNAKE_CASE_					:			str=[2, 5, 8, 11]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]=128					,      SCREAMING_SNAKE_CASE_					:			Tuple=None					,      **SCREAMING_SNAKE_CASE_					:			List[Any]					,      )   ->       Optional[Any]:
        super().__init__(**SCREAMING_SNAKE_CASE_			)

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




class  _lowercase   (  __lowercase       ):
   _SCREAMING_SNAKE_CASE     :     Union[str, Any]									=  "sam"
   _SCREAMING_SNAKE_CASE     :     Any									=  True
   def __init__(	self					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			Dict=None					,      SCREAMING_SNAKE_CASE_					:			List[Any]=None					,      SCREAMING_SNAKE_CASE_					:			List[str]=None					,      SCREAMING_SNAKE_CASE_					:			str=0.0_2					,      **SCREAMING_SNAKE_CASE_					:			str					,      )   ->       str:
        super().__init__(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	vision_config if vision_config is not None else {}
        __snake_case    			=	prompt_encoder_config if prompt_encoder_config is not None else {}
        __snake_case    			=	mask_decoder_config if mask_decoder_config is not None else {}

        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	vision_config.to_dict()
        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	prompt_encoder_config.to_dict()
        if isinstance(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			):
             __snake_case    			=	mask_decoder_config.to_dict()

        __snake_case    			=	SamVisionConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	SamPromptEncoderConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	SamMaskDecoderConfig(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	initializer_range





   def a     (	self					:			int			)   ->       str:
        __snake_case    			=	copy.deepcopy(self.__dict__			)
        __snake_case    			=	self.vision_config.to_dict()
        __snake_case    			=	self.prompt_encoder_config.to_dict()
        __snake_case    			=	self.mask_decoder_config.to_dict()
        __snake_case    			=	self.__class__.model_type
        return output




