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 				_SCREAMING_SNAKE_CASE:
   def __init__(     self				,  lowerCAmelCase_				,  lowerCAmelCase_=False				,  lowerCAmelCase_=13				,  lowerCAmelCase_=(32, 1_28)				,  lowerCAmelCase_=4				,  lowerCAmelCase_=3				,  lowerCAmelCase_=27				,  lowerCAmelCase_=38				,  lowerCAmelCase_=99				,  lowerCAmelCase_=99				,  lowerCAmelCase_=32				,  lowerCAmelCase_=5				,  lowerCAmelCase_=4				,  lowerCAmelCase_=4.0				,  lowerCAmelCase_=2_57				,  lowerCAmelCase_=None				,  )						->Optional[int]:
        a	:     int						      =    parent
        a	:     Optional[int]						      =    is_training
        a	:     Dict						      =    batch_size
        a	:     List[Any]						      =    image_size
        a	:     Any						      =    patch_size
        a	:     Tuple						      =    num_channels
        a	:     List[str]						      =    max_token_length
        a	:     Optional[Any]						      =    num_character_labels
        a	:     Tuple						      =    num_bpe_labels
        a	:     List[str]						      =    num_wordpiece_labels
        a	:     List[str]						      =    hidden_size
        a	:     List[Any]						      =    num_hidden_layers
        a	:     Dict						      =    num_attention_heads
        a	:     str						      =    mlp_ratio
        a	:     Dict						      =    patch_embeds_hidden_size
        a	:     str						      =    output_hidden_states
   def _lowercase(     self     )						->int:
        a	:     Union[str, Any]						      =    floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]     )
        a	:     Any						      =    self.get_config()
        return config, pixel_values
   def _lowercase(     self     )						->int:
        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				,  lowerCAmelCase_				,  lowerCAmelCase_     )						->Tuple:
        a	:     Tuple						      =    MgpstrForSceneTextRecognition(_UpperCAmelCase     )
        model.to(_UpperCAmelCase     )
        model.eval()
        with torch.no_grad():
             a	:     List[str]						      =    model(_UpperCAmelCase     )
        self.parent.assertEqual(
            generated_ids[0][0].shape				,  (self.batch_size, self.max_token_length, self.num_character_labels)     )


   def _lowercase(     self     )						->int:
        a	:     Optional[int]						      =    self.prepare_config_and_inputs()
        a      ,				a	:     Optional[Any]						      =    config_and_inputs
        a	:     int						      =    {'''pixel_values''': pixel_values}
        return config, inputs_dict






