





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 :



      """simple docstring"""






      def __init__( self				,						UpperCAmelCase				,						UpperCAmelCase=False				,						UpperCAmelCase=13				,						UpperCAmelCase=(32, 128)				,						UpperCAmelCase=4				,						UpperCAmelCase=3				,						UpperCAmelCase=27				,						UpperCAmelCase=38				,						UpperCAmelCase=99				,						UpperCAmelCase=99				,						UpperCAmelCase=32				,						UpperCAmelCase=5				,						UpperCAmelCase=4				,						UpperCAmelCase=4.0				,						UpperCAmelCase=257				,						UpperCAmelCase=None				,						)       ->   Dict:






        '''simple docstring'''






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







      def 						UpperCAmelCase		( self   )       ->   Dict:






        '''simple docstring'''






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







      def 						UpperCAmelCase		( 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 						UpperCAmelCase		( self				,						UpperCAmelCase				,						UpperCAmelCase   )       ->   Union[str, Any]:






        '''simple docstring'''






        __snake_case   :				int        =       MgpstrForSceneTextRecognition(UpperCAmelCase   )
        model.to(UpperCAmelCase   )
        model.eval()
        with torch.no_grad():
          __snake_case   :				List[str]        =       model(UpperCAmelCase   )
        self.parent.assertEqual(
            generated_ids[0][0].shape				,						(self.batch_size, self.max_token_length, self.num_character_labels)   )







      def 						UpperCAmelCase		( self   )       ->   Dict:






        '''simple docstring'''






        __snake_case   :				Union[str, Any]        =       self.prepare_config_and_inputs()
        __snake_case   :				Dict        =       config_and_inputs
        __snake_case   :				Union[str, Any]        =       {"pixel_values": pixel_values}
        return config, inputs_dict




@require_torch
class 				_lowerCamelCase (    a ,   a ,   unittest.TestCase    ):



      """simple docstring"""






      UpperCAmelCase_						:      Union[str, Any]       =(MgpstrForSceneTextRecognition,) if is_torch_available() else ()
      UpperCAmelCase_						:      List[Any]       ={"feature-extraction": MgpstrForSceneTextRecognition} if is_torch_available() else {}
      UpperCAmelCase_						:      Tuple       =False

      UpperCAmelCase_						:      Any       =False
      UpperCAmelCase_						:      Any       =False
      UpperCAmelCase_						:      Tuple       =False
      UpperCAmelCase_						:      Union[str, Any]       =False







      def 						UpperCAmelCase		( self   )       ->   List[str]:






        '''simple docstring'''






        __snake_case   :				int        =       MgpstrModelTester(self   )
        __snake_case   :				Union[str, Any]        =       ConfigTester(self				,						config_class=UpperCAmelCase				,						has_text_modality=UpperCAmelCase   )







      def 						UpperCAmelCase		( self   )       ->   Any:






        '''simple docstring'''






        self.config_tester.run_common_tests()







      def 						UpperCAmelCase		( self   )       ->   Tuple:






        '''simple docstring'''






        __snake_case   :				List[Any]        =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase   )







      @unittest.skip(reason="MgpstrModel does not use inputs_embeds"   )
      def 						UpperCAmelCase		( self   )       ->   Optional[Any]:






        '''simple docstring'''






        pass







      def 						UpperCAmelCase		( self   )       ->   List[str]:






        '''simple docstring'''






        __snake_case   :				int        =       self.model_tester.prepare_config_and_inputs_for_common()

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







      def 						UpperCAmelCase		( self   )       ->   List[Any]:






        '''simple docstring'''






        __snake_case   :				str        =       self.model_tester.prepare_config_and_inputs_for_common()

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

          __snake_case   :				int        =       ["pixel_values"]
          self.assertListEqual(arg_names[:1]				,						UpperCAmelCase   )







      @unittest.skip(reason="MgpstrModel does not support feedforward chunking"   )
      def 						UpperCAmelCase		( self   )       ->   int:






        '''simple docstring'''






        pass







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






        '''simple docstring'''






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

          __snake_case   :				Optional[int]        =       True
          __snake_case   :				int        =       model_class(UpperCAmelCase   )
          self.assertTrue(model.is_gradient_checkpointing   )







      def 						UpperCAmelCase		( self   )       ->   str:






        '''simple docstring'''






        def check_hidden_states_output(UpperCAmelCase				,						UpperCAmelCase				,						UpperCAmelCase   ):
          __snake_case   :				Union[str, Any]        =       model_class(UpperCAmelCase   )
          model.to(UpperCAmelCase   )
          model.eval()

          with torch.no_grad():
            __snake_case   :				List[str]        =       model(**self._prepare_for_class(UpperCAmelCase				,						UpperCAmelCase   )   )

          __snake_case   :				Union[str, Any]        =       outputs.hidden_states

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

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

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

        for model_class in self.all_model_classes:
          __snake_case   :				Dict        =       True
          check_hidden_states_output(UpperCAmelCase				,						UpperCAmelCase				,						UpperCAmelCase   )

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

          check_hidden_states_output(UpperCAmelCase				,						UpperCAmelCase				,						UpperCAmelCase   )







      def 						UpperCAmelCase		( self   )       ->   int:






        '''simple docstring'''






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

        __snake_case   :				List[Any]        =       _config_zero_init(UpperCAmelCase   )
        for model_class in self.all_model_classes:
          __snake_case   :				int        =       model_class(config=UpperCAmelCase   )
          for name, param in model.named_parameters():
            if isinstance(UpperCAmelCase				,						(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   )       ->   List[Any]:






        '''simple docstring'''






        pass







def       lowerCAmelCase__(	) ->    Any:
  __snake_case   :				Optional[Any]        =       "https://i.postimg.cc/ZKwLg2Gw/367-14.png"
  __snake_case   :				List[str]        =       Image.open(requests.get(lowercase   ,     stream=lowercase				).raw				).convert("RGB"				)
  return im




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



      """simple docstring"""






      @slow
      def 						UpperCAmelCase		( self   )       ->   Union[str, Any]:






        '''simple docstring'''






        __snake_case   :				Optional[int]        =       "alibaba-damo/mgp-str-base"
        __snake_case   :				Any        =       MgpstrForSceneTextRecognition.from_pretrained(UpperCAmelCase   ).to(UpperCAmelCase   )
        __snake_case   :				List[str]        =       MgpstrProcessor.from_pretrained(UpperCAmelCase   )

        __snake_case   :				str        =       prepare_img()
        __snake_case   :				Optional[int]        =       processor(images=UpperCAmelCase				,						return_tensors="pt"   ).pixel_values.to(UpperCAmelCase   )

        # forward pass
        with torch.no_grad():
          __snake_case   :				int        =       model(UpperCAmelCase   )

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

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

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

        __snake_case   :				Union[str, 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=UpperCAmelCase				,						)

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








import subprocess
from argparse import ArgumentParser
from typing import List, Union

from huggingface_hub.hf_api import HfFolder, create_repo, whoami
from requests.exceptions import HTTPError

from . import BaseTransformersCLICommand




class 				_lowerCamelCase (    a    ):



      """simple docstring"""






      @staticmethod
      def 						UpperCAmelCase		( UpperCAmelCase   )       ->   Any:






        '''simple docstring'''






        __snake_case   :				Dict        =       parser.add_parser("login"				,						help="Log in using the same credentials as on huggingface.co"   )
        login_parser.set_defaults(func=lambda UpperCAmelCase   : LoginCommand(UpperCAmelCase   )   )
        __snake_case   :				int        =       parser.add_parser("whoami"				,						help="Find out which huggingface.co account you are logged in as."   )
        whoami_parser.set_defaults(func=lambda UpperCAmelCase   : WhoamiCommand(UpperCAmelCase   )   )
        __snake_case   :				int        =       parser.add_parser("logout"				,						help="Log out"   )
        logout_parser.set_defaults(func=lambda UpperCAmelCase   : LogoutCommand(UpperCAmelCase   )   )

        # new system: git-based repo system
        __snake_case   :				Union[str, Any]        =       parser.add_parser(
            "repo"				,						help="Deprecated: use `huggingface-cli` instead. Commands to interact with your huggingface.co repos."				,						)
        __snake_case   :				List[str]        =       repo_parser.add_subparsers(
            help="Deprecated: use `huggingface-cli` instead. huggingface.co repos related commands"   )
        __snake_case   :				int        =       repo_subparsers.add_parser(
            "create"				,						help="Deprecated: use `huggingface-cli` instead. Create a new repo on huggingface.co"   )
        repo_create_parser.add_argument(
            "name"				,						type=UpperCAmelCase				,						help="Name for your model's repo. Will be namespaced under your username to build the model id."				,						)
        repo_create_parser.add_argument("--organization"				,						type=UpperCAmelCase				,						help="Optional: organization namespace."   )
        repo_create_parser.add_argument("-y"				,						"--yes"				,						action="store_true"				,						help="Optional: answer Yes to the prompt"   )
        repo_create_parser.set_defaults(func=lambda UpperCAmelCase   : RepoCreateCommand(UpperCAmelCase   )   )




class 				_lowerCamelCase :



      """simple docstring"""






      UpperCAmelCase_						:      Tuple       ="\u001b[1m"
      UpperCAmelCase_						:      int       ="\u001b[31m"
      UpperCAmelCase_						:      Optional[Any]       ="\u001b[90m"
      UpperCAmelCase_						:      Optional[Any]       ="\u001b[0m"







      @classmethod
      def 						UpperCAmelCase		( cls				,						UpperCAmelCase   )       ->   Union[str, Any]:






        '''simple docstring'''






        return F"""{cls._bold}{s}{cls._reset}"""







      @classmethod
      def 						UpperCAmelCase		( cls				,						UpperCAmelCase   )       ->   Optional[int]:






        '''simple docstring'''






        return F"""{cls._bold}{cls._red}{s}{cls._reset}"""







      @classmethod
      def 						UpperCAmelCase		( cls				,						UpperCAmelCase   )       ->   List[str]:






        '''simple docstring'''






        return F"""{cls._gray}{s}{cls._reset}"""







def       lowerCAmelCase__(	lowercase       :    List[List[Union[str, int]]]   ,     lowercase       :    List[str]				) ->    str:
  __snake_case   :				Dict        =       [max(len(str(lowercase				)				) for x in col				) for col in zip(*lowercase   ,     lowercase				)]
  __snake_case   :				str        =       ("{{:{}}} " * len(lowercase				)).format(*lowercase				)
  __snake_case   :				Tuple        =       []
  lines.append(row_format.format(*lowercase				)				)
  lines.append(row_format.format(*["-" * w for w in col_widths]				)				)
  for row in rows:
    lines.append(row_format.format(*lowercase				)				)
  return "\n".join(lowercase				)




class 				_lowerCamelCase :



      """simple docstring"""






      def __init__( self				,						UpperCAmelCase   )       ->   Dict:






        '''simple docstring'''






        __snake_case   :				List[str]        =       args




class 				_lowerCamelCase (    a    ):



      """simple docstring"""






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






        '''simple docstring'''






        print(
            ANSI.red(
                "ERROR! `huggingface-cli login` uses an outdated login mechanism "
                "that is not compatible with the Hugging Face Hub backend anymore. "
                "Please use `huggingface-cli login instead."   )   )




class 				_lowerCamelCase (    a    ):



      """simple docstring"""






      def 						UpperCAmelCase		( self   )       ->   str:






        '''simple docstring'''






        print(
            ANSI.red(
                "WARNING! `transformers-cli whoami` is deprecated and will be removed in v5. Please use "
                "`huggingface-cli whoami` instead."   )   )
        __snake_case   :				Optional[Any]        =       HfFolder.get_token()
        if token is None:
          print("Not logged in"   )
          exit()
        try:
          __snake_case    ,   __snake_case   :				Tuple        =       whoami(UpperCAmelCase   )
          print(UpperCAmelCase   )
          if orgs:
            print(ANSI.bold("orgs: "   )				,						",".join(UpperCAmelCase   )   )
        except HTTPError as e:
          print(UpperCAmelCase   )
          print(ANSI.red(e.response.text   )   )
          exit(1   )




class 				_lowerCamelCase (    a    ):



      """simple docstring"""






      def 						UpperCAmelCase		( self   )       ->   List[str]:






        '''simple docstring'''






        print(
            ANSI.red(
                "ERROR! `transformers-cli logout` uses an outdated logout mechanism "
                "that is not compatible with the Hugging Face Hub backend anymore. "
                "Please use `huggingface-cli logout instead."   )   )




class 				_lowerCamelCase (    a    ):



      """simple docstring"""






      def 						UpperCAmelCase		( self   )       ->   Tuple:






        '''simple docstring'''






        print(
            ANSI.red(
                "WARNING! Managing repositories through transformers-cli is deprecated. "
                "Please use `huggingface-cli` instead."   )   )
        __snake_case   :				Dict        =       HfFolder.get_token()
        if token is None:
          print("Not logged in"   )
          exit(1   )
        try:
          __snake_case   :				Optional[int]        =       subprocess.check_output(["git", "--version"]   ).decode("utf-8"   )
          print(ANSI.gray(stdout.strip()   )   )
        except FileNotFoundError:
          print("Looks like you do not have git installed, please install."   )

        try:
          __snake_case   :				Union[str, Any]        =       subprocess.check_output(["git-lfs", "--version"]   ).decode("utf-8"   )
          print(ANSI.gray(stdout.strip()   )   )
        except FileNotFoundError:
          print(
              ANSI.red(
                  "Looks like you do not have git-lfs installed, please install."
                  " You can install from https://git-lfs.github.com/."
                  " Then run `git lfs install` (you only have to do this once)."   )   )
        print(""   )

        __snake_case    ,   __snake_case   :				Any        =       whoami(UpperCAmelCase   )
        __snake_case   :				List[str]        =       self.args.organization if self.args.organization is not None else user
        __snake_case   :				Any        =       F"""{namespace}/{self.args.name}"""
        print(F"""You are about to create {ANSI.bold(UpperCAmelCase   )}"""   )

        if not self.args.yes:
          __snake_case   :				Optional[int]        =       input("Proceed? [Y/n] "   ).lower()
          if not (choice == "" or choice == "y" or choice == "yes"):
            print("Abort"   )
            exit()
        try:
          __snake_case   :				List[str]        =       create_repo(UpperCAmelCase				,						name=self.args.name				,						organization=self.args.organization   )
        except HTTPError as e:
          print(UpperCAmelCase   )
          print(ANSI.red(e.response.text   )   )
          exit(1   )
        print("\nYour repo now lives at:"   )
        print(F"""  {ANSI.bold(UpperCAmelCase   )}"""   )
        print("\nYou can clone it locally with the command below, and commit/push as usual."   )
        print(F"""\n  git clone {url}"""   )
        print(""   )

