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







     """simple docstring"""






     def __init__(		self  ,      _lowerCamelCase  ,      _lowerCamelCase=False  ,      _lowerCamelCase=1_3  ,      _lowerCamelCase=(3_2, 1_2_8)  ,      _lowerCamelCase=4  ,      _lowerCamelCase=3  ,      _lowerCamelCase=2_7  ,      _lowerCamelCase=3_8  ,      _lowerCamelCase=9_9  ,      _lowerCamelCase=9_9  ,      _lowerCamelCase=3_2  ,      _lowerCamelCase=5  ,      _lowerCamelCase=4  ,      _lowerCamelCase=4.0  ,      _lowerCamelCase=2_5_7  ,      _lowerCamelCase=None  ,      ):
         __UpperCamelCase						:						Tuple		     =	parent
         __UpperCamelCase						:						int		     =	is_training
         __UpperCamelCase						:						Optional[int]		     =	batch_size
         __UpperCamelCase						:						Any		     =	image_size
         __UpperCamelCase						:						List[Any]		     =	patch_size
         __UpperCamelCase						:						Dict		     =	num_channels
         __UpperCamelCase						:						List[Any]		     =	max_token_length
         __UpperCamelCase						:						Union[str, Any]		     =	num_character_labels
         __UpperCamelCase						:						Optional[int]		     =	num_bpe_labels
         __UpperCamelCase						:						str		     =	num_wordpiece_labels
         __UpperCamelCase						:						Tuple		     =	hidden_size
         __UpperCamelCase						:						Optional[Any]		     =	num_hidden_layers
         __UpperCamelCase						:						str		     =	num_attention_heads
         __UpperCamelCase						:						List[str]		     =	mlp_ratio
         __UpperCamelCase						:						Optional[Any]		     =	patch_embeds_hidden_size
         __UpperCamelCase						:						str		     =	output_hidden_states







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						int		     =	floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]     )
         __UpperCamelCase						:						List[str]		     =	self.get_config()
         return config, pixel_values







     def lowerCAmelCase  (		self     ):
         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  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
         __UpperCamelCase						:						Any		     =	MgpstrForSceneTextRecognition(_lowerCamelCase     )
         model.to(_lowerCamelCase     )
         model.eval()
         with torch.no_grad():
             __UpperCamelCase						:						List[Any]		     =	model(_lowerCamelCase     )
         self.parent.assertEqual(
             generated_ids[0][0].shape  ,      (self.batch_size, self.max_token_length, self.num_character_labels)     )







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






