code: 
  
  
  
  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 		_snake_case      :
  
  
  
  
  
   """simple docstring"""
  
  
  
   def __init__(						self	,    a	,    a=False	,    a=1_3	,    a=(3_2, 1_2_8)	,    a=4	,    a=3	,    a=2_7	,    a=3_8	,    a=9_9	,    a=9_9	,    a=3_2	,    a=5	,    a=4	,    a=4.0	,    a=2_5_7	,    a=None	,    )	->							List[Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							List[str]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 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	,    a	,    a					)	->							List[str]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							Union[str, Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _A           =    self.prepare_config_and_inputs()
     _A    ,   _A           =    config_and_inputs
     _A           =    {'''pixel_values''': pixel_values}
     return config, inputs_dict
  
  
  
  
  
  
  
  @require_torch
  class 		_snake_case      (			lowerCamelCase					,lowerCamelCase					,unittest.TestCase				):
  
  
  
  
  
   """simple docstring"""
  
  
  
   lowerCamelCase_          =			(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
   lowerCamelCase_          =			{'''feature-extraction''': MgpstrForSceneTextRecognition} if is_torch_available() else {}
   lowerCamelCase_          =			False
  
   lowerCamelCase_          =			False
   lowerCamelCase_          =			False
   lowerCamelCase_          =			False
   lowerCamelCase_          =			False
   def lowercase_		(						self					)	->							Optional[Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _A           =    MgpstrModelTester(self					)
     _A           =    ConfigTester(self	,    config_class=a	,    has_text_modality=a					)
   def lowercase_		(						self					)	->							Union[str, Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     self.config_tester.run_common_tests()
   def lowercase_		(						self					)	->							Optional[int]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							Any:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     pass
   def lowercase_		(						self					)	->							Union[str, Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							Tuple:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							List[Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     pass
   def lowercase_		(						self					)	->							List[Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							Optional[Any]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     def check_hidden_states_output(a	,    a	,    a					):
       _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 lowercase_		(						self					)	->							Any:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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 lowercase_		(						self					)	->							Dict:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     pass
  
  
  
  
  
  
  
  def     UpperCAmelCase__ (							)   -> Union[str, Any]:
    _A           =    '''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
    _A           =    Image.open(requests.get(__snake_case						,				stream=__snake_case							).raw							).convert('''RGB'''							)
    return im
  
  
  
  @require_vision
  @require_torch
  class 		_snake_case      (			unittest.TestCase				):
  
  
  
  
  
   """simple docstring"""
  
  
  
   @slow
   def lowercase_		(						self					)	->							Optional[int]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     _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, 2_7, 3_8)					)					)
  
     _A           =    processor.batch_decode(outputs.logits					)
     _A           =    '''ticket'''
  
     self.assertEqual(out_strs['''generated_text'''][0]	,    a					)
  
     _A           =    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=a	,    )
  
     self.assertTrue(torch.allclose(outputs.logits[0][:, 1:4, 1:4]	,    a	,    atol=1e-4					)					)
style_context: 
  
  
  
  from ..utils import requires_backends
  
  
  __lowerCamelCase  				=					None
  
  
  
  class 		_snake_case      :
  
  
  
  
  
   """simple docstring"""
  
  
  
   def __init__(						self	,    *a	,    **a					)	->							Tuple:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     requires_backends(self	,    ['''detectron2''']					)
  
  
  
   @classmethod
   def lowercase_		(						cls	,    *a	,    **a					)	->							Optional[int]:
  
  
  
  
     """simple docstring"""
  
  
  
  
  
  
  
     requires_backends(cls	,    ['''detectron2''']					)