






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_      :






      '''simple docstring'''




      def __init__(   self   :		List[str]				,      __UpperCAmelCase   :		List[str]				,      __UpperCAmelCase   :		int=False				,      __UpperCAmelCase   :		int=13				,      __UpperCAmelCase   :		Optional[int]=(32, 128)				,      __UpperCAmelCase   :		Optional[int]=4				,      __UpperCAmelCase   :		List[Any]=3				,      __UpperCAmelCase   :		Optional[int]=27				,      __UpperCAmelCase   :		int=38				,      __UpperCAmelCase   :		Optional[int]=99				,      __UpperCAmelCase   :		Tuple=99				,      __UpperCAmelCase   :		Optional[int]=32				,      __UpperCAmelCase   :		List[Any]=5				,      __UpperCAmelCase   :		Optional[Any]=4				,      __UpperCAmelCase   :		Optional[Any]=4.0				,      __UpperCAmelCase   :		Optional[int]=257				,      __UpperCAmelCase   :		Tuple=None				,      )					->int:




       """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    __lowerCAmelCase      (   self   :		str						)					->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    __lowerCAmelCase      (   self   :		Optional[int]						)					->List[str]:




       """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    __lowerCAmelCase      (   self   :		Union[str, Any]				,      __UpperCAmelCase   :		Union[str, Any]				,      __UpperCAmelCase   :		List[Any]						)					->Dict:




       """simple docstring"""


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







      def    __lowerCAmelCase      (   self   :		Tuple						)					->Tuple:




       """simple docstring"""


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






@require_torch
class 	lowercase_      (			a_				,						a_				,						unittest.TestCase     ):






      '''simple docstring'''




      __snake_case  						=						(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
      __snake_case  						=						{'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
      __snake_case  						=						False

      __snake_case  						=						False
      __snake_case  						=						False
      __snake_case  						=						False
      __snake_case  						=						False







      def    __lowerCAmelCase      (   self   :		Dict						)					->List[Any]:




       """simple docstring"""


       a							=   MgpstrModelTester(self						)
       a							=   ConfigTester(self				,      config_class=__UpperCAmelCase				,      has_text_modality=__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		List[Any]						)					->Any:




       """simple docstring"""


       self.config_tester.run_common_tests()







      def    __lowerCAmelCase      (   self   :		int						)					->Any:




       """simple docstring"""


       a							=   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    __lowerCAmelCase      (   self   :		Tuple						)					->Dict:




       """simple docstring"""


       pass







      def    __lowerCAmelCase      (   self   :		Dict						)					->Dict:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()

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







      def    __lowerCAmelCase      (   self   :		List[Any]						)					->Tuple:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        a							=   model_class(__UpperCAmelCase						)
        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]				,      __UpperCAmelCase						)







      @unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''						)
      def    __lowerCAmelCase      (   self   :		Optional[Any]						)					->Optional[Any]:




       """simple docstring"""


       pass







      def    __lowerCAmelCase      (   self   :		str						)					->List[Any]:




       """simple docstring"""


       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(__UpperCAmelCase						)
        self.assertTrue(model.is_gradient_checkpointing						)







      def    __lowerCAmelCase      (   self   :		Tuple						)					->Tuple:




       """simple docstring"""


       def check_hidden_states_output(__UpperCAmelCase   :		int				,      __UpperCAmelCase   :		Optional[Any]				,      __UpperCAmelCase   :		Optional[int]						):
        a							=   model_class(__UpperCAmelCase						)
        model.to(__UpperCAmelCase						)
        model.eval()

        with torch.no_grad():
         a							=   model(**self._prepare_for_class(__UpperCAmelCase				,      __UpperCAmelCase						)						)

        a							=   outputs.hidden_states

        a							=   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]				,      )

       a							=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        a							=   True
        check_hidden_states_output(__UpperCAmelCase				,      __UpperCAmelCase				,      __UpperCAmelCase						)

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

        check_hidden_states_output(__UpperCAmelCase				,      __UpperCAmelCase				,      __UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		List[Any]						)					->Optional[Any]:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()

       a							=   _config_zero_init(__UpperCAmelCase						)
       for model_class in self.all_model_classes:
        a							=   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    __lowerCAmelCase      (   self   :		List[str]						)					->str:




       """simple docstring"""


       pass
