"""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 							__snake_case:


    '''simple docstring'''





    def __init__(  self					,       __lowerCamelCase					,       __lowerCamelCase=False					,       __lowerCamelCase=13					,       __lowerCamelCase=(32, 128)					,       __lowerCamelCase=4					,       __lowerCamelCase=3					,       __lowerCamelCase=27					,       __lowerCamelCase=38					,       __lowerCamelCase=99					,       __lowerCamelCase=99					,       __lowerCamelCase=32					,       __lowerCamelCase=5					,       __lowerCamelCase=4					,       __lowerCamelCase=4.0					,       __lowerCamelCase=257					,       __lowerCamelCase=None					,       ):




         '''simple docstring'''



         __A					:					List[Any]								=		parent
         __A					:					int								=		is_training
         __A					:					int								=		batch_size
         __A					:					Tuple								=		image_size
         __A					:					List[Any]								=		patch_size
         __A					:					int								=		num_channels
         __A					:					int								=		max_token_length
         __A					:					Union[str, Any]								=		num_character_labels
         __A					:					Optional[int]								=		num_bpe_labels
         __A					:					List[str]								=		num_wordpiece_labels
         __A					:					List[Any]								=		hidden_size
         __A					:					str								=		num_hidden_layers
         __A					:					List[Any]								=		num_attention_heads
         __A					:					Optional[int]								=		mlp_ratio
         __A					:					Optional[int]								=		patch_embeds_hidden_size
         __A					:					Dict								=		output_hidden_states
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					str								=		floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]	)
         __A					:					List[str]								=		self.get_config()
         return config, pixel_values
    def 						_a							(  self	):




         '''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					,       __lowerCamelCase					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Union[str, Any]								=		MgpstrForSceneTextRecognition(__lowerCamelCase	)
         model.to(__lowerCamelCase	)
         model.eval()
         with torch.no_grad():
              __A					:					Dict								=		model(__lowerCamelCase	)
         self.parent.assertEqual(
             generated_ids[0][0].shape					,       (self.batch_size, self.max_token_length, self.num_character_labels)	)

    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		self.prepare_config_and_inputs()
         __A						,		__A					:					Dict								=		config_and_inputs
         __A					:					Union[str, Any]								=		{'pixel_values': pixel_values}
         return config, inputs_dict







@require_torch
class 							__snake_case(					A_				,	A_				,	unittest.TestCase	):


    '''simple docstring'''





    _UpperCAmelCase       =			(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
    _UpperCAmelCase       =			{"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
    _UpperCAmelCase       =			False

    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False
    _UpperCAmelCase       =			False
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		MgpstrModelTester(self	)
         __A					:					Dict								=		ConfigTester(self					,       config_class=__lowerCamelCase					,       has_text_modality=__lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         self.config_tester.run_common_tests()
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[Any]								=		self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__lowerCamelCase	)
    @unittest.skip(reason='MgpstrModel does not use inputs_embeds'	)
    def 						_a							(  self	):




         '''simple docstring'''



         pass
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __A					:					Any								=		model_class(__lowerCamelCase	)
              self.assertIsInstance(model.get_input_embeddings()					,       (nn.Module)	)
              __A					:					Optional[int]								=		model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(__lowerCamelCase					,       nn.Linear	)	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Dict								=		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __A					:					int								=		model_class(__lowerCamelCase	)
              __A					:					List[Any]								=		inspect.signature(model.forward	)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              __A					:					Optional[Any]								=		[*signature.parameters.keys()]

              __A					:					List[str]								=		['pixel_values']
              self.assertListEqual(arg_names[:1]					,       __lowerCamelCase	)
    @unittest.skip(reason='MgpstrModel does not support feedforward chunking'	)
    def 						_a							(  self	):




         '''simple docstring'''



         pass
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Tuple								=		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					:					List[str]								=		True
              __A					:					Optional[int]								=		model_class(__lowerCamelCase	)
              self.assertTrue(model.is_gradient_checkpointing	)
    def 						_a							(  self	):




         '''simple docstring'''



         def check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	):
              __A					:					Any								=		model_class(__lowerCamelCase	)
              model.to(__lowerCamelCase	)
              model.eval()

              with torch.no_grad():
                   __A					:					Union[str, Any]								=		model(**self._prepare_for_class(__lowerCamelCase					,       __lowerCamelCase	)	)

              __A					:					Tuple								=		outputs.hidden_states

              __A					:					Tuple								=		getattr(
                  self.model_tester					,       'expected_num_hidden_layers'					,       self.model_tester.num_hidden_layers + 1	)
              self.assertEqual(len(__lowerCamelCase	)					,       __lowerCamelCase	)

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

         __A						,		__A					:					List[str]								=		self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              __A					:					str								=		True
              check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              __A					:					str								=		True

              check_hidden_states_output(__lowerCamelCase					,       __lowerCamelCase					,       __lowerCamelCase	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A						,		__A					:					Union[str, Any]								=		self.model_tester.prepare_config_and_inputs_for_common()

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




         '''simple docstring'''



         pass







def 						_lowercase				(  )    ->     Any:







     '''simple docstring'''


     __A					:					Optional[Any]								=		'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
     __A					:					Optional[Any]								=		Image.open(requests.get(_SCREAMING_SNAKE_CASE  ,       stream=_SCREAMING_SNAKE_CASE						).raw						).convert('RGB'						)
     return im






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


    '''simple docstring'''





    @slow
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[Any]								=		'alibaba-damo/mgp-str-base'
         __A					:					List[str]								=		MgpstrForSceneTextRecognition.from_pretrained(__lowerCamelCase	).to(__lowerCamelCase	)
         __A					:					List[str]								=		MgpstrProcessor.from_pretrained(__lowerCamelCase	)

         __A					:					Tuple								=		prepare_img()
         __A					:					Optional[Any]								=		processor(images=__lowerCamelCase					,       return_tensors='pt'	).pixel_values.to(__lowerCamelCase	)

         # forward pass
         with torch.no_grad():
              __A					:					Tuple								=		model(__lowerCamelCase	)

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

         __A					:					Optional[int]								=		processor.batch_decode(outputs.logits	)
         __A					:					int								=		'ticket'

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

         __A					:					str								=		torch.tensor(
             [[[-39.53_97, -44.40_24, -36.18_44], [-61.47_09, -63.86_39, -58.34_54], [-74.02_25, -68.54_94, -71.21_64]]]					,       device=__lowerCamelCase					,       )

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




"""simple docstring"""







import pytest

from datasets.utils.version import Version




@pytest.mark.parametrize(
    'other, expected_equality'  ,       [
        (Version('1.0.0'						), True),
        ('1.0.0', True),
        (Version('2.0.0'						), False),
        ('2.0.0', False),
        ('1', False),
        ('a', False),
        (1, False),
        (None, False),
    ]  ,       )
def 						_lowercase				(  _SCREAMING_SNAKE_CASE				:				Tuple  ,       _SCREAMING_SNAKE_CASE				:				Any						)    ->     List[str]:







     '''simple docstring'''


     __A					:					Tuple								=		Version('1.0.0'						)
     assert (version == other) is expected_equality
     assert (version != other) is not expected_equality
     assert (hash(_SCREAMING_SNAKE_CASE						) == hash(_SCREAMING_SNAKE_CASE						)) is expected_equality



