






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







    """simple docstring"""







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





           '''simple docstring'''

           __magic_name__										=						parent
           __magic_name__										=						is_training
           __magic_name__										=						batch_size
           __magic_name__										=						image_size
           __magic_name__										=						patch_size
           __magic_name__										=						num_channels
           __magic_name__										=						max_token_length
           __magic_name__										=						num_character_labels
           __magic_name__										=						num_bpe_labels
           __magic_name__										=						num_wordpiece_labels
           __magic_name__										=						hidden_size
           __magic_name__										=						num_hidden_layers
           __magic_name__										=						num_attention_heads
           __magic_name__										=						mlp_ratio
           __magic_name__										=						patch_embeds_hidden_size
           __magic_name__										=						output_hidden_states







    def 							a__ (		self   :  Any   ):





           '''simple docstring'''

           __magic_name__										=						floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]   )
           __magic_name__										=						self.get_config()
           return config, pixel_values







    def 							a__ (		self   :  Any   ):





           '''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   :  Dict							,						UpperCamelCase_   :  int							,						UpperCamelCase_   :  List[Any]   ):





           '''simple docstring'''

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







    def 							a__ (		self   :  List[str]   ):





           '''simple docstring'''

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



@require_torch
class 					UpperCamelCase__   (							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   :  Optional[int]   ):





           '''simple docstring'''

           __magic_name__										=						MgpstrModelTester(self   )
           __magic_name__										=						ConfigTester(self							,						config_class=UpperCamelCase_							,						has_text_modality=UpperCamelCase_   )







    def 							a__ (		self   :  List[str]   ):





           '''simple docstring'''

           self.config_tester.run_common_tests()







    def 							a__ (		self   :  int   ):





           '''simple docstring'''

           __magic_name__										=						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 							a__ (		self   :  Union[str, Any]   ):





           '''simple docstring'''

           pass







    def 							a__ (		self   :  Tuple   ):





           '''simple docstring'''

           __magic_name__							,     __magic_name__										=						self.model_tester.prepare_config_and_inputs_for_common()

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







    def 							a__ (		self   :  int   ):





           '''simple docstring'''

           __magic_name__							,     __magic_name__										=						self.model_tester.prepare_config_and_inputs_for_common()

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

                  __magic_name__										=						['pixel_values']
                  self.assertListEqual(arg_names[:1]							,						UpperCamelCase_   )







    @unittest.skip(reason='MgpstrModel does not support feedforward chunking'   )
    def 							a__ (		self   :  List[str]   ):





           '''simple docstring'''

           pass







    def 							a__ (		self   :  Optional[int]   ):





           '''simple docstring'''

           __magic_name__							,     __magic_name__										=						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

                  __magic_name__										=						True
                  __magic_name__										=						model_class(UpperCamelCase_   )
                  self.assertTrue(model.is_gradient_checkpointing   )







    def 							a__ (		self   :  List[Any]   ):





           '''simple docstring'''

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

                  with torch.no_grad():
                         __magic_name__										=						model(**self._prepare_for_class(UpperCamelCase_							,						UpperCamelCase_   )   )

                  __magic_name__										=						outputs.hidden_states

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

           __magic_name__							,     __magic_name__										=						self.model_tester.prepare_config_and_inputs_for_common()

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

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

                  check_hidden_states_output(UpperCamelCase_							,						UpperCamelCase_							,						UpperCamelCase_   )







    def 							a__ (		self   :  Tuple   ):





           '''simple docstring'''

           __magic_name__							,     __magic_name__										=						self.model_tester.prepare_config_and_inputs_for_common()

           __magic_name__										=						_config_zero_init(UpperCamelCase_   )
           for model_class in self.all_model_classes:
                  __magic_name__										=						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 							a__ (		self   :  Dict   ):





           '''simple docstring'''

           pass


def        A	(							)						->		Tuple:

       """simple docstring"""





       __magic_name__										=						'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
       __magic_name__										=						Image.open(requests.get(__snake_case   ,    stream=__snake_case     ).raw     ).convert('RGB'     )
       return im






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







    """simple docstring"""







    @slow
    def 							a__ (		self   :  Dict   ):





           '''simple docstring'''

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

           __magic_name__										=						prepare_img()
           __magic_name__										=						processor(images=UpperCamelCase_							,						return_tensors='pt'   ).pixel_values.to(UpperCamelCase_   )

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

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

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

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

           __magic_name__										=						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   )   )







"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


snake_case   :   Optional[int]    		=		{
    """configuration_splinter""": ["""SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP""", """SplinterConfig"""],
    """tokenization_splinter""": ["""SplinterTokenizer"""],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 snake_case   :   Dict    		=		["""SplinterTokenizerFast"""]

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 snake_case   :   Dict    		=		[
     """SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST""",
     """SplinterForQuestionAnswering""",
     """SplinterForPreTraining""",
     """SplinterLayer""",
     """SplinterModel""",
     """SplinterPreTrainedModel""",
 ]


if TYPE_CHECKING:
 from .configuration_splinter import SPLINTER_PRETRAINED_CONFIG_ARCHIVE_MAP, SplinterConfig
 from .tokenization_splinter import SplinterTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_splinter_fast import SplinterTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_splinter import (
      SPLINTER_PRETRAINED_MODEL_ARCHIVE_LIST,
      SplinterForPreTraining,
      SplinterForQuestionAnswering,
      SplinterLayer,
      SplinterModel,
      SplinterPreTrainedModel,
  )


else:
 import sys

 snake_case   :   List[str]    		=		_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)