
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__		:
      def __init__(				self   ,  __magic_name__   ,  __magic_name__=False   ,  __magic_name__=1_3   ,  __magic_name__=(3_2, 1_2_8)   ,  __magic_name__=4   ,  __magic_name__=3   ,  __magic_name__=2_7   ,  __magic_name__=3_8   ,  __magic_name__=9_9   ,  __magic_name__=9_9   ,  __magic_name__=3_2   ,  __magic_name__=5   ,  __magic_name__=4   ,  __magic_name__=4.0   ,  __magic_name__=2_5_7   ,  __magic_name__=None   ,  ):
       lowerCamelCase		:     Tuple          =				parent
       lowerCamelCase		:     Dict          =				is_training
       lowerCamelCase		:     Dict          =				batch_size
       lowerCamelCase		:     List[Any]          =				image_size
       lowerCamelCase		:     List[str]          =				patch_size
       lowerCamelCase		:     Optional[Any]          =				num_channels
       lowerCamelCase		:     Union[str, Any]          =				max_token_length
       lowerCamelCase		:     Any          =				num_character_labels
       lowerCamelCase		:     Union[str, Any]          =				num_bpe_labels
       lowerCamelCase		:     List[Any]          =				num_wordpiece_labels
       lowerCamelCase		:     List[str]          =				hidden_size
       lowerCamelCase		:     Dict          =				num_hidden_layers
       lowerCamelCase		:     Optional[Any]          =				num_attention_heads
       lowerCamelCase		:     Any          =				mlp_ratio
       lowerCamelCase		:     Tuple          =				patch_embeds_hidden_size
       lowerCamelCase		:     Tuple          =				output_hidden_states
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     Optional[Any]          =				floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]				)
       lowerCamelCase		:     Any          =				self.get_config()
       return config, pixel_values
      def 						UpperCamelCase__							(				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 						UpperCamelCase__							(				self   ,  __magic_name__   ,  __magic_name__				):
       lowerCamelCase		:     Optional[int]          =				MgpstrForSceneTextRecognition(__magic_name__				)
       model.to(__magic_name__				)
       model.eval()
       with torch.no_grad():
        lowerCamelCase		:     int          =				model(__magic_name__				)
       self.parent.assertEqual(
           generated_ids[0][0].shape   ,  (self.batch_size, self.max_token_length, self.num_character_labels)				)






      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     Dict          =				self.prepare_config_and_inputs()
       lowerCamelCase      ,   lowerCamelCase		:     int          =				config_and_inputs
       lowerCamelCase		:     Optional[Any]          =				{"""pixel_values""": pixel_values}
       return config, inputs_dict





@require_torch
class 							A__		(     __SCREAMING_SNAKE_CASE  ,       __SCREAMING_SNAKE_CASE  ,       unittest.TestCase):
      _UpperCAmelCase    :   int   	=      (MgpstrForSceneTextRecognition,) if is_torch_available() else ()
      _UpperCAmelCase    :   List[str]   	=      {"""feature-extraction""": MgpstrForSceneTextRecognition} if is_torch_available() else {}
      _UpperCAmelCase    :   Union[str, Any]   	=      False

      _UpperCAmelCase    :   List[Any]   	=      False
      _UpperCAmelCase    :   Union[str, Any]   	=      False
      _UpperCAmelCase    :   Tuple   	=      False
      _UpperCAmelCase    :   Optional[Any]   	=      False
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     Tuple          =				MgpstrModelTester(self				)
       lowerCamelCase		:     Dict          =				ConfigTester(self   ,  config_class=__magic_name__   ,  has_text_modality=__magic_name__				)
      def 						UpperCamelCase__							(				self				):
       self.config_tester.run_common_tests()
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     str          =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__magic_name__				)
      @unittest.skip(reason="""MgpstrModel does not use inputs_embeds"""				)
      def 						UpperCamelCase__							(				self				):
       pass
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase      ,   lowerCamelCase		:     int          =				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase		:     Union[str, Any]          =				model_class(__magic_name__				)
        self.assertIsInstance(model.get_input_embeddings()   ,  (nn.Module)				)
        lowerCamelCase		:     int          =				model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(__magic_name__   ,  nn.Linear				)				)
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase      ,   lowerCamelCase		:     List[Any]          =				self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCamelCase		:     Tuple          =				["""pixel_values"""]
        self.assertListEqual(arg_names[:1]   ,  __magic_name__				)
      @unittest.skip(reason="""MgpstrModel does not support feedforward chunking"""				)
      def 						UpperCamelCase__							(				self				):
       pass
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase      ,   lowerCamelCase		:     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

        lowerCamelCase		:     Union[str, Any]          =				True
        lowerCamelCase		:     Any          =				model_class(__magic_name__				)
        self.assertTrue(model.is_gradient_checkpointing				)
      def 						UpperCamelCase__							(				self				):
       def check_hidden_states_output(__magic_name__   ,  __magic_name__   ,  __magic_name__				):
        lowerCamelCase		:     List[Any]          =				model_class(__magic_name__				)
        model.to(__magic_name__				)
        model.eval()

        with torch.no_grad():
         lowerCamelCase		:     Optional[Any]          =				model(**self._prepare_for_class(__magic_name__   ,  __magic_name__				)				)

        lowerCamelCase		:     str          =				outputs.hidden_states

        lowerCamelCase		:     Any          =				getattr(
            self.model_tester   ,  """expected_num_hidden_layers"""   ,  self.model_tester.num_hidden_layers + 1				)
        self.assertEqual(len(__magic_name__				)   ,  __magic_name__				)

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

       lowerCamelCase      ,   lowerCamelCase		:     List[Any]          =				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase		:     Optional[Any]          =				True
        check_hidden_states_output(__magic_name__   ,  __magic_name__   ,  __magic_name__				)

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

        check_hidden_states_output(__magic_name__   ,  __magic_name__   ,  __magic_name__				)
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase      ,   lowerCamelCase		:     List[str]          =				self.model_tester.prepare_config_and_inputs_for_common()

       lowerCamelCase		:     Optional[int]          =				_config_zero_init(__magic_name__				)
       for model_class in self.all_model_classes:
        lowerCamelCase		:     Optional[Any]          =				model_class(config=__magic_name__				)
        for name, param in model.named_parameters():
         if isinstance(__magic_name__   ,  (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 						UpperCamelCase__							(				self				):
       pass





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





@require_vision
@require_torch
class 							A__		(     unittest.TestCase):
      @slow
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     List[str]          =				"""alibaba-damo/mgp-str-base"""
       lowerCamelCase		:     Tuple          =				MgpstrForSceneTextRecognition.from_pretrained(__magic_name__				).to(__magic_name__				)
       lowerCamelCase		:     List[Any]          =				MgpstrProcessor.from_pretrained(__magic_name__				)

       lowerCamelCase		:     Tuple          =				prepare_img()
       lowerCamelCase		:     List[str]          =				processor(images=__magic_name__   ,  return_tensors="""pt"""				).pixel_values.to(__magic_name__				)

       # forward pass
       with torch.no_grad():
        lowerCamelCase		:     Union[str, Any]          =				model(__magic_name__				)

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

       lowerCamelCase		:     Any          =				processor.batch_decode(outputs.logits				)
       lowerCamelCase		:     Dict          =				"""ticket"""

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

       lowerCamelCase		:     Optional[Any]          =				torch.tensor(
           [[[-39.5_397, -44.4_024, -36.1_844], [-61.4_709, -63.8_639, -58.3_454], [-74.0_225, -68.5_494, -71.2_164]]]   ,  device=__magic_name__   ,  )

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






import sys





def    _a (						lowerCamelCase,     lowerCamelCase							):
 if not numbers:
  return 0
 if target == 0 and target in numbers:
  return 0
 if not isinstance(lowerCamelCase,     (list, tuple)							) or not all(
     isinstance(lowerCamelCase,     lowerCamelCase							) for number in numbers							):
  raise ValueError("""numbers must be an iterable of integers"""							)

 lowerCamelCase		:     str          =				0
 lowerCamelCase		:     List[str]          =				sys.maxsize

 while right < len(lowerCamelCase							):
  curr_sum += numbers[right]
  while curr_sum >= target and left <= right:
   lowerCamelCase		:     Any          =				min(lowerCamelCase,     right - left + 1							)
   curr_sum -= numbers[left]
   left += 1
  right += 1

 return 0 if min_len == sys.maxsize else min_len




