

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     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE=False     ,						_SCREAMING_SNAKE_CASE=13     ,						_SCREAMING_SNAKE_CASE=(32, 128)     ,						_SCREAMING_SNAKE_CASE=4     ,						_SCREAMING_SNAKE_CASE=3     ,						_SCREAMING_SNAKE_CASE=27     ,						_SCREAMING_SNAKE_CASE=38     ,						_SCREAMING_SNAKE_CASE=99     ,						_SCREAMING_SNAKE_CASE=99     ,						_SCREAMING_SNAKE_CASE=32     ,						_SCREAMING_SNAKE_CASE=5     ,						_SCREAMING_SNAKE_CASE=4     ,						_SCREAMING_SNAKE_CASE=4.0     ,						_SCREAMING_SNAKE_CASE=257     ,						_SCREAMING_SNAKE_CASE=None     ,						)->							Optional[Any]:
													lowerCamelCase_								=parent
													lowerCamelCase_								=is_training
													lowerCamelCase_								=batch_size
													lowerCamelCase_								=image_size
													lowerCamelCase_								=patch_size
													lowerCamelCase_								=num_channels
													lowerCamelCase_								=max_token_length
													lowerCamelCase_								=num_character_labels
													lowerCamelCase_								=num_bpe_labels
													lowerCamelCase_								=num_wordpiece_labels
													lowerCamelCase_								=hidden_size
													lowerCamelCase_								=num_hidden_layers
													lowerCamelCase_								=num_attention_heads
													lowerCamelCase_								=mlp_ratio
													lowerCamelCase_								=patch_embeds_hidden_size
													lowerCamelCase_								=output_hidden_states







						def        _snake_case				(			self							)->							Tuple:
													lowerCamelCase_								=floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]							)
													lowerCamelCase_								=self.get_config()
													return config, pixel_values







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







						def        _snake_case				(			self							)->							Optional[Any]:
													lowerCamelCase_								=self.prepare_config_and_inputs()
													lowerCamelCase_	,   lowerCamelCase_								=config_and_inputs
													lowerCamelCase_								={"""pixel_values""": pixel_values}
													return config, inputs_dict


@require_torch
class 			_SCREAMING_SNAKE_CASE      (  lowerCAmelCase__ ,    lowerCAmelCase__ ,    unittest.TestCase):
						_UpperCamelCase:Any	=		(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
						_UpperCamelCase:Any	=		{"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
						_UpperCamelCase:Optional[Any]	=		False

						_UpperCamelCase:str	=		False
						_UpperCamelCase:Optional[Any]	=		False
						_UpperCamelCase:Union[str, Any]	=		False
						_UpperCamelCase:Any	=		False







						def        _snake_case				(			self							)->							List[Any]:
													lowerCamelCase_								=MgpstrModelTester(self							)
													lowerCamelCase_								=ConfigTester(self     ,						config_class=_SCREAMING_SNAKE_CASE     ,						has_text_modality=_SCREAMING_SNAKE_CASE							)







						def        _snake_case				(			self							)->							int:
													self.config_tester.run_common_tests()







						def        _snake_case				(			self							)->							List[Any]:
													lowerCamelCase_								=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        _snake_case				(			self							)->							Optional[Any]:
													pass







						def        _snake_case				(			self							)->							Optional[Any]:
													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

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







						def        _snake_case				(			self							)->							Dict:
													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

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

																				lowerCamelCase_								=["""pixel_values"""]
																				self.assertListEqual(arg_names[:1]     ,						_SCREAMING_SNAKE_CASE							)







						@unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""							)
						def        _snake_case				(			self							)->							List[str]:
													pass







						def        _snake_case				(			self							)->							Optional[Any]:
													lowerCamelCase_	,   lowerCamelCase_								=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

																				lowerCamelCase_								=True
																				lowerCamelCase_								=model_class(_SCREAMING_SNAKE_CASE							)
																				self.assertTrue(model.is_gradient_checkpointing							)







						def        _snake_case				(			self							)->							Optional[Any]:
													def check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							):
																				lowerCamelCase_								=model_class(_SCREAMING_SNAKE_CASE							)
																				model.to(_SCREAMING_SNAKE_CASE							)
																				model.eval()

																				with torch.no_grad():
																											lowerCamelCase_								=model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)							)

																				lowerCamelCase_								=outputs.hidden_states

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

													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																				lowerCamelCase_								=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"]
																				lowerCamelCase_								=True

																				check_hidden_states_output(_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE     ,						_SCREAMING_SNAKE_CASE							)







						def        _snake_case				(			self							)->							List[str]:
													lowerCamelCase_	,   lowerCamelCase_								=self.model_tester.prepare_config_and_inputs_for_common()

													lowerCamelCase_								=_config_zero_init(_SCREAMING_SNAKE_CASE							)
													for model_class in self.all_model_classes:
																				lowerCamelCase_								=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        _snake_case				(			self							)->							List[Any]:
													pass




def        __UpperCamelCase     (      )				->Any:



							"""simple docstring"""
							lowerCamelCase_								="""https://i.postimg.cc/ZKwLg2Gw/367-14.png"""
							lowerCamelCase_								=Image.open(requests.get(_A      ,  stream=_A		).raw		).convert("""RGB"""		)
							return im






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







						@slow
						def        _snake_case				(			self							)->							int:
													lowerCamelCase_								="""alibaba-damo/mgp-str-base"""
													lowerCamelCase_								=MgpstrForSceneTextRecognition.from_pretrained(_SCREAMING_SNAKE_CASE							).to(_SCREAMING_SNAKE_CASE							)
													lowerCamelCase_								=MgpstrProcessor.from_pretrained(_SCREAMING_SNAKE_CASE							)

													lowerCamelCase_								=prepare_img()
													lowerCamelCase_								=processor(images=_SCREAMING_SNAKE_CASE     ,						return_tensors="""pt"""							).pixel_values.to(_SCREAMING_SNAKE_CASE							)

													# forward pass
													with torch.no_grad():
																				lowerCamelCase_								=model(_SCREAMING_SNAKE_CASE							)

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

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

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

													lowerCamelCase_								=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=_SCREAMING_SNAKE_CASE     ,						)

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



from __future__ import annotations




def        __UpperCamelCase     (      _A					:							int      ,  _A					:							list[int]      ,  _A					:							list[int]      ,  _A					:							int		)				->int:



							"""simple docstring"""

							# Base Case
							if counter == 0 or capacity == 0:
														return 0

							# If weight of the nth item is more than Knapsack of capacity,
							#   then this item cannot be included in the optimal solution,
							# else return the maximum of two cases:
							#   (1) nth item included
							#   (2) not included
							if weights[counter - 1] > capacity:
														return knapsack(_A      ,  _A      ,  _A      ,  counter - 1		)
							else:
														lowerCamelCase_								=capacity - weights[counter - 1]
														lowerCamelCase_								=values[counter - 1] + knapsack(
														    _A      ,  _A      ,  _A      ,  counter - 1		)
														lowerCamelCase_								=knapsack(_A      ,  _A      ,  _A      ,  counter - 1		)
														return max(_A      ,  _A		)


if __name__ == "__main__":
	import doctest

	doctest.testmod()
