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 				_lowerCamelCase :
  
  
  
        """simple docstring"""
  
  
  
  
  
  
        def __init__( self				,						UpperCAmelCase				,						UpperCAmelCase=False				,						UpperCAmelCase=13				,						UpperCAmelCase=(32, 128)				,						UpperCAmelCase=4				,						UpperCAmelCase=3				,						UpperCAmelCase=27				,						UpperCAmelCase=38				,						UpperCAmelCase=99				,						UpperCAmelCase=99				,						UpperCAmelCase=32				,						UpperCAmelCase=5				,						UpperCAmelCase=4				,						UpperCAmelCase=4.0				,						UpperCAmelCase=257				,						UpperCAmelCase=None				,						)       ->   Dict:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				List[str]        =       parent
          __snake_case   :				Tuple        =       is_training
          __snake_case   :				Dict        =       batch_size
          __snake_case   :				str        =       image_size
          __snake_case   :				Any        =       patch_size
          __snake_case   :				List[Any]        =       num_channels
          __snake_case   :				List[str]        =       max_token_length
          __snake_case   :				Any        =       num_character_labels
          __snake_case   :				Tuple        =       num_bpe_labels
          __snake_case   :				int        =       num_wordpiece_labels
          __snake_case   :				Any        =       hidden_size
          __snake_case   :				List[Any]        =       num_hidden_layers
          __snake_case   :				str        =       num_attention_heads
          __snake_case   :				Any        =       mlp_ratio
          __snake_case   :				int        =       patch_embeds_hidden_size
          __snake_case   :				Union[str, Any]        =       output_hidden_states
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   Dict:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				Any        =       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]   )
          __snake_case   :				str        =       self.get_config()
          return config, pixel_values
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   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 						UpperCAmelCase		( self				,						UpperCAmelCase				,						UpperCAmelCase   )       ->   Union[str, Any]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				int        =       MgpstrForSceneTextRecognition(UpperCAmelCase   )
          model.to(UpperCAmelCase   )
          model.eval()
          with torch.no_grad():
            __snake_case   :				List[str]        =       model(UpperCAmelCase   )
          self.parent.assertEqual(
              generated_ids[0][0].shape				,						(self.batch_size, self.max_token_length, self.num_character_labels)   )
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   Dict:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				Union[str, Any]        =       self.prepare_config_and_inputs()
          __snake_case    ,   __snake_case   :				Dict        =       config_and_inputs
          __snake_case   :				Union[str, Any]        =       {"pixel_values": pixel_values}
          return config, inputs_dict
  
  
  
  
  @require_torch
  class 				_lowerCamelCase (    a ,   a ,   unittest.TestCase    ):
  
  
  
        """simple docstring"""
  
  
  
  
  
  
        UpperCAmelCase_						:      Union[str, Any]       =(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
        UpperCAmelCase_						:      List[Any]       ={"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
        UpperCAmelCase_						:      Tuple       =False
  
        UpperCAmelCase_						:      Any       =False
        UpperCAmelCase_						:      Any       =False
        UpperCAmelCase_						:      Tuple       =False
        UpperCAmelCase_						:      Union[str, Any]       =False
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   List[str]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				int        =       MgpstrModelTester(self   )
          __snake_case   :				Union[str, Any]        =       ConfigTester(self				,						config_class=UpperCAmelCase				,						has_text_modality=UpperCAmelCase   )
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   Any:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          self.config_tester.run_common_tests()
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   Tuple:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				List[Any]        =       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 						UpperCAmelCase		( self   )       ->   Optional[Any]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          pass
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   List[str]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case    ,   __snake_case   :				int        =       self.model_tester.prepare_config_and_inputs_for_common()
  
          for model_class in self.all_model_classes:
            __snake_case   :				Optional[Any]        =       model_class(UpperCAmelCase   )
            self.assertIsInstance(model.get_input_embeddings()				,						(nn.Module)   )
            __snake_case   :				str        =       model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(UpperCAmelCase				,						nn.Linear   )   )
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   List[Any]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case    ,   __snake_case   :				str        =       self.model_tester.prepare_config_and_inputs_for_common()
  
          for model_class in self.all_model_classes:
            __snake_case   :				str        =       model_class(UpperCAmelCase   )
            __snake_case   :				Any        =       inspect.signature(model.forward   )
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            __snake_case   :				str        =       [*signature.parameters.keys()]
  
            __snake_case   :				int        =       ["pixel_values"]
            self.assertListEqual(arg_names[:1]				,						UpperCAmelCase   )
  
  
  
  
  
  
  
        @unittest.skip(reason="MgpstrModel does not support feedforward chunking"   )
        def 						UpperCAmelCase		( self   )       ->   int:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          pass
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   Union[str, Any]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case    ,   __snake_case   :				Any        =       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   :				Optional[int]        =       True
            __snake_case   :				int        =       model_class(UpperCAmelCase   )
            self.assertTrue(model.is_gradient_checkpointing   )
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   str:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          def check_hidden_states_output(UpperCAmelCase				,						UpperCAmelCase				,						UpperCAmelCase   ):
            __snake_case   :				Union[str, Any]        =       model_class(UpperCAmelCase   )
            model.to(UpperCAmelCase   )
            model.eval()
  
            with torch.no_grad():
              __snake_case   :				List[str]        =       model(**self._prepare_for_class(UpperCAmelCase				,						UpperCAmelCase   )   )
  
            __snake_case   :				Union[str, Any]        =       outputs.hidden_states
  
            __snake_case   :				Any        =       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]				,						)
  
          __snake_case    ,   __snake_case   :				Optional[Any]        =       self.model_tester.prepare_config_and_inputs_for_common()
  
          for model_class in self.all_model_classes:
            __snake_case   :				Dict        =       True
            check_hidden_states_output(UpperCAmelCase				,						UpperCAmelCase				,						UpperCAmelCase   )
  
            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            __snake_case   :				Optional[int]        =       True
  
            check_hidden_states_output(UpperCAmelCase				,						UpperCAmelCase				,						UpperCAmelCase   )
  
  
  
  
  
  
  
        def 						UpperCAmelCase		( self   )       ->   int:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case    ,   __snake_case   :				Optional[Any]        =       self.model_tester.prepare_config_and_inputs_for_common()
  
          __snake_case   :				List[Any]        =       _config_zero_init(UpperCAmelCase   )
          for model_class in self.all_model_classes:
            __snake_case   :				int        =       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 						UpperCAmelCase		( self   )       ->   List[Any]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          pass
  
  
  
  
  
  
  
  def       lowerCAmelCase__(	) ->    Any:
    __snake_case   :				Optional[Any]        =       "https://i.postimg.cc/ZKwLg2Gw/367-14.png"
    __snake_case   :				List[str]        =       Image.open(requests.get(lowercase   ,     stream=lowercase				).raw				).convert("RGB"				)
    return im
  
  
  
  
  @require_vision
  @require_torch
  class 				_lowerCamelCase (    unittest.TestCase    ):
  
  
  
        """simple docstring"""
  
  
  
  
  
  
        @slow
        def 						UpperCAmelCase		( self   )       ->   Union[str, Any]:
  
  
  
  
  
  
          '''simple docstring'''
  
  
  
  
  
  
          __snake_case   :				Optional[int]        =       "alibaba-damo/mgp-str-base"
          __snake_case   :				Any        =       MgpstrForSceneTextRecognition.from_pretrained(UpperCAmelCase   ).to(UpperCAmelCase   )
          __snake_case   :				List[str]        =       MgpstrProcessor.from_pretrained(UpperCAmelCase   )
  
          __snake_case   :				str        =       prepare_img()
          __snake_case   :				Optional[int]        =       processor(images=UpperCAmelCase				,						return_tensors="pt"   ).pixel_values.to(UpperCAmelCase   )
  
          # forward pass
          with torch.no_grad():
            __snake_case   :				int        =       model(UpperCAmelCase   )
  
          # verify the logits
          self.assertEqual(outputs.logits[0].shape				,						torch.Size((1, 27, 38)   )   )
  
          __snake_case   :				Dict        =       processor.batch_decode(outputs.logits   )
          __snake_case   :				Any        =       "ticket"
  
          self.assertEqual(out_strs["generated_text"][0]				,						UpperCAmelCase   )
  
          __snake_case   :				Union[str, Any]        =       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   )   )
  
  
style_context: 
  
  
  
  
  
  def       lowerCAmelCase__(	lowercase       :    str				) ->    int:
    __snake_case   :				List[str]        =       str(lowercase				).strip()
    if not oct_string:
      raise ValueError("Empty string was passed to the function"				)
    __snake_case   :				int        =       oct_string[0] == "-"
    if is_negative:
      __snake_case   :				Union[str, Any]        =       oct_string[1:]
    if not oct_string.isdigit() or not all(0 <= int(lowercase				) <= 7 for char in oct_string				):
      raise ValueError("Non-octal value was passed to the function"				)
    __snake_case   :				List[Any]        =       0
    for char in oct_string:
      __snake_case   :				Optional[Any]        =       8 * decimal_number + int(lowercase				)
    if is_negative:
      __snake_case   :				Any        =       -decimal_number
    return decimal_number
  
  
  if __name__ == "__main__":
       from doctest import testmod
  
       testmod()
  
  