@require_torch
class       __lowercase		(    _lowerCamelCase      ,				_lowerCamelCase      ,				unittest.TestCase    ):







     """simple docstring"""






     SCREAMING_SNAKE_CASE__		 =    (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
     SCREAMING_SNAKE_CASE__		 =    {'''feature-extraction''': MgpstrForSceneTextRecognition} if is_torch_available() else {}
     SCREAMING_SNAKE_CASE__		 =    False

     SCREAMING_SNAKE_CASE__		 =    False
     SCREAMING_SNAKE_CASE__		 =    False
     SCREAMING_SNAKE_CASE__		 =    False
     SCREAMING_SNAKE_CASE__		 =    False







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Union[str, Any]		     =	MgpstrModelTester(self     )
         __UpperCamelCase						:						int		     =	ConfigTester(self  ,      config_class=_lowerCamelCase  ,      has_text_modality=_lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         self.config_tester.run_common_tests()







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Dict		     =	self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCamelCase     )







     @unittest.skip(reason='MgpstrModel does not use inputs_embeds'     )
     def lowerCAmelCase  (		self     ):
         pass







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						Optional[int]		     =	self.model_tester.prepare_config_and_inputs_for_common()

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







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						str		     =	self.model_tester.prepare_config_and_inputs_for_common()

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

             __UpperCamelCase						:						Tuple		     =	['pixel_values']
             self.assertListEqual(arg_names[:1]  ,      _lowerCamelCase     )







     @unittest.skip(reason='MgpstrModel does not support feedforward chunking'     )
     def lowerCAmelCase  (		self     ):
         pass







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						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

             __UpperCamelCase						:						Any		     =	True
             __UpperCamelCase						:						str		     =	model_class(_lowerCamelCase     )
             self.assertTrue(model.is_gradient_checkpointing     )







     def lowerCAmelCase  (		self     ):
         def check_hidden_states_output(_lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     ):
             __UpperCamelCase						:						Optional[Any]		     =	model_class(_lowerCamelCase     )
             model.to(_lowerCamelCase     )
             model.eval()

             with torch.no_grad():
                 __UpperCamelCase						:						Dict		     =	model(**self._prepare_for_class(_lowerCamelCase  ,      _lowerCamelCase     )     )

             __UpperCamelCase						:						Dict		     =	outputs.hidden_states

             __UpperCamelCase						:						Dict		     =	getattr(
                 self.model_tester  ,      'expected_num_hidden_layers'  ,      self.model_tester.num_hidden_layers + 1     )
             self.assertEqual(len(_lowerCamelCase     )  ,      _lowerCamelCase     )

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

         __UpperCamelCase     ,       __UpperCamelCase						:						str		     =	self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             __UpperCamelCase						:						Tuple		     =	True
             check_hidden_states_output(_lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     )

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

             check_hidden_states_output(_lowerCamelCase  ,      _lowerCamelCase  ,      _lowerCamelCase     )







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase     ,       __UpperCamelCase						:						List[str]		     =	self.model_tester.prepare_config_and_inputs_for_common()

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







def 			_UpperCamelCase			(  ):




    """simple docstring"""



    __UpperCamelCase						:						List[str]		     =	'https://i.postimg.cc/ZKwLg2Gw/367-14.png'
    __UpperCamelCase						:						str		     =	Image.open(requests.get(_a					,  stream=_a      ).raw      ).convert('RGB'      )
    return im






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







     """simple docstring"""






     @slow
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[str]		     =	'alibaba-damo/mgp-str-base'
         __UpperCamelCase						:						Optional[Any]		     =	MgpstrForSceneTextRecognition.from_pretrained(_lowerCamelCase     ).to(_lowerCamelCase     )
         __UpperCamelCase						:						Optional[int]		     =	MgpstrProcessor.from_pretrained(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	prepare_img()
         __UpperCamelCase						:						Tuple		     =	processor(images=_lowerCamelCase  ,      return_tensors='pt'     ).pixel_values.to(_lowerCamelCase     )

         # forward pass
         with torch.no_grad():
             __UpperCamelCase						:						Optional[Any]		     =	model(_lowerCamelCase     )

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

         __UpperCamelCase						:						List[str]		     =	processor.batch_decode(outputs.logits     )
         __UpperCamelCase						:						List[str]		     =	'ticket'

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

         __UpperCamelCase						:						int		     =	torch.tensor(
             [[[-3_9.5_3_9_7, -4_4.4_0_2_4, -3_6.1_8_4_4], [-6_1.4_7_0_9, -6_3.8_6_3_9, -5_8.3_4_5_4], [-7_4.0_2_2_5, -6_8.5_4_9_4, -7_1.2_1_6_4]]]  ,      device=_lowerCamelCase  ,      )

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




'''simple docstring'''
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, LDMSuperResolutionPipeline, UNetaDModel, VQModel
from diffusers.utils import PIL_INTERPOLATION, floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch


enable_full_determinism()






class       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     @property
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Dict		     =	1
         __UpperCamelCase						:						Union[str, Any]		     =	3
         __UpperCamelCase						:						Tuple		     =	(3_2, 3_2)

         __UpperCamelCase						:						List[Any]		     =	floats_tensor((batch_size, num_channels) + sizes  ,      rng=random.Random(0     )     ).to(_lowerCamelCase     )
         return image







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	UNetaDModel(
             block_out_channels=(3_2, 6_4)  ,      layers_per_block=2  ,      sample_size=3_2  ,      in_channels=6  ,      out_channels=3  ,      down_block_types=('DownBlock2D', 'AttnDownBlock2D')  ,      up_block_types=('AttnUpBlock2D', 'UpBlock2D')  ,      )
         return model







     @property
     def lowerCAmelCase  (		self     ):
         torch.manual_seed(0     )
         __UpperCamelCase						:						List[str]		     =	VQModel(
             block_out_channels=[3_2, 6_4]  ,      in_channels=3  ,      out_channels=3  ,      down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']  ,      up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']  ,      latent_channels=3  ,      )
         return model







     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Tuple		     =	'cpu'
         __UpperCamelCase						:						Union[str, Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						List[str]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         __UpperCamelCase						:						Tuple		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						int		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.Generator(device=_lowerCamelCase     ).manual_seed(0     )
         __UpperCamelCase						:						Union[str, Any]		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						str		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 6_4, 6_4, 3)
         __UpperCamelCase						:						str		     =	np.array([0.8_6_7_8, 0.8_2_4_5, 0.6_3_8_1, 0.6_8_3_0, 0.4_3_8_5, 0.5_5_9_9, 0.4_6_4_1, 0.6_2_0_1, 0.5_1_5_0]     )

         assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2







     @unittest.skipIf(torch_device != 'cuda'  ,      'This test requires a GPU'     )
     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						Optional[Any]		     =	self.dummy_uncond_unet
         __UpperCamelCase						:						Optional[int]		     =	DDIMScheduler()
         __UpperCamelCase						:						Any		     =	self.dummy_vq_model

         # put models in fp16
         __UpperCamelCase						:						str		     =	unet.half()
         __UpperCamelCase						:						Optional[Any]		     =	vqvae.half()

         __UpperCamelCase						:						Optional[int]		     =	LDMSuperResolutionPipeline(unet=_lowerCamelCase  ,      vqvae=_lowerCamelCase  ,      scheduler=_lowerCamelCase     )
         ldm.to(_lowerCamelCase     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Dict		     =	self.dummy_image.to(_lowerCamelCase     )

         __UpperCamelCase						:						Optional[Any]		     =	ldm(_lowerCamelCase  ,      num_inference_steps=2  ,      output_type='numpy'     ).images

         assert image.shape == (1, 6_4, 6_4, 3)






@slow
@require_torch
class       __lowercase		(    unittest.TestCase    ):







     """simple docstring"""






     def lowerCAmelCase  (		self     ):
         __UpperCamelCase						:						List[Any]		     =	load_image(
             'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
             '/vq_diffusion/teddy_bear_pool.png'     )
         __UpperCamelCase						:						List[Any]		     =	init_image.resize((6_4, 6_4)  ,      resample=PIL_INTERPOLATION['lanczos']     )

         __UpperCamelCase						:						List[str]		     =	LDMSuperResolutionPipeline.from_pretrained('duongna/ldm-super-resolution'  ,      device_map='auto'     )
         ldm.set_progress_bar_config(disable=_lowerCamelCase     )

         __UpperCamelCase						:						Union[str, Any]		     =	torch.manual_seed(0     )
         __UpperCamelCase						:						Dict		     =	ldm(image=_lowerCamelCase  ,      generator=_lowerCamelCase  ,      num_inference_steps=2_0  ,      output_type='numpy'     ).images

         __UpperCamelCase						:						List[Any]		     =	image[0, -3:, -3:, -1]

         assert image.shape == (1, 2_5_6, 2_5_6, 3)
         __UpperCamelCase						:						str		     =	np.array([0.7_6_4_4, 0.7_6_7_9, 0.7_6_4_2, 0.7_6_3_3, 0.7_6_6_6, 0.7_5_6_0, 0.7_4_2_5, 0.7_2_5_7, 0.6_9_0_7]     )

         assert np.abs(image_slice.flatten() - expected_slice     ).max() < 1E-2



