






"""simple docstring"""



import unittest

from transformers import load_tool
from transformers.tools.agent_types import AGENT_TYPE_MAPPING

from .test_tools_common import ToolTesterMixin, output_types




class  lowerCAmelCase__ (						unittest.TestCase       ,	__lowerCamelCase      ):
   def 			__a       (		self			:  str       ):


        '''simple docstring'''
        UpperCAmelCase__	:						List[Any]       =       load_tool("translation"       )
        self.tool.setup()
        UpperCAmelCase__	:						int       =       load_tool("translation"       , remote=snake_case__       )
   def 			__a       (		self			:  Any       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Any       =       self.tool("Hey, what\'s up?"       , src_lang="English"       , tgt_lang="French"       )
        self.assertEqual(snake_case__       , "- Hé, comment ça va?"       )
   def 			__a       (		self			:  Dict       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Any       =       self.remote_tool("Hey, what\'s up?"       , src_lang="English"       , tgt_lang="French"       )
        self.assertEqual(snake_case__       , "- Hé, comment ça va?"       )
   def 			__a       (		self			:  Tuple       ):


        '''simple docstring'''
        UpperCAmelCase__	:						List[str]       =       self.tool(text="Hey, what\'s up?"       , src_lang="English"       , tgt_lang="French"       )
        self.assertEqual(snake_case__       , "- Hé, comment ça va?"       )
   def 			__a       (		self			:  Any       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Union[str, Any]       =       self.remote_tool(text="Hey, what\'s up?"       , src_lang="English"       , tgt_lang="French"       )
        self.assertEqual(snake_case__       , "- Hé, comment ça va?"       )
   def 			__a       (		self			:  Optional[int]       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Dict       =       ["Hey, what\'s up?", "English", "Spanish"]
        UpperCAmelCase__	:						Optional[int]       =       self.tool(*snake_case__       )

        # There is a single output
        if len(self.tool.outputs       ) == 1:
             UpperCAmelCase__	:						List[str]       =       [outputs]

        self.assertListEqual(output_types(snake_case__       )       , self.tool.outputs       )
   def 			__a       (		self			:  List[Any]       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Union[str, Any]       =       ["Hey, what\'s up?", "English", "Spanish"]
        UpperCAmelCase__	:						List[str]       =       self.tool(*snake_case__       )

        if not isinstance(snake_case__       , snake_case__       ):
             UpperCAmelCase__	:						List[Any]       =       [outputs]

        self.assertEqual(len(snake_case__       )       , len(self.tool.outputs       )       )

        for output, output_type in zip(snake_case__       , self.tool.outputs       ):
             UpperCAmelCase__	:						Union[str, Any]       =       AGENT_TYPE_MAPPING[output_type]
             self.assertTrue(isinstance(snake_case__       , snake_case__       )       )




   def 			__a       (		self			:  Union[str, Any]       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Dict       =       ["Hey, what\'s up?", "English", "Spanish"]

        UpperCAmelCase__	:						List[str]       =       []

        for _input, input_type in zip(snake_case__       , self.tool.inputs       ):
             if isinstance(snake_case__       , snake_case__       ):
                  _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input       ) for _input_type in input_type]       )
             else:
                  _inputs.append(AGENT_TYPE_MAPPING[input_type](_input       )       )

        # Should not raise an error
        UpperCAmelCase__	:						Union[str, Any]       =       self.tool(*snake_case__       )

        if not isinstance(snake_case__       , snake_case__       ):
             UpperCAmelCase__	:						Tuple       =       [outputs]

        self.assertEqual(len(snake_case__       )       , len(self.tool.outputs       )       )










"""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  lowerCAmelCase__ :
   def __init__(		self			:  int       , snake_case__			:  Tuple       , snake_case__			:  Any=False       , snake_case__			:  Optional[Any]=1_3       , snake_case__			:  str=(3_2, 1_2_8)       , snake_case__			:  int=4       , snake_case__			:  int=3       , snake_case__			:  int=2_7       , snake_case__			:  Tuple=3_8       , snake_case__			:  Dict=9_9       , snake_case__			:  Union[str, Any]=9_9       , snake_case__			:  Union[str, Any]=3_2       , snake_case__			:  Optional[Any]=5       , snake_case__			:  Optional[Any]=4       , snake_case__			:  str=4.0       , snake_case__			:  List[Any]=2_5_7       , snake_case__			:  int=None       , ):


        '''simple docstring'''
        UpperCAmelCase__	:						Optional[Any]       =       parent
        UpperCAmelCase__	:						Union[str, Any]       =       is_training
        UpperCAmelCase__	:						Tuple       =       batch_size
        UpperCAmelCase__	:						List[Any]       =       image_size
        UpperCAmelCase__	:						str       =       patch_size
        UpperCAmelCase__	:						List[str]       =       num_channels
        UpperCAmelCase__	:						Dict       =       max_token_length
        UpperCAmelCase__	:						List[Any]       =       num_character_labels
        UpperCAmelCase__	:						List[Any]       =       num_bpe_labels
        UpperCAmelCase__	:						List[Any]       =       num_wordpiece_labels
        UpperCAmelCase__	:						List[Any]       =       hidden_size
        UpperCAmelCase__	:						Optional[int]       =       num_hidden_layers
        UpperCAmelCase__	:						Union[str, Any]       =       num_attention_heads
        UpperCAmelCase__	:						Union[str, Any]       =       mlp_ratio
        UpperCAmelCase__	:						int       =       patch_embeds_hidden_size
        UpperCAmelCase__	:						int       =       output_hidden_states
   def 			__a       (		self			:  List[str]       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Any       =       floats_tensor([self.batch_size, self.num_channels, self.image_size[0], self.image_size[1]]       )
        UpperCAmelCase__	:						Optional[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			:  Any       , snake_case__			:  int       , snake_case__			:  Dict       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Union[str, Any]       =       MgpstrForSceneTextRecognition(snake_case__       )
        model.to(snake_case__       )
        model.eval()
        with torch.no_grad():
             UpperCAmelCase__	:						Any       =       model(snake_case__       )
        self.parent.assertEqual(
            generated_ids[0][0].shape       , (self.batch_size, self.max_token_length, self.num_character_labels)       )




   def 			__a       (		self			:  List[str]       ):


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




@require_torch
class  lowerCAmelCase__ (						__magic_name__       ,	__magic_name__       ,	unittest.TestCase      ):
   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 			__a       (		self			:  str       ):


        '''simple docstring'''
        UpperCAmelCase__	:						int       =       MgpstrModelTester(self       )
        UpperCAmelCase__	:						List[str]       =       ConfigTester(self       , config_class=snake_case__       , has_text_modality=snake_case__       )
   def 			__a       (		self			:  Optional[Any]       ):


        '''simple docstring'''
        self.config_tester.run_common_tests()
   def 			__a       (		self			:  int       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Optional[Any]       =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*snake_case__       )
   @unittest.skip(reason="MgpstrModel does not use inputs_embeds"       )
   def 			__a       (		self			:  str       ):


        '''simple docstring'''
        pass
   def 			__a       (		self			:  Union[str, Any]       ):


        '''simple docstring'''
        UpperCAmelCase__       ,							UpperCAmelCase__	:						Optional[int]       =       self.model_tester.prepare_config_and_inputs_for_common()

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


        '''simple docstring'''
        UpperCAmelCase__       ,							UpperCAmelCase__	:						Any       =       self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCAmelCase__	:						Optional[Any]       =       ["pixel_values"]
             self.assertListEqual(arg_names[:1]       , snake_case__       )
   @unittest.skip(reason="MgpstrModel does not support feedforward chunking"       )
   def 			__a       (		self			:  List[str]       ):


        '''simple docstring'''
        pass
   def 			__a       (		self			:  Dict       ):


        '''simple docstring'''
        UpperCAmelCase__       ,							UpperCAmelCase__	:						List[str]       =       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__	:						Union[str, Any]       =       True
             UpperCAmelCase__	:						Union[str, Any]       =       model_class(snake_case__       )
             self.assertTrue(model.is_gradient_checkpointing       )
   def 			__a       (		self			:  Any       ):


        '''simple docstring'''
        def check_hidden_states_output(snake_case__			:  List[Any]       , snake_case__			:  List[Any]       , snake_case__			:  List[str]       ):
             UpperCAmelCase__	:						int       =       model_class(snake_case__       )
             model.to(snake_case__       )
             model.eval()

             with torch.no_grad():
                  UpperCAmelCase__	:						Tuple       =       model(**self._prepare_for_class(snake_case__       , snake_case__       )       )

             UpperCAmelCase__	:						List[str]       =       outputs.hidden_states

             UpperCAmelCase__	:						Tuple       =       getattr(
                 self.model_tester       , "expected_num_hidden_layers"       , self.model_tester.num_hidden_layers + 1       )
             self.assertEqual(len(snake_case__       )       , snake_case__       )

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

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

        for model_class in self.all_model_classes:
             UpperCAmelCase__	:						Tuple       =       True
             check_hidden_states_output(snake_case__       , snake_case__       , snake_case__       )

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

             check_hidden_states_output(snake_case__       , snake_case__       , snake_case__       )
   def 			__a       (		self			:  Dict       ):


        '''simple docstring'''
        UpperCAmelCase__       ,							UpperCAmelCase__	:						Tuple       =       self.model_tester.prepare_config_and_inputs_for_common()

        UpperCAmelCase__	:						Dict       =       _config_zero_init(snake_case__       )
        for model_class in self.all_model_classes:
             UpperCAmelCase__	:						int       =       model_class(config=snake_case__       )
             for name, param in model.named_parameters():
                  if isinstance(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 			__a       (		self			:  Tuple       ):


        '''simple docstring'''
        pass




def   SCREAMING_SNAKE_CASE__					(     )->		List[str]:






     '''simple docstring'''



     UpperCAmelCase__	:						List[str]       =       "https://i.postimg.cc/ZKwLg2Gw/367-14.png"
     UpperCAmelCase__	:						Union[str, Any]       =       Image.open(requests.get(snake_case ,				stream=snake_case							).raw							).convert("RGB"							)
     return im




@require_vision
@require_torch
class  lowerCAmelCase__ (						unittest.TestCase      ):
   @slow
   def 			__a       (		self			:  Tuple       ):


        '''simple docstring'''
        UpperCAmelCase__	:						Optional[int]       =       "alibaba-damo/mgp-str-base"
        UpperCAmelCase__	:						Dict       =       MgpstrForSceneTextRecognition.from_pretrained(snake_case__       ).to(snake_case__       )
        UpperCAmelCase__	:						int       =       MgpstrProcessor.from_pretrained(snake_case__       )

        UpperCAmelCase__	:						Dict       =       prepare_img()
        UpperCAmelCase__	:						List[str]       =       processor(images=snake_case__       , return_tensors="pt"       ).pixel_values.to(snake_case__       )

        # forward pass
        with torch.no_grad():
             UpperCAmelCase__	:						List[str]       =       model(snake_case__       )

        # 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__	:						Dict       =       "ticket"

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

        UpperCAmelCase__	:						int       =       torch.tensor(
            [[[-39.5397, -44.4024, -36.1844], [-61.4709, -63.8639, -58.3454], [-74.0225, -68.5494, -71.2164]]]       , device=snake_case__       , )

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