def 		_a					(   )							->    str:
 a							=   'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
 a							=   Image.open(requests.get(lowercase_			,							stream=lowercase_				).raw				).convert('''RGB'''				)
 return im






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






      '''simple docstring'''




      @slow
      def    __lowerCAmelCase      (   self   :		Dict						)					->Dict:




       """simple docstring"""


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

       a							=   prepare_img()
       a							=   processor(images=__UpperCAmelCase				,      return_tensors='''pt'''						).pixel_values.to(__UpperCAmelCase						)

       # forward pass
       with torch.no_grad():
        a							=   model(__UpperCAmelCase						)

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

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

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

       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=__UpperCAmelCase				,      )

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










import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding






class 	lowercase_      (			lowercase     ):






      '''simple docstring'''




      __snake_case  						=						['''image_processor''', '''tokenizer''']
      __snake_case  						=						'''AutoImageProcessor'''
      __snake_case  						=						'''AutoTokenizer'''







      def __init__(   self   :		Any				,      __UpperCAmelCase   :		Union[str, Any]=None				,      __UpperCAmelCase   :		int=None				,      **__UpperCAmelCase   :		Union[str, Any]						)					->Dict:




       """simple docstring"""


       a							=   None
       if "feature_extractor" in kwargs:
        warnings.warn(
            '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
            ''' instead.'''				,      __UpperCAmelCase				,      )
        a							=   kwargs.pop('''feature_extractor'''						)

       a							=   image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
        raise ValueError('''You have to specify an image_processor.'''						)
       if tokenizer is None:
        raise ValueError('''You have to specify a tokenizer.'''						)

       super().__init__(__UpperCAmelCase				,      __UpperCAmelCase						)
       a							=   self.image_processor







      def __call__(   self   :		List[Any]				,      __UpperCAmelCase   :		Optional[Any]=None				,      __UpperCAmelCase   :		Optional[int]=None				,      __UpperCAmelCase   :		str=None				,      **__UpperCAmelCase   :		List[Any]						)					->Dict:




       """simple docstring"""


       if text is None and images is None:
        raise ValueError('''You have to specify either text or images. Both cannot be none.'''						)

       if text is not None:
        a							=   self.tokenizer(__UpperCAmelCase				,      return_tensors=__UpperCAmelCase				,      **__UpperCAmelCase						)

       if images is not None:
        a							=   self.image_processor(__UpperCAmelCase				,      return_tensors=__UpperCAmelCase				,      **__UpperCAmelCase						)

       if text is not None and images is not None:
        a							=   image_features.pixel_values
        return encoding
       elif text is not None:
        return encoding
       else:
        return BatchEncoding(data=dict(**__UpperCAmelCase						)				,      tensor_type=__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		List[Any]				,      *__UpperCAmelCase   :		Optional[Any]				,      **__UpperCAmelCase   :		List[str]						)					->Optional[Any]:




       """simple docstring"""


       return self.tokenizer.batch_decode(*__UpperCAmelCase				,      **__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		str				,      *__UpperCAmelCase   :		List[Any]				,      **__UpperCAmelCase   :		Optional[Any]						)					->Union[str, Any]:




       """simple docstring"""


       return self.tokenizer.decode(*__UpperCAmelCase				,      **__UpperCAmelCase						)







      @property
      def    __lowerCAmelCase      (   self   :		str						)					->str:




       """simple docstring"""


       a							=   self.tokenizer.model_input_names
       a							=   self.image_processor.model_input_names
       return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names						)						)







      @property
      def    __lowerCAmelCase      (   self   :		str						)					->Optional[Any]:




       """simple docstring"""


       warnings.warn(
           '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''				,      __UpperCAmelCase				,      )
       return self.image_processor_class







      @property
      def    __lowerCAmelCase      (   self   :		int						)					->Optional[Any]:




       """simple docstring"""


       warnings.warn(
           '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''				,      __UpperCAmelCase				,      )
       return self.image_processor


