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



	"""simple docstring"""



	def __init__(   self       ,  lowerCAmelCase_       ,  lowerCAmelCase_=False       ,  lowerCAmelCase_=13       ,  lowerCAmelCase_=(32, 128)       ,  lowerCAmelCase_=4       ,  lowerCAmelCase_=3       ,  lowerCAmelCase_=27       ,  lowerCAmelCase_=38       ,  lowerCAmelCase_=99       ,  lowerCAmelCase_=99       ,  lowerCAmelCase_=32       ,  lowerCAmelCase_=5       ,  lowerCAmelCase_=4       ,  lowerCAmelCase_=4.0       ,  lowerCAmelCase_=257       ,  lowerCAmelCase_=None       ,  ):
		_lowercase   =parent
		_lowercase   =is_training
		_lowercase   =batch_size
		_lowercase   =image_size
		_lowercase   =patch_size
		_lowercase   =num_channels
		_lowercase   =max_token_length
		_lowercase   =num_character_labels
		_lowercase   =num_bpe_labels
		_lowercase   =num_wordpiece_labels
		_lowercase   =hidden_size
		_lowercase   =num_hidden_layers
		_lowercase   =num_attention_heads
		_lowercase   =mlp_ratio
		_lowercase   =patch_embeds_hidden_size
		_lowercase   =output_hidden_states


	def __lowerCAmelCase      (   self       ):
		_lowercase   =floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]       )
		_lowercase   =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_       ):
		_lowercase   =MgpstrForSceneTextRecognition(lowerCAmelCase_       )
		model.to(lowerCAmelCase_       )
		model.eval()
		with torch.no_grad():
			_lowercase   =model(lowerCAmelCase_       )
		self.parent.assertEqual(
		    generated_ids[0][0].shape       ,  (self.batch_size, self.max_token_length, self.num_character_labels)       )


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

@require_torch
class 	_a  (							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       ):
		_lowercase   =MgpstrModelTester(self       )
		_lowercase   =ConfigTester(self       ,  config_class=lowerCAmelCase_       ,  has_text_modality=lowerCAmelCase_       )


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


	def __lowerCAmelCase      (   self       ):
		_lowercase   =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       ):
		_lowercase   ,  _lowercase   =self.model_tester.prepare_config_and_inputs_for_common()

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


	def __lowerCAmelCase      (   self       ):
		_lowercase   ,  _lowercase   =self.model_tester.prepare_config_and_inputs_for_common()

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

			_lowercase   =["pixel_values"]
			self.assertListEqual(arg_names[:1]       ,  lowerCAmelCase_       )


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


	def __lowerCAmelCase      (   self       ):
		_lowercase   ,  _lowercase   =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

			_lowercase   =True
			_lowercase   =model_class(lowerCAmelCase_       )
			self.assertTrue(model.is_gradient_checkpointing       )


	def __lowerCAmelCase      (   self       ):
		def check_hidden_states_output(lowerCAmelCase_       ,  lowerCAmelCase_       ,  lowerCAmelCase_       ):
			_lowercase   =model_class(lowerCAmelCase_       )
			model.to(lowerCAmelCase_       )
			model.eval()

			with torch.no_grad():
				_lowercase   =model(**self._prepare_for_class(lowerCAmelCase_       ,  lowerCAmelCase_       )       )

			_lowercase   =outputs.hidden_states

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

		_lowercase   ,  _lowercase   =self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			_lowercase   =True
			check_hidden_states_output(lowerCAmelCase_       ,  lowerCAmelCase_       ,  lowerCAmelCase_       )

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

			check_hidden_states_output(lowerCAmelCase_       ,  lowerCAmelCase_       ,  lowerCAmelCase_       )


	def __lowerCAmelCase      (   self       ):
		_lowercase   ,  _lowercase   =self.model_tester.prepare_config_and_inputs_for_common()

		_lowercase   =_config_zero_init(lowerCAmelCase_       )
		for model_class in self.all_model_classes:
			_lowercase   =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 	__lowerCamelCase							(				)      ->       Tuple:
	_lowercase   ="https://i.postimg.cc/ZKwLg2Gw/367-14.png"
	_lowercase   =Image.open(requests.get(__a      ,							stream=__a		).raw		).convert("RGB"		)
	return im
@require_vision
@require_torch
class 	_a  (							unittest.TestCase					):



	"""simple docstring"""



	@slow
	def __lowerCAmelCase      (   self       ):
		_lowercase   ="alibaba-damo/mgp-str-base"
		_lowercase   =MgpstrForSceneTextRecognition.from_pretrained(lowerCAmelCase_       ).to(lowerCAmelCase_       )
		_lowercase   =MgpstrProcessor.from_pretrained(lowerCAmelCase_       )

		_lowercase   =prepare_img()
		_lowercase   =processor(images=lowerCAmelCase_       ,  return_tensors="pt"       ).pixel_values.to(lowerCAmelCase_       )

		# forward pass
		with torch.no_grad():
			_lowercase   =model(lowerCAmelCase_       )

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

		_lowercase   =processor.batch_decode(outputs.logits       )
		_lowercase   ="ticket"

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

		_lowercase   =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 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 BlipImageProcessor



class 				lowercase			(    unittest.TestCase							):


 """simple docstring"""


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







 def _snake_case					(				self				)						->  List[str]:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_convert_rgb": self.do_convert_rgb,
            "do_pad": self.do_pad,
        }







 def _snake_case					(				self    ,a_=False    ,a_=False    ,a_=False				)						->  Dict:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
               _UpperCAmelCase    :		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:
               _UpperCAmelCase    :		Optional[int]     	=					[]
               for i in range(self.batch_size				):
                      _UpperCAmelCase	,_UpperCAmelCase    :		int     	=					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
               _UpperCAmelCase    :		Any     	=					[Image.fromarray(np.moveaxis(a_    ,0    ,-1				)				) for x in image_inputs]

        if torchify:
               _UpperCAmelCase    :		Optional[int]     	=					[torch.from_numpy(a_				) for x in image_inputs]

        return image_inputs







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







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







 @property
 def _snake_case					(				self				)						->  str:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Tuple:
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







 def _snake_case					(				self				)						->  Any:
        pass







 def _snake_case					(				self				)						->  Union[str, Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[str]     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		List[str]     	=					image_processor(a_    ,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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







 def _snake_case					(				self				)						->  Optional[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		str     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,numpify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,np.ndarray				)

        # Test not batched input
        _UpperCAmelCase    :		Dict     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		int     	=					image_processor(a_    ,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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







 def _snake_case					(				self				)						->  List[str]:
        # Initialize image_processor
        _UpperCAmelCase    :		Dict     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        _UpperCAmelCase    :		Union[str, Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,torchify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,torch.Tensor				)

        # Test not batched input
        _UpperCAmelCase    :		str     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		Optional[Any]     	=					image_processor(a_    ,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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					BlipImageProcessingTester(self    ,num_channels=4				)
        _UpperCAmelCase    :		List[Any]     	=					3







 @property
 def _snake_case					(				self				)						->  int:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







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







 def _snake_case					(				self				)						->  List[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		Any     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[Any]     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		Dict     	=					image_processor(a_    ,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.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)



