




'''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				,			_lowerCamelCase   :							List[str]				,			_lowerCamelCase   :							str=False				,			_lowerCamelCase   :							Union[str, Any]=13				,			_lowerCamelCase   :							Union[str, Any]=(32, 128)				,			_lowerCamelCase   :							Any=4				,			_lowerCamelCase   :							Tuple=3				,			_lowerCamelCase   :							List[str]=27				,			_lowerCamelCase   :							Optional[Any]=38				,			_lowerCamelCase   :							Optional[Any]=99				,			_lowerCamelCase   :							Union[str, Any]=99				,			_lowerCamelCase   :							Dict=32				,			_lowerCamelCase   :							Optional[Any]=5				,			_lowerCamelCase   :							Optional[int]=4				,			_lowerCamelCase   :							Any=4.0				,			_lowerCamelCase   :							List[str]=257				,			_lowerCamelCase   :							Optional[Any]=None				,			):





											"""simple docstring"""







											A_			:  Dict			=				parent
											A_			:  int			=				is_training
											A_			:  Optional[Any]			=				batch_size
											A_			:  Tuple			=				image_size
											A_			:  List[str]			=				patch_size
											A_			:  List[str]			=				num_channels
											A_			:  Tuple			=				max_token_length
											A_			:  Union[str, Any]			=				num_character_labels
											A_			:  Optional[int]			=				num_bpe_labels
											A_			:  Tuple			=				num_wordpiece_labels
											A_			:  Optional[Any]			=				hidden_size
											A_			:  Tuple			=				num_hidden_layers
											A_			:  Optional[Any]			=				num_attention_heads
											A_			:  Union[str, Any]			=				mlp_ratio
											A_			:  List[Any]			=				patch_embeds_hidden_size
											A_			:  Optional[int]			=				output_hidden_states







						def    _a     (  self   :							Dict     ):





											"""simple docstring"""







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







						def    _a     (  self   :							List[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   :							Union[str, Any]				,			_lowerCamelCase   :							Optional[Any]				,			_lowerCamelCase   :							Union[str, Any]     ):





											"""simple docstring"""







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







						def    _a     (  self   :							List[Any]     ):





											"""simple docstring"""







											A_			:  Optional[int]			=				self.prepare_config_and_inputs()
											A_			,A_			:  Any			=				config_and_inputs
											A_			:  List[str]			=				{'''pixel_values''': pixel_values}
											return config, inputs_dict






@require_torch
class      UpperCamelCase_  (a__,   a__,   unittest.TestCase  ):







						"""simple docstring"""


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

						_lowerCAmelCase         =       False
						_lowerCAmelCase         =       False
						_lowerCAmelCase         =       False
						_lowerCAmelCase         =       False







						def    _a     (  self   :							Dict     ):





											"""simple docstring"""







											A_			:  Union[str, Any]			=				MgpstrModelTester(self     )
											A_			:  Dict			=				ConfigTester(self				,			config_class=_lowerCamelCase				,			has_text_modality=_lowerCamelCase     )







						def    _a     (  self   :							List[Any]     ):





											"""simple docstring"""







											self.config_tester.run_common_tests()







						def    _a     (  self   :							Any     ):





											"""simple docstring"""







											A_			:  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    _a     (  self   :							Dict     ):





											"""simple docstring"""







											pass







						def    _a     (  self   :							str     ):





											"""simple docstring"""







											A_			,A_			:  Optional[Any]			=				self.model_tester.prepare_config_and_inputs_for_common()

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







						def    _a     (  self   :							Optional[Any]     ):





											"""simple docstring"""







											A_			,A_			:  Dict			=				self.model_tester.prepare_config_and_inputs_for_common()

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

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







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





											"""simple docstring"""







											pass







						def    _a     (  self   :							Dict     ):





											"""simple docstring"""







											A_			,A_			:  Optional[Any]			=				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_			:  List[str]			=				True
																A_			:  Union[str, Any]			=				model_class(_lowerCamelCase     )
																self.assertTrue(model.is_gradient_checkpointing     )







						def    _a     (  self   :							Dict     ):





											"""simple docstring"""







											def check_hidden_states_output(_lowerCamelCase   :							Tuple				,			_lowerCamelCase   :							Optional[int]				,			_lowerCamelCase   :							Any     ):
																A_			:  List[str]			=				model_class(_lowerCamelCase     )
																model.to(_lowerCamelCase     )
																model.eval()

																with torch.no_grad():
																					A_			:  int			=				model(**self._prepare_for_class(_lowerCamelCase				,			_lowerCamelCase     )     )

																A_			:  Optional[Any]			=				outputs.hidden_states

																A_			:  List[str]			=				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]				,			)

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

											for model_class in self.all_model_classes:
																A_			:  Optional[int]			=				True
																check_hidden_states_output(_lowerCamelCase				,			_lowerCamelCase				,			_lowerCamelCase     )

																# check that output_hidden_states also work using config
																del inputs_dict["output_hidden_states"]
																A_			:  Optional[Any]			=				True

																check_hidden_states_output(_lowerCamelCase				,			_lowerCamelCase				,			_lowerCamelCase     )







						def    _a     (  self   :							Any     ):





											"""simple docstring"""







											A_			,A_			:  Tuple			=				self.model_tester.prepare_config_and_inputs_for_common()

											A_			:  List[str]			=				_config_zero_init(_lowerCamelCase     )
											for model_class in self.all_model_classes:
																A_			:  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    _a     (  self   :							int     ):





											"""simple docstring"""







											pass






def     snake_case__     (			) -> str:
					A_			:  Union[str, Any]			=				'''https://i.postimg.cc/ZKwLg2Gw/367-14.png'''
					A_			:  Tuple			=				Image.open(requests.get(lowerCamelCase__      ,		stream=lowerCamelCase__      ).raw      ).convert('''RGB'''      )
					return im






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







						"""simple docstring"""


						@slow
						def    _a     (  self   :							List[str]     ):





											"""simple docstring"""







											A_			:  List[Any]			=				'''alibaba-damo/mgp-str-base'''
											A_			:  Optional[Any]			=				MgpstrForSceneTextRecognition.from_pretrained(_lowerCamelCase     ).to(_lowerCamelCase     )
											A_			:  Any			=				MgpstrProcessor.from_pretrained(_lowerCamelCase     )

											A_			:  Dict			=				prepare_img()
											A_			:  List[Any]			=				processor(images=_lowerCamelCase				,			return_tensors='''pt'''     ).pixel_values.to(_lowerCamelCase     )

											# forward pass
											with torch.no_grad():
																A_			:  Tuple			=				model(_lowerCamelCase     )

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

											A_			:  Optional[Any]			=				processor.batch_decode(outputs.logits     )
											A_			:  Dict			=				'''ticket'''

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

											A_			:  str			=				torch.tensor(
											    [[[-39.53_97, -44.40_24, -36.18_44], [-61.47_09, -63.86_39, -58.34_54], [-74.02_25, -68.54_94, -71.21_64]]]				,			device=_lowerCamelCase				,			)

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









