






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



  def __init__(    self:    Tuple				,   a:    Optional[int]				,   a:    Dict=False				,   a:    int=13				,   a:    List[str]=(32, 1_28)				,   a:    List[str]=4				,   a:    int=3				,   a:    Optional[int]=27				,   a:    List[str]=38				,   a:    int=99				,   a:    Tuple=99				,   a:    Optional[int]=32				,   a:    str=5				,   a:    Any=4				,   a:    Optional[int]=4.0				,   a:    List[str]=2_57				,   a:    Optional[Any]=None				,   )  ->str:






        '''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:    Union[str, Any])  ->int:






        '''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:    Any)  ->Dict:






        '''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:    Dict				,   a:    str				,   a:    Optional[int])  ->Optional[int]:






        '''simple docstring'''


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




  def _lowerCAmelCase     (    self:    Tuple)  ->Union[str, Any]:






        '''simple docstring'''


        a_				     =   self.prepare_config_and_inputs()
        a_     ,       a_				     =   config_and_inputs
        a_				     =   {"pixel_values": pixel_values}
        return config, inputs_dict





@require_torch
class 		SCREAMING_SNAKE_CASE__   (     lowercase_		,		lowercase_		,		unittest.TestCase    ):
  _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 _lowerCAmelCase     (    self:    int)  ->Any:






        '''simple docstring'''


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



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






        '''simple docstring'''


        self.config_tester.run_common_tests()



  def _lowerCAmelCase     (    self:    Dict)  ->Union[str, Any]:






        '''simple docstring'''


        a_				     =   self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*a)



  @unittest.skip(reason="MgpstrModel does not use inputs_embeds")
  def _lowerCAmelCase     (    self:    int)  ->str:






        '''simple docstring'''


        pass



  def _lowerCAmelCase     (    self:    Any)  ->Any:






        '''simple docstring'''


        a_     ,       a_				     =   self.model_tester.prepare_config_and_inputs_for_common()

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



  def _lowerCAmelCase     (    self:    Any)  ->str:






        '''simple docstring'''


        a_     ,       a_				     =   self.model_tester.prepare_config_and_inputs_for_common()

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



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






        '''simple docstring'''


        pass



  def _lowerCAmelCase     (    self:    int)  ->Dict:






        '''simple docstring'''


        a_     ,       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(a)
              self.assertTrue(model.is_gradient_checkpointing)



  def _lowerCAmelCase     (    self:    Optional[Any])  ->int:






        '''simple docstring'''


        def check_hidden_states_output(a:    Dict				,   a:    List[Any]				,   a:    List[Any]):
              a_				     =   model_class(a)
              model.to(a)
              model.eval()

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

              a_				     =   outputs.hidden_states

              a_				     =   getattr(
                  self.model_tester				,   "expected_num_hidden_layers"				,   self.model_tester.num_hidden_layers + 1)
              self.assertEqual(len(a)				,   a)

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

        a_     ,       a_				     =   self.model_tester.prepare_config_and_inputs_for_common()

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

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

              check_hidden_states_output(a				,   a				,   a)



  def _lowerCAmelCase     (    self:    int)  ->int:






        '''simple docstring'''


        a_     ,       a_				     =   self.model_tester.prepare_config_and_inputs_for_common()

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






        '''simple docstring'''


        pass





def 			__UpperCAmelCase				()		->				List[Any]:

      '''simple docstring'''


      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 		SCREAMING_SNAKE_CASE__   (     unittest.TestCase    ):



  @slow
  def _lowerCAmelCase     (    self:    Dict)  ->Optional[int]:






        '''simple docstring'''


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

        a_				     =   prepare_img()
        a_				     =   processor(images=a				,   return_tensors="pt").pixel_values.to(a)

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

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

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

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











'''simple docstring'''





from functools import partial
from typing import Any, Callable, Dict, List, Type, TypeVar, Union, overload

import torch
import torch.nn as nn
import torch.types



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						if not inplace:
												a_				     =   ma + ma
						else:
												ma += ma

						return ma



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   -1 * len(lowercase__				)
						a_				     =   list(range(len(tensor.shape[:zero_index]				)				)				)
						return tensor.permute(first_inds + [zero_index + i for i in inds]				)



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						return t.reshape(t.shape[:-no_dims] + (-1,)				)



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__	,lowercase__ = 1e-4				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   mask.expand(*value.shape				)
						return torch.sum(mask * value	,dim=lowercase__				) / (eps + torch.sum(lowercase__	,dim=lowercase__				))



def 			__UpperCAmelCase				(lowercase__	,lowercase__ = 2.3125	,lowercase__ = 21.6875	,lowercase__ = 64				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   torch.linspace(lowercase__	,lowercase__	,no_bins - 1	,device=pts.device				)
						a_				     =   torch.sqrt(torch.sum((pts.unsqueeze(-2				) - pts.unsqueeze(-3				)) ** 2	,dim=-1				)				)
						return torch.bucketize(lowercase__	,lowercase__				)



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				dict:

						'''simple docstring'''


						a_				     =   dicts[0]
						a_				     =   {}
						for k, v in first.items():
												a_				     =   [d[k] for d in dicts]
												if isinstance(lowercase__	,lowercase__				):
																		a_				     =   dict_multimap(lowercase__	,lowercase__				)
												else:
																		a_				     =   fn(lowercase__				)

						return new_dict



def 			__UpperCAmelCase				(lowercase__	,lowercase__				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   v_bins.view(((1,) * len(x.shape				)) + (len(lowercase__				),)				)
						a_				     =   x[..., None] - reshaped_bins
						a_				     =   torch.argmin(torch.abs(lowercase__				)	,dim=-1				)
						return nn.functional.one_hot(lowercase__	,num_classes=len(lowercase__				)				).float()



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__ = 0	,lowercase__ = 0				)		->				torch.Tensor:

						'''simple docstring'''


						a_				     =   []
						for i, s in enumerate(data.shape[:no_batch_dims]				):
												a_				     =   torch.arange(lowercase__				)
												a_				     =   r.view(*(*((1,) * i), -1, *((1,) * (len(inds.shape				) - i - 1)))				)
												ranges.append(lowercase__				)

						a_				     =   [slice(lowercase__				) for _ in range(len(data.shape				) - no_batch_dims				)]
						a_				     =   inds
						ranges.extend(lowercase__				)
						# Matt note: Editing this to get around the behaviour of using a list as an array index changing
						# in recent Numpy versions
						return data[tuple(lowercase__				)]


a_      = TypeVar('T')



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				Dict[Any, Union[dict, list, tuple, Any]]:

						'''simple docstring'''


						a_				     =   {}
						for k, v in dic.items():
												if isinstance(lowercase__	,lowercase__				):
																		a_				     =   dict_map(lowercase__	,lowercase__	,lowercase__				)
												else:
																		a_				     =   tree_map(lowercase__	,lowercase__	,lowercase__				)

						return new_dict



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				Any:

						'''simple docstring'''


						...



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				dict:

						'''simple docstring'''


						...



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				list:

						'''simple docstring'''


						...



@overload
def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				tuple:

						'''simple docstring'''


						...



def 			__UpperCAmelCase				(lowercase__	,lowercase__	,lowercase__				)		->				List[Any]:

						'''simple docstring'''


						if isinstance(lowercase__	,lowercase__				):
												return dict_map(lowercase__	,lowercase__	,lowercase__				)
						elif isinstance(lowercase__	,lowercase__				):
												return [tree_map(lowercase__	,lowercase__	,lowercase__				) for x in tree]
						elif isinstance(lowercase__	,lowercase__				):
												return tuple(tree_map(lowercase__	,lowercase__	,lowercase__				) for x in tree				)
						elif isinstance(lowercase__	,lowercase__				):
												return fn(lowercase__				)
						else:
												print(type(lowercase__				)				)
												raise ValueError("Not supported"				)
a_      = partial(tree_map, leaf_type=torch.Tensor)