@require_torch
class 				_SCREAMING_SNAKE_CASE( lowerCamelCase__							,   lowerCamelCase__							,   unittest.TestCase						):
   UpperCamelCase_					:    Optional[int]			      = (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
   UpperCamelCase_					:    Tuple			      = {'feature-extraction': MgpstrForSceneTextRecognition} if is_torch_available() else {}
   UpperCamelCase_					:    Union[str, Any]			      = False

   UpperCamelCase_					:    List[str]			      = False
   UpperCamelCase_					:    Tuple			      = False
   UpperCamelCase_					:    str			      = False
   UpperCamelCase_					:    List[str]			      = False
   def _lowercase(     self     )						->Any:
        a	:     Union[str, Any]						      =    MgpstrModelTester(self     )
        a	:     Optional[int]						      =    ConfigTester(self				,  config_class=_UpperCAmelCase				,  has_text_modality=_UpperCAmelCase     )
   def _lowercase(     self     )						->Any:
        self.config_tester.run_common_tests()
   def _lowercase(     self     )						->Any:
        a	:     Dict						      =    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 _lowercase(     self     )						->Dict:
        pass
   def _lowercase(     self     )						->List[str]:
        a      ,				a	:     Tuple						      =    self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             a	:     str						      =    model_class(_UpperCAmelCase     )
             self.assertIsInstance(model.get_input_embeddings()				,  (nn.Module)     )
             a	:     Union[str, Any]						      =    model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(_UpperCAmelCase				,  nn.Linear     )     )
   def _lowercase(     self     )						->Any:
        a      ,				a	:     Tuple						      =    self.model_tester.prepare_config_and_inputs_for_common()

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

             a	:     int						      =    ['''pixel_values''']
             self.assertListEqual(arg_names[:1]				,  _UpperCAmelCase     )
   @unittest.skip(reason='''MgpstrModel does not support feedforward chunking'''     )
   def _lowercase(     self     )						->List[Any]:
        pass
   def _lowercase(     self     )						->Dict:
        a      ,				a	:     List[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

             a	:     Any						      =    True
             a	:     int						      =    model_class(_UpperCAmelCase     )
             self.assertTrue(model.is_gradient_checkpointing     )
   def _lowercase(     self     )						->Any:
        def check_hidden_states_output(lowerCAmelCase_				,  lowerCAmelCase_				,  lowerCAmelCase_     ):
             a	:     List[str]						      =    model_class(_UpperCAmelCase     )
             model.to(_UpperCAmelCase     )
             model.eval()

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

             a	:     Tuple						      =    outputs.hidden_states

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

        a      ,				a	:     int						      =    self.model_tester.prepare_config_and_inputs_for_common()

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

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

             check_hidden_states_output(_UpperCAmelCase				,  _UpperCAmelCase				,  _UpperCAmelCase     )
   def _lowercase(     self     )						->List[Any]:
        a      ,				a	:     Optional[int]						      =    self.model_tester.prepare_config_and_inputs_for_common()

        a	:     Any						      =    _config_zero_init(_UpperCAmelCase     )
        for model_class in self.all_model_classes:
             a	:     Dict						      =    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 _lowercase(     self     )						->Optional[int]:
        pass







def 						UpperCAmelCase							(		)						->						List[Any]:
     a	:     List[Any]						      =    '''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
     a	:     Dict						      =    Image.open(requests.get(lowerCAmelCase_    ,   stream=lowerCAmelCase_							).raw							).convert('''RGB'''							)
     return im






@require_vision
@require_torch
class 				_SCREAMING_SNAKE_CASE( unittest.TestCase						):
   @slow
   def _lowercase(     self     )						->int:
        a	:     Tuple						      =    '''alibaba-damo/mgp-str-base'''
        a	:     Union[str, Any]						      =    MgpstrForSceneTextRecognition.from_pretrained(_UpperCAmelCase     ).to(_UpperCAmelCase     )
        a	:     Dict						      =    MgpstrProcessor.from_pretrained(_UpperCAmelCase     )

        a	:     Tuple						      =    prepare_img()
        a	:     str						      =    processor(images=_UpperCAmelCase				,  return_tensors='''pt'''     ).pixel_values.to(_UpperCAmelCase     )

        # forward pass
        with torch.no_grad():
             a	:     List[str]						      =    model(_UpperCAmelCase     )

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

        a	:     List[Any]						      =    processor.batch_decode(outputs.logits     )
        a	:     Dict						      =    '''ticket'''

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

        a	:     Dict						      =    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=_UpperCAmelCase				,  )

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



from collections import OrderedDict
from dataclasses import fields
from typing import Any, Tuple

import numpy as np

from .import_utils import is_torch_available






def 			__lowerCAmelCase       (SCREAMING_SNAKE_CASE   )->    Union[str, Any]:




      """simple docstring"""

      if is_torch_available():
            import torch

            if isinstance(SCREAMING_SNAKE_CASE   ,   torch.Tensor   ):
                  return True

      return isinstance(SCREAMING_SNAKE_CASE   ,   np.ndarray   )







class lowerCAmelCase_		(					lowerCamelCase__			):

 '''simple docstring'''

 def 		UpperCamelCase__	(      self   ):
       snake_case_			= fields(self   )

       # Safety and consistency checks
       if not len(_UpperCAmelCase   ):
             raise ValueError(F'''{self.__class__.__name__} has no fields.'''   )

       snake_case_			= getattr(self						, class_fields[0].name   )
       snake_case_			= all(getattr(self						, field.name   ) is None for field in class_fields[1:]   )

       if other_fields_are_none and isinstance(_UpperCAmelCase						, _UpperCAmelCase   ):
             for key, value in first_field.items():
                   snake_case_			= value
       else:
             for field in class_fields:
                   snake_case_			= getattr(self						, field.name   )
                   if v is not None:
                         snake_case_			= v



 def __delitem__(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``setdefault`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``pop`` on a {self.__class__.__name__} instance.'''   )



 def 		UpperCamelCase__	(      self						, *_UpperCAmelCase						, **_UpperCAmelCase   ):
       raise Exception(F'''You cannot use ``update`` on a {self.__class__.__name__} instance.'''   )



 def __getitem__(      self						, _UpperCAmelCase   ):
       if isinstance(_UpperCAmelCase						, _UpperCAmelCase   ):
             snake_case_			= dict(self.items()   )
             return inner_dict[k]
       else:
             return self.to_tuple()[k]



 def __setattr__(      self						, _UpperCAmelCase						, _UpperCAmelCase   ):
       if name in self.keys() and value is not None:
             # Don't call self.__setitem__ to avoid recursion errors
             super().__setitem__(_UpperCAmelCase						, _UpperCAmelCase   )
       super().__setattr__(_UpperCAmelCase						, _UpperCAmelCase   )



 def __setitem__(      self						, _UpperCAmelCase						, _UpperCAmelCase   ):
       # Will raise a KeyException if needed
       super().__setitem__(_UpperCAmelCase						, _UpperCAmelCase   )
       # Don't call self.__setattr__ to avoid recursion errors
       super().__setattr__(_UpperCAmelCase						, _UpperCAmelCase   )





 def 		UpperCamelCase__	(      self   ):
       return tuple(self[k] for k in self.keys()   )