'''simple docstring'''




from typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


snake_case__ 							=    {
    """configuration_utils""": ["""GenerationConfig"""],
    """streamers""": ["""TextIteratorStreamer""", """TextStreamer"""],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							snake_case__ 							=    [
							    """Constraint""",
							    """ConstraintListState""",
							    """DisjunctiveConstraint""",
							    """PhrasalConstraint""",
							]
							snake_case__ 							=    [
							    """BeamHypotheses""",
							    """BeamScorer""",
							    """BeamSearchScorer""",
							    """ConstrainedBeamSearchScorer""",
							]
							snake_case__ 							=    [
							    """EpsilonLogitsWarper""",
							    """EtaLogitsWarper""",
							    """ForcedBOSTokenLogitsProcessor""",
							    """ForcedEOSTokenLogitsProcessor""",
							    """HammingDiversityLogitsProcessor""",
							    """InfNanRemoveLogitsProcessor""",
							    """LogitsProcessor""",
							    """LogitsProcessorList""",
							    """LogitsWarper""",
							    """MinLengthLogitsProcessor""",
							    """MinNewTokensLengthLogitsProcessor""",
							    """NoBadWordsLogitsProcessor""",
							    """NoRepeatNGramLogitsProcessor""",
							    """PrefixConstrainedLogitsProcessor""",
							    """RepetitionPenaltyLogitsProcessor""",
							    """SequenceBiasLogitsProcessor""",
							    """EncoderRepetitionPenaltyLogitsProcessor""",
							    """TemperatureLogitsWarper""",
							    """TopKLogitsWarper""",
							    """TopPLogitsWarper""",
							    """TypicalLogitsWarper""",
							    """EncoderNoRepeatNGramLogitsProcessor""",
							    """ExponentialDecayLengthPenalty""",
							    """LogitNormalization""",
							]
							snake_case__ 							=    [
							    """MaxNewTokensCriteria""",
							    """MaxLengthCriteria""",
							    """MaxTimeCriteria""",
							    """StoppingCriteria""",
							    """StoppingCriteriaList""",
							    """validate_stopping_criteria""",
							]
							snake_case__ 							=    [
							    """GenerationMixin""",
							    """top_k_top_p_filtering""",
							    """GreedySearchEncoderDecoderOutput""",
							    """GreedySearchDecoderOnlyOutput""",
							    """SampleEncoderDecoderOutput""",
							    """SampleDecoderOnlyOutput""",
							    """BeamSearchEncoderDecoderOutput""",
							    """BeamSearchDecoderOnlyOutput""",
							    """BeamSampleEncoderDecoderOutput""",
							    """BeamSampleDecoderOnlyOutput""",
							    """ContrastiveSearchEncoderDecoderOutput""",
							    """ContrastiveSearchDecoderOnlyOutput""",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							snake_case__ 							=    [
							    """TFForcedBOSTokenLogitsProcessor""",
							    """TFForcedEOSTokenLogitsProcessor""",
							    """TFLogitsProcessor""",
							    """TFLogitsProcessorList""",
							    """TFLogitsWarper""",
							    """TFMinLengthLogitsProcessor""",
							    """TFNoBadWordsLogitsProcessor""",
							    """TFNoRepeatNGramLogitsProcessor""",
							    """TFRepetitionPenaltyLogitsProcessor""",
							    """TFTemperatureLogitsWarper""",
							    """TFTopKLogitsWarper""",
							    """TFTopPLogitsWarper""",
							    """TFForceTokensLogitsProcessor""",
							    """TFSuppressTokensAtBeginLogitsProcessor""",
							    """TFSuppressTokensLogitsProcessor""",
							]
							snake_case__ 							=    [
							    """TFGenerationMixin""",
							    """tf_top_k_top_p_filtering""",
							    """TFGreedySearchDecoderOnlyOutput""",
							    """TFGreedySearchEncoderDecoderOutput""",
							    """TFSampleEncoderDecoderOutput""",
							    """TFSampleDecoderOnlyOutput""",
							    """TFBeamSearchEncoderDecoderOutput""",
							    """TFBeamSearchDecoderOnlyOutput""",
							    """TFBeamSampleEncoderDecoderOutput""",
							    """TFBeamSampleDecoderOnlyOutput""",
							    """TFContrastiveSearchEncoderDecoderOutput""",
							    """TFContrastiveSearchDecoderOnlyOutput""",
							]

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							snake_case__ 							=    [
							    """FlaxForcedBOSTokenLogitsProcessor""",
							    """FlaxForcedEOSTokenLogitsProcessor""",
							    """FlaxLogitsProcessor""",
							    """FlaxLogitsProcessorList""",
							    """FlaxLogitsWarper""",
							    """FlaxMinLengthLogitsProcessor""",
							    """FlaxTemperatureLogitsWarper""",
							    """FlaxTopKLogitsWarper""",
							    """FlaxTopPLogitsWarper""",
							]
							snake_case__ 							=    [
							    """FlaxGenerationMixin""",
							    """FlaxGreedySearchOutput""",
							    """FlaxSampleOutput""",
							    """FlaxBeamSearchOutput""",
							]

if TYPE_CHECKING:
							from .configuration_utils import GenerationConfig
							from .streamers import TextIteratorStreamer, TextStreamer

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
														from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
														from .logits_process import (
														    EncoderNoRepeatNGramLogitsProcessor,
														    EncoderRepetitionPenaltyLogitsProcessor,
														    EpsilonLogitsWarper,
														    EtaLogitsWarper,
														    ExponentialDecayLengthPenalty,
														    ForcedBOSTokenLogitsProcessor,
														    ForcedEOSTokenLogitsProcessor,
														    HammingDiversityLogitsProcessor,
														    InfNanRemoveLogitsProcessor,
														    LogitNormalization,
														    LogitsProcessor,
														    LogitsProcessorList,
														    LogitsWarper,
														    MinLengthLogitsProcessor,
														    MinNewTokensLengthLogitsProcessor,
														    NoBadWordsLogitsProcessor,
														    NoRepeatNGramLogitsProcessor,
														    PrefixConstrainedLogitsProcessor,
														    RepetitionPenaltyLogitsProcessor,
														    SequenceBiasLogitsProcessor,
														    TemperatureLogitsWarper,
														    TopKLogitsWarper,
														    TopPLogitsWarper,
														    TypicalLogitsWarper,
														)
														from .stopping_criteria import (
														    MaxLengthCriteria,
														    MaxNewTokensCriteria,
														    MaxTimeCriteria,
														    StoppingCriteria,
														    StoppingCriteriaList,
														    validate_stopping_criteria,
														)
														from .utils import (
														    BeamSampleDecoderOnlyOutput,
														    BeamSampleEncoderDecoderOutput,
														    BeamSearchDecoderOnlyOutput,
														    BeamSearchEncoderDecoderOutput,
														    ContrastiveSearchDecoderOnlyOutput,
														    ContrastiveSearchEncoderDecoderOutput,
														    GenerationMixin,
														    GreedySearchDecoderOnlyOutput,
														    GreedySearchEncoderDecoderOutput,
														    SampleDecoderOnlyOutput,
														    SampleEncoderDecoderOutput,
														    top_k_top_p_filtering,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tf_logits_process import (
														    TFForcedBOSTokenLogitsProcessor,
														    TFForcedEOSTokenLogitsProcessor,
														    TFForceTokensLogitsProcessor,
														    TFLogitsProcessor,
														    TFLogitsProcessorList,
														    TFLogitsWarper,
														    TFMinLengthLogitsProcessor,
														    TFNoBadWordsLogitsProcessor,
														    TFNoRepeatNGramLogitsProcessor,
														    TFRepetitionPenaltyLogitsProcessor,
														    TFSuppressTokensAtBeginLogitsProcessor,
														    TFSuppressTokensLogitsProcessor,
														    TFTemperatureLogitsWarper,
														    TFTopKLogitsWarper,
														    TFTopPLogitsWarper,
														)
														from .tf_utils import (
														    TFBeamSampleDecoderOnlyOutput,
														    TFBeamSampleEncoderDecoderOutput,
														    TFBeamSearchDecoderOnlyOutput,
														    TFBeamSearchEncoderDecoderOutput,
														    TFContrastiveSearchDecoderOnlyOutput,
														    TFContrastiveSearchEncoderDecoderOutput,
														    TFGenerationMixin,
														    TFGreedySearchDecoderOnlyOutput,
														    TFGreedySearchEncoderDecoderOutput,
														    TFSampleDecoderOnlyOutput,
														    TFSampleEncoderDecoderOutput,
														    tf_top_k_top_p_filtering,
														)

							try:
														if not is_flax_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .flax_logits_process import (
														    FlaxForcedBOSTokenLogitsProcessor,
														    FlaxForcedEOSTokenLogitsProcessor,
														    FlaxLogitsProcessor,
														    FlaxLogitsProcessorList,
														    FlaxLogitsWarper,
														    FlaxMinLengthLogitsProcessor,
														    FlaxTemperatureLogitsWarper,
														    FlaxTopKLogitsWarper,
														    FlaxTopPLogitsWarper,
														)
														from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
							import sys

							snake_case__ 							=    _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)



