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




  def __init__(     self				:Optional[Any] ,						_SCREAMING_SNAKE_CASE				:List[str] ,						_SCREAMING_SNAKE_CASE				:List[str]=False ,						_SCREAMING_SNAKE_CASE				:Any=1_3 ,						_SCREAMING_SNAKE_CASE				:Optional[Any]=(3_2, 1_2_8) ,						_SCREAMING_SNAKE_CASE				:int=4 ,						_SCREAMING_SNAKE_CASE				:Union[str, Any]=3 ,						_SCREAMING_SNAKE_CASE				:Dict=2_7 ,						_SCREAMING_SNAKE_CASE				:Any=3_8 ,						_SCREAMING_SNAKE_CASE				:int=9_9 ,						_SCREAMING_SNAKE_CASE				:Optional[Any]=9_9 ,						_SCREAMING_SNAKE_CASE				:Dict=3_2 ,						_SCREAMING_SNAKE_CASE				:List[str]=5 ,						_SCREAMING_SNAKE_CASE				:int=4 ,						_SCREAMING_SNAKE_CASE				:Tuple=4.0 ,						_SCREAMING_SNAKE_CASE				:str=2_5_7 ,						_SCREAMING_SNAKE_CASE				:Optional[Any]=None ,						)				-> int:






        '''simple docstring'''






        UpperCamelCase_    :  Optional[Any]				    =    parent
        UpperCamelCase_    :  Dict				    =    is_training
        UpperCamelCase_    :  Union[str, Any]				    =    batch_size
        UpperCamelCase_    :  str				    =    image_size
        UpperCamelCase_    :  Any				    =    patch_size
        UpperCamelCase_    :  Optional[int]				    =    num_channels
        UpperCamelCase_    :  Any				    =    max_token_length
        UpperCamelCase_    :  Union[str, Any]				    =    num_character_labels
        UpperCamelCase_    :  Optional[Any]				    =    num_bpe_labels
        UpperCamelCase_    :  Optional[Any]				    =    num_wordpiece_labels
        UpperCamelCase_    :  str				    =    hidden_size
        UpperCamelCase_    :  Union[str, Any]				    =    num_hidden_layers
        UpperCamelCase_    :  str				    =    num_attention_heads
        UpperCamelCase_    :  Optional[int]				    =    mlp_ratio
        UpperCamelCase_    :  Any				    =    patch_embeds_hidden_size
        UpperCamelCase_    :  Optional[Any]				    =    output_hidden_states




  def   _snake_case  (     self				:List[Any])				-> int:






        '''simple docstring'''






        UpperCamelCase_    :  Optional[Any]				    =    floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]])
        UpperCamelCase_    :  int				    =    self.get_config()
        return config, pixel_values




  def   _snake_case  (     self				:Any)				-> 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   _snake_case  (     self				:Optional[Any] ,						_SCREAMING_SNAKE_CASE				:List[str] ,						_SCREAMING_SNAKE_CASE				:List[Any])				-> Dict:






        '''simple docstring'''






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





  def   _snake_case  (     self				:Optional[Any])				-> Any:






        '''simple docstring'''






        UpperCamelCase_    :  Dict				    =    self.prepare_config_and_inputs()
        UpperCamelCase_    :  Dict				    =    config_and_inputs
        UpperCamelCase_    :  List[Any]				    =    {"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_torch
class 						__snake_case (						_a				, _a				, unittest.TestCase  ):
  a_        =				(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
  a_        =				{"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
  a_        =				False

  a_        =				False
  a_        =				False
  a_        =				False
  a_        =				False




  def   _snake_case  (     self				:Union[str, Any])				-> Optional[int]:






        '''simple docstring'''






        UpperCamelCase_    :  Dict				    =    MgpstrModelTester(self)
        UpperCamelCase_    :  Union[str, Any]				    =    ConfigTester(self ,						config_class=_SCREAMING_SNAKE_CASE ,						has_text_modality=_SCREAMING_SNAKE_CASE)




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






        '''simple docstring'''






        self.config_tester.run_common_tests()




  def   _snake_case  (     self				:List[str])				-> List[str]:






        '''simple docstring'''






        UpperCamelCase_    :  int				    =    self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE)




  @unittest.skip(reason="""MgpstrModel does not use inputs_embeds""")
  def   _snake_case  (     self				:str)				-> Union[str, Any]:






        '''simple docstring'''






        pass




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






        '''simple docstring'''






        UpperCamelCase_    :  int				    =    self.model_tester.prepare_config_and_inputs_for_common()

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




  def   _snake_case  (     self				:Dict)				-> Tuple:






        '''simple docstring'''






        UpperCamelCase_    :  List[Any]				    =    self.model_tester.prepare_config_and_inputs_for_common()

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

              UpperCamelCase_    :  List[Any]				    =    ["""pixel_values"""]
              self.assertListEqual(arg_names[:1] ,						_SCREAMING_SNAKE_CASE)




  @unittest.skip(reason="""MgpstrModel does not support feedforward chunking""")
  def   _snake_case  (     self				:Dict)				-> Optional[int]:






        '''simple docstring'''






        pass




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






        '''simple docstring'''






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

              UpperCamelCase_    :  List[str]				    =    True
              UpperCamelCase_    :  List[Any]				    =    model_class(_SCREAMING_SNAKE_CASE)
              self.assertTrue(model.is_gradient_checkpointing)




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






        '''simple docstring'''






        def check_hidden_states_output(_SCREAMING_SNAKE_CASE				:Union[str, Any] ,						_SCREAMING_SNAKE_CASE				:str ,						_SCREAMING_SNAKE_CASE				:Optional[int]):
              UpperCamelCase_    :  Optional[Any]				    =    model_class(_SCREAMING_SNAKE_CASE)
              model.to(_SCREAMING_SNAKE_CASE)
              model.eval()

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

              UpperCamelCase_    :  Tuple				    =    outputs.hidden_states

              UpperCamelCase_    :  Any				    =    getattr(
                  self.model_tester ,						"""expected_num_hidden_layers""" ,						self.model_tester.num_hidden_layers + 1)
              self.assertEqual(len(_SCREAMING_SNAKE_CASE) ,						_SCREAMING_SNAKE_CASE)

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

        UpperCamelCase_    :  Optional[int]				    =    self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              UpperCamelCase_    :  Dict				    =    True
              check_hidden_states_output(_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              UpperCamelCase_    :  List[Any]				    =    True

              check_hidden_states_output(_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE ,						_SCREAMING_SNAKE_CASE)




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






        '''simple docstring'''






        UpperCamelCase_    :  Tuple				    =    self.model_tester.prepare_config_and_inputs_for_common()

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






        '''simple docstring'''






        pass







def 				__magic_name__(					):
      UpperCamelCase_    :  Tuple				    =    """https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
      UpperCamelCase_    :  List[str]				    =    Image.open(requests.get(UpperCAmelCase__       ,							stream=UpperCAmelCase__  ).raw  ).convert("""RGB"""  )
      return im







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




  @slow
  def   _snake_case  (     self				:Any)				-> Any:






        '''simple docstring'''






        UpperCamelCase_    :  int				    =    """alibaba-damo/mgp-str-base"""
        UpperCamelCase_    :  Dict				    =    MgpstrForSceneTextRecognition.from_pretrained(_SCREAMING_SNAKE_CASE).to(_SCREAMING_SNAKE_CASE)
        UpperCamelCase_    :  Union[str, Any]				    =    MgpstrProcessor.from_pretrained(_SCREAMING_SNAKE_CASE)

        UpperCamelCase_    :  List[str]				    =    prepare_img()
        UpperCamelCase_    :  int				    =    processor(images=_SCREAMING_SNAKE_CASE ,						return_tensors="""pt""").pixel_values.to(_SCREAMING_SNAKE_CASE)

        # forward pass
        with torch.no_grad():
              UpperCamelCase_    :  int				    =    model(_SCREAMING_SNAKE_CASE)

        # verify the logits
        self.assertEqual(outputs.logits[0].shape ,						torch.Size((1, 2_7, 3_8)))

        UpperCamelCase_    :  Optional[Any]				    =    processor.batch_decode(outputs.logits)
        UpperCamelCase_    :  Tuple				    =    """ticket"""

        self.assertEqual(out_strs["""generated_text"""][0] ,						_SCREAMING_SNAKE_CASE)

        UpperCamelCase_    :  List[str]				    =    torch.tensor(
            [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]] ,						device=_SCREAMING_SNAKE_CASE ,						)

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






'''simple docstring'''


import argparse
import os
import re


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_dummies.py
__SCREAMING_SNAKE_CASE  =			"src/transformers"

# Matches is_xxx_available()
__SCREAMING_SNAKE_CASE  =			re.compile(r"is\_([a-z_]*)_available()")
# Matches from xxx import bla
__SCREAMING_SNAKE_CASE  =			re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n")
__SCREAMING_SNAKE_CASE  =			re.compile(r"^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)")


__SCREAMING_SNAKE_CASE  =			"\n{0} = None\n"

__SCREAMING_SNAKE_CASE  =			"\nclass {0}(metaclass=DummyObject):\n    _backends = {1}\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, {1})\n"


__SCREAMING_SNAKE_CASE  =			"\ndef {0}(*args, **kwargs):\n    requires_backends({0}, {1})\n"
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]  ):
						if _re_test_backend.search(UpperCAmelCase__  ) is None:
												return None
						UpperCamelCase_    :  str				    =    [b[0] for b in _re_backend.findall(UpperCAmelCase__  )]
						backends.sort()
						return "_and_".join(UpperCAmelCase__  )
def 				__magic_name__(					):
						with open(os.path.join(UpperCAmelCase__       ,							"""__init__.py"""  )       ,							"""r"""       ,							encoding="""utf-8"""       ,							newline="""\n"""  ) as f:
												UpperCamelCase_    :  Dict				    =    f.readlines()

						# Get to the point we do the actual imports for type checking
						UpperCamelCase_    :  Tuple				    =    0
						while not lines[line_index].startswith("""if TYPE_CHECKING"""  ):
												line_index += 1

						UpperCamelCase_    :  Optional[int]				    =    {}
						# Go through the end of the file
						while line_index < len(UpperCAmelCase__  ):
												# If the line is an if is_backend_available, we grab all objects associated.
												UpperCamelCase_    :  str				    =    find_backend(lines[line_index]  )
												if backend is not None:
																		while not lines[line_index].startswith("""    else:"""  ):
																								line_index += 1
																		line_index += 1

																		UpperCamelCase_    :  Dict				    =    []
																		# Until we unindent, add backend objects to the list
																		while len(lines[line_index]  ) <= 1 or lines[line_index].startswith(""" """ * 8  ):
																								UpperCamelCase_    :  Any				    =    lines[line_index]
																								UpperCamelCase_    :  str				    =    _re_single_line_import.search(UpperCAmelCase__  )
																								if single_line_import_search is not None:
																														objects.extend(single_line_import_search.groups()[0].split(""", """  )  )
																								elif line.startswith(""" """ * 12  ):
																														objects.append(line[12:-2]  )
																								line_index += 1

																		UpperCamelCase_    :  List[Any]				    =    objects
												else:
																		line_index += 1

						return backend_specific_objects
def 				__magic_name__(					UpperCAmelCase__   :					Any       ,							UpperCAmelCase__   :					Optional[Any]  ):
						if name.isupper():
												return DUMMY_CONSTANT.format(UpperCAmelCase__  )
						elif name.islower():
												return DUMMY_FUNCTION.format(UpperCAmelCase__       ,							UpperCAmelCase__  )
						else:
												return DUMMY_CLASS.format(UpperCAmelCase__       ,							UpperCAmelCase__  )
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]=None  ):
						if backend_specific_objects is None:
												UpperCamelCase_    :  Optional[Any]				    =    read_init()
						# For special correspondence backend to module name as used in the function requires_modulename
						UpperCamelCase_    :  List[str]				    =    {}

						for backend, objects in backend_specific_objects.items():
												UpperCamelCase_    :  Optional[Any]				    =    """[""" + """, """.join(f"""\"{b}\"""" for b in backend.split("""_and_"""  )  ) + """]"""
												UpperCamelCase_    :  Union[str, Any]				    =    """# This file is autogenerated by the command `make fix-copies`, do not edit.\n"""
												dummy_file += "from ..utils import DummyObject, requires_backends\n\n"
												dummy_file += "\n".join([create_dummy_object(UpperCAmelCase__       ,							UpperCAmelCase__  ) for o in objects]  )
												UpperCamelCase_    :  List[Any]				    =    dummy_file

						return dummy_files
def 				__magic_name__(					UpperCAmelCase__   :					List[Any]=False  ):
						UpperCamelCase_    :  int				    =    create_dummy_files()
						# For special correspondence backend to shortcut as used in utils/dummy_xxx_objects.py
						UpperCamelCase_    :  Union[str, Any]				    =    {"""torch""": """pt"""}

						# Locate actual dummy modules and read their content.
						UpperCamelCase_    :  Optional[int]				    =    os.path.join(UpperCAmelCase__       ,							"""utils"""  )
						UpperCamelCase_    :  str				    =    {
						    backend: os.path.join(UpperCAmelCase__       ,							f"""dummy_{short_names.get(UpperCAmelCase__       ,							UpperCAmelCase__  )}_objects.py"""  )
						    for backend in dummy_files.keys()
						}

						UpperCamelCase_    :  int				    =    {}
						for backend, file_path in dummy_file_paths.items():
												if os.path.isfile(UpperCAmelCase__  ):
																		with open(UpperCAmelCase__       ,							"""r"""       ,							encoding="""utf-8"""       ,							newline="""\n"""  ) as f:
																								UpperCamelCase_    :  str				    =    f.read()
												else:
																		UpperCamelCase_    :  str				    =    """"""

						for backend in dummy_files.keys():
												if dummy_files[backend] != actual_dummies[backend]:
																		if overwrite:
																								print(
																								    f"""Updating transformers.utils.dummy_{short_names.get(UpperCAmelCase__       ,							UpperCAmelCase__  )}_objects.py as the main """
																								    """__init__ has new objects."""  )
																								with open(dummy_file_paths[backend]       ,							"""w"""       ,							encoding="""utf-8"""       ,							newline="""\n"""  ) as f:
																														f.write(dummy_files[backend]  )
																		else:
																								raise ValueError(
																								    """The main __init__ has objects that are not present in """
																								    f"""transformers.utils.dummy_{short_names.get(UpperCAmelCase__       ,							UpperCAmelCase__  )}_objects.py. Run `make fix-copies` """
																								    """to fix this."""  )


if __name__ == "__main__":
	__SCREAMING_SNAKE_CASE  =			argparse.ArgumentParser()
	parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.")
	__SCREAMING_SNAKE_CASE  =			parser.parse_args()

	check_dummies(args.fix_and_overwrite)




