


'''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  __lowerCamelCase :
    """simple docstring"""


    def __init__(  self			:							str      ,							SCREAMING_SNAKE_CASE			:							Any      ,							SCREAMING_SNAKE_CASE			:							List[Any]=False      ,							SCREAMING_SNAKE_CASE			:							Dict=13      ,							SCREAMING_SNAKE_CASE			:							Any=(32, 128)      ,							SCREAMING_SNAKE_CASE			:							int=4      ,							SCREAMING_SNAKE_CASE			:							List[str]=3      ,							SCREAMING_SNAKE_CASE			:							int=27      ,							SCREAMING_SNAKE_CASE			:							str=38      ,							SCREAMING_SNAKE_CASE			:							Optional[int]=99      ,							SCREAMING_SNAKE_CASE			:							Tuple=99      ,							SCREAMING_SNAKE_CASE			:							Union[str, Any]=32      ,							SCREAMING_SNAKE_CASE			:							Any=5      ,							SCREAMING_SNAKE_CASE			:							Union[str, Any]=4      ,							SCREAMING_SNAKE_CASE			:							Union[str, Any]=4.0      ,							SCREAMING_SNAKE_CASE			:							Union[str, Any]=257      ,							SCREAMING_SNAKE_CASE			:							Dict=None      ,							):
           _A     :	Union[str, Any]      =					parent
           _A     :	Dict      =					is_training
           _A     :	Tuple      =					batch_size
           _A     :	List[Any]      =					image_size
           _A     :	int      =					patch_size
           _A     :	Optional[int]      =					num_channels
           _A     :	List[Any]      =					max_token_length
           _A     :	Union[str, Any]      =					num_character_labels
           _A     :	Optional[Any]      =					num_bpe_labels
           _A     :	List[Any]      =					num_wordpiece_labels
           _A     :	Tuple      =					hidden_size
           _A     :	List[Any]      =					num_hidden_layers
           _A     :	Optional[int]      =					num_attention_heads
           _A     :	List[str]      =					mlp_ratio
           _A     :	Union[str, Any]      =					patch_embeds_hidden_size
           _A     :	Union[str, Any]      =					output_hidden_states


    def    A    (  self			:							Any):
           _A     :	str      =					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    A    (  self			:							Any):
           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			:							str      ,							SCREAMING_SNAKE_CASE			:							int      ,							SCREAMING_SNAKE_CASE			:							Optional[int]):
           _A     :	Any      =					MgpstrForSceneTextRecognition(SCREAMING_SNAKE_CASE)
           model.to(SCREAMING_SNAKE_CASE)
           model.eval()
           with torch.no_grad():
                  _A     :	List[str]      =					model(SCREAMING_SNAKE_CASE)
           self.parent.assertEqual(
               generated_ids[0][0].shape      ,							(self.batch_size, self.max_token_length, self.num_character_labels))


    def    A    (  self			:							List[str]):
           _A     :	str      =					self.prepare_config_and_inputs()
           _A  , _A     :	str      =					config_and_inputs
           _A     :	Union[str, Any]      =					{'pixel_values': pixel_values}
           return config, inputs_dict




@require_torch
class  __lowerCamelCase (       a_				,					a_				,					unittest.TestCase       ):
    """simple docstring"""
    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    A    (  self			:							int):
           _A     :	str      =					MgpstrModelTester(self)
           _A     :	List[Any]      =					ConfigTester(self      ,							config_class=SCREAMING_SNAKE_CASE      ,							has_text_modality=SCREAMING_SNAKE_CASE)


    def    A    (  self			:							List[str]):
           self.config_tester.run_common_tests()


    def    A    (  self			:							Any):
           _A     :	Optional[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    A    (  self			:							int):
           pass


    def    A    (  self			:							Dict):
           _A  , _A     :	int      =					self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                  _A     :	Optional[Any]      =					model_class(SCREAMING_SNAKE_CASE)
                  self.assertIsInstance(model.get_input_embeddings()      ,							(nn.Module))
                  _A     :	Union[str, Any]      =					model.get_output_embeddings()
                  self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE      ,							nn.Linear))


    def    A    (  self			:							Optional[Any]):
           _A  , _A     :	Optional[Any]      =					self.model_tester.prepare_config_and_inputs_for_common()

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

                  _A     :	Union[str, Any]      =					['pixel_values']
                  self.assertListEqual(arg_names[:1]      ,							SCREAMING_SNAKE_CASE)


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


    def    A    (  self			:							Any):
           _A  , _A     :	Optional[int]      =					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     :	Optional[Any]      =					True
                  _A     :	Optional[int]      =					model_class(SCREAMING_SNAKE_CASE)
                  self.assertTrue(model.is_gradient_checkpointing)


    def    A    (  self			:							int):
           def check_hidden_states_output(SCREAMING_SNAKE_CASE			:							Tuple      ,							SCREAMING_SNAKE_CASE			:							Optional[int]      ,							SCREAMING_SNAKE_CASE			:							Any):
                  _A     :	Union[str, Any]      =					model_class(SCREAMING_SNAKE_CASE)
                  model.to(SCREAMING_SNAKE_CASE)
                  model.eval()

                  with torch.no_grad():
                         _A     :	List[Any]      =					model(**self._prepare_for_class(SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE))

                  _A     :	int      =					outputs.hidden_states

                  _A     :	Union[str, 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]      ,							)

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

           for model_class in self.all_model_classes:
                  _A     :	Tuple      =					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"]
                  _A     :	Optional[Any]      =					True

                  check_hidden_states_output(SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE)


    def    A    (  self			:							Optional[int]):
           _A  , _A     :	Any      =					self.model_tester.prepare_config_and_inputs_for_common()

           _A     :	Any      =					_config_zero_init(SCREAMING_SNAKE_CASE)
           for model_class in self.all_model_classes:
                  _A     :	int      =					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    A    (  self			:							Union[str, Any]):
           pass






def       lowerCAmelCase__       (				):
       _A     :	Optional[int]      =					'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
       _A     :	Any      =					Image.open(requests.get(lowerCamelCase  ,stream=lowerCamelCase   ).raw   ).convert('RGB'   )
       return im


@require_vision
@require_torch
class  __lowerCamelCase (       unittest.TestCase       ):
    """simple docstring"""


    @slow
    def    A    (  self			:							List[str]):
           _A     :	Tuple      =					'alibaba-damo/mgp-str-base'
           _A     :	Union[str, Any]      =					MgpstrForSceneTextRecognition.from_pretrained(SCREAMING_SNAKE_CASE).to(SCREAMING_SNAKE_CASE)
           _A     :	str      =					MgpstrProcessor.from_pretrained(SCREAMING_SNAKE_CASE)

           _A     :	Dict      =					prepare_img()
           _A     :	Tuple      =					processor(images=SCREAMING_SNAKE_CASE      ,							return_tensors='pt').pixel_values.to(SCREAMING_SNAKE_CASE)

           # forward pass
           with torch.no_grad():
                  _A     :	int      =					model(SCREAMING_SNAKE_CASE)

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

           _A     :	int      =					processor.batch_decode(outputs.logits)
           _A     :	int      =					'ticket'

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

           _A     :	Optional[Any]      =					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 unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import CLIPImageProcessor


class  __lowerCamelCase (       unittest.TestCase       ):
    """simple docstring"""


    def __init__(  self			:							Union[str, Any]      ,							SCREAMING_SNAKE_CASE			:							Any      ,							SCREAMING_SNAKE_CASE			:							List[str]=7      ,							SCREAMING_SNAKE_CASE			:							List[Any]=3      ,							SCREAMING_SNAKE_CASE			:							Dict=18      ,							SCREAMING_SNAKE_CASE			:							List[str]=30      ,							SCREAMING_SNAKE_CASE			:							List[Any]=400      ,							SCREAMING_SNAKE_CASE			:							int=True      ,							SCREAMING_SNAKE_CASE			:							Any=None      ,							SCREAMING_SNAKE_CASE			:							str=True      ,							SCREAMING_SNAKE_CASE			:							List[Any]=None      ,							SCREAMING_SNAKE_CASE			:							List[str]=True      ,							SCREAMING_SNAKE_CASE			:							Optional[int]=[0.4814_5466, 0.457_8275, 0.4082_1073]      ,							SCREAMING_SNAKE_CASE			:							Optional[Any]=[0.2686_2954, 0.2613_0258, 0.2757_7711]      ,							SCREAMING_SNAKE_CASE			:							Union[str, Any]=True      ,							):
           _A     :	List[Any]      =					size if size is not None else {'shortest_edge': 20}
           _A     :	List[Any]      =					crop_size if crop_size is not None else {'height': 18, 'width': 18}
           _A     :	Union[str, Any]      =					parent
           _A     :	Dict      =					batch_size
           _A     :	str      =					num_channels
           _A     :	int      =					image_size
           _A     :	Dict      =					min_resolution
           _A     :	Optional[Any]      =					max_resolution
           _A     :	int      =					do_resize
           _A     :	List[Any]      =					size
           _A     :	Any      =					do_center_crop
           _A     :	List[str]      =					crop_size
           _A     :	List[str]      =					do_normalize
           _A     :	Optional[int]      =					image_mean
           _A     :	Dict      =					image_std
           _A     :	Any      =					do_convert_rgb


    def    A    (  self			:							Tuple):
           return {
               "do_resize": self.do_resize,
               "size": self.size,
               "do_center_crop": self.do_center_crop,
               "crop_size": self.crop_size,
               "do_normalize": self.do_normalize,
               "image_mean": self.image_mean,
               "image_std": self.image_std,
               "do_convert_rgb": self.do_convert_rgb,
           }


    def    A    (  self			:							Any      ,							SCREAMING_SNAKE_CASE			:							str=False      ,							SCREAMING_SNAKE_CASE			:							str=False      ,							SCREAMING_SNAKE_CASE			:							List[Any]=False):
           assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

           if equal_resolution:
                  _A     :	Union[str, Any]      =					[]
                  for i in range(self.batch_size):
                         image_inputs.append(
                             np.random.randint(
                                 255      ,							size=(self.num_channels, self.max_resolution, self.max_resolution)      ,							dtype=np.uinta))
           else:
                  _A     :	Union[str, Any]      =					[]
                  for i in range(self.batch_size):
                         _A  , _A     :	Optional[Any]      =					np.random.choice(np.arange(self.min_resolution      ,							self.max_resolution)      ,							2)
                         image_inputs.append(np.random.randint(255      ,							size=(self.num_channels, width, height)      ,							dtype=np.uinta))

           if not numpify and not torchify:
                  # PIL expects the channel dimension as last dimension
                  _A     :	List[str]      =					[Image.fromarray(np.moveaxis(SCREAMING_SNAKE_CASE      ,							0      ,							-1)) for x in image_inputs]

           if torchify:
                  _A     :	Optional[Any]      =					[torch.from_numpy(SCREAMING_SNAKE_CASE) for x in image_inputs]

           return image_inputs




@require_torch
@require_vision
class  __lowerCamelCase (       a_				,					unittest.TestCase       ):
    """simple docstring"""
    a													=    CLIPImageProcessor if is_vision_available() else None


    def    A    (  self			:							Dict):
           _A     :	Tuple      =					CLIPImageProcessingTester(self)


    @property
    def    A    (  self			:							Any):
           return self.image_processor_tester.prepare_image_processor_dict()


    def    A    (  self			:							List[str]):
           _A     :	Optional[int]      =					self.image_processing_class(**self.image_processor_dict)
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_resize'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'size'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_center_crop'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'center_crop'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_normalize'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'image_mean'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'image_std'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_convert_rgb'))


    def    A    (  self			:							Optional[int]):
           _A     :	Optional[Any]      =					self.image_processing_class.from_dict(self.image_processor_dict)
           self.assertEqual(image_processor.size      ,							{'shortest_edge': 20})
           self.assertEqual(image_processor.crop_size      ,							{'height': 18, 'width': 18})

           _A     :	Optional[int]      =					self.image_processing_class.from_dict(self.image_processor_dict      ,							size=42      ,							crop_size=84)
           self.assertEqual(image_processor.size      ,							{'shortest_edge': 42})
           self.assertEqual(image_processor.crop_size      ,							{'height': 84, 'width': 84})


    def    A    (  self			:							List[str]):
           pass


    def    A    (  self			:							Optional[int]):
           # Initialize image_processing
           _A     :	Any      =					self.image_processing_class(**self.image_processor_dict)
           # create random PIL images
           _A     :	List[Any]      =					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE)
           for image in image_inputs:
                  self.assertIsInstance(SCREAMING_SNAKE_CASE      ,							Image.Image)

           # Test not batched input
           _A     :	List[str]      =					image_processing(image_inputs[0]      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)

           # Test batched
           _A     :	List[str]      =					image_processing(SCREAMING_SNAKE_CASE      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)


    def    A    (  self			:							Dict):
           # Initialize image_processing
           _A     :	Optional[int]      =					self.image_processing_class(**self.image_processor_dict)
           # create random numpy tensors
           _A     :	Tuple      =					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE      ,							numpify=SCREAMING_SNAKE_CASE)
           for image in image_inputs:
                  self.assertIsInstance(SCREAMING_SNAKE_CASE      ,							np.ndarray)

           # Test not batched input
           _A     :	Dict      =					image_processing(image_inputs[0]      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)

           # Test batched
           _A     :	Tuple      =					image_processing(SCREAMING_SNAKE_CASE      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)


    def    A    (  self			:							str):
           # Initialize image_processing
           _A     :	Optional[Any]      =					self.image_processing_class(**self.image_processor_dict)
           # create random PyTorch tensors
           _A     :	Tuple      =					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE      ,							torchify=SCREAMING_SNAKE_CASE)
           for image in image_inputs:
                  self.assertIsInstance(SCREAMING_SNAKE_CASE      ,							torch.Tensor)

           # Test not batched input
           _A     :	Any      =					image_processing(image_inputs[0]      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   1,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)

           # Test batched
           _A     :	Union[str, Any]      =					image_processing(SCREAMING_SNAKE_CASE      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   self.image_processor_tester.batch_size,
                   self.image_processor_tester.num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)




@require_torch
@require_vision
class  __lowerCamelCase (       a_				,					unittest.TestCase       ):
    """simple docstring"""
    a													=    CLIPImageProcessor if is_vision_available() else None


    def    A    (  self			:							int):
           _A     :	Union[str, Any]      =					CLIPImageProcessingTester(self      ,							num_channels=4)
           _A     :	Dict      =					3


    @property
    def    A    (  self			:							Any):
           return self.image_processor_tester.prepare_image_processor_dict()


    def    A    (  self			:							str):
           _A     :	str      =					self.image_processing_class(**self.image_processor_dict)
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_resize'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'size'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_center_crop'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'center_crop'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_normalize'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'image_mean'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'image_std'))
           self.assertTrue(hasattr(SCREAMING_SNAKE_CASE      ,							'do_convert_rgb'))


    def    A    (  self			:							str):
           pass


    def    A    (  self			:							int):
           # Initialize image_processing
           _A     :	List[Any]      =					self.image_processing_class(**self.image_processor_dict)
           # create random PIL images
           _A     :	Union[str, Any]      =					self.image_processor_tester.prepare_inputs(equal_resolution=SCREAMING_SNAKE_CASE)
           for image in image_inputs:
                  self.assertIsInstance(SCREAMING_SNAKE_CASE      ,							Image.Image)

           # Test not batched input
           _A     :	int      =					image_processing(image_inputs[0]      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   1,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)

           # Test batched
           _A     :	str      =					image_processing(SCREAMING_SNAKE_CASE      ,							return_tensors='pt').pixel_values
           self.assertEqual(
               encoded_images.shape      ,							(
                   self.image_processor_tester.batch_size,
                   self.expected_encoded_image_num_channels,
                   self.image_processor_tester.crop_size['height'],
                   self.image_processor_tester.crop_size['width'],
               )      ,							)






