





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    :		List[Any]      ,    snake_case    :		List[str]      ,    snake_case    :		int=False      ,    snake_case    :		List[str]=13      ,    snake_case    :		int=(32, 128)      ,    snake_case    :		Tuple=4      ,    snake_case    :		Tuple=3      ,    snake_case    :		Optional[Any]=27      ,    snake_case    :		int=38      ,    snake_case    :		str=99      ,    snake_case    :		Optional[int]=99      ,    snake_case    :		List[str]=32      ,    snake_case    :		Optional[int]=5      ,    snake_case    :		Tuple=4      ,    snake_case    :		List[Any]=4.0      ,    snake_case    :		Tuple=257      ,    snake_case    :		str=None      ,    ):

      """simple docstring"""





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





    def 						A		( self    :		Any				):

      """simple docstring"""





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





    def 						A		( self    :		int				):

      """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 						A		( self    :		int      ,    snake_case    :		List[Any]      ,    snake_case    :		Tuple				):

      """simple docstring"""





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





    def 						A		( self    :		List[Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.prepare_config_and_inputs()
      __lowerCAmelCase						,    __lowerCAmelCase								=					config_and_inputs
      __lowerCAmelCase								=					{'''pixel_values''': pixel_values}
      return config, inputs_dict


@require_torch
class 	__snake_case					(      _a							,					_a							,					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 						A		( self    :		List[Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					MgpstrModelTester(self				)
      __lowerCAmelCase								=					ConfigTester(self      ,    config_class=snake_case      ,    has_text_modality=snake_case				)





    def 						A		( self    :		Optional[int]				):

      """simple docstring"""





      self.config_tester.run_common_tests()





    def 						A		( self    :		Optional[Any]				):

      """simple docstring"""





      __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case				)





    @unittest.skip(reason='''MgpstrModel does not use inputs_embeds'''				)
    def 						A		( self    :		int				):

      """simple docstring"""





      pass





    def 						A		( self    :		str				):

      """simple docstring"""





      __lowerCAmelCase						,    __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

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





    def 						A		( self    :		int				):

      """simple docstring"""





      __lowerCAmelCase						,    __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

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

        __lowerCAmelCase								=					['''pixel_values''']
        self.assertListEqual(arg_names[:1]      ,    snake_case				)





    @unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''				)
    def 						A		( self    :		List[Any]				):

      """simple docstring"""





      pass





    def 						A		( self    :		int				):

      """simple docstring"""





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

        __lowerCAmelCase								=					True
        __lowerCAmelCase								=					model_class(snake_case				)
        self.assertTrue(model.is_gradient_checkpointing				)





    def 						A		( self    :		Any				):

      """simple docstring"""





      def check_hidden_states_output(snake_case    :		int      ,    snake_case    :		Union[str, Any]      ,    snake_case    :		Dict				):
        __lowerCAmelCase								=					model_class(snake_case				)
        model.to(snake_case				)
        model.eval()

        with torch.no_grad():
          __lowerCAmelCase								=					model(**self._prepare_for_class(snake_case      ,    snake_case				)				)

        __lowerCAmelCase								=					outputs.hidden_states

        __lowerCAmelCase								=					getattr(
            self.model_tester      ,    '''expected_num_hidden_layers'''      ,    self.model_tester.num_hidden_layers + 1				)
        self.assertEqual(len(snake_case				)      ,    snake_case				)

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

      __lowerCAmelCase						,    __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        __lowerCAmelCase								=					True
        check_hidden_states_output(snake_case      ,    snake_case      ,    snake_case				)

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

        check_hidden_states_output(snake_case      ,    snake_case      ,    snake_case				)





    def 						A		( self    :		Optional[int]				):

      """simple docstring"""





      __lowerCAmelCase						,    __lowerCAmelCase								=					self.model_tester.prepare_config_and_inputs_for_common()

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

      """simple docstring"""





      pass


def        __SCREAMING_SNAKE_CASE	(				):



  '''simple docstring'''






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




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






    '''simple docstring'''





    @slow
    def 						A		( self    :		Any				):

      """simple docstring"""





      __lowerCAmelCase								=					'''alibaba-damo/mgp-str-base'''
      __lowerCAmelCase								=					MgpstrForSceneTextRecognition.from_pretrained(snake_case				).to(snake_case				)
      __lowerCAmelCase								=					MgpstrProcessor.from_pretrained(snake_case				)

      __lowerCAmelCase								=					prepare_img()
      __lowerCAmelCase								=					processor(images=snake_case      ,    return_tensors='''pt'''				).pixel_values.to(snake_case				)

      # forward pass
      with torch.no_grad():
        __lowerCAmelCase								=					model(snake_case				)

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

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

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

      __lowerCAmelCase								=					torch.tensor(
          [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]      ,    device=snake_case      ,    )

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







def        __SCREAMING_SNAKE_CASE	(				__lowercase:		int):



  '''simple docstring'''






  if not isinstance(__lowercase  ,				__lowercase):
    __lowerCAmelCase								=					F'''Input value of [number={number}] must be an integer'''
    raise TypeError(__lowercase)
  if number < 0 or number % 2 == 1:
    return False
  __lowerCAmelCase								=					int(number**0.5)
  return number == number_sqrt * (number_sqrt + 1)


if __name__ == "__main__":
      import doctest

      doctest.testmod